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 (MC_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) \
2144 while ('0' <= c && c <= '9') \
2148 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 /* Place in the uncompiled pattern (i.e., the {) to
2329 which to go back if the interval is invalid. */
2331 const US_CHAR_TYPE *beg_interval;
2333 const char *beg_interval;
2334 #endif /* MBS_SUPPORT */
2336 /* Address of the place where a forward jump should go to the end of
2337 the containing expression. Each alternative of an `or' -- except the
2338 last -- ends with a forward jump of this sort. */
2339 US_CHAR_TYPE *fixup_alt_jump = 0;
2341 /* Counts open-groups as they are encountered. Remembered for the
2342 matching close-group on the compile stack, so the same register
2343 number is put in the stop_memory as the start_memory. */
2344 regnum_t regnum = 0;
2347 /* Initialize the wchar_t PATTERN and offset_buffer. */
2348 p = pend = pattern = TALLOC(csize, CHAR_TYPE);
2349 mbs_offset = TALLOC(csize + 1, int);
2350 is_binary = TALLOC(csize + 1, char);
2351 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2353 if (pattern) free(pattern);
2354 if (mbs_offset) free(mbs_offset);
2355 if (is_binary) free(is_binary);
2358 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2362 if (pattern) free(pattern);
2363 if (mbs_offset) free(mbs_offset);
2364 if (is_binary) free(is_binary);
2370 DEBUG_PRINT1 ("\nCompiling pattern: ");
2373 unsigned debug_count;
2375 for (debug_count = 0; debug_count < size; debug_count++)
2376 PUT_CHAR (pattern[debug_count]);
2381 /* Initialize the compile stack. */
2382 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2383 if (compile_stack.stack == NULL)
2386 if (pattern) free(pattern);
2387 if (mbs_offset) free(mbs_offset);
2388 if (is_binary) free(is_binary);
2393 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2394 compile_stack.avail = 0;
2396 /* Initialize the pattern buffer. */
2397 bufp->syntax = syntax;
2398 bufp->fastmap_accurate = 0;
2399 bufp->not_bol = bufp->not_eol = 0;
2401 /* Set `used' to zero, so that if we return an error, the pattern
2402 printer (for debugging) will think there's no pattern. We reset it
2406 /* Always count groups, whether or not bufp->no_sub is set. */
2409 #if !defined emacs && !defined SYNTAX_TABLE
2410 /* Initialize the syntax table. */
2411 init_syntax_once ();
2414 if (bufp->allocated == 0)
2417 { /* If zero allocated, but buffer is non-null, try to realloc
2418 enough space. This loses if buffer's address is bogus, but
2419 that is the user's responsibility. */
2421 /* Free bufp->buffer and allocate an array for wchar_t pattern
2424 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(US_CHAR_TYPE),
2427 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, US_CHAR_TYPE);
2428 #endif /* MBS_SUPPORT */
2431 { /* Caller did not allocate a buffer. Do it for them. */
2432 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(US_CHAR_TYPE),
2436 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2438 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2439 #endif /* MBS_SUPPORT */
2440 bufp->allocated = INIT_BUF_SIZE;
2444 COMPILED_BUFFER_VAR = (US_CHAR_TYPE*) bufp->buffer;
2447 begalt = b = COMPILED_BUFFER_VAR;
2449 /* Loop through the uncompiled pattern until we're at the end. */
2458 if ( /* If at start of pattern, it's an operator. */
2460 /* If context independent, it's an operator. */
2461 || syntax & RE_CONTEXT_INDEP_ANCHORS
2462 /* Otherwise, depends on what's come before. */
2463 || at_begline_loc_p (pattern, p, syntax))
2473 if ( /* If at end of pattern, it's an operator. */
2475 /* If context independent, it's an operator. */
2476 || syntax & RE_CONTEXT_INDEP_ANCHORS
2477 /* Otherwise, depends on what's next. */
2478 || at_endline_loc_p (p, pend, syntax))
2488 if ((syntax & RE_BK_PLUS_QM)
2489 || (syntax & RE_LIMITED_OPS))
2493 /* If there is no previous pattern... */
2496 if (syntax & RE_CONTEXT_INVALID_OPS)
2497 FREE_STACK_RETURN (REG_BADRPT);
2498 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2503 /* Are we optimizing this jump? */
2504 boolean keep_string_p = false;
2506 /* 1 means zero (many) matches is allowed. */
2507 char zero_times_ok = 0, many_times_ok = 0;
2509 /* If there is a sequence of repetition chars, collapse it
2510 down to just one (the right one). We can't combine
2511 interval operators with these because of, e.g., `a{2}*',
2512 which should only match an even number of `a's. */
2516 zero_times_ok |= c != '+';
2517 many_times_ok |= c != '?';
2525 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2528 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2530 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2533 if (!(c1 == '+' || c1 == '?'))
2548 /* If we get here, we found another repeat character. */
2551 /* Star, etc. applied to an empty pattern is equivalent
2552 to an empty pattern. */
2556 /* Now we know whether or not zero matches is allowed
2557 and also whether or not two or more matches is allowed. */
2559 { /* More than one repetition is allowed, so put in at the
2560 end a backward relative jump from `b' to before the next
2561 jump we're going to put in below (which jumps from
2562 laststart to after this jump).
2564 But if we are at the `*' in the exact sequence `.*\n',
2565 insert an unconditional jump backwards to the .,
2566 instead of the beginning of the loop. This way we only
2567 push a failure point once, instead of every time
2568 through the loop. */
2569 assert (p - 1 > pattern);
2571 /* Allocate the space for the jump. */
2572 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2574 /* We know we are not at the first character of the pattern,
2575 because laststart was nonzero. And we've already
2576 incremented `p', by the way, to be the character after
2577 the `*'. Do we have to do something analogous here
2578 for null bytes, because of RE_DOT_NOT_NULL? */
2579 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2581 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2582 && !(syntax & RE_DOT_NEWLINE))
2583 { /* We have .*\n. */
2584 STORE_JUMP (jump, b, laststart);
2585 keep_string_p = true;
2588 /* Anything else. */
2589 STORE_JUMP (maybe_pop_jump, b, laststart -
2590 (1 + OFFSET_ADDRESS_SIZE));
2592 /* We've added more stuff to the buffer. */
2593 b += 1 + OFFSET_ADDRESS_SIZE;
2596 /* On failure, jump from laststart to b + 3, which will be the
2597 end of the buffer after this jump is inserted. */
2598 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2600 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2601 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2603 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2605 b += 1 + OFFSET_ADDRESS_SIZE;
2609 /* At least one repetition is required, so insert a
2610 `dummy_failure_jump' before the initial
2611 `on_failure_jump' instruction of the loop. This
2612 effects a skip over that instruction the first time
2613 we hit that loop. */
2614 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2615 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2616 2 + 2 * OFFSET_ADDRESS_SIZE);
2617 b += 1 + OFFSET_ADDRESS_SIZE;
2631 boolean had_char_class = false;
2633 CHAR_TYPE range_start = 0xffffffff;
2635 unsigned int range_start = 0xffffffff;
2637 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2640 /* We assume a charset(_not) structure as a wchar_t array.
2641 charset[0] = (re_opcode_t) charset(_not)
2642 charset[1] = l (= length of char_classes)
2643 charset[2] = m (= length of collating_symbols)
2644 charset[3] = n (= length of equivalence_classes)
2645 charset[4] = o (= length of char_ranges)
2646 charset[5] = p (= length of chars)
2648 charset[6] = char_class (wctype_t)
2649 charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2651 charset[l+5] = char_class (wctype_t)
2653 charset[l+6] = collating_symbol (wchar_t)
2655 charset[l+m+5] = collating_symbol (wchar_t)
2656 ifdef _LIBC we use the index if
2657 _NL_COLLATE_SYMB_EXTRAMB instead of
2660 charset[l+m+6] = equivalence_classes (wchar_t)
2662 charset[l+m+n+5] = equivalence_classes (wchar_t)
2663 ifdef _LIBC we use the index in
2664 _NL_COLLATE_WEIGHT instead of
2667 charset[l+m+n+6] = range_start
2668 charset[l+m+n+7] = range_end
2670 charset[l+m+n+2o+4] = range_start
2671 charset[l+m+n+2o+5] = range_end
2672 ifdef _LIBC we use the value looked up
2673 in _NL_COLLATE_COLLSEQ instead of
2676 charset[l+m+n+2o+6] = char
2678 charset[l+m+n+2o+p+5] = char
2682 /* We need at least 6 spaces: the opcode, the length of
2683 char_classes, the length of collating_symbols, the length of
2684 equivalence_classes, the length of char_ranges, the length of
2686 GET_BUFFER_SPACE (6);
2688 /* Save b as laststart. And We use laststart as the pointer
2689 to the first element of the charset here.
2690 In other words, laststart[i] indicates charset[i]. */
2693 /* We test `*p == '^' twice, instead of using an if
2694 statement, so we only need one BUF_PUSH. */
2695 BUF_PUSH (*p == '^' ? charset_not : charset);
2699 /* Push the length of char_classes, the length of
2700 collating_symbols, the length of equivalence_classes, the
2701 length of char_ranges and the length of chars. */
2702 BUF_PUSH_3 (0, 0, 0);
2705 /* Remember the first position in the bracket expression. */
2708 /* charset_not matches newline according to a syntax bit. */
2709 if ((re_opcode_t) b[-6] == charset_not
2710 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2713 laststart[5]++; /* Update the length of characters */
2716 /* Read in characters and ranges, setting map bits. */
2719 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2723 /* \ might escape characters inside [...] and [^...]. */
2724 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2726 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2730 laststart[5]++; /* Update the length of chars */
2735 /* Could be the end of the bracket expression. If it's
2736 not (i.e., when the bracket expression is `[]' so
2737 far), the ']' character bit gets set way below. */
2738 if (c == ']' && p != p1 + 1)
2741 /* Look ahead to see if it's a range when the last thing
2742 was a character class. */
2743 if (had_char_class && c == '-' && *p != ']')
2744 FREE_STACK_RETURN (REG_ERANGE);
2746 /* Look ahead to see if it's a range when the last thing
2747 was a character: if this is a hyphen not at the
2748 beginning or the end of a list, then it's the range
2751 && !(p - 2 >= pattern && p[-2] == '[')
2752 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2756 /* Allocate the space for range_start and range_end. */
2757 GET_BUFFER_SPACE (2);
2758 /* Update the pointer to indicate end of buffer. */
2760 ret = compile_range (range_start, &p, pend, translate,
2761 syntax, b, laststart);
2762 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2763 range_start = 0xffffffff;
2765 else if (p[0] == '-' && p[1] != ']')
2766 { /* This handles ranges made up of characters only. */
2769 /* Move past the `-'. */
2771 /* Allocate the space for range_start and range_end. */
2772 GET_BUFFER_SPACE (2);
2773 /* Update the pointer to indicate end of buffer. */
2775 ret = compile_range (c, &p, pend, translate, syntax, b,
2777 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2778 range_start = 0xffffffff;
2781 /* See if we're at the beginning of a possible character
2783 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2784 { /* Leave room for the null. */
2785 char str[CHAR_CLASS_MAX_LENGTH + 1];
2790 /* If pattern is `[[:'. */
2791 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2796 if ((c == ':' && *p == ']') || p == pend)
2798 if (c1 < CHAR_CLASS_MAX_LENGTH)
2801 /* This is in any case an invalid class name. */
2806 /* If isn't a word bracketed by `[:' and `:]':
2807 undo the ending character, the letters, and leave
2808 the leading `:' and `[' (but store them as character). */
2809 if (c == ':' && *p == ']')
2814 /* Query the character class as wctype_t. */
2815 wt = IS_CHAR_CLASS (str);
2817 FREE_STACK_RETURN (REG_ECTYPE);
2819 /* Throw away the ] at the end of the character
2823 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2825 /* Allocate the space for character class. */
2826 GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2827 /* Update the pointer to indicate end of buffer. */
2828 b += CHAR_CLASS_SIZE;
2829 /* Move data which follow character classes
2830 not to violate the data. */
2831 insert_space(CHAR_CLASS_SIZE,
2832 laststart + 6 + laststart[1],
2834 alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2835 + __alignof__(wctype_t) - 1)
2836 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2837 /* Store the character class. */
2838 *((wctype_t*)alignedp) = wt;
2839 /* Update length of char_classes */
2840 laststart[1] += CHAR_CLASS_SIZE;
2842 had_char_class = true;
2851 laststart[5] += 2; /* Update the length of characters */
2853 had_char_class = false;
2856 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2859 CHAR_TYPE str[128]; /* Should be large enough. */
2860 CHAR_TYPE delim = *p; /* '=' or '.' */
2863 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2868 /* If pattern is `[[=' or '[[.'. */
2869 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2874 if ((c == delim && *p == ']') || p == pend)
2876 if (c1 < sizeof (str) - 1)
2879 /* This is in any case an invalid class name. */
2884 if (c == delim && *p == ']' && str[0] != '\0')
2886 unsigned int i, offset;
2887 /* If we have no collation data we use the default
2888 collation in which each character is in a class
2889 by itself. It also means that ASCII is the
2890 character set and therefore we cannot have character
2891 with more than one byte in the multibyte
2894 /* If not defined _LIBC, we push the name and
2895 `\0' for the sake of matching performance. */
2896 int datasize = c1 + 1;
2904 FREE_STACK_RETURN (REG_ECOLLATE);
2909 const int32_t *table;
2910 const int32_t *weights;
2911 const int32_t *extra;
2912 const int32_t *indirect;
2915 /* This #include defines a local function! */
2916 # include <locale/weightwc.h>
2920 /* We push the index for equivalence class. */
2923 table = (const int32_t *)
2924 _NL_CURRENT (LC_COLLATE,
2925 _NL_COLLATE_TABLEWC);
2926 weights = (const int32_t *)
2927 _NL_CURRENT (LC_COLLATE,
2928 _NL_COLLATE_WEIGHTWC);
2929 extra = (const int32_t *)
2930 _NL_CURRENT (LC_COLLATE,
2931 _NL_COLLATE_EXTRAWC);
2932 indirect = (const int32_t *)
2933 _NL_CURRENT (LC_COLLATE,
2934 _NL_COLLATE_INDIRECTWC);
2936 idx = findidx ((const wint_t**)&cp);
2937 if (idx == 0 || cp < (wint_t*) str + c1)
2938 /* This is no valid character. */
2939 FREE_STACK_RETURN (REG_ECOLLATE);
2941 str[0] = (wchar_t)idx;
2943 else /* delim == '.' */
2945 /* We push collation sequence value
2946 for collating symbol. */
2948 const int32_t *symb_table;
2949 const unsigned char *extra;
2956 /* We have to convert the name to a single-byte
2957 string. This is possible since the names
2958 consist of ASCII characters and the internal
2959 representation is UCS4. */
2960 for (i = 0; i < c1; ++i)
2961 char_str[i] = str[i];
2964 _NL_CURRENT_WORD (LC_COLLATE,
2965 _NL_COLLATE_SYMB_HASH_SIZEMB);
2966 symb_table = (const int32_t *)
2967 _NL_CURRENT (LC_COLLATE,
2968 _NL_COLLATE_SYMB_TABLEMB);
2969 extra = (const unsigned char *)
2970 _NL_CURRENT (LC_COLLATE,
2971 _NL_COLLATE_SYMB_EXTRAMB);
2973 /* Locate the character in the hashing table. */
2974 hash = elem_hash (char_str, c1);
2977 elem = hash % table_size;
2978 second = hash % (table_size - 2);
2979 while (symb_table[2 * elem] != 0)
2981 /* First compare the hashing value. */
2982 if (symb_table[2 * elem] == hash
2983 && c1 == extra[symb_table[2 * elem + 1]]
2985 &extra[symb_table[2 * elem + 1]
2988 /* Yep, this is the entry. */
2989 idx = symb_table[2 * elem + 1];
2990 idx += 1 + extra[idx];
2998 if (symb_table[2 * elem] != 0)
3000 /* Compute the index of the byte sequence
3002 idx += 1 + extra[idx];
3003 /* Adjust for the alignment. */
3004 idx = (idx + 3) & ~4;
3006 str[0] = (wchar_t) idx + 4;
3008 else if (symb_table[2 * elem] == 0 && c1 == 1)
3010 /* No valid character. Match it as a
3011 single byte character. */
3012 had_char_class = false;
3014 /* Update the length of characters */
3016 range_start = str[0];
3018 /* Throw away the ] at the end of the
3019 collating symbol. */
3021 /* exit from the switch block. */
3025 FREE_STACK_RETURN (REG_ECOLLATE);
3030 /* Throw away the ] at the end of the equivalence
3031 class (or collating symbol). */
3034 /* Allocate the space for the equivalence class
3035 (or collating symbol) (and '\0' if needed). */
3036 GET_BUFFER_SPACE(datasize);
3037 /* Update the pointer to indicate end of buffer. */
3041 { /* equivalence class */
3042 /* Calculate the offset of char_ranges,
3043 which is next to equivalence_classes. */
3044 offset = laststart[1] + laststart[2]
3047 insert_space(datasize, laststart + offset, b - 1);
3049 /* Write the equivalence_class and \0. */
3050 for (i = 0 ; i < datasize ; i++)
3051 laststart[offset + i] = str[i];
3053 /* Update the length of equivalence_classes. */
3054 laststart[3] += datasize;
3055 had_char_class = true;
3057 else /* delim == '.' */
3058 { /* collating symbol */
3059 /* Calculate the offset of the equivalence_classes,
3060 which is next to collating_symbols. */
3061 offset = laststart[1] + laststart[2] + 6;
3062 /* Insert space and write the collationg_symbol
3064 insert_space(datasize, laststart + offset, b-1);
3065 for (i = 0 ; i < datasize ; i++)
3066 laststart[offset + i] = str[i];
3068 /* In re_match_2_internal if range_start < -1, we
3069 assume -range_start is the offset of the
3070 collating symbol which is specified as
3071 the character of the range start. So we assign
3072 -(laststart[1] + laststart[2] + 6) to
3074 range_start = -(laststart[1] + laststart[2] + 6);
3075 /* Update the length of collating_symbol. */
3076 laststart[2] += datasize;
3077 had_char_class = false;
3087 laststart[5] += 2; /* Update the length of characters */
3088 range_start = delim;
3089 had_char_class = false;
3094 had_char_class = false;
3096 laststart[5]++; /* Update the length of characters */
3101 #else /* not MBS_SUPPORT */
3102 /* Ensure that we have enough space to push a charset: the
3103 opcode, the length count, and the bitset; 34 bytes in all. */
3104 GET_BUFFER_SPACE (34);
3108 /* We test `*p == '^' twice, instead of using an if
3109 statement, so we only need one BUF_PUSH. */
3110 BUF_PUSH (*p == '^' ? charset_not : charset);
3114 /* Remember the first position in the bracket expression. */
3117 /* Push the number of bytes in the bitmap. */
3118 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3120 /* Clear the whole map. */
3121 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3123 /* charset_not matches newline according to a syntax bit. */
3124 if ((re_opcode_t) b[-2] == charset_not
3125 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3126 SET_LIST_BIT ('\n');
3128 /* Read in characters and ranges, setting map bits. */
3131 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3135 /* \ might escape characters inside [...] and [^...]. */
3136 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3138 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3146 /* Could be the end of the bracket expression. If it's
3147 not (i.e., when the bracket expression is `[]' so
3148 far), the ']' character bit gets set way below. */
3149 if (c == ']' && p != p1 + 1)
3152 /* Look ahead to see if it's a range when the last thing
3153 was a character class. */
3154 if (had_char_class && c == '-' && *p != ']')
3155 FREE_STACK_RETURN (REG_ERANGE);
3157 /* Look ahead to see if it's a range when the last thing
3158 was a character: if this is a hyphen not at the
3159 beginning or the end of a list, then it's the range
3162 && !(p - 2 >= pattern && p[-2] == '[')
3163 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3167 = compile_range (range_start, &p, pend, translate,
3169 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3170 range_start = 0xffffffff;
3173 else if (p[0] == '-' && p[1] != ']')
3174 { /* This handles ranges made up of characters only. */
3177 /* Move past the `-'. */
3180 ret = compile_range (c, &p, pend, translate, syntax, b);
3181 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3182 range_start = 0xffffffff;
3185 /* See if we're at the beginning of a possible character
3188 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3189 { /* Leave room for the null. */
3190 char str[CHAR_CLASS_MAX_LENGTH + 1];
3195 /* If pattern is `[[:'. */
3196 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3201 if ((c == ':' && *p == ']') || p == pend)
3203 if (c1 < CHAR_CLASS_MAX_LENGTH)
3206 /* This is in any case an invalid class name. */
3211 /* If isn't a word bracketed by `[:' and `:]':
3212 undo the ending character, the letters, and leave
3213 the leading `:' and `[' (but set bits for them). */
3214 if (c == ':' && *p == ']')
3216 # if defined _LIBC || WIDE_CHAR_SUPPORT
3217 boolean is_lower = STREQ (str, "lower");
3218 boolean is_upper = STREQ (str, "upper");
3222 wt = IS_CHAR_CLASS (str);
3224 FREE_STACK_RETURN (REG_ECTYPE);
3226 /* Throw away the ] at the end of the character
3230 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3232 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3235 if (__iswctype (__btowc (ch), wt))
3238 if (iswctype (btowc (ch), wt))
3242 if (translate && (is_upper || is_lower)
3243 && (ISUPPER (ch) || ISLOWER (ch)))
3247 had_char_class = true;
3250 boolean is_alnum = STREQ (str, "alnum");
3251 boolean is_alpha = STREQ (str, "alpha");
3252 boolean is_blank = STREQ (str, "blank");
3253 boolean is_cntrl = STREQ (str, "cntrl");
3254 boolean is_digit = STREQ (str, "digit");
3255 boolean is_graph = STREQ (str, "graph");
3256 boolean is_lower = STREQ (str, "lower");
3257 boolean is_print = STREQ (str, "print");
3258 boolean is_punct = STREQ (str, "punct");
3259 boolean is_space = STREQ (str, "space");
3260 boolean is_upper = STREQ (str, "upper");
3261 boolean is_xdigit = STREQ (str, "xdigit");
3263 if (!IS_CHAR_CLASS (str))
3264 FREE_STACK_RETURN (REG_ECTYPE);
3266 /* Throw away the ] at the end of the character
3270 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3272 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3274 /* This was split into 3 if's to
3275 avoid an arbitrary limit in some compiler. */
3276 if ( (is_alnum && ISALNUM (ch))
3277 || (is_alpha && ISALPHA (ch))
3278 || (is_blank && ISBLANK (ch))
3279 || (is_cntrl && ISCNTRL (ch)))
3281 if ( (is_digit && ISDIGIT (ch))
3282 || (is_graph && ISGRAPH (ch))
3283 || (is_lower && ISLOWER (ch))
3284 || (is_print && ISPRINT (ch)))
3286 if ( (is_punct && ISPUNCT (ch))
3287 || (is_space && ISSPACE (ch))
3288 || (is_upper && ISUPPER (ch))
3289 || (is_xdigit && ISXDIGIT (ch)))
3291 if ( translate && (is_upper || is_lower)
3292 && (ISUPPER (ch) || ISLOWER (ch)))
3295 had_char_class = true;
3296 # endif /* libc || wctype.h */
3306 had_char_class = false;
3309 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3311 unsigned char str[MB_LEN_MAX + 1];
3314 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3320 /* If pattern is `[[='. */
3321 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3326 if ((c == '=' && *p == ']') || p == pend)
3328 if (c1 < MB_LEN_MAX)
3331 /* This is in any case an invalid class name. */
3336 if (c == '=' && *p == ']' && str[0] != '\0')
3338 /* If we have no collation data we use the default
3339 collation in which each character is in a class
3340 by itself. It also means that ASCII is the
3341 character set and therefore we cannot have character
3342 with more than one byte in the multibyte
3349 FREE_STACK_RETURN (REG_ECOLLATE);
3351 /* Throw away the ] at the end of the equivalence
3355 /* Set the bit for the character. */
3356 SET_LIST_BIT (str[0]);
3361 /* Try to match the byte sequence in `str' against
3362 those known to the collate implementation.
3363 First find out whether the bytes in `str' are
3364 actually from exactly one character. */
3365 const int32_t *table;
3366 const unsigned char *weights;
3367 const unsigned char *extra;
3368 const int32_t *indirect;
3370 const unsigned char *cp = str;
3373 /* This #include defines a local function! */
3374 # include <locale/weight.h>
3376 table = (const int32_t *)
3377 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3378 weights = (const unsigned char *)
3379 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3380 extra = (const unsigned char *)
3381 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3382 indirect = (const int32_t *)
3383 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3385 idx = findidx (&cp);
3386 if (idx == 0 || cp < str + c1)
3387 /* This is no valid character. */
3388 FREE_STACK_RETURN (REG_ECOLLATE);
3390 /* Throw away the ] at the end of the equivalence
3394 /* Now we have to go throught the whole table
3395 and find all characters which have the same
3398 XXX Note that this is not entirely correct.
3399 we would have to match multibyte sequences
3400 but this is not possible with the current
3402 for (ch = 1; ch < 256; ++ch)
3403 /* XXX This test would have to be changed if we
3404 would allow matching multibyte sequences. */
3407 int32_t idx2 = table[ch];
3408 size_t len = weights[idx2];
3410 /* Test whether the lenghts match. */
3411 if (weights[idx] == len)
3413 /* They do. New compare the bytes of
3418 && (weights[idx + 1 + cnt]
3419 == weights[idx2 + 1 + cnt]))
3423 /* They match. Mark the character as
3430 had_char_class = true;
3440 had_char_class = false;
3443 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3445 unsigned char str[128]; /* Should be large enough. */
3448 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3454 /* If pattern is `[[.'. */
3455 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3460 if ((c == '.' && *p == ']') || p == pend)
3462 if (c1 < sizeof (str))
3465 /* This is in any case an invalid class name. */
3470 if (c == '.' && *p == ']' && str[0] != '\0')
3472 /* If we have no collation data we use the default
3473 collation in which each character is the name
3474 for its own class which contains only the one
3475 character. It also means that ASCII is the
3476 character set and therefore we cannot have character
3477 with more than one byte in the multibyte
3484 FREE_STACK_RETURN (REG_ECOLLATE);
3486 /* Throw away the ] at the end of the equivalence
3490 /* Set the bit for the character. */
3491 SET_LIST_BIT (str[0]);
3492 range_start = ((const unsigned char *) str)[0];
3497 /* Try to match the byte sequence in `str' against
3498 those known to the collate implementation.
3499 First find out whether the bytes in `str' are
3500 actually from exactly one character. */
3502 const int32_t *symb_table;
3503 const unsigned char *extra;
3510 _NL_CURRENT_WORD (LC_COLLATE,
3511 _NL_COLLATE_SYMB_HASH_SIZEMB);
3512 symb_table = (const int32_t *)
3513 _NL_CURRENT (LC_COLLATE,
3514 _NL_COLLATE_SYMB_TABLEMB);
3515 extra = (const unsigned char *)
3516 _NL_CURRENT (LC_COLLATE,
3517 _NL_COLLATE_SYMB_EXTRAMB);
3519 /* Locate the character in the hashing table. */
3520 hash = elem_hash (str, c1);
3523 elem = hash % table_size;
3524 second = hash % (table_size - 2);
3525 while (symb_table[2 * elem] != 0)
3527 /* First compare the hashing value. */
3528 if (symb_table[2 * elem] == hash
3529 && c1 == extra[symb_table[2 * elem + 1]]
3531 &extra[symb_table[2 * elem + 1]
3535 /* Yep, this is the entry. */
3536 idx = symb_table[2 * elem + 1];
3537 idx += 1 + extra[idx];
3545 if (symb_table[2 * elem] == 0)
3546 /* This is no valid character. */
3547 FREE_STACK_RETURN (REG_ECOLLATE);
3549 /* Throw away the ] at the end of the equivalence
3553 /* Now add the multibyte character(s) we found
3556 XXX Note that this is not entirely correct.
3557 we would have to match multibyte sequences
3558 but this is not possible with the current
3559 implementation. Also, we have to match
3560 collating symbols, which expand to more than
3561 one file, as a whole and not allow the
3562 individual bytes. */
3565 range_start = extra[idx];
3568 SET_LIST_BIT (extra[idx]);
3573 had_char_class = false;
3583 had_char_class = false;
3588 had_char_class = false;
3594 /* Discard any (non)matching list bytes that are all 0 at the
3595 end of the map. Decrease the map-length byte too. */
3596 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3599 #endif /* MBS_SUPPORT */
3605 if (syntax & RE_NO_BK_PARENS)
3612 if (syntax & RE_NO_BK_PARENS)
3619 if (syntax & RE_NEWLINE_ALT)
3626 if (syntax & RE_NO_BK_VBAR)
3633 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3634 goto handle_interval;
3640 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3642 /* Do not translate the character after the \, so that we can
3643 distinguish, e.g., \B from \b, even if we normally would
3644 translate, e.g., B to b. */
3650 if (syntax & RE_NO_BK_PARENS)
3651 goto normal_backslash;
3657 if (COMPILE_STACK_FULL)
3659 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3660 compile_stack_elt_t);
3661 if (compile_stack.stack == NULL) return REG_ESPACE;
3663 compile_stack.size <<= 1;
3666 /* These are the values to restore when we hit end of this
3667 group. They are all relative offsets, so that if the
3668 whole pattern moves because of realloc, they will still
3670 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3671 COMPILE_STACK_TOP.fixup_alt_jump
3672 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3673 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3674 COMPILE_STACK_TOP.regnum = regnum;
3676 /* We will eventually replace the 0 with the number of
3677 groups inner to this one. But do not push a
3678 start_memory for groups beyond the last one we can
3679 represent in the compiled pattern. */
3680 if (regnum <= MAX_REGNUM)
3682 COMPILE_STACK_TOP.inner_group_offset = b
3683 - COMPILED_BUFFER_VAR + 2;
3684 BUF_PUSH_3 (start_memory, regnum, 0);
3687 compile_stack.avail++;
3692 /* If we've reached MAX_REGNUM groups, then this open
3693 won't actually generate any code, so we'll have to
3694 clear pending_exact explicitly. */
3700 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3702 if (COMPILE_STACK_EMPTY)
3704 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3705 goto normal_backslash;
3707 FREE_STACK_RETURN (REG_ERPAREN);
3712 { /* Push a dummy failure point at the end of the
3713 alternative for a possible future
3714 `pop_failure_jump' to pop. See comments at
3715 `push_dummy_failure' in `re_match_2'. */
3716 BUF_PUSH (push_dummy_failure);
3718 /* We allocated space for this jump when we assigned
3719 to `fixup_alt_jump', in the `handle_alt' case below. */
3720 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3723 /* See similar code for backslashed left paren above. */
3724 if (COMPILE_STACK_EMPTY)
3726 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3729 FREE_STACK_RETURN (REG_ERPAREN);
3732 /* Since we just checked for an empty stack above, this
3733 ``can't happen''. */
3734 assert (compile_stack.avail != 0);
3736 /* We don't just want to restore into `regnum', because
3737 later groups should continue to be numbered higher,
3738 as in `(ab)c(de)' -- the second group is #2. */
3739 regnum_t this_group_regnum;
3741 compile_stack.avail--;
3742 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3744 = COMPILE_STACK_TOP.fixup_alt_jump
3745 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3747 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3748 this_group_regnum = COMPILE_STACK_TOP.regnum;
3749 /* If we've reached MAX_REGNUM groups, then this open
3750 won't actually generate any code, so we'll have to
3751 clear pending_exact explicitly. */
3754 /* We're at the end of the group, so now we know how many
3755 groups were inside this one. */
3756 if (this_group_regnum <= MAX_REGNUM)
3758 US_CHAR_TYPE *inner_group_loc
3759 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3761 *inner_group_loc = regnum - this_group_regnum;
3762 BUF_PUSH_3 (stop_memory, this_group_regnum,
3763 regnum - this_group_regnum);
3769 case '|': /* `\|'. */
3770 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3771 goto normal_backslash;
3773 if (syntax & RE_LIMITED_OPS)
3776 /* Insert before the previous alternative a jump which
3777 jumps to this alternative if the former fails. */
3778 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3779 INSERT_JUMP (on_failure_jump, begalt,
3780 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3782 b += 1 + OFFSET_ADDRESS_SIZE;
3784 /* The alternative before this one has a jump after it
3785 which gets executed if it gets matched. Adjust that
3786 jump so it will jump to this alternative's analogous
3787 jump (put in below, which in turn will jump to the next
3788 (if any) alternative's such jump, etc.). The last such
3789 jump jumps to the correct final destination. A picture:
3795 If we are at `b', then fixup_alt_jump right now points to a
3796 three-byte space after `a'. We'll put in the jump, set
3797 fixup_alt_jump to right after `b', and leave behind three
3798 bytes which we'll fill in when we get to after `c'. */
3801 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3803 /* Mark and leave space for a jump after this alternative,
3804 to be filled in later either by next alternative or
3805 when know we're at the end of a series of alternatives. */
3807 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3808 b += 1 + OFFSET_ADDRESS_SIZE;
3816 /* If \{ is a literal. */
3817 if (!(syntax & RE_INTERVALS)
3818 /* If we're at `\{' and it's not the open-interval
3820 || (syntax & RE_NO_BK_BRACES))
3821 goto normal_backslash;
3825 /* If got here, then the syntax allows intervals. */
3827 /* At least (most) this many matches must be made. */
3828 int lower_bound = -1, upper_bound = -1;
3829 beg_interval = p - 1;
3833 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3834 goto unfetch_interval;
3836 FREE_STACK_RETURN (REG_EBRACE);
3839 GET_UNSIGNED_NUMBER (lower_bound);
3843 GET_UNSIGNED_NUMBER (upper_bound);
3844 if ((!(syntax & RE_NO_BK_BRACES) && c != '\\')
3845 || ((syntax & RE_NO_BK_BRACES) && c != '}'))
3846 FREE_STACK_RETURN (REG_BADBR);
3848 if (upper_bound < 0)
3849 upper_bound = RE_DUP_MAX;
3852 /* Interval such as `{1}' => match exactly once. */
3853 upper_bound = lower_bound;
3855 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3856 || lower_bound > upper_bound)
3858 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3859 goto unfetch_interval;
3861 FREE_STACK_RETURN (REG_BADBR);
3864 if (!(syntax & RE_NO_BK_BRACES))
3866 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
3873 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3874 goto unfetch_interval;
3876 FREE_STACK_RETURN (REG_BADBR);
3879 /* We just parsed a valid interval. */
3881 /* If it's invalid to have no preceding re. */
3884 if (syntax & RE_CONTEXT_INVALID_OPS)
3885 FREE_STACK_RETURN (REG_BADRPT);
3886 else if (syntax & RE_CONTEXT_INDEP_OPS)
3889 goto unfetch_interval;
3892 /* If the upper bound is zero, don't want to succeed at
3893 all; jump from `laststart' to `b + 3', which will be
3894 the end of the buffer after we insert the jump. */
3895 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE'
3896 instead of 'b + 3'. */
3897 if (upper_bound == 0)
3899 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3900 INSERT_JUMP (jump, laststart, b + 1
3901 + OFFSET_ADDRESS_SIZE);
3902 b += 1 + OFFSET_ADDRESS_SIZE;
3905 /* Otherwise, we have a nontrivial interval. When
3906 we're all done, the pattern will look like:
3907 set_number_at <jump count> <upper bound>
3908 set_number_at <succeed_n count> <lower bound>
3909 succeed_n <after jump addr> <succeed_n count>
3911 jump_n <succeed_n addr> <jump count>
3912 (The upper bound and `jump_n' are omitted if
3913 `upper_bound' is 1, though.) */
3915 { /* If the upper bound is > 1, we need to insert
3916 more at the end of the loop. */
3917 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3918 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3920 GET_BUFFER_SPACE (nbytes);
3922 /* Initialize lower bound of the `succeed_n', even
3923 though it will be set during matching by its
3924 attendant `set_number_at' (inserted next),
3925 because `re_compile_fastmap' needs to know.
3926 Jump to the `jump_n' we might insert below. */
3927 INSERT_JUMP2 (succeed_n, laststart,
3928 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3929 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3931 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3933 /* Code to initialize the lower bound. Insert
3934 before the `succeed_n'. The `5' is the last two
3935 bytes of this `set_number_at', plus 3 bytes of
3936 the following `succeed_n'. */
3937 /* ifdef MBS_SUPPORT, The '1+2*OFFSET_ADDRESS_SIZE'
3938 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3939 of the following `succeed_n'. */
3940 insert_op2 (set_number_at, laststart, 1
3941 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3942 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3944 if (upper_bound > 1)
3945 { /* More than one repetition is allowed, so
3946 append a backward jump to the `succeed_n'
3947 that starts this interval.
3949 When we've reached this during matching,
3950 we'll have matched the interval once, so
3951 jump back only `upper_bound - 1' times. */
3952 STORE_JUMP2 (jump_n, b, laststart
3953 + 2 * OFFSET_ADDRESS_SIZE + 1,
3955 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3957 /* The location we want to set is the second
3958 parameter of the `jump_n'; that is `b-2' as
3959 an absolute address. `laststart' will be
3960 the `set_number_at' we're about to insert;
3961 `laststart+3' the number to set, the source
3962 for the relative address. But we are
3963 inserting into the middle of the pattern --
3964 so everything is getting moved up by 5.
3965 Conclusion: (b - 2) - (laststart + 3) + 5,
3966 i.e., b - laststart.
3968 We insert this at the beginning of the loop
3969 so that if we fail during matching, we'll
3970 reinitialize the bounds. */
3971 insert_op2 (set_number_at, laststart, b - laststart,
3972 upper_bound - 1, b);
3973 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3977 beg_interval = NULL;
3982 /* If an invalid interval, match the characters as literals. */
3983 assert (beg_interval);
3985 beg_interval = NULL;
3987 /* normal_char and normal_backslash need `c'. */
3990 if (!(syntax & RE_NO_BK_BRACES))
3992 if (p > pattern && p[-1] == '\\')
3993 goto normal_backslash;
3998 /* There is no way to specify the before_dot and after_dot
3999 operators. rms says this is ok. --karl */
4007 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
4013 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
4019 if (syntax & RE_NO_GNU_OPS)
4022 BUF_PUSH (wordchar);
4027 if (syntax & RE_NO_GNU_OPS)
4030 BUF_PUSH (notwordchar);
4035 if (syntax & RE_NO_GNU_OPS)
4041 if (syntax & RE_NO_GNU_OPS)
4047 if (syntax & RE_NO_GNU_OPS)
4049 BUF_PUSH (wordbound);
4053 if (syntax & RE_NO_GNU_OPS)
4055 BUF_PUSH (notwordbound);
4059 if (syntax & RE_NO_GNU_OPS)
4065 if (syntax & RE_NO_GNU_OPS)
4070 case '1': case '2': case '3': case '4': case '5':
4071 case '6': case '7': case '8': case '9':
4072 if (syntax & RE_NO_BK_REFS)
4078 FREE_STACK_RETURN (REG_ESUBREG);
4080 /* Can't back reference to a subexpression if inside of it. */
4081 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4085 BUF_PUSH_2 (duplicate, c1);
4091 if (syntax & RE_BK_PLUS_QM)
4094 goto normal_backslash;
4098 /* You might think it would be useful for \ to mean
4099 not to translate; but if we don't translate it
4100 it will never match anything. */
4108 /* Expects the character in `c'. */
4110 /* If no exactn currently being built. */
4113 /* If last exactn handle binary(or character) and
4114 new exactn handle character(or binary). */
4115 || is_exactn_bin != is_binary[p - 1 - pattern]
4116 #endif /* MBS_SUPPORT */
4118 /* If last exactn not at current position. */
4119 || pending_exact + *pending_exact + 1 != b
4121 /* We have only one byte following the exactn for the count. */
4122 || *pending_exact == (1 << BYTEWIDTH) - 1
4124 /* If followed by a repetition operator. */
4125 || *p == '*' || *p == '^'
4126 || ((syntax & RE_BK_PLUS_QM)
4127 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4128 : (*p == '+' || *p == '?'))
4129 || ((syntax & RE_INTERVALS)
4130 && ((syntax & RE_NO_BK_BRACES)
4132 : (p[0] == '\\' && p[1] == '{'))))
4134 /* Start building a new exactn. */
4139 /* Is this exactn binary data or character? */
4140 is_exactn_bin = is_binary[p - 1 - pattern];
4142 BUF_PUSH_2 (exactn_bin, 0);
4144 BUF_PUSH_2 (exactn, 0);
4146 BUF_PUSH_2 (exactn, 0);
4147 #endif /* MBS_SUPPORT */
4148 pending_exact = b - 1;
4155 } /* while p != pend */
4158 /* Through the pattern now. */
4161 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4163 if (!COMPILE_STACK_EMPTY)
4164 FREE_STACK_RETURN (REG_EPAREN);
4166 /* If we don't want backtracking, force success
4167 the first time we reach the end of the compiled pattern. */
4168 if (syntax & RE_NO_POSIX_BACKTRACKING)
4176 free (compile_stack.stack);
4178 /* We have succeeded; set the length of the buffer. */
4180 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4182 bufp->used = b - bufp->buffer;
4188 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4189 print_compiled_pattern (bufp);
4193 #ifndef MATCH_MAY_ALLOCATE
4194 /* Initialize the failure stack to the largest possible stack. This
4195 isn't necessary unless we're trying to avoid calling alloca in
4196 the search and match routines. */
4198 int num_regs = bufp->re_nsub + 1;
4200 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4201 is strictly greater than re_max_failures, the largest possible stack
4202 is 2 * re_max_failures failure points. */
4203 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4205 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4208 if (! fail_stack.stack)
4210 = (fail_stack_elt_t *) xmalloc (fail_stack.size
4211 * sizeof (fail_stack_elt_t));
4214 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
4216 * sizeof (fail_stack_elt_t)));
4217 # else /* not emacs */
4218 if (! fail_stack.stack)
4220 = (fail_stack_elt_t *) malloc (fail_stack.size
4221 * sizeof (fail_stack_elt_t));
4224 = (fail_stack_elt_t *) realloc (fail_stack.stack,
4226 * sizeof (fail_stack_elt_t)));
4227 # endif /* not emacs */
4230 regex_grow_registers (num_regs);
4232 #endif /* not MATCH_MAY_ALLOCATE */
4235 } /* regex_compile */
4237 /* Subroutines for `regex_compile'. */
4239 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4240 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4243 store_op1 (op, loc, arg)
4248 *loc = (US_CHAR_TYPE) op;
4249 STORE_NUMBER (loc + 1, arg);
4253 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4254 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4257 store_op2 (op, loc, arg1, arg2)
4262 *loc = (US_CHAR_TYPE) op;
4263 STORE_NUMBER (loc + 1, arg1);
4264 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4268 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4269 for OP followed by two-byte integer parameter ARG. */
4270 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4273 insert_op1 (op, loc, arg, end)
4279 register US_CHAR_TYPE *pfrom = end;
4280 register US_CHAR_TYPE *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4282 while (pfrom != loc)
4285 store_op1 (op, loc, arg);
4289 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4290 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4293 insert_op2 (op, loc, arg1, arg2, end)
4299 register US_CHAR_TYPE *pfrom = end;
4300 register US_CHAR_TYPE *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4302 while (pfrom != loc)
4305 store_op2 (op, loc, arg1, arg2);
4309 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4310 after an alternative or a begin-subexpression. We assume there is at
4311 least one character before the ^. */
4314 at_begline_loc_p (pattern, p, syntax)
4315 const CHAR_TYPE *pattern, *p;
4316 reg_syntax_t syntax;
4318 const CHAR_TYPE *prev = p - 2;
4319 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4322 /* After a subexpression? */
4323 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4324 /* After an alternative? */
4325 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4329 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4330 at least one character after the $, i.e., `P < PEND'. */
4333 at_endline_loc_p (p, pend, syntax)
4334 const CHAR_TYPE *p, *pend;
4335 reg_syntax_t syntax;
4337 const CHAR_TYPE *next = p;
4338 boolean next_backslash = *next == '\\';
4339 const CHAR_TYPE *next_next = p + 1 < pend ? p + 1 : 0;
4342 /* Before a subexpression? */
4343 (syntax & RE_NO_BK_PARENS ? *next == ')'
4344 : next_backslash && next_next && *next_next == ')')
4345 /* Before an alternative? */
4346 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4347 : next_backslash && next_next && *next_next == '|');
4351 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4352 false if it's not. */
4355 group_in_compile_stack (compile_stack, regnum)
4356 compile_stack_type compile_stack;
4361 for (this_element = compile_stack.avail - 1;
4364 if (compile_stack.stack[this_element].regnum == regnum)
4371 /* This insert space, which size is "num", into the pattern at "loc".
4372 "end" must point the end of the allocated buffer. */
4374 insert_space (num, loc, end)
4379 register CHAR_TYPE *pto = end;
4380 register CHAR_TYPE *pfrom = end - num;
4382 while (pfrom >= loc)
4385 #endif /* MBS_SUPPORT */
4388 static reg_errcode_t
4389 compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4391 CHAR_TYPE range_start_char;
4392 const CHAR_TYPE **p_ptr, *pend;
4393 CHAR_TYPE *char_set, *b;
4394 RE_TRANSLATE_TYPE translate;
4395 reg_syntax_t syntax;
4397 const CHAR_TYPE *p = *p_ptr;
4398 CHAR_TYPE range_start, range_end;
4402 uint32_t start_val, end_val;
4408 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4411 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4412 _NL_COLLATE_COLLSEQWC);
4413 const unsigned char *extra = (const unsigned char *)
4414 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4416 if (range_start_char < -1)
4418 /* range_start is a collating symbol. */
4420 /* Retreive the index and get collation sequence value. */
4421 wextra = (int32_t*)(extra + char_set[-range_start_char]);
4422 start_val = wextra[1 + *wextra];
4425 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4427 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4429 /* Report an error if the range is empty and the syntax prohibits
4431 ret = ((syntax & RE_NO_EMPTY_RANGES)
4432 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4434 /* Insert space to the end of the char_ranges. */
4435 insert_space(2, b - char_set[5] - 2, b - 1);
4436 *(b - char_set[5] - 2) = (wchar_t)start_val;
4437 *(b - char_set[5] - 1) = (wchar_t)end_val;
4438 char_set[4]++; /* ranges_index */
4443 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4445 range_end = TRANSLATE (p[0]);
4446 /* Report an error if the range is empty and the syntax prohibits
4448 ret = ((syntax & RE_NO_EMPTY_RANGES)
4449 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4451 /* Insert space to the end of the char_ranges. */
4452 insert_space(2, b - char_set[5] - 2, b - 1);
4453 *(b - char_set[5] - 2) = range_start;
4454 *(b - char_set[5] - 1) = range_end;
4455 char_set[4]++; /* ranges_index */
4457 /* Have to increment the pointer into the pattern string, so the
4458 caller isn't still at the ending character. */
4464 /* Read the ending character of a range (in a bracket expression) from the
4465 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4466 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4467 Then we set the translation of all bits between the starting and
4468 ending characters (inclusive) in the compiled pattern B.
4470 Return an error code.
4472 We use these short variable names so we can use the same macros as
4473 `regex_compile' itself. */
4475 static reg_errcode_t
4476 compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4477 unsigned int range_start_char;
4478 const char **p_ptr, *pend;
4479 RE_TRANSLATE_TYPE translate;
4480 reg_syntax_t syntax;
4484 const char *p = *p_ptr;
4487 const unsigned char *collseq;
4488 unsigned int start_colseq;
4489 unsigned int end_colseq;
4497 /* Have to increment the pointer into the pattern string, so the
4498 caller isn't still at the ending character. */
4501 /* Report an error if the range is empty and the syntax prohibits this. */
4502 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4505 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4506 _NL_COLLATE_COLLSEQMB);
4508 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4509 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4510 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4512 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4514 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4516 SET_LIST_BIT (TRANSLATE (this_char));
4521 /* Here we see why `this_char' has to be larger than an `unsigned
4522 char' -- we would otherwise go into an infinite loop, since all
4523 characters <= 0xff. */
4524 range_start_char = TRANSLATE (range_start_char);
4525 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4526 and some compilers cast it to int implicitly, so following for_loop
4527 may fall to (almost) infinite loop.
4528 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4529 To avoid this, we cast p[0] to unsigned int and truncate it. */
4530 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4532 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4534 SET_LIST_BIT (TRANSLATE (this_char));
4541 #endif /* MBS_SUPPORT */
4543 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4544 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4545 characters can start a string that matches the pattern. This fastmap
4546 is used by re_search to skip quickly over impossible starting points.
4548 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4549 area as BUFP->fastmap.
4551 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4554 Returns 0 if we succeed, -2 if an internal error. */
4557 /* local function for re_compile_fastmap.
4558 truncate wchar_t character to char. */
4559 static unsigned char truncate_wchar (CHAR_TYPE c);
4561 static unsigned char
4565 unsigned char buf[MB_LEN_MAX];
4566 int retval = wctomb(buf, c);
4567 return retval > 0 ? buf[0] : (unsigned char)c;
4569 #endif /* MBS_SUPPORT */
4572 re_compile_fastmap (bufp)
4573 struct re_pattern_buffer *bufp;
4576 #ifdef MATCH_MAY_ALLOCATE
4577 fail_stack_type fail_stack;
4579 #ifndef REGEX_MALLOC
4583 register char *fastmap = bufp->fastmap;
4586 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4587 pattern to (char*) in regex_compile. */
4588 US_CHAR_TYPE *pattern = (US_CHAR_TYPE*)bufp->buffer;
4589 register US_CHAR_TYPE *pend = (US_CHAR_TYPE*) (bufp->buffer + bufp->used);
4591 US_CHAR_TYPE *pattern = bufp->buffer;
4592 register US_CHAR_TYPE *pend = pattern + bufp->used;
4593 #endif /* MBS_SUPPORT */
4594 US_CHAR_TYPE *p = pattern;
4597 /* This holds the pointer to the failure stack, when
4598 it is allocated relocatably. */
4599 fail_stack_elt_t *failure_stack_ptr;
4602 /* Assume that each path through the pattern can be null until
4603 proven otherwise. We set this false at the bottom of switch
4604 statement, to which we get only if a particular path doesn't
4605 match the empty string. */
4606 boolean path_can_be_null = true;
4608 /* We aren't doing a `succeed_n' to begin with. */
4609 boolean succeed_n_p = false;
4611 assert (fastmap != NULL && p != NULL);
4614 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4615 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4616 bufp->can_be_null = 0;
4620 if (p == pend || *p == succeed)
4622 /* We have reached the (effective) end of pattern. */
4623 if (!FAIL_STACK_EMPTY ())
4625 bufp->can_be_null |= path_can_be_null;
4627 /* Reset for next path. */
4628 path_can_be_null = true;
4630 p = fail_stack.stack[--fail_stack.avail].pointer;
4638 /* We should never be about to go beyond the end of the pattern. */
4641 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4644 /* I guess the idea here is to simply not bother with a fastmap
4645 if a backreference is used, since it's too hard to figure out
4646 the fastmap for the corresponding group. Setting
4647 `can_be_null' stops `re_search_2' from using the fastmap, so
4648 that is all we do. */
4650 bufp->can_be_null = 1;
4654 /* Following are the cases which match a character. These end
4659 fastmap[truncate_wchar(p[1])] = 1;
4668 #endif /* MBS_SUPPORT */
4672 /* It is hard to distinguish fastmap from (multi byte) characters
4673 which depends on current locale. */
4678 bufp->can_be_null = 1;
4682 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4683 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4689 /* Chars beyond end of map must be allowed. */
4690 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4693 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4694 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4700 for (j = 0; j < (1 << BYTEWIDTH); j++)
4701 if (SYNTAX (j) == Sword)
4707 for (j = 0; j < (1 << BYTEWIDTH); j++)
4708 if (SYNTAX (j) != Sword)
4715 int fastmap_newline = fastmap['\n'];
4717 /* `.' matches anything ... */
4718 for (j = 0; j < (1 << BYTEWIDTH); j++)
4721 /* ... except perhaps newline. */
4722 if (!(bufp->syntax & RE_DOT_NEWLINE))
4723 fastmap['\n'] = fastmap_newline;
4725 /* Return if we have already set `can_be_null'; if we have,
4726 then the fastmap is irrelevant. Something's wrong here. */
4727 else if (bufp->can_be_null)
4730 /* Otherwise, have to check alternative paths. */
4737 for (j = 0; j < (1 << BYTEWIDTH); j++)
4738 if (SYNTAX (j) == (enum syntaxcode) k)
4745 for (j = 0; j < (1 << BYTEWIDTH); j++)
4746 if (SYNTAX (j) != (enum syntaxcode) k)
4751 /* All cases after this match the empty string. These end with
4771 case push_dummy_failure:
4776 case pop_failure_jump:
4777 case maybe_pop_jump:
4780 case dummy_failure_jump:
4781 EXTRACT_NUMBER_AND_INCR (j, p);
4786 /* Jump backward implies we just went through the body of a
4787 loop and matched nothing. Opcode jumped to should be
4788 `on_failure_jump' or `succeed_n'. Just treat it like an
4789 ordinary jump. For a * loop, it has pushed its failure
4790 point already; if so, discard that as redundant. */
4791 if ((re_opcode_t) *p != on_failure_jump
4792 && (re_opcode_t) *p != succeed_n)
4796 EXTRACT_NUMBER_AND_INCR (j, p);
4799 /* If what's on the stack is where we are now, pop it. */
4800 if (!FAIL_STACK_EMPTY ()
4801 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4807 case on_failure_jump:
4808 case on_failure_keep_string_jump:
4809 handle_on_failure_jump:
4810 EXTRACT_NUMBER_AND_INCR (j, p);
4812 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4813 end of the pattern. We don't want to push such a point,
4814 since when we restore it above, entering the switch will
4815 increment `p' past the end of the pattern. We don't need
4816 to push such a point since we obviously won't find any more
4817 fastmap entries beyond `pend'. Such a pattern can match
4818 the null string, though. */
4821 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4823 RESET_FAIL_STACK ();
4828 bufp->can_be_null = 1;
4832 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4833 succeed_n_p = false;
4840 /* Get to the number of times to succeed. */
4841 p += OFFSET_ADDRESS_SIZE;
4843 /* Increment p past the n for when k != 0. */
4844 EXTRACT_NUMBER_AND_INCR (k, p);
4847 p -= 2 * OFFSET_ADDRESS_SIZE;
4848 succeed_n_p = true; /* Spaghetti code alert. */
4849 goto handle_on_failure_jump;
4855 p += 2 * OFFSET_ADDRESS_SIZE;
4866 abort (); /* We have listed all the cases. */
4869 /* Getting here means we have found the possible starting
4870 characters for one path of the pattern -- and that the empty
4871 string does not match. We need not follow this path further.
4872 Instead, look at the next alternative (remembered on the
4873 stack), or quit if no more. The test at the top of the loop
4874 does these things. */
4875 path_can_be_null = false;
4879 /* Set `can_be_null' for the last path (also the first path, if the
4880 pattern is empty). */
4881 bufp->can_be_null |= path_can_be_null;
4884 RESET_FAIL_STACK ();
4886 } /* re_compile_fastmap */
4888 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4891 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4892 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4893 this memory for recording register information. STARTS and ENDS
4894 must be allocated using the malloc library routine, and must each
4895 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4897 If NUM_REGS == 0, then subsequent matches should allocate their own
4900 Unless this function is called, the first search or match using
4901 PATTERN_BUFFER will allocate its own register data, without
4902 freeing the old data. */
4905 re_set_registers (bufp, regs, num_regs, starts, ends)
4906 struct re_pattern_buffer *bufp;
4907 struct re_registers *regs;
4909 regoff_t *starts, *ends;
4913 bufp->regs_allocated = REGS_REALLOCATE;
4914 regs->num_regs = num_regs;
4915 regs->start = starts;
4920 bufp->regs_allocated = REGS_UNALLOCATED;
4922 regs->start = regs->end = (regoff_t *) 0;
4926 weak_alias (__re_set_registers, re_set_registers)
4929 /* Searching routines. */
4931 /* Like re_search_2, below, but only one string is specified, and
4932 doesn't let you say where to stop matching. */
4935 re_search (bufp, string, size, startpos, range, regs)
4936 struct re_pattern_buffer *bufp;
4938 int size, startpos, range;
4939 struct re_registers *regs;
4941 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4945 weak_alias (__re_search, re_search)
4949 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4950 virtual concatenation of STRING1 and STRING2, starting first at index
4951 STARTPOS, then at STARTPOS + 1, and so on.
4953 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4955 RANGE is how far to scan while trying to match. RANGE = 0 means try
4956 only at STARTPOS; in general, the last start tried is STARTPOS +
4959 In REGS, return the indices of the virtual concatenation of STRING1
4960 and STRING2 that matched the entire BUFP->buffer and its contained
4963 Do not consider matching one past the index STOP in the virtual
4964 concatenation of STRING1 and STRING2.
4966 We return either the position in the strings at which the match was
4967 found, -1 if no match, or -2 if error (such as failure
4971 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
4972 struct re_pattern_buffer *bufp;
4973 const char *string1, *string2;
4977 struct re_registers *regs;
4981 register char *fastmap = bufp->fastmap;
4982 register RE_TRANSLATE_TYPE translate = bufp->translate;
4983 int total_size = size1 + size2;
4984 int endpos = startpos + range;
4986 /* Check for out-of-range STARTPOS. */
4987 if (startpos < 0 || startpos > total_size)
4990 /* Fix up RANGE if it might eventually take us outside
4991 the virtual concatenation of STRING1 and STRING2.
4992 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4994 range = 0 - startpos;
4995 else if (endpos > total_size)
4996 range = total_size - startpos;
4998 /* If the search isn't to be a backwards one, don't waste time in a
4999 search for a pattern that must be anchored. */
5000 if (bufp->used > 0 && range > 0
5001 && ((re_opcode_t) bufp->buffer[0] == begbuf
5002 /* `begline' is like `begbuf' if it cannot match at newlines. */
5003 || ((re_opcode_t) bufp->buffer[0] == begline
5004 && !bufp->newline_anchor)))
5013 /* In a forward search for something that starts with \=.
5014 don't keep searching past point. */
5015 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5017 range = PT - startpos;
5023 /* Update the fastmap now if not correct already. */
5024 if (fastmap && !bufp->fastmap_accurate)
5025 if (re_compile_fastmap (bufp) == -2)
5028 /* Loop through the string, looking for a place to start matching. */
5031 /* If a fastmap is supplied, skip quickly over characters that
5032 cannot be the start of a match. If the pattern can match the
5033 null string, however, we don't need to skip characters; we want
5034 the first null string. */
5035 if (fastmap && startpos < total_size && !bufp->can_be_null)
5037 if (range > 0) /* Searching forwards. */
5039 register const char *d;
5040 register int lim = 0;
5043 if (startpos < size1 && startpos + range >= size1)
5044 lim = range - (size1 - startpos);
5046 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5048 /* Written out as an if-else to avoid testing `translate'
5052 && !fastmap[(unsigned char)
5053 translate[(unsigned char) *d++]])
5056 while (range > lim && !fastmap[(unsigned char) *d++])
5059 startpos += irange - range;
5061 else /* Searching backwards. */
5063 register CHAR_TYPE c = (size1 == 0 || startpos >= size1
5064 ? string2[startpos - size1]
5065 : string1[startpos]);
5067 if (!fastmap[(unsigned char) TRANSLATE (c)])
5072 /* If can't match the null string, and that's all we have left, fail. */
5073 if (range >= 0 && startpos == total_size && fastmap
5074 && !bufp->can_be_null)
5077 val = re_match_2_internal (bufp, string1, size1, string2, size2,
5078 startpos, regs, stop);
5079 #ifndef REGEX_MALLOC
5108 weak_alias (__re_search_2, re_search_2)
5112 /* This converts PTR, a pointer into one of the search wchar_t strings
5113 `string1' and `string2' into an multibyte string offset from the
5114 beginning of that string. We use mbs_offset to optimize.
5115 See convert_mbs_to_wcs. */
5116 # define POINTER_TO_OFFSET(ptr) \
5117 (FIRST_STRING_P (ptr) \
5118 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5119 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5122 /* This converts PTR, a pointer into one of the search strings `string1'
5123 and `string2' into an offset from the beginning of that string. */
5124 # define POINTER_TO_OFFSET(ptr) \
5125 (FIRST_STRING_P (ptr) \
5126 ? ((regoff_t) ((ptr) - string1)) \
5127 : ((regoff_t) ((ptr) - string2 + size1)))
5128 #endif /* MBS_SUPPORT */
5130 /* Macros for dealing with the split strings in re_match_2. */
5132 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5134 /* Call before fetching a character with *d. This switches over to
5135 string2 if necessary. */
5136 #define PREFETCH() \
5139 /* End of string2 => fail. */ \
5140 if (dend == end_match_2) \
5142 /* End of string1 => advance to string2. */ \
5144 dend = end_match_2; \
5148 /* Test if at very beginning or at very end of the virtual concatenation
5149 of `string1' and `string2'. If only one string, it's `string2'. */
5150 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5151 #define AT_STRINGS_END(d) ((d) == end2)
5154 /* Test if D points to a character which is word-constituent. We have
5155 two special cases to check for: if past the end of string1, look at
5156 the first character in string2; and if before the beginning of
5157 string2, look at the last character in string1. */
5159 /* Use internationalized API instead of SYNTAX. */
5160 # define WORDCHAR_P(d) \
5161 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5162 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5164 # define WORDCHAR_P(d) \
5165 (SYNTAX ((d) == end1 ? *string2 \
5166 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5168 #endif /* MBS_SUPPORT */
5170 /* Disabled due to a compiler bug -- see comment at case wordbound */
5172 /* Test if the character before D and the one at D differ with respect
5173 to being word-constituent. */
5174 #define AT_WORD_BOUNDARY(d) \
5175 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5176 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5179 /* Free everything we malloc. */
5180 #ifdef MATCH_MAY_ALLOCATE
5181 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5183 # define FREE_VARIABLES() \
5185 REGEX_FREE_STACK (fail_stack.stack); \
5186 FREE_VAR (regstart); \
5187 FREE_VAR (regend); \
5188 FREE_VAR (old_regstart); \
5189 FREE_VAR (old_regend); \
5190 FREE_VAR (best_regstart); \
5191 FREE_VAR (best_regend); \
5192 FREE_VAR (reg_info); \
5193 FREE_VAR (reg_dummy); \
5194 FREE_VAR (reg_info_dummy); \
5195 FREE_VAR (string1); \
5196 FREE_VAR (string2); \
5197 FREE_VAR (mbs_offset1); \
5198 FREE_VAR (mbs_offset2); \
5200 # else /* not MBS_SUPPORT */
5201 # define FREE_VARIABLES() \
5203 REGEX_FREE_STACK (fail_stack.stack); \
5204 FREE_VAR (regstart); \
5205 FREE_VAR (regend); \
5206 FREE_VAR (old_regstart); \
5207 FREE_VAR (old_regend); \
5208 FREE_VAR (best_regstart); \
5209 FREE_VAR (best_regend); \
5210 FREE_VAR (reg_info); \
5211 FREE_VAR (reg_dummy); \
5212 FREE_VAR (reg_info_dummy); \
5214 # endif /* MBS_SUPPORT */
5216 # define FREE_VAR(var) if (var) free (var); var = NULL
5218 # define FREE_VARIABLES() \
5220 FREE_VAR (string1); \
5221 FREE_VAR (string2); \
5222 FREE_VAR (mbs_offset1); \
5223 FREE_VAR (mbs_offset2); \
5226 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5227 # endif /* MBS_SUPPORT */
5228 #endif /* not MATCH_MAY_ALLOCATE */
5230 /* These values must meet several constraints. They must not be valid
5231 register values; since we have a limit of 255 registers (because
5232 we use only one byte in the pattern for the register number), we can
5233 use numbers larger than 255. They must differ by 1, because of
5234 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5235 be larger than the value for the highest register, so we do not try
5236 to actually save any registers when none are active. */
5237 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5238 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5240 /* Matching routines. */
5242 #ifndef emacs /* Emacs never uses this. */
5243 /* re_match is like re_match_2 except it takes only a single string. */
5246 re_match (bufp, string, size, pos, regs)
5247 struct re_pattern_buffer *bufp;
5250 struct re_registers *regs;
5252 int result = re_match_2_internal (bufp, NULL, 0, string, size,
5254 # ifndef REGEX_MALLOC
5262 weak_alias (__re_match, re_match)
5264 #endif /* not emacs */
5266 static boolean group_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5268 register_info_type *reg_info));
5269 static boolean alt_match_null_string_p _RE_ARGS ((US_CHAR_TYPE *p,
5271 register_info_type *reg_info));
5272 static boolean common_op_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5274 register_info_type *reg_info));
5275 static int bcmp_translate _RE_ARGS ((const CHAR_TYPE *s1, const CHAR_TYPE *s2,
5276 int len, char *translate));
5278 /* re_match_2 matches the compiled pattern in BUFP against the
5279 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5280 and SIZE2, respectively). We start matching at POS, and stop
5283 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5284 store offsets for the substring each group matched in REGS. See the
5285 documentation for exactly how many groups we fill.
5287 We return -1 if no match, -2 if an internal error (such as the
5288 failure stack overflowing). Otherwise, we return the length of the
5289 matched substring. */
5292 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5293 struct re_pattern_buffer *bufp;
5294 const char *string1, *string2;
5297 struct re_registers *regs;
5300 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
5302 #ifndef REGEX_MALLOC
5310 weak_alias (__re_match_2, re_match_2)
5315 static int count_mbs_length PARAMS ((int *, int));
5317 /* This check the substring (from 0, to length) of the multibyte string,
5318 to which offset_buffer correspond. And count how many wchar_t_characters
5319 the substring occupy. We use offset_buffer to optimization.
5320 See convert_mbs_to_wcs. */
5323 count_mbs_length(offset_buffer, length)
5329 /* Check whether the size is valid. */
5333 if (offset_buffer == NULL)
5336 for (wcs_size = 0 ; offset_buffer[wcs_size] != -1 ; wcs_size++)
5338 if (offset_buffer[wcs_size] == length)
5340 if (offset_buffer[wcs_size] > length)
5341 /* It is a fragment of a wide character. */
5345 /* We reached at the sentinel. */
5348 #endif /* MBS_SUPPORT */
5350 /* This is a separate function so that we can force an alloca cleanup
5354 re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos, regs, stop)
5355 struct re_pattern_buffer *bufp;
5356 const char *cstring1, *cstring2;
5359 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
5360 struct re_pattern_buffer *bufp;
5361 const char *string1, *string2;
5365 struct re_registers *regs;
5368 /* General temporaries. */
5372 /* We need wchar_t* buffers correspond to string1, string2. */
5373 CHAR_TYPE *string1 = NULL, *string2 = NULL;
5374 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5375 int size1 = 0, size2 = 0;
5376 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5377 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5378 /* They hold whether each wchar_t is binary data or not. */
5379 char *is_binary = NULL;
5380 #endif /* MBS_SUPPORT */
5382 /* Just past the end of the corresponding string. */
5383 const CHAR_TYPE *end1, *end2;
5385 /* Pointers into string1 and string2, just past the last characters in
5386 each to consider matching. */
5387 const CHAR_TYPE *end_match_1, *end_match_2;
5389 /* Where we are in the data, and the end of the current string. */
5390 const CHAR_TYPE *d, *dend;
5392 /* Where we are in the pattern, and the end of the pattern. */
5394 US_CHAR_TYPE *pattern, *p;
5395 register US_CHAR_TYPE *pend;
5397 US_CHAR_TYPE *p = bufp->buffer;
5398 register US_CHAR_TYPE *pend = p + bufp->used;
5399 #endif /* MBS_SUPPORT */
5401 /* Mark the opcode just after a start_memory, so we can test for an
5402 empty subpattern when we get to the stop_memory. */
5403 US_CHAR_TYPE *just_past_start_mem = 0;
5405 /* We use this to map every character in the string. */
5406 RE_TRANSLATE_TYPE translate = bufp->translate;
5408 /* Failure point stack. Each place that can handle a failure further
5409 down the line pushes a failure point on this stack. It consists of
5410 restart, regend, and reg_info for all registers corresponding to
5411 the subexpressions we're currently inside, plus the number of such
5412 registers, and, finally, two char *'s. The first char * is where
5413 to resume scanning the pattern; the second one is where to resume
5414 scanning the strings. If the latter is zero, the failure point is
5415 a ``dummy''; if a failure happens and the failure point is a dummy,
5416 it gets discarded and the next next one is tried. */
5417 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5418 fail_stack_type fail_stack;
5421 static unsigned failure_id;
5422 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5426 /* This holds the pointer to the failure stack, when
5427 it is allocated relocatably. */
5428 fail_stack_elt_t *failure_stack_ptr;
5431 /* We fill all the registers internally, independent of what we
5432 return, for use in backreferences. The number here includes
5433 an element for register zero. */
5434 size_t num_regs = bufp->re_nsub + 1;
5436 /* The currently active registers. */
5437 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5438 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5440 /* Information on the contents of registers. These are pointers into
5441 the input strings; they record just what was matched (on this
5442 attempt) by a subexpression part of the pattern, that is, the
5443 regnum-th regstart pointer points to where in the pattern we began
5444 matching and the regnum-th regend points to right after where we
5445 stopped matching the regnum-th subexpression. (The zeroth register
5446 keeps track of what the whole pattern matches.) */
5447 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5448 const CHAR_TYPE **regstart, **regend;
5451 /* If a group that's operated upon by a repetition operator fails to
5452 match anything, then the register for its start will need to be
5453 restored because it will have been set to wherever in the string we
5454 are when we last see its open-group operator. Similarly for a
5456 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5457 const CHAR_TYPE **old_regstart, **old_regend;
5460 /* The is_active field of reg_info helps us keep track of which (possibly
5461 nested) subexpressions we are currently in. The matched_something
5462 field of reg_info[reg_num] helps us tell whether or not we have
5463 matched any of the pattern so far this time through the reg_num-th
5464 subexpression. These two fields get reset each time through any
5465 loop their register is in. */
5466 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5467 register_info_type *reg_info;
5470 /* The following record the register info as found in the above
5471 variables when we find a match better than any we've seen before.
5472 This happens as we backtrack through the failure points, which in
5473 turn happens only if we have not yet matched the entire string. */
5474 unsigned best_regs_set = false;
5475 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5476 const CHAR_TYPE **best_regstart, **best_regend;
5479 /* Logically, this is `best_regend[0]'. But we don't want to have to
5480 allocate space for that if we're not allocating space for anything
5481 else (see below). Also, we never need info about register 0 for
5482 any of the other register vectors, and it seems rather a kludge to
5483 treat `best_regend' differently than the rest. So we keep track of
5484 the end of the best match so far in a separate variable. We
5485 initialize this to NULL so that when we backtrack the first time
5486 and need to test it, it's not garbage. */
5487 const CHAR_TYPE *match_end = NULL;
5489 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5490 int set_regs_matched_done = 0;
5492 /* Used when we pop values we don't care about. */
5493 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5494 const CHAR_TYPE **reg_dummy;
5495 register_info_type *reg_info_dummy;
5499 /* Counts the total number of registers pushed. */
5500 unsigned num_regs_pushed = 0;
5503 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5507 #ifdef MATCH_MAY_ALLOCATE
5508 /* Do not bother to initialize all the register variables if there are
5509 no groups in the pattern, as it takes a fair amount of time. If
5510 there are groups, we include space for register 0 (the whole
5511 pattern), even though we never use it, since it simplifies the
5512 array indexing. We should fix this. */
5515 regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5516 regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5517 old_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5518 old_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5519 best_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5520 best_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5521 reg_info = REGEX_TALLOC (num_regs, register_info_type);
5522 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5523 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
5525 if (!(regstart && regend && old_regstart && old_regend && reg_info
5526 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5534 /* We must initialize all our variables to NULL, so that
5535 `FREE_VARIABLES' doesn't try to free them. */
5536 regstart = regend = old_regstart = old_regend = best_regstart
5537 = best_regend = reg_dummy = NULL;
5538 reg_info = reg_info_dummy = (register_info_type *) NULL;
5540 #endif /* MATCH_MAY_ALLOCATE */
5542 /* The starting position is bogus. */
5544 if (pos < 0 || pos > csize1 + csize2)
5546 if (pos < 0 || pos > size1 + size2)
5554 /* Allocate wchar_t array for string1 and string2 and
5555 fill them with converted string. */
5558 string1 = REGEX_TALLOC (csize1 + 1, CHAR_TYPE);
5559 mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5560 is_binary = REGEX_TALLOC (csize1 + 1, char);
5561 if (!string1 || !mbs_offset1 || !is_binary)
5564 FREE_VAR (mbs_offset1);
5565 FREE_VAR (is_binary);
5568 size1 = convert_mbs_to_wcs(string1, cstring1, csize1,
5569 mbs_offset1, is_binary);
5570 string1[size1] = L'\0'; /* for a sentinel */
5571 FREE_VAR (is_binary);
5575 string2 = REGEX_TALLOC (csize2 + 1, CHAR_TYPE);
5576 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5577 is_binary = REGEX_TALLOC (csize2 + 1, char);
5578 if (!string2 || !mbs_offset2 || !is_binary)
5581 FREE_VAR (mbs_offset1);
5583 FREE_VAR (mbs_offset2);
5584 FREE_VAR (is_binary);
5587 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5588 mbs_offset2, is_binary);
5589 string2[size2] = L'\0'; /* for a sentinel */
5590 FREE_VAR (is_binary);
5593 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5594 pattern to (char*) in regex_compile. */
5595 p = pattern = (CHAR_TYPE*)bufp->buffer;
5596 pend = (CHAR_TYPE*)(bufp->buffer + bufp->used);
5598 #endif /* MBS_SUPPORT */
5600 /* Initialize subexpression text positions to -1 to mark ones that no
5601 start_memory/stop_memory has been seen for. Also initialize the
5602 register information struct. */
5603 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5605 regstart[mcnt] = regend[mcnt]
5606 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5608 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5609 IS_ACTIVE (reg_info[mcnt]) = 0;
5610 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5611 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5614 /* We move `string1' into `string2' if the latter's empty -- but not if
5615 `string1' is null. */
5616 if (size2 == 0 && string1 != NULL)
5623 end1 = string1 + size1;
5624 end2 = string2 + size2;
5626 /* Compute where to stop matching, within the two strings. */
5630 mcnt = count_mbs_length(mbs_offset1, stop);
5631 end_match_1 = string1 + mcnt;
5632 end_match_2 = string2;
5637 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5638 end_match_2 = string2 + mcnt;
5641 { /* count_mbs_length return error. */
5648 end_match_1 = string1 + stop;
5649 end_match_2 = string2;
5654 end_match_2 = string2 + stop - size1;
5656 #endif /* MBS_SUPPORT */
5658 /* `p' scans through the pattern as `d' scans through the data.
5659 `dend' is the end of the input string that `d' points within. `d'
5660 is advanced into the following input string whenever necessary, but
5661 this happens before fetching; therefore, at the beginning of the
5662 loop, `d' can be pointing at the end of a string, but it cannot
5665 if (size1 > 0 && pos <= csize1)
5667 mcnt = count_mbs_length(mbs_offset1, pos);
5673 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5679 { /* count_mbs_length return error. */
5684 if (size1 > 0 && pos <= size1)
5691 d = string2 + pos - size1;
5694 #endif /* MBS_SUPPORT */
5696 DEBUG_PRINT1 ("The compiled pattern is:\n");
5697 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5698 DEBUG_PRINT1 ("The string to match is: `");
5699 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5700 DEBUG_PRINT1 ("'\n");
5702 /* This loops over pattern commands. It exits by returning from the
5703 function if the match is complete, or it drops through if the match
5704 fails at this starting point in the input data. */
5708 DEBUG_PRINT2 ("\n%p: ", p);
5710 DEBUG_PRINT2 ("\n0x%x: ", p);
5714 { /* End of pattern means we might have succeeded. */
5715 DEBUG_PRINT1 ("end of pattern ... ");
5717 /* If we haven't matched the entire string, and we want the
5718 longest match, try backtracking. */
5719 if (d != end_match_2)
5721 /* 1 if this match ends in the same string (string1 or string2)
5722 as the best previous match. */
5723 boolean same_str_p = (FIRST_STRING_P (match_end)
5724 == MATCHING_IN_FIRST_STRING);
5725 /* 1 if this match is the best seen so far. */
5726 boolean best_match_p;
5728 /* AIX compiler got confused when this was combined
5729 with the previous declaration. */
5731 best_match_p = d > match_end;
5733 best_match_p = !MATCHING_IN_FIRST_STRING;
5735 DEBUG_PRINT1 ("backtracking.\n");
5737 if (!FAIL_STACK_EMPTY ())
5738 { /* More failure points to try. */
5740 /* If exceeds best match so far, save it. */
5741 if (!best_regs_set || best_match_p)
5743 best_regs_set = true;
5746 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5748 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5750 best_regstart[mcnt] = regstart[mcnt];
5751 best_regend[mcnt] = regend[mcnt];
5757 /* If no failure points, don't restore garbage. And if
5758 last match is real best match, don't restore second
5760 else if (best_regs_set && !best_match_p)
5763 /* Restore best match. It may happen that `dend ==
5764 end_match_1' while the restored d is in string2.
5765 For example, the pattern `x.*y.*z' against the
5766 strings `x-' and `y-z-', if the two strings are
5767 not consecutive in memory. */
5768 DEBUG_PRINT1 ("Restoring best registers.\n");
5771 dend = ((d >= string1 && d <= end1)
5772 ? end_match_1 : end_match_2);
5774 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5776 regstart[mcnt] = best_regstart[mcnt];
5777 regend[mcnt] = best_regend[mcnt];
5780 } /* d != end_match_2 */
5783 DEBUG_PRINT1 ("Accepting match.\n");
5784 /* If caller wants register contents data back, do it. */
5785 if (regs && !bufp->no_sub)
5787 /* Have the register data arrays been allocated? */
5788 if (bufp->regs_allocated == REGS_UNALLOCATED)
5789 { /* No. So allocate them with malloc. We need one
5790 extra element beyond `num_regs' for the `-1' marker
5792 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5793 regs->start = TALLOC (regs->num_regs, regoff_t);
5794 regs->end = TALLOC (regs->num_regs, regoff_t);
5795 if (regs->start == NULL || regs->end == NULL)
5800 bufp->regs_allocated = REGS_REALLOCATE;
5802 else if (bufp->regs_allocated == REGS_REALLOCATE)
5803 { /* Yes. If we need more elements than were already
5804 allocated, reallocate them. If we need fewer, just
5806 if (regs->num_regs < num_regs + 1)
5808 regs->num_regs = num_regs + 1;
5809 RETALLOC (regs->start, regs->num_regs, regoff_t);
5810 RETALLOC (regs->end, regs->num_regs, regoff_t);
5811 if (regs->start == NULL || regs->end == NULL)
5820 /* These braces fend off a "empty body in an else-statement"
5821 warning under GCC when assert expands to nothing. */
5822 assert (bufp->regs_allocated == REGS_FIXED);
5825 /* Convert the pointer data in `regstart' and `regend' to
5826 indices. Register zero has to be set differently,
5827 since we haven't kept track of any info for it. */
5828 if (regs->num_regs > 0)
5830 regs->start[0] = pos;
5832 if (MATCHING_IN_FIRST_STRING)
5833 regs->end[0] = mbs_offset1 != NULL ?
5834 mbs_offset1[d-string1] : 0;
5836 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
5837 mbs_offset2[d-string2] : 0);
5839 regs->end[0] = (MATCHING_IN_FIRST_STRING
5840 ? ((regoff_t) (d - string1))
5841 : ((regoff_t) (d - string2 + size1)));
5842 #endif /* MBS_SUPPORT */
5845 /* Go through the first `min (num_regs, regs->num_regs)'
5846 registers, since that is all we initialized. */
5847 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
5850 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
5851 regs->start[mcnt] = regs->end[mcnt] = -1;
5855 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
5857 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
5861 /* If the regs structure we return has more elements than
5862 were in the pattern, set the extra elements to -1. If
5863 we (re)allocated the registers, this is the case,
5864 because we always allocate enough to have at least one
5866 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
5867 regs->start[mcnt] = regs->end[mcnt] = -1;
5868 } /* regs && !bufp->no_sub */
5870 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5871 nfailure_points_pushed, nfailure_points_popped,
5872 nfailure_points_pushed - nfailure_points_popped);
5873 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5876 if (MATCHING_IN_FIRST_STRING)
5877 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
5879 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
5883 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
5886 #endif /* MBS_SUPPORT */
5888 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5894 /* Otherwise match next pattern command. */
5895 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5897 /* Ignore these. Used to ignore the n of succeed_n's which
5898 currently have n == 0. */
5900 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5904 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5907 /* Match the next n pattern characters exactly. The following
5908 byte in the pattern defines n, and the n bytes after that
5909 are the characters to match. */
5915 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5917 /* This is written out as an if-else so we don't waste time
5918 testing `translate' inside the loop. */
5927 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5928 != (US_CHAR_TYPE) *p++)
5933 if (*d++ != (CHAR_TYPE) *p++)
5937 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5938 != (US_CHAR_TYPE) *p++)
5940 #endif /* MBS_SUPPORT */
5949 if (*d++ != (CHAR_TYPE) *p++) goto fail;
5953 SET_REGS_MATCHED ();
5957 /* Match any character except possibly a newline or a null. */
5959 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5963 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
5964 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
5967 SET_REGS_MATCHED ();
5968 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
5976 register US_CHAR_TYPE c;
5978 unsigned int i, char_class_length, coll_symbol_length,
5979 equiv_class_length, ranges_length, chars_length, length;
5980 CHAR_TYPE *workp, *workp2, *charset_top;
5981 #define WORK_BUFFER_SIZE 128
5982 CHAR_TYPE str_buf[WORK_BUFFER_SIZE];
5986 #endif /* MBS_SUPPORT */
5987 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5989 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5991 c = TRANSLATE (*d); /* The character to match. */
5994 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
5996 charset_top = p - 1;
5997 char_class_length = *p++;
5998 coll_symbol_length = *p++;
5999 equiv_class_length = *p++;
6000 ranges_length = *p++;
6001 chars_length = *p++;
6002 /* p points charset[6], so the address of the next instruction
6003 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
6004 where l=length of char_classes, m=length of collating_symbol,
6005 n=equivalence_class, o=length of char_range,
6006 p'=length of character. */
6008 /* Update p to indicate the next instruction. */
6009 p += char_class_length + coll_symbol_length+ equiv_class_length +
6010 2*ranges_length + chars_length;
6012 /* match with char_class? */
6013 for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
6016 uintptr_t alignedp = ((uintptr_t)workp
6017 + __alignof__(wctype_t) - 1)
6018 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6019 wctype = *((wctype_t*)alignedp);
6020 workp += CHAR_CLASS_SIZE;
6021 if (iswctype((wint_t)c, wctype))
6022 goto char_set_matched;
6025 /* match with collating_symbol? */
6029 const unsigned char *extra = (const unsigned char *)
6030 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6032 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6036 wextra = (int32_t*)(extra + *workp++);
6037 for (i = 0; i < *wextra; ++i)
6038 if (TRANSLATE(d[i]) != wextra[1 + i])
6043 /* Update d, however d will be incremented at
6044 char_set_matched:, we decrement d here. */
6046 goto char_set_matched;
6050 else /* (nrules == 0) */
6052 /* If we can't look up collation data, we use wcscoll
6055 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6057 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6058 length = wcslen(workp);
6060 /* If wcscoll(the collating symbol, whole string) > 0,
6061 any substring of the string never match with the
6062 collating symbol. */
6063 if (wcscoll(workp, d) > 0)
6065 workp += length + 1;
6069 /* First, we compare the collating symbol with
6070 the first character of the string.
6071 If it don't match, we add the next character to
6072 the compare buffer in turn. */
6073 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6078 if (dend == end_match_2)
6084 /* add next character to the compare buffer. */
6085 str_buf[i] = TRANSLATE(*d);
6086 str_buf[i+1] = '\0';
6088 match = wcscoll(workp, str_buf);
6090 goto char_set_matched;
6093 /* (str_buf > workp) indicate (str_buf + X > workp),
6094 because for all X (str_buf + X > str_buf).
6095 So we don't need continue this loop. */
6098 /* Otherwise(str_buf < workp),
6099 (str_buf+next_character) may equals (workp).
6100 So we continue this loop. */
6105 workp += length + 1;
6108 /* match with equivalence_class? */
6112 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6113 /* Try to match the equivalence class against
6114 those known to the collate implementation. */
6115 const int32_t *table;
6116 const int32_t *weights;
6117 const int32_t *extra;
6118 const int32_t *indirect;
6123 /* This #include defines a local function! */
6124 # include <locale/weightwc.h>
6126 table = (const int32_t *)
6127 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6128 weights = (const wint_t *)
6129 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6130 extra = (const wint_t *)
6131 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6132 indirect = (const int32_t *)
6133 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6135 /* Write 1 collating element to str_buf, and
6139 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6141 cp = (wint_t*)str_buf;
6144 if (dend == end_match_2)
6149 str_buf[i] = TRANSLATE(*(d+i));
6150 str_buf[i+1] = '\0'; /* sentinel */
6151 idx2 = findidx ((const wint_t**)&cp);
6154 /* Update d, however d will be incremented at
6155 char_set_matched:, we decrement d here. */
6156 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6159 if (dend == end_match_2)
6168 len = weights[idx2];
6170 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6173 idx = (int32_t)*workp;
6174 /* We already checked idx != 0 in regex_compile. */
6176 if (idx2 != 0 && len == weights[idx])
6179 while (cnt < len && (weights[idx + 1 + cnt]
6180 == weights[idx2 + 1 + cnt]))
6184 goto char_set_matched;
6191 else /* (nrules == 0) */
6193 /* If we can't look up collation data, we use wcscoll
6196 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6198 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6199 length = wcslen(workp);
6201 /* If wcscoll(the collating symbol, whole string) > 0,
6202 any substring of the string never match with the
6203 collating symbol. */
6204 if (wcscoll(workp, d) > 0)
6206 workp += length + 1;
6210 /* First, we compare the equivalence class with
6211 the first character of the string.
6212 If it don't match, we add the next character to
6213 the compare buffer in turn. */
6214 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6219 if (dend == end_match_2)
6225 /* add next character to the compare buffer. */
6226 str_buf[i] = TRANSLATE(*d);
6227 str_buf[i+1] = '\0';
6229 match = wcscoll(workp, str_buf);
6232 goto char_set_matched;
6235 /* (str_buf > workp) indicate (str_buf + X > workp),
6236 because for all X (str_buf + X > str_buf).
6237 So we don't need continue this loop. */
6240 /* Otherwise(str_buf < workp),
6241 (str_buf+next_character) may equals (workp).
6242 So we continue this loop. */
6247 workp += length + 1;
6251 /* match with char_range? */
6255 uint32_t collseqval;
6256 const char *collseq = (const char *)
6257 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6259 collseqval = collseq_table_lookup (collseq, c);
6261 for (; workp < p - chars_length ;)
6263 uint32_t start_val, end_val;
6265 /* We already compute the collation sequence value
6266 of the characters (or collating symbols). */
6267 start_val = (uint32_t) *workp++; /* range_start */
6268 end_val = (uint32_t) *workp++; /* range_end */
6270 if (start_val <= collseqval && collseqval <= end_val)
6271 goto char_set_matched;
6277 /* We set range_start_char at str_buf[0], range_end_char
6278 at str_buf[4], and compared char at str_buf[2]. */
6283 for (; workp < p - chars_length ;)
6285 wchar_t *range_start_char, *range_end_char;
6287 /* match if (range_start_char <= c <= range_end_char). */
6289 /* If range_start(or end) < 0, we assume -range_start(end)
6290 is the offset of the collating symbol which is specified
6291 as the character of the range start(end). */
6295 range_start_char = charset_top - (*workp++);
6298 str_buf[0] = *workp++;
6299 range_start_char = str_buf;
6304 range_end_char = charset_top - (*workp++);
6307 str_buf[4] = *workp++;
6308 range_end_char = str_buf + 4;
6311 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6312 wcscoll(str_buf+2, range_end_char) <= 0)
6314 goto char_set_matched;
6318 /* match with char? */
6319 for (; workp < p ; workp++)
6321 goto char_set_matched;
6328 /* Cast to `unsigned' instead of `unsigned char' in case the
6329 bit list is a full 32 bytes long. */
6330 if (c < (unsigned) (*p * BYTEWIDTH)
6331 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6336 if (!not) goto fail;
6337 #undef WORK_BUFFER_SIZE
6338 #endif /* MBS_SUPPORT */
6339 SET_REGS_MATCHED ();
6345 /* The beginning of a group is represented by start_memory.
6346 The arguments are the register number in the next byte, and the
6347 number of groups inner to this one in the next. The text
6348 matched within the group is recorded (in the internal
6349 registers data structure) under the register number. */
6351 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6352 (long int) *p, (long int) p[1]);
6354 /* Find out if this group can match the empty string. */
6355 p1 = p; /* To send to group_match_null_string_p. */
6357 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6358 REG_MATCH_NULL_STRING_P (reg_info[*p])
6359 = group_match_null_string_p (&p1, pend, reg_info);
6361 /* Save the position in the string where we were the last time
6362 we were at this open-group operator in case the group is
6363 operated upon by a repetition operator, e.g., with `(a*)*b'
6364 against `ab'; then we want to ignore where we are now in
6365 the string in case this attempt to match fails. */
6366 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6367 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6369 DEBUG_PRINT2 (" old_regstart: %d\n",
6370 POINTER_TO_OFFSET (old_regstart[*p]));
6373 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6375 IS_ACTIVE (reg_info[*p]) = 1;
6376 MATCHED_SOMETHING (reg_info[*p]) = 0;
6378 /* Clear this whenever we change the register activity status. */
6379 set_regs_matched_done = 0;
6381 /* This is the new highest active register. */
6382 highest_active_reg = *p;
6384 /* If nothing was active before, this is the new lowest active
6386 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6387 lowest_active_reg = *p;
6389 /* Move past the register number and inner group count. */
6391 just_past_start_mem = p;
6396 /* The stop_memory opcode represents the end of a group. Its
6397 arguments are the same as start_memory's: the register
6398 number, and the number of inner groups. */
6400 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6401 (long int) *p, (long int) p[1]);
6403 /* We need to save the string position the last time we were at
6404 this close-group operator in case the group is operated
6405 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6406 against `aba'; then we want to ignore where we are now in
6407 the string in case this attempt to match fails. */
6408 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6409 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6411 DEBUG_PRINT2 (" old_regend: %d\n",
6412 POINTER_TO_OFFSET (old_regend[*p]));
6415 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6417 /* This register isn't active anymore. */
6418 IS_ACTIVE (reg_info[*p]) = 0;
6420 /* Clear this whenever we change the register activity status. */
6421 set_regs_matched_done = 0;
6423 /* If this was the only register active, nothing is active
6425 if (lowest_active_reg == highest_active_reg)
6427 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6428 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6431 { /* We must scan for the new highest active register, since
6432 it isn't necessarily one less than now: consider
6433 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6434 new highest active register is 1. */
6435 US_CHAR_TYPE r = *p - 1;
6436 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6439 /* If we end up at register zero, that means that we saved
6440 the registers as the result of an `on_failure_jump', not
6441 a `start_memory', and we jumped to past the innermost
6442 `stop_memory'. For example, in ((.)*) we save
6443 registers 1 and 2 as a result of the *, but when we pop
6444 back to the second ), we are at the stop_memory 1.
6445 Thus, nothing is active. */
6448 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6449 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6452 highest_active_reg = r;
6455 /* If just failed to match something this time around with a
6456 group that's operated on by a repetition operator, try to
6457 force exit from the ``loop'', and restore the register
6458 information for this group that we had before trying this
6460 if ((!MATCHED_SOMETHING (reg_info[*p])
6461 || just_past_start_mem == p - 1)
6464 boolean is_a_jump_n = false;
6468 switch ((re_opcode_t) *p1++)
6472 case pop_failure_jump:
6473 case maybe_pop_jump:
6475 case dummy_failure_jump:
6476 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6478 p1 += OFFSET_ADDRESS_SIZE;
6486 /* If the next operation is a jump backwards in the pattern
6487 to an on_failure_jump right before the start_memory
6488 corresponding to this stop_memory, exit from the loop
6489 by forcing a failure after pushing on the stack the
6490 on_failure_jump's jump in the pattern, and d. */
6491 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6492 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6493 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6495 /* If this group ever matched anything, then restore
6496 what its registers were before trying this last
6497 failed match, e.g., with `(a*)*b' against `ab' for
6498 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6499 against `aba' for regend[3].
6501 Also restore the registers for inner groups for,
6502 e.g., `((a*)(b*))*' against `aba' (register 3 would
6503 otherwise get trashed). */
6505 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6509 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6511 /* Restore this and inner groups' (if any) registers. */
6512 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6515 regstart[r] = old_regstart[r];
6517 /* xx why this test? */
6518 if (old_regend[r] >= regstart[r])
6519 regend[r] = old_regend[r];
6523 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6524 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6530 /* Move past the register number and the inner group count. */
6535 /* \<digit> has been turned into a `duplicate' command which is
6536 followed by the numeric value of <digit> as the register number. */
6539 register const CHAR_TYPE *d2, *dend2;
6540 int regno = *p++; /* Get which register to match against. */
6541 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6543 /* Can't back reference a group which we've never matched. */
6544 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6547 /* Where in input to try to start matching. */
6548 d2 = regstart[regno];
6550 /* Where to stop matching; if both the place to start and
6551 the place to stop matching are in the same string, then
6552 set to the place to stop, otherwise, for now have to use
6553 the end of the first string. */
6555 dend2 = ((FIRST_STRING_P (regstart[regno])
6556 == FIRST_STRING_P (regend[regno]))
6557 ? regend[regno] : end_match_1);
6560 /* If necessary, advance to next segment in register
6564 if (dend2 == end_match_2) break;
6565 if (dend2 == regend[regno]) break;
6567 /* End of string1 => advance to string2. */
6569 dend2 = regend[regno];
6571 /* At end of register contents => success */
6572 if (d2 == dend2) break;
6574 /* If necessary, advance to next segment in data. */
6577 /* How many characters left in this segment to match. */
6580 /* Want how many consecutive characters we can match in
6581 one shot, so, if necessary, adjust the count. */
6582 if (mcnt > dend2 - d2)
6585 /* Compare that many; failure if mismatch, else move
6588 ? bcmp_translate (d, d2, mcnt, translate)
6589 : memcmp (d, d2, mcnt*sizeof(US_CHAR_TYPE)))
6591 d += mcnt, d2 += mcnt;
6593 /* Do this because we've match some characters. */
6594 SET_REGS_MATCHED ();
6600 /* begline matches the empty string at the beginning of the string
6601 (unless `not_bol' is set in `bufp'), and, if
6602 `newline_anchor' is set, after newlines. */
6604 DEBUG_PRINT1 ("EXECUTING begline.\n");
6606 if (AT_STRINGS_BEG (d))
6608 if (!bufp->not_bol) break;
6610 else if (d[-1] == '\n' && bufp->newline_anchor)
6614 /* In all other cases, we fail. */
6618 /* endline is the dual of begline. */
6620 DEBUG_PRINT1 ("EXECUTING endline.\n");
6622 if (AT_STRINGS_END (d))
6624 if (!bufp->not_eol) break;
6627 /* We have to ``prefetch'' the next character. */
6628 else if ((d == end1 ? *string2 : *d) == '\n'
6629 && bufp->newline_anchor)
6636 /* Match at the very beginning of the data. */
6638 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6639 if (AT_STRINGS_BEG (d))
6644 /* Match at the very end of the data. */
6646 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6647 if (AT_STRINGS_END (d))
6652 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6653 pushes NULL as the value for the string on the stack. Then
6654 `pop_failure_point' will keep the current value for the
6655 string, instead of restoring it. To see why, consider
6656 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6657 then the . fails against the \n. But the next thing we want
6658 to do is match the \n against the \n; if we restored the
6659 string value, we would be back at the foo.
6661 Because this is used only in specific cases, we don't need to
6662 check all the things that `on_failure_jump' does, to make
6663 sure the right things get saved on the stack. Hence we don't
6664 share its code. The only reason to push anything on the
6665 stack at all is that otherwise we would have to change
6666 `anychar's code to do something besides goto fail in this
6667 case; that seems worse than this. */
6668 case on_failure_keep_string_jump:
6669 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6671 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6673 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6675 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6678 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6682 /* Uses of on_failure_jump:
6684 Each alternative starts with an on_failure_jump that points
6685 to the beginning of the next alternative. Each alternative
6686 except the last ends with a jump that in effect jumps past
6687 the rest of the alternatives. (They really jump to the
6688 ending jump of the following alternative, because tensioning
6689 these jumps is a hassle.)
6691 Repeats start with an on_failure_jump that points past both
6692 the repetition text and either the following jump or
6693 pop_failure_jump back to this on_failure_jump. */
6694 case on_failure_jump:
6696 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6698 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6700 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6702 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6705 /* If this on_failure_jump comes right before a group (i.e.,
6706 the original * applied to a group), save the information
6707 for that group and all inner ones, so that if we fail back
6708 to this point, the group's information will be correct.
6709 For example, in \(a*\)*\1, we need the preceding group,
6710 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6712 /* We can't use `p' to check ahead because we push
6713 a failure point to `p + mcnt' after we do this. */
6716 /* We need to skip no_op's before we look for the
6717 start_memory in case this on_failure_jump is happening as
6718 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6720 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6723 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6725 /* We have a new highest active register now. This will
6726 get reset at the start_memory we are about to get to,
6727 but we will have saved all the registers relevant to
6728 this repetition op, as described above. */
6729 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6730 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6731 lowest_active_reg = *(p1 + 1);
6734 DEBUG_PRINT1 (":\n");
6735 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6739 /* A smart repeat ends with `maybe_pop_jump'.
6740 We change it to either `pop_failure_jump' or `jump'. */
6741 case maybe_pop_jump:
6742 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6743 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6745 register US_CHAR_TYPE *p2 = p;
6747 /* Compare the beginning of the repeat with what in the
6748 pattern follows its end. If we can establish that there
6749 is nothing that they would both match, i.e., that we
6750 would have to backtrack because of (as in, e.g., `a*a')
6751 then we can change to pop_failure_jump, because we'll
6752 never have to backtrack.
6754 This is not true in the case of alternatives: in
6755 `(a|ab)*' we do need to backtrack to the `ab' alternative
6756 (e.g., if the string was `ab'). But instead of trying to
6757 detect that here, the alternative has put on a dummy
6758 failure point which is what we will end up popping. */
6760 /* Skip over open/close-group commands.
6761 If what follows this loop is a ...+ construct,
6762 look at what begins its body, since we will have to
6763 match at least one of that. */
6767 && ((re_opcode_t) *p2 == stop_memory
6768 || (re_opcode_t) *p2 == start_memory))
6770 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6771 && (re_opcode_t) *p2 == dummy_failure_jump)
6772 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6778 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
6779 to the `maybe_finalize_jump' of this case. Examine what
6782 /* If we're at the end of the pattern, we can change. */
6785 /* Consider what happens when matching ":\(.*\)"
6786 against ":/". I don't really understand this code
6788 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6791 (" End of pattern: change to `pop_failure_jump'.\n");
6794 else if ((re_opcode_t) *p2 == exactn
6796 || (re_opcode_t) *p2 == exactn_bin
6798 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
6800 register US_CHAR_TYPE c
6801 = *p2 == (US_CHAR_TYPE) endline ? '\n' : p2[2];
6803 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
6805 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
6807 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
6809 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6812 if (MB_CUR_MAX != 1)
6813 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
6815 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
6818 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
6820 (char) p1[3+OFFSET_ADDRESS_SIZE]);
6824 else if ((re_opcode_t) p1[3] == charset
6825 || (re_opcode_t) p1[3] == charset_not)
6827 int not = (re_opcode_t) p1[3] == charset_not;
6829 if (c < (unsigned) (p1[4] * BYTEWIDTH)
6830 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6833 /* `not' is equal to 1 if c would match, which means
6834 that we can't change to pop_failure_jump. */
6837 p[-3] = (unsigned char) pop_failure_jump;
6838 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6841 #endif /* not MBS_SUPPORT */
6844 else if ((re_opcode_t) *p2 == charset)
6846 /* We win if the first character of the loop is not part
6848 if ((re_opcode_t) p1[3] == exactn
6849 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
6850 && (p2[2 + p1[5] / BYTEWIDTH]
6851 & (1 << (p1[5] % BYTEWIDTH)))))
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_not)
6860 /* We win if the charset_not inside the loop
6861 lists every character listed in the charset after. */
6862 for (idx = 0; idx < (int) p2[1]; idx++)
6863 if (! (p2[2 + idx] == 0
6864 || (idx < (int) p1[4]
6865 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
6870 p[-3] = (unsigned char) pop_failure_jump;
6871 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6874 else if ((re_opcode_t) p1[3] == charset)
6877 /* We win if the charset inside the loop
6878 has no overlap with the one after the loop. */
6880 idx < (int) p2[1] && idx < (int) p1[4];
6882 if ((p2[2 + idx] & p1[5 + idx]) != 0)
6885 if (idx == p2[1] || idx == p1[4])
6887 p[-3] = (unsigned char) pop_failure_jump;
6888 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6892 #endif /* not MBS_SUPPORT */
6894 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
6895 if ((re_opcode_t) p[-1] != pop_failure_jump)
6897 p[-1] = (US_CHAR_TYPE) jump;
6898 DEBUG_PRINT1 (" Match => jump.\n");
6899 goto unconditional_jump;
6901 /* Note fall through. */
6904 /* The end of a simple repeat has a pop_failure_jump back to
6905 its matching on_failure_jump, where the latter will push a
6906 failure point. The pop_failure_jump takes off failure
6907 points put on by this pop_failure_jump's matching
6908 on_failure_jump; we got through the pattern to here from the
6909 matching on_failure_jump, so didn't fail. */
6910 case pop_failure_jump:
6912 /* We need to pass separate storage for the lowest and
6913 highest registers, even though we don't care about the
6914 actual values. Otherwise, we will restore only one
6915 register from the stack, since lowest will == highest in
6916 `pop_failure_point'. */
6917 active_reg_t dummy_low_reg, dummy_high_reg;
6918 US_CHAR_TYPE *pdummy = NULL;
6919 const CHAR_TYPE *sdummy = NULL;
6921 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
6922 POP_FAILURE_POINT (sdummy, pdummy,
6923 dummy_low_reg, dummy_high_reg,
6924 reg_dummy, reg_dummy, reg_info_dummy);
6926 /* Note fall through. */
6930 DEBUG_PRINT2 ("\n%p: ", p);
6932 DEBUG_PRINT2 ("\n0x%x: ", p);
6934 /* Note fall through. */
6936 /* Unconditionally jump (without popping any failure points). */
6938 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
6939 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
6940 p += mcnt; /* Do the jump. */
6942 DEBUG_PRINT2 ("(to %p).\n", p);
6944 DEBUG_PRINT2 ("(to 0x%x).\n", p);
6949 /* We need this opcode so we can detect where alternatives end
6950 in `group_match_null_string_p' et al. */
6952 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
6953 goto unconditional_jump;
6956 /* Normally, the on_failure_jump pushes a failure point, which
6957 then gets popped at pop_failure_jump. We will end up at
6958 pop_failure_jump, also, and with a pattern of, say, `a+', we
6959 are skipping over the on_failure_jump, so we have to push
6960 something meaningless for pop_failure_jump to pop. */
6961 case dummy_failure_jump:
6962 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
6963 /* It doesn't matter what we push for the string here. What
6964 the code at `fail' tests is the value for the pattern. */
6965 PUSH_FAILURE_POINT (NULL, NULL, -2);
6966 goto unconditional_jump;
6969 /* At the end of an alternative, we need to push a dummy failure
6970 point in case we are followed by a `pop_failure_jump', because
6971 we don't want the failure point for the alternative to be
6972 popped. For example, matching `(a|ab)*' against `aab'
6973 requires that we match the `ab' alternative. */
6974 case push_dummy_failure:
6975 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
6976 /* See comments just above at `dummy_failure_jump' about the
6978 PUSH_FAILURE_POINT (NULL, NULL, -2);
6981 /* Have to succeed matching what follows at least n times.
6982 After that, handle like `on_failure_jump'. */
6984 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6985 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
6988 /* Originally, this is how many times we HAVE to succeed. */
6992 p += OFFSET_ADDRESS_SIZE;
6993 STORE_NUMBER_AND_INCR (p, mcnt);
6995 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
6998 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
7005 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
7006 p + OFFSET_ADDRESS_SIZE);
7008 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
7009 p + OFFSET_ADDRESS_SIZE);
7013 p[1] = (US_CHAR_TYPE) no_op;
7015 p[2] = (US_CHAR_TYPE) no_op;
7016 p[3] = (US_CHAR_TYPE) no_op;
7017 #endif /* MBS_SUPPORT */
7023 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7024 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7026 /* Originally, this is how many times we CAN jump. */
7030 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7033 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7036 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7039 goto unconditional_jump;
7041 /* If don't have to jump any more, skip over the rest of command. */
7043 p += 2 * OFFSET_ADDRESS_SIZE;
7048 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7050 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7052 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7054 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7056 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7058 STORE_NUMBER (p1, mcnt);
7063 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7064 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7065 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7066 macro and introducing temporary variables works around the bug. */
7069 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7070 if (AT_WORD_BOUNDARY (d))
7075 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7076 if (AT_WORD_BOUNDARY (d))
7082 boolean prevchar, thischar;
7084 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7085 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7088 prevchar = WORDCHAR_P (d - 1);
7089 thischar = WORDCHAR_P (d);
7090 if (prevchar != thischar)
7097 boolean prevchar, thischar;
7099 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7100 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7103 prevchar = WORDCHAR_P (d - 1);
7104 thischar = WORDCHAR_P (d);
7105 if (prevchar != thischar)
7112 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7113 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7118 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7119 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7120 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
7126 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7127 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7132 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7133 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7138 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7139 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7144 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7149 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7153 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7155 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7157 SET_REGS_MATCHED ();
7161 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7163 goto matchnotsyntax;
7166 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7170 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7172 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7174 SET_REGS_MATCHED ();
7177 #else /* not emacs */
7179 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7181 if (!WORDCHAR_P (d))
7183 SET_REGS_MATCHED ();
7188 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7192 SET_REGS_MATCHED ();
7195 #endif /* not emacs */
7200 continue; /* Successfully executed one pattern command; keep going. */
7203 /* We goto here if a matching operation fails. */
7205 if (!FAIL_STACK_EMPTY ())
7206 { /* A restart point is known. Restore to that state. */
7207 DEBUG_PRINT1 ("\nFAIL:\n");
7208 POP_FAILURE_POINT (d, p,
7209 lowest_active_reg, highest_active_reg,
7210 regstart, regend, reg_info);
7212 /* If this failure point is a dummy, try the next one. */
7216 /* If we failed to the end of the pattern, don't examine *p. */
7220 boolean is_a_jump_n = false;
7222 /* If failed to a backwards jump that's part of a repetition
7223 loop, need to pop this failure point and use the next one. */
7224 switch ((re_opcode_t) *p)
7228 case maybe_pop_jump:
7229 case pop_failure_jump:
7232 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7235 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7237 && (re_opcode_t) *p1 == on_failure_jump))
7245 if (d >= string1 && d <= end1)
7249 break; /* Matching at this starting point really fails. */
7253 goto restore_best_regs;
7257 return -1; /* Failure to match. */
7260 /* Subroutine definitions for re_match_2. */
7263 /* We are passed P pointing to a register number after a start_memory.
7265 Return true if the pattern up to the corresponding stop_memory can
7266 match the empty string, and false otherwise.
7268 If we find the matching stop_memory, sets P to point to one past its number.
7269 Otherwise, sets P to an undefined byte less than or equal to END.
7271 We don't handle duplicates properly (yet). */
7274 group_match_null_string_p (p, end, reg_info)
7275 US_CHAR_TYPE **p, *end;
7276 register_info_type *reg_info;
7279 /* Point to after the args to the start_memory. */
7280 US_CHAR_TYPE *p1 = *p + 2;
7284 /* Skip over opcodes that can match nothing, and return true or
7285 false, as appropriate, when we get to one that can't, or to the
7286 matching stop_memory. */
7288 switch ((re_opcode_t) *p1)
7290 /* Could be either a loop or a series of alternatives. */
7291 case on_failure_jump:
7293 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7295 /* If the next operation is not a jump backwards in the
7300 /* Go through the on_failure_jumps of the alternatives,
7301 seeing if any of the alternatives cannot match nothing.
7302 The last alternative starts with only a jump,
7303 whereas the rest start with on_failure_jump and end
7304 with a jump, e.g., here is the pattern for `a|b|c':
7306 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7307 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7310 So, we have to first go through the first (n-1)
7311 alternatives and then deal with the last one separately. */
7314 /* Deal with the first (n-1) alternatives, which start
7315 with an on_failure_jump (see above) that jumps to right
7316 past a jump_past_alt. */
7318 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7321 /* `mcnt' holds how many bytes long the alternative
7322 is, including the ending `jump_past_alt' and
7325 if (!alt_match_null_string_p (p1, p1 + mcnt -
7326 (1 + OFFSET_ADDRESS_SIZE),
7330 /* Move to right after this alternative, including the
7334 /* Break if it's the beginning of an n-th alternative
7335 that doesn't begin with an on_failure_jump. */
7336 if ((re_opcode_t) *p1 != on_failure_jump)
7339 /* Still have to check that it's not an n-th
7340 alternative that starts with an on_failure_jump. */
7342 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7343 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7346 /* Get to the beginning of the n-th alternative. */
7347 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7352 /* Deal with the last alternative: go back and get number
7353 of the `jump_past_alt' just before it. `mcnt' contains
7354 the length of the alternative. */
7355 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7357 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
7360 p1 += mcnt; /* Get past the n-th alternative. */
7366 assert (p1[1] == **p);
7372 if (!common_op_match_null_string_p (&p1, end, reg_info))
7375 } /* while p1 < end */
7378 } /* group_match_null_string_p */
7381 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7382 It expects P to be the first byte of a single alternative and END one
7383 byte past the last. The alternative can contain groups. */
7386 alt_match_null_string_p (p, end, reg_info)
7387 US_CHAR_TYPE *p, *end;
7388 register_info_type *reg_info;
7391 US_CHAR_TYPE *p1 = p;
7395 /* Skip over opcodes that can match nothing, and break when we get
7396 to one that can't. */
7398 switch ((re_opcode_t) *p1)
7401 case on_failure_jump:
7403 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7408 if (!common_op_match_null_string_p (&p1, end, reg_info))
7411 } /* while p1 < end */
7414 } /* alt_match_null_string_p */
7417 /* Deals with the ops common to group_match_null_string_p and
7418 alt_match_null_string_p.
7420 Sets P to one after the op and its arguments, if any. */
7423 common_op_match_null_string_p (p, end, reg_info)
7424 US_CHAR_TYPE **p, *end;
7425 register_info_type *reg_info;
7430 US_CHAR_TYPE *p1 = *p;
7432 switch ((re_opcode_t) *p1++)
7452 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7453 ret = group_match_null_string_p (&p1, end, reg_info);
7455 /* Have to set this here in case we're checking a group which
7456 contains a group and a back reference to it. */
7458 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7459 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7465 /* If this is an optimized succeed_n for zero times, make the jump. */
7467 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7475 /* Get to the number of times to succeed. */
7476 p1 += OFFSET_ADDRESS_SIZE;
7477 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7481 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7482 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7490 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7495 p1 += 2 * OFFSET_ADDRESS_SIZE;
7498 /* All other opcodes mean we cannot match the empty string. */
7504 } /* common_op_match_null_string_p */
7507 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7508 bytes; nonzero otherwise. */
7511 bcmp_translate (s1, s2, len, translate)
7512 const CHAR_TYPE *s1, *s2;
7514 RE_TRANSLATE_TYPE translate;
7516 register const US_CHAR_TYPE *p1 = (const US_CHAR_TYPE *) s1;
7517 register const US_CHAR_TYPE *p2 = (const US_CHAR_TYPE *) s2;
7521 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7522 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7525 if (translate[*p1++] != translate[*p2++]) return 1;
7526 #endif /* MBS_SUPPORT */
7532 /* Entry points for GNU code. */
7534 /* re_compile_pattern is the GNU regular expression compiler: it
7535 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7536 Returns 0 if the pattern was valid, otherwise an error string.
7538 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7539 are set in BUFP on entry.
7541 We call regex_compile to do the actual compilation. */
7544 re_compile_pattern (pattern, length, bufp)
7545 const char *pattern;
7547 struct re_pattern_buffer *bufp;
7551 /* GNU code is written to assume at least RE_NREGS registers will be set
7552 (and at least one extra will be -1). */
7553 bufp->regs_allocated = REGS_UNALLOCATED;
7555 /* And GNU code determines whether or not to get register information
7556 by passing null for the REGS argument to re_match, etc., not by
7560 /* Match anchors at newline. */
7561 bufp->newline_anchor = 1;
7563 ret = regex_compile (pattern, length, re_syntax_options, bufp);
7567 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7570 weak_alias (__re_compile_pattern, re_compile_pattern)
7573 /* Entry points compatible with 4.2 BSD regex library. We don't define
7574 them unless specifically requested. */
7576 #if defined _REGEX_RE_COMP || defined _LIBC
7578 /* BSD has one and only one pattern buffer. */
7579 static struct re_pattern_buffer re_comp_buf;
7583 /* Make these definitions weak in libc, so POSIX programs can redefine
7584 these names if they don't use our functions, and still use
7585 regcomp/regexec below without link errors. */
7595 if (!re_comp_buf.buffer)
7596 return gettext ("No previous regular expression");
7600 if (!re_comp_buf.buffer)
7602 re_comp_buf.buffer = (unsigned char *) malloc (200);
7603 if (re_comp_buf.buffer == NULL)
7604 return (char *) gettext (re_error_msgid
7605 + re_error_msgid_idx[(int) REG_ESPACE]);
7606 re_comp_buf.allocated = 200;
7608 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7609 if (re_comp_buf.fastmap == NULL)
7610 return (char *) gettext (re_error_msgid
7611 + re_error_msgid_idx[(int) REG_ESPACE]);
7614 /* Since `re_exec' always passes NULL for the `regs' argument, we
7615 don't need to initialize the pattern buffer fields which affect it. */
7617 /* Match anchors at newlines. */
7618 re_comp_buf.newline_anchor = 1;
7620 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7625 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7626 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7637 const int len = strlen (s);
7639 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7642 #endif /* _REGEX_RE_COMP */
7644 /* POSIX.2 functions. Don't define these for Emacs. */
7648 /* regcomp takes a regular expression as a string and compiles it.
7650 PREG is a regex_t *. We do not expect any fields to be initialized,
7651 since POSIX says we shouldn't. Thus, we set
7653 `buffer' to the compiled pattern;
7654 `used' to the length of the compiled pattern;
7655 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7656 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7657 RE_SYNTAX_POSIX_BASIC;
7658 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7659 `fastmap' to an allocated space for the fastmap;
7660 `fastmap_accurate' to zero;
7661 `re_nsub' to the number of subexpressions in PATTERN.
7663 PATTERN is the address of the pattern string.
7665 CFLAGS is a series of bits which affect compilation.
7667 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7668 use POSIX basic syntax.
7670 If REG_NEWLINE is set, then . and [^...] don't match newline.
7671 Also, regexec will try a match beginning after every newline.
7673 If REG_ICASE is set, then we considers upper- and lowercase
7674 versions of letters to be equivalent when matching.
7676 If REG_NOSUB is set, then when PREG is passed to regexec, that
7677 routine will report only success or failure, and nothing about the
7680 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7681 the return codes and their meanings.) */
7684 regcomp (preg, pattern, cflags)
7686 const char *pattern;
7691 = (cflags & REG_EXTENDED) ?
7692 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7694 /* regex_compile will allocate the space for the compiled pattern. */
7696 preg->allocated = 0;
7699 /* Try to allocate space for the fastmap. */
7700 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7702 if (cflags & REG_ICASE)
7707 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7708 * sizeof (*(RE_TRANSLATE_TYPE)0));
7709 if (preg->translate == NULL)
7710 return (int) REG_ESPACE;
7712 /* Map uppercase characters to corresponding lowercase ones. */
7713 for (i = 0; i < CHAR_SET_SIZE; i++)
7714 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7717 preg->translate = NULL;
7719 /* If REG_NEWLINE is set, newlines are treated differently. */
7720 if (cflags & REG_NEWLINE)
7721 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7722 syntax &= ~RE_DOT_NEWLINE;
7723 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7724 /* It also changes the matching behavior. */
7725 preg->newline_anchor = 1;
7728 preg->newline_anchor = 0;
7730 preg->no_sub = !!(cflags & REG_NOSUB);
7732 /* POSIX says a null character in the pattern terminates it, so we
7733 can use strlen here in compiling the pattern. */
7734 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
7736 /* POSIX doesn't distinguish between an unmatched open-group and an
7737 unmatched close-group: both are REG_EPAREN. */
7738 if (ret == REG_ERPAREN) ret = REG_EPAREN;
7740 if (ret == REG_NOERROR && preg->fastmap)
7742 /* Compute the fastmap now, since regexec cannot modify the pattern
7744 if (re_compile_fastmap (preg) == -2)
7746 /* Some error occurred while computing the fastmap, just forget
7748 free (preg->fastmap);
7749 preg->fastmap = NULL;
7756 weak_alias (__regcomp, regcomp)
7760 /* regexec searches for a given pattern, specified by PREG, in the
7763 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7764 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
7765 least NMATCH elements, and we set them to the offsets of the
7766 corresponding matched substrings.
7768 EFLAGS specifies `execution flags' which affect matching: if
7769 REG_NOTBOL is set, then ^ does not match at the beginning of the
7770 string; if REG_NOTEOL is set, then $ does not match at the end.
7772 We return 0 if we find a match and REG_NOMATCH if not. */
7775 regexec (preg, string, nmatch, pmatch, eflags)
7776 const regex_t *preg;
7779 regmatch_t pmatch[];
7783 struct re_registers regs;
7784 regex_t private_preg;
7785 int len = strlen (string);
7786 boolean want_reg_info = !preg->no_sub && nmatch > 0;
7788 private_preg = *preg;
7790 private_preg.not_bol = !!(eflags & REG_NOTBOL);
7791 private_preg.not_eol = !!(eflags & REG_NOTEOL);
7793 /* The user has told us exactly how many registers to return
7794 information about, via `nmatch'. We have to pass that on to the
7795 matching routines. */
7796 private_preg.regs_allocated = REGS_FIXED;
7800 regs.num_regs = nmatch;
7801 regs.start = TALLOC (nmatch * 2, regoff_t);
7802 if (regs.start == NULL)
7803 return (int) REG_NOMATCH;
7804 regs.end = regs.start + nmatch;
7807 /* Perform the searching operation. */
7808 ret = re_search (&private_preg, string, len,
7809 /* start: */ 0, /* range: */ len,
7810 want_reg_info ? ®s : (struct re_registers *) 0);
7812 /* Copy the register information to the POSIX structure. */
7819 for (r = 0; r < nmatch; r++)
7821 pmatch[r].rm_so = regs.start[r];
7822 pmatch[r].rm_eo = regs.end[r];
7826 /* If we needed the temporary register info, free the space now. */
7830 /* We want zero return to mean success, unlike `re_search'. */
7831 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
7834 weak_alias (__regexec, regexec)
7838 /* Returns a message corresponding to an error code, ERRCODE, returned
7839 from either regcomp or regexec. We don't use PREG here. */
7842 regerror (errcode, preg, errbuf, errbuf_size)
7844 const regex_t *preg;
7852 || errcode >= (int) (sizeof (re_error_msgid_idx)
7853 / sizeof (re_error_msgid_idx[0])))
7854 /* Only error codes returned by the rest of the code should be passed
7855 to this routine. If we are given anything else, or if other regex
7856 code generates an invalid error code, then the program has a bug.
7857 Dump core so we can fix it. */
7860 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
7862 msg_size = strlen (msg) + 1; /* Includes the null. */
7864 if (errbuf_size != 0)
7866 if (msg_size > errbuf_size)
7868 #if defined HAVE_MEMPCPY || defined _LIBC
7869 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
7871 memcpy (errbuf, msg, errbuf_size - 1);
7872 errbuf[errbuf_size - 1] = 0;
7876 memcpy (errbuf, msg, msg_size);
7882 weak_alias (__regerror, regerror)
7886 /* Free dynamically allocated space used by PREG. */
7892 if (preg->buffer != NULL)
7893 free (preg->buffer);
7894 preg->buffer = NULL;
7896 preg->allocated = 0;
7899 if (preg->fastmap != NULL)
7900 free (preg->fastmap);
7901 preg->fastmap = NULL;
7902 preg->fastmap_accurate = 0;
7904 if (preg->translate != NULL)
7905 free (preg->translate);
7906 preg->translate = NULL;
7909 weak_alias (__regfree, regfree)
7912 #endif /* not emacs */