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 #if defined STDC_HEADERS && !defined emacs
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
49 #define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
51 /* For platform which support the ISO C amendement 1 functionality we
52 support user defined character classes. */
53 #if defined _LIBC || WIDE_CHAR_SUPPORT
54 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
59 /* This is for multi byte string support. */
61 # define CHAR_TYPE wchar_t
62 # define US_CHAR_TYPE wchar_t/* unsigned character type */
63 # define COMPILED_BUFFER_VAR wc_buffer
64 # define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
65 # define CHAR_CLASS_SIZE ((__alignof__(wctype_t)+sizeof(wctype_t))/sizeof(CHAR_TYPE)+1)
66 # define PUT_CHAR(c) \
68 if (MB_CUR_MAX == 1) \
71 printf ("%C", (wint_t) c); /* Should we use wide stream?? */ \
76 # define CHAR_TYPE char
77 # define US_CHAR_TYPE unsigned char /* unsigned character type */
78 # define COMPILED_BUFFER_VAR bufp->buffer
79 # define OFFSET_ADDRESS_SIZE 2
80 # define PUT_CHAR(c) putchar (c)
81 #endif /* MBS_SUPPORT */
84 /* We have to keep the namespace clean. */
85 # define regfree(preg) __regfree (preg)
86 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
87 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
88 # define regerror(errcode, preg, errbuf, errbuf_size) \
89 __regerror(errcode, preg, errbuf, errbuf_size)
90 # define re_set_registers(bu, re, nu, st, en) \
91 __re_set_registers (bu, re, nu, st, en)
92 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
93 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
94 # define re_match(bufp, string, size, pos, regs) \
95 __re_match (bufp, string, size, pos, regs)
96 # define re_search(bufp, string, size, startpos, range, regs) \
97 __re_search (bufp, string, size, startpos, range, regs)
98 # define re_compile_pattern(pattern, length, bufp) \
99 __re_compile_pattern (pattern, length, bufp)
100 # define re_set_syntax(syntax) __re_set_syntax (syntax)
101 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
102 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
103 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
105 # define btowc __btowc
107 /* We are also using some library internals. */
108 # include <locale/localeinfo.h>
109 # include <locale/elem-hash.h>
110 # include <langinfo.h>
111 # include <locale/coll-lookup.h>
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
119 # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
122 # define gettext(msgid) (msgid)
126 /* This define is so xgettext can find the internationalizable
128 # define gettext_noop(String) String
131 /* The `emacs' switch turns on certain matching commands
132 that make sense only in Emacs. */
139 #else /* not emacs */
141 /* If we are not linking with Emacs proper,
142 we can't use the relocating allocator
143 even if config.h says that we can. */
146 # if defined STDC_HEADERS || defined _LIBC
153 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
154 If nothing else has been done, use the method below. */
155 # ifdef INHIBIT_STRING_HEADER
156 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
157 # if !defined bzero && !defined bcopy
158 # undef INHIBIT_STRING_HEADER
163 /* This is the normal way of making sure we have a bcopy and a bzero.
164 This is used in most programs--a few other programs avoid this
165 by defining INHIBIT_STRING_HEADER. */
166 # ifndef INHIBIT_STRING_HEADER
167 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
171 # define bzero(s, n) (memset (s, '\0', n), (s))
173 # define bzero(s, n) __bzero (s, n)
177 # include <strings.h>
179 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
182 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
187 /* Define the syntax stuff for \<, \>, etc. */
189 /* This must be nonzero for the wordchar and notwordchar pattern
190 commands in re_match_2. */
195 # ifdef SWITCH_ENUM_BUG
196 # define SWITCH_ENUM_CAST(x) ((int)(x))
198 # define SWITCH_ENUM_CAST(x) (x)
201 #endif /* not emacs */
203 #if defined _LIBC || HAVE_LIMITS_H
208 # define MB_LEN_MAX 1
211 /* Get the interface, including the syntax bits. */
214 /* isalpha etc. are used for the character classes. */
217 /* Jim Meyering writes:
219 "... Some ctype macros are valid only for character codes that
220 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
221 using /bin/cc or gcc but without giving an ansi option). So, all
222 ctype uses should be through macros like ISPRINT... If
223 STDC_HEADERS is defined, then autoconf has verified that the ctype
224 macros don't need to be guarded with references to isascii. ...
225 Defining isascii to 1 should let any compiler worth its salt
226 eliminate the && through constant folding."
227 Solaris defines some of these symbols so we must undefine them first. */
229 #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
230 # define IN_CTYPE_DOMAIN(c) 1
232 # define IN_CTYPE_DOMAIN(c) isascii(c)
236 # define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
238 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
241 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
243 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
247 #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
248 #define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
249 #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
250 #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
251 #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
252 #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
253 #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
254 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
255 #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
256 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
259 # define TOLOWER(c) _tolower(c)
261 # define TOLOWER(c) tolower(c)
265 # define NULL (void *)0
268 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
269 since ours (we hope) works properly with all combinations of
270 machines, compilers, `char' and `unsigned char' argument types.
271 (Per Bothner suggested the basic approach.) */
272 #undef SIGN_EXTEND_CHAR
274 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
275 #else /* not __STDC__ */
276 /* As in Harbison and Steele. */
277 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
281 /* How many characters in the character set. */
282 # define CHAR_SET_SIZE 256
286 extern char *re_syntax_table;
288 # else /* not SYNTAX_TABLE */
290 static char re_syntax_table[CHAR_SET_SIZE];
292 static void init_syntax_once PARAMS ((void));
302 bzero (re_syntax_table, sizeof re_syntax_table);
304 for (c = 0; c < CHAR_SET_SIZE; ++c)
306 re_syntax_table[c] = Sword;
308 re_syntax_table['_'] = Sword;
313 # endif /* not SYNTAX_TABLE */
315 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
319 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
320 use `alloca' instead of `malloc'. This is because using malloc in
321 re_search* or re_match* could cause memory leaks when C-g is used in
322 Emacs; also, malloc is slower and causes storage fragmentation. On
323 the other hand, malloc is more portable, and easier to debug.
325 Because we sometimes use alloca, some routines have to be macros,
326 not functions -- `alloca'-allocated space disappears at the end of the
327 function it is called in. */
331 # define REGEX_ALLOCATE malloc
332 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
333 # define REGEX_FREE free
335 #else /* not REGEX_MALLOC */
337 /* Emacs already defines alloca, sometimes. */
340 /* Make alloca work the best possible way. */
342 # define alloca __builtin_alloca
343 # else /* not __GNUC__ */
346 # endif /* HAVE_ALLOCA_H */
347 # endif /* not __GNUC__ */
349 # endif /* not alloca */
351 # define REGEX_ALLOCATE alloca
353 /* Assumes a `char *destination' variable. */
354 # define REGEX_REALLOCATE(source, osize, nsize) \
355 (destination = (char *) alloca (nsize), \
356 memcpy (destination, source, osize))
358 /* No need to do anything to free, after alloca. */
359 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
361 #endif /* not REGEX_MALLOC */
363 /* Define how to allocate the failure stack. */
365 #if defined REL_ALLOC && defined REGEX_MALLOC
367 # define REGEX_ALLOCATE_STACK(size) \
368 r_alloc (&failure_stack_ptr, (size))
369 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
370 r_re_alloc (&failure_stack_ptr, (nsize))
371 # define REGEX_FREE_STACK(ptr) \
372 r_alloc_free (&failure_stack_ptr)
374 #else /* not using relocating allocator */
378 # define REGEX_ALLOCATE_STACK malloc
379 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
380 # define REGEX_FREE_STACK free
382 # else /* not REGEX_MALLOC */
384 # define REGEX_ALLOCATE_STACK alloca
386 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
387 REGEX_REALLOCATE (source, osize, nsize)
388 /* No need to explicitly free anything. */
389 # define REGEX_FREE_STACK(arg)
391 # endif /* not REGEX_MALLOC */
392 #endif /* not using relocating allocator */
395 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
396 `string1' or just past its end. This works if PTR is NULL, which is
398 #define FIRST_STRING_P(ptr) \
399 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
401 /* (Re)Allocate N items of type T using malloc, or fail. */
402 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
403 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
404 #define RETALLOC_IF(addr, n, t) \
405 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
406 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
408 #define BYTEWIDTH 8 /* In bits. */
410 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
414 #define MAX(a, b) ((a) > (b) ? (a) : (b))
415 #define MIN(a, b) ((a) < (b) ? (a) : (b))
417 typedef char boolean;
421 static int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
422 const char *string1, int size1,
423 const char *string2, int size2,
425 struct re_registers *regs,
428 /* These are the command codes that appear in compiled regular
429 expressions. Some opcodes are followed by argument bytes. A
430 command code can specify any interpretation whatsoever for its
431 arguments. Zero bytes may appear in the compiled regular expression. */
437 /* Succeed right away--no more backtracking. */
440 /* Followed by one byte giving n, then by n literal bytes. */
444 /* Same as exactn, but contains binary data. */
448 /* Matches any (more or less) character. */
451 /* Matches any one char belonging to specified set. First
452 following byte is number of bitmap bytes. Then come bytes
453 for a bitmap saying which chars are in. Bits in each byte
454 are ordered low-bit-first. A character is in the set if its
455 bit is 1. A character too large to have a bit in the map is
456 automatically not in the set. */
457 /* ifdef MBS_SUPPORT, following element is length of character
458 classes, length of collating symbols, length of equivalence
459 classes, length of character ranges, and length of characters.
460 Next, character class element, collating symbols elements,
461 equivalence class elements, range elements, and character
463 See regex_compile function. */
466 /* Same parameters as charset, but match any character that is
467 not one of those specified. */
470 /* Start remembering the text that is matched, for storing in a
471 register. Followed by one byte with the register number, in
472 the range 0 to one less than the pattern buffer's re_nsub
473 field. Then followed by one byte with the number of groups
474 inner to this one. (This last has to be part of the
475 start_memory only because we need it in the on_failure_jump
479 /* Stop remembering the text that is matched and store it in a
480 memory register. Followed by one byte with the register
481 number, in the range 0 to one less than `re_nsub' in the
482 pattern buffer, and one byte with the number of inner groups,
483 just like `start_memory'. (We need the number of inner
484 groups here because we don't have any easy way of finding the
485 corresponding start_memory when we're at a stop_memory.) */
488 /* Match a duplicate of something remembered. Followed by one
489 byte containing the register number. */
492 /* Fail unless at beginning of line. */
495 /* Fail unless at end of line. */
498 /* Succeeds if at beginning of buffer (if emacs) or at beginning
499 of string to be matched (if not). */
502 /* Analogously, for end of buffer/string. */
505 /* Followed by two byte relative address to which to jump. */
508 /* Same as jump, but marks the end of an alternative. */
511 /* Followed by two-byte relative address of place to resume at
512 in case of failure. */
513 /* ifdef MBS_SUPPORT, the size of address is 1. */
516 /* Like on_failure_jump, but pushes a placeholder instead of the
517 current string position when executed. */
518 on_failure_keep_string_jump,
520 /* Throw away latest failure point and then jump to following
521 two-byte relative address. */
522 /* ifdef MBS_SUPPORT, the size of address is 1. */
525 /* Change to pop_failure_jump if know won't have to backtrack to
526 match; otherwise change to jump. This is used to jump
527 back to the beginning of a repeat. If what follows this jump
528 clearly won't match what the repeat does, such that we can be
529 sure that there is no use backtracking out of repetitions
530 already matched, then we change it to a pop_failure_jump.
531 Followed by two-byte address. */
532 /* ifdef MBS_SUPPORT, the size of address is 1. */
535 /* Jump to following two-byte address, and push a dummy failure
536 point. This failure point will be thrown away if an attempt
537 is made to use it for a failure. A `+' construct makes this
538 before the first repeat. Also used as an intermediary kind
539 of jump when compiling an alternative. */
540 /* ifdef MBS_SUPPORT, the size of address is 1. */
543 /* Push a dummy failure point and continue. Used at the end of
547 /* Followed by two-byte relative address and two-byte number n.
548 After matching N times, jump to the address upon failure. */
549 /* ifdef MBS_SUPPORT, the size of address is 1. */
552 /* Followed by two-byte relative address, and two-byte number n.
553 Jump to the address N times, then fail. */
554 /* ifdef MBS_SUPPORT, the size of address is 1. */
557 /* Set the following two-byte relative address to the
558 subsequent two-byte number. The address *includes* the two
560 /* ifdef MBS_SUPPORT, the size of address is 1. */
563 wordchar, /* Matches any word-constituent character. */
564 notwordchar, /* Matches any char that is not a word-constituent. */
566 wordbeg, /* Succeeds if at word beginning. */
567 wordend, /* Succeeds if at word end. */
569 wordbound, /* Succeeds if at a word boundary. */
570 notwordbound /* Succeeds if not at a word boundary. */
573 ,before_dot, /* Succeeds if before point. */
574 at_dot, /* Succeeds if at point. */
575 after_dot, /* Succeeds if after point. */
577 /* Matches any character whose syntax is specified. Followed by
578 a byte which contains a syntax code, e.g., Sword. */
581 /* Matches any character whose syntax is not that specified. */
586 /* Common operations on the compiled pattern. */
588 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
589 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
592 # define STORE_NUMBER(destination, number) \
594 *(destination) = (US_CHAR_TYPE)(number); \
597 # define STORE_NUMBER(destination, number) \
599 (destination)[0] = (number) & 0377; \
600 (destination)[1] = (number) >> 8; \
602 #endif /* MBS_SUPPORT */
604 /* Same as STORE_NUMBER, except increment DESTINATION to
605 the byte after where the number is stored. Therefore, DESTINATION
606 must be an lvalue. */
607 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
609 #define STORE_NUMBER_AND_INCR(destination, number) \
611 STORE_NUMBER (destination, number); \
612 (destination) += OFFSET_ADDRESS_SIZE; \
615 /* Put into DESTINATION a number stored in two contiguous bytes starting
617 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
620 # define EXTRACT_NUMBER(destination, source) \
622 (destination) = *(source); \
625 # define EXTRACT_NUMBER(destination, source) \
627 (destination) = *(source) & 0377; \
628 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
633 static void extract_number _RE_ARGS ((int *dest, US_CHAR_TYPE *source));
635 extract_number (dest, source)
637 US_CHAR_TYPE *source;
642 int temp = SIGN_EXTEND_CHAR (*(source + 1));
643 *dest = *source & 0377;
648 # ifndef EXTRACT_MACROS /* To debug the macros. */
649 # undef EXTRACT_NUMBER
650 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
651 # endif /* not EXTRACT_MACROS */
655 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
656 SOURCE must be an lvalue. */
658 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
660 EXTRACT_NUMBER (destination, source); \
661 (source) += OFFSET_ADDRESS_SIZE; \
665 static void extract_number_and_incr _RE_ARGS ((int *destination,
666 US_CHAR_TYPE **source));
668 extract_number_and_incr (destination, source)
670 US_CHAR_TYPE **source;
672 extract_number (destination, *source);
673 *source += OFFSET_ADDRESS_SIZE;
676 # ifndef EXTRACT_MACROS
677 # undef EXTRACT_NUMBER_AND_INCR
678 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
679 extract_number_and_incr (&dest, &src)
680 # endif /* not EXTRACT_MACROS */
684 /* If DEBUG is defined, Regex prints many voluminous messages about what
685 it is doing (if the variable `debug' is nonzero). If linked with the
686 main program in `iregex.c', you can enter patterns and strings
687 interactively. And if linked with the main program in `main.c' and
688 the other test files, you can run the already-written tests. */
692 /* We use standard I/O for debugging. */
695 /* It is useful to test things that ``must'' be true when debugging. */
700 # define DEBUG_STATEMENT(e) e
701 # define DEBUG_PRINT1(x) if (debug) printf (x)
702 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
703 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
704 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
705 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
706 if (debug) print_partial_compiled_pattern (s, e)
707 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
708 if (debug) print_double_string (w, s1, sz1, s2, sz2)
711 /* Print the fastmap in human-readable form. */
714 print_fastmap (fastmap)
717 unsigned was_a_range = 0;
720 while (i < (1 << BYTEWIDTH))
726 while (i < (1 << BYTEWIDTH) && fastmap[i])
742 /* Print a compiled pattern string in human-readable form, starting at
743 the START pointer into it and ending just before the pointer END. */
746 print_partial_compiled_pattern (start, end)
752 US_CHAR_TYPE *p = start;
753 US_CHAR_TYPE *pend = end;
761 /* Loop over pattern commands. */
765 printf ("%td:\t", p - start);
767 printf ("%ld:\t", (long int) (p - start));
770 switch ((re_opcode_t) *p++)
778 printf ("/exactn/%d", mcnt);
790 printf ("/exactn_bin/%d", mcnt);
793 printf("/%lx", (long int) *p++);
797 #endif /* MBS_SUPPORT */
801 printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
806 printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
810 printf ("/duplicate/%ld", (long int) *p++);
823 printf ("/charset [%s",
824 (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
826 length = *workp++; /* the length of char_classes */
827 for (i=0 ; i<length ; i++)
828 printf("[:%lx:]", (long int) *p++);
829 length = *workp++; /* the length of collating_symbol */
830 for (i=0 ; i<length ;)
834 PUT_CHAR((i++,*p++));
838 length = *workp++; /* the length of equivalence_class */
839 for (i=0 ; i<length ;)
843 PUT_CHAR((i++,*p++));
847 length = *workp++; /* the length of char_range */
848 for (i=0 ; i<length ; i++)
850 wchar_t range_start = *p++;
851 wchar_t range_end = *p++;
853 printf("%c-%c", (char) range_start, (char) range_end);
855 printf("%C-%C", (wint_t) range_start, (wint_t) range_end);
857 length = *workp++; /* the length of char */
858 for (i=0 ; i<length ; i++)
862 printf("%C", (wint_t) *p++);
865 register int c, last = -100;
866 register int in_range = 0;
868 printf ("/charset [%s",
869 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
871 assert (p + *p < pend);
873 for (c = 0; c < 256; c++)
875 && (p[1 + (c/8)] & (1 << (c % 8))))
877 /* Are we starting a range? */
878 if (last + 1 == c && ! in_range)
883 /* Have we broken a range? */
884 else if (last + 1 != c && in_range)
902 #endif /* MBS_SUPPORT */
914 case on_failure_jump:
915 extract_number_and_incr (&mcnt, &p);
917 printf ("/on_failure_jump to %td", p + mcnt - start);
919 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
923 case on_failure_keep_string_jump:
924 extract_number_and_incr (&mcnt, &p);
926 printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
928 printf ("/on_failure_keep_string_jump to %ld",
929 (long int) (p + mcnt - start));
933 case dummy_failure_jump:
934 extract_number_and_incr (&mcnt, &p);
936 printf ("/dummy_failure_jump to %td", p + mcnt - start);
938 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
942 case push_dummy_failure:
943 printf ("/push_dummy_failure");
947 extract_number_and_incr (&mcnt, &p);
949 printf ("/maybe_pop_jump to %td", p + mcnt - start);
951 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
955 case pop_failure_jump:
956 extract_number_and_incr (&mcnt, &p);
958 printf ("/pop_failure_jump to %td", p + mcnt - start);
960 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
965 extract_number_and_incr (&mcnt, &p);
967 printf ("/jump_past_alt to %td", p + mcnt - start);
969 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
974 extract_number_and_incr (&mcnt, &p);
976 printf ("/jump to %td", p + mcnt - start);
978 printf ("/jump to %ld", (long int) (p + mcnt - start));
983 extract_number_and_incr (&mcnt, &p);
985 extract_number_and_incr (&mcnt2, &p);
987 printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
989 printf ("/succeed_n to %ld, %d times",
990 (long int) (p1 - start), mcnt2);
995 extract_number_and_incr (&mcnt, &p);
997 extract_number_and_incr (&mcnt2, &p);
998 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
1002 extract_number_and_incr (&mcnt, &p);
1004 extract_number_and_incr (&mcnt2, &p);
1006 printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1008 printf ("/set_number_at location %ld to %d",
1009 (long int) (p1 - start), mcnt2);
1014 printf ("/wordbound");
1018 printf ("/notwordbound");
1022 printf ("/wordbeg");
1026 printf ("/wordend");
1031 printf ("/before_dot");
1039 printf ("/after_dot");
1043 printf ("/syntaxspec");
1045 printf ("/%d", mcnt);
1049 printf ("/notsyntaxspec");
1051 printf ("/%d", mcnt);
1056 printf ("/wordchar");
1060 printf ("/notwordchar");
1072 printf ("?%ld", (long int) *(p-1));
1079 printf ("%td:\tend of pattern.\n", p - start);
1081 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1087 print_compiled_pattern (bufp)
1088 struct re_pattern_buffer *bufp;
1090 US_CHAR_TYPE *buffer = (US_CHAR_TYPE*) bufp->buffer;
1092 print_partial_compiled_pattern (buffer, buffer
1093 + bufp->used / sizeof(US_CHAR_TYPE));
1094 printf ("%ld bytes used/%ld bytes allocated.\n",
1095 bufp->used, bufp->allocated);
1097 if (bufp->fastmap_accurate && bufp->fastmap)
1099 printf ("fastmap: ");
1100 print_fastmap (bufp->fastmap);
1104 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1106 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1108 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1109 printf ("can_be_null: %d\t", bufp->can_be_null);
1110 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1111 printf ("no_sub: %d\t", bufp->no_sub);
1112 printf ("not_bol: %d\t", bufp->not_bol);
1113 printf ("not_eol: %d\t", bufp->not_eol);
1114 printf ("syntax: %lx\n", bufp->syntax);
1115 /* Perhaps we should print the translate table? */
1120 print_double_string (where, string1, size1, string2, size2)
1121 const CHAR_TYPE *where;
1122 const CHAR_TYPE *string1;
1123 const CHAR_TYPE *string2;
1133 if (FIRST_STRING_P (where))
1135 for (this_char = where - string1; this_char < size1; this_char++)
1136 PUT_CHAR (string1[this_char]);
1141 for (this_char = where - string2; this_char < size2; this_char++)
1142 PUT_CHAR (string2[this_char]);
1153 #else /* not DEBUG */
1158 # define DEBUG_STATEMENT(e)
1159 # define DEBUG_PRINT1(x)
1160 # define DEBUG_PRINT2(x1, x2)
1161 # define DEBUG_PRINT3(x1, x2, x3)
1162 # define DEBUG_PRINT4(x1, x2, x3, x4)
1163 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1164 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1166 #endif /* not DEBUG */
1169 /* This convert a multibyte string to a wide character string.
1170 And write their correspondances to offset_buffer(see below)
1171 and write whether each wchar_t is binary data to is_binary.
1172 This assume invalid multibyte sequences as binary data.
1173 We assume offset_buffer and is_binary is already allocated
1176 static size_t convert_mbs_to_wcs (CHAR_TYPE *dest, const unsigned char* src,
1177 size_t len, int *offset_buffer,
1180 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1182 const unsigned char* src;
1183 size_t len; /* the length of multibyte string. */
1185 /* It hold correspondances between src(char string) and
1186 dest(wchar_t string) for optimization.
1188 dest = {'X', 'Y', 'Z'}
1189 (each "xxx", "y" and "zz" represent one multibyte character
1190 corresponding to 'X', 'Y' and 'Z'.)
1191 offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1197 wchar_t *pdest = dest;
1198 const unsigned char *psrc = src;
1199 size_t wc_count = 0;
1201 if (MB_CUR_MAX == 1)
1202 { /* We don't need conversion. */
1203 for ( ; wc_count < len ; ++wc_count)
1206 is_binary[wc_count] = FALSE;
1207 offset_buffer[wc_count] = wc_count;
1209 offset_buffer[wc_count] = wc_count;
1213 /* We need conversion. */
1216 size_t mb_remain = len;
1217 size_t mb_count = 0;
1219 /* Initialize the conversion state. */
1220 memset (&mbs, 0, sizeof (mbstate_t));
1222 offset_buffer[0] = 0;
1223 for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1226 consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1229 /* failed to convert. maybe src contains binary data.
1230 So we consume 1 byte manualy. */
1234 is_binary[wc_count] = TRUE;
1237 is_binary[wc_count] = FALSE;
1238 /* In sjis encoding, we use yen sign as escape character in
1239 place of reverse solidus. So we convert 0x5c(yen sign in
1240 sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1241 solidus in UCS2). */
1242 if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1243 *pdest = (wchar_t) *psrc;
1245 offset_buffer[wc_count + 1] = mb_count += consumed;
1252 #endif /* MBS_SUPPORT */
1254 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1255 also be assigned to arbitrarily: each pattern buffer stores its own
1256 syntax, so it can be changed between regex compilations. */
1257 /* This has no initializer because initialized variables in Emacs
1258 become read-only after dumping. */
1259 reg_syntax_t re_syntax_options;
1262 /* Specify the precise syntax of regexps for compilation. This provides
1263 for compatibility for various utilities which historically have
1264 different, incompatible syntaxes.
1266 The argument SYNTAX is a bit mask comprised of the various bits
1267 defined in regex.h. We return the old syntax. */
1270 re_set_syntax (syntax)
1271 reg_syntax_t syntax;
1273 reg_syntax_t ret = re_syntax_options;
1275 re_syntax_options = syntax;
1277 if (syntax & RE_DEBUG)
1279 else if (debug) /* was on but now is not */
1285 weak_alias (__re_set_syntax, re_set_syntax)
1288 /* This table gives an error message for each of the error codes listed
1289 in regex.h. Obviously the order here has to be same as there.
1290 POSIX doesn't require that we do anything for REG_NOERROR,
1291 but why not be nice? */
1293 static const char re_error_msgid[] =
1295 #define REG_NOERROR_IDX 0
1296 gettext_noop ("Success") /* REG_NOERROR */
1298 #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1299 gettext_noop ("No match") /* REG_NOMATCH */
1301 #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1302 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1304 #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1305 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1307 #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1308 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1310 #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1311 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1313 #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1314 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1316 #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1317 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1319 #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1320 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1322 #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1323 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1325 #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1326 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1328 #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1329 gettext_noop ("Invalid range end") /* REG_ERANGE */
1331 #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1332 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1334 #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1335 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1337 #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1338 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1340 #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1341 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1343 #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1344 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1347 static const size_t re_error_msgid_idx[] =
1368 /* Avoiding alloca during matching, to placate r_alloc. */
1370 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1371 searching and matching functions should not call alloca. On some
1372 systems, alloca is implemented in terms of malloc, and if we're
1373 using the relocating allocator routines, then malloc could cause a
1374 relocation, which might (if the strings being searched are in the
1375 ralloc heap) shift the data out from underneath the regexp
1378 Here's another reason to avoid allocation: Emacs
1379 processes input from X in a signal handler; processing X input may
1380 call malloc; if input arrives while a matching routine is calling
1381 malloc, then we're scrod. But Emacs can't just block input while
1382 calling matching routines; then we don't notice interrupts when
1383 they come in. So, Emacs blocks input around all regexp calls
1384 except the matching calls, which it leaves unprotected, in the
1385 faith that they will not malloc. */
1387 /* Normally, this is fine. */
1388 #define MATCH_MAY_ALLOCATE
1390 /* When using GNU C, we are not REALLY using the C alloca, no matter
1391 what config.h may say. So don't take precautions for it. */
1396 /* The match routines may not allocate if (1) they would do it with malloc
1397 and (2) it's not safe for them to use malloc.
1398 Note that if REL_ALLOC is defined, matching would not use malloc for the
1399 failure stack, but we would still use it for the register vectors;
1400 so REL_ALLOC should not affect this. */
1401 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1402 # undef MATCH_MAY_ALLOCATE
1406 /* Failure stack declarations and macros; both re_compile_fastmap and
1407 re_match_2 use a failure stack. These have to be macros because of
1408 REGEX_ALLOCATE_STACK. */
1411 /* Number of failure points for which to initially allocate space
1412 when matching. If this number is exceeded, we allocate more
1413 space, so it is not a hard limit. */
1414 #ifndef INIT_FAILURE_ALLOC
1415 # define INIT_FAILURE_ALLOC 5
1418 /* Roughly the maximum number of failure points on the stack. Would be
1419 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1420 This is a variable only so users of regex can assign to it; we never
1421 change it ourselves. */
1425 # if defined MATCH_MAY_ALLOCATE
1426 /* 4400 was enough to cause a crash on Alpha OSF/1,
1427 whose default stack limit is 2mb. */
1428 long int re_max_failures = 4000;
1430 long int re_max_failures = 2000;
1433 union fail_stack_elt
1435 US_CHAR_TYPE *pointer;
1439 typedef union fail_stack_elt fail_stack_elt_t;
1443 fail_stack_elt_t *stack;
1444 unsigned long int size;
1445 unsigned long int avail; /* Offset of next open position. */
1448 #else /* not INT_IS_16BIT */
1450 # if defined MATCH_MAY_ALLOCATE
1451 /* 4400 was enough to cause a crash on Alpha OSF/1,
1452 whose default stack limit is 2mb. */
1453 int re_max_failures = 4000;
1455 int re_max_failures = 2000;
1458 union fail_stack_elt
1460 US_CHAR_TYPE *pointer;
1464 typedef union fail_stack_elt fail_stack_elt_t;
1468 fail_stack_elt_t *stack;
1470 unsigned avail; /* Offset of next open position. */
1473 #endif /* INT_IS_16BIT */
1475 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1476 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1477 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1480 /* Define macros to initialize and free the failure stack.
1481 Do `return -2' if the alloc fails. */
1483 #ifdef MATCH_MAY_ALLOCATE
1484 # define INIT_FAIL_STACK() \
1486 fail_stack.stack = (fail_stack_elt_t *) \
1487 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1489 if (fail_stack.stack == NULL) \
1492 fail_stack.size = INIT_FAILURE_ALLOC; \
1493 fail_stack.avail = 0; \
1496 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1498 # define INIT_FAIL_STACK() \
1500 fail_stack.avail = 0; \
1503 # define RESET_FAIL_STACK()
1507 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1509 Return 1 if succeeds, and 0 if either ran out of memory
1510 allocating space for it or it was already too large.
1512 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1514 #define DOUBLE_FAIL_STACK(fail_stack) \
1515 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1517 : ((fail_stack).stack = (fail_stack_elt_t *) \
1518 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1519 (fail_stack).size * sizeof (fail_stack_elt_t), \
1520 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1522 (fail_stack).stack == NULL \
1524 : ((fail_stack).size <<= 1, \
1528 /* Push pointer POINTER on FAIL_STACK.
1529 Return 1 if was able to do so and 0 if ran out of memory allocating
1531 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1532 ((FAIL_STACK_FULL () \
1533 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1535 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1538 /* Push a pointer value onto the failure stack.
1539 Assumes the variable `fail_stack'. Probably should only
1540 be called from within `PUSH_FAILURE_POINT'. */
1541 #define PUSH_FAILURE_POINTER(item) \
1542 fail_stack.stack[fail_stack.avail++].pointer = (US_CHAR_TYPE *) (item)
1544 /* This pushes an integer-valued item onto the failure stack.
1545 Assumes the variable `fail_stack'. Probably should only
1546 be called from within `PUSH_FAILURE_POINT'. */
1547 #define PUSH_FAILURE_INT(item) \
1548 fail_stack.stack[fail_stack.avail++].integer = (item)
1550 /* Push a fail_stack_elt_t value onto the failure stack.
1551 Assumes the variable `fail_stack'. Probably should only
1552 be called from within `PUSH_FAILURE_POINT'. */
1553 #define PUSH_FAILURE_ELT(item) \
1554 fail_stack.stack[fail_stack.avail++] = (item)
1556 /* These three POP... operations complement the three PUSH... operations.
1557 All assume that `fail_stack' is nonempty. */
1558 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1559 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1560 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1562 /* Used to omit pushing failure point id's when we're not debugging. */
1564 # define DEBUG_PUSH PUSH_FAILURE_INT
1565 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1567 # define DEBUG_PUSH(item)
1568 # define DEBUG_POP(item_addr)
1572 /* Push the information about the state we will need
1573 if we ever fail back to it.
1575 Requires variables fail_stack, regstart, regend, reg_info, and
1576 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1579 Does `return FAILURE_CODE' if runs out of memory. */
1581 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1583 char *destination; \
1584 /* Must be int, so when we don't save any registers, the arithmetic \
1585 of 0 + -1 isn't done as unsigned. */ \
1586 /* Can't be int, since there is not a shred of a guarantee that int \
1587 is wide enough to hold a value of something to which pointer can \
1589 active_reg_t this_reg; \
1591 DEBUG_STATEMENT (failure_id++); \
1592 DEBUG_STATEMENT (nfailure_points_pushed++); \
1593 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1594 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1595 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1597 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1598 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1600 /* Ensure we have enough space allocated for what we will push. */ \
1601 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1603 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1604 return failure_code; \
1606 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1607 (fail_stack).size); \
1608 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1611 /* Push the info, starting with the registers. */ \
1612 DEBUG_PRINT1 ("\n"); \
1615 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1618 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1619 DEBUG_STATEMENT (num_regs_pushed++); \
1621 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1622 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1624 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1625 PUSH_FAILURE_POINTER (regend[this_reg]); \
1627 DEBUG_PRINT2 (" info: %p\n ", \
1628 reg_info[this_reg].word.pointer); \
1629 DEBUG_PRINT2 (" match_null=%d", \
1630 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1631 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1632 DEBUG_PRINT2 (" matched_something=%d", \
1633 MATCHED_SOMETHING (reg_info[this_reg])); \
1634 DEBUG_PRINT2 (" ever_matched=%d", \
1635 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1636 DEBUG_PRINT1 ("\n"); \
1637 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1640 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1641 PUSH_FAILURE_INT (lowest_active_reg); \
1643 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1644 PUSH_FAILURE_INT (highest_active_reg); \
1646 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1647 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1648 PUSH_FAILURE_POINTER (pattern_place); \
1650 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1651 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1653 DEBUG_PRINT1 ("'\n"); \
1654 PUSH_FAILURE_POINTER (string_place); \
1656 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1657 DEBUG_PUSH (failure_id); \
1660 /* This is the number of items that are pushed and popped on the stack
1661 for each register. */
1662 #define NUM_REG_ITEMS 3
1664 /* Individual items aside from the registers. */
1666 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1668 # define NUM_NONREG_ITEMS 4
1671 /* We push at most this many items on the stack. */
1672 /* We used to use (num_regs - 1), which is the number of registers
1673 this regexp will save; but that was changed to 5
1674 to avoid stack overflow for a regexp with lots of parens. */
1675 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1677 /* We actually push this many items. */
1678 #define NUM_FAILURE_ITEMS \
1680 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1684 /* How many items can still be added to the stack without overflowing it. */
1685 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1688 /* Pops what PUSH_FAIL_STACK pushes.
1690 We restore into the parameters, all of which should be lvalues:
1691 STR -- the saved data position.
1692 PAT -- the saved pattern position.
1693 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1694 REGSTART, REGEND -- arrays of string positions.
1695 REG_INFO -- array of information about each subexpression.
1697 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1698 `pend', `string1', `size1', `string2', and `size2'. */
1699 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1701 DEBUG_STATEMENT (unsigned failure_id;) \
1702 active_reg_t this_reg; \
1703 const US_CHAR_TYPE *string_temp; \
1705 assert (!FAIL_STACK_EMPTY ()); \
1707 /* Remove failure points and point to how many regs pushed. */ \
1708 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1709 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1710 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1712 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1714 DEBUG_POP (&failure_id); \
1715 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1717 /* If the saved string location is NULL, it came from an \
1718 on_failure_keep_string_jump opcode, and we want to throw away the \
1719 saved NULL, thus retaining our current position in the string. */ \
1720 string_temp = POP_FAILURE_POINTER (); \
1721 if (string_temp != NULL) \
1722 str = (const CHAR_TYPE *) string_temp; \
1724 DEBUG_PRINT2 (" Popping string %p: `", str); \
1725 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1726 DEBUG_PRINT1 ("'\n"); \
1728 pat = (US_CHAR_TYPE *) POP_FAILURE_POINTER (); \
1729 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1730 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1732 /* Restore register info. */ \
1733 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1734 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1736 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1737 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1740 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1742 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1744 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1745 DEBUG_PRINT2 (" info: %p\n", \
1746 reg_info[this_reg].word.pointer); \
1748 regend[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER (); \
1749 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1751 regstart[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER ();\
1752 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1756 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1758 reg_info[this_reg].word.integer = 0; \
1759 regend[this_reg] = 0; \
1760 regstart[this_reg] = 0; \
1762 highest_active_reg = high_reg; \
1765 set_regs_matched_done = 0; \
1766 DEBUG_STATEMENT (nfailure_points_popped++); \
1767 } /* POP_FAILURE_POINT */
1770 /* Structure for per-register (a.k.a. per-group) information.
1771 Other register information, such as the
1772 starting and ending positions (which are addresses), and the list of
1773 inner groups (which is a bits list) are maintained in separate
1776 We are making a (strictly speaking) nonportable assumption here: that
1777 the compiler will pack our bit fields into something that fits into
1778 the type of `word', i.e., is something that fits into one item on the
1782 /* Declarations and macros for re_match_2. */
1786 fail_stack_elt_t word;
1789 /* This field is one if this group can match the empty string,
1790 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1791 #define MATCH_NULL_UNSET_VALUE 3
1792 unsigned match_null_string_p : 2;
1793 unsigned is_active : 1;
1794 unsigned matched_something : 1;
1795 unsigned ever_matched_something : 1;
1797 } register_info_type;
1799 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1800 #define IS_ACTIVE(R) ((R).bits.is_active)
1801 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1802 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1805 /* Call this when have matched a real character; it sets `matched' flags
1806 for the subexpressions which we are currently inside. Also records
1807 that those subexprs have matched. */
1808 #define SET_REGS_MATCHED() \
1811 if (!set_regs_matched_done) \
1814 set_regs_matched_done = 1; \
1815 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1817 MATCHED_SOMETHING (reg_info[r]) \
1818 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1825 /* Registers are set to a sentinel when they haven't yet matched. */
1826 static CHAR_TYPE reg_unset_dummy;
1827 #define REG_UNSET_VALUE (®_unset_dummy)
1828 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1830 /* Subroutine declarations and macros for regex_compile. */
1832 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1833 reg_syntax_t syntax,
1834 struct re_pattern_buffer *bufp));
1835 static void store_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc, int arg));
1836 static void store_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1837 int arg1, int arg2));
1838 static void insert_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1839 int arg, US_CHAR_TYPE *end));
1840 static void insert_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1841 int arg1, int arg2, US_CHAR_TYPE *end));
1842 static boolean at_begline_loc_p _RE_ARGS ((const CHAR_TYPE *pattern,
1844 reg_syntax_t syntax));
1845 static boolean at_endline_loc_p _RE_ARGS ((const CHAR_TYPE *p,
1846 const CHAR_TYPE *pend,
1847 reg_syntax_t syntax));
1849 static reg_errcode_t compile_range _RE_ARGS ((CHAR_TYPE range_start,
1850 const CHAR_TYPE **p_ptr,
1851 const CHAR_TYPE *pend,
1853 reg_syntax_t syntax,
1855 CHAR_TYPE *char_set));
1856 static void insert_space _RE_ARGS ((int num, CHAR_TYPE *loc, CHAR_TYPE *end));
1858 static reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
1859 const CHAR_TYPE **p_ptr,
1860 const CHAR_TYPE *pend,
1862 reg_syntax_t syntax,
1864 #endif /* MBS_SUPPORT */
1866 /* Fetch the next character in the uncompiled pattern---translating it
1867 if necessary. Also cast from a signed character in the constant
1868 string passed to us by the user to an unsigned char that we can use
1869 as an array index (in, e.g., `translate'). */
1870 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1871 because it is impossible to allocate 4GB array for some encodings
1872 which have 4 byte character_set like UCS4. */
1875 # define PATFETCH(c) \
1876 do {if (p == pend) return REG_EEND; \
1877 c = (US_CHAR_TYPE) *p++; \
1878 if (translate && (c <= 0xff)) c = (US_CHAR_TYPE) translate[c]; \
1881 # define PATFETCH(c) \
1882 do {if (p == pend) return REG_EEND; \
1883 c = (unsigned char) *p++; \
1884 if (translate) c = (unsigned char) translate[c]; \
1886 # endif /* MBS_SUPPORT */
1889 /* Fetch the next character in the uncompiled pattern, with no
1891 #define PATFETCH_RAW(c) \
1892 do {if (p == pend) return REG_EEND; \
1893 c = (US_CHAR_TYPE) *p++; \
1896 /* Go backwards one character in the pattern. */
1897 #define PATUNFETCH p--
1900 /* If `translate' is non-null, return translate[D], else just D. We
1901 cast the subscript to translate because some data is declared as
1902 `char *', to avoid warnings when a string constant is passed. But
1903 when we use a character as a subscript we must make it unsigned. */
1904 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1905 because it is impossible to allocate 4GB array for some encodings
1906 which have 4 byte character_set like UCS4. */
1909 # define TRANSLATE(d) \
1910 ((translate && ((US_CHAR_TYPE) (d)) <= 0xff) \
1911 ? (char) translate[(unsigned char) (d)] : (d))
1913 # define TRANSLATE(d) \
1914 (translate ? (char) translate[(unsigned char) (d)] : (d))
1915 # endif /* MBS_SUPPORT */
1919 /* Macros for outputting the compiled pattern into `buffer'. */
1921 /* If the buffer isn't allocated when it comes in, use this. */
1922 #define INIT_BUF_SIZE (32 * sizeof(US_CHAR_TYPE))
1924 /* Make sure we have at least N more bytes of space in buffer. */
1926 # define GET_BUFFER_SPACE(n) \
1927 while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR \
1928 + (n)*sizeof(CHAR_TYPE)) > bufp->allocated) \
1931 # define GET_BUFFER_SPACE(n) \
1932 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1934 #endif /* MBS_SUPPORT */
1936 /* Make sure we have one more byte of buffer space and then add C to it. */
1937 #define BUF_PUSH(c) \
1939 GET_BUFFER_SPACE (1); \
1940 *b++ = (US_CHAR_TYPE) (c); \
1944 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1945 #define BUF_PUSH_2(c1, c2) \
1947 GET_BUFFER_SPACE (2); \
1948 *b++ = (US_CHAR_TYPE) (c1); \
1949 *b++ = (US_CHAR_TYPE) (c2); \
1953 /* As with BUF_PUSH_2, except for three bytes. */
1954 #define BUF_PUSH_3(c1, c2, c3) \
1956 GET_BUFFER_SPACE (3); \
1957 *b++ = (US_CHAR_TYPE) (c1); \
1958 *b++ = (US_CHAR_TYPE) (c2); \
1959 *b++ = (US_CHAR_TYPE) (c3); \
1962 /* Store a jump with opcode OP at LOC to location TO. We store a
1963 relative address offset by the three bytes the jump itself occupies. */
1964 #define STORE_JUMP(op, loc, to) \
1965 store_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
1967 /* Likewise, for a two-argument jump. */
1968 #define STORE_JUMP2(op, loc, to, arg) \
1969 store_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
1971 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1972 #define INSERT_JUMP(op, loc, to) \
1973 insert_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
1975 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1976 #define INSERT_JUMP2(op, loc, to, arg) \
1977 insert_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
1981 /* This is not an arbitrary limit: the arguments which represent offsets
1982 into the pattern are two bytes long. So if 2^16 bytes turns out to
1983 be too small, many things would have to change. */
1984 /* Any other compiler which, like MSC, has allocation limit below 2^16
1985 bytes will have to use approach similar to what was done below for
1986 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1987 reallocating to 0 bytes. Such thing is not going to work too well.
1988 You have been warned!! */
1989 #if defined _MSC_VER && !defined WIN32
1990 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1991 The REALLOC define eliminates a flurry of conversion warnings,
1992 but is not required. */
1993 # define MAX_BUF_SIZE 65500L
1994 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1996 # define MAX_BUF_SIZE (1L << 16)
1997 # define REALLOC(p,s) realloc ((p), (s))
2000 /* Extend the buffer by twice its current size via realloc and
2001 reset the pointers that pointed into the old block to point to the
2002 correct places in the new one. If extending the buffer results in it
2003 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
2004 #if __BOUNDED_POINTERS__
2005 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2006 # define MOVE_BUFFER_POINTER(P) \
2007 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2008 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
2011 SET_HIGH_BOUND (b); \
2012 SET_HIGH_BOUND (begalt); \
2013 if (fixup_alt_jump) \
2014 SET_HIGH_BOUND (fixup_alt_jump); \
2016 SET_HIGH_BOUND (laststart); \
2017 if (pending_exact) \
2018 SET_HIGH_BOUND (pending_exact); \
2021 # define MOVE_BUFFER_POINTER(P) (P) += incr
2022 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
2026 # define EXTEND_BUFFER() \
2028 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2030 if (bufp->allocated + sizeof(US_CHAR_TYPE) > MAX_BUF_SIZE) \
2032 bufp->allocated <<= 1; \
2033 if (bufp->allocated > MAX_BUF_SIZE) \
2034 bufp->allocated = MAX_BUF_SIZE; \
2035 /* How many characters the new buffer can have? */ \
2036 wchar_count = bufp->allocated / sizeof(US_CHAR_TYPE); \
2037 if (wchar_count == 0) wchar_count = 1; \
2038 /* Truncate the buffer to CHAR_TYPE align. */ \
2039 bufp->allocated = wchar_count * sizeof(US_CHAR_TYPE); \
2040 RETALLOC (COMPILED_BUFFER_VAR, wchar_count, US_CHAR_TYPE); \
2041 bufp->buffer = (char*)COMPILED_BUFFER_VAR; \
2042 if (COMPILED_BUFFER_VAR == NULL) \
2043 return REG_ESPACE; \
2044 /* If the buffer moved, move all the pointers into it. */ \
2045 if (old_buffer != COMPILED_BUFFER_VAR) \
2047 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2048 MOVE_BUFFER_POINTER (b); \
2049 MOVE_BUFFER_POINTER (begalt); \
2050 if (fixup_alt_jump) \
2051 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2053 MOVE_BUFFER_POINTER (laststart); \
2054 if (pending_exact) \
2055 MOVE_BUFFER_POINTER (pending_exact); \
2057 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2060 # define EXTEND_BUFFER() \
2062 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2063 if (bufp->allocated == MAX_BUF_SIZE) \
2065 bufp->allocated <<= 1; \
2066 if (bufp->allocated > MAX_BUF_SIZE) \
2067 bufp->allocated = MAX_BUF_SIZE; \
2068 bufp->buffer = (US_CHAR_TYPE *) REALLOC (COMPILED_BUFFER_VAR, \
2070 if (COMPILED_BUFFER_VAR == NULL) \
2071 return REG_ESPACE; \
2072 /* If the buffer moved, move all the pointers into it. */ \
2073 if (old_buffer != COMPILED_BUFFER_VAR) \
2075 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2076 MOVE_BUFFER_POINTER (b); \
2077 MOVE_BUFFER_POINTER (begalt); \
2078 if (fixup_alt_jump) \
2079 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2081 MOVE_BUFFER_POINTER (laststart); \
2082 if (pending_exact) \
2083 MOVE_BUFFER_POINTER (pending_exact); \
2085 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2087 #endif /* MBS_SUPPORT */
2089 /* Since we have one byte reserved for the register number argument to
2090 {start,stop}_memory, the maximum number of groups we can report
2091 things about is what fits in that byte. */
2092 #define MAX_REGNUM 255
2094 /* But patterns can have more than `MAX_REGNUM' registers. We just
2095 ignore the excess. */
2096 typedef unsigned regnum_t;
2099 /* Macros for the compile stack. */
2101 /* Since offsets can go either forwards or backwards, this type needs to
2102 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
2103 /* int may be not enough when sizeof(int) == 2. */
2104 typedef long pattern_offset_t;
2108 pattern_offset_t begalt_offset;
2109 pattern_offset_t fixup_alt_jump;
2110 pattern_offset_t inner_group_offset;
2111 pattern_offset_t laststart_offset;
2113 } compile_stack_elt_t;
2118 compile_stack_elt_t *stack;
2120 unsigned avail; /* Offset of next open position. */
2121 } compile_stack_type;
2124 #define INIT_COMPILE_STACK_SIZE 32
2126 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
2127 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
2129 /* The next available element. */
2130 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2133 /* Set the bit for character C in a list. */
2134 #define SET_LIST_BIT(c) \
2135 (b[((unsigned char) (c)) / BYTEWIDTH] \
2136 |= 1 << (((unsigned char) c) % BYTEWIDTH))
2139 /* Get the next unsigned number in the uncompiled pattern. */
2140 #define GET_UNSIGNED_NUMBER(num) \
2145 if (c < '0' || c > '9') \
2147 if (num <= RE_DUP_MAX) \
2151 num = num * 10 + c - '0'; \
2156 #if defined _LIBC || WIDE_CHAR_SUPPORT
2157 /* The GNU C library provides support for user-defined character classes
2158 and the functions from ISO C amendement 1. */
2159 # ifdef CHARCLASS_NAME_MAX
2160 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2162 /* This shouldn't happen but some implementation might still have this
2163 problem. Use a reasonable default value. */
2164 # define CHAR_CLASS_MAX_LENGTH 256
2168 # define IS_CHAR_CLASS(string) __wctype (string)
2170 # define IS_CHAR_CLASS(string) wctype (string)
2173 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
2175 # define IS_CHAR_CLASS(string) \
2176 (STREQ (string, "alpha") || STREQ (string, "upper") \
2177 || STREQ (string, "lower") || STREQ (string, "digit") \
2178 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
2179 || STREQ (string, "space") || STREQ (string, "print") \
2180 || STREQ (string, "punct") || STREQ (string, "graph") \
2181 || STREQ (string, "cntrl") || STREQ (string, "blank"))
2184 #ifndef MATCH_MAY_ALLOCATE
2186 /* If we cannot allocate large objects within re_match_2_internal,
2187 we make the fail stack and register vectors global.
2188 The fail stack, we grow to the maximum size when a regexp
2190 The register vectors, we adjust in size each time we
2191 compile a regexp, according to the number of registers it needs. */
2193 static fail_stack_type fail_stack;
2195 /* Size with which the following vectors are currently allocated.
2196 That is so we can make them bigger as needed,
2197 but never make them smaller. */
2198 static int regs_allocated_size;
2200 static const char ** regstart, ** regend;
2201 static const char ** old_regstart, ** old_regend;
2202 static const char **best_regstart, **best_regend;
2203 static register_info_type *reg_info;
2204 static const char **reg_dummy;
2205 static register_info_type *reg_info_dummy;
2207 /* Make the register vectors big enough for NUM_REGS registers,
2208 but don't make them smaller. */
2211 regex_grow_registers (num_regs)
2214 if (num_regs > regs_allocated_size)
2216 RETALLOC_IF (regstart, num_regs, const char *);
2217 RETALLOC_IF (regend, num_regs, const char *);
2218 RETALLOC_IF (old_regstart, num_regs, const char *);
2219 RETALLOC_IF (old_regend, num_regs, const char *);
2220 RETALLOC_IF (best_regstart, num_regs, const char *);
2221 RETALLOC_IF (best_regend, num_regs, const char *);
2222 RETALLOC_IF (reg_info, num_regs, register_info_type);
2223 RETALLOC_IF (reg_dummy, num_regs, const char *);
2224 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
2226 regs_allocated_size = num_regs;
2230 #endif /* not MATCH_MAY_ALLOCATE */
2232 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2236 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2237 Returns one of error codes defined in `regex.h', or zero for success.
2239 Assumes the `allocated' (and perhaps `buffer') and `translate'
2240 fields are set in BUFP on entry.
2242 If it succeeds, results are put in BUFP (if it returns an error, the
2243 contents of BUFP are undefined):
2244 `buffer' is the compiled pattern;
2245 `syntax' is set to SYNTAX;
2246 `used' is set to the length of the compiled pattern;
2247 `fastmap_accurate' is zero;
2248 `re_nsub' is the number of subexpressions in PATTERN;
2249 `not_bol' and `not_eol' are zero;
2251 The `fastmap' and `newline_anchor' fields are neither
2252 examined nor set. */
2254 /* Return, freeing storage we allocated. */
2256 # define FREE_STACK_RETURN(value) \
2257 return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2259 # define FREE_STACK_RETURN(value) \
2260 return (free (compile_stack.stack), value)
2261 #endif /* MBS_SUPPORT */
2263 static reg_errcode_t
2265 regex_compile (cpattern, csize, syntax, bufp)
2266 const char *cpattern;
2269 regex_compile (pattern, size, syntax, bufp)
2270 const char *pattern;
2272 #endif /* MBS_SUPPORT */
2273 reg_syntax_t syntax;
2274 struct re_pattern_buffer *bufp;
2276 /* We fetch characters from PATTERN here. Even though PATTERN is
2277 `char *' (i.e., signed), we declare these variables as unsigned, so
2278 they can be reliably used as array indices. */
2279 register US_CHAR_TYPE c, c1;
2282 /* A temporary space to keep wchar_t pattern and compiled pattern. */
2283 CHAR_TYPE *pattern, *COMPILED_BUFFER_VAR;
2285 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
2286 int *mbs_offset = NULL;
2287 /* It hold whether each wchar_t is binary data or not. */
2288 char *is_binary = NULL;
2289 /* A flag whether exactn is handling binary data or not. */
2290 char is_exactn_bin = FALSE;
2291 #endif /* MBS_SUPPORT */
2293 /* A random temporary spot in PATTERN. */
2294 const CHAR_TYPE *p1;
2296 /* Points to the end of the buffer, where we should append. */
2297 register US_CHAR_TYPE *b;
2299 /* Keeps track of unclosed groups. */
2300 compile_stack_type compile_stack;
2302 /* Points to the current (ending) position in the pattern. */
2305 const CHAR_TYPE *pend;
2307 const CHAR_TYPE *p = pattern;
2308 const CHAR_TYPE *pend = pattern + size;
2309 #endif /* MBS_SUPPORT */
2311 /* How to translate the characters in the pattern. */
2312 RE_TRANSLATE_TYPE translate = bufp->translate;
2314 /* Address of the count-byte of the most recently inserted `exactn'
2315 command. This makes it possible to tell if a new exact-match
2316 character can be added to that command or if the character requires
2317 a new `exactn' command. */
2318 US_CHAR_TYPE *pending_exact = 0;
2320 /* Address of start of the most recently finished expression.
2321 This tells, e.g., postfix * where to find the start of its
2322 operand. Reset at the beginning of groups and alternatives. */
2323 US_CHAR_TYPE *laststart = 0;
2325 /* Address of beginning of regexp, or inside of last group. */
2326 US_CHAR_TYPE *begalt;
2328 /* Address of the place where a forward jump should go to the end of
2329 the containing expression. Each alternative of an `or' -- except the
2330 last -- ends with a forward jump of this sort. */
2331 US_CHAR_TYPE *fixup_alt_jump = 0;
2333 /* Counts open-groups as they are encountered. Remembered for the
2334 matching close-group on the compile stack, so the same register
2335 number is put in the stop_memory as the start_memory. */
2336 regnum_t regnum = 0;
2339 /* Initialize the wchar_t PATTERN and offset_buffer. */
2340 p = pend = pattern = TALLOC(csize + 1, CHAR_TYPE);
2341 mbs_offset = TALLOC(csize + 1, int);
2342 is_binary = TALLOC(csize + 1, char);
2343 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2350 pattern[csize] = L'\0'; /* sentinel */
2351 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2363 DEBUG_PRINT1 ("\nCompiling pattern: ");
2366 unsigned debug_count;
2368 for (debug_count = 0; debug_count < size; debug_count++)
2369 PUT_CHAR (pattern[debug_count]);
2374 /* Initialize the compile stack. */
2375 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2376 if (compile_stack.stack == NULL)
2386 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2387 compile_stack.avail = 0;
2389 /* Initialize the pattern buffer. */
2390 bufp->syntax = syntax;
2391 bufp->fastmap_accurate = 0;
2392 bufp->not_bol = bufp->not_eol = 0;
2394 /* Set `used' to zero, so that if we return an error, the pattern
2395 printer (for debugging) will think there's no pattern. We reset it
2399 /* Always count groups, whether or not bufp->no_sub is set. */
2402 #if !defined emacs && !defined SYNTAX_TABLE
2403 /* Initialize the syntax table. */
2404 init_syntax_once ();
2407 if (bufp->allocated == 0)
2410 { /* If zero allocated, but buffer is non-null, try to realloc
2411 enough space. This loses if buffer's address is bogus, but
2412 that is the user's responsibility. */
2414 /* Free bufp->buffer and allocate an array for wchar_t pattern
2417 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(US_CHAR_TYPE),
2420 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, US_CHAR_TYPE);
2421 #endif /* MBS_SUPPORT */
2424 { /* Caller did not allocate a buffer. Do it for them. */
2425 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(US_CHAR_TYPE),
2429 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2431 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2432 #endif /* MBS_SUPPORT */
2433 bufp->allocated = INIT_BUF_SIZE;
2437 COMPILED_BUFFER_VAR = (US_CHAR_TYPE*) bufp->buffer;
2440 begalt = b = COMPILED_BUFFER_VAR;
2442 /* Loop through the uncompiled pattern until we're at the end. */
2451 if ( /* If at start of pattern, it's an operator. */
2453 /* If context independent, it's an operator. */
2454 || syntax & RE_CONTEXT_INDEP_ANCHORS
2455 /* Otherwise, depends on what's come before. */
2456 || at_begline_loc_p (pattern, p, syntax))
2466 if ( /* If at end of pattern, it's an operator. */
2468 /* If context independent, it's an operator. */
2469 || syntax & RE_CONTEXT_INDEP_ANCHORS
2470 /* Otherwise, depends on what's next. */
2471 || at_endline_loc_p (p, pend, syntax))
2481 if ((syntax & RE_BK_PLUS_QM)
2482 || (syntax & RE_LIMITED_OPS))
2486 /* If there is no previous pattern... */
2489 if (syntax & RE_CONTEXT_INVALID_OPS)
2490 FREE_STACK_RETURN (REG_BADRPT);
2491 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2496 /* Are we optimizing this jump? */
2497 boolean keep_string_p = false;
2499 /* 1 means zero (many) matches is allowed. */
2500 char zero_times_ok = 0, many_times_ok = 0;
2502 /* If there is a sequence of repetition chars, collapse it
2503 down to just one (the right one). We can't combine
2504 interval operators with these because of, e.g., `a{2}*',
2505 which should only match an even number of `a's. */
2509 zero_times_ok |= c != '+';
2510 many_times_ok |= c != '?';
2518 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2521 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2523 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2526 if (!(c1 == '+' || c1 == '?'))
2541 /* If we get here, we found another repeat character. */
2544 /* Star, etc. applied to an empty pattern is equivalent
2545 to an empty pattern. */
2549 /* Now we know whether or not zero matches is allowed
2550 and also whether or not two or more matches is allowed. */
2552 { /* More than one repetition is allowed, so put in at the
2553 end a backward relative jump from `b' to before the next
2554 jump we're going to put in below (which jumps from
2555 laststart to after this jump).
2557 But if we are at the `*' in the exact sequence `.*\n',
2558 insert an unconditional jump backwards to the .,
2559 instead of the beginning of the loop. This way we only
2560 push a failure point once, instead of every time
2561 through the loop. */
2562 assert (p - 1 > pattern);
2564 /* Allocate the space for the jump. */
2565 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2567 /* We know we are not at the first character of the pattern,
2568 because laststart was nonzero. And we've already
2569 incremented `p', by the way, to be the character after
2570 the `*'. Do we have to do something analogous here
2571 for null bytes, because of RE_DOT_NOT_NULL? */
2572 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2574 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2575 && !(syntax & RE_DOT_NEWLINE))
2576 { /* We have .*\n. */
2577 STORE_JUMP (jump, b, laststart);
2578 keep_string_p = true;
2581 /* Anything else. */
2582 STORE_JUMP (maybe_pop_jump, b, laststart -
2583 (1 + OFFSET_ADDRESS_SIZE));
2585 /* We've added more stuff to the buffer. */
2586 b += 1 + OFFSET_ADDRESS_SIZE;
2589 /* On failure, jump from laststart to b + 3, which will be the
2590 end of the buffer after this jump is inserted. */
2591 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2593 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2594 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2596 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2598 b += 1 + OFFSET_ADDRESS_SIZE;
2602 /* At least one repetition is required, so insert a
2603 `dummy_failure_jump' before the initial
2604 `on_failure_jump' instruction of the loop. This
2605 effects a skip over that instruction the first time
2606 we hit that loop. */
2607 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2608 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2609 2 + 2 * OFFSET_ADDRESS_SIZE);
2610 b += 1 + OFFSET_ADDRESS_SIZE;
2624 boolean had_char_class = false;
2626 CHAR_TYPE range_start = 0xffffffff;
2628 unsigned int range_start = 0xffffffff;
2630 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2633 /* We assume a charset(_not) structure as a wchar_t array.
2634 charset[0] = (re_opcode_t) charset(_not)
2635 charset[1] = l (= length of char_classes)
2636 charset[2] = m (= length of collating_symbols)
2637 charset[3] = n (= length of equivalence_classes)
2638 charset[4] = o (= length of char_ranges)
2639 charset[5] = p (= length of chars)
2641 charset[6] = char_class (wctype_t)
2642 charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2644 charset[l+5] = char_class (wctype_t)
2646 charset[l+6] = collating_symbol (wchar_t)
2648 charset[l+m+5] = collating_symbol (wchar_t)
2649 ifdef _LIBC we use the index if
2650 _NL_COLLATE_SYMB_EXTRAMB instead of
2653 charset[l+m+6] = equivalence_classes (wchar_t)
2655 charset[l+m+n+5] = equivalence_classes (wchar_t)
2656 ifdef _LIBC we use the index in
2657 _NL_COLLATE_WEIGHT instead of
2660 charset[l+m+n+6] = range_start
2661 charset[l+m+n+7] = range_end
2663 charset[l+m+n+2o+4] = range_start
2664 charset[l+m+n+2o+5] = range_end
2665 ifdef _LIBC we use the value looked up
2666 in _NL_COLLATE_COLLSEQ instead of
2669 charset[l+m+n+2o+6] = char
2671 charset[l+m+n+2o+p+5] = char
2675 /* We need at least 6 spaces: the opcode, the length of
2676 char_classes, the length of collating_symbols, the length of
2677 equivalence_classes, the length of char_ranges, the length of
2679 GET_BUFFER_SPACE (6);
2681 /* Save b as laststart. And We use laststart as the pointer
2682 to the first element of the charset here.
2683 In other words, laststart[i] indicates charset[i]. */
2686 /* We test `*p == '^' twice, instead of using an if
2687 statement, so we only need one BUF_PUSH. */
2688 BUF_PUSH (*p == '^' ? charset_not : charset);
2692 /* Push the length of char_classes, the length of
2693 collating_symbols, the length of equivalence_classes, the
2694 length of char_ranges and the length of chars. */
2695 BUF_PUSH_3 (0, 0, 0);
2698 /* Remember the first position in the bracket expression. */
2701 /* charset_not matches newline according to a syntax bit. */
2702 if ((re_opcode_t) b[-6] == charset_not
2703 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2706 laststart[5]++; /* Update the length of characters */
2709 /* Read in characters and ranges, setting map bits. */
2712 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2716 /* \ might escape characters inside [...] and [^...]. */
2717 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2719 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2723 laststart[5]++; /* Update the length of chars */
2728 /* Could be the end of the bracket expression. If it's
2729 not (i.e., when the bracket expression is `[]' so
2730 far), the ']' character bit gets set way below. */
2731 if (c == ']' && p != p1 + 1)
2734 /* Look ahead to see if it's a range when the last thing
2735 was a character class. */
2736 if (had_char_class && c == '-' && *p != ']')
2737 FREE_STACK_RETURN (REG_ERANGE);
2739 /* Look ahead to see if it's a range when the last thing
2740 was a character: if this is a hyphen not at the
2741 beginning or the end of a list, then it's the range
2744 && !(p - 2 >= pattern && p[-2] == '[')
2745 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2749 /* Allocate the space for range_start and range_end. */
2750 GET_BUFFER_SPACE (2);
2751 /* Update the pointer to indicate end of buffer. */
2753 ret = compile_range (range_start, &p, pend, translate,
2754 syntax, b, laststart);
2755 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2756 range_start = 0xffffffff;
2758 else if (p[0] == '-' && p[1] != ']')
2759 { /* This handles ranges made up of characters only. */
2762 /* Move past the `-'. */
2764 /* Allocate the space for range_start and range_end. */
2765 GET_BUFFER_SPACE (2);
2766 /* Update the pointer to indicate end of buffer. */
2768 ret = compile_range (c, &p, pend, translate, syntax, b,
2770 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2771 range_start = 0xffffffff;
2774 /* See if we're at the beginning of a possible character
2776 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2777 { /* Leave room for the null. */
2778 char str[CHAR_CLASS_MAX_LENGTH + 1];
2783 /* If pattern is `[[:'. */
2784 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2789 if ((c == ':' && *p == ']') || p == pend)
2791 if (c1 < CHAR_CLASS_MAX_LENGTH)
2794 /* This is in any case an invalid class name. */
2799 /* If isn't a word bracketed by `[:' and `:]':
2800 undo the ending character, the letters, and leave
2801 the leading `:' and `[' (but store them as character). */
2802 if (c == ':' && *p == ']')
2807 /* Query the character class as wctype_t. */
2808 wt = IS_CHAR_CLASS (str);
2810 FREE_STACK_RETURN (REG_ECTYPE);
2812 /* Throw away the ] at the end of the character
2816 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2818 /* Allocate the space for character class. */
2819 GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2820 /* Update the pointer to indicate end of buffer. */
2821 b += CHAR_CLASS_SIZE;
2822 /* Move data which follow character classes
2823 not to violate the data. */
2824 insert_space(CHAR_CLASS_SIZE,
2825 laststart + 6 + laststart[1],
2827 alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2828 + __alignof__(wctype_t) - 1)
2829 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2830 /* Store the character class. */
2831 *((wctype_t*)alignedp) = wt;
2832 /* Update length of char_classes */
2833 laststart[1] += CHAR_CLASS_SIZE;
2835 had_char_class = true;
2844 laststart[5] += 2; /* Update the length of characters */
2846 had_char_class = false;
2849 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2852 CHAR_TYPE str[128]; /* Should be large enough. */
2853 CHAR_TYPE delim = *p; /* '=' or '.' */
2856 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2861 /* If pattern is `[[=' or '[[.'. */
2862 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2867 if ((c == delim && *p == ']') || p == pend)
2869 if (c1 < sizeof (str) - 1)
2872 /* This is in any case an invalid class name. */
2877 if (c == delim && *p == ']' && str[0] != '\0')
2879 unsigned int i, offset;
2880 /* If we have no collation data we use the default
2881 collation in which each character is in a class
2882 by itself. It also means that ASCII is the
2883 character set and therefore we cannot have character
2884 with more than one byte in the multibyte
2887 /* If not defined _LIBC, we push the name and
2888 `\0' for the sake of matching performance. */
2889 int datasize = c1 + 1;
2897 FREE_STACK_RETURN (REG_ECOLLATE);
2902 const int32_t *table;
2903 const int32_t *weights;
2904 const int32_t *extra;
2905 const int32_t *indirect;
2908 /* This #include defines a local function! */
2909 # include <locale/weightwc.h>
2913 /* We push the index for equivalence class. */
2916 table = (const int32_t *)
2917 _NL_CURRENT (LC_COLLATE,
2918 _NL_COLLATE_TABLEWC);
2919 weights = (const int32_t *)
2920 _NL_CURRENT (LC_COLLATE,
2921 _NL_COLLATE_WEIGHTWC);
2922 extra = (const int32_t *)
2923 _NL_CURRENT (LC_COLLATE,
2924 _NL_COLLATE_EXTRAWC);
2925 indirect = (const int32_t *)
2926 _NL_CURRENT (LC_COLLATE,
2927 _NL_COLLATE_INDIRECTWC);
2929 idx = findidx ((const wint_t**)&cp);
2930 if (idx == 0 || cp < (wint_t*) str + c1)
2931 /* This is no valid character. */
2932 FREE_STACK_RETURN (REG_ECOLLATE);
2934 str[0] = (wchar_t)idx;
2936 else /* delim == '.' */
2938 /* We push collation sequence value
2939 for collating symbol. */
2941 const int32_t *symb_table;
2942 const unsigned char *extra;
2949 /* We have to convert the name to a single-byte
2950 string. This is possible since the names
2951 consist of ASCII characters and the internal
2952 representation is UCS4. */
2953 for (i = 0; i < c1; ++i)
2954 char_str[i] = str[i];
2957 _NL_CURRENT_WORD (LC_COLLATE,
2958 _NL_COLLATE_SYMB_HASH_SIZEMB);
2959 symb_table = (const int32_t *)
2960 _NL_CURRENT (LC_COLLATE,
2961 _NL_COLLATE_SYMB_TABLEMB);
2962 extra = (const unsigned char *)
2963 _NL_CURRENT (LC_COLLATE,
2964 _NL_COLLATE_SYMB_EXTRAMB);
2966 /* Locate the character in the hashing table. */
2967 hash = elem_hash (char_str, c1);
2970 elem = hash % table_size;
2971 second = hash % (table_size - 2);
2972 while (symb_table[2 * elem] != 0)
2974 /* First compare the hashing value. */
2975 if (symb_table[2 * elem] == hash
2976 && c1 == extra[symb_table[2 * elem + 1]]
2978 &extra[symb_table[2 * elem + 1]
2981 /* Yep, this is the entry. */
2982 idx = symb_table[2 * elem + 1];
2983 idx += 1 + extra[idx];
2991 if (symb_table[2 * elem] != 0)
2993 /* Compute the index of the byte sequence
2995 idx += 1 + extra[idx];
2996 /* Adjust for the alignment. */
2997 idx = (idx + 3) & ~4;
2999 str[0] = (wchar_t) idx + 4;
3001 else if (symb_table[2 * elem] == 0 && c1 == 1)
3003 /* No valid character. Match it as a
3004 single byte character. */
3005 had_char_class = false;
3007 /* Update the length of characters */
3009 range_start = str[0];
3011 /* Throw away the ] at the end of the
3012 collating symbol. */
3014 /* exit from the switch block. */
3018 FREE_STACK_RETURN (REG_ECOLLATE);
3023 /* Throw away the ] at the end of the equivalence
3024 class (or collating symbol). */
3027 /* Allocate the space for the equivalence class
3028 (or collating symbol) (and '\0' if needed). */
3029 GET_BUFFER_SPACE(datasize);
3030 /* Update the pointer to indicate end of buffer. */
3034 { /* equivalence class */
3035 /* Calculate the offset of char_ranges,
3036 which is next to equivalence_classes. */
3037 offset = laststart[1] + laststart[2]
3040 insert_space(datasize, laststart + offset, b - 1);
3042 /* Write the equivalence_class and \0. */
3043 for (i = 0 ; i < datasize ; i++)
3044 laststart[offset + i] = str[i];
3046 /* Update the length of equivalence_classes. */
3047 laststart[3] += datasize;
3048 had_char_class = true;
3050 else /* delim == '.' */
3051 { /* collating symbol */
3052 /* Calculate the offset of the equivalence_classes,
3053 which is next to collating_symbols. */
3054 offset = laststart[1] + laststart[2] + 6;
3055 /* Insert space and write the collationg_symbol
3057 insert_space(datasize, laststart + offset, b-1);
3058 for (i = 0 ; i < datasize ; i++)
3059 laststart[offset + i] = str[i];
3061 /* In re_match_2_internal if range_start < -1, we
3062 assume -range_start is the offset of the
3063 collating symbol which is specified as
3064 the character of the range start. So we assign
3065 -(laststart[1] + laststart[2] + 6) to
3067 range_start = -(laststart[1] + laststart[2] + 6);
3068 /* Update the length of collating_symbol. */
3069 laststart[2] += datasize;
3070 had_char_class = false;
3080 laststart[5] += 2; /* Update the length of characters */
3081 range_start = delim;
3082 had_char_class = false;
3087 had_char_class = false;
3089 laststart[5]++; /* Update the length of characters */
3094 #else /* not MBS_SUPPORT */
3095 /* Ensure that we have enough space to push a charset: the
3096 opcode, the length count, and the bitset; 34 bytes in all. */
3097 GET_BUFFER_SPACE (34);
3101 /* We test `*p == '^' twice, instead of using an if
3102 statement, so we only need one BUF_PUSH. */
3103 BUF_PUSH (*p == '^' ? charset_not : charset);
3107 /* Remember the first position in the bracket expression. */
3110 /* Push the number of bytes in the bitmap. */
3111 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3113 /* Clear the whole map. */
3114 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3116 /* charset_not matches newline according to a syntax bit. */
3117 if ((re_opcode_t) b[-2] == charset_not
3118 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3119 SET_LIST_BIT ('\n');
3121 /* Read in characters and ranges, setting map bits. */
3124 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3128 /* \ might escape characters inside [...] and [^...]. */
3129 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3131 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3139 /* Could be the end of the bracket expression. If it's
3140 not (i.e., when the bracket expression is `[]' so
3141 far), the ']' character bit gets set way below. */
3142 if (c == ']' && p != p1 + 1)
3145 /* Look ahead to see if it's a range when the last thing
3146 was a character class. */
3147 if (had_char_class && c == '-' && *p != ']')
3148 FREE_STACK_RETURN (REG_ERANGE);
3150 /* Look ahead to see if it's a range when the last thing
3151 was a character: if this is a hyphen not at the
3152 beginning or the end of a list, then it's the range
3155 && !(p - 2 >= pattern && p[-2] == '[')
3156 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3160 = compile_range (range_start, &p, pend, translate,
3162 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3163 range_start = 0xffffffff;
3166 else if (p[0] == '-' && p[1] != ']')
3167 { /* This handles ranges made up of characters only. */
3170 /* Move past the `-'. */
3173 ret = compile_range (c, &p, pend, translate, syntax, b);
3174 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3175 range_start = 0xffffffff;
3178 /* See if we're at the beginning of a possible character
3181 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3182 { /* Leave room for the null. */
3183 char str[CHAR_CLASS_MAX_LENGTH + 1];
3188 /* If pattern is `[[:'. */
3189 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3194 if ((c == ':' && *p == ']') || p == pend)
3196 if (c1 < CHAR_CLASS_MAX_LENGTH)
3199 /* This is in any case an invalid class name. */
3204 /* If isn't a word bracketed by `[:' and `:]':
3205 undo the ending character, the letters, and leave
3206 the leading `:' and `[' (but set bits for them). */
3207 if (c == ':' && *p == ']')
3209 # if defined _LIBC || WIDE_CHAR_SUPPORT
3210 boolean is_lower = STREQ (str, "lower");
3211 boolean is_upper = STREQ (str, "upper");
3215 wt = IS_CHAR_CLASS (str);
3217 FREE_STACK_RETURN (REG_ECTYPE);
3219 /* Throw away the ] at the end of the character
3223 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3225 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3228 if (__iswctype (__btowc (ch), wt))
3231 if (iswctype (btowc (ch), wt))
3235 if (translate && (is_upper || is_lower)
3236 && (ISUPPER (ch) || ISLOWER (ch)))
3240 had_char_class = true;
3243 boolean is_alnum = STREQ (str, "alnum");
3244 boolean is_alpha = STREQ (str, "alpha");
3245 boolean is_blank = STREQ (str, "blank");
3246 boolean is_cntrl = STREQ (str, "cntrl");
3247 boolean is_digit = STREQ (str, "digit");
3248 boolean is_graph = STREQ (str, "graph");
3249 boolean is_lower = STREQ (str, "lower");
3250 boolean is_print = STREQ (str, "print");
3251 boolean is_punct = STREQ (str, "punct");
3252 boolean is_space = STREQ (str, "space");
3253 boolean is_upper = STREQ (str, "upper");
3254 boolean is_xdigit = STREQ (str, "xdigit");
3256 if (!IS_CHAR_CLASS (str))
3257 FREE_STACK_RETURN (REG_ECTYPE);
3259 /* Throw away the ] at the end of the character
3263 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3265 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3267 /* This was split into 3 if's to
3268 avoid an arbitrary limit in some compiler. */
3269 if ( (is_alnum && ISALNUM (ch))
3270 || (is_alpha && ISALPHA (ch))
3271 || (is_blank && ISBLANK (ch))
3272 || (is_cntrl && ISCNTRL (ch)))
3274 if ( (is_digit && ISDIGIT (ch))
3275 || (is_graph && ISGRAPH (ch))
3276 || (is_lower && ISLOWER (ch))
3277 || (is_print && ISPRINT (ch)))
3279 if ( (is_punct && ISPUNCT (ch))
3280 || (is_space && ISSPACE (ch))
3281 || (is_upper && ISUPPER (ch))
3282 || (is_xdigit && ISXDIGIT (ch)))
3284 if ( translate && (is_upper || is_lower)
3285 && (ISUPPER (ch) || ISLOWER (ch)))
3288 had_char_class = true;
3289 # endif /* libc || wctype.h */
3299 had_char_class = false;
3302 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3304 unsigned char str[MB_LEN_MAX + 1];
3307 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3313 /* If pattern is `[[='. */
3314 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3319 if ((c == '=' && *p == ']') || p == pend)
3321 if (c1 < MB_LEN_MAX)
3324 /* This is in any case an invalid class name. */
3329 if (c == '=' && *p == ']' && str[0] != '\0')
3331 /* If we have no collation data we use the default
3332 collation in which each character is in a class
3333 by itself. It also means that ASCII is the
3334 character set and therefore we cannot have character
3335 with more than one byte in the multibyte
3342 FREE_STACK_RETURN (REG_ECOLLATE);
3344 /* Throw away the ] at the end of the equivalence
3348 /* Set the bit for the character. */
3349 SET_LIST_BIT (str[0]);
3354 /* Try to match the byte sequence in `str' against
3355 those known to the collate implementation.
3356 First find out whether the bytes in `str' are
3357 actually from exactly one character. */
3358 const int32_t *table;
3359 const unsigned char *weights;
3360 const unsigned char *extra;
3361 const int32_t *indirect;
3363 const unsigned char *cp = str;
3366 /* This #include defines a local function! */
3367 # include <locale/weight.h>
3369 table = (const int32_t *)
3370 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3371 weights = (const unsigned char *)
3372 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3373 extra = (const unsigned char *)
3374 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3375 indirect = (const int32_t *)
3376 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3378 idx = findidx (&cp);
3379 if (idx == 0 || cp < str + c1)
3380 /* This is no valid character. */
3381 FREE_STACK_RETURN (REG_ECOLLATE);
3383 /* Throw away the ] at the end of the equivalence
3387 /* Now we have to go throught the whole table
3388 and find all characters which have the same
3391 XXX Note that this is not entirely correct.
3392 we would have to match multibyte sequences
3393 but this is not possible with the current
3395 for (ch = 1; ch < 256; ++ch)
3396 /* XXX This test would have to be changed if we
3397 would allow matching multibyte sequences. */
3400 int32_t idx2 = table[ch];
3401 size_t len = weights[idx2];
3403 /* Test whether the lenghts match. */
3404 if (weights[idx] == len)
3406 /* They do. New compare the bytes of
3411 && (weights[idx + 1 + cnt]
3412 == weights[idx2 + 1 + cnt]))
3416 /* They match. Mark the character as
3423 had_char_class = true;
3433 had_char_class = false;
3436 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3438 unsigned char str[128]; /* Should be large enough. */
3441 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3447 /* If pattern is `[[.'. */
3448 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3453 if ((c == '.' && *p == ']') || p == pend)
3455 if (c1 < sizeof (str))
3458 /* This is in any case an invalid class name. */
3463 if (c == '.' && *p == ']' && str[0] != '\0')
3465 /* If we have no collation data we use the default
3466 collation in which each character is the name
3467 for its own class which contains only the one
3468 character. It also means that ASCII is the
3469 character set and therefore we cannot have character
3470 with more than one byte in the multibyte
3477 FREE_STACK_RETURN (REG_ECOLLATE);
3479 /* Throw away the ] at the end of the equivalence
3483 /* Set the bit for the character. */
3484 SET_LIST_BIT (str[0]);
3485 range_start = ((const unsigned char *) str)[0];
3490 /* Try to match the byte sequence in `str' against
3491 those known to the collate implementation.
3492 First find out whether the bytes in `str' are
3493 actually from exactly one character. */
3495 const int32_t *symb_table;
3496 const unsigned char *extra;
3503 _NL_CURRENT_WORD (LC_COLLATE,
3504 _NL_COLLATE_SYMB_HASH_SIZEMB);
3505 symb_table = (const int32_t *)
3506 _NL_CURRENT (LC_COLLATE,
3507 _NL_COLLATE_SYMB_TABLEMB);
3508 extra = (const unsigned char *)
3509 _NL_CURRENT (LC_COLLATE,
3510 _NL_COLLATE_SYMB_EXTRAMB);
3512 /* Locate the character in the hashing table. */
3513 hash = elem_hash (str, c1);
3516 elem = hash % table_size;
3517 second = hash % (table_size - 2);
3518 while (symb_table[2 * elem] != 0)
3520 /* First compare the hashing value. */
3521 if (symb_table[2 * elem] == hash
3522 && c1 == extra[symb_table[2 * elem + 1]]
3524 &extra[symb_table[2 * elem + 1]
3528 /* Yep, this is the entry. */
3529 idx = symb_table[2 * elem + 1];
3530 idx += 1 + extra[idx];
3538 if (symb_table[2 * elem] == 0)
3539 /* This is no valid character. */
3540 FREE_STACK_RETURN (REG_ECOLLATE);
3542 /* Throw away the ] at the end of the equivalence
3546 /* Now add the multibyte character(s) we found
3549 XXX Note that this is not entirely correct.
3550 we would have to match multibyte sequences
3551 but this is not possible with the current
3552 implementation. Also, we have to match
3553 collating symbols, which expand to more than
3554 one file, as a whole and not allow the
3555 individual bytes. */
3558 range_start = extra[idx];
3561 SET_LIST_BIT (extra[idx]);
3566 had_char_class = false;
3576 had_char_class = false;
3581 had_char_class = false;
3587 /* Discard any (non)matching list bytes that are all 0 at the
3588 end of the map. Decrease the map-length byte too. */
3589 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3592 #endif /* MBS_SUPPORT */
3598 if (syntax & RE_NO_BK_PARENS)
3605 if (syntax & RE_NO_BK_PARENS)
3612 if (syntax & RE_NEWLINE_ALT)
3619 if (syntax & RE_NO_BK_VBAR)
3626 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3627 goto handle_interval;
3633 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3635 /* Do not translate the character after the \, so that we can
3636 distinguish, e.g., \B from \b, even if we normally would
3637 translate, e.g., B to b. */
3643 if (syntax & RE_NO_BK_PARENS)
3644 goto normal_backslash;
3650 if (COMPILE_STACK_FULL)
3652 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3653 compile_stack_elt_t);
3654 if (compile_stack.stack == NULL) return REG_ESPACE;
3656 compile_stack.size <<= 1;
3659 /* These are the values to restore when we hit end of this
3660 group. They are all relative offsets, so that if the
3661 whole pattern moves because of realloc, they will still
3663 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3664 COMPILE_STACK_TOP.fixup_alt_jump
3665 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3666 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3667 COMPILE_STACK_TOP.regnum = regnum;
3669 /* We will eventually replace the 0 with the number of
3670 groups inner to this one. But do not push a
3671 start_memory for groups beyond the last one we can
3672 represent in the compiled pattern. */
3673 if (regnum <= MAX_REGNUM)
3675 COMPILE_STACK_TOP.inner_group_offset = b
3676 - COMPILED_BUFFER_VAR + 2;
3677 BUF_PUSH_3 (start_memory, regnum, 0);
3680 compile_stack.avail++;
3685 /* If we've reached MAX_REGNUM groups, then this open
3686 won't actually generate any code, so we'll have to
3687 clear pending_exact explicitly. */
3693 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3695 if (COMPILE_STACK_EMPTY)
3697 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3698 goto normal_backslash;
3700 FREE_STACK_RETURN (REG_ERPAREN);
3705 { /* Push a dummy failure point at the end of the
3706 alternative for a possible future
3707 `pop_failure_jump' to pop. See comments at
3708 `push_dummy_failure' in `re_match_2'. */
3709 BUF_PUSH (push_dummy_failure);
3711 /* We allocated space for this jump when we assigned
3712 to `fixup_alt_jump', in the `handle_alt' case below. */
3713 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3716 /* See similar code for backslashed left paren above. */
3717 if (COMPILE_STACK_EMPTY)
3719 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3722 FREE_STACK_RETURN (REG_ERPAREN);
3725 /* Since we just checked for an empty stack above, this
3726 ``can't happen''. */
3727 assert (compile_stack.avail != 0);
3729 /* We don't just want to restore into `regnum', because
3730 later groups should continue to be numbered higher,
3731 as in `(ab)c(de)' -- the second group is #2. */
3732 regnum_t this_group_regnum;
3734 compile_stack.avail--;
3735 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3737 = COMPILE_STACK_TOP.fixup_alt_jump
3738 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3740 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3741 this_group_regnum = COMPILE_STACK_TOP.regnum;
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. */
3747 /* We're at the end of the group, so now we know how many
3748 groups were inside this one. */
3749 if (this_group_regnum <= MAX_REGNUM)
3751 US_CHAR_TYPE *inner_group_loc
3752 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3754 *inner_group_loc = regnum - this_group_regnum;
3755 BUF_PUSH_3 (stop_memory, this_group_regnum,
3756 regnum - this_group_regnum);
3762 case '|': /* `\|'. */
3763 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3764 goto normal_backslash;
3766 if (syntax & RE_LIMITED_OPS)
3769 /* Insert before the previous alternative a jump which
3770 jumps to this alternative if the former fails. */
3771 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3772 INSERT_JUMP (on_failure_jump, begalt,
3773 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3775 b += 1 + OFFSET_ADDRESS_SIZE;
3777 /* The alternative before this one has a jump after it
3778 which gets executed if it gets matched. Adjust that
3779 jump so it will jump to this alternative's analogous
3780 jump (put in below, which in turn will jump to the next
3781 (if any) alternative's such jump, etc.). The last such
3782 jump jumps to the correct final destination. A picture:
3788 If we are at `b', then fixup_alt_jump right now points to a
3789 three-byte space after `a'. We'll put in the jump, set
3790 fixup_alt_jump to right after `b', and leave behind three
3791 bytes which we'll fill in when we get to after `c'. */
3794 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3796 /* Mark and leave space for a jump after this alternative,
3797 to be filled in later either by next alternative or
3798 when know we're at the end of a series of alternatives. */
3800 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3801 b += 1 + OFFSET_ADDRESS_SIZE;
3809 /* If \{ is a literal. */
3810 if (!(syntax & RE_INTERVALS)
3811 /* If we're at `\{' and it's not the open-interval
3813 || (syntax & RE_NO_BK_BRACES))
3814 goto normal_backslash;
3818 /* If got here, then the syntax allows intervals. */
3820 /* At least (most) this many matches must be made. */
3821 int lower_bound = -1, upper_bound = -1;
3823 /* Place in the uncompiled pattern (i.e., just after
3824 the '{') to go back to if the interval is invalid. */
3825 const CHAR_TYPE *beg_interval = p;
3828 goto invalid_interval;
3830 GET_UNSIGNED_NUMBER (lower_bound);
3834 GET_UNSIGNED_NUMBER (upper_bound);
3835 if (upper_bound < 0)
3836 upper_bound = RE_DUP_MAX;
3839 /* Interval such as `{1}' => match exactly once. */
3840 upper_bound = lower_bound;
3842 if (! (0 <= lower_bound && lower_bound <= upper_bound))
3843 goto invalid_interval;
3845 if (!(syntax & RE_NO_BK_BRACES))
3847 if (c != '\\' || p == pend)
3848 goto invalid_interval;
3853 goto invalid_interval;
3855 /* If it's invalid to have no preceding re. */
3858 if (syntax & RE_CONTEXT_INVALID_OPS
3859 && !(syntax & RE_INVALID_INTERVAL_ORD))
3860 FREE_STACK_RETURN (REG_BADRPT);
3861 else if (syntax & RE_CONTEXT_INDEP_OPS)
3864 goto unfetch_interval;
3867 /* We just parsed a valid interval. */
3869 if (RE_DUP_MAX < upper_bound)
3870 FREE_STACK_RETURN (REG_BADBR);
3872 /* If the upper bound is zero, don't want to succeed at
3873 all; jump from `laststart' to `b + 3', which will be
3874 the end of the buffer after we insert the jump. */
3875 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE'
3876 instead of 'b + 3'. */
3877 if (upper_bound == 0)
3879 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3880 INSERT_JUMP (jump, laststart, b + 1
3881 + OFFSET_ADDRESS_SIZE);
3882 b += 1 + OFFSET_ADDRESS_SIZE;
3885 /* Otherwise, we have a nontrivial interval. When
3886 we're all done, the pattern will look like:
3887 set_number_at <jump count> <upper bound>
3888 set_number_at <succeed_n count> <lower bound>
3889 succeed_n <after jump addr> <succeed_n count>
3891 jump_n <succeed_n addr> <jump count>
3892 (The upper bound and `jump_n' are omitted if
3893 `upper_bound' is 1, though.) */
3895 { /* If the upper bound is > 1, we need to insert
3896 more at the end of the loop. */
3897 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3898 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3900 GET_BUFFER_SPACE (nbytes);
3902 /* Initialize lower bound of the `succeed_n', even
3903 though it will be set during matching by its
3904 attendant `set_number_at' (inserted next),
3905 because `re_compile_fastmap' needs to know.
3906 Jump to the `jump_n' we might insert below. */
3907 INSERT_JUMP2 (succeed_n, laststart,
3908 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3909 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3911 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3913 /* Code to initialize the lower bound. Insert
3914 before the `succeed_n'. The `5' is the last two
3915 bytes of this `set_number_at', plus 3 bytes of
3916 the following `succeed_n'. */
3917 /* ifdef MBS_SUPPORT, The '1+2*OFFSET_ADDRESS_SIZE'
3918 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3919 of the following `succeed_n'. */
3920 insert_op2 (set_number_at, laststart, 1
3921 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3922 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3924 if (upper_bound > 1)
3925 { /* More than one repetition is allowed, so
3926 append a backward jump to the `succeed_n'
3927 that starts this interval.
3929 When we've reached this during matching,
3930 we'll have matched the interval once, so
3931 jump back only `upper_bound - 1' times. */
3932 STORE_JUMP2 (jump_n, b, laststart
3933 + 2 * OFFSET_ADDRESS_SIZE + 1,
3935 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3937 /* The location we want to set is the second
3938 parameter of the `jump_n'; that is `b-2' as
3939 an absolute address. `laststart' will be
3940 the `set_number_at' we're about to insert;
3941 `laststart+3' the number to set, the source
3942 for the relative address. But we are
3943 inserting into the middle of the pattern --
3944 so everything is getting moved up by 5.
3945 Conclusion: (b - 2) - (laststart + 3) + 5,
3946 i.e., b - laststart.
3948 We insert this at the beginning of the loop
3949 so that if we fail during matching, we'll
3950 reinitialize the bounds. */
3951 insert_op2 (set_number_at, laststart, b - laststart,
3952 upper_bound - 1, b);
3953 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3960 if (!(syntax & RE_INVALID_INTERVAL_ORD))
3961 FREE_STACK_RETURN (p == pend ? REG_EBRACE : REG_BADBR);
3963 /* Match the characters as literals. */
3966 if (syntax & RE_NO_BK_BRACES)
3969 goto normal_backslash;
3973 /* There is no way to specify the before_dot and after_dot
3974 operators. rms says this is ok. --karl */
3982 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3988 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3994 if (syntax & RE_NO_GNU_OPS)
3997 BUF_PUSH (wordchar);
4002 if (syntax & RE_NO_GNU_OPS)
4005 BUF_PUSH (notwordchar);
4010 if (syntax & RE_NO_GNU_OPS)
4016 if (syntax & RE_NO_GNU_OPS)
4022 if (syntax & RE_NO_GNU_OPS)
4024 BUF_PUSH (wordbound);
4028 if (syntax & RE_NO_GNU_OPS)
4030 BUF_PUSH (notwordbound);
4034 if (syntax & RE_NO_GNU_OPS)
4040 if (syntax & RE_NO_GNU_OPS)
4045 case '1': case '2': case '3': case '4': case '5':
4046 case '6': case '7': case '8': case '9':
4047 if (syntax & RE_NO_BK_REFS)
4053 FREE_STACK_RETURN (REG_ESUBREG);
4055 /* Can't back reference to a subexpression if inside of it. */
4056 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4060 BUF_PUSH_2 (duplicate, c1);
4066 if (syntax & RE_BK_PLUS_QM)
4069 goto normal_backslash;
4073 /* You might think it would be useful for \ to mean
4074 not to translate; but if we don't translate it
4075 it will never match anything. */
4083 /* Expects the character in `c'. */
4085 /* If no exactn currently being built. */
4088 /* If last exactn handle binary(or character) and
4089 new exactn handle character(or binary). */
4090 || is_exactn_bin != is_binary[p - 1 - pattern]
4091 #endif /* MBS_SUPPORT */
4093 /* If last exactn not at current position. */
4094 || pending_exact + *pending_exact + 1 != b
4096 /* We have only one byte following the exactn for the count. */
4097 || *pending_exact == (1 << BYTEWIDTH) - 1
4099 /* If followed by a repetition operator. */
4100 || *p == '*' || *p == '^'
4101 || ((syntax & RE_BK_PLUS_QM)
4102 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4103 : (*p == '+' || *p == '?'))
4104 || ((syntax & RE_INTERVALS)
4105 && ((syntax & RE_NO_BK_BRACES)
4107 : (p[0] == '\\' && p[1] == '{'))))
4109 /* Start building a new exactn. */
4114 /* Is this exactn binary data or character? */
4115 is_exactn_bin = is_binary[p - 1 - pattern];
4117 BUF_PUSH_2 (exactn_bin, 0);
4119 BUF_PUSH_2 (exactn, 0);
4121 BUF_PUSH_2 (exactn, 0);
4122 #endif /* MBS_SUPPORT */
4123 pending_exact = b - 1;
4130 } /* while p != pend */
4133 /* Through the pattern now. */
4136 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4138 if (!COMPILE_STACK_EMPTY)
4139 FREE_STACK_RETURN (REG_EPAREN);
4141 /* If we don't want backtracking, force success
4142 the first time we reach the end of the compiled pattern. */
4143 if (syntax & RE_NO_POSIX_BACKTRACKING)
4151 free (compile_stack.stack);
4153 /* We have succeeded; set the length of the buffer. */
4155 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4157 bufp->used = b - bufp->buffer;
4163 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4164 print_compiled_pattern (bufp);
4168 #ifndef MATCH_MAY_ALLOCATE
4169 /* Initialize the failure stack to the largest possible stack. This
4170 isn't necessary unless we're trying to avoid calling alloca in
4171 the search and match routines. */
4173 int num_regs = bufp->re_nsub + 1;
4175 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4176 is strictly greater than re_max_failures, the largest possible stack
4177 is 2 * re_max_failures failure points. */
4178 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4180 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4183 if (! fail_stack.stack)
4185 = (fail_stack_elt_t *) xmalloc (fail_stack.size
4186 * sizeof (fail_stack_elt_t));
4189 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
4191 * sizeof (fail_stack_elt_t)));
4192 # else /* not emacs */
4193 if (! fail_stack.stack)
4195 = (fail_stack_elt_t *) malloc (fail_stack.size
4196 * sizeof (fail_stack_elt_t));
4199 = (fail_stack_elt_t *) realloc (fail_stack.stack,
4201 * sizeof (fail_stack_elt_t)));
4202 # endif /* not emacs */
4205 regex_grow_registers (num_regs);
4207 #endif /* not MATCH_MAY_ALLOCATE */
4210 } /* regex_compile */
4212 /* Subroutines for `regex_compile'. */
4214 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4215 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4218 store_op1 (op, loc, arg)
4223 *loc = (US_CHAR_TYPE) op;
4224 STORE_NUMBER (loc + 1, arg);
4228 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4229 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4232 store_op2 (op, loc, arg1, arg2)
4237 *loc = (US_CHAR_TYPE) op;
4238 STORE_NUMBER (loc + 1, arg1);
4239 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4243 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4244 for OP followed by two-byte integer parameter ARG. */
4245 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4248 insert_op1 (op, loc, arg, end)
4254 register US_CHAR_TYPE *pfrom = end;
4255 register US_CHAR_TYPE *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4257 while (pfrom != loc)
4260 store_op1 (op, loc, arg);
4264 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4265 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4268 insert_op2 (op, loc, arg1, arg2, end)
4274 register US_CHAR_TYPE *pfrom = end;
4275 register US_CHAR_TYPE *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4277 while (pfrom != loc)
4280 store_op2 (op, loc, arg1, arg2);
4284 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4285 after an alternative or a begin-subexpression. We assume there is at
4286 least one character before the ^. */
4289 at_begline_loc_p (pattern, p, syntax)
4290 const CHAR_TYPE *pattern, *p;
4291 reg_syntax_t syntax;
4293 const CHAR_TYPE *prev = p - 2;
4294 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4297 /* After a subexpression? */
4298 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4299 /* After an alternative? */
4300 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4304 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4305 at least one character after the $, i.e., `P < PEND'. */
4308 at_endline_loc_p (p, pend, syntax)
4309 const CHAR_TYPE *p, *pend;
4310 reg_syntax_t syntax;
4312 const CHAR_TYPE *next = p;
4313 boolean next_backslash = *next == '\\';
4314 const CHAR_TYPE *next_next = p + 1 < pend ? p + 1 : 0;
4317 /* Before a subexpression? */
4318 (syntax & RE_NO_BK_PARENS ? *next == ')'
4319 : next_backslash && next_next && *next_next == ')')
4320 /* Before an alternative? */
4321 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4322 : next_backslash && next_next && *next_next == '|');
4326 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4327 false if it's not. */
4330 group_in_compile_stack (compile_stack, regnum)
4331 compile_stack_type compile_stack;
4336 for (this_element = compile_stack.avail - 1;
4339 if (compile_stack.stack[this_element].regnum == regnum)
4346 /* This insert space, which size is "num", into the pattern at "loc".
4347 "end" must point the end of the allocated buffer. */
4349 insert_space (num, loc, end)
4354 register CHAR_TYPE *pto = end;
4355 register CHAR_TYPE *pfrom = end - num;
4357 while (pfrom >= loc)
4360 #endif /* MBS_SUPPORT */
4363 static reg_errcode_t
4364 compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4366 CHAR_TYPE range_start_char;
4367 const CHAR_TYPE **p_ptr, *pend;
4368 CHAR_TYPE *char_set, *b;
4369 RE_TRANSLATE_TYPE translate;
4370 reg_syntax_t syntax;
4372 const CHAR_TYPE *p = *p_ptr;
4373 CHAR_TYPE range_start, range_end;
4377 uint32_t start_val, end_val;
4383 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4386 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4387 _NL_COLLATE_COLLSEQWC);
4388 const unsigned char *extra = (const unsigned char *)
4389 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4391 if (range_start_char < -1)
4393 /* range_start is a collating symbol. */
4395 /* Retreive the index and get collation sequence value. */
4396 wextra = (int32_t*)(extra + char_set[-range_start_char]);
4397 start_val = wextra[1 + *wextra];
4400 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4402 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4404 /* Report an error if the range is empty and the syntax prohibits
4406 ret = ((syntax & RE_NO_EMPTY_RANGES)
4407 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4409 /* Insert space to the end of the char_ranges. */
4410 insert_space(2, b - char_set[5] - 2, b - 1);
4411 *(b - char_set[5] - 2) = (wchar_t)start_val;
4412 *(b - char_set[5] - 1) = (wchar_t)end_val;
4413 char_set[4]++; /* ranges_index */
4418 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4420 range_end = TRANSLATE (p[0]);
4421 /* Report an error if the range is empty and the syntax prohibits
4423 ret = ((syntax & RE_NO_EMPTY_RANGES)
4424 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4426 /* Insert space to the end of the char_ranges. */
4427 insert_space(2, b - char_set[5] - 2, b - 1);
4428 *(b - char_set[5] - 2) = range_start;
4429 *(b - char_set[5] - 1) = range_end;
4430 char_set[4]++; /* ranges_index */
4432 /* Have to increment the pointer into the pattern string, so the
4433 caller isn't still at the ending character. */
4439 /* Read the ending character of a range (in a bracket expression) from the
4440 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4441 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4442 Then we set the translation of all bits between the starting and
4443 ending characters (inclusive) in the compiled pattern B.
4445 Return an error code.
4447 We use these short variable names so we can use the same macros as
4448 `regex_compile' itself. */
4450 static reg_errcode_t
4451 compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4452 unsigned int range_start_char;
4453 const char **p_ptr, *pend;
4454 RE_TRANSLATE_TYPE translate;
4455 reg_syntax_t syntax;
4459 const char *p = *p_ptr;
4462 const unsigned char *collseq;
4463 unsigned int start_colseq;
4464 unsigned int end_colseq;
4472 /* Have to increment the pointer into the pattern string, so the
4473 caller isn't still at the ending character. */
4476 /* Report an error if the range is empty and the syntax prohibits this. */
4477 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4480 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4481 _NL_COLLATE_COLLSEQMB);
4483 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4484 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4485 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4487 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4489 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4491 SET_LIST_BIT (TRANSLATE (this_char));
4496 /* Here we see why `this_char' has to be larger than an `unsigned
4497 char' -- we would otherwise go into an infinite loop, since all
4498 characters <= 0xff. */
4499 range_start_char = TRANSLATE (range_start_char);
4500 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4501 and some compilers cast it to int implicitly, so following for_loop
4502 may fall to (almost) infinite loop.
4503 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4504 To avoid this, we cast p[0] to unsigned int and truncate it. */
4505 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4507 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4509 SET_LIST_BIT (TRANSLATE (this_char));
4516 #endif /* MBS_SUPPORT */
4518 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4519 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4520 characters can start a string that matches the pattern. This fastmap
4521 is used by re_search to skip quickly over impossible starting points.
4523 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4524 area as BUFP->fastmap.
4526 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4529 Returns 0 if we succeed, -2 if an internal error. */
4532 /* local function for re_compile_fastmap.
4533 truncate wchar_t character to char. */
4534 static unsigned char truncate_wchar (CHAR_TYPE c);
4536 static unsigned char
4540 unsigned char buf[MB_LEN_MAX];
4541 int retval = wctomb(buf, c);
4542 return retval > 0 ? buf[0] : (unsigned char)c;
4544 #endif /* MBS_SUPPORT */
4547 re_compile_fastmap (bufp)
4548 struct re_pattern_buffer *bufp;
4551 #ifdef MATCH_MAY_ALLOCATE
4552 fail_stack_type fail_stack;
4554 #ifndef REGEX_MALLOC
4558 register char *fastmap = bufp->fastmap;
4561 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4562 pattern to (char*) in regex_compile. */
4563 US_CHAR_TYPE *pattern = (US_CHAR_TYPE*)bufp->buffer;
4564 register US_CHAR_TYPE *pend = (US_CHAR_TYPE*) (bufp->buffer + bufp->used);
4566 US_CHAR_TYPE *pattern = bufp->buffer;
4567 register US_CHAR_TYPE *pend = pattern + bufp->used;
4568 #endif /* MBS_SUPPORT */
4569 US_CHAR_TYPE *p = pattern;
4572 /* This holds the pointer to the failure stack, when
4573 it is allocated relocatably. */
4574 fail_stack_elt_t *failure_stack_ptr;
4577 /* Assume that each path through the pattern can be null until
4578 proven otherwise. We set this false at the bottom of switch
4579 statement, to which we get only if a particular path doesn't
4580 match the empty string. */
4581 boolean path_can_be_null = true;
4583 /* We aren't doing a `succeed_n' to begin with. */
4584 boolean succeed_n_p = false;
4586 assert (fastmap != NULL && p != NULL);
4589 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4590 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4591 bufp->can_be_null = 0;
4595 if (p == pend || *p == succeed)
4597 /* We have reached the (effective) end of pattern. */
4598 if (!FAIL_STACK_EMPTY ())
4600 bufp->can_be_null |= path_can_be_null;
4602 /* Reset for next path. */
4603 path_can_be_null = true;
4605 p = fail_stack.stack[--fail_stack.avail].pointer;
4613 /* We should never be about to go beyond the end of the pattern. */
4616 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4619 /* I guess the idea here is to simply not bother with a fastmap
4620 if a backreference is used, since it's too hard to figure out
4621 the fastmap for the corresponding group. Setting
4622 `can_be_null' stops `re_search_2' from using the fastmap, so
4623 that is all we do. */
4625 bufp->can_be_null = 1;
4629 /* Following are the cases which match a character. These end
4634 fastmap[truncate_wchar(p[1])] = 1;
4643 #endif /* MBS_SUPPORT */
4647 /* It is hard to distinguish fastmap from (multi byte) characters
4648 which depends on current locale. */
4653 bufp->can_be_null = 1;
4657 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4658 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4664 /* Chars beyond end of map must be allowed. */
4665 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4668 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4669 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4675 for (j = 0; j < (1 << BYTEWIDTH); j++)
4676 if (SYNTAX (j) == Sword)
4682 for (j = 0; j < (1 << BYTEWIDTH); j++)
4683 if (SYNTAX (j) != Sword)
4690 int fastmap_newline = fastmap['\n'];
4692 /* `.' matches anything ... */
4693 for (j = 0; j < (1 << BYTEWIDTH); j++)
4696 /* ... except perhaps newline. */
4697 if (!(bufp->syntax & RE_DOT_NEWLINE))
4698 fastmap['\n'] = fastmap_newline;
4700 /* Return if we have already set `can_be_null'; if we have,
4701 then the fastmap is irrelevant. Something's wrong here. */
4702 else if (bufp->can_be_null)
4705 /* Otherwise, have to check alternative paths. */
4712 for (j = 0; j < (1 << BYTEWIDTH); j++)
4713 if (SYNTAX (j) == (enum syntaxcode) k)
4720 for (j = 0; j < (1 << BYTEWIDTH); j++)
4721 if (SYNTAX (j) != (enum syntaxcode) k)
4726 /* All cases after this match the empty string. These end with
4746 case push_dummy_failure:
4751 case pop_failure_jump:
4752 case maybe_pop_jump:
4755 case dummy_failure_jump:
4756 EXTRACT_NUMBER_AND_INCR (j, p);
4761 /* Jump backward implies we just went through the body of a
4762 loop and matched nothing. Opcode jumped to should be
4763 `on_failure_jump' or `succeed_n'. Just treat it like an
4764 ordinary jump. For a * loop, it has pushed its failure
4765 point already; if so, discard that as redundant. */
4766 if ((re_opcode_t) *p != on_failure_jump
4767 && (re_opcode_t) *p != succeed_n)
4771 EXTRACT_NUMBER_AND_INCR (j, p);
4774 /* If what's on the stack is where we are now, pop it. */
4775 if (!FAIL_STACK_EMPTY ()
4776 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4782 case on_failure_jump:
4783 case on_failure_keep_string_jump:
4784 handle_on_failure_jump:
4785 EXTRACT_NUMBER_AND_INCR (j, p);
4787 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4788 end of the pattern. We don't want to push such a point,
4789 since when we restore it above, entering the switch will
4790 increment `p' past the end of the pattern. We don't need
4791 to push such a point since we obviously won't find any more
4792 fastmap entries beyond `pend'. Such a pattern can match
4793 the null string, though. */
4796 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4798 RESET_FAIL_STACK ();
4803 bufp->can_be_null = 1;
4807 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4808 succeed_n_p = false;
4815 /* Get to the number of times to succeed. */
4816 p += OFFSET_ADDRESS_SIZE;
4818 /* Increment p past the n for when k != 0. */
4819 EXTRACT_NUMBER_AND_INCR (k, p);
4822 p -= 2 * OFFSET_ADDRESS_SIZE;
4823 succeed_n_p = true; /* Spaghetti code alert. */
4824 goto handle_on_failure_jump;
4830 p += 2 * OFFSET_ADDRESS_SIZE;
4841 abort (); /* We have listed all the cases. */
4844 /* Getting here means we have found the possible starting
4845 characters for one path of the pattern -- and that the empty
4846 string does not match. We need not follow this path further.
4847 Instead, look at the next alternative (remembered on the
4848 stack), or quit if no more. The test at the top of the loop
4849 does these things. */
4850 path_can_be_null = false;
4854 /* Set `can_be_null' for the last path (also the first path, if the
4855 pattern is empty). */
4856 bufp->can_be_null |= path_can_be_null;
4859 RESET_FAIL_STACK ();
4861 } /* re_compile_fastmap */
4863 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4866 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4867 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4868 this memory for recording register information. STARTS and ENDS
4869 must be allocated using the malloc library routine, and must each
4870 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4872 If NUM_REGS == 0, then subsequent matches should allocate their own
4875 Unless this function is called, the first search or match using
4876 PATTERN_BUFFER will allocate its own register data, without
4877 freeing the old data. */
4880 re_set_registers (bufp, regs, num_regs, starts, ends)
4881 struct re_pattern_buffer *bufp;
4882 struct re_registers *regs;
4884 regoff_t *starts, *ends;
4888 bufp->regs_allocated = REGS_REALLOCATE;
4889 regs->num_regs = num_regs;
4890 regs->start = starts;
4895 bufp->regs_allocated = REGS_UNALLOCATED;
4897 regs->start = regs->end = (regoff_t *) 0;
4901 weak_alias (__re_set_registers, re_set_registers)
4904 /* Searching routines. */
4906 /* Like re_search_2, below, but only one string is specified, and
4907 doesn't let you say where to stop matching. */
4910 re_search (bufp, string, size, startpos, range, regs)
4911 struct re_pattern_buffer *bufp;
4913 int size, startpos, range;
4914 struct re_registers *regs;
4916 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4920 weak_alias (__re_search, re_search)
4924 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4925 virtual concatenation of STRING1 and STRING2, starting first at index
4926 STARTPOS, then at STARTPOS + 1, and so on.
4928 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4930 RANGE is how far to scan while trying to match. RANGE = 0 means try
4931 only at STARTPOS; in general, the last start tried is STARTPOS +
4934 In REGS, return the indices of the virtual concatenation of STRING1
4935 and STRING2 that matched the entire BUFP->buffer and its contained
4938 Do not consider matching one past the index STOP in the virtual
4939 concatenation of STRING1 and STRING2.
4941 We return either the position in the strings at which the match was
4942 found, -1 if no match, or -2 if error (such as failure
4946 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
4947 struct re_pattern_buffer *bufp;
4948 const char *string1, *string2;
4952 struct re_registers *regs;
4956 register char *fastmap = bufp->fastmap;
4957 register RE_TRANSLATE_TYPE translate = bufp->translate;
4958 int total_size = size1 + size2;
4959 int endpos = startpos + range;
4961 /* Check for out-of-range STARTPOS. */
4962 if (startpos < 0 || startpos > total_size)
4965 /* Fix up RANGE if it might eventually take us outside
4966 the virtual concatenation of STRING1 and STRING2.
4967 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4969 range = 0 - startpos;
4970 else if (endpos > total_size)
4971 range = total_size - startpos;
4973 /* If the search isn't to be a backwards one, don't waste time in a
4974 search for a pattern that must be anchored. */
4975 if (bufp->used > 0 && range > 0
4976 && ((re_opcode_t) bufp->buffer[0] == begbuf
4977 /* `begline' is like `begbuf' if it cannot match at newlines. */
4978 || ((re_opcode_t) bufp->buffer[0] == begline
4979 && !bufp->newline_anchor)))
4988 /* In a forward search for something that starts with \=.
4989 don't keep searching past point. */
4990 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4992 range = PT - startpos;
4998 /* Update the fastmap now if not correct already. */
4999 if (fastmap && !bufp->fastmap_accurate)
5000 if (re_compile_fastmap (bufp) == -2)
5003 /* Loop through the string, looking for a place to start matching. */
5006 /* If a fastmap is supplied, skip quickly over characters that
5007 cannot be the start of a match. If the pattern can match the
5008 null string, however, we don't need to skip characters; we want
5009 the first null string. */
5010 if (fastmap && startpos < total_size && !bufp->can_be_null)
5012 if (range > 0) /* Searching forwards. */
5014 register const char *d;
5015 register int lim = 0;
5018 if (startpos < size1 && startpos + range >= size1)
5019 lim = range - (size1 - startpos);
5021 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5023 /* Written out as an if-else to avoid testing `translate'
5027 && !fastmap[(unsigned char)
5028 translate[(unsigned char) *d++]])
5031 while (range > lim && !fastmap[(unsigned char) *d++])
5034 startpos += irange - range;
5036 else /* Searching backwards. */
5038 register CHAR_TYPE c = (size1 == 0 || startpos >= size1
5039 ? string2[startpos - size1]
5040 : string1[startpos]);
5042 if (!fastmap[(unsigned char) TRANSLATE (c)])
5047 /* If can't match the null string, and that's all we have left, fail. */
5048 if (range >= 0 && startpos == total_size && fastmap
5049 && !bufp->can_be_null)
5052 val = re_match_2_internal (bufp, string1, size1, string2, size2,
5053 startpos, regs, stop);
5054 #ifndef REGEX_MALLOC
5083 weak_alias (__re_search_2, re_search_2)
5087 /* This converts PTR, a pointer into one of the search wchar_t strings
5088 `string1' and `string2' into an multibyte string offset from the
5089 beginning of that string. We use mbs_offset to optimize.
5090 See convert_mbs_to_wcs. */
5091 # define POINTER_TO_OFFSET(ptr) \
5092 (FIRST_STRING_P (ptr) \
5093 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5094 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5097 /* This converts PTR, a pointer into one of the search strings `string1'
5098 and `string2' into an offset from the beginning of that string. */
5099 # define POINTER_TO_OFFSET(ptr) \
5100 (FIRST_STRING_P (ptr) \
5101 ? ((regoff_t) ((ptr) - string1)) \
5102 : ((regoff_t) ((ptr) - string2 + size1)))
5103 #endif /* MBS_SUPPORT */
5105 /* Macros for dealing with the split strings in re_match_2. */
5107 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5109 /* Call before fetching a character with *d. This switches over to
5110 string2 if necessary. */
5111 #define PREFETCH() \
5114 /* End of string2 => fail. */ \
5115 if (dend == end_match_2) \
5117 /* End of string1 => advance to string2. */ \
5119 dend = end_match_2; \
5123 /* Test if at very beginning or at very end of the virtual concatenation
5124 of `string1' and `string2'. If only one string, it's `string2'. */
5125 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5126 #define AT_STRINGS_END(d) ((d) == end2)
5129 /* Test if D points to a character which is word-constituent. We have
5130 two special cases to check for: if past the end of string1, look at
5131 the first character in string2; and if before the beginning of
5132 string2, look at the last character in string1. */
5134 /* Use internationalized API instead of SYNTAX. */
5135 # define WORDCHAR_P(d) \
5136 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5137 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5139 # define WORDCHAR_P(d) \
5140 (SYNTAX ((d) == end1 ? *string2 \
5141 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5143 #endif /* MBS_SUPPORT */
5145 /* Disabled due to a compiler bug -- see comment at case wordbound */
5147 /* Test if the character before D and the one at D differ with respect
5148 to being word-constituent. */
5149 #define AT_WORD_BOUNDARY(d) \
5150 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5151 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5154 /* Free everything we malloc. */
5155 #ifdef MATCH_MAY_ALLOCATE
5156 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5158 # define FREE_VARIABLES() \
5160 REGEX_FREE_STACK (fail_stack.stack); \
5161 FREE_VAR (regstart); \
5162 FREE_VAR (regend); \
5163 FREE_VAR (old_regstart); \
5164 FREE_VAR (old_regend); \
5165 FREE_VAR (best_regstart); \
5166 FREE_VAR (best_regend); \
5167 FREE_VAR (reg_info); \
5168 FREE_VAR (reg_dummy); \
5169 FREE_VAR (reg_info_dummy); \
5170 FREE_VAR (string1); \
5171 FREE_VAR (string2); \
5172 FREE_VAR (mbs_offset1); \
5173 FREE_VAR (mbs_offset2); \
5175 # else /* not MBS_SUPPORT */
5176 # define FREE_VARIABLES() \
5178 REGEX_FREE_STACK (fail_stack.stack); \
5179 FREE_VAR (regstart); \
5180 FREE_VAR (regend); \
5181 FREE_VAR (old_regstart); \
5182 FREE_VAR (old_regend); \
5183 FREE_VAR (best_regstart); \
5184 FREE_VAR (best_regend); \
5185 FREE_VAR (reg_info); \
5186 FREE_VAR (reg_dummy); \
5187 FREE_VAR (reg_info_dummy); \
5189 # endif /* MBS_SUPPORT */
5191 # define FREE_VAR(var) if (var) free (var); var = NULL
5193 # define FREE_VARIABLES() \
5195 FREE_VAR (string1); \
5196 FREE_VAR (string2); \
5197 FREE_VAR (mbs_offset1); \
5198 FREE_VAR (mbs_offset2); \
5201 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5202 # endif /* MBS_SUPPORT */
5203 #endif /* not MATCH_MAY_ALLOCATE */
5205 /* These values must meet several constraints. They must not be valid
5206 register values; since we have a limit of 255 registers (because
5207 we use only one byte in the pattern for the register number), we can
5208 use numbers larger than 255. They must differ by 1, because of
5209 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5210 be larger than the value for the highest register, so we do not try
5211 to actually save any registers when none are active. */
5212 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5213 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5215 /* Matching routines. */
5217 #ifndef emacs /* Emacs never uses this. */
5218 /* re_match is like re_match_2 except it takes only a single string. */
5221 re_match (bufp, string, size, pos, regs)
5222 struct re_pattern_buffer *bufp;
5225 struct re_registers *regs;
5227 int result = re_match_2_internal (bufp, NULL, 0, string, size,
5229 # ifndef REGEX_MALLOC
5237 weak_alias (__re_match, re_match)
5239 #endif /* not emacs */
5241 static boolean group_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5243 register_info_type *reg_info));
5244 static boolean alt_match_null_string_p _RE_ARGS ((US_CHAR_TYPE *p,
5246 register_info_type *reg_info));
5247 static boolean common_op_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5249 register_info_type *reg_info));
5250 static int bcmp_translate _RE_ARGS ((const CHAR_TYPE *s1, const CHAR_TYPE *s2,
5251 int len, char *translate));
5253 /* re_match_2 matches the compiled pattern in BUFP against the
5254 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5255 and SIZE2, respectively). We start matching at POS, and stop
5258 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5259 store offsets for the substring each group matched in REGS. See the
5260 documentation for exactly how many groups we fill.
5262 We return -1 if no match, -2 if an internal error (such as the
5263 failure stack overflowing). Otherwise, we return the length of the
5264 matched substring. */
5267 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5268 struct re_pattern_buffer *bufp;
5269 const char *string1, *string2;
5272 struct re_registers *regs;
5275 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
5277 #ifndef REGEX_MALLOC
5285 weak_alias (__re_match_2, re_match_2)
5290 static int count_mbs_length PARAMS ((int *, int));
5292 /* This check the substring (from 0, to length) of the multibyte string,
5293 to which offset_buffer correspond. And count how many wchar_t_characters
5294 the substring occupy. We use offset_buffer to optimization.
5295 See convert_mbs_to_wcs. */
5298 count_mbs_length(offset_buffer, length)
5304 /* Check whether the size is valid. */
5308 if (offset_buffer == NULL)
5311 for (wcs_size = 0 ; offset_buffer[wcs_size] != -1 ; wcs_size++)
5313 if (offset_buffer[wcs_size] == length)
5315 if (offset_buffer[wcs_size] > length)
5316 /* It is a fragment of a wide character. */
5320 /* We reached at the sentinel. */
5323 #endif /* MBS_SUPPORT */
5325 /* This is a separate function so that we can force an alloca cleanup
5329 re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos, regs, stop)
5330 struct re_pattern_buffer *bufp;
5331 const char *cstring1, *cstring2;
5334 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
5335 struct re_pattern_buffer *bufp;
5336 const char *string1, *string2;
5340 struct re_registers *regs;
5343 /* General temporaries. */
5347 /* We need wchar_t* buffers correspond to string1, string2. */
5348 CHAR_TYPE *string1 = NULL, *string2 = NULL;
5349 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5350 int size1 = 0, size2 = 0;
5351 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5352 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5353 /* They hold whether each wchar_t is binary data or not. */
5354 char *is_binary = NULL;
5355 #endif /* MBS_SUPPORT */
5357 /* Just past the end of the corresponding string. */
5358 const CHAR_TYPE *end1, *end2;
5360 /* Pointers into string1 and string2, just past the last characters in
5361 each to consider matching. */
5362 const CHAR_TYPE *end_match_1, *end_match_2;
5364 /* Where we are in the data, and the end of the current string. */
5365 const CHAR_TYPE *d, *dend;
5367 /* Where we are in the pattern, and the end of the pattern. */
5369 US_CHAR_TYPE *pattern, *p;
5370 register US_CHAR_TYPE *pend;
5372 US_CHAR_TYPE *p = bufp->buffer;
5373 register US_CHAR_TYPE *pend = p + bufp->used;
5374 #endif /* MBS_SUPPORT */
5376 /* Mark the opcode just after a start_memory, so we can test for an
5377 empty subpattern when we get to the stop_memory. */
5378 US_CHAR_TYPE *just_past_start_mem = 0;
5380 /* We use this to map every character in the string. */
5381 RE_TRANSLATE_TYPE translate = bufp->translate;
5383 /* Failure point stack. Each place that can handle a failure further
5384 down the line pushes a failure point on this stack. It consists of
5385 restart, regend, and reg_info for all registers corresponding to
5386 the subexpressions we're currently inside, plus the number of such
5387 registers, and, finally, two char *'s. The first char * is where
5388 to resume scanning the pattern; the second one is where to resume
5389 scanning the strings. If the latter is zero, the failure point is
5390 a ``dummy''; if a failure happens and the failure point is a dummy,
5391 it gets discarded and the next next one is tried. */
5392 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5393 fail_stack_type fail_stack;
5396 static unsigned failure_id;
5397 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5401 /* This holds the pointer to the failure stack, when
5402 it is allocated relocatably. */
5403 fail_stack_elt_t *failure_stack_ptr;
5406 /* We fill all the registers internally, independent of what we
5407 return, for use in backreferences. The number here includes
5408 an element for register zero. */
5409 size_t num_regs = bufp->re_nsub + 1;
5411 /* The currently active registers. */
5412 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5413 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5415 /* Information on the contents of registers. These are pointers into
5416 the input strings; they record just what was matched (on this
5417 attempt) by a subexpression part of the pattern, that is, the
5418 regnum-th regstart pointer points to where in the pattern we began
5419 matching and the regnum-th regend points to right after where we
5420 stopped matching the regnum-th subexpression. (The zeroth register
5421 keeps track of what the whole pattern matches.) */
5422 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5423 const CHAR_TYPE **regstart, **regend;
5426 /* If a group that's operated upon by a repetition operator fails to
5427 match anything, then the register for its start will need to be
5428 restored because it will have been set to wherever in the string we
5429 are when we last see its open-group operator. Similarly for a
5431 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5432 const CHAR_TYPE **old_regstart, **old_regend;
5435 /* The is_active field of reg_info helps us keep track of which (possibly
5436 nested) subexpressions we are currently in. The matched_something
5437 field of reg_info[reg_num] helps us tell whether or not we have
5438 matched any of the pattern so far this time through the reg_num-th
5439 subexpression. These two fields get reset each time through any
5440 loop their register is in. */
5441 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5442 register_info_type *reg_info;
5445 /* The following record the register info as found in the above
5446 variables when we find a match better than any we've seen before.
5447 This happens as we backtrack through the failure points, which in
5448 turn happens only if we have not yet matched the entire string. */
5449 unsigned best_regs_set = false;
5450 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5451 const CHAR_TYPE **best_regstart, **best_regend;
5454 /* Logically, this is `best_regend[0]'. But we don't want to have to
5455 allocate space for that if we're not allocating space for anything
5456 else (see below). Also, we never need info about register 0 for
5457 any of the other register vectors, and it seems rather a kludge to
5458 treat `best_regend' differently than the rest. So we keep track of
5459 the end of the best match so far in a separate variable. We
5460 initialize this to NULL so that when we backtrack the first time
5461 and need to test it, it's not garbage. */
5462 const CHAR_TYPE *match_end = NULL;
5464 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5465 int set_regs_matched_done = 0;
5467 /* Used when we pop values we don't care about. */
5468 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5469 const CHAR_TYPE **reg_dummy;
5470 register_info_type *reg_info_dummy;
5474 /* Counts the total number of registers pushed. */
5475 unsigned num_regs_pushed = 0;
5478 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5482 #ifdef MATCH_MAY_ALLOCATE
5483 /* Do not bother to initialize all the register variables if there are
5484 no groups in the pattern, as it takes a fair amount of time. If
5485 there are groups, we include space for register 0 (the whole
5486 pattern), even though we never use it, since it simplifies the
5487 array indexing. We should fix this. */
5490 regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5491 regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5492 old_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5493 old_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5494 best_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5495 best_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5496 reg_info = REGEX_TALLOC (num_regs, register_info_type);
5497 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5498 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
5500 if (!(regstart && regend && old_regstart && old_regend && reg_info
5501 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5509 /* We must initialize all our variables to NULL, so that
5510 `FREE_VARIABLES' doesn't try to free them. */
5511 regstart = regend = old_regstart = old_regend = best_regstart
5512 = best_regend = reg_dummy = NULL;
5513 reg_info = reg_info_dummy = (register_info_type *) NULL;
5515 #endif /* MATCH_MAY_ALLOCATE */
5517 /* The starting position is bogus. */
5519 if (pos < 0 || pos > csize1 + csize2)
5521 if (pos < 0 || pos > size1 + size2)
5529 /* Allocate wchar_t array for string1 and string2 and
5530 fill them with converted string. */
5533 string1 = REGEX_TALLOC (csize1 + 1, CHAR_TYPE);
5534 mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5535 is_binary = REGEX_TALLOC (csize1 + 1, char);
5536 if (!string1 || !mbs_offset1 || !is_binary)
5539 FREE_VAR (mbs_offset1);
5540 FREE_VAR (is_binary);
5543 size1 = convert_mbs_to_wcs(string1, cstring1, csize1,
5544 mbs_offset1, is_binary);
5545 string1[size1] = L'\0'; /* for a sentinel */
5546 FREE_VAR (is_binary);
5550 string2 = REGEX_TALLOC (csize2 + 1, CHAR_TYPE);
5551 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5552 is_binary = REGEX_TALLOC (csize2 + 1, char);
5553 if (!string2 || !mbs_offset2 || !is_binary)
5556 FREE_VAR (mbs_offset1);
5558 FREE_VAR (mbs_offset2);
5559 FREE_VAR (is_binary);
5562 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5563 mbs_offset2, is_binary);
5564 string2[size2] = L'\0'; /* for a sentinel */
5565 FREE_VAR (is_binary);
5568 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5569 pattern to (char*) in regex_compile. */
5570 p = pattern = (CHAR_TYPE*)bufp->buffer;
5571 pend = (CHAR_TYPE*)(bufp->buffer + bufp->used);
5573 #endif /* MBS_SUPPORT */
5575 /* Initialize subexpression text positions to -1 to mark ones that no
5576 start_memory/stop_memory has been seen for. Also initialize the
5577 register information struct. */
5578 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5580 regstart[mcnt] = regend[mcnt]
5581 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5583 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5584 IS_ACTIVE (reg_info[mcnt]) = 0;
5585 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5586 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5589 /* We move `string1' into `string2' if the latter's empty -- but not if
5590 `string1' is null. */
5591 if (size2 == 0 && string1 != NULL)
5598 mbs_offset2 = mbs_offset1;
5604 end1 = string1 + size1;
5605 end2 = string2 + size2;
5607 /* Compute where to stop matching, within the two strings. */
5611 mcnt = count_mbs_length(mbs_offset1, stop);
5612 end_match_1 = string1 + mcnt;
5613 end_match_2 = string2;
5617 if (stop > csize1 + csize2)
5618 stop = csize1 + csize2;
5620 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5621 end_match_2 = string2 + mcnt;
5624 { /* count_mbs_length return error. */
5631 end_match_1 = string1 + stop;
5632 end_match_2 = string2;
5637 end_match_2 = string2 + stop - size1;
5639 #endif /* MBS_SUPPORT */
5641 /* `p' scans through the pattern as `d' scans through the data.
5642 `dend' is the end of the input string that `d' points within. `d'
5643 is advanced into the following input string whenever necessary, but
5644 this happens before fetching; therefore, at the beginning of the
5645 loop, `d' can be pointing at the end of a string, but it cannot
5648 if (size1 > 0 && pos <= csize1)
5650 mcnt = count_mbs_length(mbs_offset1, pos);
5656 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5662 { /* count_mbs_length return error. */
5667 if (size1 > 0 && pos <= size1)
5674 d = string2 + pos - size1;
5677 #endif /* MBS_SUPPORT */
5679 DEBUG_PRINT1 ("The compiled pattern is:\n");
5680 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5681 DEBUG_PRINT1 ("The string to match is: `");
5682 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5683 DEBUG_PRINT1 ("'\n");
5685 /* This loops over pattern commands. It exits by returning from the
5686 function if the match is complete, or it drops through if the match
5687 fails at this starting point in the input data. */
5691 DEBUG_PRINT2 ("\n%p: ", p);
5693 DEBUG_PRINT2 ("\n0x%x: ", p);
5697 { /* End of pattern means we might have succeeded. */
5698 DEBUG_PRINT1 ("end of pattern ... ");
5700 /* If we haven't matched the entire string, and we want the
5701 longest match, try backtracking. */
5702 if (d != end_match_2)
5704 /* 1 if this match ends in the same string (string1 or string2)
5705 as the best previous match. */
5706 boolean same_str_p = (FIRST_STRING_P (match_end)
5707 == MATCHING_IN_FIRST_STRING);
5708 /* 1 if this match is the best seen so far. */
5709 boolean best_match_p;
5711 /* AIX compiler got confused when this was combined
5712 with the previous declaration. */
5714 best_match_p = d > match_end;
5716 best_match_p = !MATCHING_IN_FIRST_STRING;
5718 DEBUG_PRINT1 ("backtracking.\n");
5720 if (!FAIL_STACK_EMPTY ())
5721 { /* More failure points to try. */
5723 /* If exceeds best match so far, save it. */
5724 if (!best_regs_set || best_match_p)
5726 best_regs_set = true;
5729 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5731 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5733 best_regstart[mcnt] = regstart[mcnt];
5734 best_regend[mcnt] = regend[mcnt];
5740 /* If no failure points, don't restore garbage. And if
5741 last match is real best match, don't restore second
5743 else if (best_regs_set && !best_match_p)
5746 /* Restore best match. It may happen that `dend ==
5747 end_match_1' while the restored d is in string2.
5748 For example, the pattern `x.*y.*z' against the
5749 strings `x-' and `y-z-', if the two strings are
5750 not consecutive in memory. */
5751 DEBUG_PRINT1 ("Restoring best registers.\n");
5754 dend = ((d >= string1 && d <= end1)
5755 ? end_match_1 : end_match_2);
5757 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5759 regstart[mcnt] = best_regstart[mcnt];
5760 regend[mcnt] = best_regend[mcnt];
5763 } /* d != end_match_2 */
5766 DEBUG_PRINT1 ("Accepting match.\n");
5767 /* If caller wants register contents data back, do it. */
5768 if (regs && !bufp->no_sub)
5770 /* Have the register data arrays been allocated? */
5771 if (bufp->regs_allocated == REGS_UNALLOCATED)
5772 { /* No. So allocate them with malloc. We need one
5773 extra element beyond `num_regs' for the `-1' marker
5775 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5776 regs->start = TALLOC (regs->num_regs, regoff_t);
5777 regs->end = TALLOC (regs->num_regs, regoff_t);
5778 if (regs->start == NULL || regs->end == NULL)
5783 bufp->regs_allocated = REGS_REALLOCATE;
5785 else if (bufp->regs_allocated == REGS_REALLOCATE)
5786 { /* Yes. If we need more elements than were already
5787 allocated, reallocate them. If we need fewer, just
5789 if (regs->num_regs < num_regs + 1)
5791 regs->num_regs = num_regs + 1;
5792 RETALLOC (regs->start, regs->num_regs, regoff_t);
5793 RETALLOC (regs->end, regs->num_regs, regoff_t);
5794 if (regs->start == NULL || regs->end == NULL)
5803 /* These braces fend off a "empty body in an else-statement"
5804 warning under GCC when assert expands to nothing. */
5805 assert (bufp->regs_allocated == REGS_FIXED);
5808 /* Convert the pointer data in `regstart' and `regend' to
5809 indices. Register zero has to be set differently,
5810 since we haven't kept track of any info for it. */
5811 if (regs->num_regs > 0)
5813 regs->start[0] = pos;
5815 if (MATCHING_IN_FIRST_STRING)
5816 regs->end[0] = mbs_offset1 != NULL ?
5817 mbs_offset1[d-string1] : 0;
5819 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
5820 mbs_offset2[d-string2] : 0);
5822 regs->end[0] = (MATCHING_IN_FIRST_STRING
5823 ? ((regoff_t) (d - string1))
5824 : ((regoff_t) (d - string2 + size1)));
5825 #endif /* MBS_SUPPORT */
5828 /* Go through the first `min (num_regs, regs->num_regs)'
5829 registers, since that is all we initialized. */
5830 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
5833 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
5834 regs->start[mcnt] = regs->end[mcnt] = -1;
5838 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
5840 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
5844 /* If the regs structure we return has more elements than
5845 were in the pattern, set the extra elements to -1. If
5846 we (re)allocated the registers, this is the case,
5847 because we always allocate enough to have at least one
5849 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
5850 regs->start[mcnt] = regs->end[mcnt] = -1;
5851 } /* regs && !bufp->no_sub */
5853 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5854 nfailure_points_pushed, nfailure_points_popped,
5855 nfailure_points_pushed - nfailure_points_popped);
5856 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5859 if (MATCHING_IN_FIRST_STRING)
5860 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
5862 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
5866 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
5869 #endif /* MBS_SUPPORT */
5871 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5877 /* Otherwise match next pattern command. */
5878 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5880 /* Ignore these. Used to ignore the n of succeed_n's which
5881 currently have n == 0. */
5883 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5887 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5890 /* Match the next n pattern characters exactly. The following
5891 byte in the pattern defines n, and the n bytes after that
5892 are the characters to match. */
5898 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5900 /* This is written out as an if-else so we don't waste time
5901 testing `translate' inside the loop. */
5910 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5911 != (US_CHAR_TYPE) *p++)
5916 if (*d++ != (CHAR_TYPE) *p++)
5920 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5921 != (US_CHAR_TYPE) *p++)
5923 #endif /* MBS_SUPPORT */
5932 if (*d++ != (CHAR_TYPE) *p++) goto fail;
5936 SET_REGS_MATCHED ();
5940 /* Match any character except possibly a newline or a null. */
5942 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5946 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
5947 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
5950 SET_REGS_MATCHED ();
5951 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
5959 register US_CHAR_TYPE c;
5961 unsigned int i, char_class_length, coll_symbol_length,
5962 equiv_class_length, ranges_length, chars_length, length;
5963 CHAR_TYPE *workp, *workp2, *charset_top;
5964 #define WORK_BUFFER_SIZE 128
5965 CHAR_TYPE str_buf[WORK_BUFFER_SIZE];
5969 #endif /* MBS_SUPPORT */
5970 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5972 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5974 c = TRANSLATE (*d); /* The character to match. */
5977 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
5979 charset_top = p - 1;
5980 char_class_length = *p++;
5981 coll_symbol_length = *p++;
5982 equiv_class_length = *p++;
5983 ranges_length = *p++;
5984 chars_length = *p++;
5985 /* p points charset[6], so the address of the next instruction
5986 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
5987 where l=length of char_classes, m=length of collating_symbol,
5988 n=equivalence_class, o=length of char_range,
5989 p'=length of character. */
5991 /* Update p to indicate the next instruction. */
5992 p += char_class_length + coll_symbol_length+ equiv_class_length +
5993 2*ranges_length + chars_length;
5995 /* match with char_class? */
5996 for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
5999 uintptr_t alignedp = ((uintptr_t)workp
6000 + __alignof__(wctype_t) - 1)
6001 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6002 wctype = *((wctype_t*)alignedp);
6003 workp += CHAR_CLASS_SIZE;
6004 if (iswctype((wint_t)c, wctype))
6005 goto char_set_matched;
6008 /* match with collating_symbol? */
6012 const unsigned char *extra = (const unsigned char *)
6013 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6015 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6019 wextra = (int32_t*)(extra + *workp++);
6020 for (i = 0; i < *wextra; ++i)
6021 if (TRANSLATE(d[i]) != wextra[1 + i])
6026 /* Update d, however d will be incremented at
6027 char_set_matched:, we decrement d here. */
6029 goto char_set_matched;
6033 else /* (nrules == 0) */
6035 /* If we can't look up collation data, we use wcscoll
6038 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6040 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6041 length = wcslen(workp);
6043 /* If wcscoll(the collating symbol, whole string) > 0,
6044 any substring of the string never match with the
6045 collating symbol. */
6046 if (wcscoll(workp, d) > 0)
6048 workp += length + 1;
6052 /* First, we compare the collating symbol with
6053 the first character of the string.
6054 If it don't match, we add the next character to
6055 the compare buffer in turn. */
6056 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6061 if (dend == end_match_2)
6067 /* add next character to the compare buffer. */
6068 str_buf[i] = TRANSLATE(*d);
6069 str_buf[i+1] = '\0';
6071 match = wcscoll(workp, str_buf);
6073 goto char_set_matched;
6076 /* (str_buf > workp) indicate (str_buf + X > workp),
6077 because for all X (str_buf + X > str_buf).
6078 So we don't need continue this loop. */
6081 /* Otherwise(str_buf < workp),
6082 (str_buf+next_character) may equals (workp).
6083 So we continue this loop. */
6088 workp += length + 1;
6091 /* match with equivalence_class? */
6095 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6096 /* Try to match the equivalence class against
6097 those known to the collate implementation. */
6098 const int32_t *table;
6099 const int32_t *weights;
6100 const int32_t *extra;
6101 const int32_t *indirect;
6106 /* This #include defines a local function! */
6107 # include <locale/weightwc.h>
6109 table = (const int32_t *)
6110 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6111 weights = (const wint_t *)
6112 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6113 extra = (const wint_t *)
6114 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6115 indirect = (const int32_t *)
6116 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6118 /* Write 1 collating element to str_buf, and
6122 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6124 cp = (wint_t*)str_buf;
6127 if (dend == end_match_2)
6132 str_buf[i] = TRANSLATE(*(d+i));
6133 str_buf[i+1] = '\0'; /* sentinel */
6134 idx2 = findidx ((const wint_t**)&cp);
6137 /* Update d, however d will be incremented at
6138 char_set_matched:, we decrement d here. */
6139 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6142 if (dend == end_match_2)
6151 len = weights[idx2];
6153 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6156 idx = (int32_t)*workp;
6157 /* We already checked idx != 0 in regex_compile. */
6159 if (idx2 != 0 && len == weights[idx])
6162 while (cnt < len && (weights[idx + 1 + cnt]
6163 == weights[idx2 + 1 + cnt]))
6167 goto char_set_matched;
6174 else /* (nrules == 0) */
6176 /* If we can't look up collation data, we use wcscoll
6179 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6181 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6182 length = wcslen(workp);
6184 /* If wcscoll(the collating symbol, whole string) > 0,
6185 any substring of the string never match with the
6186 collating symbol. */
6187 if (wcscoll(workp, d) > 0)
6189 workp += length + 1;
6193 /* First, we compare the equivalence class with
6194 the first character of the string.
6195 If it don't match, we add the next character to
6196 the compare buffer in turn. */
6197 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6202 if (dend == end_match_2)
6208 /* add next character to the compare buffer. */
6209 str_buf[i] = TRANSLATE(*d);
6210 str_buf[i+1] = '\0';
6212 match = wcscoll(workp, str_buf);
6215 goto char_set_matched;
6218 /* (str_buf > workp) indicate (str_buf + X > workp),
6219 because for all X (str_buf + X > str_buf).
6220 So we don't need continue this loop. */
6223 /* Otherwise(str_buf < workp),
6224 (str_buf+next_character) may equals (workp).
6225 So we continue this loop. */
6230 workp += length + 1;
6234 /* match with char_range? */
6238 uint32_t collseqval;
6239 const char *collseq = (const char *)
6240 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6242 collseqval = collseq_table_lookup (collseq, c);
6244 for (; workp < p - chars_length ;)
6246 uint32_t start_val, end_val;
6248 /* We already compute the collation sequence value
6249 of the characters (or collating symbols). */
6250 start_val = (uint32_t) *workp++; /* range_start */
6251 end_val = (uint32_t) *workp++; /* range_end */
6253 if (start_val <= collseqval && collseqval <= end_val)
6254 goto char_set_matched;
6260 /* We set range_start_char at str_buf[0], range_end_char
6261 at str_buf[4], and compared char at str_buf[2]. */
6266 for (; workp < p - chars_length ;)
6268 wchar_t *range_start_char, *range_end_char;
6270 /* match if (range_start_char <= c <= range_end_char). */
6272 /* If range_start(or end) < 0, we assume -range_start(end)
6273 is the offset of the collating symbol which is specified
6274 as the character of the range start(end). */
6278 range_start_char = charset_top - (*workp++);
6281 str_buf[0] = *workp++;
6282 range_start_char = str_buf;
6287 range_end_char = charset_top - (*workp++);
6290 str_buf[4] = *workp++;
6291 range_end_char = str_buf + 4;
6294 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6295 wcscoll(str_buf+2, range_end_char) <= 0)
6297 goto char_set_matched;
6301 /* match with char? */
6302 for (; workp < p ; workp++)
6304 goto char_set_matched;
6311 /* Cast to `unsigned' instead of `unsigned char' in case the
6312 bit list is a full 32 bytes long. */
6313 if (c < (unsigned) (*p * BYTEWIDTH)
6314 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6319 if (!not) goto fail;
6320 #undef WORK_BUFFER_SIZE
6321 #endif /* MBS_SUPPORT */
6322 SET_REGS_MATCHED ();
6328 /* The beginning of a group is represented by start_memory.
6329 The arguments are the register number in the next byte, and the
6330 number of groups inner to this one in the next. The text
6331 matched within the group is recorded (in the internal
6332 registers data structure) under the register number. */
6334 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6335 (long int) *p, (long int) p[1]);
6337 /* Find out if this group can match the empty string. */
6338 p1 = p; /* To send to group_match_null_string_p. */
6340 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6341 REG_MATCH_NULL_STRING_P (reg_info[*p])
6342 = group_match_null_string_p (&p1, pend, reg_info);
6344 /* Save the position in the string where we were the last time
6345 we were at this open-group operator in case the group is
6346 operated upon by a repetition operator, e.g., with `(a*)*b'
6347 against `ab'; then we want to ignore where we are now in
6348 the string in case this attempt to match fails. */
6349 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6350 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6352 DEBUG_PRINT2 (" old_regstart: %d\n",
6353 POINTER_TO_OFFSET (old_regstart[*p]));
6356 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6358 IS_ACTIVE (reg_info[*p]) = 1;
6359 MATCHED_SOMETHING (reg_info[*p]) = 0;
6361 /* Clear this whenever we change the register activity status. */
6362 set_regs_matched_done = 0;
6364 /* This is the new highest active register. */
6365 highest_active_reg = *p;
6367 /* If nothing was active before, this is the new lowest active
6369 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6370 lowest_active_reg = *p;
6372 /* Move past the register number and inner group count. */
6374 just_past_start_mem = p;
6379 /* The stop_memory opcode represents the end of a group. Its
6380 arguments are the same as start_memory's: the register
6381 number, and the number of inner groups. */
6383 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6384 (long int) *p, (long int) p[1]);
6386 /* We need to save the string position the last time we were at
6387 this close-group operator in case the group is operated
6388 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6389 against `aba'; then we want to ignore where we are now in
6390 the string in case this attempt to match fails. */
6391 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6392 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6394 DEBUG_PRINT2 (" old_regend: %d\n",
6395 POINTER_TO_OFFSET (old_regend[*p]));
6398 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6400 /* This register isn't active anymore. */
6401 IS_ACTIVE (reg_info[*p]) = 0;
6403 /* Clear this whenever we change the register activity status. */
6404 set_regs_matched_done = 0;
6406 /* If this was the only register active, nothing is active
6408 if (lowest_active_reg == highest_active_reg)
6410 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6411 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6414 { /* We must scan for the new highest active register, since
6415 it isn't necessarily one less than now: consider
6416 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6417 new highest active register is 1. */
6418 US_CHAR_TYPE r = *p - 1;
6419 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6422 /* If we end up at register zero, that means that we saved
6423 the registers as the result of an `on_failure_jump', not
6424 a `start_memory', and we jumped to past the innermost
6425 `stop_memory'. For example, in ((.)*) we save
6426 registers 1 and 2 as a result of the *, but when we pop
6427 back to the second ), we are at the stop_memory 1.
6428 Thus, nothing is active. */
6431 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6432 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6435 highest_active_reg = r;
6438 /* If just failed to match something this time around with a
6439 group that's operated on by a repetition operator, try to
6440 force exit from the ``loop'', and restore the register
6441 information for this group that we had before trying this
6443 if ((!MATCHED_SOMETHING (reg_info[*p])
6444 || just_past_start_mem == p - 1)
6447 boolean is_a_jump_n = false;
6451 switch ((re_opcode_t) *p1++)
6455 case pop_failure_jump:
6456 case maybe_pop_jump:
6458 case dummy_failure_jump:
6459 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6461 p1 += OFFSET_ADDRESS_SIZE;
6469 /* If the next operation is a jump backwards in the pattern
6470 to an on_failure_jump right before the start_memory
6471 corresponding to this stop_memory, exit from the loop
6472 by forcing a failure after pushing on the stack the
6473 on_failure_jump's jump in the pattern, and d. */
6474 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6475 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6476 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6478 /* If this group ever matched anything, then restore
6479 what its registers were before trying this last
6480 failed match, e.g., with `(a*)*b' against `ab' for
6481 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6482 against `aba' for regend[3].
6484 Also restore the registers for inner groups for,
6485 e.g., `((a*)(b*))*' against `aba' (register 3 would
6486 otherwise get trashed). */
6488 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6492 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6494 /* Restore this and inner groups' (if any) registers. */
6495 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6498 regstart[r] = old_regstart[r];
6500 /* xx why this test? */
6501 if (old_regend[r] >= regstart[r])
6502 regend[r] = old_regend[r];
6506 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6507 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6513 /* Move past the register number and the inner group count. */
6518 /* \<digit> has been turned into a `duplicate' command which is
6519 followed by the numeric value of <digit> as the register number. */
6522 register const CHAR_TYPE *d2, *dend2;
6523 int regno = *p++; /* Get which register to match against. */
6524 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6526 /* Can't back reference a group which we've never matched. */
6527 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6530 /* Where in input to try to start matching. */
6531 d2 = regstart[regno];
6533 /* Where to stop matching; if both the place to start and
6534 the place to stop matching are in the same string, then
6535 set to the place to stop, otherwise, for now have to use
6536 the end of the first string. */
6538 dend2 = ((FIRST_STRING_P (regstart[regno])
6539 == FIRST_STRING_P (regend[regno]))
6540 ? regend[regno] : end_match_1);
6543 /* If necessary, advance to next segment in register
6547 if (dend2 == end_match_2) break;
6548 if (dend2 == regend[regno]) break;
6550 /* End of string1 => advance to string2. */
6552 dend2 = regend[regno];
6554 /* At end of register contents => success */
6555 if (d2 == dend2) break;
6557 /* If necessary, advance to next segment in data. */
6560 /* How many characters left in this segment to match. */
6563 /* Want how many consecutive characters we can match in
6564 one shot, so, if necessary, adjust the count. */
6565 if (mcnt > dend2 - d2)
6568 /* Compare that many; failure if mismatch, else move
6571 ? bcmp_translate (d, d2, mcnt, translate)
6572 : memcmp (d, d2, mcnt*sizeof(US_CHAR_TYPE)))
6574 d += mcnt, d2 += mcnt;
6576 /* Do this because we've match some characters. */
6577 SET_REGS_MATCHED ();
6583 /* begline matches the empty string at the beginning of the string
6584 (unless `not_bol' is set in `bufp'), and, if
6585 `newline_anchor' is set, after newlines. */
6587 DEBUG_PRINT1 ("EXECUTING begline.\n");
6589 if (AT_STRINGS_BEG (d))
6591 if (!bufp->not_bol) break;
6593 else if (d[-1] == '\n' && bufp->newline_anchor)
6597 /* In all other cases, we fail. */
6601 /* endline is the dual of begline. */
6603 DEBUG_PRINT1 ("EXECUTING endline.\n");
6605 if (AT_STRINGS_END (d))
6607 if (!bufp->not_eol) break;
6610 /* We have to ``prefetch'' the next character. */
6611 else if ((d == end1 ? *string2 : *d) == '\n'
6612 && bufp->newline_anchor)
6619 /* Match at the very beginning of the data. */
6621 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6622 if (AT_STRINGS_BEG (d))
6627 /* Match at the very end of the data. */
6629 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6630 if (AT_STRINGS_END (d))
6635 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6636 pushes NULL as the value for the string on the stack. Then
6637 `pop_failure_point' will keep the current value for the
6638 string, instead of restoring it. To see why, consider
6639 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6640 then the . fails against the \n. But the next thing we want
6641 to do is match the \n against the \n; if we restored the
6642 string value, we would be back at the foo.
6644 Because this is used only in specific cases, we don't need to
6645 check all the things that `on_failure_jump' does, to make
6646 sure the right things get saved on the stack. Hence we don't
6647 share its code. The only reason to push anything on the
6648 stack at all is that otherwise we would have to change
6649 `anychar's code to do something besides goto fail in this
6650 case; that seems worse than this. */
6651 case on_failure_keep_string_jump:
6652 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6654 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6656 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6658 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6661 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6665 /* Uses of on_failure_jump:
6667 Each alternative starts with an on_failure_jump that points
6668 to the beginning of the next alternative. Each alternative
6669 except the last ends with a jump that in effect jumps past
6670 the rest of the alternatives. (They really jump to the
6671 ending jump of the following alternative, because tensioning
6672 these jumps is a hassle.)
6674 Repeats start with an on_failure_jump that points past both
6675 the repetition text and either the following jump or
6676 pop_failure_jump back to this on_failure_jump. */
6677 case on_failure_jump:
6679 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6681 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6683 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6685 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6688 /* If this on_failure_jump comes right before a group (i.e.,
6689 the original * applied to a group), save the information
6690 for that group and all inner ones, so that if we fail back
6691 to this point, the group's information will be correct.
6692 For example, in \(a*\)*\1, we need the preceding group,
6693 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6695 /* We can't use `p' to check ahead because we push
6696 a failure point to `p + mcnt' after we do this. */
6699 /* We need to skip no_op's before we look for the
6700 start_memory in case this on_failure_jump is happening as
6701 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6703 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6706 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6708 /* We have a new highest active register now. This will
6709 get reset at the start_memory we are about to get to,
6710 but we will have saved all the registers relevant to
6711 this repetition op, as described above. */
6712 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6713 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6714 lowest_active_reg = *(p1 + 1);
6717 DEBUG_PRINT1 (":\n");
6718 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6722 /* A smart repeat ends with `maybe_pop_jump'.
6723 We change it to either `pop_failure_jump' or `jump'. */
6724 case maybe_pop_jump:
6725 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6726 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6728 register US_CHAR_TYPE *p2 = p;
6730 /* Compare the beginning of the repeat with what in the
6731 pattern follows its end. If we can establish that there
6732 is nothing that they would both match, i.e., that we
6733 would have to backtrack because of (as in, e.g., `a*a')
6734 then we can change to pop_failure_jump, because we'll
6735 never have to backtrack.
6737 This is not true in the case of alternatives: in
6738 `(a|ab)*' we do need to backtrack to the `ab' alternative
6739 (e.g., if the string was `ab'). But instead of trying to
6740 detect that here, the alternative has put on a dummy
6741 failure point which is what we will end up popping. */
6743 /* Skip over open/close-group commands.
6744 If what follows this loop is a ...+ construct,
6745 look at what begins its body, since we will have to
6746 match at least one of that. */
6750 && ((re_opcode_t) *p2 == stop_memory
6751 || (re_opcode_t) *p2 == start_memory))
6753 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6754 && (re_opcode_t) *p2 == dummy_failure_jump)
6755 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6761 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
6762 to the `maybe_finalize_jump' of this case. Examine what
6765 /* If we're at the end of the pattern, we can change. */
6768 /* Consider what happens when matching ":\(.*\)"
6769 against ":/". I don't really understand this code
6771 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6774 (" End of pattern: change to `pop_failure_jump'.\n");
6777 else if ((re_opcode_t) *p2 == exactn
6779 || (re_opcode_t) *p2 == exactn_bin
6781 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
6783 register US_CHAR_TYPE c
6784 = *p2 == (US_CHAR_TYPE) endline ? '\n' : p2[2];
6786 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
6788 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
6790 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
6792 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6795 if (MB_CUR_MAX != 1)
6796 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
6798 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
6801 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
6803 (char) p1[3+OFFSET_ADDRESS_SIZE]);
6807 else if ((re_opcode_t) p1[3] == charset
6808 || (re_opcode_t) p1[3] == charset_not)
6810 int not = (re_opcode_t) p1[3] == charset_not;
6812 if (c < (unsigned) (p1[4] * BYTEWIDTH)
6813 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6816 /* `not' is equal to 1 if c would match, which means
6817 that we can't change to pop_failure_jump. */
6820 p[-3] = (unsigned char) pop_failure_jump;
6821 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6824 #endif /* not MBS_SUPPORT */
6827 else if ((re_opcode_t) *p2 == charset)
6829 /* We win if the first character of the loop is not part
6831 if ((re_opcode_t) p1[3] == exactn
6832 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
6833 && (p2[2 + p1[5] / BYTEWIDTH]
6834 & (1 << (p1[5] % BYTEWIDTH)))))
6836 p[-3] = (unsigned char) pop_failure_jump;
6837 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6840 else if ((re_opcode_t) p1[3] == charset_not)
6843 /* We win if the charset_not inside the loop
6844 lists every character listed in the charset after. */
6845 for (idx = 0; idx < (int) p2[1]; idx++)
6846 if (! (p2[2 + idx] == 0
6847 || (idx < (int) p1[4]
6848 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
6853 p[-3] = (unsigned char) pop_failure_jump;
6854 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6857 else if ((re_opcode_t) p1[3] == charset)
6860 /* We win if the charset inside the loop
6861 has no overlap with the one after the loop. */
6863 idx < (int) p2[1] && idx < (int) p1[4];
6865 if ((p2[2 + idx] & p1[5 + idx]) != 0)
6868 if (idx == p2[1] || idx == p1[4])
6870 p[-3] = (unsigned char) pop_failure_jump;
6871 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6875 #endif /* not MBS_SUPPORT */
6877 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
6878 if ((re_opcode_t) p[-1] != pop_failure_jump)
6880 p[-1] = (US_CHAR_TYPE) jump;
6881 DEBUG_PRINT1 (" Match => jump.\n");
6882 goto unconditional_jump;
6884 /* Note fall through. */
6887 /* The end of a simple repeat has a pop_failure_jump back to
6888 its matching on_failure_jump, where the latter will push a
6889 failure point. The pop_failure_jump takes off failure
6890 points put on by this pop_failure_jump's matching
6891 on_failure_jump; we got through the pattern to here from the
6892 matching on_failure_jump, so didn't fail. */
6893 case pop_failure_jump:
6895 /* We need to pass separate storage for the lowest and
6896 highest registers, even though we don't care about the
6897 actual values. Otherwise, we will restore only one
6898 register from the stack, since lowest will == highest in
6899 `pop_failure_point'. */
6900 active_reg_t dummy_low_reg, dummy_high_reg;
6901 US_CHAR_TYPE *pdummy = NULL;
6902 const CHAR_TYPE *sdummy = NULL;
6904 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
6905 POP_FAILURE_POINT (sdummy, pdummy,
6906 dummy_low_reg, dummy_high_reg,
6907 reg_dummy, reg_dummy, reg_info_dummy);
6909 /* Note fall through. */
6913 DEBUG_PRINT2 ("\n%p: ", p);
6915 DEBUG_PRINT2 ("\n0x%x: ", p);
6917 /* Note fall through. */
6919 /* Unconditionally jump (without popping any failure points). */
6921 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
6922 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
6923 p += mcnt; /* Do the jump. */
6925 DEBUG_PRINT2 ("(to %p).\n", p);
6927 DEBUG_PRINT2 ("(to 0x%x).\n", p);
6932 /* We need this opcode so we can detect where alternatives end
6933 in `group_match_null_string_p' et al. */
6935 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
6936 goto unconditional_jump;
6939 /* Normally, the on_failure_jump pushes a failure point, which
6940 then gets popped at pop_failure_jump. We will end up at
6941 pop_failure_jump, also, and with a pattern of, say, `a+', we
6942 are skipping over the on_failure_jump, so we have to push
6943 something meaningless for pop_failure_jump to pop. */
6944 case dummy_failure_jump:
6945 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
6946 /* It doesn't matter what we push for the string here. What
6947 the code at `fail' tests is the value for the pattern. */
6948 PUSH_FAILURE_POINT (NULL, NULL, -2);
6949 goto unconditional_jump;
6952 /* At the end of an alternative, we need to push a dummy failure
6953 point in case we are followed by a `pop_failure_jump', because
6954 we don't want the failure point for the alternative to be
6955 popped. For example, matching `(a|ab)*' against `aab'
6956 requires that we match the `ab' alternative. */
6957 case push_dummy_failure:
6958 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
6959 /* See comments just above at `dummy_failure_jump' about the
6961 PUSH_FAILURE_POINT (NULL, NULL, -2);
6964 /* Have to succeed matching what follows at least n times.
6965 After that, handle like `on_failure_jump'. */
6967 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6968 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
6971 /* Originally, this is how many times we HAVE to succeed. */
6975 p += OFFSET_ADDRESS_SIZE;
6976 STORE_NUMBER_AND_INCR (p, mcnt);
6978 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
6981 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
6988 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
6989 p + OFFSET_ADDRESS_SIZE);
6991 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
6992 p + OFFSET_ADDRESS_SIZE);
6996 p[1] = (US_CHAR_TYPE) no_op;
6998 p[2] = (US_CHAR_TYPE) no_op;
6999 p[3] = (US_CHAR_TYPE) no_op;
7000 #endif /* MBS_SUPPORT */
7006 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7007 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7009 /* Originally, this is how many times we CAN jump. */
7013 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7016 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7019 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7022 goto unconditional_jump;
7024 /* If don't have to jump any more, skip over the rest of command. */
7026 p += 2 * OFFSET_ADDRESS_SIZE;
7031 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7033 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7035 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7037 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7039 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7041 STORE_NUMBER (p1, mcnt);
7046 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7047 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7048 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7049 macro and introducing temporary variables works around the bug. */
7052 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7053 if (AT_WORD_BOUNDARY (d))
7058 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7059 if (AT_WORD_BOUNDARY (d))
7065 boolean prevchar, thischar;
7067 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7068 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7071 prevchar = WORDCHAR_P (d - 1);
7072 thischar = WORDCHAR_P (d);
7073 if (prevchar != thischar)
7080 boolean prevchar, thischar;
7082 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7083 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7086 prevchar = WORDCHAR_P (d - 1);
7087 thischar = WORDCHAR_P (d);
7088 if (prevchar != thischar)
7095 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7096 if (!AT_STRINGS_END (d) && WORDCHAR_P (d)
7097 && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7102 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7103 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7104 && (AT_STRINGS_END (d) || !WORDCHAR_P (d)))
7110 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7111 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7116 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7117 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7122 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7123 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7128 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7133 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7137 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7139 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7141 SET_REGS_MATCHED ();
7145 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7147 goto matchnotsyntax;
7150 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7154 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7156 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7158 SET_REGS_MATCHED ();
7161 #else /* not emacs */
7163 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7165 if (!WORDCHAR_P (d))
7167 SET_REGS_MATCHED ();
7172 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7176 SET_REGS_MATCHED ();
7179 #endif /* not emacs */
7184 continue; /* Successfully executed one pattern command; keep going. */
7187 /* We goto here if a matching operation fails. */
7189 if (!FAIL_STACK_EMPTY ())
7190 { /* A restart point is known. Restore to that state. */
7191 DEBUG_PRINT1 ("\nFAIL:\n");
7192 POP_FAILURE_POINT (d, p,
7193 lowest_active_reg, highest_active_reg,
7194 regstart, regend, reg_info);
7196 /* If this failure point is a dummy, try the next one. */
7200 /* If we failed to the end of the pattern, don't examine *p. */
7204 boolean is_a_jump_n = false;
7206 /* If failed to a backwards jump that's part of a repetition
7207 loop, need to pop this failure point and use the next one. */
7208 switch ((re_opcode_t) *p)
7212 case maybe_pop_jump:
7213 case pop_failure_jump:
7216 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7219 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7221 && (re_opcode_t) *p1 == on_failure_jump))
7229 if (d >= string1 && d <= end1)
7233 break; /* Matching at this starting point really fails. */
7237 goto restore_best_regs;
7241 return -1; /* Failure to match. */
7244 /* Subroutine definitions for re_match_2. */
7247 /* We are passed P pointing to a register number after a start_memory.
7249 Return true if the pattern up to the corresponding stop_memory can
7250 match the empty string, and false otherwise.
7252 If we find the matching stop_memory, sets P to point to one past its number.
7253 Otherwise, sets P to an undefined byte less than or equal to END.
7255 We don't handle duplicates properly (yet). */
7258 group_match_null_string_p (p, end, reg_info)
7259 US_CHAR_TYPE **p, *end;
7260 register_info_type *reg_info;
7263 /* Point to after the args to the start_memory. */
7264 US_CHAR_TYPE *p1 = *p + 2;
7268 /* Skip over opcodes that can match nothing, and return true or
7269 false, as appropriate, when we get to one that can't, or to the
7270 matching stop_memory. */
7272 switch ((re_opcode_t) *p1)
7274 /* Could be either a loop or a series of alternatives. */
7275 case on_failure_jump:
7277 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7279 /* If the next operation is not a jump backwards in the
7284 /* Go through the on_failure_jumps of the alternatives,
7285 seeing if any of the alternatives cannot match nothing.
7286 The last alternative starts with only a jump,
7287 whereas the rest start with on_failure_jump and end
7288 with a jump, e.g., here is the pattern for `a|b|c':
7290 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7291 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7294 So, we have to first go through the first (n-1)
7295 alternatives and then deal with the last one separately. */
7298 /* Deal with the first (n-1) alternatives, which start
7299 with an on_failure_jump (see above) that jumps to right
7300 past a jump_past_alt. */
7302 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7305 /* `mcnt' holds how many bytes long the alternative
7306 is, including the ending `jump_past_alt' and
7309 if (!alt_match_null_string_p (p1, p1 + mcnt -
7310 (1 + OFFSET_ADDRESS_SIZE),
7314 /* Move to right after this alternative, including the
7318 /* Break if it's the beginning of an n-th alternative
7319 that doesn't begin with an on_failure_jump. */
7320 if ((re_opcode_t) *p1 != on_failure_jump)
7323 /* Still have to check that it's not an n-th
7324 alternative that starts with an on_failure_jump. */
7326 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7327 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7330 /* Get to the beginning of the n-th alternative. */
7331 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7336 /* Deal with the last alternative: go back and get number
7337 of the `jump_past_alt' just before it. `mcnt' contains
7338 the length of the alternative. */
7339 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7341 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
7344 p1 += mcnt; /* Get past the n-th alternative. */
7350 assert (p1[1] == **p);
7356 if (!common_op_match_null_string_p (&p1, end, reg_info))
7359 } /* while p1 < end */
7362 } /* group_match_null_string_p */
7365 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7366 It expects P to be the first byte of a single alternative and END one
7367 byte past the last. The alternative can contain groups. */
7370 alt_match_null_string_p (p, end, reg_info)
7371 US_CHAR_TYPE *p, *end;
7372 register_info_type *reg_info;
7375 US_CHAR_TYPE *p1 = p;
7379 /* Skip over opcodes that can match nothing, and break when we get
7380 to one that can't. */
7382 switch ((re_opcode_t) *p1)
7385 case on_failure_jump:
7387 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7392 if (!common_op_match_null_string_p (&p1, end, reg_info))
7395 } /* while p1 < end */
7398 } /* alt_match_null_string_p */
7401 /* Deals with the ops common to group_match_null_string_p and
7402 alt_match_null_string_p.
7404 Sets P to one after the op and its arguments, if any. */
7407 common_op_match_null_string_p (p, end, reg_info)
7408 US_CHAR_TYPE **p, *end;
7409 register_info_type *reg_info;
7414 US_CHAR_TYPE *p1 = *p;
7416 switch ((re_opcode_t) *p1++)
7436 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7437 ret = group_match_null_string_p (&p1, end, reg_info);
7439 /* Have to set this here in case we're checking a group which
7440 contains a group and a back reference to it. */
7442 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7443 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7449 /* If this is an optimized succeed_n for zero times, make the jump. */
7451 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7459 /* Get to the number of times to succeed. */
7460 p1 += OFFSET_ADDRESS_SIZE;
7461 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7465 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7466 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7474 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7479 p1 += 2 * OFFSET_ADDRESS_SIZE;
7482 /* All other opcodes mean we cannot match the empty string. */
7488 } /* common_op_match_null_string_p */
7491 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7492 bytes; nonzero otherwise. */
7495 bcmp_translate (s1, s2, len, translate)
7496 const CHAR_TYPE *s1, *s2;
7498 RE_TRANSLATE_TYPE translate;
7500 register const US_CHAR_TYPE *p1 = (const US_CHAR_TYPE *) s1;
7501 register const US_CHAR_TYPE *p2 = (const US_CHAR_TYPE *) s2;
7505 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7506 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7509 if (translate[*p1++] != translate[*p2++]) return 1;
7510 #endif /* MBS_SUPPORT */
7516 /* Entry points for GNU code. */
7518 /* re_compile_pattern is the GNU regular expression compiler: it
7519 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7520 Returns 0 if the pattern was valid, otherwise an error string.
7522 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7523 are set in BUFP on entry.
7525 We call regex_compile to do the actual compilation. */
7528 re_compile_pattern (pattern, length, bufp)
7529 const char *pattern;
7531 struct re_pattern_buffer *bufp;
7535 /* GNU code is written to assume at least RE_NREGS registers will be set
7536 (and at least one extra will be -1). */
7537 bufp->regs_allocated = REGS_UNALLOCATED;
7539 /* And GNU code determines whether or not to get register information
7540 by passing null for the REGS argument to re_match, etc., not by
7544 /* Match anchors at newline. */
7545 bufp->newline_anchor = 1;
7547 ret = regex_compile (pattern, length, re_syntax_options, bufp);
7551 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7554 weak_alias (__re_compile_pattern, re_compile_pattern)
7557 /* Entry points compatible with 4.2 BSD regex library. We don't define
7558 them unless specifically requested. */
7560 #if defined _REGEX_RE_COMP || defined _LIBC
7562 /* BSD has one and only one pattern buffer. */
7563 static struct re_pattern_buffer re_comp_buf;
7567 /* Make these definitions weak in libc, so POSIX programs can redefine
7568 these names if they don't use our functions, and still use
7569 regcomp/regexec below without link errors. */
7579 if (!re_comp_buf.buffer)
7580 return gettext ("No previous regular expression");
7584 if (!re_comp_buf.buffer)
7586 re_comp_buf.buffer = (unsigned char *) malloc (200);
7587 if (re_comp_buf.buffer == NULL)
7588 return (char *) gettext (re_error_msgid
7589 + re_error_msgid_idx[(int) REG_ESPACE]);
7590 re_comp_buf.allocated = 200;
7592 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7593 if (re_comp_buf.fastmap == NULL)
7594 return (char *) gettext (re_error_msgid
7595 + re_error_msgid_idx[(int) REG_ESPACE]);
7598 /* Since `re_exec' always passes NULL for the `regs' argument, we
7599 don't need to initialize the pattern buffer fields which affect it. */
7601 /* Match anchors at newlines. */
7602 re_comp_buf.newline_anchor = 1;
7604 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7609 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7610 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7621 const int len = strlen (s);
7623 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7626 #endif /* _REGEX_RE_COMP */
7628 /* POSIX.2 functions. Don't define these for Emacs. */
7632 /* regcomp takes a regular expression as a string and compiles it.
7634 PREG is a regex_t *. We do not expect any fields to be initialized,
7635 since POSIX says we shouldn't. Thus, we set
7637 `buffer' to the compiled pattern;
7638 `used' to the length of the compiled pattern;
7639 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7640 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7641 RE_SYNTAX_POSIX_BASIC;
7642 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7643 `fastmap' to an allocated space for the fastmap;
7644 `fastmap_accurate' to zero;
7645 `re_nsub' to the number of subexpressions in PATTERN.
7647 PATTERN is the address of the pattern string.
7649 CFLAGS is a series of bits which affect compilation.
7651 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7652 use POSIX basic syntax.
7654 If REG_NEWLINE is set, then . and [^...] don't match newline.
7655 Also, regexec will try a match beginning after every newline.
7657 If REG_ICASE is set, then we considers upper- and lowercase
7658 versions of letters to be equivalent when matching.
7660 If REG_NOSUB is set, then when PREG is passed to regexec, that
7661 routine will report only success or failure, and nothing about the
7664 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7665 the return codes and their meanings.) */
7668 regcomp (preg, pattern, cflags)
7670 const char *pattern;
7675 = (cflags & REG_EXTENDED) ?
7676 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7678 /* regex_compile will allocate the space for the compiled pattern. */
7680 preg->allocated = 0;
7683 /* Try to allocate space for the fastmap. */
7684 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7686 if (cflags & REG_ICASE)
7691 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7692 * sizeof (*(RE_TRANSLATE_TYPE)0));
7693 if (preg->translate == NULL)
7694 return (int) REG_ESPACE;
7696 /* Map uppercase characters to corresponding lowercase ones. */
7697 for (i = 0; i < CHAR_SET_SIZE; i++)
7698 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7701 preg->translate = NULL;
7703 /* If REG_NEWLINE is set, newlines are treated differently. */
7704 if (cflags & REG_NEWLINE)
7705 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7706 syntax &= ~RE_DOT_NEWLINE;
7707 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7708 /* It also changes the matching behavior. */
7709 preg->newline_anchor = 1;
7712 preg->newline_anchor = 0;
7714 preg->no_sub = !!(cflags & REG_NOSUB);
7716 /* POSIX says a null character in the pattern terminates it, so we
7717 can use strlen here in compiling the pattern. */
7718 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
7720 /* POSIX doesn't distinguish between an unmatched open-group and an
7721 unmatched close-group: both are REG_EPAREN. */
7722 if (ret == REG_ERPAREN) ret = REG_EPAREN;
7724 if (ret == REG_NOERROR && preg->fastmap)
7726 /* Compute the fastmap now, since regexec cannot modify the pattern
7728 if (re_compile_fastmap (preg) == -2)
7730 /* Some error occurred while computing the fastmap, just forget
7732 free (preg->fastmap);
7733 preg->fastmap = NULL;
7740 weak_alias (__regcomp, regcomp)
7744 /* regexec searches for a given pattern, specified by PREG, in the
7747 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7748 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
7749 least NMATCH elements, and we set them to the offsets of the
7750 corresponding matched substrings.
7752 EFLAGS specifies `execution flags' which affect matching: if
7753 REG_NOTBOL is set, then ^ does not match at the beginning of the
7754 string; if REG_NOTEOL is set, then $ does not match at the end.
7756 We return 0 if we find a match and REG_NOMATCH if not. */
7759 regexec (preg, string, nmatch, pmatch, eflags)
7760 const regex_t *preg;
7763 regmatch_t pmatch[];
7767 struct re_registers regs;
7768 regex_t private_preg;
7769 int len = strlen (string);
7770 boolean want_reg_info = !preg->no_sub && nmatch > 0;
7772 private_preg = *preg;
7774 private_preg.not_bol = !!(eflags & REG_NOTBOL);
7775 private_preg.not_eol = !!(eflags & REG_NOTEOL);
7777 /* The user has told us exactly how many registers to return
7778 information about, via `nmatch'. We have to pass that on to the
7779 matching routines. */
7780 private_preg.regs_allocated = REGS_FIXED;
7784 regs.num_regs = nmatch;
7785 regs.start = TALLOC (nmatch * 2, regoff_t);
7786 if (regs.start == NULL)
7787 return (int) REG_NOMATCH;
7788 regs.end = regs.start + nmatch;
7791 /* Perform the searching operation. */
7792 ret = re_search (&private_preg, string, len,
7793 /* start: */ 0, /* range: */ len,
7794 want_reg_info ? ®s : (struct re_registers *) 0);
7796 /* Copy the register information to the POSIX structure. */
7803 for (r = 0; r < nmatch; r++)
7805 pmatch[r].rm_so = regs.start[r];
7806 pmatch[r].rm_eo = regs.end[r];
7810 /* If we needed the temporary register info, free the space now. */
7814 /* We want zero return to mean success, unlike `re_search'. */
7815 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
7818 weak_alias (__regexec, regexec)
7822 /* Returns a message corresponding to an error code, ERRCODE, returned
7823 from either regcomp or regexec. We don't use PREG here. */
7826 regerror (errcode, preg, errbuf, errbuf_size)
7828 const regex_t *preg;
7836 || errcode >= (int) (sizeof (re_error_msgid_idx)
7837 / sizeof (re_error_msgid_idx[0])))
7838 /* Only error codes returned by the rest of the code should be passed
7839 to this routine. If we are given anything else, or if other regex
7840 code generates an invalid error code, then the program has a bug.
7841 Dump core so we can fix it. */
7844 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
7846 msg_size = strlen (msg) + 1; /* Includes the null. */
7848 if (errbuf_size != 0)
7850 if (msg_size > errbuf_size)
7852 #if defined HAVE_MEMPCPY || defined _LIBC
7853 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
7855 memcpy (errbuf, msg, errbuf_size - 1);
7856 errbuf[errbuf_size - 1] = 0;
7860 memcpy (errbuf, msg, msg_size);
7866 weak_alias (__regerror, regerror)
7870 /* Free dynamically allocated space used by PREG. */
7876 if (preg->buffer != NULL)
7877 free (preg->buffer);
7878 preg->buffer = NULL;
7880 preg->allocated = 0;
7883 if (preg->fastmap != NULL)
7884 free (preg->fastmap);
7885 preg->fastmap = NULL;
7886 preg->fastmap_accurate = 0;
7888 if (preg->translate != NULL)
7889 free (preg->translate);
7890 preg->translate = NULL;
7893 weak_alias (__regfree, regfree)
7896 #endif /* not emacs */