1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P10003.2/D11.2, except for
4 internationalization features.)
6 Copyright (C) 1993, 1994 Free Software Foundation, Inc.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
33 /* We need this for `regex.h', and perhaps for the Emacs include files. */
34 #include <sys/types.h>
36 /* The `emacs' switch turns on certain matching commands
37 that make sense only in Emacs. */
44 /* Emacs uses `NULL' as a predicate. */
57 /* We used to test for `BSTRING' here, but only GCC and Emacs define
58 `BSTRING', as far as I know, and neither of them use this code. */
59 #ifndef INHIBIT_STRING_HEADER
60 #if HAVE_STRING_H || STDC_HEADERS
63 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
66 #define bcopy(s, d, n) memcpy ((d), (s), (n))
69 #define bzero(s, n) memset ((s), 0, (n))
76 /* Define the syntax stuff for \<, \>, etc. */
78 /* This must be nonzero for the wordchar and notwordchar pattern
79 commands in re_match_2. */
86 extern char *re_syntax_table;
88 #else /* not SYNTAX_TABLE */
90 /* How many characters in the character set. */
91 #define CHAR_SET_SIZE 256
93 static char re_syntax_table[CHAR_SET_SIZE];
104 bzero (re_syntax_table, sizeof re_syntax_table);
106 for (c = 'a'; c <= 'z'; c++)
107 re_syntax_table[c] = Sword;
109 for (c = 'A'; c <= 'Z'; c++)
110 re_syntax_table[c] = Sword;
112 for (c = '0'; c <= '9'; c++)
113 re_syntax_table[c] = Sword;
115 re_syntax_table['_'] = Sword;
120 #endif /* not SYNTAX_TABLE */
122 #define SYNTAX(c) re_syntax_table[c]
124 #endif /* not emacs */
126 /* Get the interface, including the syntax bits. */
129 /* isalpha etc. are used for the character classes. */
132 /* Jim Meyering writes:
134 "... Some ctype macros are valid only for character codes that
135 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
136 using /bin/cc or gcc but without giving an ansi option). So, all
137 ctype uses should be through macros like ISPRINT... If
138 STDC_HEADERS is defined, then autoconf has verified that the ctype
139 macros don't need to be guarded with references to isascii. ...
140 Defining isascii to 1 should let any compiler worth its salt
141 eliminate the && through constant folding." */
143 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
146 #define ISASCII(c) isascii(c)
150 #define ISBLANK(c) (ISASCII (c) && isblank (c))
152 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
155 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
157 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
160 #define ISPRINT(c) (ISASCII (c) && isprint (c))
161 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
162 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
163 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
164 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
165 #define ISLOWER(c) (ISASCII (c) && islower (c))
166 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
167 #define ISSPACE(c) (ISASCII (c) && isspace (c))
168 #define ISUPPER(c) (ISASCII (c) && isupper (c))
169 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
175 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
176 since ours (we hope) works properly with all combinations of
177 machines, compilers, `char' and `unsigned char' argument types.
178 (Per Bothner suggested the basic approach.) */
179 #undef SIGN_EXTEND_CHAR
181 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
182 #else /* not __STDC__ */
183 /* As in Harbison and Steele. */
184 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
187 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
188 use `alloca' instead of `malloc'. This is because using malloc in
189 re_search* or re_match* could cause memory leaks when C-g is used in
190 Emacs; also, malloc is slower and causes storage fragmentation. On
191 the other hand, malloc is more portable, and easier to debug.
193 Because we sometimes use alloca, some routines have to be macros,
194 not functions -- `alloca'-allocated space disappears at the end of the
195 function it is called in. */
199 #define REGEX_ALLOCATE malloc
200 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
202 #else /* not REGEX_MALLOC */
204 /* Emacs already defines alloca, sometimes. */
207 /* Make alloca work the best possible way. */
209 #define alloca __builtin_alloca
210 #else /* not __GNUC__ */
213 #else /* not __GNUC__ or HAVE_ALLOCA_H */
214 #ifndef _AIX /* Already did AIX, up at the top. */
216 #endif /* not _AIX */
217 #endif /* not HAVE_ALLOCA_H */
218 #endif /* not __GNUC__ */
220 #endif /* not alloca */
222 #define REGEX_ALLOCATE alloca
224 /* Assumes a `char *destination' variable. */
225 #define REGEX_REALLOCATE(source, osize, nsize) \
226 (destination = (char *) alloca (nsize), \
227 bcopy (source, destination, osize), \
230 #endif /* not REGEX_MALLOC */
233 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
234 `string1' or just past its end. This works if PTR is NULL, which is
236 #define FIRST_STRING_P(ptr) \
237 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
239 /* (Re)Allocate N items of type T using malloc, or fail. */
240 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
241 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
242 #define RETALLOC_IF(addr, n, t) \
243 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
244 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
246 #define BYTEWIDTH 8 /* In bits. */
248 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
252 #define MAX(a, b) ((a) > (b) ? (a) : (b))
253 #define MIN(a, b) ((a) < (b) ? (a) : (b))
255 typedef char boolean;
259 static int re_match_2_internal ();
261 /* These are the command codes that appear in compiled regular
262 expressions. Some opcodes are followed by argument bytes. A
263 command code can specify any interpretation whatsoever for its
264 arguments. Zero bytes may appear in the compiled regular expression.
266 The value of `exactn' is needed in search.c (search_buffer) in Emacs.
267 So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
268 `exactn' we use here must also be 1. */
274 /* Followed by one byte giving n, then by n literal bytes. */
277 /* Matches any (more or less) character. */
280 /* Matches any one char belonging to specified set. First
281 following byte is number of bitmap bytes. Then come bytes
282 for a bitmap saying which chars are in. Bits in each byte
283 are ordered low-bit-first. A character is in the set if its
284 bit is 1. A character too large to have a bit in the map is
285 automatically not in the set. */
288 /* Same parameters as charset, but match any character that is
289 not one of those specified. */
292 /* Start remembering the text that is matched, for storing in a
293 register. Followed by one byte with the register number, in
294 the range 0 to one less than the pattern buffer's re_nsub
295 field. Then followed by one byte with the number of groups
296 inner to this one. (This last has to be part of the
297 start_memory only because we need it in the on_failure_jump
301 /* Stop remembering the text that is matched and store it in a
302 memory register. Followed by one byte with the register
303 number, in the range 0 to one less than `re_nsub' in the
304 pattern buffer, and one byte with the number of inner groups,
305 just like `start_memory'. (We need the number of inner
306 groups here because we don't have any easy way of finding the
307 corresponding start_memory when we're at a stop_memory.) */
310 /* Match a duplicate of something remembered. Followed by one
311 byte containing the register number. */
314 /* Fail unless at beginning of line. */
317 /* Fail unless at end of line. */
320 /* Succeeds if at beginning of buffer (if emacs) or at beginning
321 of string to be matched (if not). */
324 /* Analogously, for end of buffer/string. */
327 /* Followed by two byte relative address to which to jump. */
330 /* Same as jump, but marks the end of an alternative. */
333 /* Followed by two-byte relative address of place to resume at
334 in case of failure. */
337 /* Like on_failure_jump, but pushes a placeholder instead of the
338 current string position when executed. */
339 on_failure_keep_string_jump,
341 /* Throw away latest failure point and then jump to following
342 two-byte relative address. */
345 /* Change to pop_failure_jump if know won't have to backtrack to
346 match; otherwise change to jump. This is used to jump
347 back to the beginning of a repeat. If what follows this jump
348 clearly won't match what the repeat does, such that we can be
349 sure that there is no use backtracking out of repetitions
350 already matched, then we change it to a pop_failure_jump.
351 Followed by two-byte address. */
354 /* Jump to following two-byte address, and push a dummy failure
355 point. This failure point will be thrown away if an attempt
356 is made to use it for a failure. A `+' construct makes this
357 before the first repeat. Also used as an intermediary kind
358 of jump when compiling an alternative. */
361 /* Push a dummy failure point and continue. Used at the end of
365 /* Followed by two-byte relative address and two-byte number n.
366 After matching N times, jump to the address upon failure. */
369 /* Followed by two-byte relative address, and two-byte number n.
370 Jump to the address N times, then fail. */
373 /* Set the following two-byte relative address to the
374 subsequent two-byte number. The address *includes* the two
378 wordchar, /* Matches any word-constituent character. */
379 notwordchar, /* Matches any char that is not a word-constituent. */
381 wordbeg, /* Succeeds if at word beginning. */
382 wordend, /* Succeeds if at word end. */
384 wordbound, /* Succeeds if at a word boundary. */
385 notwordbound /* Succeeds if not at a word boundary. */
388 ,before_dot, /* Succeeds if before point. */
389 at_dot, /* Succeeds if at point. */
390 after_dot, /* Succeeds if after point. */
392 /* Matches any character whose syntax is specified. Followed by
393 a byte which contains a syntax code, e.g., Sword. */
396 /* Matches any character whose syntax is not that specified. */
401 /* Common operations on the compiled pattern. */
403 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
405 #define STORE_NUMBER(destination, number) \
407 (destination)[0] = (number) & 0377; \
408 (destination)[1] = (number) >> 8; \
411 /* Same as STORE_NUMBER, except increment DESTINATION to
412 the byte after where the number is stored. Therefore, DESTINATION
413 must be an lvalue. */
415 #define STORE_NUMBER_AND_INCR(destination, number) \
417 STORE_NUMBER (destination, number); \
418 (destination) += 2; \
421 /* Put into DESTINATION a number stored in two contiguous bytes starting
424 #define EXTRACT_NUMBER(destination, source) \
426 (destination) = *(source) & 0377; \
427 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
432 extract_number (dest, source)
434 unsigned char *source;
436 int temp = SIGN_EXTEND_CHAR (*(source + 1));
437 *dest = *source & 0377;
441 #ifndef EXTRACT_MACROS /* To debug the macros. */
442 #undef EXTRACT_NUMBER
443 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
444 #endif /* not EXTRACT_MACROS */
448 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
449 SOURCE must be an lvalue. */
451 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
453 EXTRACT_NUMBER (destination, source); \
459 extract_number_and_incr (destination, source)
461 unsigned char **source;
463 extract_number (destination, *source);
467 #ifndef EXTRACT_MACROS
468 #undef EXTRACT_NUMBER_AND_INCR
469 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
470 extract_number_and_incr (&dest, &src)
471 #endif /* not EXTRACT_MACROS */
475 /* If DEBUG is defined, Regex prints many voluminous messages about what
476 it is doing (if the variable `debug' is nonzero). If linked with the
477 main program in `iregex.c', you can enter patterns and strings
478 interactively. And if linked with the main program in `main.c' and
479 the other test files, you can run the already-written tests. */
483 /* We use standard I/O for debugging. */
486 /* It is useful to test things that ``must'' be true when debugging. */
489 static int debug = 0;
491 #define DEBUG_STATEMENT(e) e
492 #define DEBUG_PRINT1(x) if (debug) printf (x)
493 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
494 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
495 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
496 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
497 if (debug) print_partial_compiled_pattern (s, e)
498 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
499 if (debug) print_double_string (w, s1, sz1, s2, sz2)
502 extern void printchar ();
504 /* Print the fastmap in human-readable form. */
507 print_fastmap (fastmap)
510 unsigned was_a_range = 0;
513 while (i < (1 << BYTEWIDTH))
519 while (i < (1 << BYTEWIDTH) && fastmap[i])
535 /* Print a compiled pattern string in human-readable form, starting at
536 the START pointer into it and ending just before the pointer END. */
539 print_partial_compiled_pattern (start, end)
540 unsigned char *start;
544 unsigned char *p = start;
545 unsigned char *pend = end;
553 /* Loop over pattern commands. */
556 printf ("%d:\t", p - start);
558 switch ((re_opcode_t) *p++)
566 printf ("/exactn/%d", mcnt);
577 printf ("/start_memory/%d/%d", mcnt, *p++);
582 printf ("/stop_memory/%d/%d", mcnt, *p++);
586 printf ("/duplicate/%d", *p++);
596 register int c, last = -100;
597 register int in_range = 0;
599 printf ("/charset [%s",
600 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
602 assert (p + *p < pend);
604 for (c = 0; c < 256; c++)
606 && (p[1 + (c/8)] & (1 << (c % 8))))
608 /* Are we starting a range? */
609 if (last + 1 == c && ! in_range)
614 /* Have we broken a range? */
615 else if (last + 1 != c && in_range)
644 case on_failure_jump:
645 extract_number_and_incr (&mcnt, &p);
646 printf ("/on_failure_jump to %d", p + mcnt - start);
649 case on_failure_keep_string_jump:
650 extract_number_and_incr (&mcnt, &p);
651 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
654 case dummy_failure_jump:
655 extract_number_and_incr (&mcnt, &p);
656 printf ("/dummy_failure_jump to %d", p + mcnt - start);
659 case push_dummy_failure:
660 printf ("/push_dummy_failure");
664 extract_number_and_incr (&mcnt, &p);
665 printf ("/maybe_pop_jump to %d", p + mcnt - start);
668 case pop_failure_jump:
669 extract_number_and_incr (&mcnt, &p);
670 printf ("/pop_failure_jump to %d", p + mcnt - start);
674 extract_number_and_incr (&mcnt, &p);
675 printf ("/jump_past_alt to %d", p + mcnt - start);
679 extract_number_and_incr (&mcnt, &p);
680 printf ("/jump to %d", p + mcnt - start);
684 extract_number_and_incr (&mcnt, &p);
685 extract_number_and_incr (&mcnt2, &p);
686 printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
690 extract_number_and_incr (&mcnt, &p);
691 extract_number_and_incr (&mcnt2, &p);
692 printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
696 extract_number_and_incr (&mcnt, &p);
697 extract_number_and_incr (&mcnt2, &p);
698 printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
702 printf ("/wordbound");
706 printf ("/notwordbound");
718 printf ("/before_dot");
726 printf ("/after_dot");
730 printf ("/syntaxspec");
732 printf ("/%d", mcnt);
736 printf ("/notsyntaxspec");
738 printf ("/%d", mcnt);
743 printf ("/wordchar");
747 printf ("/notwordchar");
759 printf ("?%d", *(p-1));
765 printf ("%d:\tend of pattern.\n", p - start);
770 print_compiled_pattern (bufp)
771 struct re_pattern_buffer *bufp;
773 unsigned char *buffer = bufp->buffer;
775 print_partial_compiled_pattern (buffer, buffer + bufp->used);
776 printf ("%ld bytes used/%ld bytes allocated.\n", bufp->used, bufp->allocated);
778 if (bufp->fastmap_accurate && bufp->fastmap)
780 printf ("fastmap: ");
781 print_fastmap (bufp->fastmap);
784 printf ("re_nsub: %d\t", bufp->re_nsub);
785 printf ("regs_alloc: %d\t", bufp->regs_allocated);
786 printf ("can_be_null: %d\t", bufp->can_be_null);
787 printf ("newline_anchor: %d\n", bufp->newline_anchor);
788 printf ("no_sub: %d\t", bufp->no_sub);
789 printf ("not_bol: %d\t", bufp->not_bol);
790 printf ("not_eol: %d\t", bufp->not_eol);
791 printf ("syntax: %d\n", bufp->syntax);
792 /* Perhaps we should print the translate table? */
797 print_double_string (where, string1, size1, string2, size2)
810 if (FIRST_STRING_P (where))
812 for (this_char = where - string1; this_char < size1; this_char++)
813 printchar (string1[this_char]);
818 for (this_char = where - string2; this_char < size2; this_char++)
819 printchar (string2[this_char]);
823 #else /* not DEBUG */
828 #define DEBUG_STATEMENT(e)
829 #define DEBUG_PRINT1(x)
830 #define DEBUG_PRINT2(x1, x2)
831 #define DEBUG_PRINT3(x1, x2, x3)
832 #define DEBUG_PRINT4(x1, x2, x3, x4)
833 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
834 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
836 #endif /* not DEBUG */
838 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
839 also be assigned to arbitrarily: each pattern buffer stores its own
840 syntax, so it can be changed between regex compilations. */
841 reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
844 /* Specify the precise syntax of regexps for compilation. This provides
845 for compatibility for various utilities which historically have
846 different, incompatible syntaxes.
848 The argument SYNTAX is a bit mask comprised of the various bits
849 defined in regex.h. We return the old syntax. */
852 re_set_syntax (syntax)
855 reg_syntax_t ret = re_syntax_options;
857 re_syntax_options = syntax;
861 /* This table gives an error message for each of the error codes listed
862 in regex.h. Obviously the order here has to be same as there. */
864 static const char *re_error_msg[] =
865 { NULL, /* REG_NOERROR */
866 "No match", /* REG_NOMATCH */
867 "Invalid regular expression", /* REG_BADPAT */
868 "Invalid collation character", /* REG_ECOLLATE */
869 "Invalid character class name", /* REG_ECTYPE */
870 "Trailing backslash", /* REG_EESCAPE */
871 "Invalid back reference", /* REG_ESUBREG */
872 "Unmatched [ or [^", /* REG_EBRACK */
873 "Unmatched ( or \\(", /* REG_EPAREN */
874 "Unmatched \\{", /* REG_EBRACE */
875 "Invalid content of \\{\\}", /* REG_BADBR */
876 "Invalid range end", /* REG_ERANGE */
877 "Memory exhausted", /* REG_ESPACE */
878 "Invalid preceding regular expression", /* REG_BADRPT */
879 "Premature end of regular expression", /* REG_EEND */
880 "Regular expression too big", /* REG_ESIZE */
881 "Unmatched ) or \\)", /* REG_ERPAREN */
884 /* Avoiding alloca during matching, to placate r_alloc. */
886 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
887 searching and matching functions should not call alloca. On some
888 systems, alloca is implemented in terms of malloc, and if we're
889 using the relocating allocator routines, then malloc could cause a
890 relocation, which might (if the strings being searched are in the
891 ralloc heap) shift the data out from underneath the regexp
894 Here's another reason to avoid allocation: Emacs
895 processes input from X in a signal handler; processing X input may
896 call malloc; if input arrives while a matching routine is calling
897 malloc, then we're scrod. But Emacs can't just block input while
898 calling matching routines; then we don't notice interrupts when
899 they come in. So, Emacs blocks input around all regexp calls
900 except the matching calls, which it leaves unprotected, in the
901 faith that they will not malloc. */
903 /* Normally, this is fine. */
904 #define MATCH_MAY_ALLOCATE
906 /* The match routines may not allocate if (1) they would do it with malloc
907 and (2) it's not safe for htem to use malloc. */
908 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && (defined (emacs) || defined (REL_ALLOC))
909 #undef MATCH_MAY_ALLOCATE
913 /* Failure stack declarations and macros; both re_compile_fastmap and
914 re_match_2 use a failure stack. These have to be macros because of
918 /* Number of failure points for which to initially allocate space
919 when matching. If this number is exceeded, we allocate more
920 space, so it is not a hard limit. */
921 #ifndef INIT_FAILURE_ALLOC
922 #define INIT_FAILURE_ALLOC 5
925 /* Roughly the maximum number of failure points on the stack. Would be
926 exactly that if always used MAX_FAILURE_SPACE each time we failed.
927 This is a variable only so users of regex can assign to it; we never
928 change it ourselves. */
929 int re_max_failures = 2000;
931 typedef unsigned char *fail_stack_elt_t;
935 fail_stack_elt_t *stack;
937 unsigned avail; /* Offset of next open position. */
940 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
941 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
942 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
943 #define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])
946 /* Initialize `fail_stack'. Do `return -2' if the alloc fails. */
948 #ifdef MATCH_MAY_ALLOCATE
949 #define INIT_FAIL_STACK() \
951 fail_stack.stack = (fail_stack_elt_t *) \
952 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
954 if (fail_stack.stack == NULL) \
957 fail_stack.size = INIT_FAILURE_ALLOC; \
958 fail_stack.avail = 0; \
961 #define INIT_FAIL_STACK() \
963 fail_stack.avail = 0; \
968 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
970 Return 1 if succeeds, and 0 if either ran out of memory
971 allocating space for it or it was already too large.
973 REGEX_REALLOCATE requires `destination' be declared. */
975 #define DOUBLE_FAIL_STACK(fail_stack) \
976 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
978 : ((fail_stack).stack = (fail_stack_elt_t *) \
979 REGEX_REALLOCATE ((fail_stack).stack, \
980 (fail_stack).size * sizeof (fail_stack_elt_t), \
981 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
983 (fail_stack).stack == NULL \
985 : ((fail_stack).size <<= 1, \
989 /* Push PATTERN_OP on FAIL_STACK.
991 Return 1 if was able to do so and 0 if ran out of memory allocating
993 #define PUSH_PATTERN_OP(pattern_op, fail_stack) \
994 ((FAIL_STACK_FULL () \
995 && !DOUBLE_FAIL_STACK (fail_stack)) \
997 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \
1000 /* This pushes an item onto the failure stack. sizeof(ITEM) must be no
1001 larger than sizeof (unsigned char *). Assumes the variable `fail_stack'.
1002 Probably should only be called from within `PUSH_FAILURE_POINT'. */
1003 #define PUSH_FAILURE_ITEM(item) \
1006 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item; \
1010 /* The complement operation. Assumes `fail_stack' is nonempty. */
1011 #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
1013 /* Used to omit pushing failure point id's when we're not debugging. */
1015 #define DEBUG_PUSH PUSH_FAILURE_ITEM
1016 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
1018 #define DEBUG_PUSH(item)
1019 #define DEBUG_POP(item_addr)
1023 /* Push the information about the state we will need
1024 if we ever fail back to it.
1026 Requires variables fail_stack, regstart, regend, reg_info, and
1027 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
1030 Does `return FAILURE_CODE' if runs out of memory. */
1032 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1034 char *destination; \
1035 /* Must be int, so when we don't save any registers, the arithmetic \
1036 of 0 + -1 isn't done as unsigned. */ \
1039 DEBUG_STATEMENT (failure_id++); \
1040 DEBUG_STATEMENT (nfailure_points_pushed++); \
1041 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1042 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1043 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1045 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1046 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1048 /* Ensure we have enough space allocated for what we will push. */ \
1049 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1051 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1052 return failure_code; \
1054 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1055 (fail_stack).size); \
1056 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1059 /* Push the info, starting with the registers. */ \
1060 DEBUG_PRINT1 ("\n"); \
1062 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1065 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1066 DEBUG_STATEMENT (num_regs_pushed++); \
1068 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1069 PUSH_FAILURE_ITEM (regstart[this_reg]); \
1071 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1072 PUSH_FAILURE_ITEM (regend[this_reg]); \
1074 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
1075 DEBUG_PRINT2 (" match_null=%d", \
1076 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1077 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1078 DEBUG_PRINT2 (" matched_something=%d", \
1079 MATCHED_SOMETHING (reg_info[this_reg])); \
1080 DEBUG_PRINT2 (" ever_matched=%d", \
1081 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1082 DEBUG_PRINT1 ("\n"); \
1083 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \
1086 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1087 PUSH_FAILURE_ITEM (lowest_active_reg); \
1089 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1090 PUSH_FAILURE_ITEM (highest_active_reg); \
1092 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
1093 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1094 PUSH_FAILURE_ITEM (pattern_place); \
1096 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
1097 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1099 DEBUG_PRINT1 ("'\n"); \
1100 PUSH_FAILURE_ITEM (string_place); \
1102 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1103 DEBUG_PUSH (failure_id); \
1106 /* This is the number of items that are pushed and popped on the stack
1107 for each register. */
1108 #define NUM_REG_ITEMS 3
1110 /* Individual items aside from the registers. */
1112 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1114 #define NUM_NONREG_ITEMS 4
1117 /* We push at most this many items on the stack. */
1118 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1120 /* We actually push this many items. */
1121 #define NUM_FAILURE_ITEMS \
1122 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
1125 /* How many items can still be added to the stack without overflowing it. */
1126 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1129 /* Pops what PUSH_FAIL_STACK pushes.
1131 We restore into the parameters, all of which should be lvalues:
1132 STR -- the saved data position.
1133 PAT -- the saved pattern position.
1134 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1135 REGSTART, REGEND -- arrays of string positions.
1136 REG_INFO -- array of information about each subexpression.
1138 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1139 `pend', `string1', `size1', `string2', and `size2'. */
1141 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1143 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
1145 const unsigned char *string_temp; \
1147 assert (!FAIL_STACK_EMPTY ()); \
1149 /* Remove failure points and point to how many regs pushed. */ \
1150 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1151 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1152 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1154 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1156 DEBUG_POP (&failure_id); \
1157 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1159 /* If the saved string location is NULL, it came from an \
1160 on_failure_keep_string_jump opcode, and we want to throw away the \
1161 saved NULL, thus retaining our current position in the string. */ \
1162 string_temp = POP_FAILURE_ITEM (); \
1163 if (string_temp != NULL) \
1164 str = (const char *) string_temp; \
1166 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
1167 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1168 DEBUG_PRINT1 ("'\n"); \
1170 pat = (unsigned char *) POP_FAILURE_ITEM (); \
1171 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
1172 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1174 /* Restore register info. */ \
1175 high_reg = (unsigned long) POP_FAILURE_ITEM (); \
1176 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1178 low_reg = (unsigned long) POP_FAILURE_ITEM (); \
1179 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1181 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1183 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1185 reg_info[this_reg].word = POP_FAILURE_ITEM (); \
1186 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
1188 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \
1189 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1191 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \
1192 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1195 DEBUG_STATEMENT (nfailure_points_popped++); \
1196 } /* POP_FAILURE_POINT */
1200 /* Structure for per-register (a.k.a. per-group) information.
1201 This must not be longer than one word, because we push this value
1202 onto the failure stack. Other register information, such as the
1203 starting and ending positions (which are addresses), and the list of
1204 inner groups (which is a bits list) are maintained in separate
1207 We are making a (strictly speaking) nonportable assumption here: that
1208 the compiler will pack our bit fields into something that fits into
1209 the type of `word', i.e., is something that fits into one item on the
1213 fail_stack_elt_t word;
1216 /* This field is one if this group can match the empty string,
1217 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1218 #define MATCH_NULL_UNSET_VALUE 3
1219 unsigned match_null_string_p : 2;
1220 unsigned is_active : 1;
1221 unsigned matched_something : 1;
1222 unsigned ever_matched_something : 1;
1224 } register_info_type;
1226 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1227 #define IS_ACTIVE(R) ((R).bits.is_active)
1228 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1229 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1232 /* Call this when have matched a real character; it sets `matched' flags
1233 for the subexpressions which we are currently inside. Also records
1234 that those subexprs have matched. */
1235 #define SET_REGS_MATCHED() \
1239 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1241 MATCHED_SOMETHING (reg_info[r]) \
1242 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1249 /* Registers are set to a sentinel when they haven't yet matched. */
1250 #define REG_UNSET_VALUE ((char *) -1)
1251 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1255 /* How do we implement a missing MATCH_MAY_ALLOCATE?
1256 We make the fail stack a global thing, and then grow it to
1257 re_max_failures when we compile. */
1258 #ifndef MATCH_MAY_ALLOCATE
1259 static fail_stack_type fail_stack;
1261 static const char ** regstart, ** regend;
1262 static const char ** old_regstart, ** old_regend;
1263 static const char **best_regstart, **best_regend;
1264 static register_info_type *reg_info;
1265 static const char **reg_dummy;
1266 static register_info_type *reg_info_dummy;
1270 /* Subroutine declarations and macros for regex_compile. */
1272 static void store_op1 (), store_op2 ();
1273 static void insert_op1 (), insert_op2 ();
1274 static boolean at_begline_loc_p (), at_endline_loc_p ();
1275 static boolean group_in_compile_stack ();
1276 static reg_errcode_t compile_range ();
1278 /* Fetch the next character in the uncompiled pattern---translating it
1279 if necessary. Also cast from a signed character in the constant
1280 string passed to us by the user to an unsigned char that we can use
1281 as an array index (in, e.g., `translate'). */
1282 #define PATFETCH(c) \
1283 do {if (p == pend) return REG_EEND; \
1284 c = (unsigned char) *p++; \
1285 if (translate) c = translate[c]; \
1288 /* Fetch the next character in the uncompiled pattern, with no
1290 #define PATFETCH_RAW(c) \
1291 do {if (p == pend) return REG_EEND; \
1292 c = (unsigned char) *p++; \
1295 /* Go backwards one character in the pattern. */
1296 #define PATUNFETCH p--
1299 /* If `translate' is non-null, return translate[D], else just D. We
1300 cast the subscript to translate because some data is declared as
1301 `char *', to avoid warnings when a string constant is passed. But
1302 when we use a character as a subscript we must make it unsigned. */
1303 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
1306 /* Macros for outputting the compiled pattern into `buffer'. */
1308 /* If the buffer isn't allocated when it comes in, use this. */
1309 #define INIT_BUF_SIZE 32
1311 /* Make sure we have at least N more bytes of space in buffer. */
1312 #define GET_BUFFER_SPACE(n) \
1313 while (b - bufp->buffer + (n) > bufp->allocated) \
1316 /* Make sure we have one more byte of buffer space and then add C to it. */
1317 #define BUF_PUSH(c) \
1319 GET_BUFFER_SPACE (1); \
1320 *b++ = (unsigned char) (c); \
1324 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1325 #define BUF_PUSH_2(c1, c2) \
1327 GET_BUFFER_SPACE (2); \
1328 *b++ = (unsigned char) (c1); \
1329 *b++ = (unsigned char) (c2); \
1333 /* As with BUF_PUSH_2, except for three bytes. */
1334 #define BUF_PUSH_3(c1, c2, c3) \
1336 GET_BUFFER_SPACE (3); \
1337 *b++ = (unsigned char) (c1); \
1338 *b++ = (unsigned char) (c2); \
1339 *b++ = (unsigned char) (c3); \
1343 /* Store a jump with opcode OP at LOC to location TO. We store a
1344 relative address offset by the three bytes the jump itself occupies. */
1345 #define STORE_JUMP(op, loc, to) \
1346 store_op1 (op, loc, (to) - (loc) - 3)
1348 /* Likewise, for a two-argument jump. */
1349 #define STORE_JUMP2(op, loc, to, arg) \
1350 store_op2 (op, loc, (to) - (loc) - 3, arg)
1352 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1353 #define INSERT_JUMP(op, loc, to) \
1354 insert_op1 (op, loc, (to) - (loc) - 3, b)
1356 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1357 #define INSERT_JUMP2(op, loc, to, arg) \
1358 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1361 /* This is not an arbitrary limit: the arguments which represent offsets
1362 into the pattern are two bytes long. So if 2^16 bytes turns out to
1363 be too small, many things would have to change. */
1364 #define MAX_BUF_SIZE (1L << 16)
1367 /* Extend the buffer by twice its current size via realloc and
1368 reset the pointers that pointed into the old block to point to the
1369 correct places in the new one. If extending the buffer results in it
1370 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1371 #define EXTEND_BUFFER() \
1373 unsigned char *old_buffer = bufp->buffer; \
1374 if (bufp->allocated == MAX_BUF_SIZE) \
1376 bufp->allocated <<= 1; \
1377 if (bufp->allocated > MAX_BUF_SIZE) \
1378 bufp->allocated = MAX_BUF_SIZE; \
1379 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1380 if (bufp->buffer == NULL) \
1381 return REG_ESPACE; \
1382 /* If the buffer moved, move all the pointers into it. */ \
1383 if (old_buffer != bufp->buffer) \
1385 b = (b - old_buffer) + bufp->buffer; \
1386 begalt = (begalt - old_buffer) + bufp->buffer; \
1387 if (fixup_alt_jump) \
1388 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1390 laststart = (laststart - old_buffer) + bufp->buffer; \
1391 if (pending_exact) \
1392 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1397 /* Since we have one byte reserved for the register number argument to
1398 {start,stop}_memory, the maximum number of groups we can report
1399 things about is what fits in that byte. */
1400 #define MAX_REGNUM 255
1402 /* But patterns can have more than `MAX_REGNUM' registers. We just
1403 ignore the excess. */
1404 typedef unsigned regnum_t;
1407 /* Macros for the compile stack. */
1409 /* Since offsets can go either forwards or backwards, this type needs to
1410 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1411 typedef int pattern_offset_t;
1415 pattern_offset_t begalt_offset;
1416 pattern_offset_t fixup_alt_jump;
1417 pattern_offset_t inner_group_offset;
1418 pattern_offset_t laststart_offset;
1420 } compile_stack_elt_t;
1425 compile_stack_elt_t *stack;
1427 unsigned avail; /* Offset of next open position. */
1428 } compile_stack_type;
1431 #define INIT_COMPILE_STACK_SIZE 32
1433 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1434 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1436 /* The next available element. */
1437 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1440 /* Set the bit for character C in a list. */
1441 #define SET_LIST_BIT(c) \
1442 (b[((unsigned char) (c)) / BYTEWIDTH] \
1443 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1446 /* Get the next unsigned number in the uncompiled pattern. */
1447 #define GET_UNSIGNED_NUMBER(num) \
1451 while (ISDIGIT (c)) \
1455 num = num * 10 + c - '0'; \
1463 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1465 #define IS_CHAR_CLASS(string) \
1466 (STREQ (string, "alpha") || STREQ (string, "upper") \
1467 || STREQ (string, "lower") || STREQ (string, "digit") \
1468 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1469 || STREQ (string, "space") || STREQ (string, "print") \
1470 || STREQ (string, "punct") || STREQ (string, "graph") \
1471 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1473 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1474 Returns one of error codes defined in `regex.h', or zero for success.
1476 Assumes the `allocated' (and perhaps `buffer') and `translate'
1477 fields are set in BUFP on entry.
1479 If it succeeds, results are put in BUFP (if it returns an error, the
1480 contents of BUFP are undefined):
1481 `buffer' is the compiled pattern;
1482 `syntax' is set to SYNTAX;
1483 `used' is set to the length of the compiled pattern;
1484 `fastmap_accurate' is zero;
1485 `re_nsub' is the number of subexpressions in PATTERN;
1486 `not_bol' and `not_eol' are zero;
1488 The `fastmap' and `newline_anchor' fields are neither
1489 examined nor set. */
1491 /* Return, freeing storage we allocated. */
1492 #define FREE_STACK_RETURN(value) \
1493 return (free (compile_stack.stack), value)
1495 static reg_errcode_t
1496 regex_compile (pattern, size, syntax, bufp)
1497 const char *pattern;
1499 reg_syntax_t syntax;
1500 struct re_pattern_buffer *bufp;
1502 /* We fetch characters from PATTERN here. Even though PATTERN is
1503 `char *' (i.e., signed), we declare these variables as unsigned, so
1504 they can be reliably used as array indices. */
1505 register unsigned char c, c1;
1507 /* A random temporary spot in PATTERN. */
1510 /* Points to the end of the buffer, where we should append. */
1511 register unsigned char *b;
1513 /* Keeps track of unclosed groups. */
1514 compile_stack_type compile_stack;
1516 /* Points to the current (ending) position in the pattern. */
1517 const char *p = pattern;
1518 const char *pend = pattern + size;
1520 /* How to translate the characters in the pattern. */
1521 char *translate = bufp->translate;
1523 /* Address of the count-byte of the most recently inserted `exactn'
1524 command. This makes it possible to tell if a new exact-match
1525 character can be added to that command or if the character requires
1526 a new `exactn' command. */
1527 unsigned char *pending_exact = 0;
1529 /* Address of start of the most recently finished expression.
1530 This tells, e.g., postfix * where to find the start of its
1531 operand. Reset at the beginning of groups and alternatives. */
1532 unsigned char *laststart = 0;
1534 /* Address of beginning of regexp, or inside of last group. */
1535 unsigned char *begalt;
1537 /* Place in the uncompiled pattern (i.e., the {) to
1538 which to go back if the interval is invalid. */
1539 const char *beg_interval;
1541 /* Address of the place where a forward jump should go to the end of
1542 the containing expression. Each alternative of an `or' -- except the
1543 last -- ends with a forward jump of this sort. */
1544 unsigned char *fixup_alt_jump = 0;
1546 /* Counts open-groups as they are encountered. Remembered for the
1547 matching close-group on the compile stack, so the same register
1548 number is put in the stop_memory as the start_memory. */
1549 regnum_t regnum = 0;
1552 DEBUG_PRINT1 ("\nCompiling pattern: ");
1555 unsigned debug_count;
1557 for (debug_count = 0; debug_count < size; debug_count++)
1558 printchar (pattern[debug_count]);
1563 /* Initialize the compile stack. */
1564 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1565 if (compile_stack.stack == NULL)
1568 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1569 compile_stack.avail = 0;
1571 /* Initialize the pattern buffer. */
1572 bufp->syntax = syntax;
1573 bufp->fastmap_accurate = 0;
1574 bufp->not_bol = bufp->not_eol = 0;
1576 /* Set `used' to zero, so that if we return an error, the pattern
1577 printer (for debugging) will think there's no pattern. We reset it
1581 /* Always count groups, whether or not bufp->no_sub is set. */
1584 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1585 /* Initialize the syntax table. */
1586 init_syntax_once ();
1589 if (bufp->allocated == 0)
1592 { /* If zero allocated, but buffer is non-null, try to realloc
1593 enough space. This loses if buffer's address is bogus, but
1594 that is the user's responsibility. */
1595 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1598 { /* Caller did not allocate a buffer. Do it for them. */
1599 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1601 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1603 bufp->allocated = INIT_BUF_SIZE;
1606 begalt = b = bufp->buffer;
1608 /* Loop through the uncompiled pattern until we're at the end. */
1617 if ( /* If at start of pattern, it's an operator. */
1619 /* If context independent, it's an operator. */
1620 || syntax & RE_CONTEXT_INDEP_ANCHORS
1621 /* Otherwise, depends on what's come before. */
1622 || at_begline_loc_p (pattern, p, syntax))
1632 if ( /* If at end of pattern, it's an operator. */
1634 /* If context independent, it's an operator. */
1635 || syntax & RE_CONTEXT_INDEP_ANCHORS
1636 /* Otherwise, depends on what's next. */
1637 || at_endline_loc_p (p, pend, syntax))
1647 if ((syntax & RE_BK_PLUS_QM)
1648 || (syntax & RE_LIMITED_OPS))
1652 /* If there is no previous pattern... */
1655 if (syntax & RE_CONTEXT_INVALID_OPS)
1656 FREE_STACK_RETURN (REG_BADRPT);
1657 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1662 /* Are we optimizing this jump? */
1663 boolean keep_string_p = false;
1665 /* 1 means zero (many) matches is allowed. */
1666 char zero_times_ok = 0, many_times_ok = 0;
1668 /* If there is a sequence of repetition chars, collapse it
1669 down to just one (the right one). We can't combine
1670 interval operators with these because of, e.g., `a{2}*',
1671 which should only match an even number of `a's. */
1675 zero_times_ok |= c != '+';
1676 many_times_ok |= c != '?';
1684 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1687 else if (syntax & RE_BK_PLUS_QM && c == '\\')
1689 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1692 if (!(c1 == '+' || c1 == '?'))
1707 /* If we get here, we found another repeat character. */
1710 /* Star, etc. applied to an empty pattern is equivalent
1711 to an empty pattern. */
1715 /* Now we know whether or not zero matches is allowed
1716 and also whether or not two or more matches is allowed. */
1718 { /* More than one repetition is allowed, so put in at the
1719 end a backward relative jump from `b' to before the next
1720 jump we're going to put in below (which jumps from
1721 laststart to after this jump).
1723 But if we are at the `*' in the exact sequence `.*\n',
1724 insert an unconditional jump backwards to the .,
1725 instead of the beginning of the loop. This way we only
1726 push a failure point once, instead of every time
1727 through the loop. */
1728 assert (p - 1 > pattern);
1730 /* Allocate the space for the jump. */
1731 GET_BUFFER_SPACE (3);
1733 /* We know we are not at the first character of the pattern,
1734 because laststart was nonzero. And we've already
1735 incremented `p', by the way, to be the character after
1736 the `*'. Do we have to do something analogous here
1737 for null bytes, because of RE_DOT_NOT_NULL? */
1738 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1740 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1741 && !(syntax & RE_DOT_NEWLINE))
1742 { /* We have .*\n. */
1743 STORE_JUMP (jump, b, laststart);
1744 keep_string_p = true;
1747 /* Anything else. */
1748 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1750 /* We've added more stuff to the buffer. */
1754 /* On failure, jump from laststart to b + 3, which will be the
1755 end of the buffer after this jump is inserted. */
1756 GET_BUFFER_SPACE (3);
1757 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1765 /* At least one repetition is required, so insert a
1766 `dummy_failure_jump' before the initial
1767 `on_failure_jump' instruction of the loop. This
1768 effects a skip over that instruction the first time
1769 we hit that loop. */
1770 GET_BUFFER_SPACE (3);
1771 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1786 boolean had_char_class = false;
1788 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1790 /* Ensure that we have enough space to push a charset: the
1791 opcode, the length count, and the bitset; 34 bytes in all. */
1792 GET_BUFFER_SPACE (34);
1796 /* We test `*p == '^' twice, instead of using an if
1797 statement, so we only need one BUF_PUSH. */
1798 BUF_PUSH (*p == '^' ? charset_not : charset);
1802 /* Remember the first position in the bracket expression. */
1805 /* Push the number of bytes in the bitmap. */
1806 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1808 /* Clear the whole map. */
1809 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1811 /* charset_not matches newline according to a syntax bit. */
1812 if ((re_opcode_t) b[-2] == charset_not
1813 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1814 SET_LIST_BIT ('\n');
1816 /* Read in characters and ranges, setting map bits. */
1819 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1823 /* \ might escape characters inside [...] and [^...]. */
1824 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1826 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1833 /* Could be the end of the bracket expression. If it's
1834 not (i.e., when the bracket expression is `[]' so
1835 far), the ']' character bit gets set way below. */
1836 if (c == ']' && p != p1 + 1)
1839 /* Look ahead to see if it's a range when the last thing
1840 was a character class. */
1841 if (had_char_class && c == '-' && *p != ']')
1842 FREE_STACK_RETURN (REG_ERANGE);
1844 /* Look ahead to see if it's a range when the last thing
1845 was a character: if this is a hyphen not at the
1846 beginning or the end of a list, then it's the range
1849 && !(p - 2 >= pattern && p[-2] == '[')
1850 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1854 = compile_range (&p, pend, translate, syntax, b);
1855 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
1858 else if (p[0] == '-' && p[1] != ']')
1859 { /* This handles ranges made up of characters only. */
1862 /* Move past the `-'. */
1865 ret = compile_range (&p, pend, translate, syntax, b);
1866 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
1869 /* See if we're at the beginning of a possible character
1872 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
1873 { /* Leave room for the null. */
1874 char str[CHAR_CLASS_MAX_LENGTH + 1];
1879 /* If pattern is `[[:'. */
1880 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1885 if (c == ':' || c == ']' || p == pend
1886 || c1 == CHAR_CLASS_MAX_LENGTH)
1892 /* If isn't a word bracketed by `[:' and:`]':
1893 undo the ending character, the letters, and leave
1894 the leading `:' and `[' (but set bits for them). */
1895 if (c == ':' && *p == ']')
1898 boolean is_alnum = STREQ (str, "alnum");
1899 boolean is_alpha = STREQ (str, "alpha");
1900 boolean is_blank = STREQ (str, "blank");
1901 boolean is_cntrl = STREQ (str, "cntrl");
1902 boolean is_digit = STREQ (str, "digit");
1903 boolean is_graph = STREQ (str, "graph");
1904 boolean is_lower = STREQ (str, "lower");
1905 boolean is_print = STREQ (str, "print");
1906 boolean is_punct = STREQ (str, "punct");
1907 boolean is_space = STREQ (str, "space");
1908 boolean is_upper = STREQ (str, "upper");
1909 boolean is_xdigit = STREQ (str, "xdigit");
1911 if (!IS_CHAR_CLASS (str))
1912 FREE_STACK_RETURN (REG_ECTYPE);
1914 /* Throw away the ] at the end of the character
1918 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1920 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
1922 /* This was split into 3 if's to
1923 avoid an arbitrary limit in some compiler. */
1924 if ( (is_alnum && ISALNUM (ch))
1925 || (is_alpha && ISALPHA (ch))
1926 || (is_blank && ISBLANK (ch))
1927 || (is_cntrl && ISCNTRL (ch)))
1929 if ( (is_digit && ISDIGIT (ch))
1930 || (is_graph && ISGRAPH (ch))
1931 || (is_lower && ISLOWER (ch))
1932 || (is_print && ISPRINT (ch)))
1934 if ( (is_punct && ISPUNCT (ch))
1935 || (is_space && ISSPACE (ch))
1936 || (is_upper && ISUPPER (ch))
1937 || (is_xdigit && ISXDIGIT (ch)))
1940 had_char_class = true;
1949 had_char_class = false;
1954 had_char_class = false;
1959 /* Discard any (non)matching list bytes that are all 0 at the
1960 end of the map. Decrease the map-length byte too. */
1961 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
1969 if (syntax & RE_NO_BK_PARENS)
1976 if (syntax & RE_NO_BK_PARENS)
1983 if (syntax & RE_NEWLINE_ALT)
1990 if (syntax & RE_NO_BK_VBAR)
1997 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1998 goto handle_interval;
2004 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2006 /* Do not translate the character after the \, so that we can
2007 distinguish, e.g., \B from \b, even if we normally would
2008 translate, e.g., B to b. */
2014 if (syntax & RE_NO_BK_PARENS)
2015 goto normal_backslash;
2021 if (COMPILE_STACK_FULL)
2023 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2024 compile_stack_elt_t);
2025 if (compile_stack.stack == NULL) return REG_ESPACE;
2027 compile_stack.size <<= 1;
2030 /* These are the values to restore when we hit end of this
2031 group. They are all relative offsets, so that if the
2032 whole pattern moves because of realloc, they will still
2034 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2035 COMPILE_STACK_TOP.fixup_alt_jump
2036 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2037 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2038 COMPILE_STACK_TOP.regnum = regnum;
2040 /* We will eventually replace the 0 with the number of
2041 groups inner to this one. But do not push a
2042 start_memory for groups beyond the last one we can
2043 represent in the compiled pattern. */
2044 if (regnum <= MAX_REGNUM)
2046 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2047 BUF_PUSH_3 (start_memory, regnum, 0);
2050 compile_stack.avail++;
2055 /* If we've reached MAX_REGNUM groups, then this open
2056 won't actually generate any code, so we'll have to
2057 clear pending_exact explicitly. */
2063 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2065 if (COMPILE_STACK_EMPTY)
2066 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2067 goto normal_backslash;
2069 FREE_STACK_RETURN (REG_ERPAREN);
2073 { /* Push a dummy failure point at the end of the
2074 alternative for a possible future
2075 `pop_failure_jump' to pop. See comments at
2076 `push_dummy_failure' in `re_match_2'. */
2077 BUF_PUSH (push_dummy_failure);
2079 /* We allocated space for this jump when we assigned
2080 to `fixup_alt_jump', in the `handle_alt' case below. */
2081 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2084 /* See similar code for backslashed left paren above. */
2085 if (COMPILE_STACK_EMPTY)
2086 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2089 FREE_STACK_RETURN (REG_ERPAREN);
2091 /* Since we just checked for an empty stack above, this
2092 ``can't happen''. */
2093 assert (compile_stack.avail != 0);
2095 /* We don't just want to restore into `regnum', because
2096 later groups should continue to be numbered higher,
2097 as in `(ab)c(de)' -- the second group is #2. */
2098 regnum_t this_group_regnum;
2100 compile_stack.avail--;
2101 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2103 = COMPILE_STACK_TOP.fixup_alt_jump
2104 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2106 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2107 this_group_regnum = COMPILE_STACK_TOP.regnum;
2108 /* If we've reached MAX_REGNUM groups, then this open
2109 won't actually generate any code, so we'll have to
2110 clear pending_exact explicitly. */
2113 /* We're at the end of the group, so now we know how many
2114 groups were inside this one. */
2115 if (this_group_regnum <= MAX_REGNUM)
2117 unsigned char *inner_group_loc
2118 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2120 *inner_group_loc = regnum - this_group_regnum;
2121 BUF_PUSH_3 (stop_memory, this_group_regnum,
2122 regnum - this_group_regnum);
2128 case '|': /* `\|'. */
2129 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2130 goto normal_backslash;
2132 if (syntax & RE_LIMITED_OPS)
2135 /* Insert before the previous alternative a jump which
2136 jumps to this alternative if the former fails. */
2137 GET_BUFFER_SPACE (3);
2138 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2142 /* The alternative before this one has a jump after it
2143 which gets executed if it gets matched. Adjust that
2144 jump so it will jump to this alternative's analogous
2145 jump (put in below, which in turn will jump to the next
2146 (if any) alternative's such jump, etc.). The last such
2147 jump jumps to the correct final destination. A picture:
2153 If we are at `b', then fixup_alt_jump right now points to a
2154 three-byte space after `a'. We'll put in the jump, set
2155 fixup_alt_jump to right after `b', and leave behind three
2156 bytes which we'll fill in when we get to after `c'. */
2159 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2161 /* Mark and leave space for a jump after this alternative,
2162 to be filled in later either by next alternative or
2163 when know we're at the end of a series of alternatives. */
2165 GET_BUFFER_SPACE (3);
2174 /* If \{ is a literal. */
2175 if (!(syntax & RE_INTERVALS)
2176 /* If we're at `\{' and it's not the open-interval
2178 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2179 || (p - 2 == pattern && p == pend))
2180 goto normal_backslash;
2184 /* If got here, then the syntax allows intervals. */
2186 /* At least (most) this many matches must be made. */
2187 int lower_bound = -1, upper_bound = -1;
2189 beg_interval = p - 1;
2193 if (syntax & RE_NO_BK_BRACES)
2194 goto unfetch_interval;
2196 FREE_STACK_RETURN (REG_EBRACE);
2199 GET_UNSIGNED_NUMBER (lower_bound);
2203 GET_UNSIGNED_NUMBER (upper_bound);
2204 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2207 /* Interval such as `{1}' => match exactly once. */
2208 upper_bound = lower_bound;
2210 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2211 || lower_bound > upper_bound)
2213 if (syntax & RE_NO_BK_BRACES)
2214 goto unfetch_interval;
2216 FREE_STACK_RETURN (REG_BADBR);
2219 if (!(syntax & RE_NO_BK_BRACES))
2221 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2228 if (syntax & RE_NO_BK_BRACES)
2229 goto unfetch_interval;
2231 FREE_STACK_RETURN (REG_BADBR);
2234 /* We just parsed a valid interval. */
2236 /* If it's invalid to have no preceding re. */
2239 if (syntax & RE_CONTEXT_INVALID_OPS)
2240 FREE_STACK_RETURN (REG_BADRPT);
2241 else if (syntax & RE_CONTEXT_INDEP_OPS)
2244 goto unfetch_interval;
2247 /* If the upper bound is zero, don't want to succeed at
2248 all; jump from `laststart' to `b + 3', which will be
2249 the end of the buffer after we insert the jump. */
2250 if (upper_bound == 0)
2252 GET_BUFFER_SPACE (3);
2253 INSERT_JUMP (jump, laststart, b + 3);
2257 /* Otherwise, we have a nontrivial interval. When
2258 we're all done, the pattern will look like:
2259 set_number_at <jump count> <upper bound>
2260 set_number_at <succeed_n count> <lower bound>
2261 succeed_n <after jump addr> <succeed_n count>
2263 jump_n <succeed_n addr> <jump count>
2264 (The upper bound and `jump_n' are omitted if
2265 `upper_bound' is 1, though.) */
2267 { /* If the upper bound is > 1, we need to insert
2268 more at the end of the loop. */
2269 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2271 GET_BUFFER_SPACE (nbytes);
2273 /* Initialize lower bound of the `succeed_n', even
2274 though it will be set during matching by its
2275 attendant `set_number_at' (inserted next),
2276 because `re_compile_fastmap' needs to know.
2277 Jump to the `jump_n' we might insert below. */
2278 INSERT_JUMP2 (succeed_n, laststart,
2279 b + 5 + (upper_bound > 1) * 5,
2283 /* Code to initialize the lower bound. Insert
2284 before the `succeed_n'. The `5' is the last two
2285 bytes of this `set_number_at', plus 3 bytes of
2286 the following `succeed_n'. */
2287 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2290 if (upper_bound > 1)
2291 { /* More than one repetition is allowed, so
2292 append a backward jump to the `succeed_n'
2293 that starts this interval.
2295 When we've reached this during matching,
2296 we'll have matched the interval once, so
2297 jump back only `upper_bound - 1' times. */
2298 STORE_JUMP2 (jump_n, b, laststart + 5,
2302 /* The location we want to set is the second
2303 parameter of the `jump_n'; that is `b-2' as
2304 an absolute address. `laststart' will be
2305 the `set_number_at' we're about to insert;
2306 `laststart+3' the number to set, the source
2307 for the relative address. But we are
2308 inserting into the middle of the pattern --
2309 so everything is getting moved up by 5.
2310 Conclusion: (b - 2) - (laststart + 3) + 5,
2311 i.e., b - laststart.
2313 We insert this at the beginning of the loop
2314 so that if we fail during matching, we'll
2315 reinitialize the bounds. */
2316 insert_op2 (set_number_at, laststart, b - laststart,
2317 upper_bound - 1, b);
2322 beg_interval = NULL;
2327 /* If an invalid interval, match the characters as literals. */
2328 assert (beg_interval);
2330 beg_interval = NULL;
2332 /* normal_char and normal_backslash need `c'. */
2335 if (!(syntax & RE_NO_BK_BRACES))
2337 if (p > pattern && p[-1] == '\\')
2338 goto normal_backslash;
2343 /* There is no way to specify the before_dot and after_dot
2344 operators. rms says this is ok. --karl */
2352 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2358 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2365 BUF_PUSH (wordchar);
2371 BUF_PUSH (notwordchar);
2384 BUF_PUSH (wordbound);
2388 BUF_PUSH (notwordbound);
2399 case '1': case '2': case '3': case '4': case '5':
2400 case '6': case '7': case '8': case '9':
2401 if (syntax & RE_NO_BK_REFS)
2407 FREE_STACK_RETURN (REG_ESUBREG);
2409 /* Can't back reference to a subexpression if inside of it. */
2410 if (group_in_compile_stack (compile_stack, c1))
2414 BUF_PUSH_2 (duplicate, c1);
2420 if (syntax & RE_BK_PLUS_QM)
2423 goto normal_backslash;
2427 /* You might think it would be useful for \ to mean
2428 not to translate; but if we don't translate it
2429 it will never match anything. */
2437 /* Expects the character in `c'. */
2439 /* If no exactn currently being built. */
2442 /* If last exactn not at current position. */
2443 || pending_exact + *pending_exact + 1 != b
2445 /* We have only one byte following the exactn for the count. */
2446 || *pending_exact == (1 << BYTEWIDTH) - 1
2448 /* If followed by a repetition operator. */
2449 || *p == '*' || *p == '^'
2450 || ((syntax & RE_BK_PLUS_QM)
2451 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2452 : (*p == '+' || *p == '?'))
2453 || ((syntax & RE_INTERVALS)
2454 && ((syntax & RE_NO_BK_BRACES)
2456 : (p[0] == '\\' && p[1] == '{'))))
2458 /* Start building a new exactn. */
2462 BUF_PUSH_2 (exactn, 0);
2463 pending_exact = b - 1;
2470 } /* while p != pend */
2473 /* Through the pattern now. */
2476 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2478 if (!COMPILE_STACK_EMPTY)
2479 FREE_STACK_RETURN (REG_EPAREN);
2481 free (compile_stack.stack);
2483 /* We have succeeded; set the length of the buffer. */
2484 bufp->used = b - bufp->buffer;
2489 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2490 print_compiled_pattern (bufp);
2494 #ifndef MATCH_MAY_ALLOCATE
2495 /* Initialize the failure stack to the largest possible stack. This
2496 isn't necessary unless we're trying to avoid calling alloca in
2497 the search and match routines. */
2499 int num_regs = bufp->re_nsub + 1;
2501 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
2502 is strictly greater than re_max_failures, the largest possible stack
2503 is 2 * re_max_failures failure points. */
2504 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
2506 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
2509 if (! fail_stack.stack)
2511 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2512 * sizeof (fail_stack_elt_t));
2515 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2517 * sizeof (fail_stack_elt_t)));
2518 #else /* not emacs */
2519 if (! fail_stack.stack)
2521 = (fail_stack_elt_t *) malloc (fail_stack.size
2522 * sizeof (fail_stack_elt_t));
2525 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2527 * sizeof (fail_stack_elt_t)));
2528 #endif /* not emacs */
2531 /* Initialize some other variables the matcher uses. */
2532 RETALLOC_IF (regstart, num_regs, const char *);
2533 RETALLOC_IF (regend, num_regs, const char *);
2534 RETALLOC_IF (old_regstart, num_regs, const char *);
2535 RETALLOC_IF (old_regend, num_regs, const char *);
2536 RETALLOC_IF (best_regstart, num_regs, const char *);
2537 RETALLOC_IF (best_regend, num_regs, const char *);
2538 RETALLOC_IF (reg_info, num_regs, register_info_type);
2539 RETALLOC_IF (reg_dummy, num_regs, const char *);
2540 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
2545 } /* regex_compile */
2547 /* Subroutines for `regex_compile'. */
2549 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2552 store_op1 (op, loc, arg)
2557 *loc = (unsigned char) op;
2558 STORE_NUMBER (loc + 1, arg);
2562 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2565 store_op2 (op, loc, arg1, arg2)
2570 *loc = (unsigned char) op;
2571 STORE_NUMBER (loc + 1, arg1);
2572 STORE_NUMBER (loc + 3, arg2);
2576 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2577 for OP followed by two-byte integer parameter ARG. */
2580 insert_op1 (op, loc, arg, end)
2586 register unsigned char *pfrom = end;
2587 register unsigned char *pto = end + 3;
2589 while (pfrom != loc)
2592 store_op1 (op, loc, arg);
2596 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2599 insert_op2 (op, loc, arg1, arg2, end)
2605 register unsigned char *pfrom = end;
2606 register unsigned char *pto = end + 5;
2608 while (pfrom != loc)
2611 store_op2 (op, loc, arg1, arg2);
2615 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2616 after an alternative or a begin-subexpression. We assume there is at
2617 least one character before the ^. */
2620 at_begline_loc_p (pattern, p, syntax)
2621 const char *pattern, *p;
2622 reg_syntax_t syntax;
2624 const char *prev = p - 2;
2625 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2628 /* After a subexpression? */
2629 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2630 /* After an alternative? */
2631 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2635 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2636 at least one character after the $, i.e., `P < PEND'. */
2639 at_endline_loc_p (p, pend, syntax)
2640 const char *p, *pend;
2643 const char *next = p;
2644 boolean next_backslash = *next == '\\';
2645 const char *next_next = p + 1 < pend ? p + 1 : NULL;
2648 /* Before a subexpression? */
2649 (syntax & RE_NO_BK_PARENS ? *next == ')'
2650 : next_backslash && next_next && *next_next == ')')
2651 /* Before an alternative? */
2652 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2653 : next_backslash && next_next && *next_next == '|');
2657 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2658 false if it's not. */
2661 group_in_compile_stack (compile_stack, regnum)
2662 compile_stack_type compile_stack;
2667 for (this_element = compile_stack.avail - 1;
2670 if (compile_stack.stack[this_element].regnum == regnum)
2677 /* Read the ending character of a range (in a bracket expression) from the
2678 uncompiled pattern *P_PTR (which ends at PEND). We assume the
2679 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2680 Then we set the translation of all bits between the starting and
2681 ending characters (inclusive) in the compiled pattern B.
2683 Return an error code.
2685 We use these short variable names so we can use the same macros as
2686 `regex_compile' itself. */
2688 static reg_errcode_t
2689 compile_range (p_ptr, pend, translate, syntax, b)
2690 const char **p_ptr, *pend;
2692 reg_syntax_t syntax;
2697 const char *p = *p_ptr;
2698 int range_start, range_end;
2703 /* Even though the pattern is a signed `char *', we need to fetch
2704 with unsigned char *'s; if the high bit of the pattern character
2705 is set, the range endpoints will be negative if we fetch using a
2708 We also want to fetch the endpoints without translating them; the
2709 appropriate translation is done in the bit-setting loop below. */
2710 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
2711 range_start = ((const unsigned char *) p)[-2];
2712 range_end = ((const unsigned char *) p)[0];
2714 /* Have to increment the pointer into the pattern string, so the
2715 caller isn't still at the ending character. */
2718 /* If the start is after the end, the range is empty. */
2719 if (range_start > range_end)
2720 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2722 /* Here we see why `this_char' has to be larger than an `unsigned
2723 char' -- the range is inclusive, so if `range_end' == 0xff
2724 (assuming 8-bit characters), we would otherwise go into an infinite
2725 loop, since all characters <= 0xff. */
2726 for (this_char = range_start; this_char <= range_end; this_char++)
2728 SET_LIST_BIT (TRANSLATE (this_char));
2734 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2735 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2736 characters can start a string that matches the pattern. This fastmap
2737 is used by re_search to skip quickly over impossible starting points.
2739 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2740 area as BUFP->fastmap.
2742 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2745 Returns 0 if we succeed, -2 if an internal error. */
2748 re_compile_fastmap (bufp)
2749 struct re_pattern_buffer *bufp;
2752 #ifdef MATCH_MAY_ALLOCATE
2753 fail_stack_type fail_stack;
2755 #ifndef REGEX_MALLOC
2758 /* We don't push any register information onto the failure stack. */
2759 unsigned num_regs = 0;
2761 register char *fastmap = bufp->fastmap;
2762 unsigned char *pattern = bufp->buffer;
2763 unsigned long size = bufp->used;
2764 unsigned char *p = pattern;
2765 register unsigned char *pend = pattern + size;
2767 /* Assume that each path through the pattern can be null until
2768 proven otherwise. We set this false at the bottom of switch
2769 statement, to which we get only if a particular path doesn't
2770 match the empty string. */
2771 boolean path_can_be_null = true;
2773 /* We aren't doing a `succeed_n' to begin with. */
2774 boolean succeed_n_p = false;
2776 assert (fastmap != NULL && p != NULL);
2779 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
2780 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2781 bufp->can_be_null = 0;
2783 while (p != pend || !FAIL_STACK_EMPTY ())
2787 bufp->can_be_null |= path_can_be_null;
2789 /* Reset for next path. */
2790 path_can_be_null = true;
2792 p = fail_stack.stack[--fail_stack.avail];
2795 /* We should never be about to go beyond the end of the pattern. */
2798 #ifdef SWITCH_ENUM_BUG
2799 switch ((int) ((re_opcode_t) *p++))
2801 switch ((re_opcode_t) *p++)
2805 /* I guess the idea here is to simply not bother with a fastmap
2806 if a backreference is used, since it's too hard to figure out
2807 the fastmap for the corresponding group. Setting
2808 `can_be_null' stops `re_search_2' from using the fastmap, so
2809 that is all we do. */
2811 bufp->can_be_null = 1;
2815 /* Following are the cases which match a character. These end
2824 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2825 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2831 /* Chars beyond end of map must be allowed. */
2832 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2835 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2836 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2842 for (j = 0; j < (1 << BYTEWIDTH); j++)
2843 if (SYNTAX (j) == Sword)
2849 for (j = 0; j < (1 << BYTEWIDTH); j++)
2850 if (SYNTAX (j) != Sword)
2857 int fastmap_newline = fastmap['\n'];
2859 /* `.' matches anything ... */
2860 for (j = 0; j < (1 << BYTEWIDTH); j++)
2863 /* ... except perhaps newline. */
2864 if (!(bufp->syntax & RE_DOT_NEWLINE))
2865 fastmap['\n'] = fastmap_newline;
2867 /* Return if we have already set `can_be_null'; if we have,
2868 then the fastmap is irrelevant. Something's wrong here. */
2869 else if (bufp->can_be_null)
2872 /* Otherwise, have to check alternative paths. */
2879 for (j = 0; j < (1 << BYTEWIDTH); j++)
2880 if (SYNTAX (j) == (enum syntaxcode) k)
2887 for (j = 0; j < (1 << BYTEWIDTH); j++)
2888 if (SYNTAX (j) != (enum syntaxcode) k)
2893 /* All cases after this match the empty string. These end with
2901 #endif /* not emacs */
2913 case push_dummy_failure:
2918 case pop_failure_jump:
2919 case maybe_pop_jump:
2922 case dummy_failure_jump:
2923 EXTRACT_NUMBER_AND_INCR (j, p);
2928 /* Jump backward implies we just went through the body of a
2929 loop and matched nothing. Opcode jumped to should be
2930 `on_failure_jump' or `succeed_n'. Just treat it like an
2931 ordinary jump. For a * loop, it has pushed its failure
2932 point already; if so, discard that as redundant. */
2933 if ((re_opcode_t) *p != on_failure_jump
2934 && (re_opcode_t) *p != succeed_n)
2938 EXTRACT_NUMBER_AND_INCR (j, p);
2941 /* If what's on the stack is where we are now, pop it. */
2942 if (!FAIL_STACK_EMPTY ()
2943 && fail_stack.stack[fail_stack.avail - 1] == p)
2949 case on_failure_jump:
2950 case on_failure_keep_string_jump:
2951 handle_on_failure_jump:
2952 EXTRACT_NUMBER_AND_INCR (j, p);
2954 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2955 end of the pattern. We don't want to push such a point,
2956 since when we restore it above, entering the switch will
2957 increment `p' past the end of the pattern. We don't need
2958 to push such a point since we obviously won't find any more
2959 fastmap entries beyond `pend'. Such a pattern can match
2960 the null string, though. */
2963 if (!PUSH_PATTERN_OP (p + j, fail_stack))
2967 bufp->can_be_null = 1;
2971 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
2972 succeed_n_p = false;
2979 /* Get to the number of times to succeed. */
2982 /* Increment p past the n for when k != 0. */
2983 EXTRACT_NUMBER_AND_INCR (k, p);
2987 succeed_n_p = true; /* Spaghetti code alert. */
2988 goto handle_on_failure_jump;
3005 abort (); /* We have listed all the cases. */
3008 /* Getting here means we have found the possible starting
3009 characters for one path of the pattern -- and that the empty
3010 string does not match. We need not follow this path further.
3011 Instead, look at the next alternative (remembered on the
3012 stack), or quit if no more. The test at the top of the loop
3013 does these things. */
3014 path_can_be_null = false;
3018 /* Set `can_be_null' for the last path (also the first path, if the
3019 pattern is empty). */
3020 bufp->can_be_null |= path_can_be_null;
3022 } /* re_compile_fastmap */
3024 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3025 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3026 this memory for recording register information. STARTS and ENDS
3027 must be allocated using the malloc library routine, and must each
3028 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3030 If NUM_REGS == 0, then subsequent matches should allocate their own
3033 Unless this function is called, the first search or match using
3034 PATTERN_BUFFER will allocate its own register data, without
3035 freeing the old data. */
3038 re_set_registers (bufp, regs, num_regs, starts, ends)
3039 struct re_pattern_buffer *bufp;
3040 struct re_registers *regs;
3042 regoff_t *starts, *ends;
3046 bufp->regs_allocated = REGS_REALLOCATE;
3047 regs->num_regs = num_regs;
3048 regs->start = starts;
3053 bufp->regs_allocated = REGS_UNALLOCATED;
3055 regs->start = regs->end = (regoff_t *) 0;
3059 /* Searching routines. */
3061 /* Like re_search_2, below, but only one string is specified, and
3062 doesn't let you say where to stop matching. */
3065 re_search (bufp, string, size, startpos, range, regs)
3066 struct re_pattern_buffer *bufp;
3068 int size, startpos, range;
3069 struct re_registers *regs;
3071 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3076 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3077 virtual concatenation of STRING1 and STRING2, starting first at index
3078 STARTPOS, then at STARTPOS + 1, and so on.
3080 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3082 RANGE is how far to scan while trying to match. RANGE = 0 means try
3083 only at STARTPOS; in general, the last start tried is STARTPOS +
3086 In REGS, return the indices of the virtual concatenation of STRING1
3087 and STRING2 that matched the entire BUFP->buffer and its contained
3090 Do not consider matching one past the index STOP in the virtual
3091 concatenation of STRING1 and STRING2.
3093 We return either the position in the strings at which the match was
3094 found, -1 if no match, or -2 if error (such as failure
3098 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3099 struct re_pattern_buffer *bufp;
3100 const char *string1, *string2;
3104 struct re_registers *regs;
3108 register char *fastmap = bufp->fastmap;
3109 register char *translate = bufp->translate;
3110 int total_size = size1 + size2;
3111 int endpos = startpos + range;
3113 /* Check for out-of-range STARTPOS. */
3114 if (startpos < 0 || startpos > total_size)
3117 /* Fix up RANGE if it might eventually take us outside
3118 the virtual concatenation of STRING1 and STRING2. */
3120 range = -1 - startpos;
3121 else if (endpos > total_size)
3122 range = total_size - startpos;
3124 /* If the search isn't to be a backwards one, don't waste time in a
3125 search for a pattern that must be anchored. */
3126 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3134 /* Update the fastmap now if not correct already. */
3135 if (fastmap && !bufp->fastmap_accurate)
3136 if (re_compile_fastmap (bufp) == -2)
3139 /* Loop through the string, looking for a place to start matching. */
3142 /* If a fastmap is supplied, skip quickly over characters that
3143 cannot be the start of a match. If the pattern can match the
3144 null string, however, we don't need to skip characters; we want
3145 the first null string. */
3146 if (fastmap && startpos < total_size && !bufp->can_be_null)
3148 if (range > 0) /* Searching forwards. */
3150 register const char *d;
3151 register int lim = 0;
3154 if (startpos < size1 && startpos + range >= size1)
3155 lim = range - (size1 - startpos);
3157 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
3159 /* Written out as an if-else to avoid testing `translate'
3163 && !fastmap[(unsigned char)
3164 translate[(unsigned char) *d++]])
3167 while (range > lim && !fastmap[(unsigned char) *d++])
3170 startpos += irange - range;
3172 else /* Searching backwards. */
3174 register char c = (size1 == 0 || startpos >= size1
3175 ? string2[startpos - size1]
3176 : string1[startpos]);
3178 if (!fastmap[(unsigned char) TRANSLATE (c)])
3183 /* If can't match the null string, and that's all we have left, fail. */
3184 if (range >= 0 && startpos == total_size && fastmap
3185 && !bufp->can_be_null)
3188 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3189 startpos, regs, stop);
3190 #ifndef REGEX_MALLOC
3219 /* Declarations and macros for re_match_2. */
3221 static int bcmp_translate ();
3222 static boolean alt_match_null_string_p (),
3223 common_op_match_null_string_p (),
3224 group_match_null_string_p ();
3226 /* This converts PTR, a pointer into one of the search strings `string1'
3227 and `string2' into an offset from the beginning of that string. */
3228 #define POINTER_TO_OFFSET(ptr) \
3229 (FIRST_STRING_P (ptr) \
3230 ? ((regoff_t) ((ptr) - string1)) \
3231 : ((regoff_t) ((ptr) - string2 + size1)))
3233 /* Macros for dealing with the split strings in re_match_2. */
3235 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3237 /* Call before fetching a character with *d. This switches over to
3238 string2 if necessary. */
3239 #define PREFETCH() \
3242 /* End of string2 => fail. */ \
3243 if (dend == end_match_2) \
3245 /* End of string1 => advance to string2. */ \
3247 dend = end_match_2; \
3251 /* Test if at very beginning or at very end of the virtual concatenation
3252 of `string1' and `string2'. If only one string, it's `string2'. */
3253 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3254 #define AT_STRINGS_END(d) ((d) == end2)
3257 /* Test if D points to a character which is word-constituent. We have
3258 two special cases to check for: if past the end of string1, look at
3259 the first character in string2; and if before the beginning of
3260 string2, look at the last character in string1. */
3261 #define WORDCHAR_P(d) \
3262 (SYNTAX ((d) == end1 ? *string2 \
3263 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3266 /* Test if the character before D and the one at D differ with respect
3267 to being word-constituent. */
3268 #define AT_WORD_BOUNDARY(d) \
3269 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3270 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3273 /* Free everything we malloc. */
3274 #ifdef MATCH_MAY_ALLOCATE
3276 #define FREE_VAR(var) if (var) free (var); var = NULL
3277 #define FREE_VARIABLES() \
3279 FREE_VAR (fail_stack.stack); \
3280 FREE_VAR (regstart); \
3281 FREE_VAR (regend); \
3282 FREE_VAR (old_regstart); \
3283 FREE_VAR (old_regend); \
3284 FREE_VAR (best_regstart); \
3285 FREE_VAR (best_regend); \
3286 FREE_VAR (reg_info); \
3287 FREE_VAR (reg_dummy); \
3288 FREE_VAR (reg_info_dummy); \
3290 #else /* not REGEX_MALLOC */
3291 /* This used to do alloca (0), but now we do that in the caller. */
3292 #define FREE_VARIABLES() /* Nothing */
3293 #endif /* not REGEX_MALLOC */
3295 #define FREE_VARIABLES() /* Do nothing! */
3296 #endif /* not MATCH_MAY_ALLOCATE */
3298 /* These values must meet several constraints. They must not be valid
3299 register values; since we have a limit of 255 registers (because
3300 we use only one byte in the pattern for the register number), we can
3301 use numbers larger than 255. They must differ by 1, because of
3302 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3303 be larger than the value for the highest register, so we do not try
3304 to actually save any registers when none are active. */
3305 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3306 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3308 /* Matching routines. */
3310 #ifndef emacs /* Emacs never uses this. */
3311 /* re_match is like re_match_2 except it takes only a single string. */
3314 re_match (bufp, string, size, pos, regs)
3315 struct re_pattern_buffer *bufp;
3318 struct re_registers *regs;
3320 int result = re_match_2_internal (bufp, NULL, 0, string, size,
3325 #endif /* not emacs */
3328 /* re_match_2 matches the compiled pattern in BUFP against the
3329 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3330 and SIZE2, respectively). We start matching at POS, and stop
3333 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3334 store offsets for the substring each group matched in REGS. See the
3335 documentation for exactly how many groups we fill.
3337 We return -1 if no match, -2 if an internal error (such as the
3338 failure stack overflowing). Otherwise, we return the length of the
3339 matched substring. */
3342 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3343 struct re_pattern_buffer *bufp;
3344 const char *string1, *string2;
3347 struct re_registers *regs;
3350 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
3356 /* This is a separate function so that we can force an alloca cleanup
3359 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
3360 struct re_pattern_buffer *bufp;
3361 const char *string1, *string2;
3364 struct re_registers *regs;
3367 /* General temporaries. */
3371 /* Just past the end of the corresponding string. */
3372 const char *end1, *end2;
3374 /* Pointers into string1 and string2, just past the last characters in
3375 each to consider matching. */
3376 const char *end_match_1, *end_match_2;
3378 /* Where we are in the data, and the end of the current string. */
3379 const char *d, *dend;
3381 /* Where we are in the pattern, and the end of the pattern. */
3382 unsigned char *p = bufp->buffer;
3383 register unsigned char *pend = p + bufp->used;
3385 /* Mark the opcode just after a start_memory, so we can test for an
3386 empty subpattern when we get to the stop_memory. */
3387 unsigned char *just_past_start_mem = 0;
3389 /* We use this to map every character in the string. */
3390 char *translate = bufp->translate;
3392 /* Failure point stack. Each place that can handle a failure further
3393 down the line pushes a failure point on this stack. It consists of
3394 restart, regend, and reg_info for all registers corresponding to
3395 the subexpressions we're currently inside, plus the number of such
3396 registers, and, finally, two char *'s. The first char * is where
3397 to resume scanning the pattern; the second one is where to resume
3398 scanning the strings. If the latter is zero, the failure point is
3399 a ``dummy''; if a failure happens and the failure point is a dummy,
3400 it gets discarded and the next next one is tried. */
3401 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3402 fail_stack_type fail_stack;
3405 static unsigned failure_id = 0;
3406 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3409 /* We fill all the registers internally, independent of what we
3410 return, for use in backreferences. The number here includes
3411 an element for register zero. */
3412 unsigned num_regs = bufp->re_nsub + 1;
3414 /* The currently active registers. */
3415 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3416 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3418 /* Information on the contents of registers. These are pointers into
3419 the input strings; they record just what was matched (on this
3420 attempt) by a subexpression part of the pattern, that is, the
3421 regnum-th regstart pointer points to where in the pattern we began
3422 matching and the regnum-th regend points to right after where we
3423 stopped matching the regnum-th subexpression. (The zeroth register
3424 keeps track of what the whole pattern matches.) */
3425 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3426 const char **regstart, **regend;
3429 /* If a group that's operated upon by a repetition operator fails to
3430 match anything, then the register for its start will need to be
3431 restored because it will have been set to wherever in the string we
3432 are when we last see its open-group operator. Similarly for a
3434 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3435 const char **old_regstart, **old_regend;
3438 /* The is_active field of reg_info helps us keep track of which (possibly
3439 nested) subexpressions we are currently in. The matched_something
3440 field of reg_info[reg_num] helps us tell whether or not we have
3441 matched any of the pattern so far this time through the reg_num-th
3442 subexpression. These two fields get reset each time through any
3443 loop their register is in. */
3444 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3445 register_info_type *reg_info;
3448 /* The following record the register info as found in the above
3449 variables when we find a match better than any we've seen before.
3450 This happens as we backtrack through the failure points, which in
3451 turn happens only if we have not yet matched the entire string. */
3452 unsigned best_regs_set = false;
3453 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3454 const char **best_regstart, **best_regend;
3457 /* Logically, this is `best_regend[0]'. But we don't want to have to
3458 allocate space for that if we're not allocating space for anything
3459 else (see below). Also, we never need info about register 0 for
3460 any of the other register vectors, and it seems rather a kludge to
3461 treat `best_regend' differently than the rest. So we keep track of
3462 the end of the best match so far in a separate variable. We
3463 initialize this to NULL so that when we backtrack the first time
3464 and need to test it, it's not garbage. */
3465 const char *match_end = NULL;
3467 /* Used when we pop values we don't care about. */
3468 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3469 const char **reg_dummy;
3470 register_info_type *reg_info_dummy;
3474 /* Counts the total number of registers pushed. */
3475 unsigned num_regs_pushed = 0;
3478 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3482 #ifdef MATCH_MAY_ALLOCATE
3483 /* Do not bother to initialize all the register variables if there are
3484 no groups in the pattern, as it takes a fair amount of time. If
3485 there are groups, we include space for register 0 (the whole
3486 pattern), even though we never use it, since it simplifies the
3487 array indexing. We should fix this. */
3490 regstart = REGEX_TALLOC (num_regs, const char *);
3491 regend = REGEX_TALLOC (num_regs, const char *);
3492 old_regstart = REGEX_TALLOC (num_regs, const char *);
3493 old_regend = REGEX_TALLOC (num_regs, const char *);
3494 best_regstart = REGEX_TALLOC (num_regs, const char *);
3495 best_regend = REGEX_TALLOC (num_regs, const char *);
3496 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3497 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3498 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3500 if (!(regstart && regend && old_regstart && old_regend && reg_info
3501 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3507 #if defined (REGEX_MALLOC)
3510 /* We must initialize all our variables to NULL, so that
3511 `FREE_VARIABLES' doesn't try to free them. */
3512 regstart = regend = old_regstart = old_regend = best_regstart
3513 = best_regend = reg_dummy = NULL;
3514 reg_info = reg_info_dummy = (register_info_type *) NULL;
3516 #endif /* REGEX_MALLOC */
3517 #endif /* MATCH_MAY_ALLOCATE */
3519 /* The starting position is bogus. */
3520 if (pos < 0 || pos > size1 + size2)
3526 /* Initialize subexpression text positions to -1 to mark ones that no
3527 start_memory/stop_memory has been seen for. Also initialize the
3528 register information struct. */
3529 for (mcnt = 1; mcnt < num_regs; mcnt++)
3531 regstart[mcnt] = regend[mcnt]
3532 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3534 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3535 IS_ACTIVE (reg_info[mcnt]) = 0;
3536 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3537 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3540 /* We move `string1' into `string2' if the latter's empty -- but not if
3541 `string1' is null. */
3542 if (size2 == 0 && string1 != NULL)
3549 end1 = string1 + size1;
3550 end2 = string2 + size2;
3552 /* Compute where to stop matching, within the two strings. */
3555 end_match_1 = string1 + stop;
3556 end_match_2 = string2;
3561 end_match_2 = string2 + stop - size1;
3564 /* `p' scans through the pattern as `d' scans through the data.
3565 `dend' is the end of the input string that `d' points within. `d'
3566 is advanced into the following input string whenever necessary, but
3567 this happens before fetching; therefore, at the beginning of the
3568 loop, `d' can be pointing at the end of a string, but it cannot
3570 if (size1 > 0 && pos <= size1)
3577 d = string2 + pos - size1;
3581 DEBUG_PRINT1 ("The compiled pattern is: ");
3582 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3583 DEBUG_PRINT1 ("The string to match is: `");
3584 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3585 DEBUG_PRINT1 ("'\n");
3587 /* This loops over pattern commands. It exits by returning from the
3588 function if the match is complete, or it drops through if the match
3589 fails at this starting point in the input data. */
3592 DEBUG_PRINT2 ("\n0x%x: ", p);
3595 { /* End of pattern means we might have succeeded. */
3596 DEBUG_PRINT1 ("end of pattern ... ");
3598 /* If we haven't matched the entire string, and we want the
3599 longest match, try backtracking. */
3600 if (d != end_match_2)
3602 /* 1 if this match ends in the same string (string1 or string2)
3603 as the best previous match. */
3604 boolean same_str_p = (FIRST_STRING_P (match_end)
3605 == MATCHING_IN_FIRST_STRING);
3606 /* 1 if this match is the best seen so far. */
3607 boolean best_match_p;
3609 /* AIX compiler got confused when this was combined
3610 with the previous declaration. */
3612 best_match_p = d > match_end;
3614 best_match_p = !MATCHING_IN_FIRST_STRING;
3616 DEBUG_PRINT1 ("backtracking.\n");
3618 if (!FAIL_STACK_EMPTY ())
3619 { /* More failure points to try. */
3621 /* If exceeds best match so far, save it. */
3622 if (!best_regs_set || best_match_p)
3624 best_regs_set = true;
3627 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3629 for (mcnt = 1; mcnt < num_regs; mcnt++)
3631 best_regstart[mcnt] = regstart[mcnt];
3632 best_regend[mcnt] = regend[mcnt];
3638 /* If no failure points, don't restore garbage. And if
3639 last match is real best match, don't restore second
3641 else if (best_regs_set && !best_match_p)
3644 /* Restore best match. It may happen that `dend ==
3645 end_match_1' while the restored d is in string2.
3646 For example, the pattern `x.*y.*z' against the
3647 strings `x-' and `y-z-', if the two strings are
3648 not consecutive in memory. */
3649 DEBUG_PRINT1 ("Restoring best registers.\n");
3652 dend = ((d >= string1 && d <= end1)
3653 ? end_match_1 : end_match_2);
3655 for (mcnt = 1; mcnt < num_regs; mcnt++)
3657 regstart[mcnt] = best_regstart[mcnt];
3658 regend[mcnt] = best_regend[mcnt];
3661 } /* d != end_match_2 */
3663 DEBUG_PRINT1 ("Accepting match.\n");
3665 /* If caller wants register contents data back, do it. */
3666 if (regs && !bufp->no_sub)
3668 /* Have the register data arrays been allocated? */
3669 if (bufp->regs_allocated == REGS_UNALLOCATED)
3670 { /* No. So allocate them with malloc. We need one
3671 extra element beyond `num_regs' for the `-1' marker
3673 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3674 regs->start = TALLOC (regs->num_regs, regoff_t);
3675 regs->end = TALLOC (regs->num_regs, regoff_t);
3676 if (regs->start == NULL || regs->end == NULL)
3678 bufp->regs_allocated = REGS_REALLOCATE;
3680 else if (bufp->regs_allocated == REGS_REALLOCATE)
3681 { /* Yes. If we need more elements than were already
3682 allocated, reallocate them. If we need fewer, just
3684 if (regs->num_regs < num_regs + 1)
3686 regs->num_regs = num_regs + 1;
3687 RETALLOC (regs->start, regs->num_regs, regoff_t);
3688 RETALLOC (regs->end, regs->num_regs, regoff_t);
3689 if (regs->start == NULL || regs->end == NULL)
3695 /* These braces fend off a "empty body in an else-statement"
3696 warning under GCC when assert expands to nothing. */
3697 assert (bufp->regs_allocated == REGS_FIXED);
3700 /* Convert the pointer data in `regstart' and `regend' to
3701 indices. Register zero has to be set differently,
3702 since we haven't kept track of any info for it. */
3703 if (regs->num_regs > 0)
3705 regs->start[0] = pos;
3706 regs->end[0] = (MATCHING_IN_FIRST_STRING
3707 ? ((regoff_t) (d - string1))
3708 : ((regoff_t) (d - string2 + size1)));
3711 /* Go through the first `min (num_regs, regs->num_regs)'
3712 registers, since that is all we initialized. */
3713 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
3715 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3716 regs->start[mcnt] = regs->end[mcnt] = -1;
3720 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
3722 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
3726 /* If the regs structure we return has more elements than
3727 were in the pattern, set the extra elements to -1. If
3728 we (re)allocated the registers, this is the case,
3729 because we always allocate enough to have at least one
3731 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3732 regs->start[mcnt] = regs->end[mcnt] = -1;
3733 } /* regs && !bufp->no_sub */
3736 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3737 nfailure_points_pushed, nfailure_points_popped,
3738 nfailure_points_pushed - nfailure_points_popped);
3739 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3741 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3745 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3750 /* Otherwise match next pattern command. */
3751 #ifdef SWITCH_ENUM_BUG
3752 switch ((int) ((re_opcode_t) *p++))
3754 switch ((re_opcode_t) *p++)
3757 /* Ignore these. Used to ignore the n of succeed_n's which
3758 currently have n == 0. */
3760 DEBUG_PRINT1 ("EXECUTING no_op.\n");
3764 /* Match the next n pattern characters exactly. The following
3765 byte in the pattern defines n, and the n bytes after that
3766 are the characters to match. */
3769 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3771 /* This is written out as an if-else so we don't waste time
3772 testing `translate' inside the loop. */
3778 if (translate[(unsigned char) *d++] != (char) *p++)
3788 if (*d++ != (char) *p++) goto fail;
3792 SET_REGS_MATCHED ();
3796 /* Match any character except possibly a newline or a null. */
3798 DEBUG_PRINT1 ("EXECUTING anychar.\n");
3802 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
3803 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
3806 SET_REGS_MATCHED ();
3807 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
3815 register unsigned char c;
3816 boolean not = (re_opcode_t) *(p - 1) == charset_not;
3818 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
3821 c = TRANSLATE (*d); /* The character to match. */
3823 /* Cast to `unsigned' instead of `unsigned char' in case the
3824 bit list is a full 32 bytes long. */
3825 if (c < (unsigned) (*p * BYTEWIDTH)
3826 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3831 if (!not) goto fail;
3833 SET_REGS_MATCHED ();
3839 /* The beginning of a group is represented by start_memory.
3840 The arguments are the register number in the next byte, and the
3841 number of groups inner to this one in the next. The text
3842 matched within the group is recorded (in the internal
3843 registers data structure) under the register number. */
3845 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3847 /* Find out if this group can match the empty string. */
3848 p1 = p; /* To send to group_match_null_string_p. */
3850 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3851 REG_MATCH_NULL_STRING_P (reg_info[*p])
3852 = group_match_null_string_p (&p1, pend, reg_info);
3854 /* Save the position in the string where we were the last time
3855 we were at this open-group operator in case the group is
3856 operated upon by a repetition operator, e.g., with `(a*)*b'
3857 against `ab'; then we want to ignore where we are now in
3858 the string in case this attempt to match fails. */
3859 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3860 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
3862 DEBUG_PRINT2 (" old_regstart: %d\n",
3863 POINTER_TO_OFFSET (old_regstart[*p]));
3866 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
3868 IS_ACTIVE (reg_info[*p]) = 1;
3869 MATCHED_SOMETHING (reg_info[*p]) = 0;
3871 /* This is the new highest active register. */
3872 highest_active_reg = *p;
3874 /* If nothing was active before, this is the new lowest active
3876 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3877 lowest_active_reg = *p;
3879 /* Move past the register number and inner group count. */
3881 just_past_start_mem = p;
3885 /* The stop_memory opcode represents the end of a group. Its
3886 arguments are the same as start_memory's: the register
3887 number, and the number of inner groups. */
3889 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
3891 /* We need to save the string position the last time we were at
3892 this close-group operator in case the group is operated
3893 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3894 against `aba'; then we want to ignore where we are now in
3895 the string in case this attempt to match fails. */
3896 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3897 ? REG_UNSET (regend[*p]) ? d : regend[*p]
3899 DEBUG_PRINT2 (" old_regend: %d\n",
3900 POINTER_TO_OFFSET (old_regend[*p]));
3903 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
3905 /* This register isn't active anymore. */
3906 IS_ACTIVE (reg_info[*p]) = 0;
3908 /* If this was the only register active, nothing is active
3910 if (lowest_active_reg == highest_active_reg)
3912 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3913 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3916 { /* We must scan for the new highest active register, since
3917 it isn't necessarily one less than now: consider
3918 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
3919 new highest active register is 1. */
3920 unsigned char r = *p - 1;
3921 while (r > 0 && !IS_ACTIVE (reg_info[r]))
3924 /* If we end up at register zero, that means that we saved
3925 the registers as the result of an `on_failure_jump', not
3926 a `start_memory', and we jumped to past the innermost
3927 `stop_memory'. For example, in ((.)*) we save
3928 registers 1 and 2 as a result of the *, but when we pop
3929 back to the second ), we are at the stop_memory 1.
3930 Thus, nothing is active. */
3933 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3934 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3937 highest_active_reg = r;
3940 /* If just failed to match something this time around with a
3941 group that's operated on by a repetition operator, try to
3942 force exit from the ``loop'', and restore the register
3943 information for this group that we had before trying this
3945 if ((!MATCHED_SOMETHING (reg_info[*p])
3946 || just_past_start_mem == p - 1)
3949 boolean is_a_jump_n = false;
3953 switch ((re_opcode_t) *p1++)
3957 case pop_failure_jump:
3958 case maybe_pop_jump:
3960 case dummy_failure_jump:
3961 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3971 /* If the next operation is a jump backwards in the pattern
3972 to an on_failure_jump right before the start_memory
3973 corresponding to this stop_memory, exit from the loop
3974 by forcing a failure after pushing on the stack the
3975 on_failure_jump's jump in the pattern, and d. */
3976 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
3977 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
3979 /* If this group ever matched anything, then restore
3980 what its registers were before trying this last
3981 failed match, e.g., with `(a*)*b' against `ab' for
3982 regstart[1], and, e.g., with `((a*)*(b*)*)*'
3983 against `aba' for regend[3].
3985 Also restore the registers for inner groups for,
3986 e.g., `((a*)(b*))*' against `aba' (register 3 would
3987 otherwise get trashed). */
3989 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
3993 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
3995 /* Restore this and inner groups' (if any) registers. */
3996 for (r = *p; r < *p + *(p + 1); r++)
3998 regstart[r] = old_regstart[r];
4000 /* xx why this test? */
4001 if (old_regend[r] >= regstart[r])
4002 regend[r] = old_regend[r];
4006 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4007 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4013 /* Move past the register number and the inner group count. */
4018 /* \<digit> has been turned into a `duplicate' command which is
4019 followed by the numeric value of <digit> as the register number. */
4022 register const char *d2, *dend2;
4023 int regno = *p++; /* Get which register to match against. */
4024 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4026 /* Can't back reference a group which we've never matched. */
4027 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4030 /* Where in input to try to start matching. */
4031 d2 = regstart[regno];
4033 /* Where to stop matching; if both the place to start and
4034 the place to stop matching are in the same string, then
4035 set to the place to stop, otherwise, for now have to use
4036 the end of the first string. */
4038 dend2 = ((FIRST_STRING_P (regstart[regno])
4039 == FIRST_STRING_P (regend[regno]))
4040 ? regend[regno] : end_match_1);
4043 /* If necessary, advance to next segment in register
4047 if (dend2 == end_match_2) break;
4048 if (dend2 == regend[regno]) break;
4050 /* End of string1 => advance to string2. */
4052 dend2 = regend[regno];
4054 /* At end of register contents => success */
4055 if (d2 == dend2) break;
4057 /* If necessary, advance to next segment in data. */
4060 /* How many characters left in this segment to match. */
4063 /* Want how many consecutive characters we can match in
4064 one shot, so, if necessary, adjust the count. */
4065 if (mcnt > dend2 - d2)
4068 /* Compare that many; failure if mismatch, else move
4071 ? bcmp_translate (d, d2, mcnt, translate)
4072 : bcmp (d, d2, mcnt))
4074 d += mcnt, d2 += mcnt;
4080 /* begline matches the empty string at the beginning of the string
4081 (unless `not_bol' is set in `bufp'), and, if
4082 `newline_anchor' is set, after newlines. */
4084 DEBUG_PRINT1 ("EXECUTING begline.\n");
4086 if (AT_STRINGS_BEG (d))
4088 if (!bufp->not_bol) break;
4090 else if (d[-1] == '\n' && bufp->newline_anchor)
4094 /* In all other cases, we fail. */
4098 /* endline is the dual of begline. */
4100 DEBUG_PRINT1 ("EXECUTING endline.\n");
4102 if (AT_STRINGS_END (d))
4104 if (!bufp->not_eol) break;
4107 /* We have to ``prefetch'' the next character. */
4108 else if ((d == end1 ? *string2 : *d) == '\n'
4109 && bufp->newline_anchor)
4116 /* Match at the very beginning of the data. */
4118 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4119 if (AT_STRINGS_BEG (d))
4124 /* Match at the very end of the data. */
4126 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4127 if (AT_STRINGS_END (d))
4132 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4133 pushes NULL as the value for the string on the stack. Then
4134 `pop_failure_point' will keep the current value for the
4135 string, instead of restoring it. To see why, consider
4136 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4137 then the . fails against the \n. But the next thing we want
4138 to do is match the \n against the \n; if we restored the
4139 string value, we would be back at the foo.
4141 Because this is used only in specific cases, we don't need to
4142 check all the things that `on_failure_jump' does, to make
4143 sure the right things get saved on the stack. Hence we don't
4144 share its code. The only reason to push anything on the
4145 stack at all is that otherwise we would have to change
4146 `anychar's code to do something besides goto fail in this
4147 case; that seems worse than this. */
4148 case on_failure_keep_string_jump:
4149 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4151 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4152 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4154 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4158 /* Uses of on_failure_jump:
4160 Each alternative starts with an on_failure_jump that points
4161 to the beginning of the next alternative. Each alternative
4162 except the last ends with a jump that in effect jumps past
4163 the rest of the alternatives. (They really jump to the
4164 ending jump of the following alternative, because tensioning
4165 these jumps is a hassle.)
4167 Repeats start with an on_failure_jump that points past both
4168 the repetition text and either the following jump or
4169 pop_failure_jump back to this on_failure_jump. */
4170 case on_failure_jump:
4172 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4174 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4175 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4177 /* If this on_failure_jump comes right before a group (i.e.,
4178 the original * applied to a group), save the information
4179 for that group and all inner ones, so that if we fail back
4180 to this point, the group's information will be correct.
4181 For example, in \(a*\)*\1, we need the preceding group,
4182 and in \(\(a*\)b*\)\2, we need the inner group. */
4184 /* We can't use `p' to check ahead because we push
4185 a failure point to `p + mcnt' after we do this. */
4188 /* We need to skip no_op's before we look for the
4189 start_memory in case this on_failure_jump is happening as
4190 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4192 while (p1 < pend && (re_opcode_t) *p1 == no_op)
4195 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
4197 /* We have a new highest active register now. This will
4198 get reset at the start_memory we are about to get to,
4199 but we will have saved all the registers relevant to
4200 this repetition op, as described above. */
4201 highest_active_reg = *(p1 + 1) + *(p1 + 2);
4202 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4203 lowest_active_reg = *(p1 + 1);
4206 DEBUG_PRINT1 (":\n");
4207 PUSH_FAILURE_POINT (p + mcnt, d, -2);
4211 /* A smart repeat ends with `maybe_pop_jump'.
4212 We change it to either `pop_failure_jump' or `jump'. */
4213 case maybe_pop_jump:
4214 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4215 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
4217 register unsigned char *p2 = p;
4219 /* Compare the beginning of the repeat with what in the
4220 pattern follows its end. If we can establish that there
4221 is nothing that they would both match, i.e., that we
4222 would have to backtrack because of (as in, e.g., `a*a')
4223 then we can change to pop_failure_jump, because we'll
4224 never have to backtrack.
4226 This is not true in the case of alternatives: in
4227 `(a|ab)*' we do need to backtrack to the `ab' alternative
4228 (e.g., if the string was `ab'). But instead of trying to
4229 detect that here, the alternative has put on a dummy
4230 failure point which is what we will end up popping. */
4232 /* Skip over open/close-group commands.
4233 If what follows this loop is a ...+ construct,
4234 look at what begins its body, since we will have to
4235 match at least one of that. */
4239 && ((re_opcode_t) *p2 == stop_memory
4240 || (re_opcode_t) *p2 == start_memory))
4242 else if (p2 + 6 < pend
4243 && (re_opcode_t) *p2 == dummy_failure_jump)
4250 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4251 to the `maybe_finalize_jump' of this case. Examine what
4254 /* If we're at the end of the pattern, we can change. */
4257 /* Consider what happens when matching ":\(.*\)"
4258 against ":/". I don't really understand this code
4260 p[-3] = (unsigned char) pop_failure_jump;
4262 (" End of pattern: change to `pop_failure_jump'.\n");
4265 else if ((re_opcode_t) *p2 == exactn
4266 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4268 register unsigned char c
4269 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4271 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4273 p[-3] = (unsigned char) pop_failure_jump;
4274 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4278 else if ((re_opcode_t) p1[3] == charset
4279 || (re_opcode_t) p1[3] == charset_not)
4281 int not = (re_opcode_t) p1[3] == charset_not;
4283 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4284 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4287 /* `not' is equal to 1 if c would match, which means
4288 that we can't change to pop_failure_jump. */
4291 p[-3] = (unsigned char) pop_failure_jump;
4292 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4296 else if ((re_opcode_t) *p2 == charset)
4299 register unsigned char c
4300 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4303 if ((re_opcode_t) p1[3] == exactn
4304 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[4]
4305 && (p2[1 + p1[4] / BYTEWIDTH]
4306 & (1 << (p1[4] % BYTEWIDTH)))))
4308 p[-3] = (unsigned char) pop_failure_jump;
4309 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4313 else if ((re_opcode_t) p1[3] == charset_not)
4316 /* We win if the charset_not inside the loop
4317 lists every character listed in the charset after. */
4318 for (idx = 0; idx < (int) p2[1]; idx++)
4319 if (! (p2[2 + idx] == 0
4320 || (idx < (int) p1[4]
4321 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
4326 p[-3] = (unsigned char) pop_failure_jump;
4327 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4330 else if ((re_opcode_t) p1[3] == charset)
4333 /* We win if the charset inside the loop
4334 has no overlap with the one after the loop. */
4336 idx < (int) p2[1] && idx < (int) p1[4];
4338 if ((p2[2 + idx] & p1[5 + idx]) != 0)
4341 if (idx == p2[1] || idx == p1[4])
4343 p[-3] = (unsigned char) pop_failure_jump;
4344 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4349 p -= 2; /* Point at relative address again. */
4350 if ((re_opcode_t) p[-1] != pop_failure_jump)
4352 p[-1] = (unsigned char) jump;
4353 DEBUG_PRINT1 (" Match => jump.\n");
4354 goto unconditional_jump;
4356 /* Note fall through. */
4359 /* The end of a simple repeat has a pop_failure_jump back to
4360 its matching on_failure_jump, where the latter will push a
4361 failure point. The pop_failure_jump takes off failure
4362 points put on by this pop_failure_jump's matching
4363 on_failure_jump; we got through the pattern to here from the
4364 matching on_failure_jump, so didn't fail. */
4365 case pop_failure_jump:
4367 /* We need to pass separate storage for the lowest and
4368 highest registers, even though we don't care about the
4369 actual values. Otherwise, we will restore only one
4370 register from the stack, since lowest will == highest in
4371 `pop_failure_point'. */
4372 unsigned long dummy_low_reg, dummy_high_reg;
4373 unsigned char *pdummy;
4376 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4377 POP_FAILURE_POINT (sdummy, pdummy,
4378 dummy_low_reg, dummy_high_reg,
4379 reg_dummy, reg_dummy, reg_info_dummy);
4381 /* Note fall through. */
4384 /* Unconditionally jump (without popping any failure points). */
4387 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4388 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4389 p += mcnt; /* Do the jump. */
4390 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4394 /* We need this opcode so we can detect where alternatives end
4395 in `group_match_null_string_p' et al. */
4397 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4398 goto unconditional_jump;
4401 /* Normally, the on_failure_jump pushes a failure point, which
4402 then gets popped at pop_failure_jump. We will end up at
4403 pop_failure_jump, also, and with a pattern of, say, `a+', we
4404 are skipping over the on_failure_jump, so we have to push
4405 something meaningless for pop_failure_jump to pop. */
4406 case dummy_failure_jump:
4407 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4408 /* It doesn't matter what we push for the string here. What
4409 the code at `fail' tests is the value for the pattern. */
4410 PUSH_FAILURE_POINT (0, 0, -2);
4411 goto unconditional_jump;
4414 /* At the end of an alternative, we need to push a dummy failure
4415 point in case we are followed by a `pop_failure_jump', because
4416 we don't want the failure point for the alternative to be
4417 popped. For example, matching `(a|ab)*' against `aab'
4418 requires that we match the `ab' alternative. */
4419 case push_dummy_failure:
4420 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4421 /* See comments just above at `dummy_failure_jump' about the
4423 PUSH_FAILURE_POINT (0, 0, -2);
4426 /* Have to succeed matching what follows at least n times.
4427 After that, handle like `on_failure_jump'. */
4429 EXTRACT_NUMBER (mcnt, p + 2);
4430 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4433 /* Originally, this is how many times we HAVE to succeed. */
4438 STORE_NUMBER_AND_INCR (p, mcnt);
4439 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
4443 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4444 p[2] = (unsigned char) no_op;
4445 p[3] = (unsigned char) no_op;
4451 EXTRACT_NUMBER (mcnt, p + 2);
4452 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4454 /* Originally, this is how many times we CAN jump. */
4458 STORE_NUMBER (p + 2, mcnt);
4459 goto unconditional_jump;
4461 /* If don't have to jump any more, skip over the rest of command. */
4468 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4470 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4472 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4473 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4474 STORE_NUMBER (p1, mcnt);
4479 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4480 if (AT_WORD_BOUNDARY (d))
4485 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4486 if (AT_WORD_BOUNDARY (d))
4491 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4492 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4497 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4498 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4499 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4505 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4506 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4511 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4512 if (PTR_CHAR_POS ((unsigned char *) d) != point)
4517 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4518 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
4521 #if 0 /* not emacs19 */
4523 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4524 if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
4527 #endif /* not emacs19 */
4530 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4535 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4539 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
4541 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
4543 SET_REGS_MATCHED ();
4547 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4549 goto matchnotsyntax;
4552 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4556 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
4558 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
4560 SET_REGS_MATCHED ();
4563 #else /* not emacs */
4565 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4567 if (!WORDCHAR_P (d))
4569 SET_REGS_MATCHED ();
4574 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4578 SET_REGS_MATCHED ();
4581 #endif /* not emacs */
4586 continue; /* Successfully executed one pattern command; keep going. */
4589 /* We goto here if a matching operation fails. */
4591 if (!FAIL_STACK_EMPTY ())
4592 { /* A restart point is known. Restore to that state. */
4593 DEBUG_PRINT1 ("\nFAIL:\n");
4594 POP_FAILURE_POINT (d, p,
4595 lowest_active_reg, highest_active_reg,
4596 regstart, regend, reg_info);
4598 /* If this failure point is a dummy, try the next one. */
4602 /* If we failed to the end of the pattern, don't examine *p. */
4606 boolean is_a_jump_n = false;
4608 /* If failed to a backwards jump that's part of a repetition
4609 loop, need to pop this failure point and use the next one. */
4610 switch ((re_opcode_t) *p)
4614 case maybe_pop_jump:
4615 case pop_failure_jump:
4618 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4621 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4623 && (re_opcode_t) *p1 == on_failure_jump))
4631 if (d >= string1 && d <= end1)
4635 break; /* Matching at this starting point really fails. */
4639 goto restore_best_regs;
4643 return -1; /* Failure to match. */
4646 /* Subroutine definitions for re_match_2. */
4649 /* We are passed P pointing to a register number after a start_memory.
4651 Return true if the pattern up to the corresponding stop_memory can
4652 match the empty string, and false otherwise.
4654 If we find the matching stop_memory, sets P to point to one past its number.
4655 Otherwise, sets P to an undefined byte less than or equal to END.
4657 We don't handle duplicates properly (yet). */
4660 group_match_null_string_p (p, end, reg_info)
4661 unsigned char **p, *end;
4662 register_info_type *reg_info;
4665 /* Point to after the args to the start_memory. */
4666 unsigned char *p1 = *p + 2;
4670 /* Skip over opcodes that can match nothing, and return true or
4671 false, as appropriate, when we get to one that can't, or to the
4672 matching stop_memory. */
4674 switch ((re_opcode_t) *p1)
4676 /* Could be either a loop or a series of alternatives. */
4677 case on_failure_jump:
4679 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4681 /* If the next operation is not a jump backwards in the
4686 /* Go through the on_failure_jumps of the alternatives,
4687 seeing if any of the alternatives cannot match nothing.
4688 The last alternative starts with only a jump,
4689 whereas the rest start with on_failure_jump and end
4690 with a jump, e.g., here is the pattern for `a|b|c':
4692 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4693 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4696 So, we have to first go through the first (n-1)
4697 alternatives and then deal with the last one separately. */
4700 /* Deal with the first (n-1) alternatives, which start
4701 with an on_failure_jump (see above) that jumps to right
4702 past a jump_past_alt. */
4704 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4706 /* `mcnt' holds how many bytes long the alternative
4707 is, including the ending `jump_past_alt' and
4710 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
4714 /* Move to right after this alternative, including the
4718 /* Break if it's the beginning of an n-th alternative
4719 that doesn't begin with an on_failure_jump. */
4720 if ((re_opcode_t) *p1 != on_failure_jump)
4723 /* Still have to check that it's not an n-th
4724 alternative that starts with an on_failure_jump. */
4726 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4727 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4729 /* Get to the beginning of the n-th alternative. */
4735 /* Deal with the last alternative: go back and get number
4736 of the `jump_past_alt' just before it. `mcnt' contains
4737 the length of the alternative. */
4738 EXTRACT_NUMBER (mcnt, p1 - 2);
4740 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
4743 p1 += mcnt; /* Get past the n-th alternative. */
4749 assert (p1[1] == **p);
4755 if (!common_op_match_null_string_p (&p1, end, reg_info))
4758 } /* while p1 < end */
4761 } /* group_match_null_string_p */
4764 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4765 It expects P to be the first byte of a single alternative and END one
4766 byte past the last. The alternative can contain groups. */
4769 alt_match_null_string_p (p, end, reg_info)
4770 unsigned char *p, *end;
4771 register_info_type *reg_info;
4774 unsigned char *p1 = p;
4778 /* Skip over opcodes that can match nothing, and break when we get
4779 to one that can't. */
4781 switch ((re_opcode_t) *p1)
4784 case on_failure_jump:
4786 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4791 if (!common_op_match_null_string_p (&p1, end, reg_info))
4794 } /* while p1 < end */
4797 } /* alt_match_null_string_p */
4800 /* Deals with the ops common to group_match_null_string_p and
4801 alt_match_null_string_p.
4803 Sets P to one after the op and its arguments, if any. */
4806 common_op_match_null_string_p (p, end, reg_info)
4807 unsigned char **p, *end;
4808 register_info_type *reg_info;
4813 unsigned char *p1 = *p;
4815 switch ((re_opcode_t) *p1++)
4835 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
4836 ret = group_match_null_string_p (&p1, end, reg_info);
4838 /* Have to set this here in case we're checking a group which
4839 contains a group and a back reference to it. */
4841 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4842 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
4848 /* If this is an optimized succeed_n for zero times, make the jump. */
4850 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4858 /* Get to the number of times to succeed. */
4860 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4865 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4873 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
4881 /* All other opcodes mean we cannot match the empty string. */
4887 } /* common_op_match_null_string_p */
4890 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4891 bytes; nonzero otherwise. */
4894 bcmp_translate (s1, s2, len, translate)
4895 unsigned char *s1, *s2;
4899 register unsigned char *p1 = s1, *p2 = s2;
4902 if (translate[*p1++] != translate[*p2++]) return 1;
4908 /* Entry points for GNU code. */
4910 /* re_compile_pattern is the GNU regular expression compiler: it
4911 compiles PATTERN (of length SIZE) and puts the result in BUFP.
4912 Returns 0 if the pattern was valid, otherwise an error string.
4914 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
4915 are set in BUFP on entry.
4917 We call regex_compile to do the actual compilation. */
4920 re_compile_pattern (pattern, length, bufp)
4921 const char *pattern;
4923 struct re_pattern_buffer *bufp;
4927 /* GNU code is written to assume at least RE_NREGS registers will be set
4928 (and at least one extra will be -1). */
4929 bufp->regs_allocated = REGS_UNALLOCATED;
4931 /* And GNU code determines whether or not to get register information
4932 by passing null for the REGS argument to re_match, etc., not by
4936 /* Match anchors at newline. */
4937 bufp->newline_anchor = 1;
4939 ret = regex_compile (pattern, length, re_syntax_options, bufp);
4941 return re_error_msg[(int) ret];
4944 /* Entry points compatible with 4.2 BSD regex library. We don't define
4945 them if this is an Emacs or POSIX compilation. */
4947 #if !defined (emacs) && !defined (_POSIX_SOURCE)
4949 /* BSD has one and only one pattern buffer. */
4950 static struct re_pattern_buffer re_comp_buf;
4960 if (!re_comp_buf.buffer)
4961 return "No previous regular expression";
4965 if (!re_comp_buf.buffer)
4967 re_comp_buf.buffer = (unsigned char *) malloc (200);
4968 if (re_comp_buf.buffer == NULL)
4969 return "Memory exhausted";
4970 re_comp_buf.allocated = 200;
4972 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
4973 if (re_comp_buf.fastmap == NULL)
4974 return "Memory exhausted";
4977 /* Since `re_exec' always passes NULL for the `regs' argument, we
4978 don't need to initialize the pattern buffer fields which affect it. */
4980 /* Match anchors at newlines. */
4981 re_comp_buf.newline_anchor = 1;
4983 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
4985 /* Yes, we're discarding `const' here. */
4986 return (char *) re_error_msg[(int) ret];
4994 const int len = strlen (s);
4996 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
4998 #endif /* not emacs and not _POSIX_SOURCE */
5000 /* POSIX.2 functions. Don't define these for Emacs. */
5004 /* regcomp takes a regular expression as a string and compiles it.
5006 PREG is a regex_t *. We do not expect any fields to be initialized,
5007 since POSIX says we shouldn't. Thus, we set
5009 `buffer' to the compiled pattern;
5010 `used' to the length of the compiled pattern;
5011 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5012 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5013 RE_SYNTAX_POSIX_BASIC;
5014 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5015 `fastmap' and `fastmap_accurate' to zero;
5016 `re_nsub' to the number of subexpressions in PATTERN.
5018 PATTERN is the address of the pattern string.
5020 CFLAGS is a series of bits which affect compilation.
5022 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5023 use POSIX basic syntax.
5025 If REG_NEWLINE is set, then . and [^...] don't match newline.
5026 Also, regexec will try a match beginning after every newline.
5028 If REG_ICASE is set, then we considers upper- and lowercase
5029 versions of letters to be equivalent when matching.
5031 If REG_NOSUB is set, then when PREG is passed to regexec, that
5032 routine will report only success or failure, and nothing about the
5035 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5036 the return codes and their meanings.) */
5039 regcomp (preg, pattern, cflags)
5041 const char *pattern;
5046 = (cflags & REG_EXTENDED) ?
5047 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5049 /* regex_compile will allocate the space for the compiled pattern. */
5051 preg->allocated = 0;
5054 /* Don't bother to use a fastmap when searching. This simplifies the
5055 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5056 characters after newlines into the fastmap. This way, we just try
5060 if (cflags & REG_ICASE)
5064 preg->translate = (char *) malloc (CHAR_SET_SIZE);
5065 if (preg->translate == NULL)
5066 return (int) REG_ESPACE;
5068 /* Map uppercase characters to corresponding lowercase ones. */
5069 for (i = 0; i < CHAR_SET_SIZE; i++)
5070 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5073 preg->translate = NULL;
5075 /* If REG_NEWLINE is set, newlines are treated differently. */
5076 if (cflags & REG_NEWLINE)
5077 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5078 syntax &= ~RE_DOT_NEWLINE;
5079 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5080 /* It also changes the matching behavior. */
5081 preg->newline_anchor = 1;
5084 preg->newline_anchor = 0;
5086 preg->no_sub = !!(cflags & REG_NOSUB);
5088 /* POSIX says a null character in the pattern terminates it, so we
5089 can use strlen here in compiling the pattern. */
5090 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5092 /* POSIX doesn't distinguish between an unmatched open-group and an
5093 unmatched close-group: both are REG_EPAREN. */
5094 if (ret == REG_ERPAREN) ret = REG_EPAREN;
5100 /* regexec searches for a given pattern, specified by PREG, in the
5103 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5104 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5105 least NMATCH elements, and we set them to the offsets of the
5106 corresponding matched substrings.
5108 EFLAGS specifies `execution flags' which affect matching: if
5109 REG_NOTBOL is set, then ^ does not match at the beginning of the
5110 string; if REG_NOTEOL is set, then $ does not match at the end.
5112 We return 0 if we find a match and REG_NOMATCH if not. */
5115 regexec (preg, string, nmatch, pmatch, eflags)
5116 const regex_t *preg;
5119 regmatch_t pmatch[];
5123 struct re_registers regs;
5124 regex_t private_preg;
5125 int len = strlen (string);
5126 boolean want_reg_info = !preg->no_sub && nmatch > 0;
5128 private_preg = *preg;
5130 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5131 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5133 /* The user has told us exactly how many registers to return
5134 information about, via `nmatch'. We have to pass that on to the
5135 matching routines. */
5136 private_preg.regs_allocated = REGS_FIXED;
5140 regs.num_regs = nmatch;
5141 regs.start = TALLOC (nmatch, regoff_t);
5142 regs.end = TALLOC (nmatch, regoff_t);
5143 if (regs.start == NULL || regs.end == NULL)
5144 return (int) REG_NOMATCH;
5147 /* Perform the searching operation. */
5148 ret = re_search (&private_preg, string, len,
5149 /* start: */ 0, /* range: */ len,
5150 want_reg_info ? ®s : (struct re_registers *) 0);
5152 /* Copy the register information to the POSIX structure. */
5159 for (r = 0; r < nmatch; r++)
5161 pmatch[r].rm_so = regs.start[r];
5162 pmatch[r].rm_eo = regs.end[r];
5166 /* If we needed the temporary register info, free the space now. */
5171 /* We want zero return to mean success, unlike `re_search'. */
5172 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5176 /* Returns a message corresponding to an error code, ERRCODE, returned
5177 from either regcomp or regexec. We don't use PREG here. */
5180 regerror (errcode, preg, errbuf, errbuf_size)
5182 const regex_t *preg;
5190 || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0])))
5191 /* Only error codes returned by the rest of the code should be passed
5192 to this routine. If we are given anything else, or if other regex
5193 code generates an invalid error code, then the program has a bug.
5194 Dump core so we can fix it. */
5197 msg = re_error_msg[errcode];
5199 /* POSIX doesn't require that we do anything in this case, but why
5204 msg_size = strlen (msg) + 1; /* Includes the null. */
5206 if (errbuf_size != 0)
5208 if (msg_size > errbuf_size)
5210 strncpy (errbuf, msg, errbuf_size - 1);
5211 errbuf[errbuf_size - 1] = 0;
5214 strcpy (errbuf, msg);
5221 /* Free dynamically allocated space used by PREG. */
5227 if (preg->buffer != NULL)
5228 free (preg->buffer);
5229 preg->buffer = NULL;
5231 preg->allocated = 0;
5234 if (preg->fastmap != NULL)
5235 free (preg->fastmap);
5236 preg->fastmap = NULL;
5237 preg->fastmap_accurate = 0;
5239 if (preg->translate != NULL)
5240 free (preg->translate);
5241 preg->translate = NULL;
5244 #endif /* not emacs */
5248 make-backup-files: t
5250 trim-versions-without-asking: nil