1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P1003.2/D11.2, except for some of the
4 internationalization features.)
5 Copyright (C) 1993-1999, 2000, 2001 Free Software Foundation, Inc.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined _AIX && !defined REGEX_MALLOC
35 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
36 # define PARAMS(args) args
38 # define PARAMS(args) ()
40 #endif /* Not PARAMS. */
42 #if defined STDC_HEADERS && !defined emacs
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
49 #define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
51 /* For platform which support the ISO C amendement 1 functionality we
52 support user defined character classes. */
53 #if defined _LIBC || WIDE_CHAR_SUPPORT
54 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
59 /* This is for multi byte string support. */
61 # define CHAR_TYPE wchar_t
62 # define US_CHAR_TYPE wchar_t/* unsigned character type */
63 # define COMPILED_BUFFER_VAR wc_buffer
64 # define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
65 # define PUT_CHAR(c) \
67 if (MC_CUR_MAX == 1) \
70 printf ("%C", (wint_t) c); /* Should we use wide stream?? */ \
75 # define CHAR_TYPE char
76 # define US_CHAR_TYPE unsigned char /* unsigned character type */
77 # define COMPILED_BUFFER_VAR bufp->buffer
78 # define OFFSET_ADDRESS_SIZE 2
79 # define PUT_CHAR(c) putchar (c)
80 #endif /* MBS_SUPPORT */
83 /* We have to keep the namespace clean. */
84 # define regfree(preg) __regfree (preg)
85 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
86 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
87 # define regerror(errcode, preg, errbuf, errbuf_size) \
88 __regerror(errcode, preg, errbuf, errbuf_size)
89 # define re_set_registers(bu, re, nu, st, en) \
90 __re_set_registers (bu, re, nu, st, en)
91 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
92 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
93 # define re_match(bufp, string, size, pos, regs) \
94 __re_match (bufp, string, size, pos, regs)
95 # define re_search(bufp, string, size, startpos, range, regs) \
96 __re_search (bufp, string, size, startpos, range, regs)
97 # define re_compile_pattern(pattern, length, bufp) \
98 __re_compile_pattern (pattern, length, bufp)
99 # define re_set_syntax(syntax) __re_set_syntax (syntax)
100 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
101 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
102 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
104 # define btowc __btowc
106 /* We are also using some library internals. */
107 # include <locale/localeinfo.h>
108 # include <locale/elem-hash.h>
109 # include <langinfo.h>
110 # include <locale/coll-lookup.h>
113 /* This is for other GNU distributions with internationalized messages. */
114 #if HAVE_LIBINTL_H || defined _LIBC
115 # include <libintl.h>
118 # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
121 # define gettext(msgid) (msgid)
125 /* This define is so xgettext can find the internationalizable
127 # define gettext_noop(String) String
130 /* The `emacs' switch turns on certain matching commands
131 that make sense only in Emacs. */
138 #else /* not emacs */
140 /* If we are not linking with Emacs proper,
141 we can't use the relocating allocator
142 even if config.h says that we can. */
145 # if defined STDC_HEADERS || defined _LIBC
152 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
153 If nothing else has been done, use the method below. */
154 # ifdef INHIBIT_STRING_HEADER
155 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
156 # if !defined bzero && !defined bcopy
157 # undef INHIBIT_STRING_HEADER
162 /* This is the normal way of making sure we have a bcopy and a bzero.
163 This is used in most programs--a few other programs avoid this
164 by defining INHIBIT_STRING_HEADER. */
165 # ifndef INHIBIT_STRING_HEADER
166 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
170 # define bzero(s, n) (memset (s, '\0', n), (s))
172 # define bzero(s, n) __bzero (s, n)
176 # include <strings.h>
178 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
181 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
186 /* Define the syntax stuff for \<, \>, etc. */
188 /* This must be nonzero for the wordchar and notwordchar pattern
189 commands in re_match_2. */
194 # ifdef SWITCH_ENUM_BUG
195 # define SWITCH_ENUM_CAST(x) ((int)(x))
197 # define SWITCH_ENUM_CAST(x) (x)
200 #endif /* not emacs */
202 #if defined _LIBC || HAVE_LIMITS_H
207 # define MB_LEN_MAX 1
210 /* Get the interface, including the syntax bits. */
213 /* isalpha etc. are used for the character classes. */
216 /* Jim Meyering writes:
218 "... Some ctype macros are valid only for character codes that
219 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
220 using /bin/cc or gcc but without giving an ansi option). So, all
221 ctype uses should be through macros like ISPRINT... If
222 STDC_HEADERS is defined, then autoconf has verified that the ctype
223 macros don't need to be guarded with references to isascii. ...
224 Defining isascii to 1 should let any compiler worth its salt
225 eliminate the && through constant folding."
226 Solaris defines some of these symbols so we must undefine them first. */
228 #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
229 # define IN_CTYPE_DOMAIN(c) 1
231 # define IN_CTYPE_DOMAIN(c) isascii(c)
235 # define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
237 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
240 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
242 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
246 #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
247 #define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
248 #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
249 #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
250 #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
251 #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
252 #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
253 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
254 #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
255 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
258 # define TOLOWER(c) _tolower(c)
260 # define TOLOWER(c) tolower(c)
264 # define NULL (void *)0
267 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
268 since ours (we hope) works properly with all combinations of
269 machines, compilers, `char' and `unsigned char' argument types.
270 (Per Bothner suggested the basic approach.) */
271 #undef SIGN_EXTEND_CHAR
273 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
274 #else /* not __STDC__ */
275 /* As in Harbison and Steele. */
276 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
280 /* How many characters in the character set. */
281 # define CHAR_SET_SIZE 256
285 extern char *re_syntax_table;
287 # else /* not SYNTAX_TABLE */
289 static char re_syntax_table[CHAR_SET_SIZE];
299 bzero (re_syntax_table, sizeof re_syntax_table);
301 for (c = 0; c < CHAR_SET_SIZE; ++c)
303 re_syntax_table[c] = Sword;
305 re_syntax_table['_'] = Sword;
310 # endif /* not SYNTAX_TABLE */
312 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
316 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
317 use `alloca' instead of `malloc'. This is because using malloc in
318 re_search* or re_match* could cause memory leaks when C-g is used in
319 Emacs; also, malloc is slower and causes storage fragmentation. On
320 the other hand, malloc is more portable, and easier to debug.
322 Because we sometimes use alloca, some routines have to be macros,
323 not functions -- `alloca'-allocated space disappears at the end of the
324 function it is called in. */
328 # define REGEX_ALLOCATE malloc
329 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
330 # define REGEX_FREE free
332 #else /* not REGEX_MALLOC */
334 /* Emacs already defines alloca, sometimes. */
337 /* Make alloca work the best possible way. */
339 # define alloca __builtin_alloca
340 # else /* not __GNUC__ */
343 # endif /* HAVE_ALLOCA_H */
344 # endif /* not __GNUC__ */
346 # endif /* not alloca */
348 # define REGEX_ALLOCATE alloca
350 /* Assumes a `char *destination' variable. */
351 # define REGEX_REALLOCATE(source, osize, nsize) \
352 (destination = (char *) alloca (nsize), \
353 memcpy (destination, source, osize))
355 /* No need to do anything to free, after alloca. */
356 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
358 #endif /* not REGEX_MALLOC */
360 /* Define how to allocate the failure stack. */
362 #if defined REL_ALLOC && defined REGEX_MALLOC
364 # define REGEX_ALLOCATE_STACK(size) \
365 r_alloc (&failure_stack_ptr, (size))
366 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
367 r_re_alloc (&failure_stack_ptr, (nsize))
368 # define REGEX_FREE_STACK(ptr) \
369 r_alloc_free (&failure_stack_ptr)
371 #else /* not using relocating allocator */
375 # define REGEX_ALLOCATE_STACK malloc
376 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
377 # define REGEX_FREE_STACK free
379 # else /* not REGEX_MALLOC */
381 # define REGEX_ALLOCATE_STACK alloca
383 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
384 REGEX_REALLOCATE (source, osize, nsize)
385 /* No need to explicitly free anything. */
386 # define REGEX_FREE_STACK(arg)
388 # endif /* not REGEX_MALLOC */
389 #endif /* not using relocating allocator */
392 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
393 `string1' or just past its end. This works if PTR is NULL, which is
395 #define FIRST_STRING_P(ptr) \
396 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
398 /* (Re)Allocate N items of type T using malloc, or fail. */
399 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
400 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
401 #define RETALLOC_IF(addr, n, t) \
402 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
403 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
405 #define BYTEWIDTH 8 /* In bits. */
407 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
411 #define MAX(a, b) ((a) > (b) ? (a) : (b))
412 #define MIN(a, b) ((a) < (b) ? (a) : (b))
414 typedef char boolean;
418 static int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
419 const char *string1, int size1,
420 const char *string2, int size2,
422 struct re_registers *regs,
425 /* These are the command codes that appear in compiled regular
426 expressions. Some opcodes are followed by argument bytes. A
427 command code can specify any interpretation whatsoever for its
428 arguments. Zero bytes may appear in the compiled regular expression. */
434 /* Succeed right away--no more backtracking. */
437 /* Followed by one byte giving n, then by n literal bytes. */
441 /* Same as exactn, but contains binary data. */
445 /* Matches any (more or less) character. */
448 /* Matches any one char belonging to specified set. First
449 following byte is number of bitmap bytes. Then come bytes
450 for a bitmap saying which chars are in. Bits in each byte
451 are ordered low-bit-first. A character is in the set if its
452 bit is 1. A character too large to have a bit in the map is
453 automatically not in the set. */
454 /* ifdef MBS_SUPPORT, following element is length of character
455 classes, length of collating symbols, length of equivalence
456 classes, length of character ranges, and length of characters.
457 Next, character class element, collating symbols elements,
458 equivalence class elements, range elements, and character
460 See regex_compile function. */
463 /* Same parameters as charset, but match any character that is
464 not one of those specified. */
467 /* Start remembering the text that is matched, for storing in a
468 register. Followed by one byte with the register number, in
469 the range 0 to one less than the pattern buffer's re_nsub
470 field. Then followed by one byte with the number of groups
471 inner to this one. (This last has to be part of the
472 start_memory only because we need it in the on_failure_jump
476 /* Stop remembering the text that is matched and store it in a
477 memory register. Followed by one byte with the register
478 number, in the range 0 to one less than `re_nsub' in the
479 pattern buffer, and one byte with the number of inner groups,
480 just like `start_memory'. (We need the number of inner
481 groups here because we don't have any easy way of finding the
482 corresponding start_memory when we're at a stop_memory.) */
485 /* Match a duplicate of something remembered. Followed by one
486 byte containing the register number. */
489 /* Fail unless at beginning of line. */
492 /* Fail unless at end of line. */
495 /* Succeeds if at beginning of buffer (if emacs) or at beginning
496 of string to be matched (if not). */
499 /* Analogously, for end of buffer/string. */
502 /* Followed by two byte relative address to which to jump. */
505 /* Same as jump, but marks the end of an alternative. */
508 /* Followed by two-byte relative address of place to resume at
509 in case of failure. */
510 /* ifdef MBS_SUPPORT, the size of address is 1. */
513 /* Like on_failure_jump, but pushes a placeholder instead of the
514 current string position when executed. */
515 on_failure_keep_string_jump,
517 /* Throw away latest failure point and then jump to following
518 two-byte relative address. */
519 /* ifdef MBS_SUPPORT, the size of address is 1. */
522 /* Change to pop_failure_jump if know won't have to backtrack to
523 match; otherwise change to jump. This is used to jump
524 back to the beginning of a repeat. If what follows this jump
525 clearly won't match what the repeat does, such that we can be
526 sure that there is no use backtracking out of repetitions
527 already matched, then we change it to a pop_failure_jump.
528 Followed by two-byte address. */
529 /* ifdef MBS_SUPPORT, the size of address is 1. */
532 /* Jump to following two-byte address, and push a dummy failure
533 point. This failure point will be thrown away if an attempt
534 is made to use it for a failure. A `+' construct makes this
535 before the first repeat. Also used as an intermediary kind
536 of jump when compiling an alternative. */
537 /* ifdef MBS_SUPPORT, the size of address is 1. */
540 /* Push a dummy failure point and continue. Used at the end of
544 /* Followed by two-byte relative address and two-byte number n.
545 After matching N times, jump to the address upon failure. */
546 /* ifdef MBS_SUPPORT, the size of address is 1. */
549 /* Followed by two-byte relative address, and two-byte number n.
550 Jump to the address N times, then fail. */
551 /* ifdef MBS_SUPPORT, the size of address is 1. */
554 /* Set the following two-byte relative address to the
555 subsequent two-byte number. The address *includes* the two
557 /* ifdef MBS_SUPPORT, the size of address is 1. */
560 wordchar, /* Matches any word-constituent character. */
561 notwordchar, /* Matches any char that is not a word-constituent. */
563 wordbeg, /* Succeeds if at word beginning. */
564 wordend, /* Succeeds if at word end. */
566 wordbound, /* Succeeds if at a word boundary. */
567 notwordbound /* Succeeds if not at a word boundary. */
570 ,before_dot, /* Succeeds if before point. */
571 at_dot, /* Succeeds if at point. */
572 after_dot, /* Succeeds if after point. */
574 /* Matches any character whose syntax is specified. Followed by
575 a byte which contains a syntax code, e.g., Sword. */
578 /* Matches any character whose syntax is not that specified. */
583 /* Common operations on the compiled pattern. */
585 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
586 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
589 # define STORE_NUMBER(destination, number) \
591 *(destination) = (US_CHAR_TYPE)(number); \
594 # define STORE_NUMBER(destination, number) \
596 (destination)[0] = (number) & 0377; \
597 (destination)[1] = (number) >> 8; \
599 #endif /* MBS_SUPPORT */
601 /* Same as STORE_NUMBER, except increment DESTINATION to
602 the byte after where the number is stored. Therefore, DESTINATION
603 must be an lvalue. */
604 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
606 #define STORE_NUMBER_AND_INCR(destination, number) \
608 STORE_NUMBER (destination, number); \
609 (destination) += OFFSET_ADDRESS_SIZE; \
612 /* Put into DESTINATION a number stored in two contiguous bytes starting
614 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
617 # define EXTRACT_NUMBER(destination, source) \
619 (destination) = *(source); \
622 # define EXTRACT_NUMBER(destination, source) \
624 (destination) = *(source) & 0377; \
625 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
630 static void extract_number _RE_ARGS ((int *dest, US_CHAR_TYPE *source));
632 extract_number (dest, source)
634 US_CHAR_TYPE *source;
639 int temp = SIGN_EXTEND_CHAR (*(source + 1));
640 *dest = *source & 0377;
645 # ifndef EXTRACT_MACROS /* To debug the macros. */
646 # undef EXTRACT_NUMBER
647 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
648 # endif /* not EXTRACT_MACROS */
652 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
653 SOURCE must be an lvalue. */
655 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
657 EXTRACT_NUMBER (destination, source); \
658 (source) += OFFSET_ADDRESS_SIZE; \
662 static void extract_number_and_incr _RE_ARGS ((int *destination,
663 US_CHAR_TYPE **source));
665 extract_number_and_incr (destination, source)
667 US_CHAR_TYPE **source;
669 extract_number (destination, *source);
670 *source += OFFSET_ADDRESS_SIZE;
673 # ifndef EXTRACT_MACROS
674 # undef EXTRACT_NUMBER_AND_INCR
675 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
676 extract_number_and_incr (&dest, &src)
677 # endif /* not EXTRACT_MACROS */
681 /* If DEBUG is defined, Regex prints many voluminous messages about what
682 it is doing (if the variable `debug' is nonzero). If linked with the
683 main program in `iregex.c', you can enter patterns and strings
684 interactively. And if linked with the main program in `main.c' and
685 the other test files, you can run the already-written tests. */
689 /* We use standard I/O for debugging. */
692 /* It is useful to test things that ``must'' be true when debugging. */
697 # define DEBUG_STATEMENT(e) e
698 # define DEBUG_PRINT1(x) if (debug) printf (x)
699 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
700 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
701 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
702 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
703 if (debug) print_partial_compiled_pattern (s, e)
704 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
705 if (debug) print_double_string (w, s1, sz1, s2, sz2)
708 /* Print the fastmap in human-readable form. */
711 print_fastmap (fastmap)
714 unsigned was_a_range = 0;
717 while (i < (1 << BYTEWIDTH))
723 while (i < (1 << BYTEWIDTH) && fastmap[i])
739 /* Print a compiled pattern string in human-readable form, starting at
740 the START pointer into it and ending just before the pointer END. */
743 print_partial_compiled_pattern (start, end)
749 US_CHAR_TYPE *p = start;
750 US_CHAR_TYPE *pend = end;
758 /* Loop over pattern commands. */
762 printf ("%td:\t", p - start);
764 printf ("%ld:\t", (long int) (p - start));
767 switch ((re_opcode_t) *p++)
775 printf ("/exactn/%d", mcnt);
787 printf ("/exactn_bin/%d", mcnt);
790 printf("/%lx", (long int) *p++);
794 #endif /* MBS_SUPPORT */
798 printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
803 printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
807 printf ("/duplicate/%ld", (long int) *p++);
820 printf ("/charset [%s",
821 (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
823 length = *workp++; /* the length of char_classes */
824 for (i=0 ; i<length ; i++)
825 printf("[:%lx:]", (long int) *p++);
826 length = *workp++; /* the length of collating_symbol */
827 for (i=0 ; i<length ;)
831 PUT_CHAR((i++,*p++));
835 length = *workp++; /* the length of equivalence_class */
836 for (i=0 ; i<length ;)
840 PUT_CHAR((i++,*p++));
844 length = *workp++; /* the length of char_range */
845 for (i=0 ; i<length ; i++)
847 wchar_t range_start = *p++;
848 wchar_t range_end = *p++;
850 printf("%c-%c", (char) range_start, (char) range_end);
852 printf("%C-%C", (wint_t) range_start, (wint_t) range_end);
854 length = *workp++; /* the length of char */
855 for (i=0 ; i<length ; i++)
859 printf("%C", (wint_t) *p++);
862 register int c, last = -100;
863 register int in_range = 0;
865 printf ("/charset [%s",
866 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
868 assert (p + *p < pend);
870 for (c = 0; c < 256; c++)
872 && (p[1 + (c/8)] & (1 << (c % 8))))
874 /* Are we starting a range? */
875 if (last + 1 == c && ! in_range)
880 /* Have we broken a range? */
881 else if (last + 1 != c && in_range)
899 #endif /* MBS_SUPPORT */
911 case on_failure_jump:
912 extract_number_and_incr (&mcnt, &p);
914 printf ("/on_failure_jump to %td", p + mcnt - start);
916 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
920 case on_failure_keep_string_jump:
921 extract_number_and_incr (&mcnt, &p);
923 printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
925 printf ("/on_failure_keep_string_jump to %ld",
926 (long int) (p + mcnt - start));
930 case dummy_failure_jump:
931 extract_number_and_incr (&mcnt, &p);
933 printf ("/dummy_failure_jump to %td", p + mcnt - start);
935 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
939 case push_dummy_failure:
940 printf ("/push_dummy_failure");
944 extract_number_and_incr (&mcnt, &p);
946 printf ("/maybe_pop_jump to %td", p + mcnt - start);
948 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
952 case pop_failure_jump:
953 extract_number_and_incr (&mcnt, &p);
955 printf ("/pop_failure_jump to %td", p + mcnt - start);
957 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
962 extract_number_and_incr (&mcnt, &p);
964 printf ("/jump_past_alt to %td", p + mcnt - start);
966 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
971 extract_number_and_incr (&mcnt, &p);
973 printf ("/jump to %td", p + mcnt - start);
975 printf ("/jump to %ld", (long int) (p + mcnt - start));
980 extract_number_and_incr (&mcnt, &p);
982 extract_number_and_incr (&mcnt2, &p);
984 printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
986 printf ("/succeed_n to %ld, %d times",
987 (long int) (p1 - start), mcnt2);
992 extract_number_and_incr (&mcnt, &p);
994 extract_number_and_incr (&mcnt2, &p);
995 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
999 extract_number_and_incr (&mcnt, &p);
1001 extract_number_and_incr (&mcnt2, &p);
1003 printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1005 printf ("/set_number_at location %ld to %d",
1006 (long int) (p1 - start), mcnt2);
1011 printf ("/wordbound");
1015 printf ("/notwordbound");
1019 printf ("/wordbeg");
1023 printf ("/wordend");
1028 printf ("/before_dot");
1036 printf ("/after_dot");
1040 printf ("/syntaxspec");
1042 printf ("/%d", mcnt);
1046 printf ("/notsyntaxspec");
1048 printf ("/%d", mcnt);
1053 printf ("/wordchar");
1057 printf ("/notwordchar");
1069 printf ("?%ld", (long int) *(p-1));
1076 printf ("%td:\tend of pattern.\n", p - start);
1078 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1084 print_compiled_pattern (bufp)
1085 struct re_pattern_buffer *bufp;
1087 US_CHAR_TYPE *buffer = (US_CHAR_TYPE*) bufp->buffer;
1089 print_partial_compiled_pattern (buffer, buffer
1090 + bufp->used / sizeof(US_CHAR_TYPE));
1091 printf ("%ld bytes used/%ld bytes allocated.\n",
1092 bufp->used, bufp->allocated);
1094 if (bufp->fastmap_accurate && bufp->fastmap)
1096 printf ("fastmap: ");
1097 print_fastmap (bufp->fastmap);
1101 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1103 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1105 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1106 printf ("can_be_null: %d\t", bufp->can_be_null);
1107 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1108 printf ("no_sub: %d\t", bufp->no_sub);
1109 printf ("not_bol: %d\t", bufp->not_bol);
1110 printf ("not_eol: %d\t", bufp->not_eol);
1111 printf ("syntax: %lx\n", bufp->syntax);
1112 /* Perhaps we should print the translate table? */
1117 print_double_string (where, string1, size1, string2, size2)
1118 const CHAR_TYPE *where;
1119 const CHAR_TYPE *string1;
1120 const CHAR_TYPE *string2;
1130 if (FIRST_STRING_P (where))
1132 for (this_char = where - string1; this_char < size1; this_char++)
1133 PUT_CHAR (string1[this_char]);
1138 for (this_char = where - string2; this_char < size2; this_char++)
1139 PUT_CHAR (string2[this_char]);
1150 #else /* not DEBUG */
1155 # define DEBUG_STATEMENT(e)
1156 # define DEBUG_PRINT1(x)
1157 # define DEBUG_PRINT2(x1, x2)
1158 # define DEBUG_PRINT3(x1, x2, x3)
1159 # define DEBUG_PRINT4(x1, x2, x3, x4)
1160 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1161 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1163 #endif /* not DEBUG */
1166 /* This convert a multibyte string to a wide character string.
1167 And write their correspondances to offset_buffer(see below)
1168 and write whether each wchar_t is binary data to is_binary.
1169 This assume invalid multibyte sequences as binary data.
1170 We assume offset_buffer and is_binary is already allocated
1173 static size_t convert_mbs_to_wcs (CHAR_TYPE *dest, const unsigned char* src,
1174 size_t len, int *offset_buffer,
1177 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1179 const unsigned char* src;
1180 size_t len; /* the length of multibyte string. */
1182 /* It hold correspondances between src(char string) and
1183 dest(wchar_t string) for optimization.
1185 dest = {'X', 'Y', 'Z'}
1186 (each "xxx", "y" and "zz" represent one multibyte character
1187 corresponding to 'X', 'Y' and 'Z'.)
1188 offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1194 wchar_t *pdest = dest;
1195 const unsigned char *psrc = src;
1196 size_t wc_count = 0;
1198 if (MB_CUR_MAX == 1)
1199 { /* We don't need conversion. */
1200 for ( ; wc_count < len ; ++wc_count)
1203 is_binary[wc_count] = FALSE;
1204 offset_buffer[wc_count] = wc_count;
1206 offset_buffer[wc_count] = wc_count;
1210 /* We need conversion. */
1213 size_t mb_remain = len;
1214 size_t mb_count = 0;
1216 /* Initialize the conversion state. */
1217 memset (&mbs, 0, sizeof (mbstate_t));
1219 offset_buffer[0] = 0;
1220 for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1223 consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1226 /* failed to convert. maybe src contains binary data.
1227 So we consume 1 byte manualy. */
1231 is_binary[wc_count] = TRUE;
1234 is_binary[wc_count] = FALSE;
1235 /* In sjis encoding, we use yen sign as escape character in
1236 place of reverse solidus. So we convert 0x5c(yen sign in
1237 sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1238 solidus in UCS2). */
1239 if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1240 *pdest = (wchar_t) *psrc;
1242 offset_buffer[wc_count + 1] = mb_count += consumed;
1249 #endif /* MBS_SUPPORT */
1251 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1252 also be assigned to arbitrarily: each pattern buffer stores its own
1253 syntax, so it can be changed between regex compilations. */
1254 /* This has no initializer because initialized variables in Emacs
1255 become read-only after dumping. */
1256 reg_syntax_t re_syntax_options;
1259 /* Specify the precise syntax of regexps for compilation. This provides
1260 for compatibility for various utilities which historically have
1261 different, incompatible syntaxes.
1263 The argument SYNTAX is a bit mask comprised of the various bits
1264 defined in regex.h. We return the old syntax. */
1267 re_set_syntax (syntax)
1268 reg_syntax_t syntax;
1270 reg_syntax_t ret = re_syntax_options;
1272 re_syntax_options = syntax;
1274 if (syntax & RE_DEBUG)
1276 else if (debug) /* was on but now is not */
1282 weak_alias (__re_set_syntax, re_set_syntax)
1285 /* This table gives an error message for each of the error codes listed
1286 in regex.h. Obviously the order here has to be same as there.
1287 POSIX doesn't require that we do anything for REG_NOERROR,
1288 but why not be nice? */
1290 static const char re_error_msgid[] =
1292 #define REG_NOERROR_IDX 0
1293 gettext_noop ("Success") /* REG_NOERROR */
1295 #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1296 gettext_noop ("No match") /* REG_NOMATCH */
1298 #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1299 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1301 #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1302 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1304 #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1305 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1307 #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1308 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1310 #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1311 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1313 #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1314 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1316 #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1317 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1319 #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1320 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1322 #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1323 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1325 #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1326 gettext_noop ("Invalid range end") /* REG_ERANGE */
1328 #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1329 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1331 #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1332 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1334 #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1335 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1337 #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1338 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1340 #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1341 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1344 static const size_t re_error_msgid_idx[] =
1365 /* Avoiding alloca during matching, to placate r_alloc. */
1367 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1368 searching and matching functions should not call alloca. On some
1369 systems, alloca is implemented in terms of malloc, and if we're
1370 using the relocating allocator routines, then malloc could cause a
1371 relocation, which might (if the strings being searched are in the
1372 ralloc heap) shift the data out from underneath the regexp
1375 Here's another reason to avoid allocation: Emacs
1376 processes input from X in a signal handler; processing X input may
1377 call malloc; if input arrives while a matching routine is calling
1378 malloc, then we're scrod. But Emacs can't just block input while
1379 calling matching routines; then we don't notice interrupts when
1380 they come in. So, Emacs blocks input around all regexp calls
1381 except the matching calls, which it leaves unprotected, in the
1382 faith that they will not malloc. */
1384 /* Normally, this is fine. */
1385 #define MATCH_MAY_ALLOCATE
1387 /* When using GNU C, we are not REALLY using the C alloca, no matter
1388 what config.h may say. So don't take precautions for it. */
1393 /* The match routines may not allocate if (1) they would do it with malloc
1394 and (2) it's not safe for them to use malloc.
1395 Note that if REL_ALLOC is defined, matching would not use malloc for the
1396 failure stack, but we would still use it for the register vectors;
1397 so REL_ALLOC should not affect this. */
1398 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1399 # undef MATCH_MAY_ALLOCATE
1403 /* Failure stack declarations and macros; both re_compile_fastmap and
1404 re_match_2 use a failure stack. These have to be macros because of
1405 REGEX_ALLOCATE_STACK. */
1408 /* Number of failure points for which to initially allocate space
1409 when matching. If this number is exceeded, we allocate more
1410 space, so it is not a hard limit. */
1411 #ifndef INIT_FAILURE_ALLOC
1412 # define INIT_FAILURE_ALLOC 5
1415 /* Roughly the maximum number of failure points on the stack. Would be
1416 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1417 This is a variable only so users of regex can assign to it; we never
1418 change it ourselves. */
1422 # if defined MATCH_MAY_ALLOCATE
1423 /* 4400 was enough to cause a crash on Alpha OSF/1,
1424 whose default stack limit is 2mb. */
1425 long int re_max_failures = 4000;
1427 long int re_max_failures = 2000;
1430 union fail_stack_elt
1432 US_CHAR_TYPE *pointer;
1436 typedef union fail_stack_elt fail_stack_elt_t;
1440 fail_stack_elt_t *stack;
1441 unsigned long int size;
1442 unsigned long int avail; /* Offset of next open position. */
1445 #else /* not INT_IS_16BIT */
1447 # if defined MATCH_MAY_ALLOCATE
1448 /* 4400 was enough to cause a crash on Alpha OSF/1,
1449 whose default stack limit is 2mb. */
1450 int re_max_failures = 4000;
1452 int re_max_failures = 2000;
1455 union fail_stack_elt
1457 US_CHAR_TYPE *pointer;
1461 typedef union fail_stack_elt fail_stack_elt_t;
1465 fail_stack_elt_t *stack;
1467 unsigned avail; /* Offset of next open position. */
1470 #endif /* INT_IS_16BIT */
1472 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1473 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1474 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1477 /* Define macros to initialize and free the failure stack.
1478 Do `return -2' if the alloc fails. */
1480 #ifdef MATCH_MAY_ALLOCATE
1481 # define INIT_FAIL_STACK() \
1483 fail_stack.stack = (fail_stack_elt_t *) \
1484 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1486 if (fail_stack.stack == NULL) \
1489 fail_stack.size = INIT_FAILURE_ALLOC; \
1490 fail_stack.avail = 0; \
1493 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1495 # define INIT_FAIL_STACK() \
1497 fail_stack.avail = 0; \
1500 # define RESET_FAIL_STACK()
1504 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1506 Return 1 if succeeds, and 0 if either ran out of memory
1507 allocating space for it or it was already too large.
1509 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1511 #define DOUBLE_FAIL_STACK(fail_stack) \
1512 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1514 : ((fail_stack).stack = (fail_stack_elt_t *) \
1515 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1516 (fail_stack).size * sizeof (fail_stack_elt_t), \
1517 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1519 (fail_stack).stack == NULL \
1521 : ((fail_stack).size <<= 1, \
1525 /* Push pointer POINTER on FAIL_STACK.
1526 Return 1 if was able to do so and 0 if ran out of memory allocating
1528 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1529 ((FAIL_STACK_FULL () \
1530 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1532 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1535 /* Push a pointer value onto the failure stack.
1536 Assumes the variable `fail_stack'. Probably should only
1537 be called from within `PUSH_FAILURE_POINT'. */
1538 #define PUSH_FAILURE_POINTER(item) \
1539 fail_stack.stack[fail_stack.avail++].pointer = (US_CHAR_TYPE *) (item)
1541 /* This pushes an integer-valued item onto the failure stack.
1542 Assumes the variable `fail_stack'. Probably should only
1543 be called from within `PUSH_FAILURE_POINT'. */
1544 #define PUSH_FAILURE_INT(item) \
1545 fail_stack.stack[fail_stack.avail++].integer = (item)
1547 /* Push a fail_stack_elt_t value onto the failure stack.
1548 Assumes the variable `fail_stack'. Probably should only
1549 be called from within `PUSH_FAILURE_POINT'. */
1550 #define PUSH_FAILURE_ELT(item) \
1551 fail_stack.stack[fail_stack.avail++] = (item)
1553 /* These three POP... operations complement the three PUSH... operations.
1554 All assume that `fail_stack' is nonempty. */
1555 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1556 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1557 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1559 /* Used to omit pushing failure point id's when we're not debugging. */
1561 # define DEBUG_PUSH PUSH_FAILURE_INT
1562 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1564 # define DEBUG_PUSH(item)
1565 # define DEBUG_POP(item_addr)
1569 /* Push the information about the state we will need
1570 if we ever fail back to it.
1572 Requires variables fail_stack, regstart, regend, reg_info, and
1573 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1576 Does `return FAILURE_CODE' if runs out of memory. */
1578 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1580 char *destination; \
1581 /* Must be int, so when we don't save any registers, the arithmetic \
1582 of 0 + -1 isn't done as unsigned. */ \
1583 /* Can't be int, since there is not a shred of a guarantee that int \
1584 is wide enough to hold a value of something to which pointer can \
1586 active_reg_t this_reg; \
1588 DEBUG_STATEMENT (failure_id++); \
1589 DEBUG_STATEMENT (nfailure_points_pushed++); \
1590 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1591 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1592 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1594 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1595 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1597 /* Ensure we have enough space allocated for what we will push. */ \
1598 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1600 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1601 return failure_code; \
1603 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1604 (fail_stack).size); \
1605 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1608 /* Push the info, starting with the registers. */ \
1609 DEBUG_PRINT1 ("\n"); \
1612 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1615 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1616 DEBUG_STATEMENT (num_regs_pushed++); \
1618 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1619 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1621 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1622 PUSH_FAILURE_POINTER (regend[this_reg]); \
1624 DEBUG_PRINT2 (" info: %p\n ", \
1625 reg_info[this_reg].word.pointer); \
1626 DEBUG_PRINT2 (" match_null=%d", \
1627 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1628 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1629 DEBUG_PRINT2 (" matched_something=%d", \
1630 MATCHED_SOMETHING (reg_info[this_reg])); \
1631 DEBUG_PRINT2 (" ever_matched=%d", \
1632 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1633 DEBUG_PRINT1 ("\n"); \
1634 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1637 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1638 PUSH_FAILURE_INT (lowest_active_reg); \
1640 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1641 PUSH_FAILURE_INT (highest_active_reg); \
1643 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1644 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1645 PUSH_FAILURE_POINTER (pattern_place); \
1647 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1648 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1650 DEBUG_PRINT1 ("'\n"); \
1651 PUSH_FAILURE_POINTER (string_place); \
1653 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1654 DEBUG_PUSH (failure_id); \
1657 /* This is the number of items that are pushed and popped on the stack
1658 for each register. */
1659 #define NUM_REG_ITEMS 3
1661 /* Individual items aside from the registers. */
1663 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1665 # define NUM_NONREG_ITEMS 4
1668 /* We push at most this many items on the stack. */
1669 /* We used to use (num_regs - 1), which is the number of registers
1670 this regexp will save; but that was changed to 5
1671 to avoid stack overflow for a regexp with lots of parens. */
1672 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1674 /* We actually push this many items. */
1675 #define NUM_FAILURE_ITEMS \
1677 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1681 /* How many items can still be added to the stack without overflowing it. */
1682 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1685 /* Pops what PUSH_FAIL_STACK pushes.
1687 We restore into the parameters, all of which should be lvalues:
1688 STR -- the saved data position.
1689 PAT -- the saved pattern position.
1690 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1691 REGSTART, REGEND -- arrays of string positions.
1692 REG_INFO -- array of information about each subexpression.
1694 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1695 `pend', `string1', `size1', `string2', and `size2'. */
1696 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1698 DEBUG_STATEMENT (unsigned failure_id;) \
1699 active_reg_t this_reg; \
1700 const US_CHAR_TYPE *string_temp; \
1702 assert (!FAIL_STACK_EMPTY ()); \
1704 /* Remove failure points and point to how many regs pushed. */ \
1705 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1706 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1707 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1709 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1711 DEBUG_POP (&failure_id); \
1712 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1714 /* If the saved string location is NULL, it came from an \
1715 on_failure_keep_string_jump opcode, and we want to throw away the \
1716 saved NULL, thus retaining our current position in the string. */ \
1717 string_temp = POP_FAILURE_POINTER (); \
1718 if (string_temp != NULL) \
1719 str = (const CHAR_TYPE *) string_temp; \
1721 DEBUG_PRINT2 (" Popping string %p: `", str); \
1722 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1723 DEBUG_PRINT1 ("'\n"); \
1725 pat = (US_CHAR_TYPE *) POP_FAILURE_POINTER (); \
1726 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1727 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1729 /* Restore register info. */ \
1730 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1731 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1733 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1734 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1737 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1739 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1741 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1742 DEBUG_PRINT2 (" info: %p\n", \
1743 reg_info[this_reg].word.pointer); \
1745 regend[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER (); \
1746 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1748 regstart[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER ();\
1749 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1753 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1755 reg_info[this_reg].word.integer = 0; \
1756 regend[this_reg] = 0; \
1757 regstart[this_reg] = 0; \
1759 highest_active_reg = high_reg; \
1762 set_regs_matched_done = 0; \
1763 DEBUG_STATEMENT (nfailure_points_popped++); \
1764 } /* POP_FAILURE_POINT */
1767 /* Structure for per-register (a.k.a. per-group) information.
1768 Other register information, such as the
1769 starting and ending positions (which are addresses), and the list of
1770 inner groups (which is a bits list) are maintained in separate
1773 We are making a (strictly speaking) nonportable assumption here: that
1774 the compiler will pack our bit fields into something that fits into
1775 the type of `word', i.e., is something that fits into one item on the
1779 /* Declarations and macros for re_match_2. */
1783 fail_stack_elt_t word;
1786 /* This field is one if this group can match the empty string,
1787 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1788 #define MATCH_NULL_UNSET_VALUE 3
1789 unsigned match_null_string_p : 2;
1790 unsigned is_active : 1;
1791 unsigned matched_something : 1;
1792 unsigned ever_matched_something : 1;
1794 } register_info_type;
1796 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1797 #define IS_ACTIVE(R) ((R).bits.is_active)
1798 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1799 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1802 /* Call this when have matched a real character; it sets `matched' flags
1803 for the subexpressions which we are currently inside. Also records
1804 that those subexprs have matched. */
1805 #define SET_REGS_MATCHED() \
1808 if (!set_regs_matched_done) \
1811 set_regs_matched_done = 1; \
1812 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1814 MATCHED_SOMETHING (reg_info[r]) \
1815 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1822 /* Registers are set to a sentinel when they haven't yet matched. */
1823 static CHAR_TYPE reg_unset_dummy;
1824 #define REG_UNSET_VALUE (®_unset_dummy)
1825 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1827 /* Subroutine declarations and macros for regex_compile. */
1829 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1830 reg_syntax_t syntax,
1831 struct re_pattern_buffer *bufp));
1832 static void store_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc, int arg));
1833 static void store_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1834 int arg1, int arg2));
1835 static void insert_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1836 int arg, US_CHAR_TYPE *end));
1837 static void insert_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1838 int arg1, int arg2, US_CHAR_TYPE *end));
1839 static boolean at_begline_loc_p _RE_ARGS ((const CHAR_TYPE *pattern,
1841 reg_syntax_t syntax));
1842 static boolean at_endline_loc_p _RE_ARGS ((const CHAR_TYPE *p,
1843 const CHAR_TYPE *pend,
1844 reg_syntax_t syntax));
1846 static reg_errcode_t compile_range _RE_ARGS ((CHAR_TYPE range_start,
1847 const CHAR_TYPE **p_ptr,
1848 const CHAR_TYPE *pend,
1850 reg_syntax_t syntax,
1852 CHAR_TYPE *char_set));
1853 static void insert_space _RE_ARGS ((int num, CHAR_TYPE *loc, CHAR_TYPE *end));
1855 static reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
1856 const CHAR_TYPE **p_ptr,
1857 const CHAR_TYPE *pend,
1859 reg_syntax_t syntax,
1861 #endif /* MBS_SUPPORT */
1863 /* Fetch the next character in the uncompiled pattern---translating it
1864 if necessary. Also cast from a signed character in the constant
1865 string passed to us by the user to an unsigned char that we can use
1866 as an array index (in, e.g., `translate'). */
1867 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1868 because it is impossible to allocate 4GB array for some encodings
1869 which have 4 byte character_set like UCS4. */
1872 # define PATFETCH(c) \
1873 do {if (p == pend) return REG_EEND; \
1874 c = (US_CHAR_TYPE) *p++; \
1875 if (translate && (c <= 0xff)) c = (US_CHAR_TYPE) translate[c]; \
1878 # define PATFETCH(c) \
1879 do {if (p == pend) return REG_EEND; \
1880 c = (unsigned char) *p++; \
1881 if (translate) c = (unsigned char) translate[c]; \
1883 # endif /* MBS_SUPPORT */
1886 /* Fetch the next character in the uncompiled pattern, with no
1888 #define PATFETCH_RAW(c) \
1889 do {if (p == pend) return REG_EEND; \
1890 c = (US_CHAR_TYPE) *p++; \
1893 /* Go backwards one character in the pattern. */
1894 #define PATUNFETCH p--
1897 /* If `translate' is non-null, return translate[D], else just D. We
1898 cast the subscript to translate because some data is declared as
1899 `char *', to avoid warnings when a string constant is passed. But
1900 when we use a character as a subscript we must make it unsigned. */
1901 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1902 because it is impossible to allocate 4GB array for some encodings
1903 which have 4 byte character_set like UCS4. */
1906 # define TRANSLATE(d) \
1907 (translate && (sizeof(d) <= 1)? (char) translate[(unsigned char) (d)] : (d))
1909 # define TRANSLATE(d) \
1910 (translate ? (char) translate[(unsigned char) (d)] : (d))
1911 # endif /* MBS_SUPPORT */
1915 /* Macros for outputting the compiled pattern into `buffer'. */
1917 /* If the buffer isn't allocated when it comes in, use this. */
1918 #define INIT_BUF_SIZE (32 * sizeof(US_CHAR_TYPE))
1920 /* Make sure we have at least N more bytes of space in buffer. */
1922 # define GET_BUFFER_SPACE(n) \
1923 while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR \
1924 + (n)*sizeof(CHAR_TYPE)) > bufp->allocated) \
1927 # define GET_BUFFER_SPACE(n) \
1928 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1930 #endif /* MBS_SUPPORT */
1932 /* Make sure we have one more byte of buffer space and then add C to it. */
1933 #define BUF_PUSH(c) \
1935 GET_BUFFER_SPACE (1); \
1936 *b++ = (US_CHAR_TYPE) (c); \
1940 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1941 #define BUF_PUSH_2(c1, c2) \
1943 GET_BUFFER_SPACE (2); \
1944 *b++ = (US_CHAR_TYPE) (c1); \
1945 *b++ = (US_CHAR_TYPE) (c2); \
1949 /* As with BUF_PUSH_2, except for three bytes. */
1950 #define BUF_PUSH_3(c1, c2, c3) \
1952 GET_BUFFER_SPACE (3); \
1953 *b++ = (US_CHAR_TYPE) (c1); \
1954 *b++ = (US_CHAR_TYPE) (c2); \
1955 *b++ = (US_CHAR_TYPE) (c3); \
1958 /* Store a jump with opcode OP at LOC to location TO. We store a
1959 relative address offset by the three bytes the jump itself occupies. */
1960 #define STORE_JUMP(op, loc, to) \
1961 store_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
1963 /* Likewise, for a two-argument jump. */
1964 #define STORE_JUMP2(op, loc, to, arg) \
1965 store_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
1967 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1968 #define INSERT_JUMP(op, loc, to) \
1969 insert_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
1971 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1972 #define INSERT_JUMP2(op, loc, to, arg) \
1973 insert_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
1977 /* This is not an arbitrary limit: the arguments which represent offsets
1978 into the pattern are two bytes long. So if 2^16 bytes turns out to
1979 be too small, many things would have to change. */
1980 /* Any other compiler which, like MSC, has allocation limit below 2^16
1981 bytes will have to use approach similar to what was done below for
1982 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1983 reallocating to 0 bytes. Such thing is not going to work too well.
1984 You have been warned!! */
1985 #if defined _MSC_VER && !defined WIN32
1986 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1987 The REALLOC define eliminates a flurry of conversion warnings,
1988 but is not required. */
1989 # define MAX_BUF_SIZE 65500L
1990 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1992 # define MAX_BUF_SIZE (1L << 16)
1993 # define REALLOC(p,s) realloc ((p), (s))
1996 /* Extend the buffer by twice its current size via realloc and
1997 reset the pointers that pointed into the old block to point to the
1998 correct places in the new one. If extending the buffer results in it
1999 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
2000 #if __BOUNDED_POINTERS__
2001 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2002 # define MOVE_BUFFER_POINTER(P) \
2003 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2004 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
2007 SET_HIGH_BOUND (b); \
2008 SET_HIGH_BOUND (begalt); \
2009 if (fixup_alt_jump) \
2010 SET_HIGH_BOUND (fixup_alt_jump); \
2012 SET_HIGH_BOUND (laststart); \
2013 if (pending_exact) \
2014 SET_HIGH_BOUND (pending_exact); \
2017 # define MOVE_BUFFER_POINTER(P) (P) += incr
2018 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
2022 # define EXTEND_BUFFER() \
2024 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2026 if (bufp->allocated + sizeof(US_CHAR_TYPE) > MAX_BUF_SIZE) \
2028 bufp->allocated <<= 1; \
2029 if (bufp->allocated > MAX_BUF_SIZE) \
2030 bufp->allocated = MAX_BUF_SIZE; \
2031 /* How many characters the new buffer can have? */ \
2032 wchar_count = bufp->allocated / sizeof(US_CHAR_TYPE); \
2033 if (wchar_count == 0) wchar_count = 1; \
2034 /* Truncate the buffer to CHAR_TYPE align. */ \
2035 bufp->allocated = wchar_count * sizeof(US_CHAR_TYPE); \
2036 RETALLOC (COMPILED_BUFFER_VAR, wchar_count, US_CHAR_TYPE); \
2037 bufp->buffer = (char*)COMPILED_BUFFER_VAR; \
2038 if (COMPILED_BUFFER_VAR == NULL) \
2039 return REG_ESPACE; \
2040 /* If the buffer moved, move all the pointers into it. */ \
2041 if (old_buffer != COMPILED_BUFFER_VAR) \
2043 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2044 MOVE_BUFFER_POINTER (b); \
2045 MOVE_BUFFER_POINTER (begalt); \
2046 if (fixup_alt_jump) \
2047 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2049 MOVE_BUFFER_POINTER (laststart); \
2050 if (pending_exact) \
2051 MOVE_BUFFER_POINTER (pending_exact); \
2053 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2056 # define EXTEND_BUFFER() \
2058 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2059 if (bufp->allocated == MAX_BUF_SIZE) \
2061 bufp->allocated <<= 1; \
2062 if (bufp->allocated > MAX_BUF_SIZE) \
2063 bufp->allocated = MAX_BUF_SIZE; \
2064 bufp->buffer = (US_CHAR_TYPE *) REALLOC (COMPILED_BUFFER_VAR, \
2066 if (COMPILED_BUFFER_VAR == NULL) \
2067 return REG_ESPACE; \
2068 /* If the buffer moved, move all the pointers into it. */ \
2069 if (old_buffer != COMPILED_BUFFER_VAR) \
2071 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2072 MOVE_BUFFER_POINTER (b); \
2073 MOVE_BUFFER_POINTER (begalt); \
2074 if (fixup_alt_jump) \
2075 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2077 MOVE_BUFFER_POINTER (laststart); \
2078 if (pending_exact) \
2079 MOVE_BUFFER_POINTER (pending_exact); \
2081 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2083 #endif /* MBS_SUPPORT */
2085 /* Since we have one byte reserved for the register number argument to
2086 {start,stop}_memory, the maximum number of groups we can report
2087 things about is what fits in that byte. */
2088 #define MAX_REGNUM 255
2090 /* But patterns can have more than `MAX_REGNUM' registers. We just
2091 ignore the excess. */
2092 typedef unsigned regnum_t;
2095 /* Macros for the compile stack. */
2097 /* Since offsets can go either forwards or backwards, this type needs to
2098 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
2099 /* int may be not enough when sizeof(int) == 2. */
2100 typedef long pattern_offset_t;
2104 pattern_offset_t begalt_offset;
2105 pattern_offset_t fixup_alt_jump;
2106 pattern_offset_t inner_group_offset;
2107 pattern_offset_t laststart_offset;
2109 } compile_stack_elt_t;
2114 compile_stack_elt_t *stack;
2116 unsigned avail; /* Offset of next open position. */
2117 } compile_stack_type;
2120 #define INIT_COMPILE_STACK_SIZE 32
2122 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
2123 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
2125 /* The next available element. */
2126 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2129 /* Set the bit for character C in a list. */
2130 #define SET_LIST_BIT(c) \
2131 (b[((unsigned char) (c)) / BYTEWIDTH] \
2132 |= 1 << (((unsigned char) c) % BYTEWIDTH))
2135 /* Get the next unsigned number in the uncompiled pattern. */
2136 #define GET_UNSIGNED_NUMBER(num) \
2140 while ('0' <= c && c <= '9') \
2144 num = num * 10 + c - '0'; \
2152 #if defined _LIBC || WIDE_CHAR_SUPPORT
2153 /* The GNU C library provides support for user-defined character classes
2154 and the functions from ISO C amendement 1. */
2155 # ifdef CHARCLASS_NAME_MAX
2156 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2158 /* This shouldn't happen but some implementation might still have this
2159 problem. Use a reasonable default value. */
2160 # define CHAR_CLASS_MAX_LENGTH 256
2164 # define IS_CHAR_CLASS(string) __wctype (string)
2166 # define IS_CHAR_CLASS(string) wctype (string)
2169 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
2171 # define IS_CHAR_CLASS(string) \
2172 (STREQ (string, "alpha") || STREQ (string, "upper") \
2173 || STREQ (string, "lower") || STREQ (string, "digit") \
2174 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
2175 || STREQ (string, "space") || STREQ (string, "print") \
2176 || STREQ (string, "punct") || STREQ (string, "graph") \
2177 || STREQ (string, "cntrl") || STREQ (string, "blank"))
2180 #ifndef MATCH_MAY_ALLOCATE
2182 /* If we cannot allocate large objects within re_match_2_internal,
2183 we make the fail stack and register vectors global.
2184 The fail stack, we grow to the maximum size when a regexp
2186 The register vectors, we adjust in size each time we
2187 compile a regexp, according to the number of registers it needs. */
2189 static fail_stack_type fail_stack;
2191 /* Size with which the following vectors are currently allocated.
2192 That is so we can make them bigger as needed,
2193 but never make them smaller. */
2194 static int regs_allocated_size;
2196 static const char ** regstart, ** regend;
2197 static const char ** old_regstart, ** old_regend;
2198 static const char **best_regstart, **best_regend;
2199 static register_info_type *reg_info;
2200 static const char **reg_dummy;
2201 static register_info_type *reg_info_dummy;
2203 /* Make the register vectors big enough for NUM_REGS registers,
2204 but don't make them smaller. */
2207 regex_grow_registers (num_regs)
2210 if (num_regs > regs_allocated_size)
2212 RETALLOC_IF (regstart, num_regs, const char *);
2213 RETALLOC_IF (regend, num_regs, const char *);
2214 RETALLOC_IF (old_regstart, num_regs, const char *);
2215 RETALLOC_IF (old_regend, num_regs, const char *);
2216 RETALLOC_IF (best_regstart, num_regs, const char *);
2217 RETALLOC_IF (best_regend, num_regs, const char *);
2218 RETALLOC_IF (reg_info, num_regs, register_info_type);
2219 RETALLOC_IF (reg_dummy, num_regs, const char *);
2220 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
2222 regs_allocated_size = num_regs;
2226 #endif /* not MATCH_MAY_ALLOCATE */
2228 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2232 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2233 Returns one of error codes defined in `regex.h', or zero for success.
2235 Assumes the `allocated' (and perhaps `buffer') and `translate'
2236 fields are set in BUFP on entry.
2238 If it succeeds, results are put in BUFP (if it returns an error, the
2239 contents of BUFP are undefined):
2240 `buffer' is the compiled pattern;
2241 `syntax' is set to SYNTAX;
2242 `used' is set to the length of the compiled pattern;
2243 `fastmap_accurate' is zero;
2244 `re_nsub' is the number of subexpressions in PATTERN;
2245 `not_bol' and `not_eol' are zero;
2247 The `fastmap' and `newline_anchor' fields are neither
2248 examined nor set. */
2250 /* Return, freeing storage we allocated. */
2252 # define FREE_STACK_RETURN(value) \
2253 return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2255 # define FREE_STACK_RETURN(value) \
2256 return (free (compile_stack.stack), value)
2257 #endif /* MBS_SUPPORT */
2259 static reg_errcode_t
2261 regex_compile (cpattern, csize, syntax, bufp)
2262 const char *cpattern;
2265 regex_compile (pattern, size, syntax, bufp)
2266 const char *pattern;
2268 #endif /* MBS_SUPPORT */
2269 reg_syntax_t syntax;
2270 struct re_pattern_buffer *bufp;
2272 /* We fetch characters from PATTERN here. Even though PATTERN is
2273 `char *' (i.e., signed), we declare these variables as unsigned, so
2274 they can be reliably used as array indices. */
2275 register US_CHAR_TYPE c, c1;
2278 /* A temporary space to keep wchar_t pattern and compiled pattern. */
2279 CHAR_TYPE *pattern, *COMPILED_BUFFER_VAR;
2281 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
2282 int *mbs_offset = NULL;
2283 /* It hold whether each wchar_t is binary data or not. */
2284 int *is_binary = NULL;
2285 /* A flag whether exactn is handling binary data or not. */
2286 int is_exactn_bin = FALSE;
2287 #endif /* MBS_SUPPORT */
2289 /* A random temporary spot in PATTERN. */
2290 const CHAR_TYPE *p1;
2292 /* Points to the end of the buffer, where we should append. */
2293 register US_CHAR_TYPE *b;
2295 /* Keeps track of unclosed groups. */
2296 compile_stack_type compile_stack;
2298 /* Points to the current (ending) position in the pattern. */
2301 const CHAR_TYPE *pend;
2303 const CHAR_TYPE *p = pattern;
2304 const CHAR_TYPE *pend = pattern + size;
2305 #endif /* MBS_SUPPORT */
2307 /* How to translate the characters in the pattern. */
2308 RE_TRANSLATE_TYPE translate = bufp->translate;
2310 /* Address of the count-byte of the most recently inserted `exactn'
2311 command. This makes it possible to tell if a new exact-match
2312 character can be added to that command or if the character requires
2313 a new `exactn' command. */
2314 US_CHAR_TYPE *pending_exact = 0;
2316 /* Address of start of the most recently finished expression.
2317 This tells, e.g., postfix * where to find the start of its
2318 operand. Reset at the beginning of groups and alternatives. */
2319 US_CHAR_TYPE *laststart = 0;
2321 /* Address of beginning of regexp, or inside of last group. */
2322 US_CHAR_TYPE *begalt;
2324 /* Place in the uncompiled pattern (i.e., the {) to
2325 which to go back if the interval is invalid. */
2327 const US_CHAR_TYPE *beg_interval;
2329 const char *beg_interval;
2330 #endif /* MBS_SUPPORT */
2332 /* Address of the place where a forward jump should go to the end of
2333 the containing expression. Each alternative of an `or' -- except the
2334 last -- ends with a forward jump of this sort. */
2335 US_CHAR_TYPE *fixup_alt_jump = 0;
2337 /* Counts open-groups as they are encountered. Remembered for the
2338 matching close-group on the compile stack, so the same register
2339 number is put in the stop_memory as the start_memory. */
2340 regnum_t regnum = 0;
2343 /* Initialize the wchar_t PATTERN and offset_buffer. */
2344 p = pend = pattern = TALLOC(csize, CHAR_TYPE);
2345 mbs_offset = TALLOC(csize + 1, int);
2346 is_binary = TALLOC(csize + 1, int);
2347 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2349 if (pattern) free(pattern);
2350 if (mbs_offset) free(mbs_offset);
2351 if (is_binary) free(is_binary);
2354 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2358 if (pattern) free(pattern);
2359 if (mbs_offset) free(mbs_offset);
2360 if (is_binary) free(is_binary);
2366 DEBUG_PRINT1 ("\nCompiling pattern: ");
2369 unsigned debug_count;
2371 for (debug_count = 0; debug_count < size; debug_count++)
2372 PUT_CHAR (pattern[debug_count]);
2377 /* Initialize the compile stack. */
2378 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2379 if (compile_stack.stack == NULL)
2382 if (pattern) free(pattern);
2383 if (mbs_offset) free(mbs_offset);
2384 if (is_binary) free(is_binary);
2389 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2390 compile_stack.avail = 0;
2392 /* Initialize the pattern buffer. */
2393 bufp->syntax = syntax;
2394 bufp->fastmap_accurate = 0;
2395 bufp->not_bol = bufp->not_eol = 0;
2397 /* Set `used' to zero, so that if we return an error, the pattern
2398 printer (for debugging) will think there's no pattern. We reset it
2402 /* Always count groups, whether or not bufp->no_sub is set. */
2405 #if !defined emacs && !defined SYNTAX_TABLE
2406 /* Initialize the syntax table. */
2407 init_syntax_once ();
2410 if (bufp->allocated == 0)
2413 { /* If zero allocated, but buffer is non-null, try to realloc
2414 enough space. This loses if buffer's address is bogus, but
2415 that is the user's responsibility. */
2417 /* Free bufp->buffer and allocate an array for wchar_t pattern
2420 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(US_CHAR_TYPE),
2423 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, US_CHAR_TYPE);
2424 #endif /* MBS_SUPPORT */
2427 { /* Caller did not allocate a buffer. Do it for them. */
2428 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(US_CHAR_TYPE),
2432 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2434 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2435 #endif /* MBS_SUPPORT */
2436 bufp->allocated = INIT_BUF_SIZE;
2440 COMPILED_BUFFER_VAR = (US_CHAR_TYPE*) bufp->buffer;
2443 begalt = b = COMPILED_BUFFER_VAR;
2445 /* Loop through the uncompiled pattern until we're at the end. */
2454 if ( /* If at start of pattern, it's an operator. */
2456 /* If context independent, it's an operator. */
2457 || syntax & RE_CONTEXT_INDEP_ANCHORS
2458 /* Otherwise, depends on what's come before. */
2459 || at_begline_loc_p (pattern, p, syntax))
2469 if ( /* If at end of pattern, it's an operator. */
2471 /* If context independent, it's an operator. */
2472 || syntax & RE_CONTEXT_INDEP_ANCHORS
2473 /* Otherwise, depends on what's next. */
2474 || at_endline_loc_p (p, pend, syntax))
2484 if ((syntax & RE_BK_PLUS_QM)
2485 || (syntax & RE_LIMITED_OPS))
2489 /* If there is no previous pattern... */
2492 if (syntax & RE_CONTEXT_INVALID_OPS)
2493 FREE_STACK_RETURN (REG_BADRPT);
2494 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2499 /* Are we optimizing this jump? */
2500 boolean keep_string_p = false;
2502 /* 1 means zero (many) matches is allowed. */
2503 char zero_times_ok = 0, many_times_ok = 0;
2505 /* If there is a sequence of repetition chars, collapse it
2506 down to just one (the right one). We can't combine
2507 interval operators with these because of, e.g., `a{2}*',
2508 which should only match an even number of `a's. */
2512 zero_times_ok |= c != '+';
2513 many_times_ok |= c != '?';
2521 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2524 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2526 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2529 if (!(c1 == '+' || c1 == '?'))
2544 /* If we get here, we found another repeat character. */
2547 /* Star, etc. applied to an empty pattern is equivalent
2548 to an empty pattern. */
2552 /* Now we know whether or not zero matches is allowed
2553 and also whether or not two or more matches is allowed. */
2555 { /* More than one repetition is allowed, so put in at the
2556 end a backward relative jump from `b' to before the next
2557 jump we're going to put in below (which jumps from
2558 laststart to after this jump).
2560 But if we are at the `*' in the exact sequence `.*\n',
2561 insert an unconditional jump backwards to the .,
2562 instead of the beginning of the loop. This way we only
2563 push a failure point once, instead of every time
2564 through the loop. */
2565 assert (p - 1 > pattern);
2567 /* Allocate the space for the jump. */
2568 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2570 /* We know we are not at the first character of the pattern,
2571 because laststart was nonzero. And we've already
2572 incremented `p', by the way, to be the character after
2573 the `*'. Do we have to do something analogous here
2574 for null bytes, because of RE_DOT_NOT_NULL? */
2575 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2577 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2578 && !(syntax & RE_DOT_NEWLINE))
2579 { /* We have .*\n. */
2580 STORE_JUMP (jump, b, laststart);
2581 keep_string_p = true;
2584 /* Anything else. */
2585 STORE_JUMP (maybe_pop_jump, b, laststart -
2586 (1 + OFFSET_ADDRESS_SIZE));
2588 /* We've added more stuff to the buffer. */
2589 b += 1 + OFFSET_ADDRESS_SIZE;
2592 /* On failure, jump from laststart to b + 3, which will be the
2593 end of the buffer after this jump is inserted. */
2594 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2596 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2597 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2599 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2601 b += 1 + OFFSET_ADDRESS_SIZE;
2605 /* At least one repetition is required, so insert a
2606 `dummy_failure_jump' before the initial
2607 `on_failure_jump' instruction of the loop. This
2608 effects a skip over that instruction the first time
2609 we hit that loop. */
2610 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2611 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2612 2 + 2 * OFFSET_ADDRESS_SIZE);
2613 b += 1 + OFFSET_ADDRESS_SIZE;
2627 boolean had_char_class = false;
2629 CHAR_TYPE range_start = 0xffffffff;
2631 unsigned int range_start = 0xffffffff;
2633 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2636 /* We assume a charset(_not) structure as a wchar_t array.
2637 charset[0] = (re_opcode_t) charset(_not)
2638 charset[1] = l (= length of char_classes)
2639 charset[2] = m (= length of collating_symbols)
2640 charset[3] = n (= length of equivalence_classes)
2641 charset[4] = o (= length of char_ranges)
2642 charset[5] = p (= length of chars)
2644 charset[6] = char_class (wctype_t)
2646 charset[l+5] = char_class (wctype_t)
2648 charset[l+6] = collating_symbol (wchar_t)
2650 charset[l+m+5] = collating_symbol (wchar_t)
2651 ifdef _LIBC we use the index if
2652 _NL_COLLATE_SYMB_EXTRAMB instead of
2655 charset[l+m+6] = equivalence_classes (wchar_t)
2657 charset[l+m+n+5] = equivalence_classes (wchar_t)
2658 ifdef _LIBC we use the index in
2659 _NL_COLLATE_WEIGHT instead of
2662 charset[l+m+n+6] = range_start
2663 charset[l+m+n+7] = range_end
2665 charset[l+m+n+2o+4] = range_start
2666 charset[l+m+n+2o+5] = range_end
2667 ifdef _LIBC we use the value looked up
2668 in _NL_COLLATE_COLLSEQ instead of
2671 charset[l+m+n+2o+6] = char
2673 charset[l+m+n+2o+p+5] = char
2677 /* We need at least 6 spaces: the opcode, the length of
2678 char_classes, the length of collating_symbols, the length of
2679 equivalence_classes, the length of char_ranges, the length of
2681 GET_BUFFER_SPACE (6);
2683 /* Save b as laststart. And We use laststart as the pointer
2684 to the first element of the charset here.
2685 In other words, laststart[i] indicates charset[i]. */
2688 /* We test `*p == '^' twice, instead of using an if
2689 statement, so we only need one BUF_PUSH. */
2690 BUF_PUSH (*p == '^' ? charset_not : charset);
2694 /* Push the length of char_classes, the length of
2695 collating_symbols, the length of equivalence_classes, the
2696 length of char_ranges and the length of chars. */
2697 BUF_PUSH_3 (0, 0, 0);
2700 /* Remember the first position in the bracket expression. */
2703 /* charset_not matches newline according to a syntax bit. */
2704 if ((re_opcode_t) b[-6] == charset_not
2705 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2708 laststart[5]++; /* Update the length of characters */
2711 /* Read in characters and ranges, setting map bits. */
2714 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2718 /* \ might escape characters inside [...] and [^...]. */
2719 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2721 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2725 laststart[5]++; /* Update the length of chars */
2730 /* Could be the end of the bracket expression. If it's
2731 not (i.e., when the bracket expression is `[]' so
2732 far), the ']' character bit gets set way below. */
2733 if (c == ']' && p != p1 + 1)
2736 /* Look ahead to see if it's a range when the last thing
2737 was a character class. */
2738 if (had_char_class && c == '-' && *p != ']')
2739 FREE_STACK_RETURN (REG_ERANGE);
2741 /* Look ahead to see if it's a range when the last thing
2742 was a character: if this is a hyphen not at the
2743 beginning or the end of a list, then it's the range
2746 && !(p - 2 >= pattern && p[-2] == '[')
2747 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2751 /* Allocate the space for range_start and range_end. */
2752 GET_BUFFER_SPACE (2);
2753 /* Update the pointer to indicate end of buffer. */
2755 ret = compile_range (range_start, &p, pend, translate,
2756 syntax, b, laststart);
2757 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2758 range_start = 0xffffffff;
2760 else if (p[0] == '-' && p[1] != ']')
2761 { /* This handles ranges made up of characters only. */
2764 /* Move past the `-'. */
2766 /* Allocate the space for range_start and range_end. */
2767 GET_BUFFER_SPACE (2);
2768 /* Update the pointer to indicate end of buffer. */
2770 ret = compile_range (c, &p, pend, translate, syntax, b,
2772 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2773 range_start = 0xffffffff;
2776 /* See if we're at the beginning of a possible character
2778 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2779 { /* Leave room for the null. */
2780 char str[CHAR_CLASS_MAX_LENGTH + 1];
2785 /* If pattern is `[[:'. */
2786 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2791 if ((c == ':' && *p == ']') || p == pend)
2793 if (c1 < CHAR_CLASS_MAX_LENGTH)
2796 /* This is in any case an invalid class name. */
2801 /* If isn't a word bracketed by `[:' and `:]':
2802 undo the ending character, the letters, and leave
2803 the leading `:' and `[' (but store them as character). */
2804 if (c == ':' && *p == ']')
2807 /* Query the character class as wctype_t. */
2808 wt = IS_CHAR_CLASS (str);
2810 FREE_STACK_RETURN (REG_ECTYPE);
2812 /* Throw away the ] at the end of the character
2816 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2818 /* Allocate the space for character class. */
2819 GET_BUFFER_SPACE(1);
2820 /* Update the pointer to indicate end of buffer. */
2822 /* Move data which follow character classes
2823 not to violate the data. */
2824 insert_space(1, laststart+6, b-1);
2825 /* Store the character class. */
2826 laststart[6] = (CHAR_TYPE) wt;
2827 laststart[1]++; /* Update length of char_classes */
2829 had_char_class = true;
2838 laststart[5] += 2; /* Update the length of characters */
2840 had_char_class = false;
2843 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2846 CHAR_TYPE str[128]; /* Should be large enough. */
2847 CHAR_TYPE delim = *p; /* '=' or '.' */
2850 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2855 /* If pattern is `[[=' or '[[.'. */
2856 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2861 if ((c == delim && *p == ']') || p == pend)
2863 if (c1 < sizeof (str) - 1)
2866 /* This is in any case an invalid class name. */
2871 if (c == delim && *p == ']' && str[0] != '\0')
2873 unsigned int i, offset;
2874 /* If we have no collation data we use the default
2875 collation in which each character is in a class
2876 by itself. It also means that ASCII is the
2877 character set and therefore we cannot have character
2878 with more than one byte in the multibyte
2881 /* If not defined _LIBC, we push the name and
2882 `\0' for the sake of matching performance. */
2883 int datasize = c1 + 1;
2891 FREE_STACK_RETURN (REG_ECOLLATE);
2896 const int32_t *table;
2897 const int32_t *weights;
2898 const int32_t *extra;
2899 const int32_t *indirect;
2902 /* This #include defines a local function! */
2903 # include <locale/weightwc.h>
2907 /* We push the index for equivalence class. */
2910 table = (const int32_t *)
2911 _NL_CURRENT (LC_COLLATE,
2912 _NL_COLLATE_TABLEWC);
2913 weights = (const int32_t *)
2914 _NL_CURRENT (LC_COLLATE,
2915 _NL_COLLATE_WEIGHTWC);
2916 extra = (const int32_t *)
2917 _NL_CURRENT (LC_COLLATE,
2918 _NL_COLLATE_EXTRAWC);
2919 indirect = (const int32_t *)
2920 _NL_CURRENT (LC_COLLATE,
2921 _NL_COLLATE_INDIRECTWC);
2923 idx = findidx ((const wint_t**)&cp);
2924 if (idx == 0 || cp < (wint_t*) str + c1)
2925 /* This is no valid character. */
2926 FREE_STACK_RETURN (REG_ECOLLATE);
2928 str[0] = (wchar_t)idx;
2930 else /* delim == '.' */
2932 /* We push collation sequence value
2933 for collating symbol. */
2935 const int32_t *symb_table;
2936 const unsigned char *extra;
2943 /* We have to convert the name to a single-byte
2944 string. This is possible since the names
2945 consist of ASCII characters and the internal
2946 representation is UCS4. */
2947 for (i = 0; i < c1; ++i)
2948 char_str[i] = str[i];
2951 _NL_CURRENT_WORD (LC_COLLATE,
2952 _NL_COLLATE_SYMB_HASH_SIZEMB);
2953 symb_table = (const int32_t *)
2954 _NL_CURRENT (LC_COLLATE,
2955 _NL_COLLATE_SYMB_TABLEMB);
2956 extra = (const unsigned char *)
2957 _NL_CURRENT (LC_COLLATE,
2958 _NL_COLLATE_SYMB_EXTRAMB);
2960 /* Locate the character in the hashing table. */
2961 hash = elem_hash (char_str, c1);
2964 elem = hash % table_size;
2965 second = hash % (table_size - 2);
2966 while (symb_table[2 * elem] != 0)
2968 /* First compare the hashing value. */
2969 if (symb_table[2 * elem] == hash
2970 && c1 == extra[symb_table[2 * elem + 1]]
2972 &extra[symb_table[2 * elem + 1]
2975 /* Yep, this is the entry. */
2976 idx = symb_table[2 * elem + 1];
2977 idx += 1 + extra[idx];
2985 if (symb_table[2 * elem] != 0)
2987 /* Compute the index of the byte sequence
2989 idx += 1 + extra[idx];
2990 /* Adjust for the alignment. */
2991 idx = (idx + 3) & ~4;
2993 str[0] = (wchar_t) &extra[idx + 4];
2995 else if (symb_table[2 * elem] == 0 && c1 == 1)
2997 /* No valid character. Match it as a
2998 single byte character. */
2999 had_char_class = false;
3001 /* Update the length of characters */
3003 range_start = str[0];
3005 /* Throw away the ] at the end of the
3006 collating symbol. */
3008 /* exit from the switch block. */
3012 FREE_STACK_RETURN (REG_ECOLLATE);
3017 /* Throw away the ] at the end of the equivalence
3018 class (or collating symbol). */
3021 /* Allocate the space for the equivalence class
3022 (or collating symbol) (and '\0' if needed). */
3023 GET_BUFFER_SPACE(datasize);
3024 /* Update the pointer to indicate end of buffer. */
3028 { /* equivalence class */
3029 /* Calculate the offset of char_ranges,
3030 which is next to equivalence_classes. */
3031 offset = laststart[1] + laststart[2]
3034 insert_space(datasize, laststart + offset, b - 1);
3036 /* Write the equivalence_class and \0. */
3037 for (i = 0 ; i < datasize ; i++)
3038 laststart[offset + i] = str[i];
3040 /* Update the length of equivalence_classes. */
3041 laststart[3] += datasize;
3042 had_char_class = true;
3044 else /* delim == '.' */
3045 { /* collating symbol */
3046 /* Calculate the offset of the equivalence_classes,
3047 which is next to collating_symbols. */
3048 offset = laststart[1] + laststart[2] + 6;
3049 /* Insert space and write the collationg_symbol
3051 insert_space(datasize, laststart + offset, b-1);
3052 for (i = 0 ; i < datasize ; i++)
3053 laststart[offset + i] = str[i];
3055 /* In re_match_2_internal if range_start < -1, we
3056 assume -range_start is the offset of the
3057 collating symbol which is specified as
3058 the character of the range start. So we assign
3059 -(laststart[1] + laststart[2] + 6) to
3061 range_start = -(laststart[1] + laststart[2] + 6);
3062 /* Update the length of collating_symbol. */
3063 laststart[2] += datasize;
3064 had_char_class = false;
3074 laststart[5] += 2; /* Update the length of characters */
3075 range_start = delim;
3076 had_char_class = false;
3081 had_char_class = false;
3083 laststart[5]++; /* Update the length of characters */
3088 #else /* not MBS_SUPPORT */
3089 /* Ensure that we have enough space to push a charset: the
3090 opcode, the length count, and the bitset; 34 bytes in all. */
3091 GET_BUFFER_SPACE (34);
3095 /* We test `*p == '^' twice, instead of using an if
3096 statement, so we only need one BUF_PUSH. */
3097 BUF_PUSH (*p == '^' ? charset_not : charset);
3101 /* Remember the first position in the bracket expression. */
3104 /* Push the number of bytes in the bitmap. */
3105 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3107 /* Clear the whole map. */
3108 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3110 /* charset_not matches newline according to a syntax bit. */
3111 if ((re_opcode_t) b[-2] == charset_not
3112 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3113 SET_LIST_BIT ('\n');
3115 /* Read in characters and ranges, setting map bits. */
3118 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3122 /* \ might escape characters inside [...] and [^...]. */
3123 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3125 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3133 /* Could be the end of the bracket expression. If it's
3134 not (i.e., when the bracket expression is `[]' so
3135 far), the ']' character bit gets set way below. */
3136 if (c == ']' && p != p1 + 1)
3139 /* Look ahead to see if it's a range when the last thing
3140 was a character class. */
3141 if (had_char_class && c == '-' && *p != ']')
3142 FREE_STACK_RETURN (REG_ERANGE);
3144 /* Look ahead to see if it's a range when the last thing
3145 was a character: if this is a hyphen not at the
3146 beginning or the end of a list, then it's the range
3149 && !(p - 2 >= pattern && p[-2] == '[')
3150 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3154 = compile_range (range_start, &p, pend, translate,
3156 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3157 range_start = 0xffffffff;
3160 else if (p[0] == '-' && p[1] != ']')
3161 { /* This handles ranges made up of characters only. */
3164 /* Move past the `-'. */
3167 ret = compile_range (c, &p, pend, translate, syntax, b);
3168 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3169 range_start = 0xffffffff;
3172 /* See if we're at the beginning of a possible character
3175 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3176 { /* Leave room for the null. */
3177 char str[CHAR_CLASS_MAX_LENGTH + 1];
3182 /* If pattern is `[[:'. */
3183 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3188 if ((c == ':' && *p == ']') || p == pend)
3190 if (c1 < CHAR_CLASS_MAX_LENGTH)
3193 /* This is in any case an invalid class name. */
3198 /* If isn't a word bracketed by `[:' and `:]':
3199 undo the ending character, the letters, and leave
3200 the leading `:' and `[' (but set bits for them). */
3201 if (c == ':' && *p == ']')
3203 # if defined _LIBC || WIDE_CHAR_SUPPORT
3204 boolean is_lower = STREQ (str, "lower");
3205 boolean is_upper = STREQ (str, "upper");
3209 wt = IS_CHAR_CLASS (str);
3211 FREE_STACK_RETURN (REG_ECTYPE);
3213 /* Throw away the ] at the end of the character
3217 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3219 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3222 if (__iswctype (__btowc (ch), wt))
3225 if (iswctype (btowc (ch), wt))
3229 if (translate && (is_upper || is_lower)
3230 && (ISUPPER (ch) || ISLOWER (ch)))
3234 had_char_class = true;
3237 boolean is_alnum = STREQ (str, "alnum");
3238 boolean is_alpha = STREQ (str, "alpha");
3239 boolean is_blank = STREQ (str, "blank");
3240 boolean is_cntrl = STREQ (str, "cntrl");
3241 boolean is_digit = STREQ (str, "digit");
3242 boolean is_graph = STREQ (str, "graph");
3243 boolean is_lower = STREQ (str, "lower");
3244 boolean is_print = STREQ (str, "print");
3245 boolean is_punct = STREQ (str, "punct");
3246 boolean is_space = STREQ (str, "space");
3247 boolean is_upper = STREQ (str, "upper");
3248 boolean is_xdigit = STREQ (str, "xdigit");
3250 if (!IS_CHAR_CLASS (str))
3251 FREE_STACK_RETURN (REG_ECTYPE);
3253 /* Throw away the ] at the end of the character
3257 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3259 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3261 /* This was split into 3 if's to
3262 avoid an arbitrary limit in some compiler. */
3263 if ( (is_alnum && ISALNUM (ch))
3264 || (is_alpha && ISALPHA (ch))
3265 || (is_blank && ISBLANK (ch))
3266 || (is_cntrl && ISCNTRL (ch)))
3268 if ( (is_digit && ISDIGIT (ch))
3269 || (is_graph && ISGRAPH (ch))
3270 || (is_lower && ISLOWER (ch))
3271 || (is_print && ISPRINT (ch)))
3273 if ( (is_punct && ISPUNCT (ch))
3274 || (is_space && ISSPACE (ch))
3275 || (is_upper && ISUPPER (ch))
3276 || (is_xdigit && ISXDIGIT (ch)))
3278 if ( translate && (is_upper || is_lower)
3279 && (ISUPPER (ch) || ISLOWER (ch)))
3282 had_char_class = true;
3283 # endif /* libc || wctype.h */
3293 had_char_class = false;
3296 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3298 unsigned char str[MB_LEN_MAX + 1];
3301 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3307 /* If pattern is `[[='. */
3308 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3313 if ((c == '=' && *p == ']') || p == pend)
3315 if (c1 < MB_LEN_MAX)
3318 /* This is in any case an invalid class name. */
3323 if (c == '=' && *p == ']' && str[0] != '\0')
3325 /* If we have no collation data we use the default
3326 collation in which each character is in a class
3327 by itself. It also means that ASCII is the
3328 character set and therefore we cannot have character
3329 with more than one byte in the multibyte
3336 FREE_STACK_RETURN (REG_ECOLLATE);
3338 /* Throw away the ] at the end of the equivalence
3342 /* Set the bit for the character. */
3343 SET_LIST_BIT (str[0]);
3348 /* Try to match the byte sequence in `str' against
3349 those known to the collate implementation.
3350 First find out whether the bytes in `str' are
3351 actually from exactly one character. */
3352 const int32_t *table;
3353 const unsigned char *weights;
3354 const unsigned char *extra;
3355 const int32_t *indirect;
3357 const unsigned char *cp = str;
3360 /* This #include defines a local function! */
3361 # include <locale/weight.h>
3363 table = (const int32_t *)
3364 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3365 weights = (const unsigned char *)
3366 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3367 extra = (const unsigned char *)
3368 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3369 indirect = (const int32_t *)
3370 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3372 idx = findidx (&cp);
3373 if (idx == 0 || cp < str + c1)
3374 /* This is no valid character. */
3375 FREE_STACK_RETURN (REG_ECOLLATE);
3377 /* Throw away the ] at the end of the equivalence
3381 /* Now we have to go throught the whole table
3382 and find all characters which have the same
3385 XXX Note that this is not entirely correct.
3386 we would have to match multibyte sequences
3387 but this is not possible with the current
3389 for (ch = 1; ch < 256; ++ch)
3390 /* XXX This test would have to be changed if we
3391 would allow matching multibyte sequences. */
3394 int32_t idx2 = table[ch];
3395 size_t len = weights[idx2];
3397 /* Test whether the lenghts match. */
3398 if (weights[idx] == len)
3400 /* They do. New compare the bytes of
3405 && (weights[idx + 1 + cnt]
3406 == weights[idx2 + 1 + cnt]))
3410 /* They match. Mark the character as
3417 had_char_class = true;
3427 had_char_class = false;
3430 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3432 unsigned char str[128]; /* Should be large enough. */
3435 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3441 /* If pattern is `[[.'. */
3442 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3447 if ((c == '.' && *p == ']') || p == pend)
3449 if (c1 < sizeof (str))
3452 /* This is in any case an invalid class name. */
3457 if (c == '.' && *p == ']' && str[0] != '\0')
3459 /* If we have no collation data we use the default
3460 collation in which each character is the name
3461 for its own class which contains only the one
3462 character. It also means that ASCII is the
3463 character set and therefore we cannot have character
3464 with more than one byte in the multibyte
3471 FREE_STACK_RETURN (REG_ECOLLATE);
3473 /* Throw away the ] at the end of the equivalence
3477 /* Set the bit for the character. */
3478 SET_LIST_BIT (str[0]);
3479 range_start = ((const unsigned char *) str)[0];
3484 /* Try to match the byte sequence in `str' against
3485 those known to the collate implementation.
3486 First find out whether the bytes in `str' are
3487 actually from exactly one character. */
3489 const int32_t *symb_table;
3490 const unsigned char *extra;
3497 _NL_CURRENT_WORD (LC_COLLATE,
3498 _NL_COLLATE_SYMB_HASH_SIZEMB);
3499 symb_table = (const int32_t *)
3500 _NL_CURRENT (LC_COLLATE,
3501 _NL_COLLATE_SYMB_TABLEMB);
3502 extra = (const unsigned char *)
3503 _NL_CURRENT (LC_COLLATE,
3504 _NL_COLLATE_SYMB_EXTRAMB);
3506 /* Locate the character in the hashing table. */
3507 hash = elem_hash (str, c1);
3510 elem = hash % table_size;
3511 second = hash % (table_size - 2);
3512 while (symb_table[2 * elem] != 0)
3514 /* First compare the hashing value. */
3515 if (symb_table[2 * elem] == hash
3516 && c1 == extra[symb_table[2 * elem + 1]]
3518 &extra[symb_table[2 * elem + 1]
3522 /* Yep, this is the entry. */
3523 idx = symb_table[2 * elem + 1];
3524 idx += 1 + extra[idx];
3532 if (symb_table[2 * elem] == 0)
3533 /* This is no valid character. */
3534 FREE_STACK_RETURN (REG_ECOLLATE);
3536 /* Throw away the ] at the end of the equivalence
3540 /* Now add the multibyte character(s) we found
3543 XXX Note that this is not entirely correct.
3544 we would have to match multibyte sequences
3545 but this is not possible with the current
3546 implementation. Also, we have to match
3547 collating symbols, which expand to more than
3548 one file, as a whole and not allow the
3549 individual bytes. */
3552 range_start = extra[idx];
3555 SET_LIST_BIT (extra[idx]);
3560 had_char_class = false;
3570 had_char_class = false;
3575 had_char_class = false;
3581 /* Discard any (non)matching list bytes that are all 0 at the
3582 end of the map. Decrease the map-length byte too. */
3583 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3586 #endif /* MBS_SUPPORT */
3592 if (syntax & RE_NO_BK_PARENS)
3599 if (syntax & RE_NO_BK_PARENS)
3606 if (syntax & RE_NEWLINE_ALT)
3613 if (syntax & RE_NO_BK_VBAR)
3620 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3621 goto handle_interval;
3627 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3629 /* Do not translate the character after the \, so that we can
3630 distinguish, e.g., \B from \b, even if we normally would
3631 translate, e.g., B to b. */
3637 if (syntax & RE_NO_BK_PARENS)
3638 goto normal_backslash;
3644 if (COMPILE_STACK_FULL)
3646 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3647 compile_stack_elt_t);
3648 if (compile_stack.stack == NULL) return REG_ESPACE;
3650 compile_stack.size <<= 1;
3653 /* These are the values to restore when we hit end of this
3654 group. They are all relative offsets, so that if the
3655 whole pattern moves because of realloc, they will still
3657 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3658 COMPILE_STACK_TOP.fixup_alt_jump
3659 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3660 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3661 COMPILE_STACK_TOP.regnum = regnum;
3663 /* We will eventually replace the 0 with the number of
3664 groups inner to this one. But do not push a
3665 start_memory for groups beyond the last one we can
3666 represent in the compiled pattern. */
3667 if (regnum <= MAX_REGNUM)
3669 COMPILE_STACK_TOP.inner_group_offset = b
3670 - COMPILED_BUFFER_VAR + 2;
3671 BUF_PUSH_3 (start_memory, regnum, 0);
3674 compile_stack.avail++;
3679 /* If we've reached MAX_REGNUM groups, then this open
3680 won't actually generate any code, so we'll have to
3681 clear pending_exact explicitly. */
3687 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3689 if (COMPILE_STACK_EMPTY)
3691 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3692 goto normal_backslash;
3694 FREE_STACK_RETURN (REG_ERPAREN);
3699 { /* Push a dummy failure point at the end of the
3700 alternative for a possible future
3701 `pop_failure_jump' to pop. See comments at
3702 `push_dummy_failure' in `re_match_2'. */
3703 BUF_PUSH (push_dummy_failure);
3705 /* We allocated space for this jump when we assigned
3706 to `fixup_alt_jump', in the `handle_alt' case below. */
3707 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3710 /* See similar code for backslashed left paren above. */
3711 if (COMPILE_STACK_EMPTY)
3713 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3716 FREE_STACK_RETURN (REG_ERPAREN);
3719 /* Since we just checked for an empty stack above, this
3720 ``can't happen''. */
3721 assert (compile_stack.avail != 0);
3723 /* We don't just want to restore into `regnum', because
3724 later groups should continue to be numbered higher,
3725 as in `(ab)c(de)' -- the second group is #2. */
3726 regnum_t this_group_regnum;
3728 compile_stack.avail--;
3729 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3731 = COMPILE_STACK_TOP.fixup_alt_jump
3732 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3734 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3735 this_group_regnum = COMPILE_STACK_TOP.regnum;
3736 /* If we've reached MAX_REGNUM groups, then this open
3737 won't actually generate any code, so we'll have to
3738 clear pending_exact explicitly. */
3741 /* We're at the end of the group, so now we know how many
3742 groups were inside this one. */
3743 if (this_group_regnum <= MAX_REGNUM)
3745 US_CHAR_TYPE *inner_group_loc
3746 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3748 *inner_group_loc = regnum - this_group_regnum;
3749 BUF_PUSH_3 (stop_memory, this_group_regnum,
3750 regnum - this_group_regnum);
3756 case '|': /* `\|'. */
3757 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3758 goto normal_backslash;
3760 if (syntax & RE_LIMITED_OPS)
3763 /* Insert before the previous alternative a jump which
3764 jumps to this alternative if the former fails. */
3765 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3766 INSERT_JUMP (on_failure_jump, begalt,
3767 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3769 b += 1 + OFFSET_ADDRESS_SIZE;
3771 /* The alternative before this one has a jump after it
3772 which gets executed if it gets matched. Adjust that
3773 jump so it will jump to this alternative's analogous
3774 jump (put in below, which in turn will jump to the next
3775 (if any) alternative's such jump, etc.). The last such
3776 jump jumps to the correct final destination. A picture:
3782 If we are at `b', then fixup_alt_jump right now points to a
3783 three-byte space after `a'. We'll put in the jump, set
3784 fixup_alt_jump to right after `b', and leave behind three
3785 bytes which we'll fill in when we get to after `c'. */
3788 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3790 /* Mark and leave space for a jump after this alternative,
3791 to be filled in later either by next alternative or
3792 when know we're at the end of a series of alternatives. */
3794 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3795 b += 1 + OFFSET_ADDRESS_SIZE;
3803 /* If \{ is a literal. */
3804 if (!(syntax & RE_INTERVALS)
3805 /* If we're at `\{' and it's not the open-interval
3807 || (syntax & RE_NO_BK_BRACES))
3808 goto normal_backslash;
3812 /* If got here, then the syntax allows intervals. */
3814 /* At least (most) this many matches must be made. */
3815 int lower_bound = -1, upper_bound = -1;
3816 beg_interval = p - 1;
3820 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3821 goto unfetch_interval;
3823 FREE_STACK_RETURN (REG_EBRACE);
3826 GET_UNSIGNED_NUMBER (lower_bound);
3830 GET_UNSIGNED_NUMBER (upper_bound);
3831 if ((!(syntax & RE_NO_BK_BRACES) && c != '\\')
3832 || ((syntax & RE_NO_BK_BRACES) && c != '}'))
3833 FREE_STACK_RETURN (REG_BADBR);
3835 if (upper_bound < 0)
3836 upper_bound = RE_DUP_MAX;
3839 /* Interval such as `{1}' => match exactly once. */
3840 upper_bound = lower_bound;
3842 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3843 || lower_bound > upper_bound)
3845 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3846 goto unfetch_interval;
3848 FREE_STACK_RETURN (REG_BADBR);
3851 if (!(syntax & RE_NO_BK_BRACES))
3853 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
3860 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3861 goto unfetch_interval;
3863 FREE_STACK_RETURN (REG_BADBR);
3866 /* We just parsed a valid interval. */
3868 /* If it's invalid to have no preceding re. */
3871 if (syntax & RE_CONTEXT_INVALID_OPS)
3872 FREE_STACK_RETURN (REG_BADRPT);
3873 else if (syntax & RE_CONTEXT_INDEP_OPS)
3876 goto unfetch_interval;
3879 /* If the upper bound is zero, don't want to succeed at
3880 all; jump from `laststart' to `b + 3', which will be
3881 the end of the buffer after we insert the jump. */
3882 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE'
3883 instead of 'b + 3'. */
3884 if (upper_bound == 0)
3886 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3887 INSERT_JUMP (jump, laststart, b + 1
3888 + OFFSET_ADDRESS_SIZE);
3889 b += 1 + OFFSET_ADDRESS_SIZE;
3892 /* Otherwise, we have a nontrivial interval. When
3893 we're all done, the pattern will look like:
3894 set_number_at <jump count> <upper bound>
3895 set_number_at <succeed_n count> <lower bound>
3896 succeed_n <after jump addr> <succeed_n count>
3898 jump_n <succeed_n addr> <jump count>
3899 (The upper bound and `jump_n' are omitted if
3900 `upper_bound' is 1, though.) */
3902 { /* If the upper bound is > 1, we need to insert
3903 more at the end of the loop. */
3904 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3905 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3907 GET_BUFFER_SPACE (nbytes);
3909 /* Initialize lower bound of the `succeed_n', even
3910 though it will be set during matching by its
3911 attendant `set_number_at' (inserted next),
3912 because `re_compile_fastmap' needs to know.
3913 Jump to the `jump_n' we might insert below. */
3914 INSERT_JUMP2 (succeed_n, laststart,
3915 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3916 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3918 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3920 /* Code to initialize the lower bound. Insert
3921 before the `succeed_n'. The `5' is the last two
3922 bytes of this `set_number_at', plus 3 bytes of
3923 the following `succeed_n'. */
3924 /* ifdef MBS_SUPPORT, The '1+2*OFFSET_ADDRESS_SIZE'
3925 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3926 of the following `succeed_n'. */
3927 insert_op2 (set_number_at, laststart, 1
3928 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3929 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3931 if (upper_bound > 1)
3932 { /* More than one repetition is allowed, so
3933 append a backward jump to the `succeed_n'
3934 that starts this interval.
3936 When we've reached this during matching,
3937 we'll have matched the interval once, so
3938 jump back only `upper_bound - 1' times. */
3939 STORE_JUMP2 (jump_n, b, laststart
3940 + 2 * OFFSET_ADDRESS_SIZE + 1,
3942 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3944 /* The location we want to set is the second
3945 parameter of the `jump_n'; that is `b-2' as
3946 an absolute address. `laststart' will be
3947 the `set_number_at' we're about to insert;
3948 `laststart+3' the number to set, the source
3949 for the relative address. But we are
3950 inserting into the middle of the pattern --
3951 so everything is getting moved up by 5.
3952 Conclusion: (b - 2) - (laststart + 3) + 5,
3953 i.e., b - laststart.
3955 We insert this at the beginning of the loop
3956 so that if we fail during matching, we'll
3957 reinitialize the bounds. */
3958 insert_op2 (set_number_at, laststart, b - laststart,
3959 upper_bound - 1, b);
3960 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3964 beg_interval = NULL;
3969 /* If an invalid interval, match the characters as literals. */
3970 assert (beg_interval);
3972 beg_interval = NULL;
3974 /* normal_char and normal_backslash need `c'. */
3977 if (!(syntax & RE_NO_BK_BRACES))
3979 if (p > pattern && p[-1] == '\\')
3980 goto normal_backslash;
3985 /* There is no way to specify the before_dot and after_dot
3986 operators. rms says this is ok. --karl */
3994 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
4000 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
4006 if (syntax & RE_NO_GNU_OPS)
4009 BUF_PUSH (wordchar);
4014 if (syntax & RE_NO_GNU_OPS)
4017 BUF_PUSH (notwordchar);
4022 if (syntax & RE_NO_GNU_OPS)
4028 if (syntax & RE_NO_GNU_OPS)
4034 if (syntax & RE_NO_GNU_OPS)
4036 BUF_PUSH (wordbound);
4040 if (syntax & RE_NO_GNU_OPS)
4042 BUF_PUSH (notwordbound);
4046 if (syntax & RE_NO_GNU_OPS)
4052 if (syntax & RE_NO_GNU_OPS)
4057 case '1': case '2': case '3': case '4': case '5':
4058 case '6': case '7': case '8': case '9':
4059 if (syntax & RE_NO_BK_REFS)
4065 FREE_STACK_RETURN (REG_ESUBREG);
4067 /* Can't back reference to a subexpression if inside of it. */
4068 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4072 BUF_PUSH_2 (duplicate, c1);
4078 if (syntax & RE_BK_PLUS_QM)
4081 goto normal_backslash;
4085 /* You might think it would be useful for \ to mean
4086 not to translate; but if we don't translate it
4087 it will never match anything. */
4095 /* Expects the character in `c'. */
4097 /* If no exactn currently being built. */
4100 /* If last exactn handle binary(or character) and
4101 new exactn handle character(or binary). */
4102 || is_exactn_bin != is_binary[p - 1 - pattern]
4103 #endif /* MBS_SUPPORT */
4105 /* If last exactn not at current position. */
4106 || pending_exact + *pending_exact + 1 != b
4108 /* We have only one byte following the exactn for the count. */
4109 || *pending_exact == (1 << BYTEWIDTH) - 1
4111 /* If followed by a repetition operator. */
4112 || *p == '*' || *p == '^'
4113 || ((syntax & RE_BK_PLUS_QM)
4114 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4115 : (*p == '+' || *p == '?'))
4116 || ((syntax & RE_INTERVALS)
4117 && ((syntax & RE_NO_BK_BRACES)
4119 : (p[0] == '\\' && p[1] == '{'))))
4121 /* Start building a new exactn. */
4126 /* Is this exactn binary data or character? */
4127 is_exactn_bin = is_binary[p - 1 - pattern];
4129 BUF_PUSH_2 (exactn_bin, 0);
4131 BUF_PUSH_2 (exactn, 0);
4133 BUF_PUSH_2 (exactn, 0);
4134 #endif /* MBS_SUPPORT */
4135 pending_exact = b - 1;
4142 } /* while p != pend */
4145 /* Through the pattern now. */
4148 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4150 if (!COMPILE_STACK_EMPTY)
4151 FREE_STACK_RETURN (REG_EPAREN);
4153 /* If we don't want backtracking, force success
4154 the first time we reach the end of the compiled pattern. */
4155 if (syntax & RE_NO_POSIX_BACKTRACKING)
4163 free (compile_stack.stack);
4165 /* We have succeeded; set the length of the buffer. */
4167 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4169 bufp->used = b - bufp->buffer;
4175 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4176 print_compiled_pattern (bufp);
4180 #ifndef MATCH_MAY_ALLOCATE
4181 /* Initialize the failure stack to the largest possible stack. This
4182 isn't necessary unless we're trying to avoid calling alloca in
4183 the search and match routines. */
4185 int num_regs = bufp->re_nsub + 1;
4187 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4188 is strictly greater than re_max_failures, the largest possible stack
4189 is 2 * re_max_failures failure points. */
4190 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4192 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4195 if (! fail_stack.stack)
4197 = (fail_stack_elt_t *) xmalloc (fail_stack.size
4198 * sizeof (fail_stack_elt_t));
4201 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
4203 * sizeof (fail_stack_elt_t)));
4204 # else /* not emacs */
4205 if (! fail_stack.stack)
4207 = (fail_stack_elt_t *) malloc (fail_stack.size
4208 * sizeof (fail_stack_elt_t));
4211 = (fail_stack_elt_t *) realloc (fail_stack.stack,
4213 * sizeof (fail_stack_elt_t)));
4214 # endif /* not emacs */
4217 regex_grow_registers (num_regs);
4219 #endif /* not MATCH_MAY_ALLOCATE */
4222 } /* regex_compile */
4224 /* Subroutines for `regex_compile'. */
4226 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4227 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4230 store_op1 (op, loc, arg)
4235 *loc = (US_CHAR_TYPE) op;
4236 STORE_NUMBER (loc + 1, arg);
4240 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4241 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4244 store_op2 (op, loc, arg1, arg2)
4249 *loc = (US_CHAR_TYPE) op;
4250 STORE_NUMBER (loc + 1, arg1);
4251 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4255 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4256 for OP followed by two-byte integer parameter ARG. */
4257 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4260 insert_op1 (op, loc, arg, end)
4266 register US_CHAR_TYPE *pfrom = end;
4267 register US_CHAR_TYPE *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4269 while (pfrom != loc)
4272 store_op1 (op, loc, arg);
4276 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4277 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4280 insert_op2 (op, loc, arg1, arg2, end)
4286 register US_CHAR_TYPE *pfrom = end;
4287 register US_CHAR_TYPE *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4289 while (pfrom != loc)
4292 store_op2 (op, loc, arg1, arg2);
4296 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4297 after an alternative or a begin-subexpression. We assume there is at
4298 least one character before the ^. */
4301 at_begline_loc_p (pattern, p, syntax)
4302 const CHAR_TYPE *pattern, *p;
4303 reg_syntax_t syntax;
4305 const CHAR_TYPE *prev = p - 2;
4306 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4309 /* After a subexpression? */
4310 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4311 /* After an alternative? */
4312 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4316 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4317 at least one character after the $, i.e., `P < PEND'. */
4320 at_endline_loc_p (p, pend, syntax)
4321 const CHAR_TYPE *p, *pend;
4322 reg_syntax_t syntax;
4324 const CHAR_TYPE *next = p;
4325 boolean next_backslash = *next == '\\';
4326 const CHAR_TYPE *next_next = p + 1 < pend ? p + 1 : 0;
4329 /* Before a subexpression? */
4330 (syntax & RE_NO_BK_PARENS ? *next == ')'
4331 : next_backslash && next_next && *next_next == ')')
4332 /* Before an alternative? */
4333 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4334 : next_backslash && next_next && *next_next == '|');
4338 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4339 false if it's not. */
4342 group_in_compile_stack (compile_stack, regnum)
4343 compile_stack_type compile_stack;
4348 for (this_element = compile_stack.avail - 1;
4351 if (compile_stack.stack[this_element].regnum == regnum)
4358 /* This insert space into the pattern. */
4360 insert_space (num, loc, end)
4365 register CHAR_TYPE *pto = end;
4366 register CHAR_TYPE *pfrom = end - num;
4368 while (pfrom >= loc)
4371 #endif /* MBS_SUPPORT */
4374 static reg_errcode_t
4375 compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4377 CHAR_TYPE range_start_char;
4378 const CHAR_TYPE **p_ptr, *pend;
4379 CHAR_TYPE *char_set, *b;
4380 RE_TRANSLATE_TYPE translate;
4381 reg_syntax_t syntax;
4383 const CHAR_TYPE *p = *p_ptr;
4384 CHAR_TYPE range_start, range_end;
4388 uint32_t start_val, end_val;
4394 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4397 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4398 _NL_COLLATE_COLLSEQWC);
4400 if (range_start_char < -1)
4402 /* range_start is a collating symbol. */
4404 /* Retreive the index and get collation sequence value. */
4405 wextra = (int32_t*)char_set[-range_start_char];
4406 start_val = wextra[1 + *wextra];
4409 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4411 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4413 /* Report an error if the range is empty and the syntax prohibits
4415 ret = ((syntax & RE_NO_EMPTY_RANGES)
4416 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4418 /* Insert space to the end of the char_ranges. */
4419 insert_space(2, b - char_set[5] - 2, b - 1);
4420 *(b - char_set[5] - 2) = (wchar_t)start_val;
4421 *(b - char_set[5] - 1) = (wchar_t)end_val;
4422 char_set[4]++; /* ranges_index */
4427 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4429 range_end = TRANSLATE (p[0]);
4430 /* Report an error if the range is empty and the syntax prohibits
4432 ret = ((syntax & RE_NO_EMPTY_RANGES)
4433 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4435 /* Insert space to the end of the char_ranges. */
4436 insert_space(2, b - char_set[5] - 2, b - 1);
4437 *(b - char_set[5] - 2) = range_start;
4438 *(b - char_set[5] - 1) = range_end;
4439 char_set[4]++; /* ranges_index */
4441 /* Have to increment the pointer into the pattern string, so the
4442 caller isn't still at the ending character. */
4448 /* Read the ending character of a range (in a bracket expression) from the
4449 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4450 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4451 Then we set the translation of all bits between the starting and
4452 ending characters (inclusive) in the compiled pattern B.
4454 Return an error code.
4456 We use these short variable names so we can use the same macros as
4457 `regex_compile' itself. */
4459 static reg_errcode_t
4460 compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4461 unsigned int range_start_char;
4462 const char **p_ptr, *pend;
4463 RE_TRANSLATE_TYPE translate;
4464 reg_syntax_t syntax;
4468 const char *p = *p_ptr;
4471 const unsigned char *collseq;
4472 unsigned int start_colseq;
4473 unsigned int end_colseq;
4481 /* Have to increment the pointer into the pattern string, so the
4482 caller isn't still at the ending character. */
4485 /* Report an error if the range is empty and the syntax prohibits this. */
4486 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4489 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4490 _NL_COLLATE_COLLSEQMB);
4492 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4493 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4494 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4496 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4498 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4500 SET_LIST_BIT (TRANSLATE (this_char));
4505 /* Here we see why `this_char' has to be larger than an `unsigned
4506 char' -- we would otherwise go into an infinite loop, since all
4507 characters <= 0xff. */
4508 range_start_char = TRANSLATE (range_start_char);
4509 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4510 and some compilers cast it to int implicitly, so following for_loop
4511 may fall to (almost) infinite loop.
4512 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4513 To avoid this, we cast p[0] to unsigned int and truncate it. */
4514 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4516 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4518 SET_LIST_BIT (TRANSLATE (this_char));
4525 #endif /* MBS_SUPPORT */
4527 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4528 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4529 characters can start a string that matches the pattern. This fastmap
4530 is used by re_search to skip quickly over impossible starting points.
4532 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4533 area as BUFP->fastmap.
4535 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4538 Returns 0 if we succeed, -2 if an internal error. */
4541 /* local function for re_compile_fastmap.
4542 truncate wchar_t character to char. */
4543 static unsigned char truncate_wchar (CHAR_TYPE c);
4545 static unsigned char
4549 unsigned char buf[MB_LEN_MAX];
4550 int retval = wctomb(buf, c);
4551 return retval > 0 ? buf[0] : (unsigned char)c;
4553 #endif /* MBS_SUPPORT */
4556 re_compile_fastmap (bufp)
4557 struct re_pattern_buffer *bufp;
4560 #ifdef MATCH_MAY_ALLOCATE
4561 fail_stack_type fail_stack;
4563 #ifndef REGEX_MALLOC
4567 register char *fastmap = bufp->fastmap;
4570 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4571 pattern to (char*) in regex_compile. */
4572 US_CHAR_TYPE *pattern = (US_CHAR_TYPE*)bufp->buffer;
4573 register US_CHAR_TYPE *pend = (US_CHAR_TYPE*) (bufp->buffer + bufp->used);
4575 US_CHAR_TYPE *pattern = bufp->buffer;
4576 register US_CHAR_TYPE *pend = pattern + bufp->used;
4577 #endif /* MBS_SUPPORT */
4578 US_CHAR_TYPE *p = pattern;
4581 /* This holds the pointer to the failure stack, when
4582 it is allocated relocatably. */
4583 fail_stack_elt_t *failure_stack_ptr;
4586 /* Assume that each path through the pattern can be null until
4587 proven otherwise. We set this false at the bottom of switch
4588 statement, to which we get only if a particular path doesn't
4589 match the empty string. */
4590 boolean path_can_be_null = true;
4592 /* We aren't doing a `succeed_n' to begin with. */
4593 boolean succeed_n_p = false;
4595 assert (fastmap != NULL && p != NULL);
4598 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4599 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4600 bufp->can_be_null = 0;
4604 if (p == pend || *p == succeed)
4606 /* We have reached the (effective) end of pattern. */
4607 if (!FAIL_STACK_EMPTY ())
4609 bufp->can_be_null |= path_can_be_null;
4611 /* Reset for next path. */
4612 path_can_be_null = true;
4614 p = fail_stack.stack[--fail_stack.avail].pointer;
4622 /* We should never be about to go beyond the end of the pattern. */
4625 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4628 /* I guess the idea here is to simply not bother with a fastmap
4629 if a backreference is used, since it's too hard to figure out
4630 the fastmap for the corresponding group. Setting
4631 `can_be_null' stops `re_search_2' from using the fastmap, so
4632 that is all we do. */
4634 bufp->can_be_null = 1;
4638 /* Following are the cases which match a character. These end
4643 fastmap[truncate_wchar(p[1])] = 1;
4652 #endif /* MBS_SUPPORT */
4656 /* It is hard to distinguish fastmap from (multi byte) characters
4657 which depends on current locale. */
4662 bufp->can_be_null = 1;
4666 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4667 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4673 /* Chars beyond end of map must be allowed. */
4674 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4677 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4678 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4684 for (j = 0; j < (1 << BYTEWIDTH); j++)
4685 if (SYNTAX (j) == Sword)
4691 for (j = 0; j < (1 << BYTEWIDTH); j++)
4692 if (SYNTAX (j) != Sword)
4699 int fastmap_newline = fastmap['\n'];
4701 /* `.' matches anything ... */
4702 for (j = 0; j < (1 << BYTEWIDTH); j++)
4705 /* ... except perhaps newline. */
4706 if (!(bufp->syntax & RE_DOT_NEWLINE))
4707 fastmap['\n'] = fastmap_newline;
4709 /* Return if we have already set `can_be_null'; if we have,
4710 then the fastmap is irrelevant. Something's wrong here. */
4711 else if (bufp->can_be_null)
4714 /* Otherwise, have to check alternative paths. */
4721 for (j = 0; j < (1 << BYTEWIDTH); j++)
4722 if (SYNTAX (j) == (enum syntaxcode) k)
4729 for (j = 0; j < (1 << BYTEWIDTH); j++)
4730 if (SYNTAX (j) != (enum syntaxcode) k)
4735 /* All cases after this match the empty string. These end with
4755 case push_dummy_failure:
4760 case pop_failure_jump:
4761 case maybe_pop_jump:
4764 case dummy_failure_jump:
4765 EXTRACT_NUMBER_AND_INCR (j, p);
4770 /* Jump backward implies we just went through the body of a
4771 loop and matched nothing. Opcode jumped to should be
4772 `on_failure_jump' or `succeed_n'. Just treat it like an
4773 ordinary jump. For a * loop, it has pushed its failure
4774 point already; if so, discard that as redundant. */
4775 if ((re_opcode_t) *p != on_failure_jump
4776 && (re_opcode_t) *p != succeed_n)
4780 EXTRACT_NUMBER_AND_INCR (j, p);
4783 /* If what's on the stack is where we are now, pop it. */
4784 if (!FAIL_STACK_EMPTY ()
4785 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4791 case on_failure_jump:
4792 case on_failure_keep_string_jump:
4793 handle_on_failure_jump:
4794 EXTRACT_NUMBER_AND_INCR (j, p);
4796 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4797 end of the pattern. We don't want to push such a point,
4798 since when we restore it above, entering the switch will
4799 increment `p' past the end of the pattern. We don't need
4800 to push such a point since we obviously won't find any more
4801 fastmap entries beyond `pend'. Such a pattern can match
4802 the null string, though. */
4805 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4807 RESET_FAIL_STACK ();
4812 bufp->can_be_null = 1;
4816 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4817 succeed_n_p = false;
4824 /* Get to the number of times to succeed. */
4825 p += OFFSET_ADDRESS_SIZE;
4827 /* Increment p past the n for when k != 0. */
4828 EXTRACT_NUMBER_AND_INCR (k, p);
4831 p -= 2 * OFFSET_ADDRESS_SIZE;
4832 succeed_n_p = true; /* Spaghetti code alert. */
4833 goto handle_on_failure_jump;
4839 p += 2 * OFFSET_ADDRESS_SIZE;
4850 abort (); /* We have listed all the cases. */
4853 /* Getting here means we have found the possible starting
4854 characters for one path of the pattern -- and that the empty
4855 string does not match. We need not follow this path further.
4856 Instead, look at the next alternative (remembered on the
4857 stack), or quit if no more. The test at the top of the loop
4858 does these things. */
4859 path_can_be_null = false;
4863 /* Set `can_be_null' for the last path (also the first path, if the
4864 pattern is empty). */
4865 bufp->can_be_null |= path_can_be_null;
4868 RESET_FAIL_STACK ();
4870 } /* re_compile_fastmap */
4872 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4875 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4876 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4877 this memory for recording register information. STARTS and ENDS
4878 must be allocated using the malloc library routine, and must each
4879 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4881 If NUM_REGS == 0, then subsequent matches should allocate their own
4884 Unless this function is called, the first search or match using
4885 PATTERN_BUFFER will allocate its own register data, without
4886 freeing the old data. */
4889 re_set_registers (bufp, regs, num_regs, starts, ends)
4890 struct re_pattern_buffer *bufp;
4891 struct re_registers *regs;
4893 regoff_t *starts, *ends;
4897 bufp->regs_allocated = REGS_REALLOCATE;
4898 regs->num_regs = num_regs;
4899 regs->start = starts;
4904 bufp->regs_allocated = REGS_UNALLOCATED;
4906 regs->start = regs->end = (regoff_t *) 0;
4910 weak_alias (__re_set_registers, re_set_registers)
4913 /* Searching routines. */
4915 /* Like re_search_2, below, but only one string is specified, and
4916 doesn't let you say where to stop matching. */
4919 re_search (bufp, string, size, startpos, range, regs)
4920 struct re_pattern_buffer *bufp;
4922 int size, startpos, range;
4923 struct re_registers *regs;
4925 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4929 weak_alias (__re_search, re_search)
4933 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4934 virtual concatenation of STRING1 and STRING2, starting first at index
4935 STARTPOS, then at STARTPOS + 1, and so on.
4937 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4939 RANGE is how far to scan while trying to match. RANGE = 0 means try
4940 only at STARTPOS; in general, the last start tried is STARTPOS +
4943 In REGS, return the indices of the virtual concatenation of STRING1
4944 and STRING2 that matched the entire BUFP->buffer and its contained
4947 Do not consider matching one past the index STOP in the virtual
4948 concatenation of STRING1 and STRING2.
4950 We return either the position in the strings at which the match was
4951 found, -1 if no match, or -2 if error (such as failure
4955 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
4956 struct re_pattern_buffer *bufp;
4957 const char *string1, *string2;
4961 struct re_registers *regs;
4965 register char *fastmap = bufp->fastmap;
4966 register RE_TRANSLATE_TYPE translate = bufp->translate;
4967 int total_size = size1 + size2;
4968 int endpos = startpos + range;
4970 /* Check for out-of-range STARTPOS. */
4971 if (startpos < 0 || startpos > total_size)
4974 /* Fix up RANGE if it might eventually take us outside
4975 the virtual concatenation of STRING1 and STRING2.
4976 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4978 range = 0 - startpos;
4979 else if (endpos > total_size)
4980 range = total_size - startpos;
4982 /* If the search isn't to be a backwards one, don't waste time in a
4983 search for a pattern that must be anchored. */
4984 if (bufp->used > 0 && range > 0
4985 && ((re_opcode_t) bufp->buffer[0] == begbuf
4986 /* `begline' is like `begbuf' if it cannot match at newlines. */
4987 || ((re_opcode_t) bufp->buffer[0] == begline
4988 && !bufp->newline_anchor)))
4997 /* In a forward search for something that starts with \=.
4998 don't keep searching past point. */
4999 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5001 range = PT - startpos;
5007 /* Update the fastmap now if not correct already. */
5008 if (fastmap && !bufp->fastmap_accurate)
5009 if (re_compile_fastmap (bufp) == -2)
5012 /* Loop through the string, looking for a place to start matching. */
5015 /* If a fastmap is supplied, skip quickly over characters that
5016 cannot be the start of a match. If the pattern can match the
5017 null string, however, we don't need to skip characters; we want
5018 the first null string. */
5019 if (fastmap && startpos < total_size && !bufp->can_be_null)
5021 if (range > 0) /* Searching forwards. */
5023 register const char *d;
5024 register int lim = 0;
5027 if (startpos < size1 && startpos + range >= size1)
5028 lim = range - (size1 - startpos);
5030 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5032 /* Written out as an if-else to avoid testing `translate'
5036 && !fastmap[(unsigned char)
5037 translate[(unsigned char) *d++]])
5040 while (range > lim && !fastmap[(unsigned char) *d++])
5043 startpos += irange - range;
5045 else /* Searching backwards. */
5047 register char c = (size1 == 0 || startpos >= size1
5048 ? string2[startpos - size1]
5049 : string1[startpos]);
5051 if (!fastmap[(unsigned char) TRANSLATE (c)])
5056 /* If can't match the null string, and that's all we have left, fail. */
5057 if (range >= 0 && startpos == total_size && fastmap
5058 && !bufp->can_be_null)
5061 val = re_match_2_internal (bufp, string1, size1, string2, size2,
5062 startpos, regs, stop);
5063 #ifndef REGEX_MALLOC
5092 weak_alias (__re_search_2, re_search_2)
5096 /* This converts PTR, a pointer into one of the search wchar_t strings
5097 `string1' and `string2' into an multibyte string offset from the
5098 beginning of that string. We use mbs_offset to optimize.
5099 See convert_mbs_to_wcs. */
5100 # define POINTER_TO_OFFSET(ptr) \
5101 (FIRST_STRING_P (ptr) \
5102 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5103 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5106 /* This converts PTR, a pointer into one of the search strings `string1'
5107 and `string2' into an offset from the beginning of that string. */
5108 # define POINTER_TO_OFFSET(ptr) \
5109 (FIRST_STRING_P (ptr) \
5110 ? ((regoff_t) ((ptr) - string1)) \
5111 : ((regoff_t) ((ptr) - string2 + size1)))
5112 #endif /* MBS_SUPPORT */
5114 /* Macros for dealing with the split strings in re_match_2. */
5116 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5118 /* Call before fetching a character with *d. This switches over to
5119 string2 if necessary. */
5120 #define PREFETCH() \
5123 /* End of string2 => fail. */ \
5124 if (dend == end_match_2) \
5126 /* End of string1 => advance to string2. */ \
5128 dend = end_match_2; \
5132 /* Test if at very beginning or at very end of the virtual concatenation
5133 of `string1' and `string2'. If only one string, it's `string2'. */
5134 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5135 #define AT_STRINGS_END(d) ((d) == end2)
5138 /* Test if D points to a character which is word-constituent. We have
5139 two special cases to check for: if past the end of string1, look at
5140 the first character in string2; and if before the beginning of
5141 string2, look at the last character in string1. */
5143 /* Use internationalized API instead of SYNTAX. */
5144 # define WORDCHAR_P(d) \
5145 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5146 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5148 # define WORDCHAR_P(d) \
5149 (SYNTAX ((d) == end1 ? *string2 \
5150 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5152 #endif /* MBS_SUPPORT */
5154 /* Disabled due to a compiler bug -- see comment at case wordbound */
5156 /* Test if the character before D and the one at D differ with respect
5157 to being word-constituent. */
5158 #define AT_WORD_BOUNDARY(d) \
5159 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5160 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5163 /* Free everything we malloc. */
5164 #ifdef MATCH_MAY_ALLOCATE
5165 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5167 # define FREE_VARIABLES() \
5169 REGEX_FREE_STACK (fail_stack.stack); \
5170 FREE_VAR (regstart); \
5171 FREE_VAR (regend); \
5172 FREE_VAR (old_regstart); \
5173 FREE_VAR (old_regend); \
5174 FREE_VAR (best_regstart); \
5175 FREE_VAR (best_regend); \
5176 FREE_VAR (reg_info); \
5177 FREE_VAR (reg_dummy); \
5178 FREE_VAR (reg_info_dummy); \
5179 FREE_VAR (string1); \
5180 FREE_VAR (string2); \
5181 FREE_VAR (mbs_offset1); \
5182 FREE_VAR (mbs_offset2); \
5183 FREE_VAR (is_binary1); \
5184 FREE_VAR (is_binary2); \
5186 # else /* not MBS_SUPPORT */
5187 # define FREE_VARIABLES() \
5189 REGEX_FREE_STACK (fail_stack.stack); \
5190 FREE_VAR (regstart); \
5191 FREE_VAR (regend); \
5192 FREE_VAR (old_regstart); \
5193 FREE_VAR (old_regend); \
5194 FREE_VAR (best_regstart); \
5195 FREE_VAR (best_regend); \
5196 FREE_VAR (reg_info); \
5197 FREE_VAR (reg_dummy); \
5198 FREE_VAR (reg_info_dummy); \
5200 # endif /* MBS_SUPPORT */
5203 # define FREE_VARIABLES() \
5205 if (string1) free (string1); \
5206 if (string2) free (string2); \
5207 if (mbs_offset1) free (mbs_offset1); \
5208 if (mbs_offset2) free (mbs_offset2); \
5209 if (is_binary1) free (is_binary1); \
5210 if (is_binary2) free (is_binary2); \
5213 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5214 # endif /* MBS_SUPPORT */
5215 #endif /* not MATCH_MAY_ALLOCATE */
5217 /* These values must meet several constraints. They must not be valid
5218 register values; since we have a limit of 255 registers (because
5219 we use only one byte in the pattern for the register number), we can
5220 use numbers larger than 255. They must differ by 1, because of
5221 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5222 be larger than the value for the highest register, so we do not try
5223 to actually save any registers when none are active. */
5224 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5225 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5227 /* Matching routines. */
5229 #ifndef emacs /* Emacs never uses this. */
5230 /* re_match is like re_match_2 except it takes only a single string. */
5233 re_match (bufp, string, size, pos, regs)
5234 struct re_pattern_buffer *bufp;
5237 struct re_registers *regs;
5239 int result = re_match_2_internal (bufp, NULL, 0, string, size,
5241 # ifndef REGEX_MALLOC
5249 weak_alias (__re_match, re_match)
5251 #endif /* not emacs */
5253 static boolean group_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5255 register_info_type *reg_info));
5256 static boolean alt_match_null_string_p _RE_ARGS ((US_CHAR_TYPE *p,
5258 register_info_type *reg_info));
5259 static boolean common_op_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5261 register_info_type *reg_info));
5262 static int bcmp_translate _RE_ARGS ((const CHAR_TYPE *s1, const CHAR_TYPE *s2,
5263 int len, char *translate));
5265 /* re_match_2 matches the compiled pattern in BUFP against the
5266 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5267 and SIZE2, respectively). We start matching at POS, and stop
5270 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5271 store offsets for the substring each group matched in REGS. See the
5272 documentation for exactly how many groups we fill.
5274 We return -1 if no match, -2 if an internal error (such as the
5275 failure stack overflowing). Otherwise, we return the length of the
5276 matched substring. */
5279 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5280 struct re_pattern_buffer *bufp;
5281 const char *string1, *string2;
5284 struct re_registers *regs;
5287 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
5289 #ifndef REGEX_MALLOC
5297 weak_alias (__re_match_2, re_match_2)
5301 /* This check the substring (from 0, to length) of the multibyte string,
5302 to which offset_buffer correspond. And count how many wchar_t_characters
5303 the substring occupy. We use offset_buffer to optimization.
5304 See convert_mbs_to_wcs. */
5306 count_mbs_length(offset_buffer, length)
5312 /* Check whether the size is valid. */
5316 if (offset_buffer == NULL)
5319 for (wcs_size = 0 ; offset_buffer[wcs_size] != -1 ; wcs_size++)
5321 if (offset_buffer[wcs_size] == length)
5323 if (offset_buffer[wcs_size] > length)
5324 /* It is a fragment of a wide character. */
5328 /* We reached at the sentinel. */
5331 #endif /* MBS_SUPPORT */
5333 /* This is a separate function so that we can force an alloca cleanup
5337 re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos, regs, stop)
5338 struct re_pattern_buffer *bufp;
5339 const char *cstring1, *cstring2;
5342 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
5343 struct re_pattern_buffer *bufp;
5344 const char *string1, *string2;
5348 struct re_registers *regs;
5351 /* General temporaries. */
5355 /* We need wchar_t* buffers correspond to string1, string2. */
5356 CHAR_TYPE *string1 = NULL, *string2 = NULL;
5357 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5358 int size1 = 0, size2 = 0;
5359 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5360 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5361 /* They hold whether each wchar_t is binary data or not. */
5362 int *is_binary1 = NULL, *is_binary2 = NULL;
5363 #endif /* MBS_SUPPORT */
5365 /* Just past the end of the corresponding string. */
5366 const CHAR_TYPE *end1, *end2;
5368 /* Pointers into string1 and string2, just past the last characters in
5369 each to consider matching. */
5370 const CHAR_TYPE *end_match_1, *end_match_2;
5372 /* Where we are in the data, and the end of the current string. */
5373 const CHAR_TYPE *d, *dend;
5375 /* Where we are in the pattern, and the end of the pattern. */
5377 US_CHAR_TYPE *pattern, *p;
5378 register US_CHAR_TYPE *pend;
5380 US_CHAR_TYPE *p = bufp->buffer;
5381 register US_CHAR_TYPE *pend = p + bufp->used;
5382 #endif /* MBS_SUPPORT */
5384 /* Mark the opcode just after a start_memory, so we can test for an
5385 empty subpattern when we get to the stop_memory. */
5386 US_CHAR_TYPE *just_past_start_mem = 0;
5388 /* We use this to map every character in the string. */
5389 RE_TRANSLATE_TYPE translate = bufp->translate;
5391 /* Failure point stack. Each place that can handle a failure further
5392 down the line pushes a failure point on this stack. It consists of
5393 restart, regend, and reg_info for all registers corresponding to
5394 the subexpressions we're currently inside, plus the number of such
5395 registers, and, finally, two char *'s. The first char * is where
5396 to resume scanning the pattern; the second one is where to resume
5397 scanning the strings. If the latter is zero, the failure point is
5398 a ``dummy''; if a failure happens and the failure point is a dummy,
5399 it gets discarded and the next next one is tried. */
5400 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5401 fail_stack_type fail_stack;
5404 static unsigned failure_id;
5405 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5409 /* This holds the pointer to the failure stack, when
5410 it is allocated relocatably. */
5411 fail_stack_elt_t *failure_stack_ptr;
5414 /* We fill all the registers internally, independent of what we
5415 return, for use in backreferences. The number here includes
5416 an element for register zero. */
5417 size_t num_regs = bufp->re_nsub + 1;
5419 /* The currently active registers. */
5420 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5421 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5423 /* Information on the contents of registers. These are pointers into
5424 the input strings; they record just what was matched (on this
5425 attempt) by a subexpression part of the pattern, that is, the
5426 regnum-th regstart pointer points to where in the pattern we began
5427 matching and the regnum-th regend points to right after where we
5428 stopped matching the regnum-th subexpression. (The zeroth register
5429 keeps track of what the whole pattern matches.) */
5430 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5431 const CHAR_TYPE **regstart, **regend;
5434 /* If a group that's operated upon by a repetition operator fails to
5435 match anything, then the register for its start will need to be
5436 restored because it will have been set to wherever in the string we
5437 are when we last see its open-group operator. Similarly for a
5439 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5440 const CHAR_TYPE **old_regstart, **old_regend;
5443 /* The is_active field of reg_info helps us keep track of which (possibly
5444 nested) subexpressions we are currently in. The matched_something
5445 field of reg_info[reg_num] helps us tell whether or not we have
5446 matched any of the pattern so far this time through the reg_num-th
5447 subexpression. These two fields get reset each time through any
5448 loop their register is in. */
5449 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5450 register_info_type *reg_info;
5453 /* The following record the register info as found in the above
5454 variables when we find a match better than any we've seen before.
5455 This happens as we backtrack through the failure points, which in
5456 turn happens only if we have not yet matched the entire string. */
5457 unsigned best_regs_set = false;
5458 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5459 const CHAR_TYPE **best_regstart, **best_regend;
5462 /* Logically, this is `best_regend[0]'. But we don't want to have to
5463 allocate space for that if we're not allocating space for anything
5464 else (see below). Also, we never need info about register 0 for
5465 any of the other register vectors, and it seems rather a kludge to
5466 treat `best_regend' differently than the rest. So we keep track of
5467 the end of the best match so far in a separate variable. We
5468 initialize this to NULL so that when we backtrack the first time
5469 and need to test it, it's not garbage. */
5470 const CHAR_TYPE *match_end = NULL;
5472 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5473 int set_regs_matched_done = 0;
5475 /* Used when we pop values we don't care about. */
5476 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5477 const CHAR_TYPE **reg_dummy;
5478 register_info_type *reg_info_dummy;
5482 /* Counts the total number of registers pushed. */
5483 unsigned num_regs_pushed = 0;
5486 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5490 #ifdef MATCH_MAY_ALLOCATE
5491 /* Do not bother to initialize all the register variables if there are
5492 no groups in the pattern, as it takes a fair amount of time. If
5493 there are groups, we include space for register 0 (the whole
5494 pattern), even though we never use it, since it simplifies the
5495 array indexing. We should fix this. */
5498 regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5499 regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5500 old_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5501 old_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5502 best_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5503 best_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5504 reg_info = REGEX_TALLOC (num_regs, register_info_type);
5505 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5506 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
5508 if (!(regstart && regend && old_regstart && old_regend && reg_info
5509 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5517 /* We must initialize all our variables to NULL, so that
5518 `FREE_VARIABLES' doesn't try to free them. */
5519 regstart = regend = old_regstart = old_regend = best_regstart
5520 = best_regend = reg_dummy = NULL;
5521 reg_info = reg_info_dummy = (register_info_type *) NULL;
5523 #endif /* MATCH_MAY_ALLOCATE */
5525 /* The starting position is bogus. */
5527 if (pos < 0 || pos > csize1 + csize2)
5529 if (pos < 0 || pos > size1 + size2)
5537 /* Allocate wchar_t array for string1 and string2 and
5538 fill them with converted string. */
5541 string1 = TALLOC (csize1 + 1, CHAR_TYPE);
5542 mbs_offset1 = TALLOC (csize1 + 1, int);
5543 is_binary1 = TALLOC (csize1 + 1, int);
5544 if (!string1 || !mbs_offset1 || !is_binary1)
5546 if (string1) free(string1);
5547 if (mbs_offset1) free(mbs_offset1);
5548 if (is_binary1) free(is_binary1);
5551 size1 = convert_mbs_to_wcs(string1, cstring1, csize1,
5552 mbs_offset1, is_binary1);
5553 string1[size1] = L'\0'; /* for a sentinel */
5557 string2 = REGEX_TALLOC (csize2 + 1, CHAR_TYPE);
5558 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5559 is_binary2 = TALLOC (csize2 + 1, int);
5560 if (!string2 || !mbs_offset2 || !is_binary2)
5562 if (string1) free(string1);
5563 if (mbs_offset1) free(mbs_offset1);
5564 if (is_binary1) free(is_binary1);
5565 if (string2) free(string2);
5566 if (mbs_offset2) free(mbs_offset2);
5567 if (is_binary2) free(is_binary2);
5570 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5571 mbs_offset2, is_binary2);
5572 string2[size2] = L'\0'; /* for a sentinel */
5575 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5576 pattern to (char*) in regex_compile. */
5577 p = pattern = (CHAR_TYPE*)bufp->buffer;
5578 pend = (CHAR_TYPE*)(bufp->buffer + bufp->used);
5580 #endif /* MBS_SUPPORT */
5582 /* Initialize subexpression text positions to -1 to mark ones that no
5583 start_memory/stop_memory has been seen for. Also initialize the
5584 register information struct. */
5585 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5587 regstart[mcnt] = regend[mcnt]
5588 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5590 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5591 IS_ACTIVE (reg_info[mcnt]) = 0;
5592 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5593 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5596 /* We move `string1' into `string2' if the latter's empty -- but not if
5597 `string1' is null. */
5598 if (size2 == 0 && string1 != NULL)
5605 end1 = string1 + size1;
5606 end2 = string2 + size2;
5608 /* Compute where to stop matching, within the two strings. */
5612 mcnt = count_mbs_length(mbs_offset1, stop);
5613 end_match_1 = string1 + mcnt;
5614 end_match_2 = string2;
5619 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5620 end_match_2 = string2 + mcnt;
5623 { /* count_mbs_length return error. */
5630 end_match_1 = string1 + stop;
5631 end_match_2 = string2;
5636 end_match_2 = string2 + stop - size1;
5638 #endif /* MBS_SUPPORT */
5640 /* `p' scans through the pattern as `d' scans through the data.
5641 `dend' is the end of the input string that `d' points within. `d'
5642 is advanced into the following input string whenever necessary, but
5643 this happens before fetching; therefore, at the beginning of the
5644 loop, `d' can be pointing at the end of a string, but it cannot
5647 if (size1 > 0 && pos <= csize1)
5649 mcnt = count_mbs_length(mbs_offset1, pos);
5655 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5661 { /* count_mbs_length return error. */
5666 if (size1 > 0 && pos <= size1)
5673 d = string2 + pos - size1;
5676 #endif /* MBS_SUPPORT */
5678 DEBUG_PRINT1 ("The compiled pattern is:\n");
5679 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5680 DEBUG_PRINT1 ("The string to match is: `");
5681 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5682 DEBUG_PRINT1 ("'\n");
5684 /* This loops over pattern commands. It exits by returning from the
5685 function if the match is complete, or it drops through if the match
5686 fails at this starting point in the input data. */
5690 DEBUG_PRINT2 ("\n%p: ", p);
5692 DEBUG_PRINT2 ("\n0x%x: ", p);
5696 { /* End of pattern means we might have succeeded. */
5697 DEBUG_PRINT1 ("end of pattern ... ");
5699 /* If we haven't matched the entire string, and we want the
5700 longest match, try backtracking. */
5701 if (d != end_match_2)
5703 /* 1 if this match ends in the same string (string1 or string2)
5704 as the best previous match. */
5705 boolean same_str_p = (FIRST_STRING_P (match_end)
5706 == MATCHING_IN_FIRST_STRING);
5707 /* 1 if this match is the best seen so far. */
5708 boolean best_match_p;
5710 /* AIX compiler got confused when this was combined
5711 with the previous declaration. */
5713 best_match_p = d > match_end;
5715 best_match_p = !MATCHING_IN_FIRST_STRING;
5717 DEBUG_PRINT1 ("backtracking.\n");
5719 if (!FAIL_STACK_EMPTY ())
5720 { /* More failure points to try. */
5722 /* If exceeds best match so far, save it. */
5723 if (!best_regs_set || best_match_p)
5725 best_regs_set = true;
5728 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5730 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5732 best_regstart[mcnt] = regstart[mcnt];
5733 best_regend[mcnt] = regend[mcnt];
5739 /* If no failure points, don't restore garbage. And if
5740 last match is real best match, don't restore second
5742 else if (best_regs_set && !best_match_p)
5745 /* Restore best match. It may happen that `dend ==
5746 end_match_1' while the restored d is in string2.
5747 For example, the pattern `x.*y.*z' against the
5748 strings `x-' and `y-z-', if the two strings are
5749 not consecutive in memory. */
5750 DEBUG_PRINT1 ("Restoring best registers.\n");
5753 dend = ((d >= string1 && d <= end1)
5754 ? end_match_1 : end_match_2);
5756 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5758 regstart[mcnt] = best_regstart[mcnt];
5759 regend[mcnt] = best_regend[mcnt];
5762 } /* d != end_match_2 */
5765 DEBUG_PRINT1 ("Accepting match.\n");
5766 /* If caller wants register contents data back, do it. */
5767 if (regs && !bufp->no_sub)
5769 /* Have the register data arrays been allocated? */
5770 if (bufp->regs_allocated == REGS_UNALLOCATED)
5771 { /* No. So allocate them with malloc. We need one
5772 extra element beyond `num_regs' for the `-1' marker
5774 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5775 regs->start = TALLOC (regs->num_regs, regoff_t);
5776 regs->end = TALLOC (regs->num_regs, regoff_t);
5777 if (regs->start == NULL || regs->end == NULL)
5782 bufp->regs_allocated = REGS_REALLOCATE;
5784 else if (bufp->regs_allocated == REGS_REALLOCATE)
5785 { /* Yes. If we need more elements than were already
5786 allocated, reallocate them. If we need fewer, just
5788 if (regs->num_regs < num_regs + 1)
5790 regs->num_regs = num_regs + 1;
5791 RETALLOC (regs->start, regs->num_regs, regoff_t);
5792 RETALLOC (regs->end, regs->num_regs, regoff_t);
5793 if (regs->start == NULL || regs->end == NULL)
5802 /* These braces fend off a "empty body in an else-statement"
5803 warning under GCC when assert expands to nothing. */
5804 assert (bufp->regs_allocated == REGS_FIXED);
5807 /* Convert the pointer data in `regstart' and `regend' to
5808 indices. Register zero has to be set differently,
5809 since we haven't kept track of any info for it. */
5810 if (regs->num_regs > 0)
5812 regs->start[0] = pos;
5814 if (MATCHING_IN_FIRST_STRING)
5815 regs->end[0] = mbs_offset1 != NULL ?
5816 mbs_offset1[d-string1] : 0;
5818 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
5819 mbs_offset2[d-string2] : 0);
5821 regs->end[0] = (MATCHING_IN_FIRST_STRING
5822 ? ((regoff_t) (d - string1))
5823 : ((regoff_t) (d - string2 + size1)));
5824 #endif /* MBS_SUPPORT */
5827 /* Go through the first `min (num_regs, regs->num_regs)'
5828 registers, since that is all we initialized. */
5829 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
5832 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
5833 regs->start[mcnt] = regs->end[mcnt] = -1;
5837 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
5839 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
5843 /* If the regs structure we return has more elements than
5844 were in the pattern, set the extra elements to -1. If
5845 we (re)allocated the registers, this is the case,
5846 because we always allocate enough to have at least one
5848 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
5849 regs->start[mcnt] = regs->end[mcnt] = -1;
5850 } /* regs && !bufp->no_sub */
5852 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5853 nfailure_points_pushed, nfailure_points_popped,
5854 nfailure_points_pushed - nfailure_points_popped);
5855 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5858 if (MATCHING_IN_FIRST_STRING)
5859 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
5861 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
5865 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
5868 #endif /* MBS_SUPPORT */
5870 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5876 /* Otherwise match next pattern command. */
5877 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5879 /* Ignore these. Used to ignore the n of succeed_n's which
5880 currently have n == 0. */
5882 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5886 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5889 /* Match the next n pattern characters exactly. The following
5890 byte in the pattern defines n, and the n bytes after that
5891 are the characters to match. */
5897 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5899 /* This is written out as an if-else so we don't waste time
5900 testing `translate' inside the loop. */
5909 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5910 != (US_CHAR_TYPE) *p++)
5915 if (*d++ != (CHAR_TYPE) *p++)
5919 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5920 != (US_CHAR_TYPE) *p++)
5922 #endif /* MBS_SUPPORT */
5931 if (*d++ != (CHAR_TYPE) *p++) goto fail;
5935 SET_REGS_MATCHED ();
5939 /* Match any character except possibly a newline or a null. */
5941 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5945 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
5946 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
5949 SET_REGS_MATCHED ();
5950 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
5958 register US_CHAR_TYPE c;
5960 unsigned int i, char_class_length, coll_symbol_length,
5961 equiv_class_length, ranges_length, chars_length, length;
5962 CHAR_TYPE *workp, *workp2, *charset_top;
5963 #define WORK_BUFFER_SIZE 128
5964 CHAR_TYPE str_buf[WORK_BUFFER_SIZE];
5968 #endif /* MBS_SUPPORT */
5969 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5971 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5973 c = TRANSLATE (*d); /* The character to match. */
5976 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
5978 charset_top = p - 1;
5979 char_class_length = *p++;
5980 coll_symbol_length = *p++;
5981 equiv_class_length = *p++;
5982 ranges_length = *p++;
5983 chars_length = *p++;
5984 /* p points charset[6], so the address of the next instruction
5985 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
5986 where l=length of char_classes, m=length of collating_symbol,
5987 n=equivalence_class, o=length of char_range,
5988 p'=length of character. */
5990 /* Update p to indicate the next instruction. */
5991 p += char_class_length + coll_symbol_length+ equiv_class_length +
5992 2*ranges_length + chars_length;
5994 /* match with char_class? */
5995 for (i = 0; i < char_class_length ; i++)
5996 if (iswctype((wint_t)c, (wctype_t)(*workp++)))
5997 goto char_set_matched;
5999 /* match with collating_symbol? */
6003 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6007 wextra = (int32_t*) *workp++;
6008 for (i = 0; i < *wextra; ++i)
6009 if (TRANSLATE(d[i]) != wextra[1 + i])
6014 /* Update d, however d will be incremented at
6015 char_set_matched:, we decrement d here. */
6017 goto char_set_matched;
6021 else /* (nrules == 0) */
6023 /* If we can't look up collation data, we use wcscoll
6026 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6028 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6029 length = wcslen(workp);
6031 /* If wcscoll(the collating symbol, whole string) > 0,
6032 any substring of the string never match with the
6033 collating symbol. */
6034 if (wcscoll(workp, d) > 0)
6036 workp += length + 1;
6040 /* First, we compare the collating symbol with
6041 the first character of the string.
6042 If it don't match, we add the next character to
6043 the compare buffer in turn. */
6044 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6049 if (dend == end_match_2)
6055 /* add next character to the compare buffer. */
6056 str_buf[i] = TRANSLATE(*d);
6057 str_buf[i+1] = '\0';
6059 match = wcscoll(workp, str_buf);
6061 goto char_set_matched;
6064 /* (str_buf > workp) indicate (str_buf + X > workp),
6065 because for all X (str_buf + X > str_buf).
6066 So we don't need continue this loop. */
6069 /* Otherwise(str_buf < workp),
6070 (str_buf+next_character) may equals (workp).
6071 So we continue this loop. */
6076 workp += length + 1;
6079 /* match with equivalence_class? */
6083 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6084 /* Try to match the equivalence class against
6085 those known to the collate implementation. */
6086 const int32_t *table;
6087 const int32_t *weights;
6088 const int32_t *extra;
6089 const int32_t *indirect;
6094 /* This #include defines a local function! */
6095 # include <locale/weightwc.h>
6097 table = (const int32_t *)
6098 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6099 weights = (const wint_t *)
6100 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6101 extra = (const wint_t *)
6102 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6103 indirect = (const int32_t *)
6104 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6106 /* Write 1 collating element to str_buf, and
6110 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6112 cp = (wint_t*)str_buf;
6115 if (dend == end_match_2)
6120 str_buf[i] = TRANSLATE(*(d+i));
6121 str_buf[i+1] = '\0'; /* sentinel */
6122 idx2 = findidx ((const wint_t**)&cp);
6125 /* Update d, however d will be incremented at
6126 char_set_matched:, we decrement d here. */
6127 d = backup_d + (wint_t)cp - (wint_t)str_buf - 1;
6130 if (dend == end_match_2)
6139 len = weights[idx2];
6141 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6144 idx = (int32_t)*workp;
6145 /* We already checked idx != 0 in regex_compile. */
6147 if (idx2 != 0 && len == weights[idx])
6150 while (cnt < len && (weights[idx + 1 + cnt]
6151 == weights[idx2 + 1 + cnt]))
6155 goto char_set_matched;
6162 else /* (nrules == 0) */
6164 /* If we can't look up collation data, we use wcscoll
6167 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6169 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6170 length = wcslen(workp);
6172 /* If wcscoll(the collating symbol, whole string) > 0,
6173 any substring of the string never match with the
6174 collating symbol. */
6175 if (wcscoll(workp, d) > 0)
6177 workp += length + 1;
6181 /* First, we compare the equivalence class with
6182 the first character of the string.
6183 If it don't match, we add the next character to
6184 the compare buffer in turn. */
6185 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6190 if (dend == end_match_2)
6196 /* add next character to the compare buffer. */
6197 str_buf[i] = TRANSLATE(*d);
6198 str_buf[i+1] = '\0';
6200 match = wcscoll(workp, str_buf);
6203 goto char_set_matched;
6206 /* (str_buf > workp) indicate (str_buf + X > workp),
6207 because for all X (str_buf + X > str_buf).
6208 So we don't need continue this loop. */
6211 /* Otherwise(str_buf < workp),
6212 (str_buf+next_character) may equals (workp).
6213 So we continue this loop. */
6218 workp += length + 1;
6222 /* match with char_range? */
6226 uint32_t collseqval;
6227 const char *collseq = (const char *)
6228 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6230 collseqval = collseq_table_lookup (collseq, c);
6232 for (; workp < p - chars_length ;)
6234 uint32_t start_val, end_val;
6236 /* We already compute the collation sequence value
6237 of the characters (or collating symbols). */
6238 start_val = (uint32_t) *workp++; /* range_start */
6239 end_val = (uint32_t) *workp++; /* range_end */
6241 if (start_val <= collseqval && collseqval <= end_val)
6242 goto char_set_matched;
6248 /* We set range_start_char at str_buf[0], range_end_char
6249 at str_buf[4], and compared char at str_buf[2]. */
6254 for (; workp < p - chars_length ;)
6256 wchar_t *range_start_char, *range_end_char;
6258 /* match if (range_start_char <= c <= range_end_char). */
6260 /* If range_start(or end) < 0, we assume -range_start(end)
6261 is the offset of the collating symbol which is specified
6262 as the character of the range start(end). */
6266 range_start_char = charset_top - (*workp++);
6269 str_buf[0] = *workp++;
6270 range_start_char = str_buf;
6275 range_end_char = charset_top - (*workp++);
6278 str_buf[4] = *workp++;
6279 range_end_char = str_buf + 4;
6282 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6283 wcscoll(str_buf+2, range_end_char) <= 0)
6285 goto char_set_matched;
6289 /* match with char? */
6290 for (; workp < p ; workp++)
6292 goto char_set_matched;
6299 /* Cast to `unsigned' instead of `unsigned char' in case the
6300 bit list is a full 32 bytes long. */
6301 if (c < (unsigned) (*p * BYTEWIDTH)
6302 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6307 if (!not) goto fail;
6308 #undef WORK_BUFFER_SIZE
6309 #endif /* MBS_SUPPORT */
6310 SET_REGS_MATCHED ();
6316 /* The beginning of a group is represented by start_memory.
6317 The arguments are the register number in the next byte, and the
6318 number of groups inner to this one in the next. The text
6319 matched within the group is recorded (in the internal
6320 registers data structure) under the register number. */
6322 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6323 (long int) *p, (long int) p[1]);
6325 /* Find out if this group can match the empty string. */
6326 p1 = p; /* To send to group_match_null_string_p. */
6328 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6329 REG_MATCH_NULL_STRING_P (reg_info[*p])
6330 = group_match_null_string_p (&p1, pend, reg_info);
6332 /* Save the position in the string where we were the last time
6333 we were at this open-group operator in case the group is
6334 operated upon by a repetition operator, e.g., with `(a*)*b'
6335 against `ab'; then we want to ignore where we are now in
6336 the string in case this attempt to match fails. */
6337 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6338 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6340 DEBUG_PRINT2 (" old_regstart: %d\n",
6341 POINTER_TO_OFFSET (old_regstart[*p]));
6344 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6346 IS_ACTIVE (reg_info[*p]) = 1;
6347 MATCHED_SOMETHING (reg_info[*p]) = 0;
6349 /* Clear this whenever we change the register activity status. */
6350 set_regs_matched_done = 0;
6352 /* This is the new highest active register. */
6353 highest_active_reg = *p;
6355 /* If nothing was active before, this is the new lowest active
6357 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6358 lowest_active_reg = *p;
6360 /* Move past the register number and inner group count. */
6362 just_past_start_mem = p;
6367 /* The stop_memory opcode represents the end of a group. Its
6368 arguments are the same as start_memory's: the register
6369 number, and the number of inner groups. */
6371 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6372 (long int) *p, (long int) p[1]);
6374 /* We need to save the string position the last time we were at
6375 this close-group operator in case the group is operated
6376 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6377 against `aba'; then we want to ignore where we are now in
6378 the string in case this attempt to match fails. */
6379 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6380 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6382 DEBUG_PRINT2 (" old_regend: %d\n",
6383 POINTER_TO_OFFSET (old_regend[*p]));
6386 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6388 /* This register isn't active anymore. */
6389 IS_ACTIVE (reg_info[*p]) = 0;
6391 /* Clear this whenever we change the register activity status. */
6392 set_regs_matched_done = 0;
6394 /* If this was the only register active, nothing is active
6396 if (lowest_active_reg == highest_active_reg)
6398 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6399 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6402 { /* We must scan for the new highest active register, since
6403 it isn't necessarily one less than now: consider
6404 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6405 new highest active register is 1. */
6406 US_CHAR_TYPE r = *p - 1;
6407 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6410 /* If we end up at register zero, that means that we saved
6411 the registers as the result of an `on_failure_jump', not
6412 a `start_memory', and we jumped to past the innermost
6413 `stop_memory'. For example, in ((.)*) we save
6414 registers 1 and 2 as a result of the *, but when we pop
6415 back to the second ), we are at the stop_memory 1.
6416 Thus, nothing is active. */
6419 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6420 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6423 highest_active_reg = r;
6426 /* If just failed to match something this time around with a
6427 group that's operated on by a repetition operator, try to
6428 force exit from the ``loop'', and restore the register
6429 information for this group that we had before trying this
6431 if ((!MATCHED_SOMETHING (reg_info[*p])
6432 || just_past_start_mem == p - 1)
6435 boolean is_a_jump_n = false;
6439 switch ((re_opcode_t) *p1++)
6443 case pop_failure_jump:
6444 case maybe_pop_jump:
6446 case dummy_failure_jump:
6447 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6449 p1 += OFFSET_ADDRESS_SIZE;
6457 /* If the next operation is a jump backwards in the pattern
6458 to an on_failure_jump right before the start_memory
6459 corresponding to this stop_memory, exit from the loop
6460 by forcing a failure after pushing on the stack the
6461 on_failure_jump's jump in the pattern, and d. */
6462 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6463 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6464 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6466 /* If this group ever matched anything, then restore
6467 what its registers were before trying this last
6468 failed match, e.g., with `(a*)*b' against `ab' for
6469 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6470 against `aba' for regend[3].
6472 Also restore the registers for inner groups for,
6473 e.g., `((a*)(b*))*' against `aba' (register 3 would
6474 otherwise get trashed). */
6476 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6480 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6482 /* Restore this and inner groups' (if any) registers. */
6483 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6486 regstart[r] = old_regstart[r];
6488 /* xx why this test? */
6489 if (old_regend[r] >= regstart[r])
6490 regend[r] = old_regend[r];
6494 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6495 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6501 /* Move past the register number and the inner group count. */
6506 /* \<digit> has been turned into a `duplicate' command which is
6507 followed by the numeric value of <digit> as the register number. */
6510 register const CHAR_TYPE *d2, *dend2;
6511 int regno = *p++; /* Get which register to match against. */
6512 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6514 /* Can't back reference a group which we've never matched. */
6515 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6518 /* Where in input to try to start matching. */
6519 d2 = regstart[regno];
6521 /* Where to stop matching; if both the place to start and
6522 the place to stop matching are in the same string, then
6523 set to the place to stop, otherwise, for now have to use
6524 the end of the first string. */
6526 dend2 = ((FIRST_STRING_P (regstart[regno])
6527 == FIRST_STRING_P (regend[regno]))
6528 ? regend[regno] : end_match_1);
6531 /* If necessary, advance to next segment in register
6535 if (dend2 == end_match_2) break;
6536 if (dend2 == regend[regno]) break;
6538 /* End of string1 => advance to string2. */
6540 dend2 = regend[regno];
6542 /* At end of register contents => success */
6543 if (d2 == dend2) break;
6545 /* If necessary, advance to next segment in data. */
6548 /* How many characters left in this segment to match. */
6551 /* Want how many consecutive characters we can match in
6552 one shot, so, if necessary, adjust the count. */
6553 if (mcnt > dend2 - d2)
6556 /* Compare that many; failure if mismatch, else move
6559 ? bcmp_translate (d, d2, mcnt, translate)
6560 : memcmp (d, d2, mcnt*sizeof(US_CHAR_TYPE)))
6562 d += mcnt, d2 += mcnt;
6564 /* Do this because we've match some characters. */
6565 SET_REGS_MATCHED ();
6571 /* begline matches the empty string at the beginning of the string
6572 (unless `not_bol' is set in `bufp'), and, if
6573 `newline_anchor' is set, after newlines. */
6575 DEBUG_PRINT1 ("EXECUTING begline.\n");
6577 if (AT_STRINGS_BEG (d))
6579 if (!bufp->not_bol) break;
6581 else if (d[-1] == '\n' && bufp->newline_anchor)
6585 /* In all other cases, we fail. */
6589 /* endline is the dual of begline. */
6591 DEBUG_PRINT1 ("EXECUTING endline.\n");
6593 if (AT_STRINGS_END (d))
6595 if (!bufp->not_eol) break;
6598 /* We have to ``prefetch'' the next character. */
6599 else if ((d == end1 ? *string2 : *d) == '\n'
6600 && bufp->newline_anchor)
6607 /* Match at the very beginning of the data. */
6609 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6610 if (AT_STRINGS_BEG (d))
6615 /* Match at the very end of the data. */
6617 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6618 if (AT_STRINGS_END (d))
6623 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6624 pushes NULL as the value for the string on the stack. Then
6625 `pop_failure_point' will keep the current value for the
6626 string, instead of restoring it. To see why, consider
6627 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6628 then the . fails against the \n. But the next thing we want
6629 to do is match the \n against the \n; if we restored the
6630 string value, we would be back at the foo.
6632 Because this is used only in specific cases, we don't need to
6633 check all the things that `on_failure_jump' does, to make
6634 sure the right things get saved on the stack. Hence we don't
6635 share its code. The only reason to push anything on the
6636 stack at all is that otherwise we would have to change
6637 `anychar's code to do something besides goto fail in this
6638 case; that seems worse than this. */
6639 case on_failure_keep_string_jump:
6640 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6642 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6644 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6646 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6649 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6653 /* Uses of on_failure_jump:
6655 Each alternative starts with an on_failure_jump that points
6656 to the beginning of the next alternative. Each alternative
6657 except the last ends with a jump that in effect jumps past
6658 the rest of the alternatives. (They really jump to the
6659 ending jump of the following alternative, because tensioning
6660 these jumps is a hassle.)
6662 Repeats start with an on_failure_jump that points past both
6663 the repetition text and either the following jump or
6664 pop_failure_jump back to this on_failure_jump. */
6665 case on_failure_jump:
6667 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6669 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6671 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6673 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6676 /* If this on_failure_jump comes right before a group (i.e.,
6677 the original * applied to a group), save the information
6678 for that group and all inner ones, so that if we fail back
6679 to this point, the group's information will be correct.
6680 For example, in \(a*\)*\1, we need the preceding group,
6681 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6683 /* We can't use `p' to check ahead because we push
6684 a failure point to `p + mcnt' after we do this. */
6687 /* We need to skip no_op's before we look for the
6688 start_memory in case this on_failure_jump is happening as
6689 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6691 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6694 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6696 /* We have a new highest active register now. This will
6697 get reset at the start_memory we are about to get to,
6698 but we will have saved all the registers relevant to
6699 this repetition op, as described above. */
6700 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6701 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6702 lowest_active_reg = *(p1 + 1);
6705 DEBUG_PRINT1 (":\n");
6706 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6710 /* A smart repeat ends with `maybe_pop_jump'.
6711 We change it to either `pop_failure_jump' or `jump'. */
6712 case maybe_pop_jump:
6713 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6714 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6716 register US_CHAR_TYPE *p2 = p;
6718 /* Compare the beginning of the repeat with what in the
6719 pattern follows its end. If we can establish that there
6720 is nothing that they would both match, i.e., that we
6721 would have to backtrack because of (as in, e.g., `a*a')
6722 then we can change to pop_failure_jump, because we'll
6723 never have to backtrack.
6725 This is not true in the case of alternatives: in
6726 `(a|ab)*' we do need to backtrack to the `ab' alternative
6727 (e.g., if the string was `ab'). But instead of trying to
6728 detect that here, the alternative has put on a dummy
6729 failure point which is what we will end up popping. */
6731 /* Skip over open/close-group commands.
6732 If what follows this loop is a ...+ construct,
6733 look at what begins its body, since we will have to
6734 match at least one of that. */
6738 && ((re_opcode_t) *p2 == stop_memory
6739 || (re_opcode_t) *p2 == start_memory))
6741 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6742 && (re_opcode_t) *p2 == dummy_failure_jump)
6743 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6749 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
6750 to the `maybe_finalize_jump' of this case. Examine what
6753 /* If we're at the end of the pattern, we can change. */
6756 /* Consider what happens when matching ":\(.*\)"
6757 against ":/". I don't really understand this code
6759 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6762 (" End of pattern: change to `pop_failure_jump'.\n");
6765 else if ((re_opcode_t) *p2 == exactn
6767 || (re_opcode_t) *p2 == exactn_bin
6769 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
6771 register US_CHAR_TYPE c
6772 = *p2 == (US_CHAR_TYPE) endline ? '\n' : p2[2];
6774 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
6776 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
6778 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
6780 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6783 if (MB_CUR_MAX != 1)
6784 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
6786 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
6789 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
6791 (char) p1[3+OFFSET_ADDRESS_SIZE]);
6795 else if ((re_opcode_t) p1[3] == charset
6796 || (re_opcode_t) p1[3] == charset_not)
6798 int not = (re_opcode_t) p1[3] == charset_not;
6800 if (c < (unsigned) (p1[4] * BYTEWIDTH)
6801 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6804 /* `not' is equal to 1 if c would match, which means
6805 that we can't change to pop_failure_jump. */
6808 p[-3] = (unsigned char) pop_failure_jump;
6809 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6812 #endif /* not MBS_SUPPORT */
6815 else if ((re_opcode_t) *p2 == charset)
6817 /* We win if the first character of the loop is not part
6819 if ((re_opcode_t) p1[3] == exactn
6820 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
6821 && (p2[2 + p1[5] / BYTEWIDTH]
6822 & (1 << (p1[5] % BYTEWIDTH)))))
6824 p[-3] = (unsigned char) pop_failure_jump;
6825 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6828 else if ((re_opcode_t) p1[3] == charset_not)
6831 /* We win if the charset_not inside the loop
6832 lists every character listed in the charset after. */
6833 for (idx = 0; idx < (int) p2[1]; idx++)
6834 if (! (p2[2 + idx] == 0
6835 || (idx < (int) p1[4]
6836 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
6841 p[-3] = (unsigned char) pop_failure_jump;
6842 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6845 else if ((re_opcode_t) p1[3] == charset)
6848 /* We win if the charset inside the loop
6849 has no overlap with the one after the loop. */
6851 idx < (int) p2[1] && idx < (int) p1[4];
6853 if ((p2[2 + idx] & p1[5 + idx]) != 0)
6856 if (idx == p2[1] || idx == p1[4])
6858 p[-3] = (unsigned char) pop_failure_jump;
6859 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6863 #endif /* not MBS_SUPPORT */
6865 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
6866 if ((re_opcode_t) p[-1] != pop_failure_jump)
6868 p[-1] = (US_CHAR_TYPE) jump;
6869 DEBUG_PRINT1 (" Match => jump.\n");
6870 goto unconditional_jump;
6872 /* Note fall through. */
6875 /* The end of a simple repeat has a pop_failure_jump back to
6876 its matching on_failure_jump, where the latter will push a
6877 failure point. The pop_failure_jump takes off failure
6878 points put on by this pop_failure_jump's matching
6879 on_failure_jump; we got through the pattern to here from the
6880 matching on_failure_jump, so didn't fail. */
6881 case pop_failure_jump:
6883 /* We need to pass separate storage for the lowest and
6884 highest registers, even though we don't care about the
6885 actual values. Otherwise, we will restore only one
6886 register from the stack, since lowest will == highest in
6887 `pop_failure_point'. */
6888 active_reg_t dummy_low_reg, dummy_high_reg;
6889 US_CHAR_TYPE *pdummy = NULL;
6890 const CHAR_TYPE *sdummy = NULL;
6892 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
6893 POP_FAILURE_POINT (sdummy, pdummy,
6894 dummy_low_reg, dummy_high_reg,
6895 reg_dummy, reg_dummy, reg_info_dummy);
6897 /* Note fall through. */
6901 DEBUG_PRINT2 ("\n%p: ", p);
6903 DEBUG_PRINT2 ("\n0x%x: ", p);
6905 /* Note fall through. */
6907 /* Unconditionally jump (without popping any failure points). */
6909 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
6910 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
6911 p += mcnt; /* Do the jump. */
6913 DEBUG_PRINT2 ("(to %p).\n", p);
6915 DEBUG_PRINT2 ("(to 0x%x).\n", p);
6920 /* We need this opcode so we can detect where alternatives end
6921 in `group_match_null_string_p' et al. */
6923 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
6924 goto unconditional_jump;
6927 /* Normally, the on_failure_jump pushes a failure point, which
6928 then gets popped at pop_failure_jump. We will end up at
6929 pop_failure_jump, also, and with a pattern of, say, `a+', we
6930 are skipping over the on_failure_jump, so we have to push
6931 something meaningless for pop_failure_jump to pop. */
6932 case dummy_failure_jump:
6933 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
6934 /* It doesn't matter what we push for the string here. What
6935 the code at `fail' tests is the value for the pattern. */
6936 PUSH_FAILURE_POINT (NULL, NULL, -2);
6937 goto unconditional_jump;
6940 /* At the end of an alternative, we need to push a dummy failure
6941 point in case we are followed by a `pop_failure_jump', because
6942 we don't want the failure point for the alternative to be
6943 popped. For example, matching `(a|ab)*' against `aab'
6944 requires that we match the `ab' alternative. */
6945 case push_dummy_failure:
6946 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
6947 /* See comments just above at `dummy_failure_jump' about the
6949 PUSH_FAILURE_POINT (NULL, NULL, -2);
6952 /* Have to succeed matching what follows at least n times.
6953 After that, handle like `on_failure_jump'. */
6955 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6956 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
6959 /* Originally, this is how many times we HAVE to succeed. */
6963 p += OFFSET_ADDRESS_SIZE;
6964 STORE_NUMBER_AND_INCR (p, mcnt);
6966 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
6969 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
6976 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
6977 p + OFFSET_ADDRESS_SIZE);
6979 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
6980 p + OFFSET_ADDRESS_SIZE);
6984 p[1] = (US_CHAR_TYPE) no_op;
6986 p[2] = (US_CHAR_TYPE) no_op;
6987 p[3] = (US_CHAR_TYPE) no_op;
6988 #endif /* MBS_SUPPORT */
6994 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6995 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
6997 /* Originally, this is how many times we CAN jump. */
7001 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7004 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7007 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7010 goto unconditional_jump;
7012 /* If don't have to jump any more, skip over the rest of command. */
7014 p += 2 * OFFSET_ADDRESS_SIZE;
7019 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7021 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7023 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7025 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7027 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7029 STORE_NUMBER (p1, mcnt);
7034 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7035 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7036 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7037 macro and introducing temporary variables works around the bug. */
7040 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7041 if (AT_WORD_BOUNDARY (d))
7046 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7047 if (AT_WORD_BOUNDARY (d))
7053 boolean prevchar, thischar;
7055 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7056 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7059 prevchar = WORDCHAR_P (d - 1);
7060 thischar = WORDCHAR_P (d);
7061 if (prevchar != thischar)
7068 boolean prevchar, thischar;
7070 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7071 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7074 prevchar = WORDCHAR_P (d - 1);
7075 thischar = WORDCHAR_P (d);
7076 if (prevchar != thischar)
7083 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7084 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7089 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7090 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7091 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
7097 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7098 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7103 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7104 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7109 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7110 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7115 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7120 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7124 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7126 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7128 SET_REGS_MATCHED ();
7132 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7134 goto matchnotsyntax;
7137 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7141 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7143 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7145 SET_REGS_MATCHED ();
7148 #else /* not emacs */
7150 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7152 if (!WORDCHAR_P (d))
7154 SET_REGS_MATCHED ();
7159 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7163 SET_REGS_MATCHED ();
7166 #endif /* not emacs */
7171 continue; /* Successfully executed one pattern command; keep going. */
7174 /* We goto here if a matching operation fails. */
7176 if (!FAIL_STACK_EMPTY ())
7177 { /* A restart point is known. Restore to that state. */
7178 DEBUG_PRINT1 ("\nFAIL:\n");
7179 POP_FAILURE_POINT (d, p,
7180 lowest_active_reg, highest_active_reg,
7181 regstart, regend, reg_info);
7183 /* If this failure point is a dummy, try the next one. */
7187 /* If we failed to the end of the pattern, don't examine *p. */
7191 boolean is_a_jump_n = false;
7193 /* If failed to a backwards jump that's part of a repetition
7194 loop, need to pop this failure point and use the next one. */
7195 switch ((re_opcode_t) *p)
7199 case maybe_pop_jump:
7200 case pop_failure_jump:
7203 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7206 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7208 && (re_opcode_t) *p1 == on_failure_jump))
7216 if (d >= string1 && d <= end1)
7220 break; /* Matching at this starting point really fails. */
7224 goto restore_best_regs;
7228 return -1; /* Failure to match. */
7231 /* Subroutine definitions for re_match_2. */
7234 /* We are passed P pointing to a register number after a start_memory.
7236 Return true if the pattern up to the corresponding stop_memory can
7237 match the empty string, and false otherwise.
7239 If we find the matching stop_memory, sets P to point to one past its number.
7240 Otherwise, sets P to an undefined byte less than or equal to END.
7242 We don't handle duplicates properly (yet). */
7245 group_match_null_string_p (p, end, reg_info)
7246 US_CHAR_TYPE **p, *end;
7247 register_info_type *reg_info;
7250 /* Point to after the args to the start_memory. */
7251 US_CHAR_TYPE *p1 = *p + 2;
7255 /* Skip over opcodes that can match nothing, and return true or
7256 false, as appropriate, when we get to one that can't, or to the
7257 matching stop_memory. */
7259 switch ((re_opcode_t) *p1)
7261 /* Could be either a loop or a series of alternatives. */
7262 case on_failure_jump:
7264 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7266 /* If the next operation is not a jump backwards in the
7271 /* Go through the on_failure_jumps of the alternatives,
7272 seeing if any of the alternatives cannot match nothing.
7273 The last alternative starts with only a jump,
7274 whereas the rest start with on_failure_jump and end
7275 with a jump, e.g., here is the pattern for `a|b|c':
7277 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7278 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7281 So, we have to first go through the first (n-1)
7282 alternatives and then deal with the last one separately. */
7285 /* Deal with the first (n-1) alternatives, which start
7286 with an on_failure_jump (see above) that jumps to right
7287 past a jump_past_alt. */
7289 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7292 /* `mcnt' holds how many bytes long the alternative
7293 is, including the ending `jump_past_alt' and
7296 if (!alt_match_null_string_p (p1, p1 + mcnt -
7297 (1 + OFFSET_ADDRESS_SIZE),
7301 /* Move to right after this alternative, including the
7305 /* Break if it's the beginning of an n-th alternative
7306 that doesn't begin with an on_failure_jump. */
7307 if ((re_opcode_t) *p1 != on_failure_jump)
7310 /* Still have to check that it's not an n-th
7311 alternative that starts with an on_failure_jump. */
7313 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7314 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7317 /* Get to the beginning of the n-th alternative. */
7318 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7323 /* Deal with the last alternative: go back and get number
7324 of the `jump_past_alt' just before it. `mcnt' contains
7325 the length of the alternative. */
7326 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7328 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
7331 p1 += mcnt; /* Get past the n-th alternative. */
7337 assert (p1[1] == **p);
7343 if (!common_op_match_null_string_p (&p1, end, reg_info))
7346 } /* while p1 < end */
7349 } /* group_match_null_string_p */
7352 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7353 It expects P to be the first byte of a single alternative and END one
7354 byte past the last. The alternative can contain groups. */
7357 alt_match_null_string_p (p, end, reg_info)
7358 US_CHAR_TYPE *p, *end;
7359 register_info_type *reg_info;
7362 US_CHAR_TYPE *p1 = p;
7366 /* Skip over opcodes that can match nothing, and break when we get
7367 to one that can't. */
7369 switch ((re_opcode_t) *p1)
7372 case on_failure_jump:
7374 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7379 if (!common_op_match_null_string_p (&p1, end, reg_info))
7382 } /* while p1 < end */
7385 } /* alt_match_null_string_p */
7388 /* Deals with the ops common to group_match_null_string_p and
7389 alt_match_null_string_p.
7391 Sets P to one after the op and its arguments, if any. */
7394 common_op_match_null_string_p (p, end, reg_info)
7395 US_CHAR_TYPE **p, *end;
7396 register_info_type *reg_info;
7401 US_CHAR_TYPE *p1 = *p;
7403 switch ((re_opcode_t) *p1++)
7423 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7424 ret = group_match_null_string_p (&p1, end, reg_info);
7426 /* Have to set this here in case we're checking a group which
7427 contains a group and a back reference to it. */
7429 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7430 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7436 /* If this is an optimized succeed_n for zero times, make the jump. */
7438 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7446 /* Get to the number of times to succeed. */
7447 p1 += OFFSET_ADDRESS_SIZE;
7448 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7452 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7453 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7461 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7466 p1 += 2 * OFFSET_ADDRESS_SIZE;
7469 /* All other opcodes mean we cannot match the empty string. */
7475 } /* common_op_match_null_string_p */
7478 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7479 bytes; nonzero otherwise. */
7482 bcmp_translate (s1, s2, len, translate)
7483 const CHAR_TYPE *s1, *s2;
7485 RE_TRANSLATE_TYPE translate;
7487 register const US_CHAR_TYPE *p1 = (const US_CHAR_TYPE *) s1;
7488 register const US_CHAR_TYPE *p2 = (const US_CHAR_TYPE *) s2;
7492 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7493 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7496 if (translate[*p1++] != translate[*p2++]) return 1;
7497 #endif /* MBS_SUPPORT */
7503 /* Entry points for GNU code. */
7505 /* re_compile_pattern is the GNU regular expression compiler: it
7506 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7507 Returns 0 if the pattern was valid, otherwise an error string.
7509 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7510 are set in BUFP on entry.
7512 We call regex_compile to do the actual compilation. */
7515 re_compile_pattern (pattern, length, bufp)
7516 const char *pattern;
7518 struct re_pattern_buffer *bufp;
7522 /* GNU code is written to assume at least RE_NREGS registers will be set
7523 (and at least one extra will be -1). */
7524 bufp->regs_allocated = REGS_UNALLOCATED;
7526 /* And GNU code determines whether or not to get register information
7527 by passing null for the REGS argument to re_match, etc., not by
7531 /* Match anchors at newline. */
7532 bufp->newline_anchor = 1;
7534 ret = regex_compile (pattern, length, re_syntax_options, bufp);
7538 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7541 weak_alias (__re_compile_pattern, re_compile_pattern)
7544 /* Entry points compatible with 4.2 BSD regex library. We don't define
7545 them unless specifically requested. */
7547 #if defined _REGEX_RE_COMP || defined _LIBC
7549 /* BSD has one and only one pattern buffer. */
7550 static struct re_pattern_buffer re_comp_buf;
7554 /* Make these definitions weak in libc, so POSIX programs can redefine
7555 these names if they don't use our functions, and still use
7556 regcomp/regexec below without link errors. */
7566 if (!re_comp_buf.buffer)
7567 return gettext ("No previous regular expression");
7571 if (!re_comp_buf.buffer)
7573 re_comp_buf.buffer = (unsigned char *) malloc (200);
7574 if (re_comp_buf.buffer == NULL)
7575 return (char *) gettext (re_error_msgid
7576 + re_error_msgid_idx[(int) REG_ESPACE]);
7577 re_comp_buf.allocated = 200;
7579 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7580 if (re_comp_buf.fastmap == NULL)
7581 return (char *) gettext (re_error_msgid
7582 + re_error_msgid_idx[(int) REG_ESPACE]);
7585 /* Since `re_exec' always passes NULL for the `regs' argument, we
7586 don't need to initialize the pattern buffer fields which affect it. */
7588 /* Match anchors at newlines. */
7589 re_comp_buf.newline_anchor = 1;
7591 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7596 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7597 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7608 const int len = strlen (s);
7610 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7613 #endif /* _REGEX_RE_COMP */
7615 /* POSIX.2 functions. Don't define these for Emacs. */
7619 /* regcomp takes a regular expression as a string and compiles it.
7621 PREG is a regex_t *. We do not expect any fields to be initialized,
7622 since POSIX says we shouldn't. Thus, we set
7624 `buffer' to the compiled pattern;
7625 `used' to the length of the compiled pattern;
7626 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7627 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7628 RE_SYNTAX_POSIX_BASIC;
7629 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7630 `fastmap' to an allocated space for the fastmap;
7631 `fastmap_accurate' to zero;
7632 `re_nsub' to the number of subexpressions in PATTERN.
7634 PATTERN is the address of the pattern string.
7636 CFLAGS is a series of bits which affect compilation.
7638 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7639 use POSIX basic syntax.
7641 If REG_NEWLINE is set, then . and [^...] don't match newline.
7642 Also, regexec will try a match beginning after every newline.
7644 If REG_ICASE is set, then we considers upper- and lowercase
7645 versions of letters to be equivalent when matching.
7647 If REG_NOSUB is set, then when PREG is passed to regexec, that
7648 routine will report only success or failure, and nothing about the
7651 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7652 the return codes and their meanings.) */
7655 regcomp (preg, pattern, cflags)
7657 const char *pattern;
7662 = (cflags & REG_EXTENDED) ?
7663 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7665 /* regex_compile will allocate the space for the compiled pattern. */
7667 preg->allocated = 0;
7670 /* Try to allocate space for the fastmap. */
7671 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7673 if (cflags & REG_ICASE)
7678 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7679 * sizeof (*(RE_TRANSLATE_TYPE)0));
7680 if (preg->translate == NULL)
7681 return (int) REG_ESPACE;
7683 /* Map uppercase characters to corresponding lowercase ones. */
7684 for (i = 0; i < CHAR_SET_SIZE; i++)
7685 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7688 preg->translate = NULL;
7690 /* If REG_NEWLINE is set, newlines are treated differently. */
7691 if (cflags & REG_NEWLINE)
7692 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7693 syntax &= ~RE_DOT_NEWLINE;
7694 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7695 /* It also changes the matching behavior. */
7696 preg->newline_anchor = 1;
7699 preg->newline_anchor = 0;
7701 preg->no_sub = !!(cflags & REG_NOSUB);
7703 /* POSIX says a null character in the pattern terminates it, so we
7704 can use strlen here in compiling the pattern. */
7705 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
7707 /* POSIX doesn't distinguish between an unmatched open-group and an
7708 unmatched close-group: both are REG_EPAREN. */
7709 if (ret == REG_ERPAREN) ret = REG_EPAREN;
7711 if (ret == REG_NOERROR && preg->fastmap)
7713 /* Compute the fastmap now, since regexec cannot modify the pattern
7715 if (re_compile_fastmap (preg) == -2)
7717 /* Some error occurred while computing the fastmap, just forget
7719 free (preg->fastmap);
7720 preg->fastmap = NULL;
7727 weak_alias (__regcomp, regcomp)
7731 /* regexec searches for a given pattern, specified by PREG, in the
7734 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7735 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
7736 least NMATCH elements, and we set them to the offsets of the
7737 corresponding matched substrings.
7739 EFLAGS specifies `execution flags' which affect matching: if
7740 REG_NOTBOL is set, then ^ does not match at the beginning of the
7741 string; if REG_NOTEOL is set, then $ does not match at the end.
7743 We return 0 if we find a match and REG_NOMATCH if not. */
7746 regexec (preg, string, nmatch, pmatch, eflags)
7747 const regex_t *preg;
7750 regmatch_t pmatch[];
7754 struct re_registers regs;
7755 regex_t private_preg;
7756 int len = strlen (string);
7757 boolean want_reg_info = !preg->no_sub && nmatch > 0;
7759 private_preg = *preg;
7761 private_preg.not_bol = !!(eflags & REG_NOTBOL);
7762 private_preg.not_eol = !!(eflags & REG_NOTEOL);
7764 /* The user has told us exactly how many registers to return
7765 information about, via `nmatch'. We have to pass that on to the
7766 matching routines. */
7767 private_preg.regs_allocated = REGS_FIXED;
7771 regs.num_regs = nmatch;
7772 regs.start = TALLOC (nmatch * 2, regoff_t);
7773 if (regs.start == NULL)
7774 return (int) REG_NOMATCH;
7775 regs.end = regs.start + nmatch;
7778 /* Perform the searching operation. */
7779 ret = re_search (&private_preg, string, len,
7780 /* start: */ 0, /* range: */ len,
7781 want_reg_info ? ®s : (struct re_registers *) 0);
7783 /* Copy the register information to the POSIX structure. */
7790 for (r = 0; r < nmatch; r++)
7792 pmatch[r].rm_so = regs.start[r];
7793 pmatch[r].rm_eo = regs.end[r];
7797 /* If we needed the temporary register info, free the space now. */
7801 /* We want zero return to mean success, unlike `re_search'. */
7802 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
7805 weak_alias (__regexec, regexec)
7809 /* Returns a message corresponding to an error code, ERRCODE, returned
7810 from either regcomp or regexec. We don't use PREG here. */
7813 regerror (errcode, preg, errbuf, errbuf_size)
7815 const regex_t *preg;
7823 || errcode >= (int) (sizeof (re_error_msgid_idx)
7824 / sizeof (re_error_msgid_idx[0])))
7825 /* Only error codes returned by the rest of the code should be passed
7826 to this routine. If we are given anything else, or if other regex
7827 code generates an invalid error code, then the program has a bug.
7828 Dump core so we can fix it. */
7831 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
7833 msg_size = strlen (msg) + 1; /* Includes the null. */
7835 if (errbuf_size != 0)
7837 if (msg_size > errbuf_size)
7839 #if defined HAVE_MEMPCPY || defined _LIBC
7840 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
7842 memcpy (errbuf, msg, errbuf_size - 1);
7843 errbuf[errbuf_size - 1] = 0;
7847 memcpy (errbuf, msg, msg_size);
7853 weak_alias (__regerror, regerror)
7857 /* Free dynamically allocated space used by PREG. */
7863 if (preg->buffer != NULL)
7864 free (preg->buffer);
7865 preg->buffer = NULL;
7867 preg->allocated = 0;
7870 if (preg->fastmap != NULL)
7871 free (preg->fastmap);
7872 preg->fastmap = NULL;
7873 preg->fastmap_accurate = 0;
7875 if (preg->translate != NULL)
7876 free (preg->translate);
7877 preg->translate = NULL;
7880 weak_alias (__regfree, regfree)
7883 #endif /* not emacs */