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, 1994, 1995, 1996, 1997 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,
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
30 /* Converts the pointer to the char to BEG-based offset from the start. */
31 #define PTR_TO_OFFSET(d) \
32 POS_AS_IN_BUFFER (MATCHING_IN_FIRST_STRING \
33 ? (d) - string1 : (d) - (string2 - size1))
34 #define POS_AS_IN_BUFFER(p) ((p) + 1)
40 /* We need this for `regex.h', and perhaps for the Emacs include files. */
41 #include <sys/types.h>
43 /* This is for other GNU distributions with internationalized messages. */
44 #if HAVE_LIBINTL_H || defined (_LIBC)
47 # define gettext(msgid) (msgid)
51 /* This define is so xgettext can find the internationalizable
53 #define gettext_noop(String) String
56 /* The `emacs' switch turns on certain matching commands
57 that make sense only in Emacs. */
63 /* Make syntax table lookup grant data in gl_state. */
64 #define SYNTAX_ENTRY_VIA_PROPERTY
70 #define malloc xmalloc
75 /* If we are not linking with Emacs proper,
76 we can't use the relocating allocator
77 even if config.h says that we can. */
80 #if defined (STDC_HEADERS) || defined (_LIBC)
87 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
88 If nothing else has been done, use the method below. */
89 #ifdef INHIBIT_STRING_HEADER
90 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
91 #if !defined (bzero) && !defined (bcopy)
92 #undef INHIBIT_STRING_HEADER
97 /* This is the normal way of making sure we have a bcopy and a bzero.
98 This is used in most programs--a few other programs avoid this
99 by defining INHIBIT_STRING_HEADER. */
100 #ifndef INHIBIT_STRING_HEADER
101 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
104 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
107 #define bcopy(s, d, n) memcpy ((d), (s), (n))
110 #define bzero(s, n) memset ((s), 0, (n))
117 /* Define the syntax stuff for \<, \>, etc. */
119 /* This must be nonzero for the wordchar and notwordchar pattern
120 commands in re_match_2. */
125 #ifdef SWITCH_ENUM_BUG
126 #define SWITCH_ENUM_CAST(x) ((int)(x))
128 #define SWITCH_ENUM_CAST(x) (x)
133 extern char *re_syntax_table;
135 #else /* not SYNTAX_TABLE */
137 /* How many characters in the character set. */
138 #define CHAR_SET_SIZE 256
140 static char re_syntax_table[CHAR_SET_SIZE];
151 bzero (re_syntax_table, sizeof re_syntax_table);
153 for (c = 'a'; c <= 'z'; c++)
154 re_syntax_table[c] = Sword;
156 for (c = 'A'; c <= 'Z'; c++)
157 re_syntax_table[c] = Sword;
159 for (c = '0'; c <= '9'; c++)
160 re_syntax_table[c] = Sword;
162 re_syntax_table['_'] = Sword;
167 #endif /* not SYNTAX_TABLE */
169 #define SYNTAX(c) re_syntax_table[c]
171 /* Dummy macro for non emacs environments. */
172 #define BASE_LEADING_CODE_P(c) (0)
173 #define WORD_BOUNDARY_P(c1, c2) (0)
174 #define CHAR_HEAD_P(p) (1)
175 #define SINGLE_BYTE_CHAR_P(c) (1)
176 #define SAME_CHARSET_P(c1, c2) (1)
177 #define MULTIBYTE_FORM_LENGTH(p, s) (1)
178 #define STRING_CHAR(p, s) (*(p))
179 #define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
180 #define GET_CHAR_AFTER_2(c, p, str1, end1, str2, end2) \
181 (c = ((p) == (end1) ? *(str2) : *(p)))
182 #define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
183 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
184 #endif /* not emacs */
186 /* Get the interface, including the syntax bits. */
189 /* isalpha etc. are used for the character classes. */
192 /* Jim Meyering writes:
194 "... Some ctype macros are valid only for character codes that
195 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
196 using /bin/cc or gcc but without giving an ansi option). So, all
197 ctype uses should be through macros like ISPRINT... If
198 STDC_HEADERS is defined, then autoconf has verified that the ctype
199 macros don't need to be guarded with references to isascii. ...
200 Defining isascii to 1 should let any compiler worth its salt
201 eliminate the && through constant folding." */
203 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
206 #define ISASCII(c) isascii(c)
210 #define ISBLANK(c) (ISASCII (c) && isblank (c))
212 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
215 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
217 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
220 #define ISPRINT(c) (ISASCII (c) && isprint (c))
221 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
222 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
223 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
224 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
225 #define ISLOWER(c) (ISASCII (c) && islower (c))
226 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
227 #define ISSPACE(c) (ISASCII (c) && isspace (c))
228 #define ISUPPER(c) (ISASCII (c) && isupper (c))
229 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
232 #define NULL (void *)0
235 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
236 since ours (we hope) works properly with all combinations of
237 machines, compilers, `char' and `unsigned char' argument types.
238 (Per Bothner suggested the basic approach.) */
239 #undef SIGN_EXTEND_CHAR
241 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
242 #else /* not __STDC__ */
243 /* As in Harbison and Steele. */
244 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
247 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
248 use `alloca' instead of `malloc'. This is because using malloc in
249 re_search* or re_match* could cause memory leaks when C-g is used in
250 Emacs; also, malloc is slower and causes storage fragmentation. On
251 the other hand, malloc is more portable, and easier to debug.
253 Because we sometimes use alloca, some routines have to be macros,
254 not functions -- `alloca'-allocated space disappears at the end of the
255 function it is called in. */
259 #define REGEX_ALLOCATE malloc
260 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
261 #define REGEX_FREE free
263 #else /* not REGEX_MALLOC */
265 /* Emacs already defines alloca, sometimes. */
268 /* Make alloca work the best possible way. */
270 #define alloca __builtin_alloca
271 #else /* not __GNUC__ */
274 #else /* not __GNUC__ or HAVE_ALLOCA_H */
275 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
276 #ifndef _AIX /* Already did AIX, up at the top. */
278 #endif /* not _AIX */
280 #endif /* not HAVE_ALLOCA_H */
281 #endif /* not __GNUC__ */
283 #endif /* not alloca */
285 #define REGEX_ALLOCATE alloca
287 /* Assumes a `char *destination' variable. */
288 #define REGEX_REALLOCATE(source, osize, nsize) \
289 (destination = (char *) alloca (nsize), \
290 bcopy (source, destination, osize), \
293 /* No need to do anything to free, after alloca. */
294 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
296 #endif /* not REGEX_MALLOC */
298 /* Define how to allocate the failure stack. */
300 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
302 #define REGEX_ALLOCATE_STACK(size) \
303 r_alloc (&failure_stack_ptr, (size))
304 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
305 r_re_alloc (&failure_stack_ptr, (nsize))
306 #define REGEX_FREE_STACK(ptr) \
307 r_alloc_free (&failure_stack_ptr)
309 #else /* not using relocating allocator */
313 #define REGEX_ALLOCATE_STACK malloc
314 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
315 #define REGEX_FREE_STACK free
317 #else /* not REGEX_MALLOC */
319 #define REGEX_ALLOCATE_STACK alloca
321 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
322 REGEX_REALLOCATE (source, osize, nsize)
323 /* No need to explicitly free anything. */
324 #define REGEX_FREE_STACK(arg)
326 #endif /* not REGEX_MALLOC */
327 #endif /* not using relocating allocator */
330 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
331 `string1' or just past its end. This works if PTR is NULL, which is
333 #define FIRST_STRING_P(ptr) \
334 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
336 /* (Re)Allocate N items of type T using malloc, or fail. */
337 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
338 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
339 #define RETALLOC_IF(addr, n, t) \
340 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
341 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
343 #define BYTEWIDTH 8 /* In bits. */
345 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
349 #define MAX(a, b) ((a) > (b) ? (a) : (b))
350 #define MIN(a, b) ((a) < (b) ? (a) : (b))
352 typedef char boolean;
356 static int re_match_2_internal ();
358 /* These are the command codes that appear in compiled regular
359 expressions. Some opcodes are followed by argument bytes. A
360 command code can specify any interpretation whatsoever for its
361 arguments. Zero bytes may appear in the compiled regular expression. */
367 /* Succeed right away--no more backtracking. */
370 /* Followed by one byte giving n, then by n literal bytes. */
373 /* Matches any (more or less) character. */
376 /* Matches any one char belonging to specified set. First
377 following byte is number of bitmap bytes. Then come bytes
378 for a bitmap saying which chars are in. Bits in each byte
379 are ordered low-bit-first. A character is in the set if its
380 bit is 1. A character too large to have a bit in the map is
381 automatically not in the set. */
384 /* Same parameters as charset, but match any character that is
385 not one of those specified. */
388 /* Start remembering the text that is matched, for storing in a
389 register. Followed by one byte with the register number, in
390 the range 0 to one less than the pattern buffer's re_nsub
391 field. Then followed by one byte with the number of groups
392 inner to this one. (This last has to be part of the
393 start_memory only because we need it in the on_failure_jump
397 /* Stop remembering the text that is matched and store it in a
398 memory register. Followed by one byte with the register
399 number, in the range 0 to one less than `re_nsub' in the
400 pattern buffer, and one byte with the number of inner groups,
401 just like `start_memory'. (We need the number of inner
402 groups here because we don't have any easy way of finding the
403 corresponding start_memory when we're at a stop_memory.) */
406 /* Match a duplicate of something remembered. Followed by one
407 byte containing the register number. */
410 /* Fail unless at beginning of line. */
413 /* Fail unless at end of line. */
416 /* Succeeds if at beginning of buffer (if emacs) or at beginning
417 of string to be matched (if not). */
420 /* Analogously, for end of buffer/string. */
423 /* Followed by two byte relative address to which to jump. */
426 /* Same as jump, but marks the end of an alternative. */
429 /* Followed by two-byte relative address of place to resume at
430 in case of failure. */
433 /* Like on_failure_jump, but pushes a placeholder instead of the
434 current string position when executed. */
435 on_failure_keep_string_jump,
437 /* Throw away latest failure point and then jump to following
438 two-byte relative address. */
441 /* Change to pop_failure_jump if know won't have to backtrack to
442 match; otherwise change to jump. This is used to jump
443 back to the beginning of a repeat. If what follows this jump
444 clearly won't match what the repeat does, such that we can be
445 sure that there is no use backtracking out of repetitions
446 already matched, then we change it to a pop_failure_jump.
447 Followed by two-byte address. */
450 /* Jump to following two-byte address, and push a dummy failure
451 point. This failure point will be thrown away if an attempt
452 is made to use it for a failure. A `+' construct makes this
453 before the first repeat. Also used as an intermediary kind
454 of jump when compiling an alternative. */
457 /* Push a dummy failure point and continue. Used at the end of
461 /* Followed by two-byte relative address and two-byte number n.
462 After matching N times, jump to the address upon failure. */
465 /* Followed by two-byte relative address, and two-byte number n.
466 Jump to the address N times, then fail. */
469 /* Set the following two-byte relative address to the
470 subsequent two-byte number. The address *includes* the two
474 wordchar, /* Matches any word-constituent character. */
475 notwordchar, /* Matches any char that is not a word-constituent. */
477 wordbeg, /* Succeeds if at word beginning. */
478 wordend, /* Succeeds if at word end. */
480 wordbound, /* Succeeds if at a word boundary. */
481 notwordbound /* Succeeds if not at a word boundary. */
484 ,before_dot, /* Succeeds if before point. */
485 at_dot, /* Succeeds if at point. */
486 after_dot, /* Succeeds if after point. */
488 /* Matches any character whose syntax is specified. Followed by
489 a byte which contains a syntax code, e.g., Sword. */
492 /* Matches any character whose syntax is not that specified. */
495 /* Matches any character whose category-set contains the specified
496 category. The operator is followed by a byte which contains a
497 category code (mnemonic ASCII character). */
500 /* Matches any character whose category-set does not contain the
501 specified category. The operator is followed by a byte which
502 contains the category code (mnemonic ASCII character). */
507 /* Common operations on the compiled pattern. */
509 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
511 #define STORE_NUMBER(destination, number) \
513 (destination)[0] = (number) & 0377; \
514 (destination)[1] = (number) >> 8; \
517 /* Same as STORE_NUMBER, except increment DESTINATION to
518 the byte after where the number is stored. Therefore, DESTINATION
519 must be an lvalue. */
521 #define STORE_NUMBER_AND_INCR(destination, number) \
523 STORE_NUMBER (destination, number); \
524 (destination) += 2; \
527 /* Put into DESTINATION a number stored in two contiguous bytes starting
530 #define EXTRACT_NUMBER(destination, source) \
532 (destination) = *(source) & 0377; \
533 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
538 extract_number (dest, source)
540 unsigned char *source;
542 int temp = SIGN_EXTEND_CHAR (*(source + 1));
543 *dest = *source & 0377;
547 #ifndef EXTRACT_MACROS /* To debug the macros. */
548 #undef EXTRACT_NUMBER
549 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
550 #endif /* not EXTRACT_MACROS */
554 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
555 SOURCE must be an lvalue. */
557 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
559 EXTRACT_NUMBER (destination, source); \
565 extract_number_and_incr (destination, source)
567 unsigned char **source;
569 extract_number (destination, *source);
573 #ifndef EXTRACT_MACROS
574 #undef EXTRACT_NUMBER_AND_INCR
575 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
576 extract_number_and_incr (&dest, &src)
577 #endif /* not EXTRACT_MACROS */
581 /* Store a multibyte character in three contiguous bytes starting
582 DESTINATION, and increment DESTINATION to the byte after where the
583 character is stored. Therefore, DESTINATION must be an lvalue. */
585 #define STORE_CHARACTER_AND_INCR(destination, character) \
587 (destination)[0] = (character) & 0377; \
588 (destination)[1] = ((character) >> 8) & 0377; \
589 (destination)[2] = (character) >> 16; \
590 (destination) += 3; \
593 /* Put into DESTINATION a character stored in three contiguous bytes
594 starting at SOURCE. */
596 #define EXTRACT_CHARACTER(destination, source) \
598 (destination) = ((source)[0] \
599 | ((source)[1] << 8) \
600 | ((source)[2] << 16)); \
604 /* Macros for charset. */
606 /* Size of bitmap of charset P in bytes. P is a start of charset,
607 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
608 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
610 /* Nonzero if charset P has range table. */
611 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
613 /* Return the address of range table of charset P. But not the start
614 of table itself, but the before where the number of ranges is
615 stored. `2 +' means to skip re_opcode_t and size of bitmap. */
616 #define CHARSET_RANGE_TABLE(p) (&(p)[2 + CHARSET_BITMAP_SIZE (p)])
618 /* Test if C is listed in the bitmap of charset P. */
619 #define CHARSET_LOOKUP_BITMAP(p, c) \
620 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
621 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
623 /* Return the address of end of RANGE_TABLE. COUNT is number of
624 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
625 is start of range and end of range. `* 3' is size of each start
627 #define CHARSET_RANGE_TABLE_END(range_table, count) \
628 ((range_table) + (count) * 2 * 3)
630 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
631 COUNT is number of ranges in RANGE_TABLE. */
632 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
635 int range_start, range_end; \
637 unsigned char *range_table_end \
638 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
640 for (p = (range_table); p < range_table_end; p += 2 * 3) \
642 EXTRACT_CHARACTER (range_start, p); \
643 EXTRACT_CHARACTER (range_end, p + 3); \
645 if (range_start <= (c) && (c) <= range_end) \
654 /* Test if C is in range table of CHARSET. The flag NOT is negated if
655 C is listed in it. */
656 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
659 /* Number of ranges in range table. */ \
661 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
663 EXTRACT_NUMBER_AND_INCR (count, range_table); \
664 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
668 /* If DEBUG is defined, Regex prints many voluminous messages about what
669 it is doing (if the variable `debug' is nonzero). If linked with the
670 main program in `iregex.c', you can enter patterns and strings
671 interactively. And if linked with the main program in `main.c' and
672 the other test files, you can run the already-written tests. */
676 /* We use standard I/O for debugging. */
679 /* It is useful to test things that ``must'' be true when debugging. */
682 static int debug = 0;
684 #define DEBUG_STATEMENT(e) e
685 #define DEBUG_PRINT1(x) if (debug) printf (x)
686 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
687 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
688 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
689 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
690 if (debug) print_partial_compiled_pattern (s, e)
691 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
692 if (debug) print_double_string (w, s1, sz1, s2, sz2)
695 /* Print the fastmap in human-readable form. */
698 print_fastmap (fastmap)
701 unsigned was_a_range = 0;
704 while (i < (1 << BYTEWIDTH))
710 while (i < (1 << BYTEWIDTH) && fastmap[i])
726 /* Print a compiled pattern string in human-readable form, starting at
727 the START pointer into it and ending just before the pointer END. */
730 print_partial_compiled_pattern (start, end)
731 unsigned char *start;
735 unsigned char *p = start;
736 unsigned char *pend = end;
744 /* Loop over pattern commands. */
747 printf ("%d:\t", p - start);
749 switch ((re_opcode_t) *p++)
757 printf ("/exactn/%d", mcnt);
768 printf ("/start_memory/%d/%d", mcnt, *p++);
773 printf ("/stop_memory/%d/%d", mcnt, *p++);
777 printf ("/duplicate/%d", *p++);
787 register int c, last = -100;
788 register int in_range = 0;
790 printf ("/charset [%s",
791 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
793 assert (p + *p < pend);
795 for (c = 0; c < 256; c++)
797 && (p[1 + (c/8)] & (1 << (c % 8))))
799 /* Are we starting a range? */
800 if (last + 1 == c && ! in_range)
805 /* Have we broken a range? */
806 else if (last + 1 != c && in_range)
835 case on_failure_jump:
836 extract_number_and_incr (&mcnt, &p);
837 printf ("/on_failure_jump to %d", p + mcnt - start);
840 case on_failure_keep_string_jump:
841 extract_number_and_incr (&mcnt, &p);
842 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
845 case dummy_failure_jump:
846 extract_number_and_incr (&mcnt, &p);
847 printf ("/dummy_failure_jump to %d", p + mcnt - start);
850 case push_dummy_failure:
851 printf ("/push_dummy_failure");
855 extract_number_and_incr (&mcnt, &p);
856 printf ("/maybe_pop_jump to %d", p + mcnt - start);
859 case pop_failure_jump:
860 extract_number_and_incr (&mcnt, &p);
861 printf ("/pop_failure_jump to %d", p + mcnt - start);
865 extract_number_and_incr (&mcnt, &p);
866 printf ("/jump_past_alt to %d", p + mcnt - start);
870 extract_number_and_incr (&mcnt, &p);
871 printf ("/jump to %d", p + mcnt - start);
875 extract_number_and_incr (&mcnt, &p);
876 extract_number_and_incr (&mcnt2, &p);
877 printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
881 extract_number_and_incr (&mcnt, &p);
882 extract_number_and_incr (&mcnt2, &p);
883 printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
887 extract_number_and_incr (&mcnt, &p);
888 extract_number_and_incr (&mcnt2, &p);
889 printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
893 printf ("/wordbound");
897 printf ("/notwordbound");
909 printf ("/before_dot");
917 printf ("/after_dot");
921 printf ("/syntaxspec");
923 printf ("/%d", mcnt);
927 printf ("/notsyntaxspec");
929 printf ("/%d", mcnt);
934 printf ("/wordchar");
938 printf ("/notwordchar");
950 printf ("?%d", *(p-1));
956 printf ("%d:\tend of pattern.\n", p - start);
961 print_compiled_pattern (bufp)
962 struct re_pattern_buffer *bufp;
964 unsigned char *buffer = bufp->buffer;
966 print_partial_compiled_pattern (buffer, buffer + bufp->used);
967 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
969 if (bufp->fastmap_accurate && bufp->fastmap)
971 printf ("fastmap: ");
972 print_fastmap (bufp->fastmap);
975 printf ("re_nsub: %d\t", bufp->re_nsub);
976 printf ("regs_alloc: %d\t", bufp->regs_allocated);
977 printf ("can_be_null: %d\t", bufp->can_be_null);
978 printf ("newline_anchor: %d\n", bufp->newline_anchor);
979 printf ("no_sub: %d\t", bufp->no_sub);
980 printf ("not_bol: %d\t", bufp->not_bol);
981 printf ("not_eol: %d\t", bufp->not_eol);
982 printf ("syntax: %d\n", bufp->syntax);
983 /* Perhaps we should print the translate table? */
988 print_double_string (where, string1, size1, string2, size2)
1001 if (FIRST_STRING_P (where))
1003 for (this_char = where - string1; this_char < size1; this_char++)
1004 putchar (string1[this_char]);
1009 for (this_char = where - string2; this_char < size2; this_char++)
1010 putchar (string2[this_char]);
1014 #else /* not DEBUG */
1019 #define DEBUG_STATEMENT(e)
1020 #define DEBUG_PRINT1(x)
1021 #define DEBUG_PRINT2(x1, x2)
1022 #define DEBUG_PRINT3(x1, x2, x3)
1023 #define DEBUG_PRINT4(x1, x2, x3, x4)
1024 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1025 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1027 #endif /* not DEBUG */
1029 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1030 also be assigned to arbitrarily: each pattern buffer stores its own
1031 syntax, so it can be changed between regex compilations. */
1032 /* This has no initializer because initialized variables in Emacs
1033 become read-only after dumping. */
1034 reg_syntax_t re_syntax_options;
1037 /* Specify the precise syntax of regexps for compilation. This provides
1038 for compatibility for various utilities which historically have
1039 different, incompatible syntaxes.
1041 The argument SYNTAX is a bit mask comprised of the various bits
1042 defined in regex.h. We return the old syntax. */
1045 re_set_syntax (syntax)
1046 reg_syntax_t syntax;
1048 reg_syntax_t ret = re_syntax_options;
1050 re_syntax_options = syntax;
1054 /* This table gives an error message for each of the error codes listed
1055 in regex.h. Obviously the order here has to be same as there.
1056 POSIX doesn't require that we do anything for REG_NOERROR,
1057 but why not be nice? */
1059 static const char *re_error_msgid[] =
1061 gettext_noop ("Success"), /* REG_NOERROR */
1062 gettext_noop ("No match"), /* REG_NOMATCH */
1063 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1064 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1065 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1066 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1067 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1068 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1069 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1070 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1071 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1072 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1073 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1074 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1075 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1076 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1077 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1080 /* Avoiding alloca during matching, to placate r_alloc. */
1082 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1083 searching and matching functions should not call alloca. On some
1084 systems, alloca is implemented in terms of malloc, and if we're
1085 using the relocating allocator routines, then malloc could cause a
1086 relocation, which might (if the strings being searched are in the
1087 ralloc heap) shift the data out from underneath the regexp
1090 Here's another reason to avoid allocation: Emacs
1091 processes input from X in a signal handler; processing X input may
1092 call malloc; if input arrives while a matching routine is calling
1093 malloc, then we're scrod. But Emacs can't just block input while
1094 calling matching routines; then we don't notice interrupts when
1095 they come in. So, Emacs blocks input around all regexp calls
1096 except the matching calls, which it leaves unprotected, in the
1097 faith that they will not malloc. */
1099 /* Normally, this is fine. */
1100 #define MATCH_MAY_ALLOCATE
1102 /* When using GNU C, we are not REALLY using the C alloca, no matter
1103 what config.h may say. So don't take precautions for it. */
1108 /* The match routines may not allocate if (1) they would do it with malloc
1109 and (2) it's not safe for them to use malloc.
1110 Note that if REL_ALLOC is defined, matching would not use malloc for the
1111 failure stack, but we would still use it for the register vectors;
1112 so REL_ALLOC should not affect this. */
1113 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1114 #undef MATCH_MAY_ALLOCATE
1118 /* Failure stack declarations and macros; both re_compile_fastmap and
1119 re_match_2 use a failure stack. These have to be macros because of
1120 REGEX_ALLOCATE_STACK. */
1123 /* Approximate number of failure points for which to initially allocate space
1124 when matching. If this number is exceeded, we allocate more
1125 space, so it is not a hard limit. */
1126 #ifndef INIT_FAILURE_ALLOC
1127 #define INIT_FAILURE_ALLOC 20
1130 /* Roughly the maximum number of failure points on the stack. Would be
1131 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1132 This is a variable only so users of regex can assign to it; we never
1133 change it ourselves. */
1134 #if defined (MATCH_MAY_ALLOCATE)
1135 /* Note that 4400 is enough to cause a crash on Alpha OSF/1,
1136 whose default stack limit is 2mb. In order for a larger
1137 value to work reliably, you have to try to make it accord
1138 with the process stack limit. */
1139 int re_max_failures = 40000;
1141 int re_max_failures = 4000;
1144 union fail_stack_elt
1146 unsigned char *pointer;
1150 typedef union fail_stack_elt fail_stack_elt_t;
1154 fail_stack_elt_t *stack;
1156 unsigned avail; /* Offset of next open position. */
1159 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1160 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1161 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1164 /* Define macros to initialize and free the failure stack.
1165 Do `return -2' if the alloc fails. */
1167 #ifdef MATCH_MAY_ALLOCATE
1168 #define INIT_FAIL_STACK() \
1170 fail_stack.stack = (fail_stack_elt_t *) \
1171 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1172 * sizeof (fail_stack_elt_t)); \
1174 if (fail_stack.stack == NULL) \
1177 fail_stack.size = INIT_FAILURE_ALLOC; \
1178 fail_stack.avail = 0; \
1181 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1183 #define INIT_FAIL_STACK() \
1185 fail_stack.avail = 0; \
1188 #define RESET_FAIL_STACK()
1192 /* Double the size of FAIL_STACK, up to a limit
1193 which allows approximately `re_max_failures' items.
1195 Return 1 if succeeds, and 0 if either ran out of memory
1196 allocating space for it or it was already too large.
1198 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1200 /* Factor to increase the failure stack size by
1201 when we increase it.
1202 This used to be 2, but 2 was too wasteful
1203 because the old discarded stacks added up to as much space
1204 were as ultimate, maximum-size stack. */
1205 #define FAIL_STACK_GROWTH_FACTOR 4
1207 #define GROW_FAIL_STACK(fail_stack) \
1208 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1209 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1211 : ((fail_stack).stack \
1212 = (fail_stack_elt_t *) \
1213 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1214 (fail_stack).size * sizeof (fail_stack_elt_t), \
1215 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1216 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1217 * FAIL_STACK_GROWTH_FACTOR))), \
1219 (fail_stack).stack == NULL \
1221 : ((fail_stack).size \
1222 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1223 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1224 * FAIL_STACK_GROWTH_FACTOR)) \
1225 / sizeof (fail_stack_elt_t)), \
1229 /* Push pointer POINTER on FAIL_STACK.
1230 Return 1 if was able to do so and 0 if ran out of memory allocating
1232 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1233 ((FAIL_STACK_FULL () \
1234 && !GROW_FAIL_STACK (FAIL_STACK)) \
1236 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1239 /* Push a pointer value onto the failure stack.
1240 Assumes the variable `fail_stack'. Probably should only
1241 be called from within `PUSH_FAILURE_POINT'. */
1242 #define PUSH_FAILURE_POINTER(item) \
1243 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1245 /* This pushes an integer-valued item onto the failure stack.
1246 Assumes the variable `fail_stack'. Probably should only
1247 be called from within `PUSH_FAILURE_POINT'. */
1248 #define PUSH_FAILURE_INT(item) \
1249 fail_stack.stack[fail_stack.avail++].integer = (item)
1251 /* Push a fail_stack_elt_t value onto the failure stack.
1252 Assumes the variable `fail_stack'. Probably should only
1253 be called from within `PUSH_FAILURE_POINT'. */
1254 #define PUSH_FAILURE_ELT(item) \
1255 fail_stack.stack[fail_stack.avail++] = (item)
1257 /* These three POP... operations complement the three PUSH... operations.
1258 All assume that `fail_stack' is nonempty. */
1259 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1260 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1261 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1263 /* Used to omit pushing failure point id's when we're not debugging. */
1265 #define DEBUG_PUSH PUSH_FAILURE_INT
1266 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1268 #define DEBUG_PUSH(item)
1269 #define DEBUG_POP(item_addr)
1273 /* Push the information about the state we will need
1274 if we ever fail back to it.
1276 Requires variables fail_stack, regstart, regend, reg_info, and
1277 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1280 Does `return FAILURE_CODE' if runs out of memory. */
1282 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1284 char *destination; \
1285 /* Must be int, so when we don't save any registers, the arithmetic \
1286 of 0 + -1 isn't done as unsigned. */ \
1289 DEBUG_STATEMENT (failure_id++); \
1290 DEBUG_STATEMENT (nfailure_points_pushed++); \
1291 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1292 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1293 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1295 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1296 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1298 /* Ensure we have enough space allocated for what we will push. */ \
1299 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1301 if (!GROW_FAIL_STACK (fail_stack)) \
1302 return failure_code; \
1304 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1305 (fail_stack).size); \
1306 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1309 /* Push the info, starting with the registers. */ \
1310 DEBUG_PRINT1 ("\n"); \
1313 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1316 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1317 DEBUG_STATEMENT (num_regs_pushed++); \
1319 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1320 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1322 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1323 PUSH_FAILURE_POINTER (regend[this_reg]); \
1325 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
1326 DEBUG_PRINT2 (" match_null=%d", \
1327 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1328 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1329 DEBUG_PRINT2 (" matched_something=%d", \
1330 MATCHED_SOMETHING (reg_info[this_reg])); \
1331 DEBUG_PRINT2 (" ever_matched=%d", \
1332 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1333 DEBUG_PRINT1 ("\n"); \
1334 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1337 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1338 PUSH_FAILURE_INT (lowest_active_reg); \
1340 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1341 PUSH_FAILURE_INT (highest_active_reg); \
1343 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
1344 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1345 PUSH_FAILURE_POINTER (pattern_place); \
1347 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
1348 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1350 DEBUG_PRINT1 ("'\n"); \
1351 PUSH_FAILURE_POINTER (string_place); \
1353 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1354 DEBUG_PUSH (failure_id); \
1357 /* This is the number of items that are pushed and popped on the stack
1358 for each register. */
1359 #define NUM_REG_ITEMS 3
1361 /* Individual items aside from the registers. */
1363 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1365 #define NUM_NONREG_ITEMS 4
1368 /* Estimate the size of data pushed by a typical failure stack entry.
1369 An estimate is all we need, because all we use this for
1370 is to choose a limit for how big to make the failure stack. */
1372 #define TYPICAL_FAILURE_SIZE 20
1374 /* This is how many items we actually use for a failure point.
1375 It depends on the regexp. */
1376 #define NUM_FAILURE_ITEMS \
1378 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1382 /* How many items can still be added to the stack without overflowing it. */
1383 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1386 /* Pops what PUSH_FAIL_STACK pushes.
1388 We restore into the parameters, all of which should be lvalues:
1389 STR -- the saved data position.
1390 PAT -- the saved pattern position.
1391 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1392 REGSTART, REGEND -- arrays of string positions.
1393 REG_INFO -- array of information about each subexpression.
1395 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1396 `pend', `string1', `size1', `string2', and `size2'. */
1398 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1400 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
1402 const unsigned char *string_temp; \
1404 assert (!FAIL_STACK_EMPTY ()); \
1406 /* Remove failure points and point to how many regs pushed. */ \
1407 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1408 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1409 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1411 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1413 DEBUG_POP (&failure_id); \
1414 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1416 /* If the saved string location is NULL, it came from an \
1417 on_failure_keep_string_jump opcode, and we want to throw away the \
1418 saved NULL, thus retaining our current position in the string. */ \
1419 string_temp = POP_FAILURE_POINTER (); \
1420 if (string_temp != NULL) \
1421 str = (const char *) string_temp; \
1423 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
1424 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1425 DEBUG_PRINT1 ("'\n"); \
1427 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1428 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
1429 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1431 /* Restore register info. */ \
1432 high_reg = (unsigned) POP_FAILURE_INT (); \
1433 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1435 low_reg = (unsigned) POP_FAILURE_INT (); \
1436 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1439 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1441 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1443 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1444 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
1446 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1447 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1449 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1450 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1454 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1456 reg_info[this_reg].word.integer = 0; \
1457 regend[this_reg] = 0; \
1458 regstart[this_reg] = 0; \
1460 highest_active_reg = high_reg; \
1463 set_regs_matched_done = 0; \
1464 DEBUG_STATEMENT (nfailure_points_popped++); \
1465 } /* POP_FAILURE_POINT */
1469 /* Structure for per-register (a.k.a. per-group) information.
1470 Other register information, such as the
1471 starting and ending positions (which are addresses), and the list of
1472 inner groups (which is a bits list) are maintained in separate
1475 We are making a (strictly speaking) nonportable assumption here: that
1476 the compiler will pack our bit fields into something that fits into
1477 the type of `word', i.e., is something that fits into one item on the
1482 fail_stack_elt_t word;
1485 /* This field is one if this group can match the empty string,
1486 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1487 #define MATCH_NULL_UNSET_VALUE 3
1488 unsigned match_null_string_p : 2;
1489 unsigned is_active : 1;
1490 unsigned matched_something : 1;
1491 unsigned ever_matched_something : 1;
1493 } register_info_type;
1495 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1496 #define IS_ACTIVE(R) ((R).bits.is_active)
1497 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1498 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1501 /* Call this when have matched a real character; it sets `matched' flags
1502 for the subexpressions which we are currently inside. Also records
1503 that those subexprs have matched. */
1504 #define SET_REGS_MATCHED() \
1507 if (!set_regs_matched_done) \
1510 set_regs_matched_done = 1; \
1511 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1513 MATCHED_SOMETHING (reg_info[r]) \
1514 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1521 /* Registers are set to a sentinel when they haven't yet matched. */
1522 static char reg_unset_dummy;
1523 #define REG_UNSET_VALUE (®_unset_dummy)
1524 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1526 /* Subroutine declarations and macros for regex_compile. */
1528 static void store_op1 (), store_op2 ();
1529 static void insert_op1 (), insert_op2 ();
1530 static boolean at_begline_loc_p (), at_endline_loc_p ();
1531 static boolean group_in_compile_stack ();
1532 static reg_errcode_t compile_range ();
1534 /* Fetch the next character in the uncompiled pattern---translating it
1535 if necessary. Also cast from a signed character in the constant
1536 string passed to us by the user to an unsigned char that we can use
1537 as an array index (in, e.g., `translate'). */
1539 #define PATFETCH(c) \
1540 do {if (p == pend) return REG_EEND; \
1541 c = (unsigned char) *p++; \
1542 if (translate) c = (unsigned char) translate[c]; \
1546 /* Fetch the next character in the uncompiled pattern, with no
1548 #define PATFETCH_RAW(c) \
1549 do {if (p == pend) return REG_EEND; \
1550 c = (unsigned char) *p++; \
1553 /* Go backwards one character in the pattern. */
1554 #define PATUNFETCH p--
1557 /* If `translate' is non-null, return translate[D], else just D. We
1558 cast the subscript to translate because some data is declared as
1559 `char *', to avoid warnings when a string constant is passed. But
1560 when we use a character as a subscript we must make it unsigned. */
1562 #define TRANSLATE(d) \
1563 (translate ? (unsigned char) RE_TRANSLATE (translate, (unsigned char) (d)) : (d))
1567 /* Macros for outputting the compiled pattern into `buffer'. */
1569 /* If the buffer isn't allocated when it comes in, use this. */
1570 #define INIT_BUF_SIZE 32
1572 /* Make sure we have at least N more bytes of space in buffer. */
1573 #define GET_BUFFER_SPACE(n) \
1574 while (b - bufp->buffer + (n) > bufp->allocated) \
1577 /* Make sure we have one more byte of buffer space and then add C to it. */
1578 #define BUF_PUSH(c) \
1580 GET_BUFFER_SPACE (1); \
1581 *b++ = (unsigned char) (c); \
1585 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1586 #define BUF_PUSH_2(c1, c2) \
1588 GET_BUFFER_SPACE (2); \
1589 *b++ = (unsigned char) (c1); \
1590 *b++ = (unsigned char) (c2); \
1594 /* As with BUF_PUSH_2, except for three bytes. */
1595 #define BUF_PUSH_3(c1, c2, c3) \
1597 GET_BUFFER_SPACE (3); \
1598 *b++ = (unsigned char) (c1); \
1599 *b++ = (unsigned char) (c2); \
1600 *b++ = (unsigned char) (c3); \
1604 /* Store a jump with opcode OP at LOC to location TO. We store a
1605 relative address offset by the three bytes the jump itself occupies. */
1606 #define STORE_JUMP(op, loc, to) \
1607 store_op1 (op, loc, (to) - (loc) - 3)
1609 /* Likewise, for a two-argument jump. */
1610 #define STORE_JUMP2(op, loc, to, arg) \
1611 store_op2 (op, loc, (to) - (loc) - 3, arg)
1613 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1614 #define INSERT_JUMP(op, loc, to) \
1615 insert_op1 (op, loc, (to) - (loc) - 3, b)
1617 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1618 #define INSERT_JUMP2(op, loc, to, arg) \
1619 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1622 /* This is not an arbitrary limit: the arguments which represent offsets
1623 into the pattern are two bytes long. So if 2^16 bytes turns out to
1624 be too small, many things would have to change. */
1625 #define MAX_BUF_SIZE (1L << 16)
1628 /* Extend the buffer by twice its current size via realloc and
1629 reset the pointers that pointed into the old block to point to the
1630 correct places in the new one. If extending the buffer results in it
1631 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1632 #define EXTEND_BUFFER() \
1634 unsigned char *old_buffer = bufp->buffer; \
1635 if (bufp->allocated == MAX_BUF_SIZE) \
1637 bufp->allocated <<= 1; \
1638 if (bufp->allocated > MAX_BUF_SIZE) \
1639 bufp->allocated = MAX_BUF_SIZE; \
1640 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1641 if (bufp->buffer == NULL) \
1642 return REG_ESPACE; \
1643 /* If the buffer moved, move all the pointers into it. */ \
1644 if (old_buffer != bufp->buffer) \
1646 b = (b - old_buffer) + bufp->buffer; \
1647 begalt = (begalt - old_buffer) + bufp->buffer; \
1648 if (fixup_alt_jump) \
1649 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1651 laststart = (laststart - old_buffer) + bufp->buffer; \
1652 if (pending_exact) \
1653 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1658 /* Since we have one byte reserved for the register number argument to
1659 {start,stop}_memory, the maximum number of groups we can report
1660 things about is what fits in that byte. */
1661 #define MAX_REGNUM 255
1663 /* But patterns can have more than `MAX_REGNUM' registers. We just
1664 ignore the excess. */
1665 typedef unsigned regnum_t;
1668 /* Macros for the compile stack. */
1670 /* Since offsets can go either forwards or backwards, this type needs to
1671 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1672 typedef int pattern_offset_t;
1676 pattern_offset_t begalt_offset;
1677 pattern_offset_t fixup_alt_jump;
1678 pattern_offset_t inner_group_offset;
1679 pattern_offset_t laststart_offset;
1681 } compile_stack_elt_t;
1686 compile_stack_elt_t *stack;
1688 unsigned avail; /* Offset of next open position. */
1689 } compile_stack_type;
1692 #define INIT_COMPILE_STACK_SIZE 32
1694 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1695 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1697 /* The next available element. */
1698 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1701 /* Structure to manage work area for range table. */
1702 struct range_table_work_area
1704 int *table; /* actual work area. */
1705 int allocated; /* allocated size for work area in bytes. */
1706 int used; /* actually used size in words. */
1709 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1710 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1712 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1714 (work_area).allocated += 16 * sizeof (int); \
1715 if ((work_area).table) \
1717 = (int *) realloc ((work_area).table, (work_area).allocated); \
1720 = (int *) malloc ((work_area).allocated); \
1721 if ((work_area).table == 0) \
1722 FREE_STACK_RETURN (REG_ESPACE); \
1726 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1727 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1729 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1730 (work_area).table[(work_area).used++] = (range_start); \
1731 (work_area).table[(work_area).used++] = (range_end); \
1734 /* Free allocated memory for WORK_AREA. */
1735 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1737 if ((work_area).table) \
1738 free ((work_area).table); \
1741 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0)
1742 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1743 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1746 /* Set the bit for character C in a list. */
1747 #define SET_LIST_BIT(c) \
1748 (b[((unsigned char) (c)) / BYTEWIDTH] \
1749 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1752 /* Get the next unsigned number in the uncompiled pattern. */
1753 #define GET_UNSIGNED_NUMBER(num) \
1757 while (ISDIGIT (c)) \
1761 num = num * 10 + c - '0'; \
1769 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1771 #define IS_CHAR_CLASS(string) \
1772 (STREQ (string, "alpha") || STREQ (string, "upper") \
1773 || STREQ (string, "lower") || STREQ (string, "digit") \
1774 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1775 || STREQ (string, "space") || STREQ (string, "print") \
1776 || STREQ (string, "punct") || STREQ (string, "graph") \
1777 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1779 #ifndef MATCH_MAY_ALLOCATE
1781 /* If we cannot allocate large objects within re_match_2_internal,
1782 we make the fail stack and register vectors global.
1783 The fail stack, we grow to the maximum size when a regexp
1785 The register vectors, we adjust in size each time we
1786 compile a regexp, according to the number of registers it needs. */
1788 static fail_stack_type fail_stack;
1790 /* Size with which the following vectors are currently allocated.
1791 That is so we can make them bigger as needed,
1792 but never make them smaller. */
1793 static int regs_allocated_size;
1795 static const char ** regstart, ** regend;
1796 static const char ** old_regstart, ** old_regend;
1797 static const char **best_regstart, **best_regend;
1798 static register_info_type *reg_info;
1799 static const char **reg_dummy;
1800 static register_info_type *reg_info_dummy;
1802 /* Make the register vectors big enough for NUM_REGS registers,
1803 but don't make them smaller. */
1806 regex_grow_registers (num_regs)
1809 if (num_regs > regs_allocated_size)
1811 RETALLOC_IF (regstart, num_regs, const char *);
1812 RETALLOC_IF (regend, num_regs, const char *);
1813 RETALLOC_IF (old_regstart, num_regs, const char *);
1814 RETALLOC_IF (old_regend, num_regs, const char *);
1815 RETALLOC_IF (best_regstart, num_regs, const char *);
1816 RETALLOC_IF (best_regend, num_regs, const char *);
1817 RETALLOC_IF (reg_info, num_regs, register_info_type);
1818 RETALLOC_IF (reg_dummy, num_regs, const char *);
1819 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1821 regs_allocated_size = num_regs;
1825 #endif /* not MATCH_MAY_ALLOCATE */
1827 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1828 Returns one of error codes defined in `regex.h', or zero for success.
1830 Assumes the `allocated' (and perhaps `buffer') and `translate'
1831 fields are set in BUFP on entry.
1833 If it succeeds, results are put in BUFP (if it returns an error, the
1834 contents of BUFP are undefined):
1835 `buffer' is the compiled pattern;
1836 `syntax' is set to SYNTAX;
1837 `used' is set to the length of the compiled pattern;
1838 `fastmap_accurate' is zero;
1839 `re_nsub' is the number of subexpressions in PATTERN;
1840 `not_bol' and `not_eol' are zero;
1842 The `fastmap' and `newline_anchor' fields are neither
1843 examined nor set. */
1845 /* Return, freeing storage we allocated. */
1846 #define FREE_STACK_RETURN(value) \
1848 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1849 free (compile_stack.stack); \
1853 static reg_errcode_t
1854 regex_compile (pattern, size, syntax, bufp)
1855 const char *pattern;
1857 reg_syntax_t syntax;
1858 struct re_pattern_buffer *bufp;
1860 /* We fetch characters from PATTERN here. Even though PATTERN is
1861 `char *' (i.e., signed), we declare these variables as unsigned, so
1862 they can be reliably used as array indices. */
1863 register unsigned int c, c1;
1865 /* A random temporary spot in PATTERN. */
1868 /* Points to the end of the buffer, where we should append. */
1869 register unsigned char *b;
1871 /* Keeps track of unclosed groups. */
1872 compile_stack_type compile_stack;
1874 /* Points to the current (ending) position in the pattern. */
1875 const char *p = pattern;
1876 const char *pend = pattern + size;
1878 /* How to translate the characters in the pattern. */
1879 RE_TRANSLATE_TYPE translate = bufp->translate;
1881 /* Address of the count-byte of the most recently inserted `exactn'
1882 command. This makes it possible to tell if a new exact-match
1883 character can be added to that command or if the character requires
1884 a new `exactn' command. */
1885 unsigned char *pending_exact = 0;
1887 /* Address of start of the most recently finished expression.
1888 This tells, e.g., postfix * where to find the start of its
1889 operand. Reset at the beginning of groups and alternatives. */
1890 unsigned char *laststart = 0;
1892 /* Address of beginning of regexp, or inside of last group. */
1893 unsigned char *begalt;
1895 /* Place in the uncompiled pattern (i.e., the {) to
1896 which to go back if the interval is invalid. */
1897 const char *beg_interval;
1899 /* Address of the place where a forward jump should go to the end of
1900 the containing expression. Each alternative of an `or' -- except the
1901 last -- ends with a forward jump of this sort. */
1902 unsigned char *fixup_alt_jump = 0;
1904 /* Counts open-groups as they are encountered. Remembered for the
1905 matching close-group on the compile stack, so the same register
1906 number is put in the stop_memory as the start_memory. */
1907 regnum_t regnum = 0;
1909 /* Work area for range table of charset. */
1910 struct range_table_work_area range_table_work;
1913 DEBUG_PRINT1 ("\nCompiling pattern: ");
1916 unsigned debug_count;
1918 for (debug_count = 0; debug_count < size; debug_count++)
1919 putchar (pattern[debug_count]);
1924 /* Initialize the compile stack. */
1925 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1926 if (compile_stack.stack == NULL)
1929 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1930 compile_stack.avail = 0;
1932 range_table_work.table = 0;
1933 range_table_work.allocated = 0;
1935 /* Initialize the pattern buffer. */
1936 bufp->syntax = syntax;
1937 bufp->fastmap_accurate = 0;
1938 bufp->not_bol = bufp->not_eol = 0;
1940 /* Set `used' to zero, so that if we return an error, the pattern
1941 printer (for debugging) will think there's no pattern. We reset it
1945 /* Always count groups, whether or not bufp->no_sub is set. */
1949 /* bufp->multibyte is set before regex_compile is called, so don't alter
1951 #else /* not emacs */
1952 /* Nothing is recognized as a multibyte character. */
1953 bufp->multibyte = 0;
1956 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1957 /* Initialize the syntax table. */
1958 init_syntax_once ();
1961 if (bufp->allocated == 0)
1964 { /* If zero allocated, but buffer is non-null, try to realloc
1965 enough space. This loses if buffer's address is bogus, but
1966 that is the user's responsibility. */
1967 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1970 { /* Caller did not allocate a buffer. Do it for them. */
1971 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1973 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1975 bufp->allocated = INIT_BUF_SIZE;
1978 begalt = b = bufp->buffer;
1980 /* Loop through the uncompiled pattern until we're at the end. */
1989 if ( /* If at start of pattern, it's an operator. */
1991 /* If context independent, it's an operator. */
1992 || syntax & RE_CONTEXT_INDEP_ANCHORS
1993 /* Otherwise, depends on what's come before. */
1994 || at_begline_loc_p (pattern, p, syntax))
2004 if ( /* If at end of pattern, it's an operator. */
2006 /* If context independent, it's an operator. */
2007 || syntax & RE_CONTEXT_INDEP_ANCHORS
2008 /* Otherwise, depends on what's next. */
2009 || at_endline_loc_p (p, pend, syntax))
2019 if ((syntax & RE_BK_PLUS_QM)
2020 || (syntax & RE_LIMITED_OPS))
2024 /* If there is no previous pattern... */
2027 if (syntax & RE_CONTEXT_INVALID_OPS)
2028 FREE_STACK_RETURN (REG_BADRPT);
2029 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2034 /* Are we optimizing this jump? */
2035 boolean keep_string_p = false;
2037 /* 1 means zero (many) matches is allowed. */
2038 char zero_times_ok = 0, many_times_ok = 0;
2040 /* If there is a sequence of repetition chars, collapse it
2041 down to just one (the right one). We can't combine
2042 interval operators with these because of, e.g., `a{2}*',
2043 which should only match an even number of `a's. */
2047 zero_times_ok |= c != '+';
2048 many_times_ok |= c != '?';
2056 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2059 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2061 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2064 if (!(c1 == '+' || c1 == '?'))
2079 /* If we get here, we found another repeat character. */
2082 /* Star, etc. applied to an empty pattern is equivalent
2083 to an empty pattern. */
2087 /* Now we know whether or not zero matches is allowed
2088 and also whether or not two or more matches is allowed. */
2090 { /* More than one repetition is allowed, so put in at the
2091 end a backward relative jump from `b' to before the next
2092 jump we're going to put in below (which jumps from
2093 laststart to after this jump).
2095 But if we are at the `*' in the exact sequence `.*\n',
2096 insert an unconditional jump backwards to the .,
2097 instead of the beginning of the loop. This way we only
2098 push a failure point once, instead of every time
2099 through the loop. */
2100 assert (p - 1 > pattern);
2102 /* Allocate the space for the jump. */
2103 GET_BUFFER_SPACE (3);
2105 /* We know we are not at the first character of the pattern,
2106 because laststart was nonzero. And we've already
2107 incremented `p', by the way, to be the character after
2108 the `*'. Do we have to do something analogous here
2109 for null bytes, because of RE_DOT_NOT_NULL? */
2110 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2112 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2113 && !(syntax & RE_DOT_NEWLINE))
2114 { /* We have .*\n. */
2115 STORE_JUMP (jump, b, laststart);
2116 keep_string_p = true;
2119 /* Anything else. */
2120 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2122 /* We've added more stuff to the buffer. */
2126 /* On failure, jump from laststart to b + 3, which will be the
2127 end of the buffer after this jump is inserted. */
2128 GET_BUFFER_SPACE (3);
2129 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2137 /* At least one repetition is required, so insert a
2138 `dummy_failure_jump' before the initial
2139 `on_failure_jump' instruction of the loop. This
2140 effects a skip over that instruction the first time
2141 we hit that loop. */
2142 GET_BUFFER_SPACE (3);
2143 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2158 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2160 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2162 /* Ensure that we have enough space to push a charset: the
2163 opcode, the length count, and the bitset; 34 bytes in all. */
2164 GET_BUFFER_SPACE (34);
2168 /* We test `*p == '^' twice, instead of using an if
2169 statement, so we only need one BUF_PUSH. */
2170 BUF_PUSH (*p == '^' ? charset_not : charset);
2174 /* Remember the first position in the bracket expression. */
2177 /* Push the number of bytes in the bitmap. */
2178 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2180 /* Clear the whole map. */
2181 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2183 /* charset_not matches newline according to a syntax bit. */
2184 if ((re_opcode_t) b[-2] == charset_not
2185 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2186 SET_LIST_BIT ('\n');
2188 /* Read in characters and ranges, setting map bits. */
2192 boolean escaped_char = false;
2194 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2198 /* \ might escape characters inside [...] and [^...]. */
2199 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2201 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2204 escaped_char = true;
2208 /* Could be the end of the bracket expression. If it's
2209 not (i.e., when the bracket expression is `[]' so
2210 far), the ']' character bit gets set way below. */
2211 if (c == ']' && p != p1 + 1)
2215 /* If C indicates start of multibyte char, get the
2216 actual character code in C, and set the pattern
2217 pointer P to the next character boundary. */
2218 if (bufp->multibyte && BASE_LEADING_CODE_P (c))
2221 c = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2224 /* What should we do for the character which is
2225 greater than 0x7F, but not BASE_LEADING_CODE_P?
2228 /* See if we're at the beginning of a possible character
2231 else if (!escaped_char &&
2232 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2234 /* Leave room for the null. */
2235 char str[CHAR_CLASS_MAX_LENGTH + 1];
2240 /* If pattern is `[[:'. */
2241 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2246 if (c == ':' || c == ']' || p == pend
2247 || c1 == CHAR_CLASS_MAX_LENGTH)
2253 /* If isn't a word bracketed by `[:' and `:]':
2254 undo the ending character, the letters, and
2255 leave the leading `:' and `[' (but set bits for
2257 if (c == ':' && *p == ']')
2260 boolean is_alnum = STREQ (str, "alnum");
2261 boolean is_alpha = STREQ (str, "alpha");
2262 boolean is_blank = STREQ (str, "blank");
2263 boolean is_cntrl = STREQ (str, "cntrl");
2264 boolean is_digit = STREQ (str, "digit");
2265 boolean is_graph = STREQ (str, "graph");
2266 boolean is_lower = STREQ (str, "lower");
2267 boolean is_print = STREQ (str, "print");
2268 boolean is_punct = STREQ (str, "punct");
2269 boolean is_space = STREQ (str, "space");
2270 boolean is_upper = STREQ (str, "upper");
2271 boolean is_xdigit = STREQ (str, "xdigit");
2273 if (!IS_CHAR_CLASS (str))
2274 FREE_STACK_RETURN (REG_ECTYPE);
2276 /* Throw away the ] at the end of the character
2280 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2282 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2284 int translated = TRANSLATE (ch);
2285 /* This was split into 3 if's to
2286 avoid an arbitrary limit in some compiler. */
2287 if ( (is_alnum && ISALNUM (ch))
2288 || (is_alpha && ISALPHA (ch))
2289 || (is_blank && ISBLANK (ch))
2290 || (is_cntrl && ISCNTRL (ch)))
2291 SET_LIST_BIT (translated);
2292 if ( (is_digit && ISDIGIT (ch))
2293 || (is_graph && ISGRAPH (ch))
2294 || (is_lower && ISLOWER (ch))
2295 || (is_print && ISPRINT (ch)))
2296 SET_LIST_BIT (translated);
2297 if ( (is_punct && ISPUNCT (ch))
2298 || (is_space && ISSPACE (ch))
2299 || (is_upper && ISUPPER (ch))
2300 || (is_xdigit && ISXDIGIT (ch)))
2301 SET_LIST_BIT (translated);
2304 /* Repeat the loop. */
2314 /* Because the `:' may starts the range, we
2315 can't simply set bit and repeat the loop.
2316 Instead, just set it to C and handle below. */
2321 if (p < pend && p[0] == '-' && p[1] != ']')
2324 /* Discard the `-'. */
2327 /* Fetch the character which ends the range. */
2329 if (bufp->multibyte && BASE_LEADING_CODE_P (c1))
2332 c1 = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2336 if (!SAME_CHARSET_P (c, c1))
2337 FREE_STACK_RETURN (REG_ERANGE);
2340 /* Range from C to C. */
2343 /* Set the range ... */
2344 if (SINGLE_BYTE_CHAR_P (c))
2345 /* ... into bitmap. */
2348 int range_start = c, range_end = c1;
2350 /* If the start is after the end, the range is empty. */
2351 if (range_start > range_end)
2353 if (syntax & RE_NO_EMPTY_RANGES)
2354 FREE_STACK_RETURN (REG_ERANGE);
2355 /* Else, repeat the loop. */
2359 for (this_char = range_start; this_char <= range_end;
2361 SET_LIST_BIT (TRANSLATE (this_char));
2365 /* ... into range table. */
2366 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2369 /* Discard any (non)matching list bytes that are all 0 at the
2370 end of the map. Decrease the map-length byte too. */
2371 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2375 /* Build real range table from work area. */
2376 if (RANGE_TABLE_WORK_USED (range_table_work))
2379 int used = RANGE_TABLE_WORK_USED (range_table_work);
2381 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2382 bytes for COUNT and three bytes for each character. */
2383 GET_BUFFER_SPACE (2 + used * 3);
2385 /* Indicate the existence of range table. */
2386 laststart[1] |= 0x80;
2388 STORE_NUMBER_AND_INCR (b, used / 2);
2389 for (i = 0; i < used; i++)
2390 STORE_CHARACTER_AND_INCR
2391 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2398 if (syntax & RE_NO_BK_PARENS)
2405 if (syntax & RE_NO_BK_PARENS)
2412 if (syntax & RE_NEWLINE_ALT)
2419 if (syntax & RE_NO_BK_VBAR)
2426 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2427 goto handle_interval;
2433 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2435 /* Do not translate the character after the \, so that we can
2436 distinguish, e.g., \B from \b, even if we normally would
2437 translate, e.g., B to b. */
2443 if (syntax & RE_NO_BK_PARENS)
2444 goto normal_backslash;
2450 if (COMPILE_STACK_FULL)
2452 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2453 compile_stack_elt_t);
2454 if (compile_stack.stack == NULL) return REG_ESPACE;
2456 compile_stack.size <<= 1;
2459 /* These are the values to restore when we hit end of this
2460 group. They are all relative offsets, so that if the
2461 whole pattern moves because of realloc, they will still
2463 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2464 COMPILE_STACK_TOP.fixup_alt_jump
2465 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2466 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2467 COMPILE_STACK_TOP.regnum = regnum;
2469 /* We will eventually replace the 0 with the number of
2470 groups inner to this one. But do not push a
2471 start_memory for groups beyond the last one we can
2472 represent in the compiled pattern. */
2473 if (regnum <= MAX_REGNUM)
2475 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2476 BUF_PUSH_3 (start_memory, regnum, 0);
2479 compile_stack.avail++;
2484 /* If we've reached MAX_REGNUM groups, then this open
2485 won't actually generate any code, so we'll have to
2486 clear pending_exact explicitly. */
2492 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2494 if (COMPILE_STACK_EMPTY)
2495 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2496 goto normal_backslash;
2498 FREE_STACK_RETURN (REG_ERPAREN);
2502 { /* Push a dummy failure point at the end of the
2503 alternative for a possible future
2504 `pop_failure_jump' to pop. See comments at
2505 `push_dummy_failure' in `re_match_2'. */
2506 BUF_PUSH (push_dummy_failure);
2508 /* We allocated space for this jump when we assigned
2509 to `fixup_alt_jump', in the `handle_alt' case below. */
2510 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2513 /* See similar code for backslashed left paren above. */
2514 if (COMPILE_STACK_EMPTY)
2515 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2518 FREE_STACK_RETURN (REG_ERPAREN);
2520 /* Since we just checked for an empty stack above, this
2521 ``can't happen''. */
2522 assert (compile_stack.avail != 0);
2524 /* We don't just want to restore into `regnum', because
2525 later groups should continue to be numbered higher,
2526 as in `(ab)c(de)' -- the second group is #2. */
2527 regnum_t this_group_regnum;
2529 compile_stack.avail--;
2530 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2532 = COMPILE_STACK_TOP.fixup_alt_jump
2533 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2535 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2536 this_group_regnum = COMPILE_STACK_TOP.regnum;
2537 /* If we've reached MAX_REGNUM groups, then this open
2538 won't actually generate any code, so we'll have to
2539 clear pending_exact explicitly. */
2542 /* We're at the end of the group, so now we know how many
2543 groups were inside this one. */
2544 if (this_group_regnum <= MAX_REGNUM)
2546 unsigned char *inner_group_loc
2547 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2549 *inner_group_loc = regnum - this_group_regnum;
2550 BUF_PUSH_3 (stop_memory, this_group_regnum,
2551 regnum - this_group_regnum);
2557 case '|': /* `\|'. */
2558 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2559 goto normal_backslash;
2561 if (syntax & RE_LIMITED_OPS)
2564 /* Insert before the previous alternative a jump which
2565 jumps to this alternative if the former fails. */
2566 GET_BUFFER_SPACE (3);
2567 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2571 /* The alternative before this one has a jump after it
2572 which gets executed if it gets matched. Adjust that
2573 jump so it will jump to this alternative's analogous
2574 jump (put in below, which in turn will jump to the next
2575 (if any) alternative's such jump, etc.). The last such
2576 jump jumps to the correct final destination. A picture:
2582 If we are at `b', then fixup_alt_jump right now points to a
2583 three-byte space after `a'. We'll put in the jump, set
2584 fixup_alt_jump to right after `b', and leave behind three
2585 bytes which we'll fill in when we get to after `c'. */
2588 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2590 /* Mark and leave space for a jump after this alternative,
2591 to be filled in later either by next alternative or
2592 when know we're at the end of a series of alternatives. */
2594 GET_BUFFER_SPACE (3);
2603 /* If \{ is a literal. */
2604 if (!(syntax & RE_INTERVALS)
2605 /* If we're at `\{' and it's not the open-interval
2607 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2608 || (p - 2 == pattern && p == pend))
2609 goto normal_backslash;
2613 /* If got here, then the syntax allows intervals. */
2615 /* At least (most) this many matches must be made. */
2616 int lower_bound = -1, upper_bound = -1;
2618 beg_interval = p - 1;
2622 if (syntax & RE_NO_BK_BRACES)
2623 goto unfetch_interval;
2625 FREE_STACK_RETURN (REG_EBRACE);
2628 GET_UNSIGNED_NUMBER (lower_bound);
2632 GET_UNSIGNED_NUMBER (upper_bound);
2633 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2636 /* Interval such as `{1}' => match exactly once. */
2637 upper_bound = lower_bound;
2639 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2640 || lower_bound > upper_bound)
2642 if (syntax & RE_NO_BK_BRACES)
2643 goto unfetch_interval;
2645 FREE_STACK_RETURN (REG_BADBR);
2648 if (!(syntax & RE_NO_BK_BRACES))
2650 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2657 if (syntax & RE_NO_BK_BRACES)
2658 goto unfetch_interval;
2660 FREE_STACK_RETURN (REG_BADBR);
2663 /* We just parsed a valid interval. */
2665 /* If it's invalid to have no preceding re. */
2668 if (syntax & RE_CONTEXT_INVALID_OPS)
2669 FREE_STACK_RETURN (REG_BADRPT);
2670 else if (syntax & RE_CONTEXT_INDEP_OPS)
2673 goto unfetch_interval;
2676 /* If the upper bound is zero, don't want to succeed at
2677 all; jump from `laststart' to `b + 3', which will be
2678 the end of the buffer after we insert the jump. */
2679 if (upper_bound == 0)
2681 GET_BUFFER_SPACE (3);
2682 INSERT_JUMP (jump, laststart, b + 3);
2686 /* Otherwise, we have a nontrivial interval. When
2687 we're all done, the pattern will look like:
2688 set_number_at <jump count> <upper bound>
2689 set_number_at <succeed_n count> <lower bound>
2690 succeed_n <after jump addr> <succeed_n count>
2692 jump_n <succeed_n addr> <jump count>
2693 (The upper bound and `jump_n' are omitted if
2694 `upper_bound' is 1, though.) */
2696 { /* If the upper bound is > 1, we need to insert
2697 more at the end of the loop. */
2698 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2700 GET_BUFFER_SPACE (nbytes);
2702 /* Initialize lower bound of the `succeed_n', even
2703 though it will be set during matching by its
2704 attendant `set_number_at' (inserted next),
2705 because `re_compile_fastmap' needs to know.
2706 Jump to the `jump_n' we might insert below. */
2707 INSERT_JUMP2 (succeed_n, laststart,
2708 b + 5 + (upper_bound > 1) * 5,
2712 /* Code to initialize the lower bound. Insert
2713 before the `succeed_n'. The `5' is the last two
2714 bytes of this `set_number_at', plus 3 bytes of
2715 the following `succeed_n'. */
2716 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2719 if (upper_bound > 1)
2720 { /* More than one repetition is allowed, so
2721 append a backward jump to the `succeed_n'
2722 that starts this interval.
2724 When we've reached this during matching,
2725 we'll have matched the interval once, so
2726 jump back only `upper_bound - 1' times. */
2727 STORE_JUMP2 (jump_n, b, laststart + 5,
2731 /* The location we want to set is the second
2732 parameter of the `jump_n'; that is `b-2' as
2733 an absolute address. `laststart' will be
2734 the `set_number_at' we're about to insert;
2735 `laststart+3' the number to set, the source
2736 for the relative address. But we are
2737 inserting into the middle of the pattern --
2738 so everything is getting moved up by 5.
2739 Conclusion: (b - 2) - (laststart + 3) + 5,
2740 i.e., b - laststart.
2742 We insert this at the beginning of the loop
2743 so that if we fail during matching, we'll
2744 reinitialize the bounds. */
2745 insert_op2 (set_number_at, laststart, b - laststart,
2746 upper_bound - 1, b);
2751 beg_interval = NULL;
2756 /* If an invalid interval, match the characters as literals. */
2757 assert (beg_interval);
2759 beg_interval = NULL;
2761 /* normal_char and normal_backslash need `c'. */
2764 if (!(syntax & RE_NO_BK_BRACES))
2766 if (p > pattern && p[-1] == '\\')
2767 goto normal_backslash;
2772 /* There is no way to specify the before_dot and after_dot
2773 operators. rms says this is ok. --karl */
2781 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2787 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2793 BUF_PUSH_2 (categoryspec, c);
2799 BUF_PUSH_2 (notcategoryspec, c);
2806 BUF_PUSH (wordchar);
2812 BUF_PUSH (notwordchar);
2825 BUF_PUSH (wordbound);
2829 BUF_PUSH (notwordbound);
2840 case '1': case '2': case '3': case '4': case '5':
2841 case '6': case '7': case '8': case '9':
2842 if (syntax & RE_NO_BK_REFS)
2848 FREE_STACK_RETURN (REG_ESUBREG);
2850 /* Can't back reference to a subexpression if inside of it. */
2851 if (group_in_compile_stack (compile_stack, c1))
2855 BUF_PUSH_2 (duplicate, c1);
2861 if (syntax & RE_BK_PLUS_QM)
2864 goto normal_backslash;
2868 /* You might think it would be useful for \ to mean
2869 not to translate; but if we don't translate it
2870 it will never match anything. */
2878 /* Expects the character in `c'. */
2880 p1 = p - 1; /* P1 points the head of C. */
2882 if (bufp->multibyte)
2883 /* Set P to the next character boundary. */
2884 p += MULTIBYTE_FORM_LENGTH (p1, pend - p1) - 1;
2886 /* If no exactn currently being built. */
2889 /* If last exactn not at current position. */
2890 || pending_exact + *pending_exact + 1 != b
2892 /* We have only one byte following the exactn for the count. */
2893 || *pending_exact >= (1 << BYTEWIDTH) - (p - p1)
2895 /* If followed by a repetition operator. */
2896 || *p == '*' || *p == '^'
2897 || ((syntax & RE_BK_PLUS_QM)
2898 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2899 : (*p == '+' || *p == '?'))
2900 || ((syntax & RE_INTERVALS)
2901 && ((syntax & RE_NO_BK_BRACES)
2903 : (p[0] == '\\' && p[1] == '{'))))
2905 /* Start building a new exactn. */
2909 BUF_PUSH_2 (exactn, 0);
2910 pending_exact = b - 1;
2913 /* Here, C may translated, therefore C may not equal to *P1. */
2921 /* Rest of multibyte form should be copied literally. */
2922 c = *(unsigned char *)p1;
2926 } /* while p != pend */
2929 /* Through the pattern now. */
2932 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2934 if (!COMPILE_STACK_EMPTY)
2935 FREE_STACK_RETURN (REG_EPAREN);
2937 /* If we don't want backtracking, force success
2938 the first time we reach the end of the compiled pattern. */
2939 if (syntax & RE_NO_POSIX_BACKTRACKING)
2942 free (compile_stack.stack);
2944 /* We have succeeded; set the length of the buffer. */
2945 bufp->used = b - bufp->buffer;
2950 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2951 print_compiled_pattern (bufp);
2955 #ifndef MATCH_MAY_ALLOCATE
2956 /* Initialize the failure stack to the largest possible stack. This
2957 isn't necessary unless we're trying to avoid calling alloca in
2958 the search and match routines. */
2960 int num_regs = bufp->re_nsub + 1;
2962 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
2964 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE);
2967 if (! fail_stack.stack)
2969 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2970 * sizeof (fail_stack_elt_t));
2973 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2975 * sizeof (fail_stack_elt_t)));
2976 #else /* not emacs */
2977 if (! fail_stack.stack)
2979 = (fail_stack_elt_t *) malloc (fail_stack.size
2980 * sizeof (fail_stack_elt_t));
2983 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2985 * sizeof (fail_stack_elt_t)));
2986 #endif /* not emacs */
2989 regex_grow_registers (num_regs);
2991 #endif /* not MATCH_MAY_ALLOCATE */
2994 } /* regex_compile */
2996 /* Subroutines for `regex_compile'. */
2998 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3001 store_op1 (op, loc, arg)
3006 *loc = (unsigned char) op;
3007 STORE_NUMBER (loc + 1, arg);
3011 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3014 store_op2 (op, loc, arg1, arg2)
3019 *loc = (unsigned char) op;
3020 STORE_NUMBER (loc + 1, arg1);
3021 STORE_NUMBER (loc + 3, arg2);
3025 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3026 for OP followed by two-byte integer parameter ARG. */
3029 insert_op1 (op, loc, arg, end)
3035 register unsigned char *pfrom = end;
3036 register unsigned char *pto = end + 3;
3038 while (pfrom != loc)
3041 store_op1 (op, loc, arg);
3045 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3048 insert_op2 (op, loc, arg1, arg2, end)
3054 register unsigned char *pfrom = end;
3055 register unsigned char *pto = end + 5;
3057 while (pfrom != loc)
3060 store_op2 (op, loc, arg1, arg2);
3064 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3065 after an alternative or a begin-subexpression. We assume there is at
3066 least one character before the ^. */
3069 at_begline_loc_p (pattern, p, syntax)
3070 const char *pattern, *p;
3071 reg_syntax_t syntax;
3073 const char *prev = p - 2;
3074 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3077 /* After a subexpression? */
3078 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3079 /* After an alternative? */
3080 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3084 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3085 at least one character after the $, i.e., `P < PEND'. */
3088 at_endline_loc_p (p, pend, syntax)
3089 const char *p, *pend;
3092 const char *next = p;
3093 boolean next_backslash = *next == '\\';
3094 const char *next_next = p + 1 < pend ? p + 1 : 0;
3097 /* Before a subexpression? */
3098 (syntax & RE_NO_BK_PARENS ? *next == ')'
3099 : next_backslash && next_next && *next_next == ')')
3100 /* Before an alternative? */
3101 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3102 : next_backslash && next_next && *next_next == '|');
3106 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3107 false if it's not. */
3110 group_in_compile_stack (compile_stack, regnum)
3111 compile_stack_type compile_stack;
3116 for (this_element = compile_stack.avail - 1;
3119 if (compile_stack.stack[this_element].regnum == regnum)
3126 /* Read the ending character of a range (in a bracket expression) from the
3127 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3128 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3129 Then we set the translation of all bits between the starting and
3130 ending characters (inclusive) in the compiled pattern B.
3132 Return an error code.
3134 We use these short variable names so we can use the same macros as
3135 `regex_compile' itself. */
3137 static reg_errcode_t
3138 compile_range (p_ptr, pend, translate, syntax, b)
3139 const char **p_ptr, *pend;
3140 RE_TRANSLATE_TYPE translate;
3141 reg_syntax_t syntax;
3146 const char *p = *p_ptr;
3147 int range_start, range_end;
3152 /* Even though the pattern is a signed `char *', we need to fetch
3153 with unsigned char *'s; if the high bit of the pattern character
3154 is set, the range endpoints will be negative if we fetch using a
3157 We also want to fetch the endpoints without translating them; the
3158 appropriate translation is done in the bit-setting loop below. */
3159 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
3160 range_start = ((const unsigned char *) p)[-2];
3161 range_end = ((const unsigned char *) p)[0];
3163 /* Have to increment the pointer into the pattern string, so the
3164 caller isn't still at the ending character. */
3167 /* If the start is after the end, the range is empty. */
3168 if (range_start > range_end)
3169 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3171 /* Here we see why `this_char' has to be larger than an `unsigned
3172 char' -- the range is inclusive, so if `range_end' == 0xff
3173 (assuming 8-bit characters), we would otherwise go into an infinite
3174 loop, since all characters <= 0xff. */
3175 for (this_char = range_start; this_char <= range_end; this_char++)
3177 SET_LIST_BIT (TRANSLATE (this_char));
3183 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3184 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3185 characters can start a string that matches the pattern. This fastmap
3186 is used by re_search to skip quickly over impossible starting points.
3188 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3189 area as BUFP->fastmap.
3191 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3194 Returns 0 if we succeed, -2 if an internal error. */
3197 re_compile_fastmap (bufp)
3198 struct re_pattern_buffer *bufp;
3201 #ifdef MATCH_MAY_ALLOCATE
3202 fail_stack_type fail_stack;
3204 #ifndef REGEX_MALLOC
3207 /* We don't push any register information onto the failure stack. */
3208 unsigned num_regs = 0;
3210 register char *fastmap = bufp->fastmap;
3211 unsigned char *pattern = bufp->buffer;
3212 unsigned long size = bufp->used;
3213 unsigned char *p = pattern;
3214 register unsigned char *pend = pattern + size;
3216 /* This holds the pointer to the failure stack, when
3217 it is allocated relocatably. */
3218 fail_stack_elt_t *failure_stack_ptr;
3220 /* Assume that each path through the pattern can be null until
3221 proven otherwise. We set this false at the bottom of switch
3222 statement, to which we get only if a particular path doesn't
3223 match the empty string. */
3224 boolean path_can_be_null = true;
3226 /* We aren't doing a `succeed_n' to begin with. */
3227 boolean succeed_n_p = false;
3229 /* If all elements for base leading-codes in fastmap is set, this
3230 flag is set true. */
3231 boolean match_any_multibyte_characters = false;
3233 /* Maximum code of simple (single byte) character. */
3234 int simple_char_max;
3236 assert (fastmap != NULL && p != NULL);
3239 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3240 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3241 bufp->can_be_null = 0;
3245 if (p == pend || *p == succeed)
3247 /* We have reached the (effective) end of pattern. */
3248 if (!FAIL_STACK_EMPTY ())
3250 bufp->can_be_null |= path_can_be_null;
3252 /* Reset for next path. */
3253 path_can_be_null = true;
3255 p = fail_stack.stack[--fail_stack.avail].pointer;
3263 /* We should never be about to go beyond the end of the pattern. */
3266 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3269 /* I guess the idea here is to simply not bother with a fastmap
3270 if a backreference is used, since it's too hard to figure out
3271 the fastmap for the corresponding group. Setting
3272 `can_be_null' stops `re_search_2' from using the fastmap, so
3273 that is all we do. */
3275 bufp->can_be_null = 1;
3279 /* Following are the cases which match a character. These end
3289 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3290 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3296 /* Chars beyond end of map must be allowed. */
3297 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3300 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3301 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3307 for (j = 0; j < (1 << BYTEWIDTH); j++)
3308 if (SYNTAX (j) == Sword)
3314 for (j = 0; j < (1 << BYTEWIDTH); j++)
3315 if (SYNTAX (j) != Sword)
3320 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3322 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3325 if (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3326 && match_any_multibyte_characters == false)
3328 /* Set fastmap[I] 1 where I is a base leading code of each
3329 multibyte character in the range table. */
3332 /* Make P points the range table. */
3333 p += CHARSET_BITMAP_SIZE (&p[-2]);
3335 /* Extract the number of ranges in range table into
3337 EXTRACT_NUMBER_AND_INCR (count, p);
3338 for (; count > 0; count--, p += 2 * 3) /* XXX */
3340 /* Extract the start of each range. */
3341 EXTRACT_CHARACTER (c, p);
3342 j = CHAR_CHARSET (c);
3343 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3350 /* Chars beyond end of map must be allowed. End of map is
3351 `127' if bufp->multibyte is nonzero. */
3352 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3353 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3354 j < simple_char_max; j++)
3357 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3359 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3362 if (bufp->multibyte)
3363 /* Any character set can possibly contain a character
3364 which doesn't match the specified set of characters. */
3366 set_fastmap_for_multibyte_characters:
3367 if (match_any_multibyte_characters == false)
3369 for (j = 0x80; j < 0xA0; j++) /* XXX */
3370 if (BASE_LEADING_CODE_P (j))
3372 match_any_multibyte_characters = true;
3379 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3380 for (j = 0; j < simple_char_max; j++)
3381 if (SYNTAX (j) == Sword)
3384 if (bufp->multibyte)
3385 /* Any character set can possibly contain a character
3386 whose syntax is `Sword'. */
3387 goto set_fastmap_for_multibyte_characters;
3392 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3393 for (j = 0; j < simple_char_max; j++)
3394 if (SYNTAX (j) != Sword)
3397 if (bufp->multibyte)
3398 /* Any character set can possibly contain a character
3399 whose syntax is not `Sword'. */
3400 goto set_fastmap_for_multibyte_characters;
3406 int fastmap_newline = fastmap['\n'];
3408 /* `.' matches anything (but if bufp->multibyte is
3409 nonzero, matches `\000' .. `\127' and possible multibyte
3411 if (bufp->multibyte)
3413 simple_char_max = 0x80;
3415 for (j = 0x80; j < 0xA0; j++)
3416 if (BASE_LEADING_CODE_P (j))
3418 match_any_multibyte_characters = true;
3421 simple_char_max = (1 << BYTEWIDTH);
3423 for (j = 0; j < simple_char_max; j++)
3426 /* ... except perhaps newline. */
3427 if (!(bufp->syntax & RE_DOT_NEWLINE))
3428 fastmap['\n'] = fastmap_newline;
3430 /* Return if we have already set `can_be_null'; if we have,
3431 then the fastmap is irrelevant. Something's wrong here. */
3432 else if (bufp->can_be_null)
3435 /* Otherwise, have to check alternative paths. */
3446 /* This match depends on text properties. These end with
3447 aborting optimizations. */
3448 bufp->can_be_null = 1;
3452 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3453 for (j = 0; j < simple_char_max; j++)
3454 if (SYNTAX (j) == (enum syntaxcode) k)
3457 if (bufp->multibyte)
3458 /* Any character set can possibly contain a character
3459 whose syntax is K. */
3460 goto set_fastmap_for_multibyte_characters;
3465 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3466 for (j = 0; j < simple_char_max; j++)
3467 if (SYNTAX (j) != (enum syntaxcode) k)
3470 if (bufp->multibyte)
3471 /* Any character set can possibly contain a character
3472 whose syntax is not K. */
3473 goto set_fastmap_for_multibyte_characters;
3480 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3481 for (j = 0; j < simple_char_max; j++)
3482 if (CHAR_HAS_CATEGORY (j, k))
3485 if (bufp->multibyte)
3486 /* Any character set can possibly contain a character
3487 whose category is K. */
3488 goto set_fastmap_for_multibyte_characters;
3492 case notcategoryspec:
3494 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3495 for (j = 0; j < simple_char_max; j++)
3496 if (!CHAR_HAS_CATEGORY (j, k))
3499 if (bufp->multibyte)
3500 /* Any character set can possibly contain a character
3501 whose category is not K. */
3502 goto set_fastmap_for_multibyte_characters;
3505 /* All cases after this match the empty string. These end with
3527 case push_dummy_failure:
3532 case pop_failure_jump:
3533 case maybe_pop_jump:
3536 case dummy_failure_jump:
3537 EXTRACT_NUMBER_AND_INCR (j, p);
3542 /* Jump backward implies we just went through the body of a
3543 loop and matched nothing. Opcode jumped to should be
3544 `on_failure_jump' or `succeed_n'. Just treat it like an
3545 ordinary jump. For a * loop, it has pushed its failure
3546 point already; if so, discard that as redundant. */
3547 if ((re_opcode_t) *p != on_failure_jump
3548 && (re_opcode_t) *p != succeed_n)
3552 EXTRACT_NUMBER_AND_INCR (j, p);
3555 /* If what's on the stack is where we are now, pop it. */
3556 if (!FAIL_STACK_EMPTY ()
3557 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3563 case on_failure_jump:
3564 case on_failure_keep_string_jump:
3565 handle_on_failure_jump:
3566 EXTRACT_NUMBER_AND_INCR (j, p);
3568 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3569 end of the pattern. We don't want to push such a point,
3570 since when we restore it above, entering the switch will
3571 increment `p' past the end of the pattern. We don't need
3572 to push such a point since we obviously won't find any more
3573 fastmap entries beyond `pend'. Such a pattern can match
3574 the null string, though. */
3577 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3579 RESET_FAIL_STACK ();
3584 bufp->can_be_null = 1;
3588 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3589 succeed_n_p = false;
3596 /* Get to the number of times to succeed. */
3599 /* Increment p past the n for when k != 0. */
3600 EXTRACT_NUMBER_AND_INCR (k, p);
3604 succeed_n_p = true; /* Spaghetti code alert. */
3605 goto handle_on_failure_jump;
3622 abort (); /* We have listed all the cases. */
3625 /* Getting here means we have found the possible starting
3626 characters for one path of the pattern -- and that the empty
3627 string does not match. We need not follow this path further.
3628 Instead, look at the next alternative (remembered on the
3629 stack), or quit if no more. The test at the top of the loop
3630 does these things. */
3631 path_can_be_null = false;
3635 /* Set `can_be_null' for the last path (also the first path, if the
3636 pattern is empty). */
3637 bufp->can_be_null |= path_can_be_null;
3640 RESET_FAIL_STACK ();
3642 } /* re_compile_fastmap */
3644 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3645 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3646 this memory for recording register information. STARTS and ENDS
3647 must be allocated using the malloc library routine, and must each
3648 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3650 If NUM_REGS == 0, then subsequent matches should allocate their own
3653 Unless this function is called, the first search or match using
3654 PATTERN_BUFFER will allocate its own register data, without
3655 freeing the old data. */
3658 re_set_registers (bufp, regs, num_regs, starts, ends)
3659 struct re_pattern_buffer *bufp;
3660 struct re_registers *regs;
3662 regoff_t *starts, *ends;
3666 bufp->regs_allocated = REGS_REALLOCATE;
3667 regs->num_regs = num_regs;
3668 regs->start = starts;
3673 bufp->regs_allocated = REGS_UNALLOCATED;
3675 regs->start = regs->end = (regoff_t *) 0;
3679 /* Searching routines. */
3681 /* Like re_search_2, below, but only one string is specified, and
3682 doesn't let you say where to stop matching. */
3685 re_search (bufp, string, size, startpos, range, regs)
3686 struct re_pattern_buffer *bufp;
3688 int size, startpos, range;
3689 struct re_registers *regs;
3691 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3695 /* End address of virtual concatenation of string. */
3696 #define STOP_ADDR_VSTRING(P) \
3697 (((P) >= size1 ? string2 + size2 : string1 + size1))
3699 /* Address of POS in the concatenation of virtual string. */
3700 #define POS_ADDR_VSTRING(POS) \
3701 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3703 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3704 virtual concatenation of STRING1 and STRING2, starting first at index
3705 STARTPOS, then at STARTPOS + 1, and so on.
3707 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3709 RANGE is how far to scan while trying to match. RANGE = 0 means try
3710 only at STARTPOS; in general, the last start tried is STARTPOS +
3713 In REGS, return the indices of the virtual concatenation of STRING1
3714 and STRING2 that matched the entire BUFP->buffer and its contained
3717 Do not consider matching one past the index STOP in the virtual
3718 concatenation of STRING1 and STRING2.
3720 We return either the position in the strings at which the match was
3721 found, -1 if no match, or -2 if error (such as failure
3725 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3726 struct re_pattern_buffer *bufp;
3727 const char *string1, *string2;
3731 struct re_registers *regs;
3735 register char *fastmap = bufp->fastmap;
3736 register RE_TRANSLATE_TYPE translate = bufp->translate;
3737 int total_size = size1 + size2;
3738 int endpos = startpos + range;
3739 int anchored_start = 0;
3741 /* Nonzero if we have to concern multibyte character. */
3742 int multibyte = bufp->multibyte;
3744 /* Check for out-of-range STARTPOS. */
3745 if (startpos < 0 || startpos > total_size)
3748 /* Fix up RANGE if it might eventually take us outside
3749 the virtual concatenation of STRING1 and STRING2.
3750 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3752 range = 0 - startpos;
3753 else if (endpos > total_size)
3754 range = total_size - startpos;
3756 /* If the search isn't to be a backwards one, don't waste time in a
3757 search for a pattern that must be anchored. */
3758 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3767 /* In a forward search for something that starts with \=.
3768 don't keep searching past point. */
3769 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3771 range = PT - startpos;
3777 /* Update the fastmap now if not correct already. */
3778 if (fastmap && !bufp->fastmap_accurate)
3779 if (re_compile_fastmap (bufp) == -2)
3782 /* See whether the pattern is anchored. */
3783 if (bufp->buffer[0] == begline)
3787 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object,
3788 POS_AS_IN_BUFFER (startpos > 0
3789 ? startpos - 1 : startpos),
3793 /* Loop through the string, looking for a place to start matching. */
3796 /* If the pattern is anchored,
3797 skip quickly past places we cannot match.
3798 We don't bother to treat startpos == 0 specially
3799 because that case doesn't repeat. */
3800 if (anchored_start && startpos > 0)
3802 if (! (bufp->newline_anchor
3803 && ((startpos <= size1 ? string1[startpos - 1]
3804 : string2[startpos - size1 - 1])
3809 /* If a fastmap is supplied, skip quickly over characters that
3810 cannot be the start of a match. If the pattern can match the
3811 null string, however, we don't need to skip characters; we want
3812 the first null string. */
3813 if (fastmap && startpos < total_size && !bufp->can_be_null)
3815 if (range > 0) /* Searching forwards. */
3817 register const char *d;
3818 register int lim = 0;
3821 if (startpos < size1 && startpos + range >= size1)
3822 lim = range - (size1 - startpos);
3824 d = POS_ADDR_VSTRING (startpos);
3826 /* Written out as an if-else to avoid testing `translate'
3830 && !fastmap[(unsigned char)
3831 RE_TRANSLATE (translate, (unsigned char) *d++)])
3834 while (range > lim && !fastmap[(unsigned char) *d++])
3837 startpos += irange - range;
3839 else /* Searching backwards. */
3841 register char c = (size1 == 0 || startpos >= size1
3842 ? string2[startpos - size1]
3843 : string1[startpos]);
3845 if (!fastmap[(unsigned char) TRANSLATE (c)])
3850 /* If can't match the null string, and that's all we have left, fail. */
3851 if (range >= 0 && startpos == total_size && fastmap
3852 && !bufp->can_be_null)
3855 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3856 startpos, regs, stop);
3857 #ifndef REGEX_MALLOC
3874 /* Update STARTPOS to the next character boundary. */
3877 const unsigned char *p
3878 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3879 const unsigned char *pend
3880 = (const unsigned char *) STOP_ADDR_VSTRING (startpos);
3881 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
3899 /* Update STARTPOS to the previous character boundary. */
3902 const unsigned char *p
3903 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3906 /* Find the head of multibyte form. */
3907 while (!CHAR_HEAD_P (*p))
3912 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
3929 /* Declarations and macros for re_match_2. */
3931 static int bcmp_translate ();
3932 static boolean alt_match_null_string_p (),
3933 common_op_match_null_string_p (),
3934 group_match_null_string_p ();
3936 /* This converts PTR, a pointer into one of the search strings `string1'
3937 and `string2' into an offset from the beginning of that string. */
3938 #define POINTER_TO_OFFSET(ptr) \
3939 (FIRST_STRING_P (ptr) \
3940 ? ((regoff_t) ((ptr) - string1)) \
3941 : ((regoff_t) ((ptr) - string2 + size1)))
3943 /* Macros for dealing with the split strings in re_match_2. */
3945 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3947 /* Call before fetching a character with *d. This switches over to
3948 string2 if necessary. */
3949 #define PREFETCH() \
3952 /* End of string2 => fail. */ \
3953 if (dend == end_match_2) \
3955 /* End of string1 => advance to string2. */ \
3957 dend = end_match_2; \
3961 /* Test if at very beginning or at very end of the virtual concatenation
3962 of `string1' and `string2'. If only one string, it's `string2'. */
3963 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3964 #define AT_STRINGS_END(d) ((d) == end2)
3967 /* Test if D points to a character which is word-constituent. We have
3968 two special cases to check for: if past the end of string1, look at
3969 the first character in string2; and if before the beginning of
3970 string2, look at the last character in string1. */
3971 #define WORDCHAR_P(d) \
3972 (SYNTAX ((d) == end1 ? *string2 \
3973 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3976 /* Disabled due to a compiler bug -- see comment at case wordbound */
3978 /* The comment at case wordbound is following one, but we don't use
3979 AT_WORD_BOUNDARY anymore to support multibyte form.
3981 The DEC Alpha C compiler 3.x generates incorrect code for the
3982 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
3983 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
3984 macro and introducing temporary variables works around the bug. */
3987 /* Test if the character before D and the one at D differ with respect
3988 to being word-constituent. */
3989 #define AT_WORD_BOUNDARY(d) \
3990 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3991 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3994 /* Free everything we malloc. */
3995 #ifdef MATCH_MAY_ALLOCATE
3996 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
3997 #define FREE_VARIABLES() \
3999 REGEX_FREE_STACK (fail_stack.stack); \
4000 FREE_VAR (regstart); \
4001 FREE_VAR (regend); \
4002 FREE_VAR (old_regstart); \
4003 FREE_VAR (old_regend); \
4004 FREE_VAR (best_regstart); \
4005 FREE_VAR (best_regend); \
4006 FREE_VAR (reg_info); \
4007 FREE_VAR (reg_dummy); \
4008 FREE_VAR (reg_info_dummy); \
4011 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4012 #endif /* not MATCH_MAY_ALLOCATE */
4014 /* These values must meet several constraints. They must not be valid
4015 register values; since we have a limit of 255 registers (because
4016 we use only one byte in the pattern for the register number), we can
4017 use numbers larger than 255. They must differ by 1, because of
4018 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4019 be larger than the value for the highest register, so we do not try
4020 to actually save any registers when none are active. */
4021 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4022 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4024 /* Matching routines. */
4026 #ifndef emacs /* Emacs never uses this. */
4027 /* re_match is like re_match_2 except it takes only a single string. */
4030 re_match (bufp, string, size, pos, regs)
4031 struct re_pattern_buffer *bufp;
4034 struct re_registers *regs;
4036 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4041 #endif /* not emacs */
4044 /* In Emacs, this is the string or buffer in which we
4045 are matching. It is used for looking up syntax properties. */
4046 Lisp_Object re_match_object;
4049 /* re_match_2 matches the compiled pattern in BUFP against the
4050 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4051 and SIZE2, respectively). We start matching at POS, and stop
4054 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4055 store offsets for the substring each group matched in REGS. See the
4056 documentation for exactly how many groups we fill.
4058 We return -1 if no match, -2 if an internal error (such as the
4059 failure stack overflowing). Otherwise, we return the length of the
4060 matched substring. */
4063 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4064 struct re_pattern_buffer *bufp;
4065 const char *string1, *string2;
4068 struct re_registers *regs;
4074 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object,
4075 POS_AS_IN_BUFFER (pos > 0 ? pos - 1 : pos),
4079 result = re_match_2_internal (bufp, string1, size1, string2, size2,
4085 /* This is a separate function so that we can force an alloca cleanup
4088 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4089 struct re_pattern_buffer *bufp;
4090 const char *string1, *string2;
4093 struct re_registers *regs;
4096 /* General temporaries. */
4100 /* Just past the end of the corresponding string. */
4101 const char *end1, *end2;
4103 /* Pointers into string1 and string2, just past the last characters in
4104 each to consider matching. */
4105 const char *end_match_1, *end_match_2;
4107 /* Where we are in the data, and the end of the current string. */
4108 const char *d, *dend;
4110 /* Where we are in the pattern, and the end of the pattern. */
4111 unsigned char *p = bufp->buffer;
4112 register unsigned char *pend = p + bufp->used;
4114 /* Mark the opcode just after a start_memory, so we can test for an
4115 empty subpattern when we get to the stop_memory. */
4116 unsigned char *just_past_start_mem = 0;
4118 /* We use this to map every character in the string. */
4119 RE_TRANSLATE_TYPE translate = bufp->translate;
4121 /* Nonzero if we have to concern multibyte character. */
4122 int multibyte = bufp->multibyte;
4124 /* Failure point stack. Each place that can handle a failure further
4125 down the line pushes a failure point on this stack. It consists of
4126 restart, regend, and reg_info for all registers corresponding to
4127 the subexpressions we're currently inside, plus the number of such
4128 registers, and, finally, two char *'s. The first char * is where
4129 to resume scanning the pattern; the second one is where to resume
4130 scanning the strings. If the latter is zero, the failure point is
4131 a ``dummy''; if a failure happens and the failure point is a dummy,
4132 it gets discarded and the next next one is tried. */
4133 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4134 fail_stack_type fail_stack;
4137 static unsigned failure_id = 0;
4138 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4141 /* This holds the pointer to the failure stack, when
4142 it is allocated relocatably. */
4143 fail_stack_elt_t *failure_stack_ptr;
4145 /* We fill all the registers internally, independent of what we
4146 return, for use in backreferences. The number here includes
4147 an element for register zero. */
4148 unsigned num_regs = bufp->re_nsub + 1;
4150 /* The currently active registers. */
4151 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4152 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4154 /* Information on the contents of registers. These are pointers into
4155 the input strings; they record just what was matched (on this
4156 attempt) by a subexpression part of the pattern, that is, the
4157 regnum-th regstart pointer points to where in the pattern we began
4158 matching and the regnum-th regend points to right after where we
4159 stopped matching the regnum-th subexpression. (The zeroth register
4160 keeps track of what the whole pattern matches.) */
4161 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4162 const char **regstart, **regend;
4165 /* If a group that's operated upon by a repetition operator fails to
4166 match anything, then the register for its start will need to be
4167 restored because it will have been set to wherever in the string we
4168 are when we last see its open-group operator. Similarly for a
4170 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4171 const char **old_regstart, **old_regend;
4174 /* The is_active field of reg_info helps us keep track of which (possibly
4175 nested) subexpressions we are currently in. The matched_something
4176 field of reg_info[reg_num] helps us tell whether or not we have
4177 matched any of the pattern so far this time through the reg_num-th
4178 subexpression. These two fields get reset each time through any
4179 loop their register is in. */
4180 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4181 register_info_type *reg_info;
4184 /* The following record the register info as found in the above
4185 variables when we find a match better than any we've seen before.
4186 This happens as we backtrack through the failure points, which in
4187 turn happens only if we have not yet matched the entire string. */
4188 unsigned best_regs_set = false;
4189 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4190 const char **best_regstart, **best_regend;
4193 /* Logically, this is `best_regend[0]'. But we don't want to have to
4194 allocate space for that if we're not allocating space for anything
4195 else (see below). Also, we never need info about register 0 for
4196 any of the other register vectors, and it seems rather a kludge to
4197 treat `best_regend' differently than the rest. So we keep track of
4198 the end of the best match so far in a separate variable. We
4199 initialize this to NULL so that when we backtrack the first time
4200 and need to test it, it's not garbage. */
4201 const char *match_end = NULL;
4203 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4204 int set_regs_matched_done = 0;
4206 /* Used when we pop values we don't care about. */
4207 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4208 const char **reg_dummy;
4209 register_info_type *reg_info_dummy;
4213 /* Counts the total number of registers pushed. */
4214 unsigned num_regs_pushed = 0;
4217 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4221 #ifdef MATCH_MAY_ALLOCATE
4222 /* Do not bother to initialize all the register variables if there are
4223 no groups in the pattern, as it takes a fair amount of time. If
4224 there are groups, we include space for register 0 (the whole
4225 pattern), even though we never use it, since it simplifies the
4226 array indexing. We should fix this. */
4229 regstart = REGEX_TALLOC (num_regs, const char *);
4230 regend = REGEX_TALLOC (num_regs, const char *);
4231 old_regstart = REGEX_TALLOC (num_regs, const char *);
4232 old_regend = REGEX_TALLOC (num_regs, const char *);
4233 best_regstart = REGEX_TALLOC (num_regs, const char *);
4234 best_regend = REGEX_TALLOC (num_regs, const char *);
4235 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4236 reg_dummy = REGEX_TALLOC (num_regs, const char *);
4237 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4239 if (!(regstart && regend && old_regstart && old_regend && reg_info
4240 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4248 /* We must initialize all our variables to NULL, so that
4249 `FREE_VARIABLES' doesn't try to free them. */
4250 regstart = regend = old_regstart = old_regend = best_regstart
4251 = best_regend = reg_dummy = NULL;
4252 reg_info = reg_info_dummy = (register_info_type *) NULL;
4254 #endif /* MATCH_MAY_ALLOCATE */
4256 /* The starting position is bogus. */
4257 if (pos < 0 || pos > size1 + size2)
4263 /* Initialize subexpression text positions to -1 to mark ones that no
4264 start_memory/stop_memory has been seen for. Also initialize the
4265 register information struct. */
4266 for (mcnt = 1; mcnt < num_regs; mcnt++)
4268 regstart[mcnt] = regend[mcnt]
4269 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4271 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4272 IS_ACTIVE (reg_info[mcnt]) = 0;
4273 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4274 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4277 /* We move `string1' into `string2' if the latter's empty -- but not if
4278 `string1' is null. */
4279 if (size2 == 0 && string1 != NULL)
4286 end1 = string1 + size1;
4287 end2 = string2 + size2;
4289 /* Compute where to stop matching, within the two strings. */
4292 end_match_1 = string1 + stop;
4293 end_match_2 = string2;
4298 end_match_2 = string2 + stop - size1;
4301 /* `p' scans through the pattern as `d' scans through the data.
4302 `dend' is the end of the input string that `d' points within. `d'
4303 is advanced into the following input string whenever necessary, but
4304 this happens before fetching; therefore, at the beginning of the
4305 loop, `d' can be pointing at the end of a string, but it cannot
4307 if (size1 > 0 && pos <= size1)
4314 d = string2 + pos - size1;
4318 DEBUG_PRINT1 ("The compiled pattern is: ");
4319 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4320 DEBUG_PRINT1 ("The string to match is: `");
4321 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4322 DEBUG_PRINT1 ("'\n");
4324 /* This loops over pattern commands. It exits by returning from the
4325 function if the match is complete, or it drops through if the match
4326 fails at this starting point in the input data. */
4329 DEBUG_PRINT2 ("\n0x%x: ", p);
4332 { /* End of pattern means we might have succeeded. */
4333 DEBUG_PRINT1 ("end of pattern ... ");
4335 /* If we haven't matched the entire string, and we want the
4336 longest match, try backtracking. */
4337 if (d != end_match_2)
4339 /* 1 if this match ends in the same string (string1 or string2)
4340 as the best previous match. */
4341 boolean same_str_p = (FIRST_STRING_P (match_end)
4342 == MATCHING_IN_FIRST_STRING);
4343 /* 1 if this match is the best seen so far. */
4344 boolean best_match_p;
4346 /* AIX compiler got confused when this was combined
4347 with the previous declaration. */
4349 best_match_p = d > match_end;
4351 best_match_p = !MATCHING_IN_FIRST_STRING;
4353 DEBUG_PRINT1 ("backtracking.\n");
4355 if (!FAIL_STACK_EMPTY ())
4356 { /* More failure points to try. */
4358 /* If exceeds best match so far, save it. */
4359 if (!best_regs_set || best_match_p)
4361 best_regs_set = true;
4364 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4366 for (mcnt = 1; mcnt < num_regs; mcnt++)
4368 best_regstart[mcnt] = regstart[mcnt];
4369 best_regend[mcnt] = regend[mcnt];
4375 /* If no failure points, don't restore garbage. And if
4376 last match is real best match, don't restore second
4378 else if (best_regs_set && !best_match_p)
4381 /* Restore best match. It may happen that `dend ==
4382 end_match_1' while the restored d is in string2.
4383 For example, the pattern `x.*y.*z' against the
4384 strings `x-' and `y-z-', if the two strings are
4385 not consecutive in memory. */
4386 DEBUG_PRINT1 ("Restoring best registers.\n");
4389 dend = ((d >= string1 && d <= end1)
4390 ? end_match_1 : end_match_2);
4392 for (mcnt = 1; mcnt < num_regs; mcnt++)
4394 regstart[mcnt] = best_regstart[mcnt];
4395 regend[mcnt] = best_regend[mcnt];
4398 } /* d != end_match_2 */
4401 DEBUG_PRINT1 ("Accepting match.\n");
4403 /* If caller wants register contents data back, do it. */
4404 if (regs && !bufp->no_sub)
4406 /* Have the register data arrays been allocated? */
4407 if (bufp->regs_allocated == REGS_UNALLOCATED)
4408 { /* No. So allocate them with malloc. We need one
4409 extra element beyond `num_regs' for the `-1' marker
4411 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4412 regs->start = TALLOC (regs->num_regs, regoff_t);
4413 regs->end = TALLOC (regs->num_regs, regoff_t);
4414 if (regs->start == NULL || regs->end == NULL)
4419 bufp->regs_allocated = REGS_REALLOCATE;
4421 else if (bufp->regs_allocated == REGS_REALLOCATE)
4422 { /* Yes. If we need more elements than were already
4423 allocated, reallocate them. If we need fewer, just
4425 if (regs->num_regs < num_regs + 1)
4427 regs->num_regs = num_regs + 1;
4428 RETALLOC (regs->start, regs->num_regs, regoff_t);
4429 RETALLOC (regs->end, regs->num_regs, regoff_t);
4430 if (regs->start == NULL || regs->end == NULL)
4439 /* These braces fend off a "empty body in an else-statement"
4440 warning under GCC when assert expands to nothing. */
4441 assert (bufp->regs_allocated == REGS_FIXED);
4444 /* Convert the pointer data in `regstart' and `regend' to
4445 indices. Register zero has to be set differently,
4446 since we haven't kept track of any info for it. */
4447 if (regs->num_regs > 0)
4449 regs->start[0] = pos;
4450 regs->end[0] = (MATCHING_IN_FIRST_STRING
4451 ? ((regoff_t) (d - string1))
4452 : ((regoff_t) (d - string2 + size1)));
4455 /* Go through the first `min (num_regs, regs->num_regs)'
4456 registers, since that is all we initialized. */
4457 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4459 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4460 regs->start[mcnt] = regs->end[mcnt] = -1;
4464 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4466 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4470 /* If the regs structure we return has more elements than
4471 were in the pattern, set the extra elements to -1. If
4472 we (re)allocated the registers, this is the case,
4473 because we always allocate enough to have at least one
4475 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4476 regs->start[mcnt] = regs->end[mcnt] = -1;
4477 } /* regs && !bufp->no_sub */
4479 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4480 nfailure_points_pushed, nfailure_points_popped,
4481 nfailure_points_pushed - nfailure_points_popped);
4482 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4484 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4488 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4494 /* Otherwise match next pattern command. */
4495 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4497 /* Ignore these. Used to ignore the n of succeed_n's which
4498 currently have n == 0. */
4500 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4504 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4507 /* Match the next n pattern characters exactly. The following
4508 byte in the pattern defines n, and the n bytes after that
4509 are the characters to match. */
4512 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4514 /* This is written out as an if-else so we don't waste time
4515 testing `translate' inside the loop. */
4521 if ((unsigned char) RE_TRANSLATE (translate, (unsigned char) *d++)
4522 != (unsigned char) *p++)
4532 if (*d++ != (char) *p++) goto fail;
4536 SET_REGS_MATCHED ();
4540 /* Match any character except possibly a newline or a null. */
4542 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4546 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4547 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4550 SET_REGS_MATCHED ();
4551 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4552 d += multibyte ? MULTIBYTE_FORM_LENGTH (d, dend - d) : 1;
4559 register unsigned int c;
4560 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4563 /* Start of actual range_table, or end of bitmap if there is no
4565 unsigned char *range_table;
4567 /* Nonzero if there is range table. */
4568 int range_table_exists;
4570 /* Number of ranges of range table. Not in bytes. */
4573 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4576 c = (unsigned char) *d;
4578 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
4579 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
4580 if (range_table_exists)
4581 EXTRACT_NUMBER_AND_INCR (count, range_table);
4585 if (multibyte && BASE_LEADING_CODE_P (c))
4586 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
4588 if (SINGLE_BYTE_CHAR_P (c))
4589 { /* Lookup bitmap. */
4590 c = TRANSLATE (c); /* The character to match. */
4593 /* Cast to `unsigned' instead of `unsigned char' in
4594 case the bit list is a full 32 bytes long. */
4595 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
4596 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4599 else if (range_table_exists)
4600 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
4602 p = CHARSET_RANGE_TABLE_END (range_table, count);
4604 if (!not) goto fail;
4606 SET_REGS_MATCHED ();
4612 /* The beginning of a group is represented by start_memory.
4613 The arguments are the register number in the next byte, and the
4614 number of groups inner to this one in the next. The text
4615 matched within the group is recorded (in the internal
4616 registers data structure) under the register number. */
4618 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4620 /* Find out if this group can match the empty string. */
4621 p1 = p; /* To send to group_match_null_string_p. */
4623 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4624 REG_MATCH_NULL_STRING_P (reg_info[*p])
4625 = group_match_null_string_p (&p1, pend, reg_info);
4627 /* Save the position in the string where we were the last time
4628 we were at this open-group operator in case the group is
4629 operated upon by a repetition operator, e.g., with `(a*)*b'
4630 against `ab'; then we want to ignore where we are now in
4631 the string in case this attempt to match fails. */
4632 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4633 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4635 DEBUG_PRINT2 (" old_regstart: %d\n",
4636 POINTER_TO_OFFSET (old_regstart[*p]));
4639 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4641 IS_ACTIVE (reg_info[*p]) = 1;
4642 MATCHED_SOMETHING (reg_info[*p]) = 0;
4644 /* Clear this whenever we change the register activity status. */
4645 set_regs_matched_done = 0;
4647 /* This is the new highest active register. */
4648 highest_active_reg = *p;
4650 /* If nothing was active before, this is the new lowest active
4652 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4653 lowest_active_reg = *p;
4655 /* Move past the register number and inner group count. */
4657 just_past_start_mem = p;
4662 /* The stop_memory opcode represents the end of a group. Its
4663 arguments are the same as start_memory's: the register
4664 number, and the number of inner groups. */
4666 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4668 /* We need to save the string position the last time we were at
4669 this close-group operator in case the group is operated
4670 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4671 against `aba'; then we want to ignore where we are now in
4672 the string in case this attempt to match fails. */
4673 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4674 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4676 DEBUG_PRINT2 (" old_regend: %d\n",
4677 POINTER_TO_OFFSET (old_regend[*p]));
4680 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4682 /* This register isn't active anymore. */
4683 IS_ACTIVE (reg_info[*p]) = 0;
4685 /* Clear this whenever we change the register activity status. */
4686 set_regs_matched_done = 0;
4688 /* If this was the only register active, nothing is active
4690 if (lowest_active_reg == highest_active_reg)
4692 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4693 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4696 { /* We must scan for the new highest active register, since
4697 it isn't necessarily one less than now: consider
4698 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4699 new highest active register is 1. */
4700 unsigned char r = *p - 1;
4701 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4704 /* If we end up at register zero, that means that we saved
4705 the registers as the result of an `on_failure_jump', not
4706 a `start_memory', and we jumped to past the innermost
4707 `stop_memory'. For example, in ((.)*) we save
4708 registers 1 and 2 as a result of the *, but when we pop
4709 back to the second ), we are at the stop_memory 1.
4710 Thus, nothing is active. */
4713 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4714 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4717 highest_active_reg = r;
4720 /* If just failed to match something this time around with a
4721 group that's operated on by a repetition operator, try to
4722 force exit from the ``loop'', and restore the register
4723 information for this group that we had before trying this
4725 if ((!MATCHED_SOMETHING (reg_info[*p])
4726 || just_past_start_mem == p - 1)
4729 boolean is_a_jump_n = false;
4733 switch ((re_opcode_t) *p1++)
4737 case pop_failure_jump:
4738 case maybe_pop_jump:
4740 case dummy_failure_jump:
4741 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4751 /* If the next operation is a jump backwards in the pattern
4752 to an on_failure_jump right before the start_memory
4753 corresponding to this stop_memory, exit from the loop
4754 by forcing a failure after pushing on the stack the
4755 on_failure_jump's jump in the pattern, and d. */
4756 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4757 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4759 /* If this group ever matched anything, then restore
4760 what its registers were before trying this last
4761 failed match, e.g., with `(a*)*b' against `ab' for
4762 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4763 against `aba' for regend[3].
4765 Also restore the registers for inner groups for,
4766 e.g., `((a*)(b*))*' against `aba' (register 3 would
4767 otherwise get trashed). */
4769 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4773 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4775 /* Restore this and inner groups' (if any) registers. */
4776 for (r = *p; r < *p + *(p + 1); r++)
4778 regstart[r] = old_regstart[r];
4780 /* xx why this test? */
4781 if (old_regend[r] >= regstart[r])
4782 regend[r] = old_regend[r];
4786 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4787 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4793 /* Move past the register number and the inner group count. */
4798 /* \<digit> has been turned into a `duplicate' command which is
4799 followed by the numeric value of <digit> as the register number. */
4802 register const char *d2, *dend2;
4803 int regno = *p++; /* Get which register to match against. */
4804 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4806 /* Can't back reference a group which we've never matched. */
4807 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4810 /* Where in input to try to start matching. */
4811 d2 = regstart[regno];
4813 /* Where to stop matching; if both the place to start and
4814 the place to stop matching are in the same string, then
4815 set to the place to stop, otherwise, for now have to use
4816 the end of the first string. */
4818 dend2 = ((FIRST_STRING_P (regstart[regno])
4819 == FIRST_STRING_P (regend[regno]))
4820 ? regend[regno] : end_match_1);
4823 /* If necessary, advance to next segment in register
4827 if (dend2 == end_match_2) break;
4828 if (dend2 == regend[regno]) break;
4830 /* End of string1 => advance to string2. */
4832 dend2 = regend[regno];
4834 /* At end of register contents => success */
4835 if (d2 == dend2) break;
4837 /* If necessary, advance to next segment in data. */
4840 /* How many characters left in this segment to match. */
4843 /* Want how many consecutive characters we can match in
4844 one shot, so, if necessary, adjust the count. */
4845 if (mcnt > dend2 - d2)
4848 /* Compare that many; failure if mismatch, else move
4851 ? bcmp_translate (d, d2, mcnt, translate)
4852 : bcmp (d, d2, mcnt))
4854 d += mcnt, d2 += mcnt;
4856 /* Do this because we've match some characters. */
4857 SET_REGS_MATCHED ();
4863 /* begline matches the empty string at the beginning of the string
4864 (unless `not_bol' is set in `bufp'), and, if
4865 `newline_anchor' is set, after newlines. */
4867 DEBUG_PRINT1 ("EXECUTING begline.\n");
4869 if (AT_STRINGS_BEG (d))
4871 if (!bufp->not_bol) break;
4873 else if (d[-1] == '\n' && bufp->newline_anchor)
4877 /* In all other cases, we fail. */
4881 /* endline is the dual of begline. */
4883 DEBUG_PRINT1 ("EXECUTING endline.\n");
4885 if (AT_STRINGS_END (d))
4887 if (!bufp->not_eol) break;
4890 /* We have to ``prefetch'' the next character. */
4891 else if ((d == end1 ? *string2 : *d) == '\n'
4892 && bufp->newline_anchor)
4899 /* Match at the very beginning of the data. */
4901 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4902 if (AT_STRINGS_BEG (d))
4907 /* Match at the very end of the data. */
4909 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4910 if (AT_STRINGS_END (d))
4915 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4916 pushes NULL as the value for the string on the stack. Then
4917 `pop_failure_point' will keep the current value for the
4918 string, instead of restoring it. To see why, consider
4919 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4920 then the . fails against the \n. But the next thing we want
4921 to do is match the \n against the \n; if we restored the
4922 string value, we would be back at the foo.
4924 Because this is used only in specific cases, we don't need to
4925 check all the things that `on_failure_jump' does, to make
4926 sure the right things get saved on the stack. Hence we don't
4927 share its code. The only reason to push anything on the
4928 stack at all is that otherwise we would have to change
4929 `anychar's code to do something besides goto fail in this
4930 case; that seems worse than this. */
4931 case on_failure_keep_string_jump:
4932 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4934 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4935 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4937 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4941 /* Uses of on_failure_jump:
4943 Each alternative starts with an on_failure_jump that points
4944 to the beginning of the next alternative. Each alternative
4945 except the last ends with a jump that in effect jumps past
4946 the rest of the alternatives. (They really jump to the
4947 ending jump of the following alternative, because tensioning
4948 these jumps is a hassle.)
4950 Repeats start with an on_failure_jump that points past both
4951 the repetition text and either the following jump or
4952 pop_failure_jump back to this on_failure_jump. */
4953 case on_failure_jump:
4955 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4957 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4958 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4960 /* If this on_failure_jump comes right before a group (i.e.,
4961 the original * applied to a group), save the information
4962 for that group and all inner ones, so that if we fail back
4963 to this point, the group's information will be correct.
4964 For example, in \(a*\)*\1, we need the preceding group,
4965 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4967 /* We can't use `p' to check ahead because we push
4968 a failure point to `p + mcnt' after we do this. */
4971 /* We need to skip no_op's before we look for the
4972 start_memory in case this on_failure_jump is happening as
4973 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4975 while (p1 < pend && (re_opcode_t) *p1 == no_op)
4978 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
4980 /* We have a new highest active register now. This will
4981 get reset at the start_memory we are about to get to,
4982 but we will have saved all the registers relevant to
4983 this repetition op, as described above. */
4984 highest_active_reg = *(p1 + 1) + *(p1 + 2);
4985 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4986 lowest_active_reg = *(p1 + 1);
4989 DEBUG_PRINT1 (":\n");
4990 PUSH_FAILURE_POINT (p + mcnt, d, -2);
4994 /* A smart repeat ends with `maybe_pop_jump'.
4995 We change it to either `pop_failure_jump' or `jump'. */
4996 case maybe_pop_jump:
4997 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4998 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5000 register unsigned char *p2 = p;
5002 /* Compare the beginning of the repeat with what in the
5003 pattern follows its end. If we can establish that there
5004 is nothing that they would both match, i.e., that we
5005 would have to backtrack because of (as in, e.g., `a*a')
5006 then we can change to pop_failure_jump, because we'll
5007 never have to backtrack.
5009 This is not true in the case of alternatives: in
5010 `(a|ab)*' we do need to backtrack to the `ab' alternative
5011 (e.g., if the string was `ab'). But instead of trying to
5012 detect that here, the alternative has put on a dummy
5013 failure point which is what we will end up popping. */
5015 /* Skip over open/close-group commands.
5016 If what follows this loop is a ...+ construct,
5017 look at what begins its body, since we will have to
5018 match at least one of that. */
5022 && ((re_opcode_t) *p2 == stop_memory
5023 || (re_opcode_t) *p2 == start_memory))
5025 else if (p2 + 6 < pend
5026 && (re_opcode_t) *p2 == dummy_failure_jump)
5033 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5034 to the `maybe_finalize_jump' of this case. Examine what
5037 /* If we're at the end of the pattern, we can change. */
5040 /* Consider what happens when matching ":\(.*\)"
5041 against ":/". I don't really understand this code
5043 p[-3] = (unsigned char) pop_failure_jump;
5045 (" End of pattern: change to `pop_failure_jump'.\n");
5048 else if ((re_opcode_t) *p2 == exactn
5049 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5051 register unsigned int c
5052 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5054 if ((re_opcode_t) p1[3] == exactn)
5056 if (!(multibyte /* && (c != '\n') */
5057 && BASE_LEADING_CODE_P (c))
5059 : (STRING_CHAR (&p2[2], pend - &p2[2])
5060 != STRING_CHAR (&p1[5], pend - &p1[5])))
5062 p[-3] = (unsigned char) pop_failure_jump;
5063 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5068 else if ((re_opcode_t) p1[3] == charset
5069 || (re_opcode_t) p1[3] == charset_not)
5071 int not = (re_opcode_t) p1[3] == charset_not;
5073 if (multibyte /* && (c != '\n') */
5074 && BASE_LEADING_CODE_P (c))
5075 c = STRING_CHAR (&p2[2], pend - &p2[2]);
5077 /* Test if C is listed in charset (or charset_not)
5079 if (SINGLE_BYTE_CHAR_P (c))
5081 if (c < CHARSET_BITMAP_SIZE (&p1[3]) * BYTEWIDTH
5082 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5085 else if (CHARSET_RANGE_TABLE_EXISTS_P (&p1[3]))
5086 CHARSET_LOOKUP_RANGE_TABLE (not, c, &p1[3]);
5088 /* `not' is equal to 1 if c would match, which means
5089 that we can't change to pop_failure_jump. */
5092 p[-3] = (unsigned char) pop_failure_jump;
5093 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5097 else if ((re_opcode_t) *p2 == charset)
5099 if ((re_opcode_t) p1[3] == exactn)
5101 register unsigned int c = p1[5];
5104 if (multibyte && BASE_LEADING_CODE_P (c))
5105 c = STRING_CHAR (&p1[5], pend - &p1[5]);
5107 /* Test if C is listed in charset at `p2'. */
5108 if (SINGLE_BYTE_CHAR_P (c))
5110 if (c < CHARSET_BITMAP_SIZE (p2) * BYTEWIDTH
5111 && (p2[2 + c / BYTEWIDTH]
5112 & (1 << (c % BYTEWIDTH))))
5115 else if (CHARSET_RANGE_TABLE_EXISTS_P (p2))
5116 CHARSET_LOOKUP_RANGE_TABLE (not, c, p2);
5120 p[-3] = (unsigned char) pop_failure_jump;
5121 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5125 /* It is hard to list up all the character in charset
5126 P2 if it includes multibyte character. Give up in
5128 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
5130 /* Now, we are sure that P2 has no range table.
5131 So, for the size of bitmap in P2, `p2[1]' is
5132 enough. But P1 may have range table, so the
5133 size of bitmap table of P1 is extracted by
5134 using macro `CHARSET_BITMAP_SIZE'.
5136 Since we know that all the character listed in
5137 P2 is ASCII, it is enough to test only bitmap
5140 if ((re_opcode_t) p1[3] == charset_not)
5143 /* We win if the charset_not inside the loop lists
5144 every character listed in the charset after. */
5145 for (idx = 0; idx < (int) p2[1]; idx++)
5146 if (! (p2[2 + idx] == 0
5147 || (idx < CHARSET_BITMAP_SIZE (&p1[3])
5148 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5153 p[-3] = (unsigned char) pop_failure_jump;
5154 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5157 else if ((re_opcode_t) p1[3] == charset)
5160 /* We win if the charset inside the loop
5161 has no overlap with the one after the loop. */
5164 && idx < CHARSET_BITMAP_SIZE (&p1[3]));
5166 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5170 || idx == CHARSET_BITMAP_SIZE (&p1[3]))
5172 p[-3] = (unsigned char) pop_failure_jump;
5173 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5179 p -= 2; /* Point at relative address again. */
5180 if ((re_opcode_t) p[-1] != pop_failure_jump)
5182 p[-1] = (unsigned char) jump;
5183 DEBUG_PRINT1 (" Match => jump.\n");
5184 goto unconditional_jump;
5186 /* Note fall through. */
5189 /* The end of a simple repeat has a pop_failure_jump back to
5190 its matching on_failure_jump, where the latter will push a
5191 failure point. The pop_failure_jump takes off failure
5192 points put on by this pop_failure_jump's matching
5193 on_failure_jump; we got through the pattern to here from the
5194 matching on_failure_jump, so didn't fail. */
5195 case pop_failure_jump:
5197 /* We need to pass separate storage for the lowest and
5198 highest registers, even though we don't care about the
5199 actual values. Otherwise, we will restore only one
5200 register from the stack, since lowest will == highest in
5201 `pop_failure_point'. */
5202 unsigned dummy_low_reg, dummy_high_reg;
5203 unsigned char *pdummy;
5206 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5207 POP_FAILURE_POINT (sdummy, pdummy,
5208 dummy_low_reg, dummy_high_reg,
5209 reg_dummy, reg_dummy, reg_info_dummy);
5211 /* Note fall through. */
5214 /* Unconditionally jump (without popping any failure points). */
5217 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5218 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5219 p += mcnt; /* Do the jump. */
5220 DEBUG_PRINT2 ("(to 0x%x).\n", p);
5224 /* We need this opcode so we can detect where alternatives end
5225 in `group_match_null_string_p' et al. */
5227 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5228 goto unconditional_jump;
5231 /* Normally, the on_failure_jump pushes a failure point, which
5232 then gets popped at pop_failure_jump. We will end up at
5233 pop_failure_jump, also, and with a pattern of, say, `a+', we
5234 are skipping over the on_failure_jump, so we have to push
5235 something meaningless for pop_failure_jump to pop. */
5236 case dummy_failure_jump:
5237 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5238 /* It doesn't matter what we push for the string here. What
5239 the code at `fail' tests is the value for the pattern. */
5240 PUSH_FAILURE_POINT (0, 0, -2);
5241 goto unconditional_jump;
5244 /* At the end of an alternative, we need to push a dummy failure
5245 point in case we are followed by a `pop_failure_jump', because
5246 we don't want the failure point for the alternative to be
5247 popped. For example, matching `(a|ab)*' against `aab'
5248 requires that we match the `ab' alternative. */
5249 case push_dummy_failure:
5250 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5251 /* See comments just above at `dummy_failure_jump' about the
5253 PUSH_FAILURE_POINT (0, 0, -2);
5256 /* Have to succeed matching what follows at least n times.
5257 After that, handle like `on_failure_jump'. */
5259 EXTRACT_NUMBER (mcnt, p + 2);
5260 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5263 /* Originally, this is how many times we HAVE to succeed. */
5268 STORE_NUMBER_AND_INCR (p, mcnt);
5269 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
5273 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
5274 p[2] = (unsigned char) no_op;
5275 p[3] = (unsigned char) no_op;
5281 EXTRACT_NUMBER (mcnt, p + 2);
5282 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5284 /* Originally, this is how many times we CAN jump. */
5288 STORE_NUMBER (p + 2, mcnt);
5289 goto unconditional_jump;
5291 /* If don't have to jump any more, skip over the rest of command. */
5298 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5300 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5302 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5303 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
5304 STORE_NUMBER (p1, mcnt);
5309 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5311 /* We SUCCEED in one of the following cases: */
5313 /* Case 1: D is at the beginning or the end of string. */
5314 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5318 /* C1 is the character before D, S1 is the syntax of C1, C2
5319 is the character at D, and S2 is the syntax of C2. */
5321 int pos1 = PTR_TO_OFFSET (d - 1);
5324 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5325 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5327 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 ? pos1 : 1);
5328 UPDATE_SYNTAX_TABLE (charpos);
5332 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5336 if (/* Case 2: Only one of S1 and S2 is Sword. */
5337 ((s1 == Sword) != (s2 == Sword))
5338 /* Case 3: Both of S1 and S2 are Sword, and macro
5339 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5340 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5346 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5348 /* We FAIL in one of the following cases: */
5350 /* Case 1: D is at the beginning or the end of string. */
5351 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5355 /* C1 is the character before D, S1 is the syntax of C1, C2
5356 is the character at D, and S2 is the syntax of C2. */
5358 int pos1 = PTR_TO_OFFSET (d - 1);
5361 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5362 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5364 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5365 UPDATE_SYNTAX_TABLE (charpos);
5369 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5373 if (/* Case 2: Only one of S1 and S2 is Sword. */
5374 ((s1 == Sword) != (s2 == Sword))
5375 /* Case 3: Both of S1 and S2 are Sword, and macro
5376 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5377 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5383 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5385 /* We FAIL in one of the following cases: */
5387 /* Case 1: D is at the end of string. */
5388 if (AT_STRINGS_END (d))
5392 /* C1 is the character before D, S1 is the syntax of C1, C2
5393 is the character at D, and S2 is the syntax of C2. */
5395 int pos1 = PTR_TO_OFFSET (d);
5398 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5400 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5401 UPDATE_SYNTAX_TABLE (charpos);
5405 /* Case 2: S2 is not Sword. */
5409 /* Case 3: D is not at the beginning of string ... */
5410 if (!AT_STRINGS_BEG (d))
5412 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5414 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5418 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5420 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5427 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5429 /* We FAIL in one of the following cases: */
5431 /* Case 1: D is at the beginning of string. */
5432 if (AT_STRINGS_BEG (d))
5436 /* C1 is the character before D, S1 is the syntax of C1, C2
5437 is the character at D, and S2 is the syntax of C2. */
5439 int pos1 = PTR_TO_OFFSET (d);
5442 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5444 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 - 1);
5445 UPDATE_SYNTAX_TABLE (charpos);
5449 /* Case 2: S1 is not Sword. */
5453 /* Case 3: D is not at the end of string ... */
5454 if (!AT_STRINGS_END (d))
5456 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5458 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5462 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5464 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5472 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5473 if (PTR_BYTE_POS ((unsigned char *) d) >= PT_BYTE)
5478 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5479 if (PTR_BYTE_POS ((unsigned char *) d) != PT_BYTE)
5484 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5485 if (PTR_BYTE_POS ((unsigned char *) d) <= PT_BYTE)
5490 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5495 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5501 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5502 UPDATE_SYNTAX_TABLE (pos1);
5509 /* we must concern about multibyte form, ... */
5510 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5512 /* everything should be handled as ASCII, even though it
5513 looks like multibyte form. */
5516 if (SYNTAX (c) != (enum syntaxcode) mcnt)
5520 SET_REGS_MATCHED ();
5524 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5526 goto matchnotsyntax;
5529 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5535 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5536 UPDATE_SYNTAX_TABLE (pos1);
5543 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5547 if (SYNTAX (c) == (enum syntaxcode) mcnt)
5551 SET_REGS_MATCHED ();
5555 DEBUG_PRINT2 ("EXECUTING categoryspec %d.\n", *p);
5562 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5566 if (!CHAR_HAS_CATEGORY (c, mcnt))
5570 SET_REGS_MATCHED ();
5573 case notcategoryspec:
5574 DEBUG_PRINT2 ("EXECUTING notcategoryspec %d.\n", *p);
5581 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5585 if (CHAR_HAS_CATEGORY (c, mcnt))
5589 SET_REGS_MATCHED ();
5592 #else /* not emacs */
5594 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5596 if (!WORDCHAR_P (d))
5598 SET_REGS_MATCHED ();
5603 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5607 SET_REGS_MATCHED ();
5610 #endif /* not emacs */
5615 continue; /* Successfully executed one pattern command; keep going. */
5618 /* We goto here if a matching operation fails. */
5620 if (!FAIL_STACK_EMPTY ())
5621 { /* A restart point is known. Restore to that state. */
5622 DEBUG_PRINT1 ("\nFAIL:\n");
5623 POP_FAILURE_POINT (d, p,
5624 lowest_active_reg, highest_active_reg,
5625 regstart, regend, reg_info);
5627 /* If this failure point is a dummy, try the next one. */
5631 /* If we failed to the end of the pattern, don't examine *p. */
5635 boolean is_a_jump_n = false;
5637 /* If failed to a backwards jump that's part of a repetition
5638 loop, need to pop this failure point and use the next one. */
5639 switch ((re_opcode_t) *p)
5643 case maybe_pop_jump:
5644 case pop_failure_jump:
5647 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5650 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5652 && (re_opcode_t) *p1 == on_failure_jump))
5660 if (d >= string1 && d <= end1)
5664 break; /* Matching at this starting point really fails. */
5668 goto restore_best_regs;
5672 return -1; /* Failure to match. */
5675 /* Subroutine definitions for re_match_2. */
5678 /* We are passed P pointing to a register number after a start_memory.
5680 Return true if the pattern up to the corresponding stop_memory can
5681 match the empty string, and false otherwise.
5683 If we find the matching stop_memory, sets P to point to one past its number.
5684 Otherwise, sets P to an undefined byte less than or equal to END.
5686 We don't handle duplicates properly (yet). */
5689 group_match_null_string_p (p, end, reg_info)
5690 unsigned char **p, *end;
5691 register_info_type *reg_info;
5694 /* Point to after the args to the start_memory. */
5695 unsigned char *p1 = *p + 2;
5699 /* Skip over opcodes that can match nothing, and return true or
5700 false, as appropriate, when we get to one that can't, or to the
5701 matching stop_memory. */
5703 switch ((re_opcode_t) *p1)
5705 /* Could be either a loop or a series of alternatives. */
5706 case on_failure_jump:
5708 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5710 /* If the next operation is not a jump backwards in the
5715 /* Go through the on_failure_jumps of the alternatives,
5716 seeing if any of the alternatives cannot match nothing.
5717 The last alternative starts with only a jump,
5718 whereas the rest start with on_failure_jump and end
5719 with a jump, e.g., here is the pattern for `a|b|c':
5721 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5722 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5725 So, we have to first go through the first (n-1)
5726 alternatives and then deal with the last one separately. */
5729 /* Deal with the first (n-1) alternatives, which start
5730 with an on_failure_jump (see above) that jumps to right
5731 past a jump_past_alt. */
5733 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5735 /* `mcnt' holds how many bytes long the alternative
5736 is, including the ending `jump_past_alt' and
5739 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5743 /* Move to right after this alternative, including the
5747 /* Break if it's the beginning of an n-th alternative
5748 that doesn't begin with an on_failure_jump. */
5749 if ((re_opcode_t) *p1 != on_failure_jump)
5752 /* Still have to check that it's not an n-th
5753 alternative that starts with an on_failure_jump. */
5755 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5756 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5758 /* Get to the beginning of the n-th alternative. */
5764 /* Deal with the last alternative: go back and get number
5765 of the `jump_past_alt' just before it. `mcnt' contains
5766 the length of the alternative. */
5767 EXTRACT_NUMBER (mcnt, p1 - 2);
5769 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5772 p1 += mcnt; /* Get past the n-th alternative. */
5778 assert (p1[1] == **p);
5784 if (!common_op_match_null_string_p (&p1, end, reg_info))
5787 } /* while p1 < end */
5790 } /* group_match_null_string_p */
5793 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5794 It expects P to be the first byte of a single alternative and END one
5795 byte past the last. The alternative can contain groups. */
5798 alt_match_null_string_p (p, end, reg_info)
5799 unsigned char *p, *end;
5800 register_info_type *reg_info;
5803 unsigned char *p1 = p;
5807 /* Skip over opcodes that can match nothing, and break when we get
5808 to one that can't. */
5810 switch ((re_opcode_t) *p1)
5813 case on_failure_jump:
5815 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5820 if (!common_op_match_null_string_p (&p1, end, reg_info))
5823 } /* while p1 < end */
5826 } /* alt_match_null_string_p */
5829 /* Deals with the ops common to group_match_null_string_p and
5830 alt_match_null_string_p.
5832 Sets P to one after the op and its arguments, if any. */
5835 common_op_match_null_string_p (p, end, reg_info)
5836 unsigned char **p, *end;
5837 register_info_type *reg_info;
5842 unsigned char *p1 = *p;
5844 switch ((re_opcode_t) *p1++)
5864 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5865 ret = group_match_null_string_p (&p1, end, reg_info);
5867 /* Have to set this here in case we're checking a group which
5868 contains a group and a back reference to it. */
5870 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5871 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5877 /* If this is an optimized succeed_n for zero times, make the jump. */
5879 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5887 /* Get to the number of times to succeed. */
5889 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5894 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5902 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5910 /* All other opcodes mean we cannot match the empty string. */
5916 } /* common_op_match_null_string_p */
5919 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5920 bytes; nonzero otherwise. */
5923 bcmp_translate (s1, s2, len, translate)
5924 unsigned char *s1, *s2;
5926 RE_TRANSLATE_TYPE translate;
5928 register unsigned char *p1 = s1, *p2 = s2;
5931 if (RE_TRANSLATE (translate, *p1++) != RE_TRANSLATE (translate, *p2++))
5938 /* Entry points for GNU code. */
5940 /* re_compile_pattern is the GNU regular expression compiler: it
5941 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5942 Returns 0 if the pattern was valid, otherwise an error string.
5944 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5945 are set in BUFP on entry.
5947 We call regex_compile to do the actual compilation. */
5950 re_compile_pattern (pattern, length, bufp)
5951 const char *pattern;
5953 struct re_pattern_buffer *bufp;
5957 /* GNU code is written to assume at least RE_NREGS registers will be set
5958 (and at least one extra will be -1). */
5959 bufp->regs_allocated = REGS_UNALLOCATED;
5961 /* And GNU code determines whether or not to get register information
5962 by passing null for the REGS argument to re_match, etc., not by
5966 /* Match anchors at newline. */
5967 bufp->newline_anchor = 1;
5969 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5973 return gettext (re_error_msgid[(int) ret]);
5976 /* Entry points compatible with 4.2 BSD regex library. We don't define
5977 them unless specifically requested. */
5979 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
5981 /* BSD has one and only one pattern buffer. */
5982 static struct re_pattern_buffer re_comp_buf;
5986 /* Make these definitions weak in libc, so POSIX programs can redefine
5987 these names if they don't use our functions, and still use
5988 regcomp/regexec below without link errors. */
5998 if (!re_comp_buf.buffer)
5999 return gettext ("No previous regular expression");
6003 if (!re_comp_buf.buffer)
6005 re_comp_buf.buffer = (unsigned char *) malloc (200);
6006 if (re_comp_buf.buffer == NULL)
6007 return gettext (re_error_msgid[(int) REG_ESPACE]);
6008 re_comp_buf.allocated = 200;
6010 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6011 if (re_comp_buf.fastmap == NULL)
6012 return gettext (re_error_msgid[(int) REG_ESPACE]);
6015 /* Since `re_exec' always passes NULL for the `regs' argument, we
6016 don't need to initialize the pattern buffer fields which affect it. */
6018 /* Match anchors at newlines. */
6019 re_comp_buf.newline_anchor = 1;
6021 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6026 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6027 return (char *) gettext (re_error_msgid[(int) ret]);
6038 const int len = strlen (s);
6040 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6042 #endif /* _REGEX_RE_COMP */
6044 /* POSIX.2 functions. Don't define these for Emacs. */
6048 /* regcomp takes a regular expression as a string and compiles it.
6050 PREG is a regex_t *. We do not expect any fields to be initialized,
6051 since POSIX says we shouldn't. Thus, we set
6053 `buffer' to the compiled pattern;
6054 `used' to the length of the compiled pattern;
6055 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6056 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6057 RE_SYNTAX_POSIX_BASIC;
6058 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6059 `fastmap' and `fastmap_accurate' to zero;
6060 `re_nsub' to the number of subexpressions in PATTERN.
6062 PATTERN is the address of the pattern string.
6064 CFLAGS is a series of bits which affect compilation.
6066 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6067 use POSIX basic syntax.
6069 If REG_NEWLINE is set, then . and [^...] don't match newline.
6070 Also, regexec will try a match beginning after every newline.
6072 If REG_ICASE is set, then we considers upper- and lowercase
6073 versions of letters to be equivalent when matching.
6075 If REG_NOSUB is set, then when PREG is passed to regexec, that
6076 routine will report only success or failure, and nothing about the
6079 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6080 the return codes and their meanings.) */
6083 regcomp (preg, pattern, cflags)
6085 const char *pattern;
6090 = (cflags & REG_EXTENDED) ?
6091 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6093 /* regex_compile will allocate the space for the compiled pattern. */
6095 preg->allocated = 0;
6098 /* Don't bother to use a fastmap when searching. This simplifies the
6099 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6100 characters after newlines into the fastmap. This way, we just try
6104 if (cflags & REG_ICASE)
6109 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6110 * sizeof (*(RE_TRANSLATE_TYPE)0));
6111 if (preg->translate == NULL)
6112 return (int) REG_ESPACE;
6114 /* Map uppercase characters to corresponding lowercase ones. */
6115 for (i = 0; i < CHAR_SET_SIZE; i++)
6116 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6119 preg->translate = NULL;
6121 /* If REG_NEWLINE is set, newlines are treated differently. */
6122 if (cflags & REG_NEWLINE)
6123 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6124 syntax &= ~RE_DOT_NEWLINE;
6125 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6126 /* It also changes the matching behavior. */
6127 preg->newline_anchor = 1;
6130 preg->newline_anchor = 0;
6132 preg->no_sub = !!(cflags & REG_NOSUB);
6134 /* POSIX says a null character in the pattern terminates it, so we
6135 can use strlen here in compiling the pattern. */
6136 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
6138 /* POSIX doesn't distinguish between an unmatched open-group and an
6139 unmatched close-group: both are REG_EPAREN. */
6140 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6146 /* regexec searches for a given pattern, specified by PREG, in the
6149 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6150 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6151 least NMATCH elements, and we set them to the offsets of the
6152 corresponding matched substrings.
6154 EFLAGS specifies `execution flags' which affect matching: if
6155 REG_NOTBOL is set, then ^ does not match at the beginning of the
6156 string; if REG_NOTEOL is set, then $ does not match at the end.
6158 We return 0 if we find a match and REG_NOMATCH if not. */
6161 regexec (preg, string, nmatch, pmatch, eflags)
6162 const regex_t *preg;
6165 regmatch_t pmatch[];
6169 struct re_registers regs;
6170 regex_t private_preg;
6171 int len = strlen (string);
6172 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6174 private_preg = *preg;
6176 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6177 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6179 /* The user has told us exactly how many registers to return
6180 information about, via `nmatch'. We have to pass that on to the
6181 matching routines. */
6182 private_preg.regs_allocated = REGS_FIXED;
6186 regs.num_regs = nmatch;
6187 regs.start = TALLOC (nmatch, regoff_t);
6188 regs.end = TALLOC (nmatch, regoff_t);
6189 if (regs.start == NULL || regs.end == NULL)
6190 return (int) REG_NOMATCH;
6193 /* Perform the searching operation. */
6194 ret = re_search (&private_preg, string, len,
6195 /* start: */ 0, /* range: */ len,
6196 want_reg_info ? ®s : (struct re_registers *) 0);
6198 /* Copy the register information to the POSIX structure. */
6205 for (r = 0; r < nmatch; r++)
6207 pmatch[r].rm_so = regs.start[r];
6208 pmatch[r].rm_eo = regs.end[r];
6212 /* If we needed the temporary register info, free the space now. */
6217 /* We want zero return to mean success, unlike `re_search'. */
6218 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6222 /* Returns a message corresponding to an error code, ERRCODE, returned
6223 from either regcomp or regexec. We don't use PREG here. */
6226 regerror (errcode, preg, errbuf, errbuf_size)
6228 const regex_t *preg;
6236 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6237 /* Only error codes returned by the rest of the code should be passed
6238 to this routine. If we are given anything else, or if other regex
6239 code generates an invalid error code, then the program has a bug.
6240 Dump core so we can fix it. */
6243 msg = gettext (re_error_msgid[errcode]);
6245 msg_size = strlen (msg) + 1; /* Includes the null. */
6247 if (errbuf_size != 0)
6249 if (msg_size > errbuf_size)
6251 strncpy (errbuf, msg, errbuf_size - 1);
6252 errbuf[errbuf_size - 1] = 0;
6255 strcpy (errbuf, msg);
6262 /* Free dynamically allocated space used by PREG. */
6268 if (preg->buffer != NULL)
6269 free (preg->buffer);
6270 preg->buffer = NULL;
6272 preg->allocated = 0;
6275 if (preg->fastmap != NULL)
6276 free (preg->fastmap);
6277 preg->fastmap = NULL;
6278 preg->fastmap_accurate = 0;
6280 if (preg->translate != NULL)
6281 free (preg->translate);
6282 preg->translate = NULL;
6285 #endif /* not emacs */