1 /* Extended regular expression matching and search library,
2 version 0.12, extended for XEmacs.
3 (Implements POSIX draft P10003.2/D11.2, except for
4 internationalization features.)
6 Copyright (C) 1993, 1994, 1995 Free Software Foundation, Inc.
7 Copyright (C) 1995 Sun Microsystems, Inc.
8 Copyright (C) 1995 Ben Wing.
9 Copyright (C) 1999,2000,2001 MORIOKA Tomohiko
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2, or (at your option)
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; see the file COPYING. If not, write to
23 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 Boston, MA 02111-1307, USA. */
26 /* Synched up with: FSF 19.29. */
28 /* Changes made for XEmacs:
30 (1) the REGEX_BEGLINE_CHECK code from the XEmacs v18 regex routines
31 was added. This causes a huge speedup in font-locking.
32 (2) Rel-alloc is disabled when the MMAP version of rel-alloc is
33 being used, because it's too slow -- all those calls to mmap()
34 add humongous overhead.
35 (3) Lots and lots of changes for Mule. They are bracketed by
36 `#ifdef MULE' or with comments that have `XEmacs' in them.
43 #ifndef REGISTER /* Rigidly enforced as of 20.3 */
51 /* We assume non-Mule if emacs isn't defined. */
56 /* We need this for `regex.h', and perhaps for the Emacs include files. */
57 #include <sys/types.h>
59 /* This is for other GNU distributions with internationalized messages. */
60 #if defined (I18N3) && (defined (HAVE_LIBINTL_H) || defined (_LIBC))
63 # define gettext(msgid) (msgid)
66 /* XEmacs: define this to add in a speedup for patterns anchored at
67 the beginning of a line. Keep the ifdefs so that it's easier to
68 tell where/why this code has diverged from v19. */
69 #define REGEX_BEGLINE_CHECK
71 /* XEmacs: the current mmap-based ralloc handles small blocks very
72 poorly, so we disable it here. */
74 #if (defined (REL_ALLOC) && defined (HAVE_MMAP)) || defined(DOUG_LEA_MALLOC)
78 /* The `emacs' switch turns on certain matching commands
79 that make sense only in Emacs. */
86 #if (defined (DEBUG_XEMACS) && !defined (DEBUG))
92 Lisp_Object Vthe_lisp_rangetab;
95 complex_vars_of_regex (void)
97 Vthe_lisp_rangetab = Fmake_range_table ();
98 staticpro (&Vthe_lisp_rangetab);
104 complex_vars_of_regex (void)
110 #define RE_TRANSLATE(ch) TRT_TABLE_OF (translate, (Emchar) ch)
111 #define TRANSLATE_P(tr) (!NILP (tr))
113 #else /* not emacs */
115 /* If we are not linking with Emacs proper,
116 we can't use the relocating allocator
117 even if config.h says that we can. */
120 #if defined (STDC_HEADERS) || defined (_LIBC)
127 #define charptr_emchar(str) ((Emchar) (str)[0])
129 #if (LONGBITS > INTBITS)
130 # define EMACS_INT long
132 # define EMACS_INT int
137 #define INC_CHARPTR(p) ((p)++)
138 #define DEC_CHARPTR(p) ((p)--)
142 /* Define the syntax stuff for \<, \>, etc. */
144 /* This must be nonzero for the wordchar and notwordchar pattern
145 commands in re_match_2. */
152 extern char *re_syntax_table;
154 #else /* not SYNTAX_TABLE */
156 /* How many characters in the character set. */
157 #define CHAR_SET_SIZE 256
159 static char re_syntax_table[CHAR_SET_SIZE];
162 init_syntax_once (void)
168 const char *word_syntax_chars =
169 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
171 memset (re_syntax_table, 0, sizeof (re_syntax_table));
173 while (*word_syntax_chars)
174 re_syntax_table[(unsigned int)(*word_syntax_chars++)] = Sword;
180 #endif /* SYNTAX_TABLE */
182 #define SYNTAX_UNSAFE(ignored, c) re_syntax_table[c]
184 #define RE_TRANSLATE(c) translate[(unsigned char) (c)]
185 #define TRANSLATE_P(tr) tr
189 /* Under XEmacs, this is needed because we don't define it elsewhere. */
190 #ifdef SWITCH_ENUM_BUG
191 #define SWITCH_ENUM_CAST(x) ((int)(x))
193 #define SWITCH_ENUM_CAST(x) (x)
197 /* Get the interface, including the syntax bits. */
200 /* isalpha etc. are used for the character classes. */
203 /* Jim Meyering writes:
205 "... Some ctype macros are valid only for character codes that
206 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
207 using /bin/cc or gcc but without giving an ansi option). So, all
208 ctype uses should be through macros like ISPRINT... If
209 STDC_HEADERS is defined, then autoconf has verified that the ctype
210 macros don't need to be guarded with references to isascii. ...
211 Defining isascii to 1 should let any compiler worth its salt
212 eliminate the && through constant folding." */
214 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
215 #define ISASCII_1(c) 1
217 #define ISASCII_1(c) isascii(c)
221 /* The IS*() macros can be passed any character, including an extended
222 one. We need to make sure there are no crashes, which would occur
223 otherwise due to out-of-bounds array references. */
224 #define ISASCII(c) (((EMACS_UINT) (c)) < 0x100 && ISASCII_1 (c))
226 #define ISASCII(c) ISASCII_1 (c)
230 #define ISBLANK(c) (ISASCII (c) && isblank (c))
232 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
235 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
237 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
240 #define ISPRINT(c) (ISASCII (c) && isprint (c))
241 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
242 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
243 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
244 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
245 #define ISLOWER(c) (ISASCII (c) && islower (c))
246 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
247 #define ISSPACE(c) (ISASCII (c) && isspace (c))
248 #define ISUPPER(c) (ISASCII (c) && isupper (c))
249 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
252 #define NULL (void *)0
255 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
256 since ours (we hope) works properly with all combinations of
257 machines, compilers, `char' and `unsigned char' argument types.
258 (Per Bothner suggested the basic approach.) */
259 #undef SIGN_EXTEND_CHAR
261 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
262 #else /* not __STDC__ */
263 /* As in Harbison and Steele. */
264 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
267 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
268 use `alloca' instead of `malloc'. This is because using malloc in
269 re_search* or re_match* could cause memory leaks when C-g is used in
270 Emacs; also, malloc is slower and causes storage fragmentation. On
271 the other hand, malloc is more portable, and easier to debug.
273 Because we sometimes use alloca, some routines have to be macros,
274 not functions -- `alloca'-allocated space disappears at the end of the
275 function it is called in. */
279 #define REGEX_ALLOCATE malloc
280 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
281 #define REGEX_FREE free
283 #else /* not REGEX_MALLOC */
285 /* Emacs already defines alloca, sometimes. */
288 /* Make alloca work the best possible way. */
290 #define alloca __builtin_alloca
291 #else /* not __GNUC__ */
294 #else /* not __GNUC__ or HAVE_ALLOCA_H */
295 #ifndef _AIX /* Already did AIX, up at the top. */
297 #endif /* not _AIX */
298 #endif /* HAVE_ALLOCA_H */
299 #endif /* __GNUC__ */
301 #endif /* not alloca */
303 #define REGEX_ALLOCATE alloca
305 /* Assumes a `char *destination' variable. */
306 #define REGEX_REALLOCATE(source, osize, nsize) \
307 (destination = (char *) alloca (nsize), \
308 memmove (destination, source, osize), \
311 /* No need to do anything to free, after alloca. */
312 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
314 #endif /* REGEX_MALLOC */
316 /* Define how to allocate the failure stack. */
319 #define REGEX_ALLOCATE_STACK(size) \
320 r_alloc ((char **) &failure_stack_ptr, (size))
321 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
322 r_re_alloc ((char **) &failure_stack_ptr, (nsize))
323 #define REGEX_FREE_STACK(ptr) \
324 r_alloc_free ((void **) &failure_stack_ptr)
326 #else /* not REL_ALLOC */
330 #define REGEX_ALLOCATE_STACK malloc
331 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
332 #define REGEX_FREE_STACK free
334 #else /* not REGEX_MALLOC */
336 #define REGEX_ALLOCATE_STACK alloca
338 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
339 REGEX_REALLOCATE (source, osize, nsize)
340 /* No need to explicitly free anything. */
341 #define REGEX_FREE_STACK(arg)
343 #endif /* REGEX_MALLOC */
344 #endif /* REL_ALLOC */
347 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
348 `string1' or just past its end. This works if PTR is NULL, which is
350 #define FIRST_STRING_P(ptr) \
351 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
353 /* (Re)Allocate N items of type T using malloc, or fail. */
354 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
355 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
356 #define RETALLOC_IF(addr, n, t) \
357 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
358 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
360 #define BYTEWIDTH 8 /* In bits. */
362 #define STREQ(s1, s2) (strcmp (s1, s2) == 0)
366 #define MAX(a, b) ((a) > (b) ? (a) : (b))
367 #define MIN(a, b) ((a) < (b) ? (a) : (b))
369 /* Type of source-pattern and string chars. */
370 typedef const unsigned char re_char;
372 typedef char boolean;
377 /* These are the command codes that appear in compiled regular
378 expressions. Some opcodes are followed by argument bytes. A
379 command code can specify any interpretation whatsoever for its
380 arguments. Zero bytes may appear in the compiled regular expression. */
386 /* Succeed right away--no more backtracking. */
389 /* Followed by one byte giving n, then by n literal bytes. */
392 /* Matches any (more or less) character. */
395 /* Matches any one char belonging to specified set. First
396 following byte is number of bitmap bytes. Then come bytes
397 for a bitmap saying which chars are in. Bits in each byte
398 are ordered low-bit-first. A character is in the set if its
399 bit is 1. A character too large to have a bit in the map is
400 automatically not in the set. */
403 /* Same parameters as charset, but match any character that is
404 not one of those specified. */
407 /* Start remembering the text that is matched, for storing in a
408 register. Followed by one byte with the register number, in
409 the range 0 to one less than the pattern buffer's re_nsub
410 field. Then followed by one byte with the number of groups
411 inner to this one. (This last has to be part of the
412 start_memory only because we need it in the on_failure_jump
416 /* Stop remembering the text that is matched and store it in a
417 memory register. Followed by one byte with the register
418 number, in the range 0 to one less than `re_nsub' in the
419 pattern buffer, and one byte with the number of inner groups,
420 just like `start_memory'. (We need the number of inner
421 groups here because we don't have any easy way of finding the
422 corresponding start_memory when we're at a stop_memory.) */
425 /* Match a duplicate of something remembered. Followed by one
426 byte containing the register number. */
429 /* Fail unless at beginning of line. */
432 /* Fail unless at end of line. */
435 /* Succeeds if at beginning of buffer (if emacs) or at beginning
436 of string to be matched (if not). */
439 /* Analogously, for end of buffer/string. */
442 /* Followed by two byte relative address to which to jump. */
445 /* Same as jump, but marks the end of an alternative. */
448 /* Followed by two-byte relative address of place to resume at
449 in case of failure. */
452 /* Like on_failure_jump, but pushes a placeholder instead of the
453 current string position when executed. */
454 on_failure_keep_string_jump,
456 /* Throw away latest failure point and then jump to following
457 two-byte relative address. */
460 /* Change to pop_failure_jump if know won't have to backtrack to
461 match; otherwise change to jump. This is used to jump
462 back to the beginning of a repeat. If what follows this jump
463 clearly won't match what the repeat does, such that we can be
464 sure that there is no use backtracking out of repetitions
465 already matched, then we change it to a pop_failure_jump.
466 Followed by two-byte address. */
469 /* Jump to following two-byte address, and push a dummy failure
470 point. This failure point will be thrown away if an attempt
471 is made to use it for a failure. A `+' construct makes this
472 before the first repeat. Also used as an intermediary kind
473 of jump when compiling an alternative. */
476 /* Push a dummy failure point and continue. Used at the end of
480 /* Followed by two-byte relative address and two-byte number n.
481 After matching N times, jump to the address upon failure. */
484 /* Followed by two-byte relative address, and two-byte number n.
485 Jump to the address N times, then fail. */
488 /* Set the following two-byte relative address to the
489 subsequent two-byte number. The address *includes* the two
493 wordchar, /* Matches any word-constituent character. */
494 notwordchar, /* Matches any char that is not a word-constituent. */
496 wordbeg, /* Succeeds if at word beginning. */
497 wordend, /* Succeeds if at word end. */
499 wordbound, /* Succeeds if at a word boundary. */
500 notwordbound /* Succeeds if not at a word boundary. */
503 ,before_dot, /* Succeeds if before point. */
504 at_dot, /* Succeeds if at point. */
505 after_dot, /* Succeeds if after point. */
507 /* Matches any character whose syntax is specified. Followed by
508 a byte which contains a syntax code, e.g., Sword. */
511 /* Matches any character whose syntax is not that specified. */
517 /* need extra stuff to be able to properly work with XEmacs/Mule
518 characters (which may take up more than one byte) */
520 ,charset_mule, /* Matches any character belonging to specified set.
521 The set is stored in "unified range-table
522 format"; see rangetab.c. Unlike the `charset'
523 opcode, this can handle arbitrary characters. */
525 charset_mule_not /* Same parameters as charset_mule, but match any
526 character that is not one of those specified. */
528 /* 97/2/17 jhod: The following two were merged back in from the Mule
529 2.3 code to enable some language specific processing */
530 ,categoryspec, /* Matches entries in the character category tables */
531 notcategoryspec /* The opposite of the above */
536 /* Common operations on the compiled pattern. */
538 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
540 #define STORE_NUMBER(destination, number) \
542 (destination)[0] = (number) & 0377; \
543 (destination)[1] = (number) >> 8; \
546 /* Same as STORE_NUMBER, except increment DESTINATION to
547 the byte after where the number is stored. Therefore, DESTINATION
548 must be an lvalue. */
550 #define STORE_NUMBER_AND_INCR(destination, number) \
552 STORE_NUMBER (destination, number); \
553 (destination) += 2; \
556 /* Put into DESTINATION a number stored in two contiguous bytes starting
559 #define EXTRACT_NUMBER(destination, source) \
561 (destination) = *(source) & 0377; \
562 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
567 extract_number (int *dest, re_char *source)
569 int temp = SIGN_EXTEND_CHAR (*(source + 1));
570 *dest = *source & 0377;
574 #ifndef EXTRACT_MACROS /* To debug the macros. */
575 #undef EXTRACT_NUMBER
576 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
577 #endif /* not EXTRACT_MACROS */
581 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
582 SOURCE must be an lvalue. */
584 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
586 EXTRACT_NUMBER (destination, source); \
592 extract_number_and_incr (int *destination, unsigned char **source)
594 extract_number (destination, *source);
598 #ifndef EXTRACT_MACROS
599 #undef EXTRACT_NUMBER_AND_INCR
600 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
601 extract_number_and_incr (&dest, &src)
602 #endif /* not EXTRACT_MACROS */
606 /* If DEBUG is defined, Regex prints many voluminous messages about what
607 it is doing (if the variable `debug' is nonzero). If linked with the
608 main program in `iregex.c', you can enter patterns and strings
609 interactively. And if linked with the main program in `main.c' and
610 the other test files, you can run the already-written tests. */
614 /* We use standard I/O for debugging. */
618 /* XEmacs provides its own version of assert() */
619 /* It is useful to test things that ``must'' be true when debugging. */
623 static int debug = 0;
625 #define DEBUG_STATEMENT(e) e
626 #define DEBUG_PRINT1(x) if (debug) printf (x)
627 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
628 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
629 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
630 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
631 if (debug) print_partial_compiled_pattern (s, e)
632 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
633 if (debug) print_double_string (w, s1, sz1, s2, sz2)
636 /* Print the fastmap in human-readable form. */
639 print_fastmap (char *fastmap)
641 unsigned was_a_range = 0;
644 while (i < (1 << BYTEWIDTH))
650 while (i < (1 << BYTEWIDTH) && fastmap[i])
666 /* Print a compiled pattern string in human-readable form, starting at
667 the START pointer into it and ending just before the pointer END. */
670 print_partial_compiled_pattern (re_char *start, re_char *end)
673 unsigned char *p = (unsigned char *) start;
682 /* Loop over pattern commands. */
685 printf ("%ld:\t", (long)(p - start));
687 switch ((re_opcode_t) *p++)
695 printf ("/exactn/%d", mcnt);
706 printf ("/start_memory/%d/%d", mcnt, *p++);
711 printf ("/stop_memory/%d/%d", mcnt, *p++);
715 printf ("/duplicate/%d", *p++);
725 REGISTER int c, last = -100;
726 REGISTER int in_range = 0;
728 printf ("/charset [%s",
729 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
731 assert (p + *p < pend);
733 for (c = 0; c < 256; c++)
734 if (((unsigned char) (c / 8) < *p)
735 && (p[1 + (c/8)] & (1 << (c % 8))))
737 /* Are we starting a range? */
738 if (last + 1 == c && ! in_range)
743 /* Have we broken a range? */
744 else if (last + 1 != c && in_range)
767 case charset_mule_not:
771 printf ("/charset_mule [%s",
772 (re_opcode_t) *(p - 1) == charset_mule_not ? "^" : "");
773 nentries = unified_range_table_nentries (p);
774 for (i = 0; i < nentries; i++)
776 EMACS_INT first, last;
777 Lisp_Object dummy_val;
779 unified_range_table_get_range (p, i, &first, &last,
784 printf ("(0x%lx)", (long)first);
791 printf ("(0x%lx)", (long)last);
795 p += unified_range_table_bytes_used (p);
808 case on_failure_jump:
809 extract_number_and_incr (&mcnt, &p);
810 printf ("/on_failure_jump to %ld", (long)(p + mcnt - start));
813 case on_failure_keep_string_jump:
814 extract_number_and_incr (&mcnt, &p);
815 printf ("/on_failure_keep_string_jump to %ld", (long)(p + mcnt - start));
818 case dummy_failure_jump:
819 extract_number_and_incr (&mcnt, &p);
820 printf ("/dummy_failure_jump to %ld", (long)(p + mcnt - start));
823 case push_dummy_failure:
824 printf ("/push_dummy_failure");
828 extract_number_and_incr (&mcnt, &p);
829 printf ("/maybe_pop_jump to %ld", (long)(p + mcnt - start));
832 case pop_failure_jump:
833 extract_number_and_incr (&mcnt, &p);
834 printf ("/pop_failure_jump to %ld", (long)(p + mcnt - start));
838 extract_number_and_incr (&mcnt, &p);
839 printf ("/jump_past_alt to %ld", (long)(p + mcnt - start));
843 extract_number_and_incr (&mcnt, &p);
844 printf ("/jump to %ld", (long)(p + mcnt - start));
848 extract_number_and_incr (&mcnt, &p);
849 extract_number_and_incr (&mcnt2, &p);
850 printf ("/succeed_n to %ld, %d times", (long)(p + mcnt - start), mcnt2);
854 extract_number_and_incr (&mcnt, &p);
855 extract_number_and_incr (&mcnt2, &p);
856 printf ("/jump_n to %ld, %d times", (long)(p + mcnt - start), mcnt2);
860 extract_number_and_incr (&mcnt, &p);
861 extract_number_and_incr (&mcnt2, &p);
862 printf ("/set_number_at location %ld to %d", (long)(p + mcnt - start), mcnt2);
866 printf ("/wordbound");
870 printf ("/notwordbound");
882 printf ("/before_dot");
890 printf ("/after_dot");
894 printf ("/syntaxspec");
896 printf ("/%d", mcnt);
900 printf ("/notsyntaxspec");
902 printf ("/%d", mcnt);
906 /* 97/2/17 jhod Mule category patch */
908 printf ("/categoryspec");
910 printf ("/%d", mcnt);
913 case notcategoryspec:
914 printf ("/notcategoryspec");
916 printf ("/%d", mcnt);
918 /* end of category patch */
923 printf ("/wordchar");
927 printf ("/notwordchar");
939 printf ("?%d", *(p-1));
945 printf ("%ld:\tend of pattern.\n", (long)(p - start));
950 print_compiled_pattern (struct re_pattern_buffer *bufp)
952 re_char *buffer = bufp->buffer;
954 print_partial_compiled_pattern (buffer, buffer + bufp->used);
955 printf ("%ld bytes used/%ld bytes allocated.\n", bufp->used,
958 if (bufp->fastmap_accurate && bufp->fastmap)
960 printf ("fastmap: ");
961 print_fastmap (bufp->fastmap);
964 printf ("re_nsub: %ld\t", (long)bufp->re_nsub);
965 printf ("regs_alloc: %d\t", bufp->regs_allocated);
966 printf ("can_be_null: %d\t", bufp->can_be_null);
967 printf ("newline_anchor: %d\n", bufp->newline_anchor);
968 printf ("no_sub: %d\t", bufp->no_sub);
969 printf ("not_bol: %d\t", bufp->not_bol);
970 printf ("not_eol: %d\t", bufp->not_eol);
971 printf ("syntax: %d\n", bufp->syntax);
972 /* Perhaps we should print the translate table? */
973 /* and maybe the category table? */
978 print_double_string (re_char *where, re_char *string1, int size1,
979 re_char *string2, int size2)
985 unsigned int this_char;
987 if (FIRST_STRING_P (where))
989 for (this_char = where - string1; this_char < size1; this_char++)
990 putchar (string1[this_char]);
995 for (this_char = where - string2; this_char < size2; this_char++)
996 putchar (string2[this_char]);
1000 #else /* not DEBUG */
1005 #define DEBUG_STATEMENT(e)
1006 #define DEBUG_PRINT1(x)
1007 #define DEBUG_PRINT2(x1, x2)
1008 #define DEBUG_PRINT3(x1, x2, x3)
1009 #define DEBUG_PRINT4(x1, x2, x3, x4)
1010 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1011 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1015 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1016 also be assigned to arbitrarily: each pattern buffer stores its own
1017 syntax, so it can be changed between regex compilations. */
1018 /* This has no initializer because initialized variables in Emacs
1019 become read-only after dumping. */
1020 reg_syntax_t re_syntax_options;
1023 /* Specify the precise syntax of regexps for compilation. This provides
1024 for compatibility for various utilities which historically have
1025 different, incompatible syntaxes.
1027 The argument SYNTAX is a bit mask comprised of the various bits
1028 defined in regex.h. We return the old syntax. */
1031 re_set_syntax (reg_syntax_t syntax)
1033 reg_syntax_t ret = re_syntax_options;
1035 re_syntax_options = syntax;
1039 /* This table gives an error message for each of the error codes listed
1040 in regex.h. Obviously the order here has to be same as there.
1041 POSIX doesn't require that we do anything for REG_NOERROR,
1042 but why not be nice? */
1044 static const char *re_error_msgid[] =
1046 "Success", /* REG_NOERROR */
1047 "No match", /* REG_NOMATCH */
1048 "Invalid regular expression", /* REG_BADPAT */
1049 "Invalid collation character", /* REG_ECOLLATE */
1050 "Invalid character class name", /* REG_ECTYPE */
1051 "Trailing backslash", /* REG_EESCAPE */
1052 "Invalid back reference", /* REG_ESUBREG */
1053 "Unmatched [ or [^", /* REG_EBRACK */
1054 "Unmatched ( or \\(", /* REG_EPAREN */
1055 "Unmatched \\{", /* REG_EBRACE */
1056 "Invalid content of \\{\\}", /* REG_BADBR */
1057 "Invalid range end", /* REG_ERANGE */
1058 "Memory exhausted", /* REG_ESPACE */
1059 "Invalid preceding regular expression", /* REG_BADRPT */
1060 "Premature end of regular expression", /* REG_EEND */
1061 "Regular expression too big", /* REG_ESIZE */
1062 "Unmatched ) or \\)", /* REG_ERPAREN */
1064 "Invalid syntax designator", /* REG_ESYNTAX */
1067 "Ranges may not span charsets", /* REG_ERANGESPAN */
1068 "Invalid category designator", /* REG_ECATEGORY */
1072 /* Avoiding alloca during matching, to placate r_alloc. */
1074 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1075 searching and matching functions should not call alloca. On some
1076 systems, alloca is implemented in terms of malloc, and if we're
1077 using the relocating allocator routines, then malloc could cause a
1078 relocation, which might (if the strings being searched are in the
1079 ralloc heap) shift the data out from underneath the regexp
1082 Here's another reason to avoid allocation: Emacs
1083 processes input from X in a signal handler; processing X input may
1084 call malloc; if input arrives while a matching routine is calling
1085 malloc, then we're scrod. But Emacs can't just block input while
1086 calling matching routines; then we don't notice interrupts when
1087 they come in. So, Emacs blocks input around all regexp calls
1088 except the matching calls, which it leaves unprotected, in the
1089 faith that they will not malloc. */
1091 /* Normally, this is fine. */
1092 #define MATCH_MAY_ALLOCATE
1094 /* When using GNU C, we are not REALLY using the C alloca, no matter
1095 what config.h may say. So don't take precautions for it. */
1100 /* The match routines may not allocate if (1) they would do it with malloc
1101 and (2) it's not safe for them to use malloc.
1102 Note that if REL_ALLOC is defined, matching would not use malloc for the
1103 failure stack, but we would still use it for the register vectors;
1104 so REL_ALLOC should not affect this. */
1105 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1106 #undef MATCH_MAY_ALLOCATE
1110 /* Failure stack declarations and macros; both re_compile_fastmap and
1111 re_match_2 use a failure stack. These have to be macros because of
1112 REGEX_ALLOCATE_STACK. */
1115 /* Number of failure points for which to initially allocate space
1116 when matching. If this number is exceeded, we allocate more
1117 space, so it is not a hard limit. */
1118 #ifndef INIT_FAILURE_ALLOC
1119 #define INIT_FAILURE_ALLOC 5
1122 /* Roughly the maximum number of failure points on the stack. Would be
1123 exactly that if always used MAX_FAILURE_SPACE each time we failed.
1124 This is a variable only so users of regex can assign to it; we never
1125 change it ourselves. */
1126 #if defined (MATCH_MAY_ALLOCATE)
1127 /* 4400 was enough to cause a crash on Alpha OSF/1,
1128 whose default stack limit is 2mb. */
1129 int re_max_failures = 20000;
1131 int re_max_failures = 2000;
1134 union fail_stack_elt
1140 typedef union fail_stack_elt fail_stack_elt_t;
1144 fail_stack_elt_t *stack;
1146 size_t avail; /* Offset of next open position. */
1149 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1150 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1151 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1154 /* Define macros to initialize and free the failure stack.
1155 Do `return -2' if the alloc fails. */
1157 #ifdef MATCH_MAY_ALLOCATE
1158 #define INIT_FAIL_STACK() \
1160 fail_stack.stack = (fail_stack_elt_t *) \
1161 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1163 if (fail_stack.stack == NULL) \
1166 fail_stack.size = INIT_FAILURE_ALLOC; \
1167 fail_stack.avail = 0; \
1170 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1172 #define INIT_FAIL_STACK() \
1174 fail_stack.avail = 0; \
1177 #define RESET_FAIL_STACK()
1181 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1183 Return 1 if succeeds, and 0 if either ran out of memory
1184 allocating space for it or it was already too large.
1186 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1188 #define DOUBLE_FAIL_STACK(fail_stack) \
1189 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
1191 : ((fail_stack).stack = (fail_stack_elt_t *) \
1192 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1193 (fail_stack).size * sizeof (fail_stack_elt_t), \
1194 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1196 (fail_stack).stack == NULL \
1198 : ((fail_stack).size <<= 1, \
1202 /* Push pointer POINTER on FAIL_STACK.
1203 Return 1 if was able to do so and 0 if ran out of memory allocating
1205 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1206 ((FAIL_STACK_FULL () \
1207 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1209 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1212 /* Push a pointer value onto the failure stack.
1213 Assumes the variable `fail_stack'. Probably should only
1214 be called from within `PUSH_FAILURE_POINT'. */
1215 #define PUSH_FAILURE_POINTER(item) \
1216 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1218 /* This pushes an integer-valued item onto the failure stack.
1219 Assumes the variable `fail_stack'. Probably should only
1220 be called from within `PUSH_FAILURE_POINT'. */
1221 #define PUSH_FAILURE_INT(item) \
1222 fail_stack.stack[fail_stack.avail++].integer = (item)
1224 /* Push a fail_stack_elt_t value onto the failure stack.
1225 Assumes the variable `fail_stack'. Probably should only
1226 be called from within `PUSH_FAILURE_POINT'. */
1227 #define PUSH_FAILURE_ELT(item) \
1228 fail_stack.stack[fail_stack.avail++] = (item)
1230 /* These three POP... operations complement the three PUSH... operations.
1231 All assume that `fail_stack' is nonempty. */
1232 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1233 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1234 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1236 /* Used to omit pushing failure point id's when we're not debugging. */
1238 #define DEBUG_PUSH PUSH_FAILURE_INT
1239 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1241 #define DEBUG_PUSH(item)
1242 #define DEBUG_POP(item_addr)
1246 /* Push the information about the state we will need
1247 if we ever fail back to it.
1249 Requires variables fail_stack, regstart, regend, reg_info, and
1250 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
1253 Does `return FAILURE_CODE' if runs out of memory. */
1255 #if !defined (REGEX_MALLOC) && !defined (REL_ALLOC)
1256 #define DECLARE_DESTINATION char *destination
1258 #define DECLARE_DESTINATION DECLARE_NOTHING
1261 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1263 DECLARE_DESTINATION; \
1264 /* Must be int, so when we don't save any registers, the arithmetic \
1265 of 0 + -1 isn't done as unsigned. */ \
1268 DEBUG_STATEMENT (failure_id++); \
1269 DEBUG_STATEMENT (nfailure_points_pushed++); \
1270 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1271 DEBUG_PRINT2 (" Before push, next avail: %lu\n", \
1272 (unsigned long) (fail_stack).avail); \
1273 DEBUG_PRINT2 (" size: %lu\n", \
1274 (unsigned long) (fail_stack).size); \
1276 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1277 DEBUG_PRINT2 (" available: %ld\n", \
1278 (long) REMAINING_AVAIL_SLOTS); \
1280 /* Ensure we have enough space allocated for what we will push. */ \
1281 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1283 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1284 return failure_code; \
1286 DEBUG_PRINT2 ("\n Doubled stack; size now: %lu\n", \
1287 (unsigned long) (fail_stack).size); \
1288 DEBUG_PRINT2 (" slots available: %ld\n", \
1289 (long) REMAINING_AVAIL_SLOTS); \
1292 /* Push the info, starting with the registers. */ \
1293 DEBUG_PRINT1 ("\n"); \
1295 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1298 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1299 DEBUG_STATEMENT (num_regs_pushed++); \
1301 DEBUG_PRINT2 (" start: 0x%lx\n", (long) regstart[this_reg]); \
1302 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1304 DEBUG_PRINT2 (" end: 0x%lx\n", (long) regend[this_reg]); \
1305 PUSH_FAILURE_POINTER (regend[this_reg]); \
1307 DEBUG_PRINT2 (" info: 0x%lx\n ", \
1308 * (long *) (®_info[this_reg])); \
1309 DEBUG_PRINT2 (" match_null=%d", \
1310 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1311 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1312 DEBUG_PRINT2 (" matched_something=%d", \
1313 MATCHED_SOMETHING (reg_info[this_reg])); \
1314 DEBUG_PRINT2 (" ever_matched_something=%d", \
1315 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1316 DEBUG_PRINT1 ("\n"); \
1317 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1320 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg); \
1321 PUSH_FAILURE_INT (lowest_active_reg); \
1323 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg); \
1324 PUSH_FAILURE_INT (highest_active_reg); \
1326 DEBUG_PRINT2 (" Pushing pattern 0x%lx: \n", (long) pattern_place); \
1327 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1328 PUSH_FAILURE_POINTER (pattern_place); \
1330 DEBUG_PRINT2 (" Pushing string 0x%lx: `", (long) string_place); \
1331 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1333 DEBUG_PRINT1 ("'\n"); \
1334 PUSH_FAILURE_POINTER (string_place); \
1336 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1337 DEBUG_PUSH (failure_id); \
1340 /* This is the number of items that are pushed and popped on the stack
1341 for each register. */
1342 #define NUM_REG_ITEMS 3
1344 /* Individual items aside from the registers. */
1346 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1348 #define NUM_NONREG_ITEMS 4
1351 /* We push at most this many items on the stack. */
1352 /* We used to use (num_regs - 1), which is the number of registers
1353 this regexp will save; but that was changed to 5
1354 to avoid stack overflow for a regexp with lots of parens. */
1355 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1357 /* We actually push this many items. */
1358 #define NUM_FAILURE_ITEMS \
1359 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
1362 /* How many items can still be added to the stack without overflowing it. */
1363 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1366 /* Pops what PUSH_FAIL_STACK pushes.
1368 We restore into the parameters, all of which should be lvalues:
1369 STR -- the saved data position.
1370 PAT -- the saved pattern position.
1371 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1372 REGSTART, REGEND -- arrays of string positions.
1373 REG_INFO -- array of information about each subexpression.
1375 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1376 `pend', `string1', `size1', `string2', and `size2'. */
1378 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, \
1379 regstart, regend, reg_info) \
1381 DEBUG_STATEMENT (fail_stack_elt_t ffailure_id;) \
1383 const unsigned char *string_temp; \
1385 assert (!FAIL_STACK_EMPTY ()); \
1387 /* Remove failure points and point to how many regs pushed. */ \
1388 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1389 DEBUG_PRINT2 (" Before pop, next avail: %lu\n", \
1390 (unsigned long) fail_stack.avail); \
1391 DEBUG_PRINT2 (" size: %lu\n", \
1392 (unsigned long) fail_stack.size); \
1394 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1396 DEBUG_POP (&ffailure_id.integer); \
1397 DEBUG_PRINT2 (" Popping failure id: %u\n", \
1398 * (unsigned int *) &ffailure_id); \
1400 /* If the saved string location is NULL, it came from an \
1401 on_failure_keep_string_jump opcode, and we want to throw away the \
1402 saved NULL, thus retaining our current position in the string. */ \
1403 string_temp = POP_FAILURE_POINTER (); \
1404 if (string_temp != NULL) \
1405 str = string_temp; \
1407 DEBUG_PRINT2 (" Popping string 0x%lx: `", (long) str); \
1408 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1409 DEBUG_PRINT1 ("'\n"); \
1411 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1412 DEBUG_PRINT2 (" Popping pattern 0x%lx: ", (long) pat); \
1413 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1415 /* Restore register info. */ \
1416 high_reg = (unsigned) POP_FAILURE_INT (); \
1417 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1419 low_reg = (unsigned) POP_FAILURE_INT (); \
1420 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1422 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1424 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1426 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1427 DEBUG_PRINT2 (" info: 0x%lx\n", \
1428 * (long *) ®_info[this_reg]); \
1430 regend[this_reg] = POP_FAILURE_POINTER (); \
1431 DEBUG_PRINT2 (" end: 0x%lx\n", (long) regend[this_reg]); \
1433 regstart[this_reg] = POP_FAILURE_POINTER (); \
1434 DEBUG_PRINT2 (" start: 0x%lx\n", (long) regstart[this_reg]); \
1437 set_regs_matched_done = 0; \
1438 DEBUG_STATEMENT (nfailure_points_popped++); \
1439 } while (0) /* POP_FAILURE_POINT */
1443 /* Structure for per-register (a.k.a. per-group) information.
1444 Other register information, such as the
1445 starting and ending positions (which are addresses), and the list of
1446 inner groups (which is a bits list) are maintained in separate
1449 We are making a (strictly speaking) nonportable assumption here: that
1450 the compiler will pack our bit fields into something that fits into
1451 the type of `word', i.e., is something that fits into one item on the
1456 fail_stack_elt_t word;
1459 /* This field is one if this group can match the empty string,
1460 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1461 #define MATCH_NULL_UNSET_VALUE 3
1462 unsigned match_null_string_p : 2;
1463 unsigned is_active : 1;
1464 unsigned matched_something : 1;
1465 unsigned ever_matched_something : 1;
1467 } register_info_type;
1469 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1470 #define IS_ACTIVE(R) ((R).bits.is_active)
1471 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1472 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1475 /* Call this when have matched a real character; it sets `matched' flags
1476 for the subexpressions which we are currently inside. Also records
1477 that those subexprs have matched. */
1478 #define SET_REGS_MATCHED() \
1481 if (!set_regs_matched_done) \
1484 set_regs_matched_done = 1; \
1485 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1487 MATCHED_SOMETHING (reg_info[r]) \
1488 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1495 /* Registers are set to a sentinel when they haven't yet matched. */
1496 static unsigned char reg_unset_dummy;
1497 #define REG_UNSET_VALUE (®_unset_dummy)
1498 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1500 /* Subroutine declarations and macros for regex_compile. */
1502 /* Fetch the next character in the uncompiled pattern---translating it
1503 if necessary. Also cast from a signed character in the constant
1504 string passed to us by the user to an unsigned char that we can use
1505 as an array index (in, e.g., `translate'). */
1506 #define PATFETCH(c) \
1509 c = TRANSLATE (c); \
1512 /* Fetch the next character in the uncompiled pattern, with no
1514 #define PATFETCH_RAW(c) \
1515 do {if (p == pend) return REG_EEND; \
1516 assert (p < pend); \
1517 c = charptr_emchar (p); \
1521 /* Go backwards one character in the pattern. */
1522 #define PATUNFETCH DEC_CHARPTR (p)
1526 #define PATFETCH_EXTENDED(emch) \
1527 do {if (p == pend) return REG_EEND; \
1528 assert (p < pend); \
1529 emch = charptr_emchar ((const Bufbyte *) p); \
1531 if (TRANSLATE_P (translate) && emch < 0x80) \
1532 emch = (Emchar) (unsigned char) RE_TRANSLATE (emch); \
1535 #define PATFETCH_RAW_EXTENDED(emch) \
1536 do {if (p == pend) return REG_EEND; \
1537 assert (p < pend); \
1538 emch = charptr_emchar ((const Bufbyte *) p); \
1542 #define PATUNFETCH_EXTENDED DEC_CHARPTR (p)
1544 #define PATFETCH_EITHER(emch) \
1546 if (has_extended_chars) \
1547 PATFETCH_EXTENDED (emch); \
1552 #define PATFETCH_RAW_EITHER(emch) \
1554 if (has_extended_chars) \
1555 PATFETCH_RAW_EXTENDED (emch); \
1557 PATFETCH_RAW (emch); \
1560 #define PATUNFETCH_EITHER \
1562 if (has_extended_chars) \
1563 PATUNFETCH_EXTENDED (emch); \
1565 PATUNFETCH (emch); \
1568 #else /* not MULE */
1570 #define PATFETCH_EITHER(emch) PATFETCH (emch)
1571 #define PATFETCH_RAW_EITHER(emch) PATFETCH_RAW (emch)
1572 #define PATUNFETCH_EITHER PATUNFETCH
1576 /* If `translate' is non-null, return translate[D], else just D. We
1577 cast the subscript to translate because some data is declared as
1578 `char *', to avoid warnings when a string constant is passed. But
1579 when we use a character as a subscript we must make it unsigned. */
1580 #define TRANSLATE(d) (TRANSLATE_P (translate) ? RE_TRANSLATE (d) : (d))
1584 #define TRANSLATE_EXTENDED_UNSAFE(emch) \
1585 (TRANSLATE_P (translate) && emch < 0x80 ? RE_TRANSLATE (emch) : (emch))
1589 /* Macros for outputting the compiled pattern into `buffer'. */
1591 /* If the buffer isn't allocated when it comes in, use this. */
1592 #define INIT_BUF_SIZE 32
1594 /* Make sure we have at least N more bytes of space in buffer. */
1595 #define GET_BUFFER_SPACE(n) \
1596 while (buf_end - bufp->buffer + (n) > bufp->allocated) \
1599 /* Make sure we have one more byte of buffer space and then add C to it. */
1600 #define BUF_PUSH(c) \
1602 GET_BUFFER_SPACE (1); \
1603 *buf_end++ = (unsigned char) (c); \
1607 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1608 #define BUF_PUSH_2(c1, c2) \
1610 GET_BUFFER_SPACE (2); \
1611 *buf_end++ = (unsigned char) (c1); \
1612 *buf_end++ = (unsigned char) (c2); \
1616 /* As with BUF_PUSH_2, except for three bytes. */
1617 #define BUF_PUSH_3(c1, c2, c3) \
1619 GET_BUFFER_SPACE (3); \
1620 *buf_end++ = (unsigned char) (c1); \
1621 *buf_end++ = (unsigned char) (c2); \
1622 *buf_end++ = (unsigned char) (c3); \
1626 /* Store a jump with opcode OP at LOC to location TO. We store a
1627 relative address offset by the three bytes the jump itself occupies. */
1628 #define STORE_JUMP(op, loc, to) \
1629 store_op1 (op, loc, (to) - (loc) - 3)
1631 /* Likewise, for a two-argument jump. */
1632 #define STORE_JUMP2(op, loc, to, arg) \
1633 store_op2 (op, loc, (to) - (loc) - 3, arg)
1635 /* Like `STORE_JUMP', but for inserting. Assume `buf_end' is the
1637 #define INSERT_JUMP(op, loc, to) \
1638 insert_op1 (op, loc, (to) - (loc) - 3, buf_end)
1640 /* Like `STORE_JUMP2', but for inserting. Assume `buf_end' is the
1642 #define INSERT_JUMP2(op, loc, to, arg) \
1643 insert_op2 (op, loc, (to) - (loc) - 3, arg, buf_end)
1646 /* This is not an arbitrary limit: the arguments which represent offsets
1647 into the pattern are two bytes long. So if 2^16 bytes turns out to
1648 be too small, many things would have to change. */
1649 #define MAX_BUF_SIZE (1L << 16)
1652 /* Extend the buffer by twice its current size via realloc and
1653 reset the pointers that pointed into the old block to point to the
1654 correct places in the new one. If extending the buffer results in it
1655 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1656 #define EXTEND_BUFFER() \
1658 re_char *old_buffer = bufp->buffer; \
1659 if (bufp->allocated == MAX_BUF_SIZE) \
1661 bufp->allocated <<= 1; \
1662 if (bufp->allocated > MAX_BUF_SIZE) \
1663 bufp->allocated = MAX_BUF_SIZE; \
1664 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1665 if (bufp->buffer == NULL) \
1666 return REG_ESPACE; \
1667 /* If the buffer moved, move all the pointers into it. */ \
1668 if (old_buffer != bufp->buffer) \
1670 buf_end = (buf_end - old_buffer) + bufp->buffer; \
1671 begalt = (begalt - old_buffer) + bufp->buffer; \
1672 if (fixup_alt_jump) \
1673 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1675 laststart = (laststart - old_buffer) + bufp->buffer; \
1676 if (pending_exact) \
1677 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1682 /* Since we have one byte reserved for the register number argument to
1683 {start,stop}_memory, the maximum number of groups we can report
1684 things about is what fits in that byte. */
1685 #define MAX_REGNUM 255
1687 /* But patterns can have more than `MAX_REGNUM' registers. We just
1688 ignore the excess. */
1689 typedef unsigned regnum_t;
1692 /* Macros for the compile stack. */
1694 /* Since offsets can go either forwards or backwards, this type needs to
1695 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1696 typedef int pattern_offset_t;
1700 pattern_offset_t begalt_offset;
1701 pattern_offset_t fixup_alt_jump;
1702 pattern_offset_t inner_group_offset;
1703 pattern_offset_t laststart_offset;
1705 } compile_stack_elt_t;
1710 compile_stack_elt_t *stack;
1712 unsigned avail; /* Offset of next open position. */
1713 } compile_stack_type;
1716 #define INIT_COMPILE_STACK_SIZE 32
1718 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1719 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1721 /* The next available element. */
1722 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1725 /* Set the bit for character C in a bit vector. */
1726 #define SET_LIST_BIT(c) \
1727 (buf_end[((unsigned char) (c)) / BYTEWIDTH] \
1728 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1732 /* Set the "bit" for character C in a range table. */
1733 #define SET_RANGETAB_BIT(c) put_range_table (rtab, c, c, Qt)
1735 /* Set the "bit" for character c in the appropriate table. */
1736 #define SET_EITHER_BIT(c) \
1738 if (has_extended_chars) \
1739 SET_RANGETAB_BIT (c); \
1744 #else /* not MULE */
1746 #define SET_EITHER_BIT(c) SET_LIST_BIT (c)
1751 /* Get the next unsigned number in the uncompiled pattern. */
1752 #define GET_UNSIGNED_NUMBER(num) \
1756 while (ISDIGIT (c)) \
1760 num = num * 10 + c - '0'; \
1768 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1770 #define IS_CHAR_CLASS(string) \
1771 (STREQ (string, "alpha") || STREQ (string, "upper") \
1772 || STREQ (string, "lower") || STREQ (string, "digit") \
1773 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1774 || STREQ (string, "space") || STREQ (string, "print") \
1775 || STREQ (string, "punct") || STREQ (string, "graph") \
1776 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1778 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1779 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1780 static void insert_op1 (re_opcode_t op, unsigned char *loc, int arg,
1781 unsigned char *end);
1782 static void insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2,
1783 unsigned char *end);
1784 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1785 reg_syntax_t syntax);
1786 static boolean at_endline_loc_p (re_char *p, re_char *pend, int syntax);
1787 static boolean group_in_compile_stack (compile_stack_type compile_stack,
1789 static reg_errcode_t compile_range (re_char **p_ptr, re_char *pend,
1790 RE_TRANSLATE_TYPE translate,
1791 reg_syntax_t syntax,
1794 static reg_errcode_t compile_extended_range (re_char **p_ptr,
1796 RE_TRANSLATE_TYPE translate,
1797 reg_syntax_t syntax,
1800 static boolean group_match_null_string_p (unsigned char **p,
1802 register_info_type *reg_info);
1803 static boolean alt_match_null_string_p (unsigned char *p, unsigned char *end,
1804 register_info_type *reg_info);
1805 static boolean common_op_match_null_string_p (unsigned char **p,
1807 register_info_type *reg_info);
1808 static int bcmp_translate (const unsigned char *s1, const unsigned char *s2,
1809 REGISTER int len, RE_TRANSLATE_TYPE translate);
1810 static int re_match_2_internal (struct re_pattern_buffer *bufp,
1811 re_char *string1, int size1,
1812 re_char *string2, int size2, int pos,
1813 struct re_registers *regs, int stop);
1815 #ifndef MATCH_MAY_ALLOCATE
1817 /* If we cannot allocate large objects within re_match_2_internal,
1818 we make the fail stack and register vectors global.
1819 The fail stack, we grow to the maximum size when a regexp
1821 The register vectors, we adjust in size each time we
1822 compile a regexp, according to the number of registers it needs. */
1824 static fail_stack_type fail_stack;
1826 /* Size with which the following vectors are currently allocated.
1827 That is so we can make them bigger as needed,
1828 but never make them smaller. */
1829 static int regs_allocated_size;
1831 static re_char ** regstart, ** regend;
1832 static re_char ** old_regstart, ** old_regend;
1833 static re_char **best_regstart, **best_regend;
1834 static register_info_type *reg_info;
1835 static re_char **reg_dummy;
1836 static register_info_type *reg_info_dummy;
1838 /* Make the register vectors big enough for NUM_REGS registers,
1839 but don't make them smaller. */
1842 regex_grow_registers (int num_regs)
1844 if (num_regs > regs_allocated_size)
1846 RETALLOC_IF (regstart, num_regs, re_char *);
1847 RETALLOC_IF (regend, num_regs, re_char *);
1848 RETALLOC_IF (old_regstart, num_regs, re_char *);
1849 RETALLOC_IF (old_regend, num_regs, re_char *);
1850 RETALLOC_IF (best_regstart, num_regs, re_char *);
1851 RETALLOC_IF (best_regend, num_regs, re_char *);
1852 RETALLOC_IF (reg_info, num_regs, register_info_type);
1853 RETALLOC_IF (reg_dummy, num_regs, re_char *);
1854 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1856 regs_allocated_size = num_regs;
1860 #endif /* not MATCH_MAY_ALLOCATE */
1862 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1863 Returns one of error codes defined in `regex.h', or zero for success.
1865 Assumes the `allocated' (and perhaps `buffer') and `translate'
1866 fields are set in BUFP on entry.
1868 If it succeeds, results are put in BUFP (if it returns an error, the
1869 contents of BUFP are undefined):
1870 `buffer' is the compiled pattern;
1871 `syntax' is set to SYNTAX;
1872 `used' is set to the length of the compiled pattern;
1873 `fastmap_accurate' is zero;
1874 `re_nsub' is the number of subexpressions in PATTERN;
1875 `not_bol' and `not_eol' are zero;
1877 The `fastmap' and `newline_anchor' fields are neither
1878 examined nor set. */
1880 /* Return, freeing storage we allocated. */
1881 #define FREE_STACK_RETURN(value) \
1882 return (free (compile_stack.stack), value)
1884 static reg_errcode_t
1885 regex_compile (re_char *pattern, int size, reg_syntax_t syntax,
1886 struct re_pattern_buffer *bufp)
1888 /* We fetch characters from PATTERN here. We declare these as int
1889 (or possibly long) so that chars above 127 can be used as
1890 array indices. The macros that fetch a character from the pattern
1891 make sure to coerce to unsigned char before assigning, so we won't
1892 get bitten by negative numbers here. */
1893 /* XEmacs change: used to be unsigned char. */
1894 REGISTER EMACS_INT c, c1;
1896 /* A random temporary spot in PATTERN. */
1899 /* Points to the end of the buffer, where we should append. */
1900 REGISTER unsigned char *buf_end;
1902 /* Keeps track of unclosed groups. */
1903 compile_stack_type compile_stack;
1905 /* Points to the current (ending) position in the pattern. */
1906 re_char *p = pattern;
1907 re_char *pend = pattern + size;
1909 /* How to translate the characters in the pattern. */
1910 RE_TRANSLATE_TYPE translate = bufp->translate;
1912 /* Address of the count-byte of the most recently inserted `exactn'
1913 command. This makes it possible to tell if a new exact-match
1914 character can be added to that command or if the character requires
1915 a new `exactn' command. */
1916 unsigned char *pending_exact = 0;
1918 /* Address of start of the most recently finished expression.
1919 This tells, e.g., postfix * where to find the start of its
1920 operand. Reset at the beginning of groups and alternatives. */
1921 unsigned char *laststart = 0;
1923 /* Address of beginning of regexp, or inside of last group. */
1924 unsigned char *begalt;
1926 /* Place in the uncompiled pattern (i.e., the {) to
1927 which to go back if the interval is invalid. */
1928 re_char *beg_interval;
1930 /* Address of the place where a forward jump should go to the end of
1931 the containing expression. Each alternative of an `or' -- except the
1932 last -- ends with a forward jump of this sort. */
1933 unsigned char *fixup_alt_jump = 0;
1935 /* Counts open-groups as they are encountered. Remembered for the
1936 matching close-group on the compile stack, so the same register
1937 number is put in the stop_memory as the start_memory. */
1938 regnum_t regnum = 0;
1941 DEBUG_PRINT1 ("\nCompiling pattern: ");
1944 unsigned debug_count;
1946 for (debug_count = 0; debug_count < size; debug_count++)
1947 putchar (pattern[debug_count]);
1952 /* Initialize the compile stack. */
1953 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1954 if (compile_stack.stack == NULL)
1957 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1958 compile_stack.avail = 0;
1960 /* Initialize the pattern buffer. */
1961 bufp->syntax = syntax;
1962 bufp->fastmap_accurate = 0;
1963 bufp->not_bol = bufp->not_eol = 0;
1965 /* Set `used' to zero, so that if we return an error, the pattern
1966 printer (for debugging) will think there's no pattern. We reset it
1970 /* Always count groups, whether or not bufp->no_sub is set. */
1973 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1974 /* Initialize the syntax table. */
1975 init_syntax_once ();
1978 if (bufp->allocated == 0)
1981 { /* If zero allocated, but buffer is non-null, try to realloc
1982 enough space. This loses if buffer's address is bogus, but
1983 that is the user's responsibility. */
1984 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1987 { /* Caller did not allocate a buffer. Do it for them. */
1988 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1990 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1992 bufp->allocated = INIT_BUF_SIZE;
1995 begalt = buf_end = bufp->buffer;
1997 /* Loop through the uncompiled pattern until we're at the end. */
2006 if ( /* If at start of pattern, it's an operator. */
2008 /* If context independent, it's an operator. */
2009 || syntax & RE_CONTEXT_INDEP_ANCHORS
2010 /* Otherwise, depends on what's come before. */
2011 || at_begline_loc_p (pattern, p, syntax))
2021 if ( /* If at end of pattern, it's an operator. */
2023 /* If context independent, it's an operator. */
2024 || syntax & RE_CONTEXT_INDEP_ANCHORS
2025 /* Otherwise, depends on what's next. */
2026 || at_endline_loc_p (p, pend, syntax))
2036 if ((syntax & RE_BK_PLUS_QM)
2037 || (syntax & RE_LIMITED_OPS))
2041 /* If there is no previous pattern... */
2044 if (syntax & RE_CONTEXT_INVALID_OPS)
2045 FREE_STACK_RETURN (REG_BADRPT);
2046 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2051 /* true means zero/many matches are allowed. */
2052 boolean zero_times_ok = c != '+';
2053 boolean many_times_ok = c != '?';
2055 /* true means match shortest string possible. */
2056 boolean minimal = false;
2058 /* If there is a sequence of repetition chars, collapse it
2059 down to just one (the right one). We can't combine
2060 interval operators with these because of, e.g., `a{2}*',
2061 which should only match an even number of `a's. */
2066 if (c == '*' || (!(syntax & RE_BK_PLUS_QM)
2067 && (c == '+' || c == '?')))
2070 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2072 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2075 if (!(c1 == '+' || c1 == '?'))
2090 /* If we get here, we found another repeat character. */
2091 if (!(syntax & RE_NO_MINIMAL_MATCHING))
2093 /* "*?" and "+?" and "??" are okay (and mean match
2094 minimally), but other sequences (such as "*??" and
2095 "+++") are rejected (reserved for future use). */
2096 if (minimal || c != '?')
2097 FREE_STACK_RETURN (REG_BADRPT);
2102 zero_times_ok |= c != '+';
2103 many_times_ok |= c != '?';
2107 /* Star, etc. applied to an empty pattern is equivalent
2108 to an empty pattern. */
2112 /* Now we know whether zero matches is allowed
2113 and whether two or more matches is allowed
2114 and whether we want minimal or maximal matching. */
2120 0: /on_failure_jump to 6
2125 GET_BUFFER_SPACE (6);
2126 INSERT_JUMP (jump, laststart, buf_end + 3);
2128 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2131 else if (zero_times_ok)
2136 6: /on_failure_jump to 3
2139 GET_BUFFER_SPACE (6);
2140 INSERT_JUMP (jump, laststart, buf_end + 3);
2142 STORE_JUMP (on_failure_jump, buf_end, laststart + 3);
2149 3: /on_failure_jump to 0
2152 GET_BUFFER_SPACE (3);
2153 STORE_JUMP (on_failure_jump, buf_end, laststart);
2159 /* Are we optimizing this jump? */
2160 boolean keep_string_p = false;
2163 { /* More than one repetition is allowed, so put in
2164 at the end a backward relative jump from
2165 `buf_end' to before the next jump we're going
2166 to put in below (which jumps from laststart to
2169 But if we are at the `*' in the exact sequence `.*\n',
2170 insert an unconditional jump backwards to the .,
2171 instead of the beginning of the loop. This way we only
2172 push a failure point once, instead of every time
2173 through the loop. */
2174 assert (p - 1 > pattern);
2176 /* Allocate the space for the jump. */
2177 GET_BUFFER_SPACE (3);
2179 /* We know we are not at the first character of the
2180 pattern, because laststart was nonzero. And we've
2181 already incremented `p', by the way, to be the
2182 character after the `*'. Do we have to do something
2183 analogous here for null bytes, because of
2187 && p < pend && *p == '\n'
2188 && !(syntax & RE_DOT_NEWLINE))
2189 { /* We have .*\n. */
2190 STORE_JUMP (jump, buf_end, laststart);
2191 keep_string_p = true;
2194 /* Anything else. */
2195 STORE_JUMP (maybe_pop_jump, buf_end, laststart - 3);
2197 /* We've added more stuff to the buffer. */
2201 /* On failure, jump from laststart to buf_end + 3,
2202 which will be the end of the buffer after this jump
2204 GET_BUFFER_SPACE (3);
2205 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2207 laststart, buf_end + 3);
2212 /* At least one repetition is required, so insert a
2213 `dummy_failure_jump' before the initial
2214 `on_failure_jump' instruction of the loop. This
2215 effects a skip over that instruction the first time
2216 we hit that loop. */
2217 GET_BUFFER_SPACE (3);
2218 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2228 laststart = buf_end;
2235 /* XEmacs change: this whole section */
2236 boolean had_char_class = false;
2238 boolean has_extended_chars = false;
2239 REGISTER Lisp_Object rtab = Qnil;
2242 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2244 /* Ensure that we have enough space to push a charset: the
2245 opcode, the length count, and the bitset; 34 bytes in all. */
2246 GET_BUFFER_SPACE (34);
2248 laststart = buf_end;
2250 /* We test `*p == '^' twice, instead of using an if
2251 statement, so we only need one BUF_PUSH. */
2252 BUF_PUSH (*p == '^' ? charset_not : charset);
2256 /* Remember the first position in the bracket expression. */
2259 /* Push the number of bytes in the bitmap. */
2260 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2262 /* Clear the whole map. */
2263 memset (buf_end, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2265 /* charset_not matches newline according to a syntax bit. */
2266 if ((re_opcode_t) buf_end[-2] == charset_not
2267 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2268 SET_LIST_BIT ('\n');
2271 start_over_with_extended:
2272 if (has_extended_chars)
2274 /* There are extended chars here, which means we need to start
2275 over and shift to unified range-table format. */
2276 if (buf_end[-2] == charset)
2277 buf_end[-2] = charset_mule;
2279 buf_end[-2] = charset_mule_not;
2281 p = p1; /* go back to the beginning of the charset, after
2283 rtab = Vthe_lisp_rangetab;
2284 Fclear_range_table (rtab);
2286 /* charset_not matches newline according to a syntax bit. */
2287 if ((re_opcode_t) buf_end[-1] == charset_mule_not
2288 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2289 SET_EITHER_BIT ('\n');
2293 /* Read in characters and ranges, setting map bits. */
2296 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2301 if (c >= 0x80 && !has_extended_chars)
2303 has_extended_chars = 1;
2304 /* Frumble-bumble, we've found some extended chars.
2305 Need to start over, process everything using
2306 the general extended-char mechanism, and need
2307 to use charset_mule and charset_mule_not instead
2308 of charset and charset_not. */
2309 goto start_over_with_extended;
2312 /* \ might escape characters inside [...] and [^...]. */
2313 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2315 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2319 if (c1 >= 0x80 && !has_extended_chars)
2321 has_extended_chars = 1;
2322 goto start_over_with_extended;
2325 SET_EITHER_BIT (c1);
2329 /* Could be the end of the bracket expression. If it's
2330 not (i.e., when the bracket expression is `[]' so
2331 far), the ']' character bit gets set way below. */
2332 if (c == ']' && p != p1 + 1)
2335 /* Look ahead to see if it's a range when the last thing
2336 was a character class. */
2337 if (had_char_class && c == '-' && *p != ']')
2338 FREE_STACK_RETURN (REG_ERANGE);
2340 /* Look ahead to see if it's a range when the last thing
2341 was a character: if this is a hyphen not at the
2342 beginning or the end of a list, then it's the range
2345 && !(p - 2 >= pattern && p[-2] == '[')
2346 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2352 if (* (unsigned char *) p >= 0x80 && !has_extended_chars)
2354 has_extended_chars = 1;
2355 goto start_over_with_extended;
2357 if (has_extended_chars)
2358 ret = compile_extended_range (&p, pend, translate,
2362 ret = compile_range (&p, pend, translate, syntax, buf_end);
2363 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2366 else if (p[0] == '-' && p[1] != ']')
2367 { /* This handles ranges made up of characters only. */
2370 /* Move past the `-'. */
2374 if (* (unsigned char *) p >= 0x80 && !has_extended_chars)
2376 has_extended_chars = 1;
2377 goto start_over_with_extended;
2379 if (has_extended_chars)
2380 ret = compile_extended_range (&p, pend, translate,
2384 ret = compile_range (&p, pend, translate, syntax, buf_end);
2385 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2388 /* See if we're at the beginning of a possible character
2391 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2392 { /* Leave room for the null. */
2393 char str[CHAR_CLASS_MAX_LENGTH + 1];
2398 /* If pattern is `[[:'. */
2399 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2403 /* #### This code is unused.
2404 Correctness is not checked after TRT
2407 if (c == ':' || c == ']' || p == pend
2408 || c1 == CHAR_CLASS_MAX_LENGTH)
2410 str[c1++] = (char) c;
2414 /* If isn't a word bracketed by `[:' and `:]':
2415 undo the ending character, the letters, and leave
2416 the leading `:' and `[' (but set bits for them). */
2417 if (c == ':' && *p == ']')
2420 boolean is_alnum = STREQ (str, "alnum");
2421 boolean is_alpha = STREQ (str, "alpha");
2422 boolean is_blank = STREQ (str, "blank");
2423 boolean is_cntrl = STREQ (str, "cntrl");
2424 boolean is_digit = STREQ (str, "digit");
2425 boolean is_graph = STREQ (str, "graph");
2426 boolean is_lower = STREQ (str, "lower");
2427 boolean is_print = STREQ (str, "print");
2428 boolean is_punct = STREQ (str, "punct");
2429 boolean is_space = STREQ (str, "space");
2430 boolean is_upper = STREQ (str, "upper");
2431 boolean is_xdigit = STREQ (str, "xdigit");
2433 if (!IS_CHAR_CLASS (str))
2434 FREE_STACK_RETURN (REG_ECTYPE);
2436 /* Throw away the ] at the end of the character
2440 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2442 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2444 /* This was split into 3 if's to
2445 avoid an arbitrary limit in some compiler. */
2446 if ( (is_alnum && ISALNUM (ch))
2447 || (is_alpha && ISALPHA (ch))
2448 || (is_blank && ISBLANK (ch))
2449 || (is_cntrl && ISCNTRL (ch)))
2450 SET_EITHER_BIT (ch);
2451 if ( (is_digit && ISDIGIT (ch))
2452 || (is_graph && ISGRAPH (ch))
2453 || (is_lower && ISLOWER (ch))
2454 || (is_print && ISPRINT (ch)))
2455 SET_EITHER_BIT (ch);
2456 if ( (is_punct && ISPUNCT (ch))
2457 || (is_space && ISSPACE (ch))
2458 || (is_upper && ISUPPER (ch))
2459 || (is_xdigit && ISXDIGIT (ch)))
2460 SET_EITHER_BIT (ch);
2462 had_char_class = true;
2469 SET_EITHER_BIT ('[');
2470 SET_EITHER_BIT (':');
2471 had_char_class = false;
2476 had_char_class = false;
2482 if (has_extended_chars)
2484 /* We have a range table, not a bit vector. */
2486 unified_range_table_bytes_needed (rtab);
2487 GET_BUFFER_SPACE (bytes_needed);
2488 unified_range_table_copy_data (rtab, buf_end);
2489 buf_end += unified_range_table_bytes_used (buf_end);
2493 /* Discard any (non)matching list bytes that are all 0 at the
2494 end of the map. Decrease the map-length byte too. */
2495 while ((int) buf_end[-1] > 0 && buf_end[buf_end[-1] - 1] == 0)
2497 buf_end += buf_end[-1];
2503 if (syntax & RE_NO_BK_PARENS)
2510 if (syntax & RE_NO_BK_PARENS)
2517 if (syntax & RE_NEWLINE_ALT)
2524 if (syntax & RE_NO_BK_VBAR)
2531 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2532 goto handle_interval;
2538 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2540 /* Do not translate the character after the \, so that we can
2541 distinguish, e.g., \B from \b, even if we normally would
2542 translate, e.g., B to b. */
2548 if (syntax & RE_NO_BK_PARENS)
2549 goto normal_backslash;
2555 if (!(syntax & RE_NO_SHY_GROUPS)
2563 case ':': /* shy groups */
2567 /* All others are reserved for future constructs. */
2569 FREE_STACK_RETURN (REG_BADPAT);
2578 if (COMPILE_STACK_FULL)
2580 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2581 compile_stack_elt_t);
2582 if (compile_stack.stack == NULL) return REG_ESPACE;
2584 compile_stack.size <<= 1;
2587 /* These are the values to restore when we hit end of this
2588 group. They are all relative offsets, so that if the
2589 whole pattern moves because of realloc, they will still
2591 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2592 COMPILE_STACK_TOP.fixup_alt_jump
2593 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2594 COMPILE_STACK_TOP.laststart_offset = buf_end - bufp->buffer;
2595 COMPILE_STACK_TOP.regnum = r;
2597 /* We will eventually replace the 0 with the number of
2598 groups inner to this one. But do not push a
2599 start_memory for groups beyond the last one we can
2600 represent in the compiled pattern. */
2601 if (r <= MAX_REGNUM)
2603 COMPILE_STACK_TOP.inner_group_offset
2604 = buf_end - bufp->buffer + 2;
2605 BUF_PUSH_3 (start_memory, r, 0);
2608 compile_stack.avail++;
2613 /* If we've reached MAX_REGNUM groups, then this open
2614 won't actually generate any code, so we'll have to
2615 clear pending_exact explicitly. */
2622 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2624 if (COMPILE_STACK_EMPTY) {
2625 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2626 goto normal_backslash;
2628 FREE_STACK_RETURN (REG_ERPAREN);
2633 { /* Push a dummy failure point at the end of the
2634 alternative for a possible future
2635 `pop_failure_jump' to pop. See comments at
2636 `push_dummy_failure' in `re_match_2'. */
2637 BUF_PUSH (push_dummy_failure);
2639 /* We allocated space for this jump when we assigned
2640 to `fixup_alt_jump', in the `handle_alt' case below. */
2641 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end - 1);
2644 /* See similar code for backslashed left paren above. */
2645 if (COMPILE_STACK_EMPTY) {
2646 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2649 FREE_STACK_RETURN (REG_ERPAREN);
2652 /* Since we just checked for an empty stack above, this
2653 ``can't happen''. */
2654 assert (compile_stack.avail != 0);
2656 /* We don't just want to restore into `regnum', because
2657 later groups should continue to be numbered higher,
2658 as in `(ab)c(de)' -- the second group is #2. */
2659 regnum_t this_group_regnum;
2661 compile_stack.avail--;
2662 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2664 = COMPILE_STACK_TOP.fixup_alt_jump
2665 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2667 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2668 this_group_regnum = COMPILE_STACK_TOP.regnum;
2669 /* If we've reached MAX_REGNUM groups, then this open
2670 won't actually generate any code, so we'll have to
2671 clear pending_exact explicitly. */
2674 /* We're at the end of the group, so now we know how many
2675 groups were inside this one. */
2676 if (this_group_regnum <= MAX_REGNUM)
2678 unsigned char *inner_group_loc
2679 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2681 *inner_group_loc = regnum - this_group_regnum;
2682 BUF_PUSH_3 (stop_memory, this_group_regnum,
2683 regnum - this_group_regnum);
2689 case '|': /* `\|'. */
2690 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2691 goto normal_backslash;
2693 if (syntax & RE_LIMITED_OPS)
2696 /* Insert before the previous alternative a jump which
2697 jumps to this alternative if the former fails. */
2698 GET_BUFFER_SPACE (3);
2699 INSERT_JUMP (on_failure_jump, begalt, buf_end + 6);
2703 /* The alternative before this one has a jump after it
2704 which gets executed if it gets matched. Adjust that
2705 jump so it will jump to this alternative's analogous
2706 jump (put in below, which in turn will jump to the next
2707 (if any) alternative's such jump, etc.). The last such
2708 jump jumps to the correct final destination. A picture:
2714 If we are at `b', then fixup_alt_jump right now points to a
2715 three-byte space after `a'. We'll put in the jump, set
2716 fixup_alt_jump to right after `b', and leave behind three
2717 bytes which we'll fill in when we get to after `c'. */
2720 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end);
2722 /* Mark and leave space for a jump after this alternative,
2723 to be filled in later either by next alternative or
2724 when know we're at the end of a series of alternatives. */
2725 fixup_alt_jump = buf_end;
2726 GET_BUFFER_SPACE (3);
2735 /* If \{ is a literal. */
2736 if (!(syntax & RE_INTERVALS)
2737 /* If we're at `\{' and it's not the open-interval
2739 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2740 || (p - 2 == pattern && p == pend))
2741 goto normal_backslash;
2745 /* If got here, then the syntax allows intervals. */
2747 /* At least (most) this many matches must be made. */
2748 int lower_bound = -1, upper_bound = -1;
2750 beg_interval = p - 1;
2754 if (syntax & RE_NO_BK_BRACES)
2755 goto unfetch_interval;
2757 FREE_STACK_RETURN (REG_EBRACE);
2760 GET_UNSIGNED_NUMBER (lower_bound);
2764 GET_UNSIGNED_NUMBER (upper_bound);
2765 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2768 /* Interval such as `{1}' => match exactly once. */
2769 upper_bound = lower_bound;
2771 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2772 || lower_bound > upper_bound)
2774 if (syntax & RE_NO_BK_BRACES)
2775 goto unfetch_interval;
2777 FREE_STACK_RETURN (REG_BADBR);
2780 if (!(syntax & RE_NO_BK_BRACES))
2782 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2789 if (syntax & RE_NO_BK_BRACES)
2790 goto unfetch_interval;
2792 FREE_STACK_RETURN (REG_BADBR);
2795 /* We just parsed a valid interval. */
2797 /* If it's invalid to have no preceding re. */
2800 if (syntax & RE_CONTEXT_INVALID_OPS)
2801 FREE_STACK_RETURN (REG_BADRPT);
2802 else if (syntax & RE_CONTEXT_INDEP_OPS)
2803 laststart = buf_end;
2805 goto unfetch_interval;
2808 /* If the upper bound is zero, don't want to succeed at
2809 all; jump from `laststart' to `b + 3', which will be
2810 the end of the buffer after we insert the jump. */
2811 if (upper_bound == 0)
2813 GET_BUFFER_SPACE (3);
2814 INSERT_JUMP (jump, laststart, buf_end + 3);
2818 /* Otherwise, we have a nontrivial interval. When
2819 we're all done, the pattern will look like:
2820 set_number_at <jump count> <upper bound>
2821 set_number_at <succeed_n count> <lower bound>
2822 succeed_n <after jump addr> <succeed_n count>
2824 jump_n <succeed_n addr> <jump count>
2825 (The upper bound and `jump_n' are omitted if
2826 `upper_bound' is 1, though.) */
2828 { /* If the upper bound is > 1, we need to insert
2829 more at the end of the loop. */
2830 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2832 GET_BUFFER_SPACE (nbytes);
2834 /* Initialize lower bound of the `succeed_n', even
2835 though it will be set during matching by its
2836 attendant `set_number_at' (inserted next),
2837 because `re_compile_fastmap' needs to know.
2838 Jump to the `jump_n' we might insert below. */
2839 INSERT_JUMP2 (succeed_n, laststart,
2840 buf_end + 5 + (upper_bound > 1) * 5,
2844 /* Code to initialize the lower bound. Insert
2845 before the `succeed_n'. The `5' is the last two
2846 bytes of this `set_number_at', plus 3 bytes of
2847 the following `succeed_n'. */
2848 insert_op2 (set_number_at, laststart, 5, lower_bound, buf_end);
2851 if (upper_bound > 1)
2852 { /* More than one repetition is allowed, so
2853 append a backward jump to the `succeed_n'
2854 that starts this interval.
2856 When we've reached this during matching,
2857 we'll have matched the interval once, so
2858 jump back only `upper_bound - 1' times. */
2859 STORE_JUMP2 (jump_n, buf_end, laststart + 5,
2863 /* The location we want to set is the second
2864 parameter of the `jump_n'; that is `b-2' as
2865 an absolute address. `laststart' will be
2866 the `set_number_at' we're about to insert;
2867 `laststart+3' the number to set, the source
2868 for the relative address. But we are
2869 inserting into the middle of the pattern --
2870 so everything is getting moved up by 5.
2871 Conclusion: (b - 2) - (laststart + 3) + 5,
2872 i.e., b - laststart.
2874 We insert this at the beginning of the loop
2875 so that if we fail during matching, we'll
2876 reinitialize the bounds. */
2877 insert_op2 (set_number_at, laststart,
2878 buf_end - laststart,
2879 upper_bound - 1, buf_end);
2884 beg_interval = NULL;
2889 /* If an invalid interval, match the characters as literals. */
2890 assert (beg_interval);
2892 beg_interval = NULL;
2894 /* normal_char and normal_backslash need `c'. */
2897 if (!(syntax & RE_NO_BK_BRACES))
2899 if (p > pattern && p[-1] == '\\')
2900 goto normal_backslash;
2905 /* There is no way to specify the before_dot and after_dot
2906 operators. rms says this is ok. --karl */
2912 laststart = buf_end;
2914 /* XEmacs addition */
2915 if (c >= 0x80 || syntax_spec_code[c] == 0377)
2916 FREE_STACK_RETURN (REG_ESYNTAX);
2917 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2921 laststart = buf_end;
2923 /* XEmacs addition */
2924 if (c >= 0x80 || syntax_spec_code[c] == 0377)
2925 FREE_STACK_RETURN (REG_ESYNTAX);
2926 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2930 /* 97.2.17 jhod merged in to XEmacs from mule-2.3 */
2932 laststart = buf_end;
2934 if (c < 32 || c > 127)
2935 FREE_STACK_RETURN (REG_ECATEGORY);
2936 BUF_PUSH_2 (categoryspec, c);
2940 laststart = buf_end;
2942 if (c < 32 || c > 127)
2943 FREE_STACK_RETURN (REG_ECATEGORY);
2944 BUF_PUSH_2 (notcategoryspec, c);
2946 /* end of category patch */
2952 laststart = buf_end;
2953 BUF_PUSH (wordchar);
2958 laststart = buf_end;
2959 BUF_PUSH (notwordchar);
2972 BUF_PUSH (wordbound);
2976 BUF_PUSH (notwordbound);
2987 case '1': case '2': case '3': case '4': case '5':
2988 case '6': case '7': case '8': case '9':
2991 if (syntax & RE_NO_BK_REFS)
2997 FREE_STACK_RETURN (REG_ESUBREG);
2999 /* Can't back reference to a subexpression if inside of it. */
3000 if (group_in_compile_stack (compile_stack, reg))
3003 laststart = buf_end;
3004 BUF_PUSH_2 (duplicate, reg);
3011 if (syntax & RE_BK_PLUS_QM)
3014 goto normal_backslash;
3018 /* You might think it would be useful for \ to mean
3019 not to translate; but if we don't translate it,
3020 it will never match anything. */
3028 /* Expects the character in `c'. */
3029 /* `p' points to the location after where `c' came from. */
3032 /* XEmacs: modifications here for Mule. */
3033 /* `q' points to the beginning of the next char. */
3036 /* If no exactn currently being built. */
3039 /* If last exactn not at current position. */
3040 || pending_exact + *pending_exact + 1 != buf_end
3042 /* We have only one byte following the exactn for the count. */
3043 || ((unsigned int) (*pending_exact + (q - p)) >=
3044 ((unsigned int) (1 << BYTEWIDTH) - 1))
3046 /* If followed by a repetition operator. */
3047 || *q == '*' || *q == '^'
3048 || ((syntax & RE_BK_PLUS_QM)
3049 ? *q == '\\' && (q[1] == '+' || q[1] == '?')
3050 : (*q == '+' || *q == '?'))
3051 || ((syntax & RE_INTERVALS)
3052 && ((syntax & RE_NO_BK_BRACES)
3054 : (q[0] == '\\' && q[1] == '{'))))
3056 /* Start building a new exactn. */
3058 laststart = buf_end;
3060 BUF_PUSH_2 (exactn, 0);
3061 pending_exact = buf_end - 1;
3070 Bufbyte tmp_buf[MAX_EMCHAR_LEN];
3073 bt_count = set_charptr_emchar (tmp_buf, c);
3075 for (i = 0; i < bt_count; i++)
3077 BUF_PUSH (tmp_buf[i]);
3085 } /* while p != pend */
3088 /* Through the pattern now. */
3091 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end);
3093 if (!COMPILE_STACK_EMPTY)
3094 FREE_STACK_RETURN (REG_EPAREN);
3096 /* If we don't want backtracking, force success
3097 the first time we reach the end of the compiled pattern. */
3098 if (syntax & RE_NO_POSIX_BACKTRACKING)
3101 free (compile_stack.stack);
3103 /* We have succeeded; set the length of the buffer. */
3104 bufp->used = buf_end - bufp->buffer;
3109 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3110 print_compiled_pattern (bufp);
3114 #ifndef MATCH_MAY_ALLOCATE
3115 /* Initialize the failure stack to the largest possible stack. This
3116 isn't necessary unless we're trying to avoid calling alloca in
3117 the search and match routines. */
3119 int num_regs = bufp->re_nsub + 1;
3121 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
3122 is strictly greater than re_max_failures, the largest possible stack
3123 is 2 * re_max_failures failure points. */
3124 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
3126 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
3129 if (! fail_stack.stack)
3131 = (fail_stack_elt_t *) xmalloc (fail_stack.size
3132 * sizeof (fail_stack_elt_t));
3135 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
3137 * sizeof (fail_stack_elt_t)));
3138 #else /* not emacs */
3139 if (! fail_stack.stack)
3141 = (fail_stack_elt_t *) malloc (fail_stack.size
3142 * sizeof (fail_stack_elt_t));
3145 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3147 * sizeof (fail_stack_elt_t)));
3151 regex_grow_registers (num_regs);
3153 #endif /* not MATCH_MAY_ALLOCATE */
3156 } /* regex_compile */
3158 /* Subroutines for `regex_compile'. */
3160 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3163 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3165 *loc = (unsigned char) op;
3166 STORE_NUMBER (loc + 1, arg);
3170 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3173 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3175 *loc = (unsigned char) op;
3176 STORE_NUMBER (loc + 1, arg1);
3177 STORE_NUMBER (loc + 3, arg2);
3181 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3182 for OP followed by two-byte integer parameter ARG. */
3185 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3187 REGISTER unsigned char *pfrom = end;
3188 REGISTER unsigned char *pto = end + 3;
3190 while (pfrom != loc)
3193 store_op1 (op, loc, arg);
3197 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3200 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2,
3203 REGISTER unsigned char *pfrom = end;
3204 REGISTER unsigned char *pto = end + 5;
3206 while (pfrom != loc)
3209 store_op2 (op, loc, arg1, arg2);
3213 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3214 after an alternative or a begin-subexpression. We assume there is at
3215 least one character before the ^. */
3218 at_begline_loc_p (re_char *pattern, re_char *p, reg_syntax_t syntax)
3220 re_char *prev = p - 2;
3221 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3224 /* After a subexpression? */
3225 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3226 /* After an alternative? */
3227 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3231 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3232 at least one character after the $, i.e., `P < PEND'. */
3235 at_endline_loc_p (re_char *p, re_char *pend, int syntax)
3238 boolean next_backslash = *next == '\\';
3239 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3242 /* Before a subexpression? */
3243 (syntax & RE_NO_BK_PARENS ? *next == ')'
3244 : next_backslash && next_next && *next_next == ')')
3245 /* Before an alternative? */
3246 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3247 : next_backslash && next_next && *next_next == '|');
3251 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3252 false if it's not. */
3255 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3259 for (this_element = compile_stack.avail - 1;
3262 if (compile_stack.stack[this_element].regnum == regnum)
3269 /* Read the ending character of a range (in a bracket expression) from the
3270 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3271 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3272 Then we set the translation of all bits between the starting and
3273 ending characters (inclusive) in the compiled pattern B.
3275 Return an error code.
3277 We use these short variable names so we can use the same macros as
3278 `regex_compile' itself. */
3280 static reg_errcode_t
3281 compile_range (re_char **p_ptr, re_char *pend, RE_TRANSLATE_TYPE translate,
3282 reg_syntax_t syntax, unsigned char *buf_end)
3286 re_char *p = *p_ptr;
3287 int range_start, range_end;
3292 /* Even though the pattern is a signed `char *', we need to fetch
3293 with unsigned char *'s; if the high bit of the pattern character
3294 is set, the range endpoints will be negative if we fetch using a
3297 We also want to fetch the endpoints without translating them; the
3298 appropriate translation is done in the bit-setting loop below. */
3299 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
3300 range_start = ((const unsigned char *) p)[-2];
3301 range_end = ((const unsigned char *) p)[0];
3303 /* Have to increment the pointer into the pattern string, so the
3304 caller isn't still at the ending character. */
3307 /* If the start is after the end, the range is empty. */
3308 if (range_start > range_end)
3309 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3311 /* Here we see why `this_char' has to be larger than an `unsigned
3312 char' -- the range is inclusive, so if `range_end' == 0xff
3313 (assuming 8-bit characters), we would otherwise go into an infinite
3314 loop, since all characters <= 0xff. */
3315 for (this_char = range_start; this_char <= range_end; this_char++)
3317 SET_LIST_BIT (TRANSLATE (this_char));
3325 static reg_errcode_t
3326 compile_extended_range (re_char **p_ptr, re_char *pend,
3327 RE_TRANSLATE_TYPE translate,
3328 reg_syntax_t syntax, Lisp_Object rtab)
3330 Emchar this_char, range_start, range_end;
3336 p = (const Bufbyte *) *p_ptr;
3337 range_end = charptr_emchar (p);
3338 p--; /* back to '-' */
3339 DEC_CHARPTR (p); /* back to start of range */
3340 /* We also want to fetch the endpoints without translating them; the
3341 appropriate translation is done in the bit-setting loop below. */
3342 range_start = charptr_emchar (p);
3343 INC_CHARPTR (*p_ptr);
3345 /* If the start is after the end, the range is empty. */
3346 if (range_start > range_end)
3347 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3349 /* Can't have ranges spanning different charsets, except maybe for
3350 ranges entirely within the first 256 chars. */
3352 if ((range_start >= 0x100 || range_end >= 0x100)
3354 && CHAR_CHARSET_ID (range_start) != CHAR_CHARSET_ID (range_end)
3356 && CHAR_LEADING_BYTE (range_start) != CHAR_LEADING_BYTE (range_end)
3359 return REG_ERANGESPAN;
3361 /* As advertised, translations only work over the 0 - 0x7F range.
3362 Making this kind of stuff work generally is much harder.
3363 Iterating over the whole range like this would be way efficient
3364 if the range encompasses 10,000 chars or something. You'd have
3365 to do something like this:
3369 map over translation table in [range_start, range_end] of
3370 (put the mapped range in a;
3371 put the translation in b)
3372 invert the range in a and truncate to [range_start, range_end]
3373 compute the union of a, b
3374 union the result into rtab
3376 for (this_char = range_start;
3377 this_char <= range_end && this_char < 0x80; this_char++)
3379 SET_RANGETAB_BIT (TRANSLATE (this_char));
3382 if (this_char <= range_end)
3383 put_range_table (rtab, this_char, range_end, Qt);
3390 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3391 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3392 characters can start a string that matches the pattern. This fastmap
3393 is used by re_search to skip quickly over impossible starting points.
3395 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3396 area as BUFP->fastmap.
3398 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3401 Returns 0 if we succeed, -2 if an internal error. */
3404 re_compile_fastmap (struct re_pattern_buffer *bufp)
3407 #ifdef MATCH_MAY_ALLOCATE
3408 fail_stack_type fail_stack;
3410 DECLARE_DESTINATION;
3411 /* We don't push any register information onto the failure stack. */
3413 REGISTER char *fastmap = bufp->fastmap;
3414 unsigned char *pattern = bufp->buffer;
3415 unsigned long size = bufp->used;
3416 unsigned char *p = pattern;
3417 REGISTER unsigned char *pend = pattern + size;
3420 /* This holds the pointer to the failure stack, when
3421 it is allocated relocatably. */
3422 fail_stack_elt_t *failure_stack_ptr;
3425 /* Assume that each path through the pattern can be null until
3426 proven otherwise. We set this false at the bottom of switch
3427 statement, to which we get only if a particular path doesn't
3428 match the empty string. */
3429 boolean path_can_be_null = true;
3431 /* We aren't doing a `succeed_n' to begin with. */
3432 boolean succeed_n_p = false;
3434 assert (fastmap != NULL && p != NULL);
3437 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3438 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3439 bufp->can_be_null = 0;
3443 if (p == pend || *p == succeed)
3445 /* We have reached the (effective) end of pattern. */
3446 if (!FAIL_STACK_EMPTY ())
3448 bufp->can_be_null |= path_can_be_null;
3450 /* Reset for next path. */
3451 path_can_be_null = true;
3453 p = (unsigned char *) fail_stack.stack[--fail_stack.avail].pointer;
3461 /* We should never be about to go beyond the end of the pattern. */
3464 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3467 /* I guess the idea here is to simply not bother with a fastmap
3468 if a backreference is used, since it's too hard to figure out
3469 the fastmap for the corresponding group. Setting
3470 `can_be_null' stops `re_search_2' from using the fastmap, so
3471 that is all we do. */
3473 bufp->can_be_null = 1;
3477 /* Following are the cases which match a character. These end
3486 /* XEmacs: Under Mule, these bit vectors will
3487 only contain values for characters below 0x80. */
3488 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3489 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3495 /* Chars beyond end of map must be allowed. */
3497 for (j = *p * BYTEWIDTH; j < 0x80; j++)
3499 /* And all extended characters must be allowed, too. */
3500 for (j = 0x80; j < 0xA0; j++)
3502 #else /* not MULE */
3503 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3507 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3508 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3518 nentries = unified_range_table_nentries (p);
3519 for (i = 0; i < nentries; i++)
3521 EMACS_INT first, last;
3522 Lisp_Object dummy_val;
3524 Bufbyte strr[MAX_EMCHAR_LEN];
3526 unified_range_table_get_range (p, i, &first, &last,
3528 for (jj = first; jj <= last && jj < 0x80; jj++)
3530 /* Ranges below 0x100 can span charsets, but there
3531 are only two (Control-1 and Latin-1), and
3532 either first or last has to be in them. */
3533 set_charptr_emchar (strr, first);
3537 set_charptr_emchar (strr, last);
3544 case charset_mule_not:
3549 nentries = unified_range_table_nentries (p);
3550 for (i = 0; i < nentries; i++)
3552 EMACS_INT first, last;
3553 Lisp_Object dummy_val;
3555 int smallest_prev = 0;
3557 unified_range_table_get_range (p, i, &first, &last,
3559 for (jj = smallest_prev; jj < first && jj < 0x80; jj++)
3561 smallest_prev = last + 1;
3562 if (smallest_prev >= 0x80)
3565 /* Calculating which leading bytes are actually allowed
3566 here is rather difficult, so we just punt and allow
3568 for (i = 0x80; i < 0xA0; i++)
3580 for (j = 0; j < (1 << BYTEWIDTH); j++)
3583 (regex_emacs_buffer->mirror_syntax_table), j) == Sword)
3592 goto matchnotsyntax;
3594 for (j = 0; j < (1 << BYTEWIDTH); j++)
3597 (regex_emacs_buffer->mirror_syntax_table), j) != Sword)
3605 int fastmap_newline = fastmap['\n'];
3607 /* `.' matches anything ... */
3609 /* "anything" only includes bytes that can be the
3610 first byte of a character. */
3611 for (j = 0; j < 0xA0; j++)
3614 for (j = 0; j < (1 << BYTEWIDTH); j++)
3618 /* ... except perhaps newline. */
3619 if (!(bufp->syntax & RE_DOT_NEWLINE))
3620 fastmap['\n'] = fastmap_newline;
3622 /* Return if we have already set `can_be_null'; if we have,
3623 then the fastmap is irrelevant. Something's wrong here. */
3624 else if (bufp->can_be_null)
3627 /* Otherwise, have to check alternative paths. */
3637 for (j = 0; j < 0x80; j++)
3640 (regex_emacs_buffer->syntax_table), j) ==
3641 (enum syntaxcode) k)
3644 for (j = 0; j < 0x80; j++)
3647 (regex_emacs_buffer->mirror_syntax_table), j) ==
3648 (enum syntaxcode) k)
3651 for (j = 0x80; j < 0xA0; j++)
3654 if (LEADING_BYTE_PREFIX_P(j))
3655 /* too complicated to calculate this right */
3663 cset = CHARSET_BY_LEADING_BYTE (j);
3664 if (CHARSETP (cset))
3666 if (charset_syntax (regex_emacs_buffer, cset,
3668 == Sword || multi_p)
3675 #else /* not MULE */
3676 for (j = 0; j < (1 << BYTEWIDTH); j++)
3679 (regex_emacs_buffer->mirror_syntax_table), j) ==
3680 (enum syntaxcode) k)
3691 for (j = 0; j < 0x80; j++)
3694 (regex_emacs_buffer->syntax_table), j) !=
3695 (enum syntaxcode) k)
3698 for (j = 0; j < 0x80; j++)
3701 (regex_emacs_buffer->mirror_syntax_table), j) !=
3702 (enum syntaxcode) k)
3705 for (j = 0x80; j < 0xA0; j++)
3708 if (LEADING_BYTE_PREFIX_P(j))
3709 /* too complicated to calculate this right */
3717 cset = CHARSET_BY_LEADING_BYTE (j);
3718 if (CHARSETP (cset))
3720 if (charset_syntax (regex_emacs_buffer, cset,
3722 != Sword || multi_p)
3729 #else /* not MULE */
3730 for (j = 0; j < (1 << BYTEWIDTH); j++)
3733 (regex_emacs_buffer->mirror_syntax_table), j) !=
3734 (enum syntaxcode) k)
3740 /* 97/2/17 jhod category patch */
3742 case notcategoryspec:
3743 bufp->can_be_null = 1;
3745 /* end if category patch */
3748 /* All cases after this match the empty string. These end with
3756 #endif /* not emacs */
3768 case push_dummy_failure:
3773 case pop_failure_jump:
3774 case maybe_pop_jump:
3777 case dummy_failure_jump:
3778 EXTRACT_NUMBER_AND_INCR (j, p);
3783 /* Jump backward implies we just went through the body of a
3784 loop and matched nothing. Opcode jumped to should be
3785 `on_failure_jump' or `succeed_n'. Just treat it like an
3786 ordinary jump. For a * loop, it has pushed its failure
3787 point already; if so, discard that as redundant. */
3788 if ((re_opcode_t) *p != on_failure_jump
3789 && (re_opcode_t) *p != succeed_n)
3793 EXTRACT_NUMBER_AND_INCR (j, p);
3796 /* If what's on the stack is where we are now, pop it. */
3797 if (!FAIL_STACK_EMPTY ()
3798 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3804 case on_failure_jump:
3805 case on_failure_keep_string_jump:
3806 handle_on_failure_jump:
3807 EXTRACT_NUMBER_AND_INCR (j, p);
3809 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3810 end of the pattern. We don't want to push such a point,
3811 since when we restore it above, entering the switch will
3812 increment `p' past the end of the pattern. We don't need
3813 to push such a point since we obviously won't find any more
3814 fastmap entries beyond `pend'. Such a pattern can match
3815 the null string, though. */
3818 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3820 RESET_FAIL_STACK ();
3825 bufp->can_be_null = 1;
3829 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3830 succeed_n_p = false;
3837 /* Get to the number of times to succeed. */
3840 /* Increment p past the n for when k != 0. */
3841 EXTRACT_NUMBER_AND_INCR (k, p);
3845 succeed_n_p = true; /* Spaghetti code alert. */
3846 goto handle_on_failure_jump;
3863 abort (); /* We have listed all the cases. */
3866 /* Getting here means we have found the possible starting
3867 characters for one path of the pattern -- and that the empty
3868 string does not match. We need not follow this path further.
3869 Instead, look at the next alternative (remembered on the
3870 stack), or quit if no more. The test at the top of the loop
3871 does these things. */
3872 path_can_be_null = false;
3876 /* Set `can_be_null' for the last path (also the first path, if the
3877 pattern is empty). */
3878 bufp->can_be_null |= path_can_be_null;
3881 RESET_FAIL_STACK ();
3883 } /* re_compile_fastmap */
3885 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3886 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3887 this memory for recording register information. STARTS and ENDS
3888 must be allocated using the malloc library routine, and must each
3889 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3891 If NUM_REGS == 0, then subsequent matches should allocate their own
3894 Unless this function is called, the first search or match using
3895 PATTERN_BUFFER will allocate its own register data, without
3896 freeing the old data. */
3899 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs,
3900 unsigned num_regs, regoff_t *starts, regoff_t *ends)
3904 bufp->regs_allocated = REGS_REALLOCATE;
3905 regs->num_regs = num_regs;
3906 regs->start = starts;
3911 bufp->regs_allocated = REGS_UNALLOCATED;
3913 regs->start = regs->end = (regoff_t *) 0;
3917 /* Searching routines. */
3919 /* Like re_search_2, below, but only one string is specified, and
3920 doesn't let you say where to stop matching. */
3923 re_search (struct re_pattern_buffer *bufp, const char *string, int size,
3924 int startpos, int range, struct re_registers *regs)
3926 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3931 /* Snarfed from src/lisp.h, needed for compiling [ce]tags. */
3932 # define bytecount_to_charcount(ptr, len) (len)
3933 # define charcount_to_bytecount(ptr, len) (len)
3934 typedef int Charcount;
3937 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3938 virtual concatenation of STRING1 and STRING2, starting first at index
3939 STARTPOS, then at STARTPOS + 1, and so on.
3941 With MULE, STARTPOS is a byte position, not a char position. And the
3942 search will increment STARTPOS by the width of the current leading
3945 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3947 RANGE is how far to scan while trying to match. RANGE = 0 means try
3948 only at STARTPOS; in general, the last start tried is STARTPOS +
3951 With MULE, RANGE is a byte position, not a char position. The last
3952 start tried is the character starting <= STARTPOS + RANGE.
3954 In REGS, return the indices of the virtual concatenation of STRING1
3955 and STRING2 that matched the entire BUFP->buffer and its contained
3958 Do not consider matching one past the index STOP in the virtual
3959 concatenation of STRING1 and STRING2.
3961 We return either the position in the strings at which the match was
3962 found, -1 if no match, or -2 if error (such as failure
3966 re_search_2 (struct re_pattern_buffer *bufp, const char *str1,
3967 int size1, const char *str2, int size2, int startpos,
3968 int range, struct re_registers *regs, int stop)
3971 re_char *string1 = (re_char *) str1;
3972 re_char *string2 = (re_char *) str2;
3973 REGISTER char *fastmap = bufp->fastmap;
3974 REGISTER RE_TRANSLATE_TYPE translate = bufp->translate;
3975 int total_size = size1 + size2;
3976 int endpos = startpos + range;
3977 #ifdef REGEX_BEGLINE_CHECK
3978 int anchored_at_begline = 0;
3983 /* Check for out-of-range STARTPOS. */
3984 if (startpos < 0 || startpos > total_size)
3987 /* Fix up RANGE if it might eventually take us outside
3988 the virtual concatenation of STRING1 and STRING2. */
3990 range = 0 - startpos;
3991 else if (endpos > total_size)
3992 range = total_size - startpos;
3994 /* If the search isn't to be a backwards one, don't waste time in a
3995 search for a pattern that must be anchored. */
3996 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4002 d = ((const unsigned char *)
4003 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4004 range = charcount_to_bytecount (d, 1);
4008 /* Update the fastmap now if not correct already. */
4009 if (fastmap && !bufp->fastmap_accurate)
4010 if (re_compile_fastmap (bufp) == -2)
4013 #ifdef REGEX_BEGLINE_CHECK
4017 while (i < bufp->used)
4019 if (bufp->buffer[i] == start_memory ||
4020 bufp->buffer[i] == stop_memory)
4025 anchored_at_begline = i < bufp->used && bufp->buffer[i] == begline;
4029 /* Loop through the string, looking for a place to start matching. */
4032 #ifdef REGEX_BEGLINE_CHECK
4033 /* If the regex is anchored at the beginning of a line (i.e. with a ^),
4034 then we can speed things up by skipping to the next beginning-of-
4036 if (anchored_at_begline && startpos > 0 && startpos != size1 &&
4039 /* whose stupid idea was it anyway to make this
4040 function take two strings to match?? */
4044 if (startpos < size1 && startpos + range >= size1)
4045 lim = range - (size1 - startpos);
4047 d = ((const unsigned char *)
4048 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4049 DEC_CHARPTR(d); /* Ok, since startpos != size1. */
4050 d_size = charcount_to_bytecount (d, 1);
4052 if (TRANSLATE_P (translate))
4053 while (range > lim && *d != '\n')
4055 d += d_size; /* Speedier INC_CHARPTR(d) */
4056 d_size = charcount_to_bytecount (d, 1);
4060 while (range > lim && *d != '\n')
4062 d += d_size; /* Speedier INC_CHARPTR(d) */
4063 d_size = charcount_to_bytecount (d, 1);
4067 startpos += irange - range;
4069 #endif /* REGEX_BEGLINE_CHECK */
4071 /* If a fastmap is supplied, skip quickly over characters that
4072 cannot be the start of a match. If the pattern can match the
4073 null string, however, we don't need to skip characters; we want
4074 the first null string. */
4075 if (fastmap && startpos < total_size && !bufp->can_be_null)
4077 if (range > 0) /* Searching forwards. */
4082 if (startpos < size1 && startpos + range >= size1)
4083 lim = range - (size1 - startpos);
4085 d = ((const unsigned char *)
4086 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4088 /* Written out as an if-else to avoid testing `translate'
4090 if (TRANSLATE_P (translate))
4096 buf_ch = charptr_emchar (d);
4097 buf_ch = RE_TRANSLATE (buf_ch);
4098 if (buf_ch >= 0200 || fastmap[(unsigned char) buf_ch])
4101 if (fastmap[(unsigned char)RE_TRANSLATE (*d)])
4104 d_size = charcount_to_bytecount (d, 1);
4106 d += d_size; /* Speedier INC_CHARPTR(d) */
4109 while (range > lim && !fastmap[*d])
4111 d_size = charcount_to_bytecount (d, 1);
4113 d += d_size; /* Speedier INC_CHARPTR(d) */
4116 startpos += irange - range;
4118 else /* Searching backwards. */
4120 Emchar c = (size1 == 0 || startpos >= size1
4121 ? charptr_emchar (string2 + startpos - size1)
4122 : charptr_emchar (string1 + startpos));
4125 if (!(c >= 0200 || fastmap[(unsigned char) c]))
4128 if (!fastmap[(unsigned char) c])
4134 /* If can't match the null string, and that's all we have left, fail. */
4135 if (range >= 0 && startpos == total_size && fastmap
4136 && !bufp->can_be_null)
4139 #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
4140 if (!no_quit_in_re_search)
4143 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4144 startpos, regs, stop);
4145 #ifndef REGEX_MALLOC
4162 d = ((const unsigned char *)
4163 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4164 d_size = charcount_to_bytecount (d, 1);
4170 /* Note startpos > size1 not >=. If we are on the
4171 string1/string2 boundary, we want to backup into string1. */
4172 d = ((const unsigned char *)
4173 (startpos > size1 ? string2 - size1 : string1) + startpos);
4175 d_size = charcount_to_bytecount (d, 1);
4183 /* Declarations and macros for re_match_2. */
4185 /* This converts PTR, a pointer into one of the search strings `string1'
4186 and `string2' into an offset from the beginning of that string. */
4187 #define POINTER_TO_OFFSET(ptr) \
4188 (FIRST_STRING_P (ptr) \
4189 ? ((regoff_t) ((ptr) - string1)) \
4190 : ((regoff_t) ((ptr) - string2 + size1)))
4192 /* Macros for dealing with the split strings in re_match_2. */
4194 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
4196 /* Call before fetching a character with *d. This switches over to
4197 string2 if necessary. */
4198 #define REGEX_PREFETCH() \
4201 /* End of string2 => fail. */ \
4202 if (dend == end_match_2) \
4204 /* End of string1 => advance to string2. */ \
4206 dend = end_match_2; \
4210 /* Test if at very beginning or at very end of the virtual concatenation
4211 of `string1' and `string2'. If only one string, it's `string2'. */
4212 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4213 #define AT_STRINGS_END(d) ((d) == end2)
4216 If the given position straddles the string gap, return the equivalent
4217 position that is before or after the gap, respectively; otherwise,
4218 return the same position. */
4219 #define POS_BEFORE_GAP_UNSAFE(d) ((d) == string2 ? end1 : (d))
4220 #define POS_AFTER_GAP_UNSAFE(d) ((d) == end1 ? string2 : (d))
4222 /* Test if CH is a word-constituent character. (XEmacs change) */
4224 #define WORDCHAR_P_UNSAFE(ch) \
4225 (SYNTAX_UNSAFE (XCHAR_TABLE (regex_emacs_buffer->syntax_table), \
4228 #define WORDCHAR_P_UNSAFE(ch) \
4229 (SYNTAX_UNSAFE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table), \
4233 /* Free everything we malloc. */
4234 #ifdef MATCH_MAY_ALLOCATE
4235 #define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
4236 #define FREE_VARIABLES() \
4238 REGEX_FREE_STACK (fail_stack.stack); \
4239 FREE_VAR (regstart); \
4240 FREE_VAR (regend); \
4241 FREE_VAR (old_regstart); \
4242 FREE_VAR (old_regend); \
4243 FREE_VAR (best_regstart); \
4244 FREE_VAR (best_regend); \
4245 FREE_VAR (reg_info); \
4246 FREE_VAR (reg_dummy); \
4247 FREE_VAR (reg_info_dummy); \
4249 #else /* not MATCH_MAY_ALLOCATE */
4250 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4251 #endif /* MATCH_MAY_ALLOCATE */
4253 /* These values must meet several constraints. They must not be valid
4254 register values; since we have a limit of 255 registers (because
4255 we use only one byte in the pattern for the register number), we can
4256 use numbers larger than 255. They must differ by 1, because of
4257 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4258 be larger than the value for the highest register, so we do not try
4259 to actually save any registers when none are active. */
4260 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4261 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4263 /* Matching routines. */
4265 #ifndef emacs /* Emacs never uses this. */
4266 /* re_match is like re_match_2 except it takes only a single string. */
4269 re_match (struct re_pattern_buffer *bufp, const char *string, int size,
4270 int pos, struct re_registers *regs)
4272 int result = re_match_2_internal (bufp, NULL, 0, (re_char *) string, size,
4277 #endif /* not emacs */
4280 /* re_match_2 matches the compiled pattern in BUFP against the
4281 (virtual) concatenation of STRING1 and STRING2 (of length SIZE1 and
4282 SIZE2, respectively). We start matching at POS, and stop matching
4285 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4286 store offsets for the substring each group matched in REGS. See the
4287 documentation for exactly how many groups we fill.
4289 We return -1 if no match, -2 if an internal error (such as the
4290 failure stack overflowing). Otherwise, we return the length of the
4291 matched substring. */
4294 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4295 int size1, const char *string2, int size2, int pos,
4296 struct re_registers *regs, int stop)
4298 int result = re_match_2_internal (bufp, (re_char *) string1, size1,
4299 (re_char *) string2, size2,
4305 /* This is a separate function so that we can force an alloca cleanup
4308 re_match_2_internal (struct re_pattern_buffer *bufp, re_char *string1,
4309 int size1, re_char *string2, int size2, int pos,
4310 struct re_registers *regs, int stop)
4312 /* General temporaries. */
4315 int should_succeed; /* XEmacs change */
4317 /* Just past the end of the corresponding string. */
4318 re_char *end1, *end2;
4320 /* Pointers into string1 and string2, just past the last characters in
4321 each to consider matching. */
4322 re_char *end_match_1, *end_match_2;
4324 /* Where we are in the data, and the end of the current string. */
4327 /* Where we are in the pattern, and the end of the pattern. */
4328 unsigned char *p = bufp->buffer;
4329 REGISTER unsigned char *pend = p + bufp->used;
4331 /* Mark the opcode just after a start_memory, so we can test for an
4332 empty subpattern when we get to the stop_memory. */
4333 re_char *just_past_start_mem = 0;
4335 /* We use this to map every character in the string. */
4336 RE_TRANSLATE_TYPE translate = bufp->translate;
4338 /* Failure point stack. Each place that can handle a failure further
4339 down the line pushes a failure point on this stack. It consists of
4340 restart, regend, and reg_info for all registers corresponding to
4341 the subexpressions we're currently inside, plus the number of such
4342 registers, and, finally, two char *'s. The first char * is where
4343 to resume scanning the pattern; the second one is where to resume
4344 scanning the strings. If the latter is zero, the failure point is
4345 a ``dummy''; if a failure happens and the failure point is a dummy,
4346 it gets discarded and the next one is tried. */
4347 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4348 fail_stack_type fail_stack;
4351 static unsigned failure_id;
4352 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4356 /* This holds the pointer to the failure stack, when
4357 it is allocated relocatably. */
4358 fail_stack_elt_t *failure_stack_ptr;
4361 /* We fill all the registers internally, independent of what we
4362 return, for use in backreferences. The number here includes
4363 an element for register zero. */
4364 unsigned num_regs = bufp->re_nsub + 1;
4366 /* The currently active registers. */
4367 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4368 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4370 /* Information on the contents of registers. These are pointers into
4371 the input strings; they record just what was matched (on this
4372 attempt) by a subexpression part of the pattern, that is, the
4373 regnum-th regstart pointer points to where in the pattern we began
4374 matching and the regnum-th regend points to right after where we
4375 stopped matching the regnum-th subexpression. (The zeroth register
4376 keeps track of what the whole pattern matches.) */
4377 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4378 re_char **regstart, **regend;
4381 /* If a group that's operated upon by a repetition operator fails to
4382 match anything, then the register for its start will need to be
4383 restored because it will have been set to wherever in the string we
4384 are when we last see its open-group operator. Similarly for a
4386 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4387 re_char **old_regstart, **old_regend;
4390 /* The is_active field of reg_info helps us keep track of which (possibly
4391 nested) subexpressions we are currently in. The matched_something
4392 field of reg_info[reg_num] helps us tell whether or not we have
4393 matched any of the pattern so far this time through the reg_num-th
4394 subexpression. These two fields get reset each time through any
4395 loop their register is in. */
4396 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4397 register_info_type *reg_info;
4400 /* The following record the register info as found in the above
4401 variables when we find a match better than any we've seen before.
4402 This happens as we backtrack through the failure points, which in
4403 turn happens only if we have not yet matched the entire string. */
4404 unsigned best_regs_set = false;
4405 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4406 re_char **best_regstart, **best_regend;
4409 /* Logically, this is `best_regend[0]'. But we don't want to have to
4410 allocate space for that if we're not allocating space for anything
4411 else (see below). Also, we never need info about register 0 for
4412 any of the other register vectors, and it seems rather a kludge to
4413 treat `best_regend' differently than the rest. So we keep track of
4414 the end of the best match so far in a separate variable. We
4415 initialize this to NULL so that when we backtrack the first time
4416 and need to test it, it's not garbage. */
4417 re_char *match_end = NULL;
4419 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4420 int set_regs_matched_done = 0;
4422 /* Used when we pop values we don't care about. */
4423 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4424 re_char **reg_dummy;
4425 register_info_type *reg_info_dummy;
4429 /* Counts the total number of registers pushed. */
4430 unsigned num_regs_pushed = 0;
4433 /* 1 if this match ends in the same string (string1 or string2)
4434 as the best previous match. */
4437 /* 1 if this match is the best seen so far. */
4438 boolean best_match_p;
4440 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4444 #ifdef MATCH_MAY_ALLOCATE
4445 /* Do not bother to initialize all the register variables if there are
4446 no groups in the pattern, as it takes a fair amount of time. If
4447 there are groups, we include space for register 0 (the whole
4448 pattern), even though we never use it, since it simplifies the
4449 array indexing. We should fix this. */
4452 regstart = REGEX_TALLOC (num_regs, re_char *);
4453 regend = REGEX_TALLOC (num_regs, re_char *);
4454 old_regstart = REGEX_TALLOC (num_regs, re_char *);
4455 old_regend = REGEX_TALLOC (num_regs, re_char *);
4456 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4457 best_regend = REGEX_TALLOC (num_regs, re_char *);
4458 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4459 reg_dummy = REGEX_TALLOC (num_regs, re_char *);
4460 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4462 if (!(regstart && regend && old_regstart && old_regend && reg_info
4463 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4471 /* We must initialize all our variables to NULL, so that
4472 `FREE_VARIABLES' doesn't try to free them. */
4473 regstart = regend = old_regstart = old_regend = best_regstart
4474 = best_regend = reg_dummy = NULL;
4475 reg_info = reg_info_dummy = (register_info_type *) NULL;
4477 #endif /* MATCH_MAY_ALLOCATE */
4479 /* The starting position is bogus. */
4480 if (pos < 0 || pos > size1 + size2)
4486 /* Initialize subexpression text positions to -1 to mark ones that no
4487 start_memory/stop_memory has been seen for. Also initialize the
4488 register information struct. */
4489 for (mcnt = 1; mcnt < num_regs; mcnt++)
4491 regstart[mcnt] = regend[mcnt]
4492 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4494 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4495 IS_ACTIVE (reg_info[mcnt]) = 0;
4496 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4497 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4499 /* We move `string1' into `string2' if the latter's empty -- but not if
4500 `string1' is null. */
4501 if (size2 == 0 && string1 != NULL)
4508 end1 = string1 + size1;
4509 end2 = string2 + size2;
4511 /* Compute where to stop matching, within the two strings. */
4514 end_match_1 = string1 + stop;
4515 end_match_2 = string2;
4520 end_match_2 = string2 + stop - size1;
4523 /* `p' scans through the pattern as `d' scans through the data.
4524 `dend' is the end of the input string that `d' points within. `d'
4525 is advanced into the following input string whenever necessary, but
4526 this happens before fetching; therefore, at the beginning of the
4527 loop, `d' can be pointing at the end of a string, but it cannot
4529 if (size1 > 0 && pos <= size1)
4536 d = string2 + pos - size1;
4540 DEBUG_PRINT1 ("The compiled pattern is: \n");
4541 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4542 DEBUG_PRINT1 ("The string to match is: `");
4543 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4544 DEBUG_PRINT1 ("'\n");
4546 /* This loops over pattern commands. It exits by returning from the
4547 function if the match is complete, or it drops through if the match
4548 fails at this starting point in the input data. */
4551 DEBUG_PRINT2 ("\n0x%lx: ", (long) p);
4552 #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
4553 if (!no_quit_in_re_search)
4558 { /* End of pattern means we might have succeeded. */
4559 DEBUG_PRINT1 ("end of pattern ... ");
4561 /* If we haven't matched the entire string, and we want the
4562 longest match, try backtracking. */
4563 if (d != end_match_2)
4565 same_str_p = (FIRST_STRING_P (match_end)
4566 == MATCHING_IN_FIRST_STRING);
4568 /* AIX compiler got confused when this was combined
4569 with the previous declaration. */
4571 best_match_p = d > match_end;
4573 best_match_p = !MATCHING_IN_FIRST_STRING;
4575 DEBUG_PRINT1 ("backtracking.\n");
4577 if (!FAIL_STACK_EMPTY ())
4578 { /* More failure points to try. */
4580 /* If exceeds best match so far, save it. */
4581 if (!best_regs_set || best_match_p)
4583 best_regs_set = true;
4586 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4588 for (mcnt = 1; mcnt < num_regs; mcnt++)
4590 best_regstart[mcnt] = regstart[mcnt];
4591 best_regend[mcnt] = regend[mcnt];
4597 /* If no failure points, don't restore garbage. And if
4598 last match is real best match, don't restore second
4600 else if (best_regs_set && !best_match_p)
4603 /* Restore best match. It may happen that `dend ==
4604 end_match_1' while the restored d is in string2.
4605 For example, the pattern `x.*y.*z' against the
4606 strings `x-' and `y-z-', if the two strings are
4607 not consecutive in memory. */
4608 DEBUG_PRINT1 ("Restoring best registers.\n");
4611 dend = ((d >= string1 && d <= end1)
4612 ? end_match_1 : end_match_2);
4614 for (mcnt = 1; mcnt < num_regs; mcnt++)
4616 regstart[mcnt] = best_regstart[mcnt];
4617 regend[mcnt] = best_regend[mcnt];
4620 } /* d != end_match_2 */
4623 DEBUG_PRINT1 ("Accepting match.\n");
4625 /* If caller wants register contents data back, do it. */
4626 if (regs && !bufp->no_sub)
4628 /* Have the register data arrays been allocated? */
4629 if (bufp->regs_allocated == REGS_UNALLOCATED)
4630 { /* No. So allocate them with malloc. We need one
4631 extra element beyond `num_regs' for the `-1' marker
4633 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4634 regs->start = TALLOC (regs->num_regs, regoff_t);
4635 regs->end = TALLOC (regs->num_regs, regoff_t);
4636 if (regs->start == NULL || regs->end == NULL)
4641 bufp->regs_allocated = REGS_REALLOCATE;
4643 else if (bufp->regs_allocated == REGS_REALLOCATE)
4644 { /* Yes. If we need more elements than were already
4645 allocated, reallocate them. If we need fewer, just
4647 if (regs->num_regs < num_regs + 1)
4649 regs->num_regs = num_regs + 1;
4650 RETALLOC (regs->start, regs->num_regs, regoff_t);
4651 RETALLOC (regs->end, regs->num_regs, regoff_t);
4652 if (regs->start == NULL || regs->end == NULL)
4661 /* These braces fend off a "empty body in an else-statement"
4662 warning under GCC when assert expands to nothing. */
4663 assert (bufp->regs_allocated == REGS_FIXED);
4666 /* Convert the pointer data in `regstart' and `regend' to
4667 indices. Register zero has to be set differently,
4668 since we haven't kept track of any info for it. */
4669 if (regs->num_regs > 0)
4671 regs->start[0] = pos;
4672 regs->end[0] = (MATCHING_IN_FIRST_STRING
4673 ? ((regoff_t) (d - string1))
4674 : ((regoff_t) (d - string2 + size1)));
4677 /* Go through the first `min (num_regs, regs->num_regs)'
4678 registers, since that is all we initialized. */
4679 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4681 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4682 regs->start[mcnt] = regs->end[mcnt] = -1;
4686 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4688 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4692 /* If the regs structure we return has more elements than
4693 were in the pattern, set the extra elements to -1. If
4694 we (re)allocated the registers, this is the case,
4695 because we always allocate enough to have at least one
4697 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4698 regs->start[mcnt] = regs->end[mcnt] = -1;
4699 } /* regs && !bufp->no_sub */
4701 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4702 nfailure_points_pushed, nfailure_points_popped,
4703 nfailure_points_pushed - nfailure_points_popped);
4704 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4706 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4710 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4716 /* Otherwise match next pattern command. */
4717 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4719 /* Ignore these. Used to ignore the n of succeed_n's which
4720 currently have n == 0. */
4722 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4726 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4729 /* Match the next n pattern characters exactly. The following
4730 byte in the pattern defines n, and the n bytes after that
4731 are the characters to match. */
4734 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4736 /* This is written out as an if-else so we don't waste time
4737 testing `translate' inside the loop. */
4738 if (TRANSLATE_P (translate))
4743 Emchar pat_ch, buf_ch;
4747 pat_ch = charptr_emchar (p);
4748 buf_ch = charptr_emchar (d);
4749 if (RE_TRANSLATE (buf_ch) != pat_ch)
4752 pat_len = charcount_to_bytecount (p, 1);
4757 #else /* not MULE */
4759 if ((unsigned char) RE_TRANSLATE (*d++) != *p++)
4771 if (*d++ != *p++) goto fail;
4775 SET_REGS_MATCHED ();
4779 /* Match any character except possibly a newline or a null. */
4781 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4785 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4786 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4789 SET_REGS_MATCHED ();
4790 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4791 INC_CHARPTR (d); /* XEmacs change */
4798 REGISTER unsigned char c;
4799 boolean not_p = (re_opcode_t) *(p - 1) == charset_not;
4801 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not_p ? "_not" : "");
4804 c = TRANSLATE (*d); /* The character to match. */
4806 /* Cast to `unsigned' instead of `unsigned char' in case the
4807 bit list is a full 32 bytes long. */
4808 if (c < (unsigned) (*p * BYTEWIDTH)
4809 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4814 if (!not_p) goto fail;
4816 SET_REGS_MATCHED ();
4817 INC_CHARPTR (d); /* XEmacs change */
4823 case charset_mule_not:
4826 boolean not_p = (re_opcode_t) *(p - 1) == charset_mule_not;
4828 DEBUG_PRINT2 ("EXECUTING charset_mule%s.\n", not_p ? "_not" : "");
4831 c = charptr_emchar ((const Bufbyte *) d);
4832 c = TRANSLATE_EXTENDED_UNSAFE (c); /* The character to match. */
4834 if (EQ (Qt, unified_range_table_lookup (p, c, Qnil)))
4837 p += unified_range_table_bytes_used (p);
4839 if (!not_p) goto fail;
4841 SET_REGS_MATCHED ();
4848 /* The beginning of a group is represented by start_memory.
4849 The arguments are the register number in the next byte, and the
4850 number of groups inner to this one in the next. The text
4851 matched within the group is recorded (in the internal
4852 registers data structure) under the register number. */
4854 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4856 /* Find out if this group can match the empty string. */
4857 p1 = p; /* To send to group_match_null_string_p. */
4859 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4860 REG_MATCH_NULL_STRING_P (reg_info[*p])
4861 = group_match_null_string_p (&p1, pend, reg_info);
4863 /* Save the position in the string where we were the last time
4864 we were at this open-group operator in case the group is
4865 operated upon by a repetition operator, e.g., with `(a*)*b'
4866 against `ab'; then we want to ignore where we are now in
4867 the string in case this attempt to match fails. */
4868 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4869 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4871 DEBUG_PRINT2 (" old_regstart: %d\n",
4872 POINTER_TO_OFFSET (old_regstart[*p]));
4875 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4877 IS_ACTIVE (reg_info[*p]) = 1;
4878 MATCHED_SOMETHING (reg_info[*p]) = 0;
4880 /* Clear this whenever we change the register activity status. */
4881 set_regs_matched_done = 0;
4883 /* This is the new highest active register. */
4884 highest_active_reg = *p;
4886 /* If nothing was active before, this is the new lowest active
4888 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4889 lowest_active_reg = *p;
4891 /* Move past the register number and inner group count. */
4893 just_past_start_mem = p;
4898 /* The stop_memory opcode represents the end of a group. Its
4899 arguments are the same as start_memory's: the register
4900 number, and the number of inner groups. */
4902 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4904 /* We need to save the string position the last time we were at
4905 this close-group operator in case the group is operated
4906 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4907 against `aba'; then we want to ignore where we are now in
4908 the string in case this attempt to match fails. */
4909 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4910 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4912 DEBUG_PRINT2 (" old_regend: %d\n",
4913 POINTER_TO_OFFSET (old_regend[*p]));
4916 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4918 /* This register isn't active anymore. */
4919 IS_ACTIVE (reg_info[*p]) = 0;
4921 /* Clear this whenever we change the register activity status. */
4922 set_regs_matched_done = 0;
4924 /* If this was the only register active, nothing is active
4926 if (lowest_active_reg == highest_active_reg)
4928 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4929 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4932 { /* We must scan for the new highest active register, since
4933 it isn't necessarily one less than now: consider
4934 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4935 new highest active register is 1. */
4936 unsigned char r = *p - 1;
4937 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4940 /* If we end up at register zero, that means that we saved
4941 the registers as the result of an `on_failure_jump', not
4942 a `start_memory', and we jumped to past the innermost
4943 `stop_memory'. For example, in ((.)*) we save
4944 registers 1 and 2 as a result of the *, but when we pop
4945 back to the second ), we are at the stop_memory 1.
4946 Thus, nothing is active. */
4949 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4950 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4954 highest_active_reg = r;
4956 /* 98/9/21 jhod: We've also gotta set lowest_active_reg, don't we? */
4958 while (r < highest_active_reg && !IS_ACTIVE(reg_info[r]))
4960 lowest_active_reg = r;
4964 /* If just failed to match something this time around with a
4965 group that's operated on by a repetition operator, try to
4966 force exit from the ``loop'', and restore the register
4967 information for this group that we had before trying this
4969 if ((!MATCHED_SOMETHING (reg_info[*p])
4970 || just_past_start_mem == p - 1)
4973 boolean is_a_jump_n = false;
4977 switch ((re_opcode_t) *p1++)
4981 case pop_failure_jump:
4982 case maybe_pop_jump:
4984 case dummy_failure_jump:
4985 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4995 /* If the next operation is a jump backwards in the pattern
4996 to an on_failure_jump right before the start_memory
4997 corresponding to this stop_memory, exit from the loop
4998 by forcing a failure after pushing on the stack the
4999 on_failure_jump's jump in the pattern, and d. */
5000 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
5001 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
5003 /* If this group ever matched anything, then restore
5004 what its registers were before trying this last
5005 failed match, e.g., with `(a*)*b' against `ab' for
5006 regstart[1], and, e.g., with `((a*)*(b*)*)*'
5007 against `aba' for regend[3].
5009 Also restore the registers for inner groups for,
5010 e.g., `((a*)(b*))*' against `aba' (register 3 would
5011 otherwise get trashed). */
5013 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
5017 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
5019 /* Restore this and inner groups' (if any) registers. */
5020 for (r = *p; r < *p + *(p + 1); r++)
5022 regstart[r] = old_regstart[r];
5024 /* xx why this test? */
5025 if (old_regend[r] >= regstart[r])
5026 regend[r] = old_regend[r];
5030 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5031 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
5037 /* Move past the register number and the inner group count. */
5042 /* \<digit> has been turned into a `duplicate' command which is
5043 followed by the numeric value of <digit> as the register number. */
5046 REGISTER re_char *d2, *dend2;
5047 int regno = *p++; /* Get which register to match against. */
5048 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5050 /* Can't back reference a group which we've never matched. */
5051 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5054 /* Where in input to try to start matching. */
5055 d2 = regstart[regno];
5057 /* Where to stop matching; if both the place to start and
5058 the place to stop matching are in the same string, then
5059 set to the place to stop, otherwise, for now have to use
5060 the end of the first string. */
5062 dend2 = ((FIRST_STRING_P (regstart[regno])
5063 == FIRST_STRING_P (regend[regno]))
5064 ? regend[regno] : end_match_1);
5067 /* If necessary, advance to next segment in register
5071 if (dend2 == end_match_2) break;
5072 if (dend2 == regend[regno]) break;
5074 /* End of string1 => advance to string2. */
5076 dend2 = regend[regno];
5078 /* At end of register contents => success */
5079 if (d2 == dend2) break;
5081 /* If necessary, advance to next segment in data. */
5084 /* How many characters left in this segment to match. */
5087 /* Want how many consecutive characters we can match in
5088 one shot, so, if necessary, adjust the count. */
5089 if (mcnt > dend2 - d2)
5092 /* Compare that many; failure if mismatch, else move
5094 if (TRANSLATE_P (translate)
5095 ? bcmp_translate ((unsigned char *) d,
5096 (unsigned char *) d2, mcnt, translate)
5097 : memcmp (d, d2, mcnt))
5099 d += mcnt, d2 += mcnt;
5101 /* Do this because we've match some characters. */
5102 SET_REGS_MATCHED ();
5108 /* begline matches the empty string at the beginning of the string
5109 (unless `not_bol' is set in `bufp'), and, if
5110 `newline_anchor' is set, after newlines. */
5112 DEBUG_PRINT1 ("EXECUTING begline.\n");
5114 if (AT_STRINGS_BEG (d))
5116 if (!bufp->not_bol) break;
5118 else if (d[-1] == '\n' && bufp->newline_anchor)
5122 /* In all other cases, we fail. */
5126 /* endline is the dual of begline. */
5128 DEBUG_PRINT1 ("EXECUTING endline.\n");
5130 if (AT_STRINGS_END (d))
5132 if (!bufp->not_eol) break;
5135 /* We have to ``prefetch'' the next character. */
5136 else if ((d == end1 ? *string2 : *d) == '\n'
5137 && bufp->newline_anchor)
5144 /* Match at the very beginning of the data. */
5146 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5147 if (AT_STRINGS_BEG (d))
5152 /* Match at the very end of the data. */
5154 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5155 if (AT_STRINGS_END (d))
5160 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5161 pushes NULL as the value for the string on the stack. Then
5162 `pop_failure_point' will keep the current value for the
5163 string, instead of restoring it. To see why, consider
5164 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5165 then the . fails against the \n. But the next thing we want
5166 to do is match the \n against the \n; if we restored the
5167 string value, we would be back at the foo.
5169 Because this is used only in specific cases, we don't need to
5170 check all the things that `on_failure_jump' does, to make
5171 sure the right things get saved on the stack. Hence we don't
5172 share its code. The only reason to push anything on the
5173 stack at all is that otherwise we would have to change
5174 `anychar's code to do something besides goto fail in this
5175 case; that seems worse than this. */
5176 case on_failure_keep_string_jump:
5177 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
5179 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5180 DEBUG_PRINT3 (" %d (to 0x%lx):\n", mcnt, (long) (p + mcnt));
5182 PUSH_FAILURE_POINT (p + mcnt, (unsigned char *) 0, -2);
5186 /* Uses of on_failure_jump:
5188 Each alternative starts with an on_failure_jump that points
5189 to the beginning of the next alternative. Each alternative
5190 except the last ends with a jump that in effect jumps past
5191 the rest of the alternatives. (They really jump to the
5192 ending jump of the following alternative, because tensioning
5193 these jumps is a hassle.)
5195 Repeats start with an on_failure_jump that points past both
5196 the repetition text and either the following jump or
5197 pop_failure_jump back to this on_failure_jump. */
5198 case on_failure_jump:
5200 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
5202 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5203 DEBUG_PRINT3 (" %d (to 0x%lx)", mcnt, (long) (p + mcnt));
5205 /* If this on_failure_jump comes right before a group (i.e.,
5206 the original * applied to a group), save the information
5207 for that group and all inner ones, so that if we fail back
5208 to this point, the group's information will be correct.
5209 For example, in \(a*\)*\1, we need the preceding group,
5210 and in \(\(a*\)b*\)\2, we need the inner group. */
5212 /* We can't use `p' to check ahead because we push
5213 a failure point to `p + mcnt' after we do this. */
5216 /* We need to skip no_op's before we look for the
5217 start_memory in case this on_failure_jump is happening as
5218 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5220 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5223 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5225 /* We have a new highest active register now. This will
5226 get reset at the start_memory we are about to get to,
5227 but we will have saved all the registers relevant to
5228 this repetition op, as described above. */
5229 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5230 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5231 lowest_active_reg = *(p1 + 1);
5234 DEBUG_PRINT1 (":\n");
5235 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5239 /* A smart repeat ends with `maybe_pop_jump'.
5240 We change it to either `pop_failure_jump' or `jump'. */
5241 case maybe_pop_jump:
5242 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5243 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5245 REGISTER unsigned char *p2 = p;
5247 /* Compare the beginning of the repeat with what in the
5248 pattern follows its end. If we can establish that there
5249 is nothing that they would both match, i.e., that we
5250 would have to backtrack because of (as in, e.g., `a*a')
5251 then we can change to pop_failure_jump, because we'll
5252 never have to backtrack.
5254 This is not true in the case of alternatives: in
5255 `(a|ab)*' we do need to backtrack to the `ab' alternative
5256 (e.g., if the string was `ab'). But instead of trying to
5257 detect that here, the alternative has put on a dummy
5258 failure point which is what we will end up popping. */
5260 /* Skip over open/close-group commands.
5261 If what follows this loop is a ...+ construct,
5262 look at what begins its body, since we will have to
5263 match at least one of that. */
5267 && ((re_opcode_t) *p2 == stop_memory
5268 || (re_opcode_t) *p2 == start_memory))
5270 else if (p2 + 6 < pend
5271 && (re_opcode_t) *p2 == dummy_failure_jump)
5278 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5279 to the `maybe_finalize_jump' of this case. Examine what
5282 /* If we're at the end of the pattern, we can change. */
5285 /* Consider what happens when matching ":\(.*\)"
5286 against ":/". I don't really understand this code
5288 p[-3] = (unsigned char) pop_failure_jump;
5290 (" End of pattern: change to `pop_failure_jump'.\n");
5293 else if ((re_opcode_t) *p2 == exactn
5294 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5296 REGISTER unsigned char c
5297 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5299 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
5301 p[-3] = (unsigned char) pop_failure_jump;
5302 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5306 else if ((re_opcode_t) p1[3] == charset
5307 || (re_opcode_t) p1[3] == charset_not)
5309 int not_p = (re_opcode_t) p1[3] == charset_not;
5311 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
5312 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5315 /* `not_p' is equal to 1 if c would match, which means
5316 that we can't change to pop_failure_jump. */
5319 p[-3] = (unsigned char) pop_failure_jump;
5320 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5324 else if ((re_opcode_t) *p2 == charset)
5327 REGISTER unsigned char c
5328 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5331 if ((re_opcode_t) p1[3] == exactn
5332 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
5333 && (p2[2 + p1[5] / BYTEWIDTH]
5334 & (1 << (p1[5] % BYTEWIDTH)))))
5336 p[-3] = (unsigned char) pop_failure_jump;
5337 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5341 else if ((re_opcode_t) p1[3] == charset_not)
5344 /* We win if the charset_not inside the loop
5345 lists every character listed in the charset after. */
5346 for (idx = 0; idx < (int) p2[1]; idx++)
5347 if (! (p2[2 + idx] == 0
5348 || (idx < (int) p1[4]
5349 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5354 p[-3] = (unsigned char) pop_failure_jump;
5355 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5358 else if ((re_opcode_t) p1[3] == charset)
5361 /* We win if the charset inside the loop
5362 has no overlap with the one after the loop. */
5364 idx < (int) p2[1] && idx < (int) p1[4];
5366 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5369 if (idx == p2[1] || idx == p1[4])
5371 p[-3] = (unsigned char) pop_failure_jump;
5372 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5377 p -= 2; /* Point at relative address again. */
5378 if ((re_opcode_t) p[-1] != pop_failure_jump)
5380 p[-1] = (unsigned char) jump;
5381 DEBUG_PRINT1 (" Match => jump.\n");
5382 goto unconditional_jump;
5384 /* Note fall through. */
5387 /* The end of a simple repeat has a pop_failure_jump back to
5388 its matching on_failure_jump, where the latter will push a
5389 failure point. The pop_failure_jump takes off failure
5390 points put on by this pop_failure_jump's matching
5391 on_failure_jump; we got through the pattern to here from the
5392 matching on_failure_jump, so didn't fail. */
5393 case pop_failure_jump:
5395 /* We need to pass separate storage for the lowest and
5396 highest registers, even though we don't care about the
5397 actual values. Otherwise, we will restore only one
5398 register from the stack, since lowest will == highest in
5399 `pop_failure_point'. */
5400 unsigned dummy_low_reg, dummy_high_reg;
5401 unsigned char *pdummy;
5402 re_char *sdummy = NULL;
5404 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5405 POP_FAILURE_POINT (sdummy, pdummy,
5406 dummy_low_reg, dummy_high_reg,
5407 reg_dummy, reg_dummy, reg_info_dummy);
5409 /* Note fall through. */
5412 /* Unconditionally jump (without popping any failure points). */
5415 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5416 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5417 p += mcnt; /* Do the jump. */
5418 DEBUG_PRINT2 ("(to 0x%lx).\n", (long) p);
5422 /* We need this opcode so we can detect where alternatives end
5423 in `group_match_null_string_p' et al. */
5425 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5426 goto unconditional_jump;
5429 /* Normally, the on_failure_jump pushes a failure point, which
5430 then gets popped at pop_failure_jump. We will end up at
5431 pop_failure_jump, also, and with a pattern of, say, `a+', we
5432 are skipping over the on_failure_jump, so we have to push
5433 something meaningless for pop_failure_jump to pop. */
5434 case dummy_failure_jump:
5435 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5436 /* It doesn't matter what we push for the string here. What
5437 the code at `fail' tests is the value for the pattern. */
5438 PUSH_FAILURE_POINT ((unsigned char *) 0, (unsigned char *) 0, -2);
5439 goto unconditional_jump;
5442 /* At the end of an alternative, we need to push a dummy failure
5443 point in case we are followed by a `pop_failure_jump', because
5444 we don't want the failure point for the alternative to be
5445 popped. For example, matching `(a|ab)*' against `aab'
5446 requires that we match the `ab' alternative. */
5447 case push_dummy_failure:
5448 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5449 /* See comments just above at `dummy_failure_jump' about the
5451 PUSH_FAILURE_POINT ((unsigned char *) 0, (unsigned char *) 0, -2);
5454 /* Have to succeed matching what follows at least n times.
5455 After that, handle like `on_failure_jump'. */
5457 EXTRACT_NUMBER (mcnt, p + 2);
5458 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5461 /* Originally, this is how many times we HAVE to succeed. */
5466 STORE_NUMBER_AND_INCR (p, mcnt);
5467 DEBUG_PRINT3 (" Setting 0x%lx to %d.\n", (long) p, mcnt);
5471 DEBUG_PRINT2 (" Setting two bytes from 0x%lx to no_op.\n",
5473 p[2] = (unsigned char) no_op;
5474 p[3] = (unsigned char) no_op;
5480 EXTRACT_NUMBER (mcnt, p + 2);
5481 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5483 /* Originally, this is how many times we CAN jump. */
5487 STORE_NUMBER (p + 2, mcnt);
5488 goto unconditional_jump;
5490 /* If don't have to jump any more, skip over the rest of command. */
5497 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5499 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5501 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5502 DEBUG_PRINT3 (" Setting 0x%lx to %d.\n", (long) p1, mcnt);
5503 STORE_NUMBER (p1, mcnt);
5508 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5514 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5518 const unsigned char *d_before =
5519 (const unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5520 const unsigned char *d_after =
5521 (const unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5522 Emchar emch1, emch2;
5524 DEC_CHARPTR (d_before);
5525 emch1 = charptr_emchar (d_before);
5526 emch2 = charptr_emchar (d_after);
5527 result = (WORDCHAR_P_UNSAFE (emch1) !=
5528 WORDCHAR_P_UNSAFE (emch2));
5530 if (result == should_succeed)
5536 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5538 goto matchwordbound;
5541 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5543 /* XEmacs: this originally read:
5545 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
5549 const unsigned char *dtmp =
5550 (const unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5551 Emchar emch = charptr_emchar (dtmp);
5552 if (!WORDCHAR_P_UNSAFE (emch))
5554 if (AT_STRINGS_BEG (d))
5556 dtmp = (const unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5558 emch = charptr_emchar (dtmp);
5559 if (!WORDCHAR_P_UNSAFE (emch))
5565 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5567 /* XEmacs: this originally read:
5569 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
5570 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
5573 The or condition is incorrect (reversed).
5575 const unsigned char *dtmp;
5577 if (AT_STRINGS_BEG (d))
5579 dtmp = (const unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5581 emch = charptr_emchar (dtmp);
5582 if (!WORDCHAR_P_UNSAFE (emch))
5584 if (AT_STRINGS_END (d))
5586 dtmp = (const unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5587 emch = charptr_emchar (dtmp);
5588 if (!WORDCHAR_P_UNSAFE (emch))
5595 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5596 if (!regex_emacs_buffer_p
5597 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5598 >= BUF_PT (regex_emacs_buffer)))
5603 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5604 if (!regex_emacs_buffer_p
5605 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5606 != BUF_PT (regex_emacs_buffer)))
5611 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5612 if (!regex_emacs_buffer_p
5613 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5614 <= BUF_PT (regex_emacs_buffer)))
5617 #if 0 /* not emacs19 */
5619 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5620 if (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d) + 1
5621 != BUF_PT (regex_emacs_buffer))
5624 #endif /* not emacs19 */
5627 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5632 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5642 emch = charptr_emchar ((const Bufbyte *) d);
5644 matches = (SYNTAX_UNSAFE
5645 (XCHAR_TABLE (regex_emacs_buffer->syntax_table),
5646 emch) == (enum syntaxcode) mcnt);
5648 matches = (SYNTAX_UNSAFE
5649 (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5650 emch) == (enum syntaxcode) mcnt);
5653 if (matches != should_succeed)
5655 SET_REGS_MATCHED ();
5660 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5662 goto matchnotsyntax;
5665 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5669 goto matchornotsyntax;
5672 /* 97/2/17 jhod Mule category code patch */
5681 emch = charptr_emchar ((const Bufbyte *) d);
5683 if (check_category_char(emch, regex_emacs_buffer->category_table,
5684 mcnt, should_succeed))
5686 SET_REGS_MATCHED ();
5690 case notcategoryspec:
5692 goto matchornotcategory;
5693 /* end of category patch */
5695 #else /* not emacs */
5697 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5699 if (!WORDCHAR_P_UNSAFE ((int) (*d)))
5701 SET_REGS_MATCHED ();
5706 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5708 if (!WORDCHAR_P_UNSAFE ((int) (*d)))
5710 SET_REGS_MATCHED ();
5718 continue; /* Successfully executed one pattern command; keep going. */
5721 /* We goto here if a matching operation fails. */
5723 if (!FAIL_STACK_EMPTY ())
5724 { /* A restart point is known. Restore to that state. */
5725 DEBUG_PRINT1 ("\nFAIL:\n");
5726 POP_FAILURE_POINT (d, p,
5727 lowest_active_reg, highest_active_reg,
5728 regstart, regend, reg_info);
5730 /* If this failure point is a dummy, try the next one. */
5734 /* If we failed to the end of the pattern, don't examine *p. */
5738 boolean is_a_jump_n = false;
5740 /* If failed to a backwards jump that's part of a repetition
5741 loop, need to pop this failure point and use the next one. */
5742 switch ((re_opcode_t) *p)
5746 case maybe_pop_jump:
5747 case pop_failure_jump:
5750 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5753 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5755 && (re_opcode_t) *p1 == on_failure_jump))
5763 if (d >= string1 && d <= end1)
5767 break; /* Matching at this starting point really fails. */
5771 goto restore_best_regs;
5775 return -1; /* Failure to match. */
5778 /* Subroutine definitions for re_match_2. */
5781 /* We are passed P pointing to a register number after a start_memory.
5783 Return true if the pattern up to the corresponding stop_memory can
5784 match the empty string, and false otherwise.
5786 If we find the matching stop_memory, sets P to point to one past its number.
5787 Otherwise, sets P to an undefined byte less than or equal to END.
5789 We don't handle duplicates properly (yet). */
5792 group_match_null_string_p (unsigned char **p, unsigned char *end,
5793 register_info_type *reg_info)
5796 /* Point to after the args to the start_memory. */
5797 unsigned char *p1 = *p + 2;
5801 /* Skip over opcodes that can match nothing, and return true or
5802 false, as appropriate, when we get to one that can't, or to the
5803 matching stop_memory. */
5805 switch ((re_opcode_t) *p1)
5807 /* Could be either a loop or a series of alternatives. */
5808 case on_failure_jump:
5810 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5812 /* If the next operation is not a jump backwards in the
5817 /* Go through the on_failure_jumps of the alternatives,
5818 seeing if any of the alternatives cannot match nothing.
5819 The last alternative starts with only a jump,
5820 whereas the rest start with on_failure_jump and end
5821 with a jump, e.g., here is the pattern for `a|b|c':
5823 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5824 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5827 So, we have to first go through the first (n-1)
5828 alternatives and then deal with the last one separately. */
5831 /* Deal with the first (n-1) alternatives, which start
5832 with an on_failure_jump (see above) that jumps to right
5833 past a jump_past_alt. */
5835 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5837 /* `mcnt' holds how many bytes long the alternative
5838 is, including the ending `jump_past_alt' and
5841 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5845 /* Move to right after this alternative, including the
5849 /* Break if it's the beginning of an n-th alternative
5850 that doesn't begin with an on_failure_jump. */
5851 if ((re_opcode_t) *p1 != on_failure_jump)
5854 /* Still have to check that it's not an n-th
5855 alternative that starts with an on_failure_jump. */
5857 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5858 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5860 /* Get to the beginning of the n-th alternative. */
5866 /* Deal with the last alternative: go back and get number
5867 of the `jump_past_alt' just before it. `mcnt' contains
5868 the length of the alternative. */
5869 EXTRACT_NUMBER (mcnt, p1 - 2);
5871 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5874 p1 += mcnt; /* Get past the n-th alternative. */
5880 assert (p1[1] == **p);
5886 if (!common_op_match_null_string_p (&p1, end, reg_info))
5889 } /* while p1 < end */
5892 } /* group_match_null_string_p */
5895 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5896 It expects P to be the first byte of a single alternative and END one
5897 byte past the last. The alternative can contain groups. */
5900 alt_match_null_string_p (unsigned char *p, unsigned char *end,
5901 register_info_type *reg_info)
5904 unsigned char *p1 = p;
5908 /* Skip over opcodes that can match nothing, and break when we get
5909 to one that can't. */
5911 switch ((re_opcode_t) *p1)
5914 case on_failure_jump:
5916 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5921 if (!common_op_match_null_string_p (&p1, end, reg_info))
5924 } /* while p1 < end */
5927 } /* alt_match_null_string_p */
5930 /* Deals with the ops common to group_match_null_string_p and
5931 alt_match_null_string_p.
5933 Sets P to one after the op and its arguments, if any. */
5936 common_op_match_null_string_p (unsigned char **p, unsigned char *end,
5937 register_info_type *reg_info)
5942 unsigned char *p1 = *p;
5944 switch ((re_opcode_t) *p1++)
5964 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5965 ret = group_match_null_string_p (&p1, end, reg_info);
5967 /* Have to set this here in case we're checking a group which
5968 contains a group and a back reference to it. */
5970 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5971 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5977 /* If this is an optimized succeed_n for zero times, make the jump. */
5979 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5987 /* Get to the number of times to succeed. */
5989 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5994 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6002 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
6010 /* All other opcodes mean we cannot match the empty string. */
6016 } /* common_op_match_null_string_p */
6019 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6020 bytes; nonzero otherwise. */
6023 bcmp_translate (re_char *s1, re_char *s2,
6024 REGISTER int len, RE_TRANSLATE_TYPE translate)
6026 REGISTER const unsigned char *p1 = s1, *p2 = s2;
6028 const unsigned char *p1_end = s1 + len;
6029 const unsigned char *p2_end = s2 + len;
6031 while (p1 != p1_end && p2 != p2_end)
6033 Emchar p1_ch, p2_ch;
6035 p1_ch = charptr_emchar (p1);
6036 p2_ch = charptr_emchar (p2);
6038 if (RE_TRANSLATE (p1_ch)
6039 != RE_TRANSLATE (p2_ch))
6044 #else /* not MULE */
6047 if (RE_TRANSLATE (*p1++) != RE_TRANSLATE (*p2++)) return 1;
6054 /* Entry points for GNU code. */
6056 /* re_compile_pattern is the GNU regular expression compiler: it
6057 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6058 Returns 0 if the pattern was valid, otherwise an error string.
6060 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6061 are set in BUFP on entry.
6063 We call regex_compile to do the actual compilation. */
6066 re_compile_pattern (const char *pattern, int length,
6067 struct re_pattern_buffer *bufp)
6071 /* GNU code is written to assume at least RE_NREGS registers will be set
6072 (and at least one extra will be -1). */
6073 bufp->regs_allocated = REGS_UNALLOCATED;
6075 /* And GNU code determines whether or not to get register information
6076 by passing null for the REGS argument to re_match, etc., not by
6080 /* Match anchors at newline. */
6081 bufp->newline_anchor = 1;
6083 ret = regex_compile ((unsigned char *) pattern, length, re_syntax_options, bufp);
6087 return gettext (re_error_msgid[(int) ret]);
6090 /* Entry points compatible with 4.2 BSD regex library. We don't define
6091 them unless specifically requested. */
6093 #ifdef _REGEX_RE_COMP
6095 /* BSD has one and only one pattern buffer. */
6096 static struct re_pattern_buffer re_comp_buf;
6099 re_comp (const char *s)
6105 if (!re_comp_buf.buffer)
6106 return gettext ("No previous regular expression");
6110 if (!re_comp_buf.buffer)
6112 re_comp_buf.buffer = (unsigned char *) malloc (200);
6113 if (re_comp_buf.buffer == NULL)
6114 return gettext (re_error_msgid[(int) REG_ESPACE]);
6115 re_comp_buf.allocated = 200;
6117 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6118 if (re_comp_buf.fastmap == NULL)
6119 return gettext (re_error_msgid[(int) REG_ESPACE]);
6122 /* Since `re_exec' always passes NULL for the `regs' argument, we
6123 don't need to initialize the pattern buffer fields which affect it. */
6125 /* Match anchors at newlines. */
6126 re_comp_buf.newline_anchor = 1;
6128 ret = regex_compile ((unsigned char *)s, strlen (s), re_syntax_options, &re_comp_buf);
6133 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6134 return (char *) gettext (re_error_msgid[(int) ret]);
6139 re_exec (const char *s)
6141 const int len = strlen (s);
6143 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6145 #endif /* _REGEX_RE_COMP */
6147 /* POSIX.2 functions. Don't define these for Emacs. */
6151 /* regcomp takes a regular expression as a string and compiles it.
6153 PREG is a regex_t *. We do not expect any fields to be initialized,
6154 since POSIX says we shouldn't. Thus, we set
6156 `buffer' to the compiled pattern;
6157 `used' to the length of the compiled pattern;
6158 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6159 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6160 RE_SYNTAX_POSIX_BASIC;
6161 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6162 `fastmap' and `fastmap_accurate' to zero;
6163 `re_nsub' to the number of subexpressions in PATTERN.
6165 PATTERN is the address of the pattern string.
6167 CFLAGS is a series of bits which affect compilation.
6169 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6170 use POSIX basic syntax.
6172 If REG_NEWLINE is set, then . and [^...] don't match newline.
6173 Also, regexec will try a match beginning after every newline.
6175 If REG_ICASE is set, then we considers upper- and lowercase
6176 versions of letters to be equivalent when matching.
6178 If REG_NOSUB is set, then when PREG is passed to regexec, that
6179 routine will report only success or failure, and nothing about the
6182 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6183 the return codes and their meanings.) */
6186 regcomp (regex_t *preg, const char *pattern, int cflags)
6190 = (cflags & REG_EXTENDED) ?
6191 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6193 /* regex_compile will allocate the space for the compiled pattern. */
6195 preg->allocated = 0;
6198 /* Don't bother to use a fastmap when searching. This simplifies the
6199 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6200 characters after newlines into the fastmap. This way, we just try
6204 if (cflags & REG_ICASE)
6208 preg->translate = (char *) malloc (CHAR_SET_SIZE);
6209 if (preg->translate == NULL)
6210 return (int) REG_ESPACE;
6212 /* Map uppercase characters to corresponding lowercase ones. */
6213 for (i = 0; i < CHAR_SET_SIZE; i++)
6214 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6217 preg->translate = NULL;
6219 /* If REG_NEWLINE is set, newlines are treated differently. */
6220 if (cflags & REG_NEWLINE)
6221 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6222 syntax &= ~RE_DOT_NEWLINE;
6223 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6224 /* It also changes the matching behavior. */
6225 preg->newline_anchor = 1;
6228 preg->newline_anchor = 0;
6230 preg->no_sub = !!(cflags & REG_NOSUB);
6232 /* POSIX says a null character in the pattern terminates it, so we
6233 can use strlen here in compiling the pattern. */
6234 ret = regex_compile ((unsigned char *) pattern, strlen (pattern), syntax, preg);
6236 /* POSIX doesn't distinguish between an unmatched open-group and an
6237 unmatched close-group: both are REG_EPAREN. */
6238 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6244 /* regexec searches for a given pattern, specified by PREG, in the
6247 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6248 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6249 least NMATCH elements, and we set them to the offsets of the
6250 corresponding matched substrings.
6252 EFLAGS specifies `execution flags' which affect matching: if
6253 REG_NOTBOL is set, then ^ does not match at the beginning of the
6254 string; if REG_NOTEOL is set, then $ does not match at the end.
6256 We return 0 if we find a match and REG_NOMATCH if not. */
6259 regexec (const regex_t *preg, const char *string, size_t nmatch,
6260 regmatch_t pmatch[], int eflags)
6263 struct re_registers regs;
6264 regex_t private_preg;
6265 int len = strlen (string);
6266 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6268 private_preg = *preg;
6270 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6271 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6273 /* The user has told us exactly how many registers to return
6274 information about, via `nmatch'. We have to pass that on to the
6275 matching routines. */
6276 private_preg.regs_allocated = REGS_FIXED;
6280 regs.num_regs = nmatch;
6281 regs.start = TALLOC (nmatch, regoff_t);
6282 regs.end = TALLOC (nmatch, regoff_t);
6283 if (regs.start == NULL || regs.end == NULL)
6284 return (int) REG_NOMATCH;
6287 /* Perform the searching operation. */
6288 ret = re_search (&private_preg, string, len,
6289 /* start: */ 0, /* range: */ len,
6290 want_reg_info ? ®s : (struct re_registers *) 0);
6292 /* Copy the register information to the POSIX structure. */
6299 for (r = 0; r < nmatch; r++)
6301 pmatch[r].rm_so = regs.start[r];
6302 pmatch[r].rm_eo = regs.end[r];
6306 /* If we needed the temporary register info, free the space now. */
6311 /* We want zero return to mean success, unlike `re_search'. */
6312 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6316 /* Returns a message corresponding to an error code, ERRCODE, returned
6317 from either regcomp or regexec. We don't use PREG here. */
6320 regerror (int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
6326 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6327 /* Only error codes returned by the rest of the code should be passed
6328 to this routine. If we are given anything else, or if other regex
6329 code generates an invalid error code, then the program has a bug.
6330 Dump core so we can fix it. */
6333 msg = gettext (re_error_msgid[errcode]);
6335 msg_size = strlen (msg) + 1; /* Includes the null. */
6337 if (errbuf_size != 0)
6339 if (msg_size > errbuf_size)
6341 strncpy (errbuf, msg, errbuf_size - 1);
6342 errbuf[errbuf_size - 1] = 0;
6345 strcpy (errbuf, msg);
6352 /* Free dynamically allocated space used by PREG. */
6355 regfree (regex_t *preg)
6357 if (preg->buffer != NULL)
6358 free (preg->buffer);
6359 preg->buffer = NULL;
6361 preg->allocated = 0;
6364 if (preg->fastmap != NULL)
6365 free (preg->fastmap);
6366 preg->fastmap = NULL;
6367 preg->fastmap_accurate = 0;
6369 if (preg->translate != NULL)
6370 free (preg->translate);
6371 preg->translate = NULL;
6374 #endif /* not emacs */
6378 make-backup-files: t
6380 trim-versions-without-asking: nil