1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P1003.2/D11.2, except for some of the
4 internationalization features.)
6 Copyright (C) 1993,1994,1995,1996,1997,1999,2000 Free Software Foundation, Inc.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software Foundation,
20 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
34 #if defined(STDC_HEADERS) && !defined(emacs)
37 /* We need this for `regex.h', and perhaps for the Emacs include files. */
38 #include <sys/types.h>
41 /* For platform which support the ISO C amendement 1 functionality we
42 support user defined character classes. */
43 #if defined _LIBC || (defined HAVE_WCTYPE_H && defined HAVE_WCHAR_H)
48 /* This is for other GNU distributions with internationalized messages. */
49 #if HAVE_LIBINTL_H || defined (_LIBC)
52 # define gettext(msgid) (msgid)
56 /* This define is so xgettext can find the internationalizable
58 #define gettext_noop(String) String
61 /* The `emacs' switch turns on certain matching commands
62 that make sense only in Emacs. */
71 /* If we are not linking with Emacs proper,
72 we can't use the relocating allocator
73 even if config.h says that we can. */
76 #if defined (STDC_HEADERS) || defined (_LIBC)
83 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
84 If nothing else has been done, use the method below. */
85 #ifdef INHIBIT_STRING_HEADER
86 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
87 #if !defined (bzero) && !defined (bcopy)
88 #undef INHIBIT_STRING_HEADER
93 /* This is the normal way of making sure we have a bcopy and a bzero.
94 This is used in most programs--a few other programs avoid this
95 by defining INHIBIT_STRING_HEADER. */
96 #ifndef INHIBIT_STRING_HEADER
97 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
100 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
103 #define bcopy(s, d, n) memcpy ((d), (s), (n))
106 #define bzero(s, n) memset ((s), 0, (n))
113 /* Define the syntax stuff for \<, \>, etc. */
115 /* This must be nonzero for the wordchar and notwordchar pattern
116 commands in re_match_2. */
121 #ifdef SWITCH_ENUM_BUG
122 #define SWITCH_ENUM_CAST(x) ((int)(x))
124 #define SWITCH_ENUM_CAST(x) (x)
127 #endif /* not emacs */
129 /* Get the interface, including the syntax bits. */
132 /* isalpha etc. are used for the character classes. */
135 /* Jim Meyering writes:
137 "... Some ctype macros are valid only for character codes that
138 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
139 using /bin/cc or gcc but without giving an ansi option). So, all
140 ctype uses should be through macros like ISPRINT... If
141 STDC_HEADERS is defined, then autoconf has verified that the ctype
142 macros don't need to be guarded with references to isascii. ...
143 Defining isascii to 1 should let any compiler worth its salt
144 eliminate the && through constant folding." */
146 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
149 #define ISASCII(c) isascii(c)
153 #define ISBLANK(c) (ISASCII (c) && isblank (c))
155 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
158 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
160 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
163 #define ISPRINT(c) (ISASCII (c) && isprint (c))
164 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
165 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
166 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
167 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
168 #define ISLOWER(c) (ISASCII (c) && islower (c))
169 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
170 #define ISSPACE(c) (ISASCII (c) && isspace (c))
171 #define ISUPPER(c) (ISASCII (c) && isupper (c))
172 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
175 #define NULL (void *)0
178 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
179 since ours (we hope) works properly with all combinations of
180 machines, compilers, `char' and `unsigned char' argument types.
181 (Per Bothner suggested the basic approach.) */
182 #undef SIGN_EXTEND_CHAR
184 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
185 #else /* not __STDC__ */
186 /* As in Harbison and Steele. */
187 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
191 /* How many characters in the character set. */
192 #define CHAR_SET_SIZE 256
196 extern char *re_syntax_table;
198 #else /* not SYNTAX_TABLE */
200 static char re_syntax_table[CHAR_SET_SIZE];
210 bzero (re_syntax_table, sizeof re_syntax_table);
212 for (c = 0; c < CHAR_SET_SIZE; c++)
214 re_syntax_table[c] = Sword;
216 re_syntax_table['_'] = Sword;
221 #endif /* not SYNTAX_TABLE */
223 #define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
227 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
228 use `alloca' instead of `malloc'. This is because using malloc in
229 re_search* or re_match* could cause memory leaks when C-g is used in
230 Emacs; also, malloc is slower and causes storage fragmentation. On
231 the other hand, malloc is more portable, and easier to debug.
233 Because we sometimes use alloca, some routines have to be macros,
234 not functions -- `alloca'-allocated space disappears at the end of the
235 function it is called in. */
239 #define REGEX_ALLOCATE malloc
240 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
241 #define REGEX_FREE free
243 #else /* not REGEX_MALLOC */
245 /* Emacs already defines alloca, sometimes. */
248 /* Make alloca work the best possible way. */
250 #define alloca __builtin_alloca
251 #else /* not __GNUC__ */
254 #else /* not __GNUC__ or HAVE_ALLOCA_H */
255 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
256 #ifndef _AIX /* Already did AIX, up at the top. */
258 #endif /* not _AIX */
260 #endif /* not HAVE_ALLOCA_H */
261 #endif /* not __GNUC__ */
263 #endif /* not alloca */
265 #define REGEX_ALLOCATE alloca
267 /* Assumes a `char *destination' variable. */
268 #define REGEX_REALLOCATE(source, osize, nsize) \
269 (destination = (char *) alloca (nsize), \
270 bcopy (source, destination, osize), \
273 /* No need to do anything to free, after alloca. */
274 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
276 #endif /* not REGEX_MALLOC */
278 /* Define how to allocate the failure stack. */
280 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
282 #define REGEX_ALLOCATE_STACK(size) \
283 r_alloc (&failure_stack_ptr, (size))
284 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
285 r_re_alloc (&failure_stack_ptr, (nsize))
286 #define REGEX_FREE_STACK(ptr) \
287 r_alloc_free (&failure_stack_ptr)
289 #else /* not using relocating allocator */
293 #define REGEX_ALLOCATE_STACK malloc
294 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
295 #define REGEX_FREE_STACK free
297 #else /* not REGEX_MALLOC */
299 #define REGEX_ALLOCATE_STACK alloca
301 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
302 REGEX_REALLOCATE (source, osize, nsize)
303 /* No need to explicitly free anything. */
304 #define REGEX_FREE_STACK(arg)
306 #endif /* not REGEX_MALLOC */
307 #endif /* not using relocating allocator */
310 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
311 `string1' or just past its end. This works if PTR is NULL, which is
313 #define FIRST_STRING_P(ptr) \
314 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
316 /* (Re)Allocate N items of type T using malloc, or fail. */
317 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
318 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
319 #define RETALLOC_IF(addr, n, t) \
320 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
321 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
323 #define BYTEWIDTH 8 /* In bits. */
325 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
329 #define MAX(a, b) ((a) > (b) ? (a) : (b))
330 #define MIN(a, b) ((a) < (b) ? (a) : (b))
332 typedef char boolean;
336 static int re_match_2_internal ();
338 /* These are the command codes that appear in compiled regular
339 expressions. Some opcodes are followed by argument bytes. A
340 command code can specify any interpretation whatsoever for its
341 arguments. Zero bytes may appear in the compiled regular expression. */
347 /* Succeed right away--no more backtracking. */
350 /* Followed by one byte giving n, then by n literal bytes. */
353 /* Matches any (more or less) character. */
356 /* Matches any one char belonging to specified set. First
357 following byte is number of bitmap bytes. Then come bytes
358 for a bitmap saying which chars are in. Bits in each byte
359 are ordered low-bit-first. A character is in the set if its
360 bit is 1. A character too large to have a bit in the map is
361 automatically not in the set. */
364 /* Same parameters as charset, but match any character that is
365 not one of those specified. */
368 /* Start remembering the text that is matched, for storing in a
369 register. Followed by one byte with the register number, in
370 the range 0 to one less than the pattern buffer's re_nsub
371 field. Then followed by one byte with the number of groups
372 inner to this one. (This last has to be part of the
373 start_memory only because we need it in the on_failure_jump
377 /* Stop remembering the text that is matched and store it in a
378 memory register. Followed by one byte with the register
379 number, in the range 0 to one less than `re_nsub' in the
380 pattern buffer, and one byte with the number of inner groups,
381 just like `start_memory'. (We need the number of inner
382 groups here because we don't have any easy way of finding the
383 corresponding start_memory when we're at a stop_memory.) */
386 /* Match a duplicate of something remembered. Followed by one
387 byte containing the register number. */
390 /* Fail unless at beginning of line. */
393 /* Fail unless at end of line. */
396 /* Succeeds if at beginning of buffer (if emacs) or at beginning
397 of string to be matched (if not). */
400 /* Analogously, for end of buffer/string. */
403 /* Followed by two byte relative address to which to jump. */
406 /* Same as jump, but marks the end of an alternative. */
409 /* Followed by two-byte relative address of place to resume at
410 in case of failure. */
413 /* Like on_failure_jump, but pushes a placeholder instead of the
414 current string position when executed. */
415 on_failure_keep_string_jump,
417 /* Throw away latest failure point and then jump to following
418 two-byte relative address. */
421 /* Change to pop_failure_jump if know won't have to backtrack to
422 match; otherwise change to jump. This is used to jump
423 back to the beginning of a repeat. If what follows this jump
424 clearly won't match what the repeat does, such that we can be
425 sure that there is no use backtracking out of repetitions
426 already matched, then we change it to a pop_failure_jump.
427 Followed by two-byte address. */
430 /* Jump to following two-byte address, and push a dummy failure
431 point. This failure point will be thrown away if an attempt
432 is made to use it for a failure. A `+' construct makes this
433 before the first repeat. Also used as an intermediary kind
434 of jump when compiling an alternative. */
437 /* Push a dummy failure point and continue. Used at the end of
441 /* Followed by two-byte relative address and two-byte number n.
442 After matching N times, jump to the address upon failure. */
445 /* Followed by two-byte relative address, and two-byte number n.
446 Jump to the address N times, then fail. */
449 /* Set the following two-byte relative address to the
450 subsequent two-byte number. The address *includes* the two
454 wordchar, /* Matches any word-constituent character. */
455 notwordchar, /* Matches any char that is not a word-constituent. */
457 wordbeg, /* Succeeds if at word beginning. */
458 wordend, /* Succeeds if at word end. */
460 wordbound, /* Succeeds if at a word boundary. */
461 notwordbound /* Succeeds if not at a word boundary. */
464 ,before_dot, /* Succeeds if before point. */
465 at_dot, /* Succeeds if at point. */
466 after_dot, /* Succeeds if after point. */
468 /* Matches any character whose syntax is specified. Followed by
469 a byte which contains a syntax code, e.g., Sword. */
472 /* Matches any character whose syntax is not that specified. */
477 /* Common operations on the compiled pattern. */
479 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
481 #define STORE_NUMBER(destination, number) \
483 (destination)[0] = (number) & 0377; \
484 (destination)[1] = (number) >> 8; \
487 /* Same as STORE_NUMBER, except increment DESTINATION to
488 the byte after where the number is stored. Therefore, DESTINATION
489 must be an lvalue. */
491 #define STORE_NUMBER_AND_INCR(destination, number) \
493 STORE_NUMBER (destination, number); \
494 (destination) += 2; \
497 /* Put into DESTINATION a number stored in two contiguous bytes starting
500 #define EXTRACT_NUMBER(destination, source) \
502 (destination) = *(source) & 0377; \
503 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
507 static void extract_number _RE_ARGS ((int *dest, unsigned char *source));
509 extract_number (dest, source)
511 unsigned char *source;
513 int temp = SIGN_EXTEND_CHAR (*(source + 1));
514 *dest = *source & 0377;
518 #ifndef EXTRACT_MACROS /* To debug the macros. */
519 #undef EXTRACT_NUMBER
520 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
521 #endif /* not EXTRACT_MACROS */
525 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
526 SOURCE must be an lvalue. */
528 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
530 EXTRACT_NUMBER (destination, source); \
535 static void extract_number_and_incr _RE_ARGS ((int *destination,
536 unsigned char **source));
538 extract_number_and_incr (destination, source)
540 unsigned char **source;
542 extract_number (destination, *source);
546 #ifndef EXTRACT_MACROS
547 #undef EXTRACT_NUMBER_AND_INCR
548 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
549 extract_number_and_incr (&dest, &src)
550 #endif /* not EXTRACT_MACROS */
554 /* If DEBUG is defined, Regex prints many voluminous messages about what
555 it is doing (if the variable `debug' is nonzero). If linked with the
556 main program in `iregex.c', you can enter patterns and strings
557 interactively. And if linked with the main program in `main.c' and
558 the other test files, you can run the already-written tests. */
562 /* We use standard I/O for debugging. */
565 /* It is useful to test things that ``must'' be true when debugging. */
568 static int debug = 0;
570 #define DEBUG_STATEMENT(e) e
571 #define DEBUG_PRINT1(x) if (debug) printf (x)
572 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
573 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
574 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
575 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
576 if (debug) print_partial_compiled_pattern (s, e)
577 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
578 if (debug) print_double_string (w, s1, sz1, s2, sz2)
581 /* Print the fastmap in human-readable form. */
584 print_fastmap (fastmap)
587 unsigned was_a_range = 0;
590 while (i < (1 << BYTEWIDTH))
596 while (i < (1 << BYTEWIDTH) && fastmap[i])
612 /* Print a compiled pattern string in human-readable form, starting at
613 the START pointer into it and ending just before the pointer END. */
616 print_partial_compiled_pattern (start, end)
617 unsigned char *start;
622 unsigned char *p = start;
623 unsigned char *pend = end;
631 /* Loop over pattern commands. */
634 printf ("%d:\t", p - start);
636 switch ((re_opcode_t) *p++)
644 printf ("/exactn/%d", mcnt);
655 printf ("/start_memory/%d/%d", mcnt, *p++);
660 printf ("/stop_memory/%d/%d", mcnt, *p++);
664 printf ("/duplicate/%d", *p++);
674 register int c, last = -100;
675 register int in_range = 0;
677 printf ("/charset [%s",
678 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
680 assert (p + *p < pend);
682 for (c = 0; c < 256; c++)
684 && (p[1 + (c/8)] & (1 << (c % 8))))
686 /* Are we starting a range? */
687 if (last + 1 == c && ! in_range)
692 /* Have we broken a range? */
693 else if (last + 1 != c && in_range)
722 case on_failure_jump:
723 extract_number_and_incr (&mcnt, &p);
724 printf ("/on_failure_jump to %d", p + mcnt - start);
727 case on_failure_keep_string_jump:
728 extract_number_and_incr (&mcnt, &p);
729 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
732 case dummy_failure_jump:
733 extract_number_and_incr (&mcnt, &p);
734 printf ("/dummy_failure_jump to %d", p + mcnt - start);
737 case push_dummy_failure:
738 printf ("/push_dummy_failure");
742 extract_number_and_incr (&mcnt, &p);
743 printf ("/maybe_pop_jump to %d", p + mcnt - start);
746 case pop_failure_jump:
747 extract_number_and_incr (&mcnt, &p);
748 printf ("/pop_failure_jump to %d", p + mcnt - start);
752 extract_number_and_incr (&mcnt, &p);
753 printf ("/jump_past_alt to %d", p + mcnt - start);
757 extract_number_and_incr (&mcnt, &p);
758 printf ("/jump to %d", p + mcnt - start);
762 extract_number_and_incr (&mcnt, &p);
764 extract_number_and_incr (&mcnt2, &p);
765 printf ("/succeed_n to %d, %d times", p1 - start, mcnt2);
769 extract_number_and_incr (&mcnt, &p);
771 extract_number_and_incr (&mcnt2, &p);
772 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
776 extract_number_and_incr (&mcnt, &p);
778 extract_number_and_incr (&mcnt2, &p);
779 printf ("/set_number_at location %d to %d", p1 - start, mcnt2);
783 printf ("/wordbound");
787 printf ("/notwordbound");
799 printf ("/before_dot");
807 printf ("/after_dot");
811 printf ("/syntaxspec");
813 printf ("/%d", mcnt);
817 printf ("/notsyntaxspec");
819 printf ("/%d", mcnt);
824 printf ("/wordchar");
828 printf ("/notwordchar");
840 printf ("?%d", *(p-1));
846 printf ("%d:\tend of pattern.\n", p - start);
851 print_compiled_pattern (bufp)
852 struct re_pattern_buffer *bufp;
854 unsigned char *buffer = bufp->buffer;
856 print_partial_compiled_pattern (buffer, buffer + bufp->used);
857 printf ("%ld bytes used/%ld bytes allocated.\n",
858 bufp->used, bufp->allocated);
860 if (bufp->fastmap_accurate && bufp->fastmap)
862 printf ("fastmap: ");
863 print_fastmap (bufp->fastmap);
866 printf ("re_nsub: %d\t", bufp->re_nsub);
867 printf ("regs_alloc: %d\t", bufp->regs_allocated);
868 printf ("can_be_null: %d\t", bufp->can_be_null);
869 printf ("newline_anchor: %d\n", bufp->newline_anchor);
870 printf ("no_sub: %d\t", bufp->no_sub);
871 printf ("not_bol: %d\t", bufp->not_bol);
872 printf ("not_eol: %d\t", bufp->not_eol);
873 printf ("syntax: %lx\n", bufp->syntax);
874 /* Perhaps we should print the translate table? */
879 print_double_string (where, string1, size1, string2, size2)
892 if (FIRST_STRING_P (where))
894 for (this_char = where - string1; this_char < size1; this_char++)
895 putchar (string1[this_char]);
900 for (this_char = where - string2; this_char < size2; this_char++)
901 putchar (string2[this_char]);
912 #else /* not DEBUG */
917 #define DEBUG_STATEMENT(e)
918 #define DEBUG_PRINT1(x)
919 #define DEBUG_PRINT2(x1, x2)
920 #define DEBUG_PRINT3(x1, x2, x3)
921 #define DEBUG_PRINT4(x1, x2, x3, x4)
922 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
923 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
925 #endif /* not DEBUG */
927 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
928 also be assigned to arbitrarily: each pattern buffer stores its own
929 syntax, so it can be changed between regex compilations. */
930 /* This has no initializer because initialized variables in Emacs
931 become read-only after dumping. */
932 reg_syntax_t re_syntax_options;
935 /* Specify the precise syntax of regexps for compilation. This provides
936 for compatibility for various utilities which historically have
937 different, incompatible syntaxes.
939 The argument SYNTAX is a bit mask comprised of the various bits
940 defined in regex.h. We return the old syntax. */
943 re_set_syntax (syntax)
946 reg_syntax_t ret = re_syntax_options;
948 re_syntax_options = syntax;
950 if (syntax & RE_DEBUG)
952 else if (debug) /* was on but now is not */
958 /* This table gives an error message for each of the error codes listed
959 in regex.h. Obviously the order here has to be same as there.
960 POSIX doesn't require that we do anything for REG_NOERROR,
961 but why not be nice? */
963 static const char *re_error_msgid[] =
965 gettext_noop ("Success"), /* REG_NOERROR */
966 gettext_noop ("No match"), /* REG_NOMATCH */
967 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
968 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
969 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
970 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
971 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
972 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
973 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
974 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
975 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
976 gettext_noop ("Invalid range end"), /* REG_ERANGE */
977 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
978 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
979 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
980 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
981 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
984 /* Avoiding alloca during matching, to placate r_alloc. */
986 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
987 searching and matching functions should not call alloca. On some
988 systems, alloca is implemented in terms of malloc, and if we're
989 using the relocating allocator routines, then malloc could cause a
990 relocation, which might (if the strings being searched are in the
991 ralloc heap) shift the data out from underneath the regexp
994 Here's another reason to avoid allocation: Emacs
995 processes input from X in a signal handler; processing X input may
996 call malloc; if input arrives while a matching routine is calling
997 malloc, then we're scrod. But Emacs can't just block input while
998 calling matching routines; then we don't notice interrupts when
999 they come in. So, Emacs blocks input around all regexp calls
1000 except the matching calls, which it leaves unprotected, in the
1001 faith that they will not malloc. */
1003 /* Normally, this is fine. */
1004 #define MATCH_MAY_ALLOCATE
1006 /* When using GNU C, we are not REALLY using the C alloca, no matter
1007 what config.h may say. So don't take precautions for it. */
1012 /* The match routines may not allocate if (1) they would do it with malloc
1013 and (2) it's not safe for them to use malloc.
1014 Note that if REL_ALLOC is defined, matching would not use malloc for the
1015 failure stack, but we would still use it for the register vectors;
1016 so REL_ALLOC should not affect this. */
1017 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1018 #undef MATCH_MAY_ALLOCATE
1022 /* Failure stack declarations and macros; both re_compile_fastmap and
1023 re_match_2 use a failure stack. These have to be macros because of
1024 REGEX_ALLOCATE_STACK. */
1027 /* Number of failure points for which to initially allocate space
1028 when matching. If this number is exceeded, we allocate more
1029 space, so it is not a hard limit. */
1030 #ifndef INIT_FAILURE_ALLOC
1031 #define INIT_FAILURE_ALLOC 5
1034 /* Roughly the maximum number of failure points on the stack. Would be
1035 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1036 This is a variable only so users of regex can assign to it; we never
1037 change it ourselves. */
1041 #if defined (MATCH_MAY_ALLOCATE)
1042 /* 4400 was enough to cause a crash on Alpha OSF/1,
1043 whose default stack limit is 2mb. */
1044 long int re_max_failures = 4000;
1046 long int re_max_failures = 2000;
1049 union fail_stack_elt
1051 unsigned char *pointer;
1055 typedef union fail_stack_elt fail_stack_elt_t;
1059 fail_stack_elt_t *stack;
1060 unsigned long int size;
1061 unsigned long int avail; /* Offset of next open position. */
1064 #else /* not INT_IS_16BIT */
1066 #if defined (MATCH_MAY_ALLOCATE)
1067 /* 4400 was enough to cause a crash on Alpha OSF/1,
1068 whose default stack limit is 2mb. */
1069 int re_max_failures = 20000;
1071 int re_max_failures = 2000;
1074 union fail_stack_elt
1076 unsigned char *pointer;
1080 typedef union fail_stack_elt fail_stack_elt_t;
1084 fail_stack_elt_t *stack;
1086 unsigned avail; /* Offset of next open position. */
1089 #endif /* INT_IS_16BIT */
1091 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1092 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1093 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1096 /* Define macros to initialize and free the failure stack.
1097 Do `return -2' if the alloc fails. */
1099 #ifdef MATCH_MAY_ALLOCATE
1100 #define INIT_FAIL_STACK() \
1102 fail_stack.stack = (fail_stack_elt_t *) \
1103 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1105 if (fail_stack.stack == NULL) \
1108 fail_stack.size = INIT_FAILURE_ALLOC; \
1109 fail_stack.avail = 0; \
1112 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1114 #define INIT_FAIL_STACK() \
1116 fail_stack.avail = 0; \
1119 #define RESET_FAIL_STACK()
1123 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1125 Return 1 if succeeds, and 0 if either ran out of memory
1126 allocating space for it or it was already too large.
1128 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1130 #define DOUBLE_FAIL_STACK(fail_stack) \
1131 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1133 : ((fail_stack).stack = (fail_stack_elt_t *) \
1134 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1135 (fail_stack).size * sizeof (fail_stack_elt_t), \
1136 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1138 (fail_stack).stack == NULL \
1140 : ((fail_stack).size <<= 1, \
1144 /* Push pointer POINTER on FAIL_STACK.
1145 Return 1 if was able to do so and 0 if ran out of memory allocating
1147 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1148 ((FAIL_STACK_FULL () \
1149 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1151 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1154 /* Push a pointer value onto the failure stack.
1155 Assumes the variable `fail_stack'. Probably should only
1156 be called from within `PUSH_FAILURE_POINT'. */
1157 #define PUSH_FAILURE_POINTER(item) \
1158 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1160 /* This pushes an integer-valued item onto the failure stack.
1161 Assumes the variable `fail_stack'. Probably should only
1162 be called from within `PUSH_FAILURE_POINT'. */
1163 #define PUSH_FAILURE_INT(item) \
1164 fail_stack.stack[fail_stack.avail++].integer = (item)
1166 /* Push a fail_stack_elt_t value onto the failure stack.
1167 Assumes the variable `fail_stack'. Probably should only
1168 be called from within `PUSH_FAILURE_POINT'. */
1169 #define PUSH_FAILURE_ELT(item) \
1170 fail_stack.stack[fail_stack.avail++] = (item)
1172 /* These three POP... operations complement the three PUSH... operations.
1173 All assume that `fail_stack' is nonempty. */
1174 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1175 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1176 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1178 /* Used to omit pushing failure point id's when we're not debugging. */
1180 #define DEBUG_PUSH PUSH_FAILURE_INT
1181 #define DEBUG_POP(item_addr) (item_addr)->integer = POP_FAILURE_INT ()
1183 #define DEBUG_PUSH(item)
1184 #define DEBUG_POP(item_addr)
1188 /* Push the information about the state we will need
1189 if we ever fail back to it.
1191 Requires variables fail_stack, regstart, regend, reg_info, and
1192 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
1195 Does `return FAILURE_CODE' if runs out of memory. */
1197 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1199 char *destination; \
1200 /* Must be int, so when we don't save any registers, the arithmetic \
1201 of 0 + -1 isn't done as unsigned. */ \
1202 /* Can't be int, since there is not a shred of a guarantee that int \
1203 is wide enough to hold a value of something to which pointer can \
1207 DEBUG_STATEMENT (failure_id++); \
1208 DEBUG_STATEMENT (nfailure_points_pushed++); \
1209 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1210 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1211 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1213 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1214 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1216 /* Ensure we have enough space allocated for what we will push. */ \
1217 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1219 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1220 return failure_code; \
1222 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1223 (fail_stack).size); \
1224 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1227 /* Push the info, starting with the registers. */ \
1228 DEBUG_PRINT1 ("\n"); \
1231 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1234 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1235 DEBUG_STATEMENT (num_regs_pushed++); \
1237 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1238 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1240 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1241 PUSH_FAILURE_POINTER (regend[this_reg]); \
1243 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
1244 DEBUG_PRINT2 (" match_null=%d", \
1245 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1246 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1247 DEBUG_PRINT2 (" matched_something=%d", \
1248 MATCHED_SOMETHING (reg_info[this_reg])); \
1249 DEBUG_PRINT2 (" ever_matched=%d", \
1250 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1251 DEBUG_PRINT1 ("\n"); \
1252 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1255 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1256 PUSH_FAILURE_INT (lowest_active_reg); \
1258 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1259 PUSH_FAILURE_INT (highest_active_reg); \
1261 DEBUG_PRINT2 (" Pushing pattern 0x%x:\n", pattern_place); \
1262 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1263 PUSH_FAILURE_POINTER (pattern_place); \
1265 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
1266 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1268 DEBUG_PRINT1 ("'\n"); \
1269 PUSH_FAILURE_POINTER (string_place); \
1271 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1272 DEBUG_PUSH (failure_id); \
1275 /* This is the number of items that are pushed and popped on the stack
1276 for each register. */
1277 #define NUM_REG_ITEMS 3
1279 /* Individual items aside from the registers. */
1281 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1283 #define NUM_NONREG_ITEMS 4
1286 /* We push at most this many items on the stack. */
1287 /* We used to use (num_regs - 1), which is the number of registers
1288 this regexp will save; but that was changed to 5
1289 to avoid stack overflow for a regexp with lots of parens. */
1290 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1292 /* We actually push this many items. */
1293 #define NUM_FAILURE_ITEMS \
1295 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1299 /* How many items can still be added to the stack without overflowing it. */
1300 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1303 /* Pops what PUSH_FAIL_STACK pushes.
1305 We restore into the parameters, all of which should be lvalues:
1306 STR -- the saved data position.
1307 PAT -- the saved pattern position.
1308 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1309 REGSTART, REGEND -- arrays of string positions.
1310 REG_INFO -- array of information about each subexpression.
1312 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1313 `pend', `string1', `size1', `string2', and `size2'. */
1315 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1317 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
1319 const unsigned char *string_temp; \
1321 assert (!FAIL_STACK_EMPTY ()); \
1323 /* Remove failure points and point to how many regs pushed. */ \
1324 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1325 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1326 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1328 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1330 DEBUG_POP (&failure_id); \
1331 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1333 /* If the saved string location is NULL, it came from an \
1334 on_failure_keep_string_jump opcode, and we want to throw away the \
1335 saved NULL, thus retaining our current position in the string. */ \
1336 string_temp = POP_FAILURE_POINTER (); \
1337 if (string_temp != NULL) \
1338 str = (const char *) string_temp; \
1340 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
1341 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1342 DEBUG_PRINT1 ("'\n"); \
1344 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1345 DEBUG_PRINT2 (" Popping pattern 0x%x:\n", pat); \
1346 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1348 /* Restore register info. */ \
1349 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1350 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1352 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1353 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1356 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1358 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1360 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1361 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
1363 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1364 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1366 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1367 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1371 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1373 reg_info[this_reg].word.integer = 0; \
1374 regend[this_reg] = 0; \
1375 regstart[this_reg] = 0; \
1377 highest_active_reg = high_reg; \
1380 set_regs_matched_done = 0; \
1381 DEBUG_STATEMENT (nfailure_points_popped++); \
1382 } /* POP_FAILURE_POINT */
1386 /* Structure for per-register (a.k.a. per-group) information.
1387 Other register information, such as the
1388 starting and ending positions (which are addresses), and the list of
1389 inner groups (which is a bits list) are maintained in separate
1392 We are making a (strictly speaking) nonportable assumption here: that
1393 the compiler will pack our bit fields into something that fits into
1394 the type of `word', i.e., is something that fits into one item on the
1398 /* Declarations and macros for re_match_2. */
1402 fail_stack_elt_t word;
1405 /* This field is one if this group can match the empty string,
1406 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1407 #define MATCH_NULL_UNSET_VALUE 3
1408 unsigned match_null_string_p : 2;
1409 unsigned is_active : 1;
1410 unsigned matched_something : 1;
1411 unsigned ever_matched_something : 1;
1413 } register_info_type;
1415 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1416 #define IS_ACTIVE(R) ((R).bits.is_active)
1417 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1418 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1421 /* Call this when have matched a real character; it sets `matched' flags
1422 for the subexpressions which we are currently inside. Also records
1423 that those subexprs have matched. */
1424 #define SET_REGS_MATCHED() \
1427 if (!set_regs_matched_done) \
1430 set_regs_matched_done = 1; \
1431 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1433 MATCHED_SOMETHING (reg_info[r]) \
1434 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1441 /* Registers are set to a sentinel when they haven't yet matched. */
1442 static char reg_unset_dummy;
1443 #define REG_UNSET_VALUE (®_unset_dummy)
1444 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1446 /* Subroutine declarations and macros for regex_compile. */
1448 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1449 reg_syntax_t syntax,
1450 struct re_pattern_buffer *bufp));
1451 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1452 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1453 int arg1, int arg2));
1454 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1455 int arg, unsigned char *end));
1456 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1457 int arg1, int arg2, unsigned char *end));
1458 static boolean at_begline_loc_p _RE_ARGS ((const char *pattern, const char *p,
1459 reg_syntax_t syntax));
1460 static boolean at_endline_loc_p _RE_ARGS ((const char *p, const char *pend,
1461 reg_syntax_t syntax));
1462 static reg_errcode_t compile_range _RE_ARGS ((const char **p_ptr,
1465 reg_syntax_t syntax,
1468 /* Fetch the next character in the uncompiled pattern---translating it
1469 if necessary. Also cast from a signed character in the constant
1470 string passed to us by the user to an unsigned char that we can use
1471 as an array index (in, e.g., `translate'). */
1473 #define PATFETCH(c) \
1474 do {if (p == pend) return REG_EEND; \
1475 c = (unsigned char) *p++; \
1476 if (translate) c = (unsigned char) translate[c]; \
1480 /* Fetch the next character in the uncompiled pattern, with no
1482 #define PATFETCH_RAW(c) \
1483 do {if (p == pend) return REG_EEND; \
1484 c = (unsigned char) *p++; \
1487 /* Go backwards one character in the pattern. */
1488 #define PATUNFETCH p--
1491 /* If `translate' is non-null, return translate[D], else just D. We
1492 cast the subscript to translate because some data is declared as
1493 `char *', to avoid warnings when a string constant is passed. But
1494 when we use a character as a subscript we must make it unsigned. */
1496 #define TRANSLATE(d) \
1497 (translate ? (char) translate[(unsigned char) (d)] : (d))
1501 /* Macros for outputting the compiled pattern into `buffer'. */
1503 /* If the buffer isn't allocated when it comes in, use this. */
1504 #define INIT_BUF_SIZE 32
1506 /* Make sure we have at least N more bytes of space in buffer. */
1507 #define GET_BUFFER_SPACE(n) \
1508 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1511 /* Make sure we have one more byte of buffer space and then add C to it. */
1512 #define BUF_PUSH(c) \
1514 GET_BUFFER_SPACE (1); \
1515 *b++ = (unsigned char) (c); \
1519 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1520 #define BUF_PUSH_2(c1, c2) \
1522 GET_BUFFER_SPACE (2); \
1523 *b++ = (unsigned char) (c1); \
1524 *b++ = (unsigned char) (c2); \
1528 /* As with BUF_PUSH_2, except for three bytes. */
1529 #define BUF_PUSH_3(c1, c2, c3) \
1531 GET_BUFFER_SPACE (3); \
1532 *b++ = (unsigned char) (c1); \
1533 *b++ = (unsigned char) (c2); \
1534 *b++ = (unsigned char) (c3); \
1538 /* Store a jump with opcode OP at LOC to location TO. We store a
1539 relative address offset by the three bytes the jump itself occupies. */
1540 #define STORE_JUMP(op, loc, to) \
1541 store_op1 (op, loc, (int) ((to) - (loc) - 3))
1543 /* Likewise, for a two-argument jump. */
1544 #define STORE_JUMP2(op, loc, to, arg) \
1545 store_op2 (op, loc, (int) ((to) - (loc) - 3), arg)
1547 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1548 #define INSERT_JUMP(op, loc, to) \
1549 insert_op1 (op, loc, (int) ((to) - (loc) - 3), b)
1551 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1552 #define INSERT_JUMP2(op, loc, to, arg) \
1553 insert_op2 (op, loc, (int) ((to) - (loc) - 3), arg, b)
1556 /* This is not an arbitrary limit: the arguments which represent offsets
1557 into the pattern are two bytes long. So if 2^16 bytes turns out to
1558 be too small, many things would have to change. */
1559 /* Any other compiler which, like MSC, has allocation limit below 2^16
1560 bytes will have to use approach similar to what was done below for
1561 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1562 reallocating to 0 bytes. Such thing is not going to work too well.
1563 You have been warned!! */
1564 #if defined(_MSC_VER) && !defined(WIN32)
1565 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1566 The REALLOC define eliminates a flurry of conversion warnings,
1567 but is not required. */
1568 #define MAX_BUF_SIZE 65500L
1569 #define REALLOC(p,s) realloc ((p), (size_t) (s))
1571 #define MAX_BUF_SIZE (1L << 16)
1572 #define REALLOC(p,s) realloc ((p), (s))
1575 /* Extend the buffer by twice its current size via realloc and
1576 reset the pointers that pointed into the old block to point to the
1577 correct places in the new one. If extending the buffer results in it
1578 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1579 #if __BOUNDED_POINTERS__
1580 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1581 # define MOVE_BUFFER_POINTER(P) \
1582 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1583 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1586 SET_HIGH_BOUND (b); \
1587 SET_HIGH_BOUND (begalt); \
1588 if (fixup_alt_jump) \
1589 SET_HIGH_BOUND (fixup_alt_jump); \
1591 SET_HIGH_BOUND (laststart); \
1592 if (pending_exact) \
1593 SET_HIGH_BOUND (pending_exact); \
1596 # define MOVE_BUFFER_POINTER(P) (P) += incr
1597 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1599 #define EXTEND_BUFFER() \
1601 unsigned char *old_buffer = bufp->buffer; \
1602 if (bufp->allocated == MAX_BUF_SIZE) \
1604 bufp->allocated <<= 1; \
1605 if (bufp->allocated > MAX_BUF_SIZE) \
1606 bufp->allocated = MAX_BUF_SIZE; \
1607 bufp->buffer = (unsigned char *) REALLOC (bufp->buffer, bufp->allocated);\
1608 if (bufp->buffer == NULL) \
1609 return REG_ESPACE; \
1610 /* If the buffer moved, move all the pointers into it. */ \
1611 if (old_buffer != bufp->buffer) \
1613 int incr = bufp->buffer - old_buffer; \
1614 MOVE_BUFFER_POINTER (b); \
1615 MOVE_BUFFER_POINTER (begalt); \
1616 if (fixup_alt_jump) \
1617 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1619 MOVE_BUFFER_POINTER (laststart); \
1620 if (pending_exact) \
1621 MOVE_BUFFER_POINTER (pending_exact); \
1623 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1627 /* Since we have one byte reserved for the register number argument to
1628 {start,stop}_memory, the maximum number of groups we can report
1629 things about is what fits in that byte. */
1630 #define MAX_REGNUM 255
1632 /* But patterns can have more than `MAX_REGNUM' registers. We just
1633 ignore the excess. */
1634 typedef unsigned regnum_t;
1637 /* Macros for the compile stack. */
1639 /* Since offsets can go either forwards or backwards, this type needs to
1640 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1641 /* int may be not enough when sizeof(int) == 2. */
1642 typedef long pattern_offset_t;
1646 pattern_offset_t begalt_offset;
1647 pattern_offset_t fixup_alt_jump;
1648 pattern_offset_t inner_group_offset;
1649 pattern_offset_t laststart_offset;
1651 } compile_stack_elt_t;
1656 compile_stack_elt_t *stack;
1658 unsigned avail; /* Offset of next open position. */
1659 } compile_stack_type;
1662 #define INIT_COMPILE_STACK_SIZE 32
1664 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1665 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1667 /* The next available element. */
1668 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1671 /* Set the bit for character C in a list. */
1672 #define SET_LIST_BIT(c) \
1673 (b[((unsigned char) (c)) / BYTEWIDTH] \
1674 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1677 /* Get the next unsigned number in the uncompiled pattern. */
1678 #define GET_UNSIGNED_NUMBER(num) \
1682 while (ISDIGIT (c)) \
1686 num = num * 10 + c - '0'; \
1694 #if defined _LIBC || (defined HAVE_WCTYPE_H && defined HAVE_WCHAR_H)
1695 /* The GNU C library provides support for user-defined character classes
1696 and the functions from ISO C amendement 1. */
1697 # ifdef CHARCLASS_NAME_MAX
1698 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1700 /* This shouldn't happen but some implementation might still have this
1701 problem. Use a reasonable default value. */
1702 # define CHAR_CLASS_MAX_LENGTH 256
1705 # define IS_CHAR_CLASS(string) wctype (string)
1707 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1709 # define IS_CHAR_CLASS(string) \
1710 (STREQ (string, "alpha") || STREQ (string, "upper") \
1711 || STREQ (string, "lower") || STREQ (string, "digit") \
1712 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1713 || STREQ (string, "space") || STREQ (string, "print") \
1714 || STREQ (string, "punct") || STREQ (string, "graph") \
1715 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1718 #ifndef MATCH_MAY_ALLOCATE
1720 /* If we cannot allocate large objects within re_match_2_internal,
1721 we make the fail stack and register vectors global.
1722 The fail stack, we grow to the maximum size when a regexp
1724 The register vectors, we adjust in size each time we
1725 compile a regexp, according to the number of registers it needs. */
1727 static fail_stack_type fail_stack;
1729 /* Size with which the following vectors are currently allocated.
1730 That is so we can make them bigger as needed,
1731 but never make them smaller. */
1732 static int regs_allocated_size;
1734 static const char ** regstart, ** regend;
1735 static const char ** old_regstart, ** old_regend;
1736 static const char **best_regstart, **best_regend;
1737 static register_info_type *reg_info;
1738 static const char **reg_dummy;
1739 static register_info_type *reg_info_dummy;
1741 /* Make the register vectors big enough for NUM_REGS registers,
1742 but don't make them smaller. */
1745 regex_grow_registers (num_regs)
1748 if (num_regs > regs_allocated_size)
1750 RETALLOC_IF (regstart, num_regs, const char *);
1751 RETALLOC_IF (regend, num_regs, const char *);
1752 RETALLOC_IF (old_regstart, num_regs, const char *);
1753 RETALLOC_IF (old_regend, num_regs, const char *);
1754 RETALLOC_IF (best_regstart, num_regs, const char *);
1755 RETALLOC_IF (best_regend, num_regs, const char *);
1756 RETALLOC_IF (reg_info, num_regs, register_info_type);
1757 RETALLOC_IF (reg_dummy, num_regs, const char *);
1758 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1760 regs_allocated_size = num_regs;
1764 #endif /* not MATCH_MAY_ALLOCATE */
1766 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
1770 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1771 Returns one of error codes defined in `regex.h', or zero for success.
1773 Assumes the `allocated' (and perhaps `buffer') and `translate'
1774 fields are set in BUFP on entry.
1776 If it succeeds, results are put in BUFP (if it returns an error, the
1777 contents of BUFP are undefined):
1778 `buffer' is the compiled pattern;
1779 `syntax' is set to SYNTAX;
1780 `used' is set to the length of the compiled pattern;
1781 `fastmap_accurate' is zero;
1782 `re_nsub' is the number of subexpressions in PATTERN;
1783 `not_bol' and `not_eol' are zero;
1785 The `fastmap' and `newline_anchor' fields are neither
1786 examined nor set. */
1788 /* Return, freeing storage we allocated. */
1789 #define FREE_STACK_RETURN(value) \
1790 return (free (compile_stack.stack), value)
1792 static reg_errcode_t
1793 regex_compile (pattern, size, syntax, bufp)
1794 const char *pattern;
1796 reg_syntax_t syntax;
1797 struct re_pattern_buffer *bufp;
1799 /* We fetch characters from PATTERN here. Even though PATTERN is
1800 `char *' (i.e., signed), we declare these variables as unsigned, so
1801 they can be reliably used as array indices. */
1802 register unsigned char c, c1;
1804 /* A random temporary spot in PATTERN. */
1807 /* Points to the end of the buffer, where we should append. */
1808 register unsigned char *b;
1810 /* Keeps track of unclosed groups. */
1811 compile_stack_type compile_stack;
1813 /* Points to the current (ending) position in the pattern. */
1814 const char *p = pattern;
1815 const char *pend = pattern + size;
1817 /* How to translate the characters in the pattern. */
1818 RE_TRANSLATE_TYPE translate = bufp->translate;
1820 /* Address of the count-byte of the most recently inserted `exactn'
1821 command. This makes it possible to tell if a new exact-match
1822 character can be added to that command or if the character requires
1823 a new `exactn' command. */
1824 unsigned char *pending_exact = 0;
1826 /* Address of start of the most recently finished expression.
1827 This tells, e.g., postfix * where to find the start of its
1828 operand. Reset at the beginning of groups and alternatives. */
1829 unsigned char *laststart = 0;
1831 /* Address of beginning of regexp, or inside of last group. */
1832 unsigned char *begalt;
1834 /* Place in the uncompiled pattern (i.e., the {) to
1835 which to go back if the interval is invalid. */
1836 const char *beg_interval;
1838 /* Address of the place where a forward jump should go to the end of
1839 the containing expression. Each alternative of an `or' -- except the
1840 last -- ends with a forward jump of this sort. */
1841 unsigned char *fixup_alt_jump = 0;
1843 /* Counts open-groups as they are encountered. Remembered for the
1844 matching close-group on the compile stack, so the same register
1845 number is put in the stop_memory as the start_memory. */
1846 regnum_t regnum = 0;
1849 DEBUG_PRINT1 ("\nCompiling pattern: ");
1852 unsigned debug_count;
1854 for (debug_count = 0; debug_count < size; debug_count++)
1855 putchar (pattern[debug_count]);
1860 /* Initialize the compile stack. */
1861 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1862 if (compile_stack.stack == NULL)
1865 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1866 compile_stack.avail = 0;
1868 /* Initialize the pattern buffer. */
1869 bufp->syntax = syntax;
1870 bufp->fastmap_accurate = 0;
1871 bufp->not_bol = bufp->not_eol = 0;
1873 /* Set `used' to zero, so that if we return an error, the pattern
1874 printer (for debugging) will think there's no pattern. We reset it
1878 /* Always count groups, whether or not bufp->no_sub is set. */
1881 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1882 /* Initialize the syntax table. */
1883 init_syntax_once ();
1886 if (bufp->allocated == 0)
1889 { /* If zero allocated, but buffer is non-null, try to realloc
1890 enough space. This loses if buffer's address is bogus, but
1891 that is the user's responsibility. */
1892 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1895 { /* Caller did not allocate a buffer. Do it for them. */
1896 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1898 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1900 bufp->allocated = INIT_BUF_SIZE;
1903 begalt = b = bufp->buffer;
1905 /* Loop through the uncompiled pattern until we're at the end. */
1914 if ( /* If at start of pattern, it's an operator. */
1916 /* If context independent, it's an operator. */
1917 || syntax & RE_CONTEXT_INDEP_ANCHORS
1918 /* Otherwise, depends on what's come before. */
1919 || at_begline_loc_p (pattern, p, syntax))
1929 if ( /* If at end of pattern, it's an operator. */
1931 /* If context independent, it's an operator. */
1932 || syntax & RE_CONTEXT_INDEP_ANCHORS
1933 /* Otherwise, depends on what's next. */
1934 || at_endline_loc_p (p, pend, syntax))
1944 if ((syntax & RE_BK_PLUS_QM)
1945 || (syntax & RE_LIMITED_OPS))
1949 /* If there is no previous pattern... */
1952 if (syntax & RE_CONTEXT_INVALID_OPS)
1953 FREE_STACK_RETURN (REG_BADRPT);
1954 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1959 /* Are we optimizing this jump? */
1960 boolean keep_string_p = false;
1962 /* 1 means zero (many) matches is allowed. */
1963 char zero_times_ok = 0, many_times_ok = 0;
1965 /* If there is a sequence of repetition chars, collapse it
1966 down to just one (the right one). We can't combine
1967 interval operators with these because of, e.g., `a{2}*',
1968 which should only match an even number of `a's. */
1972 zero_times_ok |= c != '+';
1973 many_times_ok |= c != '?';
1981 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1984 else if (syntax & RE_BK_PLUS_QM && c == '\\')
1986 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1989 if (!(c1 == '+' || c1 == '?'))
2004 /* If we get here, we found another repeat character. */
2007 /* Star, etc. applied to an empty pattern is equivalent
2008 to an empty pattern. */
2012 /* Now we know whether or not zero matches is allowed
2013 and also whether or not two or more matches is allowed. */
2015 { /* More than one repetition is allowed, so put in at the
2016 end a backward relative jump from `b' to before the next
2017 jump we're going to put in below (which jumps from
2018 laststart to after this jump).
2020 But if we are at the `*' in the exact sequence `.*\n',
2021 insert an unconditional jump backwards to the .,
2022 instead of the beginning of the loop. This way we only
2023 push a failure point once, instead of every time
2024 through the loop. */
2025 assert (p - 1 > pattern);
2027 /* Allocate the space for the jump. */
2028 GET_BUFFER_SPACE (3);
2030 /* We know we are not at the first character of the pattern,
2031 because laststart was nonzero. And we've already
2032 incremented `p', by the way, to be the character after
2033 the `*'. Do we have to do something analogous here
2034 for null bytes, because of RE_DOT_NOT_NULL? */
2035 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2037 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2038 && !(syntax & RE_DOT_NEWLINE))
2039 { /* We have .*\n. */
2040 STORE_JUMP (jump, b, laststart);
2041 keep_string_p = true;
2044 /* Anything else. */
2045 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2047 /* We've added more stuff to the buffer. */
2051 /* On failure, jump from laststart to b + 3, which will be the
2052 end of the buffer after this jump is inserted. */
2053 GET_BUFFER_SPACE (3);
2054 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2062 /* At least one repetition is required, so insert a
2063 `dummy_failure_jump' before the initial
2064 `on_failure_jump' instruction of the loop. This
2065 effects a skip over that instruction the first time
2066 we hit that loop. */
2067 GET_BUFFER_SPACE (3);
2068 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2083 boolean had_char_class = false;
2085 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2087 /* Ensure that we have enough space to push a charset: the
2088 opcode, the length count, and the bitset; 34 bytes in all. */
2089 GET_BUFFER_SPACE (34);
2093 /* We test `*p == '^' twice, instead of using an if
2094 statement, so we only need one BUF_PUSH. */
2095 BUF_PUSH (*p == '^' ? charset_not : charset);
2099 /* Remember the first position in the bracket expression. */
2102 /* Push the number of bytes in the bitmap. */
2103 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2105 /* Clear the whole map. */
2106 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2108 /* charset_not matches newline according to a syntax bit. */
2109 if ((re_opcode_t) b[-2] == charset_not
2110 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2111 SET_LIST_BIT ('\n');
2113 /* Read in characters and ranges, setting map bits. */
2116 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2120 /* \ might escape characters inside [...] and [^...]. */
2121 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2123 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2130 /* Could be the end of the bracket expression. If it's
2131 not (i.e., when the bracket expression is `[]' so
2132 far), the ']' character bit gets set way below. */
2133 if (c == ']' && p != p1 + 1)
2136 /* Look ahead to see if it's a range when the last thing
2137 was a character class. */
2138 if (had_char_class && c == '-' && *p != ']')
2139 FREE_STACK_RETURN (REG_ERANGE);
2141 /* Look ahead to see if it's a range when the last thing
2142 was a character: if this is a hyphen not at the
2143 beginning or the end of a list, then it's the range
2146 && !(p - 2 >= pattern && p[-2] == '[')
2147 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2151 = compile_range (&p, pend, translate, syntax, b);
2152 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2155 else if (p[0] == '-' && p[1] != ']')
2156 { /* This handles ranges made up of characters only. */
2159 /* Move past the `-'. */
2162 ret = compile_range (&p, pend, translate, syntax, b);
2163 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2166 /* See if we're at the beginning of a possible character
2169 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2170 { /* Leave room for the null. */
2171 char str[CHAR_CLASS_MAX_LENGTH + 1];
2176 /* If pattern is `[[:'. */
2177 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2182 if (c == ':' || c == ']' || p == pend
2183 || c1 == CHAR_CLASS_MAX_LENGTH)
2189 /* If isn't a word bracketed by `[:' and:`]':
2190 undo the ending character, the letters, and leave
2191 the leading `:' and `[' (but set bits for them). */
2192 if (c == ':' && *p == ']')
2194 #if defined _LIBC || (defined HAVE_WCTYPE_H && defined HAVE_WCHAR_H)
2195 boolean is_lower = STREQ (str, "lower");
2196 boolean is_upper = STREQ (str, "upper");
2202 FREE_STACK_RETURN (REG_ECTYPE);
2204 /* Throw away the ] at the end of the character
2208 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2210 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
2212 if (iswctype (btowc (ch), wt))
2215 if (translate && (is_upper || is_lower)
2216 && (ISUPPER (ch) || ISLOWER (ch)))
2220 had_char_class = true;
2223 boolean is_alnum = STREQ (str, "alnum");
2224 boolean is_alpha = STREQ (str, "alpha");
2225 boolean is_blank = STREQ (str, "blank");
2226 boolean is_cntrl = STREQ (str, "cntrl");
2227 boolean is_digit = STREQ (str, "digit");
2228 boolean is_graph = STREQ (str, "graph");
2229 boolean is_lower = STREQ (str, "lower");
2230 boolean is_print = STREQ (str, "print");
2231 boolean is_punct = STREQ (str, "punct");
2232 boolean is_space = STREQ (str, "space");
2233 boolean is_upper = STREQ (str, "upper");
2234 boolean is_xdigit = STREQ (str, "xdigit");
2236 if (!IS_CHAR_CLASS (str))
2237 FREE_STACK_RETURN (REG_ECTYPE);
2239 /* Throw away the ] at the end of the character
2243 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2245 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2247 /* This was split into 3 if's to
2248 avoid an arbitrary limit in some compiler. */
2249 if ( (is_alnum && ISALNUM (ch))
2250 || (is_alpha && ISALPHA (ch))
2251 || (is_blank && ISBLANK (ch))
2252 || (is_cntrl && ISCNTRL (ch)))
2254 if ( (is_digit && ISDIGIT (ch))
2255 || (is_graph && ISGRAPH (ch))
2256 || (is_lower && ISLOWER (ch))
2257 || (is_print && ISPRINT (ch)))
2259 if ( (is_punct && ISPUNCT (ch))
2260 || (is_space && ISSPACE (ch))
2261 || (is_upper && ISUPPER (ch))
2262 || (is_xdigit && ISXDIGIT (ch)))
2264 if ( translate && (is_upper || is_lower)
2265 && (ISUPPER (ch) || ISLOWER (ch)))
2268 had_char_class = true;
2269 #endif /* libc || wctype.h */
2278 had_char_class = false;
2283 had_char_class = false;
2288 /* Discard any (non)matching list bytes that are all 0 at the
2289 end of the map. Decrease the map-length byte too. */
2290 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2298 if (syntax & RE_NO_BK_PARENS)
2305 if (syntax & RE_NO_BK_PARENS)
2312 if (syntax & RE_NEWLINE_ALT)
2319 if (syntax & RE_NO_BK_VBAR)
2326 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2327 goto handle_interval;
2333 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2335 /* Do not translate the character after the \, so that we can
2336 distinguish, e.g., \B from \b, even if we normally would
2337 translate, e.g., B to b. */
2343 if (syntax & RE_NO_BK_PARENS)
2344 goto normal_backslash;
2350 if (COMPILE_STACK_FULL)
2352 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2353 compile_stack_elt_t);
2354 if (compile_stack.stack == NULL) return REG_ESPACE;
2356 compile_stack.size <<= 1;
2359 /* These are the values to restore when we hit end of this
2360 group. They are all relative offsets, so that if the
2361 whole pattern moves because of realloc, they will still
2363 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2364 COMPILE_STACK_TOP.fixup_alt_jump
2365 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2366 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2367 COMPILE_STACK_TOP.regnum = regnum;
2369 /* We will eventually replace the 0 with the number of
2370 groups inner to this one. But do not push a
2371 start_memory for groups beyond the last one we can
2372 represent in the compiled pattern. */
2373 if (regnum <= MAX_REGNUM)
2375 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2376 BUF_PUSH_3 (start_memory, regnum, 0);
2379 compile_stack.avail++;
2384 /* If we've reached MAX_REGNUM groups, then this open
2385 won't actually generate any code, so we'll have to
2386 clear pending_exact explicitly. */
2392 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2394 if (COMPILE_STACK_EMPTY)
2395 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2396 goto normal_backslash;
2398 FREE_STACK_RETURN (REG_ERPAREN);
2402 { /* Push a dummy failure point at the end of the
2403 alternative for a possible future
2404 `pop_failure_jump' to pop. See comments at
2405 `push_dummy_failure' in `re_match_2'. */
2406 BUF_PUSH (push_dummy_failure);
2408 /* We allocated space for this jump when we assigned
2409 to `fixup_alt_jump', in the `handle_alt' case below. */
2410 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2413 /* See similar code for backslashed left paren above. */
2414 if (COMPILE_STACK_EMPTY)
2415 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2418 FREE_STACK_RETURN (REG_ERPAREN);
2420 /* Since we just checked for an empty stack above, this
2421 ``can't happen''. */
2422 assert (compile_stack.avail != 0);
2424 /* We don't just want to restore into `regnum', because
2425 later groups should continue to be numbered higher,
2426 as in `(ab)c(de)' -- the second group is #2. */
2427 regnum_t this_group_regnum;
2429 compile_stack.avail--;
2430 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2432 = COMPILE_STACK_TOP.fixup_alt_jump
2433 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2435 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2436 this_group_regnum = COMPILE_STACK_TOP.regnum;
2437 /* If we've reached MAX_REGNUM groups, then this open
2438 won't actually generate any code, so we'll have to
2439 clear pending_exact explicitly. */
2442 /* We're at the end of the group, so now we know how many
2443 groups were inside this one. */
2444 if (this_group_regnum <= MAX_REGNUM)
2446 unsigned char *inner_group_loc
2447 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2449 *inner_group_loc = regnum - this_group_regnum;
2450 BUF_PUSH_3 (stop_memory, this_group_regnum,
2451 regnum - this_group_regnum);
2457 case '|': /* `\|'. */
2458 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2459 goto normal_backslash;
2461 if (syntax & RE_LIMITED_OPS)
2464 /* Insert before the previous alternative a jump which
2465 jumps to this alternative if the former fails. */
2466 GET_BUFFER_SPACE (3);
2467 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2471 /* The alternative before this one has a jump after it
2472 which gets executed if it gets matched. Adjust that
2473 jump so it will jump to this alternative's analogous
2474 jump (put in below, which in turn will jump to the next
2475 (if any) alternative's such jump, etc.). The last such
2476 jump jumps to the correct final destination. A picture:
2482 If we are at `b', then fixup_alt_jump right now points to a
2483 three-byte space after `a'. We'll put in the jump, set
2484 fixup_alt_jump to right after `b', and leave behind three
2485 bytes which we'll fill in when we get to after `c'. */
2488 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2490 /* Mark and leave space for a jump after this alternative,
2491 to be filled in later either by next alternative or
2492 when know we're at the end of a series of alternatives. */
2494 GET_BUFFER_SPACE (3);
2503 /* If \{ is a literal. */
2504 if (!(syntax & RE_INTERVALS)
2505 /* If we're at `\{' and it's not the open-interval
2507 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2508 || (p - 2 == pattern && p == pend))
2509 goto normal_backslash;
2513 /* If got here, then the syntax allows intervals. */
2515 /* At least (most) this many matches must be made. */
2516 int lower_bound = -1, upper_bound = -1;
2518 beg_interval = p - 1;
2522 if (syntax & RE_NO_BK_BRACES)
2523 goto unfetch_interval;
2525 FREE_STACK_RETURN (REG_EBRACE);
2528 GET_UNSIGNED_NUMBER (lower_bound);
2532 GET_UNSIGNED_NUMBER (upper_bound);
2533 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2536 /* Interval such as `{1}' => match exactly once. */
2537 upper_bound = lower_bound;
2539 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2540 || lower_bound > upper_bound)
2542 if (syntax & RE_NO_BK_BRACES)
2543 goto unfetch_interval;
2545 FREE_STACK_RETURN (REG_BADBR);
2548 if (!(syntax & RE_NO_BK_BRACES))
2550 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2557 if (syntax & RE_NO_BK_BRACES)
2558 goto unfetch_interval;
2560 FREE_STACK_RETURN (REG_BADBR);
2563 /* We just parsed a valid interval. */
2565 /* If it's invalid to have no preceding re. */
2568 if (syntax & RE_CONTEXT_INVALID_OPS)
2569 FREE_STACK_RETURN (REG_BADRPT);
2570 else if (syntax & RE_CONTEXT_INDEP_OPS)
2573 goto unfetch_interval;
2576 /* If the upper bound is zero, don't want to succeed at
2577 all; jump from `laststart' to `b + 3', which will be
2578 the end of the buffer after we insert the jump. */
2579 if (upper_bound == 0)
2581 GET_BUFFER_SPACE (3);
2582 INSERT_JUMP (jump, laststart, b + 3);
2586 /* Otherwise, we have a nontrivial interval. When
2587 we're all done, the pattern will look like:
2588 set_number_at <jump count> <upper bound>
2589 set_number_at <succeed_n count> <lower bound>
2590 succeed_n <after jump addr> <succeed_n count>
2592 jump_n <succeed_n addr> <jump count>
2593 (The upper bound and `jump_n' are omitted if
2594 `upper_bound' is 1, though.) */
2596 { /* If the upper bound is > 1, we need to insert
2597 more at the end of the loop. */
2598 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2600 GET_BUFFER_SPACE (nbytes);
2602 /* Initialize lower bound of the `succeed_n', even
2603 though it will be set during matching by its
2604 attendant `set_number_at' (inserted next),
2605 because `re_compile_fastmap' needs to know.
2606 Jump to the `jump_n' we might insert below. */
2607 INSERT_JUMP2 (succeed_n, laststart,
2608 b + 5 + (upper_bound > 1) * 5,
2612 /* Code to initialize the lower bound. Insert
2613 before the `succeed_n'. The `5' is the last two
2614 bytes of this `set_number_at', plus 3 bytes of
2615 the following `succeed_n'. */
2616 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2619 if (upper_bound > 1)
2620 { /* More than one repetition is allowed, so
2621 append a backward jump to the `succeed_n'
2622 that starts this interval.
2624 When we've reached this during matching,
2625 we'll have matched the interval once, so
2626 jump back only `upper_bound - 1' times. */
2627 STORE_JUMP2 (jump_n, b, laststart + 5,
2631 /* The location we want to set is the second
2632 parameter of the `jump_n'; that is `b-2' as
2633 an absolute address. `laststart' will be
2634 the `set_number_at' we're about to insert;
2635 `laststart+3' the number to set, the source
2636 for the relative address. But we are
2637 inserting into the middle of the pattern --
2638 so everything is getting moved up by 5.
2639 Conclusion: (b - 2) - (laststart + 3) + 5,
2640 i.e., b - laststart.
2642 We insert this at the beginning of the loop
2643 so that if we fail during matching, we'll
2644 reinitialize the bounds. */
2645 insert_op2 (set_number_at, laststart, b - laststart,
2646 upper_bound - 1, b);
2651 beg_interval = NULL;
2656 /* If an invalid interval, match the characters as literals. */
2657 assert (beg_interval);
2659 beg_interval = NULL;
2661 /* normal_char and normal_backslash need `c'. */
2664 if (!(syntax & RE_NO_BK_BRACES))
2666 if (p > pattern && p[-1] == '\\')
2667 goto normal_backslash;
2672 /* There is no way to specify the before_dot and after_dot
2673 operators. rms says this is ok. --karl */
2681 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2687 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2693 if (re_syntax_options & RE_NO_GNU_OPS)
2696 BUF_PUSH (wordchar);
2701 if (re_syntax_options & RE_NO_GNU_OPS)
2704 BUF_PUSH (notwordchar);
2709 if (re_syntax_options & RE_NO_GNU_OPS)
2715 if (re_syntax_options & RE_NO_GNU_OPS)
2721 if (re_syntax_options & RE_NO_GNU_OPS)
2723 BUF_PUSH (wordbound);
2727 if (re_syntax_options & RE_NO_GNU_OPS)
2729 BUF_PUSH (notwordbound);
2733 if (re_syntax_options & RE_NO_GNU_OPS)
2739 if (re_syntax_options & RE_NO_GNU_OPS)
2744 case '1': case '2': case '3': case '4': case '5':
2745 case '6': case '7': case '8': case '9':
2746 if (syntax & RE_NO_BK_REFS)
2752 FREE_STACK_RETURN (REG_ESUBREG);
2754 /* Can't back reference to a subexpression if inside of it. */
2755 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
2759 BUF_PUSH_2 (duplicate, c1);
2765 if (syntax & RE_BK_PLUS_QM)
2768 goto normal_backslash;
2772 /* You might think it would be useful for \ to mean
2773 not to translate; but if we don't translate it
2774 it will never match anything. */
2782 /* Expects the character in `c'. */
2784 /* If no exactn currently being built. */
2787 /* If last exactn not at current position. */
2788 || pending_exact + *pending_exact + 1 != b
2790 /* We have only one byte following the exactn for the count. */
2791 || *pending_exact == (1 << BYTEWIDTH) - 1
2793 /* If followed by a repetition operator. */
2794 || *p == '*' || *p == '^'
2795 || ((syntax & RE_BK_PLUS_QM)
2796 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2797 : (*p == '+' || *p == '?'))
2798 || ((syntax & RE_INTERVALS)
2799 && ((syntax & RE_NO_BK_BRACES)
2801 : (p[0] == '\\' && p[1] == '{'))))
2803 /* Start building a new exactn. */
2807 BUF_PUSH_2 (exactn, 0);
2808 pending_exact = b - 1;
2815 } /* while p != pend */
2818 /* Through the pattern now. */
2821 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2823 if (!COMPILE_STACK_EMPTY)
2824 FREE_STACK_RETURN (REG_EPAREN);
2826 /* If we don't want backtracking, force success
2827 the first time we reach the end of the compiled pattern. */
2828 if (syntax & RE_NO_POSIX_BACKTRACKING)
2831 free (compile_stack.stack);
2833 /* We have succeeded; set the length of the buffer. */
2834 bufp->used = b - bufp->buffer;
2839 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2840 print_compiled_pattern (bufp);
2844 #ifndef MATCH_MAY_ALLOCATE
2845 /* Initialize the failure stack to the largest possible stack. This
2846 isn't necessary unless we're trying to avoid calling alloca in
2847 the search and match routines. */
2849 int num_regs = bufp->re_nsub + 1;
2851 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
2852 is strictly greater than re_max_failures, the largest possible stack
2853 is 2 * re_max_failures failure points. */
2854 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
2856 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
2859 if (! fail_stack.stack)
2861 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2862 * sizeof (fail_stack_elt_t));
2865 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2867 * sizeof (fail_stack_elt_t)));
2868 #else /* not emacs */
2869 if (! fail_stack.stack)
2871 = (fail_stack_elt_t *) malloc (fail_stack.size
2872 * sizeof (fail_stack_elt_t));
2875 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2877 * sizeof (fail_stack_elt_t)));
2878 #endif /* not emacs */
2881 regex_grow_registers (num_regs);
2883 #endif /* not MATCH_MAY_ALLOCATE */
2886 } /* regex_compile */
2888 /* Subroutines for `regex_compile'. */
2890 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2893 store_op1 (op, loc, arg)
2898 *loc = (unsigned char) op;
2899 STORE_NUMBER (loc + 1, arg);
2903 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2906 store_op2 (op, loc, arg1, arg2)
2911 *loc = (unsigned char) op;
2912 STORE_NUMBER (loc + 1, arg1);
2913 STORE_NUMBER (loc + 3, arg2);
2917 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2918 for OP followed by two-byte integer parameter ARG. */
2921 insert_op1 (op, loc, arg, end)
2927 register unsigned char *pfrom = end;
2928 register unsigned char *pto = end + 3;
2930 while (pfrom != loc)
2933 store_op1 (op, loc, arg);
2937 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2940 insert_op2 (op, loc, arg1, arg2, end)
2946 register unsigned char *pfrom = end;
2947 register unsigned char *pto = end + 5;
2949 while (pfrom != loc)
2952 store_op2 (op, loc, arg1, arg2);
2956 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2957 after an alternative or a begin-subexpression. We assume there is at
2958 least one character before the ^. */
2961 at_begline_loc_p (pattern, p, syntax)
2962 const char *pattern, *p;
2963 reg_syntax_t syntax;
2965 const char *prev = p - 2;
2966 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2969 /* After a subexpression? */
2970 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2971 /* After an alternative? */
2972 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2976 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2977 at least one character after the $, i.e., `P < PEND'. */
2980 at_endline_loc_p (p, pend, syntax)
2981 const char *p, *pend;
2982 reg_syntax_t syntax;
2984 const char *next = p;
2985 boolean next_backslash = *next == '\\';
2986 const char *next_next = p + 1 < pend ? p + 1 : 0;
2989 /* Before a subexpression? */
2990 (syntax & RE_NO_BK_PARENS ? *next == ')'
2991 : next_backslash && next_next && *next_next == ')')
2992 /* Before an alternative? */
2993 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2994 : next_backslash && next_next && *next_next == '|');
2998 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2999 false if it's not. */
3002 group_in_compile_stack (compile_stack, regnum)
3003 compile_stack_type compile_stack;
3008 for (this_element = compile_stack.avail - 1;
3011 if (compile_stack.stack[this_element].regnum == regnum)
3018 /* Read the ending character of a range (in a bracket expression) from the
3019 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3020 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3021 Then we set the translation of all bits between the starting and
3022 ending characters (inclusive) in the compiled pattern B.
3024 Return an error code.
3026 We use these short variable names so we can use the same macros as
3027 `regex_compile' itself. */
3029 static reg_errcode_t
3030 compile_range (p_ptr, pend, translate, syntax, b)
3031 const char **p_ptr, *pend;
3032 RE_TRANSLATE_TYPE translate;
3033 reg_syntax_t syntax;
3038 const char *p = *p_ptr;
3039 unsigned int range_start, range_end;
3044 /* Even though the pattern is a signed `char *', we need to fetch
3045 with unsigned char *'s; if the high bit of the pattern character
3046 is set, the range endpoints will be negative if we fetch using a
3049 We also want to fetch the endpoints without translating them; the
3050 appropriate translation is done in the bit-setting loop below. */
3051 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
3052 range_start = ((const unsigned char *) p)[-2];
3053 range_end = ((const unsigned char *) p)[0];
3055 /* Have to increment the pointer into the pattern string, so the
3056 caller isn't still at the ending character. */
3059 /* If the start is after the end, the range is empty. */
3060 if (range_start > range_end)
3061 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3063 /* Here we see why `this_char' has to be larger than an `unsigned
3064 char' -- the range is inclusive, so if `range_end' == 0xff
3065 (assuming 8-bit characters), we would otherwise go into an infinite
3066 loop, since all characters <= 0xff. */
3067 for (this_char = range_start; this_char <= range_end; this_char++)
3069 SET_LIST_BIT (TRANSLATE (this_char));
3075 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3076 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3077 characters can start a string that matches the pattern. This fastmap
3078 is used by re_search to skip quickly over impossible starting points.
3080 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3081 area as BUFP->fastmap.
3083 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3086 Returns 0 if we succeed, -2 if an internal error. */
3089 re_compile_fastmap (bufp)
3090 struct re_pattern_buffer *bufp;
3093 #ifdef MATCH_MAY_ALLOCATE
3094 fail_stack_type fail_stack;
3096 #ifndef REGEX_MALLOC
3100 register char *fastmap = bufp->fastmap;
3101 unsigned char *pattern = bufp->buffer;
3102 unsigned char *p = pattern;
3103 register unsigned char *pend = pattern + bufp->used;
3106 /* This holds the pointer to the failure stack, when
3107 it is allocated relocatably. */
3108 fail_stack_elt_t *failure_stack_ptr;
3111 /* Assume that each path through the pattern can be null until
3112 proven otherwise. We set this false at the bottom of switch
3113 statement, to which we get only if a particular path doesn't
3114 match the empty string. */
3115 boolean path_can_be_null = true;
3117 /* We aren't doing a `succeed_n' to begin with. */
3118 boolean succeed_n_p = false;
3120 assert (fastmap != NULL && p != NULL);
3123 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3124 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3125 bufp->can_be_null = 0;
3129 if (p == pend || *p == succeed)
3131 /* We have reached the (effective) end of pattern. */
3132 if (!FAIL_STACK_EMPTY ())
3134 bufp->can_be_null |= path_can_be_null;
3136 /* Reset for next path. */
3137 path_can_be_null = true;
3139 p = fail_stack.stack[--fail_stack.avail].pointer;
3147 /* We should never be about to go beyond the end of the pattern. */
3150 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3153 /* I guess the idea here is to simply not bother with a fastmap
3154 if a backreference is used, since it's too hard to figure out
3155 the fastmap for the corresponding group. Setting
3156 `can_be_null' stops `re_search_2' from using the fastmap, so
3157 that is all we do. */
3159 bufp->can_be_null = 1;
3163 /* Following are the cases which match a character. These end
3172 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3173 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3179 /* Chars beyond end of map must be allowed. */
3180 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3183 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3184 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3190 for (j = 0; j < (1 << BYTEWIDTH); j++)
3191 if (SYNTAX (j) == Sword)
3197 for (j = 0; j < (1 << BYTEWIDTH); j++)
3198 if (SYNTAX (j) != Sword)
3205 int fastmap_newline = fastmap['\n'];
3207 /* `.' matches anything ... */
3208 for (j = 0; j < (1 << BYTEWIDTH); j++)
3211 /* ... except perhaps newline. */
3212 if (!(bufp->syntax & RE_DOT_NEWLINE))
3213 fastmap['\n'] = fastmap_newline;
3215 /* Return if we have already set `can_be_null'; if we have,
3216 then the fastmap is irrelevant. Something's wrong here. */
3217 else if (bufp->can_be_null)
3220 /* Otherwise, have to check alternative paths. */
3227 for (j = 0; j < (1 << BYTEWIDTH); j++)
3228 if (SYNTAX (j) == (enum syntaxcode) k)
3235 for (j = 0; j < (1 << BYTEWIDTH); j++)
3236 if (SYNTAX (j) != (enum syntaxcode) k)
3241 /* All cases after this match the empty string. These end with
3261 case push_dummy_failure:
3266 case pop_failure_jump:
3267 case maybe_pop_jump:
3270 case dummy_failure_jump:
3271 EXTRACT_NUMBER_AND_INCR (j, p);
3276 /* Jump backward implies we just went through the body of a
3277 loop and matched nothing. Opcode jumped to should be
3278 `on_failure_jump' or `succeed_n'. Just treat it like an
3279 ordinary jump. For a * loop, it has pushed its failure
3280 point already; if so, discard that as redundant. */
3281 if ((re_opcode_t) *p != on_failure_jump
3282 && (re_opcode_t) *p != succeed_n)
3286 EXTRACT_NUMBER_AND_INCR (j, p);
3289 /* If what's on the stack is where we are now, pop it. */
3290 if (!FAIL_STACK_EMPTY ()
3291 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3297 case on_failure_jump:
3298 case on_failure_keep_string_jump:
3299 handle_on_failure_jump:
3300 EXTRACT_NUMBER_AND_INCR (j, p);
3302 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3303 end of the pattern. We don't want to push such a point,
3304 since when we restore it above, entering the switch will
3305 increment `p' past the end of the pattern. We don't need
3306 to push such a point since we obviously won't find any more
3307 fastmap entries beyond `pend'. Such a pattern can match
3308 the null string, though. */
3311 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3313 RESET_FAIL_STACK ();
3318 bufp->can_be_null = 1;
3322 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3323 succeed_n_p = false;
3330 /* Get to the number of times to succeed. */
3333 /* Increment p past the n for when k != 0. */
3334 EXTRACT_NUMBER_AND_INCR (k, p);
3338 succeed_n_p = true; /* Spaghetti code alert. */
3339 goto handle_on_failure_jump;
3356 abort (); /* We have listed all the cases. */
3359 /* Getting here means we have found the possible starting
3360 characters for one path of the pattern -- and that the empty
3361 string does not match. We need not follow this path further.
3362 Instead, look at the next alternative (remembered on the
3363 stack), or quit if no more. The test at the top of the loop
3364 does these things. */
3365 path_can_be_null = false;
3369 /* Set `can_be_null' for the last path (also the first path, if the
3370 pattern is empty). */
3371 bufp->can_be_null |= path_can_be_null;
3374 RESET_FAIL_STACK ();
3376 } /* re_compile_fastmap */
3378 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3379 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3380 this memory for recording register information. STARTS and ENDS
3381 must be allocated using the malloc library routine, and must each
3382 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3384 If NUM_REGS == 0, then subsequent matches should allocate their own
3387 Unless this function is called, the first search or match using
3388 PATTERN_BUFFER will allocate its own register data, without
3389 freeing the old data. */
3392 re_set_registers (bufp, regs, num_regs, starts, ends)
3393 struct re_pattern_buffer *bufp;
3394 struct re_registers *regs;
3396 regoff_t *starts, *ends;
3400 bufp->regs_allocated = REGS_REALLOCATE;
3401 regs->num_regs = num_regs;
3402 regs->start = starts;
3407 bufp->regs_allocated = REGS_UNALLOCATED;
3409 regs->start = regs->end = (regoff_t *) 0;
3413 /* Searching routines. */
3415 /* Like re_search_2, below, but only one string is specified, and
3416 doesn't let you say where to stop matching. */
3419 re_search (bufp, string, size, startpos, range, regs)
3420 struct re_pattern_buffer *bufp;
3422 int size, startpos, range;
3423 struct re_registers *regs;
3425 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3430 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3431 virtual concatenation of STRING1 and STRING2, starting first at index
3432 STARTPOS, then at STARTPOS + 1, and so on.
3434 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3436 RANGE is how far to scan while trying to match. RANGE = 0 means try
3437 only at STARTPOS; in general, the last start tried is STARTPOS +
3440 In REGS, return the indices of the virtual concatenation of STRING1
3441 and STRING2 that matched the entire BUFP->buffer and its contained
3444 Do not consider matching one past the index STOP in the virtual
3445 concatenation of STRING1 and STRING2.
3447 We return either the position in the strings at which the match was
3448 found, -1 if no match, or -2 if error (such as failure
3452 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3453 struct re_pattern_buffer *bufp;
3454 const char *string1, *string2;
3458 struct re_registers *regs;
3462 register char *fastmap = bufp->fastmap;
3463 register RE_TRANSLATE_TYPE translate = bufp->translate;
3464 int total_size = size1 + size2;
3465 int endpos = startpos + range;
3467 /* Check for out-of-range STARTPOS. */
3468 if (startpos < 0 || startpos > total_size)
3471 /* Fix up RANGE if it might eventually take us outside
3472 the virtual concatenation of STRING1 and STRING2.
3473 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3475 range = 0 - startpos;
3476 else if (endpos > total_size)
3477 range = total_size - startpos;
3479 /* If the search isn't to be a backwards one, don't waste time in a
3480 search for a pattern that must be anchored. */
3481 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3490 /* In a forward search for something that starts with \=.
3491 don't keep searching past point. */
3492 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3494 range = PT - startpos;
3500 /* Update the fastmap now if not correct already. */
3501 if (fastmap && !bufp->fastmap_accurate)
3502 if (re_compile_fastmap (bufp) == -2)
3505 /* Loop through the string, looking for a place to start matching. */
3508 /* If a fastmap is supplied, skip quickly over characters that
3509 cannot be the start of a match. If the pattern can match the
3510 null string, however, we don't need to skip characters; we want
3511 the first null string. */
3512 if (fastmap && startpos < total_size && !bufp->can_be_null)
3514 if (range > 0) /* Searching forwards. */
3516 register const char *d;
3517 register int lim = 0;
3520 if (startpos < size1 && startpos + range >= size1)
3521 lim = range - (size1 - startpos);
3523 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
3525 /* Written out as an if-else to avoid testing `translate'
3529 && !fastmap[(unsigned char)
3530 translate[(unsigned char) *d++]])
3533 while (range > lim && !fastmap[(unsigned char) *d++])
3536 startpos += irange - range;
3538 else /* Searching backwards. */
3540 register char c = (size1 == 0 || startpos >= size1
3541 ? string2[startpos - size1]
3542 : string1[startpos]);
3544 if (!fastmap[(unsigned char) TRANSLATE (c)])
3549 /* If can't match the null string, and that's all we have left, fail. */
3550 if (range >= 0 && startpos == total_size && fastmap
3551 && !bufp->can_be_null)
3554 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3555 startpos, regs, stop);
3556 #ifndef REGEX_MALLOC
3585 /* This converts PTR, a pointer into one of the search strings `string1'
3586 and `string2' into an offset from the beginning of that string. */
3587 #define POINTER_TO_OFFSET(ptr) \
3588 (FIRST_STRING_P (ptr) \
3589 ? ((regoff_t) ((ptr) - string1)) \
3590 : ((regoff_t) ((ptr) - string2 + size1)))
3592 /* Macros for dealing with the split strings in re_match_2. */
3594 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3596 /* Call before fetching a character with *d. This switches over to
3597 string2 if necessary. */
3598 #define PREFETCH() \
3601 /* End of string2 => fail. */ \
3602 if (dend == end_match_2) \
3604 /* End of string1 => advance to string2. */ \
3606 dend = end_match_2; \
3610 /* Test if at very beginning or at very end of the virtual concatenation
3611 of `string1' and `string2'. If only one string, it's `string2'. */
3612 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3613 #define AT_STRINGS_END(d) ((d) == end2)
3616 /* Test if D points to a character which is word-constituent. We have
3617 two special cases to check for: if past the end of string1, look at
3618 the first character in string2; and if before the beginning of
3619 string2, look at the last character in string1. */
3620 #define WORDCHAR_P(d) \
3621 (SYNTAX ((d) == end1 ? *string2 \
3622 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3625 /* Disabled due to a compiler bug -- see comment at case wordbound */
3627 /* Test if the character before D and the one at D differ with respect
3628 to being word-constituent. */
3629 #define AT_WORD_BOUNDARY(d) \
3630 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3631 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3634 /* Free everything we malloc. */
3635 #ifdef MATCH_MAY_ALLOCATE
3636 #define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
3637 #define FREE_VARIABLES() \
3639 REGEX_FREE_STACK (fail_stack.stack); \
3640 FREE_VAR (regstart); \
3641 FREE_VAR (regend); \
3642 FREE_VAR (old_regstart); \
3643 FREE_VAR (old_regend); \
3644 FREE_VAR (best_regstart); \
3645 FREE_VAR (best_regend); \
3646 FREE_VAR (reg_info); \
3647 FREE_VAR (reg_dummy); \
3648 FREE_VAR (reg_info_dummy); \
3651 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
3652 #endif /* not MATCH_MAY_ALLOCATE */
3654 /* These values must meet several constraints. They must not be valid
3655 register values; since we have a limit of 255 registers (because
3656 we use only one byte in the pattern for the register number), we can
3657 use numbers larger than 255. They must differ by 1, because of
3658 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3659 be larger than the value for the highest register, so we do not try
3660 to actually save any registers when none are active. */
3661 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3662 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3664 /* Matching routines. */
3666 #ifndef emacs /* Emacs never uses this. */
3667 /* re_match is like re_match_2 except it takes only a single string. */
3670 re_match (bufp, string, size, pos, regs)
3671 struct re_pattern_buffer *bufp;
3674 struct re_registers *regs;
3676 int result = re_match_2_internal (bufp, NULL, 0, string, size,
3678 #ifndef REGEX_MALLOC
3685 #endif /* not emacs */
3687 static boolean group_match_null_string_p _RE_ARGS ((unsigned char **p,
3689 register_info_type *reg_info));
3690 static boolean alt_match_null_string_p _RE_ARGS ((unsigned char *p,
3692 register_info_type *reg_info));
3693 static boolean common_op_match_null_string_p _RE_ARGS ((unsigned char **p,
3695 register_info_type *reg_info));
3696 static int bcmp_translate _RE_ARGS ((const char *s1, const char *s2,
3697 int len, char *translate));
3699 /* re_match_2 matches the compiled pattern in BUFP against the
3700 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3701 and SIZE2, respectively). We start matching at POS, and stop
3704 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3705 store offsets for the substring each group matched in REGS. See the
3706 documentation for exactly how many groups we fill.
3708 We return -1 if no match, -2 if an internal error (such as the
3709 failure stack overflowing). Otherwise, we return the length of the
3710 matched substring. */
3713 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3714 struct re_pattern_buffer *bufp;
3715 const char *string1, *string2;
3718 struct re_registers *regs;
3721 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
3723 #ifndef REGEX_MALLOC
3731 /* This is a separate function so that we can force an alloca cleanup
3734 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
3735 struct re_pattern_buffer *bufp;
3736 const char *string1, *string2;
3739 struct re_registers *regs;
3742 /* General temporaries. */
3746 /* Just past the end of the corresponding string. */
3747 const char *end1, *end2;
3749 /* Pointers into string1 and string2, just past the last characters in
3750 each to consider matching. */
3751 const char *end_match_1, *end_match_2;
3753 /* Where we are in the data, and the end of the current string. */
3754 const char *d, *dend;
3756 /* Where we are in the pattern, and the end of the pattern. */
3757 unsigned char *p = bufp->buffer;
3758 register unsigned char *pend = p + bufp->used;
3760 /* Mark the opcode just after a start_memory, so we can test for an
3761 empty subpattern when we get to the stop_memory. */
3762 unsigned char *just_past_start_mem = 0;
3764 /* We use this to map every character in the string. */
3765 RE_TRANSLATE_TYPE translate = bufp->translate;
3767 /* Failure point stack. Each place that can handle a failure further
3768 down the line pushes a failure point on this stack. It consists of
3769 restart, regend, and reg_info for all registers corresponding to
3770 the subexpressions we're currently inside, plus the number of such
3771 registers, and, finally, two char *'s. The first char * is where
3772 to resume scanning the pattern; the second one is where to resume
3773 scanning the strings. If the latter is zero, the failure point is
3774 a ``dummy''; if a failure happens and the failure point is a dummy,
3775 it gets discarded and the next next one is tried. */
3776 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3777 fail_stack_type fail_stack;
3780 static unsigned failure_id = 0;
3781 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3785 /* This holds the pointer to the failure stack, when
3786 it is allocated relocatably. */
3787 fail_stack_elt_t *failure_stack_ptr;
3790 /* We fill all the registers internally, independent of what we
3791 return, for use in backreferences. The number here includes
3792 an element for register zero. */
3793 size_t num_regs = bufp->re_nsub + 1;
3795 /* The currently active registers. */
3796 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3797 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3799 /* Information on the contents of registers. These are pointers into
3800 the input strings; they record just what was matched (on this
3801 attempt) by a subexpression part of the pattern, that is, the
3802 regnum-th regstart pointer points to where in the pattern we began
3803 matching and the regnum-th regend points to right after where we
3804 stopped matching the regnum-th subexpression. (The zeroth register
3805 keeps track of what the whole pattern matches.) */
3806 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3807 const char **regstart, **regend;
3810 /* If a group that's operated upon by a repetition operator fails to
3811 match anything, then the register for its start will need to be
3812 restored because it will have been set to wherever in the string we
3813 are when we last see its open-group operator. Similarly for a
3815 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3816 const char **old_regstart, **old_regend;
3819 /* The is_active field of reg_info helps us keep track of which (possibly
3820 nested) subexpressions we are currently in. The matched_something
3821 field of reg_info[reg_num] helps us tell whether or not we have
3822 matched any of the pattern so far this time through the reg_num-th
3823 subexpression. These two fields get reset each time through any
3824 loop their register is in. */
3825 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3826 register_info_type *reg_info;
3829 /* The following record the register info as found in the above
3830 variables when we find a match better than any we've seen before.
3831 This happens as we backtrack through the failure points, which in
3832 turn happens only if we have not yet matched the entire string. */
3833 unsigned best_regs_set = false;
3834 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3835 const char **best_regstart, **best_regend;
3838 /* Logically, this is `best_regend[0]'. But we don't want to have to
3839 allocate space for that if we're not allocating space for anything
3840 else (see below). Also, we never need info about register 0 for
3841 any of the other register vectors, and it seems rather a kludge to
3842 treat `best_regend' differently than the rest. So we keep track of
3843 the end of the best match so far in a separate variable. We
3844 initialize this to NULL so that when we backtrack the first time
3845 and need to test it, it's not garbage. */
3846 const char *match_end = NULL;
3848 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
3849 int set_regs_matched_done = 0;
3851 /* Used when we pop values we don't care about. */
3852 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3853 const char **reg_dummy;
3854 register_info_type *reg_info_dummy;
3858 /* Counts the total number of registers pushed. */
3859 unsigned num_regs_pushed = 0;
3862 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3866 #ifdef MATCH_MAY_ALLOCATE
3867 /* Do not bother to initialize all the register variables if there are
3868 no groups in the pattern, as it takes a fair amount of time. If
3869 there are groups, we include space for register 0 (the whole
3870 pattern), even though we never use it, since it simplifies the
3871 array indexing. We should fix this. */
3874 regstart = REGEX_TALLOC (num_regs, const char *);
3875 regend = REGEX_TALLOC (num_regs, const char *);
3876 old_regstart = REGEX_TALLOC (num_regs, const char *);
3877 old_regend = REGEX_TALLOC (num_regs, const char *);
3878 best_regstart = REGEX_TALLOC (num_regs, const char *);
3879 best_regend = REGEX_TALLOC (num_regs, const char *);
3880 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3881 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3882 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3884 if (!(regstart && regend && old_regstart && old_regend && reg_info
3885 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3893 /* We must initialize all our variables to NULL, so that
3894 `FREE_VARIABLES' doesn't try to free them. */
3895 regstart = regend = old_regstart = old_regend = best_regstart
3896 = best_regend = reg_dummy = NULL;
3897 reg_info = reg_info_dummy = (register_info_type *) NULL;
3899 #endif /* MATCH_MAY_ALLOCATE */
3901 /* The starting position is bogus. */
3902 if (pos < 0 || pos > size1 + size2)
3908 /* Initialize subexpression text positions to -1 to mark ones that no
3909 start_memory/stop_memory has been seen for. Also initialize the
3910 register information struct. */
3911 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
3913 regstart[mcnt] = regend[mcnt]
3914 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3916 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3917 IS_ACTIVE (reg_info[mcnt]) = 0;
3918 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3919 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3922 /* We move `string1' into `string2' if the latter's empty -- but not if
3923 `string1' is null. */
3924 if (size2 == 0 && string1 != NULL)
3931 end1 = string1 + size1;
3932 end2 = string2 + size2;
3934 /* Compute where to stop matching, within the two strings. */
3937 end_match_1 = string1 + stop;
3938 end_match_2 = string2;
3943 end_match_2 = string2 + stop - size1;
3946 /* `p' scans through the pattern as `d' scans through the data.
3947 `dend' is the end of the input string that `d' points within. `d'
3948 is advanced into the following input string whenever necessary, but
3949 this happens before fetching; therefore, at the beginning of the
3950 loop, `d' can be pointing at the end of a string, but it cannot
3952 if (size1 > 0 && pos <= size1)
3959 d = string2 + pos - size1;
3963 DEBUG_PRINT1 ("The compiled pattern is:\n");
3964 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3965 DEBUG_PRINT1 ("The string to match is: `");
3966 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3967 DEBUG_PRINT1 ("'\n");
3969 /* This loops over pattern commands. It exits by returning from the
3970 function if the match is complete, or it drops through if the match
3971 fails at this starting point in the input data. */
3975 DEBUG_PRINT2 ("\n%p: ", p);
3977 DEBUG_PRINT2 ("\n0x%x: ", p);
3981 { /* End of pattern means we might have succeeded. */
3982 DEBUG_PRINT1 ("end of pattern ... ");
3984 /* If we haven't matched the entire string, and we want the
3985 longest match, try backtracking. */
3986 if (d != end_match_2)
3988 /* 1 if this match ends in the same string (string1 or string2)
3989 as the best previous match. */
3990 boolean same_str_p = (FIRST_STRING_P (match_end)
3991 == MATCHING_IN_FIRST_STRING);
3992 /* 1 if this match is the best seen so far. */
3993 boolean best_match_p;
3995 /* AIX compiler got confused when this was combined
3996 with the previous declaration. */
3998 best_match_p = d > match_end;
4000 best_match_p = !MATCHING_IN_FIRST_STRING;
4002 DEBUG_PRINT1 ("backtracking.\n");
4004 if (!FAIL_STACK_EMPTY ())
4005 { /* More failure points to try. */
4007 /* If exceeds best match so far, save it. */
4008 if (!best_regs_set || best_match_p)
4010 best_regs_set = true;
4013 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4015 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4017 best_regstart[mcnt] = regstart[mcnt];
4018 best_regend[mcnt] = regend[mcnt];
4024 /* If no failure points, don't restore garbage. And if
4025 last match is real best match, don't restore second
4027 else if (best_regs_set && !best_match_p)
4030 /* Restore best match. It may happen that `dend ==
4031 end_match_1' while the restored d is in string2.
4032 For example, the pattern `x.*y.*z' against the
4033 strings `x-' and `y-z-', if the two strings are
4034 not consecutive in memory. */
4035 DEBUG_PRINT1 ("Restoring best registers.\n");
4038 dend = ((d >= string1 && d <= end1)
4039 ? end_match_1 : end_match_2);
4041 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4043 regstart[mcnt] = best_regstart[mcnt];
4044 regend[mcnt] = best_regend[mcnt];
4047 } /* d != end_match_2 */
4050 DEBUG_PRINT1 ("Accepting match.\n");
4052 /* If caller wants register contents data back, do it. */
4053 if (regs && !bufp->no_sub)
4055 /* Have the register data arrays been allocated? */
4056 if (bufp->regs_allocated == REGS_UNALLOCATED)
4057 { /* No. So allocate them with malloc. We need one
4058 extra element beyond `num_regs' for the `-1' marker
4060 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4061 regs->start = TALLOC (regs->num_regs, regoff_t);
4062 regs->end = TALLOC (regs->num_regs, regoff_t);
4063 if (regs->start == NULL || regs->end == NULL)
4068 bufp->regs_allocated = REGS_REALLOCATE;
4070 else if (bufp->regs_allocated == REGS_REALLOCATE)
4071 { /* Yes. If we need more elements than were already
4072 allocated, reallocate them. If we need fewer, just
4074 if (regs->num_regs < num_regs + 1)
4076 regs->num_regs = num_regs + 1;
4077 RETALLOC (regs->start, regs->num_regs, regoff_t);
4078 RETALLOC (regs->end, regs->num_regs, regoff_t);
4079 if (regs->start == NULL || regs->end == NULL)
4088 /* These braces fend off a "empty body in an else-statement"
4089 warning under GCC when assert expands to nothing. */
4090 assert (bufp->regs_allocated == REGS_FIXED);
4093 /* Convert the pointer data in `regstart' and `regend' to
4094 indices. Register zero has to be set differently,
4095 since we haven't kept track of any info for it. */
4096 if (regs->num_regs > 0)
4098 regs->start[0] = pos;
4099 regs->end[0] = (MATCHING_IN_FIRST_STRING
4100 ? ((regoff_t) (d - string1))
4101 : ((regoff_t) (d - string2 + size1)));
4104 /* Go through the first `min (num_regs, regs->num_regs)'
4105 registers, since that is all we initialized. */
4106 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
4109 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4110 regs->start[mcnt] = regs->end[mcnt] = -1;
4114 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4116 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4120 /* If the regs structure we return has more elements than
4121 were in the pattern, set the extra elements to -1. If
4122 we (re)allocated the registers, this is the case,
4123 because we always allocate enough to have at least one
4125 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
4126 regs->start[mcnt] = regs->end[mcnt] = -1;
4127 } /* regs && !bufp->no_sub */
4129 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4130 nfailure_points_pushed, nfailure_points_popped,
4131 nfailure_points_pushed - nfailure_points_popped);
4132 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4134 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4138 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4144 /* Otherwise match next pattern command. */
4145 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4147 /* Ignore these. Used to ignore the n of succeed_n's which
4148 currently have n == 0. */
4150 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4154 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4157 /* Match the next n pattern characters exactly. The following
4158 byte in the pattern defines n, and the n bytes after that
4159 are the characters to match. */
4162 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4164 /* This is written out as an if-else so we don't waste time
4165 testing `translate' inside the loop. */
4171 if ((unsigned char) translate[(unsigned char) *d++]
4172 != (unsigned char) *p++)
4182 if (*d++ != (char) *p++) goto fail;
4186 SET_REGS_MATCHED ();
4190 /* Match any character except possibly a newline or a null. */
4192 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4196 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4197 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4200 SET_REGS_MATCHED ();
4201 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4209 register unsigned char c;
4210 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4212 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4215 c = TRANSLATE (*d); /* The character to match. */
4217 /* Cast to `unsigned' instead of `unsigned char' in case the
4218 bit list is a full 32 bytes long. */
4219 if (c < (unsigned) (*p * BYTEWIDTH)
4220 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4225 if (!not) goto fail;
4227 SET_REGS_MATCHED ();
4233 /* The beginning of a group is represented by start_memory.
4234 The arguments are the register number in the next byte, and the
4235 number of groups inner to this one in the next. The text
4236 matched within the group is recorded (in the internal
4237 registers data structure) under the register number. */
4239 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4241 /* Find out if this group can match the empty string. */
4242 p1 = p; /* To send to group_match_null_string_p. */
4244 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4245 REG_MATCH_NULL_STRING_P (reg_info[*p])
4246 = group_match_null_string_p (&p1, pend, reg_info);
4248 /* Save the position in the string where we were the last time
4249 we were at this open-group operator in case the group is
4250 operated upon by a repetition operator, e.g., with `(a*)*b'
4251 against `ab'; then we want to ignore where we are now in
4252 the string in case this attempt to match fails. */
4253 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4254 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4256 DEBUG_PRINT2 (" old_regstart: %d\n",
4257 POINTER_TO_OFFSET (old_regstart[*p]));
4260 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4262 IS_ACTIVE (reg_info[*p]) = 1;
4263 MATCHED_SOMETHING (reg_info[*p]) = 0;
4265 /* Clear this whenever we change the register activity status. */
4266 set_regs_matched_done = 0;
4268 /* This is the new highest active register. */
4269 highest_active_reg = *p;
4271 /* If nothing was active before, this is the new lowest active
4273 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4274 lowest_active_reg = *p;
4276 /* Move past the register number and inner group count. */
4278 just_past_start_mem = p;
4283 /* The stop_memory opcode represents the end of a group. Its
4284 arguments are the same as start_memory's: the register
4285 number, and the number of inner groups. */
4287 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4289 /* We need to save the string position the last time we were at
4290 this close-group operator in case the group is operated
4291 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4292 against `aba'; then we want to ignore where we are now in
4293 the string in case this attempt to match fails. */
4294 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4295 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4297 DEBUG_PRINT2 (" old_regend: %d\n",
4298 POINTER_TO_OFFSET (old_regend[*p]));
4301 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4303 /* This register isn't active anymore. */
4304 IS_ACTIVE (reg_info[*p]) = 0;
4306 /* Clear this whenever we change the register activity status. */
4307 set_regs_matched_done = 0;
4309 /* If this was the only register active, nothing is active
4311 if (lowest_active_reg == highest_active_reg)
4313 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4314 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4317 { /* We must scan for the new highest active register, since
4318 it isn't necessarily one less than now: consider
4319 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4320 new highest active register is 1. */
4321 unsigned char r = *p - 1;
4322 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4325 /* If we end up at register zero, that means that we saved
4326 the registers as the result of an `on_failure_jump', not
4327 a `start_memory', and we jumped to past the innermost
4328 `stop_memory'. For example, in ((.)*) we save
4329 registers 1 and 2 as a result of the *, but when we pop
4330 back to the second ), we are at the stop_memory 1.
4331 Thus, nothing is active. */
4334 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4335 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4338 highest_active_reg = r;
4341 /* If just failed to match something this time around with a
4342 group that's operated on by a repetition operator, try to
4343 force exit from the ``loop'', and restore the register
4344 information for this group that we had before trying this
4346 if ((!MATCHED_SOMETHING (reg_info[*p])
4347 || just_past_start_mem == p - 1)
4350 boolean is_a_jump_n = false;
4354 switch ((re_opcode_t) *p1++)
4358 case pop_failure_jump:
4359 case maybe_pop_jump:
4361 case dummy_failure_jump:
4362 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4372 /* If the next operation is a jump backwards in the pattern
4373 to an on_failure_jump right before the start_memory
4374 corresponding to this stop_memory, exit from the loop
4375 by forcing a failure after pushing on the stack the
4376 on_failure_jump's jump in the pattern, and d. */
4377 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4378 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4380 /* If this group ever matched anything, then restore
4381 what its registers were before trying this last
4382 failed match, e.g., with `(a*)*b' against `ab' for
4383 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4384 against `aba' for regend[3].
4386 Also restore the registers for inner groups for,
4387 e.g., `((a*)(b*))*' against `aba' (register 3 would
4388 otherwise get trashed). */
4390 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4394 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4396 /* Restore this and inner groups' (if any) registers. */
4397 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
4400 regstart[r] = old_regstart[r];
4402 /* xx why this test? */
4403 if (old_regend[r] >= regstart[r])
4404 regend[r] = old_regend[r];
4408 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4409 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4415 /* Move past the register number and the inner group count. */
4420 /* \<digit> has been turned into a `duplicate' command which is
4421 followed by the numeric value of <digit> as the register number. */
4424 register const char *d2, *dend2;
4425 int regno = *p++; /* Get which register to match against. */
4426 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4428 /* Can't back reference a group which we've never matched. */
4429 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4432 /* Where in input to try to start matching. */
4433 d2 = regstart[regno];
4435 /* Where to stop matching; if both the place to start and
4436 the place to stop matching are in the same string, then
4437 set to the place to stop, otherwise, for now have to use
4438 the end of the first string. */
4440 dend2 = ((FIRST_STRING_P (regstart[regno])
4441 == FIRST_STRING_P (regend[regno]))
4442 ? regend[regno] : end_match_1);
4445 /* If necessary, advance to next segment in register
4449 if (dend2 == end_match_2) break;
4450 if (dend2 == regend[regno]) break;
4452 /* End of string1 => advance to string2. */
4454 dend2 = regend[regno];
4456 /* At end of register contents => success */
4457 if (d2 == dend2) break;
4459 /* If necessary, advance to next segment in data. */
4462 /* How many characters left in this segment to match. */
4465 /* Want how many consecutive characters we can match in
4466 one shot, so, if necessary, adjust the count. */
4467 if (mcnt > dend2 - d2)
4470 /* Compare that many; failure if mismatch, else move
4473 ? bcmp_translate (d, d2, mcnt, translate)
4474 : bcmp (d, d2, mcnt))
4476 d += mcnt, d2 += mcnt;
4478 /* Do this because we've match some characters. */
4479 SET_REGS_MATCHED ();
4485 /* begline matches the empty string at the beginning of the string
4486 (unless `not_bol' is set in `bufp'), and, if
4487 `newline_anchor' is set, after newlines. */
4489 DEBUG_PRINT1 ("EXECUTING begline.\n");
4491 if (AT_STRINGS_BEG (d))
4493 if (!bufp->not_bol) break;
4495 else if (d[-1] == '\n' && bufp->newline_anchor)
4499 /* In all other cases, we fail. */
4503 /* endline is the dual of begline. */
4505 DEBUG_PRINT1 ("EXECUTING endline.\n");
4507 if (AT_STRINGS_END (d))
4509 if (!bufp->not_eol) break;
4512 /* We have to ``prefetch'' the next character. */
4513 else if ((d == end1 ? *string2 : *d) == '\n'
4514 && bufp->newline_anchor)
4521 /* Match at the very beginning of the data. */
4523 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4524 if (AT_STRINGS_BEG (d))
4529 /* Match at the very end of the data. */
4531 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4532 if (AT_STRINGS_END (d))
4537 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4538 pushes NULL as the value for the string on the stack. Then
4539 `pop_failure_point' will keep the current value for the
4540 string, instead of restoring it. To see why, consider
4541 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4542 then the . fails against the \n. But the next thing we want
4543 to do is match the \n against the \n; if we restored the
4544 string value, we would be back at the foo.
4546 Because this is used only in specific cases, we don't need to
4547 check all the things that `on_failure_jump' does, to make
4548 sure the right things get saved on the stack. Hence we don't
4549 share its code. The only reason to push anything on the
4550 stack at all is that otherwise we would have to change
4551 `anychar's code to do something besides goto fail in this
4552 case; that seems worse than this. */
4553 case on_failure_keep_string_jump:
4554 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4556 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4558 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
4560 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4563 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4567 /* Uses of on_failure_jump:
4569 Each alternative starts with an on_failure_jump that points
4570 to the beginning of the next alternative. Each alternative
4571 except the last ends with a jump that in effect jumps past
4572 the rest of the alternatives. (They really jump to the
4573 ending jump of the following alternative, because tensioning
4574 these jumps is a hassle.)
4576 Repeats start with an on_failure_jump that points past both
4577 the repetition text and either the following jump or
4578 pop_failure_jump back to this on_failure_jump. */
4579 case on_failure_jump:
4581 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4583 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4585 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
4587 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4590 /* If this on_failure_jump comes right before a group (i.e.,
4591 the original * applied to a group), save the information
4592 for that group and all inner ones, so that if we fail back
4593 to this point, the group's information will be correct.
4594 For example, in \(a*\)*\1, we need the preceding group,
4595 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4597 /* We can't use `p' to check ahead because we push
4598 a failure point to `p + mcnt' after we do this. */
4601 /* We need to skip no_op's before we look for the
4602 start_memory in case this on_failure_jump is happening as
4603 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4605 while (p1 < pend && (re_opcode_t) *p1 == no_op)
4608 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
4610 /* We have a new highest active register now. This will
4611 get reset at the start_memory we are about to get to,
4612 but we will have saved all the registers relevant to
4613 this repetition op, as described above. */
4614 highest_active_reg = *(p1 + 1) + *(p1 + 2);
4615 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4616 lowest_active_reg = *(p1 + 1);
4619 DEBUG_PRINT1 (":\n");
4620 PUSH_FAILURE_POINT (p + mcnt, d, -2);
4624 /* A smart repeat ends with `maybe_pop_jump'.
4625 We change it to either `pop_failure_jump' or `jump'. */
4626 case maybe_pop_jump:
4627 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4628 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
4630 register unsigned char *p2 = p;
4632 /* Compare the beginning of the repeat with what in the
4633 pattern follows its end. If we can establish that there
4634 is nothing that they would both match, i.e., that we
4635 would have to backtrack because of (as in, e.g., `a*a')
4636 then we can change to pop_failure_jump, because we'll
4637 never have to backtrack.
4639 This is not true in the case of alternatives: in
4640 `(a|ab)*' we do need to backtrack to the `ab' alternative
4641 (e.g., if the string was `ab'). But instead of trying to
4642 detect that here, the alternative has put on a dummy
4643 failure point which is what we will end up popping. */
4645 /* Skip over open/close-group commands.
4646 If what follows this loop is a ...+ construct,
4647 look at what begins its body, since we will have to
4648 match at least one of that. */
4652 && ((re_opcode_t) *p2 == stop_memory
4653 || (re_opcode_t) *p2 == start_memory))
4655 else if (p2 + 6 < pend
4656 && (re_opcode_t) *p2 == dummy_failure_jump)
4663 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4664 to the `maybe_finalize_jump' of this case. Examine what
4667 /* If we're at the end of the pattern, we can change. */
4670 /* Consider what happens when matching ":\(.*\)"
4671 against ":/". I don't really understand this code
4673 p[-3] = (unsigned char) pop_failure_jump;
4675 (" End of pattern: change to `pop_failure_jump'.\n");
4678 else if ((re_opcode_t) *p2 == exactn
4679 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4681 register unsigned char c
4682 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4684 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4686 p[-3] = (unsigned char) pop_failure_jump;
4687 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4691 else if ((re_opcode_t) p1[3] == charset
4692 || (re_opcode_t) p1[3] == charset_not)
4694 int not = (re_opcode_t) p1[3] == charset_not;
4696 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4697 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4700 /* `not' is equal to 1 if c would match, which means
4701 that we can't change to pop_failure_jump. */
4704 p[-3] = (unsigned char) pop_failure_jump;
4705 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4709 else if ((re_opcode_t) *p2 == charset)
4712 register unsigned char c
4713 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4717 if ((re_opcode_t) p1[3] == exactn
4718 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
4719 && (p2[2 + p1[5] / BYTEWIDTH]
4720 & (1 << (p1[5] % BYTEWIDTH)))))
4722 if ((re_opcode_t) p1[3] == exactn
4723 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[4]
4724 && (p2[2 + p1[4] / BYTEWIDTH]
4725 & (1 << (p1[4] % BYTEWIDTH)))))
4728 p[-3] = (unsigned char) pop_failure_jump;
4729 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4733 else if ((re_opcode_t) p1[3] == charset_not)
4736 /* We win if the charset_not inside the loop
4737 lists every character listed in the charset after. */
4738 for (idx = 0; idx < (int) p2[1]; idx++)
4739 if (! (p2[2 + idx] == 0
4740 || (idx < (int) p1[4]
4741 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
4746 p[-3] = (unsigned char) pop_failure_jump;
4747 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4750 else if ((re_opcode_t) p1[3] == charset)
4753 /* We win if the charset inside the loop
4754 has no overlap with the one after the loop. */
4756 idx < (int) p2[1] && idx < (int) p1[4];
4758 if ((p2[2 + idx] & p1[5 + idx]) != 0)
4761 if (idx == p2[1] || idx == p1[4])
4763 p[-3] = (unsigned char) pop_failure_jump;
4764 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4769 p -= 2; /* Point at relative address again. */
4770 if ((re_opcode_t) p[-1] != pop_failure_jump)
4772 p[-1] = (unsigned char) jump;
4773 DEBUG_PRINT1 (" Match => jump.\n");
4774 goto unconditional_jump;
4776 /* Note fall through. */
4779 /* The end of a simple repeat has a pop_failure_jump back to
4780 its matching on_failure_jump, where the latter will push a
4781 failure point. The pop_failure_jump takes off failure
4782 points put on by this pop_failure_jump's matching
4783 on_failure_jump; we got through the pattern to here from the
4784 matching on_failure_jump, so didn't fail. */
4785 case pop_failure_jump:
4787 /* We need to pass separate storage for the lowest and
4788 highest registers, even though we don't care about the
4789 actual values. Otherwise, we will restore only one
4790 register from the stack, since lowest will == highest in
4791 `pop_failure_point'. */
4792 active_reg_t dummy_low_reg, dummy_high_reg;
4793 unsigned char *pdummy;
4796 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4797 POP_FAILURE_POINT (sdummy, pdummy,
4798 dummy_low_reg, dummy_high_reg,
4799 reg_dummy, reg_dummy, reg_info_dummy);
4801 /* Note fall through. */
4805 DEBUG_PRINT2 ("\n%p: ", p);
4807 DEBUG_PRINT2 ("\n0x%x: ", p);
4809 /* Note fall through. */
4811 /* Unconditionally jump (without popping any failure points). */
4813 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4814 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4815 p += mcnt; /* Do the jump. */
4817 DEBUG_PRINT2 ("(to %p).\n", p);
4819 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4824 /* We need this opcode so we can detect where alternatives end
4825 in `group_match_null_string_p' et al. */
4827 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4828 goto unconditional_jump;
4831 /* Normally, the on_failure_jump pushes a failure point, which
4832 then gets popped at pop_failure_jump. We will end up at
4833 pop_failure_jump, also, and with a pattern of, say, `a+', we
4834 are skipping over the on_failure_jump, so we have to push
4835 something meaningless for pop_failure_jump to pop. */
4836 case dummy_failure_jump:
4837 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4838 /* It doesn't matter what we push for the string here. What
4839 the code at `fail' tests is the value for the pattern. */
4840 PUSH_FAILURE_POINT (0, 0, -2);
4841 goto unconditional_jump;
4844 /* At the end of an alternative, we need to push a dummy failure
4845 point in case we are followed by a `pop_failure_jump', because
4846 we don't want the failure point for the alternative to be
4847 popped. For example, matching `(a|ab)*' against `aab'
4848 requires that we match the `ab' alternative. */
4849 case push_dummy_failure:
4850 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4851 /* See comments just above at `dummy_failure_jump' about the
4853 PUSH_FAILURE_POINT (0, 0, -2);
4856 /* Have to succeed matching what follows at least n times.
4857 After that, handle like `on_failure_jump'. */
4859 EXTRACT_NUMBER (mcnt, p + 2);
4860 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4863 /* Originally, this is how many times we HAVE to succeed. */
4868 STORE_NUMBER_AND_INCR (p, mcnt);
4870 DEBUG_PRINT3 (" Setting %p to %d.\n", p - 2, mcnt);
4872 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - 2, mcnt);
4878 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p+2);
4880 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4882 p[2] = (unsigned char) no_op;
4883 p[3] = (unsigned char) no_op;
4889 EXTRACT_NUMBER (mcnt, p + 2);
4890 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4892 /* Originally, this is how many times we CAN jump. */
4896 STORE_NUMBER (p + 2, mcnt);
4898 DEBUG_PRINT3 (" Setting %p to %d.\n", p + 2, mcnt);
4900 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + 2, mcnt);
4902 goto unconditional_jump;
4904 /* If don't have to jump any more, skip over the rest of command. */
4911 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4913 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4915 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4917 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
4919 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4921 STORE_NUMBER (p1, mcnt);
4926 /* The DEC Alpha C compiler 3.x generates incorrect code for the
4927 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4928 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4929 macro and introducing temporary variables works around the bug. */
4932 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4933 if (AT_WORD_BOUNDARY (d))
4938 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4939 if (AT_WORD_BOUNDARY (d))
4945 boolean prevchar, thischar;
4947 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4948 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
4951 prevchar = WORDCHAR_P (d - 1);
4952 thischar = WORDCHAR_P (d);
4953 if (prevchar != thischar)
4960 boolean prevchar, thischar;
4962 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4963 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
4966 prevchar = WORDCHAR_P (d - 1);
4967 thischar = WORDCHAR_P (d);
4968 if (prevchar != thischar)
4975 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4976 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4981 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4982 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4983 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4989 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4990 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4995 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4996 if (PTR_CHAR_POS ((unsigned char *) d) != point)
5001 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5002 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
5007 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5012 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5016 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5018 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
5020 SET_REGS_MATCHED ();
5024 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5026 goto matchnotsyntax;
5029 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5033 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5035 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
5037 SET_REGS_MATCHED ();
5040 #else /* not emacs */
5042 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5044 if (!WORDCHAR_P (d))
5046 SET_REGS_MATCHED ();
5051 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5055 SET_REGS_MATCHED ();
5058 #endif /* not emacs */
5063 continue; /* Successfully executed one pattern command; keep going. */
5066 /* We goto here if a matching operation fails. */
5068 if (!FAIL_STACK_EMPTY ())
5069 { /* A restart point is known. Restore to that state. */
5070 DEBUG_PRINT1 ("\nFAIL:\n");
5071 POP_FAILURE_POINT (d, p,
5072 lowest_active_reg, highest_active_reg,
5073 regstart, regend, reg_info);
5075 /* If this failure point is a dummy, try the next one. */
5079 /* If we failed to the end of the pattern, don't examine *p. */
5083 boolean is_a_jump_n = false;
5085 /* If failed to a backwards jump that's part of a repetition
5086 loop, need to pop this failure point and use the next one. */
5087 switch ((re_opcode_t) *p)
5091 case maybe_pop_jump:
5092 case pop_failure_jump:
5095 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5098 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5100 && (re_opcode_t) *p1 == on_failure_jump))
5108 if (d >= string1 && d <= end1)
5112 break; /* Matching at this starting point really fails. */
5116 goto restore_best_regs;
5120 return -1; /* Failure to match. */
5123 /* Subroutine definitions for re_match_2. */
5126 /* We are passed P pointing to a register number after a start_memory.
5128 Return true if the pattern up to the corresponding stop_memory can
5129 match the empty string, and false otherwise.
5131 If we find the matching stop_memory, sets P to point to one past its number.
5132 Otherwise, sets P to an undefined byte less than or equal to END.
5134 We don't handle duplicates properly (yet). */
5137 group_match_null_string_p (p, end, reg_info)
5138 unsigned char **p, *end;
5139 register_info_type *reg_info;
5142 /* Point to after the args to the start_memory. */
5143 unsigned char *p1 = *p + 2;
5147 /* Skip over opcodes that can match nothing, and return true or
5148 false, as appropriate, when we get to one that can't, or to the
5149 matching stop_memory. */
5151 switch ((re_opcode_t) *p1)
5153 /* Could be either a loop or a series of alternatives. */
5154 case on_failure_jump:
5156 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5158 /* If the next operation is not a jump backwards in the
5163 /* Go through the on_failure_jumps of the alternatives,
5164 seeing if any of the alternatives cannot match nothing.
5165 The last alternative starts with only a jump,
5166 whereas the rest start with on_failure_jump and end
5167 with a jump, e.g., here is the pattern for `a|b|c':
5169 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5170 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5173 So, we have to first go through the first (n-1)
5174 alternatives and then deal with the last one separately. */
5177 /* Deal with the first (n-1) alternatives, which start
5178 with an on_failure_jump (see above) that jumps to right
5179 past a jump_past_alt. */
5181 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5183 /* `mcnt' holds how many bytes long the alternative
5184 is, including the ending `jump_past_alt' and
5187 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5191 /* Move to right after this alternative, including the
5195 /* Break if it's the beginning of an n-th alternative
5196 that doesn't begin with an on_failure_jump. */
5197 if ((re_opcode_t) *p1 != on_failure_jump)
5200 /* Still have to check that it's not an n-th
5201 alternative that starts with an on_failure_jump. */
5203 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5204 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5206 /* Get to the beginning of the n-th alternative. */
5212 /* Deal with the last alternative: go back and get number
5213 of the `jump_past_alt' just before it. `mcnt' contains
5214 the length of the alternative. */
5215 EXTRACT_NUMBER (mcnt, p1 - 2);
5217 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5220 p1 += mcnt; /* Get past the n-th alternative. */
5226 assert (p1[1] == **p);
5232 if (!common_op_match_null_string_p (&p1, end, reg_info))
5235 } /* while p1 < end */
5238 } /* group_match_null_string_p */
5241 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5242 It expects P to be the first byte of a single alternative and END one
5243 byte past the last. The alternative can contain groups. */
5246 alt_match_null_string_p (p, end, reg_info)
5247 unsigned char *p, *end;
5248 register_info_type *reg_info;
5251 unsigned char *p1 = p;
5255 /* Skip over opcodes that can match nothing, and break when we get
5256 to one that can't. */
5258 switch ((re_opcode_t) *p1)
5261 case on_failure_jump:
5263 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5268 if (!common_op_match_null_string_p (&p1, end, reg_info))
5271 } /* while p1 < end */
5274 } /* alt_match_null_string_p */
5277 /* Deals with the ops common to group_match_null_string_p and
5278 alt_match_null_string_p.
5280 Sets P to one after the op and its arguments, if any. */
5283 common_op_match_null_string_p (p, end, reg_info)
5284 unsigned char **p, *end;
5285 register_info_type *reg_info;
5290 unsigned char *p1 = *p;
5292 switch ((re_opcode_t) *p1++)
5312 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5313 ret = group_match_null_string_p (&p1, end, reg_info);
5315 /* Have to set this here in case we're checking a group which
5316 contains a group and a back reference to it. */
5318 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5319 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5325 /* If this is an optimized succeed_n for zero times, make the jump. */
5327 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5335 /* Get to the number of times to succeed. */
5337 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5342 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5350 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5358 /* All other opcodes mean we cannot match the empty string. */
5364 } /* common_op_match_null_string_p */
5367 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5368 bytes; nonzero otherwise. */
5371 bcmp_translate (s1, s2, len, translate)
5372 const char *s1, *s2;
5374 RE_TRANSLATE_TYPE translate;
5376 register const unsigned char *p1 = (const unsigned char *) s1;
5377 register const unsigned char *p2 = (const unsigned char *) s2;
5380 if (translate[*p1++] != translate[*p2++]) return 1;
5386 /* Entry points for GNU code. */
5388 /* re_compile_pattern is the GNU regular expression compiler: it
5389 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5390 Returns 0 if the pattern was valid, otherwise an error string.
5392 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5393 are set in BUFP on entry.
5395 We call regex_compile to do the actual compilation. */
5398 re_compile_pattern (pattern, length, bufp)
5399 const char *pattern;
5401 struct re_pattern_buffer *bufp;
5405 /* GNU code is written to assume at least RE_NREGS registers will be set
5406 (and at least one extra will be -1). */
5407 bufp->regs_allocated = REGS_UNALLOCATED;
5409 /* And GNU code determines whether or not to get register information
5410 by passing null for the REGS argument to re_match, etc., not by
5414 /* Match anchors at newline. */
5415 bufp->newline_anchor = 1;
5417 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5421 return gettext (re_error_msgid[(int) ret]);
5424 /* Entry points compatible with 4.2 BSD regex library. We don't define
5425 them unless specifically requested. */
5427 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
5429 /* BSD has one and only one pattern buffer. */
5430 static struct re_pattern_buffer re_comp_buf;
5434 /* Make these definitions weak in libc, so POSIX programs can redefine
5435 these names if they don't use our functions, and still use
5436 regcomp/regexec below without link errors. */
5446 if (!re_comp_buf.buffer)
5447 return gettext ("No previous regular expression");
5451 if (!re_comp_buf.buffer)
5453 re_comp_buf.buffer = (unsigned char *) malloc (200);
5454 if (re_comp_buf.buffer == NULL)
5455 return gettext (re_error_msgid[(int) REG_ESPACE]);
5456 re_comp_buf.allocated = 200;
5458 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5459 if (re_comp_buf.fastmap == NULL)
5460 return gettext (re_error_msgid[(int) REG_ESPACE]);
5463 /* Since `re_exec' always passes NULL for the `regs' argument, we
5464 don't need to initialize the pattern buffer fields which affect it. */
5466 /* Match anchors at newlines. */
5467 re_comp_buf.newline_anchor = 1;
5469 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5474 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5475 return (char *) gettext (re_error_msgid[(int) ret]);
5486 const int len = strlen (s);
5488 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5491 #endif /* _REGEX_RE_COMP */
5493 /* POSIX.2 functions. Don't define these for Emacs. */
5497 /* regcomp takes a regular expression as a string and compiles it.
5499 PREG is a regex_t *. We do not expect any fields to be initialized,
5500 since POSIX says we shouldn't. Thus, we set
5502 `buffer' to the compiled pattern;
5503 `used' to the length of the compiled pattern;
5504 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5505 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5506 RE_SYNTAX_POSIX_BASIC;
5507 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5508 `fastmap' and `fastmap_accurate' to zero;
5509 `re_nsub' to the number of subexpressions in PATTERN.
5511 PATTERN is the address of the pattern string.
5513 CFLAGS is a series of bits which affect compilation.
5515 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5516 use POSIX basic syntax.
5518 If REG_NEWLINE is set, then . and [^...] don't match newline.
5519 Also, regexec will try a match beginning after every newline.
5521 If REG_ICASE is set, then we considers upper- and lowercase
5522 versions of letters to be equivalent when matching.
5524 If REG_NOSUB is set, then when PREG is passed to regexec, that
5525 routine will report only success or failure, and nothing about the
5528 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5529 the return codes and their meanings.) */
5535 regcomp (preg, pattern, cflags)
5537 const char *pattern;
5542 = (cflags & REG_EXTENDED) ?
5543 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5545 /* regex_compile will allocate the space for the compiled pattern. */
5547 preg->allocated = 0;
5550 /* Don't bother to use a fastmap when searching. This simplifies the
5551 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5552 characters after newlines into the fastmap. This way, we just try
5556 if (cflags & REG_ICASE)
5561 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
5562 * sizeof (*(RE_TRANSLATE_TYPE)0));
5563 if (preg->translate == NULL)
5564 return (int) REG_ESPACE;
5566 /* Map uppercase characters to corresponding lowercase ones. */
5567 for (i = 0; i < CHAR_SET_SIZE; i++)
5568 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5571 preg->translate = NULL;
5573 /* If REG_NEWLINE is set, newlines are treated differently. */
5574 if (cflags & REG_NEWLINE)
5575 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5576 syntax &= ~RE_DOT_NEWLINE;
5577 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5578 /* It also changes the matching behavior. */
5579 preg->newline_anchor = 1;
5582 preg->newline_anchor = 0;
5584 preg->no_sub = !!(cflags & REG_NOSUB);
5586 /* POSIX says a null character in the pattern terminates it, so we
5587 can use strlen here in compiling the pattern. */
5588 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5590 /* POSIX doesn't distinguish between an unmatched open-group and an
5591 unmatched close-group: both are REG_EPAREN. */
5592 if (ret == REG_ERPAREN) ret = REG_EPAREN;
5598 /* regexec searches for a given pattern, specified by PREG, in the
5601 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5602 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5603 least NMATCH elements, and we set them to the offsets of the
5604 corresponding matched substrings.
5606 EFLAGS specifies `execution flags' which affect matching: if
5607 REG_NOTBOL is set, then ^ does not match at the beginning of the
5608 string; if REG_NOTEOL is set, then $ does not match at the end.
5610 We return 0 if we find a match and REG_NOMATCH if not. */
5616 regexec (preg, string, nmatch, pmatch, eflags)
5617 const regex_t *preg;
5620 regmatch_t pmatch[];
5624 struct re_registers regs;
5625 regex_t private_preg;
5626 int len = strlen (string);
5627 boolean want_reg_info = !preg->no_sub && nmatch > 0;
5629 private_preg = *preg;
5631 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5632 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5634 /* The user has told us exactly how many registers to return
5635 information about, via `nmatch'. We have to pass that on to the
5636 matching routines. */
5637 private_preg.regs_allocated = REGS_FIXED;
5641 regs.num_regs = nmatch;
5642 regs.start = TALLOC (nmatch, regoff_t);
5643 regs.end = TALLOC (nmatch, regoff_t);
5644 if (regs.start == NULL || regs.end == NULL)
5645 return (int) REG_NOMATCH;
5648 /* Perform the searching operation. */
5649 ret = re_search (&private_preg, string, len,
5650 /* start: */ 0, /* range: */ len,
5651 want_reg_info ? ®s : (struct re_registers *) 0);
5653 /* Copy the register information to the POSIX structure. */
5660 for (r = 0; r < nmatch; r++)
5662 pmatch[r].rm_so = regs.start[r];
5663 pmatch[r].rm_eo = regs.end[r];
5667 /* If we needed the temporary register info, free the space now. */
5672 /* We want zero return to mean success, unlike `re_search'. */
5673 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5677 /* Returns a message corresponding to an error code, ERRCODE, returned
5678 from either regcomp or regexec. We don't use PREG here. */
5681 regerror (errcode, preg, errbuf, errbuf_size)
5683 const regex_t *preg;
5691 || errcode >= (int) (sizeof (re_error_msgid)
5692 / sizeof (re_error_msgid[0])))
5693 /* Only error codes returned by the rest of the code should be passed
5694 to this routine. If we are given anything else, or if other regex
5695 code generates an invalid error code, then the program has a bug.
5696 Dump core so we can fix it. */
5699 msg = gettext (re_error_msgid[errcode]);
5701 msg_size = strlen (msg) + 1; /* Includes the null. */
5703 if (errbuf_size != 0)
5705 if (msg_size > errbuf_size)
5707 strncpy (errbuf, msg, errbuf_size - 1);
5708 errbuf[errbuf_size - 1] = 0;
5711 strcpy (errbuf, msg);
5718 /* Free dynamically allocated space used by PREG. */
5727 if (preg->buffer != NULL)
5728 free (preg->buffer);
5729 preg->buffer = NULL;
5731 preg->allocated = 0;
5734 if (preg->fastmap != NULL)
5735 free (preg->fastmap);
5736 preg->fastmap = NULL;
5737 preg->fastmap_accurate = 0;
5739 if (preg->translate != NULL)
5740 free (preg->translate);
5741 preg->translate = NULL;
5744 #endif /* not emacs */