1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P1003.2/D11.2, except for some of the
4 internationalization features.)
5 Copyright (C) 1993-1999, 2000, 2001 Free Software Foundation, Inc.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
12 The GNU C Library 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 GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined _AIX && !defined REGEX_MALLOC
35 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
36 # define PARAMS(args) args
38 # define PARAMS(args) ()
40 #endif /* Not PARAMS. */
42 #ifndef INSIDE_RECURSION
44 # if defined STDC_HEADERS && !defined emacs
47 /* We need this for `regex.h', and perhaps for the Emacs include files. */
48 # include <sys/types.h>
51 # define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
53 /* For platform which support the ISO C amendement 1 functionality we
54 support user defined character classes. */
55 # if defined _LIBC || WIDE_CHAR_SUPPORT
56 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
62 /* We have to keep the namespace clean. */
63 # define regfree(preg) __regfree (preg)
64 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
65 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
66 # define regerror(errcode, preg, errbuf, errbuf_size) \
67 __regerror(errcode, preg, errbuf, errbuf_size)
68 # define re_set_registers(bu, re, nu, st, en) \
69 __re_set_registers (bu, re, nu, st, en)
70 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
71 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
72 # define re_match(bufp, string, size, pos, regs) \
73 __re_match (bufp, string, size, pos, regs)
74 # define re_search(bufp, string, size, startpos, range, regs) \
75 __re_search (bufp, string, size, startpos, range, regs)
76 # define re_compile_pattern(pattern, length, bufp) \
77 __re_compile_pattern (pattern, length, bufp)
78 # define re_set_syntax(syntax) __re_set_syntax (syntax)
79 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
80 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
81 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
83 # define btowc __btowc
85 /* We are also using some library internals. */
86 # include <locale/localeinfo.h>
87 # include <locale/elem-hash.h>
88 # include <langinfo.h>
89 # include <locale/coll-lookup.h>
92 /* This is for other GNU distributions with internationalized messages. */
93 # if HAVE_LIBINTL_H || defined _LIBC
97 # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
100 # define gettext(msgid) (msgid)
103 # ifndef gettext_noop
104 /* This define is so xgettext can find the internationalizable
106 # define gettext_noop(String) String
109 /* The `emacs' switch turns on certain matching commands
110 that make sense only in Emacs. */
117 # else /* not emacs */
119 /* If we are not linking with Emacs proper,
120 we can't use the relocating allocator
121 even if config.h says that we can. */
124 # if defined STDC_HEADERS || defined _LIBC
131 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
132 If nothing else has been done, use the method below. */
133 # ifdef INHIBIT_STRING_HEADER
134 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
135 # if !defined bzero && !defined bcopy
136 # undef INHIBIT_STRING_HEADER
141 /* This is the normal way of making sure we have a bcopy and a bzero.
142 This is used in most programs--a few other programs avoid this
143 by defining INHIBIT_STRING_HEADER. */
144 # ifndef INHIBIT_STRING_HEADER
145 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
149 # define bzero(s, n) (memset (s, '\0', n), (s))
151 # define bzero(s, n) __bzero (s, n)
155 # include <strings.h>
157 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
160 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
165 /* Define the syntax stuff for \<, \>, etc. */
167 /* This must be nonzero for the wordchar and notwordchar pattern
168 commands in re_match_2. */
173 # ifdef SWITCH_ENUM_BUG
174 # define SWITCH_ENUM_CAST(x) ((int)(x))
176 # define SWITCH_ENUM_CAST(x) (x)
179 # endif /* not emacs */
181 # if defined _LIBC || HAVE_LIMITS_H
186 # define MB_LEN_MAX 1
189 /* Get the interface, including the syntax bits. */
192 /* isalpha etc. are used for the character classes. */
195 /* Jim Meyering writes:
197 "... Some ctype macros are valid only for character codes that
198 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
199 using /bin/cc or gcc but without giving an ansi option). So, all
200 ctype uses should be through macros like ISPRINT... If
201 STDC_HEADERS is defined, then autoconf has verified that the ctype
202 macros don't need to be guarded with references to isascii. ...
203 Defining isascii to 1 should let any compiler worth its salt
204 eliminate the && through constant folding."
205 Solaris defines some of these symbols so we must undefine them first. */
208 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
209 # define ISASCII(c) 1
211 # define ISASCII(c) isascii(c)
215 # define ISBLANK(c) (ISASCII (c) && isblank (c))
217 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
220 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
222 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
226 # define ISPRINT(c) (ISASCII (c) && isprint (c))
227 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
228 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
229 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
230 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
231 # define ISLOWER(c) (ISASCII (c) && islower (c))
232 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
233 # define ISSPACE(c) (ISASCII (c) && isspace (c))
234 # define ISUPPER(c) (ISASCII (c) && isupper (c))
235 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
238 # define TOLOWER(c) _tolower(c)
240 # define TOLOWER(c) tolower(c)
244 # define NULL (void *)0
247 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
248 since ours (we hope) works properly with all combinations of
249 machines, compilers, `char' and `unsigned char' argument types.
250 (Per Bothner suggested the basic approach.) */
251 # undef SIGN_EXTEND_CHAR
253 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
254 # else /* not __STDC__ */
255 /* As in Harbison and Steele. */
256 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
260 /* How many characters in the character set. */
261 # define CHAR_SET_SIZE 256
265 extern char *re_syntax_table;
267 # else /* not SYNTAX_TABLE */
269 static char re_syntax_table[CHAR_SET_SIZE];
271 static void init_syntax_once PARAMS ((void));
281 bzero (re_syntax_table, sizeof re_syntax_table);
283 for (c = 0; c < CHAR_SET_SIZE; ++c)
285 re_syntax_table[c] = Sword;
287 re_syntax_table['_'] = Sword;
292 # endif /* not SYNTAX_TABLE */
294 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
298 /* Integer type for pointers. */
300 typedef unsigned long int uintptr_t;
303 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
304 use `alloca' instead of `malloc'. This is because using malloc in
305 re_search* or re_match* could cause memory leaks when C-g is used in
306 Emacs; also, malloc is slower and causes storage fragmentation. On
307 the other hand, malloc is more portable, and easier to debug.
309 Because we sometimes use alloca, some routines have to be macros,
310 not functions -- `alloca'-allocated space disappears at the end of the
311 function it is called in. */
315 # define REGEX_ALLOCATE malloc
316 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
317 # define REGEX_FREE free
319 # else /* not REGEX_MALLOC */
321 /* Emacs already defines alloca, sometimes. */
324 /* Make alloca work the best possible way. */
326 # define alloca __builtin_alloca
327 # else /* not __GNUC__ */
330 # endif /* HAVE_ALLOCA_H */
331 # endif /* not __GNUC__ */
333 # endif /* not alloca */
335 # define REGEX_ALLOCATE alloca
337 /* Assumes a `char *destination' variable. */
338 # define REGEX_REALLOCATE(source, osize, nsize) \
339 (destination = (char *) alloca (nsize), \
340 memcpy (destination, source, osize))
342 /* No need to do anything to free, after alloca. */
343 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
345 # endif /* not REGEX_MALLOC */
347 /* Define how to allocate the failure stack. */
349 # if defined REL_ALLOC && defined REGEX_MALLOC
351 # define REGEX_ALLOCATE_STACK(size) \
352 r_alloc (&failure_stack_ptr, (size))
353 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
354 r_re_alloc (&failure_stack_ptr, (nsize))
355 # define REGEX_FREE_STACK(ptr) \
356 r_alloc_free (&failure_stack_ptr)
358 # else /* not using relocating allocator */
362 # define REGEX_ALLOCATE_STACK malloc
363 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
364 # define REGEX_FREE_STACK free
366 # else /* not REGEX_MALLOC */
368 # define REGEX_ALLOCATE_STACK alloca
370 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
371 REGEX_REALLOCATE (source, osize, nsize)
372 /* No need to explicitly free anything. */
373 # define REGEX_FREE_STACK(arg)
375 # endif /* not REGEX_MALLOC */
376 # endif /* not using relocating allocator */
379 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
380 `string1' or just past its end. This works if PTR is NULL, which is
382 # define FIRST_STRING_P(ptr) \
383 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
385 /* (Re)Allocate N items of type T using malloc, or fail. */
386 # define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
387 # define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
388 # define RETALLOC_IF(addr, n, t) \
389 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
390 # define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
392 # define BYTEWIDTH 8 /* In bits. */
394 # define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
398 # define MAX(a, b) ((a) > (b) ? (a) : (b))
399 # define MIN(a, b) ((a) < (b) ? (a) : (b))
401 typedef char boolean;
405 static reg_errcode_t byte_regex_compile _RE_ARGS ((const char *pattern, size_t size,
407 struct re_pattern_buffer *bufp));
408 static reg_errcode_t wcs_regex_compile _RE_ARGS ((const char *pattern, size_t size,
410 struct re_pattern_buffer *bufp));
412 static int byte_re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
413 const char *string1, int size1,
414 const char *string2, int size2,
416 struct re_registers *regs,
418 static int wcs_re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
419 const char *string1, int size1,
420 const char *string2, int size2,
422 struct re_registers *regs,
424 static int byte_re_search_2 PARAMS ((struct re_pattern_buffer *bufp,
425 const char *string1, int size1,
426 const char *string2, int size2,
427 int startpos, int range,
428 struct re_registers *regs, int stop));
429 static int wcs_re_search_2 PARAMS ((struct re_pattern_buffer *bufp,
430 const char *string1, int size1,
431 const char *string2, int size2,
432 int startpos, int range,
433 struct re_registers *regs, int stop));
434 static int byte_re_compile_fastmap PARAMS ((struct re_pattern_buffer *bufp));
435 static int wcs_re_compile_fastmap PARAMS ((struct re_pattern_buffer *bufp));
438 /* These are the command codes that appear in compiled regular
439 expressions. Some opcodes are followed by argument bytes. A
440 command code can specify any interpretation whatsoever for its
441 arguments. Zero bytes may appear in the compiled regular expression. */
447 /* Succeed right away--no more backtracking. */
450 /* Followed by one byte giving n, then by n literal bytes. */
454 /* Same as exactn, but contains binary data. */
458 /* Matches any (more or less) character. */
461 /* Matches any one char belonging to specified set. First
462 following byte is number of bitmap bytes. Then come bytes
463 for a bitmap saying which chars are in. Bits in each byte
464 are ordered low-bit-first. A character is in the set if its
465 bit is 1. A character too large to have a bit in the map is
466 automatically not in the set. */
467 /* ifdef MBS_SUPPORT, following element is length of character
468 classes, length of collating symbols, length of equivalence
469 classes, length of character ranges, and length of characters.
470 Next, character class element, collating symbols elements,
471 equivalence class elements, range elements, and character
473 See regex_compile function. */
476 /* Same parameters as charset, but match any character that is
477 not one of those specified. */
480 /* Start remembering the text that is matched, for storing in a
481 register. Followed by one byte with the register number, in
482 the range 0 to one less than the pattern buffer's re_nsub
483 field. Then followed by one byte with the number of groups
484 inner to this one. (This last has to be part of the
485 start_memory only because we need it in the on_failure_jump
489 /* Stop remembering the text that is matched and store it in a
490 memory register. Followed by one byte with the register
491 number, in the range 0 to one less than `re_nsub' in the
492 pattern buffer, and one byte with the number of inner groups,
493 just like `start_memory'. (We need the number of inner
494 groups here because we don't have any easy way of finding the
495 corresponding start_memory when we're at a stop_memory.) */
498 /* Match a duplicate of something remembered. Followed by one
499 byte containing the register number. */
502 /* Fail unless at beginning of line. */
505 /* Fail unless at end of line. */
508 /* Succeeds if at beginning of buffer (if emacs) or at beginning
509 of string to be matched (if not). */
512 /* Analogously, for end of buffer/string. */
515 /* Followed by two byte relative address to which to jump. */
518 /* Same as jump, but marks the end of an alternative. */
521 /* Followed by two-byte relative address of place to resume at
522 in case of failure. */
523 /* ifdef MBS_SUPPORT, the size of address is 1. */
526 /* Like on_failure_jump, but pushes a placeholder instead of the
527 current string position when executed. */
528 on_failure_keep_string_jump,
530 /* Throw away latest failure point and then jump to following
531 two-byte relative address. */
532 /* ifdef MBS_SUPPORT, the size of address is 1. */
535 /* Change to pop_failure_jump if know won't have to backtrack to
536 match; otherwise change to jump. This is used to jump
537 back to the beginning of a repeat. If what follows this jump
538 clearly won't match what the repeat does, such that we can be
539 sure that there is no use backtracking out of repetitions
540 already matched, then we change it to a pop_failure_jump.
541 Followed by two-byte address. */
542 /* ifdef MBS_SUPPORT, the size of address is 1. */
545 /* Jump to following two-byte address, and push a dummy failure
546 point. This failure point will be thrown away if an attempt
547 is made to use it for a failure. A `+' construct makes this
548 before the first repeat. Also used as an intermediary kind
549 of jump when compiling an alternative. */
550 /* ifdef MBS_SUPPORT, the size of address is 1. */
553 /* Push a dummy failure point and continue. Used at the end of
557 /* Followed by two-byte relative address and two-byte number n.
558 After matching N times, jump to the address upon failure. */
559 /* ifdef MBS_SUPPORT, the size of address is 1. */
562 /* Followed by two-byte relative address, and two-byte number n.
563 Jump to the address N times, then fail. */
564 /* ifdef MBS_SUPPORT, the size of address is 1. */
567 /* Set the following two-byte relative address to the
568 subsequent two-byte number. The address *includes* the two
570 /* ifdef MBS_SUPPORT, the size of address is 1. */
573 wordchar, /* Matches any word-constituent character. */
574 notwordchar, /* Matches any char that is not a word-constituent. */
576 wordbeg, /* Succeeds if at word beginning. */
577 wordend, /* Succeeds if at word end. */
579 wordbound, /* Succeeds if at a word boundary. */
580 notwordbound /* Succeeds if not at a word boundary. */
583 ,before_dot, /* Succeeds if before point. */
584 at_dot, /* Succeeds if at point. */
585 after_dot, /* Succeeds if after point. */
587 /* Matches any character whose syntax is specified. Followed by
588 a byte which contains a syntax code, e.g., Sword. */
591 /* Matches any character whose syntax is not that specified. */
595 #endif /* not INSIDE_RECURSION */
600 # define UCHAR_T unsigned char
601 # define COMPILED_BUFFER_VAR bufp->buffer
602 # define OFFSET_ADDRESS_SIZE 2
603 # define PREFIX(name) byte_##name
604 # define ARG_PREFIX(name) name
605 # define PUT_CHAR(c) putchar (c)
607 # define CHAR_T wchar_t
608 # define UCHAR_T wchar_t
609 # define COMPILED_BUFFER_VAR wc_buffer
610 # define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
611 # define CHAR_CLASS_SIZE ((__alignof__(wctype_t)+sizeof(wctype_t))/sizeof(CHAR_T)+1)
612 # define PREFIX(name) wcs_##name
613 # define ARG_PREFIX(name) c##name
614 /* Should we use wide stream?? */
615 # define PUT_CHAR(c) printf ("%C", c);
621 # define INSIDE_RECURSION
623 # undef INSIDE_RECURSION
626 # define INSIDE_RECURSION
628 # undef INSIDE_RECURSION
631 #ifdef INSIDE_RECURSION
632 /* Common operations on the compiled pattern. */
634 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
635 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
638 # define STORE_NUMBER(destination, number) \
640 *(destination) = (UCHAR_T)(number); \
643 # define STORE_NUMBER(destination, number) \
645 (destination)[0] = (number) & 0377; \
646 (destination)[1] = (number) >> 8; \
650 /* Same as STORE_NUMBER, except increment DESTINATION to
651 the byte after where the number is stored. Therefore, DESTINATION
652 must be an lvalue. */
653 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
655 # define STORE_NUMBER_AND_INCR(destination, number) \
657 STORE_NUMBER (destination, number); \
658 (destination) += OFFSET_ADDRESS_SIZE; \
661 /* Put into DESTINATION a number stored in two contiguous bytes starting
663 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
666 # define EXTRACT_NUMBER(destination, source) \
668 (destination) = *(source); \
671 # define EXTRACT_NUMBER(destination, source) \
673 (destination) = *(source) & 0377; \
674 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
679 static void PREFIX(extract_number) _RE_ARGS ((int *dest, UCHAR_T *source));
681 PREFIX(extract_number) (dest, source)
688 int temp = SIGN_EXTEND_CHAR (*(source + 1));
689 *dest = *source & 0377;
694 # ifndef EXTRACT_MACROS /* To debug the macros. */
695 # undef EXTRACT_NUMBER
696 # define EXTRACT_NUMBER(dest, src) PREFIX(extract_number) (&dest, src)
697 # endif /* not EXTRACT_MACROS */
701 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
702 SOURCE must be an lvalue. */
704 # define EXTRACT_NUMBER_AND_INCR(destination, source) \
706 EXTRACT_NUMBER (destination, source); \
707 (source) += OFFSET_ADDRESS_SIZE; \
711 static void PREFIX(extract_number_and_incr) _RE_ARGS ((int *destination,
714 PREFIX(extract_number_and_incr) (destination, source)
718 PREFIX(extract_number) (destination, *source);
719 *source += OFFSET_ADDRESS_SIZE;
722 # ifndef EXTRACT_MACROS
723 # undef EXTRACT_NUMBER_AND_INCR
724 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
725 PREFIX(extract_number_and_incr) (&dest, &src)
726 # endif /* not EXTRACT_MACROS */
732 /* If DEBUG is defined, Regex prints many voluminous messages about what
733 it is doing (if the variable `debug' is nonzero). If linked with the
734 main program in `iregex.c', you can enter patterns and strings
735 interactively. And if linked with the main program in `main.c' and
736 the other test files, you can run the already-written tests. */
740 # ifndef DEFINED_ONCE
742 /* We use standard I/O for debugging. */
745 /* It is useful to test things that ``must'' be true when debugging. */
750 # define DEBUG_STATEMENT(e) e
751 # define DEBUG_PRINT1(x) if (debug) printf (x)
752 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
753 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
754 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
755 # endif /* not DEFINED_ONCE */
757 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
758 if (debug) PREFIX(print_partial_compiled_pattern) (s, e)
759 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
760 if (debug) PREFIX(print_double_string) (w, s1, sz1, s2, sz2)
763 /* Print the fastmap in human-readable form. */
765 # ifndef DEFINED_ONCE
767 print_fastmap (fastmap)
770 unsigned was_a_range = 0;
773 while (i < (1 << BYTEWIDTH))
779 while (i < (1 << BYTEWIDTH) && fastmap[i])
793 # endif /* not DEFINED_ONCE */
796 /* Print a compiled pattern string in human-readable form, starting at
797 the START pointer into it and ending just before the pointer END. */
800 PREFIX(print_partial_compiled_pattern) (start, end)
815 /* Loop over pattern commands. */
819 printf ("%td:\t", p - start);
821 printf ("%ld:\t", (long int) (p - start));
824 switch ((re_opcode_t) *p++)
832 printf ("/exactn/%d", mcnt);
844 printf ("/exactn_bin/%d", mcnt);
847 printf("/%lx", (long int) *p++);
851 # endif /* MBS_SUPPORT */
855 printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
860 printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
864 printf ("/duplicate/%ld", (long int) *p++);
877 printf ("/charset [%s",
878 (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
880 length = *workp++; /* the length of char_classes */
881 for (i=0 ; i<length ; i++)
882 printf("[:%lx:]", (long int) *p++);
883 length = *workp++; /* the length of collating_symbol */
884 for (i=0 ; i<length ;)
888 PUT_CHAR((i++,*p++));
892 length = *workp++; /* the length of equivalence_class */
893 for (i=0 ; i<length ;)
897 PUT_CHAR((i++,*p++));
901 length = *workp++; /* the length of char_range */
902 for (i=0 ; i<length ; i++)
904 wchar_t range_start = *p++;
905 wchar_t range_end = *p++;
906 printf("%C-%C", range_start, range_end);
908 length = *workp++; /* the length of char */
909 for (i=0 ; i<length ; i++)
913 register int c, last = -100;
914 register int in_range = 0;
916 printf ("/charset [%s",
917 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
919 assert (p + *p < pend);
921 for (c = 0; c < 256; c++)
923 && (p[1 + (c/8)] & (1 << (c % 8))))
925 /* Are we starting a range? */
926 if (last + 1 == c && ! in_range)
931 /* Have we broken a range? */
932 else if (last + 1 != c && in_range)
962 case on_failure_jump:
963 PREFIX(extract_number_and_incr) (&mcnt, &p);
965 printf ("/on_failure_jump to %td", p + mcnt - start);
967 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
971 case on_failure_keep_string_jump:
972 PREFIX(extract_number_and_incr) (&mcnt, &p);
974 printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
976 printf ("/on_failure_keep_string_jump to %ld",
977 (long int) (p + mcnt - start));
981 case dummy_failure_jump:
982 PREFIX(extract_number_and_incr) (&mcnt, &p);
984 printf ("/dummy_failure_jump to %td", p + mcnt - start);
986 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
990 case push_dummy_failure:
991 printf ("/push_dummy_failure");
995 PREFIX(extract_number_and_incr) (&mcnt, &p);
997 printf ("/maybe_pop_jump to %td", p + mcnt - start);
999 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
1003 case pop_failure_jump:
1004 PREFIX(extract_number_and_incr) (&mcnt, &p);
1006 printf ("/pop_failure_jump to %td", p + mcnt - start);
1008 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
1013 PREFIX(extract_number_and_incr) (&mcnt, &p);
1015 printf ("/jump_past_alt to %td", p + mcnt - start);
1017 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
1022 PREFIX(extract_number_and_incr) (&mcnt, &p);
1024 printf ("/jump to %td", p + mcnt - start);
1026 printf ("/jump to %ld", (long int) (p + mcnt - start));
1031 PREFIX(extract_number_and_incr) (&mcnt, &p);
1033 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1035 printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
1037 printf ("/succeed_n to %ld, %d times",
1038 (long int) (p1 - start), mcnt2);
1043 PREFIX(extract_number_and_incr) (&mcnt, &p);
1045 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1046 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
1050 PREFIX(extract_number_and_incr) (&mcnt, &p);
1052 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1054 printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1056 printf ("/set_number_at location %ld to %d",
1057 (long int) (p1 - start), mcnt2);
1062 printf ("/wordbound");
1066 printf ("/notwordbound");
1070 printf ("/wordbeg");
1074 printf ("/wordend");
1079 printf ("/before_dot");
1087 printf ("/after_dot");
1091 printf ("/syntaxspec");
1093 printf ("/%d", mcnt);
1097 printf ("/notsyntaxspec");
1099 printf ("/%d", mcnt);
1104 printf ("/wordchar");
1108 printf ("/notwordchar");
1120 printf ("?%ld", (long int) *(p-1));
1127 printf ("%td:\tend of pattern.\n", p - start);
1129 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1135 PREFIX(print_compiled_pattern) (bufp)
1136 struct re_pattern_buffer *bufp;
1138 UCHAR_T *buffer = (UCHAR_T*) bufp->buffer;
1140 PREFIX(print_partial_compiled_pattern) (buffer, buffer
1141 + bufp->used / sizeof(UCHAR_T));
1142 printf ("%ld bytes used/%ld bytes allocated.\n",
1143 bufp->used, bufp->allocated);
1145 if (bufp->fastmap_accurate && bufp->fastmap)
1147 printf ("fastmap: ");
1148 print_fastmap (bufp->fastmap);
1152 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1154 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1156 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1157 printf ("can_be_null: %d\t", bufp->can_be_null);
1158 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1159 printf ("no_sub: %d\t", bufp->no_sub);
1160 printf ("not_bol: %d\t", bufp->not_bol);
1161 printf ("not_eol: %d\t", bufp->not_eol);
1162 printf ("syntax: %lx\n", bufp->syntax);
1163 /* Perhaps we should print the translate table? */
1168 PREFIX(print_double_string) (where, string1, size1, string2, size2)
1169 const CHAR_T *where;
1170 const CHAR_T *string1;
1171 const CHAR_T *string2;
1181 if (FIRST_STRING_P (where))
1183 for (this_char = where - string1; this_char < size1; this_char++)
1184 PUT_CHAR (string1[this_char]);
1189 for (this_char = where - string2; this_char < size2; this_char++)
1190 PUT_CHAR (string2[this_char]);
1194 # ifndef DEFINED_ONCE
1203 # else /* not DEBUG */
1205 # ifndef DEFINED_ONCE
1209 # define DEBUG_STATEMENT(e)
1210 # define DEBUG_PRINT1(x)
1211 # define DEBUG_PRINT2(x1, x2)
1212 # define DEBUG_PRINT3(x1, x2, x3)
1213 # define DEBUG_PRINT4(x1, x2, x3, x4)
1214 # endif /* not DEFINED_ONCE */
1215 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1216 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1218 # endif /* not DEBUG */
1223 /* This convert a multibyte string to a wide character string.
1224 And write their correspondances to offset_buffer(see below)
1225 and write whether each wchar_t is binary data to is_binary.
1226 This assume invalid multibyte sequences as binary data.
1227 We assume offset_buffer and is_binary is already allocated
1230 static size_t convert_mbs_to_wcs (CHAR_T *dest, const unsigned char* src,
1231 size_t len, int *offset_buffer,
1234 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1236 const unsigned char* src;
1237 size_t len; /* the length of multibyte string. */
1239 /* It hold correspondances between src(char string) and
1240 dest(wchar_t string) for optimization.
1242 dest = {'X', 'Y', 'Z'}
1243 (each "xxx", "y" and "zz" represent one multibyte character
1244 corresponding to 'X', 'Y' and 'Z'.)
1245 offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1251 wchar_t *pdest = dest;
1252 const unsigned char *psrc = src;
1253 size_t wc_count = 0;
1257 size_t mb_remain = len;
1258 size_t mb_count = 0;
1260 /* Initialize the conversion state. */
1261 memset (&mbs, 0, sizeof (mbstate_t));
1263 offset_buffer[0] = 0;
1264 for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1267 consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1270 /* failed to convert. maybe src contains binary data.
1271 So we consume 1 byte manualy. */
1275 is_binary[wc_count] = TRUE;
1278 is_binary[wc_count] = FALSE;
1279 /* In sjis encoding, we use yen sign as escape character in
1280 place of reverse solidus. So we convert 0x5c(yen sign in
1281 sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1282 solidus in UCS2). */
1283 if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1284 *pdest = (wchar_t) *psrc;
1286 offset_buffer[wc_count + 1] = mb_count += consumed;
1294 #else /* not INSIDE_RECURSION */
1296 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1297 also be assigned to arbitrarily: each pattern buffer stores its own
1298 syntax, so it can be changed between regex compilations. */
1299 /* This has no initializer because initialized variables in Emacs
1300 become read-only after dumping. */
1301 reg_syntax_t re_syntax_options;
1304 /* Specify the precise syntax of regexps for compilation. This provides
1305 for compatibility for various utilities which historically have
1306 different, incompatible syntaxes.
1308 The argument SYNTAX is a bit mask comprised of the various bits
1309 defined in regex.h. We return the old syntax. */
1312 re_set_syntax (syntax)
1313 reg_syntax_t syntax;
1315 reg_syntax_t ret = re_syntax_options;
1317 re_syntax_options = syntax;
1319 if (syntax & RE_DEBUG)
1321 else if (debug) /* was on but now is not */
1327 weak_alias (__re_set_syntax, re_set_syntax)
1330 /* This table gives an error message for each of the error codes listed
1331 in regex.h. Obviously the order here has to be same as there.
1332 POSIX doesn't require that we do anything for REG_NOERROR,
1333 but why not be nice? */
1335 static const char re_error_msgid[] =
1337 # define REG_NOERROR_IDX 0
1338 gettext_noop ("Success") /* REG_NOERROR */
1340 # define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1341 gettext_noop ("No match") /* REG_NOMATCH */
1343 # define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1344 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1346 # define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1347 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1349 # define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1350 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1352 # define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1353 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1355 # define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1356 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1358 # define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1359 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1361 # define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1362 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1364 # define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1365 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1367 # define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1368 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1370 # define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1371 gettext_noop ("Invalid range end") /* REG_ERANGE */
1373 # define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1374 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1376 # define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1377 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1379 # define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1380 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1382 # define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1383 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1385 # define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1386 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1389 static const size_t re_error_msgid_idx[] =
1410 #endif /* INSIDE_RECURSION */
1412 #ifndef DEFINED_ONCE
1413 /* Avoiding alloca during matching, to placate r_alloc. */
1415 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1416 searching and matching functions should not call alloca. On some
1417 systems, alloca is implemented in terms of malloc, and if we're
1418 using the relocating allocator routines, then malloc could cause a
1419 relocation, which might (if the strings being searched are in the
1420 ralloc heap) shift the data out from underneath the regexp
1423 Here's another reason to avoid allocation: Emacs
1424 processes input from X in a signal handler; processing X input may
1425 call malloc; if input arrives while a matching routine is calling
1426 malloc, then we're scrod. But Emacs can't just block input while
1427 calling matching routines; then we don't notice interrupts when
1428 they come in. So, Emacs blocks input around all regexp calls
1429 except the matching calls, which it leaves unprotected, in the
1430 faith that they will not malloc. */
1432 /* Normally, this is fine. */
1433 # define MATCH_MAY_ALLOCATE
1435 /* When using GNU C, we are not REALLY using the C alloca, no matter
1436 what config.h may say. So don't take precautions for it. */
1441 /* The match routines may not allocate if (1) they would do it with malloc
1442 and (2) it's not safe for them to use malloc.
1443 Note that if REL_ALLOC is defined, matching would not use malloc for the
1444 failure stack, but we would still use it for the register vectors;
1445 so REL_ALLOC should not affect this. */
1446 # if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1447 # undef MATCH_MAY_ALLOCATE
1449 #endif /* not DEFINED_ONCE */
1451 #ifdef INSIDE_RECURSION
1452 /* Failure stack declarations and macros; both re_compile_fastmap and
1453 re_match_2 use a failure stack. These have to be macros because of
1454 REGEX_ALLOCATE_STACK. */
1457 /* Number of failure points for which to initially allocate space
1458 when matching. If this number is exceeded, we allocate more
1459 space, so it is not a hard limit. */
1460 # ifndef INIT_FAILURE_ALLOC
1461 # define INIT_FAILURE_ALLOC 5
1464 /* Roughly the maximum number of failure points on the stack. Would be
1465 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1466 This is a variable only so users of regex can assign to it; we never
1467 change it ourselves. */
1469 # ifdef INT_IS_16BIT
1471 # ifndef DEFINED_ONCE
1472 # if defined MATCH_MAY_ALLOCATE
1473 /* 4400 was enough to cause a crash on Alpha OSF/1,
1474 whose default stack limit is 2mb. */
1475 long int re_max_failures = 4000;
1477 long int re_max_failures = 2000;
1481 union PREFIX(fail_stack_elt)
1487 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1491 PREFIX(fail_stack_elt_t) *stack;
1492 unsigned long int size;
1493 unsigned long int avail; /* Offset of next open position. */
1494 } PREFIX(fail_stack_type);
1496 # else /* not INT_IS_16BIT */
1498 # ifndef DEFINED_ONCE
1499 # if defined MATCH_MAY_ALLOCATE
1500 /* 4400 was enough to cause a crash on Alpha OSF/1,
1501 whose default stack limit is 2mb. */
1502 int re_max_failures = 4000;
1504 int re_max_failures = 2000;
1508 union PREFIX(fail_stack_elt)
1514 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1518 PREFIX(fail_stack_elt_t) *stack;
1520 unsigned avail; /* Offset of next open position. */
1521 } PREFIX(fail_stack_type);
1523 # endif /* INT_IS_16BIT */
1525 # ifndef DEFINED_ONCE
1526 # define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1527 # define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1528 # define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1532 /* Define macros to initialize and free the failure stack.
1533 Do `return -2' if the alloc fails. */
1535 # ifdef MATCH_MAY_ALLOCATE
1536 # define INIT_FAIL_STACK() \
1538 fail_stack.stack = (PREFIX(fail_stack_elt_t) *) \
1539 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (PREFIX(fail_stack_elt_t))); \
1541 if (fail_stack.stack == NULL) \
1544 fail_stack.size = INIT_FAILURE_ALLOC; \
1545 fail_stack.avail = 0; \
1548 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1550 # define INIT_FAIL_STACK() \
1552 fail_stack.avail = 0; \
1555 # define RESET_FAIL_STACK()
1559 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1561 Return 1 if succeeds, and 0 if either ran out of memory
1562 allocating space for it or it was already too large.
1564 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1566 # define DOUBLE_FAIL_STACK(fail_stack) \
1567 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1569 : ((fail_stack).stack = (PREFIX(fail_stack_elt_t) *) \
1570 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1571 (fail_stack).size * sizeof (PREFIX(fail_stack_elt_t)), \
1572 ((fail_stack).size << 1) * sizeof (PREFIX(fail_stack_elt_t))),\
1574 (fail_stack).stack == NULL \
1576 : ((fail_stack).size <<= 1, \
1580 /* Push pointer POINTER on FAIL_STACK.
1581 Return 1 if was able to do so and 0 if ran out of memory allocating
1583 # define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1584 ((FAIL_STACK_FULL () \
1585 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1587 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1590 /* Push a pointer value onto the failure stack.
1591 Assumes the variable `fail_stack'. Probably should only
1592 be called from within `PUSH_FAILURE_POINT'. */
1593 # define PUSH_FAILURE_POINTER(item) \
1594 fail_stack.stack[fail_stack.avail++].pointer = (UCHAR_T *) (item)
1596 /* This pushes an integer-valued item onto the failure stack.
1597 Assumes the variable `fail_stack'. Probably should only
1598 be called from within `PUSH_FAILURE_POINT'. */
1599 # define PUSH_FAILURE_INT(item) \
1600 fail_stack.stack[fail_stack.avail++].integer = (item)
1602 /* Push a fail_stack_elt_t value onto the failure stack.
1603 Assumes the variable `fail_stack'. Probably should only
1604 be called from within `PUSH_FAILURE_POINT'. */
1605 # define PUSH_FAILURE_ELT(item) \
1606 fail_stack.stack[fail_stack.avail++] = (item)
1608 /* These three POP... operations complement the three PUSH... operations.
1609 All assume that `fail_stack' is nonempty. */
1610 # define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1611 # define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1612 # define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1614 /* Used to omit pushing failure point id's when we're not debugging. */
1616 # define DEBUG_PUSH PUSH_FAILURE_INT
1617 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1619 # define DEBUG_PUSH(item)
1620 # define DEBUG_POP(item_addr)
1624 /* Push the information about the state we will need
1625 if we ever fail back to it.
1627 Requires variables fail_stack, regstart, regend, reg_info, and
1628 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1631 Does `return FAILURE_CODE' if runs out of memory. */
1633 # define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1635 char *destination; \
1636 /* Must be int, so when we don't save any registers, the arithmetic \
1637 of 0 + -1 isn't done as unsigned. */ \
1638 /* Can't be int, since there is not a shred of a guarantee that int \
1639 is wide enough to hold a value of something to which pointer can \
1641 active_reg_t this_reg; \
1643 DEBUG_STATEMENT (failure_id++); \
1644 DEBUG_STATEMENT (nfailure_points_pushed++); \
1645 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1646 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1647 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1649 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1650 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1652 /* Ensure we have enough space allocated for what we will push. */ \
1653 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1655 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1656 return failure_code; \
1658 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1659 (fail_stack).size); \
1660 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1663 /* Push the info, starting with the registers. */ \
1664 DEBUG_PRINT1 ("\n"); \
1667 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1670 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1671 DEBUG_STATEMENT (num_regs_pushed++); \
1673 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1674 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1676 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1677 PUSH_FAILURE_POINTER (regend[this_reg]); \
1679 DEBUG_PRINT2 (" info: %p\n ", \
1680 reg_info[this_reg].word.pointer); \
1681 DEBUG_PRINT2 (" match_null=%d", \
1682 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1683 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1684 DEBUG_PRINT2 (" matched_something=%d", \
1685 MATCHED_SOMETHING (reg_info[this_reg])); \
1686 DEBUG_PRINT2 (" ever_matched=%d", \
1687 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1688 DEBUG_PRINT1 ("\n"); \
1689 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1692 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1693 PUSH_FAILURE_INT (lowest_active_reg); \
1695 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1696 PUSH_FAILURE_INT (highest_active_reg); \
1698 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1699 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1700 PUSH_FAILURE_POINTER (pattern_place); \
1702 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1703 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1705 DEBUG_PRINT1 ("'\n"); \
1706 PUSH_FAILURE_POINTER (string_place); \
1708 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1709 DEBUG_PUSH (failure_id); \
1712 # ifndef DEFINED_ONCE
1713 /* This is the number of items that are pushed and popped on the stack
1714 for each register. */
1715 # define NUM_REG_ITEMS 3
1717 /* Individual items aside from the registers. */
1719 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1721 # define NUM_NONREG_ITEMS 4
1724 /* We push at most this many items on the stack. */
1725 /* We used to use (num_regs - 1), which is the number of registers
1726 this regexp will save; but that was changed to 5
1727 to avoid stack overflow for a regexp with lots of parens. */
1728 # define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1730 /* We actually push this many items. */
1731 # define NUM_FAILURE_ITEMS \
1733 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1737 /* How many items can still be added to the stack without overflowing it. */
1738 # define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1739 # endif /* not DEFINED_ONCE */
1742 /* Pops what PUSH_FAIL_STACK pushes.
1744 We restore into the parameters, all of which should be lvalues:
1745 STR -- the saved data position.
1746 PAT -- the saved pattern position.
1747 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1748 REGSTART, REGEND -- arrays of string positions.
1749 REG_INFO -- array of information about each subexpression.
1751 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1752 `pend', `string1', `size1', `string2', and `size2'. */
1753 # define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1755 DEBUG_STATEMENT (unsigned failure_id;) \
1756 active_reg_t this_reg; \
1757 const UCHAR_T *string_temp; \
1759 assert (!FAIL_STACK_EMPTY ()); \
1761 /* Remove failure points and point to how many regs pushed. */ \
1762 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1763 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1764 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1766 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1768 DEBUG_POP (&failure_id); \
1769 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1771 /* If the saved string location is NULL, it came from an \
1772 on_failure_keep_string_jump opcode, and we want to throw away the \
1773 saved NULL, thus retaining our current position in the string. */ \
1774 string_temp = POP_FAILURE_POINTER (); \
1775 if (string_temp != NULL) \
1776 str = (const CHAR_T *) string_temp; \
1778 DEBUG_PRINT2 (" Popping string %p: `", str); \
1779 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1780 DEBUG_PRINT1 ("'\n"); \
1782 pat = (UCHAR_T *) POP_FAILURE_POINTER (); \
1783 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1784 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1786 /* Restore register info. */ \
1787 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1788 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1790 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1791 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1794 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1796 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1798 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1799 DEBUG_PRINT2 (" info: %p\n", \
1800 reg_info[this_reg].word.pointer); \
1802 regend[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER (); \
1803 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1805 regstart[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER (); \
1806 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1810 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1812 reg_info[this_reg].word.integer = 0; \
1813 regend[this_reg] = 0; \
1814 regstart[this_reg] = 0; \
1816 highest_active_reg = high_reg; \
1819 set_regs_matched_done = 0; \
1820 DEBUG_STATEMENT (nfailure_points_popped++); \
1821 } /* POP_FAILURE_POINT */
1823 /* Structure for per-register (a.k.a. per-group) information.
1824 Other register information, such as the
1825 starting and ending positions (which are addresses), and the list of
1826 inner groups (which is a bits list) are maintained in separate
1829 We are making a (strictly speaking) nonportable assumption here: that
1830 the compiler will pack our bit fields into something that fits into
1831 the type of `word', i.e., is something that fits into one item on the
1835 /* Declarations and macros for re_match_2. */
1839 PREFIX(fail_stack_elt_t) word;
1842 /* This field is one if this group can match the empty string,
1843 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1844 # define MATCH_NULL_UNSET_VALUE 3
1845 unsigned match_null_string_p : 2;
1846 unsigned is_active : 1;
1847 unsigned matched_something : 1;
1848 unsigned ever_matched_something : 1;
1850 } PREFIX(register_info_type);
1852 # ifndef DEFINED_ONCE
1853 # define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1854 # define IS_ACTIVE(R) ((R).bits.is_active)
1855 # define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1856 # define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1859 /* Call this when have matched a real character; it sets `matched' flags
1860 for the subexpressions which we are currently inside. Also records
1861 that those subexprs have matched. */
1862 # define SET_REGS_MATCHED() \
1865 if (!set_regs_matched_done) \
1868 set_regs_matched_done = 1; \
1869 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1871 MATCHED_SOMETHING (reg_info[r]) \
1872 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1878 # endif /* not DEFINED_ONCE */
1880 /* Registers are set to a sentinel when they haven't yet matched. */
1881 static CHAR_T PREFIX(reg_unset_dummy);
1882 # define REG_UNSET_VALUE (&PREFIX(reg_unset_dummy))
1883 # define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1885 /* Subroutine declarations and macros for regex_compile. */
1886 static void PREFIX(store_op1) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc, int arg));
1887 static void PREFIX(store_op2) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1888 int arg1, int arg2));
1889 static void PREFIX(insert_op1) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1890 int arg, UCHAR_T *end));
1891 static void PREFIX(insert_op2) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1892 int arg1, int arg2, UCHAR_T *end));
1893 static boolean PREFIX(at_begline_loc_p) _RE_ARGS ((const CHAR_T *pattern,
1895 reg_syntax_t syntax));
1896 static boolean PREFIX(at_endline_loc_p) _RE_ARGS ((const CHAR_T *p,
1898 reg_syntax_t syntax));
1900 static reg_errcode_t wcs_compile_range _RE_ARGS ((CHAR_T range_start,
1901 const CHAR_T **p_ptr,
1904 reg_syntax_t syntax,
1907 static void insert_space _RE_ARGS ((int num, CHAR_T *loc, CHAR_T *end));
1909 static reg_errcode_t byte_compile_range _RE_ARGS ((unsigned int range_start,
1913 reg_syntax_t syntax,
1917 /* Fetch the next character in the uncompiled pattern---translating it
1918 if necessary. Also cast from a signed character in the constant
1919 string passed to us by the user to an unsigned char that we can use
1920 as an array index (in, e.g., `translate'). */
1921 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1922 because it is impossible to allocate 4GB array for some encodings
1923 which have 4 byte character_set like UCS4. */
1926 # define PATFETCH(c) \
1927 do {if (p == pend) return REG_EEND; \
1928 c = (UCHAR_T) *p++; \
1929 if (translate && (c <= 0xff)) c = (UCHAR_T) translate[c]; \
1932 # define PATFETCH(c) \
1933 do {if (p == pend) return REG_EEND; \
1934 c = (unsigned char) *p++; \
1935 if (translate) c = (unsigned char) translate[c]; \
1940 /* Fetch the next character in the uncompiled pattern, with no
1942 # define PATFETCH_RAW(c) \
1943 do {if (p == pend) return REG_EEND; \
1944 c = (UCHAR_T) *p++; \
1947 /* Go backwards one character in the pattern. */
1948 # define PATUNFETCH p--
1951 /* If `translate' is non-null, return translate[D], else just D. We
1952 cast the subscript to translate because some data is declared as
1953 `char *', to avoid warnings when a string constant is passed. But
1954 when we use a character as a subscript we must make it unsigned. */
1955 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1956 because it is impossible to allocate 4GB array for some encodings
1957 which have 4 byte character_set like UCS4. */
1961 # define TRANSLATE(d) \
1962 ((translate && ((UCHAR_T) (d)) <= 0xff) \
1963 ? (char) translate[(unsigned char) (d)] : (d))
1965 # define TRANSLATE(d) \
1966 (translate ? (char) translate[(unsigned char) (d)] : (d))
1971 /* Macros for outputting the compiled pattern into `buffer'. */
1973 /* If the buffer isn't allocated when it comes in, use this. */
1974 # define INIT_BUF_SIZE (32 * sizeof(UCHAR_T))
1976 /* Make sure we have at least N more bytes of space in buffer. */
1978 # define GET_BUFFER_SPACE(n) \
1979 while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR \
1980 + (n)*sizeof(CHAR_T)) > bufp->allocated) \
1983 # define GET_BUFFER_SPACE(n) \
1984 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1988 /* Make sure we have one more byte of buffer space and then add C to it. */
1989 # define BUF_PUSH(c) \
1991 GET_BUFFER_SPACE (1); \
1992 *b++ = (UCHAR_T) (c); \
1996 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1997 # define BUF_PUSH_2(c1, c2) \
1999 GET_BUFFER_SPACE (2); \
2000 *b++ = (UCHAR_T) (c1); \
2001 *b++ = (UCHAR_T) (c2); \
2005 /* As with BUF_PUSH_2, except for three bytes. */
2006 # define BUF_PUSH_3(c1, c2, c3) \
2008 GET_BUFFER_SPACE (3); \
2009 *b++ = (UCHAR_T) (c1); \
2010 *b++ = (UCHAR_T) (c2); \
2011 *b++ = (UCHAR_T) (c3); \
2014 /* Store a jump with opcode OP at LOC to location TO. We store a
2015 relative address offset by the three bytes the jump itself occupies. */
2016 # define STORE_JUMP(op, loc, to) \
2017 PREFIX(store_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
2019 /* Likewise, for a two-argument jump. */
2020 # define STORE_JUMP2(op, loc, to, arg) \
2021 PREFIX(store_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
2023 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
2024 # define INSERT_JUMP(op, loc, to) \
2025 PREFIX(insert_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
2027 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
2028 # define INSERT_JUMP2(op, loc, to, arg) \
2029 PREFIX(insert_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
2032 /* This is not an arbitrary limit: the arguments which represent offsets
2033 into the pattern are two bytes long. So if 2^16 bytes turns out to
2034 be too small, many things would have to change. */
2035 /* Any other compiler which, like MSC, has allocation limit below 2^16
2036 bytes will have to use approach similar to what was done below for
2037 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
2038 reallocating to 0 bytes. Such thing is not going to work too well.
2039 You have been warned!! */
2040 # ifndef DEFINED_ONCE
2041 # if defined _MSC_VER && !defined WIN32
2042 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
2043 The REALLOC define eliminates a flurry of conversion warnings,
2044 but is not required. */
2045 # define MAX_BUF_SIZE 65500L
2046 # define REALLOC(p,s) realloc ((p), (size_t) (s))
2048 # define MAX_BUF_SIZE (1L << 16)
2049 # define REALLOC(p,s) realloc ((p), (s))
2052 /* Extend the buffer by twice its current size via realloc and
2053 reset the pointers that pointed into the old block to point to the
2054 correct places in the new one. If extending the buffer results in it
2055 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
2056 # if __BOUNDED_POINTERS__
2057 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2058 # define MOVE_BUFFER_POINTER(P) \
2059 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2060 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
2063 SET_HIGH_BOUND (b); \
2064 SET_HIGH_BOUND (begalt); \
2065 if (fixup_alt_jump) \
2066 SET_HIGH_BOUND (fixup_alt_jump); \
2068 SET_HIGH_BOUND (laststart); \
2069 if (pending_exact) \
2070 SET_HIGH_BOUND (pending_exact); \
2073 # define MOVE_BUFFER_POINTER(P) (P) += incr
2074 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
2076 # endif /* not DEFINED_ONCE */
2079 # define EXTEND_BUFFER() \
2081 UCHAR_T *old_buffer = COMPILED_BUFFER_VAR; \
2083 if (bufp->allocated + sizeof(UCHAR_T) > MAX_BUF_SIZE) \
2085 bufp->allocated <<= 1; \
2086 if (bufp->allocated > MAX_BUF_SIZE) \
2087 bufp->allocated = MAX_BUF_SIZE; \
2088 /* How many characters the new buffer can have? */ \
2089 wchar_count = bufp->allocated / sizeof(UCHAR_T); \
2090 if (wchar_count == 0) wchar_count = 1; \
2091 /* Truncate the buffer to CHAR_T align. */ \
2092 bufp->allocated = wchar_count * sizeof(UCHAR_T); \
2093 RETALLOC (COMPILED_BUFFER_VAR, wchar_count, UCHAR_T); \
2094 bufp->buffer = (char*)COMPILED_BUFFER_VAR; \
2095 if (COMPILED_BUFFER_VAR == NULL) \
2096 return REG_ESPACE; \
2097 /* If the buffer moved, move all the pointers into it. */ \
2098 if (old_buffer != COMPILED_BUFFER_VAR) \
2100 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2101 MOVE_BUFFER_POINTER (b); \
2102 MOVE_BUFFER_POINTER (begalt); \
2103 if (fixup_alt_jump) \
2104 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2106 MOVE_BUFFER_POINTER (laststart); \
2107 if (pending_exact) \
2108 MOVE_BUFFER_POINTER (pending_exact); \
2110 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2113 # define EXTEND_BUFFER() \
2115 UCHAR_T *old_buffer = COMPILED_BUFFER_VAR; \
2116 if (bufp->allocated == MAX_BUF_SIZE) \
2118 bufp->allocated <<= 1; \
2119 if (bufp->allocated > MAX_BUF_SIZE) \
2120 bufp->allocated = MAX_BUF_SIZE; \
2121 bufp->buffer = (UCHAR_T *) REALLOC (COMPILED_BUFFER_VAR, \
2123 if (COMPILED_BUFFER_VAR == NULL) \
2124 return REG_ESPACE; \
2125 /* If the buffer moved, move all the pointers into it. */ \
2126 if (old_buffer != COMPILED_BUFFER_VAR) \
2128 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2129 MOVE_BUFFER_POINTER (b); \
2130 MOVE_BUFFER_POINTER (begalt); \
2131 if (fixup_alt_jump) \
2132 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2134 MOVE_BUFFER_POINTER (laststart); \
2135 if (pending_exact) \
2136 MOVE_BUFFER_POINTER (pending_exact); \
2138 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2142 # ifndef DEFINED_ONCE
2143 /* Since we have one byte reserved for the register number argument to
2144 {start,stop}_memory, the maximum number of groups we can report
2145 things about is what fits in that byte. */
2146 # define MAX_REGNUM 255
2148 /* But patterns can have more than `MAX_REGNUM' registers. We just
2149 ignore the excess. */
2150 typedef unsigned regnum_t;
2153 /* Macros for the compile stack. */
2155 /* Since offsets can go either forwards or backwards, this type needs to
2156 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
2157 /* int may be not enough when sizeof(int) == 2. */
2158 typedef long pattern_offset_t;
2162 pattern_offset_t begalt_offset;
2163 pattern_offset_t fixup_alt_jump;
2164 pattern_offset_t inner_group_offset;
2165 pattern_offset_t laststart_offset;
2167 } compile_stack_elt_t;
2172 compile_stack_elt_t *stack;
2174 unsigned avail; /* Offset of next open position. */
2175 } compile_stack_type;
2178 # define INIT_COMPILE_STACK_SIZE 32
2180 # define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
2181 # define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
2183 /* The next available element. */
2184 # define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2186 # endif /* not DEFINED_ONCE */
2188 /* Set the bit for character C in a list. */
2189 # ifndef DEFINED_ONCE
2190 # define SET_LIST_BIT(c) \
2191 (b[((unsigned char) (c)) / BYTEWIDTH] \
2192 |= 1 << (((unsigned char) c) % BYTEWIDTH))
2193 # endif /* DEFINED_ONCE */
2195 /* Get the next unsigned number in the uncompiled pattern. */
2196 # define GET_UNSIGNED_NUMBER(num) \
2201 if (c < '0' || c > '9') \
2203 if (num <= RE_DUP_MAX) \
2207 num = num * 10 + c - '0'; \
2212 # ifndef DEFINED_ONCE
2213 # if defined _LIBC || WIDE_CHAR_SUPPORT
2214 /* The GNU C library provides support for user-defined character classes
2215 and the functions from ISO C amendement 1. */
2216 # ifdef CHARCLASS_NAME_MAX
2217 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2219 /* This shouldn't happen but some implementation might still have this
2220 problem. Use a reasonable default value. */
2221 # define CHAR_CLASS_MAX_LENGTH 256
2225 # define IS_CHAR_CLASS(string) __wctype (string)
2227 # define IS_CHAR_CLASS(string) wctype (string)
2230 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
2232 # define IS_CHAR_CLASS(string) \
2233 (STREQ (string, "alpha") || STREQ (string, "upper") \
2234 || STREQ (string, "lower") || STREQ (string, "digit") \
2235 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
2236 || STREQ (string, "space") || STREQ (string, "print") \
2237 || STREQ (string, "punct") || STREQ (string, "graph") \
2238 || STREQ (string, "cntrl") || STREQ (string, "blank"))
2240 # endif /* DEFINED_ONCE */
2242 # ifndef MATCH_MAY_ALLOCATE
2244 /* If we cannot allocate large objects within re_match_2_internal,
2245 we make the fail stack and register vectors global.
2246 The fail stack, we grow to the maximum size when a regexp
2248 The register vectors, we adjust in size each time we
2249 compile a regexp, according to the number of registers it needs. */
2251 static PREFIX(fail_stack_type) fail_stack;
2253 /* Size with which the following vectors are currently allocated.
2254 That is so we can make them bigger as needed,
2255 but never make them smaller. */
2256 # ifdef DEFINED_ONCE
2257 static int regs_allocated_size;
2259 static const char ** regstart, ** regend;
2260 static const char ** old_regstart, ** old_regend;
2261 static const char **best_regstart, **best_regend;
2262 static const char **reg_dummy;
2263 # endif /* DEFINED_ONCE */
2265 static PREFIX(register_info_type) *PREFIX(reg_info);
2266 static PREFIX(register_info_type) *PREFIX(reg_info_dummy);
2268 /* Make the register vectors big enough for NUM_REGS registers,
2269 but don't make them smaller. */
2272 PREFIX(regex_grow_registers) (num_regs)
2275 if (num_regs > regs_allocated_size)
2277 RETALLOC_IF (regstart, num_regs, const char *);
2278 RETALLOC_IF (regend, num_regs, const char *);
2279 RETALLOC_IF (old_regstart, num_regs, const char *);
2280 RETALLOC_IF (old_regend, num_regs, const char *);
2281 RETALLOC_IF (best_regstart, num_regs, const char *);
2282 RETALLOC_IF (best_regend, num_regs, const char *);
2283 RETALLOC_IF (PREFIX(reg_info), num_regs, PREFIX(register_info_type));
2284 RETALLOC_IF (reg_dummy, num_regs, const char *);
2285 RETALLOC_IF (PREFIX(reg_info_dummy), num_regs, PREFIX(register_info_type));
2287 regs_allocated_size = num_regs;
2291 # endif /* not MATCH_MAY_ALLOCATE */
2293 # ifndef DEFINED_ONCE
2294 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2297 # endif /* not DEFINED_ONCE */
2299 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2300 Returns one of error codes defined in `regex.h', or zero for success.
2302 Assumes the `allocated' (and perhaps `buffer') and `translate'
2303 fields are set in BUFP on entry.
2305 If it succeeds, results are put in BUFP (if it returns an error, the
2306 contents of BUFP are undefined):
2307 `buffer' is the compiled pattern;
2308 `syntax' is set to SYNTAX;
2309 `used' is set to the length of the compiled pattern;
2310 `fastmap_accurate' is zero;
2311 `re_nsub' is the number of subexpressions in PATTERN;
2312 `not_bol' and `not_eol' are zero;
2314 The `fastmap' and `newline_anchor' fields are neither
2315 examined nor set. */
2317 /* Return, freeing storage we allocated. */
2319 # define FREE_STACK_RETURN(value) \
2320 return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2322 # define FREE_STACK_RETURN(value) \
2323 return (free (compile_stack.stack), value)
2326 static reg_errcode_t
2327 PREFIX(regex_compile) (ARG_PREFIX(pattern), ARG_PREFIX(size), syntax, bufp)
2328 const char *ARG_PREFIX(pattern);
2329 size_t ARG_PREFIX(size);
2330 reg_syntax_t syntax;
2331 struct re_pattern_buffer *bufp;
2333 /* We fetch characters from PATTERN here. Even though PATTERN is
2334 `char *' (i.e., signed), we declare these variables as unsigned, so
2335 they can be reliably used as array indices. */
2336 register UCHAR_T c, c1;
2339 /* A temporary space to keep wchar_t pattern and compiled pattern. */
2340 CHAR_T *pattern, *COMPILED_BUFFER_VAR;
2342 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
2343 int *mbs_offset = NULL;
2344 /* It hold whether each wchar_t is binary data or not. */
2345 char *is_binary = NULL;
2346 /* A flag whether exactn is handling binary data or not. */
2347 char is_exactn_bin = FALSE;
2350 /* A random temporary spot in PATTERN. */
2353 /* Points to the end of the buffer, where we should append. */
2354 register UCHAR_T *b;
2356 /* Keeps track of unclosed groups. */
2357 compile_stack_type compile_stack;
2359 /* Points to the current (ending) position in the pattern. */
2364 const CHAR_T *p = pattern;
2365 const CHAR_T *pend = pattern + size;
2368 /* How to translate the characters in the pattern. */
2369 RE_TRANSLATE_TYPE translate = bufp->translate;
2371 /* Address of the count-byte of the most recently inserted `exactn'
2372 command. This makes it possible to tell if a new exact-match
2373 character can be added to that command or if the character requires
2374 a new `exactn' command. */
2375 UCHAR_T *pending_exact = 0;
2377 /* Address of start of the most recently finished expression.
2378 This tells, e.g., postfix * where to find the start of its
2379 operand. Reset at the beginning of groups and alternatives. */
2380 UCHAR_T *laststart = 0;
2382 /* Address of beginning of regexp, or inside of last group. */
2385 /* Address of the place where a forward jump should go to the end of
2386 the containing expression. Each alternative of an `or' -- except the
2387 last -- ends with a forward jump of this sort. */
2388 UCHAR_T *fixup_alt_jump = 0;
2390 /* Counts open-groups as they are encountered. Remembered for the
2391 matching close-group on the compile stack, so the same register
2392 number is put in the stop_memory as the start_memory. */
2393 regnum_t regnum = 0;
2396 /* Initialize the wchar_t PATTERN and offset_buffer. */
2397 p = pend = pattern = TALLOC(csize + 1, CHAR_T);
2398 mbs_offset = TALLOC(csize + 1, int);
2399 is_binary = TALLOC(csize + 1, char);
2400 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2407 pattern[csize] = L'\0'; /* sentinel */
2408 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2420 DEBUG_PRINT1 ("\nCompiling pattern: ");
2423 unsigned debug_count;
2425 for (debug_count = 0; debug_count < size; debug_count++)
2426 PUT_CHAR (pattern[debug_count]);
2431 /* Initialize the compile stack. */
2432 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2433 if (compile_stack.stack == NULL)
2443 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2444 compile_stack.avail = 0;
2446 /* Initialize the pattern buffer. */
2447 bufp->syntax = syntax;
2448 bufp->fastmap_accurate = 0;
2449 bufp->not_bol = bufp->not_eol = 0;
2451 /* Set `used' to zero, so that if we return an error, the pattern
2452 printer (for debugging) will think there's no pattern. We reset it
2456 /* Always count groups, whether or not bufp->no_sub is set. */
2459 #if !defined emacs && !defined SYNTAX_TABLE
2460 /* Initialize the syntax table. */
2461 init_syntax_once ();
2464 if (bufp->allocated == 0)
2467 { /* If zero allocated, but buffer is non-null, try to realloc
2468 enough space. This loses if buffer's address is bogus, but
2469 that is the user's responsibility. */
2471 /* Free bufp->buffer and allocate an array for wchar_t pattern
2474 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(UCHAR_T),
2477 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, UCHAR_T);
2481 { /* Caller did not allocate a buffer. Do it for them. */
2482 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(UCHAR_T),
2486 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2488 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2490 bufp->allocated = INIT_BUF_SIZE;
2494 COMPILED_BUFFER_VAR = (UCHAR_T*) bufp->buffer;
2497 begalt = b = COMPILED_BUFFER_VAR;
2499 /* Loop through the uncompiled pattern until we're at the end. */
2508 if ( /* If at start of pattern, it's an operator. */
2510 /* If context independent, it's an operator. */
2511 || syntax & RE_CONTEXT_INDEP_ANCHORS
2512 /* Otherwise, depends on what's come before. */
2513 || PREFIX(at_begline_loc_p) (pattern, p, syntax))
2523 if ( /* If at end of pattern, it's an operator. */
2525 /* If context independent, it's an operator. */
2526 || syntax & RE_CONTEXT_INDEP_ANCHORS
2527 /* Otherwise, depends on what's next. */
2528 || PREFIX(at_endline_loc_p) (p, pend, syntax))
2538 if ((syntax & RE_BK_PLUS_QM)
2539 || (syntax & RE_LIMITED_OPS))
2543 /* If there is no previous pattern... */
2546 if (syntax & RE_CONTEXT_INVALID_OPS)
2547 FREE_STACK_RETURN (REG_BADRPT);
2548 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2553 /* Are we optimizing this jump? */
2554 boolean keep_string_p = false;
2556 /* 1 means zero (many) matches is allowed. */
2557 char zero_times_ok = 0, many_times_ok = 0;
2559 /* If there is a sequence of repetition chars, collapse it
2560 down to just one (the right one). We can't combine
2561 interval operators with these because of, e.g., `a{2}*',
2562 which should only match an even number of `a's. */
2566 zero_times_ok |= c != '+';
2567 many_times_ok |= c != '?';
2575 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2578 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2580 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2583 if (!(c1 == '+' || c1 == '?'))
2598 /* If we get here, we found another repeat character. */
2601 /* Star, etc. applied to an empty pattern is equivalent
2602 to an empty pattern. */
2606 /* Now we know whether or not zero matches is allowed
2607 and also whether or not two or more matches is allowed. */
2609 { /* More than one repetition is allowed, so put in at the
2610 end a backward relative jump from `b' to before the next
2611 jump we're going to put in below (which jumps from
2612 laststart to after this jump).
2614 But if we are at the `*' in the exact sequence `.*\n',
2615 insert an unconditional jump backwards to the .,
2616 instead of the beginning of the loop. This way we only
2617 push a failure point once, instead of every time
2618 through the loop. */
2619 assert (p - 1 > pattern);
2621 /* Allocate the space for the jump. */
2622 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2624 /* We know we are not at the first character of the pattern,
2625 because laststart was nonzero. And we've already
2626 incremented `p', by the way, to be the character after
2627 the `*'. Do we have to do something analogous here
2628 for null bytes, because of RE_DOT_NOT_NULL? */
2629 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2631 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2632 && !(syntax & RE_DOT_NEWLINE))
2633 { /* We have .*\n. */
2634 STORE_JUMP (jump, b, laststart);
2635 keep_string_p = true;
2638 /* Anything else. */
2639 STORE_JUMP (maybe_pop_jump, b, laststart -
2640 (1 + OFFSET_ADDRESS_SIZE));
2642 /* We've added more stuff to the buffer. */
2643 b += 1 + OFFSET_ADDRESS_SIZE;
2646 /* On failure, jump from laststart to b + 3, which will be the
2647 end of the buffer after this jump is inserted. */
2648 /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2650 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2651 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2653 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2655 b += 1 + OFFSET_ADDRESS_SIZE;
2659 /* At least one repetition is required, so insert a
2660 `dummy_failure_jump' before the initial
2661 `on_failure_jump' instruction of the loop. This
2662 effects a skip over that instruction the first time
2663 we hit that loop. */
2664 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2665 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2666 2 + 2 * OFFSET_ADDRESS_SIZE);
2667 b += 1 + OFFSET_ADDRESS_SIZE;
2681 boolean had_char_class = false;
2683 CHAR_T range_start = 0xffffffff;
2685 unsigned int range_start = 0xffffffff;
2687 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2690 /* We assume a charset(_not) structure as a wchar_t array.
2691 charset[0] = (re_opcode_t) charset(_not)
2692 charset[1] = l (= length of char_classes)
2693 charset[2] = m (= length of collating_symbols)
2694 charset[3] = n (= length of equivalence_classes)
2695 charset[4] = o (= length of char_ranges)
2696 charset[5] = p (= length of chars)
2698 charset[6] = char_class (wctype_t)
2699 charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2701 charset[l+5] = char_class (wctype_t)
2703 charset[l+6] = collating_symbol (wchar_t)
2705 charset[l+m+5] = collating_symbol (wchar_t)
2706 ifdef _LIBC we use the index if
2707 _NL_COLLATE_SYMB_EXTRAMB instead of
2710 charset[l+m+6] = equivalence_classes (wchar_t)
2712 charset[l+m+n+5] = equivalence_classes (wchar_t)
2713 ifdef _LIBC we use the index in
2714 _NL_COLLATE_WEIGHT instead of
2717 charset[l+m+n+6] = range_start
2718 charset[l+m+n+7] = range_end
2720 charset[l+m+n+2o+4] = range_start
2721 charset[l+m+n+2o+5] = range_end
2722 ifdef _LIBC we use the value looked up
2723 in _NL_COLLATE_COLLSEQ instead of
2726 charset[l+m+n+2o+6] = char
2728 charset[l+m+n+2o+p+5] = char
2732 /* We need at least 6 spaces: the opcode, the length of
2733 char_classes, the length of collating_symbols, the length of
2734 equivalence_classes, the length of char_ranges, the length of
2736 GET_BUFFER_SPACE (6);
2738 /* Save b as laststart. And We use laststart as the pointer
2739 to the first element of the charset here.
2740 In other words, laststart[i] indicates charset[i]. */
2743 /* We test `*p == '^' twice, instead of using an if
2744 statement, so we only need one BUF_PUSH. */
2745 BUF_PUSH (*p == '^' ? charset_not : charset);
2749 /* Push the length of char_classes, the length of
2750 collating_symbols, the length of equivalence_classes, the
2751 length of char_ranges and the length of chars. */
2752 BUF_PUSH_3 (0, 0, 0);
2755 /* Remember the first position in the bracket expression. */
2758 /* charset_not matches newline according to a syntax bit. */
2759 if ((re_opcode_t) b[-6] == charset_not
2760 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2763 laststart[5]++; /* Update the length of characters */
2766 /* Read in characters and ranges, setting map bits. */
2769 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2773 /* \ might escape characters inside [...] and [^...]. */
2774 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2776 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2780 laststart[5]++; /* Update the length of chars */
2785 /* Could be the end of the bracket expression. If it's
2786 not (i.e., when the bracket expression is `[]' so
2787 far), the ']' character bit gets set way below. */
2788 if (c == ']' && p != p1 + 1)
2791 /* Look ahead to see if it's a range when the last thing
2792 was a character class. */
2793 if (had_char_class && c == '-' && *p != ']')
2794 FREE_STACK_RETURN (REG_ERANGE);
2796 /* Look ahead to see if it's a range when the last thing
2797 was a character: if this is a hyphen not at the
2798 beginning or the end of a list, then it's the range
2801 && !(p - 2 >= pattern && p[-2] == '[')
2802 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2806 /* Allocate the space for range_start and range_end. */
2807 GET_BUFFER_SPACE (2);
2808 /* Update the pointer to indicate end of buffer. */
2810 ret = wcs_compile_range (range_start, &p, pend, translate,
2811 syntax, b, laststart);
2812 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2813 range_start = 0xffffffff;
2815 else if (p[0] == '-' && p[1] != ']')
2816 { /* This handles ranges made up of characters only. */
2819 /* Move past the `-'. */
2821 /* Allocate the space for range_start and range_end. */
2822 GET_BUFFER_SPACE (2);
2823 /* Update the pointer to indicate end of buffer. */
2825 ret = wcs_compile_range (c, &p, pend, translate, syntax, b,
2827 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2828 range_start = 0xffffffff;
2831 /* See if we're at the beginning of a possible character
2833 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2834 { /* Leave room for the null. */
2835 char str[CHAR_CLASS_MAX_LENGTH + 1];
2840 /* If pattern is `[[:'. */
2841 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2846 if ((c == ':' && *p == ']') || p == pend)
2848 if (c1 < CHAR_CLASS_MAX_LENGTH)
2851 /* This is in any case an invalid class name. */
2856 /* If isn't a word bracketed by `[:' and `:]':
2857 undo the ending character, the letters, and leave
2858 the leading `:' and `[' (but store them as character). */
2859 if (c == ':' && *p == ']')
2864 /* Query the character class as wctype_t. */
2865 wt = IS_CHAR_CLASS (str);
2867 FREE_STACK_RETURN (REG_ECTYPE);
2869 /* Throw away the ] at the end of the character
2873 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2875 /* Allocate the space for character class. */
2876 GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2877 /* Update the pointer to indicate end of buffer. */
2878 b += CHAR_CLASS_SIZE;
2879 /* Move data which follow character classes
2880 not to violate the data. */
2881 insert_space(CHAR_CLASS_SIZE,
2882 laststart + 6 + laststart[1],
2884 alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2885 + __alignof__(wctype_t) - 1)
2886 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2887 /* Store the character class. */
2888 *((wctype_t*)alignedp) = wt;
2889 /* Update length of char_classes */
2890 laststart[1] += CHAR_CLASS_SIZE;
2892 had_char_class = true;
2901 laststart[5] += 2; /* Update the length of characters */
2903 had_char_class = false;
2906 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2909 CHAR_T str[128]; /* Should be large enough. */
2910 CHAR_T delim = *p; /* '=' or '.' */
2913 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2918 /* If pattern is `[[=' or '[[.'. */
2919 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2924 if ((c == delim && *p == ']') || p == pend)
2926 if (c1 < sizeof (str) - 1)
2929 /* This is in any case an invalid class name. */
2934 if (c == delim && *p == ']' && str[0] != '\0')
2936 unsigned int i, offset;
2937 /* If we have no collation data we use the default
2938 collation in which each character is in a class
2939 by itself. It also means that ASCII is the
2940 character set and therefore we cannot have character
2941 with more than one byte in the multibyte
2944 /* If not defined _LIBC, we push the name and
2945 `\0' for the sake of matching performance. */
2946 int datasize = c1 + 1;
2954 FREE_STACK_RETURN (REG_ECOLLATE);
2959 const int32_t *table;
2960 const int32_t *weights;
2961 const int32_t *extra;
2962 const int32_t *indirect;
2965 /* This #include defines a local function! */
2966 # include <locale/weightwc.h>
2970 /* We push the index for equivalence class. */
2973 table = (const int32_t *)
2974 _NL_CURRENT (LC_COLLATE,
2975 _NL_COLLATE_TABLEWC);
2976 weights = (const int32_t *)
2977 _NL_CURRENT (LC_COLLATE,
2978 _NL_COLLATE_WEIGHTWC);
2979 extra = (const int32_t *)
2980 _NL_CURRENT (LC_COLLATE,
2981 _NL_COLLATE_EXTRAWC);
2982 indirect = (const int32_t *)
2983 _NL_CURRENT (LC_COLLATE,
2984 _NL_COLLATE_INDIRECTWC);
2986 idx = findidx ((const wint_t**)&cp);
2987 if (idx == 0 || cp < (wint_t*) str + c1)
2988 /* This is no valid character. */
2989 FREE_STACK_RETURN (REG_ECOLLATE);
2991 str[0] = (wchar_t)idx;
2993 else /* delim == '.' */
2995 /* We push collation sequence value
2996 for collating symbol. */
2998 const int32_t *symb_table;
2999 const unsigned char *extra;
3006 /* We have to convert the name to a single-byte
3007 string. This is possible since the names
3008 consist of ASCII characters and the internal
3009 representation is UCS4. */
3010 for (i = 0; i < c1; ++i)
3011 char_str[i] = str[i];
3014 _NL_CURRENT_WORD (LC_COLLATE,
3015 _NL_COLLATE_SYMB_HASH_SIZEMB);
3016 symb_table = (const int32_t *)
3017 _NL_CURRENT (LC_COLLATE,
3018 _NL_COLLATE_SYMB_TABLEMB);
3019 extra = (const unsigned char *)
3020 _NL_CURRENT (LC_COLLATE,
3021 _NL_COLLATE_SYMB_EXTRAMB);
3023 /* Locate the character in the hashing table. */
3024 hash = elem_hash (char_str, c1);
3027 elem = hash % table_size;
3028 second = hash % (table_size - 2);
3029 while (symb_table[2 * elem] != 0)
3031 /* First compare the hashing value. */
3032 if (symb_table[2 * elem] == hash
3033 && c1 == extra[symb_table[2 * elem + 1]]
3035 &extra[symb_table[2 * elem + 1]
3038 /* Yep, this is the entry. */
3039 idx = symb_table[2 * elem + 1];
3040 idx += 1 + extra[idx];
3048 if (symb_table[2 * elem] != 0)
3050 /* Compute the index of the byte sequence
3052 idx += 1 + extra[idx];
3053 /* Adjust for the alignment. */
3054 idx = (idx + 3) & ~4;
3056 str[0] = (wchar_t) idx + 4;
3058 else if (symb_table[2 * elem] == 0 && c1 == 1)
3060 /* No valid character. Match it as a
3061 single byte character. */
3062 had_char_class = false;
3064 /* Update the length of characters */
3066 range_start = str[0];
3068 /* Throw away the ] at the end of the
3069 collating symbol. */
3071 /* exit from the switch block. */
3075 FREE_STACK_RETURN (REG_ECOLLATE);
3080 /* Throw away the ] at the end of the equivalence
3081 class (or collating symbol). */
3084 /* Allocate the space for the equivalence class
3085 (or collating symbol) (and '\0' if needed). */
3086 GET_BUFFER_SPACE(datasize);
3087 /* Update the pointer to indicate end of buffer. */
3091 { /* equivalence class */
3092 /* Calculate the offset of char_ranges,
3093 which is next to equivalence_classes. */
3094 offset = laststart[1] + laststart[2]
3097 insert_space(datasize, laststart + offset, b - 1);
3099 /* Write the equivalence_class and \0. */
3100 for (i = 0 ; i < datasize ; i++)
3101 laststart[offset + i] = str[i];
3103 /* Update the length of equivalence_classes. */
3104 laststart[3] += datasize;
3105 had_char_class = true;
3107 else /* delim == '.' */
3108 { /* collating symbol */
3109 /* Calculate the offset of the equivalence_classes,
3110 which is next to collating_symbols. */
3111 offset = laststart[1] + laststart[2] + 6;
3112 /* Insert space and write the collationg_symbol
3114 insert_space(datasize, laststart + offset, b-1);
3115 for (i = 0 ; i < datasize ; i++)
3116 laststart[offset + i] = str[i];
3118 /* In re_match_2_internal if range_start < -1, we
3119 assume -range_start is the offset of the
3120 collating symbol which is specified as
3121 the character of the range start. So we assign
3122 -(laststart[1] + laststart[2] + 6) to
3124 range_start = -(laststart[1] + laststart[2] + 6);
3125 /* Update the length of collating_symbol. */
3126 laststart[2] += datasize;
3127 had_char_class = false;
3137 laststart[5] += 2; /* Update the length of characters */
3138 range_start = delim;
3139 had_char_class = false;
3144 had_char_class = false;
3146 laststart[5]++; /* Update the length of characters */
3152 /* Ensure that we have enough space to push a charset: the
3153 opcode, the length count, and the bitset; 34 bytes in all. */
3154 GET_BUFFER_SPACE (34);
3158 /* We test `*p == '^' twice, instead of using an if
3159 statement, so we only need one BUF_PUSH. */
3160 BUF_PUSH (*p == '^' ? charset_not : charset);
3164 /* Remember the first position in the bracket expression. */
3167 /* Push the number of bytes in the bitmap. */
3168 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3170 /* Clear the whole map. */
3171 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3173 /* charset_not matches newline according to a syntax bit. */
3174 if ((re_opcode_t) b[-2] == charset_not
3175 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3176 SET_LIST_BIT ('\n');
3178 /* Read in characters and ranges, setting map bits. */
3181 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3185 /* \ might escape characters inside [...] and [^...]. */
3186 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3188 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3196 /* Could be the end of the bracket expression. If it's
3197 not (i.e., when the bracket expression is `[]' so
3198 far), the ']' character bit gets set way below. */
3199 if (c == ']' && p != p1 + 1)
3202 /* Look ahead to see if it's a range when the last thing
3203 was a character class. */
3204 if (had_char_class && c == '-' && *p != ']')
3205 FREE_STACK_RETURN (REG_ERANGE);
3207 /* Look ahead to see if it's a range when the last thing
3208 was a character: if this is a hyphen not at the
3209 beginning or the end of a list, then it's the range
3212 && !(p - 2 >= pattern && p[-2] == '[')
3213 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3217 = byte_compile_range (range_start, &p, pend, translate,
3219 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3220 range_start = 0xffffffff;
3223 else if (p[0] == '-' && p[1] != ']')
3224 { /* This handles ranges made up of characters only. */
3227 /* Move past the `-'. */
3230 ret = byte_compile_range (c, &p, pend, translate, syntax, b);
3231 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3232 range_start = 0xffffffff;
3235 /* See if we're at the beginning of a possible character
3238 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3239 { /* Leave room for the null. */
3240 char str[CHAR_CLASS_MAX_LENGTH + 1];
3245 /* If pattern is `[[:'. */
3246 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3251 if ((c == ':' && *p == ']') || p == pend)
3253 if (c1 < CHAR_CLASS_MAX_LENGTH)
3256 /* This is in any case an invalid class name. */
3261 /* If isn't a word bracketed by `[:' and `:]':
3262 undo the ending character, the letters, and leave
3263 the leading `:' and `[' (but set bits for them). */
3264 if (c == ':' && *p == ']')
3266 # if defined _LIBC || WIDE_CHAR_SUPPORT
3267 boolean is_lower = STREQ (str, "lower");
3268 boolean is_upper = STREQ (str, "upper");
3272 wt = IS_CHAR_CLASS (str);
3274 FREE_STACK_RETURN (REG_ECTYPE);
3276 /* Throw away the ] at the end of the character
3280 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3282 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3285 if (__iswctype (__btowc (ch), wt))
3288 if (iswctype (btowc (ch), wt))
3292 if (translate && (is_upper || is_lower)
3293 && (ISUPPER (ch) || ISLOWER (ch)))
3297 had_char_class = true;
3300 boolean is_alnum = STREQ (str, "alnum");
3301 boolean is_alpha = STREQ (str, "alpha");
3302 boolean is_blank = STREQ (str, "blank");
3303 boolean is_cntrl = STREQ (str, "cntrl");
3304 boolean is_digit = STREQ (str, "digit");
3305 boolean is_graph = STREQ (str, "graph");
3306 boolean is_lower = STREQ (str, "lower");
3307 boolean is_print = STREQ (str, "print");
3308 boolean is_punct = STREQ (str, "punct");
3309 boolean is_space = STREQ (str, "space");
3310 boolean is_upper = STREQ (str, "upper");
3311 boolean is_xdigit = STREQ (str, "xdigit");
3313 if (!IS_CHAR_CLASS (str))
3314 FREE_STACK_RETURN (REG_ECTYPE);
3316 /* Throw away the ] at the end of the character
3320 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3322 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3324 /* This was split into 3 if's to
3325 avoid an arbitrary limit in some compiler. */
3326 if ( (is_alnum && ISALNUM (ch))
3327 || (is_alpha && ISALPHA (ch))
3328 || (is_blank && ISBLANK (ch))
3329 || (is_cntrl && ISCNTRL (ch)))
3331 if ( (is_digit && ISDIGIT (ch))
3332 || (is_graph && ISGRAPH (ch))
3333 || (is_lower && ISLOWER (ch))
3334 || (is_print && ISPRINT (ch)))
3336 if ( (is_punct && ISPUNCT (ch))
3337 || (is_space && ISSPACE (ch))
3338 || (is_upper && ISUPPER (ch))
3339 || (is_xdigit && ISXDIGIT (ch)))
3341 if ( translate && (is_upper || is_lower)
3342 && (ISUPPER (ch) || ISLOWER (ch)))
3345 had_char_class = true;
3346 # endif /* libc || wctype.h */
3356 had_char_class = false;
3359 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3361 unsigned char str[MB_LEN_MAX + 1];
3364 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3370 /* If pattern is `[[='. */
3371 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3376 if ((c == '=' && *p == ']') || p == pend)
3378 if (c1 < MB_LEN_MAX)
3381 /* This is in any case an invalid class name. */
3386 if (c == '=' && *p == ']' && str[0] != '\0')
3388 /* If we have no collation data we use the default
3389 collation in which each character is in a class
3390 by itself. It also means that ASCII is the
3391 character set and therefore we cannot have character
3392 with more than one byte in the multibyte
3399 FREE_STACK_RETURN (REG_ECOLLATE);
3401 /* Throw away the ] at the end of the equivalence
3405 /* Set the bit for the character. */
3406 SET_LIST_BIT (str[0]);
3411 /* Try to match the byte sequence in `str' against
3412 those known to the collate implementation.
3413 First find out whether the bytes in `str' are
3414 actually from exactly one character. */
3415 const int32_t *table;
3416 const unsigned char *weights;
3417 const unsigned char *extra;
3418 const int32_t *indirect;
3420 const unsigned char *cp = str;
3423 /* This #include defines a local function! */
3424 # include <locale/weight.h>
3426 table = (const int32_t *)
3427 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3428 weights = (const unsigned char *)
3429 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3430 extra = (const unsigned char *)
3431 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3432 indirect = (const int32_t *)
3433 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3435 idx = findidx (&cp);
3436 if (idx == 0 || cp < str + c1)
3437 /* This is no valid character. */
3438 FREE_STACK_RETURN (REG_ECOLLATE);
3440 /* Throw away the ] at the end of the equivalence
3444 /* Now we have to go throught the whole table
3445 and find all characters which have the same
3448 XXX Note that this is not entirely correct.
3449 we would have to match multibyte sequences
3450 but this is not possible with the current
3452 for (ch = 1; ch < 256; ++ch)
3453 /* XXX This test would have to be changed if we
3454 would allow matching multibyte sequences. */
3457 int32_t idx2 = table[ch];
3458 size_t len = weights[idx2];
3460 /* Test whether the lenghts match. */
3461 if (weights[idx] == len)
3463 /* They do. New compare the bytes of
3468 && (weights[idx + 1 + cnt]
3469 == weights[idx2 + 1 + cnt]))
3473 /* They match. Mark the character as
3480 had_char_class = true;
3490 had_char_class = false;
3493 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3495 unsigned char str[128]; /* Should be large enough. */
3498 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3504 /* If pattern is `[[.'. */
3505 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3510 if ((c == '.' && *p == ']') || p == pend)
3512 if (c1 < sizeof (str))
3515 /* This is in any case an invalid class name. */
3520 if (c == '.' && *p == ']' && str[0] != '\0')
3522 /* If we have no collation data we use the default
3523 collation in which each character is the name
3524 for its own class which contains only the one
3525 character. It also means that ASCII is the
3526 character set and therefore we cannot have character
3527 with more than one byte in the multibyte
3534 FREE_STACK_RETURN (REG_ECOLLATE);
3536 /* Throw away the ] at the end of the equivalence
3540 /* Set the bit for the character. */
3541 SET_LIST_BIT (str[0]);
3542 range_start = ((const unsigned char *) str)[0];
3547 /* Try to match the byte sequence in `str' against
3548 those known to the collate implementation.
3549 First find out whether the bytes in `str' are
3550 actually from exactly one character. */
3552 const int32_t *symb_table;
3553 const unsigned char *extra;
3560 _NL_CURRENT_WORD (LC_COLLATE,
3561 _NL_COLLATE_SYMB_HASH_SIZEMB);
3562 symb_table = (const int32_t *)
3563 _NL_CURRENT (LC_COLLATE,
3564 _NL_COLLATE_SYMB_TABLEMB);
3565 extra = (const unsigned char *)
3566 _NL_CURRENT (LC_COLLATE,
3567 _NL_COLLATE_SYMB_EXTRAMB);
3569 /* Locate the character in the hashing table. */
3570 hash = elem_hash (str, c1);
3573 elem = hash % table_size;
3574 second = hash % (table_size - 2);
3575 while (symb_table[2 * elem] != 0)
3577 /* First compare the hashing value. */
3578 if (symb_table[2 * elem] == hash
3579 && c1 == extra[symb_table[2 * elem + 1]]
3581 &extra[symb_table[2 * elem + 1]
3585 /* Yep, this is the entry. */
3586 idx = symb_table[2 * elem + 1];
3587 idx += 1 + extra[idx];
3595 if (symb_table[2 * elem] == 0)
3596 /* This is no valid character. */
3597 FREE_STACK_RETURN (REG_ECOLLATE);
3599 /* Throw away the ] at the end of the equivalence
3603 /* Now add the multibyte character(s) we found
3606 XXX Note that this is not entirely correct.
3607 we would have to match multibyte sequences
3608 but this is not possible with the current
3609 implementation. Also, we have to match
3610 collating symbols, which expand to more than
3611 one file, as a whole and not allow the
3612 individual bytes. */
3615 range_start = extra[idx];
3618 SET_LIST_BIT (extra[idx]);
3623 had_char_class = false;
3633 had_char_class = false;
3638 had_char_class = false;
3644 /* Discard any (non)matching list bytes that are all 0 at the
3645 end of the map. Decrease the map-length byte too. */
3646 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3655 if (syntax & RE_NO_BK_PARENS)
3662 if (syntax & RE_NO_BK_PARENS)
3669 if (syntax & RE_NEWLINE_ALT)
3676 if (syntax & RE_NO_BK_VBAR)
3683 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3684 goto handle_interval;
3690 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3692 /* Do not translate the character after the \, so that we can
3693 distinguish, e.g., \B from \b, even if we normally would
3694 translate, e.g., B to b. */
3700 if (syntax & RE_NO_BK_PARENS)
3701 goto normal_backslash;
3707 if (COMPILE_STACK_FULL)
3709 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3710 compile_stack_elt_t);
3711 if (compile_stack.stack == NULL) return REG_ESPACE;
3713 compile_stack.size <<= 1;
3716 /* These are the values to restore when we hit end of this
3717 group. They are all relative offsets, so that if the
3718 whole pattern moves because of realloc, they will still
3720 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3721 COMPILE_STACK_TOP.fixup_alt_jump
3722 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3723 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3724 COMPILE_STACK_TOP.regnum = regnum;
3726 /* We will eventually replace the 0 with the number of
3727 groups inner to this one. But do not push a
3728 start_memory for groups beyond the last one we can
3729 represent in the compiled pattern. */
3730 if (regnum <= MAX_REGNUM)
3732 COMPILE_STACK_TOP.inner_group_offset = b
3733 - COMPILED_BUFFER_VAR + 2;
3734 BUF_PUSH_3 (start_memory, regnum, 0);
3737 compile_stack.avail++;
3742 /* If we've reached MAX_REGNUM groups, then this open
3743 won't actually generate any code, so we'll have to
3744 clear pending_exact explicitly. */
3750 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3752 if (COMPILE_STACK_EMPTY)
3754 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3755 goto normal_backslash;
3757 FREE_STACK_RETURN (REG_ERPAREN);
3762 { /* Push a dummy failure point at the end of the
3763 alternative for a possible future
3764 `pop_failure_jump' to pop. See comments at
3765 `push_dummy_failure' in `re_match_2'. */
3766 BUF_PUSH (push_dummy_failure);
3768 /* We allocated space for this jump when we assigned
3769 to `fixup_alt_jump', in the `handle_alt' case below. */
3770 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3773 /* See similar code for backslashed left paren above. */
3774 if (COMPILE_STACK_EMPTY)
3776 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3779 FREE_STACK_RETURN (REG_ERPAREN);
3782 /* Since we just checked for an empty stack above, this
3783 ``can't happen''. */
3784 assert (compile_stack.avail != 0);
3786 /* We don't just want to restore into `regnum', because
3787 later groups should continue to be numbered higher,
3788 as in `(ab)c(de)' -- the second group is #2. */
3789 regnum_t this_group_regnum;
3791 compile_stack.avail--;
3792 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3794 = COMPILE_STACK_TOP.fixup_alt_jump
3795 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3797 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3798 this_group_regnum = COMPILE_STACK_TOP.regnum;
3799 /* If we've reached MAX_REGNUM groups, then this open
3800 won't actually generate any code, so we'll have to
3801 clear pending_exact explicitly. */
3804 /* We're at the end of the group, so now we know how many
3805 groups were inside this one. */
3806 if (this_group_regnum <= MAX_REGNUM)
3808 UCHAR_T *inner_group_loc
3809 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3811 *inner_group_loc = regnum - this_group_regnum;
3812 BUF_PUSH_3 (stop_memory, this_group_regnum,
3813 regnum - this_group_regnum);
3819 case '|': /* `\|'. */
3820 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3821 goto normal_backslash;
3823 if (syntax & RE_LIMITED_OPS)
3826 /* Insert before the previous alternative a jump which
3827 jumps to this alternative if the former fails. */
3828 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3829 INSERT_JUMP (on_failure_jump, begalt,
3830 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3832 b += 1 + OFFSET_ADDRESS_SIZE;
3834 /* The alternative before this one has a jump after it
3835 which gets executed if it gets matched. Adjust that
3836 jump so it will jump to this alternative's analogous
3837 jump (put in below, which in turn will jump to the next
3838 (if any) alternative's such jump, etc.). The last such
3839 jump jumps to the correct final destination. A picture:
3845 If we are at `b', then fixup_alt_jump right now points to a
3846 three-byte space after `a'. We'll put in the jump, set
3847 fixup_alt_jump to right after `b', and leave behind three
3848 bytes which we'll fill in when we get to after `c'. */
3851 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3853 /* Mark and leave space for a jump after this alternative,
3854 to be filled in later either by next alternative or
3855 when know we're at the end of a series of alternatives. */
3857 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3858 b += 1 + OFFSET_ADDRESS_SIZE;
3866 /* If \{ is a literal. */
3867 if (!(syntax & RE_INTERVALS)
3868 /* If we're at `\{' and it's not the open-interval
3870 || (syntax & RE_NO_BK_BRACES))
3871 goto normal_backslash;
3875 /* If got here, then the syntax allows intervals. */
3877 /* At least (most) this many matches must be made. */
3878 int lower_bound = -1, upper_bound = -1;
3880 /* Place in the uncompiled pattern (i.e., just after
3881 the '{') to go back to if the interval is invalid. */
3882 const CHAR_T *beg_interval = p;
3885 goto invalid_interval;
3887 GET_UNSIGNED_NUMBER (lower_bound);
3891 GET_UNSIGNED_NUMBER (upper_bound);
3892 if (upper_bound < 0)
3893 upper_bound = RE_DUP_MAX;
3896 /* Interval such as `{1}' => match exactly once. */
3897 upper_bound = lower_bound;
3899 if (! (0 <= lower_bound && lower_bound <= upper_bound))
3900 goto invalid_interval;
3902 if (!(syntax & RE_NO_BK_BRACES))
3904 if (c != '\\' || p == pend)
3905 goto invalid_interval;
3910 goto invalid_interval;
3912 /* If it's invalid to have no preceding re. */
3915 if (syntax & RE_CONTEXT_INVALID_OPS
3916 && !(syntax & RE_INVALID_INTERVAL_ORD))
3917 FREE_STACK_RETURN (REG_BADRPT);
3918 else if (syntax & RE_CONTEXT_INDEP_OPS)
3921 goto unfetch_interval;
3924 /* We just parsed a valid interval. */
3926 if (RE_DUP_MAX < upper_bound)
3927 FREE_STACK_RETURN (REG_BADBR);
3929 /* If the upper bound is zero, don't want to succeed at
3930 all; jump from `laststart' to `b + 3', which will be
3931 the end of the buffer after we insert the jump. */
3932 /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE'
3933 instead of 'b + 3'. */
3934 if (upper_bound == 0)
3936 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3937 INSERT_JUMP (jump, laststart, b + 1
3938 + OFFSET_ADDRESS_SIZE);
3939 b += 1 + OFFSET_ADDRESS_SIZE;
3942 /* Otherwise, we have a nontrivial interval. When
3943 we're all done, the pattern will look like:
3944 set_number_at <jump count> <upper bound>
3945 set_number_at <succeed_n count> <lower bound>
3946 succeed_n <after jump addr> <succeed_n count>
3948 jump_n <succeed_n addr> <jump count>
3949 (The upper bound and `jump_n' are omitted if
3950 `upper_bound' is 1, though.) */
3952 { /* If the upper bound is > 1, we need to insert
3953 more at the end of the loop. */
3954 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3955 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3957 GET_BUFFER_SPACE (nbytes);
3959 /* Initialize lower bound of the `succeed_n', even
3960 though it will be set during matching by its
3961 attendant `set_number_at' (inserted next),
3962 because `re_compile_fastmap' needs to know.
3963 Jump to the `jump_n' we might insert below. */
3964 INSERT_JUMP2 (succeed_n, laststart,
3965 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3966 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3968 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3970 /* Code to initialize the lower bound. Insert
3971 before the `succeed_n'. The `5' is the last two
3972 bytes of this `set_number_at', plus 3 bytes of
3973 the following `succeed_n'. */
3974 /* ifdef WCHAR, The '1+2*OFFSET_ADDRESS_SIZE'
3975 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3976 of the following `succeed_n'. */
3977 PREFIX(insert_op2) (set_number_at, laststart, 1
3978 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3979 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3981 if (upper_bound > 1)
3982 { /* More than one repetition is allowed, so
3983 append a backward jump to the `succeed_n'
3984 that starts this interval.
3986 When we've reached this during matching,
3987 we'll have matched the interval once, so
3988 jump back only `upper_bound - 1' times. */
3989 STORE_JUMP2 (jump_n, b, laststart
3990 + 2 * OFFSET_ADDRESS_SIZE + 1,
3992 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3994 /* The location we want to set is the second
3995 parameter of the `jump_n'; that is `b-2' as
3996 an absolute address. `laststart' will be
3997 the `set_number_at' we're about to insert;
3998 `laststart+3' the number to set, the source
3999 for the relative address. But we are
4000 inserting into the middle of the pattern --
4001 so everything is getting moved up by 5.
4002 Conclusion: (b - 2) - (laststart + 3) + 5,
4003 i.e., b - laststart.
4005 We insert this at the beginning of the loop
4006 so that if we fail during matching, we'll
4007 reinitialize the bounds. */
4008 PREFIX(insert_op2) (set_number_at, laststart,
4010 upper_bound - 1, b);
4011 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
4018 if (!(syntax & RE_INVALID_INTERVAL_ORD))
4019 FREE_STACK_RETURN (p == pend ? REG_EBRACE : REG_BADBR);
4021 /* Match the characters as literals. */
4024 if (syntax & RE_NO_BK_BRACES)
4027 goto normal_backslash;
4031 /* There is no way to specify the before_dot and after_dot
4032 operators. rms says this is ok. --karl */
4040 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
4046 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
4052 if (syntax & RE_NO_GNU_OPS)
4055 BUF_PUSH (wordchar);
4060 if (syntax & RE_NO_GNU_OPS)
4063 BUF_PUSH (notwordchar);
4068 if (syntax & RE_NO_GNU_OPS)
4074 if (syntax & RE_NO_GNU_OPS)
4080 if (syntax & RE_NO_GNU_OPS)
4082 BUF_PUSH (wordbound);
4086 if (syntax & RE_NO_GNU_OPS)
4088 BUF_PUSH (notwordbound);
4092 if (syntax & RE_NO_GNU_OPS)
4098 if (syntax & RE_NO_GNU_OPS)
4103 case '1': case '2': case '3': case '4': case '5':
4104 case '6': case '7': case '8': case '9':
4105 if (syntax & RE_NO_BK_REFS)
4111 FREE_STACK_RETURN (REG_ESUBREG);
4113 /* Can't back reference to a subexpression if inside of it. */
4114 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4118 BUF_PUSH_2 (duplicate, c1);
4124 if (syntax & RE_BK_PLUS_QM)
4127 goto normal_backslash;
4131 /* You might think it would be useful for \ to mean
4132 not to translate; but if we don't translate it
4133 it will never match anything. */
4141 /* Expects the character in `c'. */
4143 /* If no exactn currently being built. */
4146 /* If last exactn handle binary(or character) and
4147 new exactn handle character(or binary). */
4148 || is_exactn_bin != is_binary[p - 1 - pattern]
4151 /* If last exactn not at current position. */
4152 || pending_exact + *pending_exact + 1 != b
4154 /* We have only one byte following the exactn for the count. */
4155 || *pending_exact == (1 << BYTEWIDTH) - 1
4157 /* If followed by a repetition operator. */
4158 || *p == '*' || *p == '^'
4159 || ((syntax & RE_BK_PLUS_QM)
4160 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4161 : (*p == '+' || *p == '?'))
4162 || ((syntax & RE_INTERVALS)
4163 && ((syntax & RE_NO_BK_BRACES)
4165 : (p[0] == '\\' && p[1] == '{'))))
4167 /* Start building a new exactn. */
4172 /* Is this exactn binary data or character? */
4173 is_exactn_bin = is_binary[p - 1 - pattern];
4175 BUF_PUSH_2 (exactn_bin, 0);
4177 BUF_PUSH_2 (exactn, 0);
4179 BUF_PUSH_2 (exactn, 0);
4181 pending_exact = b - 1;
4188 } /* while p != pend */
4191 /* Through the pattern now. */
4194 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4196 if (!COMPILE_STACK_EMPTY)
4197 FREE_STACK_RETURN (REG_EPAREN);
4199 /* If we don't want backtracking, force success
4200 the first time we reach the end of the compiled pattern. */
4201 if (syntax & RE_NO_POSIX_BACKTRACKING)
4209 free (compile_stack.stack);
4211 /* We have succeeded; set the length of the buffer. */
4213 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4215 bufp->used = b - bufp->buffer;
4221 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4222 PREFIX(print_compiled_pattern) (bufp);
4226 #ifndef MATCH_MAY_ALLOCATE
4227 /* Initialize the failure stack to the largest possible stack. This
4228 isn't necessary unless we're trying to avoid calling alloca in
4229 the search and match routines. */
4231 int num_regs = bufp->re_nsub + 1;
4233 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4234 is strictly greater than re_max_failures, the largest possible stack
4235 is 2 * re_max_failures failure points. */
4236 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4238 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4241 if (! fail_stack.stack)
4243 = (PREFIX(fail_stack_elt_t) *) xmalloc (fail_stack.size
4244 * sizeof (PREFIX(fail_stack_elt_t)));
4247 = (PREFIX(fail_stack_elt_t) *) xrealloc (fail_stack.stack,
4249 * sizeof (PREFIX(fail_stack_elt_t))));
4250 # else /* not emacs */
4251 if (! fail_stack.stack)
4253 = (PREFIX(fail_stack_elt_t) *) malloc (fail_stack.size
4254 * sizeof (PREFIX(fail_stack_elt_t)));
4257 = (PREFIX(fail_stack_elt_t) *) realloc (fail_stack.stack,
4259 * sizeof (PREFIX(fail_stack_elt_t))));
4260 # endif /* not emacs */
4263 PREFIX(regex_grow_registers) (num_regs);
4265 #endif /* not MATCH_MAY_ALLOCATE */
4268 } /* regex_compile */
4270 /* Subroutines for `regex_compile'. */
4272 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4273 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4276 PREFIX(store_op1) (op, loc, arg)
4281 *loc = (UCHAR_T) op;
4282 STORE_NUMBER (loc + 1, arg);
4286 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4287 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4290 PREFIX(store_op2) (op, loc, arg1, arg2)
4295 *loc = (UCHAR_T) op;
4296 STORE_NUMBER (loc + 1, arg1);
4297 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4301 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4302 for OP followed by two-byte integer parameter ARG. */
4303 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4306 PREFIX(insert_op1) (op, loc, arg, end)
4312 register UCHAR_T *pfrom = end;
4313 register UCHAR_T *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4315 while (pfrom != loc)
4318 PREFIX(store_op1) (op, loc, arg);
4322 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4323 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4326 PREFIX(insert_op2) (op, loc, arg1, arg2, end)
4332 register UCHAR_T *pfrom = end;
4333 register UCHAR_T *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4335 while (pfrom != loc)
4338 PREFIX(store_op2) (op, loc, arg1, arg2);
4342 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4343 after an alternative or a begin-subexpression. We assume there is at
4344 least one character before the ^. */
4347 PREFIX(at_begline_loc_p) (pattern, p, syntax)
4348 const CHAR_T *pattern, *p;
4349 reg_syntax_t syntax;
4351 const CHAR_T *prev = p - 2;
4352 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4355 /* After a subexpression? */
4356 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4357 /* After an alternative? */
4358 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4362 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4363 at least one character after the $, i.e., `P < PEND'. */
4366 PREFIX(at_endline_loc_p) (p, pend, syntax)
4367 const CHAR_T *p, *pend;
4368 reg_syntax_t syntax;
4370 const CHAR_T *next = p;
4371 boolean next_backslash = *next == '\\';
4372 const CHAR_T *next_next = p + 1 < pend ? p + 1 : 0;
4375 /* Before a subexpression? */
4376 (syntax & RE_NO_BK_PARENS ? *next == ')'
4377 : next_backslash && next_next && *next_next == ')')
4378 /* Before an alternative? */
4379 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4380 : next_backslash && next_next && *next_next == '|');
4383 #else /* not INSIDE_RECURSION */
4385 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4386 false if it's not. */
4389 group_in_compile_stack (compile_stack, regnum)
4390 compile_stack_type compile_stack;
4395 for (this_element = compile_stack.avail - 1;
4398 if (compile_stack.stack[this_element].regnum == regnum)
4403 #endif /* not INSIDE_RECURSION */
4405 #ifdef INSIDE_RECURSION
4408 /* This insert space, which size is "num", into the pattern at "loc".
4409 "end" must point the end of the allocated buffer. */
4411 insert_space (num, loc, end)
4416 register CHAR_T *pto = end;
4417 register CHAR_T *pfrom = end - num;
4419 while (pfrom >= loc)
4425 static reg_errcode_t
4426 wcs_compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4428 CHAR_T range_start_char;
4429 const CHAR_T **p_ptr, *pend;
4430 CHAR_T *char_set, *b;
4431 RE_TRANSLATE_TYPE translate;
4432 reg_syntax_t syntax;
4434 const CHAR_T *p = *p_ptr;
4435 CHAR_T range_start, range_end;
4439 uint32_t start_val, end_val;
4445 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4448 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4449 _NL_COLLATE_COLLSEQWC);
4450 const unsigned char *extra = (const unsigned char *)
4451 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4453 if (range_start_char < -1)
4455 /* range_start is a collating symbol. */
4457 /* Retreive the index and get collation sequence value. */
4458 wextra = (int32_t*)(extra + char_set[-range_start_char]);
4459 start_val = wextra[1 + *wextra];
4462 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4464 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4466 /* Report an error if the range is empty and the syntax prohibits
4468 ret = ((syntax & RE_NO_EMPTY_RANGES)
4469 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4471 /* Insert space to the end of the char_ranges. */
4472 insert_space(2, b - char_set[5] - 2, b - 1);
4473 *(b - char_set[5] - 2) = (wchar_t)start_val;
4474 *(b - char_set[5] - 1) = (wchar_t)end_val;
4475 char_set[4]++; /* ranges_index */
4480 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4482 range_end = TRANSLATE (p[0]);
4483 /* Report an error if the range is empty and the syntax prohibits
4485 ret = ((syntax & RE_NO_EMPTY_RANGES)
4486 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4488 /* Insert space to the end of the char_ranges. */
4489 insert_space(2, b - char_set[5] - 2, b - 1);
4490 *(b - char_set[5] - 2) = range_start;
4491 *(b - char_set[5] - 1) = range_end;
4492 char_set[4]++; /* ranges_index */
4494 /* Have to increment the pointer into the pattern string, so the
4495 caller isn't still at the ending character. */
4501 /* Read the ending character of a range (in a bracket expression) from the
4502 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4503 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4504 Then we set the translation of all bits between the starting and
4505 ending characters (inclusive) in the compiled pattern B.
4507 Return an error code.
4509 We use these short variable names so we can use the same macros as
4510 `regex_compile' itself. */
4512 static reg_errcode_t
4513 byte_compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4514 unsigned int range_start_char;
4515 const char **p_ptr, *pend;
4516 RE_TRANSLATE_TYPE translate;
4517 reg_syntax_t syntax;
4521 const char *p = *p_ptr;
4524 const unsigned char *collseq;
4525 unsigned int start_colseq;
4526 unsigned int end_colseq;
4534 /* Have to increment the pointer into the pattern string, so the
4535 caller isn't still at the ending character. */
4538 /* Report an error if the range is empty and the syntax prohibits this. */
4539 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4542 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4543 _NL_COLLATE_COLLSEQMB);
4545 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4546 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4547 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4549 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4551 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4553 SET_LIST_BIT (TRANSLATE (this_char));
4558 /* Here we see why `this_char' has to be larger than an `unsigned
4559 char' -- we would otherwise go into an infinite loop, since all
4560 characters <= 0xff. */
4561 range_start_char = TRANSLATE (range_start_char);
4562 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4563 and some compilers cast it to int implicitly, so following for_loop
4564 may fall to (almost) infinite loop.
4565 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4566 To avoid this, we cast p[0] to unsigned int and truncate it. */
4567 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4569 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4571 SET_LIST_BIT (TRANSLATE (this_char));
4580 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4581 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4582 characters can start a string that matches the pattern. This fastmap
4583 is used by re_search to skip quickly over impossible starting points.
4585 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4586 area as BUFP->fastmap.
4588 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4591 Returns 0 if we succeed, -2 if an internal error. */
4594 /* local function for re_compile_fastmap.
4595 truncate wchar_t character to char. */
4596 static unsigned char truncate_wchar (CHAR_T c);
4598 static unsigned char
4602 unsigned char buf[MB_LEN_MAX];
4603 int retval = wctomb(buf, c);
4604 return retval > 0 ? buf[0] : (unsigned char)c;
4609 PREFIX(re_compile_fastmap) (bufp)
4610 struct re_pattern_buffer *bufp;
4613 #ifdef MATCH_MAY_ALLOCATE
4614 PREFIX(fail_stack_type) fail_stack;
4616 #ifndef REGEX_MALLOC
4620 register char *fastmap = bufp->fastmap;
4623 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4624 pattern to (char*) in regex_compile. */
4625 UCHAR_T *pattern = (UCHAR_T*)bufp->buffer;
4626 register UCHAR_T *pend = (UCHAR_T*) (bufp->buffer + bufp->used);
4628 UCHAR_T *pattern = bufp->buffer;
4629 register UCHAR_T *pend = pattern + bufp->used;
4631 UCHAR_T *p = pattern;
4634 /* This holds the pointer to the failure stack, when
4635 it is allocated relocatably. */
4636 fail_stack_elt_t *failure_stack_ptr;
4639 /* Assume that each path through the pattern can be null until
4640 proven otherwise. We set this false at the bottom of switch
4641 statement, to which we get only if a particular path doesn't
4642 match the empty string. */
4643 boolean path_can_be_null = true;
4645 /* We aren't doing a `succeed_n' to begin with. */
4646 boolean succeed_n_p = false;
4648 assert (fastmap != NULL && p != NULL);
4651 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4652 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4653 bufp->can_be_null = 0;
4657 if (p == pend || *p == succeed)
4659 /* We have reached the (effective) end of pattern. */
4660 if (!FAIL_STACK_EMPTY ())
4662 bufp->can_be_null |= path_can_be_null;
4664 /* Reset for next path. */
4665 path_can_be_null = true;
4667 p = fail_stack.stack[--fail_stack.avail].pointer;
4675 /* We should never be about to go beyond the end of the pattern. */
4678 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4681 /* I guess the idea here is to simply not bother with a fastmap
4682 if a backreference is used, since it's too hard to figure out
4683 the fastmap for the corresponding group. Setting
4684 `can_be_null' stops `re_search_2' from using the fastmap, so
4685 that is all we do. */
4687 bufp->can_be_null = 1;
4691 /* Following are the cases which match a character. These end
4696 fastmap[truncate_wchar(p[1])] = 1;
4710 /* It is hard to distinguish fastmap from (multi byte) characters
4711 which depends on current locale. */
4716 bufp->can_be_null = 1;
4720 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4721 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4727 /* Chars beyond end of map must be allowed. */
4728 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4731 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4732 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4738 for (j = 0; j < (1 << BYTEWIDTH); j++)
4739 if (SYNTAX (j) == Sword)
4745 for (j = 0; j < (1 << BYTEWIDTH); j++)
4746 if (SYNTAX (j) != Sword)
4753 int fastmap_newline = fastmap['\n'];
4755 /* `.' matches anything ... */
4756 for (j = 0; j < (1 << BYTEWIDTH); j++)
4759 /* ... except perhaps newline. */
4760 if (!(bufp->syntax & RE_DOT_NEWLINE))
4761 fastmap['\n'] = fastmap_newline;
4763 /* Return if we have already set `can_be_null'; if we have,
4764 then the fastmap is irrelevant. Something's wrong here. */
4765 else if (bufp->can_be_null)
4768 /* Otherwise, have to check alternative paths. */
4775 for (j = 0; j < (1 << BYTEWIDTH); j++)
4776 if (SYNTAX (j) == (enum syntaxcode) k)
4783 for (j = 0; j < (1 << BYTEWIDTH); j++)
4784 if (SYNTAX (j) != (enum syntaxcode) k)
4789 /* All cases after this match the empty string. These end with
4809 case push_dummy_failure:
4814 case pop_failure_jump:
4815 case maybe_pop_jump:
4818 case dummy_failure_jump:
4819 EXTRACT_NUMBER_AND_INCR (j, p);
4824 /* Jump backward implies we just went through the body of a
4825 loop and matched nothing. Opcode jumped to should be
4826 `on_failure_jump' or `succeed_n'. Just treat it like an
4827 ordinary jump. For a * loop, it has pushed its failure
4828 point already; if so, discard that as redundant. */
4829 if ((re_opcode_t) *p != on_failure_jump
4830 && (re_opcode_t) *p != succeed_n)
4834 EXTRACT_NUMBER_AND_INCR (j, p);
4837 /* If what's on the stack is where we are now, pop it. */
4838 if (!FAIL_STACK_EMPTY ()
4839 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4845 case on_failure_jump:
4846 case on_failure_keep_string_jump:
4847 handle_on_failure_jump:
4848 EXTRACT_NUMBER_AND_INCR (j, p);
4850 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4851 end of the pattern. We don't want to push such a point,
4852 since when we restore it above, entering the switch will
4853 increment `p' past the end of the pattern. We don't need
4854 to push such a point since we obviously won't find any more
4855 fastmap entries beyond `pend'. Such a pattern can match
4856 the null string, though. */
4859 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4861 RESET_FAIL_STACK ();
4866 bufp->can_be_null = 1;
4870 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4871 succeed_n_p = false;
4878 /* Get to the number of times to succeed. */
4879 p += OFFSET_ADDRESS_SIZE;
4881 /* Increment p past the n for when k != 0. */
4882 EXTRACT_NUMBER_AND_INCR (k, p);
4885 p -= 2 * OFFSET_ADDRESS_SIZE;
4886 succeed_n_p = true; /* Spaghetti code alert. */
4887 goto handle_on_failure_jump;
4893 p += 2 * OFFSET_ADDRESS_SIZE;
4904 abort (); /* We have listed all the cases. */
4907 /* Getting here means we have found the possible starting
4908 characters for one path of the pattern -- and that the empty
4909 string does not match. We need not follow this path further.
4910 Instead, look at the next alternative (remembered on the
4911 stack), or quit if no more. The test at the top of the loop
4912 does these things. */
4913 path_can_be_null = false;
4917 /* Set `can_be_null' for the last path (also the first path, if the
4918 pattern is empty). */
4919 bufp->can_be_null |= path_can_be_null;
4922 RESET_FAIL_STACK ();
4926 #else /* not INSIDE_RECURSION */
4929 re_compile_fastmap (bufp)
4930 struct re_pattern_buffer *bufp;
4933 if (MB_CUR_MAX != 1)
4934 return wcs_re_compile_fastmap(bufp);
4937 return byte_re_compile_fastmap(bufp);
4938 } /* re_compile_fastmap */
4940 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4944 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4945 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4946 this memory for recording register information. STARTS and ENDS
4947 must be allocated using the malloc library routine, and must each
4948 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4950 If NUM_REGS == 0, then subsequent matches should allocate their own
4953 Unless this function is called, the first search or match using
4954 PATTERN_BUFFER will allocate its own register data, without
4955 freeing the old data. */
4958 re_set_registers (bufp, regs, num_regs, starts, ends)
4959 struct re_pattern_buffer *bufp;
4960 struct re_registers *regs;
4962 regoff_t *starts, *ends;
4966 bufp->regs_allocated = REGS_REALLOCATE;
4967 regs->num_regs = num_regs;
4968 regs->start = starts;
4973 bufp->regs_allocated = REGS_UNALLOCATED;
4975 regs->start = regs->end = (regoff_t *) 0;
4979 weak_alias (__re_set_registers, re_set_registers)
4982 /* Searching routines. */
4984 /* Like re_search_2, below, but only one string is specified, and
4985 doesn't let you say where to stop matching. */
4988 re_search (bufp, string, size, startpos, range, regs)
4989 struct re_pattern_buffer *bufp;
4991 int size, startpos, range;
4992 struct re_registers *regs;
4994 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4998 weak_alias (__re_search, re_search)
5002 /* Using the compiled pattern in BUFP->buffer, first tries to match the
5003 virtual concatenation of STRING1 and STRING2, starting first at index
5004 STARTPOS, then at STARTPOS + 1, and so on.
5006 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
5008 RANGE is how far to scan while trying to match. RANGE = 0 means try
5009 only at STARTPOS; in general, the last start tried is STARTPOS +
5012 In REGS, return the indices of the virtual concatenation of STRING1
5013 and STRING2 that matched the entire BUFP->buffer and its contained
5016 Do not consider matching one past the index STOP in the virtual
5017 concatenation of STRING1 and STRING2.
5019 We return either the position in the strings at which the match was
5020 found, -1 if no match, or -2 if error (such as failure
5024 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
5025 struct re_pattern_buffer *bufp;
5026 const char *string1, *string2;
5030 struct re_registers *regs;
5034 if (MB_CUR_MAX != 1)
5035 return wcs_re_search_2 (bufp, string1, size1, string2, size2, startpos,
5039 return byte_re_search_2 (bufp, string1, size1, string2, size2, startpos,
5043 weak_alias (__re_search_2, re_search_2)
5046 #endif /* not INSIDE_RECURSION */
5048 #ifdef INSIDE_RECURSION
5051 PREFIX(re_search_2) (bufp, string1, size1, string2, size2, startpos, range,
5053 struct re_pattern_buffer *bufp;
5054 const char *string1, *string2;
5058 struct re_registers *regs;
5062 register char *fastmap = bufp->fastmap;
5063 register RE_TRANSLATE_TYPE translate = bufp->translate;
5064 int total_size = size1 + size2;
5065 int endpos = startpos + range;
5067 /* Check for out-of-range STARTPOS. */
5068 if (startpos < 0 || startpos > total_size)
5071 /* Fix up RANGE if it might eventually take us outside
5072 the virtual concatenation of STRING1 and STRING2.
5073 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
5075 range = 0 - startpos;
5076 else if (endpos > total_size)
5077 range = total_size - startpos;
5079 /* If the search isn't to be a backwards one, don't waste time in a
5080 search for a pattern that must be anchored. */
5081 if (bufp->used > 0 && range > 0
5082 && ((re_opcode_t) bufp->buffer[0] == begbuf
5083 /* `begline' is like `begbuf' if it cannot match at newlines. */
5084 || ((re_opcode_t) bufp->buffer[0] == begline
5085 && !bufp->newline_anchor)))
5094 /* In a forward search for something that starts with \=.
5095 don't keep searching past point. */
5096 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5098 range = PT - startpos;
5104 /* Update the fastmap now if not correct already. */
5105 if (fastmap && !bufp->fastmap_accurate)
5106 if (re_compile_fastmap (bufp) == -2)
5109 /* Loop through the string, looking for a place to start matching. */
5112 /* If a fastmap is supplied, skip quickly over characters that
5113 cannot be the start of a match. If the pattern can match the
5114 null string, however, we don't need to skip characters; we want
5115 the first null string. */
5116 if (fastmap && startpos < total_size && !bufp->can_be_null)
5118 if (range > 0) /* Searching forwards. */
5120 register const char *d;
5121 register int lim = 0;
5124 if (startpos < size1 && startpos + range >= size1)
5125 lim = range - (size1 - startpos);
5127 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5129 /* Written out as an if-else to avoid testing `translate'
5133 && !fastmap[(unsigned char)
5134 translate[(unsigned char) *d++]])
5137 while (range > lim && !fastmap[(unsigned char) *d++])
5140 startpos += irange - range;
5142 else /* Searching backwards. */
5144 register CHAR_T c = (size1 == 0 || startpos >= size1
5145 ? string2[startpos - size1]
5146 : string1[startpos]);
5148 if (!fastmap[(unsigned char) TRANSLATE (c)])
5153 /* If can't match the null string, and that's all we have left, fail. */
5154 if (range >= 0 && startpos == total_size && fastmap
5155 && !bufp->can_be_null)
5158 val = PREFIX(re_match_2_internal) (bufp, string1, size1, string2,
5159 size2, startpos, regs, stop);
5160 #ifndef REGEX_MALLOC
5190 /* This converts PTR, a pointer into one of the search wchar_t strings
5191 `string1' and `string2' into an multibyte string offset from the
5192 beginning of that string. We use mbs_offset to optimize.
5193 See convert_mbs_to_wcs. */
5194 # define POINTER_TO_OFFSET(ptr) \
5195 (FIRST_STRING_P (ptr) \
5196 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5197 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5200 /* This converts PTR, a pointer into one of the search strings `string1'
5201 and `string2' into an offset from the beginning of that string. */
5202 # define POINTER_TO_OFFSET(ptr) \
5203 (FIRST_STRING_P (ptr) \
5204 ? ((regoff_t) ((ptr) - string1)) \
5205 : ((regoff_t) ((ptr) - string2 + size1)))
5208 /* Macros for dealing with the split strings in re_match_2. */
5210 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5212 /* Call before fetching a character with *d. This switches over to
5213 string2 if necessary. */
5214 #define PREFETCH() \
5217 /* End of string2 => fail. */ \
5218 if (dend == end_match_2) \
5220 /* End of string1 => advance to string2. */ \
5222 dend = end_match_2; \
5225 /* Test if at very beginning or at very end of the virtual concatenation
5226 of `string1' and `string2'. If only one string, it's `string2'. */
5227 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5228 #define AT_STRINGS_END(d) ((d) == end2)
5231 /* Test if D points to a character which is word-constituent. We have
5232 two special cases to check for: if past the end of string1, look at
5233 the first character in string2; and if before the beginning of
5234 string2, look at the last character in string1. */
5236 /* Use internationalized API instead of SYNTAX. */
5237 # define WORDCHAR_P(d) \
5238 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5239 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5241 # define WORDCHAR_P(d) \
5242 (SYNTAX ((d) == end1 ? *string2 \
5243 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5247 /* Disabled due to a compiler bug -- see comment at case wordbound */
5249 /* Test if the character before D and the one at D differ with respect
5250 to being word-constituent. */
5251 #define AT_WORD_BOUNDARY(d) \
5252 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5253 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5256 /* Free everything we malloc. */
5257 #ifdef MATCH_MAY_ALLOCATE
5258 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5260 # define FREE_VARIABLES() \
5262 REGEX_FREE_STACK (fail_stack.stack); \
5263 FREE_VAR (regstart); \
5264 FREE_VAR (regend); \
5265 FREE_VAR (old_regstart); \
5266 FREE_VAR (old_regend); \
5267 FREE_VAR (best_regstart); \
5268 FREE_VAR (best_regend); \
5269 FREE_VAR (reg_info); \
5270 FREE_VAR (reg_dummy); \
5271 FREE_VAR (reg_info_dummy); \
5272 FREE_VAR (string1); \
5273 FREE_VAR (string2); \
5274 FREE_VAR (mbs_offset1); \
5275 FREE_VAR (mbs_offset2); \
5278 # define FREE_VARIABLES() \
5280 REGEX_FREE_STACK (fail_stack.stack); \
5281 FREE_VAR (regstart); \
5282 FREE_VAR (regend); \
5283 FREE_VAR (old_regstart); \
5284 FREE_VAR (old_regend); \
5285 FREE_VAR (best_regstart); \
5286 FREE_VAR (best_regend); \
5287 FREE_VAR (reg_info); \
5288 FREE_VAR (reg_dummy); \
5289 FREE_VAR (reg_info_dummy); \
5293 # define FREE_VAR(var) if (var) free (var); var = NULL
5295 # define FREE_VARIABLES() \
5297 FREE_VAR (string1); \
5298 FREE_VAR (string2); \
5299 FREE_VAR (mbs_offset1); \
5300 FREE_VAR (mbs_offset2); \
5303 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5305 #endif /* not MATCH_MAY_ALLOCATE */
5307 /* These values must meet several constraints. They must not be valid
5308 register values; since we have a limit of 255 registers (because
5309 we use only one byte in the pattern for the register number), we can
5310 use numbers larger than 255. They must differ by 1, because of
5311 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5312 be larger than the value for the highest register, so we do not try
5313 to actually save any registers when none are active. */
5314 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5315 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5317 #else /* not INSIDE_RECURSION */
5318 /* Matching routines. */
5320 #ifndef emacs /* Emacs never uses this. */
5321 /* re_match is like re_match_2 except it takes only a single string. */
5324 re_match (bufp, string, size, pos, regs)
5325 struct re_pattern_buffer *bufp;
5328 struct re_registers *regs;
5332 if (MB_CUR_MAX != 1)
5333 result = wcs_re_match_2_internal (bufp, NULL, 0, string, size,
5337 result = byte_re_match_2_internal (bufp, NULL, 0, string, size,
5339 # ifndef REGEX_MALLOC
5347 weak_alias (__re_match, re_match)
5349 #endif /* not emacs */
5351 #endif /* not INSIDE_RECURSION */
5353 #ifdef INSIDE_RECURSION
5354 static boolean PREFIX(group_match_null_string_p) _RE_ARGS ((UCHAR_T **p,
5356 PREFIX(register_info_type) *reg_info));
5357 static boolean PREFIX(alt_match_null_string_p) _RE_ARGS ((UCHAR_T *p,
5359 PREFIX(register_info_type) *reg_info));
5360 static boolean PREFIX(common_op_match_null_string_p) _RE_ARGS ((UCHAR_T **p,
5362 PREFIX(register_info_type) *reg_info));
5363 static int PREFIX(bcmp_translate) _RE_ARGS ((const CHAR_T *s1, const CHAR_T *s2,
5364 int len, char *translate));
5365 #else /* not INSIDE_RECURSION */
5367 /* re_match_2 matches the compiled pattern in BUFP against the
5368 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5369 and SIZE2, respectively). We start matching at POS, and stop
5372 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5373 store offsets for the substring each group matched in REGS. See the
5374 documentation for exactly how many groups we fill.
5376 We return -1 if no match, -2 if an internal error (such as the
5377 failure stack overflowing). Otherwise, we return the length of the
5378 matched substring. */
5381 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5382 struct re_pattern_buffer *bufp;
5383 const char *string1, *string2;
5386 struct re_registers *regs;
5391 if (MB_CUR_MAX != 1)
5392 result = wcs_re_match_2_internal (bufp, string1, size1, string2, size2,
5396 result = byte_re_match_2_internal (bufp, string1, size1, string2, size2,
5399 #ifndef REGEX_MALLOC
5407 weak_alias (__re_match_2, re_match_2)
5410 #endif /* not INSIDE_RECURSION */
5412 #ifdef INSIDE_RECURSION
5415 static int count_mbs_length PARAMS ((int *, int));
5417 /* This check the substring (from 0, to length) of the multibyte string,
5418 to which offset_buffer correspond. And count how many wchar_t_characters
5419 the substring occupy. We use offset_buffer to optimization.
5420 See convert_mbs_to_wcs. */
5423 count_mbs_length(offset_buffer, length)
5429 /* Check whether the size is valid. */
5433 if (offset_buffer == NULL)
5436 for (wcs_size = 0 ; offset_buffer[wcs_size] != -1 ; wcs_size++)
5438 if (offset_buffer[wcs_size] == length)
5440 if (offset_buffer[wcs_size] > length)
5441 /* It is a fragment of a wide character. */
5445 /* We reached at the sentinel. */
5450 /* This is a separate function so that we can force an alloca cleanup
5453 PREFIX(re_match_2_internal) (bufp, ARG_PREFIX(string1), ARG_PREFIX(size1),
5454 ARG_PREFIX(string2), ARG_PREFIX(size2), pos,
5456 struct re_pattern_buffer *bufp;
5457 const char *ARG_PREFIX(string1), *ARG_PREFIX(string2);
5458 int ARG_PREFIX(size1), ARG_PREFIX(size2);
5460 struct re_registers *regs;
5463 /* General temporaries. */
5467 /* We need wchar_t* buffers correspond to string1, string2. */
5468 CHAR_T *string1 = NULL, *string2 = NULL;
5469 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5470 int size1 = 0, size2 = 0;
5471 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5472 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5473 /* They hold whether each wchar_t is binary data or not. */
5474 char *is_binary = NULL;
5477 /* Just past the end of the corresponding string. */
5478 const CHAR_T *end1, *end2;
5480 /* Pointers into string1 and string2, just past the last characters in
5481 each to consider matching. */
5482 const CHAR_T *end_match_1, *end_match_2;
5484 /* Where we are in the data, and the end of the current string. */
5485 const CHAR_T *d, *dend;
5487 /* Where we are in the pattern, and the end of the pattern. */
5489 UCHAR_T *pattern, *p;
5490 register UCHAR_T *pend;
5492 UCHAR_T *p = bufp->buffer;
5493 register UCHAR_T *pend = p + bufp->used;
5496 /* Mark the opcode just after a start_memory, so we can test for an
5497 empty subpattern when we get to the stop_memory. */
5498 UCHAR_T *just_past_start_mem = 0;
5500 /* We use this to map every character in the string. */
5501 RE_TRANSLATE_TYPE translate = bufp->translate;
5503 /* Failure point stack. Each place that can handle a failure further
5504 down the line pushes a failure point on this stack. It consists of
5505 restart, regend, and reg_info for all registers corresponding to
5506 the subexpressions we're currently inside, plus the number of such
5507 registers, and, finally, two char *'s. The first char * is where
5508 to resume scanning the pattern; the second one is where to resume
5509 scanning the strings. If the latter is zero, the failure point is
5510 a ``dummy''; if a failure happens and the failure point is a dummy,
5511 it gets discarded and the next next one is tried. */
5512 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5513 PREFIX(fail_stack_type) fail_stack;
5516 static unsigned failure_id;
5517 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5521 /* This holds the pointer to the failure stack, when
5522 it is allocated relocatably. */
5523 fail_stack_elt_t *failure_stack_ptr;
5526 /* We fill all the registers internally, independent of what we
5527 return, for use in backreferences. The number here includes
5528 an element for register zero. */
5529 size_t num_regs = bufp->re_nsub + 1;
5531 /* The currently active registers. */
5532 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5533 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5535 /* Information on the contents of registers. These are pointers into
5536 the input strings; they record just what was matched (on this
5537 attempt) by a subexpression part of the pattern, that is, the
5538 regnum-th regstart pointer points to where in the pattern we began
5539 matching and the regnum-th regend points to right after where we
5540 stopped matching the regnum-th subexpression. (The zeroth register
5541 keeps track of what the whole pattern matches.) */
5542 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5543 const CHAR_T **regstart, **regend;
5546 /* If a group that's operated upon by a repetition operator fails to
5547 match anything, then the register for its start will need to be
5548 restored because it will have been set to wherever in the string we
5549 are when we last see its open-group operator. Similarly for a
5551 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5552 const CHAR_T **old_regstart, **old_regend;
5555 /* The is_active field of reg_info helps us keep track of which (possibly
5556 nested) subexpressions we are currently in. The matched_something
5557 field of reg_info[reg_num] helps us tell whether or not we have
5558 matched any of the pattern so far this time through the reg_num-th
5559 subexpression. These two fields get reset each time through any
5560 loop their register is in. */
5561 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5562 PREFIX(register_info_type) *reg_info;
5565 /* The following record the register info as found in the above
5566 variables when we find a match better than any we've seen before.
5567 This happens as we backtrack through the failure points, which in
5568 turn happens only if we have not yet matched the entire string. */
5569 unsigned best_regs_set = false;
5570 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5571 const CHAR_T **best_regstart, **best_regend;
5574 /* Logically, this is `best_regend[0]'. But we don't want to have to
5575 allocate space for that if we're not allocating space for anything
5576 else (see below). Also, we never need info about register 0 for
5577 any of the other register vectors, and it seems rather a kludge to
5578 treat `best_regend' differently than the rest. So we keep track of
5579 the end of the best match so far in a separate variable. We
5580 initialize this to NULL so that when we backtrack the first time
5581 and need to test it, it's not garbage. */
5582 const CHAR_T *match_end = NULL;
5584 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5585 int set_regs_matched_done = 0;
5587 /* Used when we pop values we don't care about. */
5588 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5589 const CHAR_T **reg_dummy;
5590 PREFIX(register_info_type) *reg_info_dummy;
5594 /* Counts the total number of registers pushed. */
5595 unsigned num_regs_pushed = 0;
5598 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5602 #ifdef MATCH_MAY_ALLOCATE
5603 /* Do not bother to initialize all the register variables if there are
5604 no groups in the pattern, as it takes a fair amount of time. If
5605 there are groups, we include space for register 0 (the whole
5606 pattern), even though we never use it, since it simplifies the
5607 array indexing. We should fix this. */
5610 regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5611 regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5612 old_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5613 old_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5614 best_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5615 best_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5616 reg_info = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5617 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_T *);
5618 reg_info_dummy = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5620 if (!(regstart && regend && old_regstart && old_regend && reg_info
5621 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5629 /* We must initialize all our variables to NULL, so that
5630 `FREE_VARIABLES' doesn't try to free them. */
5631 regstart = regend = old_regstart = old_regend = best_regstart
5632 = best_regend = reg_dummy = NULL;
5633 reg_info = reg_info_dummy = (PREFIX(register_info_type) *) NULL;
5635 #endif /* MATCH_MAY_ALLOCATE */
5637 /* The starting position is bogus. */
5639 if (pos < 0 || pos > csize1 + csize2)
5641 if (pos < 0 || pos > size1 + size2)
5649 /* Allocate wchar_t array for string1 and string2 and
5650 fill them with converted string. */
5653 string1 = REGEX_TALLOC (csize1 + 1, CHAR_T);
5654 mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5655 is_binary = REGEX_TALLOC (csize1 + 1, char);
5656 if (!string1 || !mbs_offset1 || !is_binary)
5659 FREE_VAR (mbs_offset1);
5660 FREE_VAR (is_binary);
5663 size1 = convert_mbs_to_wcs(string1, cstring1, csize1,
5664 mbs_offset1, is_binary);
5665 string1[size1] = L'\0'; /* for a sentinel */
5666 FREE_VAR (is_binary);
5670 string2 = REGEX_TALLOC (csize2 + 1, CHAR_T);
5671 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5672 is_binary = REGEX_TALLOC (csize2 + 1, char);
5673 if (!string2 || !mbs_offset2 || !is_binary)
5676 FREE_VAR (mbs_offset1);
5678 FREE_VAR (mbs_offset2);
5679 FREE_VAR (is_binary);
5682 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5683 mbs_offset2, is_binary);
5684 string2[size2] = L'\0'; /* for a sentinel */
5685 FREE_VAR (is_binary);
5688 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5689 pattern to (char*) in regex_compile. */
5690 p = pattern = (CHAR_T*)bufp->buffer;
5691 pend = (CHAR_T*)(bufp->buffer + bufp->used);
5695 /* Initialize subexpression text positions to -1 to mark ones that no
5696 start_memory/stop_memory has been seen for. Also initialize the
5697 register information struct. */
5698 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5700 regstart[mcnt] = regend[mcnt]
5701 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5703 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5704 IS_ACTIVE (reg_info[mcnt]) = 0;
5705 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5706 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5709 /* We move `string1' into `string2' if the latter's empty -- but not if
5710 `string1' is null. */
5711 if (size2 == 0 && string1 != NULL)
5718 mbs_offset2 = mbs_offset1;
5724 end1 = string1 + size1;
5725 end2 = string2 + size2;
5727 /* Compute where to stop matching, within the two strings. */
5731 mcnt = count_mbs_length(mbs_offset1, stop);
5732 end_match_1 = string1 + mcnt;
5733 end_match_2 = string2;
5737 if (stop > csize1 + csize2)
5738 stop = csize1 + csize2;
5740 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5741 end_match_2 = string2 + mcnt;
5744 { /* count_mbs_length return error. */
5751 end_match_1 = string1 + stop;
5752 end_match_2 = string2;
5757 end_match_2 = string2 + stop - size1;
5761 /* `p' scans through the pattern as `d' scans through the data.
5762 `dend' is the end of the input string that `d' points within. `d'
5763 is advanced into the following input string whenever necessary, but
5764 this happens before fetching; therefore, at the beginning of the
5765 loop, `d' can be pointing at the end of a string, but it cannot
5768 if (size1 > 0 && pos <= csize1)
5770 mcnt = count_mbs_length(mbs_offset1, pos);
5776 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5782 { /* count_mbs_length return error. */
5787 if (size1 > 0 && pos <= size1)
5794 d = string2 + pos - size1;
5799 DEBUG_PRINT1 ("The compiled pattern is:\n");
5800 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5801 DEBUG_PRINT1 ("The string to match is: `");
5802 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5803 DEBUG_PRINT1 ("'\n");
5805 /* This loops over pattern commands. It exits by returning from the
5806 function if the match is complete, or it drops through if the match
5807 fails at this starting point in the input data. */
5811 DEBUG_PRINT2 ("\n%p: ", p);
5813 DEBUG_PRINT2 ("\n0x%x: ", p);
5817 { /* End of pattern means we might have succeeded. */
5818 DEBUG_PRINT1 ("end of pattern ... ");
5820 /* If we haven't matched the entire string, and we want the
5821 longest match, try backtracking. */
5822 if (d != end_match_2)
5824 /* 1 if this match ends in the same string (string1 or string2)
5825 as the best previous match. */
5826 boolean same_str_p = (FIRST_STRING_P (match_end)
5827 == MATCHING_IN_FIRST_STRING);
5828 /* 1 if this match is the best seen so far. */
5829 boolean best_match_p;
5831 /* AIX compiler got confused when this was combined
5832 with the previous declaration. */
5834 best_match_p = d > match_end;
5836 best_match_p = !MATCHING_IN_FIRST_STRING;
5838 DEBUG_PRINT1 ("backtracking.\n");
5840 if (!FAIL_STACK_EMPTY ())
5841 { /* More failure points to try. */
5843 /* If exceeds best match so far, save it. */
5844 if (!best_regs_set || best_match_p)
5846 best_regs_set = true;
5849 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5851 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5853 best_regstart[mcnt] = regstart[mcnt];
5854 best_regend[mcnt] = regend[mcnt];
5860 /* If no failure points, don't restore garbage. And if
5861 last match is real best match, don't restore second
5863 else if (best_regs_set && !best_match_p)
5866 /* Restore best match. It may happen that `dend ==
5867 end_match_1' while the restored d is in string2.
5868 For example, the pattern `x.*y.*z' against the
5869 strings `x-' and `y-z-', if the two strings are
5870 not consecutive in memory. */
5871 DEBUG_PRINT1 ("Restoring best registers.\n");
5874 dend = ((d >= string1 && d <= end1)
5875 ? end_match_1 : end_match_2);
5877 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5879 regstart[mcnt] = best_regstart[mcnt];
5880 regend[mcnt] = best_regend[mcnt];
5883 } /* d != end_match_2 */
5886 DEBUG_PRINT1 ("Accepting match.\n");
5887 /* If caller wants register contents data back, do it. */
5888 if (regs && !bufp->no_sub)
5890 /* Have the register data arrays been allocated? */
5891 if (bufp->regs_allocated == REGS_UNALLOCATED)
5892 { /* No. So allocate them with malloc. We need one
5893 extra element beyond `num_regs' for the `-1' marker
5895 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5896 regs->start = TALLOC (regs->num_regs, regoff_t);
5897 regs->end = TALLOC (regs->num_regs, regoff_t);
5898 if (regs->start == NULL || regs->end == NULL)
5903 bufp->regs_allocated = REGS_REALLOCATE;
5905 else if (bufp->regs_allocated == REGS_REALLOCATE)
5906 { /* Yes. If we need more elements than were already
5907 allocated, reallocate them. If we need fewer, just
5909 if (regs->num_regs < num_regs + 1)
5911 regs->num_regs = num_regs + 1;
5912 RETALLOC (regs->start, regs->num_regs, regoff_t);
5913 RETALLOC (regs->end, regs->num_regs, regoff_t);
5914 if (regs->start == NULL || regs->end == NULL)
5923 /* These braces fend off a "empty body in an else-statement"
5924 warning under GCC when assert expands to nothing. */
5925 assert (bufp->regs_allocated == REGS_FIXED);
5928 /* Convert the pointer data in `regstart' and `regend' to
5929 indices. Register zero has to be set differently,
5930 since we haven't kept track of any info for it. */
5931 if (regs->num_regs > 0)
5933 regs->start[0] = pos;
5935 if (MATCHING_IN_FIRST_STRING)
5936 regs->end[0] = mbs_offset1 != NULL ?
5937 mbs_offset1[d-string1] : 0;
5939 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
5940 mbs_offset2[d-string2] : 0);
5942 regs->end[0] = (MATCHING_IN_FIRST_STRING
5943 ? ((regoff_t) (d - string1))
5944 : ((regoff_t) (d - string2 + size1)));
5948 /* Go through the first `min (num_regs, regs->num_regs)'
5949 registers, since that is all we initialized. */
5950 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
5953 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
5954 regs->start[mcnt] = regs->end[mcnt] = -1;
5958 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
5960 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
5964 /* If the regs structure we return has more elements than
5965 were in the pattern, set the extra elements to -1. If
5966 we (re)allocated the registers, this is the case,
5967 because we always allocate enough to have at least one
5969 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
5970 regs->start[mcnt] = regs->end[mcnt] = -1;
5971 } /* regs && !bufp->no_sub */
5973 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5974 nfailure_points_pushed, nfailure_points_popped,
5975 nfailure_points_pushed - nfailure_points_popped);
5976 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5979 if (MATCHING_IN_FIRST_STRING)
5980 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
5982 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
5986 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
5991 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5997 /* Otherwise match next pattern command. */
5998 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
6000 /* Ignore these. Used to ignore the n of succeed_n's which
6001 currently have n == 0. */
6003 DEBUG_PRINT1 ("EXECUTING no_op.\n");
6007 DEBUG_PRINT1 ("EXECUTING succeed.\n");
6010 /* Match the next n pattern characters exactly. The following
6011 byte in the pattern defines n, and the n bytes after that
6012 are the characters to match. */
6018 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
6020 /* This is written out as an if-else so we don't waste time
6021 testing `translate' inside the loop. */
6030 if ((UCHAR_T) translate[(unsigned char) *d++]
6036 if (*d++ != (CHAR_T) *p++)
6040 if ((UCHAR_T) translate[(unsigned char) *d++]
6052 if (*d++ != (CHAR_T) *p++) goto fail;
6056 SET_REGS_MATCHED ();
6060 /* Match any character except possibly a newline or a null. */
6062 DEBUG_PRINT1 ("EXECUTING anychar.\n");
6066 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
6067 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
6070 SET_REGS_MATCHED ();
6071 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
6081 unsigned int i, char_class_length, coll_symbol_length,
6082 equiv_class_length, ranges_length, chars_length, length;
6083 CHAR_T *workp, *workp2, *charset_top;
6084 #define WORK_BUFFER_SIZE 128
6085 CHAR_T str_buf[WORK_BUFFER_SIZE];
6090 boolean not = (re_opcode_t) *(p - 1) == charset_not;
6092 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
6094 c = TRANSLATE (*d); /* The character to match. */
6097 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
6099 charset_top = p - 1;
6100 char_class_length = *p++;
6101 coll_symbol_length = *p++;
6102 equiv_class_length = *p++;
6103 ranges_length = *p++;
6104 chars_length = *p++;
6105 /* p points charset[6], so the address of the next instruction
6106 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
6107 where l=length of char_classes, m=length of collating_symbol,
6108 n=equivalence_class, o=length of char_range,
6109 p'=length of character. */
6111 /* Update p to indicate the next instruction. */
6112 p += char_class_length + coll_symbol_length+ equiv_class_length +
6113 2*ranges_length + chars_length;
6115 /* match with char_class? */
6116 for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
6119 uintptr_t alignedp = ((uintptr_t)workp
6120 + __alignof__(wctype_t) - 1)
6121 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6122 wctype = *((wctype_t*)alignedp);
6123 workp += CHAR_CLASS_SIZE;
6124 if (iswctype((wint_t)c, wctype))
6125 goto char_set_matched;
6128 /* match with collating_symbol? */
6132 const unsigned char *extra = (const unsigned char *)
6133 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6135 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6139 wextra = (int32_t*)(extra + *workp++);
6140 for (i = 0; i < *wextra; ++i)
6141 if (TRANSLATE(d[i]) != wextra[1 + i])
6146 /* Update d, however d will be incremented at
6147 char_set_matched:, we decrement d here. */
6149 goto char_set_matched;
6153 else /* (nrules == 0) */
6155 /* If we can't look up collation data, we use wcscoll
6158 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6160 const CHAR_T *backup_d = d, *backup_dend = dend;
6161 length = wcslen(workp);
6163 /* If wcscoll(the collating symbol, whole string) > 0,
6164 any substring of the string never match with the
6165 collating symbol. */
6166 if (wcscoll(workp, d) > 0)
6168 workp += length + 1;
6172 /* First, we compare the collating symbol with
6173 the first character of the string.
6174 If it don't match, we add the next character to
6175 the compare buffer in turn. */
6176 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6181 if (dend == end_match_2)
6187 /* add next character to the compare buffer. */
6188 str_buf[i] = TRANSLATE(*d);
6189 str_buf[i+1] = '\0';
6191 match = wcscoll(workp, str_buf);
6193 goto char_set_matched;
6196 /* (str_buf > workp) indicate (str_buf + X > workp),
6197 because for all X (str_buf + X > str_buf).
6198 So we don't need continue this loop. */
6201 /* Otherwise(str_buf < workp),
6202 (str_buf+next_character) may equals (workp).
6203 So we continue this loop. */
6208 workp += length + 1;
6211 /* match with equivalence_class? */
6215 const CHAR_T *backup_d = d, *backup_dend = dend;
6216 /* Try to match the equivalence class against
6217 those known to the collate implementation. */
6218 const int32_t *table;
6219 const int32_t *weights;
6220 const int32_t *extra;
6221 const int32_t *indirect;
6226 /* This #include defines a local function! */
6227 # include <locale/weightwc.h>
6229 table = (const int32_t *)
6230 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6231 weights = (const wint_t *)
6232 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6233 extra = (const wint_t *)
6234 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6235 indirect = (const int32_t *)
6236 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6238 /* Write 1 collating element to str_buf, and
6242 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6244 cp = (wint_t*)str_buf;
6247 if (dend == end_match_2)
6252 str_buf[i] = TRANSLATE(*(d+i));
6253 str_buf[i+1] = '\0'; /* sentinel */
6254 idx2 = findidx ((const wint_t**)&cp);
6257 /* Update d, however d will be incremented at
6258 char_set_matched:, we decrement d here. */
6259 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6262 if (dend == end_match_2)
6271 len = weights[idx2];
6273 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6276 idx = (int32_t)*workp;
6277 /* We already checked idx != 0 in regex_compile. */
6279 if (idx2 != 0 && len == weights[idx])
6282 while (cnt < len && (weights[idx + 1 + cnt]
6283 == weights[idx2 + 1 + cnt]))
6287 goto char_set_matched;
6294 else /* (nrules == 0) */
6296 /* If we can't look up collation data, we use wcscoll
6299 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6301 const CHAR_T *backup_d = d, *backup_dend = dend;
6302 length = wcslen(workp);
6304 /* If wcscoll(the collating symbol, whole string) > 0,
6305 any substring of the string never match with the
6306 collating symbol. */
6307 if (wcscoll(workp, d) > 0)
6309 workp += length + 1;
6313 /* First, we compare the equivalence class with
6314 the first character of the string.
6315 If it don't match, we add the next character to
6316 the compare buffer in turn. */
6317 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6322 if (dend == end_match_2)
6328 /* add next character to the compare buffer. */
6329 str_buf[i] = TRANSLATE(*d);
6330 str_buf[i+1] = '\0';
6332 match = wcscoll(workp, str_buf);
6335 goto char_set_matched;
6338 /* (str_buf > workp) indicate (str_buf + X > workp),
6339 because for all X (str_buf + X > str_buf).
6340 So we don't need continue this loop. */
6343 /* Otherwise(str_buf < workp),
6344 (str_buf+next_character) may equals (workp).
6345 So we continue this loop. */
6350 workp += length + 1;
6354 /* match with char_range? */
6358 uint32_t collseqval;
6359 const char *collseq = (const char *)
6360 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6362 collseqval = collseq_table_lookup (collseq, c);
6364 for (; workp < p - chars_length ;)
6366 uint32_t start_val, end_val;
6368 /* We already compute the collation sequence value
6369 of the characters (or collating symbols). */
6370 start_val = (uint32_t) *workp++; /* range_start */
6371 end_val = (uint32_t) *workp++; /* range_end */
6373 if (start_val <= collseqval && collseqval <= end_val)
6374 goto char_set_matched;
6380 /* We set range_start_char at str_buf[0], range_end_char
6381 at str_buf[4], and compared char at str_buf[2]. */
6386 for (; workp < p - chars_length ;)
6388 wchar_t *range_start_char, *range_end_char;
6390 /* match if (range_start_char <= c <= range_end_char). */
6392 /* If range_start(or end) < 0, we assume -range_start(end)
6393 is the offset of the collating symbol which is specified
6394 as the character of the range start(end). */
6398 range_start_char = charset_top - (*workp++);
6401 str_buf[0] = *workp++;
6402 range_start_char = str_buf;
6407 range_end_char = charset_top - (*workp++);
6410 str_buf[4] = *workp++;
6411 range_end_char = str_buf + 4;
6414 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6415 wcscoll(str_buf+2, range_end_char) <= 0)
6417 goto char_set_matched;
6421 /* match with char? */
6422 for (; workp < p ; workp++)
6424 goto char_set_matched;
6431 /* Cast to `unsigned' instead of `unsigned char' in case the
6432 bit list is a full 32 bytes long. */
6433 if (c < (unsigned) (*p * BYTEWIDTH)
6434 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6439 if (!not) goto fail;
6440 #undef WORK_BUFFER_SIZE
6442 SET_REGS_MATCHED ();
6448 /* The beginning of a group is represented by start_memory.
6449 The arguments are the register number in the next byte, and the
6450 number of groups inner to this one in the next. The text
6451 matched within the group is recorded (in the internal
6452 registers data structure) under the register number. */
6454 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6455 (long int) *p, (long int) p[1]);
6457 /* Find out if this group can match the empty string. */
6458 p1 = p; /* To send to group_match_null_string_p. */
6460 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6461 REG_MATCH_NULL_STRING_P (reg_info[*p])
6462 = PREFIX(group_match_null_string_p) (&p1, pend, reg_info);
6464 /* Save the position in the string where we were the last time
6465 we were at this open-group operator in case the group is
6466 operated upon by a repetition operator, e.g., with `(a*)*b'
6467 against `ab'; then we want to ignore where we are now in
6468 the string in case this attempt to match fails. */
6469 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6470 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6472 DEBUG_PRINT2 (" old_regstart: %d\n",
6473 POINTER_TO_OFFSET (old_regstart[*p]));
6476 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6478 IS_ACTIVE (reg_info[*p]) = 1;
6479 MATCHED_SOMETHING (reg_info[*p]) = 0;
6481 /* Clear this whenever we change the register activity status. */
6482 set_regs_matched_done = 0;
6484 /* This is the new highest active register. */
6485 highest_active_reg = *p;
6487 /* If nothing was active before, this is the new lowest active
6489 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6490 lowest_active_reg = *p;
6492 /* Move past the register number and inner group count. */
6494 just_past_start_mem = p;
6499 /* The stop_memory opcode represents the end of a group. Its
6500 arguments are the same as start_memory's: the register
6501 number, and the number of inner groups. */
6503 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6504 (long int) *p, (long int) p[1]);
6506 /* We need to save the string position the last time we were at
6507 this close-group operator in case the group is operated
6508 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6509 against `aba'; then we want to ignore where we are now in
6510 the string in case this attempt to match fails. */
6511 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6512 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6514 DEBUG_PRINT2 (" old_regend: %d\n",
6515 POINTER_TO_OFFSET (old_regend[*p]));
6518 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6520 /* This register isn't active anymore. */
6521 IS_ACTIVE (reg_info[*p]) = 0;
6523 /* Clear this whenever we change the register activity status. */
6524 set_regs_matched_done = 0;
6526 /* If this was the only register active, nothing is active
6528 if (lowest_active_reg == highest_active_reg)
6530 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6531 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6534 { /* We must scan for the new highest active register, since
6535 it isn't necessarily one less than now: consider
6536 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6537 new highest active register is 1. */
6539 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6542 /* If we end up at register zero, that means that we saved
6543 the registers as the result of an `on_failure_jump', not
6544 a `start_memory', and we jumped to past the innermost
6545 `stop_memory'. For example, in ((.)*) we save
6546 registers 1 and 2 as a result of the *, but when we pop
6547 back to the second ), we are at the stop_memory 1.
6548 Thus, nothing is active. */
6551 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6552 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6555 highest_active_reg = r;
6558 /* If just failed to match something this time around with a
6559 group that's operated on by a repetition operator, try to
6560 force exit from the ``loop'', and restore the register
6561 information for this group that we had before trying this
6563 if ((!MATCHED_SOMETHING (reg_info[*p])
6564 || just_past_start_mem == p - 1)
6567 boolean is_a_jump_n = false;
6571 switch ((re_opcode_t) *p1++)
6575 case pop_failure_jump:
6576 case maybe_pop_jump:
6578 case dummy_failure_jump:
6579 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6581 p1 += OFFSET_ADDRESS_SIZE;
6589 /* If the next operation is a jump backwards in the pattern
6590 to an on_failure_jump right before the start_memory
6591 corresponding to this stop_memory, exit from the loop
6592 by forcing a failure after pushing on the stack the
6593 on_failure_jump's jump in the pattern, and d. */
6594 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6595 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6596 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6598 /* If this group ever matched anything, then restore
6599 what its registers were before trying this last
6600 failed match, e.g., with `(a*)*b' against `ab' for
6601 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6602 against `aba' for regend[3].
6604 Also restore the registers for inner groups for,
6605 e.g., `((a*)(b*))*' against `aba' (register 3 would
6606 otherwise get trashed). */
6608 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6612 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6614 /* Restore this and inner groups' (if any) registers. */
6615 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6618 regstart[r] = old_regstart[r];
6620 /* xx why this test? */
6621 if (old_regend[r] >= regstart[r])
6622 regend[r] = old_regend[r];
6626 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6627 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6633 /* Move past the register number and the inner group count. */
6638 /* \<digit> has been turned into a `duplicate' command which is
6639 followed by the numeric value of <digit> as the register number. */
6642 register const CHAR_T *d2, *dend2;
6643 int regno = *p++; /* Get which register to match against. */
6644 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6646 /* Can't back reference a group which we've never matched. */
6647 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6650 /* Where in input to try to start matching. */
6651 d2 = regstart[regno];
6653 /* Where to stop matching; if both the place to start and
6654 the place to stop matching are in the same string, then
6655 set to the place to stop, otherwise, for now have to use
6656 the end of the first string. */
6658 dend2 = ((FIRST_STRING_P (regstart[regno])
6659 == FIRST_STRING_P (regend[regno]))
6660 ? regend[regno] : end_match_1);
6663 /* If necessary, advance to next segment in register
6667 if (dend2 == end_match_2) break;
6668 if (dend2 == regend[regno]) break;
6670 /* End of string1 => advance to string2. */
6672 dend2 = regend[regno];
6674 /* At end of register contents => success */
6675 if (d2 == dend2) break;
6677 /* If necessary, advance to next segment in data. */
6680 /* How many characters left in this segment to match. */
6683 /* Want how many consecutive characters we can match in
6684 one shot, so, if necessary, adjust the count. */
6685 if (mcnt > dend2 - d2)
6688 /* Compare that many; failure if mismatch, else move
6691 ? PREFIX(bcmp_translate) (d, d2, mcnt, translate)
6692 : memcmp (d, d2, mcnt*sizeof(UCHAR_T)))
6694 d += mcnt, d2 += mcnt;
6696 /* Do this because we've match some characters. */
6697 SET_REGS_MATCHED ();
6703 /* begline matches the empty string at the beginning of the string
6704 (unless `not_bol' is set in `bufp'), and, if
6705 `newline_anchor' is set, after newlines. */
6707 DEBUG_PRINT1 ("EXECUTING begline.\n");
6709 if (AT_STRINGS_BEG (d))
6711 if (!bufp->not_bol) break;
6713 else if (d[-1] == '\n' && bufp->newline_anchor)
6717 /* In all other cases, we fail. */
6721 /* endline is the dual of begline. */
6723 DEBUG_PRINT1 ("EXECUTING endline.\n");
6725 if (AT_STRINGS_END (d))
6727 if (!bufp->not_eol) break;
6730 /* We have to ``prefetch'' the next character. */
6731 else if ((d == end1 ? *string2 : *d) == '\n'
6732 && bufp->newline_anchor)
6739 /* Match at the very beginning of the data. */
6741 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6742 if (AT_STRINGS_BEG (d))
6747 /* Match at the very end of the data. */
6749 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6750 if (AT_STRINGS_END (d))
6755 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6756 pushes NULL as the value for the string on the stack. Then
6757 `pop_failure_point' will keep the current value for the
6758 string, instead of restoring it. To see why, consider
6759 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6760 then the . fails against the \n. But the next thing we want
6761 to do is match the \n against the \n; if we restored the
6762 string value, we would be back at the foo.
6764 Because this is used only in specific cases, we don't need to
6765 check all the things that `on_failure_jump' does, to make
6766 sure the right things get saved on the stack. Hence we don't
6767 share its code. The only reason to push anything on the
6768 stack at all is that otherwise we would have to change
6769 `anychar's code to do something besides goto fail in this
6770 case; that seems worse than this. */
6771 case on_failure_keep_string_jump:
6772 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6774 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6776 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6778 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6781 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6785 /* Uses of on_failure_jump:
6787 Each alternative starts with an on_failure_jump that points
6788 to the beginning of the next alternative. Each alternative
6789 except the last ends with a jump that in effect jumps past
6790 the rest of the alternatives. (They really jump to the
6791 ending jump of the following alternative, because tensioning
6792 these jumps is a hassle.)
6794 Repeats start with an on_failure_jump that points past both
6795 the repetition text and either the following jump or
6796 pop_failure_jump back to this on_failure_jump. */
6797 case on_failure_jump:
6799 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6801 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6803 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6805 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6808 /* If this on_failure_jump comes right before a group (i.e.,
6809 the original * applied to a group), save the information
6810 for that group and all inner ones, so that if we fail back
6811 to this point, the group's information will be correct.
6812 For example, in \(a*\)*\1, we need the preceding group,
6813 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6815 /* We can't use `p' to check ahead because we push
6816 a failure point to `p + mcnt' after we do this. */
6819 /* We need to skip no_op's before we look for the
6820 start_memory in case this on_failure_jump is happening as
6821 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6823 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6826 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6828 /* We have a new highest active register now. This will
6829 get reset at the start_memory we are about to get to,
6830 but we will have saved all the registers relevant to
6831 this repetition op, as described above. */
6832 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6833 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6834 lowest_active_reg = *(p1 + 1);
6837 DEBUG_PRINT1 (":\n");
6838 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6842 /* A smart repeat ends with `maybe_pop_jump'.
6843 We change it to either `pop_failure_jump' or `jump'. */
6844 case maybe_pop_jump:
6845 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6846 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6848 register UCHAR_T *p2 = p;
6850 /* Compare the beginning of the repeat with what in the
6851 pattern follows its end. If we can establish that there
6852 is nothing that they would both match, i.e., that we
6853 would have to backtrack because of (as in, e.g., `a*a')
6854 then we can change to pop_failure_jump, because we'll
6855 never have to backtrack.
6857 This is not true in the case of alternatives: in
6858 `(a|ab)*' we do need to backtrack to the `ab' alternative
6859 (e.g., if the string was `ab'). But instead of trying to
6860 detect that here, the alternative has put on a dummy
6861 failure point which is what we will end up popping. */
6863 /* Skip over open/close-group commands.
6864 If what follows this loop is a ...+ construct,
6865 look at what begins its body, since we will have to
6866 match at least one of that. */
6870 && ((re_opcode_t) *p2 == stop_memory
6871 || (re_opcode_t) *p2 == start_memory))
6873 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6874 && (re_opcode_t) *p2 == dummy_failure_jump)
6875 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6881 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
6882 to the `maybe_finalize_jump' of this case. Examine what
6885 /* If we're at the end of the pattern, we can change. */
6888 /* Consider what happens when matching ":\(.*\)"
6889 against ":/". I don't really understand this code
6891 p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
6894 (" End of pattern: change to `pop_failure_jump'.\n");
6897 else if ((re_opcode_t) *p2 == exactn
6899 || (re_opcode_t) *p2 == exactn_bin
6901 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
6904 = *p2 == (UCHAR_T) endline ? '\n' : p2[2];
6906 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
6908 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
6910 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
6912 p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
6915 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
6917 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
6919 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
6921 (char) p1[3+OFFSET_ADDRESS_SIZE]);
6926 else if ((re_opcode_t) p1[3] == charset
6927 || (re_opcode_t) p1[3] == charset_not)
6929 int not = (re_opcode_t) p1[3] == charset_not;
6931 if (c < (unsigned) (p1[4] * BYTEWIDTH)
6932 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6935 /* `not' is equal to 1 if c would match, which means
6936 that we can't change to pop_failure_jump. */
6939 p[-3] = (unsigned char) pop_failure_jump;
6940 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6943 #endif /* not WCHAR */
6946 else if ((re_opcode_t) *p2 == charset)
6948 /* We win if the first character of the loop is not part
6950 if ((re_opcode_t) p1[3] == exactn
6951 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
6952 && (p2[2 + p1[5] / BYTEWIDTH]
6953 & (1 << (p1[5] % BYTEWIDTH)))))
6955 p[-3] = (unsigned char) pop_failure_jump;
6956 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6959 else if ((re_opcode_t) p1[3] == charset_not)
6962 /* We win if the charset_not inside the loop
6963 lists every character listed in the charset after. */
6964 for (idx = 0; idx < (int) p2[1]; idx++)
6965 if (! (p2[2 + idx] == 0
6966 || (idx < (int) p1[4]
6967 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
6972 p[-3] = (unsigned char) pop_failure_jump;
6973 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6976 else if ((re_opcode_t) p1[3] == charset)
6979 /* We win if the charset inside the loop
6980 has no overlap with the one after the loop. */
6982 idx < (int) p2[1] && idx < (int) p1[4];
6984 if ((p2[2 + idx] & p1[5 + idx]) != 0)
6987 if (idx == p2[1] || idx == p1[4])
6989 p[-3] = (unsigned char) pop_failure_jump;
6990 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6994 #endif /* not WCHAR */
6996 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
6997 if ((re_opcode_t) p[-1] != pop_failure_jump)
6999 p[-1] = (UCHAR_T) jump;
7000 DEBUG_PRINT1 (" Match => jump.\n");
7001 goto unconditional_jump;
7003 /* Note fall through. */
7006 /* The end of a simple repeat has a pop_failure_jump back to
7007 its matching on_failure_jump, where the latter will push a
7008 failure point. The pop_failure_jump takes off failure
7009 points put on by this pop_failure_jump's matching
7010 on_failure_jump; we got through the pattern to here from the
7011 matching on_failure_jump, so didn't fail. */
7012 case pop_failure_jump:
7014 /* We need to pass separate storage for the lowest and
7015 highest registers, even though we don't care about the
7016 actual values. Otherwise, we will restore only one
7017 register from the stack, since lowest will == highest in
7018 `pop_failure_point'. */
7019 active_reg_t dummy_low_reg, dummy_high_reg;
7020 UCHAR_T *pdummy = NULL;
7021 const CHAR_T *sdummy = NULL;
7023 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
7024 POP_FAILURE_POINT (sdummy, pdummy,
7025 dummy_low_reg, dummy_high_reg,
7026 reg_dummy, reg_dummy, reg_info_dummy);
7028 /* Note fall through. */
7032 DEBUG_PRINT2 ("\n%p: ", p);
7034 DEBUG_PRINT2 ("\n0x%x: ", p);
7036 /* Note fall through. */
7038 /* Unconditionally jump (without popping any failure points). */
7040 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
7041 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
7042 p += mcnt; /* Do the jump. */
7044 DEBUG_PRINT2 ("(to %p).\n", p);
7046 DEBUG_PRINT2 ("(to 0x%x).\n", p);
7051 /* We need this opcode so we can detect where alternatives end
7052 in `group_match_null_string_p' et al. */
7054 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
7055 goto unconditional_jump;
7058 /* Normally, the on_failure_jump pushes a failure point, which
7059 then gets popped at pop_failure_jump. We will end up at
7060 pop_failure_jump, also, and with a pattern of, say, `a+', we
7061 are skipping over the on_failure_jump, so we have to push
7062 something meaningless for pop_failure_jump to pop. */
7063 case dummy_failure_jump:
7064 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
7065 /* It doesn't matter what we push for the string here. What
7066 the code at `fail' tests is the value for the pattern. */
7067 PUSH_FAILURE_POINT (NULL, NULL, -2);
7068 goto unconditional_jump;
7071 /* At the end of an alternative, we need to push a dummy failure
7072 point in case we are followed by a `pop_failure_jump', because
7073 we don't want the failure point for the alternative to be
7074 popped. For example, matching `(a|ab)*' against `aab'
7075 requires that we match the `ab' alternative. */
7076 case push_dummy_failure:
7077 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
7078 /* See comments just above at `dummy_failure_jump' about the
7080 PUSH_FAILURE_POINT (NULL, NULL, -2);
7083 /* Have to succeed matching what follows at least n times.
7084 After that, handle like `on_failure_jump'. */
7086 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7087 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
7090 /* Originally, this is how many times we HAVE to succeed. */
7094 p += OFFSET_ADDRESS_SIZE;
7095 STORE_NUMBER_AND_INCR (p, mcnt);
7097 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
7100 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
7107 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
7108 p + OFFSET_ADDRESS_SIZE);
7110 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
7111 p + OFFSET_ADDRESS_SIZE);
7115 p[1] = (UCHAR_T) no_op;
7117 p[2] = (UCHAR_T) no_op;
7118 p[3] = (UCHAR_T) no_op;
7125 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7126 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7128 /* Originally, this is how many times we CAN jump. */
7132 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7135 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7138 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7141 goto unconditional_jump;
7143 /* If don't have to jump any more, skip over the rest of command. */
7145 p += 2 * OFFSET_ADDRESS_SIZE;
7150 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7152 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7154 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7156 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7158 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7160 STORE_NUMBER (p1, mcnt);
7165 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7166 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7167 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7168 macro and introducing temporary variables works around the bug. */
7171 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7172 if (AT_WORD_BOUNDARY (d))
7177 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7178 if (AT_WORD_BOUNDARY (d))
7184 boolean prevchar, thischar;
7186 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7187 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7190 prevchar = WORDCHAR_P (d - 1);
7191 thischar = WORDCHAR_P (d);
7192 if (prevchar != thischar)
7199 boolean prevchar, thischar;
7201 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7202 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7205 prevchar = WORDCHAR_P (d - 1);
7206 thischar = WORDCHAR_P (d);
7207 if (prevchar != thischar)
7214 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7215 if (!AT_STRINGS_END (d) && WORDCHAR_P (d)
7216 && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7221 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7222 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7223 && (AT_STRINGS_END (d) || !WORDCHAR_P (d)))
7229 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7230 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7235 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7236 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7241 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7242 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7247 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7252 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7256 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7258 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7260 SET_REGS_MATCHED ();
7264 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7266 goto matchnotsyntax;
7269 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7273 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7275 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7277 SET_REGS_MATCHED ();
7280 #else /* not emacs */
7282 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7284 if (!WORDCHAR_P (d))
7286 SET_REGS_MATCHED ();
7291 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7295 SET_REGS_MATCHED ();
7298 #endif /* not emacs */
7303 continue; /* Successfully executed one pattern command; keep going. */
7306 /* We goto here if a matching operation fails. */
7308 if (!FAIL_STACK_EMPTY ())
7309 { /* A restart point is known. Restore to that state. */
7310 DEBUG_PRINT1 ("\nFAIL:\n");
7311 POP_FAILURE_POINT (d, p,
7312 lowest_active_reg, highest_active_reg,
7313 regstart, regend, reg_info);
7315 /* If this failure point is a dummy, try the next one. */
7319 /* If we failed to the end of the pattern, don't examine *p. */
7323 boolean is_a_jump_n = false;
7325 /* If failed to a backwards jump that's part of a repetition
7326 loop, need to pop this failure point and use the next one. */
7327 switch ((re_opcode_t) *p)
7331 case maybe_pop_jump:
7332 case pop_failure_jump:
7335 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7338 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7340 && (re_opcode_t) *p1 == on_failure_jump))
7348 if (d >= string1 && d <= end1)
7352 break; /* Matching at this starting point really fails. */
7356 goto restore_best_regs;
7360 return -1; /* Failure to match. */
7363 /* Subroutine definitions for re_match_2. */
7366 /* We are passed P pointing to a register number after a start_memory.
7368 Return true if the pattern up to the corresponding stop_memory can
7369 match the empty string, and false otherwise.
7371 If we find the matching stop_memory, sets P to point to one past its number.
7372 Otherwise, sets P to an undefined byte less than or equal to END.
7374 We don't handle duplicates properly (yet). */
7377 PREFIX(group_match_null_string_p) (p, end, reg_info)
7379 PREFIX(register_info_type) *reg_info;
7382 /* Point to after the args to the start_memory. */
7383 UCHAR_T *p1 = *p + 2;
7387 /* Skip over opcodes that can match nothing, and return true or
7388 false, as appropriate, when we get to one that can't, or to the
7389 matching stop_memory. */
7391 switch ((re_opcode_t) *p1)
7393 /* Could be either a loop or a series of alternatives. */
7394 case on_failure_jump:
7396 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7398 /* If the next operation is not a jump backwards in the
7403 /* Go through the on_failure_jumps of the alternatives,
7404 seeing if any of the alternatives cannot match nothing.
7405 The last alternative starts with only a jump,
7406 whereas the rest start with on_failure_jump and end
7407 with a jump, e.g., here is the pattern for `a|b|c':
7409 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7410 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7413 So, we have to first go through the first (n-1)
7414 alternatives and then deal with the last one separately. */
7417 /* Deal with the first (n-1) alternatives, which start
7418 with an on_failure_jump (see above) that jumps to right
7419 past a jump_past_alt. */
7421 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7424 /* `mcnt' holds how many bytes long the alternative
7425 is, including the ending `jump_past_alt' and
7428 if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt -
7429 (1 + OFFSET_ADDRESS_SIZE),
7433 /* Move to right after this alternative, including the
7437 /* Break if it's the beginning of an n-th alternative
7438 that doesn't begin with an on_failure_jump. */
7439 if ((re_opcode_t) *p1 != on_failure_jump)
7442 /* Still have to check that it's not an n-th
7443 alternative that starts with an on_failure_jump. */
7445 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7446 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7449 /* Get to the beginning of the n-th alternative. */
7450 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7455 /* Deal with the last alternative: go back and get number
7456 of the `jump_past_alt' just before it. `mcnt' contains
7457 the length of the alternative. */
7458 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7460 if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt, reg_info))
7463 p1 += mcnt; /* Get past the n-th alternative. */
7469 assert (p1[1] == **p);
7475 if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7478 } /* while p1 < end */
7481 } /* group_match_null_string_p */
7484 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7485 It expects P to be the first byte of a single alternative and END one
7486 byte past the last. The alternative can contain groups. */
7489 PREFIX(alt_match_null_string_p) (p, end, reg_info)
7491 PREFIX(register_info_type) *reg_info;
7498 /* Skip over opcodes that can match nothing, and break when we get
7499 to one that can't. */
7501 switch ((re_opcode_t) *p1)
7504 case on_failure_jump:
7506 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7511 if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7514 } /* while p1 < end */
7517 } /* alt_match_null_string_p */
7520 /* Deals with the ops common to group_match_null_string_p and
7521 alt_match_null_string_p.
7523 Sets P to one after the op and its arguments, if any. */
7526 PREFIX(common_op_match_null_string_p) (p, end, reg_info)
7528 PREFIX(register_info_type) *reg_info;
7535 switch ((re_opcode_t) *p1++)
7555 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7556 ret = PREFIX(group_match_null_string_p) (&p1, end, reg_info);
7558 /* Have to set this here in case we're checking a group which
7559 contains a group and a back reference to it. */
7561 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7562 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7568 /* If this is an optimized succeed_n for zero times, make the jump. */
7570 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7578 /* Get to the number of times to succeed. */
7579 p1 += OFFSET_ADDRESS_SIZE;
7580 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7584 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7585 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7593 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7598 p1 += 2 * OFFSET_ADDRESS_SIZE;
7601 /* All other opcodes mean we cannot match the empty string. */
7607 } /* common_op_match_null_string_p */
7610 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7611 bytes; nonzero otherwise. */
7614 PREFIX(bcmp_translate) (s1, s2, len, translate)
7615 const CHAR_T *s1, *s2;
7617 RE_TRANSLATE_TYPE translate;
7619 register const UCHAR_T *p1 = (const UCHAR_T *) s1;
7620 register const UCHAR_T *p2 = (const UCHAR_T *) s2;
7624 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7625 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7628 if (translate[*p1++] != translate[*p2++]) return 1;
7636 #else /* not INSIDE_RECURSION */
7638 /* Entry points for GNU code. */
7640 /* re_compile_pattern is the GNU regular expression compiler: it
7641 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7642 Returns 0 if the pattern was valid, otherwise an error string.
7644 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7645 are set in BUFP on entry.
7647 We call regex_compile to do the actual compilation. */
7650 re_compile_pattern (pattern, length, bufp)
7651 const char *pattern;
7653 struct re_pattern_buffer *bufp;
7657 /* GNU code is written to assume at least RE_NREGS registers will be set
7658 (and at least one extra will be -1). */
7659 bufp->regs_allocated = REGS_UNALLOCATED;
7661 /* And GNU code determines whether or not to get register information
7662 by passing null for the REGS argument to re_match, etc., not by
7666 /* Match anchors at newline. */
7667 bufp->newline_anchor = 1;
7670 if (MB_CUR_MAX != 1)
7671 ret = wcs_regex_compile (pattern, length, re_syntax_options, bufp);
7674 ret = byte_regex_compile (pattern, length, re_syntax_options, bufp);
7678 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7681 weak_alias (__re_compile_pattern, re_compile_pattern)
7684 /* Entry points compatible with 4.2 BSD regex library. We don't define
7685 them unless specifically requested. */
7687 #if defined _REGEX_RE_COMP || defined _LIBC
7689 /* BSD has one and only one pattern buffer. */
7690 static struct re_pattern_buffer re_comp_buf;
7694 /* Make these definitions weak in libc, so POSIX programs can redefine
7695 these names if they don't use our functions, and still use
7696 regcomp/regexec below without link errors. */
7706 if (!re_comp_buf.buffer)
7707 return gettext ("No previous regular expression");
7711 if (!re_comp_buf.buffer)
7713 re_comp_buf.buffer = (unsigned char *) malloc (200);
7714 if (re_comp_buf.buffer == NULL)
7715 return (char *) gettext (re_error_msgid
7716 + re_error_msgid_idx[(int) REG_ESPACE]);
7717 re_comp_buf.allocated = 200;
7719 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7720 if (re_comp_buf.fastmap == NULL)
7721 return (char *) gettext (re_error_msgid
7722 + re_error_msgid_idx[(int) REG_ESPACE]);
7725 /* Since `re_exec' always passes NULL for the `regs' argument, we
7726 don't need to initialize the pattern buffer fields which affect it. */
7728 /* Match anchors at newlines. */
7729 re_comp_buf.newline_anchor = 1;
7732 if (MB_CUR_MAX != 1)
7733 ret = wcs_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7736 ret = byte_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7741 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7742 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7753 const int len = strlen (s);
7755 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7758 #endif /* _REGEX_RE_COMP */
7760 /* POSIX.2 functions. Don't define these for Emacs. */
7764 /* regcomp takes a regular expression as a string and compiles it.
7766 PREG is a regex_t *. We do not expect any fields to be initialized,
7767 since POSIX says we shouldn't. Thus, we set
7769 `buffer' to the compiled pattern;
7770 `used' to the length of the compiled pattern;
7771 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7772 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7773 RE_SYNTAX_POSIX_BASIC;
7774 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7775 `fastmap' to an allocated space for the fastmap;
7776 `fastmap_accurate' to zero;
7777 `re_nsub' to the number of subexpressions in PATTERN.
7779 PATTERN is the address of the pattern string.
7781 CFLAGS is a series of bits which affect compilation.
7783 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7784 use POSIX basic syntax.
7786 If REG_NEWLINE is set, then . and [^...] don't match newline.
7787 Also, regexec will try a match beginning after every newline.
7789 If REG_ICASE is set, then we considers upper- and lowercase
7790 versions of letters to be equivalent when matching.
7792 If REG_NOSUB is set, then when PREG is passed to regexec, that
7793 routine will report only success or failure, and nothing about the
7796 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7797 the return codes and their meanings.) */
7800 regcomp (preg, pattern, cflags)
7802 const char *pattern;
7807 = (cflags & REG_EXTENDED) ?
7808 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7810 /* regex_compile will allocate the space for the compiled pattern. */
7812 preg->allocated = 0;
7815 /* Try to allocate space for the fastmap. */
7816 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7818 if (cflags & REG_ICASE)
7823 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7824 * sizeof (*(RE_TRANSLATE_TYPE)0));
7825 if (preg->translate == NULL)
7826 return (int) REG_ESPACE;
7828 /* Map uppercase characters to corresponding lowercase ones. */
7829 for (i = 0; i < CHAR_SET_SIZE; i++)
7830 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7833 preg->translate = NULL;
7835 /* If REG_NEWLINE is set, newlines are treated differently. */
7836 if (cflags & REG_NEWLINE)
7837 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7838 syntax &= ~RE_DOT_NEWLINE;
7839 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7840 /* It also changes the matching behavior. */
7841 preg->newline_anchor = 1;
7844 preg->newline_anchor = 0;
7846 preg->no_sub = !!(cflags & REG_NOSUB);
7848 /* POSIX says a null character in the pattern terminates it, so we
7849 can use strlen here in compiling the pattern. */
7851 if (MB_CUR_MAX != 1)
7852 ret = wcs_regex_compile (pattern, strlen (pattern), syntax, preg);
7855 ret = byte_regex_compile (pattern, strlen (pattern), syntax, preg);
7857 /* POSIX doesn't distinguish between an unmatched open-group and an
7858 unmatched close-group: both are REG_EPAREN. */
7859 if (ret == REG_ERPAREN) ret = REG_EPAREN;
7861 if (ret == REG_NOERROR && preg->fastmap)
7863 /* Compute the fastmap now, since regexec cannot modify the pattern
7865 if (re_compile_fastmap (preg) == -2)
7867 /* Some error occurred while computing the fastmap, just forget
7869 free (preg->fastmap);
7870 preg->fastmap = NULL;
7877 weak_alias (__regcomp, regcomp)
7881 /* regexec searches for a given pattern, specified by PREG, in the
7884 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7885 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
7886 least NMATCH elements, and we set them to the offsets of the
7887 corresponding matched substrings.
7889 EFLAGS specifies `execution flags' which affect matching: if
7890 REG_NOTBOL is set, then ^ does not match at the beginning of the
7891 string; if REG_NOTEOL is set, then $ does not match at the end.
7893 We return 0 if we find a match and REG_NOMATCH if not. */
7896 regexec (preg, string, nmatch, pmatch, eflags)
7897 const regex_t *preg;
7900 regmatch_t pmatch[];
7904 struct re_registers regs;
7905 regex_t private_preg;
7906 int len = strlen (string);
7907 boolean want_reg_info = !preg->no_sub && nmatch > 0;
7909 private_preg = *preg;
7911 private_preg.not_bol = !!(eflags & REG_NOTBOL);
7912 private_preg.not_eol = !!(eflags & REG_NOTEOL);
7914 /* The user has told us exactly how many registers to return
7915 information about, via `nmatch'. We have to pass that on to the
7916 matching routines. */
7917 private_preg.regs_allocated = REGS_FIXED;
7921 regs.num_regs = nmatch;
7922 regs.start = TALLOC (nmatch * 2, regoff_t);
7923 if (regs.start == NULL)
7924 return (int) REG_NOMATCH;
7925 regs.end = regs.start + nmatch;
7928 /* Perform the searching operation. */
7929 ret = re_search (&private_preg, string, len,
7930 /* start: */ 0, /* range: */ len,
7931 want_reg_info ? ®s : (struct re_registers *) 0);
7933 /* Copy the register information to the POSIX structure. */
7940 for (r = 0; r < nmatch; r++)
7942 pmatch[r].rm_so = regs.start[r];
7943 pmatch[r].rm_eo = regs.end[r];
7947 /* If we needed the temporary register info, free the space now. */
7951 /* We want zero return to mean success, unlike `re_search'. */
7952 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
7955 weak_alias (__regexec, regexec)
7959 /* Returns a message corresponding to an error code, ERRCODE, returned
7960 from either regcomp or regexec. We don't use PREG here. */
7963 regerror (errcode, preg, errbuf, errbuf_size)
7965 const regex_t *preg;
7973 || errcode >= (int) (sizeof (re_error_msgid_idx)
7974 / sizeof (re_error_msgid_idx[0])))
7975 /* Only error codes returned by the rest of the code should be passed
7976 to this routine. If we are given anything else, or if other regex
7977 code generates an invalid error code, then the program has a bug.
7978 Dump core so we can fix it. */
7981 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
7983 msg_size = strlen (msg) + 1; /* Includes the null. */
7985 if (errbuf_size != 0)
7987 if (msg_size > errbuf_size)
7989 #if defined HAVE_MEMPCPY || defined _LIBC
7990 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
7992 memcpy (errbuf, msg, errbuf_size - 1);
7993 errbuf[errbuf_size - 1] = 0;
7997 memcpy (errbuf, msg, msg_size);
8003 weak_alias (__regerror, regerror)
8007 /* Free dynamically allocated space used by PREG. */
8013 if (preg->buffer != NULL)
8014 free (preg->buffer);
8015 preg->buffer = NULL;
8017 preg->allocated = 0;
8020 if (preg->fastmap != NULL)
8021 free (preg->fastmap);
8022 preg->fastmap = NULL;
8023 preg->fastmap_accurate = 0;
8025 if (preg->translate != NULL)
8026 free (preg->translate);
8027 preg->translate = NULL;
8030 weak_alias (__regfree, regfree)
8033 #endif /* not emacs */
8035 #endif /* not INSIDE_RECURSION */
8039 #undef STORE_NUMBER_AND_INCR
8040 #undef EXTRACT_NUMBER
8041 #undef EXTRACT_NUMBER_AND_INCR
8043 #undef DEBUG_PRINT_COMPILED_PATTERN
8044 #undef DEBUG_PRINT_DOUBLE_STRING
8046 #undef INIT_FAIL_STACK
8047 #undef RESET_FAIL_STACK
8048 #undef DOUBLE_FAIL_STACK
8049 #undef PUSH_PATTERN_OP
8050 #undef PUSH_FAILURE_POINTER
8051 #undef PUSH_FAILURE_INT
8052 #undef PUSH_FAILURE_ELT
8053 #undef POP_FAILURE_POINTER
8054 #undef POP_FAILURE_INT
8055 #undef POP_FAILURE_ELT
8058 #undef PUSH_FAILURE_POINT
8059 #undef POP_FAILURE_POINT
8061 #undef REG_UNSET_VALUE
8069 #undef INIT_BUF_SIZE
8070 #undef GET_BUFFER_SPACE
8078 #undef EXTEND_BUFFER
8079 #undef GET_UNSIGNED_NUMBER
8080 #undef FREE_STACK_RETURN
8082 # undef POINTER_TO_OFFSET
8083 # undef MATCHING_IN_FRST_STRING
8085 # undef AT_STRINGS_BEG
8086 # undef AT_STRINGS_END
8089 # undef FREE_VARIABLES
8090 # undef NO_HIGHEST_ACTIVE_REG
8091 # undef NO_LOWEST_ACTIVE_REG
8095 # undef COMPILED_BUFFER_VAR
8096 # undef OFFSET_ADDRESS_SIZE
8097 # undef CHAR_CLASS_SIZE
8104 # define DEFINED_ONCE