1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P10003.2/D11.2, except for
4 internationalization features.)
6 Copyright (C) 1985, 89, 90, 91, 92 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 /* We need this for `regex.h', and perhaps for the Emacs include files. */
30 #include <sys/types.h>
32 #if defined (HAVE_CONFIG_H) || defined (emacs)
36 /* The `emacs' switch turns on certain matching commands
37 that make sense only in Emacs. */
44 /* Emacs uses `NULL' as a predicate. */
49 /* We used to test for `BSTRING' here, but only GCC and Emacs define
50 `BSTRING', as far as I know, and neither of them use this code. */
51 #if HAVE_STRING_H || STDC_HEADERS
54 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
57 #define bcopy(s, d, n) memcpy ((d), (s), (n))
60 #define bzero(s, n) memset ((s), 0, (n))
74 /* Define the syntax stuff for \<, \>, etc. */
76 /* This must be nonzero for the wordchar and notwordchar pattern
77 commands in re_match_2. */
84 extern char *re_syntax_table;
86 #else /* not SYNTAX_TABLE */
88 /* How many characters in the character set. */
89 #define CHAR_SET_SIZE 256
91 static char re_syntax_table[CHAR_SET_SIZE];
102 bzero (re_syntax_table, sizeof re_syntax_table);
104 for (c = 'a'; c <= 'z'; c++)
105 re_syntax_table[c] = Sword;
107 for (c = 'A'; c <= 'Z'; c++)
108 re_syntax_table[c] = Sword;
110 for (c = '0'; c <= '9'; c++)
111 re_syntax_table[c] = Sword;
113 re_syntax_table['_'] = Sword;
118 #endif /* not SYNTAX_TABLE */
120 #define SYNTAX(c) re_syntax_table[c]
122 #endif /* not emacs */
124 /* Get the interface, including the syntax bits. */
128 /* isalpha etc. are used for the character classes. */
131 #define isgraph(c) (isprint (c) && !isspace (c))
134 #define isblank(c) ((c) == ' ' || (c) == '\t')
141 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
142 since ours (we hope) works properly with all combinations of
143 machines, compilers, `char' and `unsigned char' argument types.
144 (Per Bothner suggested the basic approach.) */
145 #undef SIGN_EXTEND_CHAR
147 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
148 #else /* not __STDC__ */
149 /* As in Harbison and Steele. */
150 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
153 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
154 use `alloca' instead of `malloc'. This is because using malloc in
155 re_search* or re_match* could cause memory leaks when C-g is used in
156 Emacs; also, malloc is slower and causes storage fragmentation. On
157 the other hand, malloc is more portable, and easier to debug.
159 Because we sometimes use alloca, some routines have to be macros,
160 not functions -- `alloca'-allocated space disappears at the end of the
161 function it is called in. */
165 #define REGEX_ALLOCATE malloc
166 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
168 #else /* not REGEX_MALLOC */
170 /* Emacs already defines alloca, sometimes. */
173 /* Make alloca work the best possible way. */
175 #define alloca __builtin_alloca
176 #else /* not __GNUC__ */
179 #else /* not __GNUC__ or HAVE_ALLOCA_H */
180 #ifndef _AIX /* Already did AIX, up at the top. */
182 #endif /* not _AIX */
183 #endif /* not HAVE_ALLOCA_H */
184 #endif /* not __GNUC__ */
186 #endif /* not alloca */
188 #define REGEX_ALLOCATE alloca
190 /* Assumes a `char *destination' variable. */
191 #define REGEX_REALLOCATE(source, osize, nsize) \
192 (destination = (char *) alloca (nsize), \
193 bcopy (source, destination, osize), \
196 #endif /* not REGEX_MALLOC */
199 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
200 `string1' or just past its end. This works if PTR is NULL, which is
202 #define FIRST_STRING_P(ptr) \
203 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
205 /* (Re)Allocate N items of type T using malloc, or fail. */
206 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
207 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
208 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
210 #define BYTEWIDTH 8 /* In bits. */
212 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
214 #define MAX(a, b) ((a) > (b) ? (a) : (b))
215 #define MIN(a, b) ((a) < (b) ? (a) : (b))
217 typedef char boolean;
221 /* These are the command codes that appear in compiled regular
222 expressions. Some opcodes are followed by argument bytes. A
223 command code can specify any interpretation whatsoever for its
224 arguments. Zero bytes may appear in the compiled regular expression.
226 The value of `exactn' is needed in search.c (search_buffer) in Emacs.
227 So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
228 `exactn' we use here must also be 1. */
234 /* Followed by one byte giving n, then by n literal bytes. */
237 /* Matches any (more or less) character. */
240 /* Matches any one char belonging to specified set. First
241 following byte is number of bitmap bytes. Then come bytes
242 for a bitmap saying which chars are in. Bits in each byte
243 are ordered low-bit-first. A character is in the set if its
244 bit is 1. A character too large to have a bit in the map is
245 automatically not in the set. */
248 /* Same parameters as charset, but match any character that is
249 not one of those specified. */
252 /* Start remembering the text that is matched, for storing in a
253 register. Followed by one byte with the register number, in
254 the range 0 to one less than the pattern buffer's re_nsub
255 field. Then followed by one byte with the number of groups
256 inner to this one. (This last has to be part of the
257 start_memory only because we need it in the on_failure_jump
261 /* Stop remembering the text that is matched and store it in a
262 memory register. Followed by one byte with the register
263 number, in the range 0 to one less than `re_nsub' in the
264 pattern buffer, and one byte with the number of inner groups,
265 just like `start_memory'. (We need the number of inner
266 groups here because we don't have any easy way of finding the
267 corresponding start_memory when we're at a stop_memory.) */
270 /* Match a duplicate of something remembered. Followed by one
271 byte containing the register number. */
274 /* Fail unless at beginning of line. */
277 /* Fail unless at end of line. */
280 /* Succeeds if at beginning of buffer (if emacs) or at beginning
281 of string to be matched (if not). */
284 /* Analogously, for end of buffer/string. */
287 /* Followed by two byte relative address to which to jump. */
290 /* Same as jump, but marks the end of an alternative. */
293 /* Followed by two-byte relative address of place to resume at
294 in case of failure. */
297 /* Like on_failure_jump, but pushes a placeholder instead of the
298 current string position when executed. */
299 on_failure_keep_string_jump,
301 /* Throw away latest failure point and then jump to following
302 two-byte relative address. */
305 /* Change to pop_failure_jump if know won't have to backtrack to
306 match; otherwise change to jump. This is used to jump
307 back to the beginning of a repeat. If what follows this jump
308 clearly won't match what the repeat does, such that we can be
309 sure that there is no use backtracking out of repetitions
310 already matched, then we change it to a pop_failure_jump.
311 Followed by two-byte address. */
314 /* Jump to following two-byte address, and push a dummy failure
315 point. This failure point will be thrown away if an attempt
316 is made to use it for a failure. A `+' construct makes this
317 before the first repeat. Also used as an intermediary kind
318 of jump when compiling an alternative. */
321 /* Push a dummy failure point and continue. Used at the end of
325 /* Followed by two-byte relative address and two-byte number n.
326 After matching N times, jump to the address upon failure. */
329 /* Followed by two-byte relative address, and two-byte number n.
330 Jump to the address N times, then fail. */
333 /* Set the following two-byte relative address to the
334 subsequent two-byte number. The address *includes* the two
338 wordchar, /* Matches any word-constituent character. */
339 notwordchar, /* Matches any char that is not a word-constituent. */
341 wordbeg, /* Succeeds if at word beginning. */
342 wordend, /* Succeeds if at word end. */
344 wordbound, /* Succeeds if at a word boundary. */
345 notwordbound /* Succeeds if not at a word boundary. */
348 ,before_dot, /* Succeeds if before point. */
349 at_dot, /* Succeeds if at point. */
350 after_dot, /* Succeeds if after point. */
352 /* Matches any character whose syntax is specified. Followed by
353 a byte which contains a syntax code, e.g., Sword. */
356 /* Matches any character whose syntax is not that specified. */
361 /* Common operations on the compiled pattern. */
363 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
365 #define STORE_NUMBER(destination, number) \
367 (destination)[0] = (number) & 0377; \
368 (destination)[1] = (number) >> 8; \
371 /* Same as STORE_NUMBER, except increment DESTINATION to
372 the byte after where the number is stored. Therefore, DESTINATION
373 must be an lvalue. */
375 #define STORE_NUMBER_AND_INCR(destination, number) \
377 STORE_NUMBER (destination, number); \
378 (destination) += 2; \
381 /* Put into DESTINATION a number stored in two contiguous bytes starting
384 #define EXTRACT_NUMBER(destination, source) \
386 (destination) = *(source) & 0377; \
387 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
392 extract_number (dest, source)
394 unsigned char *source;
396 int temp = SIGN_EXTEND_CHAR (*(source + 1));
397 *dest = *source & 0377;
401 #ifndef EXTRACT_MACROS /* To debug the macros. */
402 #undef EXTRACT_NUMBER
403 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
404 #endif /* not EXTRACT_MACROS */
408 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
409 SOURCE must be an lvalue. */
411 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
413 EXTRACT_NUMBER (destination, source); \
419 extract_number_and_incr (destination, source)
421 unsigned char **source;
423 extract_number (destination, *source);
427 #ifndef EXTRACT_MACROS
428 #undef EXTRACT_NUMBER_AND_INCR
429 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
430 extract_number_and_incr (&dest, &src)
431 #endif /* not EXTRACT_MACROS */
435 /* If DEBUG is defined, Regex prints many voluminous messages about what
436 it is doing (if the variable `debug' is nonzero). If linked with the
437 main program in `iregex.c', you can enter patterns and strings
438 interactively. And if linked with the main program in `main.c' and
439 the other test files, you can run the already-written tests. */
443 /* We use standard I/O for debugging. */
446 /* It is useful to test things that ``must'' be true when debugging. */
449 static int debug = 0;
451 #define DEBUG_STATEMENT(e) e
452 #define DEBUG_PRINT1(x) if (debug) printf (x)
453 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
454 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
455 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
456 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
457 if (debug) print_partial_compiled_pattern (s, e)
458 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
459 if (debug) print_double_string (w, s1, sz1, s2, sz2)
462 extern void printchar ();
464 /* Print the fastmap in human-readable form. */
467 print_fastmap (fastmap)
470 unsigned was_a_range = 0;
473 while (i < (1 << BYTEWIDTH))
479 while (i < (1 << BYTEWIDTH) && fastmap[i])
495 /* Print a compiled pattern string in human-readable form, starting at
496 the START pointer into it and ending just before the pointer END. */
499 print_partial_compiled_pattern (start, end)
500 unsigned char *start;
504 unsigned char *p = start;
505 unsigned char *pend = end;
513 /* Loop over pattern commands. */
516 switch ((re_opcode_t) *p++)
524 printf ("/exactn/%d", mcnt);
535 printf ("/start_memory/%d/%d", mcnt, *p++);
540 printf ("/stop_memory/%d/%d", mcnt, *p++);
544 printf ("/duplicate/%d", *p++);
556 printf ("/charset%s",
557 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
559 assert (p + *p < pend);
561 for (c = 0; c < *p; c++)
564 unsigned char map_byte = p[1 + c];
568 for (bit = 0; bit < BYTEWIDTH; bit++)
569 if (map_byte & (1 << bit))
570 printchar (c * BYTEWIDTH + bit);
584 case on_failure_jump:
585 extract_number_and_incr (&mcnt, &p);
586 printf ("/on_failure_jump/0/%d", mcnt);
589 case on_failure_keep_string_jump:
590 extract_number_and_incr (&mcnt, &p);
591 printf ("/on_failure_keep_string_jump/0/%d", mcnt);
594 case dummy_failure_jump:
595 extract_number_and_incr (&mcnt, &p);
596 printf ("/dummy_failure_jump/0/%d", mcnt);
599 case push_dummy_failure:
600 printf ("/push_dummy_failure");
604 extract_number_and_incr (&mcnt, &p);
605 printf ("/maybe_pop_jump/0/%d", mcnt);
608 case pop_failure_jump:
609 extract_number_and_incr (&mcnt, &p);
610 printf ("/pop_failure_jump/0/%d", mcnt);
614 extract_number_and_incr (&mcnt, &p);
615 printf ("/jump_past_alt/0/%d", mcnt);
619 extract_number_and_incr (&mcnt, &p);
620 printf ("/jump/0/%d", mcnt);
624 extract_number_and_incr (&mcnt, &p);
625 extract_number_and_incr (&mcnt2, &p);
626 printf ("/succeed_n/0/%d/0/%d", mcnt, mcnt2);
630 extract_number_and_incr (&mcnt, &p);
631 extract_number_and_incr (&mcnt2, &p);
632 printf ("/jump_n/0/%d/0/%d", mcnt, mcnt2);
636 extract_number_and_incr (&mcnt, &p);
637 extract_number_and_incr (&mcnt2, &p);
638 printf ("/set_number_at/0/%d/0/%d", mcnt, mcnt2);
642 printf ("/wordbound");
646 printf ("/notwordbound");
658 printf ("/before_dot");
666 printf ("/after_dot");
670 printf ("/syntaxspec");
672 printf ("/%d", mcnt);
676 printf ("/notsyntaxspec");
678 printf ("/%d", mcnt);
683 printf ("/wordchar");
687 printf ("/notwordchar");
699 printf ("?%d", *(p-1));
707 print_compiled_pattern (bufp)
708 struct re_pattern_buffer *bufp;
710 unsigned char *buffer = bufp->buffer;
712 print_partial_compiled_pattern (buffer, buffer + bufp->used);
713 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
715 if (bufp->fastmap_accurate && bufp->fastmap)
717 printf ("fastmap: ");
718 print_fastmap (bufp->fastmap);
721 printf ("re_nsub: %d\t", bufp->re_nsub);
722 printf ("regs_alloc: %d\t", bufp->regs_allocated);
723 printf ("can_be_null: %d\t", bufp->can_be_null);
724 printf ("newline_anchor: %d\n", bufp->newline_anchor);
725 printf ("no_sub: %d\t", bufp->no_sub);
726 printf ("not_bol: %d\t", bufp->not_bol);
727 printf ("not_eol: %d\t", bufp->not_eol);
728 printf ("syntax: %d\n", bufp->syntax);
729 /* Perhaps we should print the translate table? */
734 print_double_string (where, string1, size1, string2, size2)
747 if (FIRST_STRING_P (where))
749 for (this_char = where - string1; this_char < size1; this_char++)
750 printchar (string1[this_char]);
755 for (this_char = where - string2; this_char < size2; this_char++)
756 printchar (string2[this_char]);
760 #else /* not DEBUG */
765 #define DEBUG_STATEMENT(e)
766 #define DEBUG_PRINT1(x)
767 #define DEBUG_PRINT2(x1, x2)
768 #define DEBUG_PRINT3(x1, x2, x3)
769 #define DEBUG_PRINT4(x1, x2, x3, x4)
770 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
771 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
773 #endif /* not DEBUG */
775 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
776 also be assigned to arbitrarily: each pattern buffer stores its own
777 syntax, so it can be changed between regex compilations. */
778 reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
781 /* Specify the precise syntax of regexps for compilation. This provides
782 for compatibility for various utilities which historically have
783 different, incompatible syntaxes.
785 The argument SYNTAX is a bit mask comprised of the various bits
786 defined in regex.h. We return the old syntax. */
789 re_set_syntax (syntax)
792 reg_syntax_t ret = re_syntax_options;
794 re_syntax_options = syntax;
798 /* This table gives an error message for each of the error codes listed
799 in regex.h. Obviously the order here has to be same as there. */
801 static const char *re_error_msg[] =
802 { NULL, /* REG_NOERROR */
803 "No match", /* REG_NOMATCH */
804 "Invalid regular expression", /* REG_BADPAT */
805 "Invalid collation character", /* REG_ECOLLATE */
806 "Invalid character class name", /* REG_ECTYPE */
807 "Trailing backslash", /* REG_EESCAPE */
808 "Invalid back reference", /* REG_ESUBREG */
809 "Unmatched [ or [^", /* REG_EBRACK */
810 "Unmatched ( or \\(", /* REG_EPAREN */
811 "Unmatched \\{", /* REG_EBRACE */
812 "Invalid content of \\{\\}", /* REG_BADBR */
813 "Invalid range end", /* REG_ERANGE */
814 "Memory exhausted", /* REG_ESPACE */
815 "Invalid preceding regular expression", /* REG_BADRPT */
816 "Premature end of regular expression", /* REG_EEND */
817 "Regular expression too big", /* REG_ESIZE */
818 "Unmatched ) or \\)", /* REG_ERPAREN */
821 /* Subroutine declarations and macros for regex_compile. */
823 static void store_op1 (), store_op2 ();
824 static void insert_op1 (), insert_op2 ();
825 static boolean at_begline_loc_p (), at_endline_loc_p ();
826 static boolean group_in_compile_stack ();
827 static reg_errcode_t compile_range ();
829 /* Fetch the next character in the uncompiled pattern---translating it
830 if necessary. Also cast from a signed character in the constant
831 string passed to us by the user to an unsigned char that we can use
832 as an array index (in, e.g., `translate'). */
833 #define PATFETCH(c) \
834 do {if (p == pend) return REG_EEND; \
835 c = (unsigned char) *p++; \
836 if (translate) c = translate[c]; \
839 /* Fetch the next character in the uncompiled pattern, with no
841 #define PATFETCH_RAW(c) \
842 do {if (p == pend) return REG_EEND; \
843 c = (unsigned char) *p++; \
846 /* Go backwards one character in the pattern. */
847 #define PATUNFETCH p--
850 /* If `translate' is non-null, return translate[D], else just D. We
851 cast the subscript to translate because some data is declared as
852 `char *', to avoid warnings when a string constant is passed. But
853 when we use a character as a subscript we must make it unsigned. */
854 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
857 /* Macros for outputting the compiled pattern into `buffer'. */
859 /* If the buffer isn't allocated when it comes in, use this. */
860 #define INIT_BUF_SIZE 32
862 /* Make sure we have at least N more bytes of space in buffer. */
863 #define GET_BUFFER_SPACE(n) \
864 while (b - bufp->buffer + (n) > bufp->allocated) \
867 /* Make sure we have one more byte of buffer space and then add C to it. */
868 #define BUF_PUSH(c) \
870 GET_BUFFER_SPACE (1); \
871 *b++ = (unsigned char) (c); \
875 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
876 #define BUF_PUSH_2(c1, c2) \
878 GET_BUFFER_SPACE (2); \
879 *b++ = (unsigned char) (c1); \
880 *b++ = (unsigned char) (c2); \
884 /* As with BUF_PUSH_2, except for three bytes. */
885 #define BUF_PUSH_3(c1, c2, c3) \
887 GET_BUFFER_SPACE (3); \
888 *b++ = (unsigned char) (c1); \
889 *b++ = (unsigned char) (c2); \
890 *b++ = (unsigned char) (c3); \
894 /* Store a jump with opcode OP at LOC to location TO. We store a
895 relative address offset by the three bytes the jump itself occupies. */
896 #define STORE_JUMP(op, loc, to) \
897 store_op1 (op, loc, (to) - (loc) - 3)
899 /* Likewise, for a two-argument jump. */
900 #define STORE_JUMP2(op, loc, to, arg) \
901 store_op2 (op, loc, (to) - (loc) - 3, arg)
903 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
904 #define INSERT_JUMP(op, loc, to) \
905 insert_op1 (op, loc, (to) - (loc) - 3, b)
907 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
908 #define INSERT_JUMP2(op, loc, to, arg) \
909 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
912 /* This is not an arbitrary limit: the arguments which represent offsets
913 into the pattern are two bytes long. So if 2^16 bytes turns out to
914 be too small, many things would have to change. */
915 #define MAX_BUF_SIZE (1L << 16)
918 /* Extend the buffer by twice its current size via realloc and
919 reset the pointers that pointed into the old block to point to the
920 correct places in the new one. If extending the buffer results in it
921 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
922 #define EXTEND_BUFFER() \
924 unsigned char *old_buffer = bufp->buffer; \
925 if (bufp->allocated == MAX_BUF_SIZE) \
927 bufp->allocated <<= 1; \
928 if (bufp->allocated > MAX_BUF_SIZE) \
929 bufp->allocated = MAX_BUF_SIZE; \
930 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
931 if (bufp->buffer == NULL) \
933 /* If the buffer moved, move all the pointers into it. */ \
934 if (old_buffer != bufp->buffer) \
936 b = (b - old_buffer) + bufp->buffer; \
937 begalt = (begalt - old_buffer) + bufp->buffer; \
938 if (fixup_alt_jump) \
939 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
941 laststart = (laststart - old_buffer) + bufp->buffer; \
943 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
948 /* Since we have one byte reserved for the register number argument to
949 {start,stop}_memory, the maximum number of groups we can report
950 things about is what fits in that byte. */
951 #define MAX_REGNUM 255
953 /* But patterns can have more than `MAX_REGNUM' registers. We just
954 ignore the excess. */
955 typedef unsigned regnum_t;
958 /* Macros for the compile stack. */
960 /* Since offsets can go either forwards or backwards, this type needs to
961 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
962 typedef int pattern_offset_t;
966 pattern_offset_t begalt_offset;
967 pattern_offset_t fixup_alt_jump;
968 pattern_offset_t inner_group_offset;
969 pattern_offset_t laststart_offset;
971 } compile_stack_elt_t;
976 compile_stack_elt_t *stack;
978 unsigned avail; /* Offset of next open position. */
979 } compile_stack_type;
982 #define INIT_COMPILE_STACK_SIZE 32
984 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
985 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
987 /* The next available element. */
988 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
991 /* Set the bit for character C in a list. */
992 #define SET_LIST_BIT(c) \
993 (b[((unsigned char) (c)) / BYTEWIDTH] \
994 |= 1 << (((unsigned char) c) % BYTEWIDTH))
997 /* Get the next unsigned number in the uncompiled pattern. */
998 #define GET_UNSIGNED_NUMBER(num) \
1002 while (isdigit (c)) \
1006 num = num * 10 + c - '0'; \
1014 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1016 #define IS_CHAR_CLASS(string) \
1017 (STREQ (string, "alpha") || STREQ (string, "upper") \
1018 || STREQ (string, "lower") || STREQ (string, "digit") \
1019 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1020 || STREQ (string, "space") || STREQ (string, "print") \
1021 || STREQ (string, "punct") || STREQ (string, "graph") \
1022 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1024 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1025 Returns one of error codes defined in `regex.h', or zero for success.
1027 Assumes the `allocated' (and perhaps `buffer') and `translate'
1028 fields are set in BUFP on entry.
1030 If it succeeds, results are put in BUFP (if it returns an error, the
1031 contents of BUFP are undefined):
1032 `buffer' is the compiled pattern;
1033 `syntax' is set to SYNTAX;
1034 `used' is set to the length of the compiled pattern;
1035 `fastmap_accurate' is zero;
1036 `re_nsub' is the number of subexpressions in PATTERN;
1037 `not_bol' and `not_eol' are zero;
1039 The `fastmap' and `newline_anchor' fields are neither
1040 examined nor set. */
1042 static reg_errcode_t
1043 regex_compile (pattern, size, syntax, bufp)
1044 const char *pattern;
1046 reg_syntax_t syntax;
1047 struct re_pattern_buffer *bufp;
1049 /* We fetch characters from PATTERN here. Even though PATTERN is
1050 `char *' (i.e., signed), we declare these variables as unsigned, so
1051 they can be reliably used as array indices. */
1052 register unsigned char c, c1;
1054 /* A random tempory spot in PATTERN. */
1057 /* Points to the end of the buffer, where we should append. */
1058 register unsigned char *b;
1060 /* Keeps track of unclosed groups. */
1061 compile_stack_type compile_stack;
1063 /* Points to the current (ending) position in the pattern. */
1064 const char *p = pattern;
1065 const char *pend = pattern + size;
1067 /* How to translate the characters in the pattern. */
1068 char *translate = bufp->translate;
1070 /* Address of the count-byte of the most recently inserted `exactn'
1071 command. This makes it possible to tell if a new exact-match
1072 character can be added to that command or if the character requires
1073 a new `exactn' command. */
1074 unsigned char *pending_exact = 0;
1076 /* Address of start of the most recently finished expression.
1077 This tells, e.g., postfix * where to find the start of its
1078 operand. Reset at the beginning of groups and alternatives. */
1079 unsigned char *laststart = 0;
1081 /* Address of beginning of regexp, or inside of last group. */
1082 unsigned char *begalt;
1084 /* Place in the uncompiled pattern (i.e., the {) to
1085 which to go back if the interval is invalid. */
1086 const char *beg_interval;
1088 /* Address of the place where a forward jump should go to the end of
1089 the containing expression. Each alternative of an `or' -- except the
1090 last -- ends with a forward jump of this sort. */
1091 unsigned char *fixup_alt_jump = 0;
1093 /* Counts open-groups as they are encountered. Remembered for the
1094 matching close-group on the compile stack, so the same register
1095 number is put in the stop_memory as the start_memory. */
1096 regnum_t regnum = 0;
1099 DEBUG_PRINT1 ("\nCompiling pattern: ");
1102 unsigned debug_count;
1104 for (debug_count = 0; debug_count < size; debug_count++)
1105 printchar (pattern[debug_count]);
1110 /* Initialize the compile stack. */
1111 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1112 if (compile_stack.stack == NULL)
1115 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1116 compile_stack.avail = 0;
1118 /* Initialize the pattern buffer. */
1119 bufp->syntax = syntax;
1120 bufp->fastmap_accurate = 0;
1121 bufp->not_bol = bufp->not_eol = 0;
1123 /* Set `used' to zero, so that if we return an error, the pattern
1124 printer (for debugging) will think there's no pattern. We reset it
1128 /* Always count groups, whether or not bufp->no_sub is set. */
1131 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1132 /* Initialize the syntax table. */
1133 init_syntax_once ();
1136 if (bufp->allocated == 0)
1139 { /* If zero allocated, but buffer is non-null, try to realloc
1140 enough space. This loses if buffer's address is bogus, but
1141 that is the user's responsibility. */
1142 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1145 { /* Caller did not allocate a buffer. Do it for them. */
1146 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1148 if (!bufp->buffer) return REG_ESPACE;
1150 bufp->allocated = INIT_BUF_SIZE;
1153 begalt = b = bufp->buffer;
1155 /* Loop through the uncompiled pattern until we're at the end. */
1164 if ( /* If at start of pattern, it's an operator. */
1166 /* If context independent, it's an operator. */
1167 || syntax & RE_CONTEXT_INDEP_ANCHORS
1168 /* Otherwise, depends on what's come before. */
1169 || at_begline_loc_p (pattern, p, syntax))
1179 if ( /* If at end of pattern, it's an operator. */
1181 /* If context independent, it's an operator. */
1182 || syntax & RE_CONTEXT_INDEP_ANCHORS
1183 /* Otherwise, depends on what's next. */
1184 || at_endline_loc_p (p, pend, syntax))
1194 if ((syntax & RE_BK_PLUS_QM)
1195 || (syntax & RE_LIMITED_OPS))
1199 /* If there is no previous pattern... */
1202 if (syntax & RE_CONTEXT_INVALID_OPS)
1204 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1209 /* Are we optimizing this jump? */
1210 boolean keep_string_p = false;
1212 /* 1 means zero (many) matches is allowed. */
1213 char zero_times_ok = 0, many_times_ok = 0;
1215 /* If there is a sequence of repetition chars, collapse it
1216 down to just one (the right one). We can't combine
1217 interval operators with these because of, e.g., `a{2}*',
1218 which should only match an even number of `a's. */
1222 zero_times_ok |= c != '+';
1223 many_times_ok |= c != '?';
1231 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1234 else if (syntax & RE_BK_PLUS_QM && c == '\\')
1236 if (p == pend) return REG_EESCAPE;
1239 if (!(c1 == '+' || c1 == '?'))
1254 /* If we get here, we found another repeat character. */
1257 /* Star, etc. applied to an empty pattern is equivalent
1258 to an empty pattern. */
1262 /* Now we know whether or not zero matches is allowed
1263 and also whether or not two or more matches is allowed. */
1265 { /* More than one repetition is allowed, so put in at the
1266 end a backward relative jump from `b' to before the next
1267 jump we're going to put in below (which jumps from
1268 laststart to after this jump).
1270 But if we are at the `*' in the exact sequence `.*\n',
1271 insert an unconditional jump backwards to the .,
1272 instead of the beginning of the loop. This way we only
1273 push a failure point once, instead of every time
1274 through the loop. */
1275 assert (p - 1 > pattern);
1277 /* Allocate the space for the jump. */
1278 GET_BUFFER_SPACE (3);
1280 /* We know we are not at the first character of the pattern,
1281 because laststart was nonzero. And we've already
1282 incremented `p', by the way, to be the character after
1283 the `*'. Do we have to do something analogous here
1284 for null bytes, because of RE_DOT_NOT_NULL? */
1285 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1286 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1287 && !(syntax & RE_DOT_NEWLINE))
1288 { /* We have .*\n. */
1289 STORE_JUMP (jump, b, laststart);
1290 keep_string_p = true;
1293 /* Anything else. */
1294 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1296 /* We've added more stuff to the buffer. */
1300 /* On failure, jump from laststart to b + 3, which will be the
1301 end of the buffer after this jump is inserted. */
1302 GET_BUFFER_SPACE (3);
1303 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1311 /* At least one repetition is required, so insert a
1312 `dummy_failure_jump' before the initial
1313 `on_failure_jump' instruction of the loop. This
1314 effects a skip over that instruction the first time
1315 we hit that loop. */
1316 GET_BUFFER_SPACE (3);
1317 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1332 boolean had_char_class = false;
1334 if (p == pend) return REG_EBRACK;
1336 /* Ensure that we have enough space to push a charset: the
1337 opcode, the length count, and the bitset; 34 bytes in all. */
1338 GET_BUFFER_SPACE (34);
1342 /* We test `*p == '^' twice, instead of using an if
1343 statement, so we only need one BUF_PUSH. */
1344 BUF_PUSH (*p == '^' ? charset_not : charset);
1348 /* Remember the first position in the bracket expression. */
1351 /* Push the number of bytes in the bitmap. */
1352 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1354 /* Clear the whole map. */
1355 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1357 /* charset_not matches newline according to a syntax bit. */
1358 if ((re_opcode_t) b[-2] == charset_not
1359 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1360 SET_LIST_BIT ('\n');
1362 /* Read in characters and ranges, setting map bits. */
1365 if (p == pend) return REG_EBRACK;
1369 /* \ might escape characters inside [...] and [^...]. */
1370 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1372 if (p == pend) return REG_EESCAPE;
1379 /* Could be the end of the bracket expression. If it's
1380 not (i.e., when the bracket expression is `[]' so
1381 far), the ']' character bit gets set way below. */
1382 if (c == ']' && p != p1 + 1)
1385 /* Look ahead to see if it's a range when the last thing
1386 was a character class. */
1387 if (had_char_class && c == '-' && *p != ']')
1390 /* Look ahead to see if it's a range when the last thing
1391 was a character: if this is a hyphen not at the
1392 beginning or the end of a list, then it's the range
1395 && !(p - 2 >= pattern && p[-2] == '[')
1396 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1400 = compile_range (&p, pend, translate, syntax, b);
1401 if (ret != REG_NOERROR) return ret;
1404 else if (p[0] == '-' && p[1] != ']')
1405 { /* This handles ranges made up of characters only. */
1408 /* Move past the `-'. */
1411 ret = compile_range (&p, pend, translate, syntax, b);
1412 if (ret != REG_NOERROR) return ret;
1415 /* See if we're at the beginning of a possible character
1418 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
1419 { /* Leave room for the null. */
1420 char str[CHAR_CLASS_MAX_LENGTH + 1];
1425 /* If pattern is `[[:'. */
1426 if (p == pend) return REG_EBRACK;
1431 if (c == ':' || c == ']' || p == pend
1432 || c1 == CHAR_CLASS_MAX_LENGTH)
1438 /* If isn't a word bracketed by `[:' and:`]':
1439 undo the ending character, the letters, and leave
1440 the leading `:' and `[' (but set bits for them). */
1441 if (c == ':' && *p == ']')
1444 boolean is_alnum = STREQ (str, "alnum");
1445 boolean is_alpha = STREQ (str, "alpha");
1446 boolean is_blank = STREQ (str, "blank");
1447 boolean is_cntrl = STREQ (str, "cntrl");
1448 boolean is_digit = STREQ (str, "digit");
1449 boolean is_graph = STREQ (str, "graph");
1450 boolean is_lower = STREQ (str, "lower");
1451 boolean is_print = STREQ (str, "print");
1452 boolean is_punct = STREQ (str, "punct");
1453 boolean is_space = STREQ (str, "space");
1454 boolean is_upper = STREQ (str, "upper");
1455 boolean is_xdigit = STREQ (str, "xdigit");
1457 if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
1459 /* Throw away the ] at the end of the character
1463 if (p == pend) return REG_EBRACK;
1465 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
1467 if ( (is_alnum && isalnum (ch))
1468 || (is_alpha && isalpha (ch))
1469 || (is_blank && isblank (ch))
1470 || (is_cntrl && iscntrl (ch))
1471 || (is_digit && isdigit (ch))
1472 || (is_graph && isgraph (ch))
1473 || (is_lower && islower (ch))
1474 || (is_print && isprint (ch))
1475 || (is_punct && ispunct (ch))
1476 || (is_space && isspace (ch))
1477 || (is_upper && isupper (ch))
1478 || (is_xdigit && isxdigit (ch)))
1481 had_char_class = true;
1490 had_char_class = false;
1495 had_char_class = false;
1500 /* Discard any (non)matching list bytes that are all 0 at the
1501 end of the map. Decrease the map-length byte too. */
1502 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
1510 if (syntax & RE_NO_BK_PARENS)
1517 if (syntax & RE_NO_BK_PARENS)
1524 if (syntax & RE_NEWLINE_ALT)
1531 if (syntax & RE_NO_BK_VBAR)
1538 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1539 goto handle_interval;
1545 if (p == pend) return REG_EESCAPE;
1547 /* Do not translate the character after the \, so that we can
1548 distinguish, e.g., \B from \b, even if we normally would
1549 translate, e.g., B to b. */
1555 if (syntax & RE_NO_BK_PARENS)
1556 goto normal_backslash;
1562 if (COMPILE_STACK_FULL)
1564 RETALLOC (compile_stack.stack, compile_stack.size << 1,
1565 compile_stack_elt_t);
1566 if (compile_stack.stack == NULL) return REG_ESPACE;
1568 compile_stack.size <<= 1;
1571 /* These are the values to restore when we hit end of this
1572 group. They are all relative offsets, so that if the
1573 whole pattern moves because of realloc, they will still
1575 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
1576 COMPILE_STACK_TOP.fixup_alt_jump
1577 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
1578 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
1579 COMPILE_STACK_TOP.regnum = regnum;
1581 /* We will eventually replace the 0 with the number of
1582 groups inner to this one. But do not push a
1583 start_memory for groups beyond the last one we can
1584 represent in the compiled pattern. */
1585 if (regnum <= MAX_REGNUM)
1587 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
1588 BUF_PUSH_3 (start_memory, regnum, 0);
1591 compile_stack.avail++;
1600 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
1602 if (COMPILE_STACK_EMPTY)
1603 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1604 goto normal_backslash;
1610 { /* Push a dummy failure point at the end of the
1611 alternative for a possible future
1612 `pop_failure_jump' to pop. See comments at
1613 `push_dummy_failure' in `re_match_2'. */
1614 BUF_PUSH (push_dummy_failure);
1616 /* We allocated space for this jump when we assigned
1617 to `fixup_alt_jump', in the `handle_alt' case below. */
1618 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
1621 /* See similar code for backslashed left paren above. */
1622 if (COMPILE_STACK_EMPTY)
1623 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1628 /* Since we just checked for an empty stack above, this
1629 ``can't happen''. */
1630 assert (compile_stack.avail != 0);
1632 /* We don't just want to restore into `regnum', because
1633 later groups should continue to be numbered higher,
1634 as in `(ab)c(de)' -- the second group is #2. */
1635 regnum_t this_group_regnum;
1637 compile_stack.avail--;
1638 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
1640 = COMPILE_STACK_TOP.fixup_alt_jump
1641 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
1643 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
1644 this_group_regnum = COMPILE_STACK_TOP.regnum;
1646 /* We're at the end of the group, so now we know how many
1647 groups were inside this one. */
1648 if (this_group_regnum <= MAX_REGNUM)
1650 unsigned char *inner_group_loc
1651 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
1653 *inner_group_loc = regnum - this_group_regnum;
1654 BUF_PUSH_3 (stop_memory, this_group_regnum,
1655 regnum - this_group_regnum);
1661 case '|': /* `\|'. */
1662 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
1663 goto normal_backslash;
1665 if (syntax & RE_LIMITED_OPS)
1668 /* Insert before the previous alternative a jump which
1669 jumps to this alternative if the former fails. */
1670 GET_BUFFER_SPACE (3);
1671 INSERT_JUMP (on_failure_jump, begalt, b + 6);
1675 /* The alternative before this one has a jump after it
1676 which gets executed if it gets matched. Adjust that
1677 jump so it will jump to this alternative's analogous
1678 jump (put in below, which in turn will jump to the next
1679 (if any) alternative's such jump, etc.). The last such
1680 jump jumps to the correct final destination. A picture:
1686 If we are at `b', then fixup_alt_jump right now points to a
1687 three-byte space after `a'. We'll put in the jump, set
1688 fixup_alt_jump to right after `b', and leave behind three
1689 bytes which we'll fill in when we get to after `c'. */
1692 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
1694 /* Mark and leave space for a jump after this alternative,
1695 to be filled in later either by next alternative or
1696 when know we're at the end of a series of alternatives. */
1698 GET_BUFFER_SPACE (3);
1707 /* If \{ is a literal. */
1708 if (!(syntax & RE_INTERVALS)
1709 /* If we're at `\{' and it's not the open-interval
1711 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
1712 || (p - 2 == pattern && p == pend))
1713 goto normal_backslash;
1717 /* If got here, then the syntax allows intervals. */
1719 /* At least (most) this many matches must be made. */
1720 int lower_bound = -1, upper_bound = -1;
1722 beg_interval = p - 1;
1726 if (syntax & RE_NO_BK_BRACES)
1727 goto unfetch_interval;
1732 GET_UNSIGNED_NUMBER (lower_bound);
1736 GET_UNSIGNED_NUMBER (upper_bound);
1737 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
1740 /* Interval such as `{1}' => match exactly once. */
1741 upper_bound = lower_bound;
1743 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
1744 || lower_bound > upper_bound)
1746 if (syntax & RE_NO_BK_BRACES)
1747 goto unfetch_interval;
1752 if (!(syntax & RE_NO_BK_BRACES))
1754 if (c != '\\') return REG_EBRACE;
1761 if (syntax & RE_NO_BK_BRACES)
1762 goto unfetch_interval;
1767 /* We just parsed a valid interval. */
1769 /* If it's invalid to have no preceding re. */
1772 if (syntax & RE_CONTEXT_INVALID_OPS)
1774 else if (syntax & RE_CONTEXT_INDEP_OPS)
1777 goto unfetch_interval;
1780 /* If the upper bound is zero, don't want to succeed at
1781 all; jump from `laststart' to `b + 3', which will be
1782 the end of the buffer after we insert the jump. */
1783 if (upper_bound == 0)
1785 GET_BUFFER_SPACE (3);
1786 INSERT_JUMP (jump, laststart, b + 3);
1790 /* Otherwise, we have a nontrivial interval. When
1791 we're all done, the pattern will look like:
1792 set_number_at <jump count> <upper bound>
1793 set_number_at <succeed_n count> <lower bound>
1794 succeed_n <after jump addr> <succed_n count>
1796 jump_n <succeed_n addr> <jump count>
1797 (The upper bound and `jump_n' are omitted if
1798 `upper_bound' is 1, though.) */
1800 { /* If the upper bound is > 1, we need to insert
1801 more at the end of the loop. */
1802 unsigned nbytes = 10 + (upper_bound > 1) * 10;
1804 GET_BUFFER_SPACE (nbytes);
1806 /* Initialize lower bound of the `succeed_n', even
1807 though it will be set during matching by its
1808 attendant `set_number_at' (inserted next),
1809 because `re_compile_fastmap' needs to know.
1810 Jump to the `jump_n' we might insert below. */
1811 INSERT_JUMP2 (succeed_n, laststart,
1812 b + 5 + (upper_bound > 1) * 5,
1816 /* Code to initialize the lower bound. Insert
1817 before the `succeed_n'. The `5' is the last two
1818 bytes of this `set_number_at', plus 3 bytes of
1819 the following `succeed_n'. */
1820 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
1823 if (upper_bound > 1)
1824 { /* More than one repetition is allowed, so
1825 append a backward jump to the `succeed_n'
1826 that starts this interval.
1828 When we've reached this during matching,
1829 we'll have matched the interval once, so
1830 jump back only `upper_bound - 1' times. */
1831 STORE_JUMP2 (jump_n, b, laststart + 5,
1835 /* The location we want to set is the second
1836 parameter of the `jump_n'; that is `b-2' as
1837 an absolute address. `laststart' will be
1838 the `set_number_at' we're about to insert;
1839 `laststart+3' the number to set, the source
1840 for the relative address. But we are
1841 inserting into the middle of the pattern --
1842 so everything is getting moved up by 5.
1843 Conclusion: (b - 2) - (laststart + 3) + 5,
1844 i.e., b - laststart.
1846 We insert this at the beginning of the loop
1847 so that if we fail during matching, we'll
1848 reinitialize the bounds. */
1849 insert_op2 (set_number_at, laststart, b - laststart,
1850 upper_bound - 1, b);
1855 beg_interval = NULL;
1860 /* If an invalid interval, match the characters as literals. */
1861 assert (beg_interval);
1863 beg_interval = NULL;
1865 /* normal_char and normal_backslash need `c'. */
1868 if (!(syntax & RE_NO_BK_BRACES))
1870 if (p > pattern && p[-1] == '\\')
1871 goto normal_backslash;
1876 /* There is no way to specify the before_dot and after_dot
1877 operators. rms says this is ok. --karl */
1885 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
1891 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
1898 BUF_PUSH (wordchar);
1904 BUF_PUSH (notwordchar);
1917 BUF_PUSH (wordbound);
1921 BUF_PUSH (notwordbound);
1932 case '1': case '2': case '3': case '4': case '5':
1933 case '6': case '7': case '8': case '9':
1934 if (syntax & RE_NO_BK_REFS)
1942 /* Can't back reference to a subexpression if inside of it. */
1943 if (group_in_compile_stack (compile_stack, c1))
1947 BUF_PUSH_2 (duplicate, c1);
1953 if (syntax & RE_BK_PLUS_QM)
1956 goto normal_backslash;
1960 /* You might think it would be useful for \ to mean
1961 not to translate; but if we don't translate it
1962 it will never match anything. */
1970 /* Expects the character in `c'. */
1972 /* If no exactn currently being built. */
1975 /* If last exactn not at current position. */
1976 || pending_exact + *pending_exact + 1 != b
1978 /* We have only one byte following the exactn for the count. */
1979 || *pending_exact == (1 << BYTEWIDTH) - 1
1981 /* If followed by a repetition operator. */
1982 || *p == '*' || *p == '^'
1983 || ((syntax & RE_BK_PLUS_QM)
1984 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
1985 : (*p == '+' || *p == '?'))
1986 || ((syntax & RE_INTERVALS)
1987 && ((syntax & RE_NO_BK_BRACES)
1989 : (p[0] == '\\' && p[1] == '{'))))
1991 /* Start building a new exactn. */
1995 BUF_PUSH_2 (exactn, 0);
1996 pending_exact = b - 1;
2003 } /* while p != pend */
2006 /* Through the pattern now. */
2009 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2011 if (!COMPILE_STACK_EMPTY)
2014 free (compile_stack.stack);
2016 /* We have succeeded; set the length of the buffer. */
2017 bufp->used = b - bufp->buffer;
2022 DEBUG_PRINT1 ("\nCompiled pattern: ");
2023 print_compiled_pattern (bufp);
2028 } /* regex_compile */
2030 /* Subroutines for `regex_compile'. */
2032 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2035 store_op1 (op, loc, arg)
2040 *loc = (unsigned char) op;
2041 STORE_NUMBER (loc + 1, arg);
2045 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2048 store_op2 (op, loc, arg1, arg2)
2053 *loc = (unsigned char) op;
2054 STORE_NUMBER (loc + 1, arg1);
2055 STORE_NUMBER (loc + 3, arg2);
2059 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2060 for OP followed by two-byte integer parameter ARG. */
2063 insert_op1 (op, loc, arg, end)
2069 register unsigned char *pfrom = end;
2070 register unsigned char *pto = end + 3;
2072 while (pfrom != loc)
2075 store_op1 (op, loc, arg);
2079 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2082 insert_op2 (op, loc, arg1, arg2, end)
2088 register unsigned char *pfrom = end;
2089 register unsigned char *pto = end + 5;
2091 while (pfrom != loc)
2094 store_op2 (op, loc, arg1, arg2);
2098 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2099 after an alternative or a begin-subexpression. We assume there is at
2100 least one character before the ^. */
2103 at_begline_loc_p (pattern, p, syntax)
2104 const char *pattern, *p;
2105 reg_syntax_t syntax;
2107 const char *prev = p - 2;
2108 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2111 /* After a subexpression? */
2112 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2113 /* After an alternative? */
2114 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2118 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2119 at least one character after the $, i.e., `P < PEND'. */
2122 at_endline_loc_p (p, pend, syntax)
2123 const char *p, *pend;
2126 const char *next = p;
2127 boolean next_backslash = *next == '\\';
2128 const char *next_next = p + 1 < pend ? p + 1 : NULL;
2131 /* Before a subexpression? */
2132 (syntax & RE_NO_BK_PARENS ? *next == ')'
2133 : next_backslash && next_next && *next_next == ')')
2134 /* Before an alternative? */
2135 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2136 : next_backslash && next_next && *next_next == '|');
2140 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2141 false if it's not. */
2144 group_in_compile_stack (compile_stack, regnum)
2145 compile_stack_type compile_stack;
2150 for (this_element = compile_stack.avail - 1;
2153 if (compile_stack.stack[this_element].regnum == regnum)
2160 /* Read the ending character of a range (in a bracket expression) from the
2161 uncompiled pattern *P_PTR (which ends at PEND). We assume the
2162 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2163 Then we set the translation of all bits between the starting and
2164 ending characters (inclusive) in the compiled pattern B.
2166 Return an error code.
2168 We use these short variable names so we can use the same macros as
2169 `regex_compile' itself. */
2171 static reg_errcode_t
2172 compile_range (p_ptr, pend, translate, syntax, b)
2173 const char **p_ptr, *pend;
2175 reg_syntax_t syntax;
2180 const char *p = *p_ptr;
2182 /* Even though the pattern is a signed `char *', we need to fetch into
2183 `unsigned char's. Reason: if the high bit of the pattern character
2184 is set, the range endpoints will be negative if we fetch into a
2186 unsigned char range_end;
2187 unsigned char range_start = p[-2];
2192 PATFETCH (range_end);
2194 /* Have to increment the pointer into the pattern string, so the
2195 caller isn't still at the ending character. */
2198 /* If the start is after the end, the range is empty. */
2199 if (range_start > range_end)
2200 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2202 /* Here we see why `this_char' has to be larger than an `unsigned
2203 char' -- the range is inclusive, so if `range_end' == 0xff
2204 (assuming 8-bit characters), we would otherwise go into an infinite
2205 loop, since all characters <= 0xff. */
2206 for (this_char = range_start; this_char <= range_end; this_char++)
2208 SET_LIST_BIT (TRANSLATE (this_char));
2214 /* Failure stack declarations and macros; both re_compile_fastmap and
2215 re_match_2 use a failure stack. These have to be macros because of
2219 /* Number of failure points for which to initially allocate space
2220 when matching. If this number is exceeded, we allocate more
2221 space, so it is not a hard limit. */
2222 #ifndef INIT_FAILURE_ALLOC
2223 #define INIT_FAILURE_ALLOC 5
2226 /* Roughly the maximum number of failure points on the stack. Would be
2227 exactly that if always used MAX_FAILURE_SPACE each time we failed.
2228 This is a variable only so users of regex can assign to it; we never
2229 change it ourselves. */
2230 int re_max_failures = 2000;
2232 typedef const unsigned char *fail_stack_elt_t;
2236 fail_stack_elt_t *stack;
2238 unsigned avail; /* Offset of next open position. */
2241 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
2242 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2243 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
2244 #define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])
2247 /* Initialize `fail_stack'. Do `return -2' if the alloc fails. */
2249 #define INIT_FAIL_STACK() \
2251 fail_stack.stack = (fail_stack_elt_t *) \
2252 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
2254 if (fail_stack.stack == NULL) \
2257 fail_stack.size = INIT_FAILURE_ALLOC; \
2258 fail_stack.avail = 0; \
2262 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
2264 Return 1 if succeeds, and 0 if either ran out of memory
2265 allocating space for it or it was already too large.
2267 REGEX_REALLOCATE requires `destination' be declared. */
2269 #define DOUBLE_FAIL_STACK(fail_stack) \
2270 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
2272 : ((fail_stack).stack = (fail_stack_elt_t *) \
2273 REGEX_REALLOCATE ((fail_stack).stack, \
2274 (fail_stack).size * sizeof (fail_stack_elt_t), \
2275 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
2277 (fail_stack).stack == NULL \
2279 : ((fail_stack).size <<= 1, \
2283 /* Push PATTERN_OP on FAIL_STACK.
2285 Return 1 if was able to do so and 0 if ran out of memory allocating
2287 #define PUSH_PATTERN_OP(pattern_op, fail_stack) \
2288 ((FAIL_STACK_FULL () \
2289 && !DOUBLE_FAIL_STACK (fail_stack)) \
2291 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \
2294 /* This pushes an item onto the failure stack. Must be a four-byte
2295 value. Assumes the variable `fail_stack'. Probably should only
2296 be called from within `PUSH_FAILURE_POINT'. */
2297 #define PUSH_FAILURE_ITEM(item) \
2298 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2300 /* The complement operation. Assumes `fail_stack' is nonempty. */
2301 #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2303 /* Used to omit pushing failure point id's when we're not debugging. */
2305 #define DEBUG_PUSH PUSH_FAILURE_ITEM
2306 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2308 #define DEBUG_PUSH(item)
2309 #define DEBUG_POP(item_addr)
2313 /* Push the information about the state we will need
2314 if we ever fail back to it.
2316 Requires variables fail_stack, regstart, regend, reg_info, and
2317 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
2320 Does `return FAILURE_CODE' if runs out of memory. */
2322 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
2324 char *destination; \
2325 /* Must be int, so when we don't save any registers, the arithmetic \
2326 of 0 + -1 isn't done as unsigned. */ \
2329 DEBUG_STATEMENT (failure_id++); \
2330 DEBUG_STATEMENT (nfailure_points_pushed++); \
2331 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
2332 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
2333 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
2335 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
2336 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
2338 /* Ensure we have enough space allocated for what we will push. */ \
2339 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
2341 if (!DOUBLE_FAIL_STACK (fail_stack)) \
2342 return failure_code; \
2344 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
2345 (fail_stack).size); \
2346 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2349 /* Push the info, starting with the registers. */ \
2350 DEBUG_PRINT1 ("\n"); \
2352 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
2355 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
2356 DEBUG_STATEMENT (num_regs_pushed++); \
2358 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2359 PUSH_FAILURE_ITEM (regstart[this_reg]); \
2361 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2362 PUSH_FAILURE_ITEM (regend[this_reg]); \
2364 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
2365 DEBUG_PRINT2 (" match_null=%d", \
2366 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
2367 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
2368 DEBUG_PRINT2 (" matched_something=%d", \
2369 MATCHED_SOMETHING (reg_info[this_reg])); \
2370 DEBUG_PRINT2 (" ever_matched=%d", \
2371 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
2372 DEBUG_PRINT1 ("\n"); \
2373 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \
2376 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
2377 PUSH_FAILURE_ITEM (lowest_active_reg); \
2379 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
2380 PUSH_FAILURE_ITEM (highest_active_reg); \
2382 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
2383 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
2384 PUSH_FAILURE_ITEM (pattern_place); \
2386 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
2387 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
2389 DEBUG_PRINT1 ("'\n"); \
2390 PUSH_FAILURE_ITEM (string_place); \
2392 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
2393 DEBUG_PUSH (failure_id); \
2396 /* This is the number of items that are pushed and popped on the stack
2397 for each register. */
2398 #define NUM_REG_ITEMS 3
2400 /* Individual items aside from the registers. */
2402 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
2404 #define NUM_NONREG_ITEMS 4
2407 /* We push at most this many items on the stack. */
2408 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2410 /* We actually push this many items. */
2411 #define NUM_FAILURE_ITEMS \
2412 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
2415 /* How many items can still be added to the stack without overflowing it. */
2416 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2419 /* Pops what PUSH_FAIL_STACK pushes.
2421 We restore into the parameters, all of which should be lvalues:
2422 STR -- the saved data position.
2423 PAT -- the saved pattern position.
2424 LOW_REG, HIGH_REG -- the highest and lowest active registers.
2425 REGSTART, REGEND -- arrays of string positions.
2426 REG_INFO -- array of information about each subexpression.
2428 Also assumes the variables `fail_stack' and (if debugging), `bufp',
2429 `pend', `string1', `size1', `string2', and `size2'. */
2431 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2433 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
2435 const unsigned char *string_temp; \
2437 assert (!FAIL_STACK_EMPTY ()); \
2439 /* Remove failure points and point to how many regs pushed. */ \
2440 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
2441 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
2442 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
2444 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
2446 DEBUG_POP (&failure_id); \
2447 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
2449 /* If the saved string location is NULL, it came from an \
2450 on_failure_keep_string_jump opcode, and we want to throw away the \
2451 saved NULL, thus retaining our current position in the string. */ \
2452 string_temp = POP_FAILURE_ITEM (); \
2453 if (string_temp != NULL) \
2454 str = (const char *) string_temp; \
2456 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
2457 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
2458 DEBUG_PRINT1 ("'\n"); \
2460 pat = (unsigned char *) POP_FAILURE_ITEM (); \
2461 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
2462 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
2464 /* Restore register info. */ \
2465 high_reg = (unsigned) POP_FAILURE_ITEM (); \
2466 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
2468 low_reg = (unsigned) POP_FAILURE_ITEM (); \
2469 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
2471 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
2473 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
2475 reg_info[this_reg].word = POP_FAILURE_ITEM (); \
2476 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
2478 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2479 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2481 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2482 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2485 DEBUG_STATEMENT (nfailure_points_popped++); \
2486 } /* POP_FAILURE_POINT */
2488 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2489 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2490 characters can start a string that matches the pattern. This fastmap
2491 is used by re_search to skip quickly over impossible starting points.
2493 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2494 area as BUFP->fastmap.
2496 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2499 Returns 0 if we succeed, -2 if an internal error. */
2502 re_compile_fastmap (bufp)
2503 struct re_pattern_buffer *bufp;
2506 fail_stack_type fail_stack;
2507 #ifndef REGEX_MALLOC
2510 /* We don't push any register information onto the failure stack. */
2511 unsigned num_regs = 0;
2513 register char *fastmap = bufp->fastmap;
2514 unsigned char *pattern = bufp->buffer;
2515 unsigned long size = bufp->used;
2516 const unsigned char *p = pattern;
2517 register unsigned char *pend = pattern + size;
2519 /* Assume that each path through the pattern can be null until
2520 proven otherwise. We set this false at the bottom of switch
2521 statement, to which we get only if a particular path doesn't
2522 match the empty string. */
2523 boolean path_can_be_null = true;
2525 /* We aren't doing a `succeed_n' to begin with. */
2526 boolean succeed_n_p = false;
2528 assert (fastmap != NULL && p != NULL);
2531 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
2532 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2533 bufp->can_be_null = 0;
2535 while (p != pend || !FAIL_STACK_EMPTY ())
2539 bufp->can_be_null |= path_can_be_null;
2541 /* Reset for next path. */
2542 path_can_be_null = true;
2544 p = fail_stack.stack[--fail_stack.avail];
2547 /* We should never be about to go beyond the end of the pattern. */
2550 #ifdef SWITCH_ENUM_BUG
2551 switch ((int) ((re_opcode_t) *p++))
2553 switch ((re_opcode_t) *p++)
2557 /* I guess the idea here is to simply not bother with a fastmap
2558 if a backreference is used, since it's too hard to figure out
2559 the fastmap for the corresponding group. Setting
2560 `can_be_null' stops `re_search_2' from using the fastmap, so
2561 that is all we do. */
2563 bufp->can_be_null = 1;
2567 /* Following are the cases which match a character. These end
2576 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2577 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2583 /* Chars beyond end of map must be allowed. */
2584 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2587 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2588 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2594 for (j = 0; j < (1 << BYTEWIDTH); j++)
2595 if (SYNTAX (j) == Sword)
2601 for (j = 0; j < (1 << BYTEWIDTH); j++)
2602 if (SYNTAX (j) != Sword)
2608 /* `.' matches anything ... */
2609 for (j = 0; j < (1 << BYTEWIDTH); j++)
2612 /* ... except perhaps newline. */
2613 if (!(bufp->syntax & RE_DOT_NEWLINE))
2616 /* Return if we have already set `can_be_null'; if we have,
2617 then the fastmap is irrelevant. Something's wrong here. */
2618 else if (bufp->can_be_null)
2621 /* Otherwise, have to check alternative paths. */
2628 for (j = 0; j < (1 << BYTEWIDTH); j++)
2629 if (SYNTAX (j) == (enum syntaxcode) k)
2636 for (j = 0; j < (1 << BYTEWIDTH); j++)
2637 if (SYNTAX (j) != (enum syntaxcode) k)
2642 /* All cases after this match the empty string. These end with
2650 #endif /* not emacs */
2662 case push_dummy_failure:
2667 case pop_failure_jump:
2668 case maybe_pop_jump:
2671 case dummy_failure_jump:
2672 EXTRACT_NUMBER_AND_INCR (j, p);
2677 /* Jump backward implies we just went through the body of a
2678 loop and matched nothing. Opcode jumped to should be
2679 `on_failure_jump' or `succeed_n'. Just treat it like an
2680 ordinary jump. For a * loop, it has pushed its failure
2681 point already; if so, discard that as redundant. */
2682 if ((re_opcode_t) *p != on_failure_jump
2683 && (re_opcode_t) *p != succeed_n)
2687 EXTRACT_NUMBER_AND_INCR (j, p);
2690 /* If what's on the stack is where we are now, pop it. */
2691 if (!FAIL_STACK_EMPTY ()
2692 && fail_stack.stack[fail_stack.avail - 1] == p)
2698 case on_failure_jump:
2699 case on_failure_keep_string_jump:
2700 handle_on_failure_jump:
2701 EXTRACT_NUMBER_AND_INCR (j, p);
2703 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2704 end of the pattern. We don't want to push such a point,
2705 since when we restore it above, entering the switch will
2706 increment `p' past the end of the pattern. We don't need
2707 to push such a point since we obviously won't find any more
2708 fastmap entries beyond `pend'. Such a pattern can match
2709 the null string, though. */
2712 if (!PUSH_PATTERN_OP (p + j, fail_stack))
2716 bufp->can_be_null = 1;
2720 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
2721 succeed_n_p = false;
2728 /* Get to the number of times to succeed. */
2731 /* Increment p past the n for when k != 0. */
2732 EXTRACT_NUMBER_AND_INCR (k, p);
2736 succeed_n_p = true; /* Spaghetti code alert. */
2737 goto handle_on_failure_jump;
2754 abort (); /* We have listed all the cases. */
2757 /* Getting here means we have found the possible starting
2758 characters for one path of the pattern -- and that the empty
2759 string does not match. We need not follow this path further.
2760 Instead, look at the next alternative (remembered on the
2761 stack), or quit if no more. The test at the top of the loop
2762 does these things. */
2763 path_can_be_null = false;
2767 /* Set `can_be_null' for the last path (also the first path, if the
2768 pattern is empty). */
2769 bufp->can_be_null |= path_can_be_null;
2771 } /* re_compile_fastmap */
2773 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
2774 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
2775 this memory for recording register information. STARTS and ENDS
2776 must be allocated using the malloc library routine, and must each
2777 be at least NUM_REGS * sizeof (regoff_t) bytes long.
2779 If NUM_REGS == 0, then subsequent matches should allocate their own
2782 Unless this function is called, the first search or match using
2783 PATTERN_BUFFER will allocate its own register data, without
2784 freeing the old data. */
2787 re_set_registers (bufp, regs, num_regs, starts, ends)
2788 struct re_pattern_buffer *bufp;
2789 struct re_registers *regs;
2791 regoff_t *starts, *ends;
2795 bufp->regs_allocated = REGS_REALLOCATE;
2796 regs->num_regs = num_regs;
2797 regs->start = starts;
2802 bufp->regs_allocated = REGS_UNALLOCATED;
2804 regs->start = regs->end = (regoff_t) 0;
2808 /* Searching routines. */
2810 /* Like re_search_2, below, but only one string is specified, and
2811 doesn't let you say where to stop matching. */
2814 re_search (bufp, string, size, startpos, range, regs)
2815 struct re_pattern_buffer *bufp;
2817 int size, startpos, range;
2818 struct re_registers *regs;
2820 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
2825 /* Using the compiled pattern in BUFP->buffer, first tries to match the
2826 virtual concatenation of STRING1 and STRING2, starting first at index
2827 STARTPOS, then at STARTPOS + 1, and so on.
2829 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
2831 RANGE is how far to scan while trying to match. RANGE = 0 means try
2832 only at STARTPOS; in general, the last start tried is STARTPOS +
2835 In REGS, return the indices of the virtual concatenation of STRING1
2836 and STRING2 that matched the entire BUFP->buffer and its contained
2839 Do not consider matching one past the index STOP in the virtual
2840 concatenation of STRING1 and STRING2.
2842 We return either the position in the strings at which the match was
2843 found, -1 if no match, or -2 if error (such as failure
2847 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
2848 struct re_pattern_buffer *bufp;
2849 const char *string1, *string2;
2853 struct re_registers *regs;
2857 register char *fastmap = bufp->fastmap;
2858 register char *translate = bufp->translate;
2859 int total_size = size1 + size2;
2860 int endpos = startpos + range;
2862 /* Check for out-of-range STARTPOS. */
2863 if (startpos < 0 || startpos > total_size)
2866 /* Fix up RANGE if it might eventually take us outside
2867 the virtual concatenation of STRING1 and STRING2. */
2869 range = -1 - startpos;
2870 else if (endpos > total_size)
2871 range = total_size - startpos;
2873 /* If the search isn't to be a backwards one, don't waste time in a
2874 search for a pattern that must be anchored. */
2875 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
2883 /* Update the fastmap now if not correct already. */
2884 if (fastmap && !bufp->fastmap_accurate)
2885 if (re_compile_fastmap (bufp) == -2)
2888 /* Loop through the string, looking for a place to start matching. */
2891 /* If a fastmap is supplied, skip quickly over characters that
2892 cannot be the start of a match. If the pattern can match the
2893 null string, however, we don't need to skip characters; we want
2894 the first null string. */
2895 if (fastmap && startpos < total_size && !bufp->can_be_null)
2897 if (range > 0) /* Searching forwards. */
2899 register const char *d;
2900 register int lim = 0;
2903 if (startpos < size1 && startpos + range >= size1)
2904 lim = range - (size1 - startpos);
2906 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
2908 /* Written out as an if-else to avoid testing `translate'
2912 && !fastmap[(unsigned char) translate[*d++]])
2915 while (range > lim && !fastmap[(unsigned char) *d++])
2918 startpos += irange - range;
2920 else /* Searching backwards. */
2922 register char c = (size1 == 0 || startpos >= size1
2923 ? string2[startpos - size1]
2924 : string1[startpos]);
2926 if (!fastmap[(unsigned char) TRANSLATE (c)])
2931 /* If can't match the null string, and that's all we have left, fail. */
2932 if (range >= 0 && startpos == total_size && fastmap
2933 && !bufp->can_be_null)
2936 val = re_match_2 (bufp, string1, size1, string2, size2,
2937 startpos, regs, stop);
2961 /* Declarations and macros for re_match_2. */
2963 static int bcmp_translate ();
2964 static boolean alt_match_null_string_p (),
2965 common_op_match_null_string_p (),
2966 group_match_null_string_p ();
2968 /* Structure for per-register (a.k.a. per-group) information.
2969 This must not be longer than one word, because we push this value
2970 onto the failure stack. Other register information, such as the
2971 starting and ending positions (which are addresses), and the list of
2972 inner groups (which is a bits list) are maintained in separate
2975 We are making a (strictly speaking) nonportable assumption here: that
2976 the compiler will pack our bit fields into something that fits into
2977 the type of `word', i.e., is something that fits into one item on the
2981 fail_stack_elt_t word;
2984 /* This field is one if this group can match the empty string,
2985 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
2986 #define MATCH_NULL_UNSET_VALUE 3
2987 unsigned match_null_string_p : 2;
2988 unsigned is_active : 1;
2989 unsigned matched_something : 1;
2990 unsigned ever_matched_something : 1;
2992 } register_info_type;
2994 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
2995 #define IS_ACTIVE(R) ((R).bits.is_active)
2996 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
2997 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
3000 /* Call this when have matched a real character; it sets `matched' flags
3001 for the subexpressions which we are currently inside. Also records
3002 that those subexprs have matched. */
3003 #define SET_REGS_MATCHED() \
3007 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
3009 MATCHED_SOMETHING (reg_info[r]) \
3010 = EVER_MATCHED_SOMETHING (reg_info[r]) \
3017 /* This converts PTR, a pointer into one of the search strings `string1'
3018 and `string2' into an offset from the beginning of that string. */
3019 #define POINTER_TO_OFFSET(ptr) \
3020 (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
3022 /* Registers are set to a sentinel when they haven't yet matched. */
3023 #define REG_UNSET_VALUE ((char *) -1)
3024 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
3027 /* Macros for dealing with the split strings in re_match_2. */
3029 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3031 /* Call before fetching a character with *d. This switches over to
3032 string2 if necessary. */
3033 #define PREFETCH() \
3036 /* End of string2 => fail. */ \
3037 if (dend == end_match_2) \
3039 /* End of string1 => advance to string2. */ \
3041 dend = end_match_2; \
3045 /* Test if at very beginning or at very end of the virtual concatenation
3046 of `string1' and `string2'. If only one string, it's `string2'. */
3047 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3048 #define AT_STRINGS_END(d) ((d) == end2)
3051 /* Test if D points to a character which is word-constituent. We have
3052 two special cases to check for: if past the end of string1, look at
3053 the first character in string2; and if before the beginning of
3054 string2, look at the last character in string1. */
3055 #define WORDCHAR_P(d) \
3056 (SYNTAX ((d) == end1 ? *string2 \
3057 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3060 /* Test if the character before D and the one at D differ with respect
3061 to being word-constituent. */
3062 #define AT_WORD_BOUNDARY(d) \
3063 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3064 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3067 /* Free everything we malloc. */
3069 #define FREE_VAR(var) if (var) free (var); var = NULL
3070 #define FREE_VARIABLES() \
3072 FREE_VAR (fail_stack.stack); \
3073 FREE_VAR (regstart); \
3074 FREE_VAR (regend); \
3075 FREE_VAR (old_regstart); \
3076 FREE_VAR (old_regend); \
3077 FREE_VAR (best_regstart); \
3078 FREE_VAR (best_regend); \
3079 FREE_VAR (reg_info); \
3080 FREE_VAR (reg_dummy); \
3081 FREE_VAR (reg_info_dummy); \
3083 #else /* not REGEX_MALLOC */
3084 /* Some MIPS systems (at least) want this to free alloca'd storage. */
3085 #define FREE_VARIABLES() alloca (0)
3086 #endif /* not REGEX_MALLOC */
3089 /* These values must meet several constraints. They must not be valid
3090 register values; since we have a limit of 255 registers (because
3091 we use only one byte in the pattern for the register number), we can
3092 use numbers larger than 255. They must differ by 1, because of
3093 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3094 be larger than the value for the highest register, so we do not try
3095 to actually save any registers when none are active. */
3096 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3097 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3099 /* Matching routines. */
3101 #ifndef emacs /* Emacs never uses this. */
3102 /* re_match is like re_match_2 except it takes only a single string. */
3105 re_match (bufp, string, size, pos, regs)
3106 struct re_pattern_buffer *bufp;
3109 struct re_registers *regs;
3111 return re_match_2 (bufp, NULL, 0, string, size, pos, regs, size);
3113 #endif /* not emacs */
3116 /* re_match_2 matches the compiled pattern in BUFP against the
3117 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3118 and SIZE2, respectively). We start matching at POS, and stop
3121 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3122 store offsets for the substring each group matched in REGS. See the
3123 documentation for exactly how many groups we fill.
3125 We return -1 if no match, -2 if an internal error (such as the
3126 failure stack overflowing). Otherwise, we return the length of the
3127 matched substring. */
3130 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3131 struct re_pattern_buffer *bufp;
3132 const char *string1, *string2;
3135 struct re_registers *regs;
3138 /* General temporaries. */
3142 /* Just past the end of the corresponding string. */
3143 const char *end1, *end2;
3145 /* Pointers into string1 and string2, just past the last characters in
3146 each to consider matching. */
3147 const char *end_match_1, *end_match_2;
3149 /* Where we are in the data, and the end of the current string. */
3150 const char *d, *dend;
3152 /* Where we are in the pattern, and the end of the pattern. */
3153 unsigned char *p = bufp->buffer;
3154 register unsigned char *pend = p + bufp->used;
3156 /* We use this to map every character in the string. */
3157 char *translate = bufp->translate;
3159 /* Failure point stack. Each place that can handle a failure further
3160 down the line pushes a failure point on this stack. It consists of
3161 restart, regend, and reg_info for all registers corresponding to
3162 the subexpressions we're currently inside, plus the number of such
3163 registers, and, finally, two char *'s. The first char * is where
3164 to resume scanning the pattern; the second one is where to resume
3165 scanning the strings. If the latter is zero, the failure point is
3166 a ``dummy''; if a failure happens and the failure point is a dummy,
3167 it gets discarded and the next next one is tried. */
3168 fail_stack_type fail_stack;
3170 static unsigned failure_id = 0;
3171 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3174 /* We fill all the registers internally, independent of what we
3175 return, for use in backreferences. The number here includes
3176 an element for register zero. */
3177 unsigned num_regs = bufp->re_nsub + 1;
3179 /* The currently active registers. */
3180 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3181 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3183 /* Information on the contents of registers. These are pointers into
3184 the input strings; they record just what was matched (on this
3185 attempt) by a subexpression part of the pattern, that is, the
3186 regnum-th regstart pointer points to where in the pattern we began
3187 matching and the regnum-th regend points to right after where we
3188 stopped matching the regnum-th subexpression. (The zeroth register
3189 keeps track of what the whole pattern matches.) */
3190 const char **regstart, **regend;
3192 /* If a group that's operated upon by a repetition operator fails to
3193 match anything, then the register for its start will need to be
3194 restored because it will have been set to wherever in the string we
3195 are when we last see its open-group operator. Similarly for a
3197 const char **old_regstart, **old_regend;
3199 /* The is_active field of reg_info helps us keep track of which (possibly
3200 nested) subexpressions we are currently in. The matched_something
3201 field of reg_info[reg_num] helps us tell whether or not we have
3202 matched any of the pattern so far this time through the reg_num-th
3203 subexpression. These two fields get reset each time through any
3204 loop their register is in. */
3205 register_info_type *reg_info;
3207 /* The following record the register info as found in the above
3208 variables when we find a match better than any we've seen before.
3209 This happens as we backtrack through the failure points, which in
3210 turn happens only if we have not yet matched the entire string. */
3211 unsigned best_regs_set = false;
3212 const char **best_regstart, **best_regend;
3214 /* Logically, this is `best_regend[0]'. But we don't want to have to
3215 allocate space for that if we're not allocating space for anything
3216 else (see below). Also, we never need info about register 0 for
3217 any of the other register vectors, and it seems rather a kludge to
3218 treat `best_regend' differently than the rest. So we keep track of
3219 the end of the best match so far in a separate variable. We
3220 initialize this to NULL so that when we backtrack the first time
3221 and need to test it, it's not garbage. */
3222 const char *match_end = NULL;
3224 /* Used when we pop values we don't care about. */
3225 const char **reg_dummy;
3226 register_info_type *reg_info_dummy;
3229 /* Counts the total number of registers pushed. */
3230 unsigned num_regs_pushed = 0;
3233 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3237 /* Do not bother to initialize all the register variables if there are
3238 no groups in the pattern, as it takes a fair amount of time. If
3239 there are groups, we include space for register 0 (the whole
3240 pattern), even though we never use it, since it simplifies the
3241 array indexing. We should fix this. */
3244 regstart = REGEX_TALLOC (num_regs, const char *);
3245 regend = REGEX_TALLOC (num_regs, const char *);
3246 old_regstart = REGEX_TALLOC (num_regs, const char *);
3247 old_regend = REGEX_TALLOC (num_regs, const char *);
3248 best_regstart = REGEX_TALLOC (num_regs, const char *);
3249 best_regend = REGEX_TALLOC (num_regs, const char *);
3250 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3251 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3252 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3254 if (!(regstart && regend && old_regstart && old_regend && reg_info
3255 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3264 /* We must initialize all our variables to NULL, so that
3265 `FREE_VARIABLES' doesn't try to free them. */
3266 regstart = regend = old_regstart = old_regend = best_regstart
3267 = best_regend = reg_dummy = NULL;
3268 reg_info = reg_info_dummy = (register_info_type *) NULL;
3270 #endif /* REGEX_MALLOC */
3272 /* The starting position is bogus. */
3273 if (pos < 0 || pos > size1 + size2)
3279 /* Initialize subexpression text positions to -1 to mark ones that no
3280 start_memory/stop_memory has been seen for. Also initialize the
3281 register information struct. */
3282 for (mcnt = 1; mcnt < num_regs; mcnt++)
3284 regstart[mcnt] = regend[mcnt]
3285 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3287 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3288 IS_ACTIVE (reg_info[mcnt]) = 0;
3289 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3290 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3293 /* We move `string1' into `string2' if the latter's empty -- but not if
3294 `string1' is null. */
3295 if (size2 == 0 && string1 != NULL)
3302 end1 = string1 + size1;
3303 end2 = string2 + size2;
3305 /* Compute where to stop matching, within the two strings. */
3308 end_match_1 = string1 + stop;
3309 end_match_2 = string2;
3314 end_match_2 = string2 + stop - size1;
3317 /* `p' scans through the pattern as `d' scans through the data.
3318 `dend' is the end of the input string that `d' points within. `d'
3319 is advanced into the following input string whenever necessary, but
3320 this happens before fetching; therefore, at the beginning of the
3321 loop, `d' can be pointing at the end of a string, but it cannot
3323 if (size1 > 0 && pos <= size1)
3330 d = string2 + pos - size1;
3334 DEBUG_PRINT1 ("The compiled pattern is: ");
3335 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3336 DEBUG_PRINT1 ("The string to match is: `");
3337 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3338 DEBUG_PRINT1 ("'\n");
3340 /* This loops over pattern commands. It exits by returning from the
3341 function if the match is complete, or it drops through if the match
3342 fails at this starting point in the input data. */
3345 DEBUG_PRINT2 ("\n0x%x: ", p);
3348 { /* End of pattern means we might have succeeded. */
3349 DEBUG_PRINT1 ("end of pattern ... ");
3351 /* If we haven't matched the entire string, and we want the
3352 longest match, try backtracking. */
3353 if (d != end_match_2)
3355 DEBUG_PRINT1 ("backtracking.\n");
3357 if (!FAIL_STACK_EMPTY ())
3358 { /* More failure points to try. */
3359 boolean same_str_p = (FIRST_STRING_P (match_end)
3360 == MATCHING_IN_FIRST_STRING);
3362 /* If exceeds best match so far, save it. */
3364 || (same_str_p && d > match_end)
3365 || (!same_str_p && !MATCHING_IN_FIRST_STRING))
3367 best_regs_set = true;
3370 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3372 for (mcnt = 1; mcnt < num_regs; mcnt++)
3374 best_regstart[mcnt] = regstart[mcnt];
3375 best_regend[mcnt] = regend[mcnt];
3381 /* If no failure points, don't restore garbage. */
3382 else if (best_regs_set)
3385 /* Restore best match. It may happen that `dend ==
3386 end_match_1' while the restored d is in string2.
3387 For example, the pattern `x.*y.*z' against the
3388 strings `x-' and `y-z-', if the two strings are
3389 not consecutive in memory. */
3390 DEBUG_PRINT1 ("Restoring best registers.\n");
3393 dend = ((d >= string1 && d <= end1)
3394 ? end_match_1 : end_match_2);
3396 for (mcnt = 1; mcnt < num_regs; mcnt++)
3398 regstart[mcnt] = best_regstart[mcnt];
3399 regend[mcnt] = best_regend[mcnt];
3402 } /* d != end_match_2 */
3404 DEBUG_PRINT1 ("Accepting match.\n");
3406 /* If caller wants register contents data back, do it. */
3407 if (regs && !bufp->no_sub)
3409 /* Have the register data arrays been allocated? */
3410 if (bufp->regs_allocated == REGS_UNALLOCATED)
3411 { /* No. So allocate them with malloc. We need one
3412 extra element beyond `num_regs' for the `-1' marker
3414 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3415 regs->start = TALLOC (regs->num_regs, regoff_t);
3416 regs->end = TALLOC (regs->num_regs, regoff_t);
3417 if (regs->start == NULL || regs->end == NULL)
3419 bufp->regs_allocated = REGS_REALLOCATE;
3421 else if (bufp->regs_allocated == REGS_REALLOCATE)
3422 { /* Yes. If we need more elements than were already
3423 allocated, reallocate them. If we need fewer, just
3425 if (regs->num_regs < num_regs + 1)
3427 regs->num_regs = num_regs + 1;
3428 RETALLOC (regs->start, regs->num_regs, regoff_t);
3429 RETALLOC (regs->end, regs->num_regs, regoff_t);
3430 if (regs->start == NULL || regs->end == NULL)
3435 assert (bufp->regs_allocated == REGS_FIXED);
3437 /* Convert the pointer data in `regstart' and `regend' to
3438 indices. Register zero has to be set differently,
3439 since we haven't kept track of any info for it. */
3440 if (regs->num_regs > 0)
3442 regs->start[0] = pos;
3443 regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
3444 : d - string2 + size1);
3447 /* Go through the first `min (num_regs, regs->num_regs)'
3448 registers, since that is all we initialized. */
3449 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
3451 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3452 regs->start[mcnt] = regs->end[mcnt] = -1;
3455 regs->start[mcnt] = POINTER_TO_OFFSET (regstart[mcnt]);
3456 regs->end[mcnt] = POINTER_TO_OFFSET (regend[mcnt]);
3460 /* If the regs structure we return has more elements than
3461 were in the pattern, set the extra elements to -1. If
3462 we (re)allocated the registers, this is the case,
3463 because we always allocate enough to have at least one
3465 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3466 regs->start[mcnt] = regs->end[mcnt] = -1;
3467 } /* regs && !bufp->no_sub */
3470 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3471 nfailure_points_pushed, nfailure_points_popped,
3472 nfailure_points_pushed - nfailure_points_popped);
3473 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3475 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3479 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3484 /* Otherwise match next pattern command. */
3485 #ifdef SWITCH_ENUM_BUG
3486 switch ((int) ((re_opcode_t) *p++))
3488 switch ((re_opcode_t) *p++)
3491 /* Ignore these. Used to ignore the n of succeed_n's which
3492 currently have n == 0. */
3494 DEBUG_PRINT1 ("EXECUTING no_op.\n");
3498 /* Match the next n pattern characters exactly. The following
3499 byte in the pattern defines n, and the n bytes after that
3500 are the characters to match. */
3503 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3505 /* This is written out as an if-else so we don't waste time
3506 testing `translate' inside the loop. */
3512 if (translate[(unsigned char) *d++] != (char) *p++)
3522 if (*d++ != (char) *p++) goto fail;
3526 SET_REGS_MATCHED ();
3530 /* Match any character except possibly a newline or a null. */
3532 DEBUG_PRINT1 ("EXECUTING anychar.\n");
3536 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
3537 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
3540 SET_REGS_MATCHED ();
3541 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
3549 register unsigned char c;
3550 boolean not = (re_opcode_t) *(p - 1) == charset_not;
3552 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
3555 c = TRANSLATE (*d); /* The character to match. */
3557 /* Cast to `unsigned' instead of `unsigned char' in case the
3558 bit list is a full 32 bytes long. */
3559 if (c < (unsigned) (*p * BYTEWIDTH)
3560 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3565 if (!not) goto fail;
3567 SET_REGS_MATCHED ();
3573 /* The beginning of a group is represented by start_memory.
3574 The arguments are the register number in the next byte, and the
3575 number of groups inner to this one in the next. The text
3576 matched within the group is recorded (in the internal
3577 registers data structure) under the register number. */
3579 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3581 /* Find out if this group can match the empty string. */
3582 p1 = p; /* To send to group_match_null_string_p. */
3584 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3585 REG_MATCH_NULL_STRING_P (reg_info[*p])
3586 = group_match_null_string_p (&p1, pend, reg_info);
3588 /* Save the position in the string where we were the last time
3589 we were at this open-group operator in case the group is
3590 operated upon by a repetition operator, e.g., with `(a*)*b'
3591 against `ab'; then we want to ignore where we are now in
3592 the string in case this attempt to match fails. */
3593 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3594 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
3596 DEBUG_PRINT2 (" old_regstart: %d\n",
3597 POINTER_TO_OFFSET (old_regstart[*p]));
3600 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
3602 IS_ACTIVE (reg_info[*p]) = 1;
3603 MATCHED_SOMETHING (reg_info[*p]) = 0;
3605 /* This is the new highest active register. */
3606 highest_active_reg = *p;
3608 /* If nothing was active before, this is the new lowest active
3610 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3611 lowest_active_reg = *p;
3613 /* Move past the register number and inner group count. */
3618 /* The stop_memory opcode represents the end of a group. Its
3619 arguments are the same as start_memory's: the register
3620 number, and the number of inner groups. */
3622 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
3624 /* We need to save the string position the last time we were at
3625 this close-group operator in case the group is operated
3626 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3627 against `aba'; then we want to ignore where we are now in
3628 the string in case this attempt to match fails. */
3629 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3630 ? REG_UNSET (regend[*p]) ? d : regend[*p]
3632 DEBUG_PRINT2 (" old_regend: %d\n",
3633 POINTER_TO_OFFSET (old_regend[*p]));
3636 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
3638 /* This register isn't active anymore. */
3639 IS_ACTIVE (reg_info[*p]) = 0;
3641 /* If this was the only register active, nothing is active
3643 if (lowest_active_reg == highest_active_reg)
3645 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3646 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3649 { /* We must scan for the new highest active register, since
3650 it isn't necessarily one less than now: consider
3651 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
3652 new highest active register is 1. */
3653 unsigned char r = *p - 1;
3654 while (r > 0 && !IS_ACTIVE (reg_info[r]))
3657 /* If we end up at register zero, that means that we saved
3658 the registers as the result of an `on_failure_jump', not
3659 a `start_memory', and we jumped to past the innermost
3660 `stop_memory'. For example, in ((.)*) we save
3661 registers 1 and 2 as a result of the *, but when we pop
3662 back to the second ), we are at the stop_memory 1.
3663 Thus, nothing is active. */
3666 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3667 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3670 highest_active_reg = r;
3673 /* If just failed to match something this time around with a
3674 group that's operated on by a repetition operator, try to
3675 force exit from the ``loop'', and restore the register
3676 information for this group that we had before trying this
3678 if ((!MATCHED_SOMETHING (reg_info[*p])
3679 || (re_opcode_t) p[-3] == start_memory)
3682 boolean is_a_jump_n = false;
3686 switch ((re_opcode_t) *p1++)
3690 case pop_failure_jump:
3691 case maybe_pop_jump:
3693 case dummy_failure_jump:
3694 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3704 /* If the next operation is a jump backwards in the pattern
3705 to an on_failure_jump right before the start_memory
3706 corresponding to this stop_memory, exit from the loop
3707 by forcing a failure after pushing on the stack the
3708 on_failure_jump's jump in the pattern, and d. */
3709 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
3710 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
3712 /* If this group ever matched anything, then restore
3713 what its registers were before trying this last
3714 failed match, e.g., with `(a*)*b' against `ab' for
3715 regstart[1], and, e.g., with `((a*)*(b*)*)*'
3716 against `aba' for regend[3].
3718 Also restore the registers for inner groups for,
3719 e.g., `((a*)(b*))*' against `aba' (register 3 would
3720 otherwise get trashed). */
3722 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
3726 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
3728 /* Restore this and inner groups' (if any) registers. */
3729 for (r = *p; r < *p + *(p + 1); r++)
3731 regstart[r] = old_regstart[r];
3733 /* xx why this test? */
3734 if ((int) old_regend[r] >= (int) regstart[r])
3735 regend[r] = old_regend[r];
3739 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3740 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
3746 /* Move past the register number and the inner group count. */
3751 /* \<digit> has been turned into a `duplicate' command which is
3752 followed by the numeric value of <digit> as the register number. */
3755 register const char *d2, *dend2;
3756 int regno = *p++; /* Get which register to match against. */
3757 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
3759 /* Can't back reference a group which we've never matched. */
3760 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
3763 /* Where in input to try to start matching. */
3764 d2 = regstart[regno];
3766 /* Where to stop matching; if both the place to start and
3767 the place to stop matching are in the same string, then
3768 set to the place to stop, otherwise, for now have to use
3769 the end of the first string. */
3771 dend2 = ((FIRST_STRING_P (regstart[regno])
3772 == FIRST_STRING_P (regend[regno]))
3773 ? regend[regno] : end_match_1);
3776 /* If necessary, advance to next segment in register
3780 if (dend2 == end_match_2) break;
3781 if (dend2 == regend[regno]) break;
3783 /* End of string1 => advance to string2. */
3785 dend2 = regend[regno];
3787 /* At end of register contents => success */
3788 if (d2 == dend2) break;
3790 /* If necessary, advance to next segment in data. */
3793 /* How many characters left in this segment to match. */
3796 /* Want how many consecutive characters we can match in
3797 one shot, so, if necessary, adjust the count. */
3798 if (mcnt > dend2 - d2)
3801 /* Compare that many; failure if mismatch, else move
3804 ? bcmp_translate (d, d2, mcnt, translate)
3805 : bcmp (d, d2, mcnt))
3807 d += mcnt, d2 += mcnt;
3813 /* begline matches the empty string at the beginning of the string
3814 (unless `not_bol' is set in `bufp'), and, if
3815 `newline_anchor' is set, after newlines. */
3817 DEBUG_PRINT1 ("EXECUTING begline.\n");
3819 if (AT_STRINGS_BEG (d))
3821 if (!bufp->not_bol) break;
3823 else if (d[-1] == '\n' && bufp->newline_anchor)
3827 /* In all other cases, we fail. */
3831 /* endline is the dual of begline. */
3833 DEBUG_PRINT1 ("EXECUTING endline.\n");
3835 if (AT_STRINGS_END (d))
3837 if (!bufp->not_eol) break;
3840 /* We have to ``prefetch'' the next character. */
3841 else if ((d == end1 ? *string2 : *d) == '\n'
3842 && bufp->newline_anchor)
3849 /* Match at the very beginning of the data. */
3851 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
3852 if (AT_STRINGS_BEG (d))
3857 /* Match at the very end of the data. */
3859 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
3860 if (AT_STRINGS_END (d))
3865 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
3866 pushes NULL as the value for the string on the stack. Then
3867 `pop_failure_point' will keep the current value for the
3868 string, instead of restoring it. To see why, consider
3869 matching `foo\nbar' against `.*\n'. The .* matches the foo;
3870 then the . fails against the \n. But the next thing we want
3871 to do is match the \n against the \n; if we restored the
3872 string value, we would be back at the foo.
3874 Because this is used only in specific cases, we don't need to
3875 check all the things that `on_failure_jump' does, to make
3876 sure the right things get saved on the stack. Hence we don't
3877 share its code. The only reason to push anything on the
3878 stack at all is that otherwise we would have to change
3879 `anychar's code to do something besides goto fail in this
3880 case; that seems worse than this. */
3881 case on_failure_keep_string_jump:
3882 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
3884 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3885 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
3887 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
3891 /* Uses of on_failure_jump:
3893 Each alternative starts with an on_failure_jump that points
3894 to the beginning of the next alternative. Each alternative
3895 except the last ends with a jump that in effect jumps past
3896 the rest of the alternatives. (They really jump to the
3897 ending jump of the following alternative, because tensioning
3898 these jumps is a hassle.)
3900 Repeats start with an on_failure_jump that points past both
3901 the repetition text and either the following jump or
3902 pop_failure_jump back to this on_failure_jump. */
3903 case on_failure_jump:
3905 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
3907 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3908 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
3910 /* If this on_failure_jump comes right before a group (i.e.,
3911 the original * applied to a group), save the information
3912 for that group and all inner ones, so that if we fail back
3913 to this point, the group's information will be correct.
3914 For example, in \(a*\)*\1, we need the preceding group,
3915 and in \(\(a*\)b*\)\2, we need the inner group. */
3917 /* We can't use `p' to check ahead because we push
3918 a failure point to `p + mcnt' after we do this. */
3921 /* We need to skip no_op's before we look for the
3922 start_memory in case this on_failure_jump is happening as
3923 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
3925 while (p1 < pend && (re_opcode_t) *p1 == no_op)
3928 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
3930 /* We have a new highest active register now. This will
3931 get reset at the start_memory we are about to get to,
3932 but we will have saved all the registers relevant to
3933 this repetition op, as described above. */
3934 highest_active_reg = *(p1 + 1) + *(p1 + 2);
3935 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3936 lowest_active_reg = *(p1 + 1);
3939 DEBUG_PRINT1 (":\n");
3940 PUSH_FAILURE_POINT (p + mcnt, d, -2);
3944 /* A smart repeat ends with `maybe_pop_jump'.
3945 We change it to either `pop_failure_jump' or `jump'. */
3946 case maybe_pop_jump:
3947 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3948 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
3950 register unsigned char *p2 = p;
3952 /* Compare the beginning of the repeat with what in the
3953 pattern follows its end. If we can establish that there
3954 is nothing that they would both match, i.e., that we
3955 would have to backtrack because of (as in, e.g., `a*a')
3956 then we can change to pop_failure_jump, because we'll
3957 never have to backtrack.
3959 This is not true in the case of alternatives: in
3960 `(a|ab)*' we do need to backtrack to the `ab' alternative
3961 (e.g., if the string was `ab'). But instead of trying to
3962 detect that here, the alternative has put on a dummy
3963 failure point which is what we will end up popping. */
3965 /* Skip over open/close-group commands. */
3966 while (p2 + 2 < pend
3967 && ((re_opcode_t) *p2 == stop_memory
3968 || (re_opcode_t) *p2 == start_memory))
3969 p2 += 3; /* Skip over args, too. */
3971 /* If we're at the end of the pattern, we can change. */
3973 { /* But if we're also at the end of the string, we might
3974 as well skip changing anything. For example, in `a+'
3975 against `a', we'll have already matched the `a', and
3976 I don't see the the point of changing the opcode,
3977 popping the failure point, finding out it fails, and
3978 then going into our endgame. */
3982 DEBUG_PRINT1 (" End of pattern & string => done.\n");
3986 p[-3] = (unsigned char) pop_failure_jump;
3987 DEBUG_PRINT1 (" End of pattern => pop_failure_jump.\n");
3990 else if ((re_opcode_t) *p2 == exactn
3991 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
3993 register unsigned char c
3994 = *p2 == (unsigned char) endline ? '\n' : p2[2];
3997 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
3998 to the `maybe_finalize_jump' of this case. Examine what
4000 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4002 p[-3] = (unsigned char) pop_failure_jump;
4003 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4007 else if ((re_opcode_t) p1[3] == charset
4008 || (re_opcode_t) p1[3] == charset_not)
4010 int not = (re_opcode_t) p1[3] == charset_not;
4012 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4013 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4016 /* `not' is equal to 1 if c would match, which means
4017 that we can't change to pop_failure_jump. */
4020 p[-3] = (unsigned char) pop_failure_jump;
4021 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4026 p -= 2; /* Point at relative address again. */
4027 if ((re_opcode_t) p[-1] != pop_failure_jump)
4029 p[-1] = (unsigned char) jump;
4030 DEBUG_PRINT1 (" Match => jump.\n");
4031 goto unconditional_jump;
4033 /* Note fall through. */
4036 /* The end of a simple repeat has a pop_failure_jump back to
4037 its matching on_failure_jump, where the latter will push a
4038 failure point. The pop_failure_jump takes off failure
4039 points put on by this pop_failure_jump's matching
4040 on_failure_jump; we got through the pattern to here from the
4041 matching on_failure_jump, so didn't fail. */
4042 case pop_failure_jump:
4044 /* We need to pass separate storage for the lowest and
4045 highest registers, even though we don't care about the
4046 actual values. Otherwise, we will restore only one
4047 register from the stack, since lowest will == highest in
4048 `pop_failure_point'. */
4049 unsigned dummy_low_reg, dummy_high_reg;
4050 unsigned char *pdummy;
4053 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4054 POP_FAILURE_POINT (sdummy, pdummy,
4055 dummy_low_reg, dummy_high_reg,
4056 reg_dummy, reg_dummy, reg_info_dummy);
4058 /* Note fall through. */
4061 /* Unconditionally jump (without popping any failure points). */
4064 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4065 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4066 p += mcnt; /* Do the jump. */
4067 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4071 /* We need this opcode so we can detect where alternatives end
4072 in `group_match_null_string_p' et al. */
4074 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4075 goto unconditional_jump;
4078 /* Normally, the on_failure_jump pushes a failure point, which
4079 then gets popped at pop_failure_jump. We will end up at
4080 pop_failure_jump, also, and with a pattern of, say, `a+', we
4081 are skipping over the on_failure_jump, so we have to push
4082 something meaningless for pop_failure_jump to pop. */
4083 case dummy_failure_jump:
4084 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4085 /* It doesn't matter what we push for the string here. What
4086 the code at `fail' tests is the value for the pattern. */
4087 PUSH_FAILURE_POINT (0, 0, -2);
4088 goto unconditional_jump;
4091 /* At the end of an alternative, we need to push a dummy failure
4092 point in case we are followed by a `pop_failure_jump', because
4093 we don't want the failure point for the alternative to be
4094 popped. For example, matching `(a|ab)*' against `aab'
4095 requires that we match the `ab' alternative. */
4096 case push_dummy_failure:
4097 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4098 /* See comments just above at `dummy_failure_jump' about the
4100 PUSH_FAILURE_POINT (0, 0, -2);
4103 /* Have to succeed matching what follows at least n times.
4104 After that, handle like `on_failure_jump'. */
4106 EXTRACT_NUMBER (mcnt, p + 2);
4107 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4110 /* Originally, this is how many times we HAVE to succeed. */
4115 STORE_NUMBER_AND_INCR (p, mcnt);
4116 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
4120 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4121 p[2] = (unsigned char) no_op;
4122 p[3] = (unsigned char) no_op;
4128 EXTRACT_NUMBER (mcnt, p + 2);
4129 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4131 /* Originally, this is how many times we CAN jump. */
4135 STORE_NUMBER (p + 2, mcnt);
4136 goto unconditional_jump;
4138 /* If don't have to jump any more, skip over the rest of command. */
4145 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4147 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4149 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4150 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4151 STORE_NUMBER (p1, mcnt);
4156 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4157 if (AT_WORD_BOUNDARY (d))
4162 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4163 if (AT_WORD_BOUNDARY (d))
4168 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4169 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4174 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4175 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4176 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4183 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4184 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4189 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4190 if (PTR_CHAR_POS ((unsigned char *) d) != point)
4195 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4196 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
4199 #else /* not emacs19 */
4201 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4202 if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
4205 #endif /* not emacs19 */
4208 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4213 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4217 if (SYNTAX (*d++) != (enum syntaxcode) mcnt)
4219 SET_REGS_MATCHED ();
4223 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4225 goto matchnotsyntax;
4228 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4232 if (SYNTAX (*d++) == (enum syntaxcode) mcnt)
4234 SET_REGS_MATCHED ();
4237 #else /* not emacs */
4239 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4241 if (!WORDCHAR_P (d))
4243 SET_REGS_MATCHED ();
4248 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4252 SET_REGS_MATCHED ();
4255 #endif /* not emacs */
4260 continue; /* Successfully executed one pattern command; keep going. */
4263 /* We goto here if a matching operation fails. */
4265 if (!FAIL_STACK_EMPTY ())
4266 { /* A restart point is known. Restore to that state. */
4267 DEBUG_PRINT1 ("\nFAIL:\n");
4268 POP_FAILURE_POINT (d, p,
4269 lowest_active_reg, highest_active_reg,
4270 regstart, regend, reg_info);
4272 /* If this failure point is a dummy, try the next one. */
4276 /* If we failed to the end of the pattern, don't examine *p. */
4280 boolean is_a_jump_n = false;
4282 /* If failed to a backwards jump that's part of a repetition
4283 loop, need to pop this failure point and use the next one. */
4284 switch ((re_opcode_t) *p)
4288 case maybe_pop_jump:
4289 case pop_failure_jump:
4292 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4295 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4297 && (re_opcode_t) *p1 == on_failure_jump))
4305 if (d >= string1 && d <= end1)
4309 break; /* Matching at this starting point really fails. */
4313 goto restore_best_regs;
4317 return -1; /* Failure to match. */
4320 /* Subroutine definitions for re_match_2. */
4323 /* We are passed P pointing to a register number after a start_memory.
4325 Return true if the pattern up to the corresponding stop_memory can
4326 match the empty string, and false otherwise.
4328 If we find the matching stop_memory, sets P to point to one past its number.
4329 Otherwise, sets P to an undefined byte less than or equal to END.
4331 We don't handle duplicates properly (yet). */
4334 group_match_null_string_p (p, end, reg_info)
4335 unsigned char **p, *end;
4336 register_info_type *reg_info;
4339 /* Point to after the args to the start_memory. */
4340 unsigned char *p1 = *p + 2;
4344 /* Skip over opcodes that can match nothing, and return true or
4345 false, as appropriate, when we get to one that can't, or to the
4346 matching stop_memory. */
4348 switch ((re_opcode_t) *p1)
4350 /* Could be either a loop or a series of alternatives. */
4351 case on_failure_jump:
4353 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4355 /* If the next operation is not a jump backwards in the
4360 /* Go through the on_failure_jumps of the alternatives,
4361 seeing if any of the alternatives cannot match nothing.
4362 The last alternative starts with only a jump,
4363 whereas the rest start with on_failure_jump and end
4364 with a jump, e.g., here is the pattern for `a|b|c':
4366 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4367 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4370 So, we have to first go through the first (n-1)
4371 alternatives and then deal with the last one separately. */
4374 /* Deal with the first (n-1) alternatives, which start
4375 with an on_failure_jump (see above) that jumps to right
4376 past a jump_past_alt. */
4378 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4380 /* `mcnt' holds how many bytes long the alternative
4381 is, including the ending `jump_past_alt' and
4384 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
4388 /* Move to right after this alternative, including the
4392 /* Break if it's the beginning of an n-th alternative
4393 that doesn't begin with an on_failure_jump. */
4394 if ((re_opcode_t) *p1 != on_failure_jump)
4397 /* Still have to check that it's not an n-th
4398 alternative that starts with an on_failure_jump. */
4400 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4401 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4403 /* Get to the beginning of the n-th alternative. */
4409 /* Deal with the last alternative: go back and get number
4410 of the `jump_past_alt' just before it. `mcnt' contains
4411 the length of the alternative. */
4412 EXTRACT_NUMBER (mcnt, p1 - 2);
4414 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
4417 p1 += mcnt; /* Get past the n-th alternative. */
4423 assert (p1[1] == **p);
4429 if (!common_op_match_null_string_p (&p1, end, reg_info))
4432 } /* while p1 < end */
4435 } /* group_match_null_string_p */
4438 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4439 It expects P to be the first byte of a single alternative and END one
4440 byte past the last. The alternative can contain groups. */
4443 alt_match_null_string_p (p, end, reg_info)
4444 unsigned char *p, *end;
4445 register_info_type *reg_info;
4448 unsigned char *p1 = p;
4452 /* Skip over opcodes that can match nothing, and break when we get
4453 to one that can't. */
4455 switch ((re_opcode_t) *p1)
4458 case on_failure_jump:
4460 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4465 if (!common_op_match_null_string_p (&p1, end, reg_info))
4468 } /* while p1 < end */
4471 } /* alt_match_null_string_p */
4474 /* Deals with the ops common to group_match_null_string_p and
4475 alt_match_null_string_p.
4477 Sets P to one after the op and its arguments, if any. */
4480 common_op_match_null_string_p (p, end, reg_info)
4481 unsigned char **p, *end;
4482 register_info_type *reg_info;
4487 unsigned char *p1 = *p;
4489 switch ((re_opcode_t) *p1++)
4509 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
4510 ret = group_match_null_string_p (&p1, end, reg_info);
4512 /* Have to set this here in case we're checking a group which
4513 contains a group and a back reference to it. */
4515 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4516 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
4522 /* If this is an optimized succeed_n for zero times, make the jump. */
4524 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4532 /* Get to the number of times to succeed. */
4534 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4539 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4547 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
4555 /* All other opcodes mean we cannot match the empty string. */
4561 } /* common_op_match_null_string_p */
4564 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4565 bytes; nonzero otherwise. */
4568 bcmp_translate (s1, s2, len, translate)
4569 unsigned char *s1, *s2;
4573 register unsigned char *p1 = s1, *p2 = s2;
4576 if (translate[*p1++] != translate[*p2++]) return 1;
4582 /* Entry points for GNU code. */
4584 /* re_compile_pattern is the GNU regular expression compiler: it
4585 compiles PATTERN (of length SIZE) and puts the result in BUFP.
4586 Returns 0 if the pattern was valid, otherwise an error string.
4588 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
4589 are set in BUFP on entry.
4591 We call regex_compile to do the actual compilation. */
4594 re_compile_pattern (pattern, length, bufp)
4595 const char *pattern;
4597 struct re_pattern_buffer *bufp;
4601 /* GNU code is written to assume at least RE_NREGS registers will be set
4602 (and at least one extra will be -1). */
4603 bufp->regs_allocated = REGS_UNALLOCATED;
4605 /* And GNU code determines whether or not to get register information
4606 by passing null for the REGS argument to re_match, etc., not by
4610 /* Match anchors at newline. */
4611 bufp->newline_anchor = 1;
4613 ret = regex_compile (pattern, length, re_syntax_options, bufp);
4615 return re_error_msg[(int) ret];
4618 /* Entry points compatible with 4.2 BSD regex library. We don't define
4619 them if this is an Emacs or POSIX compilation. */
4621 #if !defined (emacs) && !defined (_POSIX_SOURCE)
4623 /* BSD has one and only one pattern buffer. */
4624 static struct re_pattern_buffer re_comp_buf;
4634 if (!re_comp_buf.buffer)
4635 return "No previous regular expression";
4639 if (!re_comp_buf.buffer)
4641 re_comp_buf.buffer = (unsigned char *) malloc (200);
4642 if (re_comp_buf.buffer == NULL)
4643 return "Memory exhausted";
4644 re_comp_buf.allocated = 200;
4646 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
4647 if (re_comp_buf.fastmap == NULL)
4648 return "Memory exhausted";
4651 /* Since `re_exec' always passes NULL for the `regs' argument, we
4652 don't need to initialize the pattern buffer fields which affect it. */
4654 /* Match anchors at newlines. */
4655 re_comp_buf.newline_anchor = 1;
4657 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
4659 /* Yes, we're discarding `const' here. */
4660 return (char *) re_error_msg[(int) ret];
4668 const int len = strlen (s);
4670 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
4672 #endif /* not emacs and not _POSIX_SOURCE */
4674 /* POSIX.2 functions. Don't define these for Emacs. */
4678 /* regcomp takes a regular expression as a string and compiles it.
4680 PREG is a regex_t *. We do not expect any fields to be initialized,
4681 since POSIX says we shouldn't. Thus, we set
4683 `buffer' to the compiled pattern;
4684 `used' to the length of the compiled pattern;
4685 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
4686 REG_EXTENDED bit in CFLAGS is set; otherwise, to
4687 RE_SYNTAX_POSIX_BASIC;
4688 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
4689 `fastmap' and `fastmap_accurate' to zero;
4690 `re_nsub' to the number of subexpressions in PATTERN.
4692 PATTERN is the address of the pattern string.
4694 CFLAGS is a series of bits which affect compilation.
4696 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
4697 use POSIX basic syntax.
4699 If REG_NEWLINE is set, then . and [^...] don't match newline.
4700 Also, regexec will try a match beginning after every newline.
4702 If REG_ICASE is set, then we considers upper- and lowercase
4703 versions of letters to be equivalent when matching.
4705 If REG_NOSUB is set, then when PREG is passed to regexec, that
4706 routine will report only success or failure, and nothing about the
4709 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
4710 the return codes and their meanings.) */
4713 regcomp (preg, pattern, cflags)
4715 const char *pattern;
4720 = (cflags & REG_EXTENDED) ?
4721 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
4723 /* regex_compile will allocate the space for the compiled pattern. */
4725 preg->allocated = 0;
4727 /* Don't bother to use a fastmap when searching. This simplifies the
4728 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
4729 characters after newlines into the fastmap. This way, we just try
4733 if (cflags & REG_ICASE)
4737 preg->translate = (char *) malloc (CHAR_SET_SIZE);
4738 if (preg->translate == NULL)
4739 return (int) REG_ESPACE;
4741 /* Map uppercase characters to corresponding lowercase ones. */
4742 for (i = 0; i < CHAR_SET_SIZE; i++)
4743 preg->translate[i] = isupper (i) ? tolower (i) : i;
4746 preg->translate = NULL;
4748 /* If REG_NEWLINE is set, newlines are treated differently. */
4749 if (cflags & REG_NEWLINE)
4750 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
4751 syntax &= ~RE_DOT_NEWLINE;
4752 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
4753 /* It also changes the matching behavior. */
4754 preg->newline_anchor = 1;
4757 preg->newline_anchor = 0;
4759 preg->no_sub = !!(cflags & REG_NOSUB);
4761 /* POSIX says a null character in the pattern terminates it, so we
4762 can use strlen here in compiling the pattern. */
4763 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
4765 /* POSIX doesn't distinguish between an unmatched open-group and an
4766 unmatched close-group: both are REG_EPAREN. */
4767 if (ret == REG_ERPAREN) ret = REG_EPAREN;
4773 /* regexec searches for a given pattern, specified by PREG, in the
4776 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
4777 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
4778 least NMATCH elements, and we set them to the offsets of the
4779 corresponding matched substrings.
4781 EFLAGS specifies `execution flags' which affect matching: if
4782 REG_NOTBOL is set, then ^ does not match at the beginning of the
4783 string; if REG_NOTEOL is set, then $ does not match at the end.
4785 We return 0 if we find a match and REG_NOMATCH if not. */
4788 regexec (preg, string, nmatch, pmatch, eflags)
4789 const regex_t *preg;
4792 regmatch_t pmatch[];
4796 struct re_registers regs;
4797 regex_t private_preg;
4798 int len = strlen (string);
4799 boolean want_reg_info = !preg->no_sub && nmatch > 0;
4801 private_preg = *preg;
4803 private_preg.not_bol = !!(eflags & REG_NOTBOL);
4804 private_preg.not_eol = !!(eflags & REG_NOTEOL);
4806 /* The user has told us exactly how many registers to return
4807 information about, via `nmatch'. We have to pass that on to the
4808 matching routines. */
4809 private_preg.regs_allocated = REGS_FIXED;
4813 regs.num_regs = nmatch;
4814 regs.start = TALLOC (nmatch, regoff_t);
4815 regs.end = TALLOC (nmatch, regoff_t);
4816 if (regs.start == NULL || regs.end == NULL)
4817 return (int) REG_NOMATCH;
4820 /* Perform the searching operation. */
4821 ret = re_search (&private_preg, string, len,
4822 /* start: */ 0, /* range: */ len,
4823 want_reg_info ? ®s : (struct re_registers *) 0);
4825 /* Copy the register information to the POSIX structure. */
4832 for (r = 0; r < nmatch; r++)
4834 pmatch[r].rm_so = regs.start[r];
4835 pmatch[r].rm_eo = regs.end[r];
4839 /* If we needed the temporary register info, free the space now. */
4844 /* We want zero return to mean success, unlike `re_search'. */
4845 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
4849 /* Returns a message corresponding to an error code, ERRCODE, returned
4850 from either regcomp or regexec. We don't use PREG here. */
4853 regerror (errcode, preg, errbuf, errbuf_size)
4855 const regex_t *preg;
4860 = re_error_msg[errcode] == NULL ? "Success" : re_error_msg[errcode];
4861 size_t msg_size = strlen (msg) + 1; /* Includes the null. */
4863 if (errbuf_size != 0)
4865 if (msg_size > errbuf_size)
4867 strncpy (errbuf, msg, errbuf_size - 1);
4868 errbuf[errbuf_size - 1] = 0;
4871 strcpy (errbuf, msg);
4878 /* Free dynamically allocated space used by PREG. */
4884 if (preg->buffer != NULL)
4885 free (preg->buffer);
4886 preg->buffer = NULL;
4888 preg->allocated = 0;
4891 if (preg->fastmap != NULL)
4892 free (preg->fastmap);
4893 preg->fastmap = NULL;
4894 preg->fastmap_accurate = 0;
4896 if (preg->translate != NULL)
4897 free (preg->translate);
4898 preg->translate = NULL;
4901 #endif /* not emacs */
4905 make-backup-files: t
4907 trim-versions-without-asking: nil