1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P10003.2/D11.2, except for
3 internationalization features.)
5 Copyright (C) 1993, 1994, 1995, 1996, 1997 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
30 /* Converts the pointer to the char to BEG-based offset from the start. */
31 #define PTR_TO_OFFSET(d) \
32 POS_AS_IN_BUFFER (MATCHING_IN_FIRST_STRING \
33 ? (d) - string1 : (d) - (string2 - size1))
34 #define POS_AS_IN_BUFFER(p) ((p) + 1)
40 /* We need this for `regex.h', and perhaps for the Emacs include files. */
41 #include <sys/types.h>
43 /* This is for other GNU distributions with internationalized messages. */
44 #if HAVE_LIBINTL_H || defined (_LIBC)
47 # define gettext(msgid) (msgid)
51 /* This define is so xgettext can find the internationalizable
53 #define gettext_noop(String) String
56 /* The `emacs' switch turns on certain matching commands
57 that make sense only in Emacs. */
63 /* Make syntax table lookup grant data in gl_state. */
64 #define SYNTAX_ENTRY_VIA_PROPERTY
70 #define malloc xmalloc
71 #define realloc xrealloc
76 /* If we are not linking with Emacs proper,
77 we can't use the relocating allocator
78 even if config.h says that we can. */
81 #if defined (STDC_HEADERS) || defined (_LIBC)
88 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
89 If nothing else has been done, use the method below. */
90 #ifdef INHIBIT_STRING_HEADER
91 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
92 #if !defined (bzero) && !defined (bcopy)
93 #undef INHIBIT_STRING_HEADER
98 /* This is the normal way of making sure we have a bcopy and a bzero.
99 This is used in most programs--a few other programs avoid this
100 by defining INHIBIT_STRING_HEADER. */
101 #ifndef INHIBIT_STRING_HEADER
102 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
105 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
108 #define bcopy(s, d, n) memcpy ((d), (s), (n))
111 #define bzero(s, n) memset ((s), 0, (n))
118 /* Define the syntax stuff for \<, \>, etc. */
120 /* This must be nonzero for the wordchar and notwordchar pattern
121 commands in re_match_2. */
126 #ifdef SWITCH_ENUM_BUG
127 #define SWITCH_ENUM_CAST(x) ((int)(x))
129 #define SWITCH_ENUM_CAST(x) (x)
134 extern char *re_syntax_table;
136 #else /* not SYNTAX_TABLE */
138 /* How many characters in the character set. */
139 #define CHAR_SET_SIZE 256
141 static char re_syntax_table[CHAR_SET_SIZE];
152 bzero (re_syntax_table, sizeof re_syntax_table);
154 for (c = 'a'; c <= 'z'; c++)
155 re_syntax_table[c] = Sword;
157 for (c = 'A'; c <= 'Z'; c++)
158 re_syntax_table[c] = Sword;
160 for (c = '0'; c <= '9'; c++)
161 re_syntax_table[c] = Sword;
163 re_syntax_table['_'] = Sword;
168 #endif /* not SYNTAX_TABLE */
170 #define SYNTAX(c) re_syntax_table[c]
172 /* Dummy macros for non-Emacs environments. */
173 #define BASE_LEADING_CODE_P(c) (0)
174 #define WORD_BOUNDARY_P(c1, c2) (0)
175 #define CHAR_HEAD_P(p) (1)
176 #define SINGLE_BYTE_CHAR_P(c) (1)
177 #define SAME_CHARSET_P(c1, c2) (1)
178 #define MULTIBYTE_FORM_LENGTH(p, s) (1)
179 #define STRING_CHAR(p, s) (*(p))
180 #define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
181 #define GET_CHAR_AFTER_2(c, p, str1, end1, str2, end2) \
182 (c = ((p) == (end1) ? *(str2) : *(p)))
183 #define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
184 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
185 #endif /* not emacs */
187 /* Get the interface, including the syntax bits. */
190 /* isalpha etc. are used for the character classes. */
193 /* Jim Meyering writes:
195 "... Some ctype macros are valid only for character codes that
196 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
197 using /bin/cc or gcc but without giving an ansi option). So, all
198 ctype uses should be through macros like ISPRINT... If
199 STDC_HEADERS is defined, then autoconf has verified that the ctype
200 macros don't need to be guarded with references to isascii. ...
201 Defining isascii to 1 should let any compiler worth its salt
202 eliminate the && through constant folding." */
204 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
207 #define ISASCII(c) isascii(c)
211 #define ISBLANK(c) (ISASCII (c) && isblank (c))
213 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
216 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
218 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
221 #define ISPRINT(c) (ISASCII (c) && isprint (c))
222 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
223 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
224 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
225 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
226 #define ISLOWER(c) (ISASCII (c) && islower (c))
227 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
228 #define ISSPACE(c) (ISASCII (c) && isspace (c))
229 #define ISUPPER(c) (ISASCII (c) && isupper (c))
230 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
233 #define NULL (void *)0
236 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
237 since ours (we hope) works properly with all combinations of
238 machines, compilers, `char' and `unsigned char' argument types.
239 (Per Bothner suggested the basic approach.) */
240 #undef SIGN_EXTEND_CHAR
242 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
243 #else /* not __STDC__ */
244 /* As in Harbison and Steele. */
245 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
248 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
249 use `alloca' instead of `malloc'. This is because using malloc in
250 re_search* or re_match* could cause memory leaks when C-g is used in
251 Emacs; also, malloc is slower and causes storage fragmentation. On
252 the other hand, malloc is more portable, and easier to debug.
254 Because we sometimes use alloca, some routines have to be macros,
255 not functions -- `alloca'-allocated space disappears at the end of the
256 function it is called in. */
260 #define REGEX_ALLOCATE malloc
261 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
262 #define REGEX_FREE free
264 #else /* not REGEX_MALLOC */
266 /* Emacs already defines alloca, sometimes. */
269 /* Make alloca work the best possible way. */
271 #define alloca __builtin_alloca
272 #else /* not __GNUC__ */
275 #else /* not __GNUC__ or HAVE_ALLOCA_H */
276 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
277 #ifndef _AIX /* Already did AIX, up at the top. */
279 #endif /* not _AIX */
281 #endif /* not HAVE_ALLOCA_H */
282 #endif /* not __GNUC__ */
284 #endif /* not alloca */
286 #define REGEX_ALLOCATE alloca
288 /* Assumes a `char *destination' variable. */
289 #define REGEX_REALLOCATE(source, osize, nsize) \
290 (destination = (char *) alloca (nsize), \
291 bcopy (source, destination, osize), \
294 /* No need to do anything to free, after alloca. */
295 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
297 #endif /* not REGEX_MALLOC */
299 /* Define how to allocate the failure stack. */
301 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
303 #define REGEX_ALLOCATE_STACK(size) \
304 r_alloc (&failure_stack_ptr, (size))
305 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
306 r_re_alloc (&failure_stack_ptr, (nsize))
307 #define REGEX_FREE_STACK(ptr) \
308 r_alloc_free (&failure_stack_ptr)
310 #else /* not using relocating allocator */
314 #define REGEX_ALLOCATE_STACK malloc
315 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
316 #define REGEX_FREE_STACK free
318 #else /* not REGEX_MALLOC */
320 #define REGEX_ALLOCATE_STACK alloca
322 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
323 REGEX_REALLOCATE (source, osize, nsize)
324 /* No need to explicitly free anything. */
325 #define REGEX_FREE_STACK(arg)
327 #endif /* not REGEX_MALLOC */
328 #endif /* not using relocating allocator */
331 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
332 `string1' or just past its end. This works if PTR is NULL, which is
334 #define FIRST_STRING_P(ptr) \
335 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
337 /* (Re)Allocate N items of type T using malloc, or fail. */
338 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
339 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
340 #define RETALLOC_IF(addr, n, t) \
341 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
342 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
344 #define BYTEWIDTH 8 /* In bits. */
346 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
350 #define MAX(a, b) ((a) > (b) ? (a) : (b))
351 #define MIN(a, b) ((a) < (b) ? (a) : (b))
353 typedef char boolean;
357 static int re_match_2_internal ();
359 /* These are the command codes that appear in compiled regular
360 expressions. Some opcodes are followed by argument bytes. A
361 command code can specify any interpretation whatsoever for its
362 arguments. Zero bytes may appear in the compiled regular expression. */
368 /* Succeed right away--no more backtracking. */
371 /* Followed by one byte giving n, then by n literal bytes. */
374 /* Matches any (more or less) character. */
377 /* Matches any one char belonging to specified set. First
378 following byte is number of bitmap bytes. Then come bytes
379 for a bitmap saying which chars are in. Bits in each byte
380 are ordered low-bit-first. A character is in the set if its
381 bit is 1. A character too large to have a bit in the map is
382 automatically not in the set. */
385 /* Same parameters as charset, but match any character that is
386 not one of those specified. */
389 /* Start remembering the text that is matched, for storing in a
390 register. Followed by one byte with the register number, in
391 the range 0 to one less than the pattern buffer's re_nsub
392 field. Then followed by one byte with the number of groups
393 inner to this one. (This last has to be part of the
394 start_memory only because we need it in the on_failure_jump
398 /* Stop remembering the text that is matched and store it in a
399 memory register. Followed by one byte with the register
400 number, in the range 0 to one less than `re_nsub' in the
401 pattern buffer, and one byte with the number of inner groups,
402 just like `start_memory'. (We need the number of inner
403 groups here because we don't have any easy way of finding the
404 corresponding start_memory when we're at a stop_memory.) */
407 /* Match a duplicate of something remembered. Followed by one
408 byte containing the register number. */
411 /* Fail unless at beginning of line. */
414 /* Fail unless at end of line. */
417 /* Succeeds if at beginning of buffer (if emacs) or at beginning
418 of string to be matched (if not). */
421 /* Analogously, for end of buffer/string. */
424 /* Followed by two byte relative address to which to jump. */
427 /* Same as jump, but marks the end of an alternative. */
430 /* Followed by two-byte relative address of place to resume at
431 in case of failure. */
434 /* Like on_failure_jump, but pushes a placeholder instead of the
435 current string position when executed. */
436 on_failure_keep_string_jump,
438 /* Throw away latest failure point and then jump to following
439 two-byte relative address. */
442 /* Change to pop_failure_jump if know won't have to backtrack to
443 match; otherwise change to jump. This is used to jump
444 back to the beginning of a repeat. If what follows this jump
445 clearly won't match what the repeat does, such that we can be
446 sure that there is no use backtracking out of repetitions
447 already matched, then we change it to a pop_failure_jump.
448 Followed by two-byte address. */
451 /* Jump to following two-byte address, and push a dummy failure
452 point. This failure point will be thrown away if an attempt
453 is made to use it for a failure. A `+' construct makes this
454 before the first repeat. Also used as an intermediary kind
455 of jump when compiling an alternative. */
458 /* Push a dummy failure point and continue. Used at the end of
462 /* Followed by two-byte relative address and two-byte number n.
463 After matching N times, jump to the address upon failure. */
466 /* Followed by two-byte relative address, and two-byte number n.
467 Jump to the address N times, then fail. */
470 /* Set the following two-byte relative address to the
471 subsequent two-byte number. The address *includes* the two
475 wordchar, /* Matches any word-constituent character. */
476 notwordchar, /* Matches any char that is not a word-constituent. */
478 wordbeg, /* Succeeds if at word beginning. */
479 wordend, /* Succeeds if at word end. */
481 wordbound, /* Succeeds if at a word boundary. */
482 notwordbound /* Succeeds if not at a word boundary. */
485 ,before_dot, /* Succeeds if before point. */
486 at_dot, /* Succeeds if at point. */
487 after_dot, /* Succeeds if after point. */
489 /* Matches any character whose syntax is specified. Followed by
490 a byte which contains a syntax code, e.g., Sword. */
493 /* Matches any character whose syntax is not that specified. */
496 /* Matches any character whose category-set contains the specified
497 category. The operator is followed by a byte which contains a
498 category code (mnemonic ASCII character). */
501 /* Matches any character whose category-set does not contain the
502 specified category. The operator is followed by a byte which
503 contains the category code (mnemonic ASCII character). */
508 /* Common operations on the compiled pattern. */
510 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
512 #define STORE_NUMBER(destination, number) \
514 (destination)[0] = (number) & 0377; \
515 (destination)[1] = (number) >> 8; \
518 /* Same as STORE_NUMBER, except increment DESTINATION to
519 the byte after where the number is stored. Therefore, DESTINATION
520 must be an lvalue. */
522 #define STORE_NUMBER_AND_INCR(destination, number) \
524 STORE_NUMBER (destination, number); \
525 (destination) += 2; \
528 /* Put into DESTINATION a number stored in two contiguous bytes starting
531 #define EXTRACT_NUMBER(destination, source) \
533 (destination) = *(source) & 0377; \
534 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
539 extract_number (dest, source)
541 unsigned char *source;
543 int temp = SIGN_EXTEND_CHAR (*(source + 1));
544 *dest = *source & 0377;
548 #ifndef EXTRACT_MACROS /* To debug the macros. */
549 #undef EXTRACT_NUMBER
550 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
551 #endif /* not EXTRACT_MACROS */
555 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
556 SOURCE must be an lvalue. */
558 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
560 EXTRACT_NUMBER (destination, source); \
566 extract_number_and_incr (destination, source)
568 unsigned char **source;
570 extract_number (destination, *source);
574 #ifndef EXTRACT_MACROS
575 #undef EXTRACT_NUMBER_AND_INCR
576 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
577 extract_number_and_incr (&dest, &src)
578 #endif /* not EXTRACT_MACROS */
582 /* Store a multibyte character in three contiguous bytes starting
583 DESTINATION, and increment DESTINATION to the byte after where the
584 character is stored. Therefore, DESTINATION must be an lvalue. */
586 #define STORE_CHARACTER_AND_INCR(destination, character) \
588 (destination)[0] = (character) & 0377; \
589 (destination)[1] = ((character) >> 8) & 0377; \
590 (destination)[2] = (character) >> 16; \
591 (destination) += 3; \
594 /* Put into DESTINATION a character stored in three contiguous bytes
595 starting at SOURCE. */
597 #define EXTRACT_CHARACTER(destination, source) \
599 (destination) = ((source)[0] \
600 | ((source)[1] << 8) \
601 | ((source)[2] << 16)); \
605 /* Macros for charset. */
607 /* Size of bitmap of charset P in bytes. P is a start of charset,
608 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
609 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
611 /* Nonzero if charset P has range table. */
612 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
614 /* Return the address of range table of charset P. But not the start
615 of table itself, but the before where the number of ranges is
616 stored. `2 +' means to skip re_opcode_t and size of bitmap. */
617 #define CHARSET_RANGE_TABLE(p) (&(p)[2 + CHARSET_BITMAP_SIZE (p)])
619 /* Test if C is listed in the bitmap of charset P. */
620 #define CHARSET_LOOKUP_BITMAP(p, c) \
621 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
622 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
624 /* Return the address of end of RANGE_TABLE. COUNT is number of
625 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
626 is start of range and end of range. `* 3' is size of each start
628 #define CHARSET_RANGE_TABLE_END(range_table, count) \
629 ((range_table) + (count) * 2 * 3)
631 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
632 COUNT is number of ranges in RANGE_TABLE. */
633 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
636 int range_start, range_end; \
638 unsigned char *range_table_end \
639 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
641 for (p = (range_table); p < range_table_end; p += 2 * 3) \
643 EXTRACT_CHARACTER (range_start, p); \
644 EXTRACT_CHARACTER (range_end, p + 3); \
646 if (range_start <= (c) && (c) <= range_end) \
655 /* Test if C is in range table of CHARSET. The flag NOT is negated if
656 C is listed in it. */
657 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
660 /* Number of ranges in range table. */ \
662 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
664 EXTRACT_NUMBER_AND_INCR (count, range_table); \
665 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
669 /* If DEBUG is defined, Regex prints many voluminous messages about what
670 it is doing (if the variable `debug' is nonzero). If linked with the
671 main program in `iregex.c', you can enter patterns and strings
672 interactively. And if linked with the main program in `main.c' and
673 the other test files, you can run the already-written tests. */
677 /* We use standard I/O for debugging. */
680 /* It is useful to test things that ``must'' be true when debugging. */
683 static int debug = 0;
685 #define DEBUG_STATEMENT(e) e
686 #define DEBUG_PRINT1(x) if (debug) printf (x)
687 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
688 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
689 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
690 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
691 if (debug) print_partial_compiled_pattern (s, e)
692 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
693 if (debug) print_double_string (w, s1, sz1, s2, sz2)
696 /* Print the fastmap in human-readable form. */
699 print_fastmap (fastmap)
702 unsigned was_a_range = 0;
705 while (i < (1 << BYTEWIDTH))
711 while (i < (1 << BYTEWIDTH) && fastmap[i])
727 /* Print a compiled pattern string in human-readable form, starting at
728 the START pointer into it and ending just before the pointer END. */
731 print_partial_compiled_pattern (start, end)
732 unsigned char *start;
736 unsigned char *p = start;
737 unsigned char *pend = end;
745 /* Loop over pattern commands. */
748 printf ("%d:\t", p - start);
750 switch ((re_opcode_t) *p++)
758 printf ("/exactn/%d", mcnt);
769 printf ("/start_memory/%d/%d", mcnt, *p++);
774 printf ("/stop_memory/%d/%d", mcnt, *p++);
778 printf ("/duplicate/%d", *p++);
788 register int c, last = -100;
789 register int in_range = 0;
791 printf ("/charset [%s",
792 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
794 assert (p + *p < pend);
796 for (c = 0; c < 256; c++)
798 && (p[1 + (c/8)] & (1 << (c % 8))))
800 /* Are we starting a range? */
801 if (last + 1 == c && ! in_range)
806 /* Have we broken a range? */
807 else if (last + 1 != c && in_range)
836 case on_failure_jump:
837 extract_number_and_incr (&mcnt, &p);
838 printf ("/on_failure_jump to %d", p + mcnt - start);
841 case on_failure_keep_string_jump:
842 extract_number_and_incr (&mcnt, &p);
843 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
846 case dummy_failure_jump:
847 extract_number_and_incr (&mcnt, &p);
848 printf ("/dummy_failure_jump to %d", p + mcnt - start);
851 case push_dummy_failure:
852 printf ("/push_dummy_failure");
856 extract_number_and_incr (&mcnt, &p);
857 printf ("/maybe_pop_jump to %d", p + mcnt - start);
860 case pop_failure_jump:
861 extract_number_and_incr (&mcnt, &p);
862 printf ("/pop_failure_jump to %d", p + mcnt - start);
866 extract_number_and_incr (&mcnt, &p);
867 printf ("/jump_past_alt to %d", p + mcnt - start);
871 extract_number_and_incr (&mcnt, &p);
872 printf ("/jump to %d", p + mcnt - start);
876 extract_number_and_incr (&mcnt, &p);
877 extract_number_and_incr (&mcnt2, &p);
878 printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
882 extract_number_and_incr (&mcnt, &p);
883 extract_number_and_incr (&mcnt2, &p);
884 printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
888 extract_number_and_incr (&mcnt, &p);
889 extract_number_and_incr (&mcnt2, &p);
890 printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
894 printf ("/wordbound");
898 printf ("/notwordbound");
910 printf ("/before_dot");
918 printf ("/after_dot");
922 printf ("/syntaxspec");
924 printf ("/%d", mcnt);
928 printf ("/notsyntaxspec");
930 printf ("/%d", mcnt);
935 printf ("/wordchar");
939 printf ("/notwordchar");
951 printf ("?%d", *(p-1));
957 printf ("%d:\tend of pattern.\n", p - start);
962 print_compiled_pattern (bufp)
963 struct re_pattern_buffer *bufp;
965 unsigned char *buffer = bufp->buffer;
967 print_partial_compiled_pattern (buffer, buffer + bufp->used);
968 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
970 if (bufp->fastmap_accurate && bufp->fastmap)
972 printf ("fastmap: ");
973 print_fastmap (bufp->fastmap);
976 printf ("re_nsub: %d\t", bufp->re_nsub);
977 printf ("regs_alloc: %d\t", bufp->regs_allocated);
978 printf ("can_be_null: %d\t", bufp->can_be_null);
979 printf ("newline_anchor: %d\n", bufp->newline_anchor);
980 printf ("no_sub: %d\t", bufp->no_sub);
981 printf ("not_bol: %d\t", bufp->not_bol);
982 printf ("not_eol: %d\t", bufp->not_eol);
983 printf ("syntax: %d\n", bufp->syntax);
984 /* Perhaps we should print the translate table? */
989 print_double_string (where, string1, size1, string2, size2)
1002 if (FIRST_STRING_P (where))
1004 for (this_char = where - string1; this_char < size1; this_char++)
1005 putchar (string1[this_char]);
1010 for (this_char = where - string2; this_char < size2; this_char++)
1011 putchar (string2[this_char]);
1015 #else /* not DEBUG */
1020 #define DEBUG_STATEMENT(e)
1021 #define DEBUG_PRINT1(x)
1022 #define DEBUG_PRINT2(x1, x2)
1023 #define DEBUG_PRINT3(x1, x2, x3)
1024 #define DEBUG_PRINT4(x1, x2, x3, x4)
1025 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1026 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1028 #endif /* not DEBUG */
1030 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1031 also be assigned to arbitrarily: each pattern buffer stores its own
1032 syntax, so it can be changed between regex compilations. */
1033 /* This has no initializer because initialized variables in Emacs
1034 become read-only after dumping. */
1035 reg_syntax_t re_syntax_options;
1038 /* Specify the precise syntax of regexps for compilation. This provides
1039 for compatibility for various utilities which historically have
1040 different, incompatible syntaxes.
1042 The argument SYNTAX is a bit mask comprised of the various bits
1043 defined in regex.h. We return the old syntax. */
1046 re_set_syntax (syntax)
1047 reg_syntax_t syntax;
1049 reg_syntax_t ret = re_syntax_options;
1051 re_syntax_options = syntax;
1055 /* This table gives an error message for each of the error codes listed
1056 in regex.h. Obviously the order here has to be same as there.
1057 POSIX doesn't require that we do anything for REG_NOERROR,
1058 but why not be nice? */
1060 static const char *re_error_msgid[] =
1062 gettext_noop ("Success"), /* REG_NOERROR */
1063 gettext_noop ("No match"), /* REG_NOMATCH */
1064 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1065 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1066 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1067 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1068 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1069 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1070 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1071 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1072 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1073 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1074 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1075 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1076 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1077 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1078 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1081 /* Avoiding alloca during matching, to placate r_alloc. */
1083 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1084 searching and matching functions should not call alloca. On some
1085 systems, alloca is implemented in terms of malloc, and if we're
1086 using the relocating allocator routines, then malloc could cause a
1087 relocation, which might (if the strings being searched are in the
1088 ralloc heap) shift the data out from underneath the regexp
1091 Here's another reason to avoid allocation: Emacs
1092 processes input from X in a signal handler; processing X input may
1093 call malloc; if input arrives while a matching routine is calling
1094 malloc, then we're scrod. But Emacs can't just block input while
1095 calling matching routines; then we don't notice interrupts when
1096 they come in. So, Emacs blocks input around all regexp calls
1097 except the matching calls, which it leaves unprotected, in the
1098 faith that they will not malloc. */
1100 /* Normally, this is fine. */
1101 #define MATCH_MAY_ALLOCATE
1103 /* When using GNU C, we are not REALLY using the C alloca, no matter
1104 what config.h may say. So don't take precautions for it. */
1109 /* The match routines may not allocate if (1) they would do it with malloc
1110 and (2) it's not safe for them to use malloc.
1111 Note that if REL_ALLOC is defined, matching would not use malloc for the
1112 failure stack, but we would still use it for the register vectors;
1113 so REL_ALLOC should not affect this. */
1114 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1115 #undef MATCH_MAY_ALLOCATE
1119 /* Failure stack declarations and macros; both re_compile_fastmap and
1120 re_match_2 use a failure stack. These have to be macros because of
1121 REGEX_ALLOCATE_STACK. */
1124 /* Approximate number of failure points for which to initially allocate space
1125 when matching. If this number is exceeded, we allocate more
1126 space, so it is not a hard limit. */
1127 #ifndef INIT_FAILURE_ALLOC
1128 #define INIT_FAILURE_ALLOC 20
1131 /* Roughly the maximum number of failure points on the stack. Would be
1132 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1133 This is a variable only so users of regex can assign to it; we never
1134 change it ourselves. */
1135 #if defined (MATCH_MAY_ALLOCATE)
1136 /* Note that 4400 is enough to cause a crash on Alpha OSF/1,
1137 whose default stack limit is 2mb. In order for a larger
1138 value to work reliably, you have to try to make it accord
1139 with the process stack limit. */
1140 int re_max_failures = 40000;
1142 int re_max_failures = 4000;
1145 union fail_stack_elt
1147 unsigned char *pointer;
1151 typedef union fail_stack_elt fail_stack_elt_t;
1155 fail_stack_elt_t *stack;
1157 unsigned avail; /* Offset of next open position. */
1160 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1161 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1162 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1165 /* Define macros to initialize and free the failure stack.
1166 Do `return -2' if the alloc fails. */
1168 #ifdef MATCH_MAY_ALLOCATE
1169 #define INIT_FAIL_STACK() \
1171 fail_stack.stack = (fail_stack_elt_t *) \
1172 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1173 * sizeof (fail_stack_elt_t)); \
1175 if (fail_stack.stack == NULL) \
1178 fail_stack.size = INIT_FAILURE_ALLOC; \
1179 fail_stack.avail = 0; \
1182 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1184 #define INIT_FAIL_STACK() \
1186 fail_stack.avail = 0; \
1189 #define RESET_FAIL_STACK()
1193 /* Double the size of FAIL_STACK, up to a limit
1194 which allows approximately `re_max_failures' items.
1196 Return 1 if succeeds, and 0 if either ran out of memory
1197 allocating space for it or it was already too large.
1199 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1201 /* Factor to increase the failure stack size by
1202 when we increase it.
1203 This used to be 2, but 2 was too wasteful
1204 because the old discarded stacks added up to as much space
1205 were as ultimate, maximum-size stack. */
1206 #define FAIL_STACK_GROWTH_FACTOR 4
1208 #define GROW_FAIL_STACK(fail_stack) \
1209 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1210 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1212 : ((fail_stack).stack \
1213 = (fail_stack_elt_t *) \
1214 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1215 (fail_stack).size * sizeof (fail_stack_elt_t), \
1216 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1217 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1218 * FAIL_STACK_GROWTH_FACTOR))), \
1220 (fail_stack).stack == NULL \
1222 : ((fail_stack).size \
1223 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1224 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1225 * FAIL_STACK_GROWTH_FACTOR)) \
1226 / sizeof (fail_stack_elt_t)), \
1230 /* Push pointer POINTER on FAIL_STACK.
1231 Return 1 if was able to do so and 0 if ran out of memory allocating
1233 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1234 ((FAIL_STACK_FULL () \
1235 && !GROW_FAIL_STACK (FAIL_STACK)) \
1237 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1240 /* Push a pointer value onto the failure stack.
1241 Assumes the variable `fail_stack'. Probably should only
1242 be called from within `PUSH_FAILURE_POINT'. */
1243 #define PUSH_FAILURE_POINTER(item) \
1244 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1246 /* This pushes an integer-valued item onto the failure stack.
1247 Assumes the variable `fail_stack'. Probably should only
1248 be called from within `PUSH_FAILURE_POINT'. */
1249 #define PUSH_FAILURE_INT(item) \
1250 fail_stack.stack[fail_stack.avail++].integer = (item)
1252 /* Push a fail_stack_elt_t value onto the failure stack.
1253 Assumes the variable `fail_stack'. Probably should only
1254 be called from within `PUSH_FAILURE_POINT'. */
1255 #define PUSH_FAILURE_ELT(item) \
1256 fail_stack.stack[fail_stack.avail++] = (item)
1258 /* These three POP... operations complement the three PUSH... operations.
1259 All assume that `fail_stack' is nonempty. */
1260 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1261 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1262 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1264 /* Used to omit pushing failure point id's when we're not debugging. */
1266 #define DEBUG_PUSH PUSH_FAILURE_INT
1267 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1269 #define DEBUG_PUSH(item)
1270 #define DEBUG_POP(item_addr)
1274 /* Push the information about the state we will need
1275 if we ever fail back to it.
1277 Requires variables fail_stack, regstart, regend, reg_info, and
1278 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1281 Does `return FAILURE_CODE' if runs out of memory. */
1283 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1285 char *destination; \
1286 /* Must be int, so when we don't save any registers, the arithmetic \
1287 of 0 + -1 isn't done as unsigned. */ \
1290 DEBUG_STATEMENT (failure_id++); \
1291 DEBUG_STATEMENT (nfailure_points_pushed++); \
1292 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1293 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1294 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1296 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1297 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1299 /* Ensure we have enough space allocated for what we will push. */ \
1300 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1302 if (!GROW_FAIL_STACK (fail_stack)) \
1303 return failure_code; \
1305 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1306 (fail_stack).size); \
1307 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1310 /* Push the info, starting with the registers. */ \
1311 DEBUG_PRINT1 ("\n"); \
1314 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1317 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1318 DEBUG_STATEMENT (num_regs_pushed++); \
1320 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1321 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1323 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1324 PUSH_FAILURE_POINTER (regend[this_reg]); \
1326 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
1327 DEBUG_PRINT2 (" match_null=%d", \
1328 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1329 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1330 DEBUG_PRINT2 (" matched_something=%d", \
1331 MATCHED_SOMETHING (reg_info[this_reg])); \
1332 DEBUG_PRINT2 (" ever_matched=%d", \
1333 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1334 DEBUG_PRINT1 ("\n"); \
1335 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1338 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1339 PUSH_FAILURE_INT (lowest_active_reg); \
1341 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1342 PUSH_FAILURE_INT (highest_active_reg); \
1344 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
1345 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1346 PUSH_FAILURE_POINTER (pattern_place); \
1348 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
1349 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1351 DEBUG_PRINT1 ("'\n"); \
1352 PUSH_FAILURE_POINTER (string_place); \
1354 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1355 DEBUG_PUSH (failure_id); \
1358 /* This is the number of items that are pushed and popped on the stack
1359 for each register. */
1360 #define NUM_REG_ITEMS 3
1362 /* Individual items aside from the registers. */
1364 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1366 #define NUM_NONREG_ITEMS 4
1369 /* Estimate the size of data pushed by a typical failure stack entry.
1370 An estimate is all we need, because all we use this for
1371 is to choose a limit for how big to make the failure stack. */
1373 #define TYPICAL_FAILURE_SIZE 20
1375 /* This is how many items we actually use for a failure point.
1376 It depends on the regexp. */
1377 #define NUM_FAILURE_ITEMS \
1379 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1383 /* How many items can still be added to the stack without overflowing it. */
1384 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1387 /* Pops what PUSH_FAIL_STACK pushes.
1389 We restore into the parameters, all of which should be lvalues:
1390 STR -- the saved data position.
1391 PAT -- the saved pattern position.
1392 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1393 REGSTART, REGEND -- arrays of string positions.
1394 REG_INFO -- array of information about each subexpression.
1396 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1397 `pend', `string1', `size1', `string2', and `size2'. */
1399 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1401 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
1403 const unsigned char *string_temp; \
1405 assert (!FAIL_STACK_EMPTY ()); \
1407 /* Remove failure points and point to how many regs pushed. */ \
1408 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1409 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1410 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1412 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1414 DEBUG_POP (&failure_id); \
1415 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1417 /* If the saved string location is NULL, it came from an \
1418 on_failure_keep_string_jump opcode, and we want to throw away the \
1419 saved NULL, thus retaining our current position in the string. */ \
1420 string_temp = POP_FAILURE_POINTER (); \
1421 if (string_temp != NULL) \
1422 str = (const char *) string_temp; \
1424 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
1425 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1426 DEBUG_PRINT1 ("'\n"); \
1428 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1429 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
1430 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1432 /* Restore register info. */ \
1433 high_reg = (unsigned) POP_FAILURE_INT (); \
1434 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1436 low_reg = (unsigned) POP_FAILURE_INT (); \
1437 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1440 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1442 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1444 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1445 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
1447 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1448 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1450 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1451 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1455 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1457 reg_info[this_reg].word.integer = 0; \
1458 regend[this_reg] = 0; \
1459 regstart[this_reg] = 0; \
1461 highest_active_reg = high_reg; \
1464 set_regs_matched_done = 0; \
1465 DEBUG_STATEMENT (nfailure_points_popped++); \
1466 } /* POP_FAILURE_POINT */
1470 /* Structure for per-register (a.k.a. per-group) information.
1471 Other register information, such as the
1472 starting and ending positions (which are addresses), and the list of
1473 inner groups (which is a bits list) are maintained in separate
1476 We are making a (strictly speaking) nonportable assumption here: that
1477 the compiler will pack our bit fields into something that fits into
1478 the type of `word', i.e., is something that fits into one item on the
1483 fail_stack_elt_t word;
1486 /* This field is one if this group can match the empty string,
1487 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1488 #define MATCH_NULL_UNSET_VALUE 3
1489 unsigned match_null_string_p : 2;
1490 unsigned is_active : 1;
1491 unsigned matched_something : 1;
1492 unsigned ever_matched_something : 1;
1494 } register_info_type;
1496 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1497 #define IS_ACTIVE(R) ((R).bits.is_active)
1498 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1499 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1502 /* Call this when have matched a real character; it sets `matched' flags
1503 for the subexpressions which we are currently inside. Also records
1504 that those subexprs have matched. */
1505 #define SET_REGS_MATCHED() \
1508 if (!set_regs_matched_done) \
1511 set_regs_matched_done = 1; \
1512 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1514 MATCHED_SOMETHING (reg_info[r]) \
1515 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1522 /* Registers are set to a sentinel when they haven't yet matched. */
1523 static char reg_unset_dummy;
1524 #define REG_UNSET_VALUE (®_unset_dummy)
1525 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1527 /* Subroutine declarations and macros for regex_compile. */
1529 static void store_op1 (), store_op2 ();
1530 static void insert_op1 (), insert_op2 ();
1531 static boolean at_begline_loc_p (), at_endline_loc_p ();
1532 static boolean group_in_compile_stack ();
1533 static reg_errcode_t compile_range ();
1535 /* Fetch the next character in the uncompiled pattern---translating it
1536 if necessary. Also cast from a signed character in the constant
1537 string passed to us by the user to an unsigned char that we can use
1538 as an array index (in, e.g., `translate'). */
1540 #define PATFETCH(c) \
1541 do {if (p == pend) return REG_EEND; \
1542 c = (unsigned char) *p++; \
1543 if (translate) c = RE_TRANSLATE (translate, c); \
1547 /* Fetch the next character in the uncompiled pattern, with no
1549 #define PATFETCH_RAW(c) \
1550 do {if (p == pend) return REG_EEND; \
1551 c = (unsigned char) *p++; \
1554 /* Go backwards one character in the pattern. */
1555 #define PATUNFETCH p--
1558 /* If `translate' is non-null, return translate[D], else just D. We
1559 cast the subscript to translate because some data is declared as
1560 `char *', to avoid warnings when a string constant is passed. But
1561 when we use a character as a subscript we must make it unsigned. */
1563 #define TRANSLATE(d) \
1564 (translate ? (unsigned) RE_TRANSLATE (translate, (unsigned) (d)) : (d))
1568 /* Macros for outputting the compiled pattern into `buffer'. */
1570 /* If the buffer isn't allocated when it comes in, use this. */
1571 #define INIT_BUF_SIZE 32
1573 /* Make sure we have at least N more bytes of space in buffer. */
1574 #define GET_BUFFER_SPACE(n) \
1575 while (b - bufp->buffer + (n) > bufp->allocated) \
1578 /* Make sure we have one more byte of buffer space and then add C to it. */
1579 #define BUF_PUSH(c) \
1581 GET_BUFFER_SPACE (1); \
1582 *b++ = (unsigned char) (c); \
1586 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1587 #define BUF_PUSH_2(c1, c2) \
1589 GET_BUFFER_SPACE (2); \
1590 *b++ = (unsigned char) (c1); \
1591 *b++ = (unsigned char) (c2); \
1595 /* As with BUF_PUSH_2, except for three bytes. */
1596 #define BUF_PUSH_3(c1, c2, c3) \
1598 GET_BUFFER_SPACE (3); \
1599 *b++ = (unsigned char) (c1); \
1600 *b++ = (unsigned char) (c2); \
1601 *b++ = (unsigned char) (c3); \
1605 /* Store a jump with opcode OP at LOC to location TO. We store a
1606 relative address offset by the three bytes the jump itself occupies. */
1607 #define STORE_JUMP(op, loc, to) \
1608 store_op1 (op, loc, (to) - (loc) - 3)
1610 /* Likewise, for a two-argument jump. */
1611 #define STORE_JUMP2(op, loc, to, arg) \
1612 store_op2 (op, loc, (to) - (loc) - 3, arg)
1614 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1615 #define INSERT_JUMP(op, loc, to) \
1616 insert_op1 (op, loc, (to) - (loc) - 3, b)
1618 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1619 #define INSERT_JUMP2(op, loc, to, arg) \
1620 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1623 /* This is not an arbitrary limit: the arguments which represent offsets
1624 into the pattern are two bytes long. So if 2^16 bytes turns out to
1625 be too small, many things would have to change. */
1626 #define MAX_BUF_SIZE (1L << 16)
1629 /* Extend the buffer by twice its current size via realloc and
1630 reset the pointers that pointed into the old block to point to the
1631 correct places in the new one. If extending the buffer results in it
1632 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1633 #define EXTEND_BUFFER() \
1635 unsigned char *old_buffer = bufp->buffer; \
1636 if (bufp->allocated == MAX_BUF_SIZE) \
1638 bufp->allocated <<= 1; \
1639 if (bufp->allocated > MAX_BUF_SIZE) \
1640 bufp->allocated = MAX_BUF_SIZE; \
1641 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1642 if (bufp->buffer == NULL) \
1643 return REG_ESPACE; \
1644 /* If the buffer moved, move all the pointers into it. */ \
1645 if (old_buffer != bufp->buffer) \
1647 b = (b - old_buffer) + bufp->buffer; \
1648 begalt = (begalt - old_buffer) + bufp->buffer; \
1649 if (fixup_alt_jump) \
1650 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1652 laststart = (laststart - old_buffer) + bufp->buffer; \
1653 if (pending_exact) \
1654 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1659 /* Since we have one byte reserved for the register number argument to
1660 {start,stop}_memory, the maximum number of groups we can report
1661 things about is what fits in that byte. */
1662 #define MAX_REGNUM 255
1664 /* But patterns can have more than `MAX_REGNUM' registers. We just
1665 ignore the excess. */
1666 typedef unsigned regnum_t;
1669 /* Macros for the compile stack. */
1671 /* Since offsets can go either forwards or backwards, this type needs to
1672 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1673 typedef int pattern_offset_t;
1677 pattern_offset_t begalt_offset;
1678 pattern_offset_t fixup_alt_jump;
1679 pattern_offset_t inner_group_offset;
1680 pattern_offset_t laststart_offset;
1682 } compile_stack_elt_t;
1687 compile_stack_elt_t *stack;
1689 unsigned avail; /* Offset of next open position. */
1690 } compile_stack_type;
1693 #define INIT_COMPILE_STACK_SIZE 32
1695 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1696 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1698 /* The next available element. */
1699 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1702 /* Structure to manage work area for range table. */
1703 struct range_table_work_area
1705 int *table; /* actual work area. */
1706 int allocated; /* allocated size for work area in bytes. */
1707 int used; /* actually used size in words. */
1710 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1711 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1713 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1715 (work_area).allocated += 16 * sizeof (int); \
1716 if ((work_area).table) \
1718 = (int *) realloc ((work_area).table, (work_area).allocated); \
1721 = (int *) malloc ((work_area).allocated); \
1722 if ((work_area).table == 0) \
1723 FREE_STACK_RETURN (REG_ESPACE); \
1727 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1728 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1730 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1731 (work_area).table[(work_area).used++] = (range_start); \
1732 (work_area).table[(work_area).used++] = (range_end); \
1735 /* Free allocated memory for WORK_AREA. */
1736 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1738 if ((work_area).table) \
1739 free ((work_area).table); \
1742 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0)
1743 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1744 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1747 /* Set the bit for character C in a list. */
1748 #define SET_LIST_BIT(c) \
1749 (b[((unsigned char) (c)) / BYTEWIDTH] \
1750 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1753 /* Get the next unsigned number in the uncompiled pattern. */
1754 #define GET_UNSIGNED_NUMBER(num) \
1758 while (ISDIGIT (c)) \
1762 num = num * 10 + c - '0'; \
1770 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1772 #define IS_CHAR_CLASS(string) \
1773 (STREQ (string, "alpha") || STREQ (string, "upper") \
1774 || STREQ (string, "lower") || STREQ (string, "digit") \
1775 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1776 || STREQ (string, "space") || STREQ (string, "print") \
1777 || STREQ (string, "punct") || STREQ (string, "graph") \
1778 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1780 #ifndef MATCH_MAY_ALLOCATE
1782 /* If we cannot allocate large objects within re_match_2_internal,
1783 we make the fail stack and register vectors global.
1784 The fail stack, we grow to the maximum size when a regexp
1786 The register vectors, we adjust in size each time we
1787 compile a regexp, according to the number of registers it needs. */
1789 static fail_stack_type fail_stack;
1791 /* Size with which the following vectors are currently allocated.
1792 That is so we can make them bigger as needed,
1793 but never make them smaller. */
1794 static int regs_allocated_size;
1796 static const char ** regstart, ** regend;
1797 static const char ** old_regstart, ** old_regend;
1798 static const char **best_regstart, **best_regend;
1799 static register_info_type *reg_info;
1800 static const char **reg_dummy;
1801 static register_info_type *reg_info_dummy;
1803 /* Make the register vectors big enough for NUM_REGS registers,
1804 but don't make them smaller. */
1807 regex_grow_registers (num_regs)
1810 if (num_regs > regs_allocated_size)
1812 RETALLOC_IF (regstart, num_regs, const char *);
1813 RETALLOC_IF (regend, num_regs, const char *);
1814 RETALLOC_IF (old_regstart, num_regs, const char *);
1815 RETALLOC_IF (old_regend, num_regs, const char *);
1816 RETALLOC_IF (best_regstart, num_regs, const char *);
1817 RETALLOC_IF (best_regend, num_regs, const char *);
1818 RETALLOC_IF (reg_info, num_regs, register_info_type);
1819 RETALLOC_IF (reg_dummy, num_regs, const char *);
1820 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1822 regs_allocated_size = num_regs;
1826 #endif /* not MATCH_MAY_ALLOCATE */
1828 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1829 Returns one of error codes defined in `regex.h', or zero for success.
1831 Assumes the `allocated' (and perhaps `buffer') and `translate'
1832 fields are set in BUFP on entry.
1834 If it succeeds, results are put in BUFP (if it returns an error, the
1835 contents of BUFP are undefined):
1836 `buffer' is the compiled pattern;
1837 `syntax' is set to SYNTAX;
1838 `used' is set to the length of the compiled pattern;
1839 `fastmap_accurate' is zero;
1840 `re_nsub' is the number of subexpressions in PATTERN;
1841 `not_bol' and `not_eol' are zero;
1843 The `fastmap' and `newline_anchor' fields are neither
1844 examined nor set. */
1846 /* Return, freeing storage we allocated. */
1847 #define FREE_STACK_RETURN(value) \
1849 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1850 free (compile_stack.stack); \
1854 static reg_errcode_t
1855 regex_compile (pattern, size, syntax, bufp)
1856 const char *pattern;
1858 reg_syntax_t syntax;
1859 struct re_pattern_buffer *bufp;
1861 /* We fetch characters from PATTERN here. Even though PATTERN is
1862 `char *' (i.e., signed), we declare these variables as unsigned, so
1863 they can be reliably used as array indices. */
1864 register unsigned int c, c1;
1866 /* A random temporary spot in PATTERN. */
1869 /* Points to the end of the buffer, where we should append. */
1870 register unsigned char *b;
1872 /* Keeps track of unclosed groups. */
1873 compile_stack_type compile_stack;
1875 /* Points to the current (ending) position in the pattern. */
1876 const char *p = pattern;
1877 const char *pend = pattern + size;
1879 /* How to translate the characters in the pattern. */
1880 RE_TRANSLATE_TYPE translate = bufp->translate;
1882 /* Address of the count-byte of the most recently inserted `exactn'
1883 command. This makes it possible to tell if a new exact-match
1884 character can be added to that command or if the character requires
1885 a new `exactn' command. */
1886 unsigned char *pending_exact = 0;
1888 /* Address of start of the most recently finished expression.
1889 This tells, e.g., postfix * where to find the start of its
1890 operand. Reset at the beginning of groups and alternatives. */
1891 unsigned char *laststart = 0;
1893 /* Address of beginning of regexp, or inside of last group. */
1894 unsigned char *begalt;
1896 /* Place in the uncompiled pattern (i.e., the {) to
1897 which to go back if the interval is invalid. */
1898 const char *beg_interval;
1900 /* Address of the place where a forward jump should go to the end of
1901 the containing expression. Each alternative of an `or' -- except the
1902 last -- ends with a forward jump of this sort. */
1903 unsigned char *fixup_alt_jump = 0;
1905 /* Counts open-groups as they are encountered. Remembered for the
1906 matching close-group on the compile stack, so the same register
1907 number is put in the stop_memory as the start_memory. */
1908 regnum_t regnum = 0;
1910 /* Work area for range table of charset. */
1911 struct range_table_work_area range_table_work;
1914 DEBUG_PRINT1 ("\nCompiling pattern: ");
1917 unsigned debug_count;
1919 for (debug_count = 0; debug_count < size; debug_count++)
1920 putchar (pattern[debug_count]);
1925 /* Initialize the compile stack. */
1926 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1927 if (compile_stack.stack == NULL)
1930 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1931 compile_stack.avail = 0;
1933 range_table_work.table = 0;
1934 range_table_work.allocated = 0;
1936 /* Initialize the pattern buffer. */
1937 bufp->syntax = syntax;
1938 bufp->fastmap_accurate = 0;
1939 bufp->not_bol = bufp->not_eol = 0;
1941 /* Set `used' to zero, so that if we return an error, the pattern
1942 printer (for debugging) will think there's no pattern. We reset it
1946 /* Always count groups, whether or not bufp->no_sub is set. */
1950 /* bufp->multibyte is set before regex_compile is called, so don't alter
1952 #else /* not emacs */
1953 /* Nothing is recognized as a multibyte character. */
1954 bufp->multibyte = 0;
1957 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1958 /* Initialize the syntax table. */
1959 init_syntax_once ();
1962 if (bufp->allocated == 0)
1965 { /* If zero allocated, but buffer is non-null, try to realloc
1966 enough space. This loses if buffer's address is bogus, but
1967 that is the user's responsibility. */
1968 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1971 { /* Caller did not allocate a buffer. Do it for them. */
1972 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1974 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1976 bufp->allocated = INIT_BUF_SIZE;
1979 begalt = b = bufp->buffer;
1981 /* Loop through the uncompiled pattern until we're at the end. */
1990 if ( /* If at start of pattern, it's an operator. */
1992 /* If context independent, it's an operator. */
1993 || syntax & RE_CONTEXT_INDEP_ANCHORS
1994 /* Otherwise, depends on what's come before. */
1995 || at_begline_loc_p (pattern, p, syntax))
2005 if ( /* If at end of pattern, it's an operator. */
2007 /* If context independent, it's an operator. */
2008 || syntax & RE_CONTEXT_INDEP_ANCHORS
2009 /* Otherwise, depends on what's next. */
2010 || at_endline_loc_p (p, pend, syntax))
2020 if ((syntax & RE_BK_PLUS_QM)
2021 || (syntax & RE_LIMITED_OPS))
2025 /* If there is no previous pattern... */
2028 if (syntax & RE_CONTEXT_INVALID_OPS)
2029 FREE_STACK_RETURN (REG_BADRPT);
2030 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2035 /* Are we optimizing this jump? */
2036 boolean keep_string_p = false;
2038 /* 1 means zero (many) matches is allowed. */
2039 char zero_times_ok = 0, many_times_ok = 0;
2041 /* If there is a sequence of repetition chars, collapse it
2042 down to just one (the right one). We can't combine
2043 interval operators with these because of, e.g., `a{2}*',
2044 which should only match an even number of `a's. */
2048 zero_times_ok |= c != '+';
2049 many_times_ok |= c != '?';
2057 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2060 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2062 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2065 if (!(c1 == '+' || c1 == '?'))
2080 /* If we get here, we found another repeat character. */
2083 /* Star, etc. applied to an empty pattern is equivalent
2084 to an empty pattern. */
2088 /* Now we know whether or not zero matches is allowed
2089 and also whether or not two or more matches is allowed. */
2091 { /* More than one repetition is allowed, so put in at the
2092 end a backward relative jump from `b' to before the next
2093 jump we're going to put in below (which jumps from
2094 laststart to after this jump).
2096 But if we are at the `*' in the exact sequence `.*\n',
2097 insert an unconditional jump backwards to the .,
2098 instead of the beginning of the loop. This way we only
2099 push a failure point once, instead of every time
2100 through the loop. */
2101 assert (p - 1 > pattern);
2103 /* Allocate the space for the jump. */
2104 GET_BUFFER_SPACE (3);
2106 /* We know we are not at the first character of the pattern,
2107 because laststart was nonzero. And we've already
2108 incremented `p', by the way, to be the character after
2109 the `*'. Do we have to do something analogous here
2110 for null bytes, because of RE_DOT_NOT_NULL? */
2111 if (TRANSLATE ((unsigned char)*(p - 2)) == TRANSLATE ('.')
2114 && TRANSLATE ((unsigned char)*p) == TRANSLATE ('\n')
2115 && !(syntax & RE_DOT_NEWLINE))
2116 { /* We have .*\n. */
2117 STORE_JUMP (jump, b, laststart);
2118 keep_string_p = true;
2121 /* Anything else. */
2122 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2124 /* We've added more stuff to the buffer. */
2128 /* On failure, jump from laststart to b + 3, which will be the
2129 end of the buffer after this jump is inserted. */
2130 GET_BUFFER_SPACE (3);
2131 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2139 /* At least one repetition is required, so insert a
2140 `dummy_failure_jump' before the initial
2141 `on_failure_jump' instruction of the loop. This
2142 effects a skip over that instruction the first time
2143 we hit that loop. */
2144 GET_BUFFER_SPACE (3);
2145 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2160 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2162 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2164 /* Ensure that we have enough space to push a charset: the
2165 opcode, the length count, and the bitset; 34 bytes in all. */
2166 GET_BUFFER_SPACE (34);
2170 /* We test `*p == '^' twice, instead of using an if
2171 statement, so we only need one BUF_PUSH. */
2172 BUF_PUSH (*p == '^' ? charset_not : charset);
2176 /* Remember the first position in the bracket expression. */
2179 /* Push the number of bytes in the bitmap. */
2180 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2182 /* Clear the whole map. */
2183 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2185 /* charset_not matches newline according to a syntax bit. */
2186 if ((re_opcode_t) b[-2] == charset_not
2187 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2188 SET_LIST_BIT ('\n');
2190 /* Read in characters and ranges, setting map bits. */
2194 boolean escaped_char = false;
2196 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2200 /* \ might escape characters inside [...] and [^...]. */
2201 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2203 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2206 escaped_char = true;
2210 /* Could be the end of the bracket expression. If it's
2211 not (i.e., when the bracket expression is `[]' so
2212 far), the ']' character bit gets set way below. */
2213 if (c == ']' && p != p1 + 1)
2217 /* If C indicates start of multibyte char, get the
2218 actual character code in C, and set the pattern
2219 pointer P to the next character boundary. */
2220 if (bufp->multibyte && BASE_LEADING_CODE_P (c))
2223 c = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2226 /* What should we do for the character which is
2227 greater than 0x7F, but not BASE_LEADING_CODE_P?
2230 /* See if we're at the beginning of a possible character
2233 else if (!escaped_char &&
2234 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2236 /* Leave room for the null. */
2237 char str[CHAR_CLASS_MAX_LENGTH + 1];
2242 /* If pattern is `[[:'. */
2243 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2248 if (c == ':' || c == ']' || p == pend
2249 || c1 == CHAR_CLASS_MAX_LENGTH)
2255 /* If isn't a word bracketed by `[:' and `:]':
2256 undo the ending character, the letters, and
2257 leave the leading `:' and `[' (but set bits for
2259 if (c == ':' && *p == ']')
2262 boolean is_alnum = STREQ (str, "alnum");
2263 boolean is_alpha = STREQ (str, "alpha");
2264 boolean is_blank = STREQ (str, "blank");
2265 boolean is_cntrl = STREQ (str, "cntrl");
2266 boolean is_digit = STREQ (str, "digit");
2267 boolean is_graph = STREQ (str, "graph");
2268 boolean is_lower = STREQ (str, "lower");
2269 boolean is_print = STREQ (str, "print");
2270 boolean is_punct = STREQ (str, "punct");
2271 boolean is_space = STREQ (str, "space");
2272 boolean is_upper = STREQ (str, "upper");
2273 boolean is_xdigit = STREQ (str, "xdigit");
2275 if (!IS_CHAR_CLASS (str))
2276 FREE_STACK_RETURN (REG_ECTYPE);
2278 /* Throw away the ] at the end of the character
2282 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2284 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2286 int translated = TRANSLATE (ch);
2287 /* This was split into 3 if's to
2288 avoid an arbitrary limit in some compiler. */
2289 if ( (is_alnum && ISALNUM (ch))
2290 || (is_alpha && ISALPHA (ch))
2291 || (is_blank && ISBLANK (ch))
2292 || (is_cntrl && ISCNTRL (ch)))
2293 SET_LIST_BIT (translated);
2294 if ( (is_digit && ISDIGIT (ch))
2295 || (is_graph && ISGRAPH (ch))
2296 || (is_lower && ISLOWER (ch))
2297 || (is_print && ISPRINT (ch)))
2298 SET_LIST_BIT (translated);
2299 if ( (is_punct && ISPUNCT (ch))
2300 || (is_space && ISSPACE (ch))
2301 || (is_upper && ISUPPER (ch))
2302 || (is_xdigit && ISXDIGIT (ch)))
2303 SET_LIST_BIT (translated);
2306 /* Repeat the loop. */
2316 /* Because the `:' may starts the range, we
2317 can't simply set bit and repeat the loop.
2318 Instead, just set it to C and handle below. */
2323 if (p < pend && p[0] == '-' && p[1] != ']')
2326 /* Discard the `-'. */
2329 /* Fetch the character which ends the range. */
2331 if (bufp->multibyte && BASE_LEADING_CODE_P (c1))
2334 c1 = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2338 if (SINGLE_BYTE_CHAR_P (c)
2339 && ! SINGLE_BYTE_CHAR_P (c1))
2341 /* Handle a range such as \177-\377 in multibyte mode.
2342 Split that into two ranges,,
2343 the low one ending at 0237, and the high one
2344 starting at ...040. */
2345 int c1_base = (c1 & ~0177) | 040;
2346 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2349 else if (!SAME_CHARSET_P (c, c1))
2350 FREE_STACK_RETURN (REG_ERANGE);
2353 /* Range from C to C. */
2356 /* Set the range ... */
2357 if (SINGLE_BYTE_CHAR_P (c))
2358 /* ... into bitmap. */
2361 int range_start = c, range_end = c1;
2363 /* If the start is after the end, the range is empty. */
2364 if (range_start > range_end)
2366 if (syntax & RE_NO_EMPTY_RANGES)
2367 FREE_STACK_RETURN (REG_ERANGE);
2368 /* Else, repeat the loop. */
2372 for (this_char = range_start; this_char <= range_end;
2374 SET_LIST_BIT (TRANSLATE (this_char));
2378 /* ... into range table. */
2379 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2382 /* Discard any (non)matching list bytes that are all 0 at the
2383 end of the map. Decrease the map-length byte too. */
2384 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2388 /* Build real range table from work area. */
2389 if (RANGE_TABLE_WORK_USED (range_table_work))
2392 int used = RANGE_TABLE_WORK_USED (range_table_work);
2394 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2395 bytes for COUNT and three bytes for each character. */
2396 GET_BUFFER_SPACE (2 + used * 3);
2398 /* Indicate the existence of range table. */
2399 laststart[1] |= 0x80;
2401 STORE_NUMBER_AND_INCR (b, used / 2);
2402 for (i = 0; i < used; i++)
2403 STORE_CHARACTER_AND_INCR
2404 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2411 if (syntax & RE_NO_BK_PARENS)
2418 if (syntax & RE_NO_BK_PARENS)
2425 if (syntax & RE_NEWLINE_ALT)
2432 if (syntax & RE_NO_BK_VBAR)
2439 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2440 goto handle_interval;
2446 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2448 /* Do not translate the character after the \, so that we can
2449 distinguish, e.g., \B from \b, even if we normally would
2450 translate, e.g., B to b. */
2456 if (syntax & RE_NO_BK_PARENS)
2457 goto normal_backslash;
2463 if (COMPILE_STACK_FULL)
2465 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2466 compile_stack_elt_t);
2467 if (compile_stack.stack == NULL) return REG_ESPACE;
2469 compile_stack.size <<= 1;
2472 /* These are the values to restore when we hit end of this
2473 group. They are all relative offsets, so that if the
2474 whole pattern moves because of realloc, they will still
2476 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2477 COMPILE_STACK_TOP.fixup_alt_jump
2478 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2479 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2480 COMPILE_STACK_TOP.regnum = regnum;
2482 /* We will eventually replace the 0 with the number of
2483 groups inner to this one. But do not push a
2484 start_memory for groups beyond the last one we can
2485 represent in the compiled pattern. */
2486 if (regnum <= MAX_REGNUM)
2488 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2489 BUF_PUSH_3 (start_memory, regnum, 0);
2492 compile_stack.avail++;
2497 /* If we've reached MAX_REGNUM groups, then this open
2498 won't actually generate any code, so we'll have to
2499 clear pending_exact explicitly. */
2505 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2507 if (COMPILE_STACK_EMPTY)
2508 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2509 goto normal_backslash;
2511 FREE_STACK_RETURN (REG_ERPAREN);
2515 { /* Push a dummy failure point at the end of the
2516 alternative for a possible future
2517 `pop_failure_jump' to pop. See comments at
2518 `push_dummy_failure' in `re_match_2'. */
2519 BUF_PUSH (push_dummy_failure);
2521 /* We allocated space for this jump when we assigned
2522 to `fixup_alt_jump', in the `handle_alt' case below. */
2523 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2526 /* See similar code for backslashed left paren above. */
2527 if (COMPILE_STACK_EMPTY)
2528 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2531 FREE_STACK_RETURN (REG_ERPAREN);
2533 /* Since we just checked for an empty stack above, this
2534 ``can't happen''. */
2535 assert (compile_stack.avail != 0);
2537 /* We don't just want to restore into `regnum', because
2538 later groups should continue to be numbered higher,
2539 as in `(ab)c(de)' -- the second group is #2. */
2540 regnum_t this_group_regnum;
2542 compile_stack.avail--;
2543 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2545 = COMPILE_STACK_TOP.fixup_alt_jump
2546 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2548 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2549 this_group_regnum = COMPILE_STACK_TOP.regnum;
2550 /* If we've reached MAX_REGNUM groups, then this open
2551 won't actually generate any code, so we'll have to
2552 clear pending_exact explicitly. */
2555 /* We're at the end of the group, so now we know how many
2556 groups were inside this one. */
2557 if (this_group_regnum <= MAX_REGNUM)
2559 unsigned char *inner_group_loc
2560 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2562 *inner_group_loc = regnum - this_group_regnum;
2563 BUF_PUSH_3 (stop_memory, this_group_regnum,
2564 regnum - this_group_regnum);
2570 case '|': /* `\|'. */
2571 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2572 goto normal_backslash;
2574 if (syntax & RE_LIMITED_OPS)
2577 /* Insert before the previous alternative a jump which
2578 jumps to this alternative if the former fails. */
2579 GET_BUFFER_SPACE (3);
2580 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2584 /* The alternative before this one has a jump after it
2585 which gets executed if it gets matched. Adjust that
2586 jump so it will jump to this alternative's analogous
2587 jump (put in below, which in turn will jump to the next
2588 (if any) alternative's such jump, etc.). The last such
2589 jump jumps to the correct final destination. A picture:
2595 If we are at `b', then fixup_alt_jump right now points to a
2596 three-byte space after `a'. We'll put in the jump, set
2597 fixup_alt_jump to right after `b', and leave behind three
2598 bytes which we'll fill in when we get to after `c'. */
2601 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2603 /* Mark and leave space for a jump after this alternative,
2604 to be filled in later either by next alternative or
2605 when know we're at the end of a series of alternatives. */
2607 GET_BUFFER_SPACE (3);
2616 /* If \{ is a literal. */
2617 if (!(syntax & RE_INTERVALS)
2618 /* If we're at `\{' and it's not the open-interval
2620 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2621 || (p - 2 == pattern && p == pend))
2622 goto normal_backslash;
2626 /* If got here, then the syntax allows intervals. */
2628 /* At least (most) this many matches must be made. */
2629 int lower_bound = -1, upper_bound = -1;
2631 beg_interval = p - 1;
2635 if (syntax & RE_NO_BK_BRACES)
2636 goto unfetch_interval;
2638 FREE_STACK_RETURN (REG_EBRACE);
2641 GET_UNSIGNED_NUMBER (lower_bound);
2645 GET_UNSIGNED_NUMBER (upper_bound);
2646 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2649 /* Interval such as `{1}' => match exactly once. */
2650 upper_bound = lower_bound;
2652 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2653 || lower_bound > upper_bound)
2655 if (syntax & RE_NO_BK_BRACES)
2656 goto unfetch_interval;
2658 FREE_STACK_RETURN (REG_BADBR);
2661 if (!(syntax & RE_NO_BK_BRACES))
2663 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2670 if (syntax & RE_NO_BK_BRACES)
2671 goto unfetch_interval;
2673 FREE_STACK_RETURN (REG_BADBR);
2676 /* We just parsed a valid interval. */
2678 /* If it's invalid to have no preceding re. */
2681 if (syntax & RE_CONTEXT_INVALID_OPS)
2682 FREE_STACK_RETURN (REG_BADRPT);
2683 else if (syntax & RE_CONTEXT_INDEP_OPS)
2686 goto unfetch_interval;
2689 /* If the upper bound is zero, don't want to succeed at
2690 all; jump from `laststart' to `b + 3', which will be
2691 the end of the buffer after we insert the jump. */
2692 if (upper_bound == 0)
2694 GET_BUFFER_SPACE (3);
2695 INSERT_JUMP (jump, laststart, b + 3);
2699 /* Otherwise, we have a nontrivial interval. When
2700 we're all done, the pattern will look like:
2701 set_number_at <jump count> <upper bound>
2702 set_number_at <succeed_n count> <lower bound>
2703 succeed_n <after jump addr> <succeed_n count>
2705 jump_n <succeed_n addr> <jump count>
2706 (The upper bound and `jump_n' are omitted if
2707 `upper_bound' is 1, though.) */
2709 { /* If the upper bound is > 1, we need to insert
2710 more at the end of the loop. */
2711 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2713 GET_BUFFER_SPACE (nbytes);
2715 /* Initialize lower bound of the `succeed_n', even
2716 though it will be set during matching by its
2717 attendant `set_number_at' (inserted next),
2718 because `re_compile_fastmap' needs to know.
2719 Jump to the `jump_n' we might insert below. */
2720 INSERT_JUMP2 (succeed_n, laststart,
2721 b + 5 + (upper_bound > 1) * 5,
2725 /* Code to initialize the lower bound. Insert
2726 before the `succeed_n'. The `5' is the last two
2727 bytes of this `set_number_at', plus 3 bytes of
2728 the following `succeed_n'. */
2729 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2732 if (upper_bound > 1)
2733 { /* More than one repetition is allowed, so
2734 append a backward jump to the `succeed_n'
2735 that starts this interval.
2737 When we've reached this during matching,
2738 we'll have matched the interval once, so
2739 jump back only `upper_bound - 1' times. */
2740 STORE_JUMP2 (jump_n, b, laststart + 5,
2744 /* The location we want to set is the second
2745 parameter of the `jump_n'; that is `b-2' as
2746 an absolute address. `laststart' will be
2747 the `set_number_at' we're about to insert;
2748 `laststart+3' the number to set, the source
2749 for the relative address. But we are
2750 inserting into the middle of the pattern --
2751 so everything is getting moved up by 5.
2752 Conclusion: (b - 2) - (laststart + 3) + 5,
2753 i.e., b - laststart.
2755 We insert this at the beginning of the loop
2756 so that if we fail during matching, we'll
2757 reinitialize the bounds. */
2758 insert_op2 (set_number_at, laststart, b - laststart,
2759 upper_bound - 1, b);
2764 beg_interval = NULL;
2769 /* If an invalid interval, match the characters as literals. */
2770 assert (beg_interval);
2772 beg_interval = NULL;
2774 /* normal_char and normal_backslash need `c'. */
2777 if (!(syntax & RE_NO_BK_BRACES))
2779 if (p > pattern && p[-1] == '\\')
2780 goto normal_backslash;
2785 /* There is no way to specify the before_dot and after_dot
2786 operators. rms says this is ok. --karl */
2794 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2800 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2806 BUF_PUSH_2 (categoryspec, c);
2812 BUF_PUSH_2 (notcategoryspec, c);
2819 BUF_PUSH (wordchar);
2825 BUF_PUSH (notwordchar);
2838 BUF_PUSH (wordbound);
2842 BUF_PUSH (notwordbound);
2853 case '1': case '2': case '3': case '4': case '5':
2854 case '6': case '7': case '8': case '9':
2855 if (syntax & RE_NO_BK_REFS)
2861 FREE_STACK_RETURN (REG_ESUBREG);
2863 /* Can't back reference to a subexpression if inside of it. */
2864 if (group_in_compile_stack (compile_stack, c1))
2868 BUF_PUSH_2 (duplicate, c1);
2874 if (syntax & RE_BK_PLUS_QM)
2877 goto normal_backslash;
2881 /* You might think it would be useful for \ to mean
2882 not to translate; but if we don't translate it
2883 it will never match anything. */
2891 /* Expects the character in `c'. */
2893 p1 = p - 1; /* P1 points the head of C. */
2895 if (bufp->multibyte)
2896 /* Set P to the next character boundary. */
2897 p += MULTIBYTE_FORM_LENGTH (p1, pend - p1) - 1;
2899 /* If no exactn currently being built. */
2902 /* If last exactn not at current position. */
2903 || pending_exact + *pending_exact + 1 != b
2905 /* We have only one byte following the exactn for the count. */
2906 || *pending_exact >= (1 << BYTEWIDTH) - (p - p1)
2908 /* If followed by a repetition operator. */
2909 || *p == '*' || *p == '^'
2910 || ((syntax & RE_BK_PLUS_QM)
2911 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2912 : (*p == '+' || *p == '?'))
2913 || ((syntax & RE_INTERVALS)
2914 && ((syntax & RE_NO_BK_BRACES)
2916 : (p[0] == '\\' && p[1] == '{'))))
2918 /* Start building a new exactn. */
2922 BUF_PUSH_2 (exactn, 0);
2923 pending_exact = b - 1;
2926 /* Here, C may translated, therefore C may not equal to *P1. */
2934 /* Rest of multibyte form should be copied literally. */
2935 c = *(unsigned char *)p1;
2939 } /* while p != pend */
2942 /* Through the pattern now. */
2945 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2947 if (!COMPILE_STACK_EMPTY)
2948 FREE_STACK_RETURN (REG_EPAREN);
2950 /* If we don't want backtracking, force success
2951 the first time we reach the end of the compiled pattern. */
2952 if (syntax & RE_NO_POSIX_BACKTRACKING)
2955 free (compile_stack.stack);
2957 /* We have succeeded; set the length of the buffer. */
2958 bufp->used = b - bufp->buffer;
2963 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2964 print_compiled_pattern (bufp);
2968 #ifndef MATCH_MAY_ALLOCATE
2969 /* Initialize the failure stack to the largest possible stack. This
2970 isn't necessary unless we're trying to avoid calling alloca in
2971 the search and match routines. */
2973 int num_regs = bufp->re_nsub + 1;
2975 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
2977 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
2980 if (! fail_stack.stack)
2982 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2983 * sizeof (fail_stack_elt_t));
2986 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2988 * sizeof (fail_stack_elt_t)));
2989 #else /* not emacs */
2990 if (! fail_stack.stack)
2992 = (fail_stack_elt_t *) malloc (fail_stack.size
2993 * sizeof (fail_stack_elt_t));
2996 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2998 * sizeof (fail_stack_elt_t)));
2999 #endif /* not emacs */
3002 regex_grow_registers (num_regs);
3004 #endif /* not MATCH_MAY_ALLOCATE */
3007 } /* regex_compile */
3009 /* Subroutines for `regex_compile'. */
3011 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3014 store_op1 (op, loc, arg)
3019 *loc = (unsigned char) op;
3020 STORE_NUMBER (loc + 1, arg);
3024 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3027 store_op2 (op, loc, arg1, arg2)
3032 *loc = (unsigned char) op;
3033 STORE_NUMBER (loc + 1, arg1);
3034 STORE_NUMBER (loc + 3, arg2);
3038 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3039 for OP followed by two-byte integer parameter ARG. */
3042 insert_op1 (op, loc, arg, end)
3048 register unsigned char *pfrom = end;
3049 register unsigned char *pto = end + 3;
3051 while (pfrom != loc)
3054 store_op1 (op, loc, arg);
3058 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3061 insert_op2 (op, loc, arg1, arg2, end)
3067 register unsigned char *pfrom = end;
3068 register unsigned char *pto = end + 5;
3070 while (pfrom != loc)
3073 store_op2 (op, loc, arg1, arg2);
3077 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3078 after an alternative or a begin-subexpression. We assume there is at
3079 least one character before the ^. */
3082 at_begline_loc_p (pattern, p, syntax)
3083 const char *pattern, *p;
3084 reg_syntax_t syntax;
3086 const char *prev = p - 2;
3087 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3090 /* After a subexpression? */
3091 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3092 /* After an alternative? */
3093 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3097 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3098 at least one character after the $, i.e., `P < PEND'. */
3101 at_endline_loc_p (p, pend, syntax)
3102 const char *p, *pend;
3105 const char *next = p;
3106 boolean next_backslash = *next == '\\';
3107 const char *next_next = p + 1 < pend ? p + 1 : 0;
3110 /* Before a subexpression? */
3111 (syntax & RE_NO_BK_PARENS ? *next == ')'
3112 : next_backslash && next_next && *next_next == ')')
3113 /* Before an alternative? */
3114 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3115 : next_backslash && next_next && *next_next == '|');
3119 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3120 false if it's not. */
3123 group_in_compile_stack (compile_stack, regnum)
3124 compile_stack_type compile_stack;
3129 for (this_element = compile_stack.avail - 1;
3132 if (compile_stack.stack[this_element].regnum == regnum)
3138 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3139 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3140 characters can start a string that matches the pattern. This fastmap
3141 is used by re_search to skip quickly over impossible starting points.
3143 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3144 area as BUFP->fastmap.
3146 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3149 Returns 0 if we succeed, -2 if an internal error. */
3152 re_compile_fastmap (bufp)
3153 struct re_pattern_buffer *bufp;
3156 #ifdef MATCH_MAY_ALLOCATE
3157 fail_stack_type fail_stack;
3159 #ifndef REGEX_MALLOC
3162 /* We don't push any register information onto the failure stack. */
3163 unsigned num_regs = 0;
3165 register char *fastmap = bufp->fastmap;
3166 unsigned char *pattern = bufp->buffer;
3167 unsigned long size = bufp->used;
3168 unsigned char *p = pattern;
3169 register unsigned char *pend = pattern + size;
3171 /* This holds the pointer to the failure stack, when
3172 it is allocated relocatably. */
3173 fail_stack_elt_t *failure_stack_ptr;
3175 /* Assume that each path through the pattern can be null until
3176 proven otherwise. We set this false at the bottom of switch
3177 statement, to which we get only if a particular path doesn't
3178 match the empty string. */
3179 boolean path_can_be_null = true;
3181 /* We aren't doing a `succeed_n' to begin with. */
3182 boolean succeed_n_p = false;
3184 /* If all elements for base leading-codes in fastmap is set, this
3185 flag is set true. */
3186 boolean match_any_multibyte_characters = false;
3188 /* Maximum code of simple (single byte) character. */
3189 int simple_char_max;
3191 assert (fastmap != NULL && p != NULL);
3194 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3195 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3196 bufp->can_be_null = 0;
3200 if (p == pend || *p == succeed)
3202 /* We have reached the (effective) end of pattern. */
3203 if (!FAIL_STACK_EMPTY ())
3205 bufp->can_be_null |= path_can_be_null;
3207 /* Reset for next path. */
3208 path_can_be_null = true;
3210 p = fail_stack.stack[--fail_stack.avail].pointer;
3218 /* We should never be about to go beyond the end of the pattern. */
3221 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3224 /* I guess the idea here is to simply not bother with a fastmap
3225 if a backreference is used, since it's too hard to figure out
3226 the fastmap for the corresponding group. Setting
3227 `can_be_null' stops `re_search_2' from using the fastmap, so
3228 that is all we do. */
3230 bufp->can_be_null = 1;
3234 /* Following are the cases which match a character. These end
3244 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3245 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3251 /* Chars beyond end of map must be allowed. */
3252 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3255 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3256 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3262 for (j = 0; j < (1 << BYTEWIDTH); j++)
3263 if (SYNTAX (j) == Sword)
3269 for (j = 0; j < (1 << BYTEWIDTH); j++)
3270 if (SYNTAX (j) != Sword)
3275 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3277 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3280 if (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3281 && match_any_multibyte_characters == false)
3283 /* Set fastmap[I] 1 where I is a base leading code of each
3284 multibyte character in the range table. */
3287 /* Make P points the range table. */
3288 p += CHARSET_BITMAP_SIZE (&p[-2]);
3290 /* Extract the number of ranges in range table into
3292 EXTRACT_NUMBER_AND_INCR (count, p);
3293 for (; count > 0; count--, p += 2 * 3) /* XXX */
3295 /* Extract the start of each range. */
3296 EXTRACT_CHARACTER (c, p);
3297 j = CHAR_CHARSET (c);
3298 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3305 /* Chars beyond end of map must be allowed. End of map is
3306 `127' if bufp->multibyte is nonzero. */
3307 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3308 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3309 j < simple_char_max; j++)
3312 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3314 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3317 if (bufp->multibyte)
3318 /* Any character set can possibly contain a character
3319 which doesn't match the specified set of characters. */
3321 set_fastmap_for_multibyte_characters:
3322 if (match_any_multibyte_characters == false)
3324 for (j = 0x80; j < 0xA0; j++) /* XXX */
3325 if (BASE_LEADING_CODE_P (j))
3327 match_any_multibyte_characters = true;
3334 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3335 for (j = 0; j < simple_char_max; j++)
3336 if (SYNTAX (j) == Sword)
3339 if (bufp->multibyte)
3340 /* Any character set can possibly contain a character
3341 whose syntax is `Sword'. */
3342 goto set_fastmap_for_multibyte_characters;
3347 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3348 for (j = 0; j < simple_char_max; j++)
3349 if (SYNTAX (j) != Sword)
3352 if (bufp->multibyte)
3353 /* Any character set can possibly contain a character
3354 whose syntax is not `Sword'. */
3355 goto set_fastmap_for_multibyte_characters;
3361 int fastmap_newline = fastmap['\n'];
3363 /* `.' matches anything (but if bufp->multibyte is
3364 nonzero, matches `\000' .. `\127' and possible multibyte
3366 if (bufp->multibyte)
3368 simple_char_max = 0x80;
3370 for (j = 0x80; j < 0xA0; j++)
3371 if (BASE_LEADING_CODE_P (j))
3373 match_any_multibyte_characters = true;
3376 simple_char_max = (1 << BYTEWIDTH);
3378 for (j = 0; j < simple_char_max; j++)
3381 /* ... except perhaps newline. */
3382 if (!(bufp->syntax & RE_DOT_NEWLINE))
3383 fastmap['\n'] = fastmap_newline;
3385 /* Return if we have already set `can_be_null'; if we have,
3386 then the fastmap is irrelevant. Something's wrong here. */
3387 else if (bufp->can_be_null)
3390 /* Otherwise, have to check alternative paths. */
3401 /* This match depends on text properties. These end with
3402 aborting optimizations. */
3403 bufp->can_be_null = 1;
3407 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3408 for (j = 0; j < simple_char_max; j++)
3409 if (SYNTAX (j) == (enum syntaxcode) k)
3412 if (bufp->multibyte)
3413 /* Any character set can possibly contain a character
3414 whose syntax is K. */
3415 goto set_fastmap_for_multibyte_characters;
3420 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3421 for (j = 0; j < simple_char_max; j++)
3422 if (SYNTAX (j) != (enum syntaxcode) k)
3425 if (bufp->multibyte)
3426 /* Any character set can possibly contain a character
3427 whose syntax is not K. */
3428 goto set_fastmap_for_multibyte_characters;
3435 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3436 for (j = 0; j < simple_char_max; j++)
3437 if (CHAR_HAS_CATEGORY (j, k))
3440 if (bufp->multibyte)
3441 /* Any character set can possibly contain a character
3442 whose category is K. */
3443 goto set_fastmap_for_multibyte_characters;
3447 case notcategoryspec:
3449 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3450 for (j = 0; j < simple_char_max; j++)
3451 if (!CHAR_HAS_CATEGORY (j, k))
3454 if (bufp->multibyte)
3455 /* Any character set can possibly contain a character
3456 whose category is not K. */
3457 goto set_fastmap_for_multibyte_characters;
3460 /* All cases after this match the empty string. These end with
3482 case push_dummy_failure:
3487 case pop_failure_jump:
3488 case maybe_pop_jump:
3491 case dummy_failure_jump:
3492 EXTRACT_NUMBER_AND_INCR (j, p);
3497 /* Jump backward implies we just went through the body of a
3498 loop and matched nothing. Opcode jumped to should be
3499 `on_failure_jump' or `succeed_n'. Just treat it like an
3500 ordinary jump. For a * loop, it has pushed its failure
3501 point already; if so, discard that as redundant. */
3502 if ((re_opcode_t) *p != on_failure_jump
3503 && (re_opcode_t) *p != succeed_n)
3507 EXTRACT_NUMBER_AND_INCR (j, p);
3510 /* If what's on the stack is where we are now, pop it. */
3511 if (!FAIL_STACK_EMPTY ()
3512 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3518 case on_failure_jump:
3519 case on_failure_keep_string_jump:
3520 handle_on_failure_jump:
3521 EXTRACT_NUMBER_AND_INCR (j, p);
3523 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3524 end of the pattern. We don't want to push such a point,
3525 since when we restore it above, entering the switch will
3526 increment `p' past the end of the pattern. We don't need
3527 to push such a point since we obviously won't find any more
3528 fastmap entries beyond `pend'. Such a pattern can match
3529 the null string, though. */
3532 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3534 RESET_FAIL_STACK ();
3539 bufp->can_be_null = 1;
3543 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3544 succeed_n_p = false;
3551 /* Get to the number of times to succeed. */
3554 /* Increment p past the n for when k != 0. */
3555 EXTRACT_NUMBER_AND_INCR (k, p);
3559 succeed_n_p = true; /* Spaghetti code alert. */
3560 goto handle_on_failure_jump;
3577 abort (); /* We have listed all the cases. */
3580 /* Getting here means we have found the possible starting
3581 characters for one path of the pattern -- and that the empty
3582 string does not match. We need not follow this path further.
3583 Instead, look at the next alternative (remembered on the
3584 stack), or quit if no more. The test at the top of the loop
3585 does these things. */
3586 path_can_be_null = false;
3590 /* Set `can_be_null' for the last path (also the first path, if the
3591 pattern is empty). */
3592 bufp->can_be_null |= path_can_be_null;
3595 RESET_FAIL_STACK ();
3597 } /* re_compile_fastmap */
3599 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3600 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3601 this memory for recording register information. STARTS and ENDS
3602 must be allocated using the malloc library routine, and must each
3603 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3605 If NUM_REGS == 0, then subsequent matches should allocate their own
3608 Unless this function is called, the first search or match using
3609 PATTERN_BUFFER will allocate its own register data, without
3610 freeing the old data. */
3613 re_set_registers (bufp, regs, num_regs, starts, ends)
3614 struct re_pattern_buffer *bufp;
3615 struct re_registers *regs;
3617 regoff_t *starts, *ends;
3621 bufp->regs_allocated = REGS_REALLOCATE;
3622 regs->num_regs = num_regs;
3623 regs->start = starts;
3628 bufp->regs_allocated = REGS_UNALLOCATED;
3630 regs->start = regs->end = (regoff_t *) 0;
3634 /* Searching routines. */
3636 /* Like re_search_2, below, but only one string is specified, and
3637 doesn't let you say where to stop matching. */
3640 re_search (bufp, string, size, startpos, range, regs)
3641 struct re_pattern_buffer *bufp;
3643 int size, startpos, range;
3644 struct re_registers *regs;
3646 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3650 /* End address of virtual concatenation of string. */
3651 #define STOP_ADDR_VSTRING(P) \
3652 (((P) >= size1 ? string2 + size2 : string1 + size1))
3654 /* Address of POS in the concatenation of virtual string. */
3655 #define POS_ADDR_VSTRING(POS) \
3656 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3658 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3659 virtual concatenation of STRING1 and STRING2, starting first at index
3660 STARTPOS, then at STARTPOS + 1, and so on.
3662 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3664 RANGE is how far to scan while trying to match. RANGE = 0 means try
3665 only at STARTPOS; in general, the last start tried is STARTPOS +
3668 In REGS, return the indices of the virtual concatenation of STRING1
3669 and STRING2 that matched the entire BUFP->buffer and its contained
3672 Do not consider matching one past the index STOP in the virtual
3673 concatenation of STRING1 and STRING2.
3675 We return either the position in the strings at which the match was
3676 found, -1 if no match, or -2 if error (such as failure
3680 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3681 struct re_pattern_buffer *bufp;
3682 const char *string1, *string2;
3686 struct re_registers *regs;
3690 register char *fastmap = bufp->fastmap;
3691 register RE_TRANSLATE_TYPE translate = bufp->translate;
3692 int total_size = size1 + size2;
3693 int endpos = startpos + range;
3694 int anchored_start = 0;
3696 /* Nonzero if we have to concern multibyte character. */
3697 int multibyte = bufp->multibyte;
3699 /* Check for out-of-range STARTPOS. */
3700 if (startpos < 0 || startpos > total_size)
3703 /* Fix up RANGE if it might eventually take us outside
3704 the virtual concatenation of STRING1 and STRING2.
3705 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3707 range = 0 - startpos;
3708 else if (endpos > total_size)
3709 range = total_size - startpos;
3711 /* If the search isn't to be a backwards one, don't waste time in a
3712 search for a pattern that must be anchored. */
3713 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3722 /* In a forward search for something that starts with \=.
3723 don't keep searching past point. */
3724 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3726 range = PT - startpos;
3732 /* Update the fastmap now if not correct already. */
3733 if (fastmap && !bufp->fastmap_accurate)
3734 if (re_compile_fastmap (bufp) == -2)
3737 /* See whether the pattern is anchored. */
3738 if (bufp->buffer[0] == begline)
3742 gl_state.object = re_match_object;
3745 = SYNTAX_TABLE_BYTE_TO_CHAR (startpos > 0 ? startpos : startpos + 1);
3747 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
3751 /* Loop through the string, looking for a place to start matching. */
3754 /* If the pattern is anchored,
3755 skip quickly past places we cannot match.
3756 We don't bother to treat startpos == 0 specially
3757 because that case doesn't repeat. */
3758 if (anchored_start && startpos > 0)
3760 if (! (bufp->newline_anchor
3761 && ((startpos <= size1 ? string1[startpos - 1]
3762 : string2[startpos - size1 - 1])
3767 /* If a fastmap is supplied, skip quickly over characters that
3768 cannot be the start of a match. If the pattern can match the
3769 null string, however, we don't need to skip characters; we want
3770 the first null string. */
3771 if (fastmap && startpos < total_size && !bufp->can_be_null)
3773 register const char *d;
3774 register unsigned int buf_ch;
3776 d = POS_ADDR_VSTRING (startpos);
3778 if (range > 0) /* Searching forwards. */
3780 register int lim = 0;
3783 if (startpos < size1 && startpos + range >= size1)
3784 lim = range - (size1 - startpos);
3786 /* Written out as an if-else to avoid testing `translate'
3795 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
3798 buf_ch = RE_TRANSLATE (translate, buf_ch);
3803 range -= buf_charlen;
3808 && !fastmap[(unsigned char)
3809 RE_TRANSLATE (translate, (unsigned char) *d++)])
3813 while (range > lim && !fastmap[(unsigned char) *d++])
3816 startpos += irange - range;
3818 else /* Searching backwards. */
3820 int room = (size1 == 0 || startpos >= size1
3821 ? size2 + size1 - startpos
3822 : size1 - startpos);
3824 buf_ch = STRING_CHAR (d, room);
3826 buf_ch = RE_TRANSLATE (translate, buf_ch);
3828 if (! (buf_ch >= 0400
3829 || fastmap[buf_ch]))
3834 /* If can't match the null string, and that's all we have left, fail. */
3835 if (range >= 0 && startpos == total_size && fastmap
3836 && !bufp->can_be_null)
3839 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3840 startpos, regs, stop);
3841 #ifndef REGEX_MALLOC
3858 /* Update STARTPOS to the next character boundary. */
3861 const unsigned char *p
3862 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3863 const unsigned char *pend
3864 = (const unsigned char *) STOP_ADDR_VSTRING (startpos);
3865 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
3883 /* Update STARTPOS to the previous character boundary. */
3886 const unsigned char *p
3887 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3890 /* Find the head of multibyte form. */
3891 while (!CHAR_HEAD_P (*p))
3896 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
3913 /* Declarations and macros for re_match_2. */
3915 static int bcmp_translate ();
3916 static boolean alt_match_null_string_p (),
3917 common_op_match_null_string_p (),
3918 group_match_null_string_p ();
3920 /* This converts PTR, a pointer into one of the search strings `string1'
3921 and `string2' into an offset from the beginning of that string. */
3922 #define POINTER_TO_OFFSET(ptr) \
3923 (FIRST_STRING_P (ptr) \
3924 ? ((regoff_t) ((ptr) - string1)) \
3925 : ((regoff_t) ((ptr) - string2 + size1)))
3927 /* Macros for dealing with the split strings in re_match_2. */
3929 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3931 /* Call before fetching a character with *d. This switches over to
3932 string2 if necessary. */
3933 #define PREFETCH() \
3936 /* End of string2 => fail. */ \
3937 if (dend == end_match_2) \
3939 /* End of string1 => advance to string2. */ \
3941 dend = end_match_2; \
3945 /* Test if at very beginning or at very end of the virtual concatenation
3946 of `string1' and `string2'. If only one string, it's `string2'. */
3947 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3948 #define AT_STRINGS_END(d) ((d) == end2)
3951 /* Test if D points to a character which is word-constituent. We have
3952 two special cases to check for: if past the end of string1, look at
3953 the first character in string2; and if before the beginning of
3954 string2, look at the last character in string1. */
3955 #define WORDCHAR_P(d) \
3956 (SYNTAX ((d) == end1 ? *string2 \
3957 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3960 /* Disabled due to a compiler bug -- see comment at case wordbound */
3962 /* The comment at case wordbound is following one, but we don't use
3963 AT_WORD_BOUNDARY anymore to support multibyte form.
3965 The DEC Alpha C compiler 3.x generates incorrect code for the
3966 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
3967 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
3968 macro and introducing temporary variables works around the bug. */
3971 /* Test if the character before D and the one at D differ with respect
3972 to being word-constituent. */
3973 #define AT_WORD_BOUNDARY(d) \
3974 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3975 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3978 /* Free everything we malloc. */
3979 #ifdef MATCH_MAY_ALLOCATE
3980 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
3981 #define FREE_VARIABLES() \
3983 REGEX_FREE_STACK (fail_stack.stack); \
3984 FREE_VAR (regstart); \
3985 FREE_VAR (regend); \
3986 FREE_VAR (old_regstart); \
3987 FREE_VAR (old_regend); \
3988 FREE_VAR (best_regstart); \
3989 FREE_VAR (best_regend); \
3990 FREE_VAR (reg_info); \
3991 FREE_VAR (reg_dummy); \
3992 FREE_VAR (reg_info_dummy); \
3995 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
3996 #endif /* not MATCH_MAY_ALLOCATE */
3998 /* These values must meet several constraints. They must not be valid
3999 register values; since we have a limit of 255 registers (because
4000 we use only one byte in the pattern for the register number), we can
4001 use numbers larger than 255. They must differ by 1, because of
4002 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4003 be larger than the value for the highest register, so we do not try
4004 to actually save any registers when none are active. */
4005 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4006 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4008 /* Matching routines. */
4010 #ifndef emacs /* Emacs never uses this. */
4011 /* re_match is like re_match_2 except it takes only a single string. */
4014 re_match (bufp, string, size, pos, regs)
4015 struct re_pattern_buffer *bufp;
4018 struct re_registers *regs;
4020 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4025 #endif /* not emacs */
4028 /* In Emacs, this is the string or buffer in which we
4029 are matching. It is used for looking up syntax properties. */
4030 Lisp_Object re_match_object;
4033 /* re_match_2 matches the compiled pattern in BUFP against the
4034 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4035 and SIZE2, respectively). We start matching at POS, and stop
4038 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4039 store offsets for the substring each group matched in REGS. See the
4040 documentation for exactly how many groups we fill.
4042 We return -1 if no match, -2 if an internal error (such as the
4043 failure stack overflowing). Otherwise, we return the length of the
4044 matched substring. */
4047 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4048 struct re_pattern_buffer *bufp;
4049 const char *string1, *string2;
4052 struct re_registers *regs;
4059 gl_state.object = re_match_object;
4060 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4061 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4064 result = re_match_2_internal (bufp, string1, size1, string2, size2,
4070 /* This is a separate function so that we can force an alloca cleanup
4073 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4074 struct re_pattern_buffer *bufp;
4075 const char *string1, *string2;
4078 struct re_registers *regs;
4081 /* General temporaries. */
4085 /* Just past the end of the corresponding string. */
4086 const char *end1, *end2;
4088 /* Pointers into string1 and string2, just past the last characters in
4089 each to consider matching. */
4090 const char *end_match_1, *end_match_2;
4092 /* Where we are in the data, and the end of the current string. */
4093 const char *d, *dend;
4095 /* Where we are in the pattern, and the end of the pattern. */
4096 unsigned char *p = bufp->buffer;
4097 register unsigned char *pend = p + bufp->used;
4099 /* Mark the opcode just after a start_memory, so we can test for an
4100 empty subpattern when we get to the stop_memory. */
4101 unsigned char *just_past_start_mem = 0;
4103 /* We use this to map every character in the string. */
4104 RE_TRANSLATE_TYPE translate = bufp->translate;
4106 /* Nonzero if we have to concern multibyte character. */
4107 int multibyte = bufp->multibyte;
4109 /* Failure point stack. Each place that can handle a failure further
4110 down the line pushes a failure point on this stack. It consists of
4111 restart, regend, and reg_info for all registers corresponding to
4112 the subexpressions we're currently inside, plus the number of such
4113 registers, and, finally, two char *'s. The first char * is where
4114 to resume scanning the pattern; the second one is where to resume
4115 scanning the strings. If the latter is zero, the failure point is
4116 a ``dummy''; if a failure happens and the failure point is a dummy,
4117 it gets discarded and the next next one is tried. */
4118 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4119 fail_stack_type fail_stack;
4122 static unsigned failure_id = 0;
4123 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4126 /* This holds the pointer to the failure stack, when
4127 it is allocated relocatably. */
4128 fail_stack_elt_t *failure_stack_ptr;
4130 /* We fill all the registers internally, independent of what we
4131 return, for use in backreferences. The number here includes
4132 an element for register zero. */
4133 unsigned num_regs = bufp->re_nsub + 1;
4135 /* The currently active registers. */
4136 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4137 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4139 /* Information on the contents of registers. These are pointers into
4140 the input strings; they record just what was matched (on this
4141 attempt) by a subexpression part of the pattern, that is, the
4142 regnum-th regstart pointer points to where in the pattern we began
4143 matching and the regnum-th regend points to right after where we
4144 stopped matching the regnum-th subexpression. (The zeroth register
4145 keeps track of what the whole pattern matches.) */
4146 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4147 const char **regstart, **regend;
4150 /* If a group that's operated upon by a repetition operator fails to
4151 match anything, then the register for its start will need to be
4152 restored because it will have been set to wherever in the string we
4153 are when we last see its open-group operator. Similarly for a
4155 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4156 const char **old_regstart, **old_regend;
4159 /* The is_active field of reg_info helps us keep track of which (possibly
4160 nested) subexpressions we are currently in. The matched_something
4161 field of reg_info[reg_num] helps us tell whether or not we have
4162 matched any of the pattern so far this time through the reg_num-th
4163 subexpression. These two fields get reset each time through any
4164 loop their register is in. */
4165 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4166 register_info_type *reg_info;
4169 /* The following record the register info as found in the above
4170 variables when we find a match better than any we've seen before.
4171 This happens as we backtrack through the failure points, which in
4172 turn happens only if we have not yet matched the entire string. */
4173 unsigned best_regs_set = false;
4174 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4175 const char **best_regstart, **best_regend;
4178 /* Logically, this is `best_regend[0]'. But we don't want to have to
4179 allocate space for that if we're not allocating space for anything
4180 else (see below). Also, we never need info about register 0 for
4181 any of the other register vectors, and it seems rather a kludge to
4182 treat `best_regend' differently than the rest. So we keep track of
4183 the end of the best match so far in a separate variable. We
4184 initialize this to NULL so that when we backtrack the first time
4185 and need to test it, it's not garbage. */
4186 const char *match_end = NULL;
4188 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4189 int set_regs_matched_done = 0;
4191 /* Used when we pop values we don't care about. */
4192 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4193 const char **reg_dummy;
4194 register_info_type *reg_info_dummy;
4198 /* Counts the total number of registers pushed. */
4199 unsigned num_regs_pushed = 0;
4202 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4206 #ifdef MATCH_MAY_ALLOCATE
4207 /* Do not bother to initialize all the register variables if there are
4208 no groups in the pattern, as it takes a fair amount of time. If
4209 there are groups, we include space for register 0 (the whole
4210 pattern), even though we never use it, since it simplifies the
4211 array indexing. We should fix this. */
4214 regstart = REGEX_TALLOC (num_regs, const char *);
4215 regend = REGEX_TALLOC (num_regs, const char *);
4216 old_regstart = REGEX_TALLOC (num_regs, const char *);
4217 old_regend = REGEX_TALLOC (num_regs, const char *);
4218 best_regstart = REGEX_TALLOC (num_regs, const char *);
4219 best_regend = REGEX_TALLOC (num_regs, const char *);
4220 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4221 reg_dummy = REGEX_TALLOC (num_regs, const char *);
4222 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4224 if (!(regstart && regend && old_regstart && old_regend && reg_info
4225 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4233 /* We must initialize all our variables to NULL, so that
4234 `FREE_VARIABLES' doesn't try to free them. */
4235 regstart = regend = old_regstart = old_regend = best_regstart
4236 = best_regend = reg_dummy = NULL;
4237 reg_info = reg_info_dummy = (register_info_type *) NULL;
4239 #endif /* MATCH_MAY_ALLOCATE */
4241 /* The starting position is bogus. */
4242 if (pos < 0 || pos > size1 + size2)
4248 /* Initialize subexpression text positions to -1 to mark ones that no
4249 start_memory/stop_memory has been seen for. Also initialize the
4250 register information struct. */
4251 for (mcnt = 1; mcnt < num_regs; mcnt++)
4253 regstart[mcnt] = regend[mcnt]
4254 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4256 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4257 IS_ACTIVE (reg_info[mcnt]) = 0;
4258 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4259 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4262 /* We move `string1' into `string2' if the latter's empty -- but not if
4263 `string1' is null. */
4264 if (size2 == 0 && string1 != NULL)
4271 end1 = string1 + size1;
4272 end2 = string2 + size2;
4274 /* Compute where to stop matching, within the two strings. */
4277 end_match_1 = string1 + stop;
4278 end_match_2 = string2;
4283 end_match_2 = string2 + stop - size1;
4286 /* `p' scans through the pattern as `d' scans through the data.
4287 `dend' is the end of the input string that `d' points within. `d'
4288 is advanced into the following input string whenever necessary, but
4289 this happens before fetching; therefore, at the beginning of the
4290 loop, `d' can be pointing at the end of a string, but it cannot
4292 if (size1 > 0 && pos <= size1)
4299 d = string2 + pos - size1;
4303 DEBUG_PRINT1 ("The compiled pattern is: ");
4304 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4305 DEBUG_PRINT1 ("The string to match is: `");
4306 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4307 DEBUG_PRINT1 ("'\n");
4309 /* This loops over pattern commands. It exits by returning from the
4310 function if the match is complete, or it drops through if the match
4311 fails at this starting point in the input data. */
4314 DEBUG_PRINT2 ("\n0x%x: ", p);
4317 { /* End of pattern means we might have succeeded. */
4318 DEBUG_PRINT1 ("end of pattern ... ");
4320 /* If we haven't matched the entire string, and we want the
4321 longest match, try backtracking. */
4322 if (d != end_match_2)
4324 /* 1 if this match ends in the same string (string1 or string2)
4325 as the best previous match. */
4326 boolean same_str_p = (FIRST_STRING_P (match_end)
4327 == MATCHING_IN_FIRST_STRING);
4328 /* 1 if this match is the best seen so far. */
4329 boolean best_match_p;
4331 /* AIX compiler got confused when this was combined
4332 with the previous declaration. */
4334 best_match_p = d > match_end;
4336 best_match_p = !MATCHING_IN_FIRST_STRING;
4338 DEBUG_PRINT1 ("backtracking.\n");
4340 if (!FAIL_STACK_EMPTY ())
4341 { /* More failure points to try. */
4343 /* If exceeds best match so far, save it. */
4344 if (!best_regs_set || best_match_p)
4346 best_regs_set = true;
4349 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4351 for (mcnt = 1; mcnt < num_regs; mcnt++)
4353 best_regstart[mcnt] = regstart[mcnt];
4354 best_regend[mcnt] = regend[mcnt];
4360 /* If no failure points, don't restore garbage. And if
4361 last match is real best match, don't restore second
4363 else if (best_regs_set && !best_match_p)
4366 /* Restore best match. It may happen that `dend ==
4367 end_match_1' while the restored d is in string2.
4368 For example, the pattern `x.*y.*z' against the
4369 strings `x-' and `y-z-', if the two strings are
4370 not consecutive in memory. */
4371 DEBUG_PRINT1 ("Restoring best registers.\n");
4374 dend = ((d >= string1 && d <= end1)
4375 ? end_match_1 : end_match_2);
4377 for (mcnt = 1; mcnt < num_regs; mcnt++)
4379 regstart[mcnt] = best_regstart[mcnt];
4380 regend[mcnt] = best_regend[mcnt];
4383 } /* d != end_match_2 */
4386 DEBUG_PRINT1 ("Accepting match.\n");
4388 /* If caller wants register contents data back, do it. */
4389 if (regs && !bufp->no_sub)
4391 /* Have the register data arrays been allocated? */
4392 if (bufp->regs_allocated == REGS_UNALLOCATED)
4393 { /* No. So allocate them with malloc. We need one
4394 extra element beyond `num_regs' for the `-1' marker
4396 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4397 regs->start = TALLOC (regs->num_regs, regoff_t);
4398 regs->end = TALLOC (regs->num_regs, regoff_t);
4399 if (regs->start == NULL || regs->end == NULL)
4404 bufp->regs_allocated = REGS_REALLOCATE;
4406 else if (bufp->regs_allocated == REGS_REALLOCATE)
4407 { /* Yes. If we need more elements than were already
4408 allocated, reallocate them. If we need fewer, just
4410 if (regs->num_regs < num_regs + 1)
4412 regs->num_regs = num_regs + 1;
4413 RETALLOC (regs->start, regs->num_regs, regoff_t);
4414 RETALLOC (regs->end, regs->num_regs, regoff_t);
4415 if (regs->start == NULL || regs->end == NULL)
4424 /* These braces fend off a "empty body in an else-statement"
4425 warning under GCC when assert expands to nothing. */
4426 assert (bufp->regs_allocated == REGS_FIXED);
4429 /* Convert the pointer data in `regstart' and `regend' to
4430 indices. Register zero has to be set differently,
4431 since we haven't kept track of any info for it. */
4432 if (regs->num_regs > 0)
4434 regs->start[0] = pos;
4435 regs->end[0] = (MATCHING_IN_FIRST_STRING
4436 ? ((regoff_t) (d - string1))
4437 : ((regoff_t) (d - string2 + size1)));
4440 /* Go through the first `min (num_regs, regs->num_regs)'
4441 registers, since that is all we initialized. */
4442 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4444 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4445 regs->start[mcnt] = regs->end[mcnt] = -1;
4449 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4451 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4455 /* If the regs structure we return has more elements than
4456 were in the pattern, set the extra elements to -1. If
4457 we (re)allocated the registers, this is the case,
4458 because we always allocate enough to have at least one
4460 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4461 regs->start[mcnt] = regs->end[mcnt] = -1;
4462 } /* regs && !bufp->no_sub */
4464 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4465 nfailure_points_pushed, nfailure_points_popped,
4466 nfailure_points_pushed - nfailure_points_popped);
4467 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4469 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4473 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4479 /* Otherwise match next pattern command. */
4480 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4482 /* Ignore these. Used to ignore the n of succeed_n's which
4483 currently have n == 0. */
4485 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4489 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4492 /* Match the next n pattern characters exactly. The following
4493 byte in the pattern defines n, and the n bytes after that
4494 are the characters to match. */
4497 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4499 /* This is written out as an if-else so we don't waste time
4500 testing `translate' inside the loop. */
4507 int pat_charlen, buf_charlen;
4508 unsigned int pat_ch, buf_ch;
4511 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
4512 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4514 if (RE_TRANSLATE (translate, buf_ch)
4520 mcnt -= pat_charlen;
4524 #endif /* not emacs */
4528 if ((unsigned char) RE_TRANSLATE (translate, (unsigned char) *d++)
4529 != (unsigned char) *p++)
4539 if (*d++ != (char) *p++) goto fail;
4543 SET_REGS_MATCHED ();
4547 /* Match any character except possibly a newline or a null. */
4551 unsigned int buf_ch;
4553 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4559 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4561 #endif /* not emacs */
4563 buf_ch = (unsigned char) *d;
4567 buf_ch = TRANSLATE (buf_ch);
4569 if ((!(bufp->syntax & RE_DOT_NEWLINE)
4571 || ((bufp->syntax & RE_DOT_NOT_NULL)
4572 && buf_ch == '\000'))
4575 SET_REGS_MATCHED ();
4576 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4585 register unsigned int c;
4586 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4589 /* Start of actual range_table, or end of bitmap if there is no
4591 unsigned char *range_table;
4593 /* Nonzero if there is range table. */
4594 int range_table_exists;
4596 /* Number of ranges of range table. Not in bytes. */
4599 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4602 c = (unsigned char) *d;
4604 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
4605 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
4606 if (range_table_exists)
4607 EXTRACT_NUMBER_AND_INCR (count, range_table);
4611 if (multibyte && BASE_LEADING_CODE_P (c))
4612 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
4614 if (SINGLE_BYTE_CHAR_P (c))
4615 { /* Lookup bitmap. */
4616 c = TRANSLATE (c); /* The character to match. */
4619 /* Cast to `unsigned' instead of `unsigned char' in
4620 case the bit list is a full 32 bytes long. */
4621 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
4622 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4625 else if (range_table_exists)
4626 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
4628 p = CHARSET_RANGE_TABLE_END (range_table, count);
4630 if (!not) goto fail;
4632 SET_REGS_MATCHED ();
4638 /* The beginning of a group is represented by start_memory.
4639 The arguments are the register number in the next byte, and the
4640 number of groups inner to this one in the next. The text
4641 matched within the group is recorded (in the internal
4642 registers data structure) under the register number. */
4644 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4646 /* Find out if this group can match the empty string. */
4647 p1 = p; /* To send to group_match_null_string_p. */
4649 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4650 REG_MATCH_NULL_STRING_P (reg_info[*p])
4651 = group_match_null_string_p (&p1, pend, reg_info);
4653 /* Save the position in the string where we were the last time
4654 we were at this open-group operator in case the group is
4655 operated upon by a repetition operator, e.g., with `(a*)*b'
4656 against `ab'; then we want to ignore where we are now in
4657 the string in case this attempt to match fails. */
4658 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4659 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4661 DEBUG_PRINT2 (" old_regstart: %d\n",
4662 POINTER_TO_OFFSET (old_regstart[*p]));
4665 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4667 IS_ACTIVE (reg_info[*p]) = 1;
4668 MATCHED_SOMETHING (reg_info[*p]) = 0;
4670 /* Clear this whenever we change the register activity status. */
4671 set_regs_matched_done = 0;
4673 /* This is the new highest active register. */
4674 highest_active_reg = *p;
4676 /* If nothing was active before, this is the new lowest active
4678 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4679 lowest_active_reg = *p;
4681 /* Move past the register number and inner group count. */
4683 just_past_start_mem = p;
4688 /* The stop_memory opcode represents the end of a group. Its
4689 arguments are the same as start_memory's: the register
4690 number, and the number of inner groups. */
4692 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4694 /* We need to save the string position the last time we were at
4695 this close-group operator in case the group is operated
4696 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4697 against `aba'; then we want to ignore where we are now in
4698 the string in case this attempt to match fails. */
4699 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4700 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4702 DEBUG_PRINT2 (" old_regend: %d\n",
4703 POINTER_TO_OFFSET (old_regend[*p]));
4706 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4708 /* This register isn't active anymore. */
4709 IS_ACTIVE (reg_info[*p]) = 0;
4711 /* Clear this whenever we change the register activity status. */
4712 set_regs_matched_done = 0;
4714 /* If this was the only register active, nothing is active
4716 if (lowest_active_reg == highest_active_reg)
4718 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4719 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4722 { /* We must scan for the new highest active register, since
4723 it isn't necessarily one less than now: consider
4724 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4725 new highest active register is 1. */
4726 unsigned char r = *p - 1;
4727 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4730 /* If we end up at register zero, that means that we saved
4731 the registers as the result of an `on_failure_jump', not
4732 a `start_memory', and we jumped to past the innermost
4733 `stop_memory'. For example, in ((.)*) we save
4734 registers 1 and 2 as a result of the *, but when we pop
4735 back to the second ), we are at the stop_memory 1.
4736 Thus, nothing is active. */
4739 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4740 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4743 highest_active_reg = r;
4746 /* If just failed to match something this time around with a
4747 group that's operated on by a repetition operator, try to
4748 force exit from the ``loop'', and restore the register
4749 information for this group that we had before trying this
4751 if ((!MATCHED_SOMETHING (reg_info[*p])
4752 || just_past_start_mem == p - 1)
4755 boolean is_a_jump_n = false;
4759 switch ((re_opcode_t) *p1++)
4763 case pop_failure_jump:
4764 case maybe_pop_jump:
4766 case dummy_failure_jump:
4767 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4777 /* If the next operation is a jump backwards in the pattern
4778 to an on_failure_jump right before the start_memory
4779 corresponding to this stop_memory, exit from the loop
4780 by forcing a failure after pushing on the stack the
4781 on_failure_jump's jump in the pattern, and d. */
4782 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4783 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4785 /* If this group ever matched anything, then restore
4786 what its registers were before trying this last
4787 failed match, e.g., with `(a*)*b' against `ab' for
4788 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4789 against `aba' for regend[3].
4791 Also restore the registers for inner groups for,
4792 e.g., `((a*)(b*))*' against `aba' (register 3 would
4793 otherwise get trashed). */
4795 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4799 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4801 /* Restore this and inner groups' (if any) registers. */
4802 for (r = *p; r < *p + *(p + 1); r++)
4804 regstart[r] = old_regstart[r];
4806 /* xx why this test? */
4807 if (old_regend[r] >= regstart[r])
4808 regend[r] = old_regend[r];
4812 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4813 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4819 /* Move past the register number and the inner group count. */
4824 /* \<digit> has been turned into a `duplicate' command which is
4825 followed by the numeric value of <digit> as the register number. */
4828 register const char *d2, *dend2;
4829 int regno = *p++; /* Get which register to match against. */
4830 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4832 /* Can't back reference a group which we've never matched. */
4833 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4836 /* Where in input to try to start matching. */
4837 d2 = regstart[regno];
4839 /* Where to stop matching; if both the place to start and
4840 the place to stop matching are in the same string, then
4841 set to the place to stop, otherwise, for now have to use
4842 the end of the first string. */
4844 dend2 = ((FIRST_STRING_P (regstart[regno])
4845 == FIRST_STRING_P (regend[regno]))
4846 ? regend[regno] : end_match_1);
4849 /* If necessary, advance to next segment in register
4853 if (dend2 == end_match_2) break;
4854 if (dend2 == regend[regno]) break;
4856 /* End of string1 => advance to string2. */
4858 dend2 = regend[regno];
4860 /* At end of register contents => success */
4861 if (d2 == dend2) break;
4863 /* If necessary, advance to next segment in data. */
4866 /* How many characters left in this segment to match. */
4869 /* Want how many consecutive characters we can match in
4870 one shot, so, if necessary, adjust the count. */
4871 if (mcnt > dend2 - d2)
4874 /* Compare that many; failure if mismatch, else move
4877 ? bcmp_translate (d, d2, mcnt, translate)
4878 : bcmp (d, d2, mcnt))
4880 d += mcnt, d2 += mcnt;
4882 /* Do this because we've match some characters. */
4883 SET_REGS_MATCHED ();
4889 /* begline matches the empty string at the beginning of the string
4890 (unless `not_bol' is set in `bufp'), and, if
4891 `newline_anchor' is set, after newlines. */
4893 DEBUG_PRINT1 ("EXECUTING begline.\n");
4895 if (AT_STRINGS_BEG (d))
4897 if (!bufp->not_bol) break;
4899 else if (d[-1] == '\n' && bufp->newline_anchor)
4903 /* In all other cases, we fail. */
4907 /* endline is the dual of begline. */
4909 DEBUG_PRINT1 ("EXECUTING endline.\n");
4911 if (AT_STRINGS_END (d))
4913 if (!bufp->not_eol) break;
4916 /* We have to ``prefetch'' the next character. */
4917 else if ((d == end1 ? *string2 : *d) == '\n'
4918 && bufp->newline_anchor)
4925 /* Match at the very beginning of the data. */
4927 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4928 if (AT_STRINGS_BEG (d))
4933 /* Match at the very end of the data. */
4935 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4936 if (AT_STRINGS_END (d))
4941 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4942 pushes NULL as the value for the string on the stack. Then
4943 `pop_failure_point' will keep the current value for the
4944 string, instead of restoring it. To see why, consider
4945 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4946 then the . fails against the \n. But the next thing we want
4947 to do is match the \n against the \n; if we restored the
4948 string value, we would be back at the foo.
4950 Because this is used only in specific cases, we don't need to
4951 check all the things that `on_failure_jump' does, to make
4952 sure the right things get saved on the stack. Hence we don't
4953 share its code. The only reason to push anything on the
4954 stack at all is that otherwise we would have to change
4955 `anychar's code to do something besides goto fail in this
4956 case; that seems worse than this. */
4957 case on_failure_keep_string_jump:
4958 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4960 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4961 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4963 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4967 /* Uses of on_failure_jump:
4969 Each alternative starts with an on_failure_jump that points
4970 to the beginning of the next alternative. Each alternative
4971 except the last ends with a jump that in effect jumps past
4972 the rest of the alternatives. (They really jump to the
4973 ending jump of the following alternative, because tensioning
4974 these jumps is a hassle.)
4976 Repeats start with an on_failure_jump that points past both
4977 the repetition text and either the following jump or
4978 pop_failure_jump back to this on_failure_jump. */
4979 case on_failure_jump:
4981 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4983 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4984 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4986 /* If this on_failure_jump comes right before a group (i.e.,
4987 the original * applied to a group), save the information
4988 for that group and all inner ones, so that if we fail back
4989 to this point, the group's information will be correct.
4990 For example, in \(a*\)*\1, we need the preceding group,
4991 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4993 /* We can't use `p' to check ahead because we push
4994 a failure point to `p + mcnt' after we do this. */
4997 /* We need to skip no_op's before we look for the
4998 start_memory in case this on_failure_jump is happening as
4999 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5001 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5004 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5006 /* We have a new highest active register now. This will
5007 get reset at the start_memory we are about to get to,
5008 but we will have saved all the registers relevant to
5009 this repetition op, as described above. */
5010 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5011 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5012 lowest_active_reg = *(p1 + 1);
5015 DEBUG_PRINT1 (":\n");
5016 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5020 /* A smart repeat ends with `maybe_pop_jump'.
5021 We change it to either `pop_failure_jump' or `jump'. */
5022 case maybe_pop_jump:
5023 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5024 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5026 register unsigned char *p2 = p;
5028 /* Compare the beginning of the repeat with what in the
5029 pattern follows its end. If we can establish that there
5030 is nothing that they would both match, i.e., that we
5031 would have to backtrack because of (as in, e.g., `a*a')
5032 then we can change to pop_failure_jump, because we'll
5033 never have to backtrack.
5035 This is not true in the case of alternatives: in
5036 `(a|ab)*' we do need to backtrack to the `ab' alternative
5037 (e.g., if the string was `ab'). But instead of trying to
5038 detect that here, the alternative has put on a dummy
5039 failure point which is what we will end up popping. */
5041 /* Skip over open/close-group commands.
5042 If what follows this loop is a ...+ construct,
5043 look at what begins its body, since we will have to
5044 match at least one of that. */
5048 && ((re_opcode_t) *p2 == stop_memory
5049 || (re_opcode_t) *p2 == start_memory))
5051 else if (p2 + 6 < pend
5052 && (re_opcode_t) *p2 == dummy_failure_jump)
5059 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5060 to the `maybe_finalize_jump' of this case. Examine what
5063 /* If we're at the end of the pattern, we can change. */
5066 /* Consider what happens when matching ":\(.*\)"
5067 against ":/". I don't really understand this code
5069 p[-3] = (unsigned char) pop_failure_jump;
5071 (" End of pattern: change to `pop_failure_jump'.\n");
5074 else if ((re_opcode_t) *p2 == exactn
5075 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5077 register unsigned int c
5078 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5080 if ((re_opcode_t) p1[3] == exactn)
5082 if (!(multibyte /* && (c != '\n') */
5083 && BASE_LEADING_CODE_P (c))
5085 : (STRING_CHAR (&p2[2], pend - &p2[2])
5086 != STRING_CHAR (&p1[5], pend - &p1[5])))
5088 p[-3] = (unsigned char) pop_failure_jump;
5089 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5094 else if ((re_opcode_t) p1[3] == charset
5095 || (re_opcode_t) p1[3] == charset_not)
5097 int not = (re_opcode_t) p1[3] == charset_not;
5099 if (multibyte /* && (c != '\n') */
5100 && BASE_LEADING_CODE_P (c))
5101 c = STRING_CHAR (&p2[2], pend - &p2[2]);
5103 /* Test if C is listed in charset (or charset_not)
5105 if (SINGLE_BYTE_CHAR_P (c))
5107 if (c < CHARSET_BITMAP_SIZE (&p1[3]) * BYTEWIDTH
5108 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5111 else if (CHARSET_RANGE_TABLE_EXISTS_P (&p1[3]))
5112 CHARSET_LOOKUP_RANGE_TABLE (not, c, &p1[3]);
5114 /* `not' is equal to 1 if c would match, which means
5115 that we can't change to pop_failure_jump. */
5118 p[-3] = (unsigned char) pop_failure_jump;
5119 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5123 else if ((re_opcode_t) *p2 == charset)
5125 if ((re_opcode_t) p1[3] == exactn)
5127 register unsigned int c = p1[5];
5130 if (multibyte && BASE_LEADING_CODE_P (c))
5131 c = STRING_CHAR (&p1[5], pend - &p1[5]);
5133 /* Test if C is listed in charset at `p2'. */
5134 if (SINGLE_BYTE_CHAR_P (c))
5136 if (c < CHARSET_BITMAP_SIZE (p2) * BYTEWIDTH
5137 && (p2[2 + c / BYTEWIDTH]
5138 & (1 << (c % BYTEWIDTH))))
5141 else if (CHARSET_RANGE_TABLE_EXISTS_P (p2))
5142 CHARSET_LOOKUP_RANGE_TABLE (not, c, p2);
5146 p[-3] = (unsigned char) pop_failure_jump;
5147 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5151 /* It is hard to list up all the character in charset
5152 P2 if it includes multibyte character. Give up in
5154 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
5156 /* Now, we are sure that P2 has no range table.
5157 So, for the size of bitmap in P2, `p2[1]' is
5158 enough. But P1 may have range table, so the
5159 size of bitmap table of P1 is extracted by
5160 using macro `CHARSET_BITMAP_SIZE'.
5162 Since we know that all the character listed in
5163 P2 is ASCII, it is enough to test only bitmap
5166 if ((re_opcode_t) p1[3] == charset_not)
5169 /* We win if the charset_not inside the loop lists
5170 every character listed in the charset after. */
5171 for (idx = 0; idx < (int) p2[1]; idx++)
5172 if (! (p2[2 + idx] == 0
5173 || (idx < CHARSET_BITMAP_SIZE (&p1[3])
5174 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5179 p[-3] = (unsigned char) pop_failure_jump;
5180 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5183 else if ((re_opcode_t) p1[3] == charset)
5186 /* We win if the charset inside the loop
5187 has no overlap with the one after the loop. */
5190 && idx < CHARSET_BITMAP_SIZE (&p1[3]));
5192 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5196 || idx == CHARSET_BITMAP_SIZE (&p1[3]))
5198 p[-3] = (unsigned char) pop_failure_jump;
5199 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5205 p -= 2; /* Point at relative address again. */
5206 if ((re_opcode_t) p[-1] != pop_failure_jump)
5208 p[-1] = (unsigned char) jump;
5209 DEBUG_PRINT1 (" Match => jump.\n");
5210 goto unconditional_jump;
5212 /* Note fall through. */
5215 /* The end of a simple repeat has a pop_failure_jump back to
5216 its matching on_failure_jump, where the latter will push a
5217 failure point. The pop_failure_jump takes off failure
5218 points put on by this pop_failure_jump's matching
5219 on_failure_jump; we got through the pattern to here from the
5220 matching on_failure_jump, so didn't fail. */
5221 case pop_failure_jump:
5223 /* We need to pass separate storage for the lowest and
5224 highest registers, even though we don't care about the
5225 actual values. Otherwise, we will restore only one
5226 register from the stack, since lowest will == highest in
5227 `pop_failure_point'. */
5228 unsigned dummy_low_reg, dummy_high_reg;
5229 unsigned char *pdummy;
5232 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5233 POP_FAILURE_POINT (sdummy, pdummy,
5234 dummy_low_reg, dummy_high_reg,
5235 reg_dummy, reg_dummy, reg_info_dummy);
5237 /* Note fall through. */
5240 /* Unconditionally jump (without popping any failure points). */
5243 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5244 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5245 p += mcnt; /* Do the jump. */
5246 DEBUG_PRINT2 ("(to 0x%x).\n", p);
5250 /* We need this opcode so we can detect where alternatives end
5251 in `group_match_null_string_p' et al. */
5253 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5254 goto unconditional_jump;
5257 /* Normally, the on_failure_jump pushes a failure point, which
5258 then gets popped at pop_failure_jump. We will end up at
5259 pop_failure_jump, also, and with a pattern of, say, `a+', we
5260 are skipping over the on_failure_jump, so we have to push
5261 something meaningless for pop_failure_jump to pop. */
5262 case dummy_failure_jump:
5263 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5264 /* It doesn't matter what we push for the string here. What
5265 the code at `fail' tests is the value for the pattern. */
5266 PUSH_FAILURE_POINT (0, 0, -2);
5267 goto unconditional_jump;
5270 /* At the end of an alternative, we need to push a dummy failure
5271 point in case we are followed by a `pop_failure_jump', because
5272 we don't want the failure point for the alternative to be
5273 popped. For example, matching `(a|ab)*' against `aab'
5274 requires that we match the `ab' alternative. */
5275 case push_dummy_failure:
5276 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5277 /* See comments just above at `dummy_failure_jump' about the
5279 PUSH_FAILURE_POINT (0, 0, -2);
5282 /* Have to succeed matching what follows at least n times.
5283 After that, handle like `on_failure_jump'. */
5285 EXTRACT_NUMBER (mcnt, p + 2);
5286 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5289 /* Originally, this is how many times we HAVE to succeed. */
5294 STORE_NUMBER_AND_INCR (p, mcnt);
5295 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
5299 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
5300 p[2] = (unsigned char) no_op;
5301 p[3] = (unsigned char) no_op;
5307 EXTRACT_NUMBER (mcnt, p + 2);
5308 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5310 /* Originally, this is how many times we CAN jump. */
5314 STORE_NUMBER (p + 2, mcnt);
5315 goto unconditional_jump;
5317 /* If don't have to jump any more, skip over the rest of command. */
5324 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5326 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5328 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5329 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
5330 STORE_NUMBER (p1, mcnt);
5335 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5337 /* We SUCCEED in one of the following cases: */
5339 /* Case 1: D is at the beginning or the end of string. */
5340 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5344 /* C1 is the character before D, S1 is the syntax of C1, C2
5345 is the character at D, and S2 is the syntax of C2. */
5347 int pos1 = PTR_TO_OFFSET (d - 1);
5350 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5351 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5353 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 ? pos1 : 1);
5354 UPDATE_SYNTAX_TABLE (charpos);
5358 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5362 if (/* Case 2: Only one of S1 and S2 is Sword. */
5363 ((s1 == Sword) != (s2 == Sword))
5364 /* Case 3: Both of S1 and S2 are Sword, and macro
5365 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5366 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5372 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5374 /* We FAIL in one of the following cases: */
5376 /* Case 1: D is at the beginning or the end of string. */
5377 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5381 /* C1 is the character before D, S1 is the syntax of C1, C2
5382 is the character at D, and S2 is the syntax of C2. */
5384 int pos1 = PTR_TO_OFFSET (d - 1);
5387 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5388 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5390 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5391 UPDATE_SYNTAX_TABLE (charpos);
5395 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5399 if (/* Case 2: Only one of S1 and S2 is Sword. */
5400 ((s1 == Sword) != (s2 == Sword))
5401 /* Case 3: Both of S1 and S2 are Sword, and macro
5402 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5403 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5409 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5411 /* We FAIL in one of the following cases: */
5413 /* Case 1: D is at the end of string. */
5414 if (AT_STRINGS_END (d))
5418 /* C1 is the character before D, S1 is the syntax of C1, C2
5419 is the character at D, and S2 is the syntax of C2. */
5421 int pos1 = PTR_TO_OFFSET (d);
5424 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5426 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5427 UPDATE_SYNTAX_TABLE (charpos);
5431 /* Case 2: S2 is not Sword. */
5435 /* Case 3: D is not at the beginning of string ... */
5436 if (!AT_STRINGS_BEG (d))
5438 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5440 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5444 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5446 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5453 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5455 /* We FAIL in one of the following cases: */
5457 /* Case 1: D is at the beginning of string. */
5458 if (AT_STRINGS_BEG (d))
5462 /* C1 is the character before D, S1 is the syntax of C1, C2
5463 is the character at D, and S2 is the syntax of C2. */
5465 int pos1 = PTR_TO_OFFSET (d);
5468 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5470 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 - 1);
5471 UPDATE_SYNTAX_TABLE (charpos);
5475 /* Case 2: S1 is not Sword. */
5479 /* Case 3: D is not at the end of string ... */
5480 if (!AT_STRINGS_END (d))
5482 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5484 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5488 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5490 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5498 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5499 if (PTR_BYTE_POS ((unsigned char *) d) >= PT_BYTE)
5504 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5505 if (PTR_BYTE_POS ((unsigned char *) d) != PT_BYTE)
5510 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5511 if (PTR_BYTE_POS ((unsigned char *) d) <= PT_BYTE)
5516 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5521 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5527 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5528 UPDATE_SYNTAX_TABLE (pos1);
5535 /* we must concern about multibyte form, ... */
5536 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5538 /* everything should be handled as ASCII, even though it
5539 looks like multibyte form. */
5542 if (SYNTAX (c) != (enum syntaxcode) mcnt)
5546 SET_REGS_MATCHED ();
5550 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5552 goto matchnotsyntax;
5555 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5561 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5562 UPDATE_SYNTAX_TABLE (pos1);
5569 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5573 if (SYNTAX (c) == (enum syntaxcode) mcnt)
5577 SET_REGS_MATCHED ();
5581 DEBUG_PRINT2 ("EXECUTING categoryspec %d.\n", *p);
5588 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5592 if (!CHAR_HAS_CATEGORY (c, mcnt))
5596 SET_REGS_MATCHED ();
5599 case notcategoryspec:
5600 DEBUG_PRINT2 ("EXECUTING notcategoryspec %d.\n", *p);
5607 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5611 if (CHAR_HAS_CATEGORY (c, mcnt))
5615 SET_REGS_MATCHED ();
5618 #else /* not emacs */
5620 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5622 if (!WORDCHAR_P (d))
5624 SET_REGS_MATCHED ();
5629 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5633 SET_REGS_MATCHED ();
5636 #endif /* not emacs */
5641 continue; /* Successfully executed one pattern command; keep going. */
5644 /* We goto here if a matching operation fails. */
5646 if (!FAIL_STACK_EMPTY ())
5647 { /* A restart point is known. Restore to that state. */
5648 DEBUG_PRINT1 ("\nFAIL:\n");
5649 POP_FAILURE_POINT (d, p,
5650 lowest_active_reg, highest_active_reg,
5651 regstart, regend, reg_info);
5653 /* If this failure point is a dummy, try the next one. */
5657 /* If we failed to the end of the pattern, don't examine *p. */
5661 boolean is_a_jump_n = false;
5663 /* If failed to a backwards jump that's part of a repetition
5664 loop, need to pop this failure point and use the next one. */
5665 switch ((re_opcode_t) *p)
5669 case maybe_pop_jump:
5670 case pop_failure_jump:
5673 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5676 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5678 && (re_opcode_t) *p1 == on_failure_jump))
5686 if (d >= string1 && d <= end1)
5690 break; /* Matching at this starting point really fails. */
5694 goto restore_best_regs;
5698 return -1; /* Failure to match. */
5701 /* Subroutine definitions for re_match_2. */
5704 /* We are passed P pointing to a register number after a start_memory.
5706 Return true if the pattern up to the corresponding stop_memory can
5707 match the empty string, and false otherwise.
5709 If we find the matching stop_memory, sets P to point to one past its number.
5710 Otherwise, sets P to an undefined byte less than or equal to END.
5712 We don't handle duplicates properly (yet). */
5715 group_match_null_string_p (p, end, reg_info)
5716 unsigned char **p, *end;
5717 register_info_type *reg_info;
5720 /* Point to after the args to the start_memory. */
5721 unsigned char *p1 = *p + 2;
5725 /* Skip over opcodes that can match nothing, and return true or
5726 false, as appropriate, when we get to one that can't, or to the
5727 matching stop_memory. */
5729 switch ((re_opcode_t) *p1)
5731 /* Could be either a loop or a series of alternatives. */
5732 case on_failure_jump:
5734 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5736 /* If the next operation is not a jump backwards in the
5741 /* Go through the on_failure_jumps of the alternatives,
5742 seeing if any of the alternatives cannot match nothing.
5743 The last alternative starts with only a jump,
5744 whereas the rest start with on_failure_jump and end
5745 with a jump, e.g., here is the pattern for `a|b|c':
5747 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5748 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5751 So, we have to first go through the first (n-1)
5752 alternatives and then deal with the last one separately. */
5755 /* Deal with the first (n-1) alternatives, which start
5756 with an on_failure_jump (see above) that jumps to right
5757 past a jump_past_alt. */
5759 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5761 /* `mcnt' holds how many bytes long the alternative
5762 is, including the ending `jump_past_alt' and
5765 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5769 /* Move to right after this alternative, including the
5773 /* Break if it's the beginning of an n-th alternative
5774 that doesn't begin with an on_failure_jump. */
5775 if ((re_opcode_t) *p1 != on_failure_jump)
5778 /* Still have to check that it's not an n-th
5779 alternative that starts with an on_failure_jump. */
5781 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5782 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5784 /* Get to the beginning of the n-th alternative. */
5790 /* Deal with the last alternative: go back and get number
5791 of the `jump_past_alt' just before it. `mcnt' contains
5792 the length of the alternative. */
5793 EXTRACT_NUMBER (mcnt, p1 - 2);
5795 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5798 p1 += mcnt; /* Get past the n-th alternative. */
5804 assert (p1[1] == **p);
5810 if (!common_op_match_null_string_p (&p1, end, reg_info))
5813 } /* while p1 < end */
5816 } /* group_match_null_string_p */
5819 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5820 It expects P to be the first byte of a single alternative and END one
5821 byte past the last. The alternative can contain groups. */
5824 alt_match_null_string_p (p, end, reg_info)
5825 unsigned char *p, *end;
5826 register_info_type *reg_info;
5829 unsigned char *p1 = p;
5833 /* Skip over opcodes that can match nothing, and break when we get
5834 to one that can't. */
5836 switch ((re_opcode_t) *p1)
5839 case on_failure_jump:
5841 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5846 if (!common_op_match_null_string_p (&p1, end, reg_info))
5849 } /* while p1 < end */
5852 } /* alt_match_null_string_p */
5855 /* Deals with the ops common to group_match_null_string_p and
5856 alt_match_null_string_p.
5858 Sets P to one after the op and its arguments, if any. */
5861 common_op_match_null_string_p (p, end, reg_info)
5862 unsigned char **p, *end;
5863 register_info_type *reg_info;
5868 unsigned char *p1 = *p;
5870 switch ((re_opcode_t) *p1++)
5890 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5891 ret = group_match_null_string_p (&p1, end, reg_info);
5893 /* Have to set this here in case we're checking a group which
5894 contains a group and a back reference to it. */
5896 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5897 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5903 /* If this is an optimized succeed_n for zero times, make the jump. */
5905 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5913 /* Get to the number of times to succeed. */
5915 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5920 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5928 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5936 /* All other opcodes mean we cannot match the empty string. */
5942 } /* common_op_match_null_string_p */
5945 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5946 bytes; nonzero otherwise. */
5949 bcmp_translate (s1, s2, len, translate)
5950 unsigned char *s1, *s2;
5952 RE_TRANSLATE_TYPE translate;
5954 register unsigned char *p1 = s1, *p2 = s2;
5955 unsigned char *p1_end = s1 + len;
5956 unsigned char *p2_end = s2 + len;
5958 while (p1 != p1_end && p2 != p2_end)
5960 int p1_charlen, p2_charlen;
5963 p1_ch = STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5964 p2_ch = STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5966 if (RE_TRANSLATE (translate, p1_ch)
5967 != RE_TRANSLATE (translate, p2_ch))
5970 p1 += p1_charlen, p2 += p2_charlen;
5973 if (p1 != p1_end || p2 != p2_end)
5979 /* Entry points for GNU code. */
5981 /* re_compile_pattern is the GNU regular expression compiler: it
5982 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5983 Returns 0 if the pattern was valid, otherwise an error string.
5985 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5986 are set in BUFP on entry.
5988 We call regex_compile to do the actual compilation. */
5991 re_compile_pattern (pattern, length, bufp)
5992 const char *pattern;
5994 struct re_pattern_buffer *bufp;
5998 /* GNU code is written to assume at least RE_NREGS registers will be set
5999 (and at least one extra will be -1). */
6000 bufp->regs_allocated = REGS_UNALLOCATED;
6002 /* And GNU code determines whether or not to get register information
6003 by passing null for the REGS argument to re_match, etc., not by
6007 /* Match anchors at newline. */
6008 bufp->newline_anchor = 1;
6010 ret = regex_compile (pattern, length, re_syntax_options, bufp);
6014 return gettext (re_error_msgid[(int) ret]);
6017 /* Entry points compatible with 4.2 BSD regex library. We don't define
6018 them unless specifically requested. */
6020 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
6022 /* BSD has one and only one pattern buffer. */
6023 static struct re_pattern_buffer re_comp_buf;
6027 /* Make these definitions weak in libc, so POSIX programs can redefine
6028 these names if they don't use our functions, and still use
6029 regcomp/regexec below without link errors. */
6039 if (!re_comp_buf.buffer)
6040 return gettext ("No previous regular expression");
6044 if (!re_comp_buf.buffer)
6046 re_comp_buf.buffer = (unsigned char *) malloc (200);
6047 if (re_comp_buf.buffer == NULL)
6048 return gettext (re_error_msgid[(int) REG_ESPACE]);
6049 re_comp_buf.allocated = 200;
6051 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6052 if (re_comp_buf.fastmap == NULL)
6053 return gettext (re_error_msgid[(int) REG_ESPACE]);
6056 /* Since `re_exec' always passes NULL for the `regs' argument, we
6057 don't need to initialize the pattern buffer fields which affect it. */
6059 /* Match anchors at newlines. */
6060 re_comp_buf.newline_anchor = 1;
6062 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6067 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6068 return (char *) gettext (re_error_msgid[(int) ret]);
6079 const int len = strlen (s);
6081 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6083 #endif /* _REGEX_RE_COMP */
6085 /* POSIX.2 functions. Don't define these for Emacs. */
6089 /* regcomp takes a regular expression as a string and compiles it.
6091 PREG is a regex_t *. We do not expect any fields to be initialized,
6092 since POSIX says we shouldn't. Thus, we set
6094 `buffer' to the compiled pattern;
6095 `used' to the length of the compiled pattern;
6096 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6097 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6098 RE_SYNTAX_POSIX_BASIC;
6099 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6100 `fastmap' and `fastmap_accurate' to zero;
6101 `re_nsub' to the number of subexpressions in PATTERN.
6103 PATTERN is the address of the pattern string.
6105 CFLAGS is a series of bits which affect compilation.
6107 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6108 use POSIX basic syntax.
6110 If REG_NEWLINE is set, then . and [^...] don't match newline.
6111 Also, regexec will try a match beginning after every newline.
6113 If REG_ICASE is set, then we considers upper- and lowercase
6114 versions of letters to be equivalent when matching.
6116 If REG_NOSUB is set, then when PREG is passed to regexec, that
6117 routine will report only success or failure, and nothing about the
6120 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6121 the return codes and their meanings.) */
6124 regcomp (preg, pattern, cflags)
6126 const char *pattern;
6131 = (cflags & REG_EXTENDED) ?
6132 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6134 /* regex_compile will allocate the space for the compiled pattern. */
6136 preg->allocated = 0;
6139 /* Don't bother to use a fastmap when searching. This simplifies the
6140 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6141 characters after newlines into the fastmap. This way, we just try
6145 if (cflags & REG_ICASE)
6150 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6151 * sizeof (*(RE_TRANSLATE_TYPE)0));
6152 if (preg->translate == NULL)
6153 return (int) REG_ESPACE;
6155 /* Map uppercase characters to corresponding lowercase ones. */
6156 for (i = 0; i < CHAR_SET_SIZE; i++)
6157 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6160 preg->translate = NULL;
6162 /* If REG_NEWLINE is set, newlines are treated differently. */
6163 if (cflags & REG_NEWLINE)
6164 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6165 syntax &= ~RE_DOT_NEWLINE;
6166 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6167 /* It also changes the matching behavior. */
6168 preg->newline_anchor = 1;
6171 preg->newline_anchor = 0;
6173 preg->no_sub = !!(cflags & REG_NOSUB);
6175 /* POSIX says a null character in the pattern terminates it, so we
6176 can use strlen here in compiling the pattern. */
6177 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
6179 /* POSIX doesn't distinguish between an unmatched open-group and an
6180 unmatched close-group: both are REG_EPAREN. */
6181 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6187 /* regexec searches for a given pattern, specified by PREG, in the
6190 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6191 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6192 least NMATCH elements, and we set them to the offsets of the
6193 corresponding matched substrings.
6195 EFLAGS specifies `execution flags' which affect matching: if
6196 REG_NOTBOL is set, then ^ does not match at the beginning of the
6197 string; if REG_NOTEOL is set, then $ does not match at the end.
6199 We return 0 if we find a match and REG_NOMATCH if not. */
6202 regexec (preg, string, nmatch, pmatch, eflags)
6203 const regex_t *preg;
6206 regmatch_t pmatch[];
6210 struct re_registers regs;
6211 regex_t private_preg;
6212 int len = strlen (string);
6213 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6215 private_preg = *preg;
6217 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6218 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6220 /* The user has told us exactly how many registers to return
6221 information about, via `nmatch'. We have to pass that on to the
6222 matching routines. */
6223 private_preg.regs_allocated = REGS_FIXED;
6227 regs.num_regs = nmatch;
6228 regs.start = TALLOC (nmatch, regoff_t);
6229 regs.end = TALLOC (nmatch, regoff_t);
6230 if (regs.start == NULL || regs.end == NULL)
6231 return (int) REG_NOMATCH;
6234 /* Perform the searching operation. */
6235 ret = re_search (&private_preg, string, len,
6236 /* start: */ 0, /* range: */ len,
6237 want_reg_info ? ®s : (struct re_registers *) 0);
6239 /* Copy the register information to the POSIX structure. */
6246 for (r = 0; r < nmatch; r++)
6248 pmatch[r].rm_so = regs.start[r];
6249 pmatch[r].rm_eo = regs.end[r];
6253 /* If we needed the temporary register info, free the space now. */
6258 /* We want zero return to mean success, unlike `re_search'. */
6259 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6263 /* Returns a message corresponding to an error code, ERRCODE, returned
6264 from either regcomp or regexec. We don't use PREG here. */
6267 regerror (errcode, preg, errbuf, errbuf_size)
6269 const regex_t *preg;
6277 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6278 /* Only error codes returned by the rest of the code should be passed
6279 to this routine. If we are given anything else, or if other regex
6280 code generates an invalid error code, then the program has a bug.
6281 Dump core so we can fix it. */
6284 msg = gettext (re_error_msgid[errcode]);
6286 msg_size = strlen (msg) + 1; /* Includes the null. */
6288 if (errbuf_size != 0)
6290 if (msg_size > errbuf_size)
6292 strncpy (errbuf, msg, errbuf_size - 1);
6293 errbuf[errbuf_size - 1] = 0;
6296 strcpy (errbuf, msg);
6303 /* Free dynamically allocated space used by PREG. */
6309 if (preg->buffer != NULL)
6310 free (preg->buffer);
6311 preg->buffer = NULL;
6313 preg->allocated = 0;
6316 if (preg->fastmap != NULL)
6317 free (preg->fastmap);
6318 preg->fastmap = NULL;
6319 preg->fastmap_accurate = 0;
6321 if (preg->translate != NULL)
6322 free (preg->translate);
6323 preg->translate = NULL;
6326 #endif /* not emacs */