1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P1003.2/D11.2, except for some of the
4 internationalization features.)
5 Copyright (C) 1993-1999, 2000 Free Software Foundation, Inc.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined _AIX && !defined REGEX_MALLOC
35 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
36 # define PARAMS(args) args
38 # define PARAMS(args) ()
40 #endif /* Not PARAMS. */
42 #if defined STDC_HEADERS && !defined emacs
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
49 #define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
51 /* For platform which support the ISO C amendement 1 functionality we
52 support user defined character classes. */
53 #if defined _LIBC || WIDE_CHAR_SUPPORT
54 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
60 /* We have to keep the namespace clean. */
61 # define regfree(preg) __regfree (preg)
62 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
63 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
64 # define regerror(errcode, preg, errbuf, errbuf_size) \
65 __regerror(errcode, preg, errbuf, errbuf_size)
66 # define re_set_registers(bu, re, nu, st, en) \
67 __re_set_registers (bu, re, nu, st, en)
68 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
69 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
70 # define re_match(bufp, string, size, pos, regs) \
71 __re_match (bufp, string, size, pos, regs)
72 # define re_search(bufp, string, size, startpos, range, regs) \
73 __re_search (bufp, string, size, startpos, range, regs)
74 # define re_compile_pattern(pattern, length, bufp) \
75 __re_compile_pattern (pattern, length, bufp)
76 # define re_set_syntax(syntax) __re_set_syntax (syntax)
77 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
78 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
79 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
81 # define btowc __btowc
83 /* We are also using some library internals. */
84 # include <locale/localeinfo.h>
85 # include <locale/elem-hash.h>
86 # include <langinfo.h>
89 /* This is for other GNU distributions with internationalized messages. */
90 #if HAVE_LIBINTL_H || defined _LIBC
94 # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
97 # define gettext(msgid) (msgid)
101 /* This define is so xgettext can find the internationalizable
103 # define gettext_noop(String) String
106 /* The `emacs' switch turns on certain matching commands
107 that make sense only in Emacs. */
114 #else /* not emacs */
116 /* If we are not linking with Emacs proper,
117 we can't use the relocating allocator
118 even if config.h says that we can. */
121 # if defined STDC_HEADERS || defined _LIBC
128 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
129 If nothing else has been done, use the method below. */
130 # ifdef INHIBIT_STRING_HEADER
131 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
132 # if !defined bzero && !defined bcopy
133 # undef INHIBIT_STRING_HEADER
138 /* This is the normal way of making sure we have a bcopy and a bzero.
139 This is used in most programs--a few other programs avoid this
140 by defining INHIBIT_STRING_HEADER. */
141 # ifndef INHIBIT_STRING_HEADER
142 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
146 # define bzero(s, n) (memset (s, '\0', n), (s))
148 # define bzero(s, n) __bzero (s, n)
152 # include <strings.h>
154 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
157 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
162 /* Define the syntax stuff for \<, \>, etc. */
164 /* This must be nonzero for the wordchar and notwordchar pattern
165 commands in re_match_2. */
170 # ifdef SWITCH_ENUM_BUG
171 # define SWITCH_ENUM_CAST(x) ((int)(x))
173 # define SWITCH_ENUM_CAST(x) (x)
176 #endif /* not emacs */
178 #if defined _LIBC || HAVE_LIMITS_H
183 # define MB_LEN_MAX 1
186 /* Get the interface, including the syntax bits. */
189 /* isalpha etc. are used for the character classes. */
192 /* Jim Meyering writes:
194 "... Some ctype macros are valid only for character codes that
195 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
196 using /bin/cc or gcc but without giving an ansi option). So, all
197 ctype uses should be through macros like ISPRINT... If
198 STDC_HEADERS is defined, then autoconf has verified that the ctype
199 macros don't need to be guarded with references to isascii. ...
200 Defining isascii to 1 should let any compiler worth its salt
201 eliminate the && through constant folding."
202 Solaris defines some of these symbols so we must undefine them first. */
204 #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
205 # define IN_CTYPE_DOMAIN(c) 1
207 # define IN_CTYPE_DOMAIN(c) isascii(c)
211 # define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
213 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
216 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
218 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
222 #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
223 #define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
224 #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
225 #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
226 #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
227 #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
228 #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
229 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
230 #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
231 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
234 # define TOLOWER(c) _tolower(c)
236 # define TOLOWER(c) tolower(c)
240 # define NULL (void *)0
243 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
244 since ours (we hope) works properly with all combinations of
245 machines, compilers, `char' and `unsigned char' argument types.
246 (Per Bothner suggested the basic approach.) */
247 #undef SIGN_EXTEND_CHAR
249 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
250 #else /* not __STDC__ */
251 /* As in Harbison and Steele. */
252 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
256 /* How many characters in the character set. */
257 # define CHAR_SET_SIZE 256
261 extern char *re_syntax_table;
263 # else /* not SYNTAX_TABLE */
265 static char re_syntax_table[CHAR_SET_SIZE];
275 bzero (re_syntax_table, sizeof re_syntax_table);
277 for (c = 0; c < CHAR_SET_SIZE; ++c)
279 re_syntax_table[c] = Sword;
281 re_syntax_table['_'] = Sword;
286 # endif /* not SYNTAX_TABLE */
288 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
292 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
293 use `alloca' instead of `malloc'. This is because using malloc in
294 re_search* or re_match* could cause memory leaks when C-g is used in
295 Emacs; also, malloc is slower and causes storage fragmentation. On
296 the other hand, malloc is more portable, and easier to debug.
298 Because we sometimes use alloca, some routines have to be macros,
299 not functions -- `alloca'-allocated space disappears at the end of the
300 function it is called in. */
304 # define REGEX_ALLOCATE malloc
305 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
306 # define REGEX_FREE free
308 #else /* not REGEX_MALLOC */
310 /* Emacs already defines alloca, sometimes. */
313 /* Make alloca work the best possible way. */
315 # define alloca __builtin_alloca
316 # else /* not __GNUC__ */
319 # endif /* HAVE_ALLOCA_H */
320 # endif /* not __GNUC__ */
322 # endif /* not alloca */
324 # define REGEX_ALLOCATE alloca
326 /* Assumes a `char *destination' variable. */
327 # define REGEX_REALLOCATE(source, osize, nsize) \
328 (destination = (char *) alloca (nsize), \
329 memcpy (destination, source, osize))
331 /* No need to do anything to free, after alloca. */
332 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
334 #endif /* not REGEX_MALLOC */
336 /* Define how to allocate the failure stack. */
338 #if defined REL_ALLOC && defined REGEX_MALLOC
340 # define REGEX_ALLOCATE_STACK(size) \
341 r_alloc (&failure_stack_ptr, (size))
342 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
343 r_re_alloc (&failure_stack_ptr, (nsize))
344 # define REGEX_FREE_STACK(ptr) \
345 r_alloc_free (&failure_stack_ptr)
347 #else /* not using relocating allocator */
351 # define REGEX_ALLOCATE_STACK malloc
352 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
353 # define REGEX_FREE_STACK free
355 # else /* not REGEX_MALLOC */
357 # define REGEX_ALLOCATE_STACK alloca
359 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
360 REGEX_REALLOCATE (source, osize, nsize)
361 /* No need to explicitly free anything. */
362 # define REGEX_FREE_STACK(arg)
364 # endif /* not REGEX_MALLOC */
365 #endif /* not using relocating allocator */
368 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
369 `string1' or just past its end. This works if PTR is NULL, which is
371 #define FIRST_STRING_P(ptr) \
372 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
374 /* (Re)Allocate N items of type T using malloc, or fail. */
375 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
376 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
377 #define RETALLOC_IF(addr, n, t) \
378 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
379 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
381 #define BYTEWIDTH 8 /* In bits. */
383 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
387 #define MAX(a, b) ((a) > (b) ? (a) : (b))
388 #define MIN(a, b) ((a) < (b) ? (a) : (b))
390 typedef char boolean;
394 static int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
395 const char *string1, int size1,
396 const char *string2, int size2,
398 struct re_registers *regs,
401 /* These are the command codes that appear in compiled regular
402 expressions. Some opcodes are followed by argument bytes. A
403 command code can specify any interpretation whatsoever for its
404 arguments. Zero bytes may appear in the compiled regular expression. */
410 /* Succeed right away--no more backtracking. */
413 /* Followed by one byte giving n, then by n literal bytes. */
416 /* Matches any (more or less) character. */
419 /* Matches any one char belonging to specified set. First
420 following byte is number of bitmap bytes. Then come bytes
421 for a bitmap saying which chars are in. Bits in each byte
422 are ordered low-bit-first. A character is in the set if its
423 bit is 1. A character too large to have a bit in the map is
424 automatically not in the set. */
427 /* Same parameters as charset, but match any character that is
428 not one of those specified. */
431 /* Start remembering the text that is matched, for storing in a
432 register. Followed by one byte with the register number, in
433 the range 0 to one less than the pattern buffer's re_nsub
434 field. Then followed by one byte with the number of groups
435 inner to this one. (This last has to be part of the
436 start_memory only because we need it in the on_failure_jump
440 /* Stop remembering the text that is matched and store it in a
441 memory register. Followed by one byte with the register
442 number, in the range 0 to one less than `re_nsub' in the
443 pattern buffer, and one byte with the number of inner groups,
444 just like `start_memory'. (We need the number of inner
445 groups here because we don't have any easy way of finding the
446 corresponding start_memory when we're at a stop_memory.) */
449 /* Match a duplicate of something remembered. Followed by one
450 byte containing the register number. */
453 /* Fail unless at beginning of line. */
456 /* Fail unless at end of line. */
459 /* Succeeds if at beginning of buffer (if emacs) or at beginning
460 of string to be matched (if not). */
463 /* Analogously, for end of buffer/string. */
466 /* Followed by two byte relative address to which to jump. */
469 /* Same as jump, but marks the end of an alternative. */
472 /* Followed by two-byte relative address of place to resume at
473 in case of failure. */
476 /* Like on_failure_jump, but pushes a placeholder instead of the
477 current string position when executed. */
478 on_failure_keep_string_jump,
480 /* Throw away latest failure point and then jump to following
481 two-byte relative address. */
484 /* Change to pop_failure_jump if know won't have to backtrack to
485 match; otherwise change to jump. This is used to jump
486 back to the beginning of a repeat. If what follows this jump
487 clearly won't match what the repeat does, such that we can be
488 sure that there is no use backtracking out of repetitions
489 already matched, then we change it to a pop_failure_jump.
490 Followed by two-byte address. */
493 /* Jump to following two-byte address, and push a dummy failure
494 point. This failure point will be thrown away if an attempt
495 is made to use it for a failure. A `+' construct makes this
496 before the first repeat. Also used as an intermediary kind
497 of jump when compiling an alternative. */
500 /* Push a dummy failure point and continue. Used at the end of
504 /* Followed by two-byte relative address and two-byte number n.
505 After matching N times, jump to the address upon failure. */
508 /* Followed by two-byte relative address, and two-byte number n.
509 Jump to the address N times, then fail. */
512 /* Set the following two-byte relative address to the
513 subsequent two-byte number. The address *includes* the two
517 wordchar, /* Matches any word-constituent character. */
518 notwordchar, /* Matches any char that is not a word-constituent. */
520 wordbeg, /* Succeeds if at word beginning. */
521 wordend, /* Succeeds if at word end. */
523 wordbound, /* Succeeds if at a word boundary. */
524 notwordbound /* Succeeds if not at a word boundary. */
527 ,before_dot, /* Succeeds if before point. */
528 at_dot, /* Succeeds if at point. */
529 after_dot, /* Succeeds if after point. */
531 /* Matches any character whose syntax is specified. Followed by
532 a byte which contains a syntax code, e.g., Sword. */
535 /* Matches any character whose syntax is not that specified. */
540 /* Common operations on the compiled pattern. */
542 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
544 #define STORE_NUMBER(destination, number) \
546 (destination)[0] = (number) & 0377; \
547 (destination)[1] = (number) >> 8; \
550 /* Same as STORE_NUMBER, except increment DESTINATION to
551 the byte after where the number is stored. Therefore, DESTINATION
552 must be an lvalue. */
554 #define STORE_NUMBER_AND_INCR(destination, number) \
556 STORE_NUMBER (destination, number); \
557 (destination) += 2; \
560 /* Put into DESTINATION a number stored in two contiguous bytes starting
563 #define EXTRACT_NUMBER(destination, source) \
565 (destination) = *(source) & 0377; \
566 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
570 static void extract_number _RE_ARGS ((int *dest, unsigned char *source));
572 extract_number (dest, source)
574 unsigned char *source;
576 int temp = SIGN_EXTEND_CHAR (*(source + 1));
577 *dest = *source & 0377;
581 # ifndef EXTRACT_MACROS /* To debug the macros. */
582 # undef EXTRACT_NUMBER
583 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
584 # endif /* not EXTRACT_MACROS */
588 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
589 SOURCE must be an lvalue. */
591 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
593 EXTRACT_NUMBER (destination, source); \
598 static void extract_number_and_incr _RE_ARGS ((int *destination,
599 unsigned char **source));
601 extract_number_and_incr (destination, source)
603 unsigned char **source;
605 extract_number (destination, *source);
609 # ifndef EXTRACT_MACROS
610 # undef EXTRACT_NUMBER_AND_INCR
611 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
612 extract_number_and_incr (&dest, &src)
613 # endif /* not EXTRACT_MACROS */
617 /* If DEBUG is defined, Regex prints many voluminous messages about what
618 it is doing (if the variable `debug' is nonzero). If linked with the
619 main program in `iregex.c', you can enter patterns and strings
620 interactively. And if linked with the main program in `main.c' and
621 the other test files, you can run the already-written tests. */
625 /* We use standard I/O for debugging. */
628 /* It is useful to test things that ``must'' be true when debugging. */
633 # define DEBUG_STATEMENT(e) e
634 # define DEBUG_PRINT1(x) if (debug) printf (x)
635 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
636 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
637 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
638 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
639 if (debug) print_partial_compiled_pattern (s, e)
640 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
641 if (debug) print_double_string (w, s1, sz1, s2, sz2)
644 /* Print the fastmap in human-readable form. */
647 print_fastmap (fastmap)
650 unsigned was_a_range = 0;
653 while (i < (1 << BYTEWIDTH))
659 while (i < (1 << BYTEWIDTH) && fastmap[i])
675 /* Print a compiled pattern string in human-readable form, starting at
676 the START pointer into it and ending just before the pointer END. */
679 print_partial_compiled_pattern (start, end)
680 unsigned char *start;
685 unsigned char *p = start;
686 unsigned char *pend = end;
694 /* Loop over pattern commands. */
698 printf ("%t:\t", p - start);
700 printf ("%ld:\t", (long int) (p - start));
703 switch ((re_opcode_t) *p++)
711 printf ("/exactn/%d", mcnt);
722 printf ("/start_memory/%d/%d", mcnt, *p++);
727 printf ("/stop_memory/%d/%d", mcnt, *p++);
731 printf ("/duplicate/%d", *p++);
741 register int c, last = -100;
742 register int in_range = 0;
744 printf ("/charset [%s",
745 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
747 assert (p + *p < pend);
749 for (c = 0; c < 256; c++)
751 && (p[1 + (c/8)] & (1 << (c % 8))))
753 /* Are we starting a range? */
754 if (last + 1 == c && ! in_range)
759 /* Have we broken a range? */
760 else if (last + 1 != c && in_range)
789 case on_failure_jump:
790 extract_number_and_incr (&mcnt, &p);
792 printf ("/on_failure_jump to %t", p + mcnt - start);
794 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
798 case on_failure_keep_string_jump:
799 extract_number_and_incr (&mcnt, &p);
801 printf ("/on_failure_keep_string_jump to %t", p + mcnt - start);
803 printf ("/on_failure_keep_string_jump to %ld",
804 (long int) (p + mcnt - start));
808 case dummy_failure_jump:
809 extract_number_and_incr (&mcnt, &p);
811 printf ("/dummy_failure_jump to %t", p + mcnt - start);
813 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
817 case push_dummy_failure:
818 printf ("/push_dummy_failure");
822 extract_number_and_incr (&mcnt, &p);
824 printf ("/maybe_pop_jump to %t", p + mcnt - start);
826 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
830 case pop_failure_jump:
831 extract_number_and_incr (&mcnt, &p);
833 printf ("/pop_failure_jump to %t", p + mcnt - start);
835 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
840 extract_number_and_incr (&mcnt, &p);
842 printf ("/jump_past_alt to %t", p + mcnt - start);
844 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
849 extract_number_and_incr (&mcnt, &p);
851 printf ("/jump to %t", p + mcnt - start);
853 printf ("/jump to %ld", (long int) (p + mcnt - start));
858 extract_number_and_incr (&mcnt, &p);
860 extract_number_and_incr (&mcnt2, &p);
862 printf ("/succeed_n to %t, %d times", p1 - start, mcnt2);
864 printf ("/succeed_n to %ld, %d times",
865 (long int) (p1 - start), mcnt2);
870 extract_number_and_incr (&mcnt, &p);
872 extract_number_and_incr (&mcnt2, &p);
873 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
877 extract_number_and_incr (&mcnt, &p);
879 extract_number_and_incr (&mcnt2, &p);
881 printf ("/set_number_at location %t to %d", p1 - start, mcnt2);
883 printf ("/set_number_at location %ld to %d",
884 (long int) (p1 - start), mcnt2);
889 printf ("/wordbound");
893 printf ("/notwordbound");
905 printf ("/before_dot");
913 printf ("/after_dot");
917 printf ("/syntaxspec");
919 printf ("/%d", mcnt);
923 printf ("/notsyntaxspec");
925 printf ("/%d", mcnt);
930 printf ("/wordchar");
934 printf ("/notwordchar");
946 printf ("?%d", *(p-1));
953 printf ("%t:\tend of pattern.\n", p - start);
955 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
961 print_compiled_pattern (bufp)
962 struct re_pattern_buffer *bufp;
964 unsigned char *buffer = bufp->buffer;
966 print_partial_compiled_pattern (buffer, buffer + bufp->used);
967 printf ("%ld bytes used/%ld bytes allocated.\n",
968 bufp->used, bufp->allocated);
970 if (bufp->fastmap_accurate && bufp->fastmap)
972 printf ("fastmap: ");
973 print_fastmap (bufp->fastmap);
977 printf ("re_nsub: %Zd\t", bufp->re_nsub);
979 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
981 printf ("regs_alloc: %d\t", bufp->regs_allocated);
982 printf ("can_be_null: %d\t", bufp->can_be_null);
983 printf ("newline_anchor: %d\n", bufp->newline_anchor);
984 printf ("no_sub: %d\t", bufp->no_sub);
985 printf ("not_bol: %d\t", bufp->not_bol);
986 printf ("not_eol: %d\t", bufp->not_eol);
987 printf ("syntax: %lx\n", bufp->syntax);
988 /* Perhaps we should print the translate table? */
993 print_double_string (where, string1, size1, string2, size2)
1006 if (FIRST_STRING_P (where))
1008 for (this_char = where - string1; this_char < size1; this_char++)
1009 putchar (string1[this_char]);
1014 for (this_char = where - string2; this_char < size2; this_char++)
1015 putchar (string2[this_char]);
1026 #else /* not DEBUG */
1031 # define DEBUG_STATEMENT(e)
1032 # define DEBUG_PRINT1(x)
1033 # define DEBUG_PRINT2(x1, x2)
1034 # define DEBUG_PRINT3(x1, x2, x3)
1035 # define DEBUG_PRINT4(x1, x2, x3, x4)
1036 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1037 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1039 #endif /* not DEBUG */
1041 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1042 also be assigned to arbitrarily: each pattern buffer stores its own
1043 syntax, so it can be changed between regex compilations. */
1044 /* This has no initializer because initialized variables in Emacs
1045 become read-only after dumping. */
1046 reg_syntax_t re_syntax_options;
1049 /* Specify the precise syntax of regexps for compilation. This provides
1050 for compatibility for various utilities which historically have
1051 different, incompatible syntaxes.
1053 The argument SYNTAX is a bit mask comprised of the various bits
1054 defined in regex.h. We return the old syntax. */
1057 re_set_syntax (syntax)
1058 reg_syntax_t syntax;
1060 reg_syntax_t ret = re_syntax_options;
1062 re_syntax_options = syntax;
1064 if (syntax & RE_DEBUG)
1066 else if (debug) /* was on but now is not */
1072 weak_alias (__re_set_syntax, re_set_syntax)
1075 /* This table gives an error message for each of the error codes listed
1076 in regex.h. Obviously the order here has to be same as there.
1077 POSIX doesn't require that we do anything for REG_NOERROR,
1078 but why not be nice? */
1080 static const char re_error_msgid[] =
1082 #define REG_NOERROR_IDX 0
1083 gettext_noop ("Success") /* REG_NOERROR */
1085 #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1086 gettext_noop ("No match") /* REG_NOMATCH */
1088 #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1089 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1091 #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1092 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1094 #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1095 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1097 #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1098 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1100 #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1101 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1103 #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1104 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1106 #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1107 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1109 #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1110 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1112 #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1113 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1115 #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1116 gettext_noop ("Invalid range end") /* REG_ERANGE */
1118 #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1119 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1121 #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1122 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1124 #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1125 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1127 #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1128 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1130 #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1131 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1134 static const size_t re_error_msgid_idx[] =
1155 /* Avoiding alloca during matching, to placate r_alloc. */
1157 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1158 searching and matching functions should not call alloca. On some
1159 systems, alloca is implemented in terms of malloc, and if we're
1160 using the relocating allocator routines, then malloc could cause a
1161 relocation, which might (if the strings being searched are in the
1162 ralloc heap) shift the data out from underneath the regexp
1165 Here's another reason to avoid allocation: Emacs
1166 processes input from X in a signal handler; processing X input may
1167 call malloc; if input arrives while a matching routine is calling
1168 malloc, then we're scrod. But Emacs can't just block input while
1169 calling matching routines; then we don't notice interrupts when
1170 they come in. So, Emacs blocks input around all regexp calls
1171 except the matching calls, which it leaves unprotected, in the
1172 faith that they will not malloc. */
1174 /* Normally, this is fine. */
1175 #define MATCH_MAY_ALLOCATE
1177 /* When using GNU C, we are not REALLY using the C alloca, no matter
1178 what config.h may say. So don't take precautions for it. */
1183 /* The match routines may not allocate if (1) they would do it with malloc
1184 and (2) it's not safe for them to use malloc.
1185 Note that if REL_ALLOC is defined, matching would not use malloc for the
1186 failure stack, but we would still use it for the register vectors;
1187 so REL_ALLOC should not affect this. */
1188 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1189 # undef MATCH_MAY_ALLOCATE
1193 /* Failure stack declarations and macros; both re_compile_fastmap and
1194 re_match_2 use a failure stack. These have to be macros because of
1195 REGEX_ALLOCATE_STACK. */
1198 /* Number of failure points for which to initially allocate space
1199 when matching. If this number is exceeded, we allocate more
1200 space, so it is not a hard limit. */
1201 #ifndef INIT_FAILURE_ALLOC
1202 # define INIT_FAILURE_ALLOC 5
1205 /* Roughly the maximum number of failure points on the stack. Would be
1206 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1207 This is a variable only so users of regex can assign to it; we never
1208 change it ourselves. */
1212 # if defined MATCH_MAY_ALLOCATE
1213 /* 4400 was enough to cause a crash on Alpha OSF/1,
1214 whose default stack limit is 2mb. */
1215 long int re_max_failures = 4000;
1217 long int re_max_failures = 2000;
1220 union fail_stack_elt
1222 unsigned char *pointer;
1226 typedef union fail_stack_elt fail_stack_elt_t;
1230 fail_stack_elt_t *stack;
1231 unsigned long int size;
1232 unsigned long int avail; /* Offset of next open position. */
1235 #else /* not INT_IS_16BIT */
1237 # if defined MATCH_MAY_ALLOCATE
1238 /* 4400 was enough to cause a crash on Alpha OSF/1,
1239 whose default stack limit is 2mb. */
1240 int re_max_failures = 4000;
1242 int re_max_failures = 2000;
1245 union fail_stack_elt
1247 unsigned char *pointer;
1251 typedef union fail_stack_elt fail_stack_elt_t;
1255 fail_stack_elt_t *stack;
1257 unsigned avail; /* Offset of next open position. */
1260 #endif /* INT_IS_16BIT */
1262 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1263 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1264 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1267 /* Define macros to initialize and free the failure stack.
1268 Do `return -2' if the alloc fails. */
1270 #ifdef MATCH_MAY_ALLOCATE
1271 # define INIT_FAIL_STACK() \
1273 fail_stack.stack = (fail_stack_elt_t *) \
1274 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1276 if (fail_stack.stack == NULL) \
1279 fail_stack.size = INIT_FAILURE_ALLOC; \
1280 fail_stack.avail = 0; \
1283 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1285 # define INIT_FAIL_STACK() \
1287 fail_stack.avail = 0; \
1290 # define RESET_FAIL_STACK()
1294 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1296 Return 1 if succeeds, and 0 if either ran out of memory
1297 allocating space for it or it was already too large.
1299 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1301 #define DOUBLE_FAIL_STACK(fail_stack) \
1302 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1304 : ((fail_stack).stack = (fail_stack_elt_t *) \
1305 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1306 (fail_stack).size * sizeof (fail_stack_elt_t), \
1307 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1309 (fail_stack).stack == NULL \
1311 : ((fail_stack).size <<= 1, \
1315 /* Push pointer POINTER on FAIL_STACK.
1316 Return 1 if was able to do so and 0 if ran out of memory allocating
1318 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1319 ((FAIL_STACK_FULL () \
1320 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1322 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1325 /* Push a pointer value onto the failure stack.
1326 Assumes the variable `fail_stack'. Probably should only
1327 be called from within `PUSH_FAILURE_POINT'. */
1328 #define PUSH_FAILURE_POINTER(item) \
1329 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1331 /* This pushes an integer-valued item onto the failure stack.
1332 Assumes the variable `fail_stack'. Probably should only
1333 be called from within `PUSH_FAILURE_POINT'. */
1334 #define PUSH_FAILURE_INT(item) \
1335 fail_stack.stack[fail_stack.avail++].integer = (item)
1337 /* Push a fail_stack_elt_t value onto the failure stack.
1338 Assumes the variable `fail_stack'. Probably should only
1339 be called from within `PUSH_FAILURE_POINT'. */
1340 #define PUSH_FAILURE_ELT(item) \
1341 fail_stack.stack[fail_stack.avail++] = (item)
1343 /* These three POP... operations complement the three PUSH... operations.
1344 All assume that `fail_stack' is nonempty. */
1345 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1346 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1347 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1349 /* Used to omit pushing failure point id's when we're not debugging. */
1351 # define DEBUG_PUSH PUSH_FAILURE_INT
1352 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1354 # define DEBUG_PUSH(item)
1355 # define DEBUG_POP(item_addr)
1359 /* Push the information about the state we will need
1360 if we ever fail back to it.
1362 Requires variables fail_stack, regstart, regend, reg_info, and
1363 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1366 Does `return FAILURE_CODE' if runs out of memory. */
1368 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1370 char *destination; \
1371 /* Must be int, so when we don't save any registers, the arithmetic \
1372 of 0 + -1 isn't done as unsigned. */ \
1373 /* Can't be int, since there is not a shred of a guarantee that int \
1374 is wide enough to hold a value of something to which pointer can \
1376 active_reg_t this_reg; \
1378 DEBUG_STATEMENT (failure_id++); \
1379 DEBUG_STATEMENT (nfailure_points_pushed++); \
1380 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1381 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1382 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1384 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1385 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1387 /* Ensure we have enough space allocated for what we will push. */ \
1388 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1390 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1391 return failure_code; \
1393 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1394 (fail_stack).size); \
1395 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1398 /* Push the info, starting with the registers. */ \
1399 DEBUG_PRINT1 ("\n"); \
1402 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1405 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1406 DEBUG_STATEMENT (num_regs_pushed++); \
1408 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1409 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1411 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1412 PUSH_FAILURE_POINTER (regend[this_reg]); \
1414 DEBUG_PRINT2 (" info: %p\n ", \
1415 reg_info[this_reg].word.pointer); \
1416 DEBUG_PRINT2 (" match_null=%d", \
1417 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1418 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1419 DEBUG_PRINT2 (" matched_something=%d", \
1420 MATCHED_SOMETHING (reg_info[this_reg])); \
1421 DEBUG_PRINT2 (" ever_matched=%d", \
1422 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1423 DEBUG_PRINT1 ("\n"); \
1424 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1427 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1428 PUSH_FAILURE_INT (lowest_active_reg); \
1430 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1431 PUSH_FAILURE_INT (highest_active_reg); \
1433 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1434 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1435 PUSH_FAILURE_POINTER (pattern_place); \
1437 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1438 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1440 DEBUG_PRINT1 ("'\n"); \
1441 PUSH_FAILURE_POINTER (string_place); \
1443 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1444 DEBUG_PUSH (failure_id); \
1447 /* This is the number of items that are pushed and popped on the stack
1448 for each register. */
1449 #define NUM_REG_ITEMS 3
1451 /* Individual items aside from the registers. */
1453 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1455 # define NUM_NONREG_ITEMS 4
1458 /* We push at most this many items on the stack. */
1459 /* We used to use (num_regs - 1), which is the number of registers
1460 this regexp will save; but that was changed to 5
1461 to avoid stack overflow for a regexp with lots of parens. */
1462 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1464 /* We actually push this many items. */
1465 #define NUM_FAILURE_ITEMS \
1467 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1471 /* How many items can still be added to the stack without overflowing it. */
1472 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1475 /* Pops what PUSH_FAIL_STACK pushes.
1477 We restore into the parameters, all of which should be lvalues:
1478 STR -- the saved data position.
1479 PAT -- the saved pattern position.
1480 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1481 REGSTART, REGEND -- arrays of string positions.
1482 REG_INFO -- array of information about each subexpression.
1484 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1485 `pend', `string1', `size1', `string2', and `size2'. */
1487 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1489 DEBUG_STATEMENT (unsigned failure_id;) \
1490 active_reg_t this_reg; \
1491 const unsigned char *string_temp; \
1493 assert (!FAIL_STACK_EMPTY ()); \
1495 /* Remove failure points and point to how many regs pushed. */ \
1496 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1497 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1498 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1500 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1502 DEBUG_POP (&failure_id); \
1503 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1505 /* If the saved string location is NULL, it came from an \
1506 on_failure_keep_string_jump opcode, and we want to throw away the \
1507 saved NULL, thus retaining our current position in the string. */ \
1508 string_temp = POP_FAILURE_POINTER (); \
1509 if (string_temp != NULL) \
1510 str = (const char *) string_temp; \
1512 DEBUG_PRINT2 (" Popping string %p: `", str); \
1513 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1514 DEBUG_PRINT1 ("'\n"); \
1516 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1517 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1518 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1520 /* Restore register info. */ \
1521 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1522 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1524 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1525 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1528 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1530 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1532 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1533 DEBUG_PRINT2 (" info: %p\n", \
1534 reg_info[this_reg].word.pointer); \
1536 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1537 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1539 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1540 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1544 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1546 reg_info[this_reg].word.integer = 0; \
1547 regend[this_reg] = 0; \
1548 regstart[this_reg] = 0; \
1550 highest_active_reg = high_reg; \
1553 set_regs_matched_done = 0; \
1554 DEBUG_STATEMENT (nfailure_points_popped++); \
1555 } /* POP_FAILURE_POINT */
1559 /* Structure for per-register (a.k.a. per-group) information.
1560 Other register information, such as the
1561 starting and ending positions (which are addresses), and the list of
1562 inner groups (which is a bits list) are maintained in separate
1565 We are making a (strictly speaking) nonportable assumption here: that
1566 the compiler will pack our bit fields into something that fits into
1567 the type of `word', i.e., is something that fits into one item on the
1571 /* Declarations and macros for re_match_2. */
1575 fail_stack_elt_t word;
1578 /* This field is one if this group can match the empty string,
1579 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1580 #define MATCH_NULL_UNSET_VALUE 3
1581 unsigned match_null_string_p : 2;
1582 unsigned is_active : 1;
1583 unsigned matched_something : 1;
1584 unsigned ever_matched_something : 1;
1586 } register_info_type;
1588 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1589 #define IS_ACTIVE(R) ((R).bits.is_active)
1590 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1591 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1594 /* Call this when have matched a real character; it sets `matched' flags
1595 for the subexpressions which we are currently inside. Also records
1596 that those subexprs have matched. */
1597 #define SET_REGS_MATCHED() \
1600 if (!set_regs_matched_done) \
1603 set_regs_matched_done = 1; \
1604 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1606 MATCHED_SOMETHING (reg_info[r]) \
1607 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1614 /* Registers are set to a sentinel when they haven't yet matched. */
1615 static char reg_unset_dummy;
1616 #define REG_UNSET_VALUE (®_unset_dummy)
1617 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1619 /* Subroutine declarations and macros for regex_compile. */
1621 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1622 reg_syntax_t syntax,
1623 struct re_pattern_buffer *bufp));
1624 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1625 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1626 int arg1, int arg2));
1627 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1628 int arg, unsigned char *end));
1629 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1630 int arg1, int arg2, unsigned char *end));
1631 static boolean at_begline_loc_p _RE_ARGS ((const char *pattern, const char *p,
1632 reg_syntax_t syntax));
1633 static boolean at_endline_loc_p _RE_ARGS ((const char *p, const char *pend,
1634 reg_syntax_t syntax));
1635 static reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
1639 reg_syntax_t syntax,
1642 /* Fetch the next character in the uncompiled pattern---translating it
1643 if necessary. Also cast from a signed character in the constant
1644 string passed to us by the user to an unsigned char that we can use
1645 as an array index (in, e.g., `translate'). */
1647 # define PATFETCH(c) \
1648 do {if (p == pend) return REG_EEND; \
1649 c = (unsigned char) *p++; \
1650 if (translate) c = (unsigned char) translate[c]; \
1654 /* Fetch the next character in the uncompiled pattern, with no
1656 #define PATFETCH_RAW(c) \
1657 do {if (p == pend) return REG_EEND; \
1658 c = (unsigned char) *p++; \
1661 /* Go backwards one character in the pattern. */
1662 #define PATUNFETCH p--
1665 /* If `translate' is non-null, return translate[D], else just D. We
1666 cast the subscript to translate because some data is declared as
1667 `char *', to avoid warnings when a string constant is passed. But
1668 when we use a character as a subscript we must make it unsigned. */
1670 # define TRANSLATE(d) \
1671 (translate ? (char) translate[(unsigned char) (d)] : (d))
1675 /* Macros for outputting the compiled pattern into `buffer'. */
1677 /* If the buffer isn't allocated when it comes in, use this. */
1678 #define INIT_BUF_SIZE 32
1680 /* Make sure we have at least N more bytes of space in buffer. */
1681 #define GET_BUFFER_SPACE(n) \
1682 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1685 /* Make sure we have one more byte of buffer space and then add C to it. */
1686 #define BUF_PUSH(c) \
1688 GET_BUFFER_SPACE (1); \
1689 *b++ = (unsigned char) (c); \
1693 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1694 #define BUF_PUSH_2(c1, c2) \
1696 GET_BUFFER_SPACE (2); \
1697 *b++ = (unsigned char) (c1); \
1698 *b++ = (unsigned char) (c2); \
1702 /* As with BUF_PUSH_2, except for three bytes. */
1703 #define BUF_PUSH_3(c1, c2, c3) \
1705 GET_BUFFER_SPACE (3); \
1706 *b++ = (unsigned char) (c1); \
1707 *b++ = (unsigned char) (c2); \
1708 *b++ = (unsigned char) (c3); \
1712 /* Store a jump with opcode OP at LOC to location TO. We store a
1713 relative address offset by the three bytes the jump itself occupies. */
1714 #define STORE_JUMP(op, loc, to) \
1715 store_op1 (op, loc, (int) ((to) - (loc) - 3))
1717 /* Likewise, for a two-argument jump. */
1718 #define STORE_JUMP2(op, loc, to, arg) \
1719 store_op2 (op, loc, (int) ((to) - (loc) - 3), arg)
1721 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1722 #define INSERT_JUMP(op, loc, to) \
1723 insert_op1 (op, loc, (int) ((to) - (loc) - 3), b)
1725 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1726 #define INSERT_JUMP2(op, loc, to, arg) \
1727 insert_op2 (op, loc, (int) ((to) - (loc) - 3), arg, b)
1730 /* This is not an arbitrary limit: the arguments which represent offsets
1731 into the pattern are two bytes long. So if 2^16 bytes turns out to
1732 be too small, many things would have to change. */
1733 /* Any other compiler which, like MSC, has allocation limit below 2^16
1734 bytes will have to use approach similar to what was done below for
1735 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1736 reallocating to 0 bytes. Such thing is not going to work too well.
1737 You have been warned!! */
1738 #if defined _MSC_VER && !defined WIN32
1739 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1740 The REALLOC define eliminates a flurry of conversion warnings,
1741 but is not required. */
1742 # define MAX_BUF_SIZE 65500L
1743 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1745 # define MAX_BUF_SIZE (1L << 16)
1746 # define REALLOC(p,s) realloc ((p), (s))
1749 /* Extend the buffer by twice its current size via realloc and
1750 reset the pointers that pointed into the old block to point to the
1751 correct places in the new one. If extending the buffer results in it
1752 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1753 #if __BOUNDED_POINTERS__
1754 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1755 # define MOVE_BUFFER_POINTER(P) \
1756 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1757 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1760 SET_HIGH_BOUND (b); \
1761 SET_HIGH_BOUND (begalt); \
1762 if (fixup_alt_jump) \
1763 SET_HIGH_BOUND (fixup_alt_jump); \
1765 SET_HIGH_BOUND (laststart); \
1766 if (pending_exact) \
1767 SET_HIGH_BOUND (pending_exact); \
1770 # define MOVE_BUFFER_POINTER(P) (P) += incr
1771 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1773 #define EXTEND_BUFFER() \
1775 unsigned char *old_buffer = bufp->buffer; \
1776 if (bufp->allocated == MAX_BUF_SIZE) \
1778 bufp->allocated <<= 1; \
1779 if (bufp->allocated > MAX_BUF_SIZE) \
1780 bufp->allocated = MAX_BUF_SIZE; \
1781 bufp->buffer = (unsigned char *) REALLOC (bufp->buffer, bufp->allocated);\
1782 if (bufp->buffer == NULL) \
1783 return REG_ESPACE; \
1784 /* If the buffer moved, move all the pointers into it. */ \
1785 if (old_buffer != bufp->buffer) \
1787 int incr = bufp->buffer - old_buffer; \
1788 MOVE_BUFFER_POINTER (b); \
1789 MOVE_BUFFER_POINTER (begalt); \
1790 if (fixup_alt_jump) \
1791 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1793 MOVE_BUFFER_POINTER (laststart); \
1794 if (pending_exact) \
1795 MOVE_BUFFER_POINTER (pending_exact); \
1797 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1801 /* Since we have one byte reserved for the register number argument to
1802 {start,stop}_memory, the maximum number of groups we can report
1803 things about is what fits in that byte. */
1804 #define MAX_REGNUM 255
1806 /* But patterns can have more than `MAX_REGNUM' registers. We just
1807 ignore the excess. */
1808 typedef unsigned regnum_t;
1811 /* Macros for the compile stack. */
1813 /* Since offsets can go either forwards or backwards, this type needs to
1814 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1815 /* int may be not enough when sizeof(int) == 2. */
1816 typedef long pattern_offset_t;
1820 pattern_offset_t begalt_offset;
1821 pattern_offset_t fixup_alt_jump;
1822 pattern_offset_t inner_group_offset;
1823 pattern_offset_t laststart_offset;
1825 } compile_stack_elt_t;
1830 compile_stack_elt_t *stack;
1832 unsigned avail; /* Offset of next open position. */
1833 } compile_stack_type;
1836 #define INIT_COMPILE_STACK_SIZE 32
1838 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1839 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1841 /* The next available element. */
1842 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1845 /* Set the bit for character C in a list. */
1846 #define SET_LIST_BIT(c) \
1847 (b[((unsigned char) (c)) / BYTEWIDTH] \
1848 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1851 /* Get the next unsigned number in the uncompiled pattern. */
1852 #define GET_UNSIGNED_NUMBER(num) \
1856 while ('0' <= c && c <= '9') \
1860 num = num * 10 + c - '0'; \
1868 #if defined _LIBC || WIDE_CHAR_SUPPORT
1869 /* The GNU C library provides support for user-defined character classes
1870 and the functions from ISO C amendement 1. */
1871 # ifdef CHARCLASS_NAME_MAX
1872 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1874 /* This shouldn't happen but some implementation might still have this
1875 problem. Use a reasonable default value. */
1876 # define CHAR_CLASS_MAX_LENGTH 256
1880 # define IS_CHAR_CLASS(string) __wctype (string)
1882 # define IS_CHAR_CLASS(string) wctype (string)
1885 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1887 # define IS_CHAR_CLASS(string) \
1888 (STREQ (string, "alpha") || STREQ (string, "upper") \
1889 || STREQ (string, "lower") || STREQ (string, "digit") \
1890 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1891 || STREQ (string, "space") || STREQ (string, "print") \
1892 || STREQ (string, "punct") || STREQ (string, "graph") \
1893 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1896 #ifndef MATCH_MAY_ALLOCATE
1898 /* If we cannot allocate large objects within re_match_2_internal,
1899 we make the fail stack and register vectors global.
1900 The fail stack, we grow to the maximum size when a regexp
1902 The register vectors, we adjust in size each time we
1903 compile a regexp, according to the number of registers it needs. */
1905 static fail_stack_type fail_stack;
1907 /* Size with which the following vectors are currently allocated.
1908 That is so we can make them bigger as needed,
1909 but never make them smaller. */
1910 static int regs_allocated_size;
1912 static const char ** regstart, ** regend;
1913 static const char ** old_regstart, ** old_regend;
1914 static const char **best_regstart, **best_regend;
1915 static register_info_type *reg_info;
1916 static const char **reg_dummy;
1917 static register_info_type *reg_info_dummy;
1919 /* Make the register vectors big enough for NUM_REGS registers,
1920 but don't make them smaller. */
1923 regex_grow_registers (num_regs)
1926 if (num_regs > regs_allocated_size)
1928 RETALLOC_IF (regstart, num_regs, const char *);
1929 RETALLOC_IF (regend, num_regs, const char *);
1930 RETALLOC_IF (old_regstart, num_regs, const char *);
1931 RETALLOC_IF (old_regend, num_regs, const char *);
1932 RETALLOC_IF (best_regstart, num_regs, const char *);
1933 RETALLOC_IF (best_regend, num_regs, const char *);
1934 RETALLOC_IF (reg_info, num_regs, register_info_type);
1935 RETALLOC_IF (reg_dummy, num_regs, const char *);
1936 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1938 regs_allocated_size = num_regs;
1942 #endif /* not MATCH_MAY_ALLOCATE */
1944 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
1948 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1949 Returns one of error codes defined in `regex.h', or zero for success.
1951 Assumes the `allocated' (and perhaps `buffer') and `translate'
1952 fields are set in BUFP on entry.
1954 If it succeeds, results are put in BUFP (if it returns an error, the
1955 contents of BUFP are undefined):
1956 `buffer' is the compiled pattern;
1957 `syntax' is set to SYNTAX;
1958 `used' is set to the length of the compiled pattern;
1959 `fastmap_accurate' is zero;
1960 `re_nsub' is the number of subexpressions in PATTERN;
1961 `not_bol' and `not_eol' are zero;
1963 The `fastmap' and `newline_anchor' fields are neither
1964 examined nor set. */
1966 /* Return, freeing storage we allocated. */
1967 #define FREE_STACK_RETURN(value) \
1968 return (free (compile_stack.stack), value)
1970 static reg_errcode_t
1971 regex_compile (pattern, size, syntax, bufp)
1972 const char *pattern;
1974 reg_syntax_t syntax;
1975 struct re_pattern_buffer *bufp;
1977 /* We fetch characters from PATTERN here. Even though PATTERN is
1978 `char *' (i.e., signed), we declare these variables as unsigned, so
1979 they can be reliably used as array indices. */
1980 register unsigned char c, c1;
1982 /* A random temporary spot in PATTERN. */
1985 /* Points to the end of the buffer, where we should append. */
1986 register unsigned char *b;
1988 /* Keeps track of unclosed groups. */
1989 compile_stack_type compile_stack;
1991 /* Points to the current (ending) position in the pattern. */
1992 const char *p = pattern;
1993 const char *pend = pattern + size;
1995 /* How to translate the characters in the pattern. */
1996 RE_TRANSLATE_TYPE translate = bufp->translate;
1998 /* Address of the count-byte of the most recently inserted `exactn'
1999 command. This makes it possible to tell if a new exact-match
2000 character can be added to that command or if the character requires
2001 a new `exactn' command. */
2002 unsigned char *pending_exact = 0;
2004 /* Address of start of the most recently finished expression.
2005 This tells, e.g., postfix * where to find the start of its
2006 operand. Reset at the beginning of groups and alternatives. */
2007 unsigned char *laststart = 0;
2009 /* Address of beginning of regexp, or inside of last group. */
2010 unsigned char *begalt;
2012 /* Place in the uncompiled pattern (i.e., the {) to
2013 which to go back if the interval is invalid. */
2014 const char *beg_interval;
2016 /* Address of the place where a forward jump should go to the end of
2017 the containing expression. Each alternative of an `or' -- except the
2018 last -- ends with a forward jump of this sort. */
2019 unsigned char *fixup_alt_jump = 0;
2021 /* Counts open-groups as they are encountered. Remembered for the
2022 matching close-group on the compile stack, so the same register
2023 number is put in the stop_memory as the start_memory. */
2024 regnum_t regnum = 0;
2027 DEBUG_PRINT1 ("\nCompiling pattern: ");
2030 unsigned debug_count;
2032 for (debug_count = 0; debug_count < size; debug_count++)
2033 putchar (pattern[debug_count]);
2038 /* Initialize the compile stack. */
2039 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2040 if (compile_stack.stack == NULL)
2043 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2044 compile_stack.avail = 0;
2046 /* Initialize the pattern buffer. */
2047 bufp->syntax = syntax;
2048 bufp->fastmap_accurate = 0;
2049 bufp->not_bol = bufp->not_eol = 0;
2051 /* Set `used' to zero, so that if we return an error, the pattern
2052 printer (for debugging) will think there's no pattern. We reset it
2056 /* Always count groups, whether or not bufp->no_sub is set. */
2059 #if !defined emacs && !defined SYNTAX_TABLE
2060 /* Initialize the syntax table. */
2061 init_syntax_once ();
2064 if (bufp->allocated == 0)
2067 { /* If zero allocated, but buffer is non-null, try to realloc
2068 enough space. This loses if buffer's address is bogus, but
2069 that is the user's responsibility. */
2070 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2073 { /* Caller did not allocate a buffer. Do it for them. */
2074 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2076 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2078 bufp->allocated = INIT_BUF_SIZE;
2081 begalt = b = bufp->buffer;
2083 /* Loop through the uncompiled pattern until we're at the end. */
2092 if ( /* If at start of pattern, it's an operator. */
2094 /* If context independent, it's an operator. */
2095 || syntax & RE_CONTEXT_INDEP_ANCHORS
2096 /* Otherwise, depends on what's come before. */
2097 || at_begline_loc_p (pattern, p, syntax))
2107 if ( /* If at end of pattern, it's an operator. */
2109 /* If context independent, it's an operator. */
2110 || syntax & RE_CONTEXT_INDEP_ANCHORS
2111 /* Otherwise, depends on what's next. */
2112 || at_endline_loc_p (p, pend, syntax))
2122 if ((syntax & RE_BK_PLUS_QM)
2123 || (syntax & RE_LIMITED_OPS))
2127 /* If there is no previous pattern... */
2130 if (syntax & RE_CONTEXT_INVALID_OPS)
2131 FREE_STACK_RETURN (REG_BADRPT);
2132 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2137 /* Are we optimizing this jump? */
2138 boolean keep_string_p = false;
2140 /* 1 means zero (many) matches is allowed. */
2141 char zero_times_ok = 0, many_times_ok = 0;
2143 /* If there is a sequence of repetition chars, collapse it
2144 down to just one (the right one). We can't combine
2145 interval operators with these because of, e.g., `a{2}*',
2146 which should only match an even number of `a's. */
2150 zero_times_ok |= c != '+';
2151 many_times_ok |= c != '?';
2159 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2162 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2164 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2167 if (!(c1 == '+' || c1 == '?'))
2182 /* If we get here, we found another repeat character. */
2185 /* Star, etc. applied to an empty pattern is equivalent
2186 to an empty pattern. */
2190 /* Now we know whether or not zero matches is allowed
2191 and also whether or not two or more matches is allowed. */
2193 { /* More than one repetition is allowed, so put in at the
2194 end a backward relative jump from `b' to before the next
2195 jump we're going to put in below (which jumps from
2196 laststart to after this jump).
2198 But if we are at the `*' in the exact sequence `.*\n',
2199 insert an unconditional jump backwards to the .,
2200 instead of the beginning of the loop. This way we only
2201 push a failure point once, instead of every time
2202 through the loop. */
2203 assert (p - 1 > pattern);
2205 /* Allocate the space for the jump. */
2206 GET_BUFFER_SPACE (3);
2208 /* We know we are not at the first character of the pattern,
2209 because laststart was nonzero. And we've already
2210 incremented `p', by the way, to be the character after
2211 the `*'. Do we have to do something analogous here
2212 for null bytes, because of RE_DOT_NOT_NULL? */
2213 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2215 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2216 && !(syntax & RE_DOT_NEWLINE))
2217 { /* We have .*\n. */
2218 STORE_JUMP (jump, b, laststart);
2219 keep_string_p = true;
2222 /* Anything else. */
2223 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2225 /* We've added more stuff to the buffer. */
2229 /* On failure, jump from laststart to b + 3, which will be the
2230 end of the buffer after this jump is inserted. */
2231 GET_BUFFER_SPACE (3);
2232 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2240 /* At least one repetition is required, so insert a
2241 `dummy_failure_jump' before the initial
2242 `on_failure_jump' instruction of the loop. This
2243 effects a skip over that instruction the first time
2244 we hit that loop. */
2245 GET_BUFFER_SPACE (3);
2246 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2261 boolean had_char_class = false;
2262 unsigned int range_start = 0xffffffff;
2264 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2266 /* Ensure that we have enough space to push a charset: the
2267 opcode, the length count, and the bitset; 34 bytes in all. */
2268 GET_BUFFER_SPACE (34);
2272 /* We test `*p == '^' twice, instead of using an if
2273 statement, so we only need one BUF_PUSH. */
2274 BUF_PUSH (*p == '^' ? charset_not : charset);
2278 /* Remember the first position in the bracket expression. */
2281 /* Push the number of bytes in the bitmap. */
2282 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2284 /* Clear the whole map. */
2285 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2287 /* charset_not matches newline according to a syntax bit. */
2288 if ((re_opcode_t) b[-2] == charset_not
2289 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2290 SET_LIST_BIT ('\n');
2292 /* Read in characters and ranges, setting map bits. */
2295 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2299 /* \ might escape characters inside [...] and [^...]. */
2300 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2302 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2310 /* Could be the end of the bracket expression. If it's
2311 not (i.e., when the bracket expression is `[]' so
2312 far), the ']' character bit gets set way below. */
2313 if (c == ']' && p != p1 + 1)
2316 /* Look ahead to see if it's a range when the last thing
2317 was a character class. */
2318 if (had_char_class && c == '-' && *p != ']')
2319 FREE_STACK_RETURN (REG_ERANGE);
2321 /* Look ahead to see if it's a range when the last thing
2322 was a character: if this is a hyphen not at the
2323 beginning or the end of a list, then it's the range
2326 && !(p - 2 >= pattern && p[-2] == '[')
2327 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2331 = compile_range (range_start, &p, pend, translate,
2333 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2334 range_start = 0xffffffff;
2337 else if (p[0] == '-' && p[1] != ']')
2338 { /* This handles ranges made up of characters only. */
2341 /* Move past the `-'. */
2344 ret = compile_range (c, &p, pend, translate, syntax, b);
2345 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2346 range_start = 0xffffffff;
2349 /* See if we're at the beginning of a possible character
2352 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2353 { /* Leave room for the null. */
2354 char str[CHAR_CLASS_MAX_LENGTH + 1];
2359 /* If pattern is `[[:'. */
2360 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2365 if ((c == ':' && *p == ']') || p == pend)
2367 if (c1 < CHAR_CLASS_MAX_LENGTH)
2370 /* This is in any case an invalid class name. */
2375 /* If isn't a word bracketed by `[:' and `:]':
2376 undo the ending character, the letters, and leave
2377 the leading `:' and `[' (but set bits for them). */
2378 if (c == ':' && *p == ']')
2380 #if defined _LIBC || WIDE_CHAR_SUPPORT
2381 boolean is_lower = STREQ (str, "lower");
2382 boolean is_upper = STREQ (str, "upper");
2386 wt = IS_CHAR_CLASS (str);
2388 FREE_STACK_RETURN (REG_ECTYPE);
2390 /* Throw away the ] at the end of the character
2394 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2396 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
2399 if (__iswctype (__btowc (ch), wt))
2402 if (iswctype (btowc (ch), wt))
2406 if (translate && (is_upper || is_lower)
2407 && (ISUPPER (ch) || ISLOWER (ch)))
2411 had_char_class = true;
2414 boolean is_alnum = STREQ (str, "alnum");
2415 boolean is_alpha = STREQ (str, "alpha");
2416 boolean is_blank = STREQ (str, "blank");
2417 boolean is_cntrl = STREQ (str, "cntrl");
2418 boolean is_digit = STREQ (str, "digit");
2419 boolean is_graph = STREQ (str, "graph");
2420 boolean is_lower = STREQ (str, "lower");
2421 boolean is_print = STREQ (str, "print");
2422 boolean is_punct = STREQ (str, "punct");
2423 boolean is_space = STREQ (str, "space");
2424 boolean is_upper = STREQ (str, "upper");
2425 boolean is_xdigit = STREQ (str, "xdigit");
2427 if (!IS_CHAR_CLASS (str))
2428 FREE_STACK_RETURN (REG_ECTYPE);
2430 /* Throw away the ] at the end of the character
2434 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2436 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2438 /* This was split into 3 if's to
2439 avoid an arbitrary limit in some compiler. */
2440 if ( (is_alnum && ISALNUM (ch))
2441 || (is_alpha && ISALPHA (ch))
2442 || (is_blank && ISBLANK (ch))
2443 || (is_cntrl && ISCNTRL (ch)))
2445 if ( (is_digit && ISDIGIT (ch))
2446 || (is_graph && ISGRAPH (ch))
2447 || (is_lower && ISLOWER (ch))
2448 || (is_print && ISPRINT (ch)))
2450 if ( (is_punct && ISPUNCT (ch))
2451 || (is_space && ISSPACE (ch))
2452 || (is_upper && ISUPPER (ch))
2453 || (is_xdigit && ISXDIGIT (ch)))
2455 if ( translate && (is_upper || is_lower)
2456 && (ISUPPER (ch) || ISLOWER (ch)))
2459 had_char_class = true;
2460 #endif /* libc || wctype.h */
2470 had_char_class = false;
2473 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
2475 unsigned char str[MB_LEN_MAX + 1];
2478 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2484 /* If pattern is `[[='. */
2485 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2490 if ((c == '=' && *p == ']') || p == pend)
2492 if (c1 < MB_LEN_MAX)
2495 /* This is in any case an invalid class name. */
2500 if (c == '=' && *p == ']' && str[0] != '\0')
2502 /* If we have no collation data we use the default
2503 collation in which each character is in a class
2504 by itself. It also means that ASCII is the
2505 character set and therefore we cannot have character
2506 with more than one byte in the multibyte
2513 FREE_STACK_RETURN (REG_ECOLLATE);
2515 /* Throw away the ] at the end of the equivalence
2519 /* Set the bit for the character. */
2520 SET_LIST_BIT (str[0]);
2525 /* Try to match the byte sequence in `str' against
2526 those known to the collate implementation.
2527 First find out whether the bytes in `str' are
2528 actually from exactly one character. */
2529 const int32_t *table;
2530 const unsigned char *weights;
2531 const unsigned char *extra;
2532 const int32_t *indirect;
2534 const unsigned char *cp = str;
2537 /* This #include defines a local function! */
2538 # include <locale/weight.h>
2540 table = (const int32_t *)
2541 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
2542 weights = (const unsigned char *)
2543 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
2544 extra = (const unsigned char *)
2545 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
2546 indirect = (const int32_t *)
2547 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
2549 idx = findidx (&cp);
2550 if (idx == 0 || cp < str + c1)
2551 /* This is no valid character. */
2552 FREE_STACK_RETURN (REG_ECOLLATE);
2554 /* Throw away the ] at the end of the equivalence
2558 /* Now we have to go throught the whole table
2559 and find all characters which have the same
2562 XXX Note that this is not entirely correct.
2563 we would have to match multibyte sequences
2564 but this is not possible with the current
2566 for (ch = 1; ch < 256; ++ch)
2567 /* XXX This test would have to be changed if we
2568 would allow matching multibyte sequences. */
2571 int32_t idx2 = table[ch];
2572 size_t len = weights[idx2];
2574 /* Test whether the lenghts match. */
2575 if (weights[idx] == len)
2577 /* They do. New compare the bytes of
2582 && (weights[idx + 1 + cnt]
2583 == weights[idx2 + 1 + cnt]))
2587 /* They match. Mark the character as
2594 had_char_class = true;
2604 had_char_class = false;
2607 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
2609 unsigned char str[128]; /* Should be large enough. */
2612 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2618 /* If pattern is `[[='. */
2619 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2624 if ((c == '.' && *p == ']') || p == pend)
2626 if (c1 < sizeof (str))
2629 /* This is in any case an invalid class name. */
2634 if (c == '.' && *p == ']' && str[0] != '\0')
2636 /* If we have no collation data we use the default
2637 collation in which each character is the name
2638 for its own class which contains only the one
2639 character. It also means that ASCII is the
2640 character set and therefore we cannot have character
2641 with more than one byte in the multibyte
2648 FREE_STACK_RETURN (REG_ECOLLATE);
2650 /* Throw away the ] at the end of the equivalence
2654 /* Set the bit for the character. */
2655 SET_LIST_BIT (str[0]);
2656 range_start = ((const unsigned char *) str)[0];
2661 /* Try to match the byte sequence in `str' against
2662 those known to the collate implementation.
2663 First find out whether the bytes in `str' are
2664 actually from exactly one character. */
2666 const int32_t *symb_table;
2667 const unsigned char *extra;
2674 _NL_CURRENT_WORD (LC_COLLATE,
2675 _NL_COLLATE_SYMB_HASH_SIZEMB);
2676 symb_table = (const int32_t *)
2677 _NL_CURRENT (LC_COLLATE,
2678 _NL_COLLATE_SYMB_TABLEMB);
2679 extra = (const unsigned char *)
2680 _NL_CURRENT (LC_COLLATE,
2681 _NL_COLLATE_SYMB_EXTRAMB);
2683 /* Locate the character in the hashing table. */
2684 hash = elem_hash (str, c1);
2687 elem = hash % table_size;
2688 second = hash % (table_size - 2);
2689 while (symb_table[2 * elem] != 0)
2691 /* First compare the hashing value. */
2692 if (symb_table[2 * elem] == hash
2693 && c1 == extra[symb_table[2 * elem + 1]]
2695 &extra[symb_table[2 * elem + 1]
2699 /* Yep, this is the entry. */
2700 idx = symb_table[2 * elem + 1];
2701 idx += 1 + extra[idx];
2709 if (symb_table[2 * elem] == 0)
2710 /* This is no valid character. */
2711 FREE_STACK_RETURN (REG_ECOLLATE);
2713 /* Throw away the ] at the end of the equivalence
2717 /* Now add the multibyte character(s) we found
2720 XXX Note that this is not entirely correct.
2721 we would have to match multibyte sequences
2722 but this is not possible with the current
2723 implementation. Also, we have to match
2724 collating symbols, which expand to more than
2725 one file, as a whole and not allow the
2726 individual bytes. */
2729 range_start = extra[idx];
2732 SET_LIST_BIT (extra[idx]);
2737 had_char_class = false;
2747 had_char_class = false;
2752 had_char_class = false;
2758 /* Discard any (non)matching list bytes that are all 0 at the
2759 end of the map. Decrease the map-length byte too. */
2760 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2768 if (syntax & RE_NO_BK_PARENS)
2775 if (syntax & RE_NO_BK_PARENS)
2782 if (syntax & RE_NEWLINE_ALT)
2789 if (syntax & RE_NO_BK_VBAR)
2796 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2797 goto handle_interval;
2803 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2805 /* Do not translate the character after the \, so that we can
2806 distinguish, e.g., \B from \b, even if we normally would
2807 translate, e.g., B to b. */
2813 if (syntax & RE_NO_BK_PARENS)
2814 goto normal_backslash;
2820 if (COMPILE_STACK_FULL)
2822 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2823 compile_stack_elt_t);
2824 if (compile_stack.stack == NULL) return REG_ESPACE;
2826 compile_stack.size <<= 1;
2829 /* These are the values to restore when we hit end of this
2830 group. They are all relative offsets, so that if the
2831 whole pattern moves because of realloc, they will still
2833 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2834 COMPILE_STACK_TOP.fixup_alt_jump
2835 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2836 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2837 COMPILE_STACK_TOP.regnum = regnum;
2839 /* We will eventually replace the 0 with the number of
2840 groups inner to this one. But do not push a
2841 start_memory for groups beyond the last one we can
2842 represent in the compiled pattern. */
2843 if (regnum <= MAX_REGNUM)
2845 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2846 BUF_PUSH_3 (start_memory, regnum, 0);
2849 compile_stack.avail++;
2854 /* If we've reached MAX_REGNUM groups, then this open
2855 won't actually generate any code, so we'll have to
2856 clear pending_exact explicitly. */
2862 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2864 if (COMPILE_STACK_EMPTY)
2866 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2867 goto normal_backslash;
2869 FREE_STACK_RETURN (REG_ERPAREN);
2874 { /* Push a dummy failure point at the end of the
2875 alternative for a possible future
2876 `pop_failure_jump' to pop. See comments at
2877 `push_dummy_failure' in `re_match_2'. */
2878 BUF_PUSH (push_dummy_failure);
2880 /* We allocated space for this jump when we assigned
2881 to `fixup_alt_jump', in the `handle_alt' case below. */
2882 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2885 /* See similar code for backslashed left paren above. */
2886 if (COMPILE_STACK_EMPTY)
2888 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2891 FREE_STACK_RETURN (REG_ERPAREN);
2894 /* Since we just checked for an empty stack above, this
2895 ``can't happen''. */
2896 assert (compile_stack.avail != 0);
2898 /* We don't just want to restore into `regnum', because
2899 later groups should continue to be numbered higher,
2900 as in `(ab)c(de)' -- the second group is #2. */
2901 regnum_t this_group_regnum;
2903 compile_stack.avail--;
2904 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2906 = COMPILE_STACK_TOP.fixup_alt_jump
2907 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2909 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2910 this_group_regnum = COMPILE_STACK_TOP.regnum;
2911 /* If we've reached MAX_REGNUM groups, then this open
2912 won't actually generate any code, so we'll have to
2913 clear pending_exact explicitly. */
2916 /* We're at the end of the group, so now we know how many
2917 groups were inside this one. */
2918 if (this_group_regnum <= MAX_REGNUM)
2920 unsigned char *inner_group_loc
2921 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2923 *inner_group_loc = regnum - this_group_regnum;
2924 BUF_PUSH_3 (stop_memory, this_group_regnum,
2925 regnum - this_group_regnum);
2931 case '|': /* `\|'. */
2932 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2933 goto normal_backslash;
2935 if (syntax & RE_LIMITED_OPS)
2938 /* Insert before the previous alternative a jump which
2939 jumps to this alternative if the former fails. */
2940 GET_BUFFER_SPACE (3);
2941 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2945 /* The alternative before this one has a jump after it
2946 which gets executed if it gets matched. Adjust that
2947 jump so it will jump to this alternative's analogous
2948 jump (put in below, which in turn will jump to the next
2949 (if any) alternative's such jump, etc.). The last such
2950 jump jumps to the correct final destination. A picture:
2956 If we are at `b', then fixup_alt_jump right now points to a
2957 three-byte space after `a'. We'll put in the jump, set
2958 fixup_alt_jump to right after `b', and leave behind three
2959 bytes which we'll fill in when we get to after `c'. */
2962 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2964 /* Mark and leave space for a jump after this alternative,
2965 to be filled in later either by next alternative or
2966 when know we're at the end of a series of alternatives. */
2968 GET_BUFFER_SPACE (3);
2977 /* If \{ is a literal. */
2978 if (!(syntax & RE_INTERVALS)
2979 /* If we're at `\{' and it's not the open-interval
2981 || (syntax & RE_NO_BK_BRACES))
2982 goto normal_backslash;
2986 /* If got here, then the syntax allows intervals. */
2988 /* At least (most) this many matches must be made. */
2989 int lower_bound = -1, upper_bound = -1;
2991 beg_interval = p - 1;
2995 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2996 goto unfetch_interval;
2998 FREE_STACK_RETURN (REG_EBRACE);
3001 GET_UNSIGNED_NUMBER (lower_bound);
3005 GET_UNSIGNED_NUMBER (upper_bound);
3006 if ((!(syntax & RE_NO_BK_BRACES) && c != '\\')
3007 || ((syntax & RE_NO_BK_BRACES) && c != '}'))
3008 FREE_STACK_RETURN (REG_BADBR);
3010 if (upper_bound < 0)
3011 upper_bound = RE_DUP_MAX;
3014 /* Interval such as `{1}' => match exactly once. */
3015 upper_bound = lower_bound;
3017 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3018 || lower_bound > upper_bound)
3020 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3021 goto unfetch_interval;
3023 FREE_STACK_RETURN (REG_BADBR);
3026 if (!(syntax & RE_NO_BK_BRACES))
3028 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
3035 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3036 goto unfetch_interval;
3038 FREE_STACK_RETURN (REG_BADBR);
3041 /* We just parsed a valid interval. */
3043 /* If it's invalid to have no preceding re. */
3046 if (syntax & RE_CONTEXT_INVALID_OPS)
3047 FREE_STACK_RETURN (REG_BADRPT);
3048 else if (syntax & RE_CONTEXT_INDEP_OPS)
3051 goto unfetch_interval;
3054 /* If the upper bound is zero, don't want to succeed at
3055 all; jump from `laststart' to `b + 3', which will be
3056 the end of the buffer after we insert the jump. */
3057 if (upper_bound == 0)
3059 GET_BUFFER_SPACE (3);
3060 INSERT_JUMP (jump, laststart, b + 3);
3064 /* Otherwise, we have a nontrivial interval. When
3065 we're all done, the pattern will look like:
3066 set_number_at <jump count> <upper bound>
3067 set_number_at <succeed_n count> <lower bound>
3068 succeed_n <after jump addr> <succeed_n count>
3070 jump_n <succeed_n addr> <jump count>
3071 (The upper bound and `jump_n' are omitted if
3072 `upper_bound' is 1, though.) */
3074 { /* If the upper bound is > 1, we need to insert
3075 more at the end of the loop. */
3076 unsigned nbytes = 10 + (upper_bound > 1) * 10;
3078 GET_BUFFER_SPACE (nbytes);
3080 /* Initialize lower bound of the `succeed_n', even
3081 though it will be set during matching by its
3082 attendant `set_number_at' (inserted next),
3083 because `re_compile_fastmap' needs to know.
3084 Jump to the `jump_n' we might insert below. */
3085 INSERT_JUMP2 (succeed_n, laststart,
3086 b + 5 + (upper_bound > 1) * 5,
3090 /* Code to initialize the lower bound. Insert
3091 before the `succeed_n'. The `5' is the last two
3092 bytes of this `set_number_at', plus 3 bytes of
3093 the following `succeed_n'. */
3094 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3097 if (upper_bound > 1)
3098 { /* More than one repetition is allowed, so
3099 append a backward jump to the `succeed_n'
3100 that starts this interval.
3102 When we've reached this during matching,
3103 we'll have matched the interval once, so
3104 jump back only `upper_bound - 1' times. */
3105 STORE_JUMP2 (jump_n, b, laststart + 5,
3109 /* The location we want to set is the second
3110 parameter of the `jump_n'; that is `b-2' as
3111 an absolute address. `laststart' will be
3112 the `set_number_at' we're about to insert;
3113 `laststart+3' the number to set, the source
3114 for the relative address. But we are
3115 inserting into the middle of the pattern --
3116 so everything is getting moved up by 5.
3117 Conclusion: (b - 2) - (laststart + 3) + 5,
3118 i.e., b - laststart.
3120 We insert this at the beginning of the loop
3121 so that if we fail during matching, we'll
3122 reinitialize the bounds. */
3123 insert_op2 (set_number_at, laststart, b - laststart,
3124 upper_bound - 1, b);
3129 beg_interval = NULL;
3134 /* If an invalid interval, match the characters as literals. */
3135 assert (beg_interval);
3137 beg_interval = NULL;
3139 /* normal_char and normal_backslash need `c'. */
3142 if (!(syntax & RE_NO_BK_BRACES))
3144 if (p > pattern && p[-1] == '\\')
3145 goto normal_backslash;
3150 /* There is no way to specify the before_dot and after_dot
3151 operators. rms says this is ok. --karl */
3159 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3165 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3171 if (syntax & RE_NO_GNU_OPS)
3174 BUF_PUSH (wordchar);
3179 if (syntax & RE_NO_GNU_OPS)
3182 BUF_PUSH (notwordchar);
3187 if (syntax & RE_NO_GNU_OPS)
3193 if (syntax & RE_NO_GNU_OPS)
3199 if (syntax & RE_NO_GNU_OPS)
3201 BUF_PUSH (wordbound);
3205 if (syntax & RE_NO_GNU_OPS)
3207 BUF_PUSH (notwordbound);
3211 if (syntax & RE_NO_GNU_OPS)
3217 if (syntax & RE_NO_GNU_OPS)
3222 case '1': case '2': case '3': case '4': case '5':
3223 case '6': case '7': case '8': case '9':
3224 if (syntax & RE_NO_BK_REFS)
3230 FREE_STACK_RETURN (REG_ESUBREG);
3232 /* Can't back reference to a subexpression if inside of it. */
3233 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
3237 BUF_PUSH_2 (duplicate, c1);
3243 if (syntax & RE_BK_PLUS_QM)
3246 goto normal_backslash;
3250 /* You might think it would be useful for \ to mean
3251 not to translate; but if we don't translate it
3252 it will never match anything. */
3260 /* Expects the character in `c'. */
3262 /* If no exactn currently being built. */
3265 /* If last exactn not at current position. */
3266 || pending_exact + *pending_exact + 1 != b
3268 /* We have only one byte following the exactn for the count. */
3269 || *pending_exact == (1 << BYTEWIDTH) - 1
3271 /* If followed by a repetition operator. */
3272 || *p == '*' || *p == '^'
3273 || ((syntax & RE_BK_PLUS_QM)
3274 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
3275 : (*p == '+' || *p == '?'))
3276 || ((syntax & RE_INTERVALS)
3277 && ((syntax & RE_NO_BK_BRACES)
3279 : (p[0] == '\\' && p[1] == '{'))))
3281 /* Start building a new exactn. */
3285 BUF_PUSH_2 (exactn, 0);
3286 pending_exact = b - 1;
3293 } /* while p != pend */
3296 /* Through the pattern now. */
3299 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3301 if (!COMPILE_STACK_EMPTY)
3302 FREE_STACK_RETURN (REG_EPAREN);
3304 /* If we don't want backtracking, force success
3305 the first time we reach the end of the compiled pattern. */
3306 if (syntax & RE_NO_POSIX_BACKTRACKING)
3309 free (compile_stack.stack);
3311 /* We have succeeded; set the length of the buffer. */
3312 bufp->used = b - bufp->buffer;
3317 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3318 print_compiled_pattern (bufp);
3322 #ifndef MATCH_MAY_ALLOCATE
3323 /* Initialize the failure stack to the largest possible stack. This
3324 isn't necessary unless we're trying to avoid calling alloca in
3325 the search and match routines. */
3327 int num_regs = bufp->re_nsub + 1;
3329 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
3330 is strictly greater than re_max_failures, the largest possible stack
3331 is 2 * re_max_failures failure points. */
3332 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
3334 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
3337 if (! fail_stack.stack)
3339 = (fail_stack_elt_t *) xmalloc (fail_stack.size
3340 * sizeof (fail_stack_elt_t));
3343 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
3345 * sizeof (fail_stack_elt_t)));
3346 # else /* not emacs */
3347 if (! fail_stack.stack)
3349 = (fail_stack_elt_t *) malloc (fail_stack.size
3350 * sizeof (fail_stack_elt_t));
3353 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3355 * sizeof (fail_stack_elt_t)));
3356 # endif /* not emacs */
3359 regex_grow_registers (num_regs);
3361 #endif /* not MATCH_MAY_ALLOCATE */
3364 } /* regex_compile */
3366 /* Subroutines for `regex_compile'. */
3368 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3371 store_op1 (op, loc, arg)
3376 *loc = (unsigned char) op;
3377 STORE_NUMBER (loc + 1, arg);
3381 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3384 store_op2 (op, loc, arg1, arg2)
3389 *loc = (unsigned char) op;
3390 STORE_NUMBER (loc + 1, arg1);
3391 STORE_NUMBER (loc + 3, arg2);
3395 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3396 for OP followed by two-byte integer parameter ARG. */
3399 insert_op1 (op, loc, arg, end)
3405 register unsigned char *pfrom = end;
3406 register unsigned char *pto = end + 3;
3408 while (pfrom != loc)
3411 store_op1 (op, loc, arg);
3415 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3418 insert_op2 (op, loc, arg1, arg2, end)
3424 register unsigned char *pfrom = end;
3425 register unsigned char *pto = end + 5;
3427 while (pfrom != loc)
3430 store_op2 (op, loc, arg1, arg2);
3434 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3435 after an alternative or a begin-subexpression. We assume there is at
3436 least one character before the ^. */
3439 at_begline_loc_p (pattern, p, syntax)
3440 const char *pattern, *p;
3441 reg_syntax_t syntax;
3443 const char *prev = p - 2;
3444 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3447 /* After a subexpression? */
3448 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3449 /* After an alternative? */
3450 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3454 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3455 at least one character after the $, i.e., `P < PEND'. */
3458 at_endline_loc_p (p, pend, syntax)
3459 const char *p, *pend;
3460 reg_syntax_t syntax;
3462 const char *next = p;
3463 boolean next_backslash = *next == '\\';
3464 const char *next_next = p + 1 < pend ? p + 1 : 0;
3467 /* Before a subexpression? */
3468 (syntax & RE_NO_BK_PARENS ? *next == ')'
3469 : next_backslash && next_next && *next_next == ')')
3470 /* Before an alternative? */
3471 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3472 : next_backslash && next_next && *next_next == '|');
3476 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3477 false if it's not. */
3480 group_in_compile_stack (compile_stack, regnum)
3481 compile_stack_type compile_stack;
3486 for (this_element = compile_stack.avail - 1;
3489 if (compile_stack.stack[this_element].regnum == regnum)
3496 /* Read the ending character of a range (in a bracket expression) from the
3497 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3498 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3499 Then we set the translation of all bits between the starting and
3500 ending characters (inclusive) in the compiled pattern B.
3502 Return an error code.
3504 We use these short variable names so we can use the same macros as
3505 `regex_compile' itself. */
3507 static reg_errcode_t
3508 compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
3509 unsigned int range_start_char;
3510 const char **p_ptr, *pend;
3511 RE_TRANSLATE_TYPE translate;
3512 reg_syntax_t syntax;
3516 const char *p = *p_ptr;
3519 const unsigned char *collseq;
3520 unsigned int start_colseq;
3521 unsigned int end_colseq;
3529 /* Have to increment the pointer into the pattern string, so the
3530 caller isn't still at the ending character. */
3533 /* Report an error if the range is empty and the syntax prohibits this. */
3534 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3537 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
3538 _NL_COLLATE_COLLSEQMB);
3540 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
3541 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
3542 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
3544 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
3546 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
3548 SET_LIST_BIT (TRANSLATE (this_char));
3553 /* Here we see why `this_char' has to be larger than an `unsigned
3554 char' -- we would otherwise go into an infinite loop, since all
3555 characters <= 0xff. */
3556 range_start_char = TRANSLATE (range_start_char);
3557 end_char = TRANSLATE (p[0]);
3558 for (this_char = range_start_char; this_char <= end_char; ++this_char)
3560 SET_LIST_BIT (TRANSLATE (this_char));
3568 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3569 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3570 characters can start a string that matches the pattern. This fastmap
3571 is used by re_search to skip quickly over impossible starting points.
3573 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3574 area as BUFP->fastmap.
3576 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3579 Returns 0 if we succeed, -2 if an internal error. */
3582 re_compile_fastmap (bufp)
3583 struct re_pattern_buffer *bufp;
3586 #ifdef MATCH_MAY_ALLOCATE
3587 fail_stack_type fail_stack;
3589 #ifndef REGEX_MALLOC
3593 register char *fastmap = bufp->fastmap;
3594 unsigned char *pattern = bufp->buffer;
3595 unsigned char *p = pattern;
3596 register unsigned char *pend = pattern + bufp->used;
3599 /* This holds the pointer to the failure stack, when
3600 it is allocated relocatably. */
3601 fail_stack_elt_t *failure_stack_ptr;
3604 /* Assume that each path through the pattern can be null until
3605 proven otherwise. We set this false at the bottom of switch
3606 statement, to which we get only if a particular path doesn't
3607 match the empty string. */
3608 boolean path_can_be_null = true;
3610 /* We aren't doing a `succeed_n' to begin with. */
3611 boolean succeed_n_p = false;
3613 assert (fastmap != NULL && p != NULL);
3616 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3617 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3618 bufp->can_be_null = 0;
3622 if (p == pend || *p == succeed)
3624 /* We have reached the (effective) end of pattern. */
3625 if (!FAIL_STACK_EMPTY ())
3627 bufp->can_be_null |= path_can_be_null;
3629 /* Reset for next path. */
3630 path_can_be_null = true;
3632 p = fail_stack.stack[--fail_stack.avail].pointer;
3640 /* We should never be about to go beyond the end of the pattern. */
3643 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3646 /* I guess the idea here is to simply not bother with a fastmap
3647 if a backreference is used, since it's too hard to figure out
3648 the fastmap for the corresponding group. Setting
3649 `can_be_null' stops `re_search_2' from using the fastmap, so
3650 that is all we do. */
3652 bufp->can_be_null = 1;
3656 /* Following are the cases which match a character. These end
3665 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3666 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3672 /* Chars beyond end of map must be allowed. */
3673 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3676 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3677 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3683 for (j = 0; j < (1 << BYTEWIDTH); j++)
3684 if (SYNTAX (j) == Sword)
3690 for (j = 0; j < (1 << BYTEWIDTH); j++)
3691 if (SYNTAX (j) != Sword)
3698 int fastmap_newline = fastmap['\n'];
3700 /* `.' matches anything ... */
3701 for (j = 0; j < (1 << BYTEWIDTH); j++)
3704 /* ... except perhaps newline. */
3705 if (!(bufp->syntax & RE_DOT_NEWLINE))
3706 fastmap['\n'] = fastmap_newline;
3708 /* Return if we have already set `can_be_null'; if we have,
3709 then the fastmap is irrelevant. Something's wrong here. */
3710 else if (bufp->can_be_null)
3713 /* Otherwise, have to check alternative paths. */
3720 for (j = 0; j < (1 << BYTEWIDTH); j++)
3721 if (SYNTAX (j) == (enum syntaxcode) k)
3728 for (j = 0; j < (1 << BYTEWIDTH); j++)
3729 if (SYNTAX (j) != (enum syntaxcode) k)
3734 /* All cases after this match the empty string. These end with
3754 case push_dummy_failure:
3759 case pop_failure_jump:
3760 case maybe_pop_jump:
3763 case dummy_failure_jump:
3764 EXTRACT_NUMBER_AND_INCR (j, p);
3769 /* Jump backward implies we just went through the body of a
3770 loop and matched nothing. Opcode jumped to should be
3771 `on_failure_jump' or `succeed_n'. Just treat it like an
3772 ordinary jump. For a * loop, it has pushed its failure
3773 point already; if so, discard that as redundant. */
3774 if ((re_opcode_t) *p != on_failure_jump
3775 && (re_opcode_t) *p != succeed_n)
3779 EXTRACT_NUMBER_AND_INCR (j, p);
3782 /* If what's on the stack is where we are now, pop it. */
3783 if (!FAIL_STACK_EMPTY ()
3784 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3790 case on_failure_jump:
3791 case on_failure_keep_string_jump:
3792 handle_on_failure_jump:
3793 EXTRACT_NUMBER_AND_INCR (j, p);
3795 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3796 end of the pattern. We don't want to push such a point,
3797 since when we restore it above, entering the switch will
3798 increment `p' past the end of the pattern. We don't need
3799 to push such a point since we obviously won't find any more
3800 fastmap entries beyond `pend'. Such a pattern can match
3801 the null string, though. */
3804 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3806 RESET_FAIL_STACK ();
3811 bufp->can_be_null = 1;
3815 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3816 succeed_n_p = false;
3823 /* Get to the number of times to succeed. */
3826 /* Increment p past the n for when k != 0. */
3827 EXTRACT_NUMBER_AND_INCR (k, p);
3831 succeed_n_p = true; /* Spaghetti code alert. */
3832 goto handle_on_failure_jump;
3849 abort (); /* We have listed all the cases. */
3852 /* Getting here means we have found the possible starting
3853 characters for one path of the pattern -- and that the empty
3854 string does not match. We need not follow this path further.
3855 Instead, look at the next alternative (remembered on the
3856 stack), or quit if no more. The test at the top of the loop
3857 does these things. */
3858 path_can_be_null = false;
3862 /* Set `can_be_null' for the last path (also the first path, if the
3863 pattern is empty). */
3864 bufp->can_be_null |= path_can_be_null;
3867 RESET_FAIL_STACK ();
3869 } /* re_compile_fastmap */
3871 weak_alias (__re_compile_fastmap, re_compile_fastmap)
3874 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3875 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3876 this memory for recording register information. STARTS and ENDS
3877 must be allocated using the malloc library routine, and must each
3878 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3880 If NUM_REGS == 0, then subsequent matches should allocate their own
3883 Unless this function is called, the first search or match using
3884 PATTERN_BUFFER will allocate its own register data, without
3885 freeing the old data. */
3888 re_set_registers (bufp, regs, num_regs, starts, ends)
3889 struct re_pattern_buffer *bufp;
3890 struct re_registers *regs;
3892 regoff_t *starts, *ends;
3896 bufp->regs_allocated = REGS_REALLOCATE;
3897 regs->num_regs = num_regs;
3898 regs->start = starts;
3903 bufp->regs_allocated = REGS_UNALLOCATED;
3905 regs->start = regs->end = (regoff_t *) 0;
3909 weak_alias (__re_set_registers, re_set_registers)
3912 /* Searching routines. */
3914 /* Like re_search_2, below, but only one string is specified, and
3915 doesn't let you say where to stop matching. */
3918 re_search (bufp, string, size, startpos, range, regs)
3919 struct re_pattern_buffer *bufp;
3921 int size, startpos, range;
3922 struct re_registers *regs;
3924 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3928 weak_alias (__re_search, re_search)
3932 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3933 virtual concatenation of STRING1 and STRING2, starting first at index
3934 STARTPOS, then at STARTPOS + 1, and so on.
3936 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3938 RANGE is how far to scan while trying to match. RANGE = 0 means try
3939 only at STARTPOS; in general, the last start tried is STARTPOS +
3942 In REGS, return the indices of the virtual concatenation of STRING1
3943 and STRING2 that matched the entire BUFP->buffer and its contained
3946 Do not consider matching one past the index STOP in the virtual
3947 concatenation of STRING1 and STRING2.
3949 We return either the position in the strings at which the match was
3950 found, -1 if no match, or -2 if error (such as failure
3954 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3955 struct re_pattern_buffer *bufp;
3956 const char *string1, *string2;
3960 struct re_registers *regs;
3964 register char *fastmap = bufp->fastmap;
3965 register RE_TRANSLATE_TYPE translate = bufp->translate;
3966 int total_size = size1 + size2;
3967 int endpos = startpos + range;
3969 /* Check for out-of-range STARTPOS. */
3970 if (startpos < 0 || startpos > total_size)
3973 /* Fix up RANGE if it might eventually take us outside
3974 the virtual concatenation of STRING1 and STRING2.
3975 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3977 range = 0 - startpos;
3978 else if (endpos > total_size)
3979 range = total_size - startpos;
3981 /* If the search isn't to be a backwards one, don't waste time in a
3982 search for a pattern that must be anchored. */
3983 if (bufp->used > 0 && range > 0
3984 && ((re_opcode_t) bufp->buffer[0] == begbuf
3985 /* `begline' is like `begbuf' if it cannot match at newlines. */
3986 || ((re_opcode_t) bufp->buffer[0] == begline
3987 && !bufp->newline_anchor)))
3996 /* In a forward search for something that starts with \=.
3997 don't keep searching past point. */
3998 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4000 range = PT - startpos;
4006 /* Update the fastmap now if not correct already. */
4007 if (fastmap && !bufp->fastmap_accurate)
4008 if (re_compile_fastmap (bufp) == -2)
4011 /* Loop through the string, looking for a place to start matching. */
4014 /* If a fastmap is supplied, skip quickly over characters that
4015 cannot be the start of a match. If the pattern can match the
4016 null string, however, we don't need to skip characters; we want
4017 the first null string. */
4018 if (fastmap && startpos < total_size && !bufp->can_be_null)
4020 if (range > 0) /* Searching forwards. */
4022 register const char *d;
4023 register int lim = 0;
4026 if (startpos < size1 && startpos + range >= size1)
4027 lim = range - (size1 - startpos);
4029 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
4031 /* Written out as an if-else to avoid testing `translate'
4035 && !fastmap[(unsigned char)
4036 translate[(unsigned char) *d++]])
4039 while (range > lim && !fastmap[(unsigned char) *d++])
4042 startpos += irange - range;
4044 else /* Searching backwards. */
4046 register char c = (size1 == 0 || startpos >= size1
4047 ? string2[startpos - size1]
4048 : string1[startpos]);
4050 if (!fastmap[(unsigned char) TRANSLATE (c)])
4055 /* If can't match the null string, and that's all we have left, fail. */
4056 if (range >= 0 && startpos == total_size && fastmap
4057 && !bufp->can_be_null)
4060 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4061 startpos, regs, stop);
4062 #ifndef REGEX_MALLOC
4091 weak_alias (__re_search_2, re_search_2)
4094 /* This converts PTR, a pointer into one of the search strings `string1'
4095 and `string2' into an offset from the beginning of that string. */
4096 #define POINTER_TO_OFFSET(ptr) \
4097 (FIRST_STRING_P (ptr) \
4098 ? ((regoff_t) ((ptr) - string1)) \
4099 : ((regoff_t) ((ptr) - string2 + size1)))
4101 /* Macros for dealing with the split strings in re_match_2. */
4103 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
4105 /* Call before fetching a character with *d. This switches over to
4106 string2 if necessary. */
4107 #define PREFETCH() \
4110 /* End of string2 => fail. */ \
4111 if (dend == end_match_2) \
4113 /* End of string1 => advance to string2. */ \
4115 dend = end_match_2; \
4119 /* Test if at very beginning or at very end of the virtual concatenation
4120 of `string1' and `string2'. If only one string, it's `string2'. */
4121 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4122 #define AT_STRINGS_END(d) ((d) == end2)
4125 /* Test if D points to a character which is word-constituent. We have
4126 two special cases to check for: if past the end of string1, look at
4127 the first character in string2; and if before the beginning of
4128 string2, look at the last character in string1. */
4129 #define WORDCHAR_P(d) \
4130 (SYNTAX ((d) == end1 ? *string2 \
4131 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4134 /* Disabled due to a compiler bug -- see comment at case wordbound */
4136 /* Test if the character before D and the one at D differ with respect
4137 to being word-constituent. */
4138 #define AT_WORD_BOUNDARY(d) \
4139 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4140 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4143 /* Free everything we malloc. */
4144 #ifdef MATCH_MAY_ALLOCATE
4145 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
4146 # define FREE_VARIABLES() \
4148 REGEX_FREE_STACK (fail_stack.stack); \
4149 FREE_VAR (regstart); \
4150 FREE_VAR (regend); \
4151 FREE_VAR (old_regstart); \
4152 FREE_VAR (old_regend); \
4153 FREE_VAR (best_regstart); \
4154 FREE_VAR (best_regend); \
4155 FREE_VAR (reg_info); \
4156 FREE_VAR (reg_dummy); \
4157 FREE_VAR (reg_info_dummy); \
4160 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4161 #endif /* not MATCH_MAY_ALLOCATE */
4163 /* These values must meet several constraints. They must not be valid
4164 register values; since we have a limit of 255 registers (because
4165 we use only one byte in the pattern for the register number), we can
4166 use numbers larger than 255. They must differ by 1, because of
4167 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4168 be larger than the value for the highest register, so we do not try
4169 to actually save any registers when none are active. */
4170 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4171 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4173 /* Matching routines. */
4175 #ifndef emacs /* Emacs never uses this. */
4176 /* re_match is like re_match_2 except it takes only a single string. */
4179 re_match (bufp, string, size, pos, regs)
4180 struct re_pattern_buffer *bufp;
4183 struct re_registers *regs;
4185 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4187 # ifndef REGEX_MALLOC
4195 weak_alias (__re_match, re_match)
4197 #endif /* not emacs */
4199 static boolean group_match_null_string_p _RE_ARGS ((unsigned char **p,
4201 register_info_type *reg_info));
4202 static boolean alt_match_null_string_p _RE_ARGS ((unsigned char *p,
4204 register_info_type *reg_info));
4205 static boolean common_op_match_null_string_p _RE_ARGS ((unsigned char **p,
4207 register_info_type *reg_info));
4208 static int bcmp_translate _RE_ARGS ((const char *s1, const char *s2,
4209 int len, char *translate));
4211 /* re_match_2 matches the compiled pattern in BUFP against the
4212 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4213 and SIZE2, respectively). We start matching at POS, and stop
4216 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4217 store offsets for the substring each group matched in REGS. See the
4218 documentation for exactly how many groups we fill.
4220 We return -1 if no match, -2 if an internal error (such as the
4221 failure stack overflowing). Otherwise, we return the length of the
4222 matched substring. */
4225 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4226 struct re_pattern_buffer *bufp;
4227 const char *string1, *string2;
4230 struct re_registers *regs;
4233 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
4235 #ifndef REGEX_MALLOC
4243 weak_alias (__re_match_2, re_match_2)
4246 /* This is a separate function so that we can force an alloca cleanup
4249 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4250 struct re_pattern_buffer *bufp;
4251 const char *string1, *string2;
4254 struct re_registers *regs;
4257 /* General temporaries. */
4261 /* Just past the end of the corresponding string. */
4262 const char *end1, *end2;
4264 /* Pointers into string1 and string2, just past the last characters in
4265 each to consider matching. */
4266 const char *end_match_1, *end_match_2;
4268 /* Where we are in the data, and the end of the current string. */
4269 const char *d, *dend;
4271 /* Where we are in the pattern, and the end of the pattern. */
4272 unsigned char *p = bufp->buffer;
4273 register unsigned char *pend = p + bufp->used;
4275 /* Mark the opcode just after a start_memory, so we can test for an
4276 empty subpattern when we get to the stop_memory. */
4277 unsigned char *just_past_start_mem = 0;
4279 /* We use this to map every character in the string. */
4280 RE_TRANSLATE_TYPE translate = bufp->translate;
4282 /* Failure point stack. Each place that can handle a failure further
4283 down the line pushes a failure point on this stack. It consists of
4284 restart, regend, and reg_info for all registers corresponding to
4285 the subexpressions we're currently inside, plus the number of such
4286 registers, and, finally, two char *'s. The first char * is where
4287 to resume scanning the pattern; the second one is where to resume
4288 scanning the strings. If the latter is zero, the failure point is
4289 a ``dummy''; if a failure happens and the failure point is a dummy,
4290 it gets discarded and the next next one is tried. */
4291 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4292 fail_stack_type fail_stack;
4295 static unsigned failure_id;
4296 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4300 /* This holds the pointer to the failure stack, when
4301 it is allocated relocatably. */
4302 fail_stack_elt_t *failure_stack_ptr;
4305 /* We fill all the registers internally, independent of what we
4306 return, for use in backreferences. The number here includes
4307 an element for register zero. */
4308 size_t num_regs = bufp->re_nsub + 1;
4310 /* The currently active registers. */
4311 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4312 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4314 /* Information on the contents of registers. These are pointers into
4315 the input strings; they record just what was matched (on this
4316 attempt) by a subexpression part of the pattern, that is, the
4317 regnum-th regstart pointer points to where in the pattern we began
4318 matching and the regnum-th regend points to right after where we
4319 stopped matching the regnum-th subexpression. (The zeroth register
4320 keeps track of what the whole pattern matches.) */
4321 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4322 const char **regstart, **regend;
4325 /* If a group that's operated upon by a repetition operator fails to
4326 match anything, then the register for its start will need to be
4327 restored because it will have been set to wherever in the string we
4328 are when we last see its open-group operator. Similarly for a
4330 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4331 const char **old_regstart, **old_regend;
4334 /* The is_active field of reg_info helps us keep track of which (possibly
4335 nested) subexpressions we are currently in. The matched_something
4336 field of reg_info[reg_num] helps us tell whether or not we have
4337 matched any of the pattern so far this time through the reg_num-th
4338 subexpression. These two fields get reset each time through any
4339 loop their register is in. */
4340 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4341 register_info_type *reg_info;
4344 /* The following record the register info as found in the above
4345 variables when we find a match better than any we've seen before.
4346 This happens as we backtrack through the failure points, which in
4347 turn happens only if we have not yet matched the entire string. */
4348 unsigned best_regs_set = false;
4349 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4350 const char **best_regstart, **best_regend;
4353 /* Logically, this is `best_regend[0]'. But we don't want to have to
4354 allocate space for that if we're not allocating space for anything
4355 else (see below). Also, we never need info about register 0 for
4356 any of the other register vectors, and it seems rather a kludge to
4357 treat `best_regend' differently than the rest. So we keep track of
4358 the end of the best match so far in a separate variable. We
4359 initialize this to NULL so that when we backtrack the first time
4360 and need to test it, it's not garbage. */
4361 const char *match_end = NULL;
4363 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4364 int set_regs_matched_done = 0;
4366 /* Used when we pop values we don't care about. */
4367 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4368 const char **reg_dummy;
4369 register_info_type *reg_info_dummy;
4373 /* Counts the total number of registers pushed. */
4374 unsigned num_regs_pushed = 0;
4377 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4381 #ifdef MATCH_MAY_ALLOCATE
4382 /* Do not bother to initialize all the register variables if there are
4383 no groups in the pattern, as it takes a fair amount of time. If
4384 there are groups, we include space for register 0 (the whole
4385 pattern), even though we never use it, since it simplifies the
4386 array indexing. We should fix this. */
4389 regstart = REGEX_TALLOC (num_regs, const char *);
4390 regend = REGEX_TALLOC (num_regs, const char *);
4391 old_regstart = REGEX_TALLOC (num_regs, const char *);
4392 old_regend = REGEX_TALLOC (num_regs, const char *);
4393 best_regstart = REGEX_TALLOC (num_regs, const char *);
4394 best_regend = REGEX_TALLOC (num_regs, const char *);
4395 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4396 reg_dummy = REGEX_TALLOC (num_regs, const char *);
4397 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4399 if (!(regstart && regend && old_regstart && old_regend && reg_info
4400 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4408 /* We must initialize all our variables to NULL, so that
4409 `FREE_VARIABLES' doesn't try to free them. */
4410 regstart = regend = old_regstart = old_regend = best_regstart
4411 = best_regend = reg_dummy = NULL;
4412 reg_info = reg_info_dummy = (register_info_type *) NULL;
4414 #endif /* MATCH_MAY_ALLOCATE */
4416 /* The starting position is bogus. */
4417 if (pos < 0 || pos > size1 + size2)
4423 /* Initialize subexpression text positions to -1 to mark ones that no
4424 start_memory/stop_memory has been seen for. Also initialize the
4425 register information struct. */
4426 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4428 regstart[mcnt] = regend[mcnt]
4429 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4431 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4432 IS_ACTIVE (reg_info[mcnt]) = 0;
4433 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4434 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4437 /* We move `string1' into `string2' if the latter's empty -- but not if
4438 `string1' is null. */
4439 if (size2 == 0 && string1 != NULL)
4446 end1 = string1 + size1;
4447 end2 = string2 + size2;
4449 /* Compute where to stop matching, within the two strings. */
4452 end_match_1 = string1 + stop;
4453 end_match_2 = string2;
4458 end_match_2 = string2 + stop - size1;
4461 /* `p' scans through the pattern as `d' scans through the data.
4462 `dend' is the end of the input string that `d' points within. `d'
4463 is advanced into the following input string whenever necessary, but
4464 this happens before fetching; therefore, at the beginning of the
4465 loop, `d' can be pointing at the end of a string, but it cannot
4467 if (size1 > 0 && pos <= size1)
4474 d = string2 + pos - size1;
4478 DEBUG_PRINT1 ("The compiled pattern is:\n");
4479 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4480 DEBUG_PRINT1 ("The string to match is: `");
4481 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4482 DEBUG_PRINT1 ("'\n");
4484 /* This loops over pattern commands. It exits by returning from the
4485 function if the match is complete, or it drops through if the match
4486 fails at this starting point in the input data. */
4490 DEBUG_PRINT2 ("\n%p: ", p);
4492 DEBUG_PRINT2 ("\n0x%x: ", p);
4496 { /* End of pattern means we might have succeeded. */
4497 DEBUG_PRINT1 ("end of pattern ... ");
4499 /* If we haven't matched the entire string, and we want the
4500 longest match, try backtracking. */
4501 if (d != end_match_2)
4503 /* 1 if this match ends in the same string (string1 or string2)
4504 as the best previous match. */
4505 boolean same_str_p = (FIRST_STRING_P (match_end)
4506 == MATCHING_IN_FIRST_STRING);
4507 /* 1 if this match is the best seen so far. */
4508 boolean best_match_p;
4510 /* AIX compiler got confused when this was combined
4511 with the previous declaration. */
4513 best_match_p = d > match_end;
4515 best_match_p = !MATCHING_IN_FIRST_STRING;
4517 DEBUG_PRINT1 ("backtracking.\n");
4519 if (!FAIL_STACK_EMPTY ())
4520 { /* More failure points to try. */
4522 /* If exceeds best match so far, save it. */
4523 if (!best_regs_set || best_match_p)
4525 best_regs_set = true;
4528 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4530 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4532 best_regstart[mcnt] = regstart[mcnt];
4533 best_regend[mcnt] = regend[mcnt];
4539 /* If no failure points, don't restore garbage. And if
4540 last match is real best match, don't restore second
4542 else if (best_regs_set && !best_match_p)
4545 /* Restore best match. It may happen that `dend ==
4546 end_match_1' while the restored d is in string2.
4547 For example, the pattern `x.*y.*z' against the
4548 strings `x-' and `y-z-', if the two strings are
4549 not consecutive in memory. */
4550 DEBUG_PRINT1 ("Restoring best registers.\n");
4553 dend = ((d >= string1 && d <= end1)
4554 ? end_match_1 : end_match_2);
4556 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4558 regstart[mcnt] = best_regstart[mcnt];
4559 regend[mcnt] = best_regend[mcnt];
4562 } /* d != end_match_2 */
4565 DEBUG_PRINT1 ("Accepting match.\n");
4567 /* If caller wants register contents data back, do it. */
4568 if (regs && !bufp->no_sub)
4570 /* Have the register data arrays been allocated? */
4571 if (bufp->regs_allocated == REGS_UNALLOCATED)
4572 { /* No. So allocate them with malloc. We need one
4573 extra element beyond `num_regs' for the `-1' marker
4575 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4576 regs->start = TALLOC (regs->num_regs, regoff_t);
4577 regs->end = TALLOC (regs->num_regs, regoff_t);
4578 if (regs->start == NULL || regs->end == NULL)
4583 bufp->regs_allocated = REGS_REALLOCATE;
4585 else if (bufp->regs_allocated == REGS_REALLOCATE)
4586 { /* Yes. If we need more elements than were already
4587 allocated, reallocate them. If we need fewer, just
4589 if (regs->num_regs < num_regs + 1)
4591 regs->num_regs = num_regs + 1;
4592 RETALLOC (regs->start, regs->num_regs, regoff_t);
4593 RETALLOC (regs->end, regs->num_regs, regoff_t);
4594 if (regs->start == NULL || regs->end == NULL)
4603 /* These braces fend off a "empty body in an else-statement"
4604 warning under GCC when assert expands to nothing. */
4605 assert (bufp->regs_allocated == REGS_FIXED);
4608 /* Convert the pointer data in `regstart' and `regend' to
4609 indices. Register zero has to be set differently,
4610 since we haven't kept track of any info for it. */
4611 if (regs->num_regs > 0)
4613 regs->start[0] = pos;
4614 regs->end[0] = (MATCHING_IN_FIRST_STRING
4615 ? ((regoff_t) (d - string1))
4616 : ((regoff_t) (d - string2 + size1)));
4619 /* Go through the first `min (num_regs, regs->num_regs)'
4620 registers, since that is all we initialized. */
4621 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
4624 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4625 regs->start[mcnt] = regs->end[mcnt] = -1;
4629 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4631 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4635 /* If the regs structure we return has more elements than
4636 were in the pattern, set the extra elements to -1. If
4637 we (re)allocated the registers, this is the case,
4638 because we always allocate enough to have at least one
4640 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
4641 regs->start[mcnt] = regs->end[mcnt] = -1;
4642 } /* regs && !bufp->no_sub */
4644 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4645 nfailure_points_pushed, nfailure_points_popped,
4646 nfailure_points_pushed - nfailure_points_popped);
4647 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4649 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4653 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4659 /* Otherwise match next pattern command. */
4660 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4662 /* Ignore these. Used to ignore the n of succeed_n's which
4663 currently have n == 0. */
4665 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4669 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4672 /* Match the next n pattern characters exactly. The following
4673 byte in the pattern defines n, and the n bytes after that
4674 are the characters to match. */
4677 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4679 /* This is written out as an if-else so we don't waste time
4680 testing `translate' inside the loop. */
4686 if ((unsigned char) translate[(unsigned char) *d++]
4687 != (unsigned char) *p++)
4697 if (*d++ != (char) *p++) goto fail;
4701 SET_REGS_MATCHED ();
4705 /* Match any character except possibly a newline or a null. */
4707 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4711 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4712 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4715 SET_REGS_MATCHED ();
4716 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4724 register unsigned char c;
4725 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4727 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4730 c = TRANSLATE (*d); /* The character to match. */
4732 /* Cast to `unsigned' instead of `unsigned char' in case the
4733 bit list is a full 32 bytes long. */
4734 if (c < (unsigned) (*p * BYTEWIDTH)
4735 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4740 if (!not) goto fail;
4742 SET_REGS_MATCHED ();
4748 /* The beginning of a group is represented by start_memory.
4749 The arguments are the register number in the next byte, and the
4750 number of groups inner to this one in the next. The text
4751 matched within the group is recorded (in the internal
4752 registers data structure) under the register number. */
4754 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4756 /* Find out if this group can match the empty string. */
4757 p1 = p; /* To send to group_match_null_string_p. */
4759 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4760 REG_MATCH_NULL_STRING_P (reg_info[*p])
4761 = group_match_null_string_p (&p1, pend, reg_info);
4763 /* Save the position in the string where we were the last time
4764 we were at this open-group operator in case the group is
4765 operated upon by a repetition operator, e.g., with `(a*)*b'
4766 against `ab'; then we want to ignore where we are now in
4767 the string in case this attempt to match fails. */
4768 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4769 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4771 DEBUG_PRINT2 (" old_regstart: %d\n",
4772 POINTER_TO_OFFSET (old_regstart[*p]));
4775 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4777 IS_ACTIVE (reg_info[*p]) = 1;
4778 MATCHED_SOMETHING (reg_info[*p]) = 0;
4780 /* Clear this whenever we change the register activity status. */
4781 set_regs_matched_done = 0;
4783 /* This is the new highest active register. */
4784 highest_active_reg = *p;
4786 /* If nothing was active before, this is the new lowest active
4788 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4789 lowest_active_reg = *p;
4791 /* Move past the register number and inner group count. */
4793 just_past_start_mem = p;
4798 /* The stop_memory opcode represents the end of a group. Its
4799 arguments are the same as start_memory's: the register
4800 number, and the number of inner groups. */
4802 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4804 /* We need to save the string position the last time we were at
4805 this close-group operator in case the group is operated
4806 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4807 against `aba'; then we want to ignore where we are now in
4808 the string in case this attempt to match fails. */
4809 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4810 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4812 DEBUG_PRINT2 (" old_regend: %d\n",
4813 POINTER_TO_OFFSET (old_regend[*p]));
4816 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4818 /* This register isn't active anymore. */
4819 IS_ACTIVE (reg_info[*p]) = 0;
4821 /* Clear this whenever we change the register activity status. */
4822 set_regs_matched_done = 0;
4824 /* If this was the only register active, nothing is active
4826 if (lowest_active_reg == highest_active_reg)
4828 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4829 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4832 { /* We must scan for the new highest active register, since
4833 it isn't necessarily one less than now: consider
4834 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4835 new highest active register is 1. */
4836 unsigned char r = *p - 1;
4837 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4840 /* If we end up at register zero, that means that we saved
4841 the registers as the result of an `on_failure_jump', not
4842 a `start_memory', and we jumped to past the innermost
4843 `stop_memory'. For example, in ((.)*) we save
4844 registers 1 and 2 as a result of the *, but when we pop
4845 back to the second ), we are at the stop_memory 1.
4846 Thus, nothing is active. */
4849 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4850 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4853 highest_active_reg = r;
4856 /* If just failed to match something this time around with a
4857 group that's operated on by a repetition operator, try to
4858 force exit from the ``loop'', and restore the register
4859 information for this group that we had before trying this
4861 if ((!MATCHED_SOMETHING (reg_info[*p])
4862 || just_past_start_mem == p - 1)
4865 boolean is_a_jump_n = false;
4869 switch ((re_opcode_t) *p1++)
4873 case pop_failure_jump:
4874 case maybe_pop_jump:
4876 case dummy_failure_jump:
4877 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4887 /* If the next operation is a jump backwards in the pattern
4888 to an on_failure_jump right before the start_memory
4889 corresponding to this stop_memory, exit from the loop
4890 by forcing a failure after pushing on the stack the
4891 on_failure_jump's jump in the pattern, and d. */
4892 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4893 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4895 /* If this group ever matched anything, then restore
4896 what its registers were before trying this last
4897 failed match, e.g., with `(a*)*b' against `ab' for
4898 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4899 against `aba' for regend[3].
4901 Also restore the registers for inner groups for,
4902 e.g., `((a*)(b*))*' against `aba' (register 3 would
4903 otherwise get trashed). */
4905 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4909 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4911 /* Restore this and inner groups' (if any) registers. */
4912 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
4915 regstart[r] = old_regstart[r];
4917 /* xx why this test? */
4918 if (old_regend[r] >= regstart[r])
4919 regend[r] = old_regend[r];
4923 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4924 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4930 /* Move past the register number and the inner group count. */
4935 /* \<digit> has been turned into a `duplicate' command which is
4936 followed by the numeric value of <digit> as the register number. */
4939 register const char *d2, *dend2;
4940 int regno = *p++; /* Get which register to match against. */
4941 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4943 /* Can't back reference a group which we've never matched. */
4944 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4947 /* Where in input to try to start matching. */
4948 d2 = regstart[regno];
4950 /* Where to stop matching; if both the place to start and
4951 the place to stop matching are in the same string, then
4952 set to the place to stop, otherwise, for now have to use
4953 the end of the first string. */
4955 dend2 = ((FIRST_STRING_P (regstart[regno])
4956 == FIRST_STRING_P (regend[regno]))
4957 ? regend[regno] : end_match_1);
4960 /* If necessary, advance to next segment in register
4964 if (dend2 == end_match_2) break;
4965 if (dend2 == regend[regno]) break;
4967 /* End of string1 => advance to string2. */
4969 dend2 = regend[regno];
4971 /* At end of register contents => success */
4972 if (d2 == dend2) break;
4974 /* If necessary, advance to next segment in data. */
4977 /* How many characters left in this segment to match. */
4980 /* Want how many consecutive characters we can match in
4981 one shot, so, if necessary, adjust the count. */
4982 if (mcnt > dend2 - d2)
4985 /* Compare that many; failure if mismatch, else move
4988 ? bcmp_translate (d, d2, mcnt, translate)
4989 : memcmp (d, d2, mcnt))
4991 d += mcnt, d2 += mcnt;
4993 /* Do this because we've match some characters. */
4994 SET_REGS_MATCHED ();
5000 /* begline matches the empty string at the beginning of the string
5001 (unless `not_bol' is set in `bufp'), and, if
5002 `newline_anchor' is set, after newlines. */
5004 DEBUG_PRINT1 ("EXECUTING begline.\n");
5006 if (AT_STRINGS_BEG (d))
5008 if (!bufp->not_bol) break;
5010 else if (d[-1] == '\n' && bufp->newline_anchor)
5014 /* In all other cases, we fail. */
5018 /* endline is the dual of begline. */
5020 DEBUG_PRINT1 ("EXECUTING endline.\n");
5022 if (AT_STRINGS_END (d))
5024 if (!bufp->not_eol) break;
5027 /* We have to ``prefetch'' the next character. */
5028 else if ((d == end1 ? *string2 : *d) == '\n'
5029 && bufp->newline_anchor)
5036 /* Match at the very beginning of the data. */
5038 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5039 if (AT_STRINGS_BEG (d))
5044 /* Match at the very end of the data. */
5046 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5047 if (AT_STRINGS_END (d))
5052 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5053 pushes NULL as the value for the string on the stack. Then
5054 `pop_failure_point' will keep the current value for the
5055 string, instead of restoring it. To see why, consider
5056 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5057 then the . fails against the \n. But the next thing we want
5058 to do is match the \n against the \n; if we restored the
5059 string value, we would be back at the foo.
5061 Because this is used only in specific cases, we don't need to
5062 check all the things that `on_failure_jump' does, to make
5063 sure the right things get saved on the stack. Hence we don't
5064 share its code. The only reason to push anything on the
5065 stack at all is that otherwise we would have to change
5066 `anychar's code to do something besides goto fail in this
5067 case; that seems worse than this. */
5068 case on_failure_keep_string_jump:
5069 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
5071 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5073 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
5075 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
5078 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
5082 /* Uses of on_failure_jump:
5084 Each alternative starts with an on_failure_jump that points
5085 to the beginning of the next alternative. Each alternative
5086 except the last ends with a jump that in effect jumps past
5087 the rest of the alternatives. (They really jump to the
5088 ending jump of the following alternative, because tensioning
5089 these jumps is a hassle.)
5091 Repeats start with an on_failure_jump that points past both
5092 the repetition text and either the following jump or
5093 pop_failure_jump back to this on_failure_jump. */
5094 case on_failure_jump:
5096 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
5098 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5100 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
5102 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
5105 /* If this on_failure_jump comes right before a group (i.e.,
5106 the original * applied to a group), save the information
5107 for that group and all inner ones, so that if we fail back
5108 to this point, the group's information will be correct.
5109 For example, in \(a*\)*\1, we need the preceding group,
5110 and in \(zz\(a*\)b*\)\2, we need the inner group. */
5112 /* We can't use `p' to check ahead because we push
5113 a failure point to `p + mcnt' after we do this. */
5116 /* We need to skip no_op's before we look for the
5117 start_memory in case this on_failure_jump is happening as
5118 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5120 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5123 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5125 /* We have a new highest active register now. This will
5126 get reset at the start_memory we are about to get to,
5127 but we will have saved all the registers relevant to
5128 this repetition op, as described above. */
5129 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5130 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5131 lowest_active_reg = *(p1 + 1);
5134 DEBUG_PRINT1 (":\n");
5135 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5139 /* A smart repeat ends with `maybe_pop_jump'.
5140 We change it to either `pop_failure_jump' or `jump'. */
5141 case maybe_pop_jump:
5142 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5143 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5145 register unsigned char *p2 = p;
5147 /* Compare the beginning of the repeat with what in the
5148 pattern follows its end. If we can establish that there
5149 is nothing that they would both match, i.e., that we
5150 would have to backtrack because of (as in, e.g., `a*a')
5151 then we can change to pop_failure_jump, because we'll
5152 never have to backtrack.
5154 This is not true in the case of alternatives: in
5155 `(a|ab)*' we do need to backtrack to the `ab' alternative
5156 (e.g., if the string was `ab'). But instead of trying to
5157 detect that here, the alternative has put on a dummy
5158 failure point which is what we will end up popping. */
5160 /* Skip over open/close-group commands.
5161 If what follows this loop is a ...+ construct,
5162 look at what begins its body, since we will have to
5163 match at least one of that. */
5167 && ((re_opcode_t) *p2 == stop_memory
5168 || (re_opcode_t) *p2 == start_memory))
5170 else if (p2 + 6 < pend
5171 && (re_opcode_t) *p2 == dummy_failure_jump)
5178 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5179 to the `maybe_finalize_jump' of this case. Examine what
5182 /* If we're at the end of the pattern, we can change. */
5185 /* Consider what happens when matching ":\(.*\)"
5186 against ":/". I don't really understand this code
5188 p[-3] = (unsigned char) pop_failure_jump;
5190 (" End of pattern: change to `pop_failure_jump'.\n");
5193 else if ((re_opcode_t) *p2 == exactn
5194 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5196 register unsigned char c
5197 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5199 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
5201 p[-3] = (unsigned char) pop_failure_jump;
5202 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5206 else if ((re_opcode_t) p1[3] == charset
5207 || (re_opcode_t) p1[3] == charset_not)
5209 int not = (re_opcode_t) p1[3] == charset_not;
5211 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
5212 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5215 /* `not' is equal to 1 if c would match, which means
5216 that we can't change to pop_failure_jump. */
5219 p[-3] = (unsigned char) pop_failure_jump;
5220 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5224 else if ((re_opcode_t) *p2 == charset)
5226 /* We win if the first character of the loop is not part
5228 if ((re_opcode_t) p1[3] == exactn
5229 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
5230 && (p2[2 + p1[5] / BYTEWIDTH]
5231 & (1 << (p1[5] % BYTEWIDTH)))))
5233 p[-3] = (unsigned char) pop_failure_jump;
5234 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5237 else if ((re_opcode_t) p1[3] == charset_not)
5240 /* We win if the charset_not inside the loop
5241 lists every character listed in the charset after. */
5242 for (idx = 0; idx < (int) p2[1]; idx++)
5243 if (! (p2[2 + idx] == 0
5244 || (idx < (int) p1[4]
5245 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5250 p[-3] = (unsigned char) pop_failure_jump;
5251 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5254 else if ((re_opcode_t) p1[3] == charset)
5257 /* We win if the charset inside the loop
5258 has no overlap with the one after the loop. */
5260 idx < (int) p2[1] && idx < (int) p1[4];
5262 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5265 if (idx == p2[1] || idx == p1[4])
5267 p[-3] = (unsigned char) pop_failure_jump;
5268 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5273 p -= 2; /* Point at relative address again. */
5274 if ((re_opcode_t) p[-1] != pop_failure_jump)
5276 p[-1] = (unsigned char) jump;
5277 DEBUG_PRINT1 (" Match => jump.\n");
5278 goto unconditional_jump;
5280 /* Note fall through. */
5283 /* The end of a simple repeat has a pop_failure_jump back to
5284 its matching on_failure_jump, where the latter will push a
5285 failure point. The pop_failure_jump takes off failure
5286 points put on by this pop_failure_jump's matching
5287 on_failure_jump; we got through the pattern to here from the
5288 matching on_failure_jump, so didn't fail. */
5289 case pop_failure_jump:
5291 /* We need to pass separate storage for the lowest and
5292 highest registers, even though we don't care about the
5293 actual values. Otherwise, we will restore only one
5294 register from the stack, since lowest will == highest in
5295 `pop_failure_point'. */
5296 active_reg_t dummy_low_reg, dummy_high_reg;
5297 unsigned char *pdummy;
5300 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5301 POP_FAILURE_POINT (sdummy, pdummy,
5302 dummy_low_reg, dummy_high_reg,
5303 reg_dummy, reg_dummy, reg_info_dummy);
5305 /* Note fall through. */
5309 DEBUG_PRINT2 ("\n%p: ", p);
5311 DEBUG_PRINT2 ("\n0x%x: ", p);
5313 /* Note fall through. */
5315 /* Unconditionally jump (without popping any failure points). */
5317 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5318 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5319 p += mcnt; /* Do the jump. */
5321 DEBUG_PRINT2 ("(to %p).\n", p);
5323 DEBUG_PRINT2 ("(to 0x%x).\n", p);
5328 /* We need this opcode so we can detect where alternatives end
5329 in `group_match_null_string_p' et al. */
5331 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5332 goto unconditional_jump;
5335 /* Normally, the on_failure_jump pushes a failure point, which
5336 then gets popped at pop_failure_jump. We will end up at
5337 pop_failure_jump, also, and with a pattern of, say, `a+', we
5338 are skipping over the on_failure_jump, so we have to push
5339 something meaningless for pop_failure_jump to pop. */
5340 case dummy_failure_jump:
5341 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5342 /* It doesn't matter what we push for the string here. What
5343 the code at `fail' tests is the value for the pattern. */
5344 PUSH_FAILURE_POINT (NULL, NULL, -2);
5345 goto unconditional_jump;
5348 /* At the end of an alternative, we need to push a dummy failure
5349 point in case we are followed by a `pop_failure_jump', because
5350 we don't want the failure point for the alternative to be
5351 popped. For example, matching `(a|ab)*' against `aab'
5352 requires that we match the `ab' alternative. */
5353 case push_dummy_failure:
5354 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5355 /* See comments just above at `dummy_failure_jump' about the
5357 PUSH_FAILURE_POINT (NULL, NULL, -2);
5360 /* Have to succeed matching what follows at least n times.
5361 After that, handle like `on_failure_jump'. */
5363 EXTRACT_NUMBER (mcnt, p + 2);
5364 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5367 /* Originally, this is how many times we HAVE to succeed. */
5372 STORE_NUMBER_AND_INCR (p, mcnt);
5374 DEBUG_PRINT3 (" Setting %p to %d.\n", p - 2, mcnt);
5376 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - 2, mcnt);
5382 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p+2);
5384 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
5386 p[2] = (unsigned char) no_op;
5387 p[3] = (unsigned char) no_op;
5393 EXTRACT_NUMBER (mcnt, p + 2);
5394 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5396 /* Originally, this is how many times we CAN jump. */
5400 STORE_NUMBER (p + 2, mcnt);
5402 DEBUG_PRINT3 (" Setting %p to %d.\n", p + 2, mcnt);
5404 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + 2, mcnt);
5406 goto unconditional_jump;
5408 /* If don't have to jump any more, skip over the rest of command. */
5415 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5417 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5419 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5421 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
5423 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
5425 STORE_NUMBER (p1, mcnt);
5430 /* The DEC Alpha C compiler 3.x generates incorrect code for the
5431 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
5432 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
5433 macro and introducing temporary variables works around the bug. */
5436 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5437 if (AT_WORD_BOUNDARY (d))
5442 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5443 if (AT_WORD_BOUNDARY (d))
5449 boolean prevchar, thischar;
5451 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5452 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5455 prevchar = WORDCHAR_P (d - 1);
5456 thischar = WORDCHAR_P (d);
5457 if (prevchar != thischar)
5464 boolean prevchar, thischar;
5466 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5467 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5470 prevchar = WORDCHAR_P (d - 1);
5471 thischar = WORDCHAR_P (d);
5472 if (prevchar != thischar)
5479 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5480 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
5485 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5486 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
5487 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
5493 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5494 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
5499 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5500 if (PTR_CHAR_POS ((unsigned char *) d) != point)
5505 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5506 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
5511 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5516 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5520 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5522 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
5524 SET_REGS_MATCHED ();
5528 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5530 goto matchnotsyntax;
5533 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5537 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5539 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
5541 SET_REGS_MATCHED ();
5544 #else /* not emacs */
5546 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5548 if (!WORDCHAR_P (d))
5550 SET_REGS_MATCHED ();
5555 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5559 SET_REGS_MATCHED ();
5562 #endif /* not emacs */
5567 continue; /* Successfully executed one pattern command; keep going. */
5570 /* We goto here if a matching operation fails. */
5572 if (!FAIL_STACK_EMPTY ())
5573 { /* A restart point is known. Restore to that state. */
5574 DEBUG_PRINT1 ("\nFAIL:\n");
5575 POP_FAILURE_POINT (d, p,
5576 lowest_active_reg, highest_active_reg,
5577 regstart, regend, reg_info);
5579 /* If this failure point is a dummy, try the next one. */
5583 /* If we failed to the end of the pattern, don't examine *p. */
5587 boolean is_a_jump_n = false;
5589 /* If failed to a backwards jump that's part of a repetition
5590 loop, need to pop this failure point and use the next one. */
5591 switch ((re_opcode_t) *p)
5595 case maybe_pop_jump:
5596 case pop_failure_jump:
5599 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5602 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5604 && (re_opcode_t) *p1 == on_failure_jump))
5612 if (d >= string1 && d <= end1)
5616 break; /* Matching at this starting point really fails. */
5620 goto restore_best_regs;
5624 return -1; /* Failure to match. */
5627 /* Subroutine definitions for re_match_2. */
5630 /* We are passed P pointing to a register number after a start_memory.
5632 Return true if the pattern up to the corresponding stop_memory can
5633 match the empty string, and false otherwise.
5635 If we find the matching stop_memory, sets P to point to one past its number.
5636 Otherwise, sets P to an undefined byte less than or equal to END.
5638 We don't handle duplicates properly (yet). */
5641 group_match_null_string_p (p, end, reg_info)
5642 unsigned char **p, *end;
5643 register_info_type *reg_info;
5646 /* Point to after the args to the start_memory. */
5647 unsigned char *p1 = *p + 2;
5651 /* Skip over opcodes that can match nothing, and return true or
5652 false, as appropriate, when we get to one that can't, or to the
5653 matching stop_memory. */
5655 switch ((re_opcode_t) *p1)
5657 /* Could be either a loop or a series of alternatives. */
5658 case on_failure_jump:
5660 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5662 /* If the next operation is not a jump backwards in the
5667 /* Go through the on_failure_jumps of the alternatives,
5668 seeing if any of the alternatives cannot match nothing.
5669 The last alternative starts with only a jump,
5670 whereas the rest start with on_failure_jump and end
5671 with a jump, e.g., here is the pattern for `a|b|c':
5673 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5674 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5677 So, we have to first go through the first (n-1)
5678 alternatives and then deal with the last one separately. */
5681 /* Deal with the first (n-1) alternatives, which start
5682 with an on_failure_jump (see above) that jumps to right
5683 past a jump_past_alt. */
5685 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5687 /* `mcnt' holds how many bytes long the alternative
5688 is, including the ending `jump_past_alt' and
5691 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5695 /* Move to right after this alternative, including the
5699 /* Break if it's the beginning of an n-th alternative
5700 that doesn't begin with an on_failure_jump. */
5701 if ((re_opcode_t) *p1 != on_failure_jump)
5704 /* Still have to check that it's not an n-th
5705 alternative that starts with an on_failure_jump. */
5707 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5708 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5710 /* Get to the beginning of the n-th alternative. */
5716 /* Deal with the last alternative: go back and get number
5717 of the `jump_past_alt' just before it. `mcnt' contains
5718 the length of the alternative. */
5719 EXTRACT_NUMBER (mcnt, p1 - 2);
5721 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5724 p1 += mcnt; /* Get past the n-th alternative. */
5730 assert (p1[1] == **p);
5736 if (!common_op_match_null_string_p (&p1, end, reg_info))
5739 } /* while p1 < end */
5742 } /* group_match_null_string_p */
5745 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5746 It expects P to be the first byte of a single alternative and END one
5747 byte past the last. The alternative can contain groups. */
5750 alt_match_null_string_p (p, end, reg_info)
5751 unsigned char *p, *end;
5752 register_info_type *reg_info;
5755 unsigned char *p1 = p;
5759 /* Skip over opcodes that can match nothing, and break when we get
5760 to one that can't. */
5762 switch ((re_opcode_t) *p1)
5765 case on_failure_jump:
5767 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5772 if (!common_op_match_null_string_p (&p1, end, reg_info))
5775 } /* while p1 < end */
5778 } /* alt_match_null_string_p */
5781 /* Deals with the ops common to group_match_null_string_p and
5782 alt_match_null_string_p.
5784 Sets P to one after the op and its arguments, if any. */
5787 common_op_match_null_string_p (p, end, reg_info)
5788 unsigned char **p, *end;
5789 register_info_type *reg_info;
5794 unsigned char *p1 = *p;
5796 switch ((re_opcode_t) *p1++)
5816 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5817 ret = group_match_null_string_p (&p1, end, reg_info);
5819 /* Have to set this here in case we're checking a group which
5820 contains a group and a back reference to it. */
5822 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5823 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5829 /* If this is an optimized succeed_n for zero times, make the jump. */
5831 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5839 /* Get to the number of times to succeed. */
5841 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5846 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5854 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5862 /* All other opcodes mean we cannot match the empty string. */
5868 } /* common_op_match_null_string_p */
5871 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5872 bytes; nonzero otherwise. */
5875 bcmp_translate (s1, s2, len, translate)
5876 const char *s1, *s2;
5878 RE_TRANSLATE_TYPE translate;
5880 register const unsigned char *p1 = (const unsigned char *) s1;
5881 register const unsigned char *p2 = (const unsigned char *) s2;
5884 if (translate[*p1++] != translate[*p2++]) return 1;
5890 /* Entry points for GNU code. */
5892 /* re_compile_pattern is the GNU regular expression compiler: it
5893 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5894 Returns 0 if the pattern was valid, otherwise an error string.
5896 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5897 are set in BUFP on entry.
5899 We call regex_compile to do the actual compilation. */
5902 re_compile_pattern (pattern, length, bufp)
5903 const char *pattern;
5905 struct re_pattern_buffer *bufp;
5909 /* GNU code is written to assume at least RE_NREGS registers will be set
5910 (and at least one extra will be -1). */
5911 bufp->regs_allocated = REGS_UNALLOCATED;
5913 /* And GNU code determines whether or not to get register information
5914 by passing null for the REGS argument to re_match, etc., not by
5918 /* Match anchors at newline. */
5919 bufp->newline_anchor = 1;
5921 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5925 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
5928 weak_alias (__re_compile_pattern, re_compile_pattern)
5931 /* Entry points compatible with 4.2 BSD regex library. We don't define
5932 them unless specifically requested. */
5934 #if defined _REGEX_RE_COMP || defined _LIBC
5936 /* BSD has one and only one pattern buffer. */
5937 static struct re_pattern_buffer re_comp_buf;
5941 /* Make these definitions weak in libc, so POSIX programs can redefine
5942 these names if they don't use our functions, and still use
5943 regcomp/regexec below without link errors. */
5953 if (!re_comp_buf.buffer)
5954 return gettext ("No previous regular expression");
5958 if (!re_comp_buf.buffer)
5960 re_comp_buf.buffer = (unsigned char *) malloc (200);
5961 if (re_comp_buf.buffer == NULL)
5962 return (char *) gettext (re_error_msgid
5963 + re_error_msgid_idx[(int) REG_ESPACE]);
5964 re_comp_buf.allocated = 200;
5966 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5967 if (re_comp_buf.fastmap == NULL)
5968 return (char *) gettext (re_error_msgid
5969 + re_error_msgid_idx[(int) REG_ESPACE]);
5972 /* Since `re_exec' always passes NULL for the `regs' argument, we
5973 don't need to initialize the pattern buffer fields which affect it. */
5975 /* Match anchors at newlines. */
5976 re_comp_buf.newline_anchor = 1;
5978 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5983 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5984 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
5995 const int len = strlen (s);
5997 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6000 #endif /* _REGEX_RE_COMP */
6002 /* POSIX.2 functions. Don't define these for Emacs. */
6006 /* regcomp takes a regular expression as a string and compiles it.
6008 PREG is a regex_t *. We do not expect any fields to be initialized,
6009 since POSIX says we shouldn't. Thus, we set
6011 `buffer' to the compiled pattern;
6012 `used' to the length of the compiled pattern;
6013 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6014 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6015 RE_SYNTAX_POSIX_BASIC;
6016 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6017 `fastmap' to an allocated space for the fastmap;
6018 `fastmap_accurate' to zero;
6019 `re_nsub' to the number of subexpressions in PATTERN.
6021 PATTERN is the address of the pattern string.
6023 CFLAGS is a series of bits which affect compilation.
6025 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6026 use POSIX basic syntax.
6028 If REG_NEWLINE is set, then . and [^...] don't match newline.
6029 Also, regexec will try a match beginning after every newline.
6031 If REG_ICASE is set, then we considers upper- and lowercase
6032 versions of letters to be equivalent when matching.
6034 If REG_NOSUB is set, then when PREG is passed to regexec, that
6035 routine will report only success or failure, and nothing about the
6038 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6039 the return codes and their meanings.) */
6042 regcomp (preg, pattern, cflags)
6044 const char *pattern;
6049 = (cflags & REG_EXTENDED) ?
6050 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6052 /* regex_compile will allocate the space for the compiled pattern. */
6054 preg->allocated = 0;
6057 /* Try to allocate space for the fastmap. */
6058 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
6060 if (cflags & REG_ICASE)
6065 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6066 * sizeof (*(RE_TRANSLATE_TYPE)0));
6067 if (preg->translate == NULL)
6068 return (int) REG_ESPACE;
6070 /* Map uppercase characters to corresponding lowercase ones. */
6071 for (i = 0; i < CHAR_SET_SIZE; i++)
6072 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6075 preg->translate = NULL;
6077 /* If REG_NEWLINE is set, newlines are treated differently. */
6078 if (cflags & REG_NEWLINE)
6079 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6080 syntax &= ~RE_DOT_NEWLINE;
6081 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6082 /* It also changes the matching behavior. */
6083 preg->newline_anchor = 1;
6086 preg->newline_anchor = 0;
6088 preg->no_sub = !!(cflags & REG_NOSUB);
6090 /* POSIX says a null character in the pattern terminates it, so we
6091 can use strlen here in compiling the pattern. */
6092 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
6094 /* POSIX doesn't distinguish between an unmatched open-group and an
6095 unmatched close-group: both are REG_EPAREN. */
6096 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6098 if (ret == REG_NOERROR && preg->fastmap)
6100 /* Compute the fastmap now, since regexec cannot modify the pattern
6102 if (re_compile_fastmap (preg) == -2)
6104 /* Some error occurred while computing the fastmap, just forget
6106 free (preg->fastmap);
6107 preg->fastmap = NULL;
6114 weak_alias (__regcomp, regcomp)
6118 /* regexec searches for a given pattern, specified by PREG, in the
6121 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6122 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6123 least NMATCH elements, and we set them to the offsets of the
6124 corresponding matched substrings.
6126 EFLAGS specifies `execution flags' which affect matching: if
6127 REG_NOTBOL is set, then ^ does not match at the beginning of the
6128 string; if REG_NOTEOL is set, then $ does not match at the end.
6130 We return 0 if we find a match and REG_NOMATCH if not. */
6133 regexec (preg, string, nmatch, pmatch, eflags)
6134 const regex_t *preg;
6137 regmatch_t pmatch[];
6141 struct re_registers regs;
6142 regex_t private_preg;
6143 int len = strlen (string);
6144 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6146 private_preg = *preg;
6148 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6149 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6151 /* The user has told us exactly how many registers to return
6152 information about, via `nmatch'. We have to pass that on to the
6153 matching routines. */
6154 private_preg.regs_allocated = REGS_FIXED;
6158 regs.num_regs = nmatch;
6159 regs.start = TALLOC (nmatch * 2, regoff_t);
6160 if (regs.start == NULL)
6161 return (int) REG_NOMATCH;
6162 regs.end = regs.start + nmatch;
6165 /* Perform the searching operation. */
6166 ret = re_search (&private_preg, string, len,
6167 /* start: */ 0, /* range: */ len,
6168 want_reg_info ? ®s : (struct re_registers *) 0);
6170 /* Copy the register information to the POSIX structure. */
6177 for (r = 0; r < nmatch; r++)
6179 pmatch[r].rm_so = regs.start[r];
6180 pmatch[r].rm_eo = regs.end[r];
6184 /* If we needed the temporary register info, free the space now. */
6188 /* We want zero return to mean success, unlike `re_search'. */
6189 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6192 weak_alias (__regexec, regexec)
6196 /* Returns a message corresponding to an error code, ERRCODE, returned
6197 from either regcomp or regexec. We don't use PREG here. */
6200 regerror (errcode, preg, errbuf, errbuf_size)
6202 const regex_t *preg;
6210 || errcode >= (int) (sizeof (re_error_msgid_idx)
6211 / sizeof (re_error_msgid_idx[0])))
6212 /* Only error codes returned by the rest of the code should be passed
6213 to this routine. If we are given anything else, or if other regex
6214 code generates an invalid error code, then the program has a bug.
6215 Dump core so we can fix it. */
6218 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
6220 msg_size = strlen (msg) + 1; /* Includes the null. */
6222 if (errbuf_size != 0)
6224 if (msg_size > errbuf_size)
6226 #if defined HAVE_MEMPCPY || defined _LIBC
6227 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
6229 memcpy (errbuf, msg, errbuf_size - 1);
6230 errbuf[errbuf_size - 1] = 0;
6234 memcpy (errbuf, msg, msg_size);
6240 weak_alias (__regerror, regerror)
6244 /* Free dynamically allocated space used by PREG. */
6250 if (preg->buffer != NULL)
6251 free (preg->buffer);
6252 preg->buffer = NULL;
6254 preg->allocated = 0;
6257 if (preg->fastmap != NULL)
6258 free (preg->fastmap);
6259 preg->fastmap = NULL;
6260 preg->fastmap_accurate = 0;
6262 if (preg->translate != NULL)
6263 free (preg->translate);
6264 preg->translate = NULL;
6267 weak_alias (__regfree, regfree)
6270 #endif /* not emacs */