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.
6 This file is part of the GNU C Library.
8 The GNU C Library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Lesser General Public
10 License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version.
13 The GNU C Library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public
19 License along with the GNU C Library; if not, write to the Free
20 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
23 /* AIX requires this to be the first thing in the file. */
24 #if defined _AIX && !defined REGEX_MALLOC
36 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
37 # define PARAMS(args) args
39 # define PARAMS(args) ()
41 #endif /* Not PARAMS. */
43 #ifndef INSIDE_RECURSION
45 # if defined STDC_HEADERS && !defined emacs
48 /* We need this for `regex.h', and perhaps for the Emacs include files. */
49 # include <sys/types.h>
52 # define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
54 /* For platform which support the ISO C amendement 1 functionality we
55 support user defined character classes. */
56 # if defined _LIBC || WIDE_CHAR_SUPPORT
57 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
63 /* We have to keep the namespace clean. */
64 # define regfree(preg) __regfree (preg)
65 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
66 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
67 # define regerror(errcode, preg, errbuf, errbuf_size) \
68 __regerror(errcode, preg, errbuf, errbuf_size)
69 # define re_set_registers(bu, re, nu, st, en) \
70 __re_set_registers (bu, re, nu, st, en)
71 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
72 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
73 # define re_match(bufp, string, size, pos, regs) \
74 __re_match (bufp, string, size, pos, regs)
75 # define re_search(bufp, string, size, startpos, range, regs) \
76 __re_search (bufp, string, size, startpos, range, regs)
77 # define re_compile_pattern(pattern, length, bufp) \
78 __re_compile_pattern (pattern, length, bufp)
79 # define re_set_syntax(syntax) __re_set_syntax (syntax)
80 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
81 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
82 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
84 # define btowc __btowc
86 /* We are also using some library internals. */
87 # include <locale/localeinfo.h>
88 # include <locale/elem-hash.h>
89 # include <langinfo.h>
90 # include <locale/coll-lookup.h>
93 /* This is for other GNU distributions with internationalized messages. */
94 # if HAVE_LIBINTL_H || defined _LIBC
98 # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
101 # define gettext(msgid) (msgid)
104 # ifndef gettext_noop
105 /* This define is so xgettext can find the internationalizable
107 # define gettext_noop(String) String
110 /* The `emacs' switch turns on certain matching commands
111 that make sense only in Emacs. */
118 # else /* not emacs */
120 /* If we are not linking with Emacs proper,
121 we can't use the relocating allocator
122 even if config.h says that we can. */
125 # if defined STDC_HEADERS || defined _LIBC
132 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
133 If nothing else has been done, use the method below. */
134 # ifdef INHIBIT_STRING_HEADER
135 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
136 # if !defined bzero && !defined bcopy
137 # undef INHIBIT_STRING_HEADER
142 /* This is the normal way of making sure we have a bcopy and a bzero.
143 This is used in most programs--a few other programs avoid this
144 by defining INHIBIT_STRING_HEADER. */
145 # ifndef INHIBIT_STRING_HEADER
146 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
150 # define bzero(s, n) (memset (s, '\0', n), (s))
152 # define bzero(s, n) __bzero (s, n)
156 # include <strings.h>
158 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
161 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
166 /* Define the syntax stuff for \<, \>, etc. */
168 /* This must be nonzero for the wordchar and notwordchar pattern
169 commands in re_match_2. */
174 # ifdef SWITCH_ENUM_BUG
175 # define SWITCH_ENUM_CAST(x) ((int)(x))
177 # define SWITCH_ENUM_CAST(x) (x)
180 # endif /* not emacs */
182 # if defined _LIBC || HAVE_LIMITS_H
187 # define MB_LEN_MAX 1
190 /* Get the interface, including the syntax bits. */
193 /* isalpha etc. are used for the character classes. */
196 /* Jim Meyering writes:
198 "... Some ctype macros are valid only for character codes that
199 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
200 using /bin/cc or gcc but without giving an ansi option). So, all
201 ctype uses should be through macros like ISPRINT... If
202 STDC_HEADERS is defined, then autoconf has verified that the ctype
203 macros don't need to be guarded with references to isascii. ...
204 Defining isascii to 1 should let any compiler worth its salt
205 eliminate the && through constant folding."
206 Solaris defines some of these symbols so we must undefine them first. */
208 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
209 # define IN_CTYPE_DOMAIN(c) 1
211 # define IN_CTYPE_DOMAIN(c) isascii(c)
215 # define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
217 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
220 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
222 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
226 # define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
227 # define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
228 # define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
229 # define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
230 # define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
231 # define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
232 # define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
233 # define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
234 # define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
235 # define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
238 # define TOLOWER(c) _tolower(c)
240 # define TOLOWER(c) tolower(c)
244 # define NULL (void *)0
247 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
248 since ours (we hope) works properly with all combinations of
249 machines, compilers, `char' and `unsigned char' argument types.
250 (Per Bothner suggested the basic approach.) */
251 # undef SIGN_EXTEND_CHAR
253 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
254 # else /* not __STDC__ */
255 /* As in Harbison and Steele. */
256 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
260 /* How many characters in the character set. */
261 # define CHAR_SET_SIZE 256
265 extern char *re_syntax_table;
267 # else /* not SYNTAX_TABLE */
269 static char re_syntax_table[CHAR_SET_SIZE];
271 static void init_syntax_once PARAMS ((void));
281 bzero (re_syntax_table, sizeof re_syntax_table);
283 for (c = 0; c < CHAR_SET_SIZE; ++c)
285 re_syntax_table[c] = Sword;
287 re_syntax_table['_'] = Sword;
292 # endif /* not SYNTAX_TABLE */
294 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
298 /* Integer type for pointers. */
300 typedef unsigned long int uintptr_t;
303 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
304 use `alloca' instead of `malloc'. This is because using malloc in
305 re_search* or re_match* could cause memory leaks when C-g is used in
306 Emacs; also, malloc is slower and causes storage fragmentation. On
307 the other hand, malloc is more portable, and easier to debug.
309 Because we sometimes use alloca, some routines have to be macros,
310 not functions -- `alloca'-allocated space disappears at the end of the
311 function it is called in. */
315 # define REGEX_ALLOCATE malloc
316 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
317 # define REGEX_FREE free
319 # else /* not REGEX_MALLOC */
321 /* Emacs already defines alloca, sometimes. */
324 /* Make alloca work the best possible way. */
326 # define alloca __builtin_alloca
327 # else /* not __GNUC__ */
330 # endif /* HAVE_ALLOCA_H */
331 # endif /* not __GNUC__ */
333 # endif /* not alloca */
335 # define REGEX_ALLOCATE alloca
337 /* Assumes a `char *destination' variable. */
338 # define REGEX_REALLOCATE(source, osize, nsize) \
339 (destination = (char *) alloca (nsize), \
340 memcpy (destination, source, osize))
342 /* No need to do anything to free, after alloca. */
343 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
345 # endif /* not REGEX_MALLOC */
347 /* Define how to allocate the failure stack. */
349 # if defined REL_ALLOC && defined REGEX_MALLOC
351 # define REGEX_ALLOCATE_STACK(size) \
352 r_alloc (&failure_stack_ptr, (size))
353 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
354 r_re_alloc (&failure_stack_ptr, (nsize))
355 # define REGEX_FREE_STACK(ptr) \
356 r_alloc_free (&failure_stack_ptr)
358 # else /* not using relocating allocator */
362 # define REGEX_ALLOCATE_STACK malloc
363 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
364 # define REGEX_FREE_STACK free
366 # else /* not REGEX_MALLOC */
368 # define REGEX_ALLOCATE_STACK alloca
370 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
371 REGEX_REALLOCATE (source, osize, nsize)
372 /* No need to explicitly free anything. */
373 # define REGEX_FREE_STACK(arg)
375 # endif /* not REGEX_MALLOC */
376 # endif /* not using relocating allocator */
379 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
380 `string1' or just past its end. This works if PTR is NULL, which is
382 # define FIRST_STRING_P(ptr) \
383 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
385 /* (Re)Allocate N items of type T using malloc, or fail. */
386 # define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
387 # define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
388 # define RETALLOC_IF(addr, n, t) \
389 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
390 # define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
392 # define BYTEWIDTH 8 /* In bits. */
394 # define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
398 # define MAX(a, b) ((a) > (b) ? (a) : (b))
399 # define MIN(a, b) ((a) < (b) ? (a) : (b))
401 typedef char boolean;
405 static reg_errcode_t byte_regex_compile _RE_ARGS ((const char *pattern, size_t size,
407 struct re_pattern_buffer *bufp));
408 static reg_errcode_t wcs_regex_compile _RE_ARGS ((const char *pattern, size_t size,
410 struct re_pattern_buffer *bufp));
412 static int byte_re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
413 const char *string1, int size1,
414 const char *string2, int size2,
416 struct re_registers *regs,
418 static int wcs_re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
419 const char *cstring1, int csize1,
420 const char *cstring2, int csize2,
422 struct re_registers *regs,
424 wchar_t *string1, int size1,
425 wchar_t *string2, int size2,
426 int *mbs_offset1, int *mbs_offset2));
427 static int byte_re_search_2 PARAMS ((struct re_pattern_buffer *bufp,
428 const char *string1, int size1,
429 const char *string2, int size2,
430 int startpos, int range,
431 struct re_registers *regs, int stop));
432 static int wcs_re_search_2 PARAMS ((struct re_pattern_buffer *bufp,
433 const char *string1, int size1,
434 const char *string2, int size2,
435 int startpos, int range,
436 struct re_registers *regs, int stop));
437 static int byte_re_compile_fastmap PARAMS ((struct re_pattern_buffer *bufp));
438 static int wcs_re_compile_fastmap PARAMS ((struct re_pattern_buffer *bufp));
441 /* These are the command codes that appear in compiled regular
442 expressions. Some opcodes are followed by argument bytes. A
443 command code can specify any interpretation whatsoever for its
444 arguments. Zero bytes may appear in the compiled regular expression. */
450 /* Succeed right away--no more backtracking. */
453 /* Followed by one byte giving n, then by n literal bytes. */
457 /* Same as exactn, but contains binary data. */
461 /* Matches any (more or less) character. */
464 /* Matches any one char belonging to specified set. First
465 following byte is number of bitmap bytes. Then come bytes
466 for a bitmap saying which chars are in. Bits in each byte
467 are ordered low-bit-first. A character is in the set if its
468 bit is 1. A character too large to have a bit in the map is
469 automatically not in the set. */
470 /* ifdef MBS_SUPPORT, following element is length of character
471 classes, length of collating symbols, length of equivalence
472 classes, length of character ranges, and length of characters.
473 Next, character class element, collating symbols elements,
474 equivalence class elements, range elements, and character
476 See regex_compile function. */
479 /* Same parameters as charset, but match any character that is
480 not one of those specified. */
483 /* Start remembering the text that is matched, for storing in a
484 register. Followed by one byte with the register number, in
485 the range 0 to one less than the pattern buffer's re_nsub
486 field. Then followed by one byte with the number of groups
487 inner to this one. (This last has to be part of the
488 start_memory only because we need it in the on_failure_jump
492 /* Stop remembering the text that is matched and store it in a
493 memory register. Followed by one byte with the register
494 number, in the range 0 to one less than `re_nsub' in the
495 pattern buffer, and one byte with the number of inner groups,
496 just like `start_memory'. (We need the number of inner
497 groups here because we don't have any easy way of finding the
498 corresponding start_memory when we're at a stop_memory.) */
501 /* Match a duplicate of something remembered. Followed by one
502 byte containing the register number. */
505 /* Fail unless at beginning of line. */
508 /* Fail unless at end of line. */
511 /* Succeeds if at beginning of buffer (if emacs) or at beginning
512 of string to be matched (if not). */
515 /* Analogously, for end of buffer/string. */
518 /* Followed by two byte relative address to which to jump. */
521 /* Same as jump, but marks the end of an alternative. */
524 /* Followed by two-byte relative address of place to resume at
525 in case of failure. */
526 /* ifdef MBS_SUPPORT, the size of address is 1. */
529 /* Like on_failure_jump, but pushes a placeholder instead of the
530 current string position when executed. */
531 on_failure_keep_string_jump,
533 /* Throw away latest failure point and then jump to following
534 two-byte relative address. */
535 /* ifdef MBS_SUPPORT, the size of address is 1. */
538 /* Change to pop_failure_jump if know won't have to backtrack to
539 match; otherwise change to jump. This is used to jump
540 back to the beginning of a repeat. If what follows this jump
541 clearly won't match what the repeat does, such that we can be
542 sure that there is no use backtracking out of repetitions
543 already matched, then we change it to a pop_failure_jump.
544 Followed by two-byte address. */
545 /* ifdef MBS_SUPPORT, the size of address is 1. */
548 /* Jump to following two-byte address, and push a dummy failure
549 point. This failure point will be thrown away if an attempt
550 is made to use it for a failure. A `+' construct makes this
551 before the first repeat. Also used as an intermediary kind
552 of jump when compiling an alternative. */
553 /* ifdef MBS_SUPPORT, the size of address is 1. */
556 /* Push a dummy failure point and continue. Used at the end of
560 /* Followed by two-byte relative address and two-byte number n.
561 After matching N times, jump to the address upon failure. */
562 /* ifdef MBS_SUPPORT, the size of address is 1. */
565 /* Followed by two-byte relative address, and two-byte number n.
566 Jump to the address N times, then fail. */
567 /* ifdef MBS_SUPPORT, the size of address is 1. */
570 /* Set the following two-byte relative address to the
571 subsequent two-byte number. The address *includes* the two
573 /* ifdef MBS_SUPPORT, the size of address is 1. */
576 wordchar, /* Matches any word-constituent character. */
577 notwordchar, /* Matches any char that is not a word-constituent. */
579 wordbeg, /* Succeeds if at word beginning. */
580 wordend, /* Succeeds if at word end. */
582 wordbound, /* Succeeds if at a word boundary. */
583 notwordbound /* Succeeds if not at a word boundary. */
586 ,before_dot, /* Succeeds if before point. */
587 at_dot, /* Succeeds if at point. */
588 after_dot, /* Succeeds if after point. */
590 /* Matches any character whose syntax is specified. Followed by
591 a byte which contains a syntax code, e.g., Sword. */
594 /* Matches any character whose syntax is not that specified. */
598 #endif /* not INSIDE_RECURSION */
603 # define UCHAR_T unsigned char
604 # define COMPILED_BUFFER_VAR bufp->buffer
605 # define OFFSET_ADDRESS_SIZE 2
606 # define PREFIX(name) byte_##name
607 # define ARG_PREFIX(name) name
608 # define PUT_CHAR(c) putchar (c)
610 # define CHAR_T wchar_t
611 # define UCHAR_T wchar_t
612 # define COMPILED_BUFFER_VAR wc_buffer
613 # define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
614 # define CHAR_CLASS_SIZE ((__alignof__(wctype_t)+sizeof(wctype_t))/sizeof(CHAR_T)+1)
615 # define PREFIX(name) wcs_##name
616 # define ARG_PREFIX(name) c##name
617 /* Should we use wide stream?? */
618 # define PUT_CHAR(c) printf ("%C", c);
624 # define INSIDE_RECURSION
626 # undef INSIDE_RECURSION
629 # define INSIDE_RECURSION
631 # undef INSIDE_RECURSION
634 #ifdef INSIDE_RECURSION
635 /* Common operations on the compiled pattern. */
637 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
638 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
641 # define STORE_NUMBER(destination, number) \
643 *(destination) = (UCHAR_T)(number); \
646 # define STORE_NUMBER(destination, number) \
648 (destination)[0] = (number) & 0377; \
649 (destination)[1] = (number) >> 8; \
653 /* Same as STORE_NUMBER, except increment DESTINATION to
654 the byte after where the number is stored. Therefore, DESTINATION
655 must be an lvalue. */
656 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
658 # define STORE_NUMBER_AND_INCR(destination, number) \
660 STORE_NUMBER (destination, number); \
661 (destination) += OFFSET_ADDRESS_SIZE; \
664 /* Put into DESTINATION a number stored in two contiguous bytes starting
666 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
669 # define EXTRACT_NUMBER(destination, source) \
671 (destination) = *(source); \
674 # define EXTRACT_NUMBER(destination, source) \
676 (destination) = *(source) & 0377; \
677 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
682 static void PREFIX(extract_number) _RE_ARGS ((int *dest, UCHAR_T *source));
684 PREFIX(extract_number) (dest, source)
691 int temp = SIGN_EXTEND_CHAR (*(source + 1));
692 *dest = *source & 0377;
697 # ifndef EXTRACT_MACROS /* To debug the macros. */
698 # undef EXTRACT_NUMBER
699 # define EXTRACT_NUMBER(dest, src) PREFIX(extract_number) (&dest, src)
700 # endif /* not EXTRACT_MACROS */
704 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
705 SOURCE must be an lvalue. */
707 # define EXTRACT_NUMBER_AND_INCR(destination, source) \
709 EXTRACT_NUMBER (destination, source); \
710 (source) += OFFSET_ADDRESS_SIZE; \
714 static void PREFIX(extract_number_and_incr) _RE_ARGS ((int *destination,
717 PREFIX(extract_number_and_incr) (destination, source)
721 PREFIX(extract_number) (destination, *source);
722 *source += OFFSET_ADDRESS_SIZE;
725 # ifndef EXTRACT_MACROS
726 # undef EXTRACT_NUMBER_AND_INCR
727 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
728 PREFIX(extract_number_and_incr) (&dest, &src)
729 # endif /* not EXTRACT_MACROS */
735 /* If DEBUG is defined, Regex prints many voluminous messages about what
736 it is doing (if the variable `debug' is nonzero). If linked with the
737 main program in `iregex.c', you can enter patterns and strings
738 interactively. And if linked with the main program in `main.c' and
739 the other test files, you can run the already-written tests. */
743 # ifndef DEFINED_ONCE
745 /* We use standard I/O for debugging. */
748 /* It is useful to test things that ``must'' be true when debugging. */
753 # define DEBUG_STATEMENT(e) e
754 # define DEBUG_PRINT1(x) if (debug) printf (x)
755 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
756 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
757 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
758 # endif /* not DEFINED_ONCE */
760 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
761 if (debug) PREFIX(print_partial_compiled_pattern) (s, e)
762 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
763 if (debug) PREFIX(print_double_string) (w, s1, sz1, s2, sz2)
766 /* Print the fastmap in human-readable form. */
768 # ifndef DEFINED_ONCE
770 print_fastmap (fastmap)
773 unsigned was_a_range = 0;
776 while (i < (1 << BYTEWIDTH))
782 while (i < (1 << BYTEWIDTH) && fastmap[i])
796 # endif /* not DEFINED_ONCE */
799 /* Print a compiled pattern string in human-readable form, starting at
800 the START pointer into it and ending just before the pointer END. */
803 PREFIX(print_partial_compiled_pattern) (start, end)
818 /* Loop over pattern commands. */
822 printf ("%td:\t", p - start);
824 printf ("%ld:\t", (long int) (p - start));
827 switch ((re_opcode_t) *p++)
835 printf ("/exactn/%d", mcnt);
847 printf ("/exactn_bin/%d", mcnt);
850 printf("/%lx", (long int) *p++);
854 # endif /* MBS_SUPPORT */
858 printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
863 printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
867 printf ("/duplicate/%ld", (long int) *p++);
880 printf ("/charset [%s",
881 (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
883 length = *workp++; /* the length of char_classes */
884 for (i=0 ; i<length ; i++)
885 printf("[:%lx:]", (long int) *p++);
886 length = *workp++; /* the length of collating_symbol */
887 for (i=0 ; i<length ;)
891 PUT_CHAR((i++,*p++));
895 length = *workp++; /* the length of equivalence_class */
896 for (i=0 ; i<length ;)
900 PUT_CHAR((i++,*p++));
904 length = *workp++; /* the length of char_range */
905 for (i=0 ; i<length ; i++)
907 wchar_t range_start = *p++;
908 wchar_t range_end = *p++;
909 printf("%C-%C", range_start, range_end);
911 length = *workp++; /* the length of char */
912 for (i=0 ; i<length ; i++)
916 register int c, last = -100;
917 register int in_range = 0;
919 printf ("/charset [%s",
920 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
922 assert (p + *p < pend);
924 for (c = 0; c < 256; c++)
926 && (p[1 + (c/8)] & (1 << (c % 8))))
928 /* Are we starting a range? */
929 if (last + 1 == c && ! in_range)
934 /* Have we broken a range? */
935 else if (last + 1 != c && in_range)
965 case on_failure_jump:
966 PREFIX(extract_number_and_incr) (&mcnt, &p);
968 printf ("/on_failure_jump to %td", p + mcnt - start);
970 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
974 case on_failure_keep_string_jump:
975 PREFIX(extract_number_and_incr) (&mcnt, &p);
977 printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
979 printf ("/on_failure_keep_string_jump to %ld",
980 (long int) (p + mcnt - start));
984 case dummy_failure_jump:
985 PREFIX(extract_number_and_incr) (&mcnt, &p);
987 printf ("/dummy_failure_jump to %td", p + mcnt - start);
989 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
993 case push_dummy_failure:
994 printf ("/push_dummy_failure");
998 PREFIX(extract_number_and_incr) (&mcnt, &p);
1000 printf ("/maybe_pop_jump to %td", p + mcnt - start);
1002 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
1006 case pop_failure_jump:
1007 PREFIX(extract_number_and_incr) (&mcnt, &p);
1009 printf ("/pop_failure_jump to %td", p + mcnt - start);
1011 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
1016 PREFIX(extract_number_and_incr) (&mcnt, &p);
1018 printf ("/jump_past_alt to %td", p + mcnt - start);
1020 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
1025 PREFIX(extract_number_and_incr) (&mcnt, &p);
1027 printf ("/jump to %td", p + mcnt - start);
1029 printf ("/jump to %ld", (long int) (p + mcnt - start));
1034 PREFIX(extract_number_and_incr) (&mcnt, &p);
1036 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1038 printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
1040 printf ("/succeed_n to %ld, %d times",
1041 (long int) (p1 - start), mcnt2);
1046 PREFIX(extract_number_and_incr) (&mcnt, &p);
1048 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1049 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
1053 PREFIX(extract_number_and_incr) (&mcnt, &p);
1055 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1057 printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1059 printf ("/set_number_at location %ld to %d",
1060 (long int) (p1 - start), mcnt2);
1065 printf ("/wordbound");
1069 printf ("/notwordbound");
1073 printf ("/wordbeg");
1077 printf ("/wordend");
1082 printf ("/before_dot");
1090 printf ("/after_dot");
1094 printf ("/syntaxspec");
1096 printf ("/%d", mcnt);
1100 printf ("/notsyntaxspec");
1102 printf ("/%d", mcnt);
1107 printf ("/wordchar");
1111 printf ("/notwordchar");
1123 printf ("?%ld", (long int) *(p-1));
1130 printf ("%td:\tend of pattern.\n", p - start);
1132 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1138 PREFIX(print_compiled_pattern) (bufp)
1139 struct re_pattern_buffer *bufp;
1141 UCHAR_T *buffer = (UCHAR_T*) bufp->buffer;
1143 PREFIX(print_partial_compiled_pattern) (buffer, buffer
1144 + bufp->used / sizeof(UCHAR_T));
1145 printf ("%ld bytes used/%ld bytes allocated.\n",
1146 bufp->used, bufp->allocated);
1148 if (bufp->fastmap_accurate && bufp->fastmap)
1150 printf ("fastmap: ");
1151 print_fastmap (bufp->fastmap);
1155 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1157 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1159 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1160 printf ("can_be_null: %d\t", bufp->can_be_null);
1161 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1162 printf ("no_sub: %d\t", bufp->no_sub);
1163 printf ("not_bol: %d\t", bufp->not_bol);
1164 printf ("not_eol: %d\t", bufp->not_eol);
1165 printf ("syntax: %lx\n", bufp->syntax);
1166 /* Perhaps we should print the translate table? */
1171 PREFIX(print_double_string) (where, string1, size1, string2, size2)
1172 const CHAR_T *where;
1173 const CHAR_T *string1;
1174 const CHAR_T *string2;
1186 if (FIRST_STRING_P (where))
1188 for (this_char = where - string1; this_char < size1; this_char++)
1189 PUT_CHAR (string1[this_char]);
1195 for (this_char = where - string2; this_char < size2; this_char++)
1197 PUT_CHAR (string2[this_char]);
1200 fputs ("...", stdout);
1207 # ifndef DEFINED_ONCE
1216 # else /* not DEBUG */
1218 # ifndef DEFINED_ONCE
1222 # define DEBUG_STATEMENT(e)
1223 # define DEBUG_PRINT1(x)
1224 # define DEBUG_PRINT2(x1, x2)
1225 # define DEBUG_PRINT3(x1, x2, x3)
1226 # define DEBUG_PRINT4(x1, x2, x3, x4)
1227 # endif /* not DEFINED_ONCE */
1228 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1229 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1231 # endif /* not DEBUG */
1236 /* This convert a multibyte string to a wide character string.
1237 And write their correspondances to offset_buffer(see below)
1238 and write whether each wchar_t is binary data to is_binary.
1239 This assume invalid multibyte sequences as binary data.
1240 We assume offset_buffer and is_binary is already allocated
1243 static size_t convert_mbs_to_wcs (CHAR_T *dest, const unsigned char* src,
1244 size_t len, int *offset_buffer,
1247 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1249 const unsigned char* src;
1250 size_t len; /* the length of multibyte string. */
1252 /* It hold correspondances between src(char string) and
1253 dest(wchar_t string) for optimization.
1255 dest = {'X', 'Y', 'Z'}
1256 (each "xxx", "y" and "zz" represent one multibyte character
1257 corresponding to 'X', 'Y' and 'Z'.)
1258 offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1264 wchar_t *pdest = dest;
1265 const unsigned char *psrc = src;
1266 size_t wc_count = 0;
1270 size_t mb_remain = len;
1271 size_t mb_count = 0;
1273 /* Initialize the conversion state. */
1274 memset (&mbs, 0, sizeof (mbstate_t));
1276 offset_buffer[0] = 0;
1277 for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1280 consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1283 /* failed to convert. maybe src contains binary data.
1284 So we consume 1 byte manualy. */
1288 is_binary[wc_count] = TRUE;
1291 is_binary[wc_count] = FALSE;
1292 /* In sjis encoding, we use yen sign as escape character in
1293 place of reverse solidus. So we convert 0x5c(yen sign in
1294 sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1295 solidus in UCS2). */
1296 if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1297 *pdest = (wchar_t) *psrc;
1299 offset_buffer[wc_count + 1] = mb_count += consumed;
1302 /* Fill remain of the buffer with sentinel. */
1303 for (i = wc_count + 1 ; i <= len ; i++)
1304 offset_buffer[i] = mb_count + 1;
1311 #else /* not INSIDE_RECURSION */
1313 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1314 also be assigned to arbitrarily: each pattern buffer stores its own
1315 syntax, so it can be changed between regex compilations. */
1316 /* This has no initializer because initialized variables in Emacs
1317 become read-only after dumping. */
1318 reg_syntax_t re_syntax_options;
1321 /* Specify the precise syntax of regexps for compilation. This provides
1322 for compatibility for various utilities which historically have
1323 different, incompatible syntaxes.
1325 The argument SYNTAX is a bit mask comprised of the various bits
1326 defined in regex.h. We return the old syntax. */
1329 re_set_syntax (syntax)
1330 reg_syntax_t syntax;
1332 reg_syntax_t ret = re_syntax_options;
1334 re_syntax_options = syntax;
1336 if (syntax & RE_DEBUG)
1338 else if (debug) /* was on but now is not */
1344 weak_alias (__re_set_syntax, re_set_syntax)
1347 /* This table gives an error message for each of the error codes listed
1348 in regex.h. Obviously the order here has to be same as there.
1349 POSIX doesn't require that we do anything for REG_NOERROR,
1350 but why not be nice? */
1352 static const char re_error_msgid[] =
1354 # define REG_NOERROR_IDX 0
1355 gettext_noop ("Success") /* REG_NOERROR */
1357 # define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1358 gettext_noop ("No match") /* REG_NOMATCH */
1360 # define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1361 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1363 # define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1364 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1366 # define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1367 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1369 # define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1370 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1372 # define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1373 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1375 # define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1376 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1378 # define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1379 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1381 # define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1382 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1384 # define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1385 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1387 # define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1388 gettext_noop ("Invalid range end") /* REG_ERANGE */
1390 # define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1391 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1393 # define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1394 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1396 # define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1397 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1399 # define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1400 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1402 # define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1403 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1406 static const size_t re_error_msgid_idx[] =
1427 #endif /* INSIDE_RECURSION */
1429 #ifndef DEFINED_ONCE
1430 /* Avoiding alloca during matching, to placate r_alloc. */
1432 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1433 searching and matching functions should not call alloca. On some
1434 systems, alloca is implemented in terms of malloc, and if we're
1435 using the relocating allocator routines, then malloc could cause a
1436 relocation, which might (if the strings being searched are in the
1437 ralloc heap) shift the data out from underneath the regexp
1440 Here's another reason to avoid allocation: Emacs
1441 processes input from X in a signal handler; processing X input may
1442 call malloc; if input arrives while a matching routine is calling
1443 malloc, then we're scrod. But Emacs can't just block input while
1444 calling matching routines; then we don't notice interrupts when
1445 they come in. So, Emacs blocks input around all regexp calls
1446 except the matching calls, which it leaves unprotected, in the
1447 faith that they will not malloc. */
1449 /* Normally, this is fine. */
1450 # define MATCH_MAY_ALLOCATE
1452 /* When using GNU C, we are not REALLY using the C alloca, no matter
1453 what config.h may say. So don't take precautions for it. */
1458 /* The match routines may not allocate if (1) they would do it with malloc
1459 and (2) it's not safe for them to use malloc.
1460 Note that if REL_ALLOC is defined, matching would not use malloc for the
1461 failure stack, but we would still use it for the register vectors;
1462 so REL_ALLOC should not affect this. */
1463 # if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1464 # undef MATCH_MAY_ALLOCATE
1466 #endif /* not DEFINED_ONCE */
1468 #ifdef INSIDE_RECURSION
1469 /* Failure stack declarations and macros; both re_compile_fastmap and
1470 re_match_2 use a failure stack. These have to be macros because of
1471 REGEX_ALLOCATE_STACK. */
1474 /* Number of failure points for which to initially allocate space
1475 when matching. If this number is exceeded, we allocate more
1476 space, so it is not a hard limit. */
1477 # ifndef INIT_FAILURE_ALLOC
1478 # define INIT_FAILURE_ALLOC 5
1481 /* Roughly the maximum number of failure points on the stack. Would be
1482 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1483 This is a variable only so users of regex can assign to it; we never
1484 change it ourselves. */
1486 # ifdef INT_IS_16BIT
1488 # ifndef DEFINED_ONCE
1489 # if defined MATCH_MAY_ALLOCATE
1490 /* 4400 was enough to cause a crash on Alpha OSF/1,
1491 whose default stack limit is 2mb. */
1492 long int re_max_failures = 4000;
1494 long int re_max_failures = 2000;
1498 union PREFIX(fail_stack_elt)
1504 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1508 PREFIX(fail_stack_elt_t) *stack;
1509 unsigned long int size;
1510 unsigned long int avail; /* Offset of next open position. */
1511 } PREFIX(fail_stack_type);
1513 # else /* not INT_IS_16BIT */
1515 # ifndef DEFINED_ONCE
1516 # if defined MATCH_MAY_ALLOCATE
1517 /* 4400 was enough to cause a crash on Alpha OSF/1,
1518 whose default stack limit is 2mb. */
1519 int re_max_failures = 4000;
1521 int re_max_failures = 2000;
1525 union PREFIX(fail_stack_elt)
1531 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1535 PREFIX(fail_stack_elt_t) *stack;
1537 unsigned avail; /* Offset of next open position. */
1538 } PREFIX(fail_stack_type);
1540 # endif /* INT_IS_16BIT */
1542 # ifndef DEFINED_ONCE
1543 # define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1544 # define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1545 # define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1549 /* Define macros to initialize and free the failure stack.
1550 Do `return -2' if the alloc fails. */
1552 # ifdef MATCH_MAY_ALLOCATE
1553 # define INIT_FAIL_STACK() \
1555 fail_stack.stack = (PREFIX(fail_stack_elt_t) *) \
1556 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (PREFIX(fail_stack_elt_t))); \
1558 if (fail_stack.stack == NULL) \
1561 fail_stack.size = INIT_FAILURE_ALLOC; \
1562 fail_stack.avail = 0; \
1565 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1567 # define INIT_FAIL_STACK() \
1569 fail_stack.avail = 0; \
1572 # define RESET_FAIL_STACK()
1576 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1578 Return 1 if succeeds, and 0 if either ran out of memory
1579 allocating space for it or it was already too large.
1581 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1583 # define DOUBLE_FAIL_STACK(fail_stack) \
1584 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1586 : ((fail_stack).stack = (PREFIX(fail_stack_elt_t) *) \
1587 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1588 (fail_stack).size * sizeof (PREFIX(fail_stack_elt_t)), \
1589 ((fail_stack).size << 1) * sizeof (PREFIX(fail_stack_elt_t))),\
1591 (fail_stack).stack == NULL \
1593 : ((fail_stack).size <<= 1, \
1597 /* Push pointer POINTER on FAIL_STACK.
1598 Return 1 if was able to do so and 0 if ran out of memory allocating
1600 # define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1601 ((FAIL_STACK_FULL () \
1602 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1604 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1607 /* Push a pointer value onto the failure stack.
1608 Assumes the variable `fail_stack'. Probably should only
1609 be called from within `PUSH_FAILURE_POINT'. */
1610 # define PUSH_FAILURE_POINTER(item) \
1611 fail_stack.stack[fail_stack.avail++].pointer = (UCHAR_T *) (item)
1613 /* This pushes an integer-valued item onto the failure stack.
1614 Assumes the variable `fail_stack'. Probably should only
1615 be called from within `PUSH_FAILURE_POINT'. */
1616 # define PUSH_FAILURE_INT(item) \
1617 fail_stack.stack[fail_stack.avail++].integer = (item)
1619 /* Push a fail_stack_elt_t value onto the failure stack.
1620 Assumes the variable `fail_stack'. Probably should only
1621 be called from within `PUSH_FAILURE_POINT'. */
1622 # define PUSH_FAILURE_ELT(item) \
1623 fail_stack.stack[fail_stack.avail++] = (item)
1625 /* These three POP... operations complement the three PUSH... operations.
1626 All assume that `fail_stack' is nonempty. */
1627 # define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1628 # define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1629 # define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1631 /* Used to omit pushing failure point id's when we're not debugging. */
1633 # define DEBUG_PUSH PUSH_FAILURE_INT
1634 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1636 # define DEBUG_PUSH(item)
1637 # define DEBUG_POP(item_addr)
1641 /* Push the information about the state we will need
1642 if we ever fail back to it.
1644 Requires variables fail_stack, regstart, regend, reg_info, and
1645 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1648 Does `return FAILURE_CODE' if runs out of memory. */
1650 # define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1652 char *destination; \
1653 /* Must be int, so when we don't save any registers, the arithmetic \
1654 of 0 + -1 isn't done as unsigned. */ \
1655 /* Can't be int, since there is not a shred of a guarantee that int \
1656 is wide enough to hold a value of something to which pointer can \
1658 active_reg_t this_reg; \
1660 DEBUG_STATEMENT (failure_id++); \
1661 DEBUG_STATEMENT (nfailure_points_pushed++); \
1662 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1663 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1664 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1666 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1667 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1669 /* Ensure we have enough space allocated for what we will push. */ \
1670 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1672 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1673 return failure_code; \
1675 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1676 (fail_stack).size); \
1677 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1680 /* Push the info, starting with the registers. */ \
1681 DEBUG_PRINT1 ("\n"); \
1684 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1687 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1688 DEBUG_STATEMENT (num_regs_pushed++); \
1690 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1691 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1693 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1694 PUSH_FAILURE_POINTER (regend[this_reg]); \
1696 DEBUG_PRINT2 (" info: %p\n ", \
1697 reg_info[this_reg].word.pointer); \
1698 DEBUG_PRINT2 (" match_null=%d", \
1699 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1700 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1701 DEBUG_PRINT2 (" matched_something=%d", \
1702 MATCHED_SOMETHING (reg_info[this_reg])); \
1703 DEBUG_PRINT2 (" ever_matched=%d", \
1704 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1705 DEBUG_PRINT1 ("\n"); \
1706 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1709 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1710 PUSH_FAILURE_INT (lowest_active_reg); \
1712 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1713 PUSH_FAILURE_INT (highest_active_reg); \
1715 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1716 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1717 PUSH_FAILURE_POINTER (pattern_place); \
1719 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1720 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1722 DEBUG_PRINT1 ("'\n"); \
1723 PUSH_FAILURE_POINTER (string_place); \
1725 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1726 DEBUG_PUSH (failure_id); \
1729 # ifndef DEFINED_ONCE
1730 /* This is the number of items that are pushed and popped on the stack
1731 for each register. */
1732 # define NUM_REG_ITEMS 3
1734 /* Individual items aside from the registers. */
1736 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1738 # define NUM_NONREG_ITEMS 4
1741 /* We push at most this many items on the stack. */
1742 /* We used to use (num_regs - 1), which is the number of registers
1743 this regexp will save; but that was changed to 5
1744 to avoid stack overflow for a regexp with lots of parens. */
1745 # define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1747 /* We actually push this many items. */
1748 # define NUM_FAILURE_ITEMS \
1750 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1754 /* How many items can still be added to the stack without overflowing it. */
1755 # define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1756 # endif /* not DEFINED_ONCE */
1759 /* Pops what PUSH_FAIL_STACK pushes.
1761 We restore into the parameters, all of which should be lvalues:
1762 STR -- the saved data position.
1763 PAT -- the saved pattern position.
1764 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1765 REGSTART, REGEND -- arrays of string positions.
1766 REG_INFO -- array of information about each subexpression.
1768 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1769 `pend', `string1', `size1', `string2', and `size2'. */
1770 # define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1772 DEBUG_STATEMENT (unsigned failure_id;) \
1773 active_reg_t this_reg; \
1774 const UCHAR_T *string_temp; \
1776 assert (!FAIL_STACK_EMPTY ()); \
1778 /* Remove failure points and point to how many regs pushed. */ \
1779 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1780 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1781 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1783 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1785 DEBUG_POP (&failure_id); \
1786 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1788 /* If the saved string location is NULL, it came from an \
1789 on_failure_keep_string_jump opcode, and we want to throw away the \
1790 saved NULL, thus retaining our current position in the string. */ \
1791 string_temp = POP_FAILURE_POINTER (); \
1792 if (string_temp != NULL) \
1793 str = (const CHAR_T *) string_temp; \
1795 DEBUG_PRINT2 (" Popping string %p: `", str); \
1796 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1797 DEBUG_PRINT1 ("'\n"); \
1799 pat = (UCHAR_T *) POP_FAILURE_POINTER (); \
1800 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1801 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1803 /* Restore register info. */ \
1804 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1805 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1807 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1808 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1811 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1813 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1815 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1816 DEBUG_PRINT2 (" info: %p\n", \
1817 reg_info[this_reg].word.pointer); \
1819 regend[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER (); \
1820 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1822 regstart[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER (); \
1823 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1827 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1829 reg_info[this_reg].word.integer = 0; \
1830 regend[this_reg] = 0; \
1831 regstart[this_reg] = 0; \
1833 highest_active_reg = high_reg; \
1836 set_regs_matched_done = 0; \
1837 DEBUG_STATEMENT (nfailure_points_popped++); \
1838 } /* POP_FAILURE_POINT */
1840 /* Structure for per-register (a.k.a. per-group) information.
1841 Other register information, such as the
1842 starting and ending positions (which are addresses), and the list of
1843 inner groups (which is a bits list) are maintained in separate
1846 We are making a (strictly speaking) nonportable assumption here: that
1847 the compiler will pack our bit fields into something that fits into
1848 the type of `word', i.e., is something that fits into one item on the
1852 /* Declarations and macros for re_match_2. */
1856 PREFIX(fail_stack_elt_t) word;
1859 /* This field is one if this group can match the empty string,
1860 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1861 # define MATCH_NULL_UNSET_VALUE 3
1862 unsigned match_null_string_p : 2;
1863 unsigned is_active : 1;
1864 unsigned matched_something : 1;
1865 unsigned ever_matched_something : 1;
1867 } PREFIX(register_info_type);
1869 # ifndef DEFINED_ONCE
1870 # define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1871 # define IS_ACTIVE(R) ((R).bits.is_active)
1872 # define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1873 # define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1876 /* Call this when have matched a real character; it sets `matched' flags
1877 for the subexpressions which we are currently inside. Also records
1878 that those subexprs have matched. */
1879 # define SET_REGS_MATCHED() \
1882 if (!set_regs_matched_done) \
1885 set_regs_matched_done = 1; \
1886 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1888 MATCHED_SOMETHING (reg_info[r]) \
1889 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1895 # endif /* not DEFINED_ONCE */
1897 /* Registers are set to a sentinel when they haven't yet matched. */
1898 static CHAR_T PREFIX(reg_unset_dummy);
1899 # define REG_UNSET_VALUE (&PREFIX(reg_unset_dummy))
1900 # define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1902 /* Subroutine declarations and macros for regex_compile. */
1903 static void PREFIX(store_op1) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc, int arg));
1904 static void PREFIX(store_op2) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1905 int arg1, int arg2));
1906 static void PREFIX(insert_op1) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1907 int arg, UCHAR_T *end));
1908 static void PREFIX(insert_op2) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1909 int arg1, int arg2, UCHAR_T *end));
1910 static boolean PREFIX(at_begline_loc_p) _RE_ARGS ((const CHAR_T *pattern,
1912 reg_syntax_t syntax));
1913 static boolean PREFIX(at_endline_loc_p) _RE_ARGS ((const CHAR_T *p,
1915 reg_syntax_t syntax));
1917 static reg_errcode_t wcs_compile_range _RE_ARGS ((CHAR_T range_start,
1918 const CHAR_T **p_ptr,
1921 reg_syntax_t syntax,
1924 static void insert_space _RE_ARGS ((int num, CHAR_T *loc, CHAR_T *end));
1926 static reg_errcode_t byte_compile_range _RE_ARGS ((unsigned int range_start,
1930 reg_syntax_t syntax,
1934 /* Fetch the next character in the uncompiled pattern---translating it
1935 if necessary. Also cast from a signed character in the constant
1936 string passed to us by the user to an unsigned char that we can use
1937 as an array index (in, e.g., `translate'). */
1938 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1939 because it is impossible to allocate 4GB array for some encodings
1940 which have 4 byte character_set like UCS4. */
1943 # define PATFETCH(c) \
1944 do {if (p == pend) return REG_EEND; \
1945 c = (UCHAR_T) *p++; \
1946 if (translate && (c <= 0xff)) c = (UCHAR_T) translate[c]; \
1949 # define PATFETCH(c) \
1950 do {if (p == pend) return REG_EEND; \
1951 c = (unsigned char) *p++; \
1952 if (translate) c = (unsigned char) translate[c]; \
1957 /* Fetch the next character in the uncompiled pattern, with no
1959 # define PATFETCH_RAW(c) \
1960 do {if (p == pend) return REG_EEND; \
1961 c = (UCHAR_T) *p++; \
1964 /* Go backwards one character in the pattern. */
1965 # define PATUNFETCH p--
1968 /* If `translate' is non-null, return translate[D], else just D. We
1969 cast the subscript to translate because some data is declared as
1970 `char *', to avoid warnings when a string constant is passed. But
1971 when we use a character as a subscript we must make it unsigned. */
1972 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1973 because it is impossible to allocate 4GB array for some encodings
1974 which have 4 byte character_set like UCS4. */
1978 # define TRANSLATE(d) \
1979 ((translate && ((UCHAR_T) (d)) <= 0xff) \
1980 ? (char) translate[(unsigned char) (d)] : (d))
1982 # define TRANSLATE(d) \
1983 (translate ? (char) translate[(unsigned char) (d)] : (d))
1988 /* Macros for outputting the compiled pattern into `buffer'. */
1990 /* If the buffer isn't allocated when it comes in, use this. */
1991 # define INIT_BUF_SIZE (32 * sizeof(UCHAR_T))
1993 /* Make sure we have at least N more bytes of space in buffer. */
1995 # define GET_BUFFER_SPACE(n) \
1996 while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR \
1997 + (n)*sizeof(CHAR_T)) > bufp->allocated) \
2000 # define GET_BUFFER_SPACE(n) \
2001 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
2005 /* Make sure we have one more byte of buffer space and then add C to it. */
2006 # define BUF_PUSH(c) \
2008 GET_BUFFER_SPACE (1); \
2009 *b++ = (UCHAR_T) (c); \
2013 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
2014 # define BUF_PUSH_2(c1, c2) \
2016 GET_BUFFER_SPACE (2); \
2017 *b++ = (UCHAR_T) (c1); \
2018 *b++ = (UCHAR_T) (c2); \
2022 /* As with BUF_PUSH_2, except for three bytes. */
2023 # define BUF_PUSH_3(c1, c2, c3) \
2025 GET_BUFFER_SPACE (3); \
2026 *b++ = (UCHAR_T) (c1); \
2027 *b++ = (UCHAR_T) (c2); \
2028 *b++ = (UCHAR_T) (c3); \
2031 /* Store a jump with opcode OP at LOC to location TO. We store a
2032 relative address offset by the three bytes the jump itself occupies. */
2033 # define STORE_JUMP(op, loc, to) \
2034 PREFIX(store_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
2036 /* Likewise, for a two-argument jump. */
2037 # define STORE_JUMP2(op, loc, to, arg) \
2038 PREFIX(store_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
2040 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
2041 # define INSERT_JUMP(op, loc, to) \
2042 PREFIX(insert_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
2044 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
2045 # define INSERT_JUMP2(op, loc, to, arg) \
2046 PREFIX(insert_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
2049 /* This is not an arbitrary limit: the arguments which represent offsets
2050 into the pattern are two bytes long. So if 2^16 bytes turns out to
2051 be too small, many things would have to change. */
2052 /* Any other compiler which, like MSC, has allocation limit below 2^16
2053 bytes will have to use approach similar to what was done below for
2054 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
2055 reallocating to 0 bytes. Such thing is not going to work too well.
2056 You have been warned!! */
2057 # ifndef DEFINED_ONCE
2058 # if defined _MSC_VER && !defined WIN32
2059 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
2060 The REALLOC define eliminates a flurry of conversion warnings,
2061 but is not required. */
2062 # define MAX_BUF_SIZE 65500L
2063 # define REALLOC(p,s) realloc ((p), (size_t) (s))
2065 # define MAX_BUF_SIZE (1L << 16)
2066 # define REALLOC(p,s) realloc ((p), (s))
2069 /* Extend the buffer by twice its current size via realloc and
2070 reset the pointers that pointed into the old block to point to the
2071 correct places in the new one. If extending the buffer results in it
2072 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
2073 # if __BOUNDED_POINTERS__
2074 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2075 # define MOVE_BUFFER_POINTER(P) \
2076 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2077 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
2080 SET_HIGH_BOUND (b); \
2081 SET_HIGH_BOUND (begalt); \
2082 if (fixup_alt_jump) \
2083 SET_HIGH_BOUND (fixup_alt_jump); \
2085 SET_HIGH_BOUND (laststart); \
2086 if (pending_exact) \
2087 SET_HIGH_BOUND (pending_exact); \
2090 # define MOVE_BUFFER_POINTER(P) (P) += incr
2091 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
2093 # endif /* not DEFINED_ONCE */
2096 # define EXTEND_BUFFER() \
2098 UCHAR_T *old_buffer = COMPILED_BUFFER_VAR; \
2100 if (bufp->allocated + sizeof(UCHAR_T) > MAX_BUF_SIZE) \
2102 bufp->allocated <<= 1; \
2103 if (bufp->allocated > MAX_BUF_SIZE) \
2104 bufp->allocated = MAX_BUF_SIZE; \
2105 /* How many characters the new buffer can have? */ \
2106 wchar_count = bufp->allocated / sizeof(UCHAR_T); \
2107 if (wchar_count == 0) wchar_count = 1; \
2108 /* Truncate the buffer to CHAR_T align. */ \
2109 bufp->allocated = wchar_count * sizeof(UCHAR_T); \
2110 RETALLOC (COMPILED_BUFFER_VAR, wchar_count, UCHAR_T); \
2111 bufp->buffer = (char*)COMPILED_BUFFER_VAR; \
2112 if (COMPILED_BUFFER_VAR == NULL) \
2113 return REG_ESPACE; \
2114 /* If the buffer moved, move all the pointers into it. */ \
2115 if (old_buffer != COMPILED_BUFFER_VAR) \
2117 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2118 MOVE_BUFFER_POINTER (b); \
2119 MOVE_BUFFER_POINTER (begalt); \
2120 if (fixup_alt_jump) \
2121 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2123 MOVE_BUFFER_POINTER (laststart); \
2124 if (pending_exact) \
2125 MOVE_BUFFER_POINTER (pending_exact); \
2127 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2130 # define EXTEND_BUFFER() \
2132 UCHAR_T *old_buffer = COMPILED_BUFFER_VAR; \
2133 if (bufp->allocated == MAX_BUF_SIZE) \
2135 bufp->allocated <<= 1; \
2136 if (bufp->allocated > MAX_BUF_SIZE) \
2137 bufp->allocated = MAX_BUF_SIZE; \
2138 bufp->buffer = (UCHAR_T *) REALLOC (COMPILED_BUFFER_VAR, \
2140 if (COMPILED_BUFFER_VAR == NULL) \
2141 return REG_ESPACE; \
2142 /* If the buffer moved, move all the pointers into it. */ \
2143 if (old_buffer != COMPILED_BUFFER_VAR) \
2145 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2146 MOVE_BUFFER_POINTER (b); \
2147 MOVE_BUFFER_POINTER (begalt); \
2148 if (fixup_alt_jump) \
2149 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2151 MOVE_BUFFER_POINTER (laststart); \
2152 if (pending_exact) \
2153 MOVE_BUFFER_POINTER (pending_exact); \
2155 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2159 # ifndef DEFINED_ONCE
2160 /* Since we have one byte reserved for the register number argument to
2161 {start,stop}_memory, the maximum number of groups we can report
2162 things about is what fits in that byte. */
2163 # define MAX_REGNUM 255
2165 /* But patterns can have more than `MAX_REGNUM' registers. We just
2166 ignore the excess. */
2167 typedef unsigned regnum_t;
2170 /* Macros for the compile stack. */
2172 /* Since offsets can go either forwards or backwards, this type needs to
2173 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
2174 /* int may be not enough when sizeof(int) == 2. */
2175 typedef long pattern_offset_t;
2179 pattern_offset_t begalt_offset;
2180 pattern_offset_t fixup_alt_jump;
2181 pattern_offset_t inner_group_offset;
2182 pattern_offset_t laststart_offset;
2184 } compile_stack_elt_t;
2189 compile_stack_elt_t *stack;
2191 unsigned avail; /* Offset of next open position. */
2192 } compile_stack_type;
2195 # define INIT_COMPILE_STACK_SIZE 32
2197 # define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
2198 # define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
2200 /* The next available element. */
2201 # define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2203 # endif /* not DEFINED_ONCE */
2205 /* Set the bit for character C in a list. */
2206 # ifndef DEFINED_ONCE
2207 # define SET_LIST_BIT(c) \
2208 (b[((unsigned char) (c)) / BYTEWIDTH] \
2209 |= 1 << (((unsigned char) c) % BYTEWIDTH))
2210 # endif /* DEFINED_ONCE */
2212 /* Get the next unsigned number in the uncompiled pattern. */
2213 # define GET_UNSIGNED_NUMBER(num) \
2218 if (c < '0' || c > '9') \
2220 if (num <= RE_DUP_MAX) \
2224 num = num * 10 + c - '0'; \
2229 # ifndef DEFINED_ONCE
2230 # if defined _LIBC || WIDE_CHAR_SUPPORT
2231 /* The GNU C library provides support for user-defined character classes
2232 and the functions from ISO C amendement 1. */
2233 # ifdef CHARCLASS_NAME_MAX
2234 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2236 /* This shouldn't happen but some implementation might still have this
2237 problem. Use a reasonable default value. */
2238 # define CHAR_CLASS_MAX_LENGTH 256
2242 # define IS_CHAR_CLASS(string) __wctype (string)
2244 # define IS_CHAR_CLASS(string) wctype (string)
2247 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
2249 # define IS_CHAR_CLASS(string) \
2250 (STREQ (string, "alpha") || STREQ (string, "upper") \
2251 || STREQ (string, "lower") || STREQ (string, "digit") \
2252 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
2253 || STREQ (string, "space") || STREQ (string, "print") \
2254 || STREQ (string, "punct") || STREQ (string, "graph") \
2255 || STREQ (string, "cntrl") || STREQ (string, "blank"))
2257 # endif /* DEFINED_ONCE */
2259 # ifndef MATCH_MAY_ALLOCATE
2261 /* If we cannot allocate large objects within re_match_2_internal,
2262 we make the fail stack and register vectors global.
2263 The fail stack, we grow to the maximum size when a regexp
2265 The register vectors, we adjust in size each time we
2266 compile a regexp, according to the number of registers it needs. */
2268 static PREFIX(fail_stack_type) fail_stack;
2270 /* Size with which the following vectors are currently allocated.
2271 That is so we can make them bigger as needed,
2272 but never make them smaller. */
2273 # ifdef DEFINED_ONCE
2274 static int regs_allocated_size;
2276 static const char ** regstart, ** regend;
2277 static const char ** old_regstart, ** old_regend;
2278 static const char **best_regstart, **best_regend;
2279 static const char **reg_dummy;
2280 # endif /* DEFINED_ONCE */
2282 static PREFIX(register_info_type) *PREFIX(reg_info);
2283 static PREFIX(register_info_type) *PREFIX(reg_info_dummy);
2285 /* Make the register vectors big enough for NUM_REGS registers,
2286 but don't make them smaller. */
2289 PREFIX(regex_grow_registers) (num_regs)
2292 if (num_regs > regs_allocated_size)
2294 RETALLOC_IF (regstart, num_regs, const char *);
2295 RETALLOC_IF (regend, num_regs, const char *);
2296 RETALLOC_IF (old_regstart, num_regs, const char *);
2297 RETALLOC_IF (old_regend, num_regs, const char *);
2298 RETALLOC_IF (best_regstart, num_regs, const char *);
2299 RETALLOC_IF (best_regend, num_regs, const char *);
2300 RETALLOC_IF (PREFIX(reg_info), num_regs, PREFIX(register_info_type));
2301 RETALLOC_IF (reg_dummy, num_regs, const char *);
2302 RETALLOC_IF (PREFIX(reg_info_dummy), num_regs, PREFIX(register_info_type));
2304 regs_allocated_size = num_regs;
2308 # endif /* not MATCH_MAY_ALLOCATE */
2310 # ifndef DEFINED_ONCE
2311 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2314 # endif /* not DEFINED_ONCE */
2316 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2317 Returns one of error codes defined in `regex.h', or zero for success.
2319 Assumes the `allocated' (and perhaps `buffer') and `translate'
2320 fields are set in BUFP on entry.
2322 If it succeeds, results are put in BUFP (if it returns an error, the
2323 contents of BUFP are undefined):
2324 `buffer' is the compiled pattern;
2325 `syntax' is set to SYNTAX;
2326 `used' is set to the length of the compiled pattern;
2327 `fastmap_accurate' is zero;
2328 `re_nsub' is the number of subexpressions in PATTERN;
2329 `not_bol' and `not_eol' are zero;
2331 The `fastmap' and `newline_anchor' fields are neither
2332 examined nor set. */
2334 /* Return, freeing storage we allocated. */
2336 # define FREE_STACK_RETURN(value) \
2337 return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2339 # define FREE_STACK_RETURN(value) \
2340 return (free (compile_stack.stack), value)
2343 static reg_errcode_t
2344 PREFIX(regex_compile) (ARG_PREFIX(pattern), ARG_PREFIX(size), syntax, bufp)
2345 const char *ARG_PREFIX(pattern);
2346 size_t ARG_PREFIX(size);
2347 reg_syntax_t syntax;
2348 struct re_pattern_buffer *bufp;
2350 /* We fetch characters from PATTERN here. Even though PATTERN is
2351 `char *' (i.e., signed), we declare these variables as unsigned, so
2352 they can be reliably used as array indices. */
2353 register UCHAR_T c, c1;
2356 /* A temporary space to keep wchar_t pattern and compiled pattern. */
2357 CHAR_T *pattern, *COMPILED_BUFFER_VAR;
2359 /* offset buffer for optimization. See convert_mbs_to_wc. */
2360 int *mbs_offset = NULL;
2361 /* It hold whether each wchar_t is binary data or not. */
2362 char *is_binary = NULL;
2363 /* A flag whether exactn is handling binary data or not. */
2364 char is_exactn_bin = FALSE;
2367 /* A random temporary spot in PATTERN. */
2370 /* Points to the end of the buffer, where we should append. */
2371 register UCHAR_T *b;
2373 /* Keeps track of unclosed groups. */
2374 compile_stack_type compile_stack;
2376 /* Points to the current (ending) position in the pattern. */
2381 const CHAR_T *p = pattern;
2382 const CHAR_T *pend = pattern + size;
2385 /* How to translate the characters in the pattern. */
2386 RE_TRANSLATE_TYPE translate = bufp->translate;
2388 /* Address of the count-byte of the most recently inserted `exactn'
2389 command. This makes it possible to tell if a new exact-match
2390 character can be added to that command or if the character requires
2391 a new `exactn' command. */
2392 UCHAR_T *pending_exact = 0;
2394 /* Address of start of the most recently finished expression.
2395 This tells, e.g., postfix * where to find the start of its
2396 operand. Reset at the beginning of groups and alternatives. */
2397 UCHAR_T *laststart = 0;
2399 /* Address of beginning of regexp, or inside of last group. */
2402 /* Address of the place where a forward jump should go to the end of
2403 the containing expression. Each alternative of an `or' -- except the
2404 last -- ends with a forward jump of this sort. */
2405 UCHAR_T *fixup_alt_jump = 0;
2407 /* Counts open-groups as they are encountered. Remembered for the
2408 matching close-group on the compile stack, so the same register
2409 number is put in the stop_memory as the start_memory. */
2410 regnum_t regnum = 0;
2413 /* Initialize the wchar_t PATTERN and offset_buffer. */
2414 p = pend = pattern = TALLOC(csize + 1, CHAR_T);
2415 mbs_offset = TALLOC(csize + 1, int);
2416 is_binary = TALLOC(csize + 1, char);
2417 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2424 pattern[csize] = L'\0'; /* sentinel */
2425 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2437 DEBUG_PRINT1 ("\nCompiling pattern: ");
2440 unsigned debug_count;
2442 for (debug_count = 0; debug_count < size; debug_count++)
2443 PUT_CHAR (pattern[debug_count]);
2448 /* Initialize the compile stack. */
2449 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2450 if (compile_stack.stack == NULL)
2460 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2461 compile_stack.avail = 0;
2463 /* Initialize the pattern buffer. */
2464 bufp->syntax = syntax;
2465 bufp->fastmap_accurate = 0;
2466 bufp->not_bol = bufp->not_eol = 0;
2468 /* Set `used' to zero, so that if we return an error, the pattern
2469 printer (for debugging) will think there's no pattern. We reset it
2473 /* Always count groups, whether or not bufp->no_sub is set. */
2476 #if !defined emacs && !defined SYNTAX_TABLE
2477 /* Initialize the syntax table. */
2478 init_syntax_once ();
2481 if (bufp->allocated == 0)
2484 { /* If zero allocated, but buffer is non-null, try to realloc
2485 enough space. This loses if buffer's address is bogus, but
2486 that is the user's responsibility. */
2488 /* Free bufp->buffer and allocate an array for wchar_t pattern
2491 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(UCHAR_T),
2494 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, UCHAR_T);
2498 { /* Caller did not allocate a buffer. Do it for them. */
2499 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(UCHAR_T),
2503 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2505 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2507 bufp->allocated = INIT_BUF_SIZE;
2511 COMPILED_BUFFER_VAR = (UCHAR_T*) bufp->buffer;
2514 begalt = b = COMPILED_BUFFER_VAR;
2516 /* Loop through the uncompiled pattern until we're at the end. */
2525 if ( /* If at start of pattern, it's an operator. */
2527 /* If context independent, it's an operator. */
2528 || syntax & RE_CONTEXT_INDEP_ANCHORS
2529 /* Otherwise, depends on what's come before. */
2530 || PREFIX(at_begline_loc_p) (pattern, p, syntax))
2540 if ( /* If at end of pattern, it's an operator. */
2542 /* If context independent, it's an operator. */
2543 || syntax & RE_CONTEXT_INDEP_ANCHORS
2544 /* Otherwise, depends on what's next. */
2545 || PREFIX(at_endline_loc_p) (p, pend, syntax))
2555 if ((syntax & RE_BK_PLUS_QM)
2556 || (syntax & RE_LIMITED_OPS))
2560 /* If there is no previous pattern... */
2563 if (syntax & RE_CONTEXT_INVALID_OPS)
2564 FREE_STACK_RETURN (REG_BADRPT);
2565 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2570 /* Are we optimizing this jump? */
2571 boolean keep_string_p = false;
2573 /* 1 means zero (many) matches is allowed. */
2574 char zero_times_ok = 0, many_times_ok = 0;
2576 /* If there is a sequence of repetition chars, collapse it
2577 down to just one (the right one). We can't combine
2578 interval operators with these because of, e.g., `a{2}*',
2579 which should only match an even number of `a's. */
2583 zero_times_ok |= c != '+';
2584 many_times_ok |= c != '?';
2592 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2595 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2597 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2600 if (!(c1 == '+' || c1 == '?'))
2615 /* If we get here, we found another repeat character. */
2618 /* Star, etc. applied to an empty pattern is equivalent
2619 to an empty pattern. */
2623 /* Now we know whether or not zero matches is allowed
2624 and also whether or not two or more matches is allowed. */
2626 { /* More than one repetition is allowed, so put in at the
2627 end a backward relative jump from `b' to before the next
2628 jump we're going to put in below (which jumps from
2629 laststart to after this jump).
2631 But if we are at the `*' in the exact sequence `.*\n',
2632 insert an unconditional jump backwards to the .,
2633 instead of the beginning of the loop. This way we only
2634 push a failure point once, instead of every time
2635 through the loop. */
2636 assert (p - 1 > pattern);
2638 /* Allocate the space for the jump. */
2639 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2641 /* We know we are not at the first character of the pattern,
2642 because laststart was nonzero. And we've already
2643 incremented `p', by the way, to be the character after
2644 the `*'. Do we have to do something analogous here
2645 for null bytes, because of RE_DOT_NOT_NULL? */
2646 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2648 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2649 && !(syntax & RE_DOT_NEWLINE))
2650 { /* We have .*\n. */
2651 STORE_JUMP (jump, b, laststart);
2652 keep_string_p = true;
2655 /* Anything else. */
2656 STORE_JUMP (maybe_pop_jump, b, laststart -
2657 (1 + OFFSET_ADDRESS_SIZE));
2659 /* We've added more stuff to the buffer. */
2660 b += 1 + OFFSET_ADDRESS_SIZE;
2663 /* On failure, jump from laststart to b + 3, which will be the
2664 end of the buffer after this jump is inserted. */
2665 /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2667 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2668 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2670 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2672 b += 1 + OFFSET_ADDRESS_SIZE;
2676 /* At least one repetition is required, so insert a
2677 `dummy_failure_jump' before the initial
2678 `on_failure_jump' instruction of the loop. This
2679 effects a skip over that instruction the first time
2680 we hit that loop. */
2681 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2682 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2683 2 + 2 * OFFSET_ADDRESS_SIZE);
2684 b += 1 + OFFSET_ADDRESS_SIZE;
2698 boolean had_char_class = false;
2700 CHAR_T range_start = 0xffffffff;
2702 unsigned int range_start = 0xffffffff;
2704 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2707 /* We assume a charset(_not) structure as a wchar_t array.
2708 charset[0] = (re_opcode_t) charset(_not)
2709 charset[1] = l (= length of char_classes)
2710 charset[2] = m (= length of collating_symbols)
2711 charset[3] = n (= length of equivalence_classes)
2712 charset[4] = o (= length of char_ranges)
2713 charset[5] = p (= length of chars)
2715 charset[6] = char_class (wctype_t)
2716 charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2718 charset[l+5] = char_class (wctype_t)
2720 charset[l+6] = collating_symbol (wchar_t)
2722 charset[l+m+5] = collating_symbol (wchar_t)
2723 ifdef _LIBC we use the index if
2724 _NL_COLLATE_SYMB_EXTRAMB instead of
2727 charset[l+m+6] = equivalence_classes (wchar_t)
2729 charset[l+m+n+5] = equivalence_classes (wchar_t)
2730 ifdef _LIBC we use the index in
2731 _NL_COLLATE_WEIGHT instead of
2734 charset[l+m+n+6] = range_start
2735 charset[l+m+n+7] = range_end
2737 charset[l+m+n+2o+4] = range_start
2738 charset[l+m+n+2o+5] = range_end
2739 ifdef _LIBC we use the value looked up
2740 in _NL_COLLATE_COLLSEQ instead of
2743 charset[l+m+n+2o+6] = char
2745 charset[l+m+n+2o+p+5] = char
2749 /* We need at least 6 spaces: the opcode, the length of
2750 char_classes, the length of collating_symbols, the length of
2751 equivalence_classes, the length of char_ranges, the length of
2753 GET_BUFFER_SPACE (6);
2755 /* Save b as laststart. And We use laststart as the pointer
2756 to the first element of the charset here.
2757 In other words, laststart[i] indicates charset[i]. */
2760 /* We test `*p == '^' twice, instead of using an if
2761 statement, so we only need one BUF_PUSH. */
2762 BUF_PUSH (*p == '^' ? charset_not : charset);
2766 /* Push the length of char_classes, the length of
2767 collating_symbols, the length of equivalence_classes, the
2768 length of char_ranges and the length of chars. */
2769 BUF_PUSH_3 (0, 0, 0);
2772 /* Remember the first position in the bracket expression. */
2775 /* charset_not matches newline according to a syntax bit. */
2776 if ((re_opcode_t) b[-6] == charset_not
2777 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2780 laststart[5]++; /* Update the length of characters */
2783 /* Read in characters and ranges, setting map bits. */
2786 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2790 /* \ might escape characters inside [...] and [^...]. */
2791 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2793 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2797 laststart[5]++; /* Update the length of chars */
2802 /* Could be the end of the bracket expression. If it's
2803 not (i.e., when the bracket expression is `[]' so
2804 far), the ']' character bit gets set way below. */
2805 if (c == ']' && p != p1 + 1)
2808 /* Look ahead to see if it's a range when the last thing
2809 was a character class. */
2810 if (had_char_class && c == '-' && *p != ']')
2811 FREE_STACK_RETURN (REG_ERANGE);
2813 /* Look ahead to see if it's a range when the last thing
2814 was a character: if this is a hyphen not at the
2815 beginning or the end of a list, then it's the range
2818 && !(p - 2 >= pattern && p[-2] == '[')
2819 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2823 /* Allocate the space for range_start and range_end. */
2824 GET_BUFFER_SPACE (2);
2825 /* Update the pointer to indicate end of buffer. */
2827 ret = wcs_compile_range (range_start, &p, pend, translate,
2828 syntax, b, laststart);
2829 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2830 range_start = 0xffffffff;
2832 else if (p[0] == '-' && p[1] != ']')
2833 { /* This handles ranges made up of characters only. */
2836 /* Move past the `-'. */
2838 /* Allocate the space for range_start and range_end. */
2839 GET_BUFFER_SPACE (2);
2840 /* Update the pointer to indicate end of buffer. */
2842 ret = wcs_compile_range (c, &p, pend, translate, syntax, b,
2844 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2845 range_start = 0xffffffff;
2848 /* See if we're at the beginning of a possible character
2850 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2851 { /* Leave room for the null. */
2852 char str[CHAR_CLASS_MAX_LENGTH + 1];
2857 /* If pattern is `[[:'. */
2858 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2863 if ((c == ':' && *p == ']') || p == pend)
2865 if (c1 < CHAR_CLASS_MAX_LENGTH)
2868 /* This is in any case an invalid class name. */
2873 /* If isn't a word bracketed by `[:' and `:]':
2874 undo the ending character, the letters, and leave
2875 the leading `:' and `[' (but store them as character). */
2876 if (c == ':' && *p == ']')
2881 /* Query the character class as wctype_t. */
2882 wt = IS_CHAR_CLASS (str);
2884 FREE_STACK_RETURN (REG_ECTYPE);
2886 /* Throw away the ] at the end of the character
2890 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2892 /* Allocate the space for character class. */
2893 GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2894 /* Update the pointer to indicate end of buffer. */
2895 b += CHAR_CLASS_SIZE;
2896 /* Move data which follow character classes
2897 not to violate the data. */
2898 insert_space(CHAR_CLASS_SIZE,
2899 laststart + 6 + laststart[1],
2901 alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2902 + __alignof__(wctype_t) - 1)
2903 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2904 /* Store the character class. */
2905 *((wctype_t*)alignedp) = wt;
2906 /* Update length of char_classes */
2907 laststart[1] += CHAR_CLASS_SIZE;
2909 had_char_class = true;
2918 laststart[5] += 2; /* Update the length of characters */
2920 had_char_class = false;
2923 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2926 CHAR_T str[128]; /* Should be large enough. */
2927 CHAR_T delim = *p; /* '=' or '.' */
2930 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2935 /* If pattern is `[[=' or '[[.'. */
2936 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2941 if ((c == delim && *p == ']') || p == pend)
2943 if (c1 < sizeof (str) - 1)
2946 /* This is in any case an invalid class name. */
2951 if (c == delim && *p == ']' && str[0] != '\0')
2953 unsigned int i, offset;
2954 /* If we have no collation data we use the default
2955 collation in which each character is in a class
2956 by itself. It also means that ASCII is the
2957 character set and therefore we cannot have character
2958 with more than one byte in the multibyte
2961 /* If not defined _LIBC, we push the name and
2962 `\0' for the sake of matching performance. */
2963 int datasize = c1 + 1;
2971 FREE_STACK_RETURN (REG_ECOLLATE);
2976 const int32_t *table;
2977 const int32_t *weights;
2978 const int32_t *extra;
2979 const int32_t *indirect;
2982 /* This #include defines a local function! */
2983 # include <locale/weightwc.h>
2987 /* We push the index for equivalence class. */
2990 table = (const int32_t *)
2991 _NL_CURRENT (LC_COLLATE,
2992 _NL_COLLATE_TABLEWC);
2993 weights = (const int32_t *)
2994 _NL_CURRENT (LC_COLLATE,
2995 _NL_COLLATE_WEIGHTWC);
2996 extra = (const int32_t *)
2997 _NL_CURRENT (LC_COLLATE,
2998 _NL_COLLATE_EXTRAWC);
2999 indirect = (const int32_t *)
3000 _NL_CURRENT (LC_COLLATE,
3001 _NL_COLLATE_INDIRECTWC);
3003 idx = findidx ((const wint_t**)&cp);
3004 if (idx == 0 || cp < (wint_t*) str + c1)
3005 /* This is no valid character. */
3006 FREE_STACK_RETURN (REG_ECOLLATE);
3008 str[0] = (wchar_t)idx;
3010 else /* delim == '.' */
3012 /* We push collation sequence value
3013 for collating symbol. */
3015 const int32_t *symb_table;
3016 const unsigned char *extra;
3023 /* We have to convert the name to a single-byte
3024 string. This is possible since the names
3025 consist of ASCII characters and the internal
3026 representation is UCS4. */
3027 for (i = 0; i < c1; ++i)
3028 char_str[i] = str[i];
3031 _NL_CURRENT_WORD (LC_COLLATE,
3032 _NL_COLLATE_SYMB_HASH_SIZEMB);
3033 symb_table = (const int32_t *)
3034 _NL_CURRENT (LC_COLLATE,
3035 _NL_COLLATE_SYMB_TABLEMB);
3036 extra = (const unsigned char *)
3037 _NL_CURRENT (LC_COLLATE,
3038 _NL_COLLATE_SYMB_EXTRAMB);
3040 /* Locate the character in the hashing table. */
3041 hash = elem_hash (char_str, c1);
3044 elem = hash % table_size;
3045 second = hash % (table_size - 2);
3046 while (symb_table[2 * elem] != 0)
3048 /* First compare the hashing value. */
3049 if (symb_table[2 * elem] == hash
3050 && c1 == extra[symb_table[2 * elem + 1]]
3052 &extra[symb_table[2 * elem + 1]
3055 /* Yep, this is the entry. */
3056 idx = symb_table[2 * elem + 1];
3057 idx += 1 + extra[idx];
3065 if (symb_table[2 * elem] != 0)
3067 /* Compute the index of the byte sequence
3069 idx += 1 + extra[idx];
3070 /* Adjust for the alignment. */
3071 idx = (idx + 3) & ~4;
3073 str[0] = (wchar_t) idx + 4;
3075 else if (symb_table[2 * elem] == 0 && c1 == 1)
3077 /* No valid character. Match it as a
3078 single byte character. */
3079 had_char_class = false;
3081 /* Update the length of characters */
3083 range_start = str[0];
3085 /* Throw away the ] at the end of the
3086 collating symbol. */
3088 /* exit from the switch block. */
3092 FREE_STACK_RETURN (REG_ECOLLATE);
3097 /* Throw away the ] at the end of the equivalence
3098 class (or collating symbol). */
3101 /* Allocate the space for the equivalence class
3102 (or collating symbol) (and '\0' if needed). */
3103 GET_BUFFER_SPACE(datasize);
3104 /* Update the pointer to indicate end of buffer. */
3108 { /* equivalence class */
3109 /* Calculate the offset of char_ranges,
3110 which is next to equivalence_classes. */
3111 offset = laststart[1] + laststart[2]
3114 insert_space(datasize, laststart + offset, b - 1);
3116 /* Write the equivalence_class and \0. */
3117 for (i = 0 ; i < datasize ; i++)
3118 laststart[offset + i] = str[i];
3120 /* Update the length of equivalence_classes. */
3121 laststart[3] += datasize;
3122 had_char_class = true;
3124 else /* delim == '.' */
3125 { /* collating symbol */
3126 /* Calculate the offset of the equivalence_classes,
3127 which is next to collating_symbols. */
3128 offset = laststart[1] + laststart[2] + 6;
3129 /* Insert space and write the collationg_symbol
3131 insert_space(datasize, laststart + offset, b-1);
3132 for (i = 0 ; i < datasize ; i++)
3133 laststart[offset + i] = str[i];
3135 /* In re_match_2_internal if range_start < -1, we
3136 assume -range_start is the offset of the
3137 collating symbol which is specified as
3138 the character of the range start. So we assign
3139 -(laststart[1] + laststart[2] + 6) to
3141 range_start = -(laststart[1] + laststart[2] + 6);
3142 /* Update the length of collating_symbol. */
3143 laststart[2] += datasize;
3144 had_char_class = false;
3154 laststart[5] += 2; /* Update the length of characters */
3155 range_start = delim;
3156 had_char_class = false;
3161 had_char_class = false;
3163 laststart[5]++; /* Update the length of characters */
3169 /* Ensure that we have enough space to push a charset: the
3170 opcode, the length count, and the bitset; 34 bytes in all. */
3171 GET_BUFFER_SPACE (34);
3175 /* We test `*p == '^' twice, instead of using an if
3176 statement, so we only need one BUF_PUSH. */
3177 BUF_PUSH (*p == '^' ? charset_not : charset);
3181 /* Remember the first position in the bracket expression. */
3184 /* Push the number of bytes in the bitmap. */
3185 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3187 /* Clear the whole map. */
3188 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3190 /* charset_not matches newline according to a syntax bit. */
3191 if ((re_opcode_t) b[-2] == charset_not
3192 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3193 SET_LIST_BIT ('\n');
3195 /* Read in characters and ranges, setting map bits. */
3198 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3202 /* \ might escape characters inside [...] and [^...]. */
3203 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3205 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3213 /* Could be the end of the bracket expression. If it's
3214 not (i.e., when the bracket expression is `[]' so
3215 far), the ']' character bit gets set way below. */
3216 if (c == ']' && p != p1 + 1)
3219 /* Look ahead to see if it's a range when the last thing
3220 was a character class. */
3221 if (had_char_class && c == '-' && *p != ']')
3222 FREE_STACK_RETURN (REG_ERANGE);
3224 /* Look ahead to see if it's a range when the last thing
3225 was a character: if this is a hyphen not at the
3226 beginning or the end of a list, then it's the range
3229 && !(p - 2 >= pattern && p[-2] == '[')
3230 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3234 = byte_compile_range (range_start, &p, pend, translate,
3236 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3237 range_start = 0xffffffff;
3240 else if (p[0] == '-' && p[1] != ']')
3241 { /* This handles ranges made up of characters only. */
3244 /* Move past the `-'. */
3247 ret = byte_compile_range (c, &p, pend, translate, syntax, b);
3248 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3249 range_start = 0xffffffff;
3252 /* See if we're at the beginning of a possible character
3255 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3256 { /* Leave room for the null. */
3257 char str[CHAR_CLASS_MAX_LENGTH + 1];
3262 /* If pattern is `[[:'. */
3263 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3268 if ((c == ':' && *p == ']') || p == pend)
3270 if (c1 < CHAR_CLASS_MAX_LENGTH)
3273 /* This is in any case an invalid class name. */
3278 /* If isn't a word bracketed by `[:' and `:]':
3279 undo the ending character, the letters, and leave
3280 the leading `:' and `[' (but set bits for them). */
3281 if (c == ':' && *p == ']')
3283 # if defined _LIBC || WIDE_CHAR_SUPPORT
3284 boolean is_lower = STREQ (str, "lower");
3285 boolean is_upper = STREQ (str, "upper");
3289 wt = IS_CHAR_CLASS (str);
3291 FREE_STACK_RETURN (REG_ECTYPE);
3293 /* Throw away the ] at the end of the character
3297 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3299 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3302 if (__iswctype (__btowc (ch), wt))
3305 if (iswctype (btowc (ch), wt))
3309 if (translate && (is_upper || is_lower)
3310 && (ISUPPER (ch) || ISLOWER (ch)))
3314 had_char_class = true;
3317 boolean is_alnum = STREQ (str, "alnum");
3318 boolean is_alpha = STREQ (str, "alpha");
3319 boolean is_blank = STREQ (str, "blank");
3320 boolean is_cntrl = STREQ (str, "cntrl");
3321 boolean is_digit = STREQ (str, "digit");
3322 boolean is_graph = STREQ (str, "graph");
3323 boolean is_lower = STREQ (str, "lower");
3324 boolean is_print = STREQ (str, "print");
3325 boolean is_punct = STREQ (str, "punct");
3326 boolean is_space = STREQ (str, "space");
3327 boolean is_upper = STREQ (str, "upper");
3328 boolean is_xdigit = STREQ (str, "xdigit");
3330 if (!IS_CHAR_CLASS (str))
3331 FREE_STACK_RETURN (REG_ECTYPE);
3333 /* Throw away the ] at the end of the character
3337 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3339 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3341 /* This was split into 3 if's to
3342 avoid an arbitrary limit in some compiler. */
3343 if ( (is_alnum && ISALNUM (ch))
3344 || (is_alpha && ISALPHA (ch))
3345 || (is_blank && ISBLANK (ch))
3346 || (is_cntrl && ISCNTRL (ch)))
3348 if ( (is_digit && ISDIGIT (ch))
3349 || (is_graph && ISGRAPH (ch))
3350 || (is_lower && ISLOWER (ch))
3351 || (is_print && ISPRINT (ch)))
3353 if ( (is_punct && ISPUNCT (ch))
3354 || (is_space && ISSPACE (ch))
3355 || (is_upper && ISUPPER (ch))
3356 || (is_xdigit && ISXDIGIT (ch)))
3358 if ( translate && (is_upper || is_lower)
3359 && (ISUPPER (ch) || ISLOWER (ch)))
3362 had_char_class = true;
3363 # endif /* libc || wctype.h */
3373 had_char_class = false;
3376 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3378 unsigned char str[MB_LEN_MAX + 1];
3381 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3387 /* If pattern is `[[='. */
3388 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3393 if ((c == '=' && *p == ']') || p == pend)
3395 if (c1 < MB_LEN_MAX)
3398 /* This is in any case an invalid class name. */
3403 if (c == '=' && *p == ']' && str[0] != '\0')
3405 /* If we have no collation data we use the default
3406 collation in which each character is in a class
3407 by itself. It also means that ASCII is the
3408 character set and therefore we cannot have character
3409 with more than one byte in the multibyte
3416 FREE_STACK_RETURN (REG_ECOLLATE);
3418 /* Throw away the ] at the end of the equivalence
3422 /* Set the bit for the character. */
3423 SET_LIST_BIT (str[0]);
3428 /* Try to match the byte sequence in `str' against
3429 those known to the collate implementation.
3430 First find out whether the bytes in `str' are
3431 actually from exactly one character. */
3432 const int32_t *table;
3433 const unsigned char *weights;
3434 const unsigned char *extra;
3435 const int32_t *indirect;
3437 const unsigned char *cp = str;
3440 /* This #include defines a local function! */
3441 # include <locale/weight.h>
3443 table = (const int32_t *)
3444 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3445 weights = (const unsigned char *)
3446 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3447 extra = (const unsigned char *)
3448 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3449 indirect = (const int32_t *)
3450 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3452 idx = findidx (&cp);
3453 if (idx == 0 || cp < str + c1)
3454 /* This is no valid character. */
3455 FREE_STACK_RETURN (REG_ECOLLATE);
3457 /* Throw away the ] at the end of the equivalence
3461 /* Now we have to go throught the whole table
3462 and find all characters which have the same
3465 XXX Note that this is not entirely correct.
3466 we would have to match multibyte sequences
3467 but this is not possible with the current
3469 for (ch = 1; ch < 256; ++ch)
3470 /* XXX This test would have to be changed if we
3471 would allow matching multibyte sequences. */
3474 int32_t idx2 = table[ch];
3475 size_t len = weights[idx2];
3477 /* Test whether the lenghts match. */
3478 if (weights[idx] == len)
3480 /* They do. New compare the bytes of
3485 && (weights[idx + 1 + cnt]
3486 == weights[idx2 + 1 + cnt]))
3490 /* They match. Mark the character as
3497 had_char_class = true;
3507 had_char_class = false;
3510 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3512 unsigned char str[128]; /* Should be large enough. */
3515 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3521 /* If pattern is `[[.'. */
3522 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3527 if ((c == '.' && *p == ']') || p == pend)
3529 if (c1 < sizeof (str))
3532 /* This is in any case an invalid class name. */
3537 if (c == '.' && *p == ']' && str[0] != '\0')
3539 /* If we have no collation data we use the default
3540 collation in which each character is the name
3541 for its own class which contains only the one
3542 character. It also means that ASCII is the
3543 character set and therefore we cannot have character
3544 with more than one byte in the multibyte
3551 FREE_STACK_RETURN (REG_ECOLLATE);
3553 /* Throw away the ] at the end of the equivalence
3557 /* Set the bit for the character. */
3558 SET_LIST_BIT (str[0]);
3559 range_start = ((const unsigned char *) str)[0];
3564 /* Try to match the byte sequence in `str' against
3565 those known to the collate implementation.
3566 First find out whether the bytes in `str' are
3567 actually from exactly one character. */
3569 const int32_t *symb_table;
3570 const unsigned char *extra;
3577 _NL_CURRENT_WORD (LC_COLLATE,
3578 _NL_COLLATE_SYMB_HASH_SIZEMB);
3579 symb_table = (const int32_t *)
3580 _NL_CURRENT (LC_COLLATE,
3581 _NL_COLLATE_SYMB_TABLEMB);
3582 extra = (const unsigned char *)
3583 _NL_CURRENT (LC_COLLATE,
3584 _NL_COLLATE_SYMB_EXTRAMB);
3586 /* Locate the character in the hashing table. */
3587 hash = elem_hash (str, c1);
3590 elem = hash % table_size;
3591 second = hash % (table_size - 2);
3592 while (symb_table[2 * elem] != 0)
3594 /* First compare the hashing value. */
3595 if (symb_table[2 * elem] == hash
3596 && c1 == extra[symb_table[2 * elem + 1]]
3598 &extra[symb_table[2 * elem + 1]
3602 /* Yep, this is the entry. */
3603 idx = symb_table[2 * elem + 1];
3604 idx += 1 + extra[idx];
3612 if (symb_table[2 * elem] == 0)
3613 /* This is no valid character. */
3614 FREE_STACK_RETURN (REG_ECOLLATE);
3616 /* Throw away the ] at the end of the equivalence
3620 /* Now add the multibyte character(s) we found
3623 XXX Note that this is not entirely correct.
3624 we would have to match multibyte sequences
3625 but this is not possible with the current
3626 implementation. Also, we have to match
3627 collating symbols, which expand to more than
3628 one file, as a whole and not allow the
3629 individual bytes. */
3632 range_start = extra[idx];
3635 SET_LIST_BIT (extra[idx]);
3640 had_char_class = false;
3650 had_char_class = false;
3655 had_char_class = false;
3661 /* Discard any (non)matching list bytes that are all 0 at the
3662 end of the map. Decrease the map-length byte too. */
3663 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3672 if (syntax & RE_NO_BK_PARENS)
3679 if (syntax & RE_NO_BK_PARENS)
3686 if (syntax & RE_NEWLINE_ALT)
3693 if (syntax & RE_NO_BK_VBAR)
3700 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3701 goto handle_interval;
3707 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3709 /* Do not translate the character after the \, so that we can
3710 distinguish, e.g., \B from \b, even if we normally would
3711 translate, e.g., B to b. */
3717 if (syntax & RE_NO_BK_PARENS)
3718 goto normal_backslash;
3724 if (COMPILE_STACK_FULL)
3726 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3727 compile_stack_elt_t);
3728 if (compile_stack.stack == NULL) return REG_ESPACE;
3730 compile_stack.size <<= 1;
3733 /* These are the values to restore when we hit end of this
3734 group. They are all relative offsets, so that if the
3735 whole pattern moves because of realloc, they will still
3737 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3738 COMPILE_STACK_TOP.fixup_alt_jump
3739 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3740 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3741 COMPILE_STACK_TOP.regnum = regnum;
3743 /* We will eventually replace the 0 with the number of
3744 groups inner to this one. But do not push a
3745 start_memory for groups beyond the last one we can
3746 represent in the compiled pattern. */
3747 if (regnum <= MAX_REGNUM)
3749 COMPILE_STACK_TOP.inner_group_offset = b
3750 - COMPILED_BUFFER_VAR + 2;
3751 BUF_PUSH_3 (start_memory, regnum, 0);
3754 compile_stack.avail++;
3759 /* If we've reached MAX_REGNUM groups, then this open
3760 won't actually generate any code, so we'll have to
3761 clear pending_exact explicitly. */
3767 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3769 if (COMPILE_STACK_EMPTY)
3771 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3772 goto normal_backslash;
3774 FREE_STACK_RETURN (REG_ERPAREN);
3779 { /* Push a dummy failure point at the end of the
3780 alternative for a possible future
3781 `pop_failure_jump' to pop. See comments at
3782 `push_dummy_failure' in `re_match_2'. */
3783 BUF_PUSH (push_dummy_failure);
3785 /* We allocated space for this jump when we assigned
3786 to `fixup_alt_jump', in the `handle_alt' case below. */
3787 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3790 /* See similar code for backslashed left paren above. */
3791 if (COMPILE_STACK_EMPTY)
3793 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3796 FREE_STACK_RETURN (REG_ERPAREN);
3799 /* Since we just checked for an empty stack above, this
3800 ``can't happen''. */
3801 assert (compile_stack.avail != 0);
3803 /* We don't just want to restore into `regnum', because
3804 later groups should continue to be numbered higher,
3805 as in `(ab)c(de)' -- the second group is #2. */
3806 regnum_t this_group_regnum;
3808 compile_stack.avail--;
3809 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3811 = COMPILE_STACK_TOP.fixup_alt_jump
3812 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3814 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3815 this_group_regnum = COMPILE_STACK_TOP.regnum;
3816 /* If we've reached MAX_REGNUM groups, then this open
3817 won't actually generate any code, so we'll have to
3818 clear pending_exact explicitly. */
3821 /* We're at the end of the group, so now we know how many
3822 groups were inside this one. */
3823 if (this_group_regnum <= MAX_REGNUM)
3825 UCHAR_T *inner_group_loc
3826 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3828 *inner_group_loc = regnum - this_group_regnum;
3829 BUF_PUSH_3 (stop_memory, this_group_regnum,
3830 regnum - this_group_regnum);
3836 case '|': /* `\|'. */
3837 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3838 goto normal_backslash;
3840 if (syntax & RE_LIMITED_OPS)
3843 /* Insert before the previous alternative a jump which
3844 jumps to this alternative if the former fails. */
3845 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3846 INSERT_JUMP (on_failure_jump, begalt,
3847 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3849 b += 1 + OFFSET_ADDRESS_SIZE;
3851 /* The alternative before this one has a jump after it
3852 which gets executed if it gets matched. Adjust that
3853 jump so it will jump to this alternative's analogous
3854 jump (put in below, which in turn will jump to the next
3855 (if any) alternative's such jump, etc.). The last such
3856 jump jumps to the correct final destination. A picture:
3862 If we are at `b', then fixup_alt_jump right now points to a
3863 three-byte space after `a'. We'll put in the jump, set
3864 fixup_alt_jump to right after `b', and leave behind three
3865 bytes which we'll fill in when we get to after `c'. */
3868 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3870 /* Mark and leave space for a jump after this alternative,
3871 to be filled in later either by next alternative or
3872 when know we're at the end of a series of alternatives. */
3874 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3875 b += 1 + OFFSET_ADDRESS_SIZE;
3883 /* If \{ is a literal. */
3884 if (!(syntax & RE_INTERVALS)
3885 /* If we're at `\{' and it's not the open-interval
3887 || (syntax & RE_NO_BK_BRACES))
3888 goto normal_backslash;
3892 /* If got here, then the syntax allows intervals. */
3894 /* At least (most) this many matches must be made. */
3895 int lower_bound = -1, upper_bound = -1;
3897 /* Place in the uncompiled pattern (i.e., just after
3898 the '{') to go back to if the interval is invalid. */
3899 const CHAR_T *beg_interval = p;
3902 goto invalid_interval;
3904 GET_UNSIGNED_NUMBER (lower_bound);
3908 GET_UNSIGNED_NUMBER (upper_bound);
3909 if (upper_bound < 0)
3910 upper_bound = RE_DUP_MAX;
3913 /* Interval such as `{1}' => match exactly once. */
3914 upper_bound = lower_bound;
3916 if (! (0 <= lower_bound && lower_bound <= upper_bound))
3917 goto invalid_interval;
3919 if (!(syntax & RE_NO_BK_BRACES))
3921 if (c != '\\' || p == pend)
3922 goto invalid_interval;
3927 goto invalid_interval;
3929 /* If it's invalid to have no preceding re. */
3932 if (syntax & RE_CONTEXT_INVALID_OPS
3933 && !(syntax & RE_INVALID_INTERVAL_ORD))
3934 FREE_STACK_RETURN (REG_BADRPT);
3935 else if (syntax & RE_CONTEXT_INDEP_OPS)
3938 goto unfetch_interval;
3941 /* We just parsed a valid interval. */
3943 if (RE_DUP_MAX < upper_bound)
3944 FREE_STACK_RETURN (REG_BADBR);
3946 /* If the upper bound is zero, don't want to succeed at
3947 all; jump from `laststart' to `b + 3', which will be
3948 the end of the buffer after we insert the jump. */
3949 /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE'
3950 instead of 'b + 3'. */
3951 if (upper_bound == 0)
3953 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3954 INSERT_JUMP (jump, laststart, b + 1
3955 + OFFSET_ADDRESS_SIZE);
3956 b += 1 + OFFSET_ADDRESS_SIZE;
3959 /* Otherwise, we have a nontrivial interval. When
3960 we're all done, the pattern will look like:
3961 set_number_at <jump count> <upper bound>
3962 set_number_at <succeed_n count> <lower bound>
3963 succeed_n <after jump addr> <succeed_n count>
3965 jump_n <succeed_n addr> <jump count>
3966 (The upper bound and `jump_n' are omitted if
3967 `upper_bound' is 1, though.) */
3969 { /* If the upper bound is > 1, we need to insert
3970 more at the end of the loop. */
3971 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3972 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3974 GET_BUFFER_SPACE (nbytes);
3976 /* Initialize lower bound of the `succeed_n', even
3977 though it will be set during matching by its
3978 attendant `set_number_at' (inserted next),
3979 because `re_compile_fastmap' needs to know.
3980 Jump to the `jump_n' we might insert below. */
3981 INSERT_JUMP2 (succeed_n, laststart,
3982 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3983 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3985 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3987 /* Code to initialize the lower bound. Insert
3988 before the `succeed_n'. The `5' is the last two
3989 bytes of this `set_number_at', plus 3 bytes of
3990 the following `succeed_n'. */
3991 /* ifdef WCHAR, The '1+2*OFFSET_ADDRESS_SIZE'
3992 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3993 of the following `succeed_n'. */
3994 PREFIX(insert_op2) (set_number_at, laststart, 1
3995 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3996 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3998 if (upper_bound > 1)
3999 { /* More than one repetition is allowed, so
4000 append a backward jump to the `succeed_n'
4001 that starts this interval.
4003 When we've reached this during matching,
4004 we'll have matched the interval once, so
4005 jump back only `upper_bound - 1' times. */
4006 STORE_JUMP2 (jump_n, b, laststart
4007 + 2 * OFFSET_ADDRESS_SIZE + 1,
4009 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
4011 /* The location we want to set is the second
4012 parameter of the `jump_n'; that is `b-2' as
4013 an absolute address. `laststart' will be
4014 the `set_number_at' we're about to insert;
4015 `laststart+3' the number to set, the source
4016 for the relative address. But we are
4017 inserting into the middle of the pattern --
4018 so everything is getting moved up by 5.
4019 Conclusion: (b - 2) - (laststart + 3) + 5,
4020 i.e., b - laststart.
4022 We insert this at the beginning of the loop
4023 so that if we fail during matching, we'll
4024 reinitialize the bounds. */
4025 PREFIX(insert_op2) (set_number_at, laststart,
4027 upper_bound - 1, b);
4028 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
4035 if (!(syntax & RE_INVALID_INTERVAL_ORD))
4036 FREE_STACK_RETURN (p == pend ? REG_EBRACE : REG_BADBR);
4038 /* Match the characters as literals. */
4041 if (syntax & RE_NO_BK_BRACES)
4044 goto normal_backslash;
4048 /* There is no way to specify the before_dot and after_dot
4049 operators. rms says this is ok. --karl */
4057 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
4063 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
4069 if (syntax & RE_NO_GNU_OPS)
4072 BUF_PUSH (wordchar);
4077 if (syntax & RE_NO_GNU_OPS)
4080 BUF_PUSH (notwordchar);
4085 if (syntax & RE_NO_GNU_OPS)
4091 if (syntax & RE_NO_GNU_OPS)
4097 if (syntax & RE_NO_GNU_OPS)
4099 BUF_PUSH (wordbound);
4103 if (syntax & RE_NO_GNU_OPS)
4105 BUF_PUSH (notwordbound);
4109 if (syntax & RE_NO_GNU_OPS)
4115 if (syntax & RE_NO_GNU_OPS)
4120 case '1': case '2': case '3': case '4': case '5':
4121 case '6': case '7': case '8': case '9':
4122 if (syntax & RE_NO_BK_REFS)
4128 FREE_STACK_RETURN (REG_ESUBREG);
4130 /* Can't back reference to a subexpression if inside of it. */
4131 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4135 BUF_PUSH_2 (duplicate, c1);
4141 if (syntax & RE_BK_PLUS_QM)
4144 goto normal_backslash;
4148 /* You might think it would be useful for \ to mean
4149 not to translate; but if we don't translate it
4150 it will never match anything. */
4158 /* Expects the character in `c'. */
4160 /* If no exactn currently being built. */
4163 /* If last exactn handle binary(or character) and
4164 new exactn handle character(or binary). */
4165 || is_exactn_bin != is_binary[p - 1 - pattern]
4168 /* If last exactn not at current position. */
4169 || pending_exact + *pending_exact + 1 != b
4171 /* We have only one byte following the exactn for the count. */
4172 || *pending_exact == (1 << BYTEWIDTH) - 1
4174 /* If followed by a repetition operator. */
4175 || *p == '*' || *p == '^'
4176 || ((syntax & RE_BK_PLUS_QM)
4177 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4178 : (*p == '+' || *p == '?'))
4179 || ((syntax & RE_INTERVALS)
4180 && ((syntax & RE_NO_BK_BRACES)
4182 : (p[0] == '\\' && p[1] == '{'))))
4184 /* Start building a new exactn. */
4189 /* Is this exactn binary data or character? */
4190 is_exactn_bin = is_binary[p - 1 - pattern];
4192 BUF_PUSH_2 (exactn_bin, 0);
4194 BUF_PUSH_2 (exactn, 0);
4196 BUF_PUSH_2 (exactn, 0);
4198 pending_exact = b - 1;
4205 } /* while p != pend */
4208 /* Through the pattern now. */
4211 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4213 if (!COMPILE_STACK_EMPTY)
4214 FREE_STACK_RETURN (REG_EPAREN);
4216 /* If we don't want backtracking, force success
4217 the first time we reach the end of the compiled pattern. */
4218 if (syntax & RE_NO_POSIX_BACKTRACKING)
4226 free (compile_stack.stack);
4228 /* We have succeeded; set the length of the buffer. */
4230 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4232 bufp->used = b - bufp->buffer;
4238 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4239 PREFIX(print_compiled_pattern) (bufp);
4243 #ifndef MATCH_MAY_ALLOCATE
4244 /* Initialize the failure stack to the largest possible stack. This
4245 isn't necessary unless we're trying to avoid calling alloca in
4246 the search and match routines. */
4248 int num_regs = bufp->re_nsub + 1;
4250 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4251 is strictly greater than re_max_failures, the largest possible stack
4252 is 2 * re_max_failures failure points. */
4253 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4255 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4258 if (! fail_stack.stack)
4260 = (PREFIX(fail_stack_elt_t) *) xmalloc (fail_stack.size
4261 * sizeof (PREFIX(fail_stack_elt_t)));
4264 = (PREFIX(fail_stack_elt_t) *) xrealloc (fail_stack.stack,
4266 * sizeof (PREFIX(fail_stack_elt_t))));
4267 # else /* not emacs */
4268 if (! fail_stack.stack)
4270 = (PREFIX(fail_stack_elt_t) *) malloc (fail_stack.size
4271 * sizeof (PREFIX(fail_stack_elt_t)));
4274 = (PREFIX(fail_stack_elt_t) *) realloc (fail_stack.stack,
4276 * sizeof (PREFIX(fail_stack_elt_t))));
4277 # endif /* not emacs */
4280 PREFIX(regex_grow_registers) (num_regs);
4282 #endif /* not MATCH_MAY_ALLOCATE */
4285 } /* regex_compile */
4287 /* Subroutines for `regex_compile'. */
4289 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4290 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4293 PREFIX(store_op1) (op, loc, arg)
4298 *loc = (UCHAR_T) op;
4299 STORE_NUMBER (loc + 1, arg);
4303 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4304 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4307 PREFIX(store_op2) (op, loc, arg1, arg2)
4312 *loc = (UCHAR_T) op;
4313 STORE_NUMBER (loc + 1, arg1);
4314 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4318 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4319 for OP followed by two-byte integer parameter ARG. */
4320 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4323 PREFIX(insert_op1) (op, loc, arg, end)
4329 register UCHAR_T *pfrom = end;
4330 register UCHAR_T *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4332 while (pfrom != loc)
4335 PREFIX(store_op1) (op, loc, arg);
4339 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4340 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4343 PREFIX(insert_op2) (op, loc, arg1, arg2, end)
4349 register UCHAR_T *pfrom = end;
4350 register UCHAR_T *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4352 while (pfrom != loc)
4355 PREFIX(store_op2) (op, loc, arg1, arg2);
4359 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4360 after an alternative or a begin-subexpression. We assume there is at
4361 least one character before the ^. */
4364 PREFIX(at_begline_loc_p) (pattern, p, syntax)
4365 const CHAR_T *pattern, *p;
4366 reg_syntax_t syntax;
4368 const CHAR_T *prev = p - 2;
4369 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4372 /* After a subexpression? */
4373 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4374 /* After an alternative? */
4375 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4379 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4380 at least one character after the $, i.e., `P < PEND'. */
4383 PREFIX(at_endline_loc_p) (p, pend, syntax)
4384 const CHAR_T *p, *pend;
4385 reg_syntax_t syntax;
4387 const CHAR_T *next = p;
4388 boolean next_backslash = *next == '\\';
4389 const CHAR_T *next_next = p + 1 < pend ? p + 1 : 0;
4392 /* Before a subexpression? */
4393 (syntax & RE_NO_BK_PARENS ? *next == ')'
4394 : next_backslash && next_next && *next_next == ')')
4395 /* Before an alternative? */
4396 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4397 : next_backslash && next_next && *next_next == '|');
4400 #else /* not INSIDE_RECURSION */
4402 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4403 false if it's not. */
4406 group_in_compile_stack (compile_stack, regnum)
4407 compile_stack_type compile_stack;
4412 for (this_element = compile_stack.avail - 1;
4415 if (compile_stack.stack[this_element].regnum == regnum)
4420 #endif /* not INSIDE_RECURSION */
4422 #ifdef INSIDE_RECURSION
4425 /* This insert space, which size is "num", into the pattern at "loc".
4426 "end" must point the end of the allocated buffer. */
4428 insert_space (num, loc, end)
4433 register CHAR_T *pto = end;
4434 register CHAR_T *pfrom = end - num;
4436 while (pfrom >= loc)
4442 static reg_errcode_t
4443 wcs_compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4445 CHAR_T range_start_char;
4446 const CHAR_T **p_ptr, *pend;
4447 CHAR_T *char_set, *b;
4448 RE_TRANSLATE_TYPE translate;
4449 reg_syntax_t syntax;
4451 const CHAR_T *p = *p_ptr;
4452 CHAR_T range_start, range_end;
4456 uint32_t start_val, end_val;
4462 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4465 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4466 _NL_COLLATE_COLLSEQWC);
4467 const unsigned char *extra = (const unsigned char *)
4468 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4470 if (range_start_char < -1)
4472 /* range_start is a collating symbol. */
4474 /* Retreive the index and get collation sequence value. */
4475 wextra = (int32_t*)(extra + char_set[-range_start_char]);
4476 start_val = wextra[1 + *wextra];
4479 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4481 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4483 /* Report an error if the range is empty and the syntax prohibits
4485 ret = ((syntax & RE_NO_EMPTY_RANGES)
4486 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4488 /* Insert space to the end of the char_ranges. */
4489 insert_space(2, b - char_set[5] - 2, b - 1);
4490 *(b - char_set[5] - 2) = (wchar_t)start_val;
4491 *(b - char_set[5] - 1) = (wchar_t)end_val;
4492 char_set[4]++; /* ranges_index */
4497 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4499 range_end = TRANSLATE (p[0]);
4500 /* Report an error if the range is empty and the syntax prohibits
4502 ret = ((syntax & RE_NO_EMPTY_RANGES)
4503 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4505 /* Insert space to the end of the char_ranges. */
4506 insert_space(2, b - char_set[5] - 2, b - 1);
4507 *(b - char_set[5] - 2) = range_start;
4508 *(b - char_set[5] - 1) = range_end;
4509 char_set[4]++; /* ranges_index */
4511 /* Have to increment the pointer into the pattern string, so the
4512 caller isn't still at the ending character. */
4518 /* Read the ending character of a range (in a bracket expression) from the
4519 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4520 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4521 Then we set the translation of all bits between the starting and
4522 ending characters (inclusive) in the compiled pattern B.
4524 Return an error code.
4526 We use these short variable names so we can use the same macros as
4527 `regex_compile' itself. */
4529 static reg_errcode_t
4530 byte_compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4531 unsigned int range_start_char;
4532 const char **p_ptr, *pend;
4533 RE_TRANSLATE_TYPE translate;
4534 reg_syntax_t syntax;
4538 const char *p = *p_ptr;
4541 const unsigned char *collseq;
4542 unsigned int start_colseq;
4543 unsigned int end_colseq;
4551 /* Have to increment the pointer into the pattern string, so the
4552 caller isn't still at the ending character. */
4555 /* Report an error if the range is empty and the syntax prohibits this. */
4556 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4559 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4560 _NL_COLLATE_COLLSEQMB);
4562 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4563 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4564 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4566 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4568 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4570 SET_LIST_BIT (TRANSLATE (this_char));
4575 /* Here we see why `this_char' has to be larger than an `unsigned
4576 char' -- we would otherwise go into an infinite loop, since all
4577 characters <= 0xff. */
4578 range_start_char = TRANSLATE (range_start_char);
4579 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4580 and some compilers cast it to int implicitly, so following for_loop
4581 may fall to (almost) infinite loop.
4582 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4583 To avoid this, we cast p[0] to unsigned int and truncate it. */
4584 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4586 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4588 SET_LIST_BIT (TRANSLATE (this_char));
4597 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4598 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4599 characters can start a string that matches the pattern. This fastmap
4600 is used by re_search to skip quickly over impossible starting points.
4602 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4603 area as BUFP->fastmap.
4605 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4608 Returns 0 if we succeed, -2 if an internal error. */
4611 /* local function for re_compile_fastmap.
4612 truncate wchar_t character to char. */
4613 static unsigned char truncate_wchar (CHAR_T c);
4615 static unsigned char
4619 unsigned char buf[MB_LEN_MAX];
4620 int retval = wctomb(buf, c);
4621 return retval > 0 ? buf[0] : (unsigned char)c;
4626 PREFIX(re_compile_fastmap) (bufp)
4627 struct re_pattern_buffer *bufp;
4630 #ifdef MATCH_MAY_ALLOCATE
4631 PREFIX(fail_stack_type) fail_stack;
4633 #ifndef REGEX_MALLOC
4637 register char *fastmap = bufp->fastmap;
4640 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4641 pattern to (char*) in regex_compile. */
4642 UCHAR_T *pattern = (UCHAR_T*)bufp->buffer;
4643 register UCHAR_T *pend = (UCHAR_T*) (bufp->buffer + bufp->used);
4645 UCHAR_T *pattern = bufp->buffer;
4646 register UCHAR_T *pend = pattern + bufp->used;
4648 UCHAR_T *p = pattern;
4651 /* This holds the pointer to the failure stack, when
4652 it is allocated relocatably. */
4653 fail_stack_elt_t *failure_stack_ptr;
4656 /* Assume that each path through the pattern can be null until
4657 proven otherwise. We set this false at the bottom of switch
4658 statement, to which we get only if a particular path doesn't
4659 match the empty string. */
4660 boolean path_can_be_null = true;
4662 /* We aren't doing a `succeed_n' to begin with. */
4663 boolean succeed_n_p = false;
4665 assert (fastmap != NULL && p != NULL);
4668 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4669 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4670 bufp->can_be_null = 0;
4674 if (p == pend || *p == succeed)
4676 /* We have reached the (effective) end of pattern. */
4677 if (!FAIL_STACK_EMPTY ())
4679 bufp->can_be_null |= path_can_be_null;
4681 /* Reset for next path. */
4682 path_can_be_null = true;
4684 p = fail_stack.stack[--fail_stack.avail].pointer;
4692 /* We should never be about to go beyond the end of the pattern. */
4695 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4698 /* I guess the idea here is to simply not bother with a fastmap
4699 if a backreference is used, since it's too hard to figure out
4700 the fastmap for the corresponding group. Setting
4701 `can_be_null' stops `re_search_2' from using the fastmap, so
4702 that is all we do. */
4704 bufp->can_be_null = 1;
4708 /* Following are the cases which match a character. These end
4713 fastmap[truncate_wchar(p[1])] = 1;
4727 /* It is hard to distinguish fastmap from (multi byte) characters
4728 which depends on current locale. */
4733 bufp->can_be_null = 1;
4737 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4738 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4744 /* Chars beyond end of map must be allowed. */
4745 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4748 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4749 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4755 for (j = 0; j < (1 << BYTEWIDTH); j++)
4756 if (SYNTAX (j) == Sword)
4762 for (j = 0; j < (1 << BYTEWIDTH); j++)
4763 if (SYNTAX (j) != Sword)
4770 int fastmap_newline = fastmap['\n'];
4772 /* `.' matches anything ... */
4773 for (j = 0; j < (1 << BYTEWIDTH); j++)
4776 /* ... except perhaps newline. */
4777 if (!(bufp->syntax & RE_DOT_NEWLINE))
4778 fastmap['\n'] = fastmap_newline;
4780 /* Return if we have already set `can_be_null'; if we have,
4781 then the fastmap is irrelevant. Something's wrong here. */
4782 else if (bufp->can_be_null)
4785 /* Otherwise, have to check alternative paths. */
4792 for (j = 0; j < (1 << BYTEWIDTH); j++)
4793 if (SYNTAX (j) == (enum syntaxcode) k)
4800 for (j = 0; j < (1 << BYTEWIDTH); j++)
4801 if (SYNTAX (j) != (enum syntaxcode) k)
4806 /* All cases after this match the empty string. These end with
4826 case push_dummy_failure:
4831 case pop_failure_jump:
4832 case maybe_pop_jump:
4835 case dummy_failure_jump:
4836 EXTRACT_NUMBER_AND_INCR (j, p);
4841 /* Jump backward implies we just went through the body of a
4842 loop and matched nothing. Opcode jumped to should be
4843 `on_failure_jump' or `succeed_n'. Just treat it like an
4844 ordinary jump. For a * loop, it has pushed its failure
4845 point already; if so, discard that as redundant. */
4846 if ((re_opcode_t) *p != on_failure_jump
4847 && (re_opcode_t) *p != succeed_n)
4851 EXTRACT_NUMBER_AND_INCR (j, p);
4854 /* If what's on the stack is where we are now, pop it. */
4855 if (!FAIL_STACK_EMPTY ()
4856 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4862 case on_failure_jump:
4863 case on_failure_keep_string_jump:
4864 handle_on_failure_jump:
4865 EXTRACT_NUMBER_AND_INCR (j, p);
4867 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4868 end of the pattern. We don't want to push such a point,
4869 since when we restore it above, entering the switch will
4870 increment `p' past the end of the pattern. We don't need
4871 to push such a point since we obviously won't find any more
4872 fastmap entries beyond `pend'. Such a pattern can match
4873 the null string, though. */
4876 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4878 RESET_FAIL_STACK ();
4883 bufp->can_be_null = 1;
4887 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4888 succeed_n_p = false;
4895 /* Get to the number of times to succeed. */
4896 p += OFFSET_ADDRESS_SIZE;
4898 /* Increment p past the n for when k != 0. */
4899 EXTRACT_NUMBER_AND_INCR (k, p);
4902 p -= 2 * OFFSET_ADDRESS_SIZE;
4903 succeed_n_p = true; /* Spaghetti code alert. */
4904 goto handle_on_failure_jump;
4910 p += 2 * OFFSET_ADDRESS_SIZE;
4921 abort (); /* We have listed all the cases. */
4924 /* Getting here means we have found the possible starting
4925 characters for one path of the pattern -- and that the empty
4926 string does not match. We need not follow this path further.
4927 Instead, look at the next alternative (remembered on the
4928 stack), or quit if no more. The test at the top of the loop
4929 does these things. */
4930 path_can_be_null = false;
4934 /* Set `can_be_null' for the last path (also the first path, if the
4935 pattern is empty). */
4936 bufp->can_be_null |= path_can_be_null;
4939 RESET_FAIL_STACK ();
4943 #else /* not INSIDE_RECURSION */
4946 re_compile_fastmap (bufp)
4947 struct re_pattern_buffer *bufp;
4950 if (MB_CUR_MAX != 1)
4951 return wcs_re_compile_fastmap(bufp);
4954 return byte_re_compile_fastmap(bufp);
4955 } /* re_compile_fastmap */
4957 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4961 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4962 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4963 this memory for recording register information. STARTS and ENDS
4964 must be allocated using the malloc library routine, and must each
4965 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4967 If NUM_REGS == 0, then subsequent matches should allocate their own
4970 Unless this function is called, the first search or match using
4971 PATTERN_BUFFER will allocate its own register data, without
4972 freeing the old data. */
4975 re_set_registers (bufp, regs, num_regs, starts, ends)
4976 struct re_pattern_buffer *bufp;
4977 struct re_registers *regs;
4979 regoff_t *starts, *ends;
4983 bufp->regs_allocated = REGS_REALLOCATE;
4984 regs->num_regs = num_regs;
4985 regs->start = starts;
4990 bufp->regs_allocated = REGS_UNALLOCATED;
4992 regs->start = regs->end = (regoff_t *) 0;
4996 weak_alias (__re_set_registers, re_set_registers)
4999 /* Searching routines. */
5001 /* Like re_search_2, below, but only one string is specified, and
5002 doesn't let you say where to stop matching. */
5005 re_search (bufp, string, size, startpos, range, regs)
5006 struct re_pattern_buffer *bufp;
5008 int size, startpos, range;
5009 struct re_registers *regs;
5011 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
5015 weak_alias (__re_search, re_search)
5019 /* Using the compiled pattern in BUFP->buffer, first tries to match the
5020 virtual concatenation of STRING1 and STRING2, starting first at index
5021 STARTPOS, then at STARTPOS + 1, and so on.
5023 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
5025 RANGE is how far to scan while trying to match. RANGE = 0 means try
5026 only at STARTPOS; in general, the last start tried is STARTPOS +
5029 In REGS, return the indices of the virtual concatenation of STRING1
5030 and STRING2 that matched the entire BUFP->buffer and its contained
5033 Do not consider matching one past the index STOP in the virtual
5034 concatenation of STRING1 and STRING2.
5036 We return either the position in the strings at which the match was
5037 found, -1 if no match, or -2 if error (such as failure
5041 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
5042 struct re_pattern_buffer *bufp;
5043 const char *string1, *string2;
5047 struct re_registers *regs;
5051 if (MB_CUR_MAX != 1)
5052 return wcs_re_search_2 (bufp, string1, size1, string2, size2, startpos,
5056 return byte_re_search_2 (bufp, string1, size1, string2, size2, startpos,
5060 weak_alias (__re_search_2, re_search_2)
5063 #endif /* not INSIDE_RECURSION */
5065 #ifdef INSIDE_RECURSION
5067 #ifdef MATCH_MAY_ALLOCATE
5068 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5070 # define FREE_VAR(var) if (var) free (var); var = NULL
5074 # define FREE_WCS_BUFFERS() \
5076 FREE_VAR (string1); \
5077 FREE_VAR (string2); \
5078 FREE_VAR (mbs_offset1); \
5079 FREE_VAR (mbs_offset2); \
5085 PREFIX(re_search_2) (bufp, string1, size1, string2, size2, startpos, range,
5087 struct re_pattern_buffer *bufp;
5088 const char *string1, *string2;
5092 struct re_registers *regs;
5096 register char *fastmap = bufp->fastmap;
5097 register RE_TRANSLATE_TYPE translate = bufp->translate;
5098 int total_size = size1 + size2;
5099 int endpos = startpos + range;
5101 /* We need wchar_t* buffers correspond to cstring1, cstring2. */
5102 wchar_t *wcs_string1 = NULL, *wcs_string2 = NULL;
5103 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5104 int wcs_size1 = 0, wcs_size2 = 0;
5105 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5106 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5107 /* They hold whether each wchar_t is binary data or not. */
5108 char *is_binary = NULL;
5111 /* Check for out-of-range STARTPOS. */
5112 if (startpos < 0 || startpos > total_size)
5115 /* Fix up RANGE if it might eventually take us outside
5116 the virtual concatenation of STRING1 and STRING2.
5117 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
5119 range = 0 - startpos;
5120 else if (endpos > total_size)
5121 range = total_size - startpos;
5123 /* If the search isn't to be a backwards one, don't waste time in a
5124 search for a pattern that must be anchored. */
5125 if (bufp->used > 0 && range > 0
5126 && ((re_opcode_t) bufp->buffer[0] == begbuf
5127 /* `begline' is like `begbuf' if it cannot match at newlines. */
5128 || ((re_opcode_t) bufp->buffer[0] == begline
5129 && !bufp->newline_anchor)))
5138 /* In a forward search for something that starts with \=.
5139 don't keep searching past point. */
5140 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5142 range = PT - startpos;
5148 /* Update the fastmap now if not correct already. */
5149 if (fastmap && !bufp->fastmap_accurate)
5150 if (re_compile_fastmap (bufp) == -2)
5154 /* Allocate wchar_t array for wcs_string1 and wcs_string2 and
5155 fill them with converted string. */
5158 wcs_string1 = REGEX_TALLOC (size1 + 1, CHAR_T);
5159 mbs_offset1 = REGEX_TALLOC (size1 + 1, int);
5160 is_binary = REGEX_TALLOC (size1 + 1, char);
5161 if (!wcs_string1 || !mbs_offset1 || !is_binary)
5163 FREE_VAR (wcs_string1);
5164 FREE_VAR (mbs_offset1);
5165 FREE_VAR (is_binary);
5168 wcs_size1 = convert_mbs_to_wcs(wcs_string1, string1, size1,
5169 mbs_offset1, is_binary);
5170 wcs_string1[wcs_size1] = L'\0'; /* for a sentinel */
5171 FREE_VAR (is_binary);
5175 wcs_string2 = REGEX_TALLOC (size2 + 1, CHAR_T);
5176 mbs_offset2 = REGEX_TALLOC (size2 + 1, int);
5177 is_binary = REGEX_TALLOC (size2 + 1, char);
5178 if (!wcs_string2 || !mbs_offset2 || !is_binary)
5180 FREE_WCS_BUFFERS ();
5181 FREE_VAR (is_binary);
5184 wcs_size2 = convert_mbs_to_wcs(wcs_string2, string2, size2,
5185 mbs_offset2, is_binary);
5186 wcs_string2[wcs_size2] = L'\0'; /* for a sentinel */
5187 FREE_VAR (is_binary);
5192 /* Loop through the string, looking for a place to start matching. */
5195 /* If a fastmap is supplied, skip quickly over characters that
5196 cannot be the start of a match. If the pattern can match the
5197 null string, however, we don't need to skip characters; we want
5198 the first null string. */
5199 if (fastmap && startpos < total_size && !bufp->can_be_null)
5201 if (range > 0) /* Searching forwards. */
5203 register const char *d;
5204 register int lim = 0;
5207 if (startpos < size1 && startpos + range >= size1)
5208 lim = range - (size1 - startpos);
5210 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5212 /* Written out as an if-else to avoid testing `translate'
5216 && !fastmap[(unsigned char)
5217 translate[(unsigned char) *d++]])
5220 while (range > lim && !fastmap[(unsigned char) *d++])
5223 startpos += irange - range;
5225 else /* Searching backwards. */
5227 register CHAR_T c = (size1 == 0 || startpos >= size1
5228 ? string2[startpos - size1]
5229 : string1[startpos]);
5231 if (!fastmap[(unsigned char) TRANSLATE (c)])
5236 /* If can't match the null string, and that's all we have left, fail. */
5237 if (range >= 0 && startpos == total_size && fastmap
5238 && !bufp->can_be_null)
5241 FREE_WCS_BUFFERS ();
5247 val = wcs_re_match_2_internal (bufp, string1, size1, string2,
5248 size2, startpos, regs, stop,
5249 wcs_string1, wcs_size1,
5250 wcs_string2, wcs_size2,
5251 mbs_offset1, mbs_offset2);
5253 val = byte_re_match_2_internal (bufp, string1, size1, string2,
5254 size2, startpos, regs, stop);
5257 #ifndef REGEX_MALLOC
5266 FREE_WCS_BUFFERS ();
5274 FREE_WCS_BUFFERS ();
5294 FREE_WCS_BUFFERS ();
5300 /* This converts PTR, a pointer into one of the search wchar_t strings
5301 `string1' and `string2' into an multibyte string offset from the
5302 beginning of that string. We use mbs_offset to optimize.
5303 See convert_mbs_to_wcs. */
5304 # define POINTER_TO_OFFSET(ptr) \
5305 (FIRST_STRING_P (ptr) \
5306 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5307 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5310 /* This converts PTR, a pointer into one of the search strings `string1'
5311 and `string2' into an offset from the beginning of that string. */
5312 # define POINTER_TO_OFFSET(ptr) \
5313 (FIRST_STRING_P (ptr) \
5314 ? ((regoff_t) ((ptr) - string1)) \
5315 : ((regoff_t) ((ptr) - string2 + size1)))
5318 /* Macros for dealing with the split strings in re_match_2. */
5320 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5322 /* Call before fetching a character with *d. This switches over to
5323 string2 if necessary. */
5324 #define PREFETCH() \
5327 /* End of string2 => fail. */ \
5328 if (dend == end_match_2) \
5330 /* End of string1 => advance to string2. */ \
5332 dend = end_match_2; \
5335 /* Test if at very beginning or at very end of the virtual concatenation
5336 of `string1' and `string2'. If only one string, it's `string2'. */
5337 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5338 #define AT_STRINGS_END(d) ((d) == end2)
5341 /* Test if D points to a character which is word-constituent. We have
5342 two special cases to check for: if past the end of string1, look at
5343 the first character in string2; and if before the beginning of
5344 string2, look at the last character in string1. */
5346 /* Use internationalized API instead of SYNTAX. */
5347 # define WORDCHAR_P(d) \
5348 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5349 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5351 # define WORDCHAR_P(d) \
5352 (SYNTAX ((d) == end1 ? *string2 \
5353 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5357 /* Disabled due to a compiler bug -- see comment at case wordbound */
5359 /* Test if the character before D and the one at D differ with respect
5360 to being word-constituent. */
5361 #define AT_WORD_BOUNDARY(d) \
5362 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5363 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5366 /* Free everything we malloc. */
5367 #ifdef MATCH_MAY_ALLOCATE
5369 # define FREE_VARIABLES() \
5371 REGEX_FREE_STACK (fail_stack.stack); \
5372 FREE_VAR (regstart); \
5373 FREE_VAR (regend); \
5374 FREE_VAR (old_regstart); \
5375 FREE_VAR (old_regend); \
5376 FREE_VAR (best_regstart); \
5377 FREE_VAR (best_regend); \
5378 FREE_VAR (reg_info); \
5379 FREE_VAR (reg_dummy); \
5380 FREE_VAR (reg_info_dummy); \
5381 if (!cant_free_wcs_buf) \
5383 FREE_VAR (string1); \
5384 FREE_VAR (string2); \
5385 FREE_VAR (mbs_offset1); \
5386 FREE_VAR (mbs_offset2); \
5390 # define FREE_VARIABLES() \
5392 REGEX_FREE_STACK (fail_stack.stack); \
5393 FREE_VAR (regstart); \
5394 FREE_VAR (regend); \
5395 FREE_VAR (old_regstart); \
5396 FREE_VAR (old_regend); \
5397 FREE_VAR (best_regstart); \
5398 FREE_VAR (best_regend); \
5399 FREE_VAR (reg_info); \
5400 FREE_VAR (reg_dummy); \
5401 FREE_VAR (reg_info_dummy); \
5406 # define FREE_VARIABLES() \
5408 if (!cant_free_wcs_buf) \
5410 FREE_VAR (string1); \
5411 FREE_VAR (string2); \
5412 FREE_VAR (mbs_offset1); \
5413 FREE_VAR (mbs_offset2); \
5417 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5419 #endif /* not MATCH_MAY_ALLOCATE */
5421 /* These values must meet several constraints. They must not be valid
5422 register values; since we have a limit of 255 registers (because
5423 we use only one byte in the pattern for the register number), we can
5424 use numbers larger than 255. They must differ by 1, because of
5425 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5426 be larger than the value for the highest register, so we do not try
5427 to actually save any registers when none are active. */
5428 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5429 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5431 #else /* not INSIDE_RECURSION */
5432 /* Matching routines. */
5434 #ifndef emacs /* Emacs never uses this. */
5435 /* re_match is like re_match_2 except it takes only a single string. */
5438 re_match (bufp, string, size, pos, regs)
5439 struct re_pattern_buffer *bufp;
5442 struct re_registers *regs;
5446 if (MB_CUR_MAX != 1)
5447 result = wcs_re_match_2_internal (bufp, NULL, 0, string, size,
5449 NULL, 0, NULL, 0, NULL, NULL);
5452 result = byte_re_match_2_internal (bufp, NULL, 0, string, size,
5454 # ifndef REGEX_MALLOC
5462 weak_alias (__re_match, re_match)
5464 #endif /* not emacs */
5466 #endif /* not INSIDE_RECURSION */
5468 #ifdef INSIDE_RECURSION
5469 static boolean PREFIX(group_match_null_string_p) _RE_ARGS ((UCHAR_T **p,
5471 PREFIX(register_info_type) *reg_info));
5472 static boolean PREFIX(alt_match_null_string_p) _RE_ARGS ((UCHAR_T *p,
5474 PREFIX(register_info_type) *reg_info));
5475 static boolean PREFIX(common_op_match_null_string_p) _RE_ARGS ((UCHAR_T **p,
5477 PREFIX(register_info_type) *reg_info));
5478 static int PREFIX(bcmp_translate) _RE_ARGS ((const CHAR_T *s1, const CHAR_T *s2,
5479 int len, char *translate));
5480 #else /* not INSIDE_RECURSION */
5482 /* re_match_2 matches the compiled pattern in BUFP against the
5483 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5484 and SIZE2, respectively). We start matching at POS, and stop
5487 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5488 store offsets for the substring each group matched in REGS. See the
5489 documentation for exactly how many groups we fill.
5491 We return -1 if no match, -2 if an internal error (such as the
5492 failure stack overflowing). Otherwise, we return the length of the
5493 matched substring. */
5496 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5497 struct re_pattern_buffer *bufp;
5498 const char *string1, *string2;
5501 struct re_registers *regs;
5506 if (MB_CUR_MAX != 1)
5507 result = wcs_re_match_2_internal (bufp, string1, size1, string2, size2,
5509 NULL, 0, NULL, 0, NULL, NULL);
5512 result = byte_re_match_2_internal (bufp, string1, size1, string2, size2,
5515 #ifndef REGEX_MALLOC
5523 weak_alias (__re_match_2, re_match_2)
5526 #endif /* not INSIDE_RECURSION */
5528 #ifdef INSIDE_RECURSION
5531 static int count_mbs_length PARAMS ((int *, int));
5533 /* This check the substring (from 0, to length) of the multibyte string,
5534 to which offset_buffer correspond. And count how many wchar_t_characters
5535 the substring occupy. We use offset_buffer to optimization.
5536 See convert_mbs_to_wcs. */
5539 count_mbs_length(offset_buffer, length)
5545 /* Check whether the size is valid. */
5549 if (offset_buffer == NULL)
5552 /* If there are no multibyte character, offset_buffer[i] == i.
5553 Optmize for this case. */
5554 if (offset_buffer[length] == length)
5557 /* Set up upper with length. (because for all i, offset_buffer[i] >= i) */
5563 int middle = (lower + upper) / 2;
5564 if (middle == lower || middle == upper)
5566 if (offset_buffer[middle] > length)
5568 else if (offset_buffer[middle] < length)
5578 /* This is a separate function so that we can force an alloca cleanup
5582 wcs_re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos,
5583 regs, stop, string1, size1, string2, size2,
5584 mbs_offset1, mbs_offset2)
5585 struct re_pattern_buffer *bufp;
5586 const char *cstring1, *cstring2;
5589 struct re_registers *regs;
5591 /* string1 == string2 == NULL means string1/2, size1/2 and
5592 mbs_offset1/2 need seting up in this function. */
5593 /* We need wchar_t* buffers correspond to cstring1, cstring2. */
5594 wchar_t *string1, *string2;
5595 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5597 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5598 int *mbs_offset1, *mbs_offset2;
5601 byte_re_match_2_internal (bufp, string1, size1,string2, size2, pos,
5603 struct re_pattern_buffer *bufp;
5604 const char *string1, *string2;
5607 struct re_registers *regs;
5611 /* General temporaries. */
5615 /* They hold whether each wchar_t is binary data or not. */
5616 char *is_binary = NULL;
5617 /* If true, we can't free string1/2, mbs_offset1/2. */
5618 int cant_free_wcs_buf = 1;
5621 /* Just past the end of the corresponding string. */
5622 const CHAR_T *end1, *end2;
5624 /* Pointers into string1 and string2, just past the last characters in
5625 each to consider matching. */
5626 const CHAR_T *end_match_1, *end_match_2;
5628 /* Where we are in the data, and the end of the current string. */
5629 const CHAR_T *d, *dend;
5631 /* Where we are in the pattern, and the end of the pattern. */
5633 UCHAR_T *pattern, *p;
5634 register UCHAR_T *pend;
5636 UCHAR_T *p = bufp->buffer;
5637 register UCHAR_T *pend = p + bufp->used;
5640 /* Mark the opcode just after a start_memory, so we can test for an
5641 empty subpattern when we get to the stop_memory. */
5642 UCHAR_T *just_past_start_mem = 0;
5644 /* We use this to map every character in the string. */
5645 RE_TRANSLATE_TYPE translate = bufp->translate;
5647 /* Failure point stack. Each place that can handle a failure further
5648 down the line pushes a failure point on this stack. It consists of
5649 restart, regend, and reg_info for all registers corresponding to
5650 the subexpressions we're currently inside, plus the number of such
5651 registers, and, finally, two char *'s. The first char * is where
5652 to resume scanning the pattern; the second one is where to resume
5653 scanning the strings. If the latter is zero, the failure point is
5654 a ``dummy''; if a failure happens and the failure point is a dummy,
5655 it gets discarded and the next next one is tried. */
5656 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5657 PREFIX(fail_stack_type) fail_stack;
5660 static unsigned failure_id;
5661 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5665 /* This holds the pointer to the failure stack, when
5666 it is allocated relocatably. */
5667 fail_stack_elt_t *failure_stack_ptr;
5670 /* We fill all the registers internally, independent of what we
5671 return, for use in backreferences. The number here includes
5672 an element for register zero. */
5673 size_t num_regs = bufp->re_nsub + 1;
5675 /* The currently active registers. */
5676 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5677 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5679 /* Information on the contents of registers. These are pointers into
5680 the input strings; they record just what was matched (on this
5681 attempt) by a subexpression part of the pattern, that is, the
5682 regnum-th regstart pointer points to where in the pattern we began
5683 matching and the regnum-th regend points to right after where we
5684 stopped matching the regnum-th subexpression. (The zeroth register
5685 keeps track of what the whole pattern matches.) */
5686 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5687 const CHAR_T **regstart, **regend;
5690 /* If a group that's operated upon by a repetition operator fails to
5691 match anything, then the register for its start will need to be
5692 restored because it will have been set to wherever in the string we
5693 are when we last see its open-group operator. Similarly for a
5695 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5696 const CHAR_T **old_regstart, **old_regend;
5699 /* The is_active field of reg_info helps us keep track of which (possibly
5700 nested) subexpressions we are currently in. The matched_something
5701 field of reg_info[reg_num] helps us tell whether or not we have
5702 matched any of the pattern so far this time through the reg_num-th
5703 subexpression. These two fields get reset each time through any
5704 loop their register is in. */
5705 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5706 PREFIX(register_info_type) *reg_info;
5709 /* The following record the register info as found in the above
5710 variables when we find a match better than any we've seen before.
5711 This happens as we backtrack through the failure points, which in
5712 turn happens only if we have not yet matched the entire string. */
5713 unsigned best_regs_set = false;
5714 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5715 const CHAR_T **best_regstart, **best_regend;
5718 /* Logically, this is `best_regend[0]'. But we don't want to have to
5719 allocate space for that if we're not allocating space for anything
5720 else (see below). Also, we never need info about register 0 for
5721 any of the other register vectors, and it seems rather a kludge to
5722 treat `best_regend' differently than the rest. So we keep track of
5723 the end of the best match so far in a separate variable. We
5724 initialize this to NULL so that when we backtrack the first time
5725 and need to test it, it's not garbage. */
5726 const CHAR_T *match_end = NULL;
5728 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5729 int set_regs_matched_done = 0;
5731 /* Used when we pop values we don't care about. */
5732 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5733 const CHAR_T **reg_dummy;
5734 PREFIX(register_info_type) *reg_info_dummy;
5738 /* Counts the total number of registers pushed. */
5739 unsigned num_regs_pushed = 0;
5742 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5746 #ifdef MATCH_MAY_ALLOCATE
5747 /* Do not bother to initialize all the register variables if there are
5748 no groups in the pattern, as it takes a fair amount of time. If
5749 there are groups, we include space for register 0 (the whole
5750 pattern), even though we never use it, since it simplifies the
5751 array indexing. We should fix this. */
5754 regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5755 regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5756 old_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5757 old_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5758 best_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5759 best_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5760 reg_info = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5761 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_T *);
5762 reg_info_dummy = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5764 if (!(regstart && regend && old_regstart && old_regend && reg_info
5765 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5773 /* We must initialize all our variables to NULL, so that
5774 `FREE_VARIABLES' doesn't try to free them. */
5775 regstart = regend = old_regstart = old_regend = best_regstart
5776 = best_regend = reg_dummy = NULL;
5777 reg_info = reg_info_dummy = (PREFIX(register_info_type) *) NULL;
5779 #endif /* MATCH_MAY_ALLOCATE */
5781 /* The starting position is bogus. */
5783 if (pos < 0 || pos > csize1 + csize2)
5785 if (pos < 0 || pos > size1 + size2)
5793 /* Allocate wchar_t array for string1 and string2 and
5794 fill them with converted string. */
5795 if (string1 == NULL && string2 == NULL)
5797 /* We need seting up buffers here. */
5799 /* We must free wcs buffers in this function. */
5800 cant_free_wcs_buf = 0;
5804 string1 = REGEX_TALLOC (csize1 + 1, CHAR_T);
5805 mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5806 is_binary = REGEX_TALLOC (csize1 + 1, char);
5807 if (!string1 || !mbs_offset1 || !is_binary)
5810 FREE_VAR (mbs_offset1);
5811 FREE_VAR (is_binary);
5817 string2 = REGEX_TALLOC (csize2 + 1, CHAR_T);
5818 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5819 is_binary = REGEX_TALLOC (csize2 + 1, char);
5820 if (!string2 || !mbs_offset2 || !is_binary)
5823 FREE_VAR (mbs_offset1);
5825 FREE_VAR (mbs_offset2);
5826 FREE_VAR (is_binary);
5829 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5830 mbs_offset2, is_binary);
5831 string2[size2] = L'\0'; /* for a sentinel */
5832 FREE_VAR (is_binary);
5836 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5837 pattern to (char*) in regex_compile. */
5838 p = pattern = (CHAR_T*)bufp->buffer;
5839 pend = (CHAR_T*)(bufp->buffer + bufp->used);
5843 /* Initialize subexpression text positions to -1 to mark ones that no
5844 start_memory/stop_memory has been seen for. Also initialize the
5845 register information struct. */
5846 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5848 regstart[mcnt] = regend[mcnt]
5849 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5851 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5852 IS_ACTIVE (reg_info[mcnt]) = 0;
5853 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5854 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5857 /* We move `string1' into `string2' if the latter's empty -- but not if
5858 `string1' is null. */
5859 if (size2 == 0 && string1 != NULL)
5866 mbs_offset2 = mbs_offset1;
5872 end1 = string1 + size1;
5873 end2 = string2 + size2;
5875 /* Compute where to stop matching, within the two strings. */
5879 mcnt = count_mbs_length(mbs_offset1, stop);
5880 end_match_1 = string1 + mcnt;
5881 end_match_2 = string2;
5885 if (stop > csize1 + csize2)
5886 stop = csize1 + csize2;
5888 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5889 end_match_2 = string2 + mcnt;
5892 { /* count_mbs_length return error. */
5899 end_match_1 = string1 + stop;
5900 end_match_2 = string2;
5905 end_match_2 = string2 + stop - size1;
5909 /* `p' scans through the pattern as `d' scans through the data.
5910 `dend' is the end of the input string that `d' points within. `d'
5911 is advanced into the following input string whenever necessary, but
5912 this happens before fetching; therefore, at the beginning of the
5913 loop, `d' can be pointing at the end of a string, but it cannot
5916 if (size1 > 0 && pos <= csize1)
5918 mcnt = count_mbs_length(mbs_offset1, pos);
5924 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5930 { /* count_mbs_length return error. */
5935 if (size1 > 0 && pos <= size1)
5942 d = string2 + pos - size1;
5947 DEBUG_PRINT1 ("The compiled pattern is:\n");
5948 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5949 DEBUG_PRINT1 ("The string to match is: `");
5950 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5951 DEBUG_PRINT1 ("'\n");
5953 /* This loops over pattern commands. It exits by returning from the
5954 function if the match is complete, or it drops through if the match
5955 fails at this starting point in the input data. */
5959 DEBUG_PRINT2 ("\n%p: ", p);
5961 DEBUG_PRINT2 ("\n0x%x: ", p);
5965 { /* End of pattern means we might have succeeded. */
5966 DEBUG_PRINT1 ("end of pattern ... ");
5968 /* If we haven't matched the entire string, and we want the
5969 longest match, try backtracking. */
5970 if (d != end_match_2)
5972 /* 1 if this match ends in the same string (string1 or string2)
5973 as the best previous match. */
5974 boolean same_str_p = (FIRST_STRING_P (match_end)
5975 == MATCHING_IN_FIRST_STRING);
5976 /* 1 if this match is the best seen so far. */
5977 boolean best_match_p;
5979 /* AIX compiler got confused when this was combined
5980 with the previous declaration. */
5982 best_match_p = d > match_end;
5984 best_match_p = !MATCHING_IN_FIRST_STRING;
5986 DEBUG_PRINT1 ("backtracking.\n");
5988 if (!FAIL_STACK_EMPTY ())
5989 { /* More failure points to try. */
5991 /* If exceeds best match so far, save it. */
5992 if (!best_regs_set || best_match_p)
5994 best_regs_set = true;
5997 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5999 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
6001 best_regstart[mcnt] = regstart[mcnt];
6002 best_regend[mcnt] = regend[mcnt];
6008 /* If no failure points, don't restore garbage. And if
6009 last match is real best match, don't restore second
6011 else if (best_regs_set && !best_match_p)
6014 /* Restore best match. It may happen that `dend ==
6015 end_match_1' while the restored d is in string2.
6016 For example, the pattern `x.*y.*z' against the
6017 strings `x-' and `y-z-', if the two strings are
6018 not consecutive in memory. */
6019 DEBUG_PRINT1 ("Restoring best registers.\n");
6022 dend = ((d >= string1 && d <= end1)
6023 ? end_match_1 : end_match_2);
6025 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
6027 regstart[mcnt] = best_regstart[mcnt];
6028 regend[mcnt] = best_regend[mcnt];
6031 } /* d != end_match_2 */
6034 DEBUG_PRINT1 ("Accepting match.\n");
6035 /* If caller wants register contents data back, do it. */
6036 if (regs && !bufp->no_sub)
6038 /* Have the register data arrays been allocated? */
6039 if (bufp->regs_allocated == REGS_UNALLOCATED)
6040 { /* No. So allocate them with malloc. We need one
6041 extra element beyond `num_regs' for the `-1' marker
6043 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
6044 regs->start = TALLOC (regs->num_regs, regoff_t);
6045 regs->end = TALLOC (regs->num_regs, regoff_t);
6046 if (regs->start == NULL || regs->end == NULL)
6051 bufp->regs_allocated = REGS_REALLOCATE;
6053 else if (bufp->regs_allocated == REGS_REALLOCATE)
6054 { /* Yes. If we need more elements than were already
6055 allocated, reallocate them. If we need fewer, just
6057 if (regs->num_regs < num_regs + 1)
6059 regs->num_regs = num_regs + 1;
6060 RETALLOC (regs->start, regs->num_regs, regoff_t);
6061 RETALLOC (regs->end, regs->num_regs, regoff_t);
6062 if (regs->start == NULL || regs->end == NULL)
6071 /* These braces fend off a "empty body in an else-statement"
6072 warning under GCC when assert expands to nothing. */
6073 assert (bufp->regs_allocated == REGS_FIXED);
6076 /* Convert the pointer data in `regstart' and `regend' to
6077 indices. Register zero has to be set differently,
6078 since we haven't kept track of any info for it. */
6079 if (regs->num_regs > 0)
6081 regs->start[0] = pos;
6083 if (MATCHING_IN_FIRST_STRING)
6084 regs->end[0] = mbs_offset1 != NULL ?
6085 mbs_offset1[d-string1] : 0;
6087 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
6088 mbs_offset2[d-string2] : 0);
6090 regs->end[0] = (MATCHING_IN_FIRST_STRING
6091 ? ((regoff_t) (d - string1))
6092 : ((regoff_t) (d - string2 + size1)));
6096 /* Go through the first `min (num_regs, regs->num_regs)'
6097 registers, since that is all we initialized. */
6098 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
6101 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
6102 regs->start[mcnt] = regs->end[mcnt] = -1;
6106 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
6108 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
6112 /* If the regs structure we return has more elements than
6113 were in the pattern, set the extra elements to -1. If
6114 we (re)allocated the registers, this is the case,
6115 because we always allocate enough to have at least one
6117 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
6118 regs->start[mcnt] = regs->end[mcnt] = -1;
6119 } /* regs && !bufp->no_sub */
6121 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
6122 nfailure_points_pushed, nfailure_points_popped,
6123 nfailure_points_pushed - nfailure_points_popped);
6124 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
6127 if (MATCHING_IN_FIRST_STRING)
6128 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
6130 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
6134 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
6139 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
6145 /* Otherwise match next pattern command. */
6146 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
6148 /* Ignore these. Used to ignore the n of succeed_n's which
6149 currently have n == 0. */
6151 DEBUG_PRINT1 ("EXECUTING no_op.\n");
6155 DEBUG_PRINT1 ("EXECUTING succeed.\n");
6158 /* Match the next n pattern characters exactly. The following
6159 byte in the pattern defines n, and the n bytes after that
6160 are the characters to match. */
6166 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
6168 /* This is written out as an if-else so we don't waste time
6169 testing `translate' inside the loop. */
6178 if ((UCHAR_T) translate[(unsigned char) *d++]
6184 if (*d++ != (CHAR_T) *p++)
6188 if ((UCHAR_T) translate[(unsigned char) *d++]
6200 if (*d++ != (CHAR_T) *p++) goto fail;
6204 SET_REGS_MATCHED ();
6208 /* Match any character except possibly a newline or a null. */
6210 DEBUG_PRINT1 ("EXECUTING anychar.\n");
6214 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
6215 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
6218 SET_REGS_MATCHED ();
6219 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
6229 unsigned int i, char_class_length, coll_symbol_length,
6230 equiv_class_length, ranges_length, chars_length, length;
6231 CHAR_T *workp, *workp2, *charset_top;
6232 #define WORK_BUFFER_SIZE 128
6233 CHAR_T str_buf[WORK_BUFFER_SIZE];
6238 boolean not = (re_opcode_t) *(p - 1) == charset_not;
6240 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
6242 c = TRANSLATE (*d); /* The character to match. */
6245 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
6247 charset_top = p - 1;
6248 char_class_length = *p++;
6249 coll_symbol_length = *p++;
6250 equiv_class_length = *p++;
6251 ranges_length = *p++;
6252 chars_length = *p++;
6253 /* p points charset[6], so the address of the next instruction
6254 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
6255 where l=length of char_classes, m=length of collating_symbol,
6256 n=equivalence_class, o=length of char_range,
6257 p'=length of character. */
6259 /* Update p to indicate the next instruction. */
6260 p += char_class_length + coll_symbol_length+ equiv_class_length +
6261 2*ranges_length + chars_length;
6263 /* match with char_class? */
6264 for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
6267 uintptr_t alignedp = ((uintptr_t)workp
6268 + __alignof__(wctype_t) - 1)
6269 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6270 wctype = *((wctype_t*)alignedp);
6271 workp += CHAR_CLASS_SIZE;
6272 if (iswctype((wint_t)c, wctype))
6273 goto char_set_matched;
6276 /* match with collating_symbol? */
6280 const unsigned char *extra = (const unsigned char *)
6281 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6283 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6287 wextra = (int32_t*)(extra + *workp++);
6288 for (i = 0; i < *wextra; ++i)
6289 if (TRANSLATE(d[i]) != wextra[1 + i])
6294 /* Update d, however d will be incremented at
6295 char_set_matched:, we decrement d here. */
6297 goto char_set_matched;
6301 else /* (nrules == 0) */
6303 /* If we can't look up collation data, we use wcscoll
6306 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6308 const CHAR_T *backup_d = d, *backup_dend = dend;
6309 length = wcslen(workp);
6311 /* If wcscoll(the collating symbol, whole string) > 0,
6312 any substring of the string never match with the
6313 collating symbol. */
6314 if (wcscoll(workp, d) > 0)
6316 workp += length + 1;
6320 /* First, we compare the collating symbol with
6321 the first character of the string.
6322 If it don't match, we add the next character to
6323 the compare buffer in turn. */
6324 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6329 if (dend == end_match_2)
6335 /* add next character to the compare buffer. */
6336 str_buf[i] = TRANSLATE(*d);
6337 str_buf[i+1] = '\0';
6339 match = wcscoll(workp, str_buf);
6341 goto char_set_matched;
6344 /* (str_buf > workp) indicate (str_buf + X > workp),
6345 because for all X (str_buf + X > str_buf).
6346 So we don't need continue this loop. */
6349 /* Otherwise(str_buf < workp),
6350 (str_buf+next_character) may equals (workp).
6351 So we continue this loop. */
6356 workp += length + 1;
6359 /* match with equivalence_class? */
6363 const CHAR_T *backup_d = d, *backup_dend = dend;
6364 /* Try to match the equivalence class against
6365 those known to the collate implementation. */
6366 const int32_t *table;
6367 const int32_t *weights;
6368 const int32_t *extra;
6369 const int32_t *indirect;
6374 /* This #include defines a local function! */
6375 # include <locale/weightwc.h>
6377 table = (const int32_t *)
6378 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6379 weights = (const wint_t *)
6380 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6381 extra = (const wint_t *)
6382 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6383 indirect = (const int32_t *)
6384 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6386 /* Write 1 collating element to str_buf, and
6390 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6392 cp = (wint_t*)str_buf;
6395 if (dend == end_match_2)
6400 str_buf[i] = TRANSLATE(*(d+i));
6401 str_buf[i+1] = '\0'; /* sentinel */
6402 idx2 = findidx ((const wint_t**)&cp);
6405 /* Update d, however d will be incremented at
6406 char_set_matched:, we decrement d here. */
6407 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6410 if (dend == end_match_2)
6419 len = weights[idx2];
6421 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6424 idx = (int32_t)*workp;
6425 /* We already checked idx != 0 in regex_compile. */
6427 if (idx2 != 0 && len == weights[idx])
6430 while (cnt < len && (weights[idx + 1 + cnt]
6431 == weights[idx2 + 1 + cnt]))
6435 goto char_set_matched;
6442 else /* (nrules == 0) */
6444 /* If we can't look up collation data, we use wcscoll
6447 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6449 const CHAR_T *backup_d = d, *backup_dend = dend;
6450 length = wcslen(workp);
6452 /* If wcscoll(the collating symbol, whole string) > 0,
6453 any substring of the string never match with the
6454 collating symbol. */
6455 if (wcscoll(workp, d) > 0)
6457 workp += length + 1;
6461 /* First, we compare the equivalence class with
6462 the first character of the string.
6463 If it don't match, we add the next character to
6464 the compare buffer in turn. */
6465 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6470 if (dend == end_match_2)
6476 /* add next character to the compare buffer. */
6477 str_buf[i] = TRANSLATE(*d);
6478 str_buf[i+1] = '\0';
6480 match = wcscoll(workp, str_buf);
6483 goto char_set_matched;
6486 /* (str_buf > workp) indicate (str_buf + X > workp),
6487 because for all X (str_buf + X > str_buf).
6488 So we don't need continue this loop. */
6491 /* Otherwise(str_buf < workp),
6492 (str_buf+next_character) may equals (workp).
6493 So we continue this loop. */
6498 workp += length + 1;
6502 /* match with char_range? */
6506 uint32_t collseqval;
6507 const char *collseq = (const char *)
6508 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6510 collseqval = collseq_table_lookup (collseq, c);
6512 for (; workp < p - chars_length ;)
6514 uint32_t start_val, end_val;
6516 /* We already compute the collation sequence value
6517 of the characters (or collating symbols). */
6518 start_val = (uint32_t) *workp++; /* range_start */
6519 end_val = (uint32_t) *workp++; /* range_end */
6521 if (start_val <= collseqval && collseqval <= end_val)
6522 goto char_set_matched;
6528 /* We set range_start_char at str_buf[0], range_end_char
6529 at str_buf[4], and compared char at str_buf[2]. */
6534 for (; workp < p - chars_length ;)
6536 wchar_t *range_start_char, *range_end_char;
6538 /* match if (range_start_char <= c <= range_end_char). */
6540 /* If range_start(or end) < 0, we assume -range_start(end)
6541 is the offset of the collating symbol which is specified
6542 as the character of the range start(end). */
6546 range_start_char = charset_top - (*workp++);
6549 str_buf[0] = *workp++;
6550 range_start_char = str_buf;
6555 range_end_char = charset_top - (*workp++);
6558 str_buf[4] = *workp++;
6559 range_end_char = str_buf + 4;
6562 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6563 wcscoll(str_buf+2, range_end_char) <= 0)
6565 goto char_set_matched;
6569 /* match with char? */
6570 for (; workp < p ; workp++)
6572 goto char_set_matched;
6579 /* Cast to `unsigned' instead of `unsigned char' in case the
6580 bit list is a full 32 bytes long. */
6581 if (c < (unsigned) (*p * BYTEWIDTH)
6582 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6587 if (!not) goto fail;
6588 #undef WORK_BUFFER_SIZE
6590 SET_REGS_MATCHED ();
6596 /* The beginning of a group is represented by start_memory.
6597 The arguments are the register number in the next byte, and the
6598 number of groups inner to this one in the next. The text
6599 matched within the group is recorded (in the internal
6600 registers data structure) under the register number. */
6602 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6603 (long int) *p, (long int) p[1]);
6605 /* Find out if this group can match the empty string. */
6606 p1 = p; /* To send to group_match_null_string_p. */
6608 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6609 REG_MATCH_NULL_STRING_P (reg_info[*p])
6610 = PREFIX(group_match_null_string_p) (&p1, pend, reg_info);
6612 /* Save the position in the string where we were the last time
6613 we were at this open-group operator in case the group is
6614 operated upon by a repetition operator, e.g., with `(a*)*b'
6615 against `ab'; then we want to ignore where we are now in
6616 the string in case this attempt to match fails. */
6617 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6618 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6620 DEBUG_PRINT2 (" old_regstart: %d\n",
6621 POINTER_TO_OFFSET (old_regstart[*p]));
6624 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6626 IS_ACTIVE (reg_info[*p]) = 1;
6627 MATCHED_SOMETHING (reg_info[*p]) = 0;
6629 /* Clear this whenever we change the register activity status. */
6630 set_regs_matched_done = 0;
6632 /* This is the new highest active register. */
6633 highest_active_reg = *p;
6635 /* If nothing was active before, this is the new lowest active
6637 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6638 lowest_active_reg = *p;
6640 /* Move past the register number and inner group count. */
6642 just_past_start_mem = p;
6647 /* The stop_memory opcode represents the end of a group. Its
6648 arguments are the same as start_memory's: the register
6649 number, and the number of inner groups. */
6651 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6652 (long int) *p, (long int) p[1]);
6654 /* We need to save the string position the last time we were at
6655 this close-group operator in case the group is operated
6656 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6657 against `aba'; then we want to ignore where we are now in
6658 the string in case this attempt to match fails. */
6659 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6660 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6662 DEBUG_PRINT2 (" old_regend: %d\n",
6663 POINTER_TO_OFFSET (old_regend[*p]));
6666 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6668 /* This register isn't active anymore. */
6669 IS_ACTIVE (reg_info[*p]) = 0;
6671 /* Clear this whenever we change the register activity status. */
6672 set_regs_matched_done = 0;
6674 /* If this was the only register active, nothing is active
6676 if (lowest_active_reg == highest_active_reg)
6678 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6679 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6682 { /* We must scan for the new highest active register, since
6683 it isn't necessarily one less than now: consider
6684 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6685 new highest active register is 1. */
6687 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6690 /* If we end up at register zero, that means that we saved
6691 the registers as the result of an `on_failure_jump', not
6692 a `start_memory', and we jumped to past the innermost
6693 `stop_memory'. For example, in ((.)*) we save
6694 registers 1 and 2 as a result of the *, but when we pop
6695 back to the second ), we are at the stop_memory 1.
6696 Thus, nothing is active. */
6699 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6700 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6703 highest_active_reg = r;
6706 /* If just failed to match something this time around with a
6707 group that's operated on by a repetition operator, try to
6708 force exit from the ``loop'', and restore the register
6709 information for this group that we had before trying this
6711 if ((!MATCHED_SOMETHING (reg_info[*p])
6712 || just_past_start_mem == p - 1)
6715 boolean is_a_jump_n = false;
6719 switch ((re_opcode_t) *p1++)
6723 case pop_failure_jump:
6724 case maybe_pop_jump:
6726 case dummy_failure_jump:
6727 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6729 p1 += OFFSET_ADDRESS_SIZE;
6737 /* If the next operation is a jump backwards in the pattern
6738 to an on_failure_jump right before the start_memory
6739 corresponding to this stop_memory, exit from the loop
6740 by forcing a failure after pushing on the stack the
6741 on_failure_jump's jump in the pattern, and d. */
6742 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6743 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6744 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6746 /* If this group ever matched anything, then restore
6747 what its registers were before trying this last
6748 failed match, e.g., with `(a*)*b' against `ab' for
6749 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6750 against `aba' for regend[3].
6752 Also restore the registers for inner groups for,
6753 e.g., `((a*)(b*))*' against `aba' (register 3 would
6754 otherwise get trashed). */
6756 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6760 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6762 /* Restore this and inner groups' (if any) registers. */
6763 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6766 regstart[r] = old_regstart[r];
6768 /* xx why this test? */
6769 if (old_regend[r] >= regstart[r])
6770 regend[r] = old_regend[r];
6774 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6775 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6781 /* Move past the register number and the inner group count. */
6786 /* \<digit> has been turned into a `duplicate' command which is
6787 followed by the numeric value of <digit> as the register number. */
6790 register const CHAR_T *d2, *dend2;
6791 int regno = *p++; /* Get which register to match against. */
6792 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6794 /* Can't back reference a group which we've never matched. */
6795 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6798 /* Where in input to try to start matching. */
6799 d2 = regstart[regno];
6801 /* Where to stop matching; if both the place to start and
6802 the place to stop matching are in the same string, then
6803 set to the place to stop, otherwise, for now have to use
6804 the end of the first string. */
6806 dend2 = ((FIRST_STRING_P (regstart[regno])
6807 == FIRST_STRING_P (regend[regno]))
6808 ? regend[regno] : end_match_1);
6811 /* If necessary, advance to next segment in register
6815 if (dend2 == end_match_2) break;
6816 if (dend2 == regend[regno]) break;
6818 /* End of string1 => advance to string2. */
6820 dend2 = regend[regno];
6822 /* At end of register contents => success */
6823 if (d2 == dend2) break;
6825 /* If necessary, advance to next segment in data. */
6828 /* How many characters left in this segment to match. */
6831 /* Want how many consecutive characters we can match in
6832 one shot, so, if necessary, adjust the count. */
6833 if (mcnt > dend2 - d2)
6836 /* Compare that many; failure if mismatch, else move
6839 ? PREFIX(bcmp_translate) (d, d2, mcnt, translate)
6840 : memcmp (d, d2, mcnt*sizeof(UCHAR_T)))
6842 d += mcnt, d2 += mcnt;
6844 /* Do this because we've match some characters. */
6845 SET_REGS_MATCHED ();
6851 /* begline matches the empty string at the beginning of the string
6852 (unless `not_bol' is set in `bufp'), and, if
6853 `newline_anchor' is set, after newlines. */
6855 DEBUG_PRINT1 ("EXECUTING begline.\n");
6857 if (AT_STRINGS_BEG (d))
6859 if (!bufp->not_bol) break;
6861 else if (d[-1] == '\n' && bufp->newline_anchor)
6865 /* In all other cases, we fail. */
6869 /* endline is the dual of begline. */
6871 DEBUG_PRINT1 ("EXECUTING endline.\n");
6873 if (AT_STRINGS_END (d))
6875 if (!bufp->not_eol) break;
6878 /* We have to ``prefetch'' the next character. */
6879 else if ((d == end1 ? *string2 : *d) == '\n'
6880 && bufp->newline_anchor)
6887 /* Match at the very beginning of the data. */
6889 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6890 if (AT_STRINGS_BEG (d))
6895 /* Match at the very end of the data. */
6897 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6898 if (AT_STRINGS_END (d))
6903 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6904 pushes NULL as the value for the string on the stack. Then
6905 `pop_failure_point' will keep the current value for the
6906 string, instead of restoring it. To see why, consider
6907 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6908 then the . fails against the \n. But the next thing we want
6909 to do is match the \n against the \n; if we restored the
6910 string value, we would be back at the foo.
6912 Because this is used only in specific cases, we don't need to
6913 check all the things that `on_failure_jump' does, to make
6914 sure the right things get saved on the stack. Hence we don't
6915 share its code. The only reason to push anything on the
6916 stack at all is that otherwise we would have to change
6917 `anychar's code to do something besides goto fail in this
6918 case; that seems worse than this. */
6919 case on_failure_keep_string_jump:
6920 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6922 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6924 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6926 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6929 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6933 /* Uses of on_failure_jump:
6935 Each alternative starts with an on_failure_jump that points
6936 to the beginning of the next alternative. Each alternative
6937 except the last ends with a jump that in effect jumps past
6938 the rest of the alternatives. (They really jump to the
6939 ending jump of the following alternative, because tensioning
6940 these jumps is a hassle.)
6942 Repeats start with an on_failure_jump that points past both
6943 the repetition text and either the following jump or
6944 pop_failure_jump back to this on_failure_jump. */
6945 case on_failure_jump:
6947 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6949 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6951 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6953 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6956 /* If this on_failure_jump comes right before a group (i.e.,
6957 the original * applied to a group), save the information
6958 for that group and all inner ones, so that if we fail back
6959 to this point, the group's information will be correct.
6960 For example, in \(a*\)*\1, we need the preceding group,
6961 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6963 /* We can't use `p' to check ahead because we push
6964 a failure point to `p + mcnt' after we do this. */
6967 /* We need to skip no_op's before we look for the
6968 start_memory in case this on_failure_jump is happening as
6969 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6971 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6974 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6976 /* We have a new highest active register now. This will
6977 get reset at the start_memory we are about to get to,
6978 but we will have saved all the registers relevant to
6979 this repetition op, as described above. */
6980 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6981 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6982 lowest_active_reg = *(p1 + 1);
6985 DEBUG_PRINT1 (":\n");
6986 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6990 /* A smart repeat ends with `maybe_pop_jump'.
6991 We change it to either `pop_failure_jump' or `jump'. */
6992 case maybe_pop_jump:
6993 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6994 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6996 register UCHAR_T *p2 = p;
6998 /* Compare the beginning of the repeat with what in the
6999 pattern follows its end. If we can establish that there
7000 is nothing that they would both match, i.e., that we
7001 would have to backtrack because of (as in, e.g., `a*a')
7002 then we can change to pop_failure_jump, because we'll
7003 never have to backtrack.
7005 This is not true in the case of alternatives: in
7006 `(a|ab)*' we do need to backtrack to the `ab' alternative
7007 (e.g., if the string was `ab'). But instead of trying to
7008 detect that here, the alternative has put on a dummy
7009 failure point which is what we will end up popping. */
7011 /* Skip over open/close-group commands.
7012 If what follows this loop is a ...+ construct,
7013 look at what begins its body, since we will have to
7014 match at least one of that. */
7018 && ((re_opcode_t) *p2 == stop_memory
7019 || (re_opcode_t) *p2 == start_memory))
7021 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
7022 && (re_opcode_t) *p2 == dummy_failure_jump)
7023 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
7029 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
7030 to the `maybe_finalize_jump' of this case. Examine what
7033 /* If we're at the end of the pattern, we can change. */
7036 /* Consider what happens when matching ":\(.*\)"
7037 against ":/". I don't really understand this code
7039 p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
7042 (" End of pattern: change to `pop_failure_jump'.\n");
7045 else if ((re_opcode_t) *p2 == exactn
7047 || (re_opcode_t) *p2 == exactn_bin
7049 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
7052 = *p2 == (UCHAR_T) endline ? '\n' : p2[2];
7054 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
7056 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
7058 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
7060 p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
7063 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
7065 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
7067 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
7069 (char) p1[3+OFFSET_ADDRESS_SIZE]);
7074 else if ((re_opcode_t) p1[3] == charset
7075 || (re_opcode_t) p1[3] == charset_not)
7077 int not = (re_opcode_t) p1[3] == charset_not;
7079 if (c < (unsigned) (p1[4] * BYTEWIDTH)
7080 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
7083 /* `not' is equal to 1 if c would match, which means
7084 that we can't change to pop_failure_jump. */
7087 p[-3] = (unsigned char) pop_failure_jump;
7088 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
7091 #endif /* not WCHAR */
7094 else if ((re_opcode_t) *p2 == charset)
7096 /* We win if the first character of the loop is not part
7098 if ((re_opcode_t) p1[3] == exactn
7099 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
7100 && (p2[2 + p1[5] / BYTEWIDTH]
7101 & (1 << (p1[5] % BYTEWIDTH)))))
7103 p[-3] = (unsigned char) pop_failure_jump;
7104 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
7107 else if ((re_opcode_t) p1[3] == charset_not)
7110 /* We win if the charset_not inside the loop
7111 lists every character listed in the charset after. */
7112 for (idx = 0; idx < (int) p2[1]; idx++)
7113 if (! (p2[2 + idx] == 0
7114 || (idx < (int) p1[4]
7115 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
7120 p[-3] = (unsigned char) pop_failure_jump;
7121 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
7124 else if ((re_opcode_t) p1[3] == charset)
7127 /* We win if the charset inside the loop
7128 has no overlap with the one after the loop. */
7130 idx < (int) p2[1] && idx < (int) p1[4];
7132 if ((p2[2 + idx] & p1[5 + idx]) != 0)
7135 if (idx == p2[1] || idx == p1[4])
7137 p[-3] = (unsigned char) pop_failure_jump;
7138 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
7142 #endif /* not WCHAR */
7144 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
7145 if ((re_opcode_t) p[-1] != pop_failure_jump)
7147 p[-1] = (UCHAR_T) jump;
7148 DEBUG_PRINT1 (" Match => jump.\n");
7149 goto unconditional_jump;
7151 /* Note fall through. */
7154 /* The end of a simple repeat has a pop_failure_jump back to
7155 its matching on_failure_jump, where the latter will push a
7156 failure point. The pop_failure_jump takes off failure
7157 points put on by this pop_failure_jump's matching
7158 on_failure_jump; we got through the pattern to here from the
7159 matching on_failure_jump, so didn't fail. */
7160 case pop_failure_jump:
7162 /* We need to pass separate storage for the lowest and
7163 highest registers, even though we don't care about the
7164 actual values. Otherwise, we will restore only one
7165 register from the stack, since lowest will == highest in
7166 `pop_failure_point'. */
7167 active_reg_t dummy_low_reg, dummy_high_reg;
7168 UCHAR_T *pdummy = NULL;
7169 const CHAR_T *sdummy = NULL;
7171 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
7172 POP_FAILURE_POINT (sdummy, pdummy,
7173 dummy_low_reg, dummy_high_reg,
7174 reg_dummy, reg_dummy, reg_info_dummy);
7176 /* Note fall through. */
7180 DEBUG_PRINT2 ("\n%p: ", p);
7182 DEBUG_PRINT2 ("\n0x%x: ", p);
7184 /* Note fall through. */
7186 /* Unconditionally jump (without popping any failure points). */
7188 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
7189 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
7190 p += mcnt; /* Do the jump. */
7192 DEBUG_PRINT2 ("(to %p).\n", p);
7194 DEBUG_PRINT2 ("(to 0x%x).\n", p);
7199 /* We need this opcode so we can detect where alternatives end
7200 in `group_match_null_string_p' et al. */
7202 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
7203 goto unconditional_jump;
7206 /* Normally, the on_failure_jump pushes a failure point, which
7207 then gets popped at pop_failure_jump. We will end up at
7208 pop_failure_jump, also, and with a pattern of, say, `a+', we
7209 are skipping over the on_failure_jump, so we have to push
7210 something meaningless for pop_failure_jump to pop. */
7211 case dummy_failure_jump:
7212 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
7213 /* It doesn't matter what we push for the string here. What
7214 the code at `fail' tests is the value for the pattern. */
7215 PUSH_FAILURE_POINT (NULL, NULL, -2);
7216 goto unconditional_jump;
7219 /* At the end of an alternative, we need to push a dummy failure
7220 point in case we are followed by a `pop_failure_jump', because
7221 we don't want the failure point for the alternative to be
7222 popped. For example, matching `(a|ab)*' against `aab'
7223 requires that we match the `ab' alternative. */
7224 case push_dummy_failure:
7225 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
7226 /* See comments just above at `dummy_failure_jump' about the
7228 PUSH_FAILURE_POINT (NULL, NULL, -2);
7231 /* Have to succeed matching what follows at least n times.
7232 After that, handle like `on_failure_jump'. */
7234 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7235 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
7238 /* Originally, this is how many times we HAVE to succeed. */
7242 p += OFFSET_ADDRESS_SIZE;
7243 STORE_NUMBER_AND_INCR (p, mcnt);
7245 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
7248 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
7255 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
7256 p + OFFSET_ADDRESS_SIZE);
7258 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
7259 p + OFFSET_ADDRESS_SIZE);
7263 p[1] = (UCHAR_T) no_op;
7265 p[2] = (UCHAR_T) no_op;
7266 p[3] = (UCHAR_T) no_op;
7273 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7274 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7276 /* Originally, this is how many times we CAN jump. */
7280 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7283 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7286 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7289 goto unconditional_jump;
7291 /* If don't have to jump any more, skip over the rest of command. */
7293 p += 2 * OFFSET_ADDRESS_SIZE;
7298 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7300 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7302 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7304 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7306 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7308 STORE_NUMBER (p1, mcnt);
7313 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7314 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7315 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7316 macro and introducing temporary variables works around the bug. */
7319 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7320 if (AT_WORD_BOUNDARY (d))
7325 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7326 if (AT_WORD_BOUNDARY (d))
7332 boolean prevchar, thischar;
7334 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7335 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7338 prevchar = WORDCHAR_P (d - 1);
7339 thischar = WORDCHAR_P (d);
7340 if (prevchar != thischar)
7347 boolean prevchar, thischar;
7349 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7350 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7353 prevchar = WORDCHAR_P (d - 1);
7354 thischar = WORDCHAR_P (d);
7355 if (prevchar != thischar)
7362 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7363 if (!AT_STRINGS_END (d) && WORDCHAR_P (d)
7364 && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7369 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7370 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7371 && (AT_STRINGS_END (d) || !WORDCHAR_P (d)))
7377 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7378 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7383 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7384 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7389 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7390 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7395 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7400 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7404 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7406 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7408 SET_REGS_MATCHED ();
7412 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7414 goto matchnotsyntax;
7417 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7421 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7423 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7425 SET_REGS_MATCHED ();
7428 #else /* not emacs */
7430 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7432 if (!WORDCHAR_P (d))
7434 SET_REGS_MATCHED ();
7439 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7443 SET_REGS_MATCHED ();
7446 #endif /* not emacs */
7451 continue; /* Successfully executed one pattern command; keep going. */
7454 /* We goto here if a matching operation fails. */
7456 if (!FAIL_STACK_EMPTY ())
7457 { /* A restart point is known. Restore to that state. */
7458 DEBUG_PRINT1 ("\nFAIL:\n");
7459 POP_FAILURE_POINT (d, p,
7460 lowest_active_reg, highest_active_reg,
7461 regstart, regend, reg_info);
7463 /* If this failure point is a dummy, try the next one. */
7467 /* If we failed to the end of the pattern, don't examine *p. */
7471 boolean is_a_jump_n = false;
7473 /* If failed to a backwards jump that's part of a repetition
7474 loop, need to pop this failure point and use the next one. */
7475 switch ((re_opcode_t) *p)
7479 case maybe_pop_jump:
7480 case pop_failure_jump:
7483 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7486 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7488 && (re_opcode_t) *p1 == on_failure_jump))
7496 if (d >= string1 && d <= end1)
7500 break; /* Matching at this starting point really fails. */
7504 goto restore_best_regs;
7508 return -1; /* Failure to match. */
7511 /* Subroutine definitions for re_match_2. */
7514 /* We are passed P pointing to a register number after a start_memory.
7516 Return true if the pattern up to the corresponding stop_memory can
7517 match the empty string, and false otherwise.
7519 If we find the matching stop_memory, sets P to point to one past its number.
7520 Otherwise, sets P to an undefined byte less than or equal to END.
7522 We don't handle duplicates properly (yet). */
7525 PREFIX(group_match_null_string_p) (p, end, reg_info)
7527 PREFIX(register_info_type) *reg_info;
7530 /* Point to after the args to the start_memory. */
7531 UCHAR_T *p1 = *p + 2;
7535 /* Skip over opcodes that can match nothing, and return true or
7536 false, as appropriate, when we get to one that can't, or to the
7537 matching stop_memory. */
7539 switch ((re_opcode_t) *p1)
7541 /* Could be either a loop or a series of alternatives. */
7542 case on_failure_jump:
7544 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7546 /* If the next operation is not a jump backwards in the
7551 /* Go through the on_failure_jumps of the alternatives,
7552 seeing if any of the alternatives cannot match nothing.
7553 The last alternative starts with only a jump,
7554 whereas the rest start with on_failure_jump and end
7555 with a jump, e.g., here is the pattern for `a|b|c':
7557 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7558 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7561 So, we have to first go through the first (n-1)
7562 alternatives and then deal with the last one separately. */
7565 /* Deal with the first (n-1) alternatives, which start
7566 with an on_failure_jump (see above) that jumps to right
7567 past a jump_past_alt. */
7569 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7572 /* `mcnt' holds how many bytes long the alternative
7573 is, including the ending `jump_past_alt' and
7576 if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt -
7577 (1 + OFFSET_ADDRESS_SIZE),
7581 /* Move to right after this alternative, including the
7585 /* Break if it's the beginning of an n-th alternative
7586 that doesn't begin with an on_failure_jump. */
7587 if ((re_opcode_t) *p1 != on_failure_jump)
7590 /* Still have to check that it's not an n-th
7591 alternative that starts with an on_failure_jump. */
7593 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7594 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7597 /* Get to the beginning of the n-th alternative. */
7598 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7603 /* Deal with the last alternative: go back and get number
7604 of the `jump_past_alt' just before it. `mcnt' contains
7605 the length of the alternative. */
7606 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7608 if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt, reg_info))
7611 p1 += mcnt; /* Get past the n-th alternative. */
7617 assert (p1[1] == **p);
7623 if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7626 } /* while p1 < end */
7629 } /* group_match_null_string_p */
7632 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7633 It expects P to be the first byte of a single alternative and END one
7634 byte past the last. The alternative can contain groups. */
7637 PREFIX(alt_match_null_string_p) (p, end, reg_info)
7639 PREFIX(register_info_type) *reg_info;
7646 /* Skip over opcodes that can match nothing, and break when we get
7647 to one that can't. */
7649 switch ((re_opcode_t) *p1)
7652 case on_failure_jump:
7654 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7659 if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7662 } /* while p1 < end */
7665 } /* alt_match_null_string_p */
7668 /* Deals with the ops common to group_match_null_string_p and
7669 alt_match_null_string_p.
7671 Sets P to one after the op and its arguments, if any. */
7674 PREFIX(common_op_match_null_string_p) (p, end, reg_info)
7676 PREFIX(register_info_type) *reg_info;
7683 switch ((re_opcode_t) *p1++)
7703 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7704 ret = PREFIX(group_match_null_string_p) (&p1, end, reg_info);
7706 /* Have to set this here in case we're checking a group which
7707 contains a group and a back reference to it. */
7709 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7710 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7716 /* If this is an optimized succeed_n for zero times, make the jump. */
7718 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7726 /* Get to the number of times to succeed. */
7727 p1 += OFFSET_ADDRESS_SIZE;
7728 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7732 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7733 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7741 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7746 p1 += 2 * OFFSET_ADDRESS_SIZE;
7749 /* All other opcodes mean we cannot match the empty string. */
7755 } /* common_op_match_null_string_p */
7758 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7759 bytes; nonzero otherwise. */
7762 PREFIX(bcmp_translate) (s1, s2, len, translate)
7763 const CHAR_T *s1, *s2;
7765 RE_TRANSLATE_TYPE translate;
7767 register const UCHAR_T *p1 = (const UCHAR_T *) s1;
7768 register const UCHAR_T *p2 = (const UCHAR_T *) s2;
7772 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7773 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7776 if (translate[*p1++] != translate[*p2++]) return 1;
7784 #else /* not INSIDE_RECURSION */
7786 /* Entry points for GNU code. */
7788 /* re_compile_pattern is the GNU regular expression compiler: it
7789 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7790 Returns 0 if the pattern was valid, otherwise an error string.
7792 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7793 are set in BUFP on entry.
7795 We call regex_compile to do the actual compilation. */
7798 re_compile_pattern (pattern, length, bufp)
7799 const char *pattern;
7801 struct re_pattern_buffer *bufp;
7805 /* GNU code is written to assume at least RE_NREGS registers will be set
7806 (and at least one extra will be -1). */
7807 bufp->regs_allocated = REGS_UNALLOCATED;
7809 /* And GNU code determines whether or not to get register information
7810 by passing null for the REGS argument to re_match, etc., not by
7814 /* Match anchors at newline. */
7815 bufp->newline_anchor = 1;
7818 if (MB_CUR_MAX != 1)
7819 ret = wcs_regex_compile (pattern, length, re_syntax_options, bufp);
7822 ret = byte_regex_compile (pattern, length, re_syntax_options, bufp);
7826 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7829 weak_alias (__re_compile_pattern, re_compile_pattern)
7832 /* Entry points compatible with 4.2 BSD regex library. We don't define
7833 them unless specifically requested. */
7835 #if defined _REGEX_RE_COMP || defined _LIBC
7837 /* BSD has one and only one pattern buffer. */
7838 static struct re_pattern_buffer re_comp_buf;
7842 /* Make these definitions weak in libc, so POSIX programs can redefine
7843 these names if they don't use our functions, and still use
7844 regcomp/regexec below without link errors. */
7854 if (!re_comp_buf.buffer)
7855 return gettext ("No previous regular expression");
7859 if (!re_comp_buf.buffer)
7861 re_comp_buf.buffer = (unsigned char *) malloc (200);
7862 if (re_comp_buf.buffer == NULL)
7863 return (char *) gettext (re_error_msgid
7864 + re_error_msgid_idx[(int) REG_ESPACE]);
7865 re_comp_buf.allocated = 200;
7867 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7868 if (re_comp_buf.fastmap == NULL)
7869 return (char *) gettext (re_error_msgid
7870 + re_error_msgid_idx[(int) REG_ESPACE]);
7873 /* Since `re_exec' always passes NULL for the `regs' argument, we
7874 don't need to initialize the pattern buffer fields which affect it. */
7876 /* Match anchors at newlines. */
7877 re_comp_buf.newline_anchor = 1;
7880 if (MB_CUR_MAX != 1)
7881 ret = wcs_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7884 ret = byte_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7889 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7890 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7901 const int len = strlen (s);
7903 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7906 #endif /* _REGEX_RE_COMP */
7908 /* POSIX.2 functions. Don't define these for Emacs. */
7912 /* regcomp takes a regular expression as a string and compiles it.
7914 PREG is a regex_t *. We do not expect any fields to be initialized,
7915 since POSIX says we shouldn't. Thus, we set
7917 `buffer' to the compiled pattern;
7918 `used' to the length of the compiled pattern;
7919 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7920 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7921 RE_SYNTAX_POSIX_BASIC;
7922 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7923 `fastmap' to an allocated space for the fastmap;
7924 `fastmap_accurate' to zero;
7925 `re_nsub' to the number of subexpressions in PATTERN.
7927 PATTERN is the address of the pattern string.
7929 CFLAGS is a series of bits which affect compilation.
7931 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7932 use POSIX basic syntax.
7934 If REG_NEWLINE is set, then . and [^...] don't match newline.
7935 Also, regexec will try a match beginning after every newline.
7937 If REG_ICASE is set, then we considers upper- and lowercase
7938 versions of letters to be equivalent when matching.
7940 If REG_NOSUB is set, then when PREG is passed to regexec, that
7941 routine will report only success or failure, and nothing about the
7944 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7945 the return codes and their meanings.) */
7948 regcomp (preg, pattern, cflags)
7950 const char *pattern;
7955 = (cflags & REG_EXTENDED) ?
7956 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7958 /* regex_compile will allocate the space for the compiled pattern. */
7960 preg->allocated = 0;
7963 /* Try to allocate space for the fastmap. */
7964 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7966 if (cflags & REG_ICASE)
7971 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7972 * sizeof (*(RE_TRANSLATE_TYPE)0));
7973 if (preg->translate == NULL)
7974 return (int) REG_ESPACE;
7976 /* Map uppercase characters to corresponding lowercase ones. */
7977 for (i = 0; i < CHAR_SET_SIZE; i++)
7978 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7981 preg->translate = NULL;
7983 /* If REG_NEWLINE is set, newlines are treated differently. */
7984 if (cflags & REG_NEWLINE)
7985 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7986 syntax &= ~RE_DOT_NEWLINE;
7987 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7988 /* It also changes the matching behavior. */
7989 preg->newline_anchor = 1;
7992 preg->newline_anchor = 0;
7994 preg->no_sub = !!(cflags & REG_NOSUB);
7996 /* POSIX says a null character in the pattern terminates it, so we
7997 can use strlen here in compiling the pattern. */
7999 if (MB_CUR_MAX != 1)
8000 ret = wcs_regex_compile (pattern, strlen (pattern), syntax, preg);
8003 ret = byte_regex_compile (pattern, strlen (pattern), syntax, preg);
8005 /* POSIX doesn't distinguish between an unmatched open-group and an
8006 unmatched close-group: both are REG_EPAREN. */
8007 if (ret == REG_ERPAREN) ret = REG_EPAREN;
8009 if (ret == REG_NOERROR && preg->fastmap)
8011 /* Compute the fastmap now, since regexec cannot modify the pattern
8013 if (re_compile_fastmap (preg) == -2)
8015 /* Some error occurred while computing the fastmap, just forget
8017 free (preg->fastmap);
8018 preg->fastmap = NULL;
8025 weak_alias (__regcomp, regcomp)
8029 /* regexec searches for a given pattern, specified by PREG, in the
8032 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
8033 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
8034 least NMATCH elements, and we set them to the offsets of the
8035 corresponding matched substrings.
8037 EFLAGS specifies `execution flags' which affect matching: if
8038 REG_NOTBOL is set, then ^ does not match at the beginning of the
8039 string; if REG_NOTEOL is set, then $ does not match at the end.
8041 We return 0 if we find a match and REG_NOMATCH if not. */
8044 regexec (preg, string, nmatch, pmatch, eflags)
8045 const regex_t *preg;
8048 regmatch_t pmatch[];
8052 struct re_registers regs;
8053 regex_t private_preg;
8054 int len = strlen (string);
8055 boolean want_reg_info = !preg->no_sub && nmatch > 0;
8057 private_preg = *preg;
8059 private_preg.not_bol = !!(eflags & REG_NOTBOL);
8060 private_preg.not_eol = !!(eflags & REG_NOTEOL);
8062 /* The user has told us exactly how many registers to return
8063 information about, via `nmatch'. We have to pass that on to the
8064 matching routines. */
8065 private_preg.regs_allocated = REGS_FIXED;
8069 regs.num_regs = nmatch;
8070 regs.start = TALLOC (nmatch * 2, regoff_t);
8071 if (regs.start == NULL)
8072 return (int) REG_NOMATCH;
8073 regs.end = regs.start + nmatch;
8076 /* Perform the searching operation. */
8077 ret = re_search (&private_preg, string, len,
8078 /* start: */ 0, /* range: */ len,
8079 want_reg_info ? ®s : (struct re_registers *) 0);
8081 /* Copy the register information to the POSIX structure. */
8088 for (r = 0; r < nmatch; r++)
8090 pmatch[r].rm_so = regs.start[r];
8091 pmatch[r].rm_eo = regs.end[r];
8095 /* If we needed the temporary register info, free the space now. */
8099 /* We want zero return to mean success, unlike `re_search'. */
8100 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
8103 weak_alias (__regexec, regexec)
8107 /* Returns a message corresponding to an error code, ERRCODE, returned
8108 from either regcomp or regexec. We don't use PREG here. */
8111 regerror (errcode, preg, errbuf, errbuf_size)
8113 const regex_t *preg;
8121 || errcode >= (int) (sizeof (re_error_msgid_idx)
8122 / sizeof (re_error_msgid_idx[0])))
8123 /* Only error codes returned by the rest of the code should be passed
8124 to this routine. If we are given anything else, or if other regex
8125 code generates an invalid error code, then the program has a bug.
8126 Dump core so we can fix it. */
8129 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
8131 msg_size = strlen (msg) + 1; /* Includes the null. */
8133 if (errbuf_size != 0)
8135 if (msg_size > errbuf_size)
8137 #if defined HAVE_MEMPCPY || defined _LIBC
8138 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
8140 memcpy (errbuf, msg, errbuf_size - 1);
8141 errbuf[errbuf_size - 1] = 0;
8145 memcpy (errbuf, msg, msg_size);
8151 weak_alias (__regerror, regerror)
8155 /* Free dynamically allocated space used by PREG. */
8161 if (preg->buffer != NULL)
8162 free (preg->buffer);
8163 preg->buffer = NULL;
8165 preg->allocated = 0;
8168 if (preg->fastmap != NULL)
8169 free (preg->fastmap);
8170 preg->fastmap = NULL;
8171 preg->fastmap_accurate = 0;
8173 if (preg->translate != NULL)
8174 free (preg->translate);
8175 preg->translate = NULL;
8178 weak_alias (__regfree, regfree)
8181 #endif /* not emacs */
8183 #endif /* not INSIDE_RECURSION */
8187 #undef STORE_NUMBER_AND_INCR
8188 #undef EXTRACT_NUMBER
8189 #undef EXTRACT_NUMBER_AND_INCR
8191 #undef DEBUG_PRINT_COMPILED_PATTERN
8192 #undef DEBUG_PRINT_DOUBLE_STRING
8194 #undef INIT_FAIL_STACK
8195 #undef RESET_FAIL_STACK
8196 #undef DOUBLE_FAIL_STACK
8197 #undef PUSH_PATTERN_OP
8198 #undef PUSH_FAILURE_POINTER
8199 #undef PUSH_FAILURE_INT
8200 #undef PUSH_FAILURE_ELT
8201 #undef POP_FAILURE_POINTER
8202 #undef POP_FAILURE_INT
8203 #undef POP_FAILURE_ELT
8206 #undef PUSH_FAILURE_POINT
8207 #undef POP_FAILURE_POINT
8209 #undef REG_UNSET_VALUE
8217 #undef INIT_BUF_SIZE
8218 #undef GET_BUFFER_SPACE
8226 #undef EXTEND_BUFFER
8227 #undef GET_UNSIGNED_NUMBER
8228 #undef FREE_STACK_RETURN
8230 # undef POINTER_TO_OFFSET
8231 # undef MATCHING_IN_FRST_STRING
8233 # undef AT_STRINGS_BEG
8234 # undef AT_STRINGS_END
8237 # undef FREE_VARIABLES
8238 # undef NO_HIGHEST_ACTIVE_REG
8239 # undef NO_LOWEST_ACTIVE_REG
8243 # undef COMPILED_BUFFER_VAR
8244 # undef OFFSET_ADDRESS_SIZE
8245 # undef CHAR_CLASS_SIZE
8252 # define DEFINED_ONCE