1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P10003.2/D11.2, except for
4 internationalization features.)
6 Copyright (C) 1993-1995 Free Software Foundation, Inc.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
29 #include "../../includes/config.h"
31 #if defined(STDC_HEADERS) && !defined(emacs)
34 /* We need this for `regex.h', and perhaps for the Emacs include files. */
35 #include <sys/types.h>
38 /* The `emacs' switch turns on certain matching commands
39 that make sense only in Emacs. */
46 /* Emacs uses `NULL' as a predicate. */
51 /* We used to test for `BSTRING' here, but only GCC and Emacs define
52 `BSTRING', as far as I know, and neither of them use this code. */
53 #if HAVE_STRING_H || STDC_HEADERS
56 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
59 #define bcopy(s, d, n) memcpy ((d), (s), (n))
62 #define bzero(s, n) memset ((s), 0, (n))
76 /* Define the syntax stuff for \<, \>, etc. */
78 /* This must be nonzero for the wordchar and notwordchar pattern
79 commands in re_match_2. */
86 extern char *re_syntax_table;
88 #else /* not SYNTAX_TABLE */
90 /* How many characters in the character set. */
91 #define CHAR_SET_SIZE 256
93 static char re_syntax_table[CHAR_SET_SIZE];
104 bzero (re_syntax_table, sizeof re_syntax_table);
106 for (c = 'a'; c <= 'z'; c++)
107 re_syntax_table[c] = Sword;
109 for (c = 'A'; c <= 'Z'; c++)
110 re_syntax_table[c] = Sword;
112 for (c = '0'; c <= '9'; c++)
113 re_syntax_table[c] = Sword;
115 re_syntax_table['_'] = Sword;
120 #endif /* not SYNTAX_TABLE */
122 #define SYNTAX(c) re_syntax_table[c]
124 #endif /* not emacs */
126 /* Get the interface, including the syntax bits. */
127 #include "ghcRegex.h"
129 /* isalpha etc. are used for the character classes. */
132 /* Jim Meyering writes:
134 "... Some ctype macros are valid only for character codes that
135 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
136 using /bin/cc or gcc but without giving an ansi option). So, all
137 ctype uses should be through macros like ISPRINT... If
138 STDC_HEADERS is defined, then autoconf has verified that the ctype
139 macros don't need to be guarded with references to isascii. ...
140 Defining isascii to 1 should let any compiler worth its salt
141 eliminate the && through constant folding." */
142 #if ! defined (isascii) || defined (STDC_HEADERS)
148 #define ISBLANK(c) (isascii (c) && isblank (c))
150 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
153 #define ISGRAPH(c) (isascii (c) && isgraph (c))
155 #define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c))
158 #define ISPRINT(c) (isascii (c) && isprint (c))
159 #define ISDIGIT(c) (isascii (c) && isdigit (c))
160 #define ISALNUM(c) (isascii (c) && isalnum (c))
161 #define ISALPHA(c) (isascii (c) && isalpha (c))
162 #define ISCNTRL(c) (isascii (c) && iscntrl (c))
163 #define ISLOWER(c) (isascii (c) && islower (c))
164 #define ISPUNCT(c) (isascii (c) && ispunct (c))
165 #define ISSPACE(c) (isascii (c) && isspace (c))
166 #define ISUPPER(c) (isascii (c) && isupper (c))
167 #define ISXDIGIT(c) (isascii (c) && isxdigit (c))
173 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
174 since ours (we hope) works properly with all combinations of
175 machines, compilers, `char' and `unsigned char' argument types.
176 (Per Bothner suggested the basic approach.) */
177 #undef SIGN_EXTEND_CHAR
179 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
180 #else /* not __STDC__ */
181 /* As in Harbison and Steele. */
182 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
185 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
186 use `alloca' instead of `malloc'. This is because using malloc in
187 re_search* or re_match* could cause memory leaks when C-g is used in
188 Emacs; also, malloc is slower and causes storage fragmentation. On
189 the other hand, malloc is more portable, and easier to debug.
191 Because we sometimes use alloca, some routines have to be macros,
192 not functions -- `alloca'-allocated space disappears at the end of the
193 function it is called in. */
197 #define REGEX_ALLOCATE malloc
198 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
200 #else /* not REGEX_MALLOC */
202 /* Emacs already defines alloca, sometimes. */
205 /* Make alloca work the best possible way. */
207 #define alloca __builtin_alloca
208 #else /* not __GNUC__ */
211 #else /* not __GNUC__ or HAVE_ALLOCA_H */
212 #ifndef _AIX /* Already did AIX, up at the top. */
214 #endif /* not _AIX */
215 #endif /* not HAVE_ALLOCA_H */
216 #endif /* not __GNUC__ */
218 #endif /* not alloca */
220 #define REGEX_ALLOCATE alloca
222 /* Assumes a `char *destination' variable. */
223 #define REGEX_REALLOCATE(source, osize, nsize) \
224 (destination = (char *) alloca (nsize), \
225 bcopy (source, destination, osize), \
228 #endif /* not REGEX_MALLOC */
231 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
232 `string1' or just past its end. This works if PTR is NULL, which is
234 #define FIRST_STRING_P(ptr) \
235 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
237 /* (Re)Allocate N items of type T using malloc, or fail. */
238 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
239 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
240 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
242 #define BYTEWIDTH 8 /* In bits. */
244 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
246 #define MAX(a, b) ((a) > (b) ? (a) : (b))
247 #define MIN(a, b) ((a) < (b) ? (a) : (b))
249 typedef char boolean;
253 /* These are the command codes that appear in compiled regular
254 expressions. Some opcodes are followed by argument bytes. A
255 command code can specify any interpretation whatsoever for its
256 arguments. Zero bytes may appear in the compiled regular expression.
258 The value of `exactn' is needed in search.c (search_buffer) in Emacs.
259 So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
260 `exactn' we use here must also be 1. */
266 /* Followed by one byte giving n, then by n literal bytes. */
269 /* Matches any (more or less) character. */
272 /* Matches any one char belonging to specified set. First
273 following byte is number of bitmap bytes. Then come bytes
274 for a bitmap saying which chars are in. Bits in each byte
275 are ordered low-bit-first. A character is in the set if its
276 bit is 1. A character too large to have a bit in the map is
277 automatically not in the set. */
280 /* Same parameters as charset, but match any character that is
281 not one of those specified. */
284 /* Start remembering the text that is matched, for storing in a
285 register. Followed by one byte with the register number, in
286 the range 0 to one less than the pattern buffer's re_nsub
287 field. Then followed by one byte with the number of groups
288 inner to this one. (This last has to be part of the
289 start_memory only because we need it in the on_failure_jump
293 /* Stop remembering the text that is matched and store it in a
294 memory register. Followed by one byte with the register
295 number, in the range 0 to one less than `re_nsub' in the
296 pattern buffer, and one byte with the number of inner groups,
297 just like `start_memory'. (We need the number of inner
298 groups here because we don't have any easy way of finding the
299 corresponding start_memory when we're at a stop_memory.) */
302 /* Match a duplicate of something remembered. Followed by one
303 byte containing the register number. */
306 /* Fail unless at beginning of line. */
309 /* Fail unless at end of line. */
312 /* Succeeds if at beginning of buffer (if emacs) or at beginning
313 of string to be matched (if not). */
316 /* Analogously, for end of buffer/string. */
319 /* Followed by two byte relative address to which to jump. */
322 /* Same as jump, but marks the end of an alternative. */
325 /* Followed by two-byte relative address of place to resume at
326 in case of failure. */
329 /* Like on_failure_jump, but pushes a placeholder instead of the
330 current string position when executed. */
331 on_failure_keep_string_jump,
333 /* Throw away latest failure point and then jump to following
334 two-byte relative address. */
337 /* Change to pop_failure_jump if know won't have to backtrack to
338 match; otherwise change to jump. This is used to jump
339 back to the beginning of a repeat. If what follows this jump
340 clearly won't match what the repeat does, such that we can be
341 sure that there is no use backtracking out of repetitions
342 already matched, then we change it to a pop_failure_jump.
343 Followed by two-byte address. */
346 /* Jump to following two-byte address, and push a dummy failure
347 point. This failure point will be thrown away if an attempt
348 is made to use it for a failure. A `+' construct makes this
349 before the first repeat. Also used as an intermediary kind
350 of jump when compiling an alternative. */
353 /* Push a dummy failure point and continue. Used at the end of
357 /* Followed by two-byte relative address and two-byte number n.
358 After matching N times, jump to the address upon failure. */
361 /* Followed by two-byte relative address, and two-byte number n.
362 Jump to the address N times, then fail. */
365 /* Set the following two-byte relative address to the
366 subsequent two-byte number. The address *includes* the two
370 wordchar, /* Matches any word-constituent character. */
371 notwordchar, /* Matches any char that is not a word-constituent. */
373 wordbeg, /* Succeeds if at word beginning. */
374 wordend, /* Succeeds if at word end. */
376 wordbound, /* Succeeds if at a word boundary. */
377 notwordbound /* Succeeds if not at a word boundary. */
380 ,before_dot, /* Succeeds if before point. */
381 at_dot, /* Succeeds if at point. */
382 after_dot, /* Succeeds if after point. */
384 /* Matches any character whose syntax is specified. Followed by
385 a byte which contains a syntax code, e.g., Sword. */
388 /* Matches any character whose syntax is not that specified. */
393 /* Common operations on the compiled pattern. */
395 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
397 #define STORE_NUMBER(destination, number) \
399 (destination)[0] = (number) & 0377; \
400 (destination)[1] = (number) >> 8; \
403 /* Same as STORE_NUMBER, except increment DESTINATION to
404 the byte after where the number is stored. Therefore, DESTINATION
405 must be an lvalue. */
407 #define STORE_NUMBER_AND_INCR(destination, number) \
409 STORE_NUMBER (destination, number); \
410 (destination) += 2; \
413 /* Put into DESTINATION a number stored in two contiguous bytes starting
416 #define EXTRACT_NUMBER(destination, source) \
418 (destination) = *(source) & 0377; \
419 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
423 static void extract_number _RE_ARGS((int *dest, unsigned char *source));
425 extract_number (dest, source)
427 unsigned char *source;
429 int temp = SIGN_EXTEND_CHAR (*(source + 1));
430 *dest = *source & 0377;
434 #ifndef EXTRACT_MACROS /* To debug the macros. */
435 #undef EXTRACT_NUMBER
436 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
437 #endif /* not EXTRACT_MACROS */
441 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
442 SOURCE must be an lvalue. */
444 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
446 EXTRACT_NUMBER (destination, source); \
451 static void extract_number_and_incr _RE_ARGS((int *destination,
452 unsigned char **source));
454 extract_number_and_incr (destination, source)
456 unsigned char **source;
458 extract_number (destination, *source);
462 #ifndef EXTRACT_MACROS
463 #undef EXTRACT_NUMBER_AND_INCR
464 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
465 extract_number_and_incr (&dest, &src)
466 #endif /* not EXTRACT_MACROS */
470 /* If DEBUG is defined, Regex prints many voluminous messages about what
471 it is doing (if the variable `debug' is nonzero). If linked with the
472 main program in `iregex.c', you can enter patterns and strings
473 interactively. And if linked with the main program in `main.c' and
474 the other test files, you can run the already-written tests. */
478 /* We use standard I/O for debugging. */
481 /* It is useful to test things that ``must'' be true when debugging. */
484 static int debug = 0;
486 #define DEBUG_STATEMENT(e) e
487 #define DEBUG_PRINT1(x) if (debug) printf (x)
488 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
489 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
490 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
491 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
492 if (debug) print_partial_compiled_pattern (s, e)
493 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
494 if (debug) print_double_string (w, s1, sz1, s2, sz2)
497 extern void printchar ();
499 /* Print the fastmap in human-readable form. */
502 print_fastmap (fastmap)
505 unsigned was_a_range = 0;
508 while (i < (1 << BYTEWIDTH))
514 while (i < (1 << BYTEWIDTH) && fastmap[i])
530 /* Print a compiled pattern string in human-readable form, starting at
531 the START pointer into it and ending just before the pointer END. */
534 print_partial_compiled_pattern (start, end)
535 unsigned char *start;
539 unsigned char *p = start;
540 unsigned char *pend = end;
548 /* Loop over pattern commands. */
551 printf ("%d:\t", p - start);
553 switch ((re_opcode_t) *p++)
561 printf ("/exactn/%d", mcnt);
572 printf ("/start_memory/%d/%d", mcnt, *p++);
577 printf ("/stop_memory/%d/%d", mcnt, *p++);
581 printf ("/duplicate/%d", *p++);
591 register int c, last = -100;
592 register int in_range = 0;
594 printf ("/charset [%s",
595 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
597 assert (p + *p < pend);
599 for (c = 0; c < 256; c++)
601 && (p[1 + (c/8)] & (1 << (c % 8))))
603 /* Are we starting a range? */
604 if (last + 1 == c && ! in_range)
609 /* Have we broken a range? */
610 else if (last + 1 != c && in_range)
639 case on_failure_jump:
640 extract_number_and_incr (&mcnt, &p);
641 printf ("/on_failure_jump to %d", p + mcnt - start);
644 case on_failure_keep_string_jump:
645 extract_number_and_incr (&mcnt, &p);
646 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
649 case dummy_failure_jump:
650 extract_number_and_incr (&mcnt, &p);
651 printf ("/dummy_failure_jump to %d", p + mcnt - start);
654 case push_dummy_failure:
655 printf ("/push_dummy_failure");
659 extract_number_and_incr (&mcnt, &p);
660 printf ("/maybe_pop_jump to %d", p + mcnt - start);
663 case pop_failure_jump:
664 extract_number_and_incr (&mcnt, &p);
665 printf ("/pop_failure_jump to %d", p + mcnt - start);
669 extract_number_and_incr (&mcnt, &p);
670 printf ("/jump_past_alt to %d", p + mcnt - start);
674 extract_number_and_incr (&mcnt, &p);
675 printf ("/jump to %d", p + mcnt - start);
679 extract_number_and_incr (&mcnt, &p);
680 extract_number_and_incr (&mcnt2, &p);
681 printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
685 extract_number_and_incr (&mcnt, &p);
686 extract_number_and_incr (&mcnt2, &p);
687 printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
691 extract_number_and_incr (&mcnt, &p);
692 extract_number_and_incr (&mcnt2, &p);
693 printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
697 printf ("/wordbound");
701 printf ("/notwordbound");
713 printf ("/before_dot");
721 printf ("/after_dot");
725 printf ("/syntaxspec");
727 printf ("/%d", mcnt);
731 printf ("/notsyntaxspec");
733 printf ("/%d", mcnt);
738 printf ("/wordchar");
742 printf ("/notwordchar");
754 printf ("?%d", *(p-1));
760 printf ("%d:\tend of pattern.\n", p - start);
765 print_compiled_pattern (bufp)
766 struct re_pattern_buffer *bufp;
768 unsigned char *buffer = bufp->buffer;
770 print_partial_compiled_pattern (buffer, buffer + bufp->used);
771 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
773 if (bufp->fastmap_accurate && bufp->fastmap)
775 printf ("fastmap: ");
776 print_fastmap (bufp->fastmap);
779 printf ("re_nsub: %d\t", bufp->re_nsub);
780 printf ("regs_alloc: %d\t", bufp->regs_allocated);
781 printf ("can_be_null: %d\t", bufp->can_be_null);
782 printf ("newline_anchor: %d\n", bufp->newline_anchor);
783 printf ("no_sub: %d\t", bufp->no_sub);
784 printf ("not_bol: %d\t", bufp->not_bol);
785 printf ("not_eol: %d\t", bufp->not_eol);
786 printf ("syntax: %d\n", bufp->syntax);
787 /* Perhaps we should print the translate table? */
792 print_double_string (where, string1, size1, string2, size2)
805 if (FIRST_STRING_P (where))
807 for (this_char = where - string1; this_char < size1; this_char++)
808 printchar (string1[this_char]);
813 for (this_char = where - string2; this_char < size2; this_char++)
814 printchar (string2[this_char]);
825 #else /* not DEBUG */
830 #define DEBUG_STATEMENT(e)
831 #define DEBUG_PRINT1(x)
832 #define DEBUG_PRINT2(x1, x2)
833 #define DEBUG_PRINT3(x1, x2, x3)
834 #define DEBUG_PRINT4(x1, x2, x3, x4)
835 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
836 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
838 #endif /* not DEBUG */
840 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
841 also be assigned to arbitrarily: each pattern buffer stores its own
842 syntax, so it can be changed between regex compilations. */
843 reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
846 /* Specify the precise syntax of regexps for compilation. This provides
847 for compatibility for various utilities which historically have
848 different, incompatible syntaxes.
850 The argument SYNTAX is a bit mask comprised of the various bits
851 defined in regex.h. We return the old syntax. */
854 re_set_syntax (syntax)
857 reg_syntax_t ret = re_syntax_options;
859 re_syntax_options = syntax;
863 /* This table gives an error message for each of the error codes listed
864 in regex.h. Obviously the order here has to be same as there. */
866 static const char *re_error_msg[] =
867 { NULL, /* REG_NOERROR */
868 "No match", /* REG_NOMATCH */
869 "Invalid regular expression", /* REG_BADPAT */
870 "Invalid collation character", /* REG_ECOLLATE */
871 "Invalid character class name", /* REG_ECTYPE */
872 "Trailing backslash", /* REG_EESCAPE */
873 "Invalid back reference", /* REG_ESUBREG */
874 "Unmatched [ or [^", /* REG_EBRACK */
875 "Unmatched ( or \\(", /* REG_EPAREN */
876 "Unmatched \\{", /* REG_EBRACE */
877 "Invalid content of \\{\\}", /* REG_BADBR */
878 "Invalid range end", /* REG_ERANGE */
879 "Memory exhausted", /* REG_ESPACE */
880 "Invalid preceding regular expression", /* REG_BADRPT */
881 "Premature end of regular expression", /* REG_EEND */
882 "Regular expression too big", /* REG_ESIZE */
883 "Unmatched ) or \\)", /* REG_ERPAREN */
886 /* Subroutine declarations and macros for regex_compile. */
888 static reg_errcode_t regex_compile _RE_ARGS((const char *pattern, size_t size,
890 struct re_pattern_buffer *bufp));
891 static void store_op1 _RE_ARGS((re_opcode_t op, unsigned char *loc, int arg));
892 static void store_op2 _RE_ARGS((re_opcode_t op, unsigned char *loc,
893 int arg1, int arg2));
894 static void insert_op1 _RE_ARGS((re_opcode_t op, unsigned char *loc,
895 int arg, unsigned char *end));
896 static void insert_op2 _RE_ARGS((re_opcode_t op, unsigned char *loc,
897 int arg1, int arg2, unsigned char *end));
898 static boolean at_begline_loc_p _RE_ARGS((const char *pattern, const char *p,
899 reg_syntax_t syntax));
900 static boolean at_endline_loc_p _RE_ARGS((const char *p, const char *pend,
901 reg_syntax_t syntax));
902 static reg_errcode_t compile_range _RE_ARGS((const char **p_ptr,
908 /* Fetch the next character in the uncompiled pattern---translating it
909 if necessary. Also cast from a signed character in the constant
910 string passed to us by the user to an unsigned char that we can use
911 as an array index (in, e.g., `translate'). */
912 #define PATFETCH(c) \
913 do {if (p == pend) return REG_EEND; \
914 c = (unsigned char) *p++; \
915 if (translate) c = translate[c]; \
918 /* Fetch the next character in the uncompiled pattern, with no
920 #define PATFETCH_RAW(c) \
921 do {if (p == pend) return REG_EEND; \
922 c = (unsigned char) *p++; \
925 /* Go backwards one character in the pattern. */
926 #define PATUNFETCH p--
929 /* If `translate' is non-null, return translate[D], else just D. We
930 cast the subscript to translate because some data is declared as
931 `char *', to avoid warnings when a string constant is passed. But
932 when we use a character as a subscript we must make it unsigned. */
933 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
936 /* Macros for outputting the compiled pattern into `buffer'. */
938 /* If the buffer isn't allocated when it comes in, use this. */
939 #define INIT_BUF_SIZE 32
941 /* Make sure we have at least N more bytes of space in buffer. */
942 #define GET_BUFFER_SPACE(n) \
943 while (b - bufp->buffer + (n) > bufp->allocated) \
946 /* Make sure we have one more byte of buffer space and then add C to it. */
947 #define BUF_PUSH(c) \
949 GET_BUFFER_SPACE (1); \
950 *b++ = (unsigned char) (c); \
954 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
955 #define BUF_PUSH_2(c1, c2) \
957 GET_BUFFER_SPACE (2); \
958 *b++ = (unsigned char) (c1); \
959 *b++ = (unsigned char) (c2); \
963 /* As with BUF_PUSH_2, except for three bytes. */
964 #define BUF_PUSH_3(c1, c2, c3) \
966 GET_BUFFER_SPACE (3); \
967 *b++ = (unsigned char) (c1); \
968 *b++ = (unsigned char) (c2); \
969 *b++ = (unsigned char) (c3); \
973 /* Store a jump with opcode OP at LOC to location TO. We store a
974 relative address offset by the three bytes the jump itself occupies. */
975 #define STORE_JUMP(op, loc, to) \
976 store_op1 (op, loc, (int)((to) - (loc) - 3))
978 /* Likewise, for a two-argument jump. */
979 #define STORE_JUMP2(op, loc, to, arg) \
980 store_op2 (op, loc, (int)((to) - (loc) - 3), arg)
982 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
983 #define INSERT_JUMP(op, loc, to) \
984 insert_op1 (op, loc, (int)((to) - (loc) - 3), b)
986 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
987 #define INSERT_JUMP2(op, loc, to, arg) \
988 insert_op2 (op, loc, (int)((to) - (loc) - 3), arg, b)
991 /* This is not an arbitrary limit: the arguments which represent offsets
992 into the pattern are two bytes long. So if 2^16 bytes turns out to
993 be too small, many things would have to change. */
994 /* Any other compiler which, like MSC, has allocation limit below 2^16
995 bytes will have to use approach similar to what was done below for
996 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
997 reallocating to 0 bytes. Such thing is not going to work too well.
998 You have been warned!! */
1000 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1001 The REALLOC define eliminates a flurry of conversion warnings,
1002 but is not required. */
1003 #define MAX_BUF_SIZE 65500L
1004 #define REALLOC(p,s) realloc((p), (size_t) (s))
1006 #define MAX_BUF_SIZE (1L << 16)
1007 #define REALLOC realloc
1010 /* Extend the buffer by twice its current size via realloc and
1011 reset the pointers that pointed into the old block to point to the
1012 correct places in the new one. If extending the buffer results in it
1013 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1014 #define EXTEND_BUFFER() \
1016 unsigned char *old_buffer = bufp->buffer; \
1017 if (bufp->allocated == MAX_BUF_SIZE) \
1019 bufp->allocated <<= 1; \
1020 if (bufp->allocated > MAX_BUF_SIZE) \
1021 bufp->allocated = MAX_BUF_SIZE; \
1022 bufp->buffer = (unsigned char *) REALLOC(bufp->buffer, bufp->allocated);\
1023 if (bufp->buffer == NULL) \
1024 return REG_ESPACE; \
1025 /* If the buffer moved, move all the pointers into it. */ \
1026 if (old_buffer != bufp->buffer) \
1028 b = (b - old_buffer) + bufp->buffer; \
1029 begalt = (begalt - old_buffer) + bufp->buffer; \
1030 if (fixup_alt_jump) \
1031 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1033 laststart = (laststart - old_buffer) + bufp->buffer; \
1034 if (pending_exact) \
1035 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1040 /* Since we have one byte reserved for the register number argument to
1041 {start,stop}_memory, the maximum number of groups we can report
1042 things about is what fits in that byte. */
1043 #define MAX_REGNUM 255
1045 /* But patterns can have more than `MAX_REGNUM' registers. We just
1046 ignore the excess. */
1047 typedef unsigned regnum_t;
1050 /* Macros for the compile stack. */
1052 /* Since offsets can go either forwards or backwards, this type needs to
1053 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1054 /* int may be not enough when sizeof(int) == 2 */
1055 typedef long pattern_offset_t;
1059 pattern_offset_t begalt_offset;
1060 pattern_offset_t fixup_alt_jump;
1061 pattern_offset_t inner_group_offset;
1062 pattern_offset_t laststart_offset;
1064 } compile_stack_elt_t;
1069 compile_stack_elt_t *stack;
1071 unsigned avail; /* Offset of next open position. */
1072 } compile_stack_type;
1075 #define INIT_COMPILE_STACK_SIZE 32
1077 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1078 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1080 /* The next available element. */
1081 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1084 /* Set the bit for character C in a list. */
1085 #define SET_LIST_BIT(c) \
1086 (b[((unsigned char) (c)) / BYTEWIDTH] \
1087 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1090 /* Get the next unsigned number in the uncompiled pattern. */
1091 #define GET_UNSIGNED_NUMBER(num) \
1095 while (ISDIGIT (c)) \
1099 num = num * 10 + c - '0'; \
1107 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1109 #define IS_CHAR_CLASS(string) \
1110 (STREQ (string, "alpha") || STREQ (string, "upper") \
1111 || STREQ (string, "lower") || STREQ (string, "digit") \
1112 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1113 || STREQ (string, "space") || STREQ (string, "print") \
1114 || STREQ (string, "punct") || STREQ (string, "graph") \
1115 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1117 static boolean group_in_compile_stack _RE_ARGS((compile_stack_type
1121 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1122 Returns one of error codes defined in `regex.h', or zero for success.
1124 Assumes the `allocated' (and perhaps `buffer') and `translate'
1125 fields are set in BUFP on entry.
1127 If it succeeds, results are put in BUFP (if it returns an error, the
1128 contents of BUFP are undefined):
1129 `buffer' is the compiled pattern;
1130 `syntax' is set to SYNTAX;
1131 `used' is set to the length of the compiled pattern;
1132 `fastmap_accurate' is zero;
1133 `re_nsub' is the number of subexpressions in PATTERN;
1134 `not_bol' and `not_eol' are zero;
1136 The `fastmap' and `newline_anchor' fields are neither
1137 examined nor set. */
1139 static reg_errcode_t
1140 regex_compile (pattern, size, syntax, bufp)
1141 const char *pattern;
1143 reg_syntax_t syntax;
1144 struct re_pattern_buffer *bufp;
1146 /* We fetch characters from PATTERN here. Even though PATTERN is
1147 `char *' (i.e., signed), we declare these variables as unsigned, so
1148 they can be reliably used as array indices. */
1149 register unsigned char c, c1;
1151 /* A random tempory spot in PATTERN. */
1154 /* Points to the end of the buffer, where we should append. */
1155 register unsigned char *b;
1157 /* Keeps track of unclosed groups. */
1158 compile_stack_type compile_stack;
1160 /* Points to the current (ending) position in the pattern. */
1161 const char *p = pattern;
1162 const char *pend = pattern + size;
1164 /* How to translate the characters in the pattern. */
1165 char *translate = bufp->translate;
1167 /* Address of the count-byte of the most recently inserted `exactn'
1168 command. This makes it possible to tell if a new exact-match
1169 character can be added to that command or if the character requires
1170 a new `exactn' command. */
1171 unsigned char *pending_exact = 0;
1173 /* Address of start of the most recently finished expression.
1174 This tells, e.g., postfix * where to find the start of its
1175 operand. Reset at the beginning of groups and alternatives. */
1176 unsigned char *laststart = 0;
1178 /* Address of beginning of regexp, or inside of last group. */
1179 unsigned char *begalt;
1181 /* Place in the uncompiled pattern (i.e., the {) to
1182 which to go back if the interval is invalid. */
1183 const char *beg_interval;
1185 /* Address of the place where a forward jump should go to the end of
1186 the containing expression. Each alternative of an `or' -- except the
1187 last -- ends with a forward jump of this sort. */
1188 unsigned char *fixup_alt_jump = 0;
1190 /* Counts open-groups as they are encountered. Remembered for the
1191 matching close-group on the compile stack, so the same register
1192 number is put in the stop_memory as the start_memory. */
1193 regnum_t regnum = 0;
1196 DEBUG_PRINT1 ("\nCompiling pattern: ");
1199 unsigned debug_count;
1201 for (debug_count = 0; debug_count < size; debug_count++)
1202 printchar (pattern[debug_count]);
1207 /* Initialize the compile stack. */
1208 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1209 if (compile_stack.stack == NULL)
1212 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1213 compile_stack.avail = 0;
1215 /* Initialize the pattern buffer. */
1216 bufp->syntax = syntax;
1217 bufp->fastmap_accurate = 0;
1218 bufp->not_bol = bufp->not_eol = 0;
1220 /* Set `used' to zero, so that if we return an error, the pattern
1221 printer (for debugging) will think there's no pattern. We reset it
1225 /* Always count groups, whether or not bufp->no_sub is set. */
1228 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1229 /* Initialize the syntax table. */
1230 init_syntax_once ();
1233 if (bufp->allocated == 0)
1236 { /* If zero allocated, but buffer is non-null, try to realloc
1237 enough space. This loses if buffer's address is bogus, but
1238 that is the user's responsibility. */
1239 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1242 { /* Caller did not allocate a buffer. Do it for them. */
1243 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1245 if (!bufp->buffer) return REG_ESPACE;
1247 bufp->allocated = INIT_BUF_SIZE;
1250 begalt = b = bufp->buffer;
1252 /* Loop through the uncompiled pattern until we're at the end. */
1261 if ( /* If at start of pattern, it's an operator. */
1263 /* If context independent, it's an operator. */
1264 || syntax & RE_CONTEXT_INDEP_ANCHORS
1265 /* Otherwise, depends on what's come before. */
1266 || at_begline_loc_p (pattern, p, syntax))
1276 if ( /* If at end of pattern, it's an operator. */
1278 /* If context independent, it's an operator. */
1279 || syntax & RE_CONTEXT_INDEP_ANCHORS
1280 /* Otherwise, depends on what's next. */
1281 || at_endline_loc_p (p, pend, syntax))
1291 if ((syntax & RE_BK_PLUS_QM)
1292 || (syntax & RE_LIMITED_OPS))
1296 /* If there is no previous pattern... */
1299 if (syntax & RE_CONTEXT_INVALID_OPS)
1301 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1306 /* Are we optimizing this jump? */
1307 boolean keep_string_p = false;
1309 /* 1 means zero (many) matches is allowed. */
1310 char zero_times_ok = 0, many_times_ok = 0;
1312 /* If there is a sequence of repetition chars, collapse it
1313 down to just one (the right one). We can't combine
1314 interval operators with these because of, e.g., `a{2}*',
1315 which should only match an even number of `a's. */
1319 zero_times_ok |= c != '+';
1320 many_times_ok |= c != '?';
1328 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1331 else if (syntax & RE_BK_PLUS_QM && c == '\\')
1333 if (p == pend) return REG_EESCAPE;
1336 if (!(c1 == '+' || c1 == '?'))
1351 /* If we get here, we found another repeat character. */
1354 /* Star, etc. applied to an empty pattern is equivalent
1355 to an empty pattern. */
1359 /* Now we know whether or not zero matches is allowed
1360 and also whether or not two or more matches is allowed. */
1362 { /* More than one repetition is allowed, so put in at the
1363 end a backward relative jump from `b' to before the next
1364 jump we're going to put in below (which jumps from
1365 laststart to after this jump).
1367 But if we are at the `*' in the exact sequence `.*\n',
1368 insert an unconditional jump backwards to the .,
1369 instead of the beginning of the loop. This way we only
1370 push a failure point once, instead of every time
1371 through the loop. */
1372 assert (p - 1 > pattern);
1374 /* Allocate the space for the jump. */
1375 GET_BUFFER_SPACE (3);
1377 /* We know we are not at the first character of the pattern,
1378 because laststart was nonzero. And we've already
1379 incremented `p', by the way, to be the character after
1380 the `*'. Do we have to do something analogous here
1381 for null bytes, because of RE_DOT_NOT_NULL? */
1382 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1384 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1385 && !(syntax & RE_DOT_NEWLINE))
1386 { /* We have .*\n. */
1387 STORE_JUMP (jump, b, laststart);
1388 keep_string_p = true;
1391 /* Anything else. */
1392 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1394 /* We've added more stuff to the buffer. */
1398 /* On failure, jump from laststart to b + 3, which will be the
1399 end of the buffer after this jump is inserted. */
1400 GET_BUFFER_SPACE (3);
1401 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1409 /* At least one repetition is required, so insert a
1410 `dummy_failure_jump' before the initial
1411 `on_failure_jump' instruction of the loop. This
1412 effects a skip over that instruction the first time
1413 we hit that loop. */
1414 GET_BUFFER_SPACE (3);
1415 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1430 boolean had_char_class = false;
1432 if (p == pend) return REG_EBRACK;
1434 /* Ensure that we have enough space to push a charset: the
1435 opcode, the length count, and the bitset; 34 bytes in all. */
1436 GET_BUFFER_SPACE (34);
1440 /* We test `*p == '^' twice, instead of using an if
1441 statement, so we only need one BUF_PUSH. */
1442 BUF_PUSH (*p == '^' ? charset_not : charset);
1446 /* Remember the first position in the bracket expression. */
1449 /* Push the number of bytes in the bitmap. */
1450 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1452 /* Clear the whole map. */
1453 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1455 /* charset_not matches newline according to a syntax bit. */
1456 if ((re_opcode_t) b[-2] == charset_not
1457 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1458 SET_LIST_BIT ('\n');
1460 /* Read in characters and ranges, setting map bits. */
1463 if (p == pend) return REG_EBRACK;
1467 /* \ might escape characters inside [...] and [^...]. */
1468 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1470 if (p == pend) return REG_EESCAPE;
1477 /* Could be the end of the bracket expression. If it's
1478 not (i.e., when the bracket expression is `[]' so
1479 far), the ']' character bit gets set way below. */
1480 if (c == ']' && p != p1 + 1)
1483 /* Look ahead to see if it's a range when the last thing
1484 was a character class. */
1485 if (had_char_class && c == '-' && *p != ']')
1488 /* Look ahead to see if it's a range when the last thing
1489 was a character: if this is a hyphen not at the
1490 beginning or the end of a list, then it's the range
1493 && !(p - 2 >= pattern && p[-2] == '[')
1494 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1498 = compile_range (&p, pend, translate, syntax, b);
1499 if (ret != REG_NOERROR) return ret;
1502 else if (p[0] == '-' && p[1] != ']')
1503 { /* This handles ranges made up of characters only. */
1506 /* Move past the `-'. */
1509 ret = compile_range (&p, pend, translate, syntax, b);
1510 if (ret != REG_NOERROR) return ret;
1513 /* See if we're at the beginning of a possible character
1516 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
1517 { /* Leave room for the null. */
1518 char str[CHAR_CLASS_MAX_LENGTH + 1];
1523 /* If pattern is `[[:'. */
1524 if (p == pend) return REG_EBRACK;
1529 if (c == ':' || c == ']' || p == pend
1530 || c1 == CHAR_CLASS_MAX_LENGTH)
1536 /* If isn't a word bracketed by `[:' and:`]':
1537 undo the ending character, the letters, and leave
1538 the leading `:' and `[' (but set bits for them). */
1539 if (c == ':' && *p == ']')
1542 boolean is_alnum = STREQ (str, "alnum");
1543 boolean is_alpha = STREQ (str, "alpha");
1544 boolean is_blank = STREQ (str, "blank");
1545 boolean is_cntrl = STREQ (str, "cntrl");
1546 boolean is_digit = STREQ (str, "digit");
1547 boolean is_graph = STREQ (str, "graph");
1548 boolean is_lower = STREQ (str, "lower");
1549 boolean is_print = STREQ (str, "print");
1550 boolean is_punct = STREQ (str, "punct");
1551 boolean is_space = STREQ (str, "space");
1552 boolean is_upper = STREQ (str, "upper");
1553 boolean is_xdigit = STREQ (str, "xdigit");
1555 if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
1557 /* Throw away the ] at the end of the character
1561 if (p == pend) return REG_EBRACK;
1563 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
1565 if ( (is_alnum && ISALNUM (ch))
1566 || (is_alpha && ISALPHA (ch))
1567 || (is_blank && ISBLANK (ch))
1568 || (is_cntrl && ISCNTRL (ch))
1569 || (is_digit && ISDIGIT (ch))
1570 || (is_graph && ISGRAPH (ch))
1571 || (is_lower && ISLOWER (ch))
1572 || (is_print && ISPRINT (ch))
1573 || (is_punct && ISPUNCT (ch))
1574 || (is_space && ISSPACE (ch))
1575 || (is_upper && ISUPPER (ch))
1576 || (is_xdigit && ISXDIGIT (ch)))
1579 had_char_class = true;
1588 had_char_class = false;
1593 had_char_class = false;
1598 /* Discard any (non)matching list bytes that are all 0 at the
1599 end of the map. Decrease the map-length byte too. */
1600 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
1608 if (syntax & RE_NO_BK_PARENS)
1615 if (syntax & RE_NO_BK_PARENS)
1622 if (syntax & RE_NEWLINE_ALT)
1629 if (syntax & RE_NO_BK_VBAR)
1636 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1637 goto handle_interval;
1643 if (p == pend) return REG_EESCAPE;
1645 /* Do not translate the character after the \, so that we can
1646 distinguish, e.g., \B from \b, even if we normally would
1647 translate, e.g., B to b. */
1653 if (syntax & RE_NO_BK_PARENS)
1654 goto normal_backslash;
1660 if (COMPILE_STACK_FULL)
1662 RETALLOC (compile_stack.stack, compile_stack.size << 1,
1663 compile_stack_elt_t);
1664 if (compile_stack.stack == NULL) return REG_ESPACE;
1666 compile_stack.size <<= 1;
1669 /* These are the values to restore when we hit end of this
1670 group. They are all relative offsets, so that if the
1671 whole pattern moves because of realloc, they will still
1673 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
1674 COMPILE_STACK_TOP.fixup_alt_jump
1675 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
1676 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
1677 COMPILE_STACK_TOP.regnum = regnum;
1679 /* We will eventually replace the 0 with the number of
1680 groups inner to this one. But do not push a
1681 start_memory for groups beyond the last one we can
1682 represent in the compiled pattern. */
1683 if (regnum <= MAX_REGNUM)
1685 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
1686 BUF_PUSH_3 (start_memory, regnum, 0);
1689 compile_stack.avail++;
1694 /* If we've reached MAX_REGNUM groups, then this open
1695 won't actually generate any code, so we'll have to
1696 clear pending_exact explicitly. */
1702 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
1704 if (COMPILE_STACK_EMPTY)
1705 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1706 goto normal_backslash;
1712 { /* Push a dummy failure point at the end of the
1713 alternative for a possible future
1714 `pop_failure_jump' to pop. See comments at
1715 `push_dummy_failure' in `re_match_2'. */
1716 BUF_PUSH (push_dummy_failure);
1718 /* We allocated space for this jump when we assigned
1719 to `fixup_alt_jump', in the `handle_alt' case below. */
1720 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
1723 /* See similar code for backslashed left paren above. */
1724 if (COMPILE_STACK_EMPTY)
1725 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1730 /* Since we just checked for an empty stack above, this
1731 ``can't happen''. */
1732 assert (compile_stack.avail != 0);
1734 /* We don't just want to restore into `regnum', because
1735 later groups should continue to be numbered higher,
1736 as in `(ab)c(de)' -- the second group is #2. */
1737 regnum_t this_group_regnum;
1739 compile_stack.avail--;
1740 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
1742 = COMPILE_STACK_TOP.fixup_alt_jump
1743 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
1745 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
1746 this_group_regnum = COMPILE_STACK_TOP.regnum;
1747 /* If we've reached MAX_REGNUM groups, then this open
1748 won't actually generate any code, so we'll have to
1749 clear pending_exact explicitly. */
1752 /* We're at the end of the group, so now we know how many
1753 groups were inside this one. */
1754 if (this_group_regnum <= MAX_REGNUM)
1756 unsigned char *inner_group_loc
1757 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
1759 *inner_group_loc = regnum - this_group_regnum;
1760 BUF_PUSH_3 (stop_memory, this_group_regnum,
1761 regnum - this_group_regnum);
1767 case '|': /* `\|'. */
1768 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
1769 goto normal_backslash;
1771 if (syntax & RE_LIMITED_OPS)
1774 /* Insert before the previous alternative a jump which
1775 jumps to this alternative if the former fails. */
1776 GET_BUFFER_SPACE (3);
1777 INSERT_JUMP (on_failure_jump, begalt, b + 6);
1781 /* The alternative before this one has a jump after it
1782 which gets executed if it gets matched. Adjust that
1783 jump so it will jump to this alternative's analogous
1784 jump (put in below, which in turn will jump to the next
1785 (if any) alternative's such jump, etc.). The last such
1786 jump jumps to the correct final destination. A picture:
1792 If we are at `b', then fixup_alt_jump right now points to a
1793 three-byte space after `a'. We'll put in the jump, set
1794 fixup_alt_jump to right after `b', and leave behind three
1795 bytes which we'll fill in when we get to after `c'. */
1798 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
1800 /* Mark and leave space for a jump after this alternative,
1801 to be filled in later either by next alternative or
1802 when know we're at the end of a series of alternatives. */
1804 GET_BUFFER_SPACE (3);
1813 /* If \{ is a literal. */
1814 if (!(syntax & RE_INTERVALS)
1815 /* If we're at `\{' and it's not the open-interval
1817 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
1818 || (p - 2 == pattern && p == pend))
1819 goto normal_backslash;
1823 /* If got here, then the syntax allows intervals. */
1825 /* At least (most) this many matches must be made. */
1826 int lower_bound = -1, upper_bound = -1;
1828 beg_interval = p - 1;
1832 if (syntax & RE_NO_BK_BRACES)
1833 goto unfetch_interval;
1838 GET_UNSIGNED_NUMBER (lower_bound);
1842 GET_UNSIGNED_NUMBER (upper_bound);
1843 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
1846 /* Interval such as `{1}' => match exactly once. */
1847 upper_bound = lower_bound;
1849 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
1850 || lower_bound > upper_bound)
1852 if (syntax & RE_NO_BK_BRACES)
1853 goto unfetch_interval;
1858 if (!(syntax & RE_NO_BK_BRACES))
1860 if (c != '\\') return REG_EBRACE;
1867 if (syntax & RE_NO_BK_BRACES)
1868 goto unfetch_interval;
1873 /* We just parsed a valid interval. */
1875 /* If it's invalid to have no preceding re. */
1878 if (syntax & RE_CONTEXT_INVALID_OPS)
1880 else if (syntax & RE_CONTEXT_INDEP_OPS)
1883 goto unfetch_interval;
1886 /* If the upper bound is zero, don't want to succeed at
1887 all; jump from `laststart' to `b + 3', which will be
1888 the end of the buffer after we insert the jump. */
1889 if (upper_bound == 0)
1891 GET_BUFFER_SPACE (3);
1892 INSERT_JUMP (jump, laststart, b + 3);
1896 /* Otherwise, we have a nontrivial interval. When
1897 we're all done, the pattern will look like:
1898 set_number_at <jump count> <upper bound>
1899 set_number_at <succeed_n count> <lower bound>
1900 succeed_n <after jump addr> <succed_n count>
1902 jump_n <succeed_n addr> <jump count>
1903 (The upper bound and `jump_n' are omitted if
1904 `upper_bound' is 1, though.) */
1906 { /* If the upper bound is > 1, we need to insert
1907 more at the end of the loop. */
1908 unsigned nbytes = 10 + (upper_bound > 1) * 10;
1910 GET_BUFFER_SPACE (nbytes);
1912 /* Initialize lower bound of the `succeed_n', even
1913 though it will be set during matching by its
1914 attendant `set_number_at' (inserted next),
1915 because `re_compile_fastmap' needs to know.
1916 Jump to the `jump_n' we might insert below. */
1917 INSERT_JUMP2 (succeed_n, laststart,
1918 b + 5 + (upper_bound > 1) * 5,
1922 /* Code to initialize the lower bound. Insert
1923 before the `succeed_n'. The `5' is the last two
1924 bytes of this `set_number_at', plus 3 bytes of
1925 the following `succeed_n'. */
1926 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
1929 if (upper_bound > 1)
1930 { /* More than one repetition is allowed, so
1931 append a backward jump to the `succeed_n'
1932 that starts this interval.
1934 When we've reached this during matching,
1935 we'll have matched the interval once, so
1936 jump back only `upper_bound - 1' times. */
1937 STORE_JUMP2 (jump_n, b, laststart + 5,
1941 /* The location we want to set is the second
1942 parameter of the `jump_n'; that is `b-2' as
1943 an absolute address. `laststart' will be
1944 the `set_number_at' we're about to insert;
1945 `laststart+3' the number to set, the source
1946 for the relative address. But we are
1947 inserting into the middle of the pattern --
1948 so everything is getting moved up by 5.
1949 Conclusion: (b - 2) - (laststart + 3) + 5,
1950 i.e., b - laststart.
1952 We insert this at the beginning of the loop
1953 so that if we fail during matching, we'll
1954 reinitialize the bounds. */
1955 insert_op2 (set_number_at, laststart, b - laststart,
1956 upper_bound - 1, b);
1961 beg_interval = NULL;
1966 /* If an invalid interval, match the characters as literals. */
1967 assert (beg_interval);
1969 beg_interval = NULL;
1971 /* normal_char and normal_backslash need `c'. */
1974 if (!(syntax & RE_NO_BK_BRACES))
1976 if (p > pattern && p[-1] == '\\')
1977 goto normal_backslash;
1986 BUF_PUSH_2 (exactn, 1);
1990 case 't': /* (horiz) tabn */
1994 BUF_PUSH_2 (exactn, 1);
1998 case 'r': /* Carriage Return */
2002 BUF_PUSH_2 (exactn, 1);
2006 case 'f': /* Formfeed */
2010 BUF_PUSH_2 (exactn, 1);
2014 case 'v': /* Vertical tab */
2018 BUF_PUSH_2 (exactn, 1);
2022 case 'a': /* Alarm bell */
2026 BUF_PUSH_2 (exactn, 1);
2030 case 'e': /* Escape */
2034 BUF_PUSH_2 (exactn, 1);
2047 case 's': /* \s matches whitespace */
2052 /* Ensure that we have enough space to push a charset: the
2053 opcode, the length count, and the bitset; 34 bytes in all. */
2054 GET_BUFFER_SPACE (34);
2060 /* Push the number of bytes in the bitmap. */
2061 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2063 /* Clear the whole map. */
2064 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2066 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2070 /* Discard any (non)matching list bytes that are all 0 at the
2071 end of the map. Decrease the map-length byte too. */
2072 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2078 case 'S': /* \S matches non-whitespace */
2083 /* Ensure that we have enough space to push a charset: the
2084 opcode, the length count, and the bitset; 34 bytes in all. */
2085 GET_BUFFER_SPACE (34);
2089 BUF_PUSH (charset_not);
2091 /* Push the number of bytes in the bitmap. */
2092 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2094 /* Clear the whole map. */
2095 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2097 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2101 /* Discard any (non)matching list bytes that are all 0 at the
2102 end of the map. Decrease the map-length byte too. */
2103 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2110 case 'w': /* \w matches alphanumeric (+ '_')*/
2115 /* Ensure that we have enough space to push a charset: the
2116 opcode, the length count, and the bitset; 34 bytes in all. */
2117 GET_BUFFER_SPACE (34);
2123 /* Push the number of bytes in the bitmap. */
2124 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2126 /* Clear the whole map. */
2127 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2129 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2135 /* Discard any (non)matching list bytes that are all 0 at the
2136 end of the map. Decrease the map-length byte too. */
2137 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2143 case 'W': /* \W matches non-alphanumeric */
2148 /* Ensure that we have enough space to push a charset: the
2149 opcode, the length count, and the bitset; 34 bytes in all. */
2150 GET_BUFFER_SPACE (34);
2154 BUF_PUSH (charset_not);
2156 /* Push the number of bytes in the bitmap. */
2157 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2159 /* Clear the whole map. */
2160 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2162 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2168 /* Discard any (non)matching list bytes that are all 0 at the
2169 end of the map. Decrease the map-length byte too. */
2170 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2176 case 'd': /* \d matches a numeric */
2181 /* Ensure that we have enough space to push a charset: the
2182 opcode, the length count, and the bitset; 34 bytes in all. */
2183 GET_BUFFER_SPACE (34);
2189 /* Push the number of bytes in the bitmap. */
2190 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2192 /* Clear the whole map. */
2193 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2195 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2199 /* Discard any (non)matching list bytes that are all 0 at the
2200 end of the map. Decrease the map-length byte too. */
2201 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2207 case 'D': /* \D matches a non-numeric */
2212 /* Ensure that we have enough space to push a charset: the
2213 opcode, the length count, and the bitset; 34 bytes in all. */
2214 GET_BUFFER_SPACE (34);
2218 BUF_PUSH (charset_not);
2220 /* Push the number of bytes in the bitmap. */
2221 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2223 /* Clear the whole map. */
2224 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2226 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2230 /* Discard any (non)matching list bytes that are all 0 at the
2231 end of the map. Decrease the map-length byte too. */
2232 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2238 #endif /* PERLSYNTAX */
2241 /* There is no way to specify the before_dot and after_dot
2242 operators. rms says this is ok. --karl */
2250 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2256 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2260 #if !defined(PERLSYNTAX)
2262 if (re_syntax_options & RE_NO_GNU_OPS)
2265 BUF_PUSH (wordchar);
2270 if (re_syntax_options & RE_NO_GNU_OPS)
2273 BUF_PUSH (notwordchar);
2278 if (re_syntax_options & RE_NO_GNU_OPS)
2284 if (re_syntax_options & RE_NO_GNU_OPS)
2289 #endif /* !defined PERLSYNTAX */
2292 if (re_syntax_options & RE_NO_GNU_OPS)
2294 BUF_PUSH (wordbound);
2298 if (re_syntax_options & RE_NO_GNU_OPS)
2300 BUF_PUSH (notwordbound);
2303 #if !defined(PERLSYNTAX)
2306 if (re_syntax_options & RE_NO_GNU_OPS)
2312 if (re_syntax_options & RE_NO_GNU_OPS)
2317 #endif /* !defined PERLSYNTAX */
2319 case '1': case '2': case '3': case '4': case '5':
2320 case '6': case '7': case '8': case '9':
2321 if (syntax & RE_NO_BK_REFS)
2329 /* Can't back reference to a subexpression if inside of it. */
2330 if (group_in_compile_stack (compile_stack, (regnum_t)c1))
2334 BUF_PUSH_2 (duplicate, c1);
2340 if (syntax & RE_BK_PLUS_QM)
2343 goto normal_backslash;
2347 /* You might think it would be useful for \ to mean
2348 not to translate; but if we don't translate it
2349 it will never match anything. */
2357 /* Expects the character in `c'. */
2359 /* If no exactn currently being built. */
2362 /* If last exactn not at current position. */
2363 || pending_exact + *pending_exact + 1 != b
2365 /* We have only one byte following the exactn for the count. */
2366 || *pending_exact == (1 << BYTEWIDTH) - 1
2368 /* If followed by a repetition operator. */
2369 || *p == '*' || *p == '^'
2370 || ((syntax & RE_BK_PLUS_QM)
2371 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2372 : (*p == '+' || *p == '?'))
2373 || ((syntax & RE_INTERVALS)
2374 && ((syntax & RE_NO_BK_BRACES)
2376 : (p[0] == '\\' && p[1] == '{'))))
2378 /* Start building a new exactn. */
2382 BUF_PUSH_2 (exactn, 0);
2383 pending_exact = b - 1;
2390 } /* while p != pend */
2393 /* Through the pattern now. */
2396 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2398 if (!COMPILE_STACK_EMPTY)
2401 free (compile_stack.stack);
2403 /* We have succeeded; set the length of the buffer. */
2404 bufp->used = b - bufp->buffer;
2409 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2410 print_compiled_pattern (bufp);
2415 } /* regex_compile */
2417 /* Subroutines for `regex_compile'. */
2419 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2422 store_op1 (op, loc, arg)
2427 *loc = (unsigned char) op;
2428 STORE_NUMBER (loc + 1, arg);
2432 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2435 store_op2 (op, loc, arg1, arg2)
2440 *loc = (unsigned char) op;
2441 STORE_NUMBER (loc + 1, arg1);
2442 STORE_NUMBER (loc + 3, arg2);
2446 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2447 for OP followed by two-byte integer parameter ARG. */
2450 insert_op1 (op, loc, arg, end)
2456 register unsigned char *pfrom = end;
2457 register unsigned char *pto = end + 3;
2459 while (pfrom != loc)
2462 store_op1 (op, loc, arg);
2466 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2469 insert_op2 (op, loc, arg1, arg2, end)
2475 register unsigned char *pfrom = end;
2476 register unsigned char *pto = end + 5;
2478 while (pfrom != loc)
2481 store_op2 (op, loc, arg1, arg2);
2485 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2486 after an alternative or a begin-subexpression. We assume there is at
2487 least one character before the ^. */
2490 at_begline_loc_p (pattern, p, syntax)
2491 const char *pattern, *p;
2492 reg_syntax_t syntax;
2494 const char *prev = p - 2;
2495 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2498 /* After a subexpression? */
2499 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2500 /* After an alternative? */
2501 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2505 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2506 at least one character after the $, i.e., `P < PEND'. */
2509 at_endline_loc_p (p, pend, syntax)
2510 const char *p, *pend;
2511 reg_syntax_t syntax;
2513 const char *next = p;
2514 boolean next_backslash = *next == '\\';
2515 const char *next_next = p + 1 < pend ? p + 1 : NULL;
2518 /* Before a subexpression? */
2519 (syntax & RE_NO_BK_PARENS ? *next == ')'
2520 : next_backslash && next_next && *next_next == ')')
2521 /* Before an alternative? */
2522 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2523 : next_backslash && next_next && *next_next == '|');
2527 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2528 false if it's not. */
2531 group_in_compile_stack (compile_stack, regnum)
2532 compile_stack_type compile_stack;
2537 for (this_element = compile_stack.avail - 1;
2540 if (compile_stack.stack[this_element].regnum == regnum)
2547 /* Read the ending character of a range (in a bracket expression) from the
2548 uncompiled pattern *P_PTR (which ends at PEND). We assume the
2549 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2550 Then we set the translation of all bits between the starting and
2551 ending characters (inclusive) in the compiled pattern B.
2553 Return an error code.
2555 We use these short variable names so we can use the same macros as
2556 `regex_compile' itself. */
2558 static reg_errcode_t
2559 compile_range (p_ptr, pend, translate, syntax, b)
2560 const char **p_ptr, *pend;
2562 reg_syntax_t syntax;
2567 const char *p = *p_ptr;
2568 int range_start, range_end;
2573 /* Even though the pattern is a signed `char *', we need to fetch
2574 with unsigned char *'s; if the high bit of the pattern character
2575 is set, the range endpoints will be negative if we fetch using a
2578 We also want to fetch the endpoints without translating them; the
2579 appropriate translation is done in the bit-setting loop below. */
2580 range_start = ((unsigned char *) p)[-2];
2581 range_end = ((unsigned char *) p)[0];
2583 /* Have to increment the pointer into the pattern string, so the
2584 caller isn't still at the ending character. */
2587 /* If the start is after the end, the range is empty. */
2588 if (range_start > range_end)
2589 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2591 /* Here we see why `this_char' has to be larger than an `unsigned
2592 char' -- the range is inclusive, so if `range_end' == 0xff
2593 (assuming 8-bit characters), we would otherwise go into an infinite
2594 loop, since all characters <= 0xff. */
2595 for (this_char = range_start; this_char <= range_end; this_char++)
2597 SET_LIST_BIT (TRANSLATE (this_char));
2603 /* Failure stack declarations and macros; both re_compile_fastmap and
2604 re_match_2 use a failure stack. These have to be macros because of
2608 /* Number of failure points for which to initially allocate space
2609 when matching. If this number is exceeded, we allocate more
2610 space, so it is not a hard limit. */
2611 #ifndef INIT_FAILURE_ALLOC
2612 #define INIT_FAILURE_ALLOC 5
2615 /* Roughly the maximum number of failure points on the stack. Would be
2616 exactly that if always used MAX_FAILURE_SPACE each time we failed.
2617 This is a variable only so users of regex can assign to it; we never
2618 change it ourselves. */
2619 int re_max_failures = 2000;
2621 typedef const unsigned char *fail_stack_elt_t;
2625 fail_stack_elt_t *stack;
2627 unsigned avail; /* Offset of next open position. */
2630 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
2631 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2632 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
2633 #define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])
2636 /* Initialize `fail_stack'. Do `return -2' if the alloc fails. */
2638 #define INIT_FAIL_STACK() \
2640 fail_stack.stack = (fail_stack_elt_t *) \
2641 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
2643 if (fail_stack.stack == NULL) \
2646 fail_stack.size = INIT_FAILURE_ALLOC; \
2647 fail_stack.avail = 0; \
2651 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
2653 Return 1 if succeeds, and 0 if either ran out of memory
2654 allocating space for it or it was already too large.
2656 REGEX_REALLOCATE requires `destination' be declared. */
2658 #define DOUBLE_FAIL_STACK(fail_stack) \
2659 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
2661 : ((fail_stack).stack = (fail_stack_elt_t *) \
2662 REGEX_REALLOCATE ((fail_stack).stack, \
2663 (fail_stack).size * sizeof (fail_stack_elt_t), \
2664 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
2666 (fail_stack).stack == NULL \
2668 : ((fail_stack).size <<= 1, \
2672 /* Push PATTERN_OP on FAIL_STACK.
2674 Return 1 if was able to do so and 0 if ran out of memory allocating
2676 #define PUSH_PATTERN_OP(pattern_op, fail_stack) \
2677 ((FAIL_STACK_FULL () \
2678 && !DOUBLE_FAIL_STACK (fail_stack)) \
2680 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \
2683 /* This pushes an item onto the failure stack. Must be a four-byte
2684 value. Assumes the variable `fail_stack'. Probably should only
2685 be called from within `PUSH_FAILURE_POINT'. */
2686 #define PUSH_FAILURE_ITEM(item) \
2687 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2689 /* The complement operation. Assumes `fail_stack' is nonempty. */
2690 #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2692 /* Used to omit pushing failure point id's when we're not debugging. */
2694 #define DEBUG_PUSH PUSH_FAILURE_ITEM
2695 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2697 #define DEBUG_PUSH(item)
2698 #define DEBUG_POP(item_addr)
2702 /* Push the information about the state we will need
2703 if we ever fail back to it.
2705 Requires variables fail_stack, regstart, regend, reg_info, and
2706 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
2709 Does `return FAILURE_CODE' if runs out of memory. */
2711 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
2713 char *destination; \
2714 /* Must be int, so when we don't save any registers, the arithmetic \
2715 of 0 + -1 isn't done as unsigned. */ \
2716 /* Can't be int, since there is not a shred of a guarantee that int \
2717 is wide enough to hold a value of something to which pointer can \
2721 DEBUG_STATEMENT (failure_id++); \
2722 DEBUG_STATEMENT (nfailure_points_pushed++); \
2723 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
2724 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
2725 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
2727 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
2728 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
2730 /* Ensure we have enough space allocated for what we will push. */ \
2731 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
2733 if (!DOUBLE_FAIL_STACK (fail_stack)) \
2734 return failure_code; \
2736 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
2737 (fail_stack).size); \
2738 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2741 #define PUSH_FAILURE_POINT2(pattern_place, string_place, failure_code) \
2742 /* Push the info, starting with the registers. */ \
2743 DEBUG_PRINT1 ("\n"); \
2745 PUSH_FAILURE_POINT_LOOP (); \
2747 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
2748 PUSH_FAILURE_ITEM (lowest_active_reg); \
2750 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
2751 PUSH_FAILURE_ITEM (highest_active_reg); \
2753 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
2754 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
2755 PUSH_FAILURE_ITEM (pattern_place); \
2757 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
2758 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
2760 DEBUG_PRINT1 ("'\n"); \
2761 PUSH_FAILURE_ITEM (string_place); \
2763 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
2764 DEBUG_PUSH (failure_id); \
2767 /* Pulled out of PUSH_FAILURE_POINT() to shorten the definition
2768 of that macro. (for VAX C) */
2769 #define PUSH_FAILURE_POINT_LOOP() \
2770 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
2773 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
2774 DEBUG_STATEMENT (num_regs_pushed++); \
2776 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2777 PUSH_FAILURE_ITEM (regstart[this_reg]); \
2779 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2780 PUSH_FAILURE_ITEM (regend[this_reg]); \
2782 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
2783 DEBUG_PRINT2 (" match_null=%d", \
2784 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
2785 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
2786 DEBUG_PRINT2 (" matched_something=%d", \
2787 MATCHED_SOMETHING (reg_info[this_reg])); \
2788 DEBUG_PRINT2 (" ever_matched=%d", \
2789 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
2790 DEBUG_PRINT1 ("\n"); \
2791 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \
2794 /* This is the number of items that are pushed and popped on the stack
2795 for each register. */
2796 #define NUM_REG_ITEMS 3
2798 /* Individual items aside from the registers. */
2800 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
2802 #define NUM_NONREG_ITEMS 4
2805 /* We push at most this many items on the stack. */
2806 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2808 /* We actually push this many items. */
2809 #define NUM_FAILURE_ITEMS \
2810 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
2813 /* How many items can still be added to the stack without overflowing it. */
2814 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2817 /* Pops what PUSH_FAIL_STACK pushes.
2819 We restore into the parameters, all of which should be lvalues:
2820 STR -- the saved data position.
2821 PAT -- the saved pattern position.
2822 LOW_REG, HIGH_REG -- the highest and lowest active registers.
2823 REGSTART, REGEND -- arrays of string positions.
2824 REG_INFO -- array of information about each subexpression.
2826 Also assumes the variables `fail_stack' and (if debugging), `bufp',
2827 `pend', `string1', `size1', `string2', and `size2'. */
2829 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2831 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
2833 const unsigned char *string_temp; \
2835 assert (!FAIL_STACK_EMPTY ()); \
2837 /* Remove failure points and point to how many regs pushed. */ \
2838 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
2839 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
2840 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
2842 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
2844 DEBUG_POP (&failure_id); \
2845 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
2847 /* If the saved string location is NULL, it came from an \
2848 on_failure_keep_string_jump opcode, and we want to throw away the \
2849 saved NULL, thus retaining our current position in the string. */ \
2850 string_temp = POP_FAILURE_ITEM (); \
2851 if (string_temp != NULL) \
2852 str = (const char *) string_temp; \
2854 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
2855 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
2856 DEBUG_PRINT1 ("'\n"); \
2858 pat = (unsigned char *) POP_FAILURE_ITEM (); \
2859 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
2860 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
2862 POP_FAILURE_POINT2 (low_reg, high_reg, regstart, regend, reg_info);
2864 /* Pulled out of POP_FAILURE_POINT() to shorten the definition
2865 of that macro. (for MSC 5.1) */
2866 #define POP_FAILURE_POINT2(low_reg, high_reg, regstart, regend, reg_info) \
2868 /* Restore register info. */ \
2869 high_reg = (active_reg_t) POP_FAILURE_ITEM (); \
2870 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
2872 low_reg = (active_reg_t) POP_FAILURE_ITEM (); \
2873 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
2875 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
2877 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
2879 reg_info[this_reg].word = POP_FAILURE_ITEM (); \
2880 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
2882 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2883 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2885 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2886 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2889 DEBUG_STATEMENT (nfailure_points_popped++); \
2890 } /* POP_FAILURE_POINT */
2893 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2894 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2895 characters can start a string that matches the pattern. This fastmap
2896 is used by re_search to skip quickly over impossible starting points.
2898 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2899 area as BUFP->fastmap.
2901 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2904 Returns 0 if we succeed, -2 if an internal error. */
2907 re_compile_fastmap (bufp)
2908 struct re_pattern_buffer *bufp;
2911 fail_stack_type fail_stack;
2912 #ifndef REGEX_MALLOC
2915 /* We don't push any register information onto the failure stack. */
2916 unsigned num_regs = 0;
2918 register char *fastmap = bufp->fastmap;
2919 unsigned char *pattern = bufp->buffer;
2920 const unsigned char *p = pattern;
2921 register unsigned char *pend = pattern + bufp->used;
2923 /* Assume that each path through the pattern can be null until
2924 proven otherwise. We set this false at the bottom of switch
2925 statement, to which we get only if a particular path doesn't
2926 match the empty string. */
2927 boolean path_can_be_null = true;
2929 /* We aren't doing a `succeed_n' to begin with. */
2930 boolean succeed_n_p = false;
2932 assert (fastmap != NULL && p != NULL);
2935 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
2936 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2937 bufp->can_be_null = 0;
2939 while (p != pend || !FAIL_STACK_EMPTY ())
2943 bufp->can_be_null |= path_can_be_null;
2945 /* Reset for next path. */
2946 path_can_be_null = true;
2948 p = fail_stack.stack[--fail_stack.avail];
2951 /* We should never be about to go beyond the end of the pattern. */
2954 #ifdef SWITCH_ENUM_BUG
2955 switch ((int) ((re_opcode_t) *p++))
2957 switch ((re_opcode_t) *p++)
2961 /* I guess the idea here is to simply not bother with a fastmap
2962 if a backreference is used, since it's too hard to figure out
2963 the fastmap for the corresponding group. Setting
2964 `can_be_null' stops `re_search_2' from using the fastmap, so
2965 that is all we do. */
2967 bufp->can_be_null = 1;
2971 /* Following are the cases which match a character. These end
2980 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2981 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2987 /* Chars beyond end of map must be allowed. */
2988 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2991 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2992 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2998 for (j = 0; j < (1 << BYTEWIDTH); j++)
2999 if (SYNTAX (j) == Sword)
3005 for (j = 0; j < (1 << BYTEWIDTH); j++)
3006 if (SYNTAX (j) != Sword)
3012 /* `.' matches anything ... */
3013 for (j = 0; j < (1 << BYTEWIDTH); j++)
3016 /* ... except perhaps newline. */
3017 if (!(bufp->syntax & RE_DOT_NEWLINE))
3020 /* Return if we have already set `can_be_null'; if we have,
3021 then the fastmap is irrelevant. Something's wrong here. */
3022 else if (bufp->can_be_null)
3025 /* Otherwise, have to check alternative paths. */
3032 for (j = 0; j < (1 << BYTEWIDTH); j++)
3033 if (SYNTAX (j) == (enum syntaxcode) k)
3040 for (j = 0; j < (1 << BYTEWIDTH); j++)
3041 if (SYNTAX (j) != (enum syntaxcode) k)
3046 /* All cases after this match the empty string. These end with
3054 #endif /* not emacs */
3066 case push_dummy_failure:
3071 case pop_failure_jump:
3072 case maybe_pop_jump:
3075 case dummy_failure_jump:
3076 EXTRACT_NUMBER_AND_INCR (j, p);
3081 /* Jump backward implies we just went through the body of a
3082 loop and matched nothing. Opcode jumped to should be
3083 `on_failure_jump' or `succeed_n'. Just treat it like an
3084 ordinary jump. For a * loop, it has pushed its failure
3085 point already; if so, discard that as redundant. */
3086 if ((re_opcode_t) *p != on_failure_jump
3087 && (re_opcode_t) *p != succeed_n)
3091 EXTRACT_NUMBER_AND_INCR (j, p);
3094 /* If what's on the stack is where we are now, pop it. */
3095 if (!FAIL_STACK_EMPTY ()
3096 && fail_stack.stack[fail_stack.avail - 1] == p)
3102 case on_failure_jump:
3103 case on_failure_keep_string_jump:
3104 handle_on_failure_jump:
3105 EXTRACT_NUMBER_AND_INCR (j, p);
3107 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3108 end of the pattern. We don't want to push such a point,
3109 since when we restore it above, entering the switch will
3110 increment `p' past the end of the pattern. We don't need
3111 to push such a point since we obviously won't find any more
3112 fastmap entries beyond `pend'. Such a pattern can match
3113 the null string, though. */
3116 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3120 bufp->can_be_null = 1;
3124 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3125 succeed_n_p = false;
3132 /* Get to the number of times to succeed. */
3135 /* Increment p past the n for when k != 0. */
3136 EXTRACT_NUMBER_AND_INCR (k, p);
3140 succeed_n_p = true; /* Spaghetti code alert. */
3141 goto handle_on_failure_jump;
3158 abort (); /* We have listed all the cases. */
3161 /* Getting here means we have found the possible starting
3162 characters for one path of the pattern -- and that the empty
3163 string does not match. We need not follow this path further.
3164 Instead, look at the next alternative (remembered on the
3165 stack), or quit if no more. The test at the top of the loop
3166 does these things. */
3167 path_can_be_null = false;
3171 /* Set `can_be_null' for the last path (also the first path, if the
3172 pattern is empty). */
3173 bufp->can_be_null |= path_can_be_null;
3175 } /* re_compile_fastmap */
3177 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3178 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3179 this memory for recording register information. STARTS and ENDS
3180 must be allocated using the malloc library routine, and must each
3181 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3183 If NUM_REGS == 0, then subsequent matches should allocate their own
3186 Unless this function is called, the first search or match using
3187 PATTERN_BUFFER will allocate its own register data, without
3188 freeing the old data. */
3191 re_set_registers (bufp, regs, num_regs, starts, ends)
3192 struct re_pattern_buffer *bufp;
3193 struct re_registers *regs;
3195 regoff_t *starts, *ends;
3199 bufp->regs_allocated = REGS_REALLOCATE;
3200 regs->num_regs = num_regs;
3201 regs->start = starts;
3206 bufp->regs_allocated = REGS_UNALLOCATED;
3208 regs->start = regs->end = 0;
3212 /* Searching routines. */
3214 /* Like re_search_2, below, but only one string is specified, and
3215 doesn't let you say where to stop matching. */
3218 re_search (bufp, string, size, startpos, range, regs)
3219 struct re_pattern_buffer *bufp;
3221 int size, startpos, range;
3222 struct re_registers *regs;
3224 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3229 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3230 virtual concatenation of STRING1 and STRING2, starting first at index
3231 STARTPOS, then at STARTPOS + 1, and so on.
3233 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3235 RANGE is how far to scan while trying to match. RANGE = 0 means try
3236 only at STARTPOS; in general, the last start tried is STARTPOS +
3239 In REGS, return the indices of the virtual concatenation of STRING1
3240 and STRING2 that matched the entire BUFP->buffer and its contained
3243 Do not consider matching one past the index STOP in the virtual
3244 concatenation of STRING1 and STRING2.
3246 We return either the position in the strings at which the match was
3247 found, -1 if no match, or -2 if error (such as failure
3251 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3252 struct re_pattern_buffer *bufp;
3253 const char *string1, *string2;
3257 struct re_registers *regs;
3261 register char *fastmap = bufp->fastmap;
3262 register char *translate = bufp->translate;
3263 int total_size = size1 + size2;
3264 int endpos = startpos + range;
3266 /* Check for out-of-range STARTPOS. */
3267 if (startpos < 0 || startpos > total_size)
3270 /* Fix up RANGE if it might eventually take us outside
3271 the virtual concatenation of STRING1 and STRING2. */
3273 range = -1 - startpos;
3274 else if (endpos > total_size)
3275 range = total_size - startpos;
3277 /* If the search isn't to be a backwards one, don't waste time in a
3278 search for a pattern that must be anchored. */
3279 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3287 /* Update the fastmap now if not correct already. */
3288 if (fastmap && !bufp->fastmap_accurate)
3289 if (re_compile_fastmap (bufp) == -2)
3292 /* Loop through the string, looking for a place to start matching. */
3295 /* If a fastmap is supplied, skip quickly over characters that
3296 cannot be the start of a match. If the pattern can match the
3297 null string, however, we don't need to skip characters; we want
3298 the first null string. */
3299 if (fastmap && startpos < total_size && !bufp->can_be_null)
3301 if (range > 0) /* Searching forwards. */
3303 register const char *d;
3304 register int lim = 0;
3307 if (startpos < size1 && startpos + range >= size1)
3308 lim = range - (size1 - startpos);
3310 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
3312 /* Written out as an if-else to avoid testing `translate'
3316 && !fastmap[(unsigned char)
3317 translate[(unsigned char) *d++]])
3320 while (range > lim && !fastmap[(unsigned char) *d++])
3323 startpos += irange - range;
3325 else /* Searching backwards. */
3327 register char c = (size1 == 0 || startpos >= size1
3328 ? string2[startpos - size1]
3329 : string1[startpos]);
3331 if (!fastmap[(unsigned char) TRANSLATE (c)])
3336 /* If can't match the null string, and that's all we have left, fail. */
3337 if (range >= 0 && startpos == total_size && fastmap
3338 && !bufp->can_be_null)
3341 val = re_match_2 (bufp, string1, size1, string2, size2,
3342 startpos, regs, stop);
3366 /* Structure for per-register (a.k.a. per-group) information.
3367 This must not be longer than one word, because we push this value
3368 onto the failure stack. Other register information, such as the
3369 starting and ending positions (which are addresses), and the list of
3370 inner groups (which is a bits list) are maintained in separate
3373 We are making a (strictly speaking) nonportable assumption here: that
3374 the compiler will pack our bit fields into something that fits into
3375 the type of `word', i.e., is something that fits into one item on the
3378 /* Declarations and macros for re_match_2. */
3382 fail_stack_elt_t word;
3385 /* This field is one if this group can match the empty string,
3386 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
3387 #define MATCH_NULL_UNSET_VALUE 3
3388 unsigned match_null_string_p : 2;
3389 unsigned is_active : 1;
3390 unsigned matched_something : 1;
3391 unsigned ever_matched_something : 1;
3393 } register_info_type;
3395 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
3396 #define IS_ACTIVE(R) ((R).bits.is_active)
3397 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
3398 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
3400 static boolean group_match_null_string_p _RE_ARGS((unsigned char **p,
3402 register_info_type *reg_info));
3403 static boolean alt_match_null_string_p _RE_ARGS((unsigned char *p,
3405 register_info_type *reg_info));
3406 static boolean common_op_match_null_string_p _RE_ARGS((unsigned char **p,
3408 register_info_type *reg_info));
3409 static int bcmp_translate _RE_ARGS((const char *s1, const char *s2,
3410 int len, char *translate));
3412 /* Call this when have matched a real character; it sets `matched' flags
3413 for the subexpressions which we are currently inside. Also records
3414 that those subexprs have matched. */
3415 #define SET_REGS_MATCHED() \
3419 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
3421 MATCHED_SOMETHING (reg_info[r]) \
3422 = EVER_MATCHED_SOMETHING (reg_info[r]) \
3429 /* This converts PTR, a pointer into one of the search strings `string1'
3430 and `string2' into an offset from the beginning of that string. */
3431 #define POINTER_TO_OFFSET(ptr) \
3432 (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
3434 /* Registers are set to a sentinel when they haven't yet matched. */
3435 static char reg_unset_dummy;
3436 #define REG_UNSET_VALUE (®_unset_dummy)
3437 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
3440 /* Macros for dealing with the split strings in re_match_2. */
3442 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3444 /* Call before fetching a character with *d. This switches over to
3445 string2 if necessary. */
3446 #define PREFETCH() \
3449 /* End of string2 => fail. */ \
3450 if (dend == end_match_2) \
3452 /* End of string1 => advance to string2. */ \
3454 dend = end_match_2; \
3458 /* Test if at very beginning or at very end of the virtual concatenation
3459 of `string1' and `string2'. If only one string, it's `string2'. */
3460 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3461 #define AT_STRINGS_END(d) ((d) == end2)
3464 /* Test if D points to a character which is word-constituent. We have
3465 two special cases to check for: if past the end of string1, look at
3466 the first character in string2; and if before the beginning of
3467 string2, look at the last character in string1. */
3468 #define WORDCHAR_P(d) \
3469 (SYNTAX ((d) == end1 ? *string2 \
3470 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3473 /* Test if the character before D and the one at D differ with respect
3474 to being word-constituent. */
3475 #define AT_WORD_BOUNDARY(d) \
3476 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3477 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3480 /* Free everything we malloc. */
3482 #define FREE_VAR(var) if (var) free (var); var = NULL
3483 #define FREE_VARIABLES() \
3485 FREE_VAR (fail_stack.stack); \
3486 FREE_VAR (regstart); \
3487 FREE_VAR (regend); \
3488 FREE_VAR (old_regstart); \
3489 FREE_VAR (old_regend); \
3490 FREE_VAR (best_regstart); \
3491 FREE_VAR (best_regend); \
3492 FREE_VAR (reg_info); \
3493 FREE_VAR (reg_dummy); \
3494 FREE_VAR (reg_info_dummy); \
3496 #else /* not REGEX_MALLOC */
3497 /* Some MIPS systems (at least) want this to free alloca'd storage. */
3498 #define FREE_VARIABLES() alloca (0)
3499 #endif /* not REGEX_MALLOC */
3502 /* These values must meet several constraints. They must not be valid
3503 register values; since we have a limit of 255 registers (because
3504 we use only one byte in the pattern for the register number), we can
3505 use numbers larger than 255. They must differ by 1, because of
3506 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3507 be larger than the value for the highest register, so we do not try
3508 to actually save any registers when none are active. */
3509 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3510 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3512 /* Matching routines. */
3514 #ifndef emacs /* Emacs never uses this. */
3515 /* re_match is like re_match_2 except it takes only a single string. */
3518 re_match (bufp, string, size, pos, regs)
3519 struct re_pattern_buffer *bufp;
3522 struct re_registers *regs;
3524 return re_match_2 (bufp, NULL, 0, string, size, pos, regs, size);
3526 #endif /* not emacs */
3529 /* re_match_2 matches the compiled pattern in BUFP against the
3530 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3531 and SIZE2, respectively). We start matching at POS, and stop
3534 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3535 store offsets for the substring each group matched in REGS. See the
3536 documentation for exactly how many groups we fill.
3538 We return -1 if no match, -2 if an internal error (such as the
3539 failure stack overflowing). Otherwise, we return the length of the
3540 matched substring. */
3543 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3544 struct re_pattern_buffer *bufp;
3545 const char *string1, *string2;
3548 struct re_registers *regs;
3551 /* General temporaries. */
3555 /* Just past the end of the corresponding string. */
3556 const char *end1, *end2;
3558 /* Pointers into string1 and string2, just past the last characters in
3559 each to consider matching. */
3560 const char *end_match_1, *end_match_2;
3562 /* Where we are in the data, and the end of the current string. */
3563 const char *d, *dend;
3565 /* Where we are in the pattern, and the end of the pattern. */
3566 unsigned char *p = bufp->buffer;
3567 register unsigned char *pend = p + bufp->used;
3569 /* We use this to map every character in the string. */
3570 char *translate = bufp->translate;
3572 /* Failure point stack. Each place that can handle a failure further
3573 down the line pushes a failure point on this stack. It consists of
3574 restart, regend, and reg_info for all registers corresponding to
3575 the subexpressions we're currently inside, plus the number of such
3576 registers, and, finally, two char *'s. The first char * is where
3577 to resume scanning the pattern; the second one is where to resume
3578 scanning the strings. If the latter is zero, the failure point is
3579 a ``dummy''; if a failure happens and the failure point is a dummy,
3580 it gets discarded and the next next one is tried. */
3581 fail_stack_type fail_stack;
3583 static unsigned failure_id = 0;
3584 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3587 /* We fill all the registers internally, independent of what we
3588 return, for use in backreferences. The number here includes
3589 an element for register zero. */
3590 size_t num_regs = bufp->re_nsub + 1;
3592 /* The currently active registers. */
3593 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3594 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3596 /* Information on the contents of registers. These are pointers into
3597 the input strings; they record just what was matched (on this
3598 attempt) by a subexpression part of the pattern, that is, the
3599 regnum-th regstart pointer points to where in the pattern we began
3600 matching and the regnum-th regend points to right after where we
3601 stopped matching the regnum-th subexpression. (The zeroth register
3602 keeps track of what the whole pattern matches.) */
3603 const char **regstart = 0, **regend = 0;
3605 /* If a group that's operated upon by a repetition operator fails to
3606 match anything, then the register for its start will need to be
3607 restored because it will have been set to wherever in the string we
3608 are when we last see its open-group operator. Similarly for a
3610 const char **old_regstart = 0, **old_regend = 0;
3612 /* The is_active field of reg_info helps us keep track of which (possibly
3613 nested) subexpressions we are currently in. The matched_something
3614 field of reg_info[reg_num] helps us tell whether or not we have
3615 matched any of the pattern so far this time through the reg_num-th
3616 subexpression. These two fields get reset each time through any
3617 loop their register is in. */
3618 register_info_type *reg_info = 0;
3620 /* The following record the register info as found in the above
3621 variables when we find a match better than any we've seen before.
3622 This happens as we backtrack through the failure points, which in
3623 turn happens only if we have not yet matched the entire string. */
3624 unsigned best_regs_set = false;
3625 const char **best_regstart = 0, **best_regend = 0;
3627 /* Logically, this is `best_regend[0]'. But we don't want to have to
3628 allocate space for that if we're not allocating space for anything
3629 else (see below). Also, we never need info about register 0 for
3630 any of the other register vectors, and it seems rather a kludge to
3631 treat `best_regend' differently than the rest. So we keep track of
3632 the end of the best match so far in a separate variable. We
3633 initialize this to NULL so that when we backtrack the first time
3634 and need to test it, it's not garbage. */
3635 const char *match_end = NULL;
3637 /* Used when we pop values we don't care about. */
3638 const char **reg_dummy = 0;
3639 register_info_type *reg_info_dummy = 0;
3642 /* Counts the total number of registers pushed. */
3643 unsigned num_regs_pushed = 0;
3646 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3650 /* Do not bother to initialize all the register variables if there are
3651 no groups in the pattern, as it takes a fair amount of time. If
3652 there are groups, we include space for register 0 (the whole
3653 pattern), even though we never use it, since it simplifies the
3654 array indexing. We should fix this. */
3657 regstart = REGEX_TALLOC (num_regs, const char *);
3658 regend = REGEX_TALLOC (num_regs, const char *);
3659 old_regstart = REGEX_TALLOC (num_regs, const char *);
3660 old_regend = REGEX_TALLOC (num_regs, const char *);
3661 best_regstart = REGEX_TALLOC (num_regs, const char *);
3662 best_regend = REGEX_TALLOC (num_regs, const char *);
3663 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3664 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3665 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3667 if (!(regstart && regend && old_regstart && old_regend && reg_info
3668 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3677 /* We must initialize all our variables to NULL, so that
3678 `FREE_VARIABLES' doesn't try to free them. */
3679 regstart = regend = old_regstart = old_regend = best_regstart
3680 = best_regend = reg_dummy = NULL;
3681 reg_info = reg_info_dummy = (register_info_type *) NULL;
3683 #endif /* REGEX_MALLOC */
3685 /* The starting position is bogus. */
3686 if (pos < 0 || pos > size1 + size2)
3692 /* Initialize subexpression text positions to -1 to mark ones that no
3693 start_memory/stop_memory has been seen for. Also initialize the
3694 register information struct. */
3695 for (mcnt = 1; mcnt < num_regs; mcnt++)
3697 regstart[mcnt] = regend[mcnt]
3698 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3700 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3701 IS_ACTIVE (reg_info[mcnt]) = 0;
3702 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3703 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3706 /* We move `string1' into `string2' if the latter's empty -- but not if
3707 `string1' is null. */
3708 if (size2 == 0 && string1 != NULL)
3715 end1 = string1 + size1;
3716 end2 = string2 + size2;
3718 /* Compute where to stop matching, within the two strings. */
3721 end_match_1 = string1 + stop;
3722 end_match_2 = string2;
3727 end_match_2 = string2 + stop - size1;
3730 /* `p' scans through the pattern as `d' scans through the data.
3731 `dend' is the end of the input string that `d' points within. `d'
3732 is advanced into the following input string whenever necessary, but
3733 this happens before fetching; therefore, at the beginning of the
3734 loop, `d' can be pointing at the end of a string, but it cannot
3736 if (size1 > 0 && pos <= size1)
3743 d = string2 + pos - size1;
3747 DEBUG_PRINT1 ("The compiled pattern is: ");
3748 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3749 DEBUG_PRINT1 ("The string to match is: `");
3750 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3751 DEBUG_PRINT1 ("'\n");
3753 /* This loops over pattern commands. It exits by returning from the
3754 function if the match is complete, or it drops through if the match
3755 fails at this starting point in the input data. */
3758 DEBUG_PRINT2 ("\n0x%x: ", p);
3761 { /* End of pattern means we might have succeeded. */
3762 DEBUG_PRINT1 ("end of pattern ... ");
3764 /* If we haven't matched the entire string, and we want the
3765 longest match, try backtracking. */
3766 if (d != end_match_2)
3768 DEBUG_PRINT1 ("backtracking.\n");
3770 if (!FAIL_STACK_EMPTY ())
3771 { /* More failure points to try. */
3772 boolean same_str_p = (FIRST_STRING_P (match_end)
3773 == MATCHING_IN_FIRST_STRING);
3775 /* If exceeds best match so far, save it. */
3777 || (same_str_p && d > match_end)
3778 || (!same_str_p && !MATCHING_IN_FIRST_STRING))
3780 best_regs_set = true;
3783 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3785 for (mcnt = 1; mcnt < num_regs; mcnt++)
3787 best_regstart[mcnt] = regstart[mcnt];
3788 best_regend[mcnt] = regend[mcnt];
3794 /* If no failure points, don't restore garbage. */
3795 else if (best_regs_set)
3798 /* Restore best match. It may happen that `dend ==
3799 end_match_1' while the restored d is in string2.
3800 For example, the pattern `x.*y.*z' against the
3801 strings `x-' and `y-z-', if the two strings are
3802 not consecutive in memory. */
3803 DEBUG_PRINT1 ("Restoring best registers.\n");
3806 dend = ((d >= string1 && d <= end1)
3807 ? end_match_1 : end_match_2);
3809 for (mcnt = 1; mcnt < num_regs; mcnt++)
3811 regstart[mcnt] = best_regstart[mcnt];
3812 regend[mcnt] = best_regend[mcnt];
3815 } /* d != end_match_2 */
3817 DEBUG_PRINT1 ("Accepting match.\n");
3819 /* If caller wants register contents data back, do it. */
3820 if (regs && !bufp->no_sub)
3822 /* Have the register data arrays been allocated? */
3823 if (bufp->regs_allocated == REGS_UNALLOCATED)
3824 { /* No. So allocate them with malloc. We need one
3825 extra element beyond `num_regs' for the `-1' marker
3827 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3828 regs->start = TALLOC (regs->num_regs, regoff_t);
3829 regs->end = TALLOC (regs->num_regs, regoff_t);
3830 if (regs->start == NULL || regs->end == NULL)
3832 bufp->regs_allocated = REGS_REALLOCATE;
3834 else if (bufp->regs_allocated == REGS_REALLOCATE)
3835 { /* Yes. If we need more elements than were already
3836 allocated, reallocate them. If we need fewer, just
3838 if (regs->num_regs < num_regs + 1)
3840 regs->num_regs = num_regs + 1;
3841 RETALLOC (regs->start, regs->num_regs, regoff_t);
3842 RETALLOC (regs->end, regs->num_regs, regoff_t);
3843 if (regs->start == NULL || regs->end == NULL)
3849 /* These braces fend off a "empty body in an else-statement"
3850 warning under GCC when assert expands to nothing. */
3851 assert (bufp->regs_allocated == REGS_FIXED);
3854 /* Convert the pointer data in `regstart' and `regend' to
3855 indices. Register zero has to be set differently,
3856 since we haven't kept track of any info for it. */
3857 if (regs->num_regs > 0)
3859 regs->start[0] = pos;
3860 regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
3861 : d - string2 + size1);
3864 /* Go through the first `min (num_regs, regs->num_regs)'
3865 registers, since that is all we initialized. */
3866 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
3868 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3869 regs->start[mcnt] = regs->end[mcnt] = -1;
3872 regs->start[mcnt] = POINTER_TO_OFFSET (regstart[mcnt]);
3873 regs->end[mcnt] = POINTER_TO_OFFSET (regend[mcnt]);
3877 /* If the regs structure we return has more elements than
3878 were in the pattern, set the extra elements to -1. If
3879 we (re)allocated the registers, this is the case,
3880 because we always allocate enough to have at least one
3882 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3883 regs->start[mcnt] = regs->end[mcnt] = -1;
3884 } /* regs && !bufp->no_sub */
3887 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3888 nfailure_points_pushed, nfailure_points_popped,
3889 nfailure_points_pushed - nfailure_points_popped);
3890 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3892 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3896 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3901 /* Otherwise match next pattern command. */
3902 #ifdef SWITCH_ENUM_BUG
3903 switch ((int) ((re_opcode_t) *p++))
3905 switch ((re_opcode_t) *p++)
3908 /* Ignore these. Used to ignore the n of succeed_n's which
3909 currently have n == 0. */
3911 DEBUG_PRINT1 ("EXECUTING no_op.\n");
3915 /* Match the next n pattern characters exactly. The following
3916 byte in the pattern defines n, and the n bytes after that
3917 are the characters to match. */
3920 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3922 /* This is written out as an if-else so we don't waste time
3923 testing `translate' inside the loop. */
3929 if (translate[(unsigned char) *d++] != (char) *p++)
3939 if (*d++ != (char) *p++) goto fail;
3943 SET_REGS_MATCHED ();
3947 /* Match any character except possibly a newline or a null. */
3949 DEBUG_PRINT1 ("EXECUTING anychar.\n");
3953 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
3954 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
3957 SET_REGS_MATCHED ();
3958 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
3966 register unsigned char c;
3967 boolean not = (re_opcode_t) *(p - 1) == charset_not;
3969 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
3972 c = TRANSLATE (*d); /* The character to match. */
3974 /* Cast to `unsigned' instead of `unsigned char' in case the
3975 bit list is a full 32 bytes long. */
3976 if (c < (unsigned) (*p * BYTEWIDTH)
3977 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3982 if (!not) goto fail;
3984 SET_REGS_MATCHED ();
3990 /* The beginning of a group is represented by start_memory.
3991 The arguments are the register number in the next byte, and the
3992 number of groups inner to this one in the next. The text
3993 matched within the group is recorded (in the internal
3994 registers data structure) under the register number. */
3996 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3998 /* Find out if this group can match the empty string. */
3999 p1 = p; /* To send to group_match_null_string_p. */
4001 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4002 REG_MATCH_NULL_STRING_P (reg_info[*p])
4003 = group_match_null_string_p (&p1, pend, reg_info);
4005 /* Save the position in the string where we were the last time
4006 we were at this open-group operator in case the group is
4007 operated upon by a repetition operator, e.g., with `(a*)*b'
4008 against `ab'; then we want to ignore where we are now in
4009 the string in case this attempt to match fails. */
4010 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4011 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4013 DEBUG_PRINT2 (" old_regstart: %d\n",
4014 POINTER_TO_OFFSET (old_regstart[*p]));
4017 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4019 IS_ACTIVE (reg_info[*p]) = 1;
4020 MATCHED_SOMETHING (reg_info[*p]) = 0;
4022 /* This is the new highest active register. */
4023 highest_active_reg = *p;
4025 /* If nothing was active before, this is the new lowest active
4027 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4028 lowest_active_reg = *p;
4030 /* Move past the register number and inner group count. */
4035 /* The stop_memory opcode represents the end of a group. Its
4036 arguments are the same as start_memory's: the register
4037 number, and the number of inner groups. */
4039 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4041 /* We need to save the string position the last time we were at
4042 this close-group operator in case the group is operated
4043 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4044 against `aba'; then we want to ignore where we are now in
4045 the string in case this attempt to match fails. */
4046 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4047 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4049 DEBUG_PRINT2 (" old_regend: %d\n",
4050 POINTER_TO_OFFSET (old_regend[*p]));
4053 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4055 /* This register isn't active anymore. */
4056 IS_ACTIVE (reg_info[*p]) = 0;
4058 /* If this was the only register active, nothing is active
4060 if (lowest_active_reg == highest_active_reg)
4062 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4063 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4066 { /* We must scan for the new highest active register, since
4067 it isn't necessarily one less than now: consider
4068 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4069 new highest active register is 1. */
4070 unsigned char r = *p - 1;
4071 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4074 /* If we end up at register zero, that means that we saved
4075 the registers as the result of an `on_failure_jump', not
4076 a `start_memory', and we jumped to past the innermost
4077 `stop_memory'. For example, in ((.)*) we save
4078 registers 1 and 2 as a result of the *, but when we pop
4079 back to the second ), we are at the stop_memory 1.
4080 Thus, nothing is active. */
4083 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4084 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4087 highest_active_reg = r;
4090 /* If just failed to match something this time around with a
4091 group that's operated on by a repetition operator, try to
4092 force exit from the ``loop'', and restore the register
4093 information for this group that we had before trying this
4095 if ((!MATCHED_SOMETHING (reg_info[*p])
4096 || (re_opcode_t) p[-3] == start_memory)
4099 boolean is_a_jump_n = false;
4103 switch ((re_opcode_t) *p1++)
4107 case pop_failure_jump:
4108 case maybe_pop_jump:
4110 case dummy_failure_jump:
4111 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4121 /* If the next operation is a jump backwards in the pattern
4122 to an on_failure_jump right before the start_memory
4123 corresponding to this stop_memory, exit from the loop
4124 by forcing a failure after pushing on the stack the
4125 on_failure_jump's jump in the pattern, and d. */
4126 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4127 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4129 /* If this group ever matched anything, then restore
4130 what its registers were before trying this last
4131 failed match, e.g., with `(a*)*b' against `ab' for
4132 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4133 against `aba' for regend[3].
4135 Also restore the registers for inner groups for,
4136 e.g., `((a*)(b*))*' against `aba' (register 3 would
4137 otherwise get trashed). */
4139 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4143 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4145 /* Restore this and inner groups' (if any) registers. */
4146 for (r = *p; r < *p + *(p + 1); r++)
4148 regstart[r] = old_regstart[r];
4150 /* xx why this test? */
4151 if ((s_reg_t) old_regend[r] >= (s_reg_t) regstart[r])
4152 regend[r] = old_regend[r];
4156 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4157 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4158 PUSH_FAILURE_POINT2(p1 + mcnt, d, -2);
4164 /* Move past the register number and the inner group count. */
4169 /* \<digit> has been turned into a `duplicate' command which is
4170 followed by the numeric value of <digit> as the register number. */
4173 register const char *d2, *dend2;
4174 int regno = *p++; /* Get which register to match against. */
4175 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4177 /* Can't back reference a group which we've never matched. */
4178 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4181 /* Where in input to try to start matching. */
4182 d2 = regstart[regno];
4184 /* Where to stop matching; if both the place to start and
4185 the place to stop matching are in the same string, then
4186 set to the place to stop, otherwise, for now have to use
4187 the end of the first string. */
4189 dend2 = ((FIRST_STRING_P (regstart[regno])
4190 == FIRST_STRING_P (regend[regno]))
4191 ? regend[regno] : end_match_1);
4194 /* If necessary, advance to next segment in register
4198 if (dend2 == end_match_2) break;
4199 if (dend2 == regend[regno]) break;
4201 /* End of string1 => advance to string2. */
4203 dend2 = regend[regno];
4205 /* At end of register contents => success */
4206 if (d2 == dend2) break;
4208 /* If necessary, advance to next segment in data. */
4211 /* How many characters left in this segment to match. */
4214 /* Want how many consecutive characters we can match in
4215 one shot, so, if necessary, adjust the count. */
4216 if (mcnt > dend2 - d2)
4219 /* Compare that many; failure if mismatch, else move
4222 ? bcmp_translate (d, d2, mcnt, translate)
4223 : bcmp (d, d2, mcnt))
4225 d += mcnt, d2 += mcnt;
4231 /* begline matches the empty string at the beginning of the string
4232 (unless `not_bol' is set in `bufp'), and, if
4233 `newline_anchor' is set, after newlines. */
4235 DEBUG_PRINT1 ("EXECUTING begline.\n");
4237 if (AT_STRINGS_BEG (d))
4239 if (!bufp->not_bol) break;
4241 else if (d[-1] == '\n' && bufp->newline_anchor)
4245 /* In all other cases, we fail. */
4249 /* endline is the dual of begline. */
4251 DEBUG_PRINT1 ("EXECUTING endline.\n");
4253 if (AT_STRINGS_END (d))
4255 if (!bufp->not_eol) break;
4258 /* We have to ``prefetch'' the next character. */
4259 else if ((d == end1 ? *string2 : *d) == '\n'
4260 && bufp->newline_anchor)
4267 /* Match at the very beginning of the data. */
4269 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4270 if (AT_STRINGS_BEG (d))
4275 /* Match at the very end of the data. */
4277 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4278 if (AT_STRINGS_END (d))
4283 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4284 pushes NULL as the value for the string on the stack. Then
4285 `pop_failure_point' will keep the current value for the
4286 string, instead of restoring it. To see why, consider
4287 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4288 then the . fails against the \n. But the next thing we want
4289 to do is match the \n against the \n; if we restored the
4290 string value, we would be back at the foo.
4292 Because this is used only in specific cases, we don't need to
4293 check all the things that `on_failure_jump' does, to make
4294 sure the right things get saved on the stack. Hence we don't
4295 share its code. The only reason to push anything on the
4296 stack at all is that otherwise we would have to change
4297 `anychar's code to do something besides goto fail in this
4298 case; that seems worse than this. */
4299 case on_failure_keep_string_jump:
4300 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4302 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4303 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4305 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4306 PUSH_FAILURE_POINT2(p + mcnt, NULL, -2);
4310 /* Uses of on_failure_jump:
4312 Each alternative starts with an on_failure_jump that points
4313 to the beginning of the next alternative. Each alternative
4314 except the last ends with a jump that in effect jumps past
4315 the rest of the alternatives. (They really jump to the
4316 ending jump of the following alternative, because tensioning
4317 these jumps is a hassle.)
4319 Repeats start with an on_failure_jump that points past both
4320 the repetition text and either the following jump or
4321 pop_failure_jump back to this on_failure_jump. */
4322 case on_failure_jump:
4324 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4326 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4327 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4329 /* If this on_failure_jump comes right before a group (i.e.,
4330 the original * applied to a group), save the information
4331 for that group and all inner ones, so that if we fail back
4332 to this point, the group's information will be correct.
4333 For example, in \(a*\)*\1, we need the preceding group,
4334 and in \(\(a*\)b*\)\2, we need the inner group. */
4336 /* We can't use `p' to check ahead because we push
4337 a failure point to `p + mcnt' after we do this. */
4340 /* We need to skip no_op's before we look for the
4341 start_memory in case this on_failure_jump is happening as
4342 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4344 while (p1 < pend && (re_opcode_t) *p1 == no_op)
4347 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
4349 /* We have a new highest active register now. This will
4350 get reset at the start_memory we are about to get to,
4351 but we will have saved all the registers relevant to
4352 this repetition op, as described above. */
4353 highest_active_reg = *(p1 + 1) + *(p1 + 2);
4354 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4355 lowest_active_reg = *(p1 + 1);
4358 DEBUG_PRINT1 (":\n");
4359 PUSH_FAILURE_POINT (p + mcnt, d, -2);
4360 PUSH_FAILURE_POINT2(p + mcnt, d, -2);
4364 /* A smart repeat ends with `maybe_pop_jump'.
4365 We change it to either `pop_failure_jump' or `jump'. */
4366 case maybe_pop_jump:
4367 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4368 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
4370 register unsigned char *p2 = p;
4372 /* Compare the beginning of the repeat with what in the
4373 pattern follows its end. If we can establish that there
4374 is nothing that they would both match, i.e., that we
4375 would have to backtrack because of (as in, e.g., `a*a')
4376 then we can change to pop_failure_jump, because we'll
4377 never have to backtrack.
4379 This is not true in the case of alternatives: in
4380 `(a|ab)*' we do need to backtrack to the `ab' alternative
4381 (e.g., if the string was `ab'). But instead of trying to
4382 detect that here, the alternative has put on a dummy
4383 failure point which is what we will end up popping. */
4385 /* Skip over open/close-group commands. */
4386 while (p2 + 2 < pend
4387 && ((re_opcode_t) *p2 == stop_memory
4388 || (re_opcode_t) *p2 == start_memory))
4389 p2 += 3; /* Skip over args, too. */
4391 /* If we're at the end of the pattern, we can change. */
4394 /* Consider what happens when matching ":\(.*\)"
4395 against ":/". I don't really understand this code
4397 p[-3] = (unsigned char) pop_failure_jump;
4399 (" End of pattern: change to `pop_failure_jump'.\n");
4402 else if ((re_opcode_t) *p2 == exactn
4403 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4405 register unsigned char c
4406 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4409 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4410 to the `maybe_finalize_jump' of this case. Examine what
4412 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4414 p[-3] = (unsigned char) pop_failure_jump;
4415 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4419 else if ((re_opcode_t) p1[3] == charset
4420 || (re_opcode_t) p1[3] == charset_not)
4422 int not = (re_opcode_t) p1[3] == charset_not;
4424 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4425 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4428 /* `not' is equal to 1 if c would match, which means
4429 that we can't change to pop_failure_jump. */
4432 p[-3] = (unsigned char) pop_failure_jump;
4433 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4438 p -= 2; /* Point at relative address again. */
4439 if ((re_opcode_t) p[-1] != pop_failure_jump)
4441 p[-1] = (unsigned char) jump;
4442 DEBUG_PRINT1 (" Match => jump.\n");
4443 goto unconditional_jump;
4445 /* Note fall through. */
4448 /* The end of a simple repeat has a pop_failure_jump back to
4449 its matching on_failure_jump, where the latter will push a
4450 failure point. The pop_failure_jump takes off failure
4451 points put on by this pop_failure_jump's matching
4452 on_failure_jump; we got through the pattern to here from the
4453 matching on_failure_jump, so didn't fail. */
4454 case pop_failure_jump:
4456 /* We need to pass separate storage for the lowest and
4457 highest registers, even though we don't care about the
4458 actual values. Otherwise, we will restore only one
4459 register from the stack, since lowest will == highest in
4460 `pop_failure_point'. */
4461 active_reg_t dummy_low_reg, dummy_high_reg;
4462 unsigned char *pdummy;
4465 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4466 POP_FAILURE_POINT (sdummy, pdummy,
4467 dummy_low_reg, dummy_high_reg,
4468 reg_dummy, reg_dummy, reg_info_dummy);
4470 /* Note fall through. */
4473 /* Unconditionally jump (without popping any failure points). */
4476 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4477 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4478 p += mcnt; /* Do the jump. */
4479 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4483 /* We need this opcode so we can detect where alternatives end
4484 in `group_match_null_string_p' et al. */
4486 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4487 goto unconditional_jump;
4490 /* Normally, the on_failure_jump pushes a failure point, which
4491 then gets popped at pop_failure_jump. We will end up at
4492 pop_failure_jump, also, and with a pattern of, say, `a+', we
4493 are skipping over the on_failure_jump, so we have to push
4494 something meaningless for pop_failure_jump to pop. */
4495 case dummy_failure_jump:
4496 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4497 /* It doesn't matter what we push for the string here. What
4498 the code at `fail' tests is the value for the pattern. */
4499 PUSH_FAILURE_POINT (0, 0, -2);
4500 PUSH_FAILURE_POINT2(0, 0, -2);
4501 goto unconditional_jump;
4504 /* At the end of an alternative, we need to push a dummy failure
4505 point in case we are followed by a `pop_failure_jump', because
4506 we don't want the failure point for the alternative to be
4507 popped. For example, matching `(a|ab)*' against `aab'
4508 requires that we match the `ab' alternative. */
4509 case push_dummy_failure:
4510 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4511 /* See comments just above at `dummy_failure_jump' about the
4513 PUSH_FAILURE_POINT (0, 0, -2);
4514 PUSH_FAILURE_POINT2(0, 0, -2);
4517 /* Have to succeed matching what follows at least n times.
4518 After that, handle like `on_failure_jump'. */
4520 EXTRACT_NUMBER (mcnt, p + 2);
4521 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4524 /* Originally, this is how many times we HAVE to succeed. */
4529 STORE_NUMBER_AND_INCR (p, mcnt);
4530 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
4534 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4535 p[2] = (unsigned char) no_op;
4536 p[3] = (unsigned char) no_op;
4542 EXTRACT_NUMBER (mcnt, p + 2);
4543 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4545 /* Originally, this is how many times we CAN jump. */
4549 STORE_NUMBER (p + 2, mcnt);
4550 goto unconditional_jump;
4552 /* If don't have to jump any more, skip over the rest of command. */
4559 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4561 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4563 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4564 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4565 STORE_NUMBER (p1, mcnt);
4570 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4571 if (AT_WORD_BOUNDARY (d))
4576 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4577 if (AT_WORD_BOUNDARY (d))
4582 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4583 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4588 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4589 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4590 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4597 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4598 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4603 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4604 if (PTR_CHAR_POS ((unsigned char *) d) != point)
4609 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4610 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
4613 #else /* not emacs19 */
4615 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4616 if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
4619 #endif /* not emacs19 */
4622 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4627 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4631 if (SYNTAX (*d++) != (enum syntaxcode) mcnt)
4633 SET_REGS_MATCHED ();
4637 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4639 goto matchnotsyntax;
4642 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4646 if (SYNTAX (*d++) == (enum syntaxcode) mcnt)
4648 SET_REGS_MATCHED ();
4651 #else /* not emacs */
4653 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4655 if (!WORDCHAR_P (d))
4657 SET_REGS_MATCHED ();
4662 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4666 SET_REGS_MATCHED ();
4669 #endif /* not emacs */
4674 continue; /* Successfully executed one pattern command; keep going. */
4677 /* We goto here if a matching operation fails. */
4679 if (!FAIL_STACK_EMPTY ())
4680 { /* A restart point is known. Restore to that state. */
4681 DEBUG_PRINT1 ("\nFAIL:\n");
4682 POP_FAILURE_POINT (d, p,
4683 lowest_active_reg, highest_active_reg,
4684 regstart, regend, reg_info);
4686 /* If this failure point is a dummy, try the next one. */
4690 /* If we failed to the end of the pattern, don't examine *p. */
4694 boolean is_a_jump_n = false;
4696 /* If failed to a backwards jump that's part of a repetition
4697 loop, need to pop this failure point and use the next one. */
4698 switch ((re_opcode_t) *p)
4702 case maybe_pop_jump:
4703 case pop_failure_jump:
4706 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4709 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4711 && (re_opcode_t) *p1 == on_failure_jump))
4719 if (d >= string1 && d <= end1)
4723 break; /* Matching at this starting point really fails. */
4727 goto restore_best_regs;
4731 return -1; /* Failure to match. */
4734 /* Subroutine definitions for re_match_2. */
4737 /* We are passed P pointing to a register number after a start_memory.
4739 Return true if the pattern up to the corresponding stop_memory can
4740 match the empty string, and false otherwise.
4742 If we find the matching stop_memory, sets P to point to one past its number.
4743 Otherwise, sets P to an undefined byte less than or equal to END.
4745 We don't handle duplicates properly (yet). */
4748 group_match_null_string_p (p, end, reg_info)
4749 unsigned char **p, *end;
4750 register_info_type *reg_info;
4753 /* Point to after the args to the start_memory. */
4754 unsigned char *p1 = *p + 2;
4758 /* Skip over opcodes that can match nothing, and return true or
4759 false, as appropriate, when we get to one that can't, or to the
4760 matching stop_memory. */
4762 switch ((re_opcode_t) *p1)
4764 /* Could be either a loop or a series of alternatives. */
4765 case on_failure_jump:
4767 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4769 /* If the next operation is not a jump backwards in the
4774 /* Go through the on_failure_jumps of the alternatives,
4775 seeing if any of the alternatives cannot match nothing.
4776 The last alternative starts with only a jump,
4777 whereas the rest start with on_failure_jump and end
4778 with a jump, e.g., here is the pattern for `a|b|c':
4780 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4781 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4784 So, we have to first go through the first (n-1)
4785 alternatives and then deal with the last one separately. */
4788 /* Deal with the first (n-1) alternatives, which start
4789 with an on_failure_jump (see above) that jumps to right
4790 past a jump_past_alt. */
4792 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4794 /* `mcnt' holds how many bytes long the alternative
4795 is, including the ending `jump_past_alt' and
4798 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
4802 /* Move to right after this alternative, including the
4806 /* Break if it's the beginning of an n-th alternative
4807 that doesn't begin with an on_failure_jump. */
4808 if ((re_opcode_t) *p1 != on_failure_jump)
4811 /* Still have to check that it's not an n-th
4812 alternative that starts with an on_failure_jump. */
4814 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4815 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4817 /* Get to the beginning of the n-th alternative. */
4823 /* Deal with the last alternative: go back and get number
4824 of the `jump_past_alt' just before it. `mcnt' contains
4825 the length of the alternative. */
4826 EXTRACT_NUMBER (mcnt, p1 - 2);
4828 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
4831 p1 += mcnt; /* Get past the n-th alternative. */
4837 assert (p1[1] == **p);
4843 if (!common_op_match_null_string_p (&p1, end, reg_info))
4846 } /* while p1 < end */
4849 } /* group_match_null_string_p */
4852 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4853 It expects P to be the first byte of a single alternative and END one
4854 byte past the last. The alternative can contain groups. */
4857 alt_match_null_string_p (p, end, reg_info)
4858 unsigned char *p, *end;
4859 register_info_type *reg_info;
4862 unsigned char *p1 = p;
4866 /* Skip over opcodes that can match nothing, and break when we get
4867 to one that can't. */
4869 switch ((re_opcode_t) *p1)
4872 case on_failure_jump:
4874 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4879 if (!common_op_match_null_string_p (&p1, end, reg_info))
4882 } /* while p1 < end */
4885 } /* alt_match_null_string_p */
4888 /* Deals with the ops common to group_match_null_string_p and
4889 alt_match_null_string_p.
4891 Sets P to one after the op and its arguments, if any. */
4894 common_op_match_null_string_p (p, end, reg_info)
4895 unsigned char **p, *end;
4896 register_info_type *reg_info;
4901 unsigned char *p1 = *p;
4903 switch ((re_opcode_t) *p1++)
4923 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
4924 ret = group_match_null_string_p (&p1, end, reg_info);
4926 /* Have to set this here in case we're checking a group which
4927 contains a group and a back reference to it. */
4929 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4930 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
4936 /* If this is an optimized succeed_n for zero times, make the jump. */
4938 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4946 /* Get to the number of times to succeed. */
4948 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4953 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4961 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
4969 /* All other opcodes mean we cannot match the empty string. */
4975 } /* common_op_match_null_string_p */
4978 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4979 bytes; nonzero otherwise. */
4982 bcmp_translate (s1, s2, len, translate)
4983 const char *s1, *s2;
4987 register const unsigned char *p1 = (const unsigned char *) s1,
4988 *p2 = (const unsigned char *) s2;
4991 if (translate[*p1++] != translate[*p2++]) return 1;
4997 /* Entry points for GNU code. */
4999 /* re_compile_pattern is the GNU regular expression compiler: it
5000 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5001 Returns 0 if the pattern was valid, otherwise an error string.
5003 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5004 are set in BUFP on entry.
5006 We call regex_compile to do the actual compilation. */
5009 re_compile_pattern (pattern, length, bufp)
5010 const char *pattern;
5012 struct re_pattern_buffer *bufp;
5016 /* GNU code is written to assume at least RE_NREGS registers will be set
5017 (and at least one extra will be -1). */
5018 bufp->regs_allocated = REGS_UNALLOCATED;
5020 /* And GNU code determines whether or not to get register information
5021 by passing null for the REGS argument to re_match, etc., not by
5025 /* Match anchors at newline. */
5026 bufp->newline_anchor = 1;
5028 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5030 return re_error_msg[(int) ret];
5033 /* Entry points compatible with 4.2 BSD regex library. We don't define
5034 them if this is an Emacs or POSIX compilation. */
5036 #if !defined (emacs) && !defined (_POSIX_SOURCE)
5038 /* BSD has one and only one pattern buffer. */
5039 static struct re_pattern_buffer re_comp_buf;
5049 if (!re_comp_buf.buffer)
5050 return "No previous regular expression";
5054 if (!re_comp_buf.buffer)
5056 re_comp_buf.buffer = (unsigned char *) malloc (200);
5057 if (re_comp_buf.buffer == NULL)
5058 return "Memory exhausted";
5059 re_comp_buf.allocated = 200;
5061 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5062 if (re_comp_buf.fastmap == NULL)
5063 return "Memory exhausted";
5066 /* Since `re_exec' always passes NULL for the `regs' argument, we
5067 don't need to initialize the pattern buffer fields which affect it. */
5069 /* Match anchors at newlines. */
5070 re_comp_buf.newline_anchor = 1;
5072 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5074 /* Yes, we're discarding `const' here. */
5075 return (char *) re_error_msg[(int) ret];
5083 const int len = strlen (s);
5085 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5087 #endif /* not emacs and not _POSIX_SOURCE */
5089 /* POSIX.2 functions. Don't define these for Emacs. */
5093 /* regcomp takes a regular expression as a string and compiles it.
5095 PREG is a regex_t *. We do not expect any fields to be initialized,
5096 since POSIX says we shouldn't. Thus, we set
5098 `buffer' to the compiled pattern;
5099 `used' to the length of the compiled pattern;
5100 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5101 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5102 RE_SYNTAX_POSIX_BASIC;
5103 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5104 `fastmap' and `fastmap_accurate' to zero;
5105 `re_nsub' to the number of subexpressions in PATTERN.
5107 PATTERN is the address of the pattern string.
5109 CFLAGS is a series of bits which affect compilation.
5111 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5112 use POSIX basic syntax.
5114 If REG_NEWLINE is set, then . and [^...] don't match newline.
5115 Also, regexec will try a match beginning after every newline.
5117 If REG_ICASE is set, then we considers upper- and lowercase
5118 versions of letters to be equivalent when matching.
5120 If REG_NOSUB is set, then when PREG is passed to regexec, that
5121 routine will report only success or failure, and nothing about the
5124 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5125 the return codes and their meanings.) */
5128 regcomp (preg, pattern, cflags)
5130 const char *pattern;
5135 = (cflags & REG_EXTENDED) ?
5136 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5138 /* regex_compile will allocate the space for the compiled pattern. */
5140 preg->allocated = 0;
5143 /* Don't bother to use a fastmap when searching. This simplifies the
5144 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5145 characters after newlines into the fastmap. This way, we just try
5149 if (cflags & REG_ICASE)
5153 preg->translate = (char *) malloc (CHAR_SET_SIZE);
5154 if (preg->translate == NULL)
5155 return (int) REG_ESPACE;
5157 /* Map uppercase characters to corresponding lowercase ones. */
5158 for (i = 0; i < CHAR_SET_SIZE; i++)
5159 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5162 preg->translate = NULL;
5164 /* If REG_NEWLINE is set, newlines are treated differently. */
5165 if (cflags & REG_NEWLINE)
5166 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5167 syntax &= ~RE_DOT_NEWLINE;
5168 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5169 /* It also changes the matching behavior. */
5170 preg->newline_anchor = 1;
5173 preg->newline_anchor = 0;
5175 preg->no_sub = !!(cflags & REG_NOSUB);
5177 /* POSIX says a null character in the pattern terminates it, so we
5178 can use strlen here in compiling the pattern. */
5179 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5181 /* POSIX doesn't distinguish between an unmatched open-group and an
5182 unmatched close-group: both are REG_EPAREN. */
5183 if (ret == REG_ERPAREN) ret = REG_EPAREN;
5189 /* regexec searches for a given pattern, specified by PREG, in the
5192 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5193 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5194 least NMATCH elements, and we set them to the offsets of the
5195 corresponding matched substrings.
5197 EFLAGS specifies `execution flags' which affect matching: if
5198 REG_NOTBOL is set, then ^ does not match at the beginning of the
5199 string; if REG_NOTEOL is set, then $ does not match at the end.
5201 We return 0 if we find a match and REG_NOMATCH if not. */
5204 regexec (preg, string, nmatch, pmatch, eflags)
5205 const regex_t *preg;
5208 regmatch_t pmatch[];
5212 struct re_registers regs;
5213 regex_t private_preg;
5214 int len = strlen (string);
5215 boolean want_reg_info = !preg->no_sub && nmatch > 0;
5217 private_preg = *preg;
5219 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5220 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5222 /* The user has told us exactly how many registers to return
5223 information about, via `nmatch'. We have to pass that on to the
5224 matching routines. */
5225 private_preg.regs_allocated = REGS_FIXED;
5229 regs.num_regs = nmatch;
5230 regs.start = TALLOC (nmatch, regoff_t);
5231 regs.end = TALLOC (nmatch, regoff_t);
5232 if (regs.start == NULL || regs.end == NULL)
5233 return (int) REG_NOMATCH;
5236 /* Perform the searching operation. */
5237 ret = re_search (&private_preg, string, len,
5238 /* start: */ 0, /* range: */ len,
5239 want_reg_info ? ®s : (struct re_registers *) 0);
5241 /* Copy the register information to the POSIX structure. */
5248 for (r = 0; r < nmatch; r++)
5250 pmatch[r].rm_so = regs.start[r];
5251 pmatch[r].rm_eo = regs.end[r];
5255 /* If we needed the temporary register info, free the space now. */
5260 /* We want zero return to mean success, unlike `re_search'. */
5261 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5265 /* Returns a message corresponding to an error code, ERRCODE, returned
5266 from either regcomp or regexec. We don't use PREG here. */
5269 regerror (errcode, preg, errbuf, errbuf_size)
5271 const regex_t *preg;
5279 || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0])))
5280 /* Only error codes returned by the rest of the code should be passed
5281 to this routine. If we are given anything else, or if other regex
5282 code generates an invalid error code, then the program has a bug.
5283 Dump core so we can fix it. */
5286 msg = re_error_msg[errcode];
5288 /* POSIX doesn't require that we do anything in this case, but why
5293 msg_size = strlen (msg) + 1; /* Includes the null. */
5295 if (errbuf_size != 0)
5297 if (msg_size > errbuf_size)
5299 strncpy (errbuf, msg, errbuf_size - 1);
5300 errbuf[errbuf_size - 1] = 0;
5303 strcpy (errbuf, msg);
5310 /* Free dynamically allocated space used by PREG. */
5316 if (preg->buffer != NULL)
5317 free (preg->buffer);
5318 preg->buffer = NULL;
5320 preg->allocated = 0;
5323 if (preg->fastmap != NULL)
5324 free (preg->fastmap);
5325 preg->fastmap = NULL;
5326 preg->fastmap_accurate = 0;
5328 if (preg->translate != NULL)
5329 free (preg->translate);
5330 preg->translate = NULL;
5333 #endif /* not emacs */
5337 make-backup-files: t
5339 trim-versions-without-asking: nil