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
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: %d\n", (fail_stack).avail);\
1272 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1274 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1275 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1277 /* Ensure we have enough space allocated for what we will push. */ \
1278 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1280 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1281 return failure_code; \
1283 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1284 (fail_stack).size); \
1285 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1288 /* Push the info, starting with the registers. */ \
1289 DEBUG_PRINT1 ("\n"); \
1291 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1294 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1295 DEBUG_STATEMENT (num_regs_pushed++); \
1297 DEBUG_PRINT2 (" start: 0x%lx\n", (long) regstart[this_reg]); \
1298 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1300 DEBUG_PRINT2 (" end: 0x%lx\n", (long) regend[this_reg]); \
1301 PUSH_FAILURE_POINTER (regend[this_reg]); \
1303 DEBUG_PRINT2 (" info: 0x%lx\n ", \
1304 * (long *) (®_info[this_reg])); \
1305 DEBUG_PRINT2 (" match_null=%d", \
1306 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1307 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1308 DEBUG_PRINT2 (" matched_something=%d", \
1309 MATCHED_SOMETHING (reg_info[this_reg])); \
1310 DEBUG_PRINT2 (" ever_matched=%d", \
1311 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1312 DEBUG_PRINT1 ("\n"); \
1313 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1316 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1317 PUSH_FAILURE_INT (lowest_active_reg); \
1319 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1320 PUSH_FAILURE_INT (highest_active_reg); \
1322 DEBUG_PRINT2 (" Pushing pattern 0x%lx: \n", (long) pattern_place); \
1323 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1324 PUSH_FAILURE_POINTER (pattern_place); \
1326 DEBUG_PRINT2 (" Pushing string 0x%lx: `", (long) string_place); \
1327 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1329 DEBUG_PRINT1 ("'\n"); \
1330 PUSH_FAILURE_POINTER (string_place); \
1332 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1333 DEBUG_PUSH (failure_id); \
1336 /* This is the number of items that are pushed and popped on the stack
1337 for each register. */
1338 #define NUM_REG_ITEMS 3
1340 /* Individual items aside from the registers. */
1342 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1344 #define NUM_NONREG_ITEMS 4
1347 /* We push at most this many items on the stack. */
1348 /* We used to use (num_regs - 1), which is the number of registers
1349 this regexp will save; but that was changed to 5
1350 to avoid stack overflow for a regexp with lots of parens. */
1351 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1353 /* We actually push this many items. */
1354 #define NUM_FAILURE_ITEMS \
1355 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
1358 /* How many items can still be added to the stack without overflowing it. */
1359 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1362 /* Pops what PUSH_FAIL_STACK pushes.
1364 We restore into the parameters, all of which should be lvalues:
1365 STR -- the saved data position.
1366 PAT -- the saved pattern position.
1367 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1368 REGSTART, REGEND -- arrays of string positions.
1369 REG_INFO -- array of information about each subexpression.
1371 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1372 `pend', `string1', `size1', `string2', and `size2'. */
1374 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1376 DEBUG_STATEMENT (fail_stack_elt_t ffailure_id;) \
1378 const unsigned char *string_temp; \
1380 assert (!FAIL_STACK_EMPTY ()); \
1382 /* Remove failure points and point to how many regs pushed. */ \
1383 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1384 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1385 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1387 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1389 DEBUG_POP (&ffailure_id.integer); \
1390 DEBUG_PRINT2 (" Popping failure id: %u\n", \
1391 * (unsigned int *) &ffailure_id); \
1393 /* If the saved string location is NULL, it came from an \
1394 on_failure_keep_string_jump opcode, and we want to throw away the \
1395 saved NULL, thus retaining our current position in the string. */ \
1396 string_temp = POP_FAILURE_POINTER (); \
1397 if (string_temp != NULL) \
1398 str = string_temp; \
1400 DEBUG_PRINT2 (" Popping string 0x%lx: `", (long) str); \
1401 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1402 DEBUG_PRINT1 ("'\n"); \
1404 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1405 DEBUG_PRINT2 (" Popping pattern 0x%lx: ", (long) pat); \
1406 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1408 /* Restore register info. */ \
1409 high_reg = (unsigned) POP_FAILURE_INT (); \
1410 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1412 low_reg = (unsigned) POP_FAILURE_INT (); \
1413 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1415 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1417 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1419 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1420 DEBUG_PRINT2 (" info: 0x%lx\n", \
1421 * (long *) ®_info[this_reg]); \
1423 regend[this_reg] = POP_FAILURE_POINTER (); \
1424 DEBUG_PRINT2 (" end: 0x%lx\n", (long) regend[this_reg]); \
1426 regstart[this_reg] = POP_FAILURE_POINTER (); \
1427 DEBUG_PRINT2 (" start: 0x%lx\n", (long) regstart[this_reg]); \
1430 set_regs_matched_done = 0; \
1431 DEBUG_STATEMENT (nfailure_points_popped++); \
1432 } /* POP_FAILURE_POINT */
1436 /* Structure for per-register (a.k.a. per-group) information.
1437 Other register information, such as the
1438 starting and ending positions (which are addresses), and the list of
1439 inner groups (which is a bits list) are maintained in separate
1442 We are making a (strictly speaking) nonportable assumption here: that
1443 the compiler will pack our bit fields into something that fits into
1444 the type of `word', i.e., is something that fits into one item on the
1449 fail_stack_elt_t word;
1452 /* This field is one if this group can match the empty string,
1453 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1454 #define MATCH_NULL_UNSET_VALUE 3
1455 unsigned match_null_string_p : 2;
1456 unsigned is_active : 1;
1457 unsigned matched_something : 1;
1458 unsigned ever_matched_something : 1;
1460 } register_info_type;
1462 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1463 #define IS_ACTIVE(R) ((R).bits.is_active)
1464 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1465 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1468 /* Call this when have matched a real character; it sets `matched' flags
1469 for the subexpressions which we are currently inside. Also records
1470 that those subexprs have matched. */
1471 #define SET_REGS_MATCHED() \
1474 if (!set_regs_matched_done) \
1477 set_regs_matched_done = 1; \
1478 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1480 MATCHED_SOMETHING (reg_info[r]) \
1481 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1488 /* Registers are set to a sentinel when they haven't yet matched. */
1489 static unsigned char reg_unset_dummy;
1490 #define REG_UNSET_VALUE (®_unset_dummy)
1491 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1493 /* Subroutine declarations and macros for regex_compile. */
1495 /* Fetch the next character in the uncompiled pattern---translating it
1496 if necessary. Also cast from a signed character in the constant
1497 string passed to us by the user to an unsigned char that we can use
1498 as an array index (in, e.g., `translate'). */
1499 #define PATFETCH(c) \
1502 c = TRANSLATE (c); \
1505 /* Fetch the next character in the uncompiled pattern, with no
1507 #define PATFETCH_RAW(c) \
1508 do {if (p == pend) return REG_EEND; \
1509 assert (p < pend); \
1510 c = charptr_emchar (p); \
1514 /* Go backwards one character in the pattern. */
1515 #define PATUNFETCH DEC_CHARPTR (p)
1519 #define PATFETCH_EXTENDED(emch) \
1520 do {if (p == pend) return REG_EEND; \
1521 assert (p < pend); \
1522 emch = charptr_emchar ((const Bufbyte *) p); \
1524 if (TRANSLATE_P (translate) && emch < 0x80) \
1525 emch = (Emchar) (unsigned char) RE_TRANSLATE (emch); \
1528 #define PATFETCH_RAW_EXTENDED(emch) \
1529 do {if (p == pend) return REG_EEND; \
1530 assert (p < pend); \
1531 emch = charptr_emchar ((const Bufbyte *) p); \
1535 #define PATUNFETCH_EXTENDED DEC_CHARPTR (p)
1537 #define PATFETCH_EITHER(emch) \
1539 if (has_extended_chars) \
1540 PATFETCH_EXTENDED (emch); \
1545 #define PATFETCH_RAW_EITHER(emch) \
1547 if (has_extended_chars) \
1548 PATFETCH_RAW_EXTENDED (emch); \
1550 PATFETCH_RAW (emch); \
1553 #define PATUNFETCH_EITHER \
1555 if (has_extended_chars) \
1556 PATUNFETCH_EXTENDED (emch); \
1558 PATUNFETCH (emch); \
1561 #else /* not MULE */
1563 #define PATFETCH_EITHER(emch) PATFETCH (emch)
1564 #define PATFETCH_RAW_EITHER(emch) PATFETCH_RAW (emch)
1565 #define PATUNFETCH_EITHER PATUNFETCH
1569 /* If `translate' is non-null, return translate[D], else just D. We
1570 cast the subscript to translate because some data is declared as
1571 `char *', to avoid warnings when a string constant is passed. But
1572 when we use a character as a subscript we must make it unsigned. */
1573 #define TRANSLATE(d) (TRANSLATE_P (translate) ? RE_TRANSLATE (d) : (d))
1577 #define TRANSLATE_EXTENDED_UNSAFE(emch) \
1578 (TRANSLATE_P (translate) && emch < 0x80 ? RE_TRANSLATE (emch) : (emch))
1582 /* Macros for outputting the compiled pattern into `buffer'. */
1584 /* If the buffer isn't allocated when it comes in, use this. */
1585 #define INIT_BUF_SIZE 32
1587 /* Make sure we have at least N more bytes of space in buffer. */
1588 #define GET_BUFFER_SPACE(n) \
1589 while (buf_end - bufp->buffer + (n) > bufp->allocated) \
1592 /* Make sure we have one more byte of buffer space and then add C to it. */
1593 #define BUF_PUSH(c) \
1595 GET_BUFFER_SPACE (1); \
1596 *buf_end++ = (unsigned char) (c); \
1600 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1601 #define BUF_PUSH_2(c1, c2) \
1603 GET_BUFFER_SPACE (2); \
1604 *buf_end++ = (unsigned char) (c1); \
1605 *buf_end++ = (unsigned char) (c2); \
1609 /* As with BUF_PUSH_2, except for three bytes. */
1610 #define BUF_PUSH_3(c1, c2, c3) \
1612 GET_BUFFER_SPACE (3); \
1613 *buf_end++ = (unsigned char) (c1); \
1614 *buf_end++ = (unsigned char) (c2); \
1615 *buf_end++ = (unsigned char) (c3); \
1619 /* Store a jump with opcode OP at LOC to location TO. We store a
1620 relative address offset by the three bytes the jump itself occupies. */
1621 #define STORE_JUMP(op, loc, to) \
1622 store_op1 (op, loc, (to) - (loc) - 3)
1624 /* Likewise, for a two-argument jump. */
1625 #define STORE_JUMP2(op, loc, to, arg) \
1626 store_op2 (op, loc, (to) - (loc) - 3, arg)
1628 /* Like `STORE_JUMP', but for inserting. Assume `buf_end' is the
1630 #define INSERT_JUMP(op, loc, to) \
1631 insert_op1 (op, loc, (to) - (loc) - 3, buf_end)
1633 /* Like `STORE_JUMP2', but for inserting. Assume `buf_end' is the
1635 #define INSERT_JUMP2(op, loc, to, arg) \
1636 insert_op2 (op, loc, (to) - (loc) - 3, arg, buf_end)
1639 /* This is not an arbitrary limit: the arguments which represent offsets
1640 into the pattern are two bytes long. So if 2^16 bytes turns out to
1641 be too small, many things would have to change. */
1642 #define MAX_BUF_SIZE (1L << 16)
1645 /* Extend the buffer by twice its current size via realloc and
1646 reset the pointers that pointed into the old block to point to the
1647 correct places in the new one. If extending the buffer results in it
1648 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1649 #define EXTEND_BUFFER() \
1651 re_char *old_buffer = bufp->buffer; \
1652 if (bufp->allocated == MAX_BUF_SIZE) \
1654 bufp->allocated <<= 1; \
1655 if (bufp->allocated > MAX_BUF_SIZE) \
1656 bufp->allocated = MAX_BUF_SIZE; \
1657 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1658 if (bufp->buffer == NULL) \
1659 return REG_ESPACE; \
1660 /* If the buffer moved, move all the pointers into it. */ \
1661 if (old_buffer != bufp->buffer) \
1663 buf_end = (buf_end - old_buffer) + bufp->buffer; \
1664 begalt = (begalt - old_buffer) + bufp->buffer; \
1665 if (fixup_alt_jump) \
1666 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1668 laststart = (laststart - old_buffer) + bufp->buffer; \
1669 if (pending_exact) \
1670 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1675 /* Since we have one byte reserved for the register number argument to
1676 {start,stop}_memory, the maximum number of groups we can report
1677 things about is what fits in that byte. */
1678 #define MAX_REGNUM 255
1680 /* But patterns can have more than `MAX_REGNUM' registers. We just
1681 ignore the excess. */
1682 typedef unsigned regnum_t;
1685 /* Macros for the compile stack. */
1687 /* Since offsets can go either forwards or backwards, this type needs to
1688 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1689 typedef int pattern_offset_t;
1693 pattern_offset_t begalt_offset;
1694 pattern_offset_t fixup_alt_jump;
1695 pattern_offset_t inner_group_offset;
1696 pattern_offset_t laststart_offset;
1698 } compile_stack_elt_t;
1703 compile_stack_elt_t *stack;
1705 unsigned avail; /* Offset of next open position. */
1706 } compile_stack_type;
1709 #define INIT_COMPILE_STACK_SIZE 32
1711 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1712 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1714 /* The next available element. */
1715 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1718 /* Set the bit for character C in a bit vector. */
1719 #define SET_LIST_BIT(c) \
1720 (buf_end[((unsigned char) (c)) / BYTEWIDTH] \
1721 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1725 /* Set the "bit" for character C in a range table. */
1726 #define SET_RANGETAB_BIT(c) put_range_table (rtab, c, c, Qt)
1728 /* Set the "bit" for character c in the appropriate table. */
1729 #define SET_EITHER_BIT(c) \
1731 if (has_extended_chars) \
1732 SET_RANGETAB_BIT (c); \
1737 #else /* not MULE */
1739 #define SET_EITHER_BIT(c) SET_LIST_BIT (c)
1744 /* Get the next unsigned number in the uncompiled pattern. */
1745 #define GET_UNSIGNED_NUMBER(num) \
1749 while (ISDIGIT (c)) \
1753 num = num * 10 + c - '0'; \
1761 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1763 #define IS_CHAR_CLASS(string) \
1764 (STREQ (string, "alpha") || STREQ (string, "upper") \
1765 || STREQ (string, "lower") || STREQ (string, "digit") \
1766 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1767 || STREQ (string, "space") || STREQ (string, "print") \
1768 || STREQ (string, "punct") || STREQ (string, "graph") \
1769 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1771 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1772 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1773 static void insert_op1 (re_opcode_t op, unsigned char *loc, int arg,
1774 unsigned char *end);
1775 static void insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2,
1776 unsigned char *end);
1777 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1778 reg_syntax_t syntax);
1779 static boolean at_endline_loc_p (re_char *p, re_char *pend, int syntax);
1780 static boolean group_in_compile_stack (compile_stack_type compile_stack,
1782 static reg_errcode_t compile_range (re_char **p_ptr, re_char *pend,
1783 RE_TRANSLATE_TYPE translate,
1784 reg_syntax_t syntax,
1787 static reg_errcode_t compile_extended_range (re_char **p_ptr,
1789 RE_TRANSLATE_TYPE translate,
1790 reg_syntax_t syntax,
1793 static boolean group_match_null_string_p (unsigned char **p,
1795 register_info_type *reg_info);
1796 static boolean alt_match_null_string_p (unsigned char *p, unsigned char *end,
1797 register_info_type *reg_info);
1798 static boolean common_op_match_null_string_p (unsigned char **p,
1800 register_info_type *reg_info);
1801 static int bcmp_translate (const unsigned char *s1, const unsigned char *s2,
1802 REGISTER int len, RE_TRANSLATE_TYPE translate);
1803 static int re_match_2_internal (struct re_pattern_buffer *bufp,
1804 re_char *string1, int size1,
1805 re_char *string2, int size2, int pos,
1806 struct re_registers *regs, int stop);
1808 #ifndef MATCH_MAY_ALLOCATE
1810 /* If we cannot allocate large objects within re_match_2_internal,
1811 we make the fail stack and register vectors global.
1812 The fail stack, we grow to the maximum size when a regexp
1814 The register vectors, we adjust in size each time we
1815 compile a regexp, according to the number of registers it needs. */
1817 static fail_stack_type fail_stack;
1819 /* Size with which the following vectors are currently allocated.
1820 That is so we can make them bigger as needed,
1821 but never make them smaller. */
1822 static int regs_allocated_size;
1824 static re_char ** regstart, ** regend;
1825 static re_char ** old_regstart, ** old_regend;
1826 static re_char **best_regstart, **best_regend;
1827 static register_info_type *reg_info;
1828 static re_char **reg_dummy;
1829 static register_info_type *reg_info_dummy;
1831 /* Make the register vectors big enough for NUM_REGS registers,
1832 but don't make them smaller. */
1835 regex_grow_registers (int num_regs)
1837 if (num_regs > regs_allocated_size)
1839 RETALLOC_IF (regstart, num_regs, re_char *);
1840 RETALLOC_IF (regend, num_regs, re_char *);
1841 RETALLOC_IF (old_regstart, num_regs, re_char *);
1842 RETALLOC_IF (old_regend, num_regs, re_char *);
1843 RETALLOC_IF (best_regstart, num_regs, re_char *);
1844 RETALLOC_IF (best_regend, num_regs, re_char *);
1845 RETALLOC_IF (reg_info, num_regs, register_info_type);
1846 RETALLOC_IF (reg_dummy, num_regs, re_char *);
1847 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1849 regs_allocated_size = num_regs;
1853 #endif /* not MATCH_MAY_ALLOCATE */
1855 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1856 Returns one of error codes defined in `regex.h', or zero for success.
1858 Assumes the `allocated' (and perhaps `buffer') and `translate'
1859 fields are set in BUFP on entry.
1861 If it succeeds, results are put in BUFP (if it returns an error, the
1862 contents of BUFP are undefined):
1863 `buffer' is the compiled pattern;
1864 `syntax' is set to SYNTAX;
1865 `used' is set to the length of the compiled pattern;
1866 `fastmap_accurate' is zero;
1867 `re_nsub' is the number of subexpressions in PATTERN;
1868 `not_bol' and `not_eol' are zero;
1870 The `fastmap' and `newline_anchor' fields are neither
1871 examined nor set. */
1873 /* Return, freeing storage we allocated. */
1874 #define FREE_STACK_RETURN(value) \
1875 return (free (compile_stack.stack), value)
1877 static reg_errcode_t
1878 regex_compile (re_char *pattern, int size, reg_syntax_t syntax,
1879 struct re_pattern_buffer *bufp)
1881 /* We fetch characters from PATTERN here. We declare these as int
1882 (or possibly long) so that chars above 127 can be used as
1883 array indices. The macros that fetch a character from the pattern
1884 make sure to coerce to unsigned char before assigning, so we won't
1885 get bitten by negative numbers here. */
1886 /* XEmacs change: used to be unsigned char. */
1887 REGISTER EMACS_INT c, c1;
1889 /* A random temporary spot in PATTERN. */
1892 /* Points to the end of the buffer, where we should append. */
1893 REGISTER unsigned char *buf_end;
1895 /* Keeps track of unclosed groups. */
1896 compile_stack_type compile_stack;
1898 /* Points to the current (ending) position in the pattern. */
1899 re_char *p = pattern;
1900 re_char *pend = pattern + size;
1902 /* How to translate the characters in the pattern. */
1903 RE_TRANSLATE_TYPE translate = bufp->translate;
1905 /* Address of the count-byte of the most recently inserted `exactn'
1906 command. This makes it possible to tell if a new exact-match
1907 character can be added to that command or if the character requires
1908 a new `exactn' command. */
1909 unsigned char *pending_exact = 0;
1911 /* Address of start of the most recently finished expression.
1912 This tells, e.g., postfix * where to find the start of its
1913 operand. Reset at the beginning of groups and alternatives. */
1914 unsigned char *laststart = 0;
1916 /* Address of beginning of regexp, or inside of last group. */
1917 unsigned char *begalt;
1919 /* Place in the uncompiled pattern (i.e., the {) to
1920 which to go back if the interval is invalid. */
1921 re_char *beg_interval;
1923 /* Address of the place where a forward jump should go to the end of
1924 the containing expression. Each alternative of an `or' -- except the
1925 last -- ends with a forward jump of this sort. */
1926 unsigned char *fixup_alt_jump = 0;
1928 /* Counts open-groups as they are encountered. Remembered for the
1929 matching close-group on the compile stack, so the same register
1930 number is put in the stop_memory as the start_memory. */
1931 regnum_t regnum = 0;
1934 DEBUG_PRINT1 ("\nCompiling pattern: ");
1937 unsigned debug_count;
1939 for (debug_count = 0; debug_count < size; debug_count++)
1940 putchar (pattern[debug_count]);
1945 /* Initialize the compile stack. */
1946 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1947 if (compile_stack.stack == NULL)
1950 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1951 compile_stack.avail = 0;
1953 /* Initialize the pattern buffer. */
1954 bufp->syntax = syntax;
1955 bufp->fastmap_accurate = 0;
1956 bufp->not_bol = bufp->not_eol = 0;
1958 /* Set `used' to zero, so that if we return an error, the pattern
1959 printer (for debugging) will think there's no pattern. We reset it
1963 /* Always count groups, whether or not bufp->no_sub is set. */
1966 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1967 /* Initialize the syntax table. */
1968 init_syntax_once ();
1971 if (bufp->allocated == 0)
1974 { /* If zero allocated, but buffer is non-null, try to realloc
1975 enough space. This loses if buffer's address is bogus, but
1976 that is the user's responsibility. */
1977 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1980 { /* Caller did not allocate a buffer. Do it for them. */
1981 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1983 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1985 bufp->allocated = INIT_BUF_SIZE;
1988 begalt = buf_end = bufp->buffer;
1990 /* Loop through the uncompiled pattern until we're at the end. */
1999 if ( /* If at start of pattern, it's an operator. */
2001 /* If context independent, it's an operator. */
2002 || syntax & RE_CONTEXT_INDEP_ANCHORS
2003 /* Otherwise, depends on what's come before. */
2004 || at_begline_loc_p (pattern, p, syntax))
2014 if ( /* If at end of pattern, it's an operator. */
2016 /* If context independent, it's an operator. */
2017 || syntax & RE_CONTEXT_INDEP_ANCHORS
2018 /* Otherwise, depends on what's next. */
2019 || at_endline_loc_p (p, pend, syntax))
2029 if ((syntax & RE_BK_PLUS_QM)
2030 || (syntax & RE_LIMITED_OPS))
2034 /* If there is no previous pattern... */
2037 if (syntax & RE_CONTEXT_INVALID_OPS)
2038 FREE_STACK_RETURN (REG_BADRPT);
2039 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2044 /* true means zero/many matches are allowed. */
2045 boolean zero_times_ok = c != '+';
2046 boolean many_times_ok = c != '?';
2048 /* true means match shortest string possible. */
2049 boolean minimal = false;
2051 /* If there is a sequence of repetition chars, collapse it
2052 down to just one (the right one). We can't combine
2053 interval operators with these because of, e.g., `a{2}*',
2054 which should only match an even number of `a's. */
2059 if (c == '*' || (!(syntax & RE_BK_PLUS_QM)
2060 && (c == '+' || c == '?')))
2063 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2065 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2068 if (!(c1 == '+' || c1 == '?'))
2083 /* If we get here, we found another repeat character. */
2084 if (!(syntax & RE_NO_MINIMAL_MATCHING))
2086 /* "*?" and "+?" and "??" are okay (and mean match
2087 minimally), but other sequences (such as "*??" and
2088 "+++") are rejected (reserved for future use). */
2089 if (minimal || c != '?')
2090 FREE_STACK_RETURN (REG_BADRPT);
2095 zero_times_ok |= c != '+';
2096 many_times_ok |= c != '?';
2100 /* Star, etc. applied to an empty pattern is equivalent
2101 to an empty pattern. */
2105 /* Now we know whether zero matches is allowed
2106 and whether two or more matches is allowed
2107 and whether we want minimal or maximal matching. */
2113 0: /on_failure_jump to 6
2118 GET_BUFFER_SPACE (6);
2119 INSERT_JUMP (jump, laststart, buf_end + 3);
2121 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2124 else if (zero_times_ok)
2129 6: /on_failure_jump to 3
2132 GET_BUFFER_SPACE (6);
2133 INSERT_JUMP (jump, laststart, buf_end + 3);
2135 STORE_JUMP (on_failure_jump, buf_end, laststart + 3);
2142 3: /on_failure_jump to 0
2145 GET_BUFFER_SPACE (3);
2146 STORE_JUMP (on_failure_jump, buf_end, laststart);
2152 /* Are we optimizing this jump? */
2153 boolean keep_string_p = false;
2156 { /* More than one repetition is allowed, so put in
2157 at the end a backward relative jump from
2158 `buf_end' to before the next jump we're going
2159 to put in below (which jumps from laststart to
2162 But if we are at the `*' in the exact sequence `.*\n',
2163 insert an unconditional jump backwards to the .,
2164 instead of the beginning of the loop. This way we only
2165 push a failure point once, instead of every time
2166 through the loop. */
2167 assert (p - 1 > pattern);
2169 /* Allocate the space for the jump. */
2170 GET_BUFFER_SPACE (3);
2172 /* We know we are not at the first character of the
2173 pattern, because laststart was nonzero. And we've
2174 already incremented `p', by the way, to be the
2175 character after the `*'. Do we have to do something
2176 analogous here for null bytes, because of
2180 && p < pend && *p == '\n'
2181 && !(syntax & RE_DOT_NEWLINE))
2182 { /* We have .*\n. */
2183 STORE_JUMP (jump, buf_end, laststart);
2184 keep_string_p = true;
2187 /* Anything else. */
2188 STORE_JUMP (maybe_pop_jump, buf_end, laststart - 3);
2190 /* We've added more stuff to the buffer. */
2194 /* On failure, jump from laststart to buf_end + 3,
2195 which will be the end of the buffer after this jump
2197 GET_BUFFER_SPACE (3);
2198 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2200 laststart, buf_end + 3);
2205 /* At least one repetition is required, so insert a
2206 `dummy_failure_jump' before the initial
2207 `on_failure_jump' instruction of the loop. This
2208 effects a skip over that instruction the first time
2209 we hit that loop. */
2210 GET_BUFFER_SPACE (3);
2211 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2221 laststart = buf_end;
2228 /* XEmacs change: this whole section */
2229 boolean had_char_class = false;
2231 boolean has_extended_chars = false;
2232 REGISTER Lisp_Object rtab = Qnil;
2235 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2237 /* Ensure that we have enough space to push a charset: the
2238 opcode, the length count, and the bitset; 34 bytes in all. */
2239 GET_BUFFER_SPACE (34);
2241 laststart = buf_end;
2243 /* We test `*p == '^' twice, instead of using an if
2244 statement, so we only need one BUF_PUSH. */
2245 BUF_PUSH (*p == '^' ? charset_not : charset);
2249 /* Remember the first position in the bracket expression. */
2252 /* Push the number of bytes in the bitmap. */
2253 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2255 /* Clear the whole map. */
2256 memset (buf_end, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2258 /* charset_not matches newline according to a syntax bit. */
2259 if ((re_opcode_t) buf_end[-2] == charset_not
2260 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2261 SET_LIST_BIT ('\n');
2264 start_over_with_extended:
2265 if (has_extended_chars)
2267 /* There are extended chars here, which means we need to start
2268 over and shift to unified range-table format. */
2269 if (buf_end[-2] == charset)
2270 buf_end[-2] = charset_mule;
2272 buf_end[-2] = charset_mule_not;
2274 p = p1; /* go back to the beginning of the charset, after
2276 rtab = Vthe_lisp_rangetab;
2277 Fclear_range_table (rtab);
2279 /* charset_not matches newline according to a syntax bit. */
2280 if ((re_opcode_t) buf_end[-1] == charset_mule_not
2281 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2282 SET_EITHER_BIT ('\n');
2286 /* Read in characters and ranges, setting map bits. */
2289 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2294 if (c >= 0x80 && !has_extended_chars)
2296 has_extended_chars = 1;
2297 /* Frumble-bumble, we've found some extended chars.
2298 Need to start over, process everything using
2299 the general extended-char mechanism, and need
2300 to use charset_mule and charset_mule_not instead
2301 of charset and charset_not. */
2302 goto start_over_with_extended;
2305 /* \ might escape characters inside [...] and [^...]. */
2306 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2308 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2312 if (c1 >= 0x80 && !has_extended_chars)
2314 has_extended_chars = 1;
2315 goto start_over_with_extended;
2318 SET_EITHER_BIT (c1);
2322 /* Could be the end of the bracket expression. If it's
2323 not (i.e., when the bracket expression is `[]' so
2324 far), the ']' character bit gets set way below. */
2325 if (c == ']' && p != p1 + 1)
2328 /* Look ahead to see if it's a range when the last thing
2329 was a character class. */
2330 if (had_char_class && c == '-' && *p != ']')
2331 FREE_STACK_RETURN (REG_ERANGE);
2333 /* Look ahead to see if it's a range when the last thing
2334 was a character: if this is a hyphen not at the
2335 beginning or the end of a list, then it's the range
2338 && !(p - 2 >= pattern && p[-2] == '[')
2339 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2345 if (* (unsigned char *) p >= 0x80 && !has_extended_chars)
2347 has_extended_chars = 1;
2348 goto start_over_with_extended;
2350 if (has_extended_chars)
2351 ret = compile_extended_range (&p, pend, translate,
2355 ret = compile_range (&p, pend, translate, syntax, buf_end);
2356 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2359 else if (p[0] == '-' && p[1] != ']')
2360 { /* This handles ranges made up of characters only. */
2363 /* Move past the `-'. */
2367 if (* (unsigned char *) p >= 0x80 && !has_extended_chars)
2369 has_extended_chars = 1;
2370 goto start_over_with_extended;
2372 if (has_extended_chars)
2373 ret = compile_extended_range (&p, pend, translate,
2377 ret = compile_range (&p, pend, translate, syntax, buf_end);
2378 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2381 /* See if we're at the beginning of a possible character
2384 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2385 { /* Leave room for the null. */
2386 char str[CHAR_CLASS_MAX_LENGTH + 1];
2391 /* If pattern is `[[:'. */
2392 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2396 /* #### This code is unused.
2397 Correctness is not checked after TRT
2400 if (c == ':' || c == ']' || p == pend
2401 || c1 == CHAR_CLASS_MAX_LENGTH)
2403 str[c1++] = (char) c;
2407 /* If isn't a word bracketed by `[:' and `:]':
2408 undo the ending character, the letters, and leave
2409 the leading `:' and `[' (but set bits for them). */
2410 if (c == ':' && *p == ']')
2413 boolean is_alnum = STREQ (str, "alnum");
2414 boolean is_alpha = STREQ (str, "alpha");
2415 boolean is_blank = STREQ (str, "blank");
2416 boolean is_cntrl = STREQ (str, "cntrl");
2417 boolean is_digit = STREQ (str, "digit");
2418 boolean is_graph = STREQ (str, "graph");
2419 boolean is_lower = STREQ (str, "lower");
2420 boolean is_print = STREQ (str, "print");
2421 boolean is_punct = STREQ (str, "punct");
2422 boolean is_space = STREQ (str, "space");
2423 boolean is_upper = STREQ (str, "upper");
2424 boolean is_xdigit = STREQ (str, "xdigit");
2426 if (!IS_CHAR_CLASS (str))
2427 FREE_STACK_RETURN (REG_ECTYPE);
2429 /* Throw away the ] at the end of the character
2433 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2435 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2437 /* This was split into 3 if's to
2438 avoid an arbitrary limit in some compiler. */
2439 if ( (is_alnum && ISALNUM (ch))
2440 || (is_alpha && ISALPHA (ch))
2441 || (is_blank && ISBLANK (ch))
2442 || (is_cntrl && ISCNTRL (ch)))
2443 SET_EITHER_BIT (ch);
2444 if ( (is_digit && ISDIGIT (ch))
2445 || (is_graph && ISGRAPH (ch))
2446 || (is_lower && ISLOWER (ch))
2447 || (is_print && ISPRINT (ch)))
2448 SET_EITHER_BIT (ch);
2449 if ( (is_punct && ISPUNCT (ch))
2450 || (is_space && ISSPACE (ch))
2451 || (is_upper && ISUPPER (ch))
2452 || (is_xdigit && ISXDIGIT (ch)))
2453 SET_EITHER_BIT (ch);
2455 had_char_class = true;
2462 SET_EITHER_BIT ('[');
2463 SET_EITHER_BIT (':');
2464 had_char_class = false;
2469 had_char_class = false;
2475 if (has_extended_chars)
2477 /* We have a range table, not a bit vector. */
2479 unified_range_table_bytes_needed (rtab);
2480 GET_BUFFER_SPACE (bytes_needed);
2481 unified_range_table_copy_data (rtab, buf_end);
2482 buf_end += unified_range_table_bytes_used (buf_end);
2486 /* Discard any (non)matching list bytes that are all 0 at the
2487 end of the map. Decrease the map-length byte too. */
2488 while ((int) buf_end[-1] > 0 && buf_end[buf_end[-1] - 1] == 0)
2490 buf_end += buf_end[-1];
2496 if (syntax & RE_NO_BK_PARENS)
2503 if (syntax & RE_NO_BK_PARENS)
2510 if (syntax & RE_NEWLINE_ALT)
2517 if (syntax & RE_NO_BK_VBAR)
2524 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2525 goto handle_interval;
2531 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2533 /* Do not translate the character after the \, so that we can
2534 distinguish, e.g., \B from \b, even if we normally would
2535 translate, e.g., B to b. */
2541 if (syntax & RE_NO_BK_PARENS)
2542 goto normal_backslash;
2548 if (!(syntax & RE_NO_SHY_GROUPS)
2556 case ':': /* shy groups */
2560 /* All others are reserved for future constructs. */
2562 FREE_STACK_RETURN (REG_BADPAT);
2571 if (COMPILE_STACK_FULL)
2573 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2574 compile_stack_elt_t);
2575 if (compile_stack.stack == NULL) return REG_ESPACE;
2577 compile_stack.size <<= 1;
2580 /* These are the values to restore when we hit end of this
2581 group. They are all relative offsets, so that if the
2582 whole pattern moves because of realloc, they will still
2584 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2585 COMPILE_STACK_TOP.fixup_alt_jump
2586 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2587 COMPILE_STACK_TOP.laststart_offset = buf_end - bufp->buffer;
2588 COMPILE_STACK_TOP.regnum = r;
2590 /* We will eventually replace the 0 with the number of
2591 groups inner to this one. But do not push a
2592 start_memory for groups beyond the last one we can
2593 represent in the compiled pattern. */
2594 if (r <= MAX_REGNUM)
2596 COMPILE_STACK_TOP.inner_group_offset
2597 = buf_end - bufp->buffer + 2;
2598 BUF_PUSH_3 (start_memory, r, 0);
2601 compile_stack.avail++;
2606 /* If we've reached MAX_REGNUM groups, then this open
2607 won't actually generate any code, so we'll have to
2608 clear pending_exact explicitly. */
2615 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2617 if (COMPILE_STACK_EMPTY) {
2618 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2619 goto normal_backslash;
2621 FREE_STACK_RETURN (REG_ERPAREN);
2626 { /* Push a dummy failure point at the end of the
2627 alternative for a possible future
2628 `pop_failure_jump' to pop. See comments at
2629 `push_dummy_failure' in `re_match_2'. */
2630 BUF_PUSH (push_dummy_failure);
2632 /* We allocated space for this jump when we assigned
2633 to `fixup_alt_jump', in the `handle_alt' case below. */
2634 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end - 1);
2637 /* See similar code for backslashed left paren above. */
2638 if (COMPILE_STACK_EMPTY) {
2639 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2642 FREE_STACK_RETURN (REG_ERPAREN);
2645 /* Since we just checked for an empty stack above, this
2646 ``can't happen''. */
2647 assert (compile_stack.avail != 0);
2649 /* We don't just want to restore into `regnum', because
2650 later groups should continue to be numbered higher,
2651 as in `(ab)c(de)' -- the second group is #2. */
2652 regnum_t this_group_regnum;
2654 compile_stack.avail--;
2655 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2657 = COMPILE_STACK_TOP.fixup_alt_jump
2658 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2660 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2661 this_group_regnum = COMPILE_STACK_TOP.regnum;
2662 /* If we've reached MAX_REGNUM groups, then this open
2663 won't actually generate any code, so we'll have to
2664 clear pending_exact explicitly. */
2667 /* We're at the end of the group, so now we know how many
2668 groups were inside this one. */
2669 if (this_group_regnum <= MAX_REGNUM)
2671 unsigned char *inner_group_loc
2672 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2674 *inner_group_loc = regnum - this_group_regnum;
2675 BUF_PUSH_3 (stop_memory, this_group_regnum,
2676 regnum - this_group_regnum);
2682 case '|': /* `\|'. */
2683 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2684 goto normal_backslash;
2686 if (syntax & RE_LIMITED_OPS)
2689 /* Insert before the previous alternative a jump which
2690 jumps to this alternative if the former fails. */
2691 GET_BUFFER_SPACE (3);
2692 INSERT_JUMP (on_failure_jump, begalt, buf_end + 6);
2696 /* The alternative before this one has a jump after it
2697 which gets executed if it gets matched. Adjust that
2698 jump so it will jump to this alternative's analogous
2699 jump (put in below, which in turn will jump to the next
2700 (if any) alternative's such jump, etc.). The last such
2701 jump jumps to the correct final destination. A picture:
2707 If we are at `b', then fixup_alt_jump right now points to a
2708 three-byte space after `a'. We'll put in the jump, set
2709 fixup_alt_jump to right after `b', and leave behind three
2710 bytes which we'll fill in when we get to after `c'. */
2713 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end);
2715 /* Mark and leave space for a jump after this alternative,
2716 to be filled in later either by next alternative or
2717 when know we're at the end of a series of alternatives. */
2718 fixup_alt_jump = buf_end;
2719 GET_BUFFER_SPACE (3);
2728 /* If \{ is a literal. */
2729 if (!(syntax & RE_INTERVALS)
2730 /* If we're at `\{' and it's not the open-interval
2732 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2733 || (p - 2 == pattern && p == pend))
2734 goto normal_backslash;
2738 /* If got here, then the syntax allows intervals. */
2740 /* At least (most) this many matches must be made. */
2741 int lower_bound = -1, upper_bound = -1;
2743 beg_interval = p - 1;
2747 if (syntax & RE_NO_BK_BRACES)
2748 goto unfetch_interval;
2750 FREE_STACK_RETURN (REG_EBRACE);
2753 GET_UNSIGNED_NUMBER (lower_bound);
2757 GET_UNSIGNED_NUMBER (upper_bound);
2758 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2761 /* Interval such as `{1}' => match exactly once. */
2762 upper_bound = lower_bound;
2764 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2765 || lower_bound > upper_bound)
2767 if (syntax & RE_NO_BK_BRACES)
2768 goto unfetch_interval;
2770 FREE_STACK_RETURN (REG_BADBR);
2773 if (!(syntax & RE_NO_BK_BRACES))
2775 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2782 if (syntax & RE_NO_BK_BRACES)
2783 goto unfetch_interval;
2785 FREE_STACK_RETURN (REG_BADBR);
2788 /* We just parsed a valid interval. */
2790 /* If it's invalid to have no preceding re. */
2793 if (syntax & RE_CONTEXT_INVALID_OPS)
2794 FREE_STACK_RETURN (REG_BADRPT);
2795 else if (syntax & RE_CONTEXT_INDEP_OPS)
2796 laststart = buf_end;
2798 goto unfetch_interval;
2801 /* If the upper bound is zero, don't want to succeed at
2802 all; jump from `laststart' to `b + 3', which will be
2803 the end of the buffer after we insert the jump. */
2804 if (upper_bound == 0)
2806 GET_BUFFER_SPACE (3);
2807 INSERT_JUMP (jump, laststart, buf_end + 3);
2811 /* Otherwise, we have a nontrivial interval. When
2812 we're all done, the pattern will look like:
2813 set_number_at <jump count> <upper bound>
2814 set_number_at <succeed_n count> <lower bound>
2815 succeed_n <after jump addr> <succeed_n count>
2817 jump_n <succeed_n addr> <jump count>
2818 (The upper bound and `jump_n' are omitted if
2819 `upper_bound' is 1, though.) */
2821 { /* If the upper bound is > 1, we need to insert
2822 more at the end of the loop. */
2823 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2825 GET_BUFFER_SPACE (nbytes);
2827 /* Initialize lower bound of the `succeed_n', even
2828 though it will be set during matching by its
2829 attendant `set_number_at' (inserted next),
2830 because `re_compile_fastmap' needs to know.
2831 Jump to the `jump_n' we might insert below. */
2832 INSERT_JUMP2 (succeed_n, laststart,
2833 buf_end + 5 + (upper_bound > 1) * 5,
2837 /* Code to initialize the lower bound. Insert
2838 before the `succeed_n'. The `5' is the last two
2839 bytes of this `set_number_at', plus 3 bytes of
2840 the following `succeed_n'. */
2841 insert_op2 (set_number_at, laststart, 5, lower_bound, buf_end);
2844 if (upper_bound > 1)
2845 { /* More than one repetition is allowed, so
2846 append a backward jump to the `succeed_n'
2847 that starts this interval.
2849 When we've reached this during matching,
2850 we'll have matched the interval once, so
2851 jump back only `upper_bound - 1' times. */
2852 STORE_JUMP2 (jump_n, buf_end, laststart + 5,
2856 /* The location we want to set is the second
2857 parameter of the `jump_n'; that is `b-2' as
2858 an absolute address. `laststart' will be
2859 the `set_number_at' we're about to insert;
2860 `laststart+3' the number to set, the source
2861 for the relative address. But we are
2862 inserting into the middle of the pattern --
2863 so everything is getting moved up by 5.
2864 Conclusion: (b - 2) - (laststart + 3) + 5,
2865 i.e., b - laststart.
2867 We insert this at the beginning of the loop
2868 so that if we fail during matching, we'll
2869 reinitialize the bounds. */
2870 insert_op2 (set_number_at, laststart,
2871 buf_end - laststart,
2872 upper_bound - 1, buf_end);
2877 beg_interval = NULL;
2882 /* If an invalid interval, match the characters as literals. */
2883 assert (beg_interval);
2885 beg_interval = NULL;
2887 /* normal_char and normal_backslash need `c'. */
2890 if (!(syntax & RE_NO_BK_BRACES))
2892 if (p > pattern && p[-1] == '\\')
2893 goto normal_backslash;
2898 /* There is no way to specify the before_dot and after_dot
2899 operators. rms says this is ok. --karl */
2905 laststart = buf_end;
2907 /* XEmacs addition */
2908 if (c >= 0x80 || syntax_spec_code[c] == 0377)
2909 FREE_STACK_RETURN (REG_ESYNTAX);
2910 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2914 laststart = buf_end;
2916 /* XEmacs addition */
2917 if (c >= 0x80 || syntax_spec_code[c] == 0377)
2918 FREE_STACK_RETURN (REG_ESYNTAX);
2919 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2923 /* 97.2.17 jhod merged in to XEmacs from mule-2.3 */
2925 laststart = buf_end;
2927 if (c < 32 || c > 127)
2928 FREE_STACK_RETURN (REG_ECATEGORY);
2929 BUF_PUSH_2 (categoryspec, c);
2933 laststart = buf_end;
2935 if (c < 32 || c > 127)
2936 FREE_STACK_RETURN (REG_ECATEGORY);
2937 BUF_PUSH_2 (notcategoryspec, c);
2939 /* end of category patch */
2945 laststart = buf_end;
2946 BUF_PUSH (wordchar);
2951 laststart = buf_end;
2952 BUF_PUSH (notwordchar);
2965 BUF_PUSH (wordbound);
2969 BUF_PUSH (notwordbound);
2980 case '1': case '2': case '3': case '4': case '5':
2981 case '6': case '7': case '8': case '9':
2984 if (syntax & RE_NO_BK_REFS)
2990 FREE_STACK_RETURN (REG_ESUBREG);
2992 /* Can't back reference to a subexpression if inside of it. */
2993 if (group_in_compile_stack (compile_stack, reg))
2996 laststart = buf_end;
2997 BUF_PUSH_2 (duplicate, reg);
3004 if (syntax & RE_BK_PLUS_QM)
3007 goto normal_backslash;
3011 /* You might think it would be useful for \ to mean
3012 not to translate; but if we don't translate it,
3013 it will never match anything. */
3021 /* Expects the character in `c'. */
3022 /* `p' points to the location after where `c' came from. */
3025 /* XEmacs: modifications here for Mule. */
3026 /* `q' points to the beginning of the next char. */
3029 /* If no exactn currently being built. */
3032 /* If last exactn not at current position. */
3033 || pending_exact + *pending_exact + 1 != buf_end
3035 /* We have only one byte following the exactn for the count. */
3036 || ((unsigned int) (*pending_exact + (q - p)) >=
3037 ((unsigned int) (1 << BYTEWIDTH) - 1))
3039 /* If followed by a repetition operator. */
3040 || *q == '*' || *q == '^'
3041 || ((syntax & RE_BK_PLUS_QM)
3042 ? *q == '\\' && (q[1] == '+' || q[1] == '?')
3043 : (*q == '+' || *q == '?'))
3044 || ((syntax & RE_INTERVALS)
3045 && ((syntax & RE_NO_BK_BRACES)
3047 : (q[0] == '\\' && q[1] == '{'))))
3049 /* Start building a new exactn. */
3051 laststart = buf_end;
3053 BUF_PUSH_2 (exactn, 0);
3054 pending_exact = buf_end - 1;
3063 Bufbyte tmp_buf[MAX_EMCHAR_LEN];
3066 bt_count = set_charptr_emchar (tmp_buf, c);
3068 for (i = 0; i < bt_count; i++)
3070 BUF_PUSH (tmp_buf[i]);
3078 } /* while p != pend */
3081 /* Through the pattern now. */
3084 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end);
3086 if (!COMPILE_STACK_EMPTY)
3087 FREE_STACK_RETURN (REG_EPAREN);
3089 /* If we don't want backtracking, force success
3090 the first time we reach the end of the compiled pattern. */
3091 if (syntax & RE_NO_POSIX_BACKTRACKING)
3094 free (compile_stack.stack);
3096 /* We have succeeded; set the length of the buffer. */
3097 bufp->used = buf_end - bufp->buffer;
3102 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3103 print_compiled_pattern (bufp);
3107 #ifndef MATCH_MAY_ALLOCATE
3108 /* Initialize the failure stack to the largest possible stack. This
3109 isn't necessary unless we're trying to avoid calling alloca in
3110 the search and match routines. */
3112 int num_regs = bufp->re_nsub + 1;
3114 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
3115 is strictly greater than re_max_failures, the largest possible stack
3116 is 2 * re_max_failures failure points. */
3117 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
3119 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
3122 if (! fail_stack.stack)
3124 = (fail_stack_elt_t *) xmalloc (fail_stack.size
3125 * sizeof (fail_stack_elt_t));
3128 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
3130 * sizeof (fail_stack_elt_t)));
3131 #else /* not emacs */
3132 if (! fail_stack.stack)
3134 = (fail_stack_elt_t *) malloc (fail_stack.size
3135 * sizeof (fail_stack_elt_t));
3138 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3140 * sizeof (fail_stack_elt_t)));
3144 regex_grow_registers (num_regs);
3146 #endif /* not MATCH_MAY_ALLOCATE */
3149 } /* regex_compile */
3151 /* Subroutines for `regex_compile'. */
3153 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3156 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3158 *loc = (unsigned char) op;
3159 STORE_NUMBER (loc + 1, arg);
3163 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3166 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3168 *loc = (unsigned char) op;
3169 STORE_NUMBER (loc + 1, arg1);
3170 STORE_NUMBER (loc + 3, arg2);
3174 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3175 for OP followed by two-byte integer parameter ARG. */
3178 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3180 REGISTER unsigned char *pfrom = end;
3181 REGISTER unsigned char *pto = end + 3;
3183 while (pfrom != loc)
3186 store_op1 (op, loc, arg);
3190 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3193 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2,
3196 REGISTER unsigned char *pfrom = end;
3197 REGISTER unsigned char *pto = end + 5;
3199 while (pfrom != loc)
3202 store_op2 (op, loc, arg1, arg2);
3206 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3207 after an alternative or a begin-subexpression. We assume there is at
3208 least one character before the ^. */
3211 at_begline_loc_p (re_char *pattern, re_char *p, reg_syntax_t syntax)
3213 re_char *prev = p - 2;
3214 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3217 /* After a subexpression? */
3218 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3219 /* After an alternative? */
3220 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3224 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3225 at least one character after the $, i.e., `P < PEND'. */
3228 at_endline_loc_p (re_char *p, re_char *pend, int syntax)
3231 boolean next_backslash = *next == '\\';
3232 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3235 /* Before a subexpression? */
3236 (syntax & RE_NO_BK_PARENS ? *next == ')'
3237 : next_backslash && next_next && *next_next == ')')
3238 /* Before an alternative? */
3239 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3240 : next_backslash && next_next && *next_next == '|');
3244 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3245 false if it's not. */
3248 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3252 for (this_element = compile_stack.avail - 1;
3255 if (compile_stack.stack[this_element].regnum == regnum)
3262 /* Read the ending character of a range (in a bracket expression) from the
3263 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3264 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3265 Then we set the translation of all bits between the starting and
3266 ending characters (inclusive) in the compiled pattern B.
3268 Return an error code.
3270 We use these short variable names so we can use the same macros as
3271 `regex_compile' itself. */
3273 static reg_errcode_t
3274 compile_range (re_char **p_ptr, re_char *pend, RE_TRANSLATE_TYPE translate,
3275 reg_syntax_t syntax, unsigned char *buf_end)
3279 re_char *p = *p_ptr;
3280 int range_start, range_end;
3285 /* Even though the pattern is a signed `char *', we need to fetch
3286 with unsigned char *'s; if the high bit of the pattern character
3287 is set, the range endpoints will be negative if we fetch using a
3290 We also want to fetch the endpoints without translating them; the
3291 appropriate translation is done in the bit-setting loop below. */
3292 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
3293 range_start = ((const unsigned char *) p)[-2];
3294 range_end = ((const unsigned char *) p)[0];
3296 /* Have to increment the pointer into the pattern string, so the
3297 caller isn't still at the ending character. */
3300 /* If the start is after the end, the range is empty. */
3301 if (range_start > range_end)
3302 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3304 /* Here we see why `this_char' has to be larger than an `unsigned
3305 char' -- the range is inclusive, so if `range_end' == 0xff
3306 (assuming 8-bit characters), we would otherwise go into an infinite
3307 loop, since all characters <= 0xff. */
3308 for (this_char = range_start; this_char <= range_end; this_char++)
3310 SET_LIST_BIT (TRANSLATE (this_char));
3318 static reg_errcode_t
3319 compile_extended_range (re_char **p_ptr, re_char *pend,
3320 RE_TRANSLATE_TYPE translate,
3321 reg_syntax_t syntax, Lisp_Object rtab)
3323 Emchar this_char, range_start, range_end;
3329 p = (const Bufbyte *) *p_ptr;
3330 range_end = charptr_emchar (p);
3331 p--; /* back to '-' */
3332 DEC_CHARPTR (p); /* back to start of range */
3333 /* We also want to fetch the endpoints without translating them; the
3334 appropriate translation is done in the bit-setting loop below. */
3335 range_start = charptr_emchar (p);
3336 INC_CHARPTR (*p_ptr);
3338 /* If the start is after the end, the range is empty. */
3339 if (range_start > range_end)
3340 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3342 /* Can't have ranges spanning different charsets, except maybe for
3343 ranges entirely within the first 256 chars. */
3345 if ((range_start >= 0x100 || range_end >= 0x100)
3347 && CHAR_CHARSET_ID (range_start) != CHAR_CHARSET_ID (range_end)
3349 && CHAR_LEADING_BYTE (range_start) != CHAR_LEADING_BYTE (range_end)
3352 return REG_ERANGESPAN;
3354 /* As advertised, translations only work over the 0 - 0x7F range.
3355 Making this kind of stuff work generally is much harder.
3356 Iterating over the whole range like this would be way efficient
3357 if the range encompasses 10,000 chars or something. You'd have
3358 to do something like this:
3362 map over translation table in [range_start, range_end] of
3363 (put the mapped range in a;
3364 put the translation in b)
3365 invert the range in a and truncate to [range_start, range_end]
3366 compute the union of a, b
3367 union the result into rtab
3369 for (this_char = range_start;
3370 this_char <= range_end && this_char < 0x80; this_char++)
3372 SET_RANGETAB_BIT (TRANSLATE (this_char));
3375 if (this_char <= range_end)
3376 put_range_table (rtab, this_char, range_end, Qt);
3383 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3384 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3385 characters can start a string that matches the pattern. This fastmap
3386 is used by re_search to skip quickly over impossible starting points.
3388 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3389 area as BUFP->fastmap.
3391 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3394 Returns 0 if we succeed, -2 if an internal error. */
3397 re_compile_fastmap (struct re_pattern_buffer *bufp)
3400 #ifdef MATCH_MAY_ALLOCATE
3401 fail_stack_type fail_stack;
3404 /* We don't push any register information onto the failure stack. */
3406 REGISTER char *fastmap = bufp->fastmap;
3407 unsigned char *pattern = bufp->buffer;
3408 unsigned long size = bufp->used;
3409 unsigned char *p = pattern;
3410 REGISTER unsigned char *pend = pattern + size;
3413 /* This holds the pointer to the failure stack, when
3414 it is allocated relocatably. */
3415 fail_stack_elt_t *failure_stack_ptr;
3418 /* Assume that each path through the pattern can be null until
3419 proven otherwise. We set this false at the bottom of switch
3420 statement, to which we get only if a particular path doesn't
3421 match the empty string. */
3422 boolean path_can_be_null = true;
3424 /* We aren't doing a `succeed_n' to begin with. */
3425 boolean succeed_n_p = false;
3427 assert (fastmap != NULL && p != NULL);
3430 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3431 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3432 bufp->can_be_null = 0;
3436 if (p == pend || *p == succeed)
3438 /* We have reached the (effective) end of pattern. */
3439 if (!FAIL_STACK_EMPTY ())
3441 bufp->can_be_null |= path_can_be_null;
3443 /* Reset for next path. */
3444 path_can_be_null = true;
3446 p = (unsigned char *) fail_stack.stack[--fail_stack.avail].pointer;
3454 /* We should never be about to go beyond the end of the pattern. */
3457 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3460 /* I guess the idea here is to simply not bother with a fastmap
3461 if a backreference is used, since it's too hard to figure out
3462 the fastmap for the corresponding group. Setting
3463 `can_be_null' stops `re_search_2' from using the fastmap, so
3464 that is all we do. */
3466 bufp->can_be_null = 1;
3470 /* Following are the cases which match a character. These end
3479 /* XEmacs: Under Mule, these bit vectors will
3480 only contain values for characters below 0x80. */
3481 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3482 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3488 /* Chars beyond end of map must be allowed. */
3490 for (j = *p * BYTEWIDTH; j < 0x80; j++)
3492 /* And all extended characters must be allowed, too. */
3493 for (j = 0x80; j < 0xA0; j++)
3495 #else /* not MULE */
3496 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3500 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3501 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3511 nentries = unified_range_table_nentries (p);
3512 for (i = 0; i < nentries; i++)
3514 EMACS_INT first, last;
3515 Lisp_Object dummy_val;
3517 Bufbyte strr[MAX_EMCHAR_LEN];
3519 unified_range_table_get_range (p, i, &first, &last,
3521 for (jj = first; jj <= last && jj < 0x80; jj++)
3523 /* Ranges below 0x100 can span charsets, but there
3524 are only two (Control-1 and Latin-1), and
3525 either first or last has to be in them. */
3526 set_charptr_emchar (strr, first);
3530 set_charptr_emchar (strr, last);
3537 case charset_mule_not:
3542 nentries = unified_range_table_nentries (p);
3543 for (i = 0; i < nentries; i++)
3545 EMACS_INT first, last;
3546 Lisp_Object dummy_val;
3548 int smallest_prev = 0;
3550 unified_range_table_get_range (p, i, &first, &last,
3552 for (jj = smallest_prev; jj < first && jj < 0x80; jj++)
3554 smallest_prev = last + 1;
3555 if (smallest_prev >= 0x80)
3558 /* Calculating which leading bytes are actually allowed
3559 here is rather difficult, so we just punt and allow
3561 for (i = 0x80; i < 0xA0; i++)
3573 for (j = 0; j < (1 << BYTEWIDTH); j++)
3576 (regex_emacs_buffer->mirror_syntax_table), j) == Sword)
3585 goto matchnotsyntax;
3587 for (j = 0; j < (1 << BYTEWIDTH); j++)
3590 (regex_emacs_buffer->mirror_syntax_table), j) != Sword)
3598 int fastmap_newline = fastmap['\n'];
3600 /* `.' matches anything ... */
3602 /* "anything" only includes bytes that can be the
3603 first byte of a character. */
3604 for (j = 0; j < 0xA0; j++)
3607 for (j = 0; j < (1 << BYTEWIDTH); j++)
3611 /* ... except perhaps newline. */
3612 if (!(bufp->syntax & RE_DOT_NEWLINE))
3613 fastmap['\n'] = fastmap_newline;
3615 /* Return if we have already set `can_be_null'; if we have,
3616 then the fastmap is irrelevant. Something's wrong here. */
3617 else if (bufp->can_be_null)
3620 /* Otherwise, have to check alternative paths. */
3630 for (j = 0; j < 0x80; j++)
3633 (regex_emacs_buffer->syntax_table), j) ==
3634 (enum syntaxcode) k)
3637 for (j = 0; j < 0x80; j++)
3640 (regex_emacs_buffer->mirror_syntax_table), j) ==
3641 (enum syntaxcode) k)
3644 for (j = 0x80; j < 0xA0; j++)
3647 if (LEADING_BYTE_PREFIX_P(j))
3648 /* too complicated to calculate this right */
3656 cset = CHARSET_BY_LEADING_BYTE (j);
3657 if (CHARSETP (cset))
3659 if (charset_syntax (regex_emacs_buffer, cset,
3661 == Sword || multi_p)
3668 #else /* not MULE */
3669 for (j = 0; j < (1 << BYTEWIDTH); j++)
3672 (regex_emacs_buffer->mirror_syntax_table), j) ==
3673 (enum syntaxcode) k)
3684 for (j = 0; j < 0x80; j++)
3687 (regex_emacs_buffer->syntax_table), j) !=
3688 (enum syntaxcode) k)
3691 for (j = 0; j < 0x80; j++)
3694 (regex_emacs_buffer->mirror_syntax_table), j) !=
3695 (enum syntaxcode) k)
3698 for (j = 0x80; j < 0xA0; j++)
3701 if (LEADING_BYTE_PREFIX_P(j))
3702 /* too complicated to calculate this right */
3710 cset = CHARSET_BY_LEADING_BYTE (j);
3711 if (CHARSETP (cset))
3713 if (charset_syntax (regex_emacs_buffer, cset,
3715 != Sword || multi_p)
3722 #else /* not MULE */
3723 for (j = 0; j < (1 << BYTEWIDTH); j++)
3726 (regex_emacs_buffer->mirror_syntax_table), j) !=
3727 (enum syntaxcode) k)
3733 /* 97/2/17 jhod category patch */
3735 case notcategoryspec:
3736 bufp->can_be_null = 1;
3738 /* end if category patch */
3741 /* All cases after this match the empty string. These end with
3749 #endif /* not emacs */
3761 case push_dummy_failure:
3766 case pop_failure_jump:
3767 case maybe_pop_jump:
3770 case dummy_failure_jump:
3771 EXTRACT_NUMBER_AND_INCR (j, p);
3776 /* Jump backward implies we just went through the body of a
3777 loop and matched nothing. Opcode jumped to should be
3778 `on_failure_jump' or `succeed_n'. Just treat it like an
3779 ordinary jump. For a * loop, it has pushed its failure
3780 point already; if so, discard that as redundant. */
3781 if ((re_opcode_t) *p != on_failure_jump
3782 && (re_opcode_t) *p != succeed_n)
3786 EXTRACT_NUMBER_AND_INCR (j, p);
3789 /* If what's on the stack is where we are now, pop it. */
3790 if (!FAIL_STACK_EMPTY ()
3791 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3797 case on_failure_jump:
3798 case on_failure_keep_string_jump:
3799 handle_on_failure_jump:
3800 EXTRACT_NUMBER_AND_INCR (j, p);
3802 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3803 end of the pattern. We don't want to push such a point,
3804 since when we restore it above, entering the switch will
3805 increment `p' past the end of the pattern. We don't need
3806 to push such a point since we obviously won't find any more
3807 fastmap entries beyond `pend'. Such a pattern can match
3808 the null string, though. */
3811 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3813 RESET_FAIL_STACK ();
3818 bufp->can_be_null = 1;
3822 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3823 succeed_n_p = false;
3830 /* Get to the number of times to succeed. */
3833 /* Increment p past the n for when k != 0. */
3834 EXTRACT_NUMBER_AND_INCR (k, p);
3838 succeed_n_p = true; /* Spaghetti code alert. */
3839 goto handle_on_failure_jump;
3856 abort (); /* We have listed all the cases. */
3859 /* Getting here means we have found the possible starting
3860 characters for one path of the pattern -- and that the empty
3861 string does not match. We need not follow this path further.
3862 Instead, look at the next alternative (remembered on the
3863 stack), or quit if no more. The test at the top of the loop
3864 does these things. */
3865 path_can_be_null = false;
3869 /* Set `can_be_null' for the last path (also the first path, if the
3870 pattern is empty). */
3871 bufp->can_be_null |= path_can_be_null;
3874 RESET_FAIL_STACK ();
3876 } /* re_compile_fastmap */
3878 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3879 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3880 this memory for recording register information. STARTS and ENDS
3881 must be allocated using the malloc library routine, and must each
3882 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3884 If NUM_REGS == 0, then subsequent matches should allocate their own
3887 Unless this function is called, the first search or match using
3888 PATTERN_BUFFER will allocate its own register data, without
3889 freeing the old data. */
3892 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs,
3893 unsigned num_regs, regoff_t *starts, regoff_t *ends)
3897 bufp->regs_allocated = REGS_REALLOCATE;
3898 regs->num_regs = num_regs;
3899 regs->start = starts;
3904 bufp->regs_allocated = REGS_UNALLOCATED;
3906 regs->start = regs->end = (regoff_t *) 0;
3910 /* Searching routines. */
3912 /* Like re_search_2, below, but only one string is specified, and
3913 doesn't let you say where to stop matching. */
3916 re_search (struct re_pattern_buffer *bufp, const char *string, int size,
3917 int startpos, int range, struct re_registers *regs)
3919 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3924 /* Snarfed from src/lisp.h, needed for compiling [ce]tags. */
3925 # define bytecount_to_charcount(ptr, len) (len)
3926 # define charcount_to_bytecount(ptr, len) (len)
3927 typedef int Charcount;
3930 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3931 virtual concatenation of STRING1 and STRING2, starting first at index
3932 STARTPOS, then at STARTPOS + 1, and so on.
3934 With MULE, STARTPOS is a byte position, not a char position. And the
3935 search will increment STARTPOS by the width of the current leading
3938 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3940 RANGE is how far to scan while trying to match. RANGE = 0 means try
3941 only at STARTPOS; in general, the last start tried is STARTPOS +
3944 With MULE, RANGE is a byte position, not a char position. The last
3945 start tried is the character starting <= STARTPOS + RANGE.
3947 In REGS, return the indices of the virtual concatenation of STRING1
3948 and STRING2 that matched the entire BUFP->buffer and its contained
3951 Do not consider matching one past the index STOP in the virtual
3952 concatenation of STRING1 and STRING2.
3954 We return either the position in the strings at which the match was
3955 found, -1 if no match, or -2 if error (such as failure
3959 re_search_2 (struct re_pattern_buffer *bufp, const char *str1,
3960 int size1, const char *str2, int size2, int startpos,
3961 int range, struct re_registers *regs, int stop)
3964 re_char *string1 = (re_char *) str1;
3965 re_char *string2 = (re_char *) str2;
3966 REGISTER char *fastmap = bufp->fastmap;
3967 REGISTER RE_TRANSLATE_TYPE translate = bufp->translate;
3968 int total_size = size1 + size2;
3969 int endpos = startpos + range;
3970 #ifdef REGEX_BEGLINE_CHECK
3971 int anchored_at_begline = 0;
3976 /* Check for out-of-range STARTPOS. */
3977 if (startpos < 0 || startpos > total_size)
3980 /* Fix up RANGE if it might eventually take us outside
3981 the virtual concatenation of STRING1 and STRING2. */
3983 range = 0 - startpos;
3984 else if (endpos > total_size)
3985 range = total_size - startpos;
3987 /* If the search isn't to be a backwards one, don't waste time in a
3988 search for a pattern that must be anchored. */
3989 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3995 d = ((const unsigned char *)
3996 (startpos >= size1 ? string2 - size1 : string1) + startpos);
3997 range = charcount_to_bytecount (d, 1);
4001 /* Update the fastmap now if not correct already. */
4002 if (fastmap && !bufp->fastmap_accurate)
4003 if (re_compile_fastmap (bufp) == -2)
4006 #ifdef REGEX_BEGLINE_CHECK
4010 while (i < bufp->used)
4012 if (bufp->buffer[i] == start_memory ||
4013 bufp->buffer[i] == stop_memory)
4018 anchored_at_begline = i < bufp->used && bufp->buffer[i] == begline;
4022 /* Loop through the string, looking for a place to start matching. */
4025 #ifdef REGEX_BEGLINE_CHECK
4026 /* If the regex is anchored at the beginning of a line (i.e. with a ^),
4027 then we can speed things up by skipping to the next beginning-of-
4029 if (anchored_at_begline && startpos > 0 && startpos != size1 &&
4032 /* whose stupid idea was it anyway to make this
4033 function take two strings to match?? */
4037 if (startpos < size1 && startpos + range >= size1)
4038 lim = range - (size1 - startpos);
4040 d = ((const unsigned char *)
4041 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4042 DEC_CHARPTR(d); /* Ok, since startpos != size1. */
4043 d_size = charcount_to_bytecount (d, 1);
4045 if (TRANSLATE_P (translate))
4046 while (range > lim && *d != '\n')
4048 d += d_size; /* Speedier INC_CHARPTR(d) */
4049 d_size = charcount_to_bytecount (d, 1);
4053 while (range > lim && *d != '\n')
4055 d += d_size; /* Speedier INC_CHARPTR(d) */
4056 d_size = charcount_to_bytecount (d, 1);
4060 startpos += irange - range;
4062 #endif /* REGEX_BEGLINE_CHECK */
4064 /* If a fastmap is supplied, skip quickly over characters that
4065 cannot be the start of a match. If the pattern can match the
4066 null string, however, we don't need to skip characters; we want
4067 the first null string. */
4068 if (fastmap && startpos < total_size && !bufp->can_be_null)
4070 if (range > 0) /* Searching forwards. */
4075 if (startpos < size1 && startpos + range >= size1)
4076 lim = range - (size1 - startpos);
4078 d = ((const unsigned char *)
4079 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4081 /* Written out as an if-else to avoid testing `translate'
4083 if (TRANSLATE_P (translate))
4089 buf_ch = charptr_emchar (d);
4090 buf_ch = RE_TRANSLATE (buf_ch);
4091 if (buf_ch >= 0200 || fastmap[(unsigned char) buf_ch])
4094 if (fastmap[(unsigned char)RE_TRANSLATE (*d)])
4097 d_size = charcount_to_bytecount (d, 1);
4099 d += d_size; /* Speedier INC_CHARPTR(d) */
4102 while (range > lim && !fastmap[*d])
4104 d_size = charcount_to_bytecount (d, 1);
4106 d += d_size; /* Speedier INC_CHARPTR(d) */
4109 startpos += irange - range;
4111 else /* Searching backwards. */
4113 Emchar c = (size1 == 0 || startpos >= size1
4114 ? charptr_emchar (string2 + startpos - size1)
4115 : charptr_emchar (string1 + startpos));
4118 if (!(c >= 0200 || fastmap[(unsigned char) c]))
4121 if (!fastmap[(unsigned char) c])
4127 /* If can't match the null string, and that's all we have left, fail. */
4128 if (range >= 0 && startpos == total_size && fastmap
4129 && !bufp->can_be_null)
4132 #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
4133 if (!no_quit_in_re_search)
4136 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4137 startpos, regs, stop);
4138 #ifndef REGEX_MALLOC
4155 d = ((const unsigned char *)
4156 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4157 d_size = charcount_to_bytecount (d, 1);
4163 /* Note startpos > size1 not >=. If we are on the
4164 string1/string2 boundary, we want to backup into string1. */
4165 d = ((const unsigned char *)
4166 (startpos > size1 ? string2 - size1 : string1) + startpos);
4168 d_size = charcount_to_bytecount (d, 1);
4176 /* Declarations and macros for re_match_2. */
4178 /* This converts PTR, a pointer into one of the search strings `string1'
4179 and `string2' into an offset from the beginning of that string. */
4180 #define POINTER_TO_OFFSET(ptr) \
4181 (FIRST_STRING_P (ptr) \
4182 ? ((regoff_t) ((ptr) - string1)) \
4183 : ((regoff_t) ((ptr) - string2 + size1)))
4185 /* Macros for dealing with the split strings in re_match_2. */
4187 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
4189 /* Call before fetching a character with *d. This switches over to
4190 string2 if necessary. */
4191 #define REGEX_PREFETCH() \
4194 /* End of string2 => fail. */ \
4195 if (dend == end_match_2) \
4197 /* End of string1 => advance to string2. */ \
4199 dend = end_match_2; \
4203 /* Test if at very beginning or at very end of the virtual concatenation
4204 of `string1' and `string2'. If only one string, it's `string2'. */
4205 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4206 #define AT_STRINGS_END(d) ((d) == end2)
4209 If the given position straddles the string gap, return the equivalent
4210 position that is before or after the gap, respectively; otherwise,
4211 return the same position. */
4212 #define POS_BEFORE_GAP_UNSAFE(d) ((d) == string2 ? end1 : (d))
4213 #define POS_AFTER_GAP_UNSAFE(d) ((d) == end1 ? string2 : (d))
4215 /* Test if CH is a word-constituent character. (XEmacs change) */
4217 #define WORDCHAR_P_UNSAFE(ch) \
4218 (SYNTAX_UNSAFE (XCHAR_TABLE (regex_emacs_buffer->syntax_table), \
4221 #define WORDCHAR_P_UNSAFE(ch) \
4222 (SYNTAX_UNSAFE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table), \
4226 /* Free everything we malloc. */
4227 #ifdef MATCH_MAY_ALLOCATE
4228 #define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
4229 #define FREE_VARIABLES() \
4231 REGEX_FREE_STACK (fail_stack.stack); \
4232 FREE_VAR (regstart); \
4233 FREE_VAR (regend); \
4234 FREE_VAR (old_regstart); \
4235 FREE_VAR (old_regend); \
4236 FREE_VAR (best_regstart); \
4237 FREE_VAR (best_regend); \
4238 FREE_VAR (reg_info); \
4239 FREE_VAR (reg_dummy); \
4240 FREE_VAR (reg_info_dummy); \
4242 #else /* not MATCH_MAY_ALLOCATE */
4243 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4244 #endif /* MATCH_MAY_ALLOCATE */
4246 /* These values must meet several constraints. They must not be valid
4247 register values; since we have a limit of 255 registers (because
4248 we use only one byte in the pattern for the register number), we can
4249 use numbers larger than 255. They must differ by 1, because of
4250 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4251 be larger than the value for the highest register, so we do not try
4252 to actually save any registers when none are active. */
4253 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4254 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4256 /* Matching routines. */
4258 #ifndef emacs /* Emacs never uses this. */
4259 /* re_match is like re_match_2 except it takes only a single string. */
4262 re_match (struct re_pattern_buffer *bufp, const char *string, int size,
4263 int pos, struct re_registers *regs)
4265 int result = re_match_2_internal (bufp, NULL, 0, (re_char *) string, size,
4270 #endif /* not emacs */
4273 /* re_match_2 matches the compiled pattern in BUFP against the
4274 (virtual) concatenation of STRING1 and STRING2 (of length SIZE1 and
4275 SIZE2, respectively). We start matching at POS, and stop matching
4278 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4279 store offsets for the substring each group matched in REGS. See the
4280 documentation for exactly how many groups we fill.
4282 We return -1 if no match, -2 if an internal error (such as the
4283 failure stack overflowing). Otherwise, we return the length of the
4284 matched substring. */
4287 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4288 int size1, const char *string2, int size2, int pos,
4289 struct re_registers *regs, int stop)
4291 int result = re_match_2_internal (bufp, (re_char *) string1, size1,
4292 (re_char *) string2, size2,
4298 /* This is a separate function so that we can force an alloca cleanup
4301 re_match_2_internal (struct re_pattern_buffer *bufp, re_char *string1,
4302 int size1, re_char *string2, int size2, int pos,
4303 struct re_registers *regs, int stop)
4305 /* General temporaries. */
4308 int should_succeed; /* XEmacs change */
4310 /* Just past the end of the corresponding string. */
4311 re_char *end1, *end2;
4313 /* Pointers into string1 and string2, just past the last characters in
4314 each to consider matching. */
4315 re_char *end_match_1, *end_match_2;
4317 /* Where we are in the data, and the end of the current string. */
4320 /* Where we are in the pattern, and the end of the pattern. */
4321 unsigned char *p = bufp->buffer;
4322 REGISTER unsigned char *pend = p + bufp->used;
4324 /* Mark the opcode just after a start_memory, so we can test for an
4325 empty subpattern when we get to the stop_memory. */
4326 re_char *just_past_start_mem = 0;
4328 /* We use this to map every character in the string. */
4329 RE_TRANSLATE_TYPE translate = bufp->translate;
4331 /* Failure point stack. Each place that can handle a failure further
4332 down the line pushes a failure point on this stack. It consists of
4333 restart, regend, and reg_info for all registers corresponding to
4334 the subexpressions we're currently inside, plus the number of such
4335 registers, and, finally, two char *'s. The first char * is where
4336 to resume scanning the pattern; the second one is where to resume
4337 scanning the strings. If the latter is zero, the failure point is
4338 a ``dummy''; if a failure happens and the failure point is a dummy,
4339 it gets discarded and the next one is tried. */
4340 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4341 fail_stack_type fail_stack;
4344 static unsigned failure_id;
4345 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4349 /* This holds the pointer to the failure stack, when
4350 it is allocated relocatably. */
4351 fail_stack_elt_t *failure_stack_ptr;
4354 /* We fill all the registers internally, independent of what we
4355 return, for use in backreferences. The number here includes
4356 an element for register zero. */
4357 unsigned num_regs = bufp->re_nsub + 1;
4359 /* The currently active registers. */
4360 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4361 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4363 /* Information on the contents of registers. These are pointers into
4364 the input strings; they record just what was matched (on this
4365 attempt) by a subexpression part of the pattern, that is, the
4366 regnum-th regstart pointer points to where in the pattern we began
4367 matching and the regnum-th regend points to right after where we
4368 stopped matching the regnum-th subexpression. (The zeroth register
4369 keeps track of what the whole pattern matches.) */
4370 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4371 re_char **regstart, **regend;
4374 /* If a group that's operated upon by a repetition operator fails to
4375 match anything, then the register for its start will need to be
4376 restored because it will have been set to wherever in the string we
4377 are when we last see its open-group operator. Similarly for a
4379 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4380 re_char **old_regstart, **old_regend;
4383 /* The is_active field of reg_info helps us keep track of which (possibly
4384 nested) subexpressions we are currently in. The matched_something
4385 field of reg_info[reg_num] helps us tell whether or not we have
4386 matched any of the pattern so far this time through the reg_num-th
4387 subexpression. These two fields get reset each time through any
4388 loop their register is in. */
4389 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4390 register_info_type *reg_info;
4393 /* The following record the register info as found in the above
4394 variables when we find a match better than any we've seen before.
4395 This happens as we backtrack through the failure points, which in
4396 turn happens only if we have not yet matched the entire string. */
4397 unsigned best_regs_set = false;
4398 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4399 re_char **best_regstart, **best_regend;
4402 /* Logically, this is `best_regend[0]'. But we don't want to have to
4403 allocate space for that if we're not allocating space for anything
4404 else (see below). Also, we never need info about register 0 for
4405 any of the other register vectors, and it seems rather a kludge to
4406 treat `best_regend' differently than the rest. So we keep track of
4407 the end of the best match so far in a separate variable. We
4408 initialize this to NULL so that when we backtrack the first time
4409 and need to test it, it's not garbage. */
4410 re_char *match_end = NULL;
4412 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4413 int set_regs_matched_done = 0;
4415 /* Used when we pop values we don't care about. */
4416 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4417 re_char **reg_dummy;
4418 register_info_type *reg_info_dummy;
4422 /* Counts the total number of registers pushed. */
4423 unsigned num_regs_pushed = 0;
4426 /* 1 if this match ends in the same string (string1 or string2)
4427 as the best previous match. */
4430 /* 1 if this match is the best seen so far. */
4431 boolean best_match_p;
4433 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4437 #ifdef MATCH_MAY_ALLOCATE
4438 /* Do not bother to initialize all the register variables if there are
4439 no groups in the pattern, as it takes a fair amount of time. If
4440 there are groups, we include space for register 0 (the whole
4441 pattern), even though we never use it, since it simplifies the
4442 array indexing. We should fix this. */
4445 regstart = REGEX_TALLOC (num_regs, re_char *);
4446 regend = REGEX_TALLOC (num_regs, re_char *);
4447 old_regstart = REGEX_TALLOC (num_regs, re_char *);
4448 old_regend = REGEX_TALLOC (num_regs, re_char *);
4449 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4450 best_regend = REGEX_TALLOC (num_regs, re_char *);
4451 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4452 reg_dummy = REGEX_TALLOC (num_regs, re_char *);
4453 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4455 if (!(regstart && regend && old_regstart && old_regend && reg_info
4456 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4464 /* We must initialize all our variables to NULL, so that
4465 `FREE_VARIABLES' doesn't try to free them. */
4466 regstart = regend = old_regstart = old_regend = best_regstart
4467 = best_regend = reg_dummy = NULL;
4468 reg_info = reg_info_dummy = (register_info_type *) NULL;
4470 #endif /* MATCH_MAY_ALLOCATE */
4472 /* The starting position is bogus. */
4473 if (pos < 0 || pos > size1 + size2)
4479 /* Initialize subexpression text positions to -1 to mark ones that no
4480 start_memory/stop_memory has been seen for. Also initialize the
4481 register information struct. */
4482 for (mcnt = 1; mcnt < num_regs; mcnt++)
4484 regstart[mcnt] = regend[mcnt]
4485 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4487 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4488 IS_ACTIVE (reg_info[mcnt]) = 0;
4489 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4490 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4492 /* We move `string1' into `string2' if the latter's empty -- but not if
4493 `string1' is null. */
4494 if (size2 == 0 && string1 != NULL)
4501 end1 = string1 + size1;
4502 end2 = string2 + size2;
4504 /* Compute where to stop matching, within the two strings. */
4507 end_match_1 = string1 + stop;
4508 end_match_2 = string2;
4513 end_match_2 = string2 + stop - size1;
4516 /* `p' scans through the pattern as `d' scans through the data.
4517 `dend' is the end of the input string that `d' points within. `d'
4518 is advanced into the following input string whenever necessary, but
4519 this happens before fetching; therefore, at the beginning of the
4520 loop, `d' can be pointing at the end of a string, but it cannot
4522 if (size1 > 0 && pos <= size1)
4529 d = string2 + pos - size1;
4533 DEBUG_PRINT1 ("The compiled pattern is: \n");
4534 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4535 DEBUG_PRINT1 ("The string to match is: `");
4536 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4537 DEBUG_PRINT1 ("'\n");
4539 /* This loops over pattern commands. It exits by returning from the
4540 function if the match is complete, or it drops through if the match
4541 fails at this starting point in the input data. */
4544 DEBUG_PRINT2 ("\n0x%lx: ", (long) p);
4545 #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
4546 if (!no_quit_in_re_search)
4551 { /* End of pattern means we might have succeeded. */
4552 DEBUG_PRINT1 ("end of pattern ... ");
4554 /* If we haven't matched the entire string, and we want the
4555 longest match, try backtracking. */
4556 if (d != end_match_2)
4558 same_str_p = (FIRST_STRING_P (match_end)
4559 == MATCHING_IN_FIRST_STRING);
4561 /* AIX compiler got confused when this was combined
4562 with the previous declaration. */
4564 best_match_p = d > match_end;
4566 best_match_p = !MATCHING_IN_FIRST_STRING;
4568 DEBUG_PRINT1 ("backtracking.\n");
4570 if (!FAIL_STACK_EMPTY ())
4571 { /* More failure points to try. */
4573 /* If exceeds best match so far, save it. */
4574 if (!best_regs_set || best_match_p)
4576 best_regs_set = true;
4579 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4581 for (mcnt = 1; mcnt < num_regs; mcnt++)
4583 best_regstart[mcnt] = regstart[mcnt];
4584 best_regend[mcnt] = regend[mcnt];
4590 /* If no failure points, don't restore garbage. And if
4591 last match is real best match, don't restore second
4593 else if (best_regs_set && !best_match_p)
4596 /* Restore best match. It may happen that `dend ==
4597 end_match_1' while the restored d is in string2.
4598 For example, the pattern `x.*y.*z' against the
4599 strings `x-' and `y-z-', if the two strings are
4600 not consecutive in memory. */
4601 DEBUG_PRINT1 ("Restoring best registers.\n");
4604 dend = ((d >= string1 && d <= end1)
4605 ? end_match_1 : end_match_2);
4607 for (mcnt = 1; mcnt < num_regs; mcnt++)
4609 regstart[mcnt] = best_regstart[mcnt];
4610 regend[mcnt] = best_regend[mcnt];
4613 } /* d != end_match_2 */
4616 DEBUG_PRINT1 ("Accepting match.\n");
4618 /* If caller wants register contents data back, do it. */
4619 if (regs && !bufp->no_sub)
4621 /* Have the register data arrays been allocated? */
4622 if (bufp->regs_allocated == REGS_UNALLOCATED)
4623 { /* No. So allocate them with malloc. We need one
4624 extra element beyond `num_regs' for the `-1' marker
4626 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4627 regs->start = TALLOC (regs->num_regs, regoff_t);
4628 regs->end = TALLOC (regs->num_regs, regoff_t);
4629 if (regs->start == NULL || regs->end == NULL)
4634 bufp->regs_allocated = REGS_REALLOCATE;
4636 else if (bufp->regs_allocated == REGS_REALLOCATE)
4637 { /* Yes. If we need more elements than were already
4638 allocated, reallocate them. If we need fewer, just
4640 if (regs->num_regs < num_regs + 1)
4642 regs->num_regs = num_regs + 1;
4643 RETALLOC (regs->start, regs->num_regs, regoff_t);
4644 RETALLOC (regs->end, regs->num_regs, regoff_t);
4645 if (regs->start == NULL || regs->end == NULL)
4654 /* These braces fend off a "empty body in an else-statement"
4655 warning under GCC when assert expands to nothing. */
4656 assert (bufp->regs_allocated == REGS_FIXED);
4659 /* Convert the pointer data in `regstart' and `regend' to
4660 indices. Register zero has to be set differently,
4661 since we haven't kept track of any info for it. */
4662 if (regs->num_regs > 0)
4664 regs->start[0] = pos;
4665 regs->end[0] = (MATCHING_IN_FIRST_STRING
4666 ? ((regoff_t) (d - string1))
4667 : ((regoff_t) (d - string2 + size1)));
4670 /* Go through the first `min (num_regs, regs->num_regs)'
4671 registers, since that is all we initialized. */
4672 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4674 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4675 regs->start[mcnt] = regs->end[mcnt] = -1;
4679 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4681 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4685 /* If the regs structure we return has more elements than
4686 were in the pattern, set the extra elements to -1. If
4687 we (re)allocated the registers, this is the case,
4688 because we always allocate enough to have at least one
4690 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4691 regs->start[mcnt] = regs->end[mcnt] = -1;
4692 } /* regs && !bufp->no_sub */
4694 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4695 nfailure_points_pushed, nfailure_points_popped,
4696 nfailure_points_pushed - nfailure_points_popped);
4697 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4699 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4703 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4709 /* Otherwise match next pattern command. */
4710 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4712 /* Ignore these. Used to ignore the n of succeed_n's which
4713 currently have n == 0. */
4715 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4719 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4722 /* Match the next n pattern characters exactly. The following
4723 byte in the pattern defines n, and the n bytes after that
4724 are the characters to match. */
4727 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4729 /* This is written out as an if-else so we don't waste time
4730 testing `translate' inside the loop. */
4731 if (TRANSLATE_P (translate))
4736 Emchar pat_ch, buf_ch;
4740 pat_ch = charptr_emchar (p);
4741 buf_ch = charptr_emchar (d);
4742 if (RE_TRANSLATE (buf_ch) != pat_ch)
4745 pat_len = charcount_to_bytecount (p, 1);
4750 #else /* not MULE */
4752 if ((unsigned char) RE_TRANSLATE (*d++) != *p++)
4764 if (*d++ != *p++) goto fail;
4768 SET_REGS_MATCHED ();
4772 /* Match any character except possibly a newline or a null. */
4774 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4778 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4779 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4782 SET_REGS_MATCHED ();
4783 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4784 INC_CHARPTR (d); /* XEmacs change */
4791 REGISTER unsigned char c;
4792 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4794 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4797 c = TRANSLATE (*d); /* The character to match. */
4799 /* Cast to `unsigned' instead of `unsigned char' in case the
4800 bit list is a full 32 bytes long. */
4801 if (c < (unsigned) (*p * BYTEWIDTH)
4802 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4807 if (!not) goto fail;
4809 SET_REGS_MATCHED ();
4810 INC_CHARPTR (d); /* XEmacs change */
4816 case charset_mule_not:
4819 boolean not = (re_opcode_t) *(p - 1) == charset_mule_not;
4821 DEBUG_PRINT2 ("EXECUTING charset_mule%s.\n", not ? "_not" : "");
4824 c = charptr_emchar ((const Bufbyte *) d);
4825 c = TRANSLATE_EXTENDED_UNSAFE (c); /* The character to match. */
4827 if (EQ (Qt, unified_range_table_lookup (p, c, Qnil)))
4830 p += unified_range_table_bytes_used (p);
4832 if (!not) goto fail;
4834 SET_REGS_MATCHED ();
4841 /* The beginning of a group is represented by start_memory.
4842 The arguments are the register number in the next byte, and the
4843 number of groups inner to this one in the next. The text
4844 matched within the group is recorded (in the internal
4845 registers data structure) under the register number. */
4847 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4849 /* Find out if this group can match the empty string. */
4850 p1 = p; /* To send to group_match_null_string_p. */
4852 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4853 REG_MATCH_NULL_STRING_P (reg_info[*p])
4854 = group_match_null_string_p (&p1, pend, reg_info);
4856 /* Save the position in the string where we were the last time
4857 we were at this open-group operator in case the group is
4858 operated upon by a repetition operator, e.g., with `(a*)*b'
4859 against `ab'; then we want to ignore where we are now in
4860 the string in case this attempt to match fails. */
4861 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4862 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4864 DEBUG_PRINT2 (" old_regstart: %d\n",
4865 POINTER_TO_OFFSET (old_regstart[*p]));
4868 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4870 IS_ACTIVE (reg_info[*p]) = 1;
4871 MATCHED_SOMETHING (reg_info[*p]) = 0;
4873 /* Clear this whenever we change the register activity status. */
4874 set_regs_matched_done = 0;
4876 /* This is the new highest active register. */
4877 highest_active_reg = *p;
4879 /* If nothing was active before, this is the new lowest active
4881 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4882 lowest_active_reg = *p;
4884 /* Move past the register number and inner group count. */
4886 just_past_start_mem = p;
4891 /* The stop_memory opcode represents the end of a group. Its
4892 arguments are the same as start_memory's: the register
4893 number, and the number of inner groups. */
4895 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4897 /* We need to save the string position the last time we were at
4898 this close-group operator in case the group is operated
4899 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4900 against `aba'; then we want to ignore where we are now in
4901 the string in case this attempt to match fails. */
4902 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4903 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4905 DEBUG_PRINT2 (" old_regend: %d\n",
4906 POINTER_TO_OFFSET (old_regend[*p]));
4909 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4911 /* This register isn't active anymore. */
4912 IS_ACTIVE (reg_info[*p]) = 0;
4914 /* Clear this whenever we change the register activity status. */
4915 set_regs_matched_done = 0;
4917 /* If this was the only register active, nothing is active
4919 if (lowest_active_reg == highest_active_reg)
4921 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4922 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4925 { /* We must scan for the new highest active register, since
4926 it isn't necessarily one less than now: consider
4927 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4928 new highest active register is 1. */
4929 unsigned char r = *p - 1;
4930 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4933 /* If we end up at register zero, that means that we saved
4934 the registers as the result of an `on_failure_jump', not
4935 a `start_memory', and we jumped to past the innermost
4936 `stop_memory'. For example, in ((.)*) we save
4937 registers 1 and 2 as a result of the *, but when we pop
4938 back to the second ), we are at the stop_memory 1.
4939 Thus, nothing is active. */
4942 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4943 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4947 highest_active_reg = r;
4949 /* 98/9/21 jhod: We've also gotta set lowest_active_reg, don't we? */
4951 while (r < highest_active_reg && !IS_ACTIVE(reg_info[r]))
4953 lowest_active_reg = r;
4957 /* If just failed to match something this time around with a
4958 group that's operated on by a repetition operator, try to
4959 force exit from the ``loop'', and restore the register
4960 information for this group that we had before trying this
4962 if ((!MATCHED_SOMETHING (reg_info[*p])
4963 || just_past_start_mem == p - 1)
4966 boolean is_a_jump_n = false;
4970 switch ((re_opcode_t) *p1++)
4974 case pop_failure_jump:
4975 case maybe_pop_jump:
4977 case dummy_failure_jump:
4978 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4988 /* If the next operation is a jump backwards in the pattern
4989 to an on_failure_jump right before the start_memory
4990 corresponding to this stop_memory, exit from the loop
4991 by forcing a failure after pushing on the stack the
4992 on_failure_jump's jump in the pattern, and d. */
4993 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4994 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4996 /* If this group ever matched anything, then restore
4997 what its registers were before trying this last
4998 failed match, e.g., with `(a*)*b' against `ab' for
4999 regstart[1], and, e.g., with `((a*)*(b*)*)*'
5000 against `aba' for regend[3].
5002 Also restore the registers for inner groups for,
5003 e.g., `((a*)(b*))*' against `aba' (register 3 would
5004 otherwise get trashed). */
5006 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
5010 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
5012 /* Restore this and inner groups' (if any) registers. */
5013 for (r = *p; r < *p + *(p + 1); r++)
5015 regstart[r] = old_regstart[r];
5017 /* xx why this test? */
5018 if (old_regend[r] >= regstart[r])
5019 regend[r] = old_regend[r];
5023 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5024 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
5030 /* Move past the register number and the inner group count. */
5035 /* \<digit> has been turned into a `duplicate' command which is
5036 followed by the numeric value of <digit> as the register number. */
5039 REGISTER re_char *d2, *dend2;
5040 int regno = *p++; /* Get which register to match against. */
5041 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5043 /* Can't back reference a group which we've never matched. */
5044 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5047 /* Where in input to try to start matching. */
5048 d2 = regstart[regno];
5050 /* Where to stop matching; if both the place to start and
5051 the place to stop matching are in the same string, then
5052 set to the place to stop, otherwise, for now have to use
5053 the end of the first string. */
5055 dend2 = ((FIRST_STRING_P (regstart[regno])
5056 == FIRST_STRING_P (regend[regno]))
5057 ? regend[regno] : end_match_1);
5060 /* If necessary, advance to next segment in register
5064 if (dend2 == end_match_2) break;
5065 if (dend2 == regend[regno]) break;
5067 /* End of string1 => advance to string2. */
5069 dend2 = regend[regno];
5071 /* At end of register contents => success */
5072 if (d2 == dend2) break;
5074 /* If necessary, advance to next segment in data. */
5077 /* How many characters left in this segment to match. */
5080 /* Want how many consecutive characters we can match in
5081 one shot, so, if necessary, adjust the count. */
5082 if (mcnt > dend2 - d2)
5085 /* Compare that many; failure if mismatch, else move
5087 if (TRANSLATE_P (translate)
5088 ? bcmp_translate ((unsigned char *) d,
5089 (unsigned char *) d2, mcnt, translate)
5090 : memcmp (d, d2, mcnt))
5092 d += mcnt, d2 += mcnt;
5094 /* Do this because we've match some characters. */
5095 SET_REGS_MATCHED ();
5101 /* begline matches the empty string at the beginning of the string
5102 (unless `not_bol' is set in `bufp'), and, if
5103 `newline_anchor' is set, after newlines. */
5105 DEBUG_PRINT1 ("EXECUTING begline.\n");
5107 if (AT_STRINGS_BEG (d))
5109 if (!bufp->not_bol) break;
5111 else if (d[-1] == '\n' && bufp->newline_anchor)
5115 /* In all other cases, we fail. */
5119 /* endline is the dual of begline. */
5121 DEBUG_PRINT1 ("EXECUTING endline.\n");
5123 if (AT_STRINGS_END (d))
5125 if (!bufp->not_eol) break;
5128 /* We have to ``prefetch'' the next character. */
5129 else if ((d == end1 ? *string2 : *d) == '\n'
5130 && bufp->newline_anchor)
5137 /* Match at the very beginning of the data. */
5139 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5140 if (AT_STRINGS_BEG (d))
5145 /* Match at the very end of the data. */
5147 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5148 if (AT_STRINGS_END (d))
5153 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5154 pushes NULL as the value for the string on the stack. Then
5155 `pop_failure_point' will keep the current value for the
5156 string, instead of restoring it. To see why, consider
5157 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5158 then the . fails against the \n. But the next thing we want
5159 to do is match the \n against the \n; if we restored the
5160 string value, we would be back at the foo.
5162 Because this is used only in specific cases, we don't need to
5163 check all the things that `on_failure_jump' does, to make
5164 sure the right things get saved on the stack. Hence we don't
5165 share its code. The only reason to push anything on the
5166 stack at all is that otherwise we would have to change
5167 `anychar's code to do something besides goto fail in this
5168 case; that seems worse than this. */
5169 case on_failure_keep_string_jump:
5170 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
5172 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5173 DEBUG_PRINT3 (" %d (to 0x%lx):\n", mcnt, (long) (p + mcnt));
5175 PUSH_FAILURE_POINT (p + mcnt, (unsigned char *) 0, -2);
5179 /* Uses of on_failure_jump:
5181 Each alternative starts with an on_failure_jump that points
5182 to the beginning of the next alternative. Each alternative
5183 except the last ends with a jump that in effect jumps past
5184 the rest of the alternatives. (They really jump to the
5185 ending jump of the following alternative, because tensioning
5186 these jumps is a hassle.)
5188 Repeats start with an on_failure_jump that points past both
5189 the repetition text and either the following jump or
5190 pop_failure_jump back to this on_failure_jump. */
5191 case on_failure_jump:
5193 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
5195 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5196 DEBUG_PRINT3 (" %d (to 0x%lx)", mcnt, (long) (p + mcnt));
5198 /* If this on_failure_jump comes right before a group (i.e.,
5199 the original * applied to a group), save the information
5200 for that group and all inner ones, so that if we fail back
5201 to this point, the group's information will be correct.
5202 For example, in \(a*\)*\1, we need the preceding group,
5203 and in \(\(a*\)b*\)\2, we need the inner group. */
5205 /* We can't use `p' to check ahead because we push
5206 a failure point to `p + mcnt' after we do this. */
5209 /* We need to skip no_op's before we look for the
5210 start_memory in case this on_failure_jump is happening as
5211 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5213 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5216 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5218 /* We have a new highest active register now. This will
5219 get reset at the start_memory we are about to get to,
5220 but we will have saved all the registers relevant to
5221 this repetition op, as described above. */
5222 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5223 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5224 lowest_active_reg = *(p1 + 1);
5227 DEBUG_PRINT1 (":\n");
5228 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5232 /* A smart repeat ends with `maybe_pop_jump'.
5233 We change it to either `pop_failure_jump' or `jump'. */
5234 case maybe_pop_jump:
5235 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5236 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5238 REGISTER unsigned char *p2 = p;
5240 /* Compare the beginning of the repeat with what in the
5241 pattern follows its end. If we can establish that there
5242 is nothing that they would both match, i.e., that we
5243 would have to backtrack because of (as in, e.g., `a*a')
5244 then we can change to pop_failure_jump, because we'll
5245 never have to backtrack.
5247 This is not true in the case of alternatives: in
5248 `(a|ab)*' we do need to backtrack to the `ab' alternative
5249 (e.g., if the string was `ab'). But instead of trying to
5250 detect that here, the alternative has put on a dummy
5251 failure point which is what we will end up popping. */
5253 /* Skip over open/close-group commands.
5254 If what follows this loop is a ...+ construct,
5255 look at what begins its body, since we will have to
5256 match at least one of that. */
5260 && ((re_opcode_t) *p2 == stop_memory
5261 || (re_opcode_t) *p2 == start_memory))
5263 else if (p2 + 6 < pend
5264 && (re_opcode_t) *p2 == dummy_failure_jump)
5271 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5272 to the `maybe_finalize_jump' of this case. Examine what
5275 /* If we're at the end of the pattern, we can change. */
5278 /* Consider what happens when matching ":\(.*\)"
5279 against ":/". I don't really understand this code
5281 p[-3] = (unsigned char) pop_failure_jump;
5283 (" End of pattern: change to `pop_failure_jump'.\n");
5286 else if ((re_opcode_t) *p2 == exactn
5287 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5289 REGISTER unsigned char c
5290 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5292 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
5294 p[-3] = (unsigned char) pop_failure_jump;
5295 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5299 else if ((re_opcode_t) p1[3] == charset
5300 || (re_opcode_t) p1[3] == charset_not)
5302 int not = (re_opcode_t) p1[3] == charset_not;
5304 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
5305 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5308 /* `not' is equal to 1 if c would match, which means
5309 that we can't change to pop_failure_jump. */
5312 p[-3] = (unsigned char) pop_failure_jump;
5313 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5317 else if ((re_opcode_t) *p2 == charset)
5320 REGISTER unsigned char c
5321 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5324 if ((re_opcode_t) p1[3] == exactn
5325 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
5326 && (p2[2 + p1[5] / BYTEWIDTH]
5327 & (1 << (p1[5] % BYTEWIDTH)))))
5329 p[-3] = (unsigned char) pop_failure_jump;
5330 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5334 else if ((re_opcode_t) p1[3] == charset_not)
5337 /* We win if the charset_not inside the loop
5338 lists every character listed in the charset after. */
5339 for (idx = 0; idx < (int) p2[1]; idx++)
5340 if (! (p2[2 + idx] == 0
5341 || (idx < (int) p1[4]
5342 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5347 p[-3] = (unsigned char) pop_failure_jump;
5348 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5351 else if ((re_opcode_t) p1[3] == charset)
5354 /* We win if the charset inside the loop
5355 has no overlap with the one after the loop. */
5357 idx < (int) p2[1] && idx < (int) p1[4];
5359 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5362 if (idx == p2[1] || idx == p1[4])
5364 p[-3] = (unsigned char) pop_failure_jump;
5365 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5370 p -= 2; /* Point at relative address again. */
5371 if ((re_opcode_t) p[-1] != pop_failure_jump)
5373 p[-1] = (unsigned char) jump;
5374 DEBUG_PRINT1 (" Match => jump.\n");
5375 goto unconditional_jump;
5377 /* Note fall through. */
5380 /* The end of a simple repeat has a pop_failure_jump back to
5381 its matching on_failure_jump, where the latter will push a
5382 failure point. The pop_failure_jump takes off failure
5383 points put on by this pop_failure_jump's matching
5384 on_failure_jump; we got through the pattern to here from the
5385 matching on_failure_jump, so didn't fail. */
5386 case pop_failure_jump:
5388 /* We need to pass separate storage for the lowest and
5389 highest registers, even though we don't care about the
5390 actual values. Otherwise, we will restore only one
5391 register from the stack, since lowest will == highest in
5392 `pop_failure_point'. */
5393 unsigned dummy_low_reg, dummy_high_reg;
5394 unsigned char *pdummy;
5395 re_char *sdummy = NULL;
5397 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5398 POP_FAILURE_POINT (sdummy, pdummy,
5399 dummy_low_reg, dummy_high_reg,
5400 reg_dummy, reg_dummy, reg_info_dummy);
5402 /* Note fall through. */
5405 /* Unconditionally jump (without popping any failure points). */
5408 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5409 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5410 p += mcnt; /* Do the jump. */
5411 DEBUG_PRINT2 ("(to 0x%lx).\n", (long) p);
5415 /* We need this opcode so we can detect where alternatives end
5416 in `group_match_null_string_p' et al. */
5418 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5419 goto unconditional_jump;
5422 /* Normally, the on_failure_jump pushes a failure point, which
5423 then gets popped at pop_failure_jump. We will end up at
5424 pop_failure_jump, also, and with a pattern of, say, `a+', we
5425 are skipping over the on_failure_jump, so we have to push
5426 something meaningless for pop_failure_jump to pop. */
5427 case dummy_failure_jump:
5428 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5429 /* It doesn't matter what we push for the string here. What
5430 the code at `fail' tests is the value for the pattern. */
5431 PUSH_FAILURE_POINT ((unsigned char *) 0, (unsigned char *) 0, -2);
5432 goto unconditional_jump;
5435 /* At the end of an alternative, we need to push a dummy failure
5436 point in case we are followed by a `pop_failure_jump', because
5437 we don't want the failure point for the alternative to be
5438 popped. For example, matching `(a|ab)*' against `aab'
5439 requires that we match the `ab' alternative. */
5440 case push_dummy_failure:
5441 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5442 /* See comments just above at `dummy_failure_jump' about the
5444 PUSH_FAILURE_POINT ((unsigned char *) 0, (unsigned char *) 0, -2);
5447 /* Have to succeed matching what follows at least n times.
5448 After that, handle like `on_failure_jump'. */
5450 EXTRACT_NUMBER (mcnt, p + 2);
5451 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5454 /* Originally, this is how many times we HAVE to succeed. */
5459 STORE_NUMBER_AND_INCR (p, mcnt);
5460 DEBUG_PRINT3 (" Setting 0x%lx to %d.\n", (long) p, mcnt);
5464 DEBUG_PRINT2 (" Setting two bytes from 0x%lx to no_op.\n",
5466 p[2] = (unsigned char) no_op;
5467 p[3] = (unsigned char) no_op;
5473 EXTRACT_NUMBER (mcnt, p + 2);
5474 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5476 /* Originally, this is how many times we CAN jump. */
5480 STORE_NUMBER (p + 2, mcnt);
5481 goto unconditional_jump;
5483 /* If don't have to jump any more, skip over the rest of command. */
5490 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5492 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5494 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5495 DEBUG_PRINT3 (" Setting 0x%lx to %d.\n", (long) p1, mcnt);
5496 STORE_NUMBER (p1, mcnt);
5501 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5507 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5511 const unsigned char *d_before =
5512 (const unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5513 const unsigned char *d_after =
5514 (const unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5515 Emchar emch1, emch2;
5517 DEC_CHARPTR (d_before);
5518 emch1 = charptr_emchar (d_before);
5519 emch2 = charptr_emchar (d_after);
5520 result = (WORDCHAR_P_UNSAFE (emch1) !=
5521 WORDCHAR_P_UNSAFE (emch2));
5523 if (result == should_succeed)
5529 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5531 goto matchwordbound;
5534 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5536 /* XEmacs: this originally read:
5538 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
5542 const unsigned char *dtmp =
5543 (const unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5544 Emchar emch = charptr_emchar (dtmp);
5545 if (!WORDCHAR_P_UNSAFE (emch))
5547 if (AT_STRINGS_BEG (d))
5549 dtmp = (const unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5551 emch = charptr_emchar (dtmp);
5552 if (!WORDCHAR_P_UNSAFE (emch))
5558 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5560 /* XEmacs: this originally read:
5562 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
5563 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
5566 The or condition is incorrect (reversed).
5568 const unsigned char *dtmp;
5570 if (AT_STRINGS_BEG (d))
5572 dtmp = (const unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5574 emch = charptr_emchar (dtmp);
5575 if (!WORDCHAR_P_UNSAFE (emch))
5577 if (AT_STRINGS_END (d))
5579 dtmp = (const unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5580 emch = charptr_emchar (dtmp);
5581 if (!WORDCHAR_P_UNSAFE (emch))
5588 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5589 if (!regex_emacs_buffer_p
5590 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5591 >= BUF_PT (regex_emacs_buffer)))
5596 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5597 if (!regex_emacs_buffer_p
5598 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5599 != BUF_PT (regex_emacs_buffer)))
5604 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5605 if (!regex_emacs_buffer_p
5606 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5607 <= BUF_PT (regex_emacs_buffer)))
5610 #if 0 /* not emacs19 */
5612 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5613 if (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d) + 1
5614 != BUF_PT (regex_emacs_buffer))
5617 #endif /* not emacs19 */
5620 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5625 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5635 emch = charptr_emchar ((const Bufbyte *) d);
5637 matches = (SYNTAX_UNSAFE
5638 (XCHAR_TABLE (regex_emacs_buffer->syntax_table),
5639 emch) == (enum syntaxcode) mcnt);
5641 matches = (SYNTAX_UNSAFE
5642 (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5643 emch) == (enum syntaxcode) mcnt);
5646 if (matches != should_succeed)
5648 SET_REGS_MATCHED ();
5653 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5655 goto matchnotsyntax;
5658 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5662 goto matchornotsyntax;
5665 /* 97/2/17 jhod Mule category code patch */
5674 emch = charptr_emchar ((const Bufbyte *) d);
5676 if (check_category_char(emch, regex_emacs_buffer->category_table,
5677 mcnt, should_succeed))
5679 SET_REGS_MATCHED ();
5683 case notcategoryspec:
5685 goto matchornotcategory;
5686 /* end of category patch */
5688 #else /* not emacs */
5690 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5692 if (!WORDCHAR_P_UNSAFE ((int) (*d)))
5694 SET_REGS_MATCHED ();
5699 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5701 if (!WORDCHAR_P_UNSAFE ((int) (*d)))
5703 SET_REGS_MATCHED ();
5711 continue; /* Successfully executed one pattern command; keep going. */
5714 /* We goto here if a matching operation fails. */
5716 if (!FAIL_STACK_EMPTY ())
5717 { /* A restart point is known. Restore to that state. */
5718 DEBUG_PRINT1 ("\nFAIL:\n");
5719 POP_FAILURE_POINT (d, p,
5720 lowest_active_reg, highest_active_reg,
5721 regstart, regend, reg_info);
5723 /* If this failure point is a dummy, try the next one. */
5727 /* If we failed to the end of the pattern, don't examine *p. */
5731 boolean is_a_jump_n = false;
5733 /* If failed to a backwards jump that's part of a repetition
5734 loop, need to pop this failure point and use the next one. */
5735 switch ((re_opcode_t) *p)
5739 case maybe_pop_jump:
5740 case pop_failure_jump:
5743 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5746 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5748 && (re_opcode_t) *p1 == on_failure_jump))
5756 if (d >= string1 && d <= end1)
5760 break; /* Matching at this starting point really fails. */
5764 goto restore_best_regs;
5768 return -1; /* Failure to match. */
5771 /* Subroutine definitions for re_match_2. */
5774 /* We are passed P pointing to a register number after a start_memory.
5776 Return true if the pattern up to the corresponding stop_memory can
5777 match the empty string, and false otherwise.
5779 If we find the matching stop_memory, sets P to point to one past its number.
5780 Otherwise, sets P to an undefined byte less than or equal to END.
5782 We don't handle duplicates properly (yet). */
5785 group_match_null_string_p (unsigned char **p, unsigned char *end,
5786 register_info_type *reg_info)
5789 /* Point to after the args to the start_memory. */
5790 unsigned char *p1 = *p + 2;
5794 /* Skip over opcodes that can match nothing, and return true or
5795 false, as appropriate, when we get to one that can't, or to the
5796 matching stop_memory. */
5798 switch ((re_opcode_t) *p1)
5800 /* Could be either a loop or a series of alternatives. */
5801 case on_failure_jump:
5803 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5805 /* If the next operation is not a jump backwards in the
5810 /* Go through the on_failure_jumps of the alternatives,
5811 seeing if any of the alternatives cannot match nothing.
5812 The last alternative starts with only a jump,
5813 whereas the rest start with on_failure_jump and end
5814 with a jump, e.g., here is the pattern for `a|b|c':
5816 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5817 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5820 So, we have to first go through the first (n-1)
5821 alternatives and then deal with the last one separately. */
5824 /* Deal with the first (n-1) alternatives, which start
5825 with an on_failure_jump (see above) that jumps to right
5826 past a jump_past_alt. */
5828 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5830 /* `mcnt' holds how many bytes long the alternative
5831 is, including the ending `jump_past_alt' and
5834 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5838 /* Move to right after this alternative, including the
5842 /* Break if it's the beginning of an n-th alternative
5843 that doesn't begin with an on_failure_jump. */
5844 if ((re_opcode_t) *p1 != on_failure_jump)
5847 /* Still have to check that it's not an n-th
5848 alternative that starts with an on_failure_jump. */
5850 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5851 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5853 /* Get to the beginning of the n-th alternative. */
5859 /* Deal with the last alternative: go back and get number
5860 of the `jump_past_alt' just before it. `mcnt' contains
5861 the length of the alternative. */
5862 EXTRACT_NUMBER (mcnt, p1 - 2);
5864 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5867 p1 += mcnt; /* Get past the n-th alternative. */
5873 assert (p1[1] == **p);
5879 if (!common_op_match_null_string_p (&p1, end, reg_info))
5882 } /* while p1 < end */
5885 } /* group_match_null_string_p */
5888 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5889 It expects P to be the first byte of a single alternative and END one
5890 byte past the last. The alternative can contain groups. */
5893 alt_match_null_string_p (unsigned char *p, unsigned char *end,
5894 register_info_type *reg_info)
5897 unsigned char *p1 = p;
5901 /* Skip over opcodes that can match nothing, and break when we get
5902 to one that can't. */
5904 switch ((re_opcode_t) *p1)
5907 case on_failure_jump:
5909 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5914 if (!common_op_match_null_string_p (&p1, end, reg_info))
5917 } /* while p1 < end */
5920 } /* alt_match_null_string_p */
5923 /* Deals with the ops common to group_match_null_string_p and
5924 alt_match_null_string_p.
5926 Sets P to one after the op and its arguments, if any. */
5929 common_op_match_null_string_p (unsigned char **p, unsigned char *end,
5930 register_info_type *reg_info)
5935 unsigned char *p1 = *p;
5937 switch ((re_opcode_t) *p1++)
5957 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5958 ret = group_match_null_string_p (&p1, end, reg_info);
5960 /* Have to set this here in case we're checking a group which
5961 contains a group and a back reference to it. */
5963 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5964 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5970 /* If this is an optimized succeed_n for zero times, make the jump. */
5972 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5980 /* Get to the number of times to succeed. */
5982 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5987 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5995 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
6003 /* All other opcodes mean we cannot match the empty string. */
6009 } /* common_op_match_null_string_p */
6012 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6013 bytes; nonzero otherwise. */
6016 bcmp_translate (re_char *s1, re_char *s2,
6017 REGISTER int len, RE_TRANSLATE_TYPE translate)
6019 REGISTER const unsigned char *p1 = s1, *p2 = s2;
6021 const unsigned char *p1_end = s1 + len;
6022 const unsigned char *p2_end = s2 + len;
6024 while (p1 != p1_end && p2 != p2_end)
6026 Emchar p1_ch, p2_ch;
6028 p1_ch = charptr_emchar (p1);
6029 p2_ch = charptr_emchar (p2);
6031 if (RE_TRANSLATE (p1_ch)
6032 != RE_TRANSLATE (p2_ch))
6037 #else /* not MULE */
6040 if (RE_TRANSLATE (*p1++) != RE_TRANSLATE (*p2++)) return 1;
6047 /* Entry points for GNU code. */
6049 /* re_compile_pattern is the GNU regular expression compiler: it
6050 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6051 Returns 0 if the pattern was valid, otherwise an error string.
6053 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6054 are set in BUFP on entry.
6056 We call regex_compile to do the actual compilation. */
6059 re_compile_pattern (const char *pattern, int length,
6060 struct re_pattern_buffer *bufp)
6064 /* GNU code is written to assume at least RE_NREGS registers will be set
6065 (and at least one extra will be -1). */
6066 bufp->regs_allocated = REGS_UNALLOCATED;
6068 /* And GNU code determines whether or not to get register information
6069 by passing null for the REGS argument to re_match, etc., not by
6073 /* Match anchors at newline. */
6074 bufp->newline_anchor = 1;
6076 ret = regex_compile ((unsigned char *) pattern, length, re_syntax_options, bufp);
6080 return gettext (re_error_msgid[(int) ret]);
6083 /* Entry points compatible with 4.2 BSD regex library. We don't define
6084 them unless specifically requested. */
6086 #ifdef _REGEX_RE_COMP
6088 /* BSD has one and only one pattern buffer. */
6089 static struct re_pattern_buffer re_comp_buf;
6092 re_comp (const char *s)
6098 if (!re_comp_buf.buffer)
6099 return gettext ("No previous regular expression");
6103 if (!re_comp_buf.buffer)
6105 re_comp_buf.buffer = (unsigned char *) malloc (200);
6106 if (re_comp_buf.buffer == NULL)
6107 return gettext (re_error_msgid[(int) REG_ESPACE]);
6108 re_comp_buf.allocated = 200;
6110 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6111 if (re_comp_buf.fastmap == NULL)
6112 return gettext (re_error_msgid[(int) REG_ESPACE]);
6115 /* Since `re_exec' always passes NULL for the `regs' argument, we
6116 don't need to initialize the pattern buffer fields which affect it. */
6118 /* Match anchors at newlines. */
6119 re_comp_buf.newline_anchor = 1;
6121 ret = regex_compile ((unsigned char *)s, strlen (s), re_syntax_options, &re_comp_buf);
6126 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6127 return (char *) gettext (re_error_msgid[(int) ret]);
6132 re_exec (const char *s)
6134 const int len = strlen (s);
6136 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6138 #endif /* _REGEX_RE_COMP */
6140 /* POSIX.2 functions. Don't define these for Emacs. */
6144 /* regcomp takes a regular expression as a string and compiles it.
6146 PREG is a regex_t *. We do not expect any fields to be initialized,
6147 since POSIX says we shouldn't. Thus, we set
6149 `buffer' to the compiled pattern;
6150 `used' to the length of the compiled pattern;
6151 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6152 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6153 RE_SYNTAX_POSIX_BASIC;
6154 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6155 `fastmap' and `fastmap_accurate' to zero;
6156 `re_nsub' to the number of subexpressions in PATTERN.
6158 PATTERN is the address of the pattern string.
6160 CFLAGS is a series of bits which affect compilation.
6162 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6163 use POSIX basic syntax.
6165 If REG_NEWLINE is set, then . and [^...] don't match newline.
6166 Also, regexec will try a match beginning after every newline.
6168 If REG_ICASE is set, then we considers upper- and lowercase
6169 versions of letters to be equivalent when matching.
6171 If REG_NOSUB is set, then when PREG is passed to regexec, that
6172 routine will report only success or failure, and nothing about the
6175 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6176 the return codes and their meanings.) */
6179 regcomp (regex_t *preg, const char *pattern, int cflags)
6183 = (cflags & REG_EXTENDED) ?
6184 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6186 /* regex_compile will allocate the space for the compiled pattern. */
6188 preg->allocated = 0;
6191 /* Don't bother to use a fastmap when searching. This simplifies the
6192 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6193 characters after newlines into the fastmap. This way, we just try
6197 if (cflags & REG_ICASE)
6201 preg->translate = (char *) malloc (CHAR_SET_SIZE);
6202 if (preg->translate == NULL)
6203 return (int) REG_ESPACE;
6205 /* Map uppercase characters to corresponding lowercase ones. */
6206 for (i = 0; i < CHAR_SET_SIZE; i++)
6207 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6210 preg->translate = NULL;
6212 /* If REG_NEWLINE is set, newlines are treated differently. */
6213 if (cflags & REG_NEWLINE)
6214 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6215 syntax &= ~RE_DOT_NEWLINE;
6216 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6217 /* It also changes the matching behavior. */
6218 preg->newline_anchor = 1;
6221 preg->newline_anchor = 0;
6223 preg->no_sub = !!(cflags & REG_NOSUB);
6225 /* POSIX says a null character in the pattern terminates it, so we
6226 can use strlen here in compiling the pattern. */
6227 ret = regex_compile ((unsigned char *) pattern, strlen (pattern), syntax, preg);
6229 /* POSIX doesn't distinguish between an unmatched open-group and an
6230 unmatched close-group: both are REG_EPAREN. */
6231 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6237 /* regexec searches for a given pattern, specified by PREG, in the
6240 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6241 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6242 least NMATCH elements, and we set them to the offsets of the
6243 corresponding matched substrings.
6245 EFLAGS specifies `execution flags' which affect matching: if
6246 REG_NOTBOL is set, then ^ does not match at the beginning of the
6247 string; if REG_NOTEOL is set, then $ does not match at the end.
6249 We return 0 if we find a match and REG_NOMATCH if not. */
6252 regexec (const regex_t *preg, const char *string, size_t nmatch,
6253 regmatch_t pmatch[], int eflags)
6256 struct re_registers regs;
6257 regex_t private_preg;
6258 int len = strlen (string);
6259 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6261 private_preg = *preg;
6263 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6264 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6266 /* The user has told us exactly how many registers to return
6267 information about, via `nmatch'. We have to pass that on to the
6268 matching routines. */
6269 private_preg.regs_allocated = REGS_FIXED;
6273 regs.num_regs = nmatch;
6274 regs.start = TALLOC (nmatch, regoff_t);
6275 regs.end = TALLOC (nmatch, regoff_t);
6276 if (regs.start == NULL || regs.end == NULL)
6277 return (int) REG_NOMATCH;
6280 /* Perform the searching operation. */
6281 ret = re_search (&private_preg, string, len,
6282 /* start: */ 0, /* range: */ len,
6283 want_reg_info ? ®s : (struct re_registers *) 0);
6285 /* Copy the register information to the POSIX structure. */
6292 for (r = 0; r < nmatch; r++)
6294 pmatch[r].rm_so = regs.start[r];
6295 pmatch[r].rm_eo = regs.end[r];
6299 /* If we needed the temporary register info, free the space now. */
6304 /* We want zero return to mean success, unlike `re_search'. */
6305 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6309 /* Returns a message corresponding to an error code, ERRCODE, returned
6310 from either regcomp or regexec. We don't use PREG here. */
6313 regerror (int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
6319 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6320 /* Only error codes returned by the rest of the code should be passed
6321 to this routine. If we are given anything else, or if other regex
6322 code generates an invalid error code, then the program has a bug.
6323 Dump core so we can fix it. */
6326 msg = gettext (re_error_msgid[errcode]);
6328 msg_size = strlen (msg) + 1; /* Includes the null. */
6330 if (errbuf_size != 0)
6332 if (msg_size > errbuf_size)
6334 strncpy (errbuf, msg, errbuf_size - 1);
6335 errbuf[errbuf_size - 1] = 0;
6338 strcpy (errbuf, msg);
6345 /* Free dynamically allocated space used by PREG. */
6348 regfree (regex_t *preg)
6350 if (preg->buffer != NULL)
6351 free (preg->buffer);
6352 preg->buffer = NULL;
6354 preg->allocated = 0;
6357 if (preg->fastmap != NULL)
6358 free (preg->fastmap);
6359 preg->fastmap = NULL;
6360 preg->fastmap_accurate = 0;
6362 if (preg->translate != NULL)
6363 free (preg->translate);
6364 preg->translate = NULL;
6367 #endif /* not emacs */
6371 make-backup-files: t
6373 trim-versions-without-asking: nil