1 /* Extended regular expression matching and search library,
3 * (Implements POSIX draft P10003.2/D11.2, except for
4 * internationalization features.)
6 * Copyright (C) 1993 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., 59 Temple Place, Suite 330, Boston, MA 02111, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined(REGEX_MALLOC)
33 #if USE_GNUREGEX /* only if squid needs it. Usually not */
36 #define REGEX_MALLOC 1
39 /* We used to test for `BSTRING' here, but only GCC and Emacs define
40 * `BSTRING', as far as I know, and neither of them use this code. */
41 #if HAVE_STRING_H || STDC_HEADERS
47 /* Define the syntax stuff for \<, \>, etc. */
49 /* This must be nonzero for the wordchar and notwordchar pattern
50 * commands in re_match_2. */
57 extern char *re_syntax_table
;
59 #else /* not SYNTAX_TABLE */
61 /* How many characters in the character set. */
62 #define CHAR_SET_SIZE 256
64 static char re_syntax_table
[CHAR_SET_SIZE
];
67 init_syntax_once(void)
75 memset(re_syntax_table
, 0, sizeof re_syntax_table
);
77 for (c
= 'a'; c
<= 'z'; c
++)
78 re_syntax_table
[c
] = Sword
;
80 for (c
= 'A'; c
<= 'Z'; c
++)
81 re_syntax_table
[c
] = Sword
;
83 for (c
= '0'; c
<= '9'; c
++)
84 re_syntax_table
[c
] = Sword
;
86 re_syntax_table
['_'] = Sword
;
91 #endif /* not SYNTAX_TABLE */
93 #define SYNTAX(c) re_syntax_table[c]
95 /* Get the interface, including the syntax bits. */
96 #include "compat/GnuRegex.h"
98 /* Compile a fastmap for the compiled pattern in BUFFER; used to
99 * accelerate searches. Return 0 if successful and -2 if was an
101 static int re_compile_fastmap(struct re_pattern_buffer
* buffer
);
103 /* Search in the string STRING (with length LENGTH) for the pattern
104 * compiled into BUFFER. Start searching at position START, for RANGE
105 * characters. Return the starting position of the match, -1 for no
106 * match, or -2 for an internal error. Also return register
107 * information in REGS (if REGS and BUFFER->no_sub are nonzero). */
108 static int re_search(struct re_pattern_buffer
* buffer
, const char *string
,
109 int length
, int start
, int range
, struct re_registers
* regs
);
111 /* Like `re_search', but search in the concatenation of STRING1 and
112 * STRING2. Also, stop searching at index START + STOP. */
113 static int re_search_2(struct re_pattern_buffer
* buffer
, const char *string1
,
114 int length1
, const char *string2
, int length2
,
115 int start
, int range
, struct re_registers
* regs
, int stop
);
117 /* Like `re_search_2', but return how many characters in STRING the regexp
118 * in BUFFER matched, starting at position START. */
119 static int re_match_2(struct re_pattern_buffer
* buffer
, const char *string1
,
120 int length1
, const char *string2
, int length2
,
121 int start
, struct re_registers
* regs
, int stop
);
123 /* isalpha etc. are used for the character classes. */
131 #define ISBLANK(c) (isascii ((unsigned char)c) && isblank ((unsigned char)c))
133 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
136 #define ISGRAPH(c) (isascii ((unsigned char)c) && isgraph ((unsigned char)c))
138 #define ISGRAPH(c) (isascii ((unsigned char)c) && isprint ((unsigned char)c) && !isspace ((unsigned char)c))
141 #define ISPRINT(c) (isascii ((unsigned char)c) && isprint ((unsigned char)c))
142 #define ISDIGIT(c) (isascii ((unsigned char)c) && isdigit ((unsigned char)c))
143 #define ISALNUM(c) (isascii ((unsigned char)c) && isalnum ((unsigned char)c))
144 #define ISALPHA(c) (isascii ((unsigned char)c) && isalpha ((unsigned char)c))
145 #define ISCNTRL(c) (isascii ((unsigned char)c) && iscntrl ((unsigned char)c))
146 #define ISLOWER(c) (isascii ((unsigned char)c) && islower ((unsigned char)c))
147 #define ISPUNCT(c) (isascii ((unsigned char)c) && ispunct ((unsigned char)c))
148 #define ISSPACE(c) (isascii ((unsigned char)c) && isspace ((unsigned char)c))
149 #define ISUPPER(c) (isascii ((unsigned char)c) && isupper ((unsigned char)c))
150 #define ISXDIGIT(c) (isascii ((unsigned char)c) && isxdigit ((unsigned char)c))
152 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
153 * since ours (we hope) works properly with all combinations of
154 * machines, compilers, `char' and `unsigned char' argument types.
155 * (Per Bothner suggested the basic approach.) */
156 #undef SIGN_EXTEND_CHAR
158 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
159 #else /* not __STDC__ */
160 /* As in Harbison and Steele. */
161 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
164 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
165 * use `alloca' instead of `malloc'. This is because using malloc in
166 * re_search* or re_match* could cause memory leaks when C-g is used in
167 * Emacs; also, malloc is slower and causes storage fragmentation. On
168 * the other hand, malloc is more portable, and easier to debug.
170 * Because we sometimes use alloca, some routines have to be macros,
171 * not functions -- `alloca'-allocated space disappears at the end of the
172 * function it is called in. */
176 #define REGEX_ALLOCATE malloc
177 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
179 #else /* not REGEX_MALLOC */
181 /* Emacs already defines alloca, sometimes. */
184 /* Make alloca work the best possible way. */
186 #define alloca __builtin_alloca
187 #else /* not __GNUC__ */
190 #else /* not __GNUC__ or HAVE_ALLOCA_H */
191 #ifndef _AIX /* Already did AIX, up at the top. */
193 #endif /* not _AIX */
194 #endif /* not HAVE_ALLOCA_H */
195 #endif /* not __GNUC__ */
197 #endif /* not alloca */
199 #define REGEX_ALLOCATE alloca
201 /* Assumes a `char *destination' variable. */
202 #define REGEX_REALLOCATE(source, osize, nsize) \
203 (destination = (char *) alloca (nsize), \
204 memcpy (destination, source, osize), \
207 #endif /* not REGEX_MALLOC */
209 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
210 * `string1' or just past its end. This works if PTR is NULL, which is
212 #define FIRST_STRING_P(ptr) \
213 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
215 /* (Re)Allocate N items of type T using malloc, or fail. */
216 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
217 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
218 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
220 #define BYTEWIDTH 8 /* In bits. */
222 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
224 #if !defined(__MINGW32__) /* MinGW defines boolean */
225 typedef char boolean
;
230 /* These are the command codes that appear in compiled regular
231 * expressions. Some opcodes are followed by argument bytes. A
232 * command code can specify any interpretation whatsoever for its
233 * arguments. Zero bytes may appear in the compiled regular expression.
235 * The value of `exactn' is needed in search.c (search_buffer) in Emacs.
236 * So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
237 * `exactn' we use here must also be 1. */
242 /* Followed by one byte giving n, then by n literal bytes. */
245 /* Matches any (more or less) character. */
248 /* Matches any one char belonging to specified set. First
249 * following byte is number of bitmap bytes. Then come bytes
250 * for a bitmap saying which chars are in. Bits in each byte
251 * are ordered low-bit-first. A character is in the set if its
252 * bit is 1. A character too large to have a bit in the map is
253 * automatically not in the set. */
256 /* Same parameters as charset, but match any character that is
257 * not one of those specified. */
260 /* Start remembering the text that is matched, for storing in a
261 * register. Followed by one byte with the register number, in
262 * the range 0 to one less than the pattern buffer's re_nsub
263 * field. Then followed by one byte with the number of groups
264 * inner to this one. (This last has to be part of the
265 * start_memory only because we need it in the on_failure_jump
269 /* Stop remembering the text that is matched and store it in a
270 * memory register. Followed by one byte with the register
271 * number, in the range 0 to one less than `re_nsub' in the
272 * pattern buffer, and one byte with the number of inner groups,
273 * just like `start_memory'. (We need the number of inner
274 * groups here because we don't have any easy way of finding the
275 * corresponding start_memory when we're at a stop_memory.) */
278 /* Match a duplicate of something remembered. Followed by one
279 * byte containing the register number. */
282 /* Fail unless at beginning of line. */
285 /* Fail unless at end of line. */
288 /* Succeeds if or at beginning of string to be matched. */
291 /* Analogously, for end of buffer/string. */
294 /* Followed by two byte relative address to which to jump. */
297 /* Same as jump, but marks the end of an alternative. */
300 /* Followed by two-byte relative address of place to resume at
301 * in case of failure. */
304 /* Like on_failure_jump, but pushes a placeholder instead of the
305 * current string position when executed. */
306 on_failure_keep_string_jump
,
308 /* Throw away latest failure point and then jump to following
309 * two-byte relative address. */
312 /* Change to pop_failure_jump if know won't have to backtrack to
313 * match; otherwise change to jump. This is used to jump
314 * back to the beginning of a repeat. If what follows this jump
315 * clearly won't match what the repeat does, such that we can be
316 * sure that there is no use backtracking out of repetitions
317 * already matched, then we change it to a pop_failure_jump.
318 * Followed by two-byte address. */
321 /* Jump to following two-byte address, and push a dummy failure
322 * point. This failure point will be thrown away if an attempt
323 * is made to use it for a failure. A `+' construct makes this
324 * before the first repeat. Also used as an intermediary kind
325 * of jump when compiling an alternative. */
328 /* Push a dummy failure point and continue. Used at the end of
332 /* Followed by two-byte relative address and two-byte number n.
333 * After matching N times, jump to the address upon failure. */
336 /* Followed by two-byte relative address, and two-byte number n.
337 * Jump to the address N times, then fail. */
340 /* Set the following two-byte relative address to the
341 * subsequent two-byte number. The address *includes* the two
342 * bytes of number. */
345 wordchar
, /* Matches any word-constituent character. */
346 notwordchar
, /* Matches any char that is not a word-constituent. */
348 wordbeg
, /* Succeeds if at word beginning. */
349 wordend
, /* Succeeds if at word end. */
351 wordbound
, /* Succeeds if at a word boundary. */
352 notwordbound
/* Succeeds if not at a word boundary. */
356 /* Common operations on the compiled pattern. */
358 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
360 #define STORE_NUMBER(destination, number) \
362 (destination)[0] = (number) & 0377; \
363 (destination)[1] = (number) >> 8; \
366 /* Same as STORE_NUMBER, except increment DESTINATION to
367 * the byte after where the number is stored. Therefore, DESTINATION
368 * must be an lvalue. */
370 #define STORE_NUMBER_AND_INCR(destination, number) \
372 STORE_NUMBER (destination, number); \
373 (destination) += 2; \
376 /* Put into DESTINATION a number stored in two contiguous bytes starting
379 #define EXTRACT_NUMBER(destination, source) \
381 (destination) = *(source) & 0377; \
382 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
387 extract_number(dest
, source
)
389 unsigned char *source
;
391 int temp
= SIGN_EXTEND_CHAR(*(source
+ 1));
392 *dest
= *source
& 0377;
396 #ifndef EXTRACT_MACROS /* To debug the macros. */
397 #undef EXTRACT_NUMBER
398 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
399 #endif /* not EXTRACT_MACROS */
403 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
404 * SOURCE must be an lvalue. */
406 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
408 EXTRACT_NUMBER (destination, source); \
414 extract_number_and_incr(destination
, source
)
416 unsigned char **source
;
418 extract_number(destination
, *source
);
422 #ifndef EXTRACT_MACROS
423 #undef EXTRACT_NUMBER_AND_INCR
424 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
425 extract_number_and_incr (&dest, &src)
426 #endif /* not EXTRACT_MACROS */
430 /* If DEBUG is defined, Regex prints many voluminous messages about what
431 * it is doing (if the variable `debug' is nonzero). If linked with the
432 * main program in `iregex.c', you can enter patterns and strings
433 * interactively. And if linked with the main program in `main.c' and
434 * the other test files, you can run the already-written tests. */
438 static int debug
= 0;
440 #define DEBUG_STATEMENT(e) e
441 #define DEBUG_PRINT1(x) if (debug) printf (x)
442 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
443 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
444 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
445 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
446 if (debug) print_partial_compiled_pattern (s, e)
447 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
448 if (debug) print_double_string (w, s1, sz1, s2, sz2)
450 extern void printchar();
452 /* Print the fastmap in human-readable form. */
455 print_fastmap(fastmap
)
458 unsigned was_a_range
= 0;
461 while (i
< (1 << BYTEWIDTH
)) {
465 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
]) {
478 /* Print a compiled pattern string in human-readable form, starting at
479 * the START pointer into it and ending just before the pointer END. */
482 print_partial_compiled_pattern(start
, end
)
483 unsigned char *start
;
487 unsigned char *p
= start
;
488 unsigned char *pend
= end
;
494 /* Loop over pattern commands. */
496 switch ((re_opcode_t
) * p
++) {
503 printf("/exactn/%d", mcnt
);
512 printf("/start_memory/%d/%d", mcnt
, *p
++);
517 printf("/stop_memory/%d/%d", mcnt
, *p
++);
521 printf("/duplicate/%d", *p
++);
533 (re_opcode_t
) * (p
- 1) == charset_not
? "_not" : "");
535 assert(p
+ *p
< pend
);
537 for (c
= 0; c
< *p
; c
++) {
539 unsigned char map_byte
= p
[1 + c
];
543 for (bit
= 0; bit
< BYTEWIDTH
; bit
++)
544 if (map_byte
& (1 << bit
))
545 printchar(c
* BYTEWIDTH
+ bit
);
559 case on_failure_jump
:
560 extract_number_and_incr(&mcnt
, &p
);
561 printf("/on_failure_jump/0/%d", mcnt
);
564 case on_failure_keep_string_jump
:
565 extract_number_and_incr(&mcnt
, &p
);
566 printf("/on_failure_keep_string_jump/0/%d", mcnt
);
569 case dummy_failure_jump
:
570 extract_number_and_incr(&mcnt
, &p
);
571 printf("/dummy_failure_jump/0/%d", mcnt
);
574 case push_dummy_failure
:
575 printf("/push_dummy_failure");
579 extract_number_and_incr(&mcnt
, &p
);
580 printf("/maybe_pop_jump/0/%d", mcnt
);
583 case pop_failure_jump
:
584 extract_number_and_incr(&mcnt
, &p
);
585 printf("/pop_failure_jump/0/%d", mcnt
);
589 extract_number_and_incr(&mcnt
, &p
);
590 printf("/jump_past_alt/0/%d", mcnt
);
594 extract_number_and_incr(&mcnt
, &p
);
595 printf("/jump/0/%d", mcnt
);
599 extract_number_and_incr(&mcnt
, &p
);
600 extract_number_and_incr(&mcnt2
, &p
);
601 printf("/succeed_n/0/%d/0/%d", mcnt
, mcnt2
);
605 extract_number_and_incr(&mcnt
, &p
);
606 extract_number_and_incr(&mcnt2
, &p
);
607 printf("/jump_n/0/%d/0/%d", mcnt
, mcnt2
);
611 extract_number_and_incr(&mcnt
, &p
);
612 extract_number_and_incr(&mcnt2
, &p
);
613 printf("/set_number_at/0/%d/0/%d", mcnt
, mcnt2
);
617 printf("/wordbound");
621 printf("/notwordbound");
636 printf("/notwordchar");
648 printf("?%d", *(p
- 1));
655 print_compiled_pattern(bufp
)
656 struct re_pattern_buffer
*bufp
;
658 unsigned char *buffer
= bufp
->buffer
;
660 print_partial_compiled_pattern(buffer
, buffer
+ bufp
->used
);
661 printf("%d bytes used/%d bytes allocated.\n", bufp
->used
, bufp
->allocated
);
663 if (bufp
->fastmap_accurate
&& bufp
->fastmap
) {
665 print_fastmap(bufp
->fastmap
);
667 printf("re_nsub: %d\t", bufp
->re_nsub
);
668 printf("regs_alloc: %d\t", bufp
->regs_allocated
);
669 printf("can_be_null: %d\t", bufp
->can_be_null
);
670 printf("newline_anchor: %d\n", bufp
->newline_anchor
);
671 printf("no_sub: %d\t", bufp
->no_sub
);
672 printf("not_bol: %d\t", bufp
->not_bol
);
673 printf("not_eol: %d\t", bufp
->not_eol
);
674 printf("syntax: %d\n", bufp
->syntax
);
675 /* Perhaps we should print the translate table? */
679 print_double_string(where
, string1
, size1
, string2
, size2
)
691 if (FIRST_STRING_P(where
)) {
692 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
693 printchar(string1
[this_char
]);
697 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
698 printchar(string2
[this_char
]);
702 #else /* not DEBUG */
707 #define DEBUG_STATEMENT(e)
708 #define DEBUG_PRINT1(x)
709 #define DEBUG_PRINT2(x1, x2)
710 #define DEBUG_PRINT3(x1, x2, x3)
711 #define DEBUG_PRINT4(x1, x2, x3, x4)
712 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
713 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
715 #endif /* not DEBUG */
717 /* This table gives an error message for each of the error codes listed
718 * in regex.h. Obviously the order here has to be same as there. */
720 static const char *re_error_msg
[] = {NULL
, /* REG_NOERROR */
721 "No match", /* REG_NOMATCH */
722 "Invalid regular expression", /* REG_BADPAT */
723 "Invalid collation character", /* REG_ECOLLATE */
724 "Invalid character class name", /* REG_ECTYPE */
725 "Trailing backslash", /* REG_EESCAPE */
726 "Invalid back reference", /* REG_ESUBREG */
727 "Unmatched [ or [^", /* REG_EBRACK */
728 "Unmatched ( or \\(", /* REG_EPAREN */
729 "Unmatched \\{", /* REG_EBRACE */
730 "Invalid content of \\{\\}", /* REG_BADBR */
731 "Invalid range end", /* REG_ERANGE */
732 "Memory exhausted", /* REG_ESPACE */
733 "Invalid preceding regular expression", /* REG_BADRPT */
734 "Premature end of regular expression", /* REG_EEND */
735 "Regular expression too big", /* REG_ESIZE */
736 "Unmatched ) or \\)", /* REG_ERPAREN */
739 /* Subroutine declarations and macros for regex_compile. */
741 /* Fetch the next character in the uncompiled pattern---translating it
742 * if necessary. Also cast from a signed character in the constant
743 * string passed to us by the user to an unsigned char that we can use
744 * as an array index (in, e.g., `translate'). */
745 #define PATFETCH(c) \
746 do {if (p == pend) return REG_EEND; \
747 c = (unsigned char) *p++; \
748 if (translate) c = translate[c]; \
751 /* Fetch the next character in the uncompiled pattern, with no
753 #define PATFETCH_RAW(c) \
754 do {if (p == pend) return REG_EEND; \
755 c = (unsigned char) *p++; \
758 /* Go backwards one character in the pattern. */
759 #define PATUNFETCH p--
761 /* If `translate' is non-null, return translate[D], else just D. We
762 * cast the subscript to translate because some data is declared as
763 * `char *', to avoid warnings when a string constant is passed. But
764 * when we use a character as a subscript we must make it unsigned. */
765 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
767 /* Macros for outputting the compiled pattern into `buffer'. */
769 /* If the buffer isn't allocated when it comes in, use this. */
770 #define INIT_BUF_SIZE 32
772 /* Make sure we have at least N more bytes of space in buffer. */
773 #define GET_BUFFER_SPACE(n) \
774 while (b - bufp->buffer + (n) > bufp->allocated) \
777 /* Make sure we have one more byte of buffer space and then add C to it. */
778 #define BUF_PUSH(c) \
780 GET_BUFFER_SPACE (1); \
781 *b++ = (unsigned char) (c); \
784 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
785 #define BUF_PUSH_2(c1, c2) \
787 GET_BUFFER_SPACE (2); \
788 *b++ = (unsigned char) (c1); \
789 *b++ = (unsigned char) (c2); \
792 /* As with BUF_PUSH_2, except for three bytes. */
793 #define BUF_PUSH_3(c1, c2, c3) \
795 GET_BUFFER_SPACE (3); \
796 *b++ = (unsigned char) (c1); \
797 *b++ = (unsigned char) (c2); \
798 *b++ = (unsigned char) (c3); \
801 /* Store a jump with opcode OP at LOC to location TO. We store a
802 * relative address offset by the three bytes the jump itself occupies. */
803 #define STORE_JUMP(op, loc, to) \
804 store_op1 (op, loc, (to) - (loc) - 3)
806 /* Likewise, for a two-argument jump. */
807 #define STORE_JUMP2(op, loc, to, arg) \
808 store_op2 (op, loc, (to) - (loc) - 3, arg)
810 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
811 #define INSERT_JUMP(op, loc, to) \
812 insert_op1 (op, loc, (to) - (loc) - 3, b)
814 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
815 #define INSERT_JUMP2(op, loc, to, arg) \
816 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
818 /* This is not an arbitrary limit: the arguments which represent offsets
819 * into the pattern are two bytes long. So if 2^16 bytes turns out to
820 * be too small, many things would have to change. */
821 #define MAX_BUF_SIZE (1L << 16)
823 /* Extend the buffer by twice its current size via realloc and
824 * reset the pointers that pointed into the old block to point to the
825 * correct places in the new one. If extending the buffer results in it
826 * being larger than MAX_BUF_SIZE, then flag memory exhausted. */
827 #define EXTEND_BUFFER() \
829 unsigned char *old_buffer = bufp->buffer; \
830 if (bufp->allocated == MAX_BUF_SIZE) \
832 bufp->allocated <<= 1; \
833 if (bufp->allocated > MAX_BUF_SIZE) \
834 bufp->allocated = MAX_BUF_SIZE; \
835 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
836 if (bufp->buffer == NULL) \
838 /* If the buffer moved, move all the pointers into it. */ \
839 if (old_buffer != bufp->buffer) \
841 b = (b - old_buffer) + bufp->buffer; \
842 begalt = (begalt - old_buffer) + bufp->buffer; \
843 if (fixup_alt_jump) \
844 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
846 laststart = (laststart - old_buffer) + bufp->buffer; \
848 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
852 /* Since we have one byte reserved for the register number argument to
853 * {start,stop}_memory, the maximum number of groups we can report
854 * things about is what fits in that byte. */
855 #define MAX_REGNUM 255
857 /* But patterns can have more than `MAX_REGNUM' registers. We just
858 * ignore the excess. */
859 typedef unsigned regnum_t
;
861 /* Macros for the compile stack. */
863 /* Since offsets can go either forwards or backwards, this type needs to
864 * be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
865 typedef int pattern_offset_t
;
868 pattern_offset_t begalt_offset
;
869 pattern_offset_t fixup_alt_jump
;
870 pattern_offset_t inner_group_offset
;
871 pattern_offset_t laststart_offset
;
873 } compile_stack_elt_t
;
876 compile_stack_elt_t
*stack
;
878 unsigned avail
; /* Offset of next open position. */
879 } compile_stack_type
;
881 static void store_op1(re_opcode_t op
, unsigned char *loc
, int arg
);
882 static void store_op2( re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
);
883 static void insert_op1(re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
);
884 static void insert_op2(re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
);
885 static boolean
at_begline_loc_p(const char * pattern
, const char *p
, reg_syntax_t syntax
);
886 static boolean
at_endline_loc_p(const char *p
, const char *pend
, int syntax
);
887 static boolean
group_in_compile_stack(compile_stack_type compile_stack
, regnum_t regnum
);
888 static reg_errcode_t
compile_range(const char **p_ptr
, const char *pend
, char *translate
, reg_syntax_t syntax
, unsigned char *b
);
890 #define INIT_COMPILE_STACK_SIZE 32
892 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
893 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
895 /* The next available element. */
896 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
898 /* Set the bit for character C in a list. */
899 #define SET_LIST_BIT(c) \
900 (b[((unsigned char) (c)) / BYTEWIDTH] \
901 |= 1 << (((unsigned char) c) % BYTEWIDTH))
903 /* Get the next unsigned number in the uncompiled pattern. */
904 #define GET_UNSIGNED_NUMBER(num) \
908 while (ISDIGIT (c)) \
912 num = num * 10 + c - '0'; \
920 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
922 #define IS_CHAR_CLASS(string) \
923 (STREQ (string, "alpha") || STREQ (string, "upper") \
924 || STREQ (string, "lower") || STREQ (string, "digit") \
925 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
926 || STREQ (string, "space") || STREQ (string, "print") \
927 || STREQ (string, "punct") || STREQ (string, "graph") \
928 || STREQ (string, "cntrl") || STREQ (string, "blank"))
930 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
931 * Returns one of error codes defined in `regex.h', or zero for success.
933 * Assumes the `allocated' (and perhaps `buffer') and `translate'
934 * fields are set in BUFP on entry.
936 * If it succeeds, results are put in BUFP (if it returns an error, the
937 * contents of BUFP are undefined):
938 * `buffer' is the compiled pattern;
939 * `syntax' is set to SYNTAX;
940 * `used' is set to the length of the compiled pattern;
941 * `fastmap_accurate' is zero;
942 * `re_nsub' is the number of subexpressions in PATTERN;
943 * `not_bol' and `not_eol' are zero;
945 * The `fastmap' and `newline_anchor' fields are neither
946 * examined nor set. */
949 regex_compile(const char *pattern
, int size
, reg_syntax_t syntax
, struct re_pattern_buffer
*bufp
)
951 /* We fetch characters from PATTERN here. Even though PATTERN is
952 * `char *' (i.e., signed), we declare these variables as unsigned, so
953 * they can be reliably used as array indices. */
954 register unsigned char c
, c1
;
956 /* A random tempory spot in PATTERN. */
959 /* Points to the end of the buffer, where we should append. */
960 register unsigned char *b
;
962 /* Keeps track of unclosed groups. */
963 compile_stack_type compile_stack
;
965 /* Points to the current (ending) position in the pattern. */
966 const char *p
= pattern
;
967 const char *pend
= pattern
+ size
;
969 /* How to translate the characters in the pattern. */
970 char *translate
= bufp
->translate
;
972 /* Address of the count-byte of the most recently inserted `exactn'
973 * command. This makes it possible to tell if a new exact-match
974 * character can be added to that command or if the character requires
975 * a new `exactn' command. */
976 unsigned char *pending_exact
= 0;
978 /* Address of start of the most recently finished expression.
979 * This tells, e.g., postfix * where to find the start of its
980 * operand. Reset at the beginning of groups and alternatives. */
981 unsigned char *laststart
= 0;
983 /* Address of beginning of regexp, or inside of last group. */
984 unsigned char *begalt
;
986 /* Place in the uncompiled pattern (i.e., the {) to
987 * which to go back if the interval is invalid. */
988 const char *beg_interval
;
990 /* Address of the place where a forward jump should go to the end of
991 * the containing expression. Each alternative of an `or' -- except the
992 * last -- ends with a forward jump of this sort. */
993 unsigned char *fixup_alt_jump
= 0;
995 /* Counts open-groups as they are encountered. Remembered for the
996 * matching close-group on the compile stack, so the same register
997 * number is put in the stop_memory as the start_memory. */
1001 DEBUG_PRINT1("\nCompiling pattern: ");
1003 unsigned debug_count
;
1005 for (debug_count
= 0; debug_count
< size
; debug_count
++)
1006 printchar(pattern
[debug_count
]);
1011 /* Initialize the compile stack. */
1012 compile_stack
.stack
= TALLOC(INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
1013 if (compile_stack
.stack
== NULL
)
1016 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
1017 compile_stack
.avail
= 0;
1019 /* Initialize the pattern buffer. */
1020 bufp
->syntax
= syntax
;
1021 bufp
->fastmap_accurate
= 0;
1022 bufp
->not_bol
= bufp
->not_eol
= 0;
1024 /* Set `used' to zero, so that if we return an error, the pattern
1025 * printer (for debugging) will think there's no pattern. We reset it
1029 /* Always count groups, whether or not bufp->no_sub is set. */
1032 #if !defined (SYNTAX_TABLE)
1033 /* Initialize the syntax table. */
1037 if (bufp
->allocated
== 0) {
1038 if (bufp
->buffer
) { /* If zero allocated, but buffer is non-null, try to realloc
1039 * enough space. This loses if buffer's address is bogus, but
1040 * that is the user's responsibility. */
1041 RETALLOC(bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
1042 } else { /* Caller did not allocate a buffer. Do it for them. */
1043 bufp
->buffer
= TALLOC(INIT_BUF_SIZE
, unsigned char);
1048 bufp
->allocated
= INIT_BUF_SIZE
;
1050 begalt
= b
= bufp
->buffer
;
1052 /* Loop through the uncompiled pattern until we're at the end. */
1058 if ( /* If at start of pattern, it's an operator. */
1060 /* If context independent, it's an operator. */
1061 || syntax
& RE_CONTEXT_INDEP_ANCHORS
1062 /* Otherwise, depends on what's come before. */
1063 || at_begline_loc_p(pattern
, p
, syntax
))
1071 if ( /* If at end of pattern, it's an operator. */
1073 /* If context independent, it's an operator. */
1074 || syntax
& RE_CONTEXT_INDEP_ANCHORS
1075 /* Otherwise, depends on what's next. */
1076 || at_endline_loc_p(p
, pend
, syntax
))
1085 if ((syntax
& RE_BK_PLUS_QM
)
1086 || (syntax
& RE_LIMITED_OPS
))
1090 /* If there is no previous pattern... */
1092 if (syntax
& RE_CONTEXT_INVALID_OPS
)
1094 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
1097 /* Are we optimizing this jump? */
1098 boolean keep_string_p
= false;
1100 /* 1 means zero (many) matches is allowed. */
1101 char zero_times_ok
= 0, many_times_ok
= 0;
1103 /* If there is a sequence of repetition chars, collapse it
1104 * down to just one (the right one). We can't combine
1105 * interval operators with these because of, e.g., `a{2}*',
1106 * which should only match an even number of `a's. */
1109 zero_times_ok
|= c
!= '+';
1110 many_times_ok
|= c
!= '?';
1118 || (!(syntax
& RE_BK_PLUS_QM
) && (c
== '+' || c
== '?')));
1120 else if (syntax
& RE_BK_PLUS_QM
&& c
== '\\') {
1125 if (!(c1
== '+' || c1
== '?')) {
1136 /* If we get here, we found another repeat character. */
1139 /* Star, etc. applied to an empty pattern is equivalent
1140 * to an empty pattern. */
1144 /* Now we know whether or not zero matches is allowed
1145 * and also whether or not two or more matches is allowed. */
1146 if (many_times_ok
) { /* More than one repetition is allowed, so put in at the
1147 * end a backward relative jump from `b' to before the next
1148 * jump we're going to put in below (which jumps from
1149 * laststart to after this jump).
1151 * But if we are at the `*' in the exact sequence `.*\n',
1152 * insert an unconditional jump backwards to the .,
1153 * instead of the beginning of the loop. This way we only
1154 * push a failure point once, instead of every time
1155 * through the loop. */
1156 assert(p
- 1 > pattern
);
1158 /* Allocate the space for the jump. */
1159 GET_BUFFER_SPACE(3);
1161 /* We know we are not at the first character of the pattern,
1162 * because laststart was nonzero. And we've already
1163 * incremented `p', by the way, to be the character after
1164 * the `*'. Do we have to do something analogous here
1165 * for null bytes, because of RE_DOT_NOT_NULL? */
1166 if (TRANSLATE(*(p
- 2)) == TRANSLATE('.')
1168 && p
< pend
&& TRANSLATE(*p
) == TRANSLATE('\n')
1169 && !(syntax
& RE_DOT_NEWLINE
)) { /* We have .*\n. */
1170 STORE_JUMP(jump
, b
, laststart
);
1171 keep_string_p
= true;
1173 /* Anything else. */
1174 STORE_JUMP(maybe_pop_jump
, b
, laststart
- 3);
1176 /* We've added more stuff to the buffer. */
1179 /* On failure, jump from laststart to b + 3, which will be the
1180 * end of the buffer after this jump is inserted. */
1181 GET_BUFFER_SPACE(3);
1182 INSERT_JUMP(keep_string_p
? on_failure_keep_string_jump
1188 if (!zero_times_ok
) {
1189 /* At least one repetition is required, so insert a
1190 * `dummy_failure_jump' before the initial
1191 * `on_failure_jump' instruction of the loop. This
1192 * effects a skip over that instruction the first time
1193 * we hit that loop. */
1194 GET_BUFFER_SPACE(3);
1195 INSERT_JUMP(dummy_failure_jump
, laststart
, laststart
+ 6);
1207 boolean had_char_class
= false;
1212 /* Ensure that we have enough space to push a charset: the
1213 * opcode, the length count, and the bitset; 34 bytes in all. */
1214 GET_BUFFER_SPACE(34);
1218 /* We test `*p == '^' twice, instead of using an if
1219 * statement, so we only need one BUF_PUSH. */
1220 BUF_PUSH(*p
== '^' ? charset_not
: charset
);
1224 /* Remember the first position in the bracket expression. */
1227 /* Push the number of bytes in the bitmap. */
1228 BUF_PUSH((1 << BYTEWIDTH
) / BYTEWIDTH
);
1230 /* Clear the whole map. */
1231 memset(b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
1233 /* charset_not matches newline according to a syntax bit. */
1234 if ((re_opcode_t
) b
[-2] == charset_not
1235 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
1238 /* Read in characters and ranges, setting map bits. */
1245 /* \ might escape characters inside [...] and [^...]. */
1246 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\') {
1254 /* Could be the end of the bracket expression. If it's
1255 * not (i.e., when the bracket expression is `[]' so
1256 * far), the ']' character bit gets set way below. */
1257 if (c
== ']' && p
!= p1
+ 1)
1260 /* Look ahead to see if it's a range when the last thing
1261 * was a character class. */
1262 if (had_char_class
&& c
== '-' && *p
!= ']')
1265 /* Look ahead to see if it's a range when the last thing
1266 * was a character: if this is a hyphen not at the
1267 * beginning or the end of a list, then it's the range
1270 && !(p
- 2 >= pattern
&& p
[-2] == '[')
1271 && !(p
- 3 >= pattern
&& p
[-3] == '[' && p
[-2] == '^')
1274 = compile_range(&p
, pend
, translate
, syntax
, b
);
1275 if (ret
!= REG_NOERROR
)
1277 } else if (p
[0] == '-' && p
[1] != ']') { /* This handles ranges made up of characters only. */
1280 /* Move past the `-'. */
1283 ret
= compile_range(&p
, pend
, translate
, syntax
, b
);
1284 if (ret
!= REG_NOERROR
)
1287 /* See if we're at the beginning of a possible character
1290 else if (syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':') { /* Leave room for the null. */
1291 char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
1296 /* If pattern is `[[:'. */
1302 if (c
== ':' || c
== ']' || p
== pend
1303 || c1
== CHAR_CLASS_MAX_LENGTH
)
1309 /* If isn't a word bracketed by `[:' and:`]':
1310 * undo the ending character, the letters, and leave
1311 * the leading `:' and `[' (but set bits for them). */
1312 if (c
== ':' && *p
== ']') {
1314 boolean is_alnum
= STREQ(str
, "alnum");
1315 boolean is_alpha
= STREQ(str
, "alpha");
1316 boolean is_blank
= STREQ(str
, "blank");
1317 boolean is_cntrl
= STREQ(str
, "cntrl");
1318 boolean is_digit
= STREQ(str
, "digit");
1319 boolean is_graph
= STREQ(str
, "graph");
1320 boolean is_lower
= STREQ(str
, "lower");
1321 boolean is_print
= STREQ(str
, "print");
1322 boolean is_punct
= STREQ(str
, "punct");
1323 boolean is_space
= STREQ(str
, "space");
1324 boolean is_upper
= STREQ(str
, "upper");
1325 boolean is_xdigit
= STREQ(str
, "xdigit");
1327 if (!IS_CHAR_CLASS(str
))
1330 /* Throw away the ] at the end of the character
1337 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ch
++) {
1338 if ((is_alnum
&& ISALNUM(ch
))
1339 || (is_alpha
&& ISALPHA(ch
))
1340 || (is_blank
&& ISBLANK(ch
))
1341 || (is_cntrl
&& ISCNTRL(ch
))
1342 || (is_digit
&& ISDIGIT(ch
))
1343 || (is_graph
&& ISGRAPH(ch
))
1344 || (is_lower
&& ISLOWER(ch
))
1345 || (is_print
&& ISPRINT(ch
))
1346 || (is_punct
&& ISPUNCT(ch
))
1347 || (is_space
&& ISSPACE(ch
))
1348 || (is_upper
&& ISUPPER(ch
))
1349 || (is_xdigit
&& ISXDIGIT(ch
)))
1352 had_char_class
= true;
1359 had_char_class
= false;
1362 had_char_class
= false;
1367 /* Discard any (non)matching list bytes that are all 0 at the
1368 * end of the map. Decrease the map-length byte too. */
1369 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
1376 if (syntax
& RE_NO_BK_PARENS
)
1382 if (syntax
& RE_NO_BK_PARENS
)
1388 if (syntax
& RE_NEWLINE_ALT
)
1394 if (syntax
& RE_NO_BK_VBAR
)
1400 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
1401 goto handle_interval
;
1409 /* Do not translate the character after the \, so that we can
1410 * distinguish, e.g., \B from \b, even if we normally would
1411 * translate, e.g., B to b. */
1416 if (syntax
& RE_NO_BK_PARENS
)
1417 goto normal_backslash
;
1423 if (COMPILE_STACK_FULL
) {
1424 RETALLOC(compile_stack
.stack
, compile_stack
.size
<< 1,
1425 compile_stack_elt_t
);
1426 if (compile_stack
.stack
== NULL
)
1429 compile_stack
.size
<<= 1;
1431 /* These are the values to restore when we hit end of this
1432 * group. They are all relative offsets, so that if the
1433 * whole pattern moves because of realloc, they will still
1435 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
1436 COMPILE_STACK_TOP
.fixup_alt_jump
1437 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
1438 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
1439 COMPILE_STACK_TOP
.regnum
= regnum
;
1441 /* We will eventually replace the 0 with the number of
1442 * groups inner to this one. But do not push a
1443 * start_memory for groups beyond the last one we can
1444 * represent in the compiled pattern. */
1445 if (regnum
<= MAX_REGNUM
) {
1446 COMPILE_STACK_TOP
.inner_group_offset
= b
- bufp
->buffer
+ 2;
1447 BUF_PUSH_3(start_memory
, regnum
, 0);
1449 compile_stack
.avail
++;
1454 /* If we've reached MAX_REGNUM groups, then this open
1455 * won't actually generate any code, so we'll have to
1456 * clear pending_exact explicitly. */
1461 if (syntax
& RE_NO_BK_PARENS
)
1462 goto normal_backslash
;
1464 if (COMPILE_STACK_EMPTY
) {
1465 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
1466 goto normal_backslash
;
1471 if (fixup_alt_jump
) { /* Push a dummy failure point at the end of the
1472 * alternative for a possible future
1473 * `pop_failure_jump' to pop. See comments at
1474 * `push_dummy_failure' in `re_match_2'. */
1475 BUF_PUSH(push_dummy_failure
);
1477 /* We allocated space for this jump when we assigned
1478 * to `fixup_alt_jump', in the `handle_alt' case below. */
1479 STORE_JUMP(jump_past_alt
, fixup_alt_jump
, b
- 1);
1481 /* See similar code for backslashed left paren above. */
1482 if (COMPILE_STACK_EMPTY
) {
1483 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
1488 /* Since we just checked for an empty stack above, this
1489 * ``can't happen''. */
1490 assert(compile_stack
.avail
!= 0);
1492 /* We don't just want to restore into `regnum', because
1493 * later groups should continue to be numbered higher,
1494 * as in `(ab)c(de)' -- the second group is #2. */
1495 regnum_t this_group_regnum
;
1497 compile_stack
.avail
--;
1498 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
1500 = COMPILE_STACK_TOP
.fixup_alt_jump
1501 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
1503 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
1504 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
1505 /* If we've reached MAX_REGNUM groups, then this open
1506 * won't actually generate any code, so we'll have to
1507 * clear pending_exact explicitly. */
1510 /* We're at the end of the group, so now we know how many
1511 * groups were inside this one. */
1512 if (this_group_regnum
<= MAX_REGNUM
) {
1513 unsigned char *inner_group_loc
1514 = bufp
->buffer
+ COMPILE_STACK_TOP
.inner_group_offset
;
1516 *inner_group_loc
= regnum
- this_group_regnum
;
1517 BUF_PUSH_3(stop_memory
, this_group_regnum
,
1518 regnum
- this_group_regnum
);
1523 case '|': /* `\|'. */
1524 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
1525 goto normal_backslash
;
1527 if (syntax
& RE_LIMITED_OPS
)
1530 /* Insert before the previous alternative a jump which
1531 * jumps to this alternative if the former fails. */
1532 GET_BUFFER_SPACE(3);
1533 INSERT_JUMP(on_failure_jump
, begalt
, b
+ 6);
1537 /* The alternative before this one has a jump after it
1538 * which gets executed if it gets matched. Adjust that
1539 * jump so it will jump to this alternative's analogous
1540 * jump (put in below, which in turn will jump to the next
1541 * (if any) alternative's such jump, etc.). The last such
1542 * jump jumps to the correct final destination. A picture:
1548 * If we are at `b', then fixup_alt_jump right now points to a
1549 * three-byte space after `a'. We'll put in the jump, set
1550 * fixup_alt_jump to right after `b', and leave behind three
1551 * bytes which we'll fill in when we get to after `c'. */
1554 STORE_JUMP(jump_past_alt
, fixup_alt_jump
, b
);
1556 /* Mark and leave space for a jump after this alternative,
1557 * to be filled in later either by next alternative or
1558 * when know we're at the end of a series of alternatives. */
1560 GET_BUFFER_SPACE(3);
1568 /* If \{ is a literal. */
1569 if (!(syntax
& RE_INTERVALS
)
1570 /* If we're at `\{' and it's not the open-interval
1572 || ((syntax
& RE_INTERVALS
) && (syntax
& RE_NO_BK_BRACES
))
1573 || (p
- 2 == pattern
&& p
== pend
))
1574 goto normal_backslash
;
1577 /* If got here, then the syntax allows intervals. */
1579 /* At least (most) this many matches must be made. */
1580 int lower_bound
= -1, upper_bound
= -1;
1582 beg_interval
= p
- 1;
1585 if (syntax
& RE_NO_BK_BRACES
)
1586 goto unfetch_interval
;
1590 GET_UNSIGNED_NUMBER(lower_bound
);
1593 GET_UNSIGNED_NUMBER(upper_bound
);
1594 if (upper_bound
< 0)
1595 upper_bound
= RE_DUP_MAX
;
1597 /* Interval such as `{1}' => match exactly once. */
1598 upper_bound
= lower_bound
;
1600 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
1601 || lower_bound
> upper_bound
) {
1602 if (syntax
& RE_NO_BK_BRACES
)
1603 goto unfetch_interval
;
1607 if (!(syntax
& RE_NO_BK_BRACES
)) {
1614 if (syntax
& RE_NO_BK_BRACES
)
1615 goto unfetch_interval
;
1619 /* We just parsed a valid interval. */
1621 /* If it's invalid to have no preceding re. */
1623 if (syntax
& RE_CONTEXT_INVALID_OPS
)
1625 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
1628 goto unfetch_interval
;
1630 /* If the upper bound is zero, don't want to succeed at
1631 * all; jump from `laststart' to `b + 3', which will be
1632 * the end of the buffer after we insert the jump. */
1633 if (upper_bound
== 0) {
1634 GET_BUFFER_SPACE(3);
1635 INSERT_JUMP(jump
, laststart
, b
+ 3);
1638 /* Otherwise, we have a nontrivial interval. When
1639 * we're all done, the pattern will look like:
1640 * set_number_at <jump count> <upper bound>
1641 * set_number_at <succeed_n count> <lower bound>
1642 * succeed_n <after jump addr> <succed_n count>
1644 * jump_n <succeed_n addr> <jump count>
1645 * (The upper bound and `jump_n' are omitted if
1646 * `upper_bound' is 1, though.) */
1647 else { /* If the upper bound is > 1, we need to insert
1648 * more at the end of the loop. */
1649 unsigned nbytes
= 10 + (upper_bound
> 1) * 10;
1651 GET_BUFFER_SPACE(nbytes
);
1653 /* Initialize lower bound of the `succeed_n', even
1654 * though it will be set during matching by its
1655 * attendant `set_number_at' (inserted next),
1656 * because `re_compile_fastmap' needs to know.
1657 * Jump to the `jump_n' we might insert below. */
1658 INSERT_JUMP2(succeed_n
, laststart
,
1659 b
+ 5 + (upper_bound
> 1) * 5,
1663 /* Code to initialize the lower bound. Insert
1664 * before the `succeed_n'. The `5' is the last two
1665 * bytes of this `set_number_at', plus 3 bytes of
1666 * the following `succeed_n'. */
1667 insert_op2(set_number_at
, laststart
, 5, lower_bound
, b
);
1670 if (upper_bound
> 1) { /* More than one repetition is allowed, so
1671 * append a backward jump to the `succeed_n'
1672 * that starts this interval.
1674 * When we've reached this during matching,
1675 * we'll have matched the interval once, so
1676 * jump back only `upper_bound - 1' times. */
1677 STORE_JUMP2(jump_n
, b
, laststart
+ 5,
1681 /* The location we want to set is the second
1682 * parameter of the `jump_n'; that is `b-2' as
1683 * an absolute address. `laststart' will be
1684 * the `set_number_at' we're about to insert;
1685 * `laststart+3' the number to set, the source
1686 * for the relative address. But we are
1687 * inserting into the middle of the pattern --
1688 * so everything is getting moved up by 5.
1689 * Conclusion: (b - 2) - (laststart + 3) + 5,
1690 * i.e., b - laststart.
1692 * We insert this at the beginning of the loop
1693 * so that if we fail during matching, we'll
1694 * reinitialize the bounds. */
1695 insert_op2(set_number_at
, laststart
, b
- laststart
,
1696 upper_bound
- 1, b
);
1701 beg_interval
= NULL
;
1706 /* If an invalid interval, match the characters as literals. */
1707 assert(beg_interval
);
1709 beg_interval
= NULL
;
1711 /* normal_char and normal_backslash need `c'. */
1714 if (!(syntax
& RE_NO_BK_BRACES
)) {
1715 if (p
> pattern
&& p
[-1] == '\\')
1716 goto normal_backslash
;
1727 BUF_PUSH(notwordchar
);
1739 BUF_PUSH(wordbound
);
1743 BUF_PUSH(notwordbound
);
1763 if (syntax
& RE_NO_BK_REFS
)
1771 /* Can't back reference to a subexpression if inside of it. */
1772 if (group_in_compile_stack(compile_stack
, c1
))
1776 BUF_PUSH_2(duplicate
, c1
);
1781 if (syntax
& RE_BK_PLUS_QM
)
1784 goto normal_backslash
;
1788 /* You might think it would be useful for \ to mean
1789 * not to translate; but if we don't translate it
1790 * it will never match anything. */
1797 /* Expects the character in `c'. */
1799 /* If no exactn currently being built. */
1802 /* If last exactn not at current position. */
1803 || pending_exact
+ *pending_exact
+ 1 != b
1805 /* We have only one byte following the exactn for the count. */
1806 || *pending_exact
== (1 << BYTEWIDTH
) - 1
1808 /* If followed by a repetition operator. */
1809 || *p
== '*' || *p
== '^'
1810 || ((syntax
& RE_BK_PLUS_QM
)
1811 ? *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
1812 : (*p
== '+' || *p
== '?'))
1813 || ((syntax
& RE_INTERVALS
)
1814 && ((syntax
& RE_NO_BK_BRACES
)
1816 : (p
[0] == '\\' && p
[1] == '{')))) {
1817 /* Start building a new exactn. */
1821 BUF_PUSH_2(exactn
, 0);
1822 pending_exact
= b
- 1;
1828 } /* while p != pend */
1830 /* Through the pattern now. */
1833 STORE_JUMP(jump_past_alt
, fixup_alt_jump
, b
);
1835 if (!COMPILE_STACK_EMPTY
)
1838 free(compile_stack
.stack
);
1840 /* We have succeeded; set the length of the buffer. */
1841 bufp
->used
= b
- bufp
->buffer
;
1845 DEBUG_PRINT1("\nCompiled pattern: ");
1846 print_compiled_pattern(bufp
);
1851 } /* regex_compile */
1853 /* Subroutines for `regex_compile'. */
1855 /* Store OP at LOC followed by two-byte integer parameter ARG. */
1857 void store_op1(re_opcode_t op
, unsigned char *loc
, int arg
)
1859 *loc
= (unsigned char) op
;
1860 STORE_NUMBER(loc
+ 1, arg
);
1863 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
1866 store_op2( re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
1868 *loc
= (unsigned char) op
;
1869 STORE_NUMBER(loc
+ 1, arg1
);
1870 STORE_NUMBER(loc
+ 3, arg2
);
1873 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
1874 * for OP followed by two-byte integer parameter ARG. */
1877 insert_op1(re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
1879 register unsigned char *pfrom
= end
;
1880 register unsigned char *pto
= end
+ 3;
1882 while (pfrom
!= loc
)
1885 store_op1(op
, loc
, arg
);
1888 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
1891 insert_op2(re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
1893 register unsigned char *pfrom
= end
;
1894 register unsigned char *pto
= end
+ 5;
1896 while (pfrom
!= loc
)
1899 store_op2(op
, loc
, arg1
, arg2
);
1902 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
1903 * after an alternative or a begin-subexpression. We assume there is at
1904 * least one character before the ^. */
1907 at_begline_loc_p(const char * pattern
, const char *p
, reg_syntax_t syntax
)
1909 const char *prev
= p
- 2;
1910 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
1913 /* After a subexpression? */
1914 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
1915 /* After an alternative? */
1916 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
));
1919 /* The dual of at_begline_loc_p. This one is for $. We assume there is
1920 * at least one character after the $, i.e., `P < PEND'. */
1923 at_endline_loc_p(const char *p
, const char *pend
, int syntax
)
1925 const char *next
= p
;
1926 boolean next_backslash
= *next
== '\\';
1927 const char *next_next
= p
+ 1 < pend
? p
+ 1 : NULL
;
1930 /* Before a subexpression? */
1931 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
1932 : next_backslash
&& next_next
&& *next_next
== ')')
1933 /* Before an alternative? */
1934 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
1935 : next_backslash
&& next_next
&& *next_next
== '|');
1938 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
1939 * false if it's not. */
1942 group_in_compile_stack(compile_stack_type compile_stack
, regnum_t regnum
)
1946 for (this_element
= compile_stack
.avail
- 1;
1949 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
1955 /* Read the ending character of a range (in a bracket expression) from the
1956 * uncompiled pattern *P_PTR (which ends at PEND). We assume the
1957 * starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
1958 * Then we set the translation of all bits between the starting and
1959 * ending characters (inclusive) in the compiled pattern B.
1961 * Return an error code.
1963 * We use these short variable names so we can use the same macros as
1964 * `regex_compile' itself. */
1967 compile_range(const char **p_ptr
, const char *pend
, char *translate
, reg_syntax_t syntax
, unsigned char *b
)
1971 const char *p
= *p_ptr
;
1972 int range_start
, range_end
;
1977 /* Even though the pattern is a signed `char *', we need to fetch
1978 * with unsigned char *'s; if the high bit of the pattern character
1979 * is set, the range endpoints will be negative if we fetch using a
1982 * We also want to fetch the endpoints without translating them; the
1983 * appropriate translation is done in the bit-setting loop below. */
1984 range_start
= ((unsigned char *) p
)[-2];
1985 range_end
= ((unsigned char *) p
)[0];
1987 /* Have to increment the pointer into the pattern string, so the
1988 * caller isn't still at the ending character. */
1991 /* If the start is after the end, the range is empty. */
1992 if (range_start
> range_end
)
1993 return syntax
& RE_NO_EMPTY_RANGES
? REG_ERANGE
: REG_NOERROR
;
1995 /* Here we see why `this_char' has to be larger than an `unsigned
1996 * char' -- the range is inclusive, so if `range_end' == 0xff
1997 * (assuming 8-bit characters), we would otherwise go into an infinite
1998 * loop, since all characters <= 0xff. */
1999 for (this_char
= range_start
; this_char
<= range_end
; this_char
++) {
2000 SET_LIST_BIT(TRANSLATE(this_char
));
2006 /* Failure stack declarations and macros; both re_compile_fastmap and
2007 * re_match_2 use a failure stack. These have to be macros because of
2008 * REGEX_ALLOCATE. */
2010 /* Number of failure points for which to initially allocate space
2011 * when matching. If this number is exceeded, we allocate more
2012 * space, so it is not a hard limit. */
2013 #ifndef INIT_FAILURE_ALLOC
2014 #define INIT_FAILURE_ALLOC 5
2017 /* Roughly the maximum number of failure points on the stack. Would be
2018 * exactly that if always used MAX_FAILURE_SPACE each time we failed.
2019 * This is a variable only so users of regex can assign to it; we never
2020 * change it ourselves. */
2021 int re_max_failures
= 2000;
2023 typedef const unsigned char *fail_stack_elt_t
;
2026 fail_stack_elt_t
*stack
;
2028 unsigned avail
; /* Offset of next open position. */
2031 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
2032 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2033 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
2034 #define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])
2036 /* Initialize `fail_stack'. Do `return -2' if the alloc fails. */
2038 #define INIT_FAIL_STACK() \
2040 fail_stack.stack = (fail_stack_elt_t *) \
2041 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
2043 if (fail_stack.stack == NULL) \
2046 fail_stack.size = INIT_FAILURE_ALLOC; \
2047 fail_stack.avail = 0; \
2050 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
2052 * Return 1 if succeeds, and 0 if either ran out of memory
2053 * allocating space for it or it was already too large.
2055 * REGEX_REALLOCATE requires `destination' be declared. */
2057 #define DOUBLE_FAIL_STACK(fail_stack) \
2058 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
2060 : ((fail_stack).stack = (fail_stack_elt_t *) \
2061 REGEX_REALLOCATE ((fail_stack).stack, \
2062 (fail_stack).size * sizeof (fail_stack_elt_t), \
2063 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
2065 (fail_stack).stack == NULL \
2067 : ((fail_stack).size <<= 1, \
2070 /* Push PATTERN_OP on FAIL_STACK.
2072 * Return 1 if was able to do so and 0 if ran out of memory allocating
2073 * space to do so. */
2074 #define PUSH_PATTERN_OP(pattern_op, fail_stack) \
2075 ((FAIL_STACK_FULL () \
2076 && !DOUBLE_FAIL_STACK (fail_stack)) \
2078 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \
2081 /* This pushes an item onto the failure stack. Must be a four-byte
2082 * value. Assumes the variable `fail_stack'. Probably should only
2083 * be called from within `PUSH_FAILURE_POINT'. */
2084 #define PUSH_FAILURE_ITEM(item) \
2085 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2087 /* The complement operation. Assumes `fail_stack' is nonempty. */
2088 #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2090 /* Used to omit pushing failure point id's when we're not debugging. */
2092 #define DEBUG_PUSH PUSH_FAILURE_ITEM
2093 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2095 #define DEBUG_PUSH(item)
2096 #define DEBUG_POP(item_addr)
2099 /* Push the information about the state we will need
2100 * if we ever fail back to it.
2102 * Requires variables fail_stack, regstart, regend, reg_info, and
2103 * num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
2106 * Does `return FAILURE_CODE' if runs out of memory. */
2108 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
2110 char *destination; \
2111 /* Must be int, so when we don't save any registers, the arithmetic \
2112 of 0 + -1 isn't done as unsigned. */ \
2115 DEBUG_STATEMENT (failure_id++); \
2116 DEBUG_STATEMENT (nfailure_points_pushed++); \
2117 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
2118 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
2119 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
2121 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
2122 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
2124 /* Ensure we have enough space allocated for what we will push. */ \
2125 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
2127 if (!DOUBLE_FAIL_STACK (fail_stack)) \
2128 return failure_code; \
2130 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
2131 (fail_stack).size); \
2132 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2135 /* Push the info, starting with the registers. */ \
2136 DEBUG_PRINT1 ("\n"); \
2138 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
2141 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
2142 DEBUG_STATEMENT (num_regs_pushed++); \
2144 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2145 PUSH_FAILURE_ITEM (regstart[this_reg]); \
2147 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2148 PUSH_FAILURE_ITEM (regend[this_reg]); \
2150 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
2151 DEBUG_PRINT2 (" match_null=%d", \
2152 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
2153 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
2154 DEBUG_PRINT2 (" matched_something=%d", \
2155 MATCHED_SOMETHING (reg_info[this_reg])); \
2156 DEBUG_PRINT2 (" ever_matched=%d", \
2157 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
2158 DEBUG_PRINT1 ("\n"); \
2159 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \
2162 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
2163 PUSH_FAILURE_ITEM (lowest_active_reg); \
2165 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
2166 PUSH_FAILURE_ITEM (highest_active_reg); \
2168 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
2169 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
2170 PUSH_FAILURE_ITEM (pattern_place); \
2172 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
2173 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
2175 DEBUG_PRINT1 ("'\n"); \
2176 PUSH_FAILURE_ITEM (string_place); \
2178 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
2179 DEBUG_PUSH (failure_id); \
2182 /* This is the number of items that are pushed and popped on the stack
2183 * for each register. */
2184 #define NUM_REG_ITEMS 3
2186 /* Individual items aside from the registers. */
2188 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
2190 #define NUM_NONREG_ITEMS 4
2193 /* We push at most this many items on the stack. */
2194 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2196 /* We actually push this many items. */
2197 #define NUM_FAILURE_ITEMS \
2198 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
2201 /* How many items can still be added to the stack without overflowing it. */
2202 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2204 /* Pops what PUSH_FAIL_STACK pushes.
2206 * We restore into the parameters, all of which should be lvalues:
2207 * STR -- the saved data position.
2208 * PAT -- the saved pattern position.
2209 * LOW_REG, HIGH_REG -- the highest and lowest active registers.
2210 * REGSTART, REGEND -- arrays of string positions.
2211 * REG_INFO -- array of information about each subexpression.
2213 * Also assumes the variables `fail_stack' and (if debugging), `bufp',
2214 * `pend', `string1', `size1', `string2', and `size2'. */
2216 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2218 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
2220 const unsigned char *string_temp; \
2222 assert (!FAIL_STACK_EMPTY ()); \
2224 /* Remove failure points and point to how many regs pushed. */ \
2225 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
2226 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
2227 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
2229 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
2231 DEBUG_POP (&failure_id); \
2232 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
2234 /* If the saved string location is NULL, it came from an \
2235 on_failure_keep_string_jump opcode, and we want to throw away the \
2236 saved NULL, thus retaining our current position in the string. */ \
2237 string_temp = POP_FAILURE_ITEM (); \
2238 if (string_temp != NULL) \
2239 str = (const char *) string_temp; \
2241 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
2242 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
2243 DEBUG_PRINT1 ("'\n"); \
2245 pat = (unsigned char *) POP_FAILURE_ITEM (); \
2246 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
2247 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
2249 /* Restore register info. */ \
2250 high_reg = (unsigned long) POP_FAILURE_ITEM (); \
2251 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
2253 low_reg = (unsigned long) POP_FAILURE_ITEM (); \
2254 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
2256 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
2258 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
2260 reg_info[this_reg].word = POP_FAILURE_ITEM (); \
2261 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
2263 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2264 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2266 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2267 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2270 DEBUG_STATEMENT (nfailure_points_popped++); \
2271 } /* POP_FAILURE_POINT */
2273 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2274 * BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2275 * characters can start a string that matches the pattern. This fastmap
2276 * is used by re_search to skip quickly over impossible starting points.
2278 * The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2279 * area as BUFP->fastmap.
2281 * We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2282 * the pattern buffer.
2284 * Returns 0 if we succeed, -2 if an internal error. */
2287 re_compile_fastmap(struct re_pattern_buffer
*bufp
)
2290 re_compile_fastmap(bufp
)
2291 struct re_pattern_buffer
*bufp
;
2295 fail_stack_type fail_stack
;
2296 #ifndef REGEX_MALLOC
2299 /* We don't push any register information onto the failure stack. */
2300 unsigned num_regs
= 0;
2302 register char *fastmap
= bufp
->fastmap
;
2303 unsigned char *pattern
= bufp
->buffer
;
2304 unsigned long size
= bufp
->used
;
2305 const unsigned char *p
= pattern
;
2306 register unsigned char *pend
= pattern
+ size
;
2308 /* Assume that each path through the pattern can be null until
2309 * proven otherwise. We set this false at the bottom of switch
2310 * statement, to which we get only if a particular path doesn't
2311 * match the empty string. */
2312 boolean path_can_be_null
= true;
2314 /* We aren't doing a `succeed_n' to begin with. */
2315 boolean succeed_n_p
= false;
2317 assert(fastmap
!= NULL
&& p
!= NULL
);
2320 memset(fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
2321 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
2322 bufp
->can_be_null
= 0;
2324 while (p
!= pend
|| !FAIL_STACK_EMPTY()) {
2326 bufp
->can_be_null
|= path_can_be_null
;
2328 /* Reset for next path. */
2329 path_can_be_null
= true;
2331 p
= fail_stack
.stack
[--fail_stack
.avail
];
2333 /* We should never be about to go beyond the end of the pattern. */
2336 #ifdef SWITCH_ENUM_BUG
2337 switch ((int) ((re_opcode_t
) * p
++))
2339 switch ((re_opcode_t
) * p
++)
2343 /* I guess the idea here is to simply not bother with a fastmap
2344 * if a backreference is used, since it's too hard to figure out
2345 * the fastmap for the corresponding group. Setting
2346 * `can_be_null' stops `re_search_2' from using the fastmap, so
2347 * that is all we do. */
2349 bufp
->can_be_null
= 1;
2352 /* Following are the cases which match a character. These end
2360 for (j
= *p
++ * BYTEWIDTH
- 1; j
>= 0; j
--)
2361 if (p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
)))
2366 /* Chars beyond end of map must be allowed. */
2367 for (j
= *p
* BYTEWIDTH
; j
< (1 << BYTEWIDTH
); j
++)
2370 for (j
= *p
++ * BYTEWIDTH
- 1; j
>= 0; j
--)
2371 if (!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))))
2376 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
2377 if (SYNTAX(j
) == Sword
)
2382 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
2383 if (SYNTAX(j
) != Sword
)
2388 /* `.' matches anything ... */
2389 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
2392 /* ... except perhaps newline. */
2393 if (!(bufp
->syntax
& RE_DOT_NEWLINE
))
2396 /* Return if we have already set `can_be_null'; if we have,
2397 * then the fastmap is irrelevant. Something's wrong here. */
2398 else if (bufp
->can_be_null
)
2401 /* Otherwise, have to check alternative paths. */
2413 case push_dummy_failure
:
2417 case pop_failure_jump
:
2418 case maybe_pop_jump
:
2421 case dummy_failure_jump
:
2422 EXTRACT_NUMBER_AND_INCR(j
, p
);
2427 /* Jump backward implies we just went through the body of a
2428 * loop and matched nothing. Opcode jumped to should be
2429 * `on_failure_jump' or `succeed_n'. Just treat it like an
2430 * ordinary jump. For a * loop, it has pushed its failure
2431 * point already; if so, discard that as redundant. */
2432 if ((re_opcode_t
) * p
!= on_failure_jump
2433 && (re_opcode_t
) * p
!= succeed_n
)
2437 EXTRACT_NUMBER_AND_INCR(j
, p
);
2440 /* If what's on the stack is where we are now, pop it. */
2441 if (!FAIL_STACK_EMPTY()
2442 && fail_stack
.stack
[fail_stack
.avail
- 1] == p
)
2447 case on_failure_jump
:
2448 case on_failure_keep_string_jump
:
2449 handle_on_failure_jump
:
2450 EXTRACT_NUMBER_AND_INCR(j
, p
);
2452 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2453 * end of the pattern. We don't want to push such a point,
2454 * since when we restore it above, entering the switch will
2455 * increment `p' past the end of the pattern. We don't need
2456 * to push such a point since we obviously won't find any more
2457 * fastmap entries beyond `pend'. Such a pattern can match
2458 * the null string, though. */
2460 if (!PUSH_PATTERN_OP(p
+ j
, fail_stack
))
2463 bufp
->can_be_null
= 1;
2466 EXTRACT_NUMBER_AND_INCR(k
, p
); /* Skip the n. */
2467 succeed_n_p
= false;
2472 /* Get to the number of times to succeed. */
2475 /* Increment p past the n for when k != 0. */
2476 EXTRACT_NUMBER_AND_INCR(k
, p
);
2479 succeed_n_p
= true; /* Spaghetti code alert. */
2480 goto handle_on_failure_jump
;
2494 abort(); /* We have listed all the cases. */
2497 /* Getting here means we have found the possible starting
2498 * characters for one path of the pattern -- and that the empty
2499 * string does not match. We need not follow this path further.
2500 * Instead, look at the next alternative (remembered on the
2501 * stack), or quit if no more. The test at the top of the loop
2502 * does these things. */
2503 path_can_be_null
= false;
2507 /* Set `can_be_null' for the last path (also the first path, if the
2508 * pattern is empty). */
2509 bufp
->can_be_null
|= path_can_be_null
;
2511 } /* re_compile_fastmap */
2513 /* Searching routines. */
2515 /* Like re_search_2, below, but only one string is specified, and
2516 * doesn't let you say where to stop matching. */
2519 re_search(bufp
, string
, size
, startpos
, range
, regs
)
2520 struct re_pattern_buffer
*bufp
;
2522 int size
, startpos
, range
;
2523 struct re_registers
*regs
;
2525 return re_search_2(bufp
, NULL
, 0, string
, size
, startpos
, range
,
2529 /* Using the compiled pattern in BUFP->buffer, first tries to match the
2530 * virtual concatenation of STRING1 and STRING2, starting first at index
2531 * STARTPOS, then at STARTPOS + 1, and so on.
2533 * STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
2535 * RANGE is how far to scan while trying to match. RANGE = 0 means try
2536 * only at STARTPOS; in general, the last start tried is STARTPOS +
2539 * In REGS, return the indices of the virtual concatenation of STRING1
2540 * and STRING2 that matched the entire BUFP->buffer and its contained
2543 * Do not consider matching one past the index STOP in the virtual
2544 * concatenation of STRING1 and STRING2.
2546 * We return either the position in the strings at which the match was
2547 * found, -1 if no match, or -2 if error (such as failure
2548 * stack overflow). */
2551 re_search_2(bufp
, string1
, size1
, string2
, size2
, startpos
, range
, regs
, stop
)
2552 struct re_pattern_buffer
*bufp
;
2553 const char *string1
, *string2
;
2557 struct re_registers
*regs
;
2561 register char *fastmap
= bufp
->fastmap
;
2562 register char *translate
= bufp
->translate
;
2563 int total_size
= size1
+ size2
;
2564 int endpos
= startpos
+ range
;
2566 /* Check for out-of-range STARTPOS. */
2567 if (startpos
< 0 || startpos
> total_size
)
2570 /* Fix up RANGE if it might eventually take us outside
2571 * the virtual concatenation of STRING1 and STRING2. */
2573 range
= -1 - startpos
;
2574 else if (endpos
> total_size
)
2575 range
= total_size
- startpos
;
2577 /* If the search isn't to be a backwards one, don't waste time in a
2578 * search for a pattern that must be anchored. */
2579 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0) {
2585 /* Update the fastmap now if not correct already. */
2586 if (fastmap
&& !bufp
->fastmap_accurate
)
2587 if (re_compile_fastmap(bufp
) == -2)
2590 /* Loop through the string, looking for a place to start matching. */
2592 /* If a fastmap is supplied, skip quickly over characters that
2593 * cannot be the start of a match. If the pattern can match the
2594 * null string, however, we don't need to skip characters; we want
2595 * the first null string. */
2596 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
) {
2597 if (range
> 0) { /* Searching forwards. */
2598 register const char *d
;
2599 register int lim
= 0;
2602 if (startpos
< size1
&& startpos
+ range
>= size1
)
2603 lim
= range
- (size1
- startpos
);
2605 d
= (startpos
>= size1
? string2
- size1
: string1
) + startpos
;
2607 /* Written out as an if-else to avoid testing `translate'
2608 * inside the loop. */
2611 && !fastmap
[(unsigned char)
2612 translate
[(unsigned char) *d
++]])
2615 while (range
> lim
&& !fastmap
[(unsigned char) *d
++])
2618 startpos
+= irange
- range
;
2619 } else { /* Searching backwards. */
2620 register char c
= (size1
== 0 || startpos
>= size1
2621 ? string2
[startpos
- size1
]
2622 : string1
[startpos
]);
2624 if (!fastmap
[(unsigned char) TRANSLATE(c
)])
2628 /* If can't match the null string, and that's all we have left, fail. */
2629 if (range
>= 0 && startpos
== total_size
&& fastmap
2630 && !bufp
->can_be_null
)
2633 val
= re_match_2(bufp
, string1
, size1
, string2
, size2
,
2634 startpos
, regs
, stop
);
2644 else if (range
> 0) {
2655 /* Declarations and macros for re_match_2. */
2657 /* Structure for per-register (a.k.a. per-group) information.
2658 * This must not be longer than one word, because we push this value
2659 * onto the failure stack. Other register information, such as the
2660 * starting and ending positions (which are addresses), and the list of
2661 * inner groups (which is a bits list) are maintained in separate
2664 * We are making a (strictly speaking) nonportable assumption here: that
2665 * the compiler will pack our bit fields into something that fits into
2666 * the type of `word', i.e., is something that fits into one item on the
2669 fail_stack_elt_t word
;
2671 /* This field is one if this group can match the empty string,
2672 * zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
2673 #define MATCH_NULL_UNSET_VALUE 3
2674 unsigned match_null_string_p
:2;
2675 unsigned is_active
:1;
2676 unsigned matched_something
:1;
2677 unsigned ever_matched_something
:1;
2679 } register_info_type
;
2680 static boolean
alt_match_null_string_p(unsigned char *p
, unsigned char *end
, register_info_type
*reg_info
);
2681 static boolean
common_op_match_null_string_p( unsigned char **p
, unsigned char *end
, register_info_type
*reg_info
);
2682 static int bcmp_translate(unsigned char const *s1
, unsigned char const *s2
, register int len
, char *translate
);
2683 static boolean
group_match_null_string_p(unsigned char **p
, unsigned char *end
, register_info_type
*reg_info
);
2685 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
2686 #define IS_ACTIVE(R) ((R).bits.is_active)
2687 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
2688 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
2690 /* Call this when have matched a real character; it sets `matched' flags
2691 * for the subexpressions which we are currently inside. Also records
2692 * that those subexprs have matched. */
2693 #define SET_REGS_MATCHED() \
2697 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
2699 MATCHED_SOMETHING (reg_info[r]) \
2700 = EVER_MATCHED_SOMETHING (reg_info[r]) \
2706 /* This converts PTR, a pointer into one of the search strings `string1'
2707 * and `string2' into an offset from the beginning of that string. */
2708 #define POINTER_TO_OFFSET(ptr) \
2709 (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
2711 /* Registers are set to a sentinel when they haven't yet matched. */
2712 #define REG_UNSET_VALUE ((char *) -1)
2713 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
2715 /* Macros for dealing with the split strings in re_match_2. */
2717 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
2719 /* Call before fetching a character with *d. This switches over to
2720 * string2 if necessary. */
2721 #define PREFETCH() \
2724 /* End of string2 => fail. */ \
2725 if (dend == end_match_2) \
2727 /* End of string1 => advance to string2. */ \
2729 dend = end_match_2; \
2732 /* Test if at very beginning or at very end of the virtual concatenation
2733 * of `string1' and `string2'. If only one string, it's `string2'. */
2734 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
2735 #define AT_STRINGS_END(d) ((d) == end2)
2737 /* Test if D points to a character which is word-constituent. We have
2738 * two special cases to check for: if past the end of string1, look at
2739 * the first character in string2; and if before the beginning of
2740 * string2, look at the last character in string1. */
2741 #define WORDCHAR_P(d) \
2742 (SYNTAX ((d) == end1 ? *string2 \
2743 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
2746 /* Test if the character before D and the one at D differ with respect
2747 * to being word-constituent. */
2748 #define AT_WORD_BOUNDARY(d) \
2749 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
2750 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
2752 /* Free everything we malloc. */
2754 #define FREE_VAR(var) if (var) free (var); var = NULL
2755 #define FREE_VARIABLES() \
2757 FREE_VAR (fail_stack.stack); \
2758 FREE_VAR (regstart); \
2759 FREE_VAR (regend); \
2760 FREE_VAR (old_regstart); \
2761 FREE_VAR (old_regend); \
2762 FREE_VAR (best_regstart); \
2763 FREE_VAR (best_regend); \
2764 FREE_VAR (reg_info); \
2765 FREE_VAR (reg_dummy); \
2766 FREE_VAR (reg_info_dummy); \
2768 #else /* not REGEX_MALLOC */
2769 /* Some MIPS systems (at least) want this to free alloca'd storage. */
2770 #define FREE_VARIABLES() alloca (0)
2771 #endif /* not REGEX_MALLOC */
2773 /* These values must meet several constraints. They must not be valid
2774 * register values; since we have a limit of 255 registers (because
2775 * we use only one byte in the pattern for the register number), we can
2776 * use numbers larger than 255. They must differ by 1, because of
2777 * NUM_FAILURE_ITEMS above. And the value for the lowest register must
2778 * be larger than the value for the highest register, so we do not try
2779 * to actually save any registers when none are active. */
2780 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
2781 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
2783 /* Matching routines. */
2785 /* re_match_2 matches the compiled pattern in BUFP against the
2786 * the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
2787 * and SIZE2, respectively). We start matching at POS, and stop
2790 * If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
2791 * store offsets for the substring each group matched in REGS. See the
2792 * documentation for exactly how many groups we fill.
2794 * We return -1 if no match, -2 if an internal error (such as the
2795 * failure stack overflowing). Otherwise, we return the length of the
2796 * matched substring. */
2799 re_match_2(bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
2800 struct re_pattern_buffer
*bufp
;
2801 const char *string1
, *string2
;
2804 struct re_registers
*regs
;
2807 /* General temporaries. */
2811 /* Just past the end of the corresponding string. */
2812 const char *end1
, *end2
;
2814 /* Pointers into string1 and string2, just past the last characters in
2815 * each to consider matching. */
2816 const char *end_match_1
, *end_match_2
;
2818 /* Where we are in the data, and the end of the current string. */
2819 const char *d
, *dend
;
2821 /* Where we are in the pattern, and the end of the pattern. */
2822 unsigned char *p
= bufp
->buffer
;
2823 register unsigned char *pend
= p
+ bufp
->used
;
2825 /* We use this to map every character in the string. */
2826 char *translate
= bufp
->translate
;
2828 /* Failure point stack. Each place that can handle a failure further
2829 * down the line pushes a failure point on this stack. It consists of
2830 * restart, regend, and reg_info for all registers corresponding to
2831 * the subexpressions we're currently inside, plus the number of such
2832 * registers, and, finally, two char *'s. The first char * is where
2833 * to resume scanning the pattern; the second one is where to resume
2834 * scanning the strings. If the latter is zero, the failure point is
2835 * a ``dummy''; if a failure happens and the failure point is a dummy,
2836 * it gets discarded and the next next one is tried. */
2837 fail_stack_type fail_stack
;
2839 static unsigned failure_id
= 0;
2840 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
2843 /* We fill all the registers internally, independent of what we
2844 * return, for use in backreferences. The number here includes
2845 * an element for register zero. */
2846 unsigned num_regs
= bufp
->re_nsub
+ 1;
2848 /* The currently active registers. */
2849 unsigned long lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
2850 unsigned long highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
2852 /* Information on the contents of registers. These are pointers into
2853 * the input strings; they record just what was matched (on this
2854 * attempt) by a subexpression part of the pattern, that is, the
2855 * regnum-th regstart pointer points to where in the pattern we began
2856 * matching and the regnum-th regend points to right after where we
2857 * stopped matching the regnum-th subexpression. (The zeroth register
2858 * keeps track of what the whole pattern matches.) */
2859 const char **regstart
= NULL
, **regend
= NULL
;
2861 /* If a group that's operated upon by a repetition operator fails to
2862 * match anything, then the register for its start will need to be
2863 * restored because it will have been set to wherever in the string we
2864 * are when we last see its open-group operator. Similarly for a
2865 * register's end. */
2866 const char **old_regstart
= NULL
, **old_regend
= NULL
;
2868 /* The is_active field of reg_info helps us keep track of which (possibly
2869 * nested) subexpressions we are currently in. The matched_something
2870 * field of reg_info[reg_num] helps us tell whether or not we have
2871 * matched any of the pattern so far this time through the reg_num-th
2872 * subexpression. These two fields get reset each time through any
2873 * loop their register is in. */
2874 register_info_type
*reg_info
= NULL
;
2876 /* The following record the register info as found in the above
2877 * variables when we find a match better than any we've seen before.
2878 * This happens as we backtrack through the failure points, which in
2879 * turn happens only if we have not yet matched the entire string. */
2880 unsigned best_regs_set
= false;
2881 const char **best_regstart
= NULL
, **best_regend
= NULL
;
2883 /* Logically, this is `best_regend[0]'. But we don't want to have to
2884 * allocate space for that if we're not allocating space for anything
2885 * else (see below). Also, we never need info about register 0 for
2886 * any of the other register vectors, and it seems rather a kludge to
2887 * treat `best_regend' differently than the rest. So we keep track of
2888 * the end of the best match so far in a separate variable. We
2889 * initialize this to NULL so that when we backtrack the first time
2890 * and need to test it, it's not garbage. */
2891 const char *match_end
= NULL
;
2893 /* Used when we pop values we don't care about. */
2894 const char **reg_dummy
= NULL
;
2895 register_info_type
*reg_info_dummy
= NULL
;
2898 /* Counts the total number of registers pushed. */
2899 unsigned num_regs_pushed
= 0;
2902 DEBUG_PRINT1("\n\nEntering re_match_2.\n");
2906 /* Do not bother to initialize all the register variables if there are
2907 * no groups in the pattern, as it takes a fair amount of time. If
2908 * there are groups, we include space for register 0 (the whole
2909 * pattern), even though we never use it, since it simplifies the
2910 * array indexing. We should fix this. */
2911 if (bufp
->re_nsub
) {
2912 regstart
= REGEX_TALLOC(num_regs
, const char *);
2913 regend
= REGEX_TALLOC(num_regs
, const char *);
2914 old_regstart
= REGEX_TALLOC(num_regs
, const char *);
2915 old_regend
= REGEX_TALLOC(num_regs
, const char *);
2916 best_regstart
= REGEX_TALLOC(num_regs
, const char *);
2917 best_regend
= REGEX_TALLOC(num_regs
, const char *);
2918 reg_info
= REGEX_TALLOC(num_regs
, register_info_type
);
2919 reg_dummy
= REGEX_TALLOC(num_regs
, const char *);
2920 reg_info_dummy
= REGEX_TALLOC(num_regs
, register_info_type
);
2922 if (!(regstart
&& regend
&& old_regstart
&& old_regend
&& reg_info
2923 && best_regstart
&& best_regend
&& reg_dummy
&& reg_info_dummy
)) {
2930 /* We must initialize all our variables to NULL, so that
2931 * `FREE_VARIABLES' doesn't try to free them. */
2932 regstart
= regend
= old_regstart
= old_regend
= best_regstart
2933 = best_regend
= reg_dummy
= NULL
;
2934 reg_info
= reg_info_dummy
= (register_info_type
*) NULL
;
2936 #endif /* REGEX_MALLOC */
2938 /* The starting position is bogus. */
2939 if (pos
< 0 || pos
> size1
+ size2
) {
2943 /* Initialize subexpression text positions to -1 to mark ones that no
2944 * start_memory/stop_memory has been seen for. Also initialize the
2945 * register information struct. */
2946 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++) {
2947 regstart
[mcnt
] = regend
[mcnt
]
2948 = old_regstart
[mcnt
] = old_regend
[mcnt
] = REG_UNSET_VALUE
;
2950 REG_MATCH_NULL_STRING_P(reg_info
[mcnt
]) = MATCH_NULL_UNSET_VALUE
;
2951 IS_ACTIVE(reg_info
[mcnt
]) = 0;
2952 MATCHED_SOMETHING(reg_info
[mcnt
]) = 0;
2953 EVER_MATCHED_SOMETHING(reg_info
[mcnt
]) = 0;
2956 /* We move `string1' into `string2' if the latter's empty -- but not if
2957 * `string1' is null. */
2958 if (size2
== 0 && string1
!= NULL
) {
2964 end1
= string1
+ size1
;
2965 end2
= string2
+ size2
;
2967 /* Compute where to stop matching, within the two strings. */
2968 if (stop
<= size1
) {
2969 end_match_1
= string1
+ stop
;
2970 end_match_2
= string2
;
2973 end_match_2
= string2
+ stop
- size1
;
2976 /* `p' scans through the pattern as `d' scans through the data.
2977 * `dend' is the end of the input string that `d' points within. `d'
2978 * is advanced into the following input string whenever necessary, but
2979 * this happens before fetching; therefore, at the beginning of the
2980 * loop, `d' can be pointing at the end of a string, but it cannot
2981 * equal `string2'. */
2982 if (size1
> 0 && pos
<= size1
) {
2986 d
= string2
+ pos
- size1
;
2990 DEBUG_PRINT1("The compiled pattern is: ");
2991 DEBUG_PRINT_COMPILED_PATTERN(bufp
, p
, pend
);
2992 DEBUG_PRINT1("The string to match is: `");
2993 DEBUG_PRINT_DOUBLE_STRING(d
, string1
, size1
, string2
, size2
);
2994 DEBUG_PRINT1("'\n");
2996 /* This loops over pattern commands. It exits by returning from the
2997 * function if the match is complete, or it drops through if the match
2998 * fails at this starting point in the input data. */
3000 DEBUG_PRINT2("\n0x%x: ", p
);
3002 if (p
== pend
) { /* End of pattern means we might have succeeded. */
3003 DEBUG_PRINT1("end of pattern ... ");
3005 /* If we haven't matched the entire string, and we want the
3006 * longest match, try backtracking. */
3007 if (d
!= end_match_2
) {
3008 DEBUG_PRINT1("backtracking.\n");
3010 if (!FAIL_STACK_EMPTY()) { /* More failure points to try. */
3011 boolean same_str_p
= (FIRST_STRING_P(match_end
)
3012 == MATCHING_IN_FIRST_STRING
);
3014 /* If exceeds best match so far, save it. */
3016 || (same_str_p
&& d
> match_end
)
3017 || (!same_str_p
&& !MATCHING_IN_FIRST_STRING
)) {
3018 best_regs_set
= true;
3021 DEBUG_PRINT1("\nSAVING match as best so far.\n");
3023 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++) {
3024 best_regstart
[mcnt
] = regstart
[mcnt
];
3025 best_regend
[mcnt
] = regend
[mcnt
];
3030 /* If no failure points, don't restore garbage. */
3031 else if (best_regs_set
) {
3033 /* Restore best match. It may happen that `dend ==
3034 * end_match_1' while the restored d is in string2.
3035 * For example, the pattern `x.*y.*z' against the
3036 * strings `x-' and `y-z-', if the two strings are
3037 * not consecutive in memory. */
3038 DEBUG_PRINT1("Restoring best registers.\n");
3041 dend
= ((d
>= string1
&& d
<= end1
)
3042 ? end_match_1
: end_match_2
);
3044 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++) {
3045 regstart
[mcnt
] = best_regstart
[mcnt
];
3046 regend
[mcnt
] = best_regend
[mcnt
];
3049 } /* d != end_match_2 */
3050 DEBUG_PRINT1("Accepting match.\n");
3052 /* If caller wants register contents data back, do it. */
3053 if (regs
&& !bufp
->no_sub
) {
3054 /* Have the register data arrays been allocated? */
3055 if (bufp
->regs_allocated
== REGS_UNALLOCATED
) { /* No. So allocate them with malloc. We need one
3056 * extra element beyond `num_regs' for the `-1' marker
3058 regs
->num_regs
= max(RE_NREGS
, num_regs
+ 1);
3059 regs
->start
= TALLOC(regs
->num_regs
, regoff_t
);
3060 regs
->end
= TALLOC(regs
->num_regs
, regoff_t
);
3061 if (regs
->start
== NULL
|| regs
->end
== NULL
)
3063 bufp
->regs_allocated
= REGS_REALLOCATE
;
3064 } else if (bufp
->regs_allocated
== REGS_REALLOCATE
) { /* Yes. If we need more elements than were already
3065 * allocated, reallocate them. If we need fewer, just
3066 * leave it alone. */
3067 if (regs
->num_regs
< num_regs
+ 1) {
3068 regs
->num_regs
= num_regs
+ 1;
3069 RETALLOC(regs
->start
, regs
->num_regs
, regoff_t
);
3070 RETALLOC(regs
->end
, regs
->num_regs
, regoff_t
);
3071 if (regs
->start
== NULL
|| regs
->end
== NULL
)
3075 assert(bufp
->regs_allocated
== REGS_FIXED
);
3077 /* Convert the pointer data in `regstart' and `regend' to
3078 * indices. Register zero has to be set differently,
3079 * since we haven't kept track of any info for it. */
3080 if (regs
->num_regs
> 0) {
3081 regs
->start
[0] = pos
;
3082 regs
->end
[0] = (MATCHING_IN_FIRST_STRING
? d
- string1
3083 : d
- string2
+ size1
);
3085 /* Go through the first `min (num_regs, regs->num_regs)'
3086 * registers, since that is all we initialized. */
3087 for (mcnt
= 1; mcnt
< min(num_regs
, regs
->num_regs
); mcnt
++) {
3088 if (REG_UNSET(regstart
[mcnt
]) || REG_UNSET(regend
[mcnt
]))
3089 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
3091 regs
->start
[mcnt
] = POINTER_TO_OFFSET(regstart
[mcnt
]);
3092 regs
->end
[mcnt
] = POINTER_TO_OFFSET(regend
[mcnt
]);
3096 /* If the regs structure we return has more elements than
3097 * were in the pattern, set the extra elements to -1. If
3098 * we (re)allocated the registers, this is the case,
3099 * because we always allocate enough to have at least one
3101 for (mcnt
= num_regs
; mcnt
< regs
->num_regs
; mcnt
++)
3102 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
3103 } /* regs && !bufp->no_sub */
3105 DEBUG_PRINT4("%u failure points pushed, %u popped (%u remain).\n",
3106 nfailure_points_pushed
, nfailure_points_popped
,
3107 nfailure_points_pushed
- nfailure_points_popped
);
3108 DEBUG_PRINT2("%u registers pushed.\n", num_regs_pushed
);
3110 mcnt
= d
- pos
- (MATCHING_IN_FIRST_STRING
3114 DEBUG_PRINT2("Returning %d from re_match_2.\n", mcnt
);
3118 /* Otherwise match next pattern command. */
3119 #ifdef SWITCH_ENUM_BUG
3120 switch ((int) ((re_opcode_t
) * p
++))
3122 switch ((re_opcode_t
) * p
++)
3125 /* Ignore these. Used to ignore the n of succeed_n's which
3126 * currently have n == 0. */
3128 DEBUG_PRINT1("EXECUTING no_op.\n");
3131 /* Match the next n pattern characters exactly. The following
3132 * byte in the pattern defines n, and the n bytes after that
3133 * are the characters to match. */
3136 DEBUG_PRINT2("EXECUTING exactn %d.\n", mcnt
);
3138 /* This is written out as an if-else so we don't waste time
3139 * testing `translate' inside the loop. */
3143 if (translate
[(unsigned char) *d
++] != (char) *p
++)
3149 if (*d
++ != (char) *p
++)
3156 /* Match any character except possibly a newline or a null. */
3158 DEBUG_PRINT1("EXECUTING anychar.\n");
3162 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
) && TRANSLATE(*d
) == '\n')
3163 || (bufp
->syntax
& RE_DOT_NOT_NULL
&& TRANSLATE(*d
) == '\000'))
3167 DEBUG_PRINT2(" Matched `%d'.\n", *d
);
3173 register unsigned char c
;
3174 boolean
not = (re_opcode_t
) * (p
- 1) == charset_not
;
3176 DEBUG_PRINT2("EXECUTING charset%s.\n", not ? "_not" : "");
3179 c
= TRANSLATE(*d
); /* The character to match. */
3181 /* Cast to `unsigned' instead of `unsigned char' in case the
3182 * bit list is a full 32 bytes long. */
3183 if (c
< (unsigned) (*p
* BYTEWIDTH
)
3184 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
3197 /* The beginning of a group is represented by start_memory.
3198 * The arguments are the register number in the next byte, and the
3199 * number of groups inner to this one in the next. The text
3200 * matched within the group is recorded (in the internal
3201 * registers data structure) under the register number. */
3203 DEBUG_PRINT3("EXECUTING start_memory %d (%d):\n", *p
, p
[1]);
3205 /* Find out if this group can match the empty string. */
3206 p1
= p
; /* To send to group_match_null_string_p. */
3208 if (REG_MATCH_NULL_STRING_P(reg_info
[*p
]) == MATCH_NULL_UNSET_VALUE
)
3209 REG_MATCH_NULL_STRING_P(reg_info
[*p
])
3210 = group_match_null_string_p(&p1
, pend
, reg_info
);
3212 /* Save the position in the string where we were the last time
3213 * we were at this open-group operator in case the group is
3214 * operated upon by a repetition operator, e.g., with `(a*)*b'
3215 * against `ab'; then we want to ignore where we are now in
3216 * the string in case this attempt to match fails. */
3217 old_regstart
[*p
] = REG_MATCH_NULL_STRING_P(reg_info
[*p
])
3218 ? REG_UNSET(regstart
[*p
]) ? d
: regstart
[*p
]
3220 DEBUG_PRINT2(" old_regstart: %d\n",
3221 POINTER_TO_OFFSET(old_regstart
[*p
]));
3224 DEBUG_PRINT2(" regstart: %d\n", POINTER_TO_OFFSET(regstart
[*p
]));
3226 IS_ACTIVE(reg_info
[*p
]) = 1;
3227 MATCHED_SOMETHING(reg_info
[*p
]) = 0;
3229 /* This is the new highest active register. */
3230 highest_active_reg
= *p
;
3232 /* If nothing was active before, this is the new lowest active
3234 if (lowest_active_reg
== NO_LOWEST_ACTIVE_REG
)
3235 lowest_active_reg
= *p
;
3237 /* Move past the register number and inner group count. */
3241 /* The stop_memory opcode represents the end of a group. Its
3242 * arguments are the same as start_memory's: the register
3243 * number, and the number of inner groups. */
3245 DEBUG_PRINT3("EXECUTING stop_memory %d (%d):\n", *p
, p
[1]);
3247 /* We need to save the string position the last time we were at
3248 * this close-group operator in case the group is operated
3249 * upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3250 * against `aba'; then we want to ignore where we are now in
3251 * the string in case this attempt to match fails. */
3252 old_regend
[*p
] = REG_MATCH_NULL_STRING_P(reg_info
[*p
])
3253 ? REG_UNSET(regend
[*p
]) ? d
: regend
[*p
]
3255 DEBUG_PRINT2(" old_regend: %d\n",
3256 POINTER_TO_OFFSET(old_regend
[*p
]));
3259 DEBUG_PRINT2(" regend: %d\n", POINTER_TO_OFFSET(regend
[*p
]));
3261 /* This register isn't active anymore. */
3262 IS_ACTIVE(reg_info
[*p
]) = 0;
3264 /* If this was the only register active, nothing is active
3266 if (lowest_active_reg
== highest_active_reg
) {
3267 lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
3268 highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
3269 } else { /* We must scan for the new highest active register, since
3270 * it isn't necessarily one less than now: consider
3271 * (a(b)c(d(e)f)g). When group 3 ends, after the f), the
3272 * new highest active register is 1. */
3273 unsigned char r
= *p
- 1;
3274 while (r
> 0 && !IS_ACTIVE(reg_info
[r
]))
3277 /* If we end up at register zero, that means that we saved
3278 * the registers as the result of an `on_failure_jump', not
3279 * a `start_memory', and we jumped to past the innermost
3280 * `stop_memory'. For example, in ((.)*) we save
3281 * registers 1 and 2 as a result of the *, but when we pop
3282 * back to the second ), we are at the stop_memory 1.
3283 * Thus, nothing is active. */
3285 lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
3286 highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
3288 highest_active_reg
= r
;
3291 /* If just failed to match something this time around with a
3292 * group that's operated on by a repetition operator, try to
3293 * force exit from the ``loop'', and restore the register
3294 * information for this group that we had before trying this
3296 if ((!MATCHED_SOMETHING(reg_info
[*p
])
3297 || (re_opcode_t
) p
[-3] == start_memory
)
3298 && (p
+ 2) < pend
) {
3299 boolean is_a_jump_n
= false;
3303 switch ((re_opcode_t
) * p1
++) {
3306 case pop_failure_jump
:
3307 case maybe_pop_jump
:
3309 case dummy_failure_jump
:
3310 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
3321 /* If the next operation is a jump backwards in the pattern
3322 * to an on_failure_jump right before the start_memory
3323 * corresponding to this stop_memory, exit from the loop
3324 * by forcing a failure after pushing on the stack the
3325 * on_failure_jump's jump in the pattern, and d. */
3326 if (mcnt
< 0 && (re_opcode_t
) * p1
== on_failure_jump
3327 && (re_opcode_t
) p1
[3] == start_memory
&& p1
[4] == *p
) {
3328 /* If this group ever matched anything, then restore
3329 * what its registers were before trying this last
3330 * failed match, e.g., with `(a*)*b' against `ab' for
3331 * regstart[1], and, e.g., with `((a*)*(b*)*)*'
3332 * against `aba' for regend[3].
3334 * Also restore the registers for inner groups for,
3335 * e.g., `((a*)(b*))*' against `aba' (register 3 would
3336 * otherwise get trashed). */
3338 if (EVER_MATCHED_SOMETHING(reg_info
[*p
])) {
3341 EVER_MATCHED_SOMETHING(reg_info
[*p
]) = 0;
3343 /* Restore this and inner groups' (if any) registers. */
3344 for (r
= *p
; r
< *p
+ *(p
+ 1); r
++) {
3345 regstart
[r
] = old_regstart
[r
];
3347 /* xx why this test? */
3348 if ((long) old_regend
[r
] >= (long) regstart
[r
])
3349 regend
[r
] = old_regend
[r
];
3353 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
3354 PUSH_FAILURE_POINT(p1
+ mcnt
, d
, -2);
3359 /* Move past the register number and the inner group count. */
3363 /* \<digit> has been turned into a `duplicate' command which is
3364 * followed by the numeric value of <digit> as the register number. */
3366 register const char *d2
, *dend2
;
3367 int regno
= *p
++; /* Get which register to match against. */
3368 DEBUG_PRINT2("EXECUTING duplicate %d.\n", regno
);
3370 /* Can't back reference a group which we've never matched. */
3371 if (REG_UNSET(regstart
[regno
]) || REG_UNSET(regend
[regno
]))
3374 /* Where in input to try to start matching. */
3375 d2
= regstart
[regno
];
3377 /* Where to stop matching; if both the place to start and
3378 * the place to stop matching are in the same string, then
3379 * set to the place to stop, otherwise, for now have to use
3380 * the end of the first string. */
3382 dend2
= ((FIRST_STRING_P(regstart
[regno
])
3383 == FIRST_STRING_P(regend
[regno
]))
3384 ? regend
[regno
] : end_match_1
);
3386 /* If necessary, advance to next segment in register
3388 while (d2
== dend2
) {
3389 if (dend2
== end_match_2
)
3391 if (dend2
== regend
[regno
])
3394 /* End of string1 => advance to string2. */
3396 dend2
= regend
[regno
];
3398 /* At end of register contents => success */
3402 /* If necessary, advance to next segment in data. */
3405 /* How many characters left in this segment to match. */
3408 /* Want how many consecutive characters we can match in
3409 * one shot, so, if necessary, adjust the count. */
3410 if (mcnt
> dend2
- d2
)
3413 /* Compare that many; failure if mismatch, else move
3416 ? bcmp_translate((unsigned char *)d
, (unsigned char *)d2
, mcnt
, translate
)
3417 : memcmp(d
, d2
, mcnt
))
3419 d
+= mcnt
, d2
+= mcnt
;
3424 /* begline matches the empty string at the beginning of the string
3425 * (unless `not_bol' is set in `bufp'), and, if
3426 * `newline_anchor' is set, after newlines. */
3428 DEBUG_PRINT1("EXECUTING begline.\n");
3430 if (AT_STRINGS_BEG(d
)) {
3433 } else if (d
[-1] == '\n' && bufp
->newline_anchor
) {
3436 /* In all other cases, we fail. */
3439 /* endline is the dual of begline. */
3441 DEBUG_PRINT1("EXECUTING endline.\n");
3443 if (AT_STRINGS_END(d
)) {
3447 /* We have to ``prefetch'' the next character. */
3448 else if ((d
== end1
? *string2
: *d
) == '\n'
3449 && bufp
->newline_anchor
) {
3454 /* Match at the very beginning of the data. */
3456 DEBUG_PRINT1("EXECUTING begbuf.\n");
3457 if (AT_STRINGS_BEG(d
))
3461 /* Match at the very end of the data. */
3463 DEBUG_PRINT1("EXECUTING endbuf.\n");
3464 if (AT_STRINGS_END(d
))
3468 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
3469 * pushes NULL as the value for the string on the stack. Then
3470 * `pop_failure_point' will keep the current value for the
3471 * string, instead of restoring it. To see why, consider
3472 * matching `foo\nbar' against `.*\n'. The .* matches the foo;
3473 * then the . fails against the \n. But the next thing we want
3474 * to do is match the \n against the \n; if we restored the
3475 * string value, we would be back at the foo.
3477 * Because this is used only in specific cases, we don't need to
3478 * check all the things that `on_failure_jump' does, to make
3479 * sure the right things get saved on the stack. Hence we don't
3480 * share its code. The only reason to push anything on the
3481 * stack at all is that otherwise we would have to change
3482 * `anychar's code to do something besides goto fail in this
3483 * case; that seems worse than this. */
3484 case on_failure_keep_string_jump
:
3485 DEBUG_PRINT1("EXECUTING on_failure_keep_string_jump");
3487 EXTRACT_NUMBER_AND_INCR(mcnt
, p
);
3488 DEBUG_PRINT3(" %d (to 0x%x):\n", mcnt
, p
+ mcnt
);
3490 PUSH_FAILURE_POINT(p
+ mcnt
, NULL
, -2);
3493 /* Uses of on_failure_jump:
3495 * Each alternative starts with an on_failure_jump that points
3496 * to the beginning of the next alternative. Each alternative
3497 * except the last ends with a jump that in effect jumps past
3498 * the rest of the alternatives. (They really jump to the
3499 * ending jump of the following alternative, because tensioning
3500 * these jumps is a hassle.)
3502 * Repeats start with an on_failure_jump that points past both
3503 * the repetition text and either the following jump or
3504 * pop_failure_jump back to this on_failure_jump. */
3505 case on_failure_jump
:
3507 DEBUG_PRINT1("EXECUTING on_failure_jump");
3509 EXTRACT_NUMBER_AND_INCR(mcnt
, p
);
3510 DEBUG_PRINT3(" %d (to 0x%x)", mcnt
, p
+ mcnt
);
3512 /* If this on_failure_jump comes right before a group (i.e.,
3513 * the original * applied to a group), save the information
3514 * for that group and all inner ones, so that if we fail back
3515 * to this point, the group's information will be correct.
3516 * For example, in \(a*\)*\1, we need the preceding group,
3517 * and in \(\(a*\)b*\)\2, we need the inner group. */
3519 /* We can't use `p' to check ahead because we push
3520 * a failure point to `p + mcnt' after we do this. */
3523 /* We need to skip no_op's before we look for the
3524 * start_memory in case this on_failure_jump is happening as
3525 * the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
3527 while (p1
< pend
&& (re_opcode_t
) * p1
== no_op
)
3530 if (p1
< pend
&& (re_opcode_t
) * p1
== start_memory
) {
3531 /* We have a new highest active register now. This will
3532 * get reset at the start_memory we are about to get to,
3533 * but we will have saved all the registers relevant to
3534 * this repetition op, as described above. */
3535 highest_active_reg
= *(p1
+ 1) + *(p1
+ 2);
3536 if (lowest_active_reg
== NO_LOWEST_ACTIVE_REG
)
3537 lowest_active_reg
= *(p1
+ 1);
3539 DEBUG_PRINT1(":\n");
3540 PUSH_FAILURE_POINT(p
+ mcnt
, d
, -2);
3543 /* A smart repeat ends with `maybe_pop_jump'.
3544 * We change it to either `pop_failure_jump' or `jump'. */
3545 case maybe_pop_jump
:
3546 EXTRACT_NUMBER_AND_INCR(mcnt
, p
);
3547 DEBUG_PRINT2("EXECUTING maybe_pop_jump %d.\n", mcnt
);
3549 register unsigned char *p2
= p
;
3551 /* Compare the beginning of the repeat with what in the
3552 * pattern follows its end. If we can establish that there
3553 * is nothing that they would both match, i.e., that we
3554 * would have to backtrack because of (as in, e.g., `a*a')
3555 * then we can change to pop_failure_jump, because we'll
3556 * never have to backtrack.
3558 * This is not true in the case of alternatives: in
3559 * `(a|ab)*' we do need to backtrack to the `ab' alternative
3560 * (e.g., if the string was `ab'). But instead of trying to
3561 * detect that here, the alternative has put on a dummy
3562 * failure point which is what we will end up popping. */
3564 /* Skip over open/close-group commands. */
3565 while (p2
+ 2 < pend
3566 && ((re_opcode_t
) * p2
== stop_memory
3567 || (re_opcode_t
) * p2
== start_memory
))
3568 p2
+= 3; /* Skip over args, too. */
3570 /* If we're at the end of the pattern, we can change. */
3572 /* Consider what happens when matching ":\(.*\)"
3573 * against ":/". I don't really understand this code
3575 p
[-3] = (unsigned char) pop_failure_jump
;
3577 (" End of pattern: change to `pop_failure_jump'.\n");
3578 } else if ((re_opcode_t
) * p2
== exactn
3579 || (bufp
->newline_anchor
&& (re_opcode_t
) * p2
== endline
)) {
3580 register unsigned char c
3581 = *p2
== (unsigned char) endline
? '\n' : p2
[2];
3584 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
3585 * to the `maybe_finalize_jump' of this case. Examine what
3587 if ((re_opcode_t
) p1
[3] == exactn
&& p1
[5] != c
) {
3588 p
[-3] = (unsigned char) pop_failure_jump
;
3589 DEBUG_PRINT3(" %c != %c => pop_failure_jump.\n",
3591 } else if ((re_opcode_t
) p1
[3] == charset
3592 || (re_opcode_t
) p1
[3] == charset_not
) {
3593 int not = (re_opcode_t
) p1
[3] == charset_not
;
3595 if (c
< (unsigned char) (p1
[4] * BYTEWIDTH
)
3596 && p1
[5 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
3599 /* `not' is equal to 1 if c would match, which means
3600 * that we can't change to pop_failure_jump. */
3602 p
[-3] = (unsigned char) pop_failure_jump
;
3603 DEBUG_PRINT1(" No match => pop_failure_jump.\n");
3608 p
-= 2; /* Point at relative address again. */
3609 if ((re_opcode_t
) p
[-1] != pop_failure_jump
) {
3610 p
[-1] = (unsigned char) jump
;
3611 DEBUG_PRINT1(" Match => jump.\n");
3612 goto unconditional_jump
;
3614 /* Note fall through. */
3616 /* The end of a simple repeat has a pop_failure_jump back to
3617 * its matching on_failure_jump, where the latter will push a
3618 * failure point. The pop_failure_jump takes off failure
3619 * points put on by this pop_failure_jump's matching
3620 * on_failure_jump; we got through the pattern to here from the
3621 * matching on_failure_jump, so didn't fail. */
3622 case pop_failure_jump
: {
3623 /* We need to pass separate storage for the lowest and
3624 * highest registers, even though we don't care about the
3625 * actual values. Otherwise, we will restore only one
3626 * register from the stack, since lowest will == highest in
3627 * `pop_failure_point'. */
3628 unsigned long dummy_low_reg
, dummy_high_reg
;
3629 unsigned char *pdummy
;
3632 DEBUG_PRINT1("EXECUTING pop_failure_jump.\n");
3633 POP_FAILURE_POINT(sdummy
, pdummy
,
3634 dummy_low_reg
, dummy_high_reg
,
3635 reg_dummy
, reg_dummy
, reg_info_dummy
);
3636 /* avoid GCC 4.6 set but unused variables warning. Does not matter here. */
3637 if (pdummy
|| sdummy
)
3640 /* Note fall through. */
3642 /* Unconditionally jump (without popping any failure points). */
3645 EXTRACT_NUMBER_AND_INCR(mcnt
, p
); /* Get the amount to jump. */
3646 DEBUG_PRINT2("EXECUTING jump %d ", mcnt
);
3647 p
+= mcnt
; /* Do the jump. */
3648 DEBUG_PRINT2("(to 0x%x).\n", p
);
3651 /* We need this opcode so we can detect where alternatives end
3652 * in `group_match_null_string_p' et al. */
3654 DEBUG_PRINT1("EXECUTING jump_past_alt.\n");
3655 goto unconditional_jump
;
3657 /* Normally, the on_failure_jump pushes a failure point, which
3658 * then gets popped at pop_failure_jump. We will end up at
3659 * pop_failure_jump, also, and with a pattern of, say, `a+', we
3660 * are skipping over the on_failure_jump, so we have to push
3661 * something meaningless for pop_failure_jump to pop. */
3662 case dummy_failure_jump
:
3663 DEBUG_PRINT1("EXECUTING dummy_failure_jump.\n");
3664 /* It doesn't matter what we push for the string here. What
3665 * the code at `fail' tests is the value for the pattern. */
3666 PUSH_FAILURE_POINT(0, 0, -2);
3667 goto unconditional_jump
;
3669 /* At the end of an alternative, we need to push a dummy failure
3670 * point in case we are followed by a `pop_failure_jump', because
3671 * we don't want the failure point for the alternative to be
3672 * popped. For example, matching `(a|ab)*' against `aab'
3673 * requires that we match the `ab' alternative. */
3674 case push_dummy_failure
:
3675 DEBUG_PRINT1("EXECUTING push_dummy_failure.\n");
3676 /* See comments just above at `dummy_failure_jump' about the
3678 PUSH_FAILURE_POINT(0, 0, -2);
3681 /* Have to succeed matching what follows at least n times.
3682 * After that, handle like `on_failure_jump'. */
3684 EXTRACT_NUMBER(mcnt
, p
+ 2);
3685 DEBUG_PRINT2("EXECUTING succeed_n %d.\n", mcnt
);
3688 /* Originally, this is how many times we HAVE to succeed. */
3692 STORE_NUMBER_AND_INCR(p
, mcnt
);
3693 DEBUG_PRINT3(" Setting 0x%x to %d.\n", p
, mcnt
);
3694 } else if (mcnt
== 0) {
3695 DEBUG_PRINT2(" Setting two bytes from 0x%x to no_op.\n", p
+ 2);
3696 p
[2] = (unsigned char) no_op
;
3697 p
[3] = (unsigned char) no_op
;
3703 EXTRACT_NUMBER(mcnt
, p
+ 2);
3704 DEBUG_PRINT2("EXECUTING jump_n %d.\n", mcnt
);
3706 /* Originally, this is how many times we CAN jump. */
3709 STORE_NUMBER(p
+ 2, mcnt
);
3710 goto unconditional_jump
;
3712 /* If don't have to jump any more, skip over the rest of command. */
3717 case set_number_at
: {
3718 DEBUG_PRINT1("EXECUTING set_number_at.\n");
3720 EXTRACT_NUMBER_AND_INCR(mcnt
, p
);
3722 EXTRACT_NUMBER_AND_INCR(mcnt
, p
);
3723 DEBUG_PRINT3(" Setting 0x%x to %d.\n", p1
, mcnt
);
3724 STORE_NUMBER(p1
, mcnt
);
3729 DEBUG_PRINT1("EXECUTING wordbound.\n");
3730 if (AT_WORD_BOUNDARY(d
))
3735 DEBUG_PRINT1("EXECUTING notwordbound.\n");
3736 if (AT_WORD_BOUNDARY(d
))
3741 DEBUG_PRINT1("EXECUTING wordbeg.\n");
3742 if (WORDCHAR_P(d
) && (AT_STRINGS_BEG(d
) || !WORDCHAR_P(d
- 1)))
3747 DEBUG_PRINT1("EXECUTING wordend.\n");
3748 if (!AT_STRINGS_BEG(d
) && WORDCHAR_P(d
- 1)
3749 && (!WORDCHAR_P(d
) || AT_STRINGS_END(d
)))
3754 DEBUG_PRINT1("EXECUTING non-Emacs wordchar.\n");
3763 DEBUG_PRINT1("EXECUTING non-Emacs notwordchar.\n");
3774 continue; /* Successfully executed one pattern command; keep going. */
3776 /* We goto here if a matching operation fails. */
3778 if (!FAIL_STACK_EMPTY()) { /* A restart point is known. Restore to that state. */
3779 DEBUG_PRINT1("\nFAIL:\n");
3780 POP_FAILURE_POINT(d
, p
,
3781 lowest_active_reg
, highest_active_reg
,
3782 regstart
, regend
, reg_info
);
3784 /* If this failure point is a dummy, try the next one. */
3788 /* If we failed to the end of the pattern, don't examine *p. */
3791 boolean is_a_jump_n
= false;
3793 /* If failed to a backwards jump that's part of a repetition
3794 * loop, need to pop this failure point and use the next one. */
3795 switch ((re_opcode_t
) * p
) {
3798 case maybe_pop_jump
:
3799 case pop_failure_jump
:
3802 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
3805 if ((is_a_jump_n
&& (re_opcode_t
) * p1
== succeed_n
)
3807 && (re_opcode_t
) * p1
== on_failure_jump
))
3815 if (d
>= string1
&& d
<= end1
)
3818 break; /* Matching at this starting point really fails. */
3822 goto restore_best_regs
;
3826 return -1; /* Failure to match. */
3829 /* Subroutine definitions for re_match_2. */
3831 /* We are passed P pointing to a register number after a start_memory.
3833 * Return true if the pattern up to the corresponding stop_memory can
3834 * match the empty string, and false otherwise.
3836 * If we find the matching stop_memory, sets P to point to one past its number.
3837 * Otherwise, sets P to an undefined byte less than or equal to END.
3839 * We don't handle duplicates properly (yet). */
3842 group_match_null_string_p(unsigned char **p
, unsigned char *end
, register_info_type
*reg_info
)
3845 /* Point to after the args to the start_memory. */
3846 unsigned char *p1
= *p
+ 2;
3849 /* Skip over opcodes that can match nothing, and return true or
3850 * false, as appropriate, when we get to one that can't, or to the
3851 * matching stop_memory. */
3853 switch ((re_opcode_t
) * p1
) {
3854 /* Could be either a loop or a series of alternatives. */
3855 case on_failure_jump
:
3857 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
3859 /* If the next operation is not a jump backwards in the
3863 /* Go through the on_failure_jumps of the alternatives,
3864 * seeing if any of the alternatives cannot match nothing.
3865 * The last alternative starts with only a jump,
3866 * whereas the rest start with on_failure_jump and end
3867 * with a jump, e.g., here is the pattern for `a|b|c':
3869 * /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
3870 * /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
3873 * So, we have to first go through the first (n-1)
3874 * alternatives and then deal with the last one separately. */
3876 /* Deal with the first (n-1) alternatives, which start
3877 * with an on_failure_jump (see above) that jumps to right
3878 * past a jump_past_alt. */
3880 while ((re_opcode_t
) p1
[mcnt
- 3] == jump_past_alt
) {
3881 /* `mcnt' holds how many bytes long the alternative
3882 * is, including the ending `jump_past_alt' and
3885 if (!alt_match_null_string_p(p1
, p1
+ mcnt
- 3,
3889 /* Move to right after this alternative, including the
3893 /* Break if it's the beginning of an n-th alternative
3894 * that doesn't begin with an on_failure_jump. */
3895 if ((re_opcode_t
) * p1
!= on_failure_jump
)
3898 /* Still have to check that it's not an n-th
3899 * alternative that starts with an on_failure_jump. */
3901 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
3902 if ((re_opcode_t
) p1
[mcnt
- 3] != jump_past_alt
) {
3903 /* Get to the beginning of the n-th alternative. */
3909 /* Deal with the last alternative: go back and get number
3910 * of the `jump_past_alt' just before it. `mcnt' contains
3911 * the length of the alternative. */
3912 EXTRACT_NUMBER(mcnt
, p1
- 2);
3914 if (!alt_match_null_string_p(p1
, p1
+ mcnt
, reg_info
))
3917 p1
+= mcnt
; /* Get past the n-th alternative. */
3922 assert(p1
[1] == **p
);
3927 if (!common_op_match_null_string_p(&p1
, end
, reg_info
))
3930 } /* while p1 < end */
3933 } /* group_match_null_string_p */
3935 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
3936 * It expects P to be the first byte of a single alternative and END one
3937 * byte past the last. The alternative can contain groups. */
3940 alt_match_null_string_p(unsigned char *p
, unsigned char *end
, register_info_type
*reg_info
)
3943 unsigned char *p1
= p
;
3946 /* Skip over opcodes that can match nothing, and break when we get
3947 * to one that can't. */
3949 switch ((re_opcode_t
) * p1
) {
3951 case on_failure_jump
:
3953 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
3958 if (!common_op_match_null_string_p(&p1
, end
, reg_info
))
3961 } /* while p1 < end */
3964 } /* alt_match_null_string_p */
3966 /* Deals with the ops common to group_match_null_string_p and
3967 * alt_match_null_string_p.
3969 * Sets P to one after the op and its arguments, if any. */
3972 common_op_match_null_string_p( unsigned char **p
, unsigned char *end
, register_info_type
*reg_info
)
3977 unsigned char *p1
= *p
;
3979 switch ((re_opcode_t
) * p1
++) {
3993 assert(reg_no
> 0 && reg_no
<= MAX_REGNUM
);
3994 ret
= group_match_null_string_p(&p1
, end
, reg_info
);
3996 /* Have to set this here in case we're checking a group which
3997 * contains a group and a back reference to it. */
3999 if (REG_MATCH_NULL_STRING_P(reg_info
[reg_no
]) == MATCH_NULL_UNSET_VALUE
)
4000 REG_MATCH_NULL_STRING_P(reg_info
[reg_no
]) = ret
;
4006 /* If this is an optimized succeed_n for zero times, make the jump. */
4008 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
4016 /* Get to the number of times to succeed. */
4018 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
4022 EXTRACT_NUMBER_AND_INCR(mcnt
, p1
);
4029 if (!REG_MATCH_NULL_STRING_P(reg_info
[*p1
]))
4037 /* All other opcodes mean we cannot match the empty string. */
4043 } /* common_op_match_null_string_p */
4045 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4046 * bytes; nonzero otherwise. */
4049 bcmp_translate(unsigned char const *s1
, unsigned char const*s2
, register int len
, char *translate
)
4051 register unsigned char const *p1
= s1
, *p2
= s2
;
4053 if (translate
[*p1
++] != translate
[*p2
++])
4060 /* Entry points for GNU code. */
4062 /* POSIX.2 functions */
4064 /* regcomp takes a regular expression as a string and compiles it.
4066 * PREG is a regex_t *. We do not expect any fields to be initialized,
4067 * since POSIX says we shouldn't. Thus, we set
4069 * `buffer' to the compiled pattern;
4070 * `used' to the length of the compiled pattern;
4071 * `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
4072 * REG_EXTENDED bit in CFLAGS is set; otherwise, to
4073 * RE_SYNTAX_POSIX_BASIC;
4074 * `newline_anchor' to REG_NEWLINE being set in CFLAGS;
4075 * `fastmap' and `fastmap_accurate' to zero;
4076 * `re_nsub' to the number of subexpressions in PATTERN.
4078 * PATTERN is the address of the pattern string.
4080 * CFLAGS is a series of bits which affect compilation.
4082 * If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
4083 * use POSIX basic syntax.
4085 * If REG_NEWLINE is set, then . and [^...] don't match newline.
4086 * Also, regexec will try a match beginning after every newline.
4088 * If REG_ICASE is set, then we considers upper- and lowercase
4089 * versions of letters to be equivalent when matching.
4091 * If REG_NOSUB is set, then when PREG is passed to regexec, that
4092 * routine will report only success or failure, and nothing about the
4095 * It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
4096 * the return codes and their meanings.) */
4099 regcomp(preg
, pattern
, cflags
)
4101 const char *pattern
;
4106 = (cflags
& REG_EXTENDED
) ?
4107 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
4109 /* regex_compile will allocate the space for the compiled pattern. */
4111 preg
->allocated
= 0;
4113 /* Don't bother to use a fastmap when searching. This simplifies the
4114 * REG_NEWLINE case: if we used a fastmap, we'd have to put all the
4115 * characters after newlines into the fastmap. This way, we just try
4116 * every character. */
4119 if (cflags
& REG_ICASE
) {
4122 preg
->translate
= (char *) malloc(CHAR_SET_SIZE
);
4123 if (preg
->translate
== NULL
)
4124 return (int) REG_ESPACE
;
4126 /* Map uppercase characters to corresponding lowercase ones. */
4127 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
4128 preg
->translate
[i
] = ISUPPER(i
) ? tolower(i
) : i
;
4130 preg
->translate
= NULL
;
4132 /* If REG_NEWLINE is set, newlines are treated differently. */
4133 if (cflags
& REG_NEWLINE
) { /* REG_NEWLINE implies neither . nor [^...] match newline. */
4134 syntax
&= ~RE_DOT_NEWLINE
;
4135 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
4136 /* It also changes the matching behavior. */
4137 preg
->newline_anchor
= 1;
4139 preg
->newline_anchor
= 0;
4141 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
4143 /* POSIX says a null character in the pattern terminates it, so we
4144 * can use strlen here in compiling the pattern. */
4145 ret
= regex_compile(pattern
, strlen(pattern
), syntax
, preg
);
4147 /* POSIX doesn't distinguish between an unmatched open-group and an
4148 * unmatched close-group: both are REG_EPAREN. */
4149 if (ret
== REG_ERPAREN
)
4155 /* regexec searches for a given pattern, specified by PREG, in the
4158 * If NMATCH is zero or REG_NOSUB was set in the cflags argument to
4159 * `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
4160 * least NMATCH elements, and we set them to the offsets of the
4161 * corresponding matched substrings.
4163 * EFLAGS specifies `execution flags' which affect matching: if
4164 * REG_NOTBOL is set, then ^ does not match at the beginning of the
4165 * string; if REG_NOTEOL is set, then $ does not match at the end.
4167 * We return 0 if we find a match and REG_NOMATCH if not. */
4170 regexec(preg
, string
, nmatch
, pmatch
, eflags
)
4171 const regex_t
*preg
;
4174 regmatch_t pmatch
[];
4178 struct re_registers regs
;
4179 regex_t private_preg
;
4180 int len
= strlen(string
);
4181 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0;
4183 private_preg
= *preg
;
4185 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
4186 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
4188 /* The user has told us exactly how many registers to return
4189 * information about, via `nmatch'. We have to pass that on to the
4190 * matching routines. */
4191 private_preg
.regs_allocated
= REGS_FIXED
;
4193 if (want_reg_info
) {
4194 regs
.num_regs
= nmatch
;
4195 regs
.start
= TALLOC(nmatch
, regoff_t
);
4196 regs
.end
= TALLOC(nmatch
, regoff_t
);
4197 if (regs
.start
== NULL
|| regs
.end
== NULL
)
4198 return (int) REG_NOMATCH
;
4200 /* Perform the searching operation. */
4201 ret
= re_search(&private_preg
, string
, len
,
4202 /* start: */ 0, /* range: */ len
,
4203 want_reg_info
? ®s
: (struct re_registers
*) 0);
4205 /* Copy the register information to the POSIX structure. */
4206 if (want_reg_info
) {
4210 for (r
= 0; r
< nmatch
; r
++) {
4211 pmatch
[r
].rm_so
= regs
.start
[r
];
4212 pmatch
[r
].rm_eo
= regs
.end
[r
];
4215 /* If we needed the temporary register info, free the space now. */
4219 /* We want zero return to mean success, unlike `re_search'. */
4220 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
4223 /* Returns a message corresponding to an error code, ERRCODE, returned
4224 * from either regcomp or regexec. We don't use PREG here. */
4227 regerror(int errcode
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
4233 || errcode
>= (sizeof(re_error_msg
) / sizeof(re_error_msg
[0])))
4234 /* Only error codes returned by the rest of the code should be passed
4235 * to this routine. If we are given anything else, or if other regex
4236 * code generates an invalid error code, then the program has a bug.
4237 * Dump core so we can fix it. */
4240 msg
= re_error_msg
[errcode
];
4242 /* POSIX doesn't require that we do anything in this case, but why
4247 msg_size
= strlen(msg
) + 1; /* Includes the null. */
4249 if (errbuf_size
!= 0) {
4250 if (msg_size
> errbuf_size
) {
4251 strncpy(errbuf
, msg
, errbuf_size
- 1);
4252 errbuf
[errbuf_size
- 1] = 0;
4254 strcpy(errbuf
, msg
);
4259 /* Free dynamically allocated space used by PREG. */
4265 if (preg
->buffer
!= NULL
)
4267 preg
->buffer
= NULL
;
4269 preg
->allocated
= 0;
4272 if (preg
->fastmap
!= NULL
)
4273 free(preg
->fastmap
);
4274 preg
->fastmap
= NULL
;
4275 preg
->fastmap_accurate
= 0;
4277 if (preg
->translate
!= NULL
)
4278 free(preg
->translate
);
4279 preg
->translate
= NULL
;
4281 #endif /* USE_GNUREGEX */
4285 * make-backup-files: t
4286 * version-control: t
4287 * trim-versions-without-asking: nil