2 * regex.c -- POSIX-conformant regular expression function set for the lsof
5 * This file is used when the UNIX dialect does not have a POSIX-conformant
6 * regular expression function set. In that case USE_LIB_REGEX is defined.
8 * V. Abell <abe@purdue.edu>
9 * Purdue University Computing Center
14 * Copyright 2000 Purdue Research Foundation, West Lafayette, Indiana
15 * 47907. All rights reserved.
17 * Written by Victor A. Abell
19 * This software is not subject to any license of the American Telephone
20 * and Telegraph Company or the Regents of the University of California.
22 * This software has been adapted from snprintf.c in sendmail 8.9.3. It
23 * is subject to the sendmail copyright statements listed below, and the
24 * sendmail licensing terms stated in the sendmail LICENSE file comment
25 * section of this file.
27 * Permission is granted to anyone to use this software for any purpose on
28 * any computer system, and to alter it and redistribute it freely, subject
29 * to the following restrictions:
31 * 1. Neither the authors nor Purdue University are responsible for any
32 * consequences of the use of this software.
34 * 2. The origin of this software must not be misrepresented, either by
35 * explicit claim or by omission. Credit to the authors and Purdue
36 * University must appear in documentation and sources.
38 * 3. Altered versions must be plainly marked as such, and must not be
39 * misrepresented as being the original software.
41 * 4. This notice may not be removed or altered.
45 #include "../machine.h"
49 * This file comes from GLIBC 2.2. It is used when the UNIX dialect does not
50 * have a POSIX-conformant regular expression function set. In that case
51 * USE_LIB_REGEX is defined.
54 /* Extended regular expression matching and search library,
56 (Implements POSIX draft P1003.2/D11.2, except for some of the
57 internationalization features.)
58 Copyright (C) 1993-1999, 2000 Free Software Foundation, Inc.
60 The GNU C Library is free software; you can redistribute it and/or
61 modify it under the terms of the GNU Library General Public License as
62 published by the Free Software Foundation; either version 2 of the
63 License, or (at your option) any later version.
65 The GNU C Library is distributed in the hope that it will be useful,
66 but WITHOUT ANY WARRANTY; without even the implied warranty of
67 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
68 Library General Public License for more details.
70 You should have received a copy of the GNU Library General Public
71 License along with the GNU C Library; see the file COPYING.LIB. If not,
72 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
73 Boston, MA 02111-1307, USA. */
75 /* AIX requires this to be the first thing in the file. */
76 #if defined _AIX && !defined REGEX_MALLOC
88 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
89 # define PARAMS(args) args
91 # define PARAMS(args) ()
93 #endif /* Not PARAMS. */
95 #if defined STDC_HEADERS && !defined emacs
98 /* We need this for `regex.h', and perhaps for the Emacs include files. */
99 # include <sys/types.h>
102 #define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
104 /* For platform which support the ISO C amendement 1 functionality we
105 support user defined character classes. */
106 #if defined _LIBC || WIDE_CHAR_SUPPORT
107 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
113 /* We have to keep the namespace clean. */
114 # define regfree(preg) __regfree (preg)
115 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
116 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
117 # define regerror(errcode, preg, errbuf, errbuf_size) \
118 __regerror(errcode, preg, errbuf, errbuf_size)
119 # define re_set_registers(bu, re, nu, st, en) \
120 __re_set_registers (bu, re, nu, st, en)
121 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
122 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
123 # define re_match(bufp, string, size, pos, regs) \
124 __re_match (bufp, string, size, pos, regs)
125 # define re_search(bufp, string, size, startpos, range, regs) \
126 __re_search (bufp, string, size, startpos, range, regs)
127 # define re_compile_pattern(pattern, length, bufp) \
128 __re_compile_pattern (pattern, length, bufp)
129 # define re_set_syntax(syntax) __re_set_syntax (syntax)
130 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
131 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
132 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
134 # define btowc __btowc
136 /* We are also using some library internals. */
137 # include <locale/localeinfo.h>
138 # include <locale/elem-hash.h>
139 # include <langinfo.h>
142 /* This is for other GNU distributions with internationalized messages. */
143 #if HAVE_LIBINTL_H || defined _LIBC
144 # include <libintl.h>
147 # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
150 # define gettext(msgid) (msgid)
154 /* This define is so xgettext can find the internationalizable
156 # define gettext_noop(String) String
159 /* The `emacs' switch turns on certain matching commands
160 that make sense only in Emacs. */
167 #else /* not emacs */
169 /* If we are not linking with Emacs proper,
170 we can't use the relocating allocator
171 even if config.h says that we can. */
174 # if defined STDC_HEADERS || defined _LIBC
181 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
182 If nothing else has been done, use the method below. */
183 # ifdef INHIBIT_STRING_HEADER
184 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
185 # if !defined bzero && !defined bcopy
186 # undef INHIBIT_STRING_HEADER
191 /* This is the normal way of making sure we have a bcopy and a bzero.
192 This is used in most programs--a few other programs avoid this
193 by defining INHIBIT_STRING_HEADER. */
194 # ifndef INHIBIT_STRING_HEADER
195 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
199 # define bzero(s, n) (memset (s, '\0', n), (s))
201 # define bzero(s, n) __bzero (s, n)
205 # include <strings.h>
207 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
210 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
215 /* Define the syntax stuff for \<, \>, etc. */
217 /* This must be nonzero for the wordchar and notwordchar pattern
218 commands in re_match_2. */
223 # ifdef SWITCH_ENUM_BUG
224 # define SWITCH_ENUM_CAST(x) ((int)(x))
226 # define SWITCH_ENUM_CAST(x) (x)
229 #endif /* not emacs */
231 #if defined _LIBC || HAVE_LIMITS_H
236 # define MB_LEN_MAX 1
239 /* Get the interface, including the syntax bits. */
240 /* Disabled by V. Abell on January 29, 2001: #include <regex.h> */
241 #include "../regex.h"
243 /* isalpha etc. are used for the character classes. */
246 /* Jim Meyering writes:
248 "... Some ctype macros are valid only for character codes that
249 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
250 using /bin/cc or gcc but without giving an ansi option). So, all
251 ctype uses should be through macros like ISPRINT... If
252 STDC_HEADERS is defined, then autoconf has verified that the ctype
253 macros don't need to be guarded with references to isascii. ...
254 Defining isascii to 1 should let any compiler worth its salt
255 eliminate the && through constant folding."
256 Solaris defines some of these symbols so we must undefine them first. */
259 #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
260 # define ISASCII(c) 1
262 # define ISASCII(c) isascii(c)
266 # define ISBLANK(c) (ISASCII (c) && isblank (c))
268 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
271 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
273 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
277 #define ISPRINT(c) (ISASCII (c) && isprint (c))
278 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
279 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
280 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
281 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
282 #define ISLOWER(c) (ISASCII (c) && islower (c))
283 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
284 #define ISSPACE(c) (ISASCII (c) && isspace (c))
285 #define ISUPPER(c) (ISASCII (c) && isupper (c))
286 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
289 # define TOLOWER(c) _tolower(c)
291 # define TOLOWER(c) tolower(c)
295 # define NULL (void *)0
298 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
299 since ours (we hope) works properly with all combinations of
300 machines, compilers, `char' and `unsigned char' argument types.
301 (Per Bothner suggested the basic approach.) */
302 #undef SIGN_EXTEND_CHAR
304 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
305 #else /* not __STDC__ */
306 /* As in Harbison and Steele. */
307 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
311 /* How many characters in the character set. */
312 # define CHAR_SET_SIZE 256
316 extern char *re_syntax_table;
318 # else /* not SYNTAX_TABLE */
320 static char re_syntax_table[CHAR_SET_SIZE];
330 bzero (re_syntax_table, sizeof re_syntax_table);
332 for (c = 0; c < CHAR_SET_SIZE; ++c)
334 re_syntax_table[c] = Sword;
336 re_syntax_table['_'] = Sword;
341 # endif /* not SYNTAX_TABLE */
343 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
347 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
348 use `alloca' instead of `malloc'. This is because using malloc in
349 re_search* or re_match* could cause memory leaks when C-g is used in
350 Emacs; also, malloc is slower and causes storage fragmentation. On
351 the other hand, malloc is more portable, and easier to debug.
353 Because we sometimes use alloca, some routines have to be macros,
354 not functions -- `alloca'-allocated space disappears at the end of the
355 function it is called in. */
359 # define REGEX_ALLOCATE malloc
360 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
361 # define REGEX_FREE free
363 #else /* not REGEX_MALLOC */
365 /* Emacs already defines alloca, sometimes. */
368 /* Make alloca work the best possible way. */
370 # define alloca __builtin_alloca
371 # else /* not __GNUC__ */
374 # endif /* HAVE_ALLOCA_H */
375 # endif /* not __GNUC__ */
377 # endif /* not alloca */
379 # define REGEX_ALLOCATE alloca
381 /* Assumes a `char *destination' variable. */
382 # define REGEX_REALLOCATE(source, osize, nsize) \
383 (destination = (char *) alloca (nsize), \
384 memcpy (destination, source, osize))
386 /* No need to do anything to free, after alloca. */
387 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
389 #endif /* not REGEX_MALLOC */
391 /* Define how to allocate the failure stack. */
393 #if defined REL_ALLOC && defined REGEX_MALLOC
395 # define REGEX_ALLOCATE_STACK(size) \
396 r_alloc (&failure_stack_ptr, (size))
397 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
398 r_re_alloc (&failure_stack_ptr, (nsize))
399 # define REGEX_FREE_STACK(ptr) \
400 r_alloc_free (&failure_stack_ptr)
402 #else /* not using relocating allocator */
406 # define REGEX_ALLOCATE_STACK malloc
407 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
408 # define REGEX_FREE_STACK free
410 # else /* not REGEX_MALLOC */
412 # define REGEX_ALLOCATE_STACK alloca
414 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
415 REGEX_REALLOCATE (source, osize, nsize)
416 /* No need to explicitly free anything. */
417 # define REGEX_FREE_STACK(arg)
419 # endif /* not REGEX_MALLOC */
420 #endif /* not using relocating allocator */
423 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
424 `string1' or just past its end. This works if PTR is NULL, which is
426 #define FIRST_STRING_P(ptr) \
427 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
429 /* (Re)Allocate N items of type T using malloc, or fail. */
430 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
431 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
432 #define RETALLOC_IF(addr, n, t) \
433 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
434 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
436 #define BYTEWIDTH 8 /* In bits. */
438 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
442 #define MAX(a, b) ((a) > (b) ? (a) : (b))
443 #define MIN(a, b) ((a) < (b) ? (a) : (b))
445 typedef char boolean;
449 static int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
450 const char *string1, int size1,
451 const char *string2, int size2,
453 struct re_registers *regs,
456 /* These are the command codes that appear in compiled regular
457 expressions. Some opcodes are followed by argument bytes. A
458 command code can specify any interpretation whatsoever for its
459 arguments. Zero bytes may appear in the compiled regular expression. */
465 /* Succeed right away--no more backtracking. */
468 /* Followed by one byte giving n, then by n literal bytes. */
471 /* Matches any (more or less) character. */
474 /* Matches any one char belonging to specified set. First
475 following byte is number of bitmap bytes. Then come bytes
476 for a bitmap saying which chars are in. Bits in each byte
477 are ordered low-bit-first. A character is in the set if its
478 bit is 1. A character too large to have a bit in the map is
479 automatically not in the set. */
482 /* Same parameters as charset, but match any character that is
483 not one of those specified. */
486 /* Start remembering the text that is matched, for storing in a
487 register. Followed by one byte with the register number, in
488 the range 0 to one less than the pattern buffer's re_nsub
489 field. Then followed by one byte with the number of groups
490 inner to this one. (This last has to be part of the
491 start_memory only because we need it in the on_failure_jump
495 /* Stop remembering the text that is matched and store it in a
496 memory register. Followed by one byte with the register
497 number, in the range 0 to one less than `re_nsub' in the
498 pattern buffer, and one byte with the number of inner groups,
499 just like `start_memory'. (We need the number of inner
500 groups here because we don't have any easy way of finding the
501 corresponding start_memory when we're at a stop_memory.) */
504 /* Match a duplicate of something remembered. Followed by one
505 byte containing the register number. */
508 /* Fail unless at beginning of line. */
511 /* Fail unless at end of line. */
514 /* Succeeds if at beginning of buffer (if emacs) or at beginning
515 of string to be matched (if not). */
518 /* Analogously, for end of buffer/string. */
521 /* Followed by two byte relative address to which to jump. */
524 /* Same as jump, but marks the end of an alternative. */
527 /* Followed by two-byte relative address of place to resume at
528 in case of failure. */
531 /* Like on_failure_jump, but pushes a placeholder instead of the
532 current string position when executed. */
533 on_failure_keep_string_jump,
535 /* Throw away latest failure point and then jump to following
536 two-byte relative address. */
539 /* Change to pop_failure_jump if know won't have to backtrack to
540 match; otherwise change to jump. This is used to jump
541 back to the beginning of a repeat. If what follows this jump
542 clearly won't match what the repeat does, such that we can be
543 sure that there is no use backtracking out of repetitions
544 already matched, then we change it to a pop_failure_jump.
545 Followed by two-byte address. */
548 /* Jump to following two-byte address, and push a dummy failure
549 point. This failure point will be thrown away if an attempt
550 is made to use it for a failure. A `+' construct makes this
551 before the first repeat. Also used as an intermediary kind
552 of jump when compiling an alternative. */
555 /* Push a dummy failure point and continue. Used at the end of
559 /* Followed by two-byte relative address and two-byte number n.
560 After matching N times, jump to the address upon failure. */
563 /* Followed by two-byte relative address, and two-byte number n.
564 Jump to the address N times, then fail. */
567 /* Set the following two-byte relative address to the
568 subsequent two-byte number. The address *includes* the two
572 wordchar, /* Matches any word-constituent character. */
573 notwordchar, /* Matches any char that is not a word-constituent. */
575 wordbeg, /* Succeeds if at word beginning. */
576 wordend, /* Succeeds if at word end. */
578 wordbound, /* Succeeds if at a word boundary. */
579 notwordbound /* Succeeds if not at a word boundary. */
582 ,before_dot, /* Succeeds if before point. */
583 at_dot, /* Succeeds if at point. */
584 after_dot, /* Succeeds if after point. */
586 /* Matches any character whose syntax is specified. Followed by
587 a byte which contains a syntax code, e.g., Sword. */
590 /* Matches any character whose syntax is not that specified. */
595 /* Common operations on the compiled pattern. */
597 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
599 #define STORE_NUMBER(destination, number) \
601 (destination)[0] = (number) & 0377; \
602 (destination)[1] = (number) >> 8; \
605 /* Same as STORE_NUMBER, except increment DESTINATION to
606 the byte after where the number is stored. Therefore, DESTINATION
607 must be an lvalue. */
609 #define STORE_NUMBER_AND_INCR(destination, number) \
611 STORE_NUMBER (destination, number); \
612 (destination) += 2; \
615 /* Put into DESTINATION a number stored in two contiguous bytes starting
618 #define EXTRACT_NUMBER(destination, source) \
620 (destination) = *(source) & 0377; \
621 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
625 static void extract_number _RE_ARGS ((int *dest, unsigned char *source));
627 extract_number (dest, source)
629 unsigned char *source;
631 int temp = SIGN_EXTEND_CHAR (*(source + 1));
632 *dest = *source & 0377;
636 # ifndef EXTRACT_MACROS /* To debug the macros. */
637 # undef EXTRACT_NUMBER
638 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
639 # endif /* not EXTRACT_MACROS */
643 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
644 SOURCE must be an lvalue. */
646 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
648 EXTRACT_NUMBER (destination, source); \
653 static void extract_number_and_incr _RE_ARGS ((int *destination,
654 unsigned char **source));
656 extract_number_and_incr (destination, source)
658 unsigned char **source;
660 extract_number (destination, *source);
664 # ifndef EXTRACT_MACROS
665 # undef EXTRACT_NUMBER_AND_INCR
666 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
667 extract_number_and_incr (&dest, &src)
668 # endif /* not EXTRACT_MACROS */
672 /* If DEBUG is defined, Regex prints many voluminous messages about what
673 it is doing (if the variable `debug' is nonzero). If linked with the
674 main program in `iregex.c', you can enter patterns and strings
675 interactively. And if linked with the main program in `main.c' and
676 the other test files, you can run the already-written tests. */
680 /* We use standard I/O for debugging. */
683 /* It is useful to test things that ``must'' be true when debugging. */
688 # define DEBUG_STATEMENT(e) e
689 # define DEBUG_PRINT1(x) if (debug) printf (x)
690 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
691 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
692 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
693 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
694 if (debug) print_partial_compiled_pattern (s, e)
695 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
696 if (debug) print_double_string (w, s1, sz1, s2, sz2)
699 /* Print the fastmap in human-readable form. */
702 print_fastmap (fastmap)
705 unsigned was_a_range = 0;
708 while (i < (1 << BYTEWIDTH))
714 while (i < (1 << BYTEWIDTH) && fastmap[i])
730 /* Print a compiled pattern string in human-readable form, starting at
731 the START pointer into it and ending just before the pointer END. */
734 print_partial_compiled_pattern (start, end)
735 unsigned char *start;
740 unsigned char *p = start;
741 unsigned char *pend = end;
749 /* Loop over pattern commands. */
753 printf ("%t:\t", p - start);
755 printf ("%ld:\t", (long int) (p - start));
758 switch ((re_opcode_t) *p++)
766 printf ("/exactn/%d", mcnt);
777 printf ("/start_memory/%d/%d", mcnt, *p++);
782 printf ("/stop_memory/%d/%d", mcnt, *p++);
786 printf ("/duplicate/%d", *p++);
796 register int c, last = -100;
797 register int in_range = 0;
799 printf ("/charset [%s",
800 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
802 assert (p + *p < pend);
804 for (c = 0; c < 256; c++)
806 && (p[1 + (c/8)] & (1 << (c % 8))))
808 /* Are we starting a range? */
809 if (last + 1 == c && ! in_range)
814 /* Have we broken a range? */
815 else if (last + 1 != c && in_range)
844 case on_failure_jump:
845 extract_number_and_incr (&mcnt, &p);
847 printf ("/on_failure_jump to %t", p + mcnt - start);
849 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
853 case on_failure_keep_string_jump:
854 extract_number_and_incr (&mcnt, &p);
856 printf ("/on_failure_keep_string_jump to %t", p + mcnt - start);
858 printf ("/on_failure_keep_string_jump to %ld",
859 (long int) (p + mcnt - start));
863 case dummy_failure_jump:
864 extract_number_and_incr (&mcnt, &p);
866 printf ("/dummy_failure_jump to %t", p + mcnt - start);
868 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
872 case push_dummy_failure:
873 printf ("/push_dummy_failure");
877 extract_number_and_incr (&mcnt, &p);
879 printf ("/maybe_pop_jump to %t", p + mcnt - start);
881 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
885 case pop_failure_jump:
886 extract_number_and_incr (&mcnt, &p);
888 printf ("/pop_failure_jump to %t", p + mcnt - start);
890 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
895 extract_number_and_incr (&mcnt, &p);
897 printf ("/jump_past_alt to %t", p + mcnt - start);
899 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
904 extract_number_and_incr (&mcnt, &p);
906 printf ("/jump to %t", p + mcnt - start);
908 printf ("/jump to %ld", (long int) (p + mcnt - start));
913 extract_number_and_incr (&mcnt, &p);
915 extract_number_and_incr (&mcnt2, &p);
917 printf ("/succeed_n to %t, %d times", p1 - start, mcnt2);
919 printf ("/succeed_n to %ld, %d times",
920 (long int) (p1 - start), mcnt2);
925 extract_number_and_incr (&mcnt, &p);
927 extract_number_and_incr (&mcnt2, &p);
928 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
932 extract_number_and_incr (&mcnt, &p);
934 extract_number_and_incr (&mcnt2, &p);
936 printf ("/set_number_at location %t to %d", p1 - start, mcnt2);
938 printf ("/set_number_at location %ld to %d",
939 (long int) (p1 - start), mcnt2);
944 printf ("/wordbound");
948 printf ("/notwordbound");
960 printf ("/before_dot");
968 printf ("/after_dot");
972 printf ("/syntaxspec");
974 printf ("/%d", mcnt);
978 printf ("/notsyntaxspec");
980 printf ("/%d", mcnt);
985 printf ("/wordchar");
989 printf ("/notwordchar");
1001 printf ("?%d", *(p-1));
1008 printf ("%t:\tend of pattern.\n", p - start);
1010 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1016 print_compiled_pattern (bufp)
1017 struct re_pattern_buffer *bufp;
1019 unsigned char *buffer = bufp->buffer;
1021 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1022 printf ("%ld bytes used/%ld bytes allocated.\n",
1023 bufp->used, bufp->allocated);
1025 if (bufp->fastmap_accurate && bufp->fastmap)
1027 printf ("fastmap: ");
1028 print_fastmap (bufp->fastmap);
1032 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1034 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1036 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1037 printf ("can_be_null: %d\t", bufp->can_be_null);
1038 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1039 printf ("no_sub: %d\t", bufp->no_sub);
1040 printf ("not_bol: %d\t", bufp->not_bol);
1041 printf ("not_eol: %d\t", bufp->not_eol);
1042 printf ("syntax: %lx\n", bufp->syntax);
1043 /* Perhaps we should print the translate table? */
1048 print_double_string (where, string1, size1, string2, size2)
1050 const char *string1;
1051 const char *string2;
1061 if (FIRST_STRING_P (where))
1063 for (this_char = where - string1; this_char < size1; this_char++)
1064 putchar (string1[this_char]);
1069 for (this_char = where - string2; this_char < size2; this_char++)
1070 putchar (string2[this_char]);
1081 #else /* not DEBUG */
1086 # define DEBUG_STATEMENT(e)
1087 # define DEBUG_PRINT1(x)
1088 # define DEBUG_PRINT2(x1, x2)
1089 # define DEBUG_PRINT3(x1, x2, x3)
1090 # define DEBUG_PRINT4(x1, x2, x3, x4)
1091 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1092 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1094 #endif /* not DEBUG */
1096 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1097 also be assigned to arbitrarily: each pattern buffer stores its own
1098 syntax, so it can be changed between regex compilations. */
1099 /* This has no initializer because initialized variables in Emacs
1100 become read-only after dumping. */
1101 reg_syntax_t re_syntax_options;
1104 /* Specify the precise syntax of regexps for compilation. This provides
1105 for compatibility for various utilities which historically have
1106 different, incompatible syntaxes.
1108 The argument SYNTAX is a bit mask comprised of the various bits
1109 defined in regex.h. We return the old syntax. */
1112 re_set_syntax (syntax)
1113 reg_syntax_t syntax;
1115 reg_syntax_t ret = re_syntax_options;
1117 re_syntax_options = syntax;
1119 if (syntax & RE_DEBUG)
1121 else if (debug) /* was on but now is not */
1127 weak_alias (__re_set_syntax, re_set_syntax)
1130 /* This table gives an error message for each of the error codes listed
1131 in regex.h. Obviously the order here has to be same as there.
1132 POSIX doesn't require that we do anything for REG_NOERROR,
1133 but why not be nice? */
1135 static const char re_error_msgid[] =
1137 #define REG_NOERROR_IDX 0
1138 gettext_noop ("Success") /* REG_NOERROR */
1140 #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1141 gettext_noop ("No match") /* REG_NOMATCH */
1143 #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1144 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1146 #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1147 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1149 #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1150 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1152 #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1153 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1155 #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1156 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1158 #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1159 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1161 #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1162 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1164 #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1165 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1167 #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1168 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1170 #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1171 gettext_noop ("Invalid range end") /* REG_ERANGE */
1173 #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1174 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1176 #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1177 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1179 #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1180 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1182 #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1183 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1185 #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1186 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1189 static const size_t re_error_msgid_idx[] =
1210 /* Avoiding alloca during matching, to placate r_alloc. */
1212 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1213 searching and matching functions should not call alloca. On some
1214 systems, alloca is implemented in terms of malloc, and if we're
1215 using the relocating allocator routines, then malloc could cause a
1216 relocation, which might (if the strings being searched are in the
1217 ralloc heap) shift the data out from underneath the regexp
1220 Here's another reason to avoid allocation: Emacs
1221 processes input from X in a signal handler; processing X input may
1222 call malloc; if input arrives while a matching routine is calling
1223 malloc, then we're scrod. But Emacs can't just block input while
1224 calling matching routines; then we don't notice interrupts when
1225 they come in. So, Emacs blocks input around all regexp calls
1226 except the matching calls, which it leaves unprotected, in the
1227 faith that they will not malloc. */
1229 /* Normally, this is fine. */
1230 #define MATCH_MAY_ALLOCATE
1232 /* When using GNU C, we are not REALLY using the C alloca, no matter
1233 what config.h may say. So don't take precautions for it. */
1238 /* The match routines may not allocate if (1) they would do it with malloc
1239 and (2) it's not safe for them to use malloc.
1240 Note that if REL_ALLOC is defined, matching would not use malloc for the
1241 failure stack, but we would still use it for the register vectors;
1242 so REL_ALLOC should not affect this. */
1243 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1244 # undef MATCH_MAY_ALLOCATE
1248 /* Failure stack declarations and macros; both re_compile_fastmap and
1249 re_match_2 use a failure stack. These have to be macros because of
1250 REGEX_ALLOCATE_STACK. */
1253 /* Number of failure points for which to initially allocate space
1254 when matching. If this number is exceeded, we allocate more
1255 space, so it is not a hard limit. */
1256 #ifndef INIT_FAILURE_ALLOC
1257 # define INIT_FAILURE_ALLOC 5
1260 /* Roughly the maximum number of failure points on the stack. Would be
1261 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1262 This is a variable only so users of regex can assign to it; we never
1263 change it ourselves. */
1267 # if defined MATCH_MAY_ALLOCATE
1268 /* 4400 was enough to cause a crash on Alpha OSF/1,
1269 whose default stack limit is 2mb. */
1270 long int re_max_failures = 4000;
1272 long int re_max_failures = 2000;
1275 union fail_stack_elt
1277 unsigned char *pointer;
1281 typedef union fail_stack_elt fail_stack_elt_t;
1285 fail_stack_elt_t *stack;
1286 unsigned long int size;
1287 unsigned long int avail; /* Offset of next open position. */
1290 #else /* not INT_IS_16BIT */
1292 # if defined MATCH_MAY_ALLOCATE
1293 /* 4400 was enough to cause a crash on Alpha OSF/1,
1294 whose default stack limit is 2mb. */
1295 int re_max_failures = 4000;
1297 int re_max_failures = 2000;
1300 union fail_stack_elt
1302 unsigned char *pointer;
1306 typedef union fail_stack_elt fail_stack_elt_t;
1310 fail_stack_elt_t *stack;
1312 unsigned avail; /* Offset of next open position. */
1315 #endif /* INT_IS_16BIT */
1317 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1318 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1319 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1322 /* Define macros to initialize and free the failure stack.
1323 Do `return -2' if the alloc fails. */
1325 #ifdef MATCH_MAY_ALLOCATE
1326 # define INIT_FAIL_STACK() \
1328 fail_stack.stack = (fail_stack_elt_t *) \
1329 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1331 if (fail_stack.stack == NULL) \
1334 fail_stack.size = INIT_FAILURE_ALLOC; \
1335 fail_stack.avail = 0; \
1338 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1340 # define INIT_FAIL_STACK() \
1342 fail_stack.avail = 0; \
1345 # define RESET_FAIL_STACK()
1349 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1351 Return 1 if succeeds, and 0 if either ran out of memory
1352 allocating space for it or it was already too large.
1354 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1356 #define DOUBLE_FAIL_STACK(fail_stack) \
1357 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1359 : ((fail_stack).stack = (fail_stack_elt_t *) \
1360 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1361 (fail_stack).size * sizeof (fail_stack_elt_t), \
1362 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1364 (fail_stack).stack == NULL \
1366 : ((fail_stack).size <<= 1, \
1370 /* Push pointer POINTER on FAIL_STACK.
1371 Return 1 if was able to do so and 0 if ran out of memory allocating
1373 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1374 ((FAIL_STACK_FULL () \
1375 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1377 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1380 /* Push a pointer value onto the failure stack.
1381 Assumes the variable `fail_stack'. Probably should only
1382 be called from within `PUSH_FAILURE_POINT'. */
1383 #define PUSH_FAILURE_POINTER(item) \
1384 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1386 /* This pushes an integer-valued item onto the failure stack.
1387 Assumes the variable `fail_stack'. Probably should only
1388 be called from within `PUSH_FAILURE_POINT'. */
1389 #define PUSH_FAILURE_INT(item) \
1390 fail_stack.stack[fail_stack.avail++].integer = (item)
1392 /* Push a fail_stack_elt_t value onto the failure stack.
1393 Assumes the variable `fail_stack'. Probably should only
1394 be called from within `PUSH_FAILURE_POINT'. */
1395 #define PUSH_FAILURE_ELT(item) \
1396 fail_stack.stack[fail_stack.avail++] = (item)
1398 /* These three POP... operations complement the three PUSH... operations.
1399 All assume that `fail_stack' is nonempty. */
1400 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1401 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1402 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1404 /* Used to omit pushing failure point id's when we're not debugging. */
1406 # define DEBUG_PUSH PUSH_FAILURE_INT
1407 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1409 # define DEBUG_PUSH(item)
1410 # define DEBUG_POP(item_addr)
1414 /* Push the information about the state we will need
1415 if we ever fail back to it.
1417 Requires variables fail_stack, regstart, regend, reg_info, and
1418 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1421 Does `return FAILURE_CODE' if runs out of memory. */
1423 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1425 char *destination; \
1426 /* Must be int, so when we don't save any registers, the arithmetic \
1427 of 0 + -1 isn't done as unsigned. */ \
1428 /* Can't be int, since there is not a shred of a guarantee that int \
1429 is wide enough to hold a value of something to which pointer can \
1431 active_reg_t this_reg; \
1433 DEBUG_STATEMENT (failure_id++); \
1434 DEBUG_STATEMENT (nfailure_points_pushed++); \
1435 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1436 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1437 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1439 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1440 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1442 /* Ensure we have enough space allocated for what we will push. */ \
1443 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1445 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1446 return failure_code; \
1448 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1449 (fail_stack).size); \
1450 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1453 /* Push the info, starting with the registers. */ \
1454 DEBUG_PRINT1 ("\n"); \
1457 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1460 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1461 DEBUG_STATEMENT (num_regs_pushed++); \
1463 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1464 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1466 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1467 PUSH_FAILURE_POINTER (regend[this_reg]); \
1469 DEBUG_PRINT2 (" info: %p\n ", \
1470 reg_info[this_reg].word.pointer); \
1471 DEBUG_PRINT2 (" match_null=%d", \
1472 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1473 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1474 DEBUG_PRINT2 (" matched_something=%d", \
1475 MATCHED_SOMETHING (reg_info[this_reg])); \
1476 DEBUG_PRINT2 (" ever_matched=%d", \
1477 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1478 DEBUG_PRINT1 ("\n"); \
1479 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1482 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1483 PUSH_FAILURE_INT (lowest_active_reg); \
1485 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1486 PUSH_FAILURE_INT (highest_active_reg); \
1488 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1489 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1490 PUSH_FAILURE_POINTER (pattern_place); \
1492 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1493 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1495 DEBUG_PRINT1 ("'\n"); \
1496 PUSH_FAILURE_POINTER (string_place); \
1498 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1499 DEBUG_PUSH (failure_id); \
1502 /* This is the number of items that are pushed and popped on the stack
1503 for each register. */
1504 #define NUM_REG_ITEMS 3
1506 /* Individual items aside from the registers. */
1508 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1510 # define NUM_NONREG_ITEMS 4
1513 /* We push at most this many items on the stack. */
1514 /* We used to use (num_regs - 1), which is the number of registers
1515 this regexp will save; but that was changed to 5
1516 to avoid stack overflow for a regexp with lots of parens. */
1517 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1519 /* We actually push this many items. */
1520 #define NUM_FAILURE_ITEMS \
1522 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1526 /* How many items can still be added to the stack without overflowing it. */
1527 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1530 /* Pops what PUSH_FAIL_STACK pushes.
1532 We restore into the parameters, all of which should be lvalues:
1533 STR -- the saved data position.
1534 PAT -- the saved pattern position.
1535 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1536 REGSTART, REGEND -- arrays of string positions.
1537 REG_INFO -- array of information about each subexpression.
1539 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1540 `pend', `string1', `size1', `string2', and `size2'. */
1542 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1544 DEBUG_STATEMENT (unsigned failure_id;) \
1545 active_reg_t this_reg; \
1546 const unsigned char *string_temp; \
1548 assert (!FAIL_STACK_EMPTY ()); \
1550 /* Remove failure points and point to how many regs pushed. */ \
1551 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1552 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1553 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1555 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1557 DEBUG_POP (&failure_id); \
1558 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1560 /* If the saved string location is NULL, it came from an \
1561 on_failure_keep_string_jump opcode, and we want to throw away the \
1562 saved NULL, thus retaining our current position in the string. */ \
1563 string_temp = POP_FAILURE_POINTER (); \
1564 if (string_temp != NULL) \
1565 str = (const char *) string_temp; \
1567 DEBUG_PRINT2 (" Popping string %p: `", str); \
1568 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1569 DEBUG_PRINT1 ("'\n"); \
1571 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1572 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1573 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1575 /* Restore register info. */ \
1576 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1577 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1579 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1580 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1583 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1585 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1587 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1588 DEBUG_PRINT2 (" info: %p\n", \
1589 reg_info[this_reg].word.pointer); \
1591 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1592 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1594 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1595 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1599 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1601 reg_info[this_reg].word.integer = 0; \
1602 regend[this_reg] = 0; \
1603 regstart[this_reg] = 0; \
1605 highest_active_reg = high_reg; \
1608 set_regs_matched_done = 0; \
1609 DEBUG_STATEMENT (nfailure_points_popped++); \
1610 } /* POP_FAILURE_POINT */
1614 /* Structure for per-register (a.k.a. per-group) information.
1615 Other register information, such as the
1616 starting and ending positions (which are addresses), and the list of
1617 inner groups (which is a bits list) are maintained in separate
1620 We are making a (strictly speaking) nonportable assumption here: that
1621 the compiler will pack our bit fields into something that fits into
1622 the type of `word', i.e., is something that fits into one item on the
1626 /* Declarations and macros for re_match_2. */
1630 fail_stack_elt_t word;
1633 /* This field is one if this group can match the empty string,
1634 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1635 #define MATCH_NULL_UNSET_VALUE 3
1636 unsigned match_null_string_p : 2;
1637 unsigned is_active : 1;
1638 unsigned matched_something : 1;
1639 unsigned ever_matched_something : 1;
1641 } register_info_type;
1643 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1644 #define IS_ACTIVE(R) ((R).bits.is_active)
1645 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1646 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1649 /* Call this when have matched a real character; it sets `matched' flags
1650 for the subexpressions which we are currently inside. Also records
1651 that those subexprs have matched. */
1652 #define SET_REGS_MATCHED() \
1655 if (!set_regs_matched_done) \
1658 set_regs_matched_done = 1; \
1659 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1661 MATCHED_SOMETHING (reg_info[r]) \
1662 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1669 /* Registers are set to a sentinel when they haven't yet matched. */
1670 static char reg_unset_dummy;
1671 #define REG_UNSET_VALUE (®_unset_dummy)
1672 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1674 /* Subroutine declarations and macros for regex_compile. */
1676 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1677 reg_syntax_t syntax,
1678 struct re_pattern_buffer *bufp));
1679 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1680 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1681 int arg1, int arg2));
1682 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1683 int arg, unsigned char *end));
1684 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1685 int arg1, int arg2, unsigned char *end));
1686 static boolean at_begline_loc_p _RE_ARGS ((const char *pattern, const char *p,
1687 reg_syntax_t syntax));
1688 static boolean at_endline_loc_p _RE_ARGS ((const char *p, const char *pend,
1689 reg_syntax_t syntax));
1690 static reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
1694 reg_syntax_t syntax,
1697 /* Fetch the next character in the uncompiled pattern---translating it
1698 if necessary. Also cast from a signed character in the constant
1699 string passed to us by the user to an unsigned char that we can use
1700 as an array index (in, e.g., `translate'). */
1702 # define PATFETCH(c) \
1703 do {if (p == pend) return REG_EEND; \
1704 c = (unsigned char) *p++; \
1705 if (translate) c = (unsigned char) translate[c]; \
1709 /* Fetch the next character in the uncompiled pattern, with no
1711 #define PATFETCH_RAW(c) \
1712 do {if (p == pend) return REG_EEND; \
1713 c = (unsigned char) *p++; \
1716 /* Go backwards one character in the pattern. */
1717 #define PATUNFETCH p--
1720 /* If `translate' is non-null, return translate[D], else just D. We
1721 cast the subscript to translate because some data is declared as
1722 `char *', to avoid warnings when a string constant is passed. But
1723 when we use a character as a subscript we must make it unsigned. */
1725 # define TRANSLATE(d) \
1726 (translate ? (char) translate[(unsigned char) (d)] : (d))
1730 /* Macros for outputting the compiled pattern into `buffer'. */
1732 /* If the buffer isn't allocated when it comes in, use this. */
1733 #define INIT_BUF_SIZE 32
1735 /* Make sure we have at least N more bytes of space in buffer. */
1736 #define GET_BUFFER_SPACE(n) \
1737 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1740 /* Make sure we have one more byte of buffer space and then add C to it. */
1741 #define BUF_PUSH(c) \
1743 GET_BUFFER_SPACE (1); \
1744 *b++ = (unsigned char) (c); \
1748 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1749 #define BUF_PUSH_2(c1, c2) \
1751 GET_BUFFER_SPACE (2); \
1752 *b++ = (unsigned char) (c1); \
1753 *b++ = (unsigned char) (c2); \
1757 /* As with BUF_PUSH_2, except for three bytes. */
1758 #define BUF_PUSH_3(c1, c2, c3) \
1760 GET_BUFFER_SPACE (3); \
1761 *b++ = (unsigned char) (c1); \
1762 *b++ = (unsigned char) (c2); \
1763 *b++ = (unsigned char) (c3); \
1767 /* Store a jump with opcode OP at LOC to location TO. We store a
1768 relative address offset by the three bytes the jump itself occupies. */
1769 #define STORE_JUMP(op, loc, to) \
1770 store_op1 (op, loc, (int) ((to) - (loc) - 3))
1772 /* Likewise, for a two-argument jump. */
1773 #define STORE_JUMP2(op, loc, to, arg) \
1774 store_op2 (op, loc, (int) ((to) - (loc) - 3), arg)
1776 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1777 #define INSERT_JUMP(op, loc, to) \
1778 insert_op1 (op, loc, (int) ((to) - (loc) - 3), b)
1780 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1781 #define INSERT_JUMP2(op, loc, to, arg) \
1782 insert_op2 (op, loc, (int) ((to) - (loc) - 3), arg, b)
1785 /* This is not an arbitrary limit: the arguments which represent offsets
1786 into the pattern are two bytes long. So if 2^16 bytes turns out to
1787 be too small, many things would have to change. */
1788 /* Any other compiler which, like MSC, has allocation limit below 2^16
1789 bytes will have to use approach similar to what was done below for
1790 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1791 reallocating to 0 bytes. Such thing is not going to work too well.
1792 You have been warned!! */
1793 #if defined _MSC_VER && !defined WIN32
1794 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1795 The REALLOC define eliminates a flurry of conversion warnings,
1796 but is not required. */
1797 # define MAX_BUF_SIZE 65500L
1798 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1800 # define MAX_BUF_SIZE (1L << 16)
1801 # define REALLOC(p,s) realloc ((p), (s))
1804 /* Extend the buffer by twice its current size via realloc and
1805 reset the pointers that pointed into the old block to point to the
1806 correct places in the new one. If extending the buffer results in it
1807 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1808 #if __BOUNDED_POINTERS__
1809 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1810 # define MOVE_BUFFER_POINTER(P) \
1811 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1812 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1815 SET_HIGH_BOUND (b); \
1816 SET_HIGH_BOUND (begalt); \
1817 if (fixup_alt_jump) \
1818 SET_HIGH_BOUND (fixup_alt_jump); \
1820 SET_HIGH_BOUND (laststart); \
1821 if (pending_exact) \
1822 SET_HIGH_BOUND (pending_exact); \
1825 # define MOVE_BUFFER_POINTER(P) (P) += incr
1826 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1828 #define EXTEND_BUFFER() \
1830 unsigned char *old_buffer = bufp->buffer; \
1831 if (bufp->allocated == MAX_BUF_SIZE) \
1833 bufp->allocated <<= 1; \
1834 if (bufp->allocated > MAX_BUF_SIZE) \
1835 bufp->allocated = MAX_BUF_SIZE; \
1836 bufp->buffer = (unsigned char *) REALLOC (bufp->buffer, bufp->allocated);\
1837 if (bufp->buffer == NULL) \
1838 return REG_ESPACE; \
1839 /* If the buffer moved, move all the pointers into it. */ \
1840 if (old_buffer != bufp->buffer) \
1842 int incr = bufp->buffer - old_buffer; \
1843 MOVE_BUFFER_POINTER (b); \
1844 MOVE_BUFFER_POINTER (begalt); \
1845 if (fixup_alt_jump) \
1846 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1848 MOVE_BUFFER_POINTER (laststart); \
1849 if (pending_exact) \
1850 MOVE_BUFFER_POINTER (pending_exact); \
1852 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1856 /* Since we have one byte reserved for the register number argument to
1857 {start,stop}_memory, the maximum number of groups we can report
1858 things about is what fits in that byte. */
1859 #define MAX_REGNUM 255
1861 /* But patterns can have more than `MAX_REGNUM' registers. We just
1862 ignore the excess. */
1863 typedef unsigned regnum_t;
1866 /* Macros for the compile stack. */
1868 /* Since offsets can go either forwards or backwards, this type needs to
1869 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1870 /* int may be not enough when sizeof(int) == 2. */
1871 typedef long pattern_offset_t;
1875 pattern_offset_t begalt_offset;
1876 pattern_offset_t fixup_alt_jump;
1877 pattern_offset_t inner_group_offset;
1878 pattern_offset_t laststart_offset;
1880 } compile_stack_elt_t;
1885 compile_stack_elt_t *stack;
1887 unsigned avail; /* Offset of next open position. */
1888 } compile_stack_type;
1891 #define INIT_COMPILE_STACK_SIZE 32
1893 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1894 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1896 /* The next available element. */
1897 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1900 /* Set the bit for character C in a list. */
1901 #define SET_LIST_BIT(c) \
1902 (b[((unsigned char) (c)) / BYTEWIDTH] \
1903 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1906 /* Get the next unsigned number in the uncompiled pattern. */
1907 #define GET_UNSIGNED_NUMBER(num) \
1911 while ('0' <= c && c <= '9') \
1915 num = num * 10 + c - '0'; \
1923 #if defined _LIBC || WIDE_CHAR_SUPPORT
1924 /* The GNU C library provides support for user-defined character classes
1925 and the functions from ISO C amendement 1. */
1926 # ifdef CHARCLASS_NAME_MAX
1927 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1929 /* This shouldn't happen but some implementation might still have this
1930 problem. Use a reasonable default value. */
1931 # define CHAR_CLASS_MAX_LENGTH 256
1935 # define IS_CHAR_CLASS(string) __wctype (string)
1937 # define IS_CHAR_CLASS(string) wctype (string)
1940 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1942 # define IS_CHAR_CLASS(string) \
1943 (STREQ (string, "alpha") || STREQ (string, "upper") \
1944 || STREQ (string, "lower") || STREQ (string, "digit") \
1945 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1946 || STREQ (string, "space") || STREQ (string, "print") \
1947 || STREQ (string, "punct") || STREQ (string, "graph") \
1948 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1951 #ifndef MATCH_MAY_ALLOCATE
1953 /* If we cannot allocate large objects within re_match_2_internal,
1954 we make the fail stack and register vectors global.
1955 The fail stack, we grow to the maximum size when a regexp
1957 The register vectors, we adjust in size each time we
1958 compile a regexp, according to the number of registers it needs. */
1960 static fail_stack_type fail_stack;
1962 /* Size with which the following vectors are currently allocated.
1963 That is so we can make them bigger as needed,
1964 but never make them smaller. */
1965 static int regs_allocated_size;
1967 static const char ** regstart, ** regend;
1968 static const char ** old_regstart, ** old_regend;
1969 static const char **best_regstart, **best_regend;
1970 static register_info_type *reg_info;
1971 static const char **reg_dummy;
1972 static register_info_type *reg_info_dummy;
1974 /* Make the register vectors big enough for NUM_REGS registers,
1975 but don't make them smaller. */
1978 regex_grow_registers (num_regs)
1981 if (num_regs > regs_allocated_size)
1983 RETALLOC_IF (regstart, num_regs, const char *);
1984 RETALLOC_IF (regend, num_regs, const char *);
1985 RETALLOC_IF (old_regstart, num_regs, const char *);
1986 RETALLOC_IF (old_regend, num_regs, const char *);
1987 RETALLOC_IF (best_regstart, num_regs, const char *);
1988 RETALLOC_IF (best_regend, num_regs, const char *);
1989 RETALLOC_IF (reg_info, num_regs, register_info_type);
1990 RETALLOC_IF (reg_dummy, num_regs, const char *);
1991 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1993 regs_allocated_size = num_regs;
1997 #endif /* not MATCH_MAY_ALLOCATE */
1999 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2003 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2004 Returns one of error codes defined in `regex.h', or zero for success.
2006 Assumes the `allocated' (and perhaps `buffer') and `translate'
2007 fields are set in BUFP on entry.
2009 If it succeeds, results are put in BUFP (if it returns an error, the
2010 contents of BUFP are undefined):
2011 `buffer' is the compiled pattern;
2012 `syntax' is set to SYNTAX;
2013 `used' is set to the length of the compiled pattern;
2014 `fastmap_accurate' is zero;
2015 `re_nsub' is the number of subexpressions in PATTERN;
2016 `not_bol' and `not_eol' are zero;
2018 The `fastmap' and `newline_anchor' fields are neither
2019 examined nor set. */
2021 /* Return, freeing storage we allocated. */
2022 #define FREE_STACK_RETURN(value) \
2023 return (free (compile_stack.stack), value)
2025 static reg_errcode_t
2026 regex_compile (pattern, size, syntax, bufp)
2027 const char *pattern;
2029 reg_syntax_t syntax;
2030 struct re_pattern_buffer *bufp;
2032 /* We fetch characters from PATTERN here. Even though PATTERN is
2033 `char *' (i.e., signed), we declare these variables as unsigned, so
2034 they can be reliably used as array indices. */
2035 register unsigned char c, c1;
2037 /* A random temporary spot in PATTERN. */
2040 /* Points to the end of the buffer, where we should append. */
2041 register unsigned char *b;
2043 /* Keeps track of unclosed groups. */
2044 compile_stack_type compile_stack;
2046 /* Points to the current (ending) position in the pattern. */
2047 const char *p = pattern;
2048 const char *pend = pattern + size;
2050 /* How to translate the characters in the pattern. */
2051 RE_TRANSLATE_TYPE translate = bufp->translate;
2053 /* Address of the count-byte of the most recently inserted `exactn'
2054 command. This makes it possible to tell if a new exact-match
2055 character can be added to that command or if the character requires
2056 a new `exactn' command. */
2057 unsigned char *pending_exact = 0;
2059 /* Address of start of the most recently finished expression.
2060 This tells, e.g., postfix * where to find the start of its
2061 operand. Reset at the beginning of groups and alternatives. */
2062 unsigned char *laststart = 0;
2064 /* Address of beginning of regexp, or inside of last group. */
2065 unsigned char *begalt;
2067 /* Place in the uncompiled pattern (i.e., the {) to
2068 which to go back if the interval is invalid. */
2069 const char *beg_interval;
2071 /* Address of the place where a forward jump should go to the end of
2072 the containing expression. Each alternative of an `or' -- except the
2073 last -- ends with a forward jump of this sort. */
2074 unsigned char *fixup_alt_jump = 0;
2076 /* Counts open-groups as they are encountered. Remembered for the
2077 matching close-group on the compile stack, so the same register
2078 number is put in the stop_memory as the start_memory. */
2079 regnum_t regnum = 0;
2082 DEBUG_PRINT1 ("\nCompiling pattern: ");
2085 unsigned debug_count;
2087 for (debug_count = 0; debug_count < size; debug_count++)
2088 putchar (pattern[debug_count]);
2093 /* Initialize the compile stack. */
2094 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2095 if (compile_stack.stack == NULL)
2098 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2099 compile_stack.avail = 0;
2101 /* Initialize the pattern buffer. */
2102 bufp->syntax = syntax;
2103 bufp->fastmap_accurate = 0;
2104 bufp->not_bol = bufp->not_eol = 0;
2106 /* Set `used' to zero, so that if we return an error, the pattern
2107 printer (for debugging) will think there's no pattern. We reset it
2111 /* Always count groups, whether or not bufp->no_sub is set. */
2114 #if !defined emacs && !defined SYNTAX_TABLE
2115 /* Initialize the syntax table. */
2116 init_syntax_once ();
2119 if (bufp->allocated == 0)
2122 { /* If zero allocated, but buffer is non-null, try to realloc
2123 enough space. This loses if buffer's address is bogus, but
2124 that is the user's responsibility. */
2125 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2128 { /* Caller did not allocate a buffer. Do it for them. */
2129 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2131 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2133 bufp->allocated = INIT_BUF_SIZE;
2136 begalt = b = bufp->buffer;
2138 /* Loop through the uncompiled pattern until we're at the end. */
2147 if ( /* If at start of pattern, it's an operator. */
2149 /* If context independent, it's an operator. */
2150 || syntax & RE_CONTEXT_INDEP_ANCHORS
2151 /* Otherwise, depends on what's come before. */
2152 || at_begline_loc_p (pattern, p, syntax))
2162 if ( /* If at end of pattern, it's an operator. */
2164 /* If context independent, it's an operator. */
2165 || syntax & RE_CONTEXT_INDEP_ANCHORS
2166 /* Otherwise, depends on what's next. */
2167 || at_endline_loc_p (p, pend, syntax))
2177 if ((syntax & RE_BK_PLUS_QM)
2178 || (syntax & RE_LIMITED_OPS))
2182 /* If there is no previous pattern... */
2185 if (syntax & RE_CONTEXT_INVALID_OPS)
2186 FREE_STACK_RETURN (REG_BADRPT);
2187 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2192 /* Are we optimizing this jump? */
2193 boolean keep_string_p = false;
2195 /* 1 means zero (many) matches is allowed. */
2196 char zero_times_ok = 0, many_times_ok = 0;
2198 /* If there is a sequence of repetition chars, collapse it
2199 down to just one (the right one). We can't combine
2200 interval operators with these because of, e.g., `a{2}*',
2201 which should only match an even number of `a's. */
2205 zero_times_ok |= c != '+';
2206 many_times_ok |= c != '?';
2214 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2217 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2219 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2222 if (!(c1 == '+' || c1 == '?'))
2237 /* If we get here, we found another repeat character. */
2240 /* Star, etc. applied to an empty pattern is equivalent
2241 to an empty pattern. */
2245 /* Now we know whether or not zero matches is allowed
2246 and also whether or not two or more matches is allowed. */
2248 { /* More than one repetition is allowed, so put in at the
2249 end a backward relative jump from `b' to before the next
2250 jump we're going to put in below (which jumps from
2251 laststart to after this jump).
2253 But if we are at the `*' in the exact sequence `.*\n',
2254 insert an unconditional jump backwards to the .,
2255 instead of the beginning of the loop. This way we only
2256 push a failure point once, instead of every time
2257 through the loop. */
2258 assert (p - 1 > pattern);
2260 /* Allocate the space for the jump. */
2261 GET_BUFFER_SPACE (3);
2263 /* We know we are not at the first character of the pattern,
2264 because laststart was nonzero. And we've already
2265 incremented `p', by the way, to be the character after
2266 the `*'. Do we have to do something analogous here
2267 for null bytes, because of RE_DOT_NOT_NULL? */
2268 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2270 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2271 && !(syntax & RE_DOT_NEWLINE))
2272 { /* We have .*\n. */
2273 STORE_JUMP (jump, b, laststart);
2274 keep_string_p = true;
2277 /* Anything else. */
2278 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2280 /* We've added more stuff to the buffer. */
2284 /* On failure, jump from laststart to b + 3, which will be the
2285 end of the buffer after this jump is inserted. */
2286 GET_BUFFER_SPACE (3);
2287 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2295 /* At least one repetition is required, so insert a
2296 `dummy_failure_jump' before the initial
2297 `on_failure_jump' instruction of the loop. This
2298 effects a skip over that instruction the first time
2299 we hit that loop. */
2300 GET_BUFFER_SPACE (3);
2301 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2316 boolean had_char_class = false;
2317 unsigned int range_start = 0xffffffff;
2319 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2321 /* Ensure that we have enough space to push a charset: the
2322 opcode, the length count, and the bitset; 34 bytes in all. */
2323 GET_BUFFER_SPACE (34);
2327 /* We test `*p == '^' twice, instead of using an if
2328 statement, so we only need one BUF_PUSH. */
2329 BUF_PUSH (*p == '^' ? charset_not : charset);
2333 /* Remember the first position in the bracket expression. */
2336 /* Push the number of bytes in the bitmap. */
2337 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2339 /* Clear the whole map. */
2340 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2342 /* charset_not matches newline according to a syntax bit. */
2343 if ((re_opcode_t) b[-2] == charset_not
2344 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2345 SET_LIST_BIT ('\n');
2347 /* Read in characters and ranges, setting map bits. */
2350 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2354 /* \ might escape characters inside [...] and [^...]. */
2355 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2357 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2365 /* Could be the end of the bracket expression. If it's
2366 not (i.e., when the bracket expression is `[]' so
2367 far), the ']' character bit gets set way below. */
2368 if (c == ']' && p != p1 + 1)
2371 /* Look ahead to see if it's a range when the last thing
2372 was a character class. */
2373 if (had_char_class && c == '-' && *p != ']')
2374 FREE_STACK_RETURN (REG_ERANGE);
2376 /* Look ahead to see if it's a range when the last thing
2377 was a character: if this is a hyphen not at the
2378 beginning or the end of a list, then it's the range
2381 && !(p - 2 >= pattern && p[-2] == '[')
2382 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2386 = compile_range (range_start, &p, pend, translate,
2388 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2389 range_start = 0xffffffff;
2392 else if (p[0] == '-' && p[1] != ']')
2393 { /* This handles ranges made up of characters only. */
2396 /* Move past the `-'. */
2399 ret = compile_range (c, &p, pend, translate, syntax, b);
2400 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2401 range_start = 0xffffffff;
2404 /* See if we're at the beginning of a possible character
2407 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2408 { /* Leave room for the null. */
2409 char str[CHAR_CLASS_MAX_LENGTH + 1];
2414 /* If pattern is `[[:'. */
2415 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2420 if ((c == ':' && *p == ']') || p == pend)
2422 if (c1 < CHAR_CLASS_MAX_LENGTH)
2425 /* This is in any case an invalid class name. */
2430 /* If isn't a word bracketed by `[:' and `:]':
2431 undo the ending character, the letters, and leave
2432 the leading `:' and `[' (but set bits for them). */
2433 if (c == ':' && *p == ']')
2435 #if defined _LIBC || WIDE_CHAR_SUPPORT
2436 boolean is_lower = STREQ (str, "lower");
2437 boolean is_upper = STREQ (str, "upper");
2441 wt = IS_CHAR_CLASS (str);
2443 FREE_STACK_RETURN (REG_ECTYPE);
2445 /* Throw away the ] at the end of the character
2449 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2451 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
2454 if (__iswctype (__btowc (ch), wt))
2457 if (iswctype (btowc (ch), wt))
2461 if (translate && (is_upper || is_lower)
2462 && (ISUPPER (ch) || ISLOWER (ch)))
2466 had_char_class = true;
2469 boolean is_alnum = STREQ (str, "alnum");
2470 boolean is_alpha = STREQ (str, "alpha");
2471 boolean is_blank = STREQ (str, "blank");
2472 boolean is_cntrl = STREQ (str, "cntrl");
2473 boolean is_digit = STREQ (str, "digit");
2474 boolean is_graph = STREQ (str, "graph");
2475 boolean is_lower = STREQ (str, "lower");
2476 boolean is_print = STREQ (str, "print");
2477 boolean is_punct = STREQ (str, "punct");
2478 boolean is_space = STREQ (str, "space");
2479 boolean is_upper = STREQ (str, "upper");
2480 boolean is_xdigit = STREQ (str, "xdigit");
2482 if (!IS_CHAR_CLASS (str))
2483 FREE_STACK_RETURN (REG_ECTYPE);
2485 /* Throw away the ] at the end of the character
2489 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2491 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2493 /* This was split into 3 if's to
2494 avoid an arbitrary limit in some compiler. */
2495 if ( (is_alnum && ISALNUM (ch))
2496 || (is_alpha && ISALPHA (ch))
2497 || (is_blank && ISBLANK (ch))
2498 || (is_cntrl && ISCNTRL (ch)))
2500 if ( (is_digit && ISDIGIT (ch))
2501 || (is_graph && ISGRAPH (ch))
2502 || (is_lower && ISLOWER (ch))
2503 || (is_print && ISPRINT (ch)))
2505 if ( (is_punct && ISPUNCT (ch))
2506 || (is_space && ISSPACE (ch))
2507 || (is_upper && ISUPPER (ch))
2508 || (is_xdigit && ISXDIGIT (ch)))
2510 if ( translate && (is_upper || is_lower)
2511 && (ISUPPER (ch) || ISLOWER (ch)))
2514 had_char_class = true;
2515 #endif /* libc || wctype.h */
2525 had_char_class = false;
2528 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
2530 unsigned char str[MB_LEN_MAX + 1];
2533 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2539 /* If pattern is `[[='. */
2540 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2545 if ((c == '=' && *p == ']') || p == pend)
2547 if (c1 < MB_LEN_MAX)
2550 /* This is in any case an invalid class name. */
2555 if (c == '=' && *p == ']' && str[0] != '\0')
2557 /* If we have no collation data we use the default
2558 collation in which each character is in a class
2559 by itself. It also means that ASCII is the
2560 character set and therefore we cannot have character
2561 with more than one byte in the multibyte
2568 FREE_STACK_RETURN (REG_ECOLLATE);
2570 /* Throw away the ] at the end of the equivalence
2574 /* Set the bit for the character. */
2575 SET_LIST_BIT (str[0]);
2580 /* Try to match the byte sequence in `str' against
2581 those known to the collate implementation.
2582 First find out whether the bytes in `str' are
2583 actually from exactly one character. */
2584 const int32_t *table;
2585 const unsigned char *weights;
2586 const unsigned char *extra;
2587 const int32_t *indirect;
2589 const unsigned char *cp = str;
2592 /* This #include defines a local function! */
2593 # include <locale/weight.h>
2595 table = (const int32_t *)
2596 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
2597 weights = (const unsigned char *)
2598 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
2599 extra = (const unsigned char *)
2600 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
2601 indirect = (const int32_t *)
2602 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
2604 idx = findidx (&cp);
2605 if (idx == 0 || cp < str + c1)
2606 /* This is no valid character. */
2607 FREE_STACK_RETURN (REG_ECOLLATE);
2609 /* Throw away the ] at the end of the equivalence
2613 /* Now we have to go throught the whole table
2614 and find all characters which have the same
2617 XXX Note that this is not entirely correct.
2618 we would have to match multibyte sequences
2619 but this is not possible with the current
2621 for (ch = 1; ch < 256; ++ch)
2622 /* XXX This test would have to be changed if we
2623 would allow matching multibyte sequences. */
2626 int32_t idx2 = table[ch];
2627 size_t len = weights[idx2];
2629 /* Test whether the lenghts match. */
2630 if (weights[idx] == len)
2632 /* They do. New compare the bytes of
2637 && (weights[idx + 1 + cnt]
2638 == weights[idx2 + 1 + cnt]))
2642 /* They match. Mark the character as
2649 had_char_class = true;
2659 had_char_class = false;
2662 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
2664 unsigned char str[128]; /* Should be large enough. */
2667 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2673 /* If pattern is `[[='. */
2674 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2679 if ((c == '.' && *p == ']') || p == pend)
2681 if (c1 < sizeof (str))
2684 /* This is in any case an invalid class name. */
2689 if (c == '.' && *p == ']' && str[0] != '\0')
2691 /* If we have no collation data we use the default
2692 collation in which each character is the name
2693 for its own class which contains only the one
2694 character. It also means that ASCII is the
2695 character set and therefore we cannot have character
2696 with more than one byte in the multibyte
2703 FREE_STACK_RETURN (REG_ECOLLATE);
2705 /* Throw away the ] at the end of the equivalence
2709 /* Set the bit for the character. */
2710 SET_LIST_BIT (str[0]);
2711 range_start = ((const unsigned char *) str)[0];
2716 /* Try to match the byte sequence in `str' against
2717 those known to the collate implementation.
2718 First find out whether the bytes in `str' are
2719 actually from exactly one character. */
2721 const int32_t *symb_table;
2722 const unsigned char *extra;
2729 _NL_CURRENT_WORD (LC_COLLATE,
2730 _NL_COLLATE_SYMB_HASH_SIZEMB);
2731 symb_table = (const int32_t *)
2732 _NL_CURRENT (LC_COLLATE,
2733 _NL_COLLATE_SYMB_TABLEMB);
2734 extra = (const unsigned char *)
2735 _NL_CURRENT (LC_COLLATE,
2736 _NL_COLLATE_SYMB_EXTRAMB);
2738 /* Locate the character in the hashing table. */
2739 hash = elem_hash (str, c1);
2742 elem = hash % table_size;
2743 second = hash % (table_size - 2);
2744 while (symb_table[2 * elem] != 0)
2746 /* First compare the hashing value. */
2747 if (symb_table[2 * elem] == hash
2748 && c1 == extra[symb_table[2 * elem + 1]]
2750 &extra[symb_table[2 * elem + 1]
2754 /* Yep, this is the entry. */
2755 idx = symb_table[2 * elem + 1];
2756 idx += 1 + extra[idx];
2764 if (symb_table[2 * elem] == 0)
2765 /* This is no valid character. */
2766 FREE_STACK_RETURN (REG_ECOLLATE);
2768 /* Throw away the ] at the end of the equivalence
2772 /* Now add the multibyte character(s) we found
2775 XXX Note that this is not entirely correct.
2776 we would have to match multibyte sequences
2777 but this is not possible with the current
2778 implementation. Also, we have to match
2779 collating symbols, which expand to more than
2780 one file, as a whole and not allow the
2781 individual bytes. */
2784 range_start = extra[idx];
2787 SET_LIST_BIT (extra[idx]);
2792 had_char_class = false;
2802 had_char_class = false;
2807 had_char_class = false;
2813 /* Discard any (non)matching list bytes that are all 0 at the
2814 end of the map. Decrease the map-length byte too. */
2815 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2823 if (syntax & RE_NO_BK_PARENS)
2830 if (syntax & RE_NO_BK_PARENS)
2837 if (syntax & RE_NEWLINE_ALT)
2844 if (syntax & RE_NO_BK_VBAR)
2851 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2852 goto handle_interval;
2858 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2860 /* Do not translate the character after the \, so that we can
2861 distinguish, e.g., \B from \b, even if we normally would
2862 translate, e.g., B to b. */
2868 if (syntax & RE_NO_BK_PARENS)
2869 goto normal_backslash;
2875 if (COMPILE_STACK_FULL)
2877 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2878 compile_stack_elt_t);
2879 if (compile_stack.stack == NULL) return REG_ESPACE;
2881 compile_stack.size <<= 1;
2884 /* These are the values to restore when we hit end of this
2885 group. They are all relative offsets, so that if the
2886 whole pattern moves because of realloc, they will still
2888 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2889 COMPILE_STACK_TOP.fixup_alt_jump
2890 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2891 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2892 COMPILE_STACK_TOP.regnum = regnum;
2894 /* We will eventually replace the 0 with the number of
2895 groups inner to this one. But do not push a
2896 start_memory for groups beyond the last one we can
2897 represent in the compiled pattern. */
2898 if (regnum <= MAX_REGNUM)
2900 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2901 BUF_PUSH_3 (start_memory, regnum, 0);
2904 compile_stack.avail++;
2909 /* If we've reached MAX_REGNUM groups, then this open
2910 won't actually generate any code, so we'll have to
2911 clear pending_exact explicitly. */
2917 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2919 if (COMPILE_STACK_EMPTY)
2921 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2922 goto normal_backslash;
2924 FREE_STACK_RETURN (REG_ERPAREN);
2929 { /* Push a dummy failure point at the end of the
2930 alternative for a possible future
2931 `pop_failure_jump' to pop. See comments at
2932 `push_dummy_failure' in `re_match_2'. */
2933 BUF_PUSH (push_dummy_failure);
2935 /* We allocated space for this jump when we assigned
2936 to `fixup_alt_jump', in the `handle_alt' case below. */
2937 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2940 /* See similar code for backslashed left paren above. */
2941 if (COMPILE_STACK_EMPTY)
2943 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2946 FREE_STACK_RETURN (REG_ERPAREN);
2949 /* Since we just checked for an empty stack above, this
2950 ``can't happen''. */
2951 assert (compile_stack.avail != 0);
2953 /* We don't just want to restore into `regnum', because
2954 later groups should continue to be numbered higher,
2955 as in `(ab)c(de)' -- the second group is #2. */
2956 regnum_t this_group_regnum;
2958 compile_stack.avail--;
2959 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2961 = COMPILE_STACK_TOP.fixup_alt_jump
2962 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2964 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2965 this_group_regnum = COMPILE_STACK_TOP.regnum;
2966 /* If we've reached MAX_REGNUM groups, then this open
2967 won't actually generate any code, so we'll have to
2968 clear pending_exact explicitly. */
2971 /* We're at the end of the group, so now we know how many
2972 groups were inside this one. */
2973 if (this_group_regnum <= MAX_REGNUM)
2975 unsigned char *inner_group_loc
2976 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2978 *inner_group_loc = regnum - this_group_regnum;
2979 BUF_PUSH_3 (stop_memory, this_group_regnum,
2980 regnum - this_group_regnum);
2986 case '|': /* `\|'. */
2987 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2988 goto normal_backslash;
2990 if (syntax & RE_LIMITED_OPS)
2993 /* Insert before the previous alternative a jump which
2994 jumps to this alternative if the former fails. */
2995 GET_BUFFER_SPACE (3);
2996 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3000 /* The alternative before this one has a jump after it
3001 which gets executed if it gets matched. Adjust that
3002 jump so it will jump to this alternative's analogous
3003 jump (put in below, which in turn will jump to the next
3004 (if any) alternative's such jump, etc.). The last such
3005 jump jumps to the correct final destination. A picture:
3011 If we are at `b', then fixup_alt_jump right now points to a
3012 three-byte space after `a'. We'll put in the jump, set
3013 fixup_alt_jump to right after `b', and leave behind three
3014 bytes which we'll fill in when we get to after `c'. */
3017 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3019 /* Mark and leave space for a jump after this alternative,
3020 to be filled in later either by next alternative or
3021 when know we're at the end of a series of alternatives. */
3023 GET_BUFFER_SPACE (3);
3032 /* If \{ is a literal. */
3033 if (!(syntax & RE_INTERVALS)
3034 /* If we're at `\{' and it's not the open-interval
3036 || (syntax & RE_NO_BK_BRACES))
3037 goto normal_backslash;
3041 /* If got here, then the syntax allows intervals. */
3043 /* At least (most) this many matches must be made. */
3044 int lower_bound = -1, upper_bound = -1;
3046 beg_interval = p - 1;
3050 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3051 goto unfetch_interval;
3053 FREE_STACK_RETURN (REG_EBRACE);
3056 GET_UNSIGNED_NUMBER (lower_bound);
3060 GET_UNSIGNED_NUMBER (upper_bound);
3061 if ((!(syntax & RE_NO_BK_BRACES) && c != '\\')
3062 || ((syntax & RE_NO_BK_BRACES) && c != '}'))
3063 FREE_STACK_RETURN (REG_BADBR);
3065 if (upper_bound < 0)
3066 upper_bound = RE_DUP_MAX;
3069 /* Interval such as `{1}' => match exactly once. */
3070 upper_bound = lower_bound;
3072 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3073 || lower_bound > upper_bound)
3075 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3076 goto unfetch_interval;
3078 FREE_STACK_RETURN (REG_BADBR);
3081 if (!(syntax & RE_NO_BK_BRACES))
3083 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
3090 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3091 goto unfetch_interval;
3093 FREE_STACK_RETURN (REG_BADBR);
3096 /* We just parsed a valid interval. */
3098 /* If it's invalid to have no preceding re. */
3101 if (syntax & RE_CONTEXT_INVALID_OPS)
3102 FREE_STACK_RETURN (REG_BADRPT);
3103 else if (syntax & RE_CONTEXT_INDEP_OPS)
3106 goto unfetch_interval;
3109 /* If the upper bound is zero, don't want to succeed at
3110 all; jump from `laststart' to `b + 3', which will be
3111 the end of the buffer after we insert the jump. */
3112 if (upper_bound == 0)
3114 GET_BUFFER_SPACE (3);
3115 INSERT_JUMP (jump, laststart, b + 3);
3119 /* Otherwise, we have a nontrivial interval. When
3120 we're all done, the pattern will look like:
3121 set_number_at <jump count> <upper bound>
3122 set_number_at <succeed_n count> <lower bound>
3123 succeed_n <after jump addr> <succeed_n count>
3125 jump_n <succeed_n addr> <jump count>
3126 (The upper bound and `jump_n' are omitted if
3127 `upper_bound' is 1, though.) */
3129 { /* If the upper bound is > 1, we need to insert
3130 more at the end of the loop. */
3131 unsigned nbytes = 10 + (upper_bound > 1) * 10;
3133 GET_BUFFER_SPACE (nbytes);
3135 /* Initialize lower bound of the `succeed_n', even
3136 though it will be set during matching by its
3137 attendant `set_number_at' (inserted next),
3138 because `re_compile_fastmap' needs to know.
3139 Jump to the `jump_n' we might insert below. */
3140 INSERT_JUMP2 (succeed_n, laststart,
3141 b + 5 + (upper_bound > 1) * 5,
3145 /* Code to initialize the lower bound. Insert
3146 before the `succeed_n'. The `5' is the last two
3147 bytes of this `set_number_at', plus 3 bytes of
3148 the following `succeed_n'. */
3149 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3152 if (upper_bound > 1)
3153 { /* More than one repetition is allowed, so
3154 append a backward jump to the `succeed_n'
3155 that starts this interval.
3157 When we've reached this during matching,
3158 we'll have matched the interval once, so
3159 jump back only `upper_bound - 1' times. */
3160 STORE_JUMP2 (jump_n, b, laststart + 5,
3164 /* The location we want to set is the second
3165 parameter of the `jump_n'; that is `b-2' as
3166 an absolute address. `laststart' will be
3167 the `set_number_at' we're about to insert;
3168 `laststart+3' the number to set, the source
3169 for the relative address. But we are
3170 inserting into the middle of the pattern --
3171 so everything is getting moved up by 5.
3172 Conclusion: (b - 2) - (laststart + 3) + 5,
3173 i.e., b - laststart.
3175 We insert this at the beginning of the loop
3176 so that if we fail during matching, we'll
3177 reinitialize the bounds. */
3178 insert_op2 (set_number_at, laststart, b - laststart,
3179 upper_bound - 1, b);
3184 beg_interval = NULL;
3189 /* If an invalid interval, match the characters as literals. */
3190 assert (beg_interval);
3192 beg_interval = NULL;
3194 /* normal_char and normal_backslash need `c'. */
3197 if (!(syntax & RE_NO_BK_BRACES))
3199 if (p > pattern && p[-1] == '\\')
3200 goto normal_backslash;
3205 /* There is no way to specify the before_dot and after_dot
3206 operators. rms says this is ok. --karl */
3214 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3220 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3226 if (syntax & RE_NO_GNU_OPS)
3229 BUF_PUSH (wordchar);
3234 if (syntax & RE_NO_GNU_OPS)
3237 BUF_PUSH (notwordchar);
3242 if (syntax & RE_NO_GNU_OPS)
3248 if (syntax & RE_NO_GNU_OPS)
3254 if (syntax & RE_NO_GNU_OPS)
3256 BUF_PUSH (wordbound);
3260 if (syntax & RE_NO_GNU_OPS)
3262 BUF_PUSH (notwordbound);
3266 if (syntax & RE_NO_GNU_OPS)
3272 if (syntax & RE_NO_GNU_OPS)
3277 case '1': case '2': case '3': case '4': case '5':
3278 case '6': case '7': case '8': case '9':
3279 if (syntax & RE_NO_BK_REFS)
3285 FREE_STACK_RETURN (REG_ESUBREG);
3287 /* Can't back reference to a subexpression if inside of it. */
3288 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
3292 BUF_PUSH_2 (duplicate, c1);
3298 if (syntax & RE_BK_PLUS_QM)
3301 goto normal_backslash;
3305 /* You might think it would be useful for \ to mean
3306 not to translate; but if we don't translate it
3307 it will never match anything. */
3315 /* Expects the character in `c'. */
3317 /* If no exactn currently being built. */
3320 /* If last exactn not at current position. */
3321 || pending_exact + *pending_exact + 1 != b
3323 /* We have only one byte following the exactn for the count. */
3324 || *pending_exact == (1 << BYTEWIDTH) - 1
3326 /* If followed by a repetition operator. */
3327 || *p == '*' || *p == '^'
3328 || ((syntax & RE_BK_PLUS_QM)
3329 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
3330 : (*p == '+' || *p == '?'))
3331 || ((syntax & RE_INTERVALS)
3332 && ((syntax & RE_NO_BK_BRACES)
3334 : (p[0] == '\\' && p[1] == '{'))))
3336 /* Start building a new exactn. */
3340 BUF_PUSH_2 (exactn, 0);
3341 pending_exact = b - 1;
3348 } /* while p != pend */
3351 /* Through the pattern now. */
3354 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3356 if (!COMPILE_STACK_EMPTY)
3357 FREE_STACK_RETURN (REG_EPAREN);
3359 /* If we don't want backtracking, force success
3360 the first time we reach the end of the compiled pattern. */
3361 if (syntax & RE_NO_POSIX_BACKTRACKING)
3364 free (compile_stack.stack);
3366 /* We have succeeded; set the length of the buffer. */
3367 bufp->used = b - bufp->buffer;
3372 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3373 print_compiled_pattern (bufp);
3377 #ifndef MATCH_MAY_ALLOCATE
3378 /* Initialize the failure stack to the largest possible stack. This
3379 isn't necessary unless we're trying to avoid calling alloca in
3380 the search and match routines. */
3382 int num_regs = bufp->re_nsub + 1;
3384 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
3385 is strictly greater than re_max_failures, the largest possible stack
3386 is 2 * re_max_failures failure points. */
3387 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
3389 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
3392 if (! fail_stack.stack)
3394 = (fail_stack_elt_t *) xmalloc (fail_stack.size
3395 * sizeof (fail_stack_elt_t));
3398 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
3400 * sizeof (fail_stack_elt_t)));
3401 # else /* not emacs */
3402 if (! fail_stack.stack)
3404 = (fail_stack_elt_t *) malloc (fail_stack.size
3405 * sizeof (fail_stack_elt_t));
3408 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3410 * sizeof (fail_stack_elt_t)));
3411 # endif /* not emacs */
3414 regex_grow_registers (num_regs);
3416 #endif /* not MATCH_MAY_ALLOCATE */
3419 } /* regex_compile */
3421 /* Subroutines for `regex_compile'. */
3423 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3426 store_op1 (op, loc, arg)
3431 *loc = (unsigned char) op;
3432 STORE_NUMBER (loc + 1, arg);
3436 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3439 store_op2 (op, loc, arg1, arg2)
3444 *loc = (unsigned char) op;
3445 STORE_NUMBER (loc + 1, arg1);
3446 STORE_NUMBER (loc + 3, arg2);
3450 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3451 for OP followed by two-byte integer parameter ARG. */
3454 insert_op1 (op, loc, arg, end)
3460 register unsigned char *pfrom = end;
3461 register unsigned char *pto = end + 3;
3463 while (pfrom != loc)
3466 store_op1 (op, loc, arg);
3470 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3473 insert_op2 (op, loc, arg1, arg2, end)
3479 register unsigned char *pfrom = end;
3480 register unsigned char *pto = end + 5;
3482 while (pfrom != loc)
3485 store_op2 (op, loc, arg1, arg2);
3489 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3490 after an alternative or a begin-subexpression. We assume there is at
3491 least one character before the ^. */
3494 at_begline_loc_p (pattern, p, syntax)
3495 const char *pattern, *p;
3496 reg_syntax_t syntax;
3498 const char *prev = p - 2;
3499 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3502 /* After a subexpression? */
3503 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3504 /* After an alternative? */
3505 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3509 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3510 at least one character after the $, i.e., `P < PEND'. */
3513 at_endline_loc_p (p, pend, syntax)
3514 const char *p, *pend;
3515 reg_syntax_t syntax;
3517 const char *next = p;
3518 boolean next_backslash = *next == '\\';
3519 const char *next_next = p + 1 < pend ? p + 1 : 0;
3522 /* Before a subexpression? */
3523 (syntax & RE_NO_BK_PARENS ? *next == ')'
3524 : next_backslash && next_next && *next_next == ')')
3525 /* Before an alternative? */
3526 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3527 : next_backslash && next_next && *next_next == '|');
3531 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3532 false if it's not. */
3535 group_in_compile_stack (compile_stack, regnum)
3536 compile_stack_type compile_stack;
3541 for (this_element = compile_stack.avail - 1;
3544 if (compile_stack.stack[this_element].regnum == regnum)
3551 /* Read the ending character of a range (in a bracket expression) from the
3552 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3553 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3554 Then we set the translation of all bits between the starting and
3555 ending characters (inclusive) in the compiled pattern B.
3557 Return an error code.
3559 We use these short variable names so we can use the same macros as
3560 `regex_compile' itself. */
3562 static reg_errcode_t
3563 compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
3564 unsigned int range_start_char;
3565 const char **p_ptr, *pend;
3566 RE_TRANSLATE_TYPE translate;
3567 reg_syntax_t syntax;
3571 const char *p = *p_ptr;
3574 const unsigned char *collseq;
3575 unsigned int start_colseq;
3576 unsigned int end_colseq;
3584 /* Have to increment the pointer into the pattern string, so the
3585 caller isn't still at the ending character. */
3588 /* Report an error if the range is empty and the syntax prohibits this. */
3589 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3592 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
3593 _NL_COLLATE_COLLSEQMB);
3595 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
3596 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
3597 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
3599 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
3601 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
3603 SET_LIST_BIT (TRANSLATE (this_char));
3608 /* Here we see why `this_char' has to be larger than an `unsigned
3609 char' -- we would otherwise go into an infinite loop, since all
3610 characters <= 0xff. */
3611 range_start_char = TRANSLATE (range_start_char);
3612 end_char = TRANSLATE (p[0]);
3613 for (this_char = range_start_char; this_char <= end_char; ++this_char)
3615 SET_LIST_BIT (TRANSLATE (this_char));
3623 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3624 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3625 characters can start a string that matches the pattern. This fastmap
3626 is used by re_search to skip quickly over impossible starting points.
3628 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3629 area as BUFP->fastmap.
3631 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3634 Returns 0 if we succeed, -2 if an internal error. */
3637 re_compile_fastmap (bufp)
3638 struct re_pattern_buffer *bufp;
3641 #ifdef MATCH_MAY_ALLOCATE
3642 fail_stack_type fail_stack;
3644 #ifndef REGEX_MALLOC
3648 register char *fastmap = bufp->fastmap;
3649 unsigned char *pattern = bufp->buffer;
3650 unsigned char *p = pattern;
3651 register unsigned char *pend = pattern + bufp->used;
3654 /* This holds the pointer to the failure stack, when
3655 it is allocated relocatably. */
3656 fail_stack_elt_t *failure_stack_ptr;
3659 /* Assume that each path through the pattern can be null until
3660 proven otherwise. We set this false at the bottom of switch
3661 statement, to which we get only if a particular path doesn't
3662 match the empty string. */
3663 boolean path_can_be_null = true;
3665 /* We aren't doing a `succeed_n' to begin with. */
3666 boolean succeed_n_p = false;
3668 assert (fastmap != NULL && p != NULL);
3671 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3672 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3673 bufp->can_be_null = 0;
3677 if (p == pend || *p == succeed)
3679 /* We have reached the (effective) end of pattern. */
3680 if (!FAIL_STACK_EMPTY ())
3682 bufp->can_be_null |= path_can_be_null;
3684 /* Reset for next path. */
3685 path_can_be_null = true;
3687 p = fail_stack.stack[--fail_stack.avail].pointer;
3695 /* We should never be about to go beyond the end of the pattern. */
3698 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3701 /* I guess the idea here is to simply not bother with a fastmap
3702 if a backreference is used, since it's too hard to figure out
3703 the fastmap for the corresponding group. Setting
3704 `can_be_null' stops `re_search_2' from using the fastmap, so
3705 that is all we do. */
3707 bufp->can_be_null = 1;
3711 /* Following are the cases which match a character. These end
3720 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3721 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3727 /* Chars beyond end of map must be allowed. */
3728 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3731 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3732 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3738 for (j = 0; j < (1 << BYTEWIDTH); j++)
3739 if (SYNTAX (j) == Sword)
3745 for (j = 0; j < (1 << BYTEWIDTH); j++)
3746 if (SYNTAX (j) != Sword)
3753 int fastmap_newline = fastmap['\n'];
3755 /* `.' matches anything ... */
3756 for (j = 0; j < (1 << BYTEWIDTH); j++)
3759 /* ... except perhaps newline. */
3760 if (!(bufp->syntax & RE_DOT_NEWLINE))
3761 fastmap['\n'] = fastmap_newline;
3763 /* Return if we have already set `can_be_null'; if we have,
3764 then the fastmap is irrelevant. Something's wrong here. */
3765 else if (bufp->can_be_null)
3768 /* Otherwise, have to check alternative paths. */
3775 for (j = 0; j < (1 << BYTEWIDTH); j++)
3776 if (SYNTAX (j) == (enum syntaxcode) k)
3783 for (j = 0; j < (1 << BYTEWIDTH); j++)
3784 if (SYNTAX (j) != (enum syntaxcode) k)
3789 /* All cases after this match the empty string. These end with
3809 case push_dummy_failure:
3814 case pop_failure_jump:
3815 case maybe_pop_jump:
3818 case dummy_failure_jump:
3819 EXTRACT_NUMBER_AND_INCR (j, p);
3824 /* Jump backward implies we just went through the body of a
3825 loop and matched nothing. Opcode jumped to should be
3826 `on_failure_jump' or `succeed_n'. Just treat it like an
3827 ordinary jump. For a * loop, it has pushed its failure
3828 point already; if so, discard that as redundant. */
3829 if ((re_opcode_t) *p != on_failure_jump
3830 && (re_opcode_t) *p != succeed_n)
3834 EXTRACT_NUMBER_AND_INCR (j, p);
3837 /* If what's on the stack is where we are now, pop it. */
3838 if (!FAIL_STACK_EMPTY ()
3839 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3845 case on_failure_jump:
3846 case on_failure_keep_string_jump:
3847 handle_on_failure_jump:
3848 EXTRACT_NUMBER_AND_INCR (j, p);
3850 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3851 end of the pattern. We don't want to push such a point,
3852 since when we restore it above, entering the switch will
3853 increment `p' past the end of the pattern. We don't need
3854 to push such a point since we obviously won't find any more
3855 fastmap entries beyond `pend'. Such a pattern can match
3856 the null string, though. */
3859 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3861 RESET_FAIL_STACK ();
3866 bufp->can_be_null = 1;
3870 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3871 succeed_n_p = false;
3878 /* Get to the number of times to succeed. */
3881 /* Increment p past the n for when k != 0. */
3882 EXTRACT_NUMBER_AND_INCR (k, p);
3886 succeed_n_p = true; /* Spaghetti code alert. */
3887 goto handle_on_failure_jump;
3904 abort (); /* We have listed all the cases. */
3907 /* Getting here means we have found the possible starting
3908 characters for one path of the pattern -- and that the empty
3909 string does not match. We need not follow this path further.
3910 Instead, look at the next alternative (remembered on the
3911 stack), or quit if no more. The test at the top of the loop
3912 does these things. */
3913 path_can_be_null = false;
3917 /* Set `can_be_null' for the last path (also the first path, if the
3918 pattern is empty). */
3919 bufp->can_be_null |= path_can_be_null;
3922 RESET_FAIL_STACK ();
3924 } /* re_compile_fastmap */
3926 weak_alias (__re_compile_fastmap, re_compile_fastmap)
3929 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3930 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3931 this memory for recording register information. STARTS and ENDS
3932 must be allocated using the malloc library routine, and must each
3933 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3935 If NUM_REGS == 0, then subsequent matches should allocate their own
3938 Unless this function is called, the first search or match using
3939 PATTERN_BUFFER will allocate its own register data, without
3940 freeing the old data. */
3943 re_set_registers (bufp, regs, num_regs, starts, ends)
3944 struct re_pattern_buffer *bufp;
3945 struct re_registers *regs;
3947 regoff_t *starts, *ends;
3951 bufp->regs_allocated = REGS_REALLOCATE;
3952 regs->num_regs = num_regs;
3953 regs->start = starts;
3958 bufp->regs_allocated = REGS_UNALLOCATED;
3960 regs->start = regs->end = (regoff_t *) 0;
3964 weak_alias (__re_set_registers, re_set_registers)
3967 /* Searching routines. */
3969 /* Like re_search_2, below, but only one string is specified, and
3970 doesn't let you say where to stop matching. */
3973 re_search (bufp, string, size, startpos, range, regs)
3974 struct re_pattern_buffer *bufp;
3976 int size, startpos, range;
3977 struct re_registers *regs;
3979 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3983 weak_alias (__re_search, re_search)
3987 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3988 virtual concatenation of STRING1 and STRING2, starting first at index
3989 STARTPOS, then at STARTPOS + 1, and so on.
3991 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3993 RANGE is how far to scan while trying to match. RANGE = 0 means try
3994 only at STARTPOS; in general, the last start tried is STARTPOS +
3997 In REGS, return the indices of the virtual concatenation of STRING1
3998 and STRING2 that matched the entire BUFP->buffer and its contained
4001 Do not consider matching one past the index STOP in the virtual
4002 concatenation of STRING1 and STRING2.
4004 We return either the position in the strings at which the match was
4005 found, -1 if no match, or -2 if error (such as failure
4009 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
4010 struct re_pattern_buffer *bufp;
4011 const char *string1, *string2;
4015 struct re_registers *regs;
4019 register char *fastmap = bufp->fastmap;
4020 register RE_TRANSLATE_TYPE translate = bufp->translate;
4021 int total_size = size1 + size2;
4022 int endpos = startpos + range;
4024 /* Check for out-of-range STARTPOS. */
4025 if (startpos < 0 || startpos > total_size)
4028 /* Fix up RANGE if it might eventually take us outside
4029 the virtual concatenation of STRING1 and STRING2.
4030 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4032 range = 0 - startpos;
4033 else if (endpos > total_size)
4034 range = total_size - startpos;
4036 /* If the search isn't to be a backwards one, don't waste time in a
4037 search for a pattern that must be anchored. */
4038 if (bufp->used > 0 && range > 0
4039 && ((re_opcode_t) bufp->buffer[0] == begbuf
4040 /* `begline' is like `begbuf' if it cannot match at newlines. */
4041 || ((re_opcode_t) bufp->buffer[0] == begline
4042 && !bufp->newline_anchor)))
4051 /* In a forward search for something that starts with \=.
4052 don't keep searching past point. */
4053 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4055 range = PT - startpos;
4061 /* Update the fastmap now if not correct already. */
4062 if (fastmap && !bufp->fastmap_accurate)
4063 if (re_compile_fastmap (bufp) == -2)
4066 /* Loop through the string, looking for a place to start matching. */
4069 /* If a fastmap is supplied, skip quickly over characters that
4070 cannot be the start of a match. If the pattern can match the
4071 null string, however, we don't need to skip characters; we want
4072 the first null string. */
4073 if (fastmap && startpos < total_size && !bufp->can_be_null)
4075 if (range > 0) /* Searching forwards. */
4077 register const char *d;
4078 register int lim = 0;
4081 if (startpos < size1 && startpos + range >= size1)
4082 lim = range - (size1 - startpos);
4084 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
4086 /* Written out as an if-else to avoid testing `translate'
4090 && !fastmap[(unsigned char)
4091 translate[(unsigned char) *d++]])
4094 while (range > lim && !fastmap[(unsigned char) *d++])
4097 startpos += irange - range;
4099 else /* Searching backwards. */
4101 register char c = (size1 == 0 || startpos >= size1
4102 ? string2[startpos - size1]
4103 : string1[startpos]);
4105 if (!fastmap[(unsigned char) TRANSLATE (c)])
4110 /* If can't match the null string, and that's all we have left, fail. */
4111 if (range >= 0 && startpos == total_size && fastmap
4112 && !bufp->can_be_null)
4115 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4116 startpos, regs, stop);
4117 #ifndef REGEX_MALLOC
4146 weak_alias (__re_search_2, re_search_2)
4149 /* This converts PTR, a pointer into one of the search strings `string1'
4150 and `string2' into an offset from the beginning of that string. */
4151 #define POINTER_TO_OFFSET(ptr) \
4152 (FIRST_STRING_P (ptr) \
4153 ? ((regoff_t) ((ptr) - string1)) \
4154 : ((regoff_t) ((ptr) - string2 + size1)))
4156 /* Macros for dealing with the split strings in re_match_2. */
4158 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
4160 /* Call before fetching a character with *d. This switches over to
4161 string2 if necessary. */
4162 #define PREFETCH() \
4165 /* End of string2 => fail. */ \
4166 if (dend == end_match_2) \
4168 /* End of string1 => advance to string2. */ \
4170 dend = end_match_2; \
4174 /* Test if at very beginning or at very end of the virtual concatenation
4175 of `string1' and `string2'. If only one string, it's `string2'. */
4176 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4177 #define AT_STRINGS_END(d) ((d) == end2)
4180 /* Test if D points to a character which is word-constituent. We have
4181 two special cases to check for: if past the end of string1, look at
4182 the first character in string2; and if before the beginning of
4183 string2, look at the last character in string1. */
4184 #define WORDCHAR_P(d) \
4185 (SYNTAX ((d) == end1 ? *string2 \
4186 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4189 /* Disabled due to a compiler bug -- see comment at case wordbound */
4191 /* Test if the character before D and the one at D differ with respect
4192 to being word-constituent. */
4193 #define AT_WORD_BOUNDARY(d) \
4194 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4195 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4198 /* Free everything we malloc. */
4199 #ifdef MATCH_MAY_ALLOCATE
4200 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
4201 # define FREE_VARIABLES() \
4203 REGEX_FREE_STACK (fail_stack.stack); \
4204 FREE_VAR (regstart); \
4205 FREE_VAR (regend); \
4206 FREE_VAR (old_regstart); \
4207 FREE_VAR (old_regend); \
4208 FREE_VAR (best_regstart); \
4209 FREE_VAR (best_regend); \
4210 FREE_VAR (reg_info); \
4211 FREE_VAR (reg_dummy); \
4212 FREE_VAR (reg_info_dummy); \
4215 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4216 #endif /* not MATCH_MAY_ALLOCATE */
4218 /* These values must meet several constraints. They must not be valid
4219 register values; since we have a limit of 255 registers (because
4220 we use only one byte in the pattern for the register number), we can
4221 use numbers larger than 255. They must differ by 1, because of
4222 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4223 be larger than the value for the highest register, so we do not try
4224 to actually save any registers when none are active. */
4225 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4226 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4228 /* Matching routines. */
4230 #ifndef emacs /* Emacs never uses this. */
4231 /* re_match is like re_match_2 except it takes only a single string. */
4234 re_match (bufp, string, size, pos, regs)
4235 struct re_pattern_buffer *bufp;
4238 struct re_registers *regs;
4240 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4242 # ifndef REGEX_MALLOC
4250 weak_alias (__re_match, re_match)
4252 #endif /* not emacs */
4254 static boolean group_match_null_string_p _RE_ARGS ((unsigned char **p,
4256 register_info_type *reg_info));
4257 static boolean alt_match_null_string_p _RE_ARGS ((unsigned char *p,
4259 register_info_type *reg_info));
4260 static boolean common_op_match_null_string_p _RE_ARGS ((unsigned char **p,
4262 register_info_type *reg_info));
4263 static int bcmp_translate _RE_ARGS ((const char *s1, const char *s2,
4264 int len, char *translate));
4266 /* re_match_2 matches the compiled pattern in BUFP against the
4267 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4268 and SIZE2, respectively). We start matching at POS, and stop
4271 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4272 store offsets for the substring each group matched in REGS. See the
4273 documentation for exactly how many groups we fill.
4275 We return -1 if no match, -2 if an internal error (such as the
4276 failure stack overflowing). Otherwise, we return the length of the
4277 matched substring. */
4280 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4281 struct re_pattern_buffer *bufp;
4282 const char *string1, *string2;
4285 struct re_registers *regs;
4288 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
4290 #ifndef REGEX_MALLOC
4298 weak_alias (__re_match_2, re_match_2)
4301 /* This is a separate function so that we can force an alloca cleanup
4304 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4305 struct re_pattern_buffer *bufp;
4306 const char *string1, *string2;
4309 struct re_registers *regs;
4312 /* General temporaries. */
4316 /* Just past the end of the corresponding string. */
4317 const char *end1, *end2;
4319 /* Pointers into string1 and string2, just past the last characters in
4320 each to consider matching. */
4321 const char *end_match_1, *end_match_2;
4323 /* Where we are in the data, and the end of the current string. */
4324 const char *d, *dend;
4326 /* Where we are in the pattern, and the end of the pattern. */
4327 unsigned char *p = bufp->buffer;
4328 register unsigned char *pend = p + bufp->used;
4330 /* Mark the opcode just after a start_memory, so we can test for an
4331 empty subpattern when we get to the stop_memory. */
4332 unsigned char *just_past_start_mem = 0;
4334 /* We use this to map every character in the string. */
4335 RE_TRANSLATE_TYPE translate = bufp->translate;
4337 /* Failure point stack. Each place that can handle a failure further
4338 down the line pushes a failure point on this stack. It consists of
4339 restart, regend, and reg_info for all registers corresponding to
4340 the subexpressions we're currently inside, plus the number of such
4341 registers, and, finally, two char *'s. The first char * is where
4342 to resume scanning the pattern; the second one is where to resume
4343 scanning the strings. If the latter is zero, the failure point is
4344 a ``dummy''; if a failure happens and the failure point is a dummy,
4345 it gets discarded and the next next one is tried. */
4346 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4347 fail_stack_type fail_stack;
4350 static unsigned failure_id;
4351 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4355 /* This holds the pointer to the failure stack, when
4356 it is allocated relocatably. */
4357 fail_stack_elt_t *failure_stack_ptr;
4360 /* We fill all the registers internally, independent of what we
4361 return, for use in backreferences. The number here includes
4362 an element for register zero. */
4363 size_t num_regs = bufp->re_nsub + 1;
4365 /* The currently active registers. */
4366 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4367 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4369 /* Information on the contents of registers. These are pointers into
4370 the input strings; they record just what was matched (on this
4371 attempt) by a subexpression part of the pattern, that is, the
4372 regnum-th regstart pointer points to where in the pattern we began
4373 matching and the regnum-th regend points to right after where we
4374 stopped matching the regnum-th subexpression. (The zeroth register
4375 keeps track of what the whole pattern matches.) */
4376 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4377 const char **regstart, **regend;
4380 /* If a group that's operated upon by a repetition operator fails to
4381 match anything, then the register for its start will need to be
4382 restored because it will have been set to wherever in the string we
4383 are when we last see its open-group operator. Similarly for a
4385 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4386 const char **old_regstart, **old_regend;
4389 /* The is_active field of reg_info helps us keep track of which (possibly
4390 nested) subexpressions we are currently in. The matched_something
4391 field of reg_info[reg_num] helps us tell whether or not we have
4392 matched any of the pattern so far this time through the reg_num-th
4393 subexpression. These two fields get reset each time through any
4394 loop their register is in. */
4395 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4396 register_info_type *reg_info;
4399 /* The following record the register info as found in the above
4400 variables when we find a match better than any we've seen before.
4401 This happens as we backtrack through the failure points, which in
4402 turn happens only if we have not yet matched the entire string. */
4403 unsigned best_regs_set = false;
4404 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4405 const char **best_regstart, **best_regend;
4408 /* Logically, this is `best_regend[0]'. But we don't want to have to
4409 allocate space for that if we're not allocating space for anything
4410 else (see below). Also, we never need info about register 0 for
4411 any of the other register vectors, and it seems rather a kludge to
4412 treat `best_regend' differently than the rest. So we keep track of
4413 the end of the best match so far in a separate variable. We
4414 initialize this to NULL so that when we backtrack the first time
4415 and need to test it, it's not garbage. */
4416 const char *match_end = NULL;
4418 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4419 int set_regs_matched_done = 0;
4421 /* Used when we pop values we don't care about. */
4422 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4423 const char **reg_dummy;
4424 register_info_type *reg_info_dummy;
4428 /* Counts the total number of registers pushed. */
4429 unsigned num_regs_pushed = 0;
4432 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4436 #ifdef MATCH_MAY_ALLOCATE
4437 /* Do not bother to initialize all the register variables if there are
4438 no groups in the pattern, as it takes a fair amount of time. If
4439 there are groups, we include space for register 0 (the whole
4440 pattern), even though we never use it, since it simplifies the
4441 array indexing. We should fix this. */
4444 regstart = REGEX_TALLOC (num_regs, const char *);
4445 regend = REGEX_TALLOC (num_regs, const char *);
4446 old_regstart = REGEX_TALLOC (num_regs, const char *);
4447 old_regend = REGEX_TALLOC (num_regs, const char *);
4448 best_regstart = REGEX_TALLOC (num_regs, const char *);
4449 best_regend = REGEX_TALLOC (num_regs, const char *);
4450 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4451 reg_dummy = REGEX_TALLOC (num_regs, const char *);
4452 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4454 if (!(regstart && regend && old_regstart && old_regend && reg_info
4455 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4463 /* We must initialize all our variables to NULL, so that
4464 `FREE_VARIABLES' doesn't try to free them. */
4465 regstart = regend = old_regstart = old_regend = best_regstart
4466 = best_regend = reg_dummy = NULL;
4467 reg_info = reg_info_dummy = (register_info_type *) NULL;
4469 #endif /* MATCH_MAY_ALLOCATE */
4471 /* The starting position is bogus. */
4472 if (pos < 0 || pos > size1 + size2)
4478 /* Initialize subexpression text positions to -1 to mark ones that no
4479 start_memory/stop_memory has been seen for. Also initialize the
4480 register information struct. */
4481 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4483 regstart[mcnt] = regend[mcnt]
4484 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4486 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4487 IS_ACTIVE (reg_info[mcnt]) = 0;
4488 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4489 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4492 /* We move `string1' into `string2' if the latter's empty -- but not if
4493 `string1' is null. */
4494 if (size2 == 0 && string1 != NULL)
4501 end1 = string1 + size1;
4502 end2 = string2 + size2;
4504 /* Compute where to stop matching, within the two strings. */
4507 end_match_1 = string1 + stop;
4508 end_match_2 = string2;
4513 end_match_2 = string2 + stop - size1;
4516 /* `p' scans through the pattern as `d' scans through the data.
4517 `dend' is the end of the input string that `d' points within. `d'
4518 is advanced into the following input string whenever necessary, but
4519 this happens before fetching; therefore, at the beginning of the
4520 loop, `d' can be pointing at the end of a string, but it cannot
4522 if (size1 > 0 && pos <= size1)
4529 d = string2 + pos - size1;
4533 DEBUG_PRINT1 ("The compiled pattern is:\n");
4534 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4535 DEBUG_PRINT1 ("The string to match is: `");
4536 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4537 DEBUG_PRINT1 ("'\n");
4539 /* This loops over pattern commands. It exits by returning from the
4540 function if the match is complete, or it drops through if the match
4541 fails at this starting point in the input data. */
4545 DEBUG_PRINT2 ("\n%p: ", p);
4547 DEBUG_PRINT2 ("\n0x%x: ", p);
4551 { /* End of pattern means we might have succeeded. */
4552 DEBUG_PRINT1 ("end of pattern ... ");
4554 /* If we haven't matched the entire string, and we want the
4555 longest match, try backtracking. */
4556 if (d != end_match_2)
4558 /* 1 if this match ends in the same string (string1 or string2)
4559 as the best previous match. */
4560 boolean same_str_p = (FIRST_STRING_P (match_end)
4561 == MATCHING_IN_FIRST_STRING);
4562 /* 1 if this match is the best seen so far. */
4563 boolean best_match_p;
4565 /* AIX compiler got confused when this was combined
4566 with the previous declaration. */
4568 best_match_p = d > match_end;
4570 best_match_p = !MATCHING_IN_FIRST_STRING;
4572 DEBUG_PRINT1 ("backtracking.\n");
4574 if (!FAIL_STACK_EMPTY ())
4575 { /* More failure points to try. */
4577 /* If exceeds best match so far, save it. */
4578 if (!best_regs_set || best_match_p)
4580 best_regs_set = true;
4583 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4585 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4587 best_regstart[mcnt] = regstart[mcnt];
4588 best_regend[mcnt] = regend[mcnt];
4594 /* If no failure points, don't restore garbage. And if
4595 last match is real best match, don't restore second
4597 else if (best_regs_set && !best_match_p)
4600 /* Restore best match. It may happen that `dend ==
4601 end_match_1' while the restored d is in string2.
4602 For example, the pattern `x.*y.*z' against the
4603 strings `x-' and `y-z-', if the two strings are
4604 not consecutive in memory. */
4605 DEBUG_PRINT1 ("Restoring best registers.\n");
4608 dend = ((d >= string1 && d <= end1)
4609 ? end_match_1 : end_match_2);
4611 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4613 regstart[mcnt] = best_regstart[mcnt];
4614 regend[mcnt] = best_regend[mcnt];
4617 } /* d != end_match_2 */
4620 DEBUG_PRINT1 ("Accepting match.\n");
4622 /* If caller wants register contents data back, do it. */
4623 if (regs && !bufp->no_sub)
4625 /* Have the register data arrays been allocated? */
4626 if (bufp->regs_allocated == REGS_UNALLOCATED)
4627 { /* No. So allocate them with malloc. We need one
4628 extra element beyond `num_regs' for the `-1' marker
4630 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4631 regs->start = TALLOC (regs->num_regs, regoff_t);
4632 regs->end = TALLOC (regs->num_regs, regoff_t);
4633 if (regs->start == NULL || regs->end == NULL)
4638 bufp->regs_allocated = REGS_REALLOCATE;
4640 else if (bufp->regs_allocated == REGS_REALLOCATE)
4641 { /* Yes. If we need more elements than were already
4642 allocated, reallocate them. If we need fewer, just
4644 if (regs->num_regs < num_regs + 1)
4646 regs->num_regs = num_regs + 1;
4647 RETALLOC (regs->start, regs->num_regs, regoff_t);
4648 RETALLOC (regs->end, regs->num_regs, regoff_t);
4649 if (regs->start == NULL || regs->end == NULL)
4658 /* These braces fend off a "empty body in an else-statement"
4659 warning under GCC when assert expands to nothing. */
4660 assert (bufp->regs_allocated == REGS_FIXED);
4663 /* Convert the pointer data in `regstart' and `regend' to
4664 indices. Register zero has to be set differently,
4665 since we haven't kept track of any info for it. */
4666 if (regs->num_regs > 0)
4668 regs->start[0] = pos;
4669 regs->end[0] = (MATCHING_IN_FIRST_STRING
4670 ? ((regoff_t) (d - string1))
4671 : ((regoff_t) (d - string2 + size1)));
4674 /* Go through the first `min (num_regs, regs->num_regs)'
4675 registers, since that is all we initialized. */
4676 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
4679 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4680 regs->start[mcnt] = regs->end[mcnt] = -1;
4684 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4686 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4690 /* If the regs structure we return has more elements than
4691 were in the pattern, set the extra elements to -1. If
4692 we (re)allocated the registers, this is the case,
4693 because we always allocate enough to have at least one
4695 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
4696 regs->start[mcnt] = regs->end[mcnt] = -1;
4697 } /* regs && !bufp->no_sub */
4699 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4700 nfailure_points_pushed, nfailure_points_popped,
4701 nfailure_points_pushed - nfailure_points_popped);
4702 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4704 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4708 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4714 /* Otherwise match next pattern command. */
4715 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4717 /* Ignore these. Used to ignore the n of succeed_n's which
4718 currently have n == 0. */
4720 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4724 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4727 /* Match the next n pattern characters exactly. The following
4728 byte in the pattern defines n, and the n bytes after that
4729 are the characters to match. */
4732 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4734 /* This is written out as an if-else so we don't waste time
4735 testing `translate' inside the loop. */
4741 if ((unsigned char) translate[(unsigned char) *d++]
4742 != (unsigned char) *p++)
4752 if (*d++ != (char) *p++) goto fail;
4756 SET_REGS_MATCHED ();
4760 /* Match any character except possibly a newline or a null. */
4762 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4766 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4767 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4770 SET_REGS_MATCHED ();
4771 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4779 register unsigned char c;
4780 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4782 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4785 c = TRANSLATE (*d); /* The character to match. */
4787 /* Cast to `unsigned' instead of `unsigned char' in case the
4788 bit list is a full 32 bytes long. */
4789 if (c < (unsigned) (*p * BYTEWIDTH)
4790 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4795 if (!not) goto fail;
4797 SET_REGS_MATCHED ();
4803 /* The beginning of a group is represented by start_memory.
4804 The arguments are the register number in the next byte, and the
4805 number of groups inner to this one in the next. The text
4806 matched within the group is recorded (in the internal
4807 registers data structure) under the register number. */
4809 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4811 /* Find out if this group can match the empty string. */
4812 p1 = p; /* To send to group_match_null_string_p. */
4814 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4815 REG_MATCH_NULL_STRING_P (reg_info[*p])
4816 = group_match_null_string_p (&p1, pend, reg_info);
4818 /* Save the position in the string where we were the last time
4819 we were at this open-group operator in case the group is
4820 operated upon by a repetition operator, e.g., with `(a*)*b'
4821 against `ab'; then we want to ignore where we are now in
4822 the string in case this attempt to match fails. */
4823 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4824 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4826 DEBUG_PRINT2 (" old_regstart: %d\n",
4827 POINTER_TO_OFFSET (old_regstart[*p]));
4830 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4832 IS_ACTIVE (reg_info[*p]) = 1;
4833 MATCHED_SOMETHING (reg_info[*p]) = 0;
4835 /* Clear this whenever we change the register activity status. */
4836 set_regs_matched_done = 0;
4838 /* This is the new highest active register. */
4839 highest_active_reg = *p;
4841 /* If nothing was active before, this is the new lowest active
4843 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4844 lowest_active_reg = *p;
4846 /* Move past the register number and inner group count. */
4848 just_past_start_mem = p;
4853 /* The stop_memory opcode represents the end of a group. Its
4854 arguments are the same as start_memory's: the register
4855 number, and the number of inner groups. */
4857 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4859 /* We need to save the string position the last time we were at
4860 this close-group operator in case the group is operated
4861 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4862 against `aba'; then we want to ignore where we are now in
4863 the string in case this attempt to match fails. */
4864 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4865 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4867 DEBUG_PRINT2 (" old_regend: %d\n",
4868 POINTER_TO_OFFSET (old_regend[*p]));
4871 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4873 /* This register isn't active anymore. */
4874 IS_ACTIVE (reg_info[*p]) = 0;
4876 /* Clear this whenever we change the register activity status. */
4877 set_regs_matched_done = 0;
4879 /* If this was the only register active, nothing is active
4881 if (lowest_active_reg == highest_active_reg)
4883 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4884 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4887 { /* We must scan for the new highest active register, since
4888 it isn't necessarily one less than now: consider
4889 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4890 new highest active register is 1. */
4891 unsigned char r = *p - 1;
4892 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4895 /* If we end up at register zero, that means that we saved
4896 the registers as the result of an `on_failure_jump', not
4897 a `start_memory', and we jumped to past the innermost
4898 `stop_memory'. For example, in ((.)*) we save
4899 registers 1 and 2 as a result of the *, but when we pop
4900 back to the second ), we are at the stop_memory 1.
4901 Thus, nothing is active. */
4904 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4905 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4908 highest_active_reg = r;
4911 /* If just failed to match something this time around with a
4912 group that's operated on by a repetition operator, try to
4913 force exit from the ``loop'', and restore the register
4914 information for this group that we had before trying this
4916 if ((!MATCHED_SOMETHING (reg_info[*p])
4917 || just_past_start_mem == p - 1)
4920 boolean is_a_jump_n = false;
4924 switch ((re_opcode_t) *p1++)
4928 case pop_failure_jump:
4929 case maybe_pop_jump:
4931 case dummy_failure_jump:
4932 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4942 /* If the next operation is a jump backwards in the pattern
4943 to an on_failure_jump right before the start_memory
4944 corresponding to this stop_memory, exit from the loop
4945 by forcing a failure after pushing on the stack the
4946 on_failure_jump's jump in the pattern, and d. */
4947 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4948 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4950 /* If this group ever matched anything, then restore
4951 what its registers were before trying this last
4952 failed match, e.g., with `(a*)*b' against `ab' for
4953 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4954 against `aba' for regend[3].
4956 Also restore the registers for inner groups for,
4957 e.g., `((a*)(b*))*' against `aba' (register 3 would
4958 otherwise get trashed). */
4960 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4964 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4966 /* Restore this and inner groups' (if any) registers. */
4967 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
4970 regstart[r] = old_regstart[r];
4972 /* xx why this test? */
4973 if (old_regend[r] >= regstart[r])
4974 regend[r] = old_regend[r];
4978 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4979 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4985 /* Move past the register number and the inner group count. */
4990 /* \<digit> has been turned into a `duplicate' command which is
4991 followed by the numeric value of <digit> as the register number. */
4994 register const char *d2, *dend2;
4995 int regno = *p++; /* Get which register to match against. */
4996 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4998 /* Can't back reference a group which we've never matched. */
4999 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5002 /* Where in input to try to start matching. */
5003 d2 = regstart[regno];
5005 /* Where to stop matching; if both the place to start and
5006 the place to stop matching are in the same string, then
5007 set to the place to stop, otherwise, for now have to use
5008 the end of the first string. */
5010 dend2 = ((FIRST_STRING_P (regstart[regno])
5011 == FIRST_STRING_P (regend[regno]))
5012 ? regend[regno] : end_match_1);
5015 /* If necessary, advance to next segment in register
5019 if (dend2 == end_match_2) break;
5020 if (dend2 == regend[regno]) break;
5022 /* End of string1 => advance to string2. */
5024 dend2 = regend[regno];
5026 /* At end of register contents => success */
5027 if (d2 == dend2) break;
5029 /* If necessary, advance to next segment in data. */
5032 /* How many characters left in this segment to match. */
5035 /* Want how many consecutive characters we can match in
5036 one shot, so, if necessary, adjust the count. */
5037 if (mcnt > dend2 - d2)
5040 /* Compare that many; failure if mismatch, else move
5043 ? bcmp_translate (d, d2, mcnt, translate)
5044 : memcmp (d, d2, mcnt))
5046 d += mcnt, d2 += mcnt;
5048 /* Do this because we've match some characters. */
5049 SET_REGS_MATCHED ();
5055 /* begline matches the empty string at the beginning of the string
5056 (unless `not_bol' is set in `bufp'), and, if
5057 `newline_anchor' is set, after newlines. */
5059 DEBUG_PRINT1 ("EXECUTING begline.\n");
5061 if (AT_STRINGS_BEG (d))
5063 if (!bufp->not_bol) break;
5065 else if (d[-1] == '\n' && bufp->newline_anchor)
5069 /* In all other cases, we fail. */
5073 /* endline is the dual of begline. */
5075 DEBUG_PRINT1 ("EXECUTING endline.\n");
5077 if (AT_STRINGS_END (d))
5079 if (!bufp->not_eol) break;
5082 /* We have to ``prefetch'' the next character. */
5083 else if ((d == end1 ? *string2 : *d) == '\n'
5084 && bufp->newline_anchor)
5091 /* Match at the very beginning of the data. */
5093 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5094 if (AT_STRINGS_BEG (d))
5099 /* Match at the very end of the data. */
5101 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5102 if (AT_STRINGS_END (d))
5107 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5108 pushes NULL as the value for the string on the stack. Then
5109 `pop_failure_point' will keep the current value for the
5110 string, instead of restoring it. To see why, consider
5111 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5112 then the . fails against the \n. But the next thing we want
5113 to do is match the \n against the \n; if we restored the
5114 string value, we would be back at the foo.
5116 Because this is used only in specific cases, we don't need to
5117 check all the things that `on_failure_jump' does, to make
5118 sure the right things get saved on the stack. Hence we don't
5119 share its code. The only reason to push anything on the
5120 stack at all is that otherwise we would have to change
5121 `anychar's code to do something besides goto fail in this
5122 case; that seems worse than this. */
5123 case on_failure_keep_string_jump:
5124 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
5126 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5128 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
5130 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
5133 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
5137 /* Uses of on_failure_jump:
5139 Each alternative starts with an on_failure_jump that points
5140 to the beginning of the next alternative. Each alternative
5141 except the last ends with a jump that in effect jumps past
5142 the rest of the alternatives. (They really jump to the
5143 ending jump of the following alternative, because tensioning
5144 these jumps is a hassle.)
5146 Repeats start with an on_failure_jump that points past both
5147 the repetition text and either the following jump or
5148 pop_failure_jump back to this on_failure_jump. */
5149 case on_failure_jump:
5151 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
5153 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5155 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
5157 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
5160 /* If this on_failure_jump comes right before a group (i.e.,
5161 the original * applied to a group), save the information
5162 for that group and all inner ones, so that if we fail back
5163 to this point, the group's information will be correct.
5164 For example, in \(a*\)*\1, we need the preceding group,
5165 and in \(zz\(a*\)b*\)\2, we need the inner group. */
5167 /* We can't use `p' to check ahead because we push
5168 a failure point to `p + mcnt' after we do this. */
5171 /* We need to skip no_op's before we look for the
5172 start_memory in case this on_failure_jump is happening as
5173 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5175 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5178 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5180 /* We have a new highest active register now. This will
5181 get reset at the start_memory we are about to get to,
5182 but we will have saved all the registers relevant to
5183 this repetition op, as described above. */
5184 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5185 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5186 lowest_active_reg = *(p1 + 1);
5189 DEBUG_PRINT1 (":\n");
5190 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5194 /* A smart repeat ends with `maybe_pop_jump'.
5195 We change it to either `pop_failure_jump' or `jump'. */
5196 case maybe_pop_jump:
5197 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5198 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5200 register unsigned char *p2 = p;
5202 /* Compare the beginning of the repeat with what in the
5203 pattern follows its end. If we can establish that there
5204 is nothing that they would both match, i.e., that we
5205 would have to backtrack because of (as in, e.g., `a*a')
5206 then we can change to pop_failure_jump, because we'll
5207 never have to backtrack.
5209 This is not true in the case of alternatives: in
5210 `(a|ab)*' we do need to backtrack to the `ab' alternative
5211 (e.g., if the string was `ab'). But instead of trying to
5212 detect that here, the alternative has put on a dummy
5213 failure point which is what we will end up popping. */
5215 /* Skip over open/close-group commands.
5216 If what follows this loop is a ...+ construct,
5217 look at what begins its body, since we will have to
5218 match at least one of that. */
5222 && ((re_opcode_t) *p2 == stop_memory
5223 || (re_opcode_t) *p2 == start_memory))
5225 else if (p2 + 6 < pend
5226 && (re_opcode_t) *p2 == dummy_failure_jump)
5233 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5234 to the `maybe_finalize_jump' of this case. Examine what
5237 /* If we're at the end of the pattern, we can change. */
5240 /* Consider what happens when matching ":\(.*\)"
5241 against ":/". I don't really understand this code
5243 p[-3] = (unsigned char) pop_failure_jump;
5245 (" End of pattern: change to `pop_failure_jump'.\n");
5248 else if ((re_opcode_t) *p2 == exactn
5249 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5251 register unsigned char c
5252 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5254 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
5256 p[-3] = (unsigned char) pop_failure_jump;
5257 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5261 else if ((re_opcode_t) p1[3] == charset
5262 || (re_opcode_t) p1[3] == charset_not)
5264 int not = (re_opcode_t) p1[3] == charset_not;
5266 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
5267 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5270 /* `not' is equal to 1 if c would match, which means
5271 that we can't change to pop_failure_jump. */
5274 p[-3] = (unsigned char) pop_failure_jump;
5275 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5279 else if ((re_opcode_t) *p2 == charset)
5281 /* We win if the first character of the loop is not part
5283 if ((re_opcode_t) p1[3] == exactn
5284 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
5285 && (p2[2 + p1[5] / BYTEWIDTH]
5286 & (1 << (p1[5] % BYTEWIDTH)))))
5288 p[-3] = (unsigned char) pop_failure_jump;
5289 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5292 else if ((re_opcode_t) p1[3] == charset_not)
5295 /* We win if the charset_not inside the loop
5296 lists every character listed in the charset after. */
5297 for (idx = 0; idx < (int) p2[1]; idx++)
5298 if (! (p2[2 + idx] == 0
5299 || (idx < (int) p1[4]
5300 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5305 p[-3] = (unsigned char) pop_failure_jump;
5306 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5309 else if ((re_opcode_t) p1[3] == charset)
5312 /* We win if the charset inside the loop
5313 has no overlap with the one after the loop. */
5315 idx < (int) p2[1] && idx < (int) p1[4];
5317 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5320 if (idx == p2[1] || idx == p1[4])
5322 p[-3] = (unsigned char) pop_failure_jump;
5323 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5328 p -= 2; /* Point at relative address again. */
5329 if ((re_opcode_t) p[-1] != pop_failure_jump)
5331 p[-1] = (unsigned char) jump;
5332 DEBUG_PRINT1 (" Match => jump.\n");
5333 goto unconditional_jump;
5335 /* Note fall through. */
5338 /* The end of a simple repeat has a pop_failure_jump back to
5339 its matching on_failure_jump, where the latter will push a
5340 failure point. The pop_failure_jump takes off failure
5341 points put on by this pop_failure_jump's matching
5342 on_failure_jump; we got through the pattern to here from the
5343 matching on_failure_jump, so didn't fail. */
5344 case pop_failure_jump:
5346 /* We need to pass separate storage for the lowest and
5347 highest registers, even though we don't care about the
5348 actual values. Otherwise, we will restore only one
5349 register from the stack, since lowest will == highest in
5350 `pop_failure_point'. */
5351 active_reg_t dummy_low_reg, dummy_high_reg;
5352 unsigned char *pdummy;
5355 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5356 POP_FAILURE_POINT (sdummy, pdummy,
5357 dummy_low_reg, dummy_high_reg,
5358 reg_dummy, reg_dummy, reg_info_dummy);
5360 /* Note fall through. */
5364 DEBUG_PRINT2 ("\n%p: ", p);
5366 DEBUG_PRINT2 ("\n0x%x: ", p);
5368 /* Note fall through. */
5370 /* Unconditionally jump (without popping any failure points). */
5372 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5373 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5374 p += mcnt; /* Do the jump. */
5376 DEBUG_PRINT2 ("(to %p).\n", p);
5378 DEBUG_PRINT2 ("(to 0x%x).\n", p);
5383 /* We need this opcode so we can detect where alternatives end
5384 in `group_match_null_string_p' et al. */
5386 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5387 goto unconditional_jump;
5390 /* Normally, the on_failure_jump pushes a failure point, which
5391 then gets popped at pop_failure_jump. We will end up at
5392 pop_failure_jump, also, and with a pattern of, say, `a+', we
5393 are skipping over the on_failure_jump, so we have to push
5394 something meaningless for pop_failure_jump to pop. */
5395 case dummy_failure_jump:
5396 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5397 /* It doesn't matter what we push for the string here. What
5398 the code at `fail' tests is the value for the pattern. */
5399 PUSH_FAILURE_POINT (NULL, NULL, -2);
5400 goto unconditional_jump;
5403 /* At the end of an alternative, we need to push a dummy failure
5404 point in case we are followed by a `pop_failure_jump', because
5405 we don't want the failure point for the alternative to be
5406 popped. For example, matching `(a|ab)*' against `aab'
5407 requires that we match the `ab' alternative. */
5408 case push_dummy_failure:
5409 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5410 /* See comments just above at `dummy_failure_jump' about the
5412 PUSH_FAILURE_POINT (NULL, NULL, -2);
5415 /* Have to succeed matching what follows at least n times.
5416 After that, handle like `on_failure_jump'. */
5418 EXTRACT_NUMBER (mcnt, p + 2);
5419 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5422 /* Originally, this is how many times we HAVE to succeed. */
5427 STORE_NUMBER_AND_INCR (p, mcnt);
5429 DEBUG_PRINT3 (" Setting %p to %d.\n", p - 2, mcnt);
5431 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - 2, mcnt);
5437 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p+2);
5439 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
5441 p[2] = (unsigned char) no_op;
5442 p[3] = (unsigned char) no_op;
5448 EXTRACT_NUMBER (mcnt, p + 2);
5449 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5451 /* Originally, this is how many times we CAN jump. */
5455 STORE_NUMBER (p + 2, mcnt);
5457 DEBUG_PRINT3 (" Setting %p to %d.\n", p + 2, mcnt);
5459 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + 2, mcnt);
5461 goto unconditional_jump;
5463 /* If don't have to jump any more, skip over the rest of command. */
5470 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5472 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5474 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5476 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
5478 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
5480 STORE_NUMBER (p1, mcnt);
5485 /* The DEC Alpha C compiler 3.x generates incorrect code for the
5486 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
5487 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
5488 macro and introducing temporary variables works around the bug. */
5491 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5492 if (AT_WORD_BOUNDARY (d))
5497 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5498 if (AT_WORD_BOUNDARY (d))
5504 boolean prevchar, thischar;
5506 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5507 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5510 prevchar = WORDCHAR_P (d - 1);
5511 thischar = WORDCHAR_P (d);
5512 if (prevchar != thischar)
5519 boolean prevchar, thischar;
5521 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5522 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5525 prevchar = WORDCHAR_P (d - 1);
5526 thischar = WORDCHAR_P (d);
5527 if (prevchar != thischar)
5534 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5535 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
5540 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5541 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
5542 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
5548 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5549 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
5554 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5555 if (PTR_CHAR_POS ((unsigned char *) d) != point)
5560 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5561 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
5566 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5571 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5575 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5577 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
5579 SET_REGS_MATCHED ();
5583 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5585 goto matchnotsyntax;
5588 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5592 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5594 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
5596 SET_REGS_MATCHED ();
5599 #else /* not emacs */
5601 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5603 if (!WORDCHAR_P (d))
5605 SET_REGS_MATCHED ();
5610 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5614 SET_REGS_MATCHED ();
5617 #endif /* not emacs */
5622 continue; /* Successfully executed one pattern command; keep going. */
5625 /* We goto here if a matching operation fails. */
5627 if (!FAIL_STACK_EMPTY ())
5628 { /* A restart point is known. Restore to that state. */
5629 DEBUG_PRINT1 ("\nFAIL:\n");
5630 POP_FAILURE_POINT (d, p,
5631 lowest_active_reg, highest_active_reg,
5632 regstart, regend, reg_info);
5634 /* If this failure point is a dummy, try the next one. */
5638 /* If we failed to the end of the pattern, don't examine *p. */
5642 boolean is_a_jump_n = false;
5644 /* If failed to a backwards jump that's part of a repetition
5645 loop, need to pop this failure point and use the next one. */
5646 switch ((re_opcode_t) *p)
5650 case maybe_pop_jump:
5651 case pop_failure_jump:
5654 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5657 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5659 && (re_opcode_t) *p1 == on_failure_jump))
5667 if (d >= string1 && d <= end1)
5671 break; /* Matching at this starting point really fails. */
5675 goto restore_best_regs;
5679 return -1; /* Failure to match. */
5682 /* Subroutine definitions for re_match_2. */
5685 /* We are passed P pointing to a register number after a start_memory.
5687 Return true if the pattern up to the corresponding stop_memory can
5688 match the empty string, and false otherwise.
5690 If we find the matching stop_memory, sets P to point to one past its number.
5691 Otherwise, sets P to an undefined byte less than or equal to END.
5693 We don't handle duplicates properly (yet). */
5696 group_match_null_string_p (p, end, reg_info)
5697 unsigned char **p, *end;
5698 register_info_type *reg_info;
5701 /* Point to after the args to the start_memory. */
5702 unsigned char *p1 = *p + 2;
5706 /* Skip over opcodes that can match nothing, and return true or
5707 false, as appropriate, when we get to one that can't, or to the
5708 matching stop_memory. */
5710 switch ((re_opcode_t) *p1)
5712 /* Could be either a loop or a series of alternatives. */
5713 case on_failure_jump:
5715 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5717 /* If the next operation is not a jump backwards in the
5722 /* Go through the on_failure_jumps of the alternatives,
5723 seeing if any of the alternatives cannot match nothing.
5724 The last alternative starts with only a jump,
5725 whereas the rest start with on_failure_jump and end
5726 with a jump, e.g., here is the pattern for `a|b|c':
5728 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5729 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5732 So, we have to first go through the first (n-1)
5733 alternatives and then deal with the last one separately. */
5736 /* Deal with the first (n-1) alternatives, which start
5737 with an on_failure_jump (see above) that jumps to right
5738 past a jump_past_alt. */
5740 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5742 /* `mcnt' holds how many bytes long the alternative
5743 is, including the ending `jump_past_alt' and
5746 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5750 /* Move to right after this alternative, including the
5754 /* Break if it's the beginning of an n-th alternative
5755 that doesn't begin with an on_failure_jump. */
5756 if ((re_opcode_t) *p1 != on_failure_jump)
5759 /* Still have to check that it's not an n-th
5760 alternative that starts with an on_failure_jump. */
5762 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5763 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5765 /* Get to the beginning of the n-th alternative. */
5771 /* Deal with the last alternative: go back and get number
5772 of the `jump_past_alt' just before it. `mcnt' contains
5773 the length of the alternative. */
5774 EXTRACT_NUMBER (mcnt, p1 - 2);
5776 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5779 p1 += mcnt; /* Get past the n-th alternative. */
5785 assert (p1[1] == **p);
5791 if (!common_op_match_null_string_p (&p1, end, reg_info))
5794 } /* while p1 < end */
5797 } /* group_match_null_string_p */
5800 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5801 It expects P to be the first byte of a single alternative and END one
5802 byte past the last. The alternative can contain groups. */
5805 alt_match_null_string_p (p, end, reg_info)
5806 unsigned char *p, *end;
5807 register_info_type *reg_info;
5810 unsigned char *p1 = p;
5814 /* Skip over opcodes that can match nothing, and break when we get
5815 to one that can't. */
5817 switch ((re_opcode_t) *p1)
5820 case on_failure_jump:
5822 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5827 if (!common_op_match_null_string_p (&p1, end, reg_info))
5830 } /* while p1 < end */
5833 } /* alt_match_null_string_p */
5836 /* Deals with the ops common to group_match_null_string_p and
5837 alt_match_null_string_p.
5839 Sets P to one after the op and its arguments, if any. */
5842 common_op_match_null_string_p (p, end, reg_info)
5843 unsigned char **p, *end;
5844 register_info_type *reg_info;
5849 unsigned char *p1 = *p;
5851 switch ((re_opcode_t) *p1++)
5871 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5872 ret = group_match_null_string_p (&p1, end, reg_info);
5874 /* Have to set this here in case we're checking a group which
5875 contains a group and a back reference to it. */
5877 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5878 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5884 /* If this is an optimized succeed_n for zero times, make the jump. */
5886 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5894 /* Get to the number of times to succeed. */
5896 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5901 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5909 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5917 /* All other opcodes mean we cannot match the empty string. */
5923 } /* common_op_match_null_string_p */
5926 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5927 bytes; nonzero otherwise. */
5930 bcmp_translate (s1, s2, len, translate)
5931 const char *s1, *s2;
5933 RE_TRANSLATE_TYPE translate;
5935 register const unsigned char *p1 = (const unsigned char *) s1;
5936 register const unsigned char *p2 = (const unsigned char *) s2;
5939 if (translate[*p1++] != translate[*p2++]) return 1;
5945 /* Entry points for GNU code. */
5947 /* re_compile_pattern is the GNU regular expression compiler: it
5948 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5949 Returns 0 if the pattern was valid, otherwise an error string.
5951 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5952 are set in BUFP on entry.
5954 We call regex_compile to do the actual compilation. */
5957 re_compile_pattern (pattern, length, bufp)
5958 const char *pattern;
5960 struct re_pattern_buffer *bufp;
5964 /* GNU code is written to assume at least RE_NREGS registers will be set
5965 (and at least one extra will be -1). */
5966 bufp->regs_allocated = REGS_UNALLOCATED;
5968 /* And GNU code determines whether or not to get register information
5969 by passing null for the REGS argument to re_match, etc., not by
5973 /* Match anchors at newline. */
5974 bufp->newline_anchor = 1;
5976 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5980 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
5983 weak_alias (__re_compile_pattern, re_compile_pattern)
5986 /* Entry points compatible with 4.2 BSD regex library. We don't define
5987 them unless specifically requested. */
5989 #if defined _REGEX_RE_COMP || defined _LIBC
5991 /* BSD has one and only one pattern buffer. */
5992 static struct re_pattern_buffer re_comp_buf;
5996 /* Make these definitions weak in libc, so POSIX programs can redefine
5997 these names if they don't use our functions, and still use
5998 regcomp/regexec below without link errors. */
6008 if (!re_comp_buf.buffer)
6009 return gettext ("No previous regular expression");
6013 if (!re_comp_buf.buffer)
6015 re_comp_buf.buffer = (unsigned char *) malloc (200);
6016 if (re_comp_buf.buffer == NULL)
6017 return (char *) gettext (re_error_msgid
6018 + re_error_msgid_idx[(int) REG_ESPACE]);
6019 re_comp_buf.allocated = 200;
6021 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6022 if (re_comp_buf.fastmap == NULL)
6023 return (char *) gettext (re_error_msgid
6024 + re_error_msgid_idx[(int) REG_ESPACE]);
6027 /* Since `re_exec' always passes NULL for the `regs' argument, we
6028 don't need to initialize the pattern buffer fields which affect it. */
6030 /* Match anchors at newlines. */
6031 re_comp_buf.newline_anchor = 1;
6033 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6038 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6039 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
6050 const int len = strlen (s);
6052 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6055 #endif /* _REGEX_RE_COMP */
6057 /* POSIX.2 functions. Don't define these for Emacs. */
6061 /* regcomp takes a regular expression as a string and compiles it.
6063 PREG is a regex_t *. We do not expect any fields to be initialized,
6064 since POSIX says we shouldn't. Thus, we set
6066 `buffer' to the compiled pattern;
6067 `used' to the length of the compiled pattern;
6068 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6069 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6070 RE_SYNTAX_POSIX_BASIC;
6071 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6072 `fastmap' to an allocated space for the fastmap;
6073 `fastmap_accurate' to zero;
6074 `re_nsub' to the number of subexpressions in PATTERN.
6076 PATTERN is the address of the pattern string.
6078 CFLAGS is a series of bits which affect compilation.
6080 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6081 use POSIX basic syntax.
6083 If REG_NEWLINE is set, then . and [^...] don't match newline.
6084 Also, regexec will try a match beginning after every newline.
6086 If REG_ICASE is set, then we considers upper- and lowercase
6087 versions of letters to be equivalent when matching.
6089 If REG_NOSUB is set, then when PREG is passed to regexec, that
6090 routine will report only success or failure, and nothing about the
6093 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6094 the return codes and their meanings.) */
6097 regcomp (preg, pattern, cflags)
6099 const char *pattern;
6104 = (cflags & REG_EXTENDED) ?
6105 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6107 /* regex_compile will allocate the space for the compiled pattern. */
6109 preg->allocated = 0;
6112 /* Try to allocate space for the fastmap. */
6113 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
6115 if (cflags & REG_ICASE)
6120 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6121 * sizeof (*(RE_TRANSLATE_TYPE)0));
6122 if (preg->translate == NULL)
6123 return (int) REG_ESPACE;
6125 /* Map uppercase characters to corresponding lowercase ones. */
6126 for (i = 0; i < CHAR_SET_SIZE; i++)
6127 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6130 preg->translate = NULL;
6132 /* If REG_NEWLINE is set, newlines are treated differently. */
6133 if (cflags & REG_NEWLINE)
6134 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6135 syntax &= ~RE_DOT_NEWLINE;
6136 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6137 /* It also changes the matching behavior. */
6138 preg->newline_anchor = 1;
6141 preg->newline_anchor = 0;
6143 preg->no_sub = !!(cflags & REG_NOSUB);
6145 /* POSIX says a null character in the pattern terminates it, so we
6146 can use strlen here in compiling the pattern. */
6147 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
6149 /* POSIX doesn't distinguish between an unmatched open-group and an
6150 unmatched close-group: both are REG_EPAREN. */
6151 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6153 if (ret == REG_NOERROR && preg->fastmap)
6155 /* Compute the fastmap now, since regexec cannot modify the pattern
6157 if (re_compile_fastmap (preg) == -2)
6159 /* Some error occurred while computing the fastmap, just forget
6161 free (preg->fastmap);
6162 preg->fastmap = NULL;
6169 weak_alias (__regcomp, regcomp)
6173 /* regexec searches for a given pattern, specified by PREG, in the
6176 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6177 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6178 least NMATCH elements, and we set them to the offsets of the
6179 corresponding matched substrings.
6181 EFLAGS specifies `execution flags' which affect matching: if
6182 REG_NOTBOL is set, then ^ does not match at the beginning of the
6183 string; if REG_NOTEOL is set, then $ does not match at the end.
6185 We return 0 if we find a match and REG_NOMATCH if not. */
6188 regexec (preg, string, nmatch, pmatch, eflags)
6189 const regex_t *preg;
6192 regmatch_t pmatch[];
6196 struct re_registers regs;
6197 regex_t private_preg;
6198 int len = strlen (string);
6199 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6201 private_preg = *preg;
6203 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6204 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6206 /* The user has told us exactly how many registers to return
6207 information about, via `nmatch'. We have to pass that on to the
6208 matching routines. */
6209 private_preg.regs_allocated = REGS_FIXED;
6213 regs.num_regs = nmatch;
6214 regs.start = TALLOC (nmatch * 2, regoff_t);
6215 if (regs.start == NULL)
6216 return (int) REG_NOMATCH;
6217 regs.end = regs.start + nmatch;
6220 /* Perform the searching operation. */
6221 ret = re_search (&private_preg, string, len,
6222 /* start: */ 0, /* range: */ len,
6223 want_reg_info ? ®s : (struct re_registers *) 0);
6225 /* Copy the register information to the POSIX structure. */
6232 for (r = 0; r < nmatch; r++)
6234 pmatch[r].rm_so = regs.start[r];
6235 pmatch[r].rm_eo = regs.end[r];
6239 /* If we needed the temporary register info, free the space now. */
6243 /* We want zero return to mean success, unlike `re_search'. */
6244 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6247 weak_alias (__regexec, regexec)
6251 /* Returns a message corresponding to an error code, ERRCODE, returned
6252 from either regcomp or regexec. We don't use PREG here. */
6255 regerror (errcode, preg, errbuf, errbuf_size)
6257 const regex_t *preg;
6265 || errcode >= (int) (sizeof (re_error_msgid_idx)
6266 / sizeof (re_error_msgid_idx[0])))
6267 /* Only error codes returned by the rest of the code should be passed
6268 to this routine. If we are given anything else, or if other regex
6269 code generates an invalid error code, then the program has a bug.
6270 Dump core so we can fix it. */
6273 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
6275 msg_size = strlen (msg) + 1; /* Includes the null. */
6277 if (errbuf_size != 0)
6279 if (msg_size > errbuf_size)
6281 #if defined HAVE_MEMPCPY || defined _LIBC
6282 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
6284 memcpy (errbuf, msg, errbuf_size - 1);
6285 errbuf[errbuf_size - 1] = 0;
6289 memcpy (errbuf, msg, msg_size);
6295 weak_alias (__regerror, regerror)
6299 /* Free dynamically allocated space used by PREG. */
6305 if (preg->buffer != NULL)
6306 free (preg->buffer);
6307 preg->buffer = NULL;
6309 preg->allocated = 0;
6312 if (preg->fastmap != NULL)
6313 free (preg->fastmap);
6314 preg->fastmap = NULL;
6315 preg->fastmap_accurate = 0;
6317 if (preg->translate != NULL)
6318 free (preg->translate);
6319 preg->translate = NULL;
6322 weak_alias (__regfree, regfree)
6325 #endif /* not emacs */
6326 #else /* !defined(USE_LIB_REGEX) */
6327 char regex_d1[] = "d"; char *regex_d2 = regex_d1;
6328 #endif /* defined(USE_LIB_REGEX) */