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.
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2, or (at your option)
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; see the file COPYING. If not, write to
22 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 Boston, MA 02111-1307, USA. */
25 /* Synched up with: FSF 19.29. */
27 /* Changes made for XEmacs:
29 (1) the REGEX_BEGLINE_CHECK code from the XEmacs v18 regex routines
30 was added. This causes a huge speedup in font-locking.
31 (2) Rel-alloc is disabled when the MMAP version of rel-alloc is
32 being used, because it's too slow -- all those calls to mmap()
33 add humongous overhead.
34 (3) Lots and lots of changes for Mule. They are bracketed by
35 `#ifdef MULE' or with comments that have `XEmacs' in them.
42 #ifndef REGISTER /* Rigidly enforced as of 20.3 */
51 /* Converts the pointer to the char to BEG-based offset from the start. */
52 #define PTR_TO_OFFSET(d) (MATCHING_IN_FIRST_STRING \
53 ? (d) - string1 : (d) - (string2 - size1))
55 #define PTR_TO_OFFSET(d) 0
58 /* We assume non-Mule if emacs isn't defined. */
63 /* We need this for `regex.h', and perhaps for the Emacs include files. */
64 #include <sys/types.h>
66 /* This is for other GNU distributions with internationalized messages. */
67 #if defined (I18N3) && (defined (HAVE_LIBINTL_H) || defined (_LIBC))
70 # define gettext(msgid) (msgid)
73 /* XEmacs: define this to add in a speedup for patterns anchored at
74 the beginning of a line. Keep the ifdefs so that it's easier to
75 tell where/why this code has diverged from v19. */
76 #define REGEX_BEGLINE_CHECK
78 /* XEmacs: the current mmap-based ralloc handles small blocks very
79 poorly, so we disable it here. */
81 #if (defined (REL_ALLOC) && defined (HAVE_MMAP)) || defined(DOUG_LEA_MALLOC)
85 /* The `emacs' switch turns on certain matching commands
86 that make sense only in Emacs. */
93 #if (defined (DEBUG_XEMACS) && !defined (DEBUG))
99 Lisp_Object Vthe_lisp_rangetab;
102 complex_vars_of_regex (void)
104 Vthe_lisp_rangetab = Fmake_range_table ();
105 staticpro (&Vthe_lisp_rangetab);
111 complex_vars_of_regex (void)
117 #define RE_TRANSLATE(ch) TRT_TABLE_OF (translate, (Emchar) ch)
118 #define TRANSLATE_P(tr) (!NILP (tr))
120 #else /* not emacs */
122 /* If we are not linking with Emacs proper,
123 we can't use the relocating allocator
124 even if config.h says that we can. */
127 #if defined (STDC_HEADERS) || defined (_LIBC)
134 /* Types normally included via lisp.h */
135 #include <stddef.h> /* for ptrdiff_t */
138 #ifndef DECLARE_NOTHING
139 #define DECLARE_NOTHING struct nosuchstruct
145 #define charptr_emchar(str) ((Emchar) (str)[0])
147 #define INC_CHARPTR(p) ((p)++)
148 #define DEC_CHARPTR(p) ((p)--)
152 /* Define the syntax stuff for \<, \>, etc. */
154 /* This must be nonzero for the wordchar and notwordchar pattern
155 commands in re_match_2. */
162 extern char *re_syntax_table;
164 #else /* not SYNTAX_TABLE */
166 /* How many characters in the character set. */
167 #define CHAR_SET_SIZE 256
169 static char re_syntax_table[CHAR_SET_SIZE];
172 init_syntax_once (void)
178 const char *word_syntax_chars =
179 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
181 memset (re_syntax_table, 0, sizeof (re_syntax_table));
183 while (*word_syntax_chars)
184 re_syntax_table[(unsigned int)(*word_syntax_chars++)] = Sword;
190 #endif /* SYNTAX_TABLE */
192 #define SYNTAX_UNSAFE(ignored, c) re_syntax_table[c]
193 #undef SYNTAX_FROM_CACHE
194 #define SYNTAX_FROM_CACHE SYNTAX_UNSAFE
196 #define RE_TRANSLATE(c) translate[(unsigned char) (c)]
197 #define TRANSLATE_P(tr) tr
201 /* Under XEmacs, this is needed because we don't define it elsewhere. */
202 #ifdef SWITCH_ENUM_BUG
203 #define SWITCH_ENUM_CAST(x) ((int)(x))
205 #define SWITCH_ENUM_CAST(x) (x)
209 /* Get the interface, including the syntax bits. */
212 /* isalpha etc. are used for the character classes. */
215 /* Jim Meyering writes:
217 "... Some ctype macros are valid only for character codes that
218 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
219 using /bin/cc or gcc but without giving an ansi option). So, all
220 ctype uses should be through macros like ISPRINT... If
221 STDC_HEADERS is defined, then autoconf has verified that the ctype
222 macros don't need to be guarded with references to isascii. ...
223 Defining isascii to 1 should let any compiler worth its salt
224 eliminate the && through constant folding." */
226 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
227 #define ISASCII_1(c) 1
229 #define ISASCII_1(c) isascii(c)
233 /* The IS*() macros can be passed any character, including an extended
234 one. We need to make sure there are no crashes, which would occur
235 otherwise due to out-of-bounds array references. */
236 #define ISASCII(c) (((EMACS_UINT) (c)) < 0x100 && ISASCII_1 (c))
238 #define ISASCII(c) ISASCII_1 (c)
242 #define ISBLANK(c) (ISASCII (c) && isblank (c))
244 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
247 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
249 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
252 #define ISPRINT(c) (ISASCII (c) && isprint (c))
253 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
254 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
255 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
256 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
257 #define ISLOWER(c) (ISASCII (c) && islower (c))
258 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
259 #define ISSPACE(c) (ISASCII (c) && isspace (c))
260 #define ISUPPER(c) (ISASCII (c) && isupper (c))
261 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
264 #define NULL (void *)0
267 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
268 since ours (we hope) works properly with all combinations of
269 machines, compilers, `char' and `unsigned char' argument types.
270 (Per Bothner suggested the basic approach.) */
271 #undef SIGN_EXTEND_CHAR
273 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
274 #else /* not __STDC__ */
275 /* As in Harbison and Steele. */
276 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
279 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
280 use `alloca' instead of `malloc'. This is because using malloc in
281 re_search* or re_match* could cause memory leaks when C-g is used in
282 Emacs; also, malloc is slower and causes storage fragmentation. On
283 the other hand, malloc is more portable, and easier to debug.
285 Because we sometimes use alloca, some routines have to be macros,
286 not functions -- `alloca'-allocated space disappears at the end of the
287 function it is called in. */
291 #define REGEX_ALLOCATE malloc
292 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
293 #define REGEX_FREE free
295 #else /* not REGEX_MALLOC */
297 /* Emacs already defines alloca, sometimes. */
300 /* Make alloca work the best possible way. */
302 #define alloca __builtin_alloca
303 #else /* not __GNUC__ */
306 #else /* not __GNUC__ or HAVE_ALLOCA_H */
307 #ifndef _AIX /* Already did AIX, up at the top. */
309 #endif /* not _AIX */
310 #endif /* HAVE_ALLOCA_H */
311 #endif /* __GNUC__ */
313 #endif /* not alloca */
315 #define REGEX_ALLOCATE alloca
317 /* Assumes a `char *destination' variable. */
318 #define REGEX_REALLOCATE(source, osize, nsize) \
319 (destination = (char *) alloca (nsize), \
320 memmove (destination, source, osize), \
323 /* No need to do anything to free, after alloca. */
324 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
326 #endif /* REGEX_MALLOC */
328 /* Define how to allocate the failure stack. */
331 #define REGEX_ALLOCATE_STACK(size) \
332 r_alloc ((char **) &failure_stack_ptr, (size))
333 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
334 r_re_alloc ((char **) &failure_stack_ptr, (nsize))
335 #define REGEX_FREE_STACK(ptr) \
336 r_alloc_free ((void **) &failure_stack_ptr)
338 #else /* not REL_ALLOC */
342 #define REGEX_ALLOCATE_STACK malloc
343 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
344 #define REGEX_FREE_STACK free
346 #else /* not REGEX_MALLOC */
348 #define REGEX_ALLOCATE_STACK alloca
350 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
351 REGEX_REALLOCATE (source, osize, nsize)
352 /* No need to explicitly free anything. */
353 #define REGEX_FREE_STACK(arg)
355 #endif /* REGEX_MALLOC */
356 #endif /* REL_ALLOC */
359 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
360 `string1' or just past its end. This works if PTR is NULL, which is
362 #define FIRST_STRING_P(ptr) \
363 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
365 /* (Re)Allocate N items of type T using malloc, or fail. */
366 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
367 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
368 #define RETALLOC_IF(addr, n, t) \
369 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
370 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
372 #define BYTEWIDTH 8 /* In bits. */
374 #define STREQ(s1, s2) (strcmp (s1, s2) == 0)
378 #define MAX(a, b) ((a) > (b) ? (a) : (b))
379 #define MIN(a, b) ((a) < (b) ? (a) : (b))
381 /* Type of source-pattern and string chars. */
382 typedef const unsigned char re_char;
384 typedef char re_bool;
389 /* These are the command codes that appear in compiled regular
390 expressions. Some opcodes are followed by argument bytes. A
391 command code can specify any interpretation whatsoever for its
392 arguments. Zero bytes may appear in the compiled regular expression. */
398 /* Succeed right away--no more backtracking. */
401 /* Followed by one byte giving n, then by n literal bytes. */
404 /* Matches any (more or less) character. */
407 /* Matches any one char belonging to specified set. First
408 following byte is number of bitmap bytes. Then come bytes
409 for a bitmap saying which chars are in. Bits in each byte
410 are ordered low-bit-first. A character is in the set if its
411 bit is 1. A character too large to have a bit in the map is
412 automatically not in the set. */
415 /* Same parameters as charset, but match any character that is
416 not one of those specified. */
419 /* Start remembering the text that is matched, for storing in a
420 register. Followed by one byte with the register number, in
421 the range 0 to one less than the pattern buffer's re_nsub
422 field. Then followed by one byte with the number of groups
423 inner to this one. (This last has to be part of the
424 start_memory only because we need it in the on_failure_jump
428 /* Stop remembering the text that is matched and store it in a
429 memory register. Followed by one byte with the register
430 number, in the range 0 to one less than `re_nsub' in the
431 pattern buffer, and one byte with the number of inner groups,
432 just like `start_memory'. (We need the number of inner
433 groups here because we don't have any easy way of finding the
434 corresponding start_memory when we're at a stop_memory.) */
437 /* Match a duplicate of something remembered. Followed by one
438 byte containing the register number. */
441 /* Fail unless at beginning of line. */
444 /* Fail unless at end of line. */
447 /* Succeeds if at beginning of buffer (if emacs) or at beginning
448 of string to be matched (if not). */
451 /* Analogously, for end of buffer/string. */
454 /* Followed by two byte relative address to which to jump. */
457 /* Same as jump, but marks the end of an alternative. */
460 /* Followed by two-byte relative address of place to resume at
461 in case of failure. */
464 /* Like on_failure_jump, but pushes a placeholder instead of the
465 current string position when executed. */
466 on_failure_keep_string_jump,
468 /* Throw away latest failure point and then jump to following
469 two-byte relative address. */
472 /* Change to pop_failure_jump if know won't have to backtrack to
473 match; otherwise change to jump. This is used to jump
474 back to the beginning of a repeat. If what follows this jump
475 clearly won't match what the repeat does, such that we can be
476 sure that there is no use backtracking out of repetitions
477 already matched, then we change it to a pop_failure_jump.
478 Followed by two-byte address. */
481 /* Jump to following two-byte address, and push a dummy failure
482 point. This failure point will be thrown away if an attempt
483 is made to use it for a failure. A `+' construct makes this
484 before the first repeat. Also used as an intermediary kind
485 of jump when compiling an alternative. */
488 /* Push a dummy failure point and continue. Used at the end of
492 /* Followed by two-byte relative address and two-byte number n.
493 After matching N times, jump to the address upon failure. */
496 /* Followed by two-byte relative address, and two-byte number n.
497 Jump to the address N times, then fail. */
500 /* Set the following two-byte relative address to the
501 subsequent two-byte number. The address *includes* the two
505 wordchar, /* Matches any word-constituent character. */
506 notwordchar, /* Matches any char that is not a word-constituent. */
508 wordbeg, /* Succeeds if at word beginning. */
509 wordend, /* Succeeds if at word end. */
511 wordbound, /* Succeeds if at a word boundary. */
512 notwordbound /* Succeeds if not at a word boundary. */
515 ,before_dot, /* Succeeds if before point. */
516 at_dot, /* Succeeds if at point. */
517 after_dot, /* Succeeds if after point. */
519 /* Matches any character whose syntax is specified. Followed by
520 a byte which contains a syntax code, e.g., Sword. */
523 /* Matches any character whose syntax is not that specified. */
529 /* need extra stuff to be able to properly work with XEmacs/Mule
530 characters (which may take up more than one byte) */
532 ,charset_mule, /* Matches any character belonging to specified set.
533 The set is stored in "unified range-table
534 format"; see rangetab.c. Unlike the `charset'
535 opcode, this can handle arbitrary characters. */
537 charset_mule_not /* Same parameters as charset_mule, but match any
538 character that is not one of those specified. */
540 /* 97/2/17 jhod: The following two were merged back in from the Mule
541 2.3 code to enable some language specific processing */
542 ,categoryspec, /* Matches entries in the character category tables */
543 notcategoryspec /* The opposite of the above */
548 /* Common operations on the compiled pattern. */
550 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
552 #define STORE_NUMBER(destination, number) \
554 (destination)[0] = (number) & 0377; \
555 (destination)[1] = (number) >> 8; \
558 /* Same as STORE_NUMBER, except increment DESTINATION to
559 the byte after where the number is stored. Therefore, DESTINATION
560 must be an lvalue. */
562 #define STORE_NUMBER_AND_INCR(destination, number) \
564 STORE_NUMBER (destination, number); \
565 (destination) += 2; \
568 /* Put into DESTINATION a number stored in two contiguous bytes starting
571 #define EXTRACT_NUMBER(destination, source) \
573 (destination) = *(source) & 0377; \
574 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
579 extract_number (int *dest, re_char *source)
581 int temp = SIGN_EXTEND_CHAR (*(source + 1));
582 *dest = *source & 0377;
586 #ifndef EXTRACT_MACROS /* To debug the macros. */
587 #undef EXTRACT_NUMBER
588 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
589 #endif /* not EXTRACT_MACROS */
593 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
594 SOURCE must be an lvalue. */
596 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
598 EXTRACT_NUMBER (destination, source); \
604 extract_number_and_incr (int *destination, unsigned char **source)
606 extract_number (destination, *source);
610 #ifndef EXTRACT_MACROS
611 #undef EXTRACT_NUMBER_AND_INCR
612 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
613 extract_number_and_incr (&dest, &src)
614 #endif /* not EXTRACT_MACROS */
618 /* If DEBUG is defined, Regex prints many voluminous messages about what
619 it is doing (if the variable `debug' is nonzero). If linked with the
620 main program in `iregex.c', you can enter patterns and strings
621 interactively. And if linked with the main program in `main.c' and
622 the other test files, you can run the already-written tests. */
626 /* We use standard I/O for debugging. */
630 /* XEmacs provides its own version of assert() */
631 /* It is useful to test things that ``must'' be true when debugging. */
635 static int debug = 0;
637 #define DEBUG_STATEMENT(e) e
638 #define DEBUG_PRINT1(x) if (debug) printf (x)
639 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
640 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
641 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
642 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
643 if (debug) print_partial_compiled_pattern (s, e)
644 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
645 if (debug) print_double_string (w, s1, sz1, s2, sz2)
648 /* Print the fastmap in human-readable form. */
651 print_fastmap (char *fastmap)
653 unsigned was_a_range = 0;
656 while (i < (1 << BYTEWIDTH))
662 while (i < (1 << BYTEWIDTH) && fastmap[i])
678 /* Print a compiled pattern string in human-readable form, starting at
679 the START pointer into it and ending just before the pointer END. */
682 print_partial_compiled_pattern (re_char *start, re_char *end)
685 unsigned char *p = (unsigned char *) start;
694 /* Loop over pattern commands. */
697 printf ("%ld:\t", (long)(p - start));
699 switch ((re_opcode_t) *p++)
707 printf ("/exactn/%d", mcnt);
718 printf ("/start_memory/%d/%d", mcnt, *p++);
723 printf ("/stop_memory/%d/%d", mcnt, *p++);
727 printf ("/duplicate/%d", *p++);
737 REGISTER int c, last = -100;
738 REGISTER int in_range = 0;
740 printf ("/charset [%s",
741 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
743 assert (p + *p < pend);
745 for (c = 0; c < 256; c++)
746 if (((unsigned char) (c / 8) < *p)
747 && (p[1 + (c/8)] & (1 << (c % 8))))
749 /* Are we starting a range? */
750 if (last + 1 == c && ! in_range)
755 /* Have we broken a range? */
756 else if (last + 1 != c && in_range)
779 case charset_mule_not:
783 printf ("/charset_mule [%s",
784 (re_opcode_t) *(p - 1) == charset_mule_not ? "^" : "");
785 nentries = unified_range_table_nentries (p);
786 for (i = 0; i < nentries; i++)
788 EMACS_INT first, last;
789 Lisp_Object dummy_val;
791 unified_range_table_get_range (p, i, &first, &last,
796 printf ("(0x%lx)", (long)first);
803 printf ("(0x%lx)", (long)last);
807 p += unified_range_table_bytes_used (p);
820 case on_failure_jump:
821 extract_number_and_incr (&mcnt, &p);
822 printf ("/on_failure_jump to %ld", (long)(p + mcnt - start));
825 case on_failure_keep_string_jump:
826 extract_number_and_incr (&mcnt, &p);
827 printf ("/on_failure_keep_string_jump to %ld", (long)(p + mcnt - start));
830 case dummy_failure_jump:
831 extract_number_and_incr (&mcnt, &p);
832 printf ("/dummy_failure_jump to %ld", (long)(p + mcnt - start));
835 case push_dummy_failure:
836 printf ("/push_dummy_failure");
840 extract_number_and_incr (&mcnt, &p);
841 printf ("/maybe_pop_jump to %ld", (long)(p + mcnt - start));
844 case pop_failure_jump:
845 extract_number_and_incr (&mcnt, &p);
846 printf ("/pop_failure_jump to %ld", (long)(p + mcnt - start));
850 extract_number_and_incr (&mcnt, &p);
851 printf ("/jump_past_alt to %ld", (long)(p + mcnt - start));
855 extract_number_and_incr (&mcnt, &p);
856 printf ("/jump to %ld", (long)(p + mcnt - start));
860 extract_number_and_incr (&mcnt, &p);
861 extract_number_and_incr (&mcnt2, &p);
862 printf ("/succeed_n to %ld, %d times", (long)(p + mcnt - start), mcnt2);
866 extract_number_and_incr (&mcnt, &p);
867 extract_number_and_incr (&mcnt2, &p);
868 printf ("/jump_n to %ld, %d times", (long)(p + mcnt - start), mcnt2);
872 extract_number_and_incr (&mcnt, &p);
873 extract_number_and_incr (&mcnt2, &p);
874 printf ("/set_number_at location %ld to %d", (long)(p + mcnt - start), mcnt2);
878 printf ("/wordbound");
882 printf ("/notwordbound");
894 printf ("/before_dot");
902 printf ("/after_dot");
906 printf ("/syntaxspec");
908 printf ("/%d", mcnt);
912 printf ("/notsyntaxspec");
914 printf ("/%d", mcnt);
918 /* 97/2/17 jhod Mule category patch */
920 printf ("/categoryspec");
922 printf ("/%d", mcnt);
925 case notcategoryspec:
926 printf ("/notcategoryspec");
928 printf ("/%d", mcnt);
930 /* end of category patch */
935 printf ("/wordchar");
939 printf ("/notwordchar");
951 printf ("?%d", *(p-1));
957 printf ("%ld:\tend of pattern.\n", (long)(p - start));
962 print_compiled_pattern (struct re_pattern_buffer *bufp)
964 re_char *buffer = bufp->buffer;
966 print_partial_compiled_pattern (buffer, buffer + bufp->used);
967 printf ("%ld bytes used/%ld bytes allocated.\n", bufp->used,
970 if (bufp->fastmap_accurate && bufp->fastmap)
972 printf ("fastmap: ");
973 print_fastmap (bufp->fastmap);
976 printf ("re_nsub: %ld\t", (long)bufp->re_nsub);
977 printf ("regs_alloc: %d\t", bufp->regs_allocated);
978 printf ("can_be_null: %d\t", bufp->can_be_null);
979 printf ("newline_anchor: %d\n", bufp->newline_anchor);
980 printf ("no_sub: %d\t", bufp->no_sub);
981 printf ("not_bol: %d\t", bufp->not_bol);
982 printf ("not_eol: %d\t", bufp->not_eol);
983 printf ("syntax: %d\n", bufp->syntax);
984 /* Perhaps we should print the translate table? */
985 /* and maybe the category table? */
990 print_double_string (re_char *where, re_char *string1, int size1,
991 re_char *string2, int size2)
997 Element_count this_char;
999 if (FIRST_STRING_P (where))
1001 for (this_char = where - string1; this_char < size1; this_char++)
1002 putchar (string1[this_char]);
1007 for (this_char = where - string2; this_char < size2; this_char++)
1008 putchar (string2[this_char]);
1012 #else /* not DEBUG */
1017 #define DEBUG_STATEMENT(e)
1018 #define DEBUG_PRINT1(x)
1019 #define DEBUG_PRINT2(x1, x2)
1020 #define DEBUG_PRINT3(x1, x2, x3)
1021 #define DEBUG_PRINT4(x1, x2, x3, x4)
1022 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1023 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1027 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1028 also be assigned to arbitrarily: each pattern buffer stores its own
1029 syntax, so it can be changed between regex compilations. */
1030 /* This has no initializer because initialized variables in Emacs
1031 become read-only after dumping. */
1032 reg_syntax_t re_syntax_options;
1035 /* Specify the precise syntax of regexps for compilation. This provides
1036 for compatibility for various utilities which historically have
1037 different, incompatible syntaxes.
1039 The argument SYNTAX is a bit mask comprised of the various bits
1040 defined in regex.h. We return the old syntax. */
1043 re_set_syntax (reg_syntax_t syntax)
1045 reg_syntax_t ret = re_syntax_options;
1047 re_syntax_options = syntax;
1051 /* This table gives an error message for each of the error codes listed
1052 in regex.h. Obviously the order here has to be same as there.
1053 POSIX doesn't require that we do anything for REG_NOERROR,
1054 but why not be nice? */
1056 static const char *re_error_msgid[] =
1058 "Success", /* REG_NOERROR */
1059 "No match", /* REG_NOMATCH */
1060 "Invalid regular expression", /* REG_BADPAT */
1061 "Invalid collation character", /* REG_ECOLLATE */
1062 "Invalid character class name", /* REG_ECTYPE */
1063 "Trailing backslash", /* REG_EESCAPE */
1064 "Invalid back reference", /* REG_ESUBREG */
1065 "Unmatched [ or [^", /* REG_EBRACK */
1066 "Unmatched ( or \\(", /* REG_EPAREN */
1067 "Unmatched \\{", /* REG_EBRACE */
1068 "Invalid content of \\{\\}", /* REG_BADBR */
1069 "Invalid range end", /* REG_ERANGE */
1070 "Memory exhausted", /* REG_ESPACE */
1071 "Invalid preceding regular expression", /* REG_BADRPT */
1072 "Premature end of regular expression", /* REG_EEND */
1073 "Regular expression too big", /* REG_ESIZE */
1074 "Unmatched ) or \\)", /* REG_ERPAREN */
1076 "Invalid syntax designator", /* REG_ESYNTAX */
1079 "Ranges may not span charsets", /* REG_ERANGESPAN */
1080 "Invalid category designator", /* REG_ECATEGORY */
1084 /* Avoiding alloca during matching, to placate r_alloc. */
1086 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1087 searching and matching functions should not call alloca. On some
1088 systems, alloca is implemented in terms of malloc, and if we're
1089 using the relocating allocator routines, then malloc could cause a
1090 relocation, which might (if the strings being searched are in the
1091 ralloc heap) shift the data out from underneath the regexp
1094 Here's another reason to avoid allocation: Emacs
1095 processes input from X in a signal handler; processing X input may
1096 call malloc; if input arrives while a matching routine is calling
1097 malloc, then we're scrod. But Emacs can't just block input while
1098 calling matching routines; then we don't notice interrupts when
1099 they come in. So, Emacs blocks input around all regexp calls
1100 except the matching calls, which it leaves unprotected, in the
1101 faith that they will not malloc. */
1103 /* Normally, this is fine. */
1104 #define MATCH_MAY_ALLOCATE
1106 /* When using GNU C, we are not REALLY using the C alloca, no matter
1107 what config.h may say. So don't take precautions for it. */
1112 /* The match routines may not allocate if (1) they would do it with malloc
1113 and (2) it's not safe for them to use malloc.
1114 Note that if REL_ALLOC is defined, matching would not use malloc for the
1115 failure stack, but we would still use it for the register vectors;
1116 so REL_ALLOC should not affect this. */
1117 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1118 #undef MATCH_MAY_ALLOCATE
1122 /* Failure stack declarations and macros; both re_compile_fastmap and
1123 re_match_2 use a failure stack. These have to be macros because of
1124 REGEX_ALLOCATE_STACK. */
1127 /* Number of failure points for which to initially allocate space
1128 when matching. If this number is exceeded, we allocate more
1129 space, so it is not a hard limit. */
1130 #ifndef INIT_FAILURE_ALLOC
1131 #define INIT_FAILURE_ALLOC 5
1134 /* Roughly the maximum number of failure points on the stack. Would be
1135 exactly that if always used MAX_FAILURE_SPACE each time we failed.
1136 This is a variable only so users of regex can assign to it; we never
1137 change it ourselves. */
1138 #if defined (MATCH_MAY_ALLOCATE)
1139 /* 4400 was enough to cause a crash on Alpha OSF/1,
1140 whose default stack limit is 2mb. */
1141 int re_max_failures = 20000;
1143 int re_max_failures = 2000;
1146 union fail_stack_elt
1152 typedef union fail_stack_elt fail_stack_elt_t;
1156 fail_stack_elt_t *stack;
1158 Element_count avail; /* Offset of next open position. */
1161 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1162 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1163 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1166 /* Define macros to initialize and free the failure stack.
1167 Do `return -2' if the alloc fails. */
1169 #ifdef MATCH_MAY_ALLOCATE
1170 #define INIT_FAIL_STACK() \
1172 fail_stack.stack = (fail_stack_elt_t *) \
1173 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1175 if (fail_stack.stack == NULL) \
1178 fail_stack.size = INIT_FAILURE_ALLOC; \
1179 fail_stack.avail = 0; \
1182 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1184 #define INIT_FAIL_STACK() \
1186 fail_stack.avail = 0; \
1189 #define RESET_FAIL_STACK()
1193 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1195 Return 1 if succeeds, and 0 if either ran out of memory
1196 allocating space for it or it was already too large.
1198 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1200 #define DOUBLE_FAIL_STACK(fail_stack) \
1201 ((int) (fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
1203 : ((fail_stack).stack = (fail_stack_elt_t *) \
1204 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1205 (fail_stack).size * sizeof (fail_stack_elt_t), \
1206 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1208 (fail_stack).stack == NULL \
1210 : ((fail_stack).size <<= 1, \
1214 /* Push pointer POINTER on FAIL_STACK.
1215 Return 1 if was able to do so and 0 if ran out of memory allocating
1217 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1218 ((FAIL_STACK_FULL () \
1219 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1221 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1224 /* Push a pointer 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_POINTER(item) \
1228 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1230 /* This pushes an integer-valued item onto the failure stack.
1231 Assumes the variable `fail_stack'. Probably should only
1232 be called from within `PUSH_FAILURE_POINT'. */
1233 #define PUSH_FAILURE_INT(item) \
1234 fail_stack.stack[fail_stack.avail++].integer = (item)
1236 /* Push a fail_stack_elt_t value onto the failure stack.
1237 Assumes the variable `fail_stack'. Probably should only
1238 be called from within `PUSH_FAILURE_POINT'. */
1239 #define PUSH_FAILURE_ELT(item) \
1240 fail_stack.stack[fail_stack.avail++] = (item)
1242 /* These three POP... operations complement the three PUSH... operations.
1243 All assume that `fail_stack' is nonempty. */
1244 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1245 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1246 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1248 /* Used to omit pushing failure point id's when we're not debugging. */
1250 #define DEBUG_PUSH PUSH_FAILURE_INT
1251 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1253 #define DEBUG_PUSH(item)
1254 #define DEBUG_POP(item_addr)
1258 /* Push the information about the state we will need
1259 if we ever fail back to it.
1261 Requires variables fail_stack, regstart, regend, reg_info, and
1262 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
1265 Does `return FAILURE_CODE' if runs out of memory. */
1267 #if !defined (REGEX_MALLOC) && !defined (REL_ALLOC)
1268 #define DECLARE_DESTINATION char *destination
1270 #define DECLARE_DESTINATION DECLARE_NOTHING
1273 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1275 DECLARE_DESTINATION; \
1276 /* Must be int, so when we don't save any registers, the arithmetic \
1277 of 0 + -1 isn't done as unsigned. */ \
1280 DEBUG_STATEMENT (failure_id++); \
1281 DEBUG_STATEMENT (nfailure_points_pushed++); \
1282 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1283 DEBUG_PRINT2 (" Before push, next avail: %lu\n", \
1284 (unsigned long) (fail_stack).avail); \
1285 DEBUG_PRINT2 (" size: %lu\n", \
1286 (unsigned long) (fail_stack).size); \
1288 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1289 DEBUG_PRINT2 (" available: %ld\n", \
1290 (long) REMAINING_AVAIL_SLOTS); \
1292 /* Ensure we have enough space allocated for what we will push. */ \
1293 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1295 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1296 return failure_code; \
1298 DEBUG_PRINT2 ("\n Doubled stack; size now: %lu\n", \
1299 (unsigned long) (fail_stack).size); \
1300 DEBUG_PRINT2 (" slots available: %ld\n", \
1301 (long) REMAINING_AVAIL_SLOTS); \
1304 /* Push the info, starting with the registers. */ \
1305 DEBUG_PRINT1 ("\n"); \
1307 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1310 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1311 DEBUG_STATEMENT (num_regs_pushed++); \
1313 DEBUG_PRINT2 (" start: 0x%lx\n", (long) regstart[this_reg]); \
1314 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1316 DEBUG_PRINT2 (" end: 0x%lx\n", (long) regend[this_reg]); \
1317 PUSH_FAILURE_POINTER (regend[this_reg]); \
1319 DEBUG_PRINT2 (" info: 0x%lx\n ", \
1320 * (long *) (®_info[this_reg])); \
1321 DEBUG_PRINT2 (" match_null=%d", \
1322 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1323 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1324 DEBUG_PRINT2 (" matched_something=%d", \
1325 MATCHED_SOMETHING (reg_info[this_reg])); \
1326 DEBUG_PRINT2 (" ever_matched_something=%d", \
1327 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1328 DEBUG_PRINT1 ("\n"); \
1329 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1332 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg); \
1333 PUSH_FAILURE_INT (lowest_active_reg); \
1335 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg); \
1336 PUSH_FAILURE_INT (highest_active_reg); \
1338 DEBUG_PRINT2 (" Pushing pattern 0x%lx: \n", (long) pattern_place); \
1339 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1340 PUSH_FAILURE_POINTER (pattern_place); \
1342 DEBUG_PRINT2 (" Pushing string 0x%lx: `", (long) string_place); \
1343 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1345 DEBUG_PRINT1 ("'\n"); \
1346 PUSH_FAILURE_POINTER (string_place); \
1348 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1349 DEBUG_PUSH (failure_id); \
1352 /* This is the number of items that are pushed and popped on the stack
1353 for each register. */
1354 #define NUM_REG_ITEMS 3
1356 /* Individual items aside from the registers. */
1358 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1360 #define NUM_NONREG_ITEMS 4
1363 /* We push at most this many items on the stack. */
1364 /* We used to use (num_regs - 1), which is the number of registers
1365 this regexp will save; but that was changed to 5
1366 to avoid stack overflow for a regexp with lots of parens. */
1367 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1369 /* We actually push this many items. */
1370 #define NUM_FAILURE_ITEMS \
1371 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
1374 /* How many items can still be added to the stack without overflowing it. */
1375 #define REMAINING_AVAIL_SLOTS ((int) ((fail_stack).size - (fail_stack).avail))
1378 /* Pops what PUSH_FAIL_STACK pushes.
1380 We restore into the parameters, all of which should be lvalues:
1381 STR -- the saved data position.
1382 PAT -- the saved pattern position.
1383 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1384 REGSTART, REGEND -- arrays of string positions.
1385 REG_INFO -- array of information about each subexpression.
1387 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1388 `pend', `string1', `size1', `string2', and `size2'. */
1390 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, \
1391 regstart, regend, reg_info) \
1393 DEBUG_STATEMENT (fail_stack_elt_t ffailure_id;) \
1395 const unsigned char *string_temp; \
1397 assert (!FAIL_STACK_EMPTY ()); \
1399 /* Remove failure points and point to how many regs pushed. */ \
1400 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1401 DEBUG_PRINT2 (" Before pop, next avail: %lu\n", \
1402 (unsigned long) fail_stack.avail); \
1403 DEBUG_PRINT2 (" size: %lu\n", \
1404 (unsigned long) fail_stack.size); \
1406 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1408 DEBUG_POP (&ffailure_id.integer); \
1409 DEBUG_PRINT2 (" Popping failure id: %u\n", \
1410 * (unsigned int *) &ffailure_id); \
1412 /* If the saved string location is NULL, it came from an \
1413 on_failure_keep_string_jump opcode, and we want to throw away the \
1414 saved NULL, thus retaining our current position in the string. */ \
1415 string_temp = POP_FAILURE_POINTER (); \
1416 if (string_temp != NULL) \
1417 str = string_temp; \
1419 DEBUG_PRINT2 (" Popping string 0x%lx: `", (long) str); \
1420 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1421 DEBUG_PRINT1 ("'\n"); \
1423 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1424 DEBUG_PRINT2 (" Popping pattern 0x%lx: ", (long) pat); \
1425 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1427 /* Restore register info. */ \
1428 high_reg = (unsigned) POP_FAILURE_INT (); \
1429 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1431 low_reg = (unsigned) POP_FAILURE_INT (); \
1432 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1434 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1436 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1438 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1439 DEBUG_PRINT2 (" info: 0x%lx\n", \
1440 * (long *) ®_info[this_reg]); \
1442 regend[this_reg] = POP_FAILURE_POINTER (); \
1443 DEBUG_PRINT2 (" end: 0x%lx\n", (long) regend[this_reg]); \
1445 regstart[this_reg] = POP_FAILURE_POINTER (); \
1446 DEBUG_PRINT2 (" start: 0x%lx\n", (long) regstart[this_reg]); \
1449 set_regs_matched_done = 0; \
1450 DEBUG_STATEMENT (nfailure_points_popped++); \
1451 } while (0) /* POP_FAILURE_POINT */
1455 /* Structure for per-register (a.k.a. per-group) information.
1456 Other register information, such as the
1457 starting and ending positions (which are addresses), and the list of
1458 inner groups (which is a bits list) are maintained in separate
1461 We are making a (strictly speaking) nonportable assumption here: that
1462 the compiler will pack our bit fields into something that fits into
1463 the type of `word', i.e., is something that fits into one item on the
1468 fail_stack_elt_t word;
1471 /* This field is one if this group can match the empty string,
1472 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1473 #define MATCH_NULL_UNSET_VALUE 3
1474 unsigned match_null_string_p : 2;
1475 unsigned is_active : 1;
1476 unsigned matched_something : 1;
1477 unsigned ever_matched_something : 1;
1479 } register_info_type;
1481 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1482 #define IS_ACTIVE(R) ((R).bits.is_active)
1483 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1484 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1487 /* Call this when have matched a real character; it sets `matched' flags
1488 for the subexpressions which we are currently inside. Also records
1489 that those subexprs have matched. */
1490 #define SET_REGS_MATCHED() \
1493 if (!set_regs_matched_done) \
1496 set_regs_matched_done = 1; \
1497 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1499 MATCHED_SOMETHING (reg_info[r]) \
1500 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1507 /* Registers are set to a sentinel when they haven't yet matched. */
1508 static unsigned char reg_unset_dummy;
1509 #define REG_UNSET_VALUE (®_unset_dummy)
1510 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1512 /* Subroutine declarations and macros for regex_compile. */
1514 /* Fetch the next character in the uncompiled pattern---translating it
1515 if necessary. Also cast from a signed character in the constant
1516 string passed to us by the user to an unsigned char that we can use
1517 as an array index (in, e.g., `translate'). */
1518 #define PATFETCH(c) \
1521 c = TRANSLATE (c); \
1524 /* Fetch the next character in the uncompiled pattern, with no
1526 #define PATFETCH_RAW(c) \
1527 do {if (p == pend) return REG_EEND; \
1528 assert (p < pend); \
1529 c = charptr_emchar (p); \
1533 /* Go backwards one character in the pattern. */
1534 #define PATUNFETCH DEC_CHARPTR (p)
1538 #define PATFETCH_EXTENDED(emch) \
1539 do {if (p == pend) return REG_EEND; \
1540 assert (p < pend); \
1541 emch = charptr_emchar ((const Bufbyte *) p); \
1543 if (TRANSLATE_P (translate) && emch < 0x80) \
1544 emch = (Emchar) (unsigned char) RE_TRANSLATE (emch); \
1547 #define PATFETCH_RAW_EXTENDED(emch) \
1548 do {if (p == pend) return REG_EEND; \
1549 assert (p < pend); \
1550 emch = charptr_emchar ((const Bufbyte *) p); \
1554 #define PATUNFETCH_EXTENDED DEC_CHARPTR (p)
1556 #define PATFETCH_EITHER(emch) \
1558 if (has_extended_chars) \
1559 PATFETCH_EXTENDED (emch); \
1564 #define PATFETCH_RAW_EITHER(emch) \
1566 if (has_extended_chars) \
1567 PATFETCH_RAW_EXTENDED (emch); \
1569 PATFETCH_RAW (emch); \
1572 #define PATUNFETCH_EITHER \
1574 if (has_extended_chars) \
1575 PATUNFETCH_EXTENDED (emch); \
1577 PATUNFETCH (emch); \
1580 #else /* not MULE */
1582 #define PATFETCH_EITHER(emch) PATFETCH (emch)
1583 #define PATFETCH_RAW_EITHER(emch) PATFETCH_RAW (emch)
1584 #define PATUNFETCH_EITHER PATUNFETCH
1588 /* If `translate' is non-null, return translate[D], else just D. We
1589 cast the subscript to translate because some data is declared as
1590 `char *', to avoid warnings when a string constant is passed. But
1591 when we use a character as a subscript we must make it unsigned. */
1592 #define TRANSLATE(d) (TRANSLATE_P (translate) ? RE_TRANSLATE (d) : (d))
1596 #define TRANSLATE_EXTENDED_UNSAFE(emch) \
1597 (TRANSLATE_P (translate) && emch < 0x80 ? RE_TRANSLATE (emch) : (emch))
1601 /* Macros for outputting the compiled pattern into `buffer'. */
1603 /* If the buffer isn't allocated when it comes in, use this. */
1604 #define INIT_BUF_SIZE 32
1606 /* Make sure we have at least N more bytes of space in buffer. */
1607 #define GET_BUFFER_SPACE(n) \
1608 while (buf_end - bufp->buffer + (n) > (ptrdiff_t) bufp->allocated) \
1611 /* Make sure we have one more byte of buffer space and then add C to it. */
1612 #define BUF_PUSH(c) \
1614 GET_BUFFER_SPACE (1); \
1615 *buf_end++ = (unsigned char) (c); \
1619 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1620 #define BUF_PUSH_2(c1, c2) \
1622 GET_BUFFER_SPACE (2); \
1623 *buf_end++ = (unsigned char) (c1); \
1624 *buf_end++ = (unsigned char) (c2); \
1628 /* As with BUF_PUSH_2, except for three bytes. */
1629 #define BUF_PUSH_3(c1, c2, c3) \
1631 GET_BUFFER_SPACE (3); \
1632 *buf_end++ = (unsigned char) (c1); \
1633 *buf_end++ = (unsigned char) (c2); \
1634 *buf_end++ = (unsigned char) (c3); \
1638 /* Store a jump with opcode OP at LOC to location TO. We store a
1639 relative address offset by the three bytes the jump itself occupies. */
1640 #define STORE_JUMP(op, loc, to) \
1641 store_op1 (op, loc, (to) - (loc) - 3)
1643 /* Likewise, for a two-argument jump. */
1644 #define STORE_JUMP2(op, loc, to, arg) \
1645 store_op2 (op, loc, (to) - (loc) - 3, arg)
1647 /* Like `STORE_JUMP', but for inserting. Assume `buf_end' is the
1649 #define INSERT_JUMP(op, loc, to) \
1650 insert_op1 (op, loc, (to) - (loc) - 3, buf_end)
1652 /* Like `STORE_JUMP2', but for inserting. Assume `buf_end' is the
1654 #define INSERT_JUMP2(op, loc, to, arg) \
1655 insert_op2 (op, loc, (to) - (loc) - 3, arg, buf_end)
1658 /* This is not an arbitrary limit: the arguments which represent offsets
1659 into the pattern are two bytes long. So if 2^16 bytes turns out to
1660 be too small, many things would have to change. */
1661 #define MAX_BUF_SIZE (1L << 16)
1664 /* Extend the buffer by twice its current size via realloc and
1665 reset the pointers that pointed into the old block to point to the
1666 correct places in the new one. If extending the buffer results in it
1667 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1668 #define EXTEND_BUFFER() \
1670 re_char *old_buffer = bufp->buffer; \
1671 if (bufp->allocated == MAX_BUF_SIZE) \
1673 bufp->allocated <<= 1; \
1674 if (bufp->allocated > MAX_BUF_SIZE) \
1675 bufp->allocated = MAX_BUF_SIZE; \
1676 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1677 if (bufp->buffer == NULL) \
1678 return REG_ESPACE; \
1679 /* If the buffer moved, move all the pointers into it. */ \
1680 if (old_buffer != bufp->buffer) \
1682 buf_end = (buf_end - old_buffer) + bufp->buffer; \
1683 begalt = (begalt - old_buffer) + bufp->buffer; \
1684 if (fixup_alt_jump) \
1685 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1687 laststart = (laststart - old_buffer) + bufp->buffer; \
1688 if (pending_exact) \
1689 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1694 /* Since we have one byte reserved for the register number argument to
1695 {start,stop}_memory, the maximum number of groups we can report
1696 things about is what fits in that byte. */
1697 #define MAX_REGNUM 255
1699 /* But patterns can have more than `MAX_REGNUM' registers. We just
1700 ignore the excess. */
1701 typedef unsigned regnum_t;
1704 /* Macros for the compile stack. */
1706 /* Since offsets can go either forwards or backwards, this type needs to
1707 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1708 typedef int pattern_offset_t;
1712 pattern_offset_t begalt_offset;
1713 pattern_offset_t fixup_alt_jump;
1714 pattern_offset_t inner_group_offset;
1715 pattern_offset_t laststart_offset;
1717 } compile_stack_elt_t;
1722 compile_stack_elt_t *stack;
1724 unsigned avail; /* Offset of next open position. */
1725 } compile_stack_type;
1728 #define INIT_COMPILE_STACK_SIZE 32
1730 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1731 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1733 /* The next available element. */
1734 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1737 /* Set the bit for character C in a bit vector. */
1738 #define SET_LIST_BIT(c) \
1739 (buf_end[((unsigned char) (c)) / BYTEWIDTH] \
1740 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1744 /* Set the "bit" for character C in a range table. */
1745 #define SET_RANGETAB_BIT(c) put_range_table (rtab, c, c, Qt)
1747 /* Set the "bit" for character c in the appropriate table. */
1748 #define SET_EITHER_BIT(c) \
1750 if (has_extended_chars) \
1751 SET_RANGETAB_BIT (c); \
1756 #else /* not MULE */
1758 #define SET_EITHER_BIT(c) SET_LIST_BIT (c)
1763 /* Get the next unsigned number in the uncompiled pattern. */
1764 #define GET_UNSIGNED_NUMBER(num) \
1768 while (ISDIGIT (c)) \
1772 num = num * 10 + c - '0'; \
1780 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1782 #define IS_CHAR_CLASS(string) \
1783 (STREQ (string, "alpha") || STREQ (string, "upper") \
1784 || STREQ (string, "lower") || STREQ (string, "digit") \
1785 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1786 || STREQ (string, "space") || STREQ (string, "print") \
1787 || STREQ (string, "punct") || STREQ (string, "graph") \
1788 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1790 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1791 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1792 static void insert_op1 (re_opcode_t op, unsigned char *loc, int arg,
1793 unsigned char *end);
1794 static void insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2,
1795 unsigned char *end);
1796 static re_bool at_begline_loc_p (re_char *pattern, re_char *p,
1797 reg_syntax_t syntax);
1798 static re_bool at_endline_loc_p (re_char *p, re_char *pend, int syntax);
1799 static re_bool group_in_compile_stack (compile_stack_type compile_stack,
1801 static reg_errcode_t compile_range (re_char **p_ptr, re_char *pend,
1802 RE_TRANSLATE_TYPE translate,
1803 reg_syntax_t syntax,
1806 static reg_errcode_t compile_extended_range (re_char **p_ptr,
1808 RE_TRANSLATE_TYPE translate,
1809 reg_syntax_t syntax,
1812 static re_bool group_match_null_string_p (unsigned char **p,
1814 register_info_type *reg_info);
1815 static re_bool alt_match_null_string_p (unsigned char *p, unsigned char *end,
1816 register_info_type *reg_info);
1817 static re_bool common_op_match_null_string_p (unsigned char **p,
1819 register_info_type *reg_info);
1820 static int bcmp_translate (const unsigned char *s1, const unsigned char *s2,
1821 REGISTER int len, RE_TRANSLATE_TYPE translate);
1822 static int re_match_2_internal (struct re_pattern_buffer *bufp,
1823 re_char *string1, int size1,
1824 re_char *string2, int size2, int pos,
1825 struct re_registers *regs, int stop);
1827 #ifndef MATCH_MAY_ALLOCATE
1829 /* If we cannot allocate large objects within re_match_2_internal,
1830 we make the fail stack and register vectors global.
1831 The fail stack, we grow to the maximum size when a regexp
1833 The register vectors, we adjust in size each time we
1834 compile a regexp, according to the number of registers it needs. */
1836 static fail_stack_type fail_stack;
1838 /* Size with which the following vectors are currently allocated.
1839 That is so we can make them bigger as needed,
1840 but never make them smaller. */
1841 static int regs_allocated_size;
1843 static re_char ** regstart, ** regend;
1844 static re_char ** old_regstart, ** old_regend;
1845 static re_char **best_regstart, **best_regend;
1846 static register_info_type *reg_info;
1847 static re_char **reg_dummy;
1848 static register_info_type *reg_info_dummy;
1850 /* Make the register vectors big enough for NUM_REGS registers,
1851 but don't make them smaller. */
1854 regex_grow_registers (int num_regs)
1856 if (num_regs > regs_allocated_size)
1858 RETALLOC_IF (regstart, num_regs, re_char *);
1859 RETALLOC_IF (regend, num_regs, re_char *);
1860 RETALLOC_IF (old_regstart, num_regs, re_char *);
1861 RETALLOC_IF (old_regend, num_regs, re_char *);
1862 RETALLOC_IF (best_regstart, num_regs, re_char *);
1863 RETALLOC_IF (best_regend, num_regs, re_char *);
1864 RETALLOC_IF (reg_info, num_regs, register_info_type);
1865 RETALLOC_IF (reg_dummy, num_regs, re_char *);
1866 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1868 regs_allocated_size = num_regs;
1872 #endif /* not MATCH_MAY_ALLOCATE */
1874 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1875 Returns one of error codes defined in `regex.h', or zero for success.
1877 Assumes the `allocated' (and perhaps `buffer') and `translate'
1878 fields are set in BUFP on entry.
1880 If it succeeds, results are put in BUFP (if it returns an error, the
1881 contents of BUFP are undefined):
1882 `buffer' is the compiled pattern;
1883 `syntax' is set to SYNTAX;
1884 `used' is set to the length of the compiled pattern;
1885 `fastmap_accurate' is zero;
1886 `re_nsub' is the number of subexpressions in PATTERN;
1887 `not_bol' and `not_eol' are zero;
1889 The `fastmap' and `newline_anchor' fields are neither
1890 examined nor set. */
1892 /* Return, freeing storage we allocated. */
1893 #define FREE_STACK_RETURN(value) \
1894 return (free (compile_stack.stack), value)
1896 static reg_errcode_t
1897 regex_compile (re_char *pattern, int size, reg_syntax_t syntax,
1898 struct re_pattern_buffer *bufp)
1900 /* We fetch characters from PATTERN here. We declare these as int
1901 (or possibly long) so that chars above 127 can be used as
1902 array indices. The macros that fetch a character from the pattern
1903 make sure to coerce to unsigned char before assigning, so we won't
1904 get bitten by negative numbers here. */
1905 /* XEmacs change: used to be unsigned char. */
1906 REGISTER EMACS_INT c, c1;
1908 /* A random temporary spot in PATTERN. */
1911 /* Points to the end of the buffer, where we should append. */
1912 REGISTER unsigned char *buf_end;
1914 /* Keeps track of unclosed groups. */
1915 compile_stack_type compile_stack;
1917 /* Points to the current (ending) position in the pattern. */
1918 re_char *p = pattern;
1919 re_char *pend = pattern + size;
1921 /* How to translate the characters in the pattern. */
1922 RE_TRANSLATE_TYPE translate = bufp->translate;
1924 /* Address of the count-byte of the most recently inserted `exactn'
1925 command. This makes it possible to tell if a new exact-match
1926 character can be added to that command or if the character requires
1927 a new `exactn' command. */
1928 unsigned char *pending_exact = 0;
1930 /* Address of start of the most recently finished expression.
1931 This tells, e.g., postfix * where to find the start of its
1932 operand. Reset at the beginning of groups and alternatives. */
1933 unsigned char *laststart = 0;
1935 /* Address of beginning of regexp, or inside of last group. */
1936 unsigned char *begalt;
1938 /* Place in the uncompiled pattern (i.e., the {) to
1939 which to go back if the interval is invalid. */
1940 re_char *beg_interval;
1942 /* Address of the place where a forward jump should go to the end of
1943 the containing expression. Each alternative of an `or' -- except the
1944 last -- ends with a forward jump of this sort. */
1945 unsigned char *fixup_alt_jump = 0;
1947 /* Counts open-groups as they are encountered. Remembered for the
1948 matching close-group on the compile stack, so the same register
1949 number is put in the stop_memory as the start_memory. */
1950 regnum_t regnum = 0;
1953 DEBUG_PRINT1 ("\nCompiling pattern: ");
1958 for (debug_count = 0; debug_count < size; debug_count++)
1959 putchar (pattern[debug_count]);
1964 /* Initialize the compile stack. */
1965 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1966 if (compile_stack.stack == NULL)
1969 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1970 compile_stack.avail = 0;
1972 /* Initialize the pattern buffer. */
1973 bufp->syntax = syntax;
1974 bufp->fastmap_accurate = 0;
1975 bufp->not_bol = bufp->not_eol = 0;
1977 /* Set `used' to zero, so that if we return an error, the pattern
1978 printer (for debugging) will think there's no pattern. We reset it
1982 /* Always count groups, whether or not bufp->no_sub is set. */
1985 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1986 /* Initialize the syntax table. */
1987 init_syntax_once ();
1990 if (bufp->allocated == 0)
1993 { /* If zero allocated, but buffer is non-null, try to realloc
1994 enough space. This loses if buffer's address is bogus, but
1995 that is the user's responsibility. */
1996 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1999 { /* Caller did not allocate a buffer. Do it for them. */
2000 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2002 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2004 bufp->allocated = INIT_BUF_SIZE;
2007 begalt = buf_end = bufp->buffer;
2009 /* Loop through the uncompiled pattern until we're at the end. */
2018 if ( /* If at start of pattern, it's an operator. */
2020 /* If context independent, it's an operator. */
2021 || syntax & RE_CONTEXT_INDEP_ANCHORS
2022 /* Otherwise, depends on what's come before. */
2023 || at_begline_loc_p (pattern, p, syntax))
2033 if ( /* If at end of pattern, it's an operator. */
2035 /* If context independent, it's an operator. */
2036 || syntax & RE_CONTEXT_INDEP_ANCHORS
2037 /* Otherwise, depends on what's next. */
2038 || at_endline_loc_p (p, pend, syntax))
2048 if ((syntax & RE_BK_PLUS_QM)
2049 || (syntax & RE_LIMITED_OPS))
2053 /* If there is no previous pattern... */
2056 if (syntax & RE_CONTEXT_INVALID_OPS)
2057 FREE_STACK_RETURN (REG_BADRPT);
2058 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2063 /* true means zero/many matches are allowed. */
2064 re_bool zero_times_ok = c != '+';
2065 re_bool many_times_ok = c != '?';
2067 /* true means match shortest string possible. */
2068 re_bool minimal = false;
2070 /* If there is a sequence of repetition chars, collapse it
2071 down to just one (the right one). We can't combine
2072 interval operators with these because of, e.g., `a{2}*',
2073 which should only match an even number of `a's. */
2078 if (c == '*' || (!(syntax & RE_BK_PLUS_QM)
2079 && (c == '+' || c == '?')))
2082 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2084 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2087 if (!(c1 == '+' || c1 == '?'))
2102 /* If we get here, we found another repeat character. */
2103 if (!(syntax & RE_NO_MINIMAL_MATCHING))
2105 /* "*?" and "+?" and "??" are okay (and mean match
2106 minimally), but other sequences (such as "*??" and
2107 "+++") are rejected (reserved for future use). */
2108 if (minimal || c != '?')
2109 FREE_STACK_RETURN (REG_BADRPT);
2114 zero_times_ok |= c != '+';
2115 many_times_ok |= c != '?';
2119 /* Star, etc. applied to an empty pattern is equivalent
2120 to an empty pattern. */
2124 /* Now we know whether zero matches is allowed
2125 and whether two or more matches is allowed
2126 and whether we want minimal or maximal matching. */
2132 0: /on_failure_jump to 6
2137 GET_BUFFER_SPACE (6);
2138 INSERT_JUMP (jump, laststart, buf_end + 3);
2140 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2143 else if (zero_times_ok)
2148 6: /on_failure_jump to 3
2151 GET_BUFFER_SPACE (6);
2152 INSERT_JUMP (jump, laststart, buf_end + 3);
2154 STORE_JUMP (on_failure_jump, buf_end, laststart + 3);
2161 3: /on_failure_jump to 0
2164 GET_BUFFER_SPACE (3);
2165 STORE_JUMP (on_failure_jump, buf_end, laststart);
2171 /* Are we optimizing this jump? */
2172 re_bool keep_string_p = false;
2175 { /* More than one repetition is allowed, so put in
2176 at the end a backward relative jump from
2177 `buf_end' to before the next jump we're going
2178 to put in below (which jumps from laststart to
2181 But if we are at the `*' in the exact sequence `.*\n',
2182 insert an unconditional jump backwards to the .,
2183 instead of the beginning of the loop. This way we only
2184 push a failure point once, instead of every time
2185 through the loop. */
2186 assert (p - 1 > pattern);
2188 /* Allocate the space for the jump. */
2189 GET_BUFFER_SPACE (3);
2191 /* We know we are not at the first character of the
2192 pattern, because laststart was nonzero. And we've
2193 already incremented `p', by the way, to be the
2194 character after the `*'. Do we have to do something
2195 analogous here for null bytes, because of
2199 && p < pend && *p == '\n'
2200 && !(syntax & RE_DOT_NEWLINE))
2201 { /* We have .*\n. */
2202 STORE_JUMP (jump, buf_end, laststart);
2203 keep_string_p = true;
2206 /* Anything else. */
2207 STORE_JUMP (maybe_pop_jump, buf_end, laststart - 3);
2209 /* We've added more stuff to the buffer. */
2213 /* On failure, jump from laststart to buf_end + 3,
2214 which will be the end of the buffer after this jump
2216 GET_BUFFER_SPACE (3);
2217 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2219 laststart, buf_end + 3);
2224 /* At least one repetition is required, so insert a
2225 `dummy_failure_jump' before the initial
2226 `on_failure_jump' instruction of the loop. This
2227 effects a skip over that instruction the first time
2228 we hit that loop. */
2229 GET_BUFFER_SPACE (3);
2230 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2240 laststart = buf_end;
2247 /* XEmacs change: this whole section */
2248 re_bool had_char_class = false;
2250 re_bool has_extended_chars = false;
2251 REGISTER Lisp_Object rtab = Qnil;
2254 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2256 /* Ensure that we have enough space to push a charset: the
2257 opcode, the length count, and the bitset; 34 bytes in all. */
2258 GET_BUFFER_SPACE (34);
2260 laststart = buf_end;
2262 /* We test `*p == '^' twice, instead of using an if
2263 statement, so we only need one BUF_PUSH. */
2264 BUF_PUSH (*p == '^' ? charset_not : charset);
2268 /* Remember the first position in the bracket expression. */
2271 /* Push the number of bytes in the bitmap. */
2272 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2274 /* Clear the whole map. */
2275 memset (buf_end, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2277 /* charset_not matches newline according to a syntax bit. */
2278 if ((re_opcode_t) buf_end[-2] == charset_not
2279 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2280 SET_LIST_BIT ('\n');
2283 start_over_with_extended:
2284 if (has_extended_chars)
2286 /* There are extended chars here, which means we need to start
2287 over and shift to unified range-table format. */
2288 if (buf_end[-2] == charset)
2289 buf_end[-2] = charset_mule;
2291 buf_end[-2] = charset_mule_not;
2293 p = p1; /* go back to the beginning of the charset, after
2295 rtab = Vthe_lisp_rangetab;
2296 Fclear_range_table (rtab);
2298 /* charset_not matches newline according to a syntax bit. */
2299 if ((re_opcode_t) buf_end[-1] == charset_mule_not
2300 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2301 SET_EITHER_BIT ('\n');
2305 /* Read in characters and ranges, setting map bits. */
2308 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2313 if (c >= 0x80 && !has_extended_chars)
2315 has_extended_chars = 1;
2316 /* Frumble-bumble, we've found some extended chars.
2317 Need to start over, process everything using
2318 the general extended-char mechanism, and need
2319 to use charset_mule and charset_mule_not instead
2320 of charset and charset_not. */
2321 goto start_over_with_extended;
2324 /* \ might escape characters inside [...] and [^...]. */
2325 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2327 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2331 if (c1 >= 0x80 && !has_extended_chars)
2333 has_extended_chars = 1;
2334 goto start_over_with_extended;
2337 SET_EITHER_BIT (c1);
2341 /* Could be the end of the bracket expression. If it's
2342 not (i.e., when the bracket expression is `[]' so
2343 far), the ']' character bit gets set way below. */
2344 if (c == ']' && p != p1 + 1)
2347 /* Look ahead to see if it's a range when the last thing
2348 was a character class. */
2349 if (had_char_class && c == '-' && *p != ']')
2350 FREE_STACK_RETURN (REG_ERANGE);
2352 /* Look ahead to see if it's a range when the last thing
2353 was a character: if this is a hyphen not at the
2354 beginning or the end of a list, then it's the range
2357 && !(p - 2 >= pattern && p[-2] == '[')
2358 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2364 if (* (unsigned char *) p >= 0x80 && !has_extended_chars)
2366 has_extended_chars = 1;
2367 goto start_over_with_extended;
2369 if (has_extended_chars)
2370 ret = compile_extended_range (&p, pend, translate,
2374 ret = compile_range (&p, pend, translate, syntax, buf_end);
2375 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2378 else if (p[0] == '-' && p[1] != ']')
2379 { /* This handles ranges made up of characters only. */
2382 /* Move past the `-'. */
2386 if (* (unsigned char *) p >= 0x80 && !has_extended_chars)
2388 has_extended_chars = 1;
2389 goto start_over_with_extended;
2391 if (has_extended_chars)
2392 ret = compile_extended_range (&p, pend, translate,
2396 ret = compile_range (&p, pend, translate, syntax, buf_end);
2397 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2400 /* See if we're at the beginning of a possible character
2403 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2404 { /* Leave room for the null. */
2405 char str[CHAR_CLASS_MAX_LENGTH + 1];
2410 /* If pattern is `[[:'. */
2411 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2415 /* #### This code is unused.
2416 Correctness is not checked after TRT
2419 if (c == ':' || c == ']' || p == pend
2420 || c1 == CHAR_CLASS_MAX_LENGTH)
2422 str[c1++] = (char) c;
2426 /* If isn't a word bracketed by `[:' and `:]':
2427 undo the ending character, the letters, and leave
2428 the leading `:' and `[' (but set bits for them). */
2429 if (c == ':' && *p == ']')
2432 re_bool is_alnum = STREQ (str, "alnum");
2433 re_bool is_alpha = STREQ (str, "alpha");
2434 re_bool is_blank = STREQ (str, "blank");
2435 re_bool is_cntrl = STREQ (str, "cntrl");
2436 re_bool is_digit = STREQ (str, "digit");
2437 re_bool is_graph = STREQ (str, "graph");
2438 re_bool is_lower = STREQ (str, "lower");
2439 re_bool is_print = STREQ (str, "print");
2440 re_bool is_punct = STREQ (str, "punct");
2441 re_bool is_space = STREQ (str, "space");
2442 re_bool is_upper = STREQ (str, "upper");
2443 re_bool is_xdigit = STREQ (str, "xdigit");
2445 if (!IS_CHAR_CLASS (str))
2446 FREE_STACK_RETURN (REG_ECTYPE);
2448 /* Throw away the ] at the end of the character
2452 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2454 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2456 /* This was split into 3 if's to
2457 avoid an arbitrary limit in some compiler. */
2458 if ( (is_alnum && ISALNUM (ch))
2459 || (is_alpha && ISALPHA (ch))
2460 || (is_blank && ISBLANK (ch))
2461 || (is_cntrl && ISCNTRL (ch)))
2462 SET_EITHER_BIT (ch);
2463 if ( (is_digit && ISDIGIT (ch))
2464 || (is_graph && ISGRAPH (ch))
2465 || (is_lower && ISLOWER (ch))
2466 || (is_print && ISPRINT (ch)))
2467 SET_EITHER_BIT (ch);
2468 if ( (is_punct && ISPUNCT (ch))
2469 || (is_space && ISSPACE (ch))
2470 || (is_upper && ISUPPER (ch))
2471 || (is_xdigit && ISXDIGIT (ch)))
2472 SET_EITHER_BIT (ch);
2474 had_char_class = true;
2481 SET_EITHER_BIT ('[');
2482 SET_EITHER_BIT (':');
2483 had_char_class = false;
2488 had_char_class = false;
2494 if (has_extended_chars)
2496 /* We have a range table, not a bit vector. */
2498 unified_range_table_bytes_needed (rtab);
2499 GET_BUFFER_SPACE (bytes_needed);
2500 unified_range_table_copy_data (rtab, buf_end);
2501 buf_end += unified_range_table_bytes_used (buf_end);
2505 /* Discard any (non)matching list bytes that are all 0 at the
2506 end of the map. Decrease the map-length byte too. */
2507 while ((int) buf_end[-1] > 0 && buf_end[buf_end[-1] - 1] == 0)
2509 buf_end += buf_end[-1];
2515 if (syntax & RE_NO_BK_PARENS)
2522 if (syntax & RE_NO_BK_PARENS)
2529 if (syntax & RE_NEWLINE_ALT)
2536 if (syntax & RE_NO_BK_VBAR)
2543 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2544 goto handle_interval;
2550 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2552 /* Do not translate the character after the \, so that we can
2553 distinguish, e.g., \B from \b, even if we normally would
2554 translate, e.g., B to b. */
2560 if (syntax & RE_NO_BK_PARENS)
2561 goto normal_backslash;
2567 if (!(syntax & RE_NO_SHY_GROUPS)
2575 case ':': /* shy groups */
2579 /* All others are reserved for future constructs. */
2581 FREE_STACK_RETURN (REG_BADPAT);
2590 if (COMPILE_STACK_FULL)
2592 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2593 compile_stack_elt_t);
2594 if (compile_stack.stack == NULL) return REG_ESPACE;
2596 compile_stack.size <<= 1;
2599 /* These are the values to restore when we hit end of this
2600 group. They are all relative offsets, so that if the
2601 whole pattern moves because of realloc, they will still
2603 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2604 COMPILE_STACK_TOP.fixup_alt_jump
2605 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2606 COMPILE_STACK_TOP.laststart_offset = buf_end - bufp->buffer;
2607 COMPILE_STACK_TOP.regnum = r;
2609 /* We will eventually replace the 0 with the number of
2610 groups inner to this one. But do not push a
2611 start_memory for groups beyond the last one we can
2612 represent in the compiled pattern. */
2613 if (r <= MAX_REGNUM)
2615 COMPILE_STACK_TOP.inner_group_offset
2616 = buf_end - bufp->buffer + 2;
2617 BUF_PUSH_3 (start_memory, r, 0);
2620 compile_stack.avail++;
2625 /* If we've reached MAX_REGNUM groups, then this open
2626 won't actually generate any code, so we'll have to
2627 clear pending_exact explicitly. */
2634 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2636 if (COMPILE_STACK_EMPTY) {
2637 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2638 goto normal_backslash;
2640 FREE_STACK_RETURN (REG_ERPAREN);
2645 { /* Push a dummy failure point at the end of the
2646 alternative for a possible future
2647 `pop_failure_jump' to pop. See comments at
2648 `push_dummy_failure' in `re_match_2'. */
2649 BUF_PUSH (push_dummy_failure);
2651 /* We allocated space for this jump when we assigned
2652 to `fixup_alt_jump', in the `handle_alt' case below. */
2653 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end - 1);
2656 /* See similar code for backslashed left paren above. */
2657 if (COMPILE_STACK_EMPTY) {
2658 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2661 FREE_STACK_RETURN (REG_ERPAREN);
2664 /* Since we just checked for an empty stack above, this
2665 ``can't happen''. */
2666 assert (compile_stack.avail != 0);
2668 /* We don't just want to restore into `regnum', because
2669 later groups should continue to be numbered higher,
2670 as in `(ab)c(de)' -- the second group is #2. */
2671 regnum_t this_group_regnum;
2673 compile_stack.avail--;
2674 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2676 = COMPILE_STACK_TOP.fixup_alt_jump
2677 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2679 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2680 this_group_regnum = COMPILE_STACK_TOP.regnum;
2681 /* If we've reached MAX_REGNUM groups, then this open
2682 won't actually generate any code, so we'll have to
2683 clear pending_exact explicitly. */
2686 /* We're at the end of the group, so now we know how many
2687 groups were inside this one. */
2688 if (this_group_regnum <= MAX_REGNUM)
2690 unsigned char *inner_group_loc
2691 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2693 *inner_group_loc = regnum - this_group_regnum;
2694 BUF_PUSH_3 (stop_memory, this_group_regnum,
2695 regnum - this_group_regnum);
2701 case '|': /* `\|'. */
2702 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2703 goto normal_backslash;
2705 if (syntax & RE_LIMITED_OPS)
2708 /* Insert before the previous alternative a jump which
2709 jumps to this alternative if the former fails. */
2710 GET_BUFFER_SPACE (3);
2711 INSERT_JUMP (on_failure_jump, begalt, buf_end + 6);
2715 /* The alternative before this one has a jump after it
2716 which gets executed if it gets matched. Adjust that
2717 jump so it will jump to this alternative's analogous
2718 jump (put in below, which in turn will jump to the next
2719 (if any) alternative's such jump, etc.). The last such
2720 jump jumps to the correct final destination. A picture:
2726 If we are at `b', then fixup_alt_jump right now points to a
2727 three-byte space after `a'. We'll put in the jump, set
2728 fixup_alt_jump to right after `b', and leave behind three
2729 bytes which we'll fill in when we get to after `c'. */
2732 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end);
2734 /* Mark and leave space for a jump after this alternative,
2735 to be filled in later either by next alternative or
2736 when know we're at the end of a series of alternatives. */
2737 fixup_alt_jump = buf_end;
2738 GET_BUFFER_SPACE (3);
2747 /* If \{ is a literal. */
2748 if (!(syntax & RE_INTERVALS)
2749 /* If we're at `\{' and it's not the open-interval
2751 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2752 || (p - 2 == pattern && p == pend))
2753 goto normal_backslash;
2757 /* If got here, then the syntax allows intervals. */
2759 /* At least (most) this many matches must be made. */
2760 int lower_bound = -1, upper_bound = -1;
2762 beg_interval = p - 1;
2766 if (syntax & RE_NO_BK_BRACES)
2767 goto unfetch_interval;
2769 FREE_STACK_RETURN (REG_EBRACE);
2772 GET_UNSIGNED_NUMBER (lower_bound);
2776 GET_UNSIGNED_NUMBER (upper_bound);
2777 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2780 /* Interval such as `{1}' => match exactly once. */
2781 upper_bound = lower_bound;
2783 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2784 || lower_bound > upper_bound)
2786 if (syntax & RE_NO_BK_BRACES)
2787 goto unfetch_interval;
2789 FREE_STACK_RETURN (REG_BADBR);
2792 if (!(syntax & RE_NO_BK_BRACES))
2794 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2801 if (syntax & RE_NO_BK_BRACES)
2802 goto unfetch_interval;
2804 FREE_STACK_RETURN (REG_BADBR);
2807 /* We just parsed a valid interval. */
2809 /* If it's invalid to have no preceding re. */
2812 if (syntax & RE_CONTEXT_INVALID_OPS)
2813 FREE_STACK_RETURN (REG_BADRPT);
2814 else if (syntax & RE_CONTEXT_INDEP_OPS)
2815 laststart = buf_end;
2817 goto unfetch_interval;
2820 /* If the upper bound is zero, don't want to succeed at
2821 all; jump from `laststart' to `b + 3', which will be
2822 the end of the buffer after we insert the jump. */
2823 if (upper_bound == 0)
2825 GET_BUFFER_SPACE (3);
2826 INSERT_JUMP (jump, laststart, buf_end + 3);
2830 /* Otherwise, we have a nontrivial interval. When
2831 we're all done, the pattern will look like:
2832 set_number_at <jump count> <upper bound>
2833 set_number_at <succeed_n count> <lower bound>
2834 succeed_n <after jump addr> <succeed_n count>
2836 jump_n <succeed_n addr> <jump count>
2837 (The upper bound and `jump_n' are omitted if
2838 `upper_bound' is 1, though.) */
2840 { /* If the upper bound is > 1, we need to insert
2841 more at the end of the loop. */
2842 Memory_count nbytes = 10 + (upper_bound > 1) * 10;
2844 GET_BUFFER_SPACE (nbytes);
2846 /* Initialize lower bound of the `succeed_n', even
2847 though it will be set during matching by its
2848 attendant `set_number_at' (inserted next),
2849 because `re_compile_fastmap' needs to know.
2850 Jump to the `jump_n' we might insert below. */
2851 INSERT_JUMP2 (succeed_n, laststart,
2852 buf_end + 5 + (upper_bound > 1) * 5,
2856 /* Code to initialize the lower bound. Insert
2857 before the `succeed_n'. The `5' is the last two
2858 bytes of this `set_number_at', plus 3 bytes of
2859 the following `succeed_n'. */
2860 insert_op2 (set_number_at, laststart, 5, lower_bound, buf_end);
2863 if (upper_bound > 1)
2864 { /* More than one repetition is allowed, so
2865 append a backward jump to the `succeed_n'
2866 that starts this interval.
2868 When we've reached this during matching,
2869 we'll have matched the interval once, so
2870 jump back only `upper_bound - 1' times. */
2871 STORE_JUMP2 (jump_n, buf_end, laststart + 5,
2875 /* The location we want to set is the second
2876 parameter of the `jump_n'; that is `b-2' as
2877 an absolute address. `laststart' will be
2878 the `set_number_at' we're about to insert;
2879 `laststart+3' the number to set, the source
2880 for the relative address. But we are
2881 inserting into the middle of the pattern --
2882 so everything is getting moved up by 5.
2883 Conclusion: (b - 2) - (laststart + 3) + 5,
2884 i.e., b - laststart.
2886 We insert this at the beginning of the loop
2887 so that if we fail during matching, we'll
2888 reinitialize the bounds. */
2889 insert_op2 (set_number_at, laststart,
2890 buf_end - laststart,
2891 upper_bound - 1, buf_end);
2896 beg_interval = NULL;
2901 /* If an invalid interval, match the characters as literals. */
2902 assert (beg_interval);
2904 beg_interval = NULL;
2906 /* normal_char and normal_backslash need `c'. */
2909 if (!(syntax & RE_NO_BK_BRACES))
2911 if (p > pattern && p[-1] == '\\')
2912 goto normal_backslash;
2917 /* There is no way to specify the before_dot and after_dot
2918 operators. rms says this is ok. --karl */
2924 laststart = buf_end;
2926 /* XEmacs addition */
2927 if (c >= 0x80 || syntax_spec_code[c] == 0377)
2928 FREE_STACK_RETURN (REG_ESYNTAX);
2929 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2933 laststart = buf_end;
2935 /* XEmacs addition */
2936 if (c >= 0x80 || syntax_spec_code[c] == 0377)
2937 FREE_STACK_RETURN (REG_ESYNTAX);
2938 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2942 /* 97.2.17 jhod merged in to XEmacs from mule-2.3 */
2944 laststart = buf_end;
2946 if (c < 32 || c > 127)
2947 FREE_STACK_RETURN (REG_ECATEGORY);
2948 BUF_PUSH_2 (categoryspec, c);
2952 laststart = buf_end;
2954 if (c < 32 || c > 127)
2955 FREE_STACK_RETURN (REG_ECATEGORY);
2956 BUF_PUSH_2 (notcategoryspec, c);
2958 /* end of category patch */
2964 laststart = buf_end;
2965 BUF_PUSH (wordchar);
2970 laststart = buf_end;
2971 BUF_PUSH (notwordchar);
2984 BUF_PUSH (wordbound);
2988 BUF_PUSH (notwordbound);
2999 case '1': case '2': case '3': case '4': case '5':
3000 case '6': case '7': case '8': case '9':
3003 if (syntax & RE_NO_BK_REFS)
3009 FREE_STACK_RETURN (REG_ESUBREG);
3011 /* Can't back reference to a subexpression if inside of it. */
3012 if (group_in_compile_stack (compile_stack, reg))
3015 laststart = buf_end;
3016 BUF_PUSH_2 (duplicate, reg);
3023 if (syntax & RE_BK_PLUS_QM)
3026 goto normal_backslash;
3030 /* You might think it would be useful for \ to mean
3031 not to translate; but if we don't translate it,
3032 it will never match anything. */
3040 /* Expects the character in `c'. */
3041 /* `p' points to the location after where `c' came from. */
3044 /* XEmacs: modifications here for Mule. */
3045 /* `q' points to the beginning of the next char. */
3048 /* If no exactn currently being built. */
3051 /* If last exactn not at current position. */
3052 || pending_exact + *pending_exact + 1 != buf_end
3054 /* We have only one byte following the exactn for the count. */
3055 || ((unsigned int) (*pending_exact + (q - p)) >=
3056 ((unsigned int) (1 << BYTEWIDTH) - 1))
3058 /* If followed by a repetition operator. */
3059 || *q == '*' || *q == '^'
3060 || ((syntax & RE_BK_PLUS_QM)
3061 ? *q == '\\' && (q[1] == '+' || q[1] == '?')
3062 : (*q == '+' || *q == '?'))
3063 || ((syntax & RE_INTERVALS)
3064 && ((syntax & RE_NO_BK_BRACES)
3066 : (q[0] == '\\' && q[1] == '{'))))
3068 /* Start building a new exactn. */
3070 laststart = buf_end;
3072 BUF_PUSH_2 (exactn, 0);
3073 pending_exact = buf_end - 1;
3082 Bufbyte tmp_buf[MAX_EMCHAR_LEN];
3085 bt_count = set_charptr_emchar (tmp_buf, c);
3087 for (i = 0; i < bt_count; i++)
3089 BUF_PUSH (tmp_buf[i]);
3097 } /* while p != pend */
3100 /* Through the pattern now. */
3103 STORE_JUMP (jump_past_alt, fixup_alt_jump, buf_end);
3105 if (!COMPILE_STACK_EMPTY)
3106 FREE_STACK_RETURN (REG_EPAREN);
3108 /* If we don't want backtracking, force success
3109 the first time we reach the end of the compiled pattern. */
3110 if (syntax & RE_NO_POSIX_BACKTRACKING)
3113 free (compile_stack.stack);
3115 /* We have succeeded; set the length of the buffer. */
3116 bufp->used = buf_end - bufp->buffer;
3121 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3122 print_compiled_pattern (bufp);
3126 #ifndef MATCH_MAY_ALLOCATE
3127 /* Initialize the failure stack to the largest possible stack. This
3128 isn't necessary unless we're trying to avoid calling alloca in
3129 the search and match routines. */
3131 int num_regs = bufp->re_nsub + 1;
3133 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
3134 is strictly greater than re_max_failures, the largest possible stack
3135 is 2 * re_max_failures failure points. */
3136 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
3138 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
3141 if (! fail_stack.stack)
3143 = (fail_stack_elt_t *) xmalloc (fail_stack.size
3144 * sizeof (fail_stack_elt_t));
3147 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
3149 * sizeof (fail_stack_elt_t)));
3150 #else /* not emacs */
3151 if (! fail_stack.stack)
3153 = (fail_stack_elt_t *) malloc (fail_stack.size
3154 * sizeof (fail_stack_elt_t));
3157 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3159 * sizeof (fail_stack_elt_t)));
3163 regex_grow_registers (num_regs);
3165 #endif /* not MATCH_MAY_ALLOCATE */
3168 } /* regex_compile */
3170 /* Subroutines for `regex_compile'. */
3172 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3175 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3177 *loc = (unsigned char) op;
3178 STORE_NUMBER (loc + 1, arg);
3182 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3185 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3187 *loc = (unsigned char) op;
3188 STORE_NUMBER (loc + 1, arg1);
3189 STORE_NUMBER (loc + 3, arg2);
3193 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3194 for OP followed by two-byte integer parameter ARG. */
3197 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3199 REGISTER unsigned char *pfrom = end;
3200 REGISTER unsigned char *pto = end + 3;
3202 while (pfrom != loc)
3205 store_op1 (op, loc, arg);
3209 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3212 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2,
3215 REGISTER unsigned char *pfrom = end;
3216 REGISTER unsigned char *pto = end + 5;
3218 while (pfrom != loc)
3221 store_op2 (op, loc, arg1, arg2);
3225 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3226 after an alternative or a begin-subexpression. We assume there is at
3227 least one character before the ^. */
3230 at_begline_loc_p (re_char *pattern, re_char *p, reg_syntax_t syntax)
3232 re_char *prev = p - 2;
3233 re_bool prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3236 /* After a subexpression? */
3237 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3238 /* After an alternative? */
3239 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3243 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3244 at least one character after the $, i.e., `P < PEND'. */
3247 at_endline_loc_p (re_char *p, re_char *pend, int syntax)
3250 re_bool next_backslash = *next == '\\';
3251 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3254 /* Before a subexpression? */
3255 (syntax & RE_NO_BK_PARENS ? *next == ')'
3256 : next_backslash && next_next && *next_next == ')')
3257 /* Before an alternative? */
3258 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3259 : next_backslash && next_next && *next_next == '|');
3263 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3264 false if it's not. */
3267 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3271 for (this_element = compile_stack.avail - 1;
3274 if (compile_stack.stack[this_element].regnum == regnum)
3281 /* Read the ending character of a range (in a bracket expression) from the
3282 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3283 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3284 Then we set the translation of all bits between the starting and
3285 ending characters (inclusive) in the compiled pattern B.
3287 Return an error code.
3289 We use these short variable names so we can use the same macros as
3290 `regex_compile' itself. */
3292 static reg_errcode_t
3293 compile_range (re_char **p_ptr, re_char *pend, RE_TRANSLATE_TYPE translate,
3294 reg_syntax_t syntax, unsigned char *buf_end)
3296 Element_count this_char;
3298 re_char *p = *p_ptr;
3299 int range_start, range_end;
3304 /* Even though the pattern is a signed `char *', we need to fetch
3305 with unsigned char *'s; if the high bit of the pattern character
3306 is set, the range endpoints will be negative if we fetch using a
3309 We also want to fetch the endpoints without translating them; the
3310 appropriate translation is done in the bit-setting loop below. */
3311 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
3312 range_start = ((const unsigned char *) p)[-2];
3313 range_end = ((const unsigned char *) p)[0];
3315 /* Have to increment the pointer into the pattern string, so the
3316 caller isn't still at the ending character. */
3319 /* If the start is after the end, the range is empty. */
3320 if (range_start > range_end)
3321 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3323 /* Here we see why `this_char' has to be larger than an `unsigned
3324 char' -- the range is inclusive, so if `range_end' == 0xff
3325 (assuming 8-bit characters), we would otherwise go into an infinite
3326 loop, since all characters <= 0xff. */
3327 for (this_char = range_start; this_char <= range_end; this_char++)
3329 SET_LIST_BIT (TRANSLATE (this_char));
3337 static reg_errcode_t
3338 compile_extended_range (re_char **p_ptr, re_char *pend,
3339 RE_TRANSLATE_TYPE translate,
3340 reg_syntax_t syntax, Lisp_Object rtab)
3342 Emchar this_char, range_start, range_end;
3348 p = (const Bufbyte *) *p_ptr;
3349 range_end = charptr_emchar (p);
3350 p--; /* back to '-' */
3351 DEC_CHARPTR (p); /* back to start of range */
3352 /* We also want to fetch the endpoints without translating them; the
3353 appropriate translation is done in the bit-setting loop below. */
3354 range_start = charptr_emchar (p);
3355 INC_CHARPTR (*p_ptr);
3357 /* If the start is after the end, the range is empty. */
3358 if (range_start > range_end)
3359 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3361 /* Can't have ranges spanning different charsets, except maybe for
3362 ranges entirely within the first 256 chars. */
3364 if ((range_start >= 0x100 || range_end >= 0x100)
3365 && CHAR_LEADING_BYTE (range_start) !=
3366 CHAR_LEADING_BYTE (range_end))
3367 return REG_ERANGESPAN;
3369 /* As advertised, translations only work over the 0 - 0x7F range.
3370 Making this kind of stuff work generally is much harder.
3371 Iterating over the whole range like this would be way efficient
3372 if the range encompasses 10,000 chars or something. You'd have
3373 to do something like this:
3377 map over translation table in [range_start, range_end] of
3378 (put the mapped range in a;
3379 put the translation in b)
3380 invert the range in a and truncate to [range_start, range_end]
3381 compute the union of a, b
3382 union the result into rtab
3384 for (this_char = range_start;
3385 this_char <= range_end && this_char < 0x80; this_char++)
3387 SET_RANGETAB_BIT (TRANSLATE (this_char));
3390 if (this_char <= range_end)
3391 put_range_table (rtab, this_char, range_end, Qt);
3398 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3399 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3400 characters can start a string that matches the pattern. This fastmap
3401 is used by re_search to skip quickly over impossible starting points.
3403 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3404 area as BUFP->fastmap.
3406 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3409 Returns 0 if we succeed, -2 if an internal error. */
3412 re_compile_fastmap (struct re_pattern_buffer *bufp)
3415 #ifdef MATCH_MAY_ALLOCATE
3416 fail_stack_type fail_stack;
3418 DECLARE_DESTINATION;
3419 /* We don't push any register information onto the failure stack. */
3421 REGISTER char *fastmap = bufp->fastmap;
3422 unsigned char *pattern = bufp->buffer;
3423 unsigned long size = bufp->used;
3424 unsigned char *p = pattern;
3425 REGISTER unsigned char *pend = pattern + size;
3428 /* This holds the pointer to the failure stack, when
3429 it is allocated relocatably. */
3430 fail_stack_elt_t *failure_stack_ptr;
3433 /* Assume that each path through the pattern can be null until
3434 proven otherwise. We set this false at the bottom of switch
3435 statement, to which we get only if a particular path doesn't
3436 match the empty string. */
3437 re_bool path_can_be_null = true;
3439 /* We aren't doing a `succeed_n' to begin with. */
3440 re_bool succeed_n_p = false;
3442 assert (fastmap != NULL && p != NULL);
3445 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3446 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3447 bufp->can_be_null = 0;
3451 if (p == pend || *p == succeed)
3453 /* We have reached the (effective) end of pattern. */
3454 if (!FAIL_STACK_EMPTY ())
3456 bufp->can_be_null |= path_can_be_null;
3458 /* Reset for next path. */
3459 path_can_be_null = true;
3461 p = (unsigned char *) fail_stack.stack[--fail_stack.avail].pointer;
3469 /* We should never be about to go beyond the end of the pattern. */
3472 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3475 /* I guess the idea here is to simply not bother with a fastmap
3476 if a backreference is used, since it's too hard to figure out
3477 the fastmap for the corresponding group. Setting
3478 `can_be_null' stops `re_search_2' from using the fastmap, so
3479 that is all we do. */
3481 bufp->can_be_null = 1;
3485 /* Following are the cases which match a character. These end
3494 /* XEmacs: Under Mule, these bit vectors will
3495 only contain values for characters below 0x80. */
3496 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3497 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3503 /* Chars beyond end of map must be allowed. */
3505 for (j = *p * BYTEWIDTH; j < 0x80; j++)
3507 /* And all extended characters must be allowed, too. */
3508 for (j = 0x80; j < 0xA0; j++)
3510 #else /* not MULE */
3511 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3515 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3516 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3526 nentries = unified_range_table_nentries (p);
3527 for (i = 0; i < nentries; i++)
3529 EMACS_INT first, last;
3530 Lisp_Object dummy_val;
3532 Bufbyte strr[MAX_EMCHAR_LEN];
3534 unified_range_table_get_range (p, i, &first, &last,
3536 for (jj = first; jj <= last && jj < 0x80; jj++)
3538 /* Ranges below 0x100 can span charsets, but there
3539 are only two (Control-1 and Latin-1), and
3540 either first or last has to be in them. */
3541 set_charptr_emchar (strr, first);
3545 set_charptr_emchar (strr, last);
3552 case charset_mule_not:
3557 nentries = unified_range_table_nentries (p);
3558 for (i = 0; i < nentries; i++)
3560 EMACS_INT first, last;
3561 Lisp_Object dummy_val;
3563 int smallest_prev = 0;
3565 unified_range_table_get_range (p, i, &first, &last,
3567 for (jj = smallest_prev; jj < first && jj < 0x80; jj++)
3569 smallest_prev = last + 1;
3570 if (smallest_prev >= 0x80)
3573 /* Calculating which leading bytes are actually allowed
3574 here is rather difficult, so we just punt and allow
3576 for (i = 0x80; i < 0xA0; i++)
3588 for (j = 0; j < (1 << BYTEWIDTH); j++)
3591 (regex_emacs_buffer->mirror_syntax_table), j) == Sword)
3600 goto matchnotsyntax;
3602 for (j = 0; j < (1 << BYTEWIDTH); j++)
3605 (regex_emacs_buffer->mirror_syntax_table), j) != Sword)
3613 int fastmap_newline = fastmap['\n'];
3615 /* `.' matches anything ... */
3617 /* "anything" only includes bytes that can be the
3618 first byte of a character. */
3619 for (j = 0; j < 0xA0; j++)
3622 for (j = 0; j < (1 << BYTEWIDTH); j++)
3626 /* ... except perhaps newline. */
3627 if (!(bufp->syntax & RE_DOT_NEWLINE))
3628 fastmap['\n'] = fastmap_newline;
3630 /* Return if we have already set `can_be_null'; if we have,
3631 then the fastmap is irrelevant. Something's wrong here. */
3632 else if (bufp->can_be_null)
3635 /* Otherwise, have to check alternative paths. */
3646 /* This match depends on text properties. These end with
3647 aborting optimizations. */
3648 bufp->can_be_null = 1;
3652 #if 0 /* Removed during syntax-table properties patch -- 2000/12/07 mct */
3658 for (j = 0; j < 0x80; j++)
3661 (regex_emacs_buffer->mirror_syntax_table), j) ==
3662 (enum syntaxcode) k)
3664 for (j = 0x80; j < 0xA0; j++)
3666 if (LEADING_BYTE_PREFIX_P(j))
3667 /* too complicated to calculate this right */
3674 cset = CHARSET_BY_LEADING_BYTE (j);
3675 if (CHARSETP (cset))
3677 if (charset_syntax (regex_emacs_buffer, cset,
3679 == Sword || multi_p)
3684 #else /* not MULE */
3685 for (j = 0; j < (1 << BYTEWIDTH); j++)
3688 (regex_emacs_buffer->mirror_syntax_table), j) ==
3689 (enum syntaxcode) k)
3695 #if 0 /* Removed during syntax-table properties patch -- 2000/12/07 mct */
3701 for (j = 0; j < 0x80; j++)
3704 (regex_emacs_buffer->mirror_syntax_table), j) !=
3705 (enum syntaxcode) k)
3707 for (j = 0x80; j < 0xA0; j++)
3709 if (LEADING_BYTE_PREFIX_P(j))
3710 /* too complicated to calculate this right */
3717 cset = CHARSET_BY_LEADING_BYTE (j);
3718 if (CHARSETP (cset))
3720 if (charset_syntax (regex_emacs_buffer, cset,
3722 != Sword || multi_p)
3727 #else /* not MULE */
3728 for (j = 0; j < (1 << BYTEWIDTH); j++)
3731 (regex_emacs_buffer->mirror_syntax_table), j) !=
3732 (enum syntaxcode) k)
3739 /* 97/2/17 jhod category patch */
3741 case notcategoryspec:
3742 bufp->can_be_null = 1;
3744 /* end if category patch */
3747 /* All cases after this match the empty string. These end with
3769 case push_dummy_failure:
3774 case pop_failure_jump:
3775 case maybe_pop_jump:
3778 case dummy_failure_jump:
3779 EXTRACT_NUMBER_AND_INCR (j, p);
3784 /* Jump backward implies we just went through the body of a
3785 loop and matched nothing. Opcode jumped to should be
3786 `on_failure_jump' or `succeed_n'. Just treat it like an
3787 ordinary jump. For a * loop, it has pushed its failure
3788 point already; if so, discard that as redundant. */
3789 if ((re_opcode_t) *p != on_failure_jump
3790 && (re_opcode_t) *p != succeed_n)
3794 EXTRACT_NUMBER_AND_INCR (j, p);
3797 /* If what's on the stack is where we are now, pop it. */
3798 if (!FAIL_STACK_EMPTY ()
3799 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3805 case on_failure_jump:
3806 case on_failure_keep_string_jump:
3807 handle_on_failure_jump:
3808 EXTRACT_NUMBER_AND_INCR (j, p);
3810 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3811 end of the pattern. We don't want to push such a point,
3812 since when we restore it above, entering the switch will
3813 increment `p' past the end of the pattern. We don't need
3814 to push such a point since we obviously won't find any more
3815 fastmap entries beyond `pend'. Such a pattern can match
3816 the null string, though. */
3819 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3821 RESET_FAIL_STACK ();
3826 bufp->can_be_null = 1;
3830 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3831 succeed_n_p = false;
3838 /* Get to the number of times to succeed. */
3841 /* Increment p past the n for when k != 0. */
3842 EXTRACT_NUMBER_AND_INCR (k, p);
3846 succeed_n_p = true; /* Spaghetti code alert. */
3847 goto handle_on_failure_jump;
3864 abort (); /* We have listed all the cases. */
3867 /* Getting here means we have found the possible starting
3868 characters for one path of the pattern -- and that the empty
3869 string does not match. We need not follow this path further.
3870 Instead, look at the next alternative (remembered on the
3871 stack), or quit if no more. The test at the top of the loop
3872 does these things. */
3873 path_can_be_null = false;
3877 /* Set `can_be_null' for the last path (also the first path, if the
3878 pattern is empty). */
3879 bufp->can_be_null |= path_can_be_null;
3882 RESET_FAIL_STACK ();
3884 } /* re_compile_fastmap */
3886 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3887 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3888 this memory for recording register information. STARTS and ENDS
3889 must be allocated using the malloc library routine, and must each
3890 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3892 If NUM_REGS == 0, then subsequent matches should allocate their own
3895 Unless this function is called, the first search or match using
3896 PATTERN_BUFFER will allocate its own register data, without
3897 freeing the old data. */
3900 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs,
3901 unsigned num_regs, regoff_t *starts, regoff_t *ends)
3905 bufp->regs_allocated = REGS_REALLOCATE;
3906 regs->num_regs = num_regs;
3907 regs->start = starts;
3912 bufp->regs_allocated = REGS_UNALLOCATED;
3914 regs->start = regs->end = (regoff_t *) 0;
3918 /* Searching routines. */
3920 /* Like re_search_2, below, but only one string is specified, and
3921 doesn't let you say where to stop matching. */
3924 re_search (struct re_pattern_buffer *bufp, const char *string, int size,
3925 int startpos, int range, struct re_registers *regs)
3927 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3932 /* Snarfed from src/lisp.h, needed for compiling [ce]tags. */
3933 # define bytecount_to_charcount(ptr, len) (len)
3934 # define charcount_to_bytecount(ptr, len) (len)
3935 typedef int Charcount;
3938 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3939 virtual concatenation of STRING1 and STRING2, starting first at index
3940 STARTPOS, then at STARTPOS + 1, and so on.
3942 With MULE, STARTPOS is a byte position, not a char position. And the
3943 search will increment STARTPOS by the width of the current leading
3946 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3948 RANGE is how far to scan while trying to match. RANGE = 0 means try
3949 only at STARTPOS; in general, the last start tried is STARTPOS +
3952 With MULE, RANGE is a byte position, not a char position. The last
3953 start tried is the character starting <= STARTPOS + RANGE.
3955 In REGS, return the indices of the virtual concatenation of STRING1
3956 and STRING2 that matched the entire BUFP->buffer and its contained
3959 Do not consider matching one past the index STOP in the virtual
3960 concatenation of STRING1 and STRING2.
3962 We return either the position in the strings at which the match was
3963 found, -1 if no match, or -2 if error (such as failure
3967 re_search_2 (struct re_pattern_buffer *bufp, const char *str1,
3968 int size1, const char *str2, int size2, int startpos,
3969 int range, struct re_registers *regs, int stop)
3972 re_char *string1 = (re_char *) str1;
3973 re_char *string2 = (re_char *) str2;
3974 REGISTER char *fastmap = bufp->fastmap;
3975 REGISTER RE_TRANSLATE_TYPE translate = bufp->translate;
3976 int total_size = size1 + size2;
3977 int endpos = startpos + range;
3978 #ifdef REGEX_BEGLINE_CHECK
3979 int anchored_at_begline = 0;
3984 /* Check for out-of-range STARTPOS. */
3985 if (startpos < 0 || startpos > total_size)
3988 /* Fix up RANGE if it might eventually take us outside
3989 the virtual concatenation of STRING1 and STRING2. */
3991 range = 0 - startpos;
3992 else if (endpos > total_size)
3993 range = total_size - startpos;
3995 /* If the search isn't to be a backwards one, don't waste time in a
3996 search for a pattern that must be anchored. */
3997 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4003 d = ((const unsigned char *)
4004 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4005 range = charcount_to_bytecount (d, 1);
4010 /* In a forward search for something that starts with \=.
4011 don't keep searching past point. */
4012 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4014 range = BUF_PT (regex_emacs_buffer) - BUF_BEGV (regex_emacs_buffer)
4021 /* Update the fastmap now if not correct already. */
4022 if (fastmap && !bufp->fastmap_accurate)
4023 if (re_compile_fastmap (bufp) == -2)
4026 #ifdef REGEX_BEGLINE_CHECK
4028 unsigned long i = 0;
4030 while (i < bufp->used)
4032 if (bufp->buffer[i] == start_memory ||
4033 bufp->buffer[i] == stop_memory)
4038 anchored_at_begline = i < bufp->used && bufp->buffer[i] == begline;
4043 SETUP_SYNTAX_CACHE_FOR_OBJECT (regex_match_object,
4045 SYNTAX_CACHE_OBJECT_BYTE_TO_CHAR (regex_match_object,
4051 /* Loop through the string, looking for a place to start matching. */
4054 #ifdef REGEX_BEGLINE_CHECK
4055 /* If the regex is anchored at the beginning of a line (i.e. with a ^),
4056 then we can speed things up by skipping to the next beginning-of-
4058 if (anchored_at_begline && startpos > 0 && startpos != size1 &&
4061 /* whose stupid idea was it anyway to make this
4062 function take two strings to match?? */
4066 if (startpos < size1 && startpos + range >= size1)
4067 lim = range - (size1 - startpos);
4069 d = ((const unsigned char *)
4070 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4071 DEC_CHARPTR(d); /* Ok, since startpos != size1. */
4072 d_size = charcount_to_bytecount (d, 1);
4074 if (TRANSLATE_P (translate))
4075 while (range > lim && *d != '\n')
4077 d += d_size; /* Speedier INC_CHARPTR(d) */
4078 d_size = charcount_to_bytecount (d, 1);
4082 while (range > lim && *d != '\n')
4084 d += d_size; /* Speedier INC_CHARPTR(d) */
4085 d_size = charcount_to_bytecount (d, 1);
4089 startpos += irange - range;
4091 #endif /* REGEX_BEGLINE_CHECK */
4093 /* If a fastmap is supplied, skip quickly over characters that
4094 cannot be the start of a match. If the pattern can match the
4095 null string, however, we don't need to skip characters; we want
4096 the first null string. */
4097 if (fastmap && startpos < total_size && !bufp->can_be_null)
4099 if (range > 0) /* Searching forwards. */
4104 if (startpos < size1 && startpos + range >= size1)
4105 lim = range - (size1 - startpos);
4107 d = ((const unsigned char *)
4108 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4110 /* Written out as an if-else to avoid testing `translate'
4112 if (TRANSLATE_P (translate))
4118 buf_ch = charptr_emchar (d);
4119 buf_ch = RE_TRANSLATE (buf_ch);
4120 if (buf_ch >= 0200 || fastmap[(unsigned char) buf_ch])
4123 if (fastmap[(unsigned char)RE_TRANSLATE (*d)])
4126 d_size = charcount_to_bytecount (d, 1);
4128 d += d_size; /* Speedier INC_CHARPTR(d) */
4131 while (range > lim && !fastmap[*d])
4133 d_size = charcount_to_bytecount (d, 1);
4135 d += d_size; /* Speedier INC_CHARPTR(d) */
4138 startpos += irange - range;
4140 else /* Searching backwards. */
4142 Emchar c = (size1 == 0 || startpos >= size1
4143 ? charptr_emchar (string2 + startpos - size1)
4144 : charptr_emchar (string1 + startpos));
4147 if (!(c >= 0200 || fastmap[(unsigned char) c]))
4150 if (!fastmap[(unsigned char) c])
4156 /* If can't match the null string, and that's all we have left, fail. */
4157 if (range >= 0 && startpos == total_size && fastmap
4158 && !bufp->can_be_null)
4161 #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
4162 if (!no_quit_in_re_search)
4165 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4166 startpos, regs, stop);
4167 #ifndef REGEX_MALLOC
4184 d = ((const unsigned char *)
4185 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4186 d_size = charcount_to_bytecount (d, 1);
4192 /* Note startpos > size1 not >=. If we are on the
4193 string1/string2 boundary, we want to backup into string1. */
4194 d = ((const unsigned char *)
4195 (startpos > size1 ? string2 - size1 : string1) + startpos);
4197 d_size = charcount_to_bytecount (d, 1);
4205 /* Declarations and macros for re_match_2. */
4207 /* This converts PTR, a pointer into one of the search strings `string1'
4208 and `string2' into an offset from the beginning of that string. */
4209 #define POINTER_TO_OFFSET(ptr) \
4210 (FIRST_STRING_P (ptr) \
4211 ? ((regoff_t) ((ptr) - string1)) \
4212 : ((regoff_t) ((ptr) - string2 + size1)))
4214 /* Macros for dealing with the split strings in re_match_2. */
4216 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
4218 /* Call before fetching a character with *d. This switches over to
4219 string2 if necessary. */
4220 #define REGEX_PREFETCH() \
4223 /* End of string2 => fail. */ \
4224 if (dend == end_match_2) \
4226 /* End of string1 => advance to string2. */ \
4228 dend = end_match_2; \
4232 /* Test if at very beginning or at very end of the virtual concatenation
4233 of `string1' and `string2'. If only one string, it's `string2'. */
4234 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4235 #define AT_STRINGS_END(d) ((d) == end2)
4238 If the given position straddles the string gap, return the equivalent
4239 position that is before or after the gap, respectively; otherwise,
4240 return the same position. */
4241 #define POS_BEFORE_GAP_UNSAFE(d) ((d) == string2 ? end1 : (d))
4242 #define POS_AFTER_GAP_UNSAFE(d) ((d) == end1 ? string2 : (d))
4244 /* Test if CH is a word-constituent character. (XEmacs change) */
4245 #define WORDCHAR_P_UNSAFE(ch) \
4246 (SYNTAX_UNSAFE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table), \
4249 /* Free everything we malloc. */
4250 #ifdef MATCH_MAY_ALLOCATE
4251 #define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
4252 #define FREE_VARIABLES() \
4254 REGEX_FREE_STACK (fail_stack.stack); \
4255 FREE_VAR (regstart); \
4256 FREE_VAR (regend); \
4257 FREE_VAR (old_regstart); \
4258 FREE_VAR (old_regend); \
4259 FREE_VAR (best_regstart); \
4260 FREE_VAR (best_regend); \
4261 FREE_VAR (reg_info); \
4262 FREE_VAR (reg_dummy); \
4263 FREE_VAR (reg_info_dummy); \
4265 #else /* not MATCH_MAY_ALLOCATE */
4266 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4267 #endif /* MATCH_MAY_ALLOCATE */
4269 /* These values must meet several constraints. They must not be valid
4270 register values; since we have a limit of 255 registers (because
4271 we use only one byte in the pattern for the register number), we can
4272 use numbers larger than 255. They must differ by 1, because of
4273 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4274 be larger than the value for the highest register, so we do not try
4275 to actually save any registers when none are active. */
4276 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4277 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4279 /* Matching routines. */
4281 #ifndef emacs /* Emacs never uses this. */
4282 /* re_match is like re_match_2 except it takes only a single string. */
4285 re_match (struct re_pattern_buffer *bufp, const char *string, int size,
4286 int pos, struct re_registers *regs)
4288 int result = re_match_2_internal (bufp, NULL, 0, (re_char *) string, size,
4293 #endif /* not emacs */
4296 /* re_match_2 matches the compiled pattern in BUFP against the
4297 (virtual) concatenation of STRING1 and STRING2 (of length SIZE1 and
4298 SIZE2, respectively). We start matching at POS, and stop matching
4301 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4302 store offsets for the substring each group matched in REGS. See the
4303 documentation for exactly how many groups we fill.
4305 We return -1 if no match, -2 if an internal error (such as the
4306 failure stack overflowing). Otherwise, we return the length of the
4307 matched substring. */
4310 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4311 int size1, const char *string2, int size2, int pos,
4312 struct re_registers *regs, int stop)
4317 SETUP_SYNTAX_CACHE_FOR_OBJECT (regex_match_object,
4319 SYNTAX_CACHE_OBJECT_BYTE_TO_CHAR (regex_match_object,
4325 result = re_match_2_internal (bufp, (re_char *) string1, size1,
4326 (re_char *) string2, size2,
4333 /* This is a separate function so that we can force an alloca cleanup
4336 re_match_2_internal (struct re_pattern_buffer *bufp, re_char *string1,
4337 int size1, re_char *string2, int size2, int pos,
4338 struct re_registers *regs, int stop)
4340 /* General temporaries. */
4343 int should_succeed; /* XEmacs change */
4345 /* Just past the end of the corresponding string. */
4346 re_char *end1, *end2;
4348 /* Pointers into string1 and string2, just past the last characters in
4349 each to consider matching. */
4350 re_char *end_match_1, *end_match_2;
4352 /* Where we are in the data, and the end of the current string. */
4355 /* Where we are in the pattern, and the end of the pattern. */
4356 unsigned char *p = bufp->buffer;
4357 REGISTER unsigned char *pend = p + bufp->used;
4359 /* Mark the opcode just after a start_memory, so we can test for an
4360 empty subpattern when we get to the stop_memory. */
4361 re_char *just_past_start_mem = 0;
4363 /* We use this to map every character in the string. */
4364 RE_TRANSLATE_TYPE translate = bufp->translate;
4366 /* Failure point stack. Each place that can handle a failure further
4367 down the line pushes a failure point on this stack. It consists of
4368 restart, regend, and reg_info for all registers corresponding to
4369 the subexpressions we're currently inside, plus the number of such
4370 registers, and, finally, two char *'s. The first char * is where
4371 to resume scanning the pattern; the second one is where to resume
4372 scanning the strings. If the latter is zero, the failure point is
4373 a ``dummy''; if a failure happens and the failure point is a dummy,
4374 it gets discarded and the next one is tried. */
4375 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4376 fail_stack_type fail_stack;
4379 static unsigned failure_id;
4380 int nfailure_points_pushed = 0, nfailure_points_popped = 0;
4384 /* This holds the pointer to the failure stack, when
4385 it is allocated relocatably. */
4386 fail_stack_elt_t *failure_stack_ptr;
4389 /* We fill all the registers internally, independent of what we
4390 return, for use in backreferences. The number here includes
4391 an element for register zero. */
4392 int num_regs = bufp->re_nsub + 1;
4394 /* The currently active registers. */
4395 int lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4396 int highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4398 /* Information on the contents of registers. These are pointers into
4399 the input strings; they record just what was matched (on this
4400 attempt) by a subexpression part of the pattern, that is, the
4401 regnum-th regstart pointer points to where in the pattern we began
4402 matching and the regnum-th regend points to right after where we
4403 stopped matching the regnum-th subexpression. (The zeroth register
4404 keeps track of what the whole pattern matches.) */
4405 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4406 re_char **regstart, **regend;
4409 /* If a group that's operated upon by a repetition operator fails to
4410 match anything, then the register for its start will need to be
4411 restored because it will have been set to wherever in the string we
4412 are when we last see its open-group operator. Similarly for a
4414 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4415 re_char **old_regstart, **old_regend;
4418 /* The is_active field of reg_info helps us keep track of which (possibly
4419 nested) subexpressions we are currently in. The matched_something
4420 field of reg_info[reg_num] helps us tell whether or not we have
4421 matched any of the pattern so far this time through the reg_num-th
4422 subexpression. These two fields get reset each time through any
4423 loop their register is in. */
4424 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4425 register_info_type *reg_info;
4428 /* The following record the register info as found in the above
4429 variables when we find a match better than any we've seen before.
4430 This happens as we backtrack through the failure points, which in
4431 turn happens only if we have not yet matched the entire string. */
4432 unsigned best_regs_set = false;
4433 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4434 re_char **best_regstart, **best_regend;
4437 /* Logically, this is `best_regend[0]'. But we don't want to have to
4438 allocate space for that if we're not allocating space for anything
4439 else (see below). Also, we never need info about register 0 for
4440 any of the other register vectors, and it seems rather a kludge to
4441 treat `best_regend' differently than the rest. So we keep track of
4442 the end of the best match so far in a separate variable. We
4443 initialize this to NULL so that when we backtrack the first time
4444 and need to test it, it's not garbage. */
4445 re_char *match_end = NULL;
4447 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4448 int set_regs_matched_done = 0;
4450 /* Used when we pop values we don't care about. */
4451 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4452 re_char **reg_dummy;
4453 register_info_type *reg_info_dummy;
4457 /* Counts the total number of registers pushed. */
4458 unsigned num_regs_pushed = 0;
4461 /* 1 if this match ends in the same string (string1 or string2)
4462 as the best previous match. */
4465 /* 1 if this match is the best seen so far. */
4466 re_bool best_match_p;
4468 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4472 #ifdef MATCH_MAY_ALLOCATE
4473 /* Do not bother to initialize all the register variables if there are
4474 no groups in the pattern, as it takes a fair amount of time. If
4475 there are groups, we include space for register 0 (the whole
4476 pattern), even though we never use it, since it simplifies the
4477 array indexing. We should fix this. */
4480 regstart = REGEX_TALLOC (num_regs, re_char *);
4481 regend = REGEX_TALLOC (num_regs, re_char *);
4482 old_regstart = REGEX_TALLOC (num_regs, re_char *);
4483 old_regend = REGEX_TALLOC (num_regs, re_char *);
4484 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4485 best_regend = REGEX_TALLOC (num_regs, re_char *);
4486 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4487 reg_dummy = REGEX_TALLOC (num_regs, re_char *);
4488 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4490 if (!(regstart && regend && old_regstart && old_regend && reg_info
4491 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4499 /* We must initialize all our variables to NULL, so that
4500 `FREE_VARIABLES' doesn't try to free them. */
4501 regstart = regend = old_regstart = old_regend = best_regstart
4502 = best_regend = reg_dummy = NULL;
4503 reg_info = reg_info_dummy = (register_info_type *) NULL;
4505 #endif /* MATCH_MAY_ALLOCATE */
4507 /* The starting position is bogus. */
4508 if (pos < 0 || pos > size1 + size2)
4514 /* Initialize subexpression text positions to -1 to mark ones that no
4515 start_memory/stop_memory has been seen for. Also initialize the
4516 register information struct. */
4517 for (mcnt = 1; mcnt < num_regs; mcnt++)
4519 regstart[mcnt] = regend[mcnt]
4520 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4522 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4523 IS_ACTIVE (reg_info[mcnt]) = 0;
4524 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4525 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4527 /* We move `string1' into `string2' if the latter's empty -- but not if
4528 `string1' is null. */
4529 if (size2 == 0 && string1 != NULL)
4536 end1 = string1 + size1;
4537 end2 = string2 + size2;
4539 /* Compute where to stop matching, within the two strings. */
4542 end_match_1 = string1 + stop;
4543 end_match_2 = string2;
4548 end_match_2 = string2 + stop - size1;
4551 /* `p' scans through the pattern as `d' scans through the data.
4552 `dend' is the end of the input string that `d' points within. `d'
4553 is advanced into the following input string whenever necessary, but
4554 this happens before fetching; therefore, at the beginning of the
4555 loop, `d' can be pointing at the end of a string, but it cannot
4557 if (size1 > 0 && pos <= size1)
4564 d = string2 + pos - size1;
4568 DEBUG_PRINT1 ("The compiled pattern is: \n");
4569 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4570 DEBUG_PRINT1 ("The string to match is: `");
4571 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4572 DEBUG_PRINT1 ("'\n");
4574 /* This loops over pattern commands. It exits by returning from the
4575 function if the match is complete, or it drops through if the match
4576 fails at this starting point in the input data. */
4579 DEBUG_PRINT2 ("\n0x%lx: ", (long) p);
4580 #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
4581 if (!no_quit_in_re_search)
4586 { /* End of pattern means we might have succeeded. */
4587 DEBUG_PRINT1 ("end of pattern ... ");
4589 /* If we haven't matched the entire string, and we want the
4590 longest match, try backtracking. */
4591 if (d != end_match_2)
4593 same_str_p = (FIRST_STRING_P (match_end)
4594 == MATCHING_IN_FIRST_STRING);
4596 /* AIX compiler got confused when this was combined
4597 with the previous declaration. */
4599 best_match_p = d > match_end;
4601 best_match_p = !MATCHING_IN_FIRST_STRING;
4603 DEBUG_PRINT1 ("backtracking.\n");
4605 if (!FAIL_STACK_EMPTY ())
4606 { /* More failure points to try. */
4608 /* If exceeds best match so far, save it. */
4609 if (!best_regs_set || best_match_p)
4611 best_regs_set = true;
4614 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4616 for (mcnt = 1; mcnt < num_regs; mcnt++)
4618 best_regstart[mcnt] = regstart[mcnt];
4619 best_regend[mcnt] = regend[mcnt];
4625 /* If no failure points, don't restore garbage. And if
4626 last match is real best match, don't restore second
4628 else if (best_regs_set && !best_match_p)
4631 /* Restore best match. It may happen that `dend ==
4632 end_match_1' while the restored d is in string2.
4633 For example, the pattern `x.*y.*z' against the
4634 strings `x-' and `y-z-', if the two strings are
4635 not consecutive in memory. */
4636 DEBUG_PRINT1 ("Restoring best registers.\n");
4639 dend = ((d >= string1 && d <= end1)
4640 ? end_match_1 : end_match_2);
4642 for (mcnt = 1; mcnt < num_regs; mcnt++)
4644 regstart[mcnt] = best_regstart[mcnt];
4645 regend[mcnt] = best_regend[mcnt];
4648 } /* d != end_match_2 */
4651 DEBUG_PRINT1 ("Accepting match.\n");
4653 /* If caller wants register contents data back, do it. */
4654 if (regs && !bufp->no_sub)
4656 /* Have the register data arrays been allocated? */
4657 if (bufp->regs_allocated == REGS_UNALLOCATED)
4658 { /* No. So allocate them with malloc. We need one
4659 extra element beyond `num_regs' for the `-1' marker
4661 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4662 regs->start = TALLOC (regs->num_regs, regoff_t);
4663 regs->end = TALLOC (regs->num_regs, regoff_t);
4664 if (regs->start == NULL || regs->end == NULL)
4669 bufp->regs_allocated = REGS_REALLOCATE;
4671 else if (bufp->regs_allocated == REGS_REALLOCATE)
4672 { /* Yes. If we need more elements than were already
4673 allocated, reallocate them. If we need fewer, just
4675 if (regs->num_regs < num_regs + 1)
4677 regs->num_regs = num_regs + 1;
4678 RETALLOC (regs->start, regs->num_regs, regoff_t);
4679 RETALLOC (regs->end, regs->num_regs, regoff_t);
4680 if (regs->start == NULL || regs->end == NULL)
4689 /* These braces fend off a "empty body in an else-statement"
4690 warning under GCC when assert expands to nothing. */
4691 assert (bufp->regs_allocated == REGS_FIXED);
4694 /* Convert the pointer data in `regstart' and `regend' to
4695 indices. Register zero has to be set differently,
4696 since we haven't kept track of any info for it. */
4697 if (regs->num_regs > 0)
4699 regs->start[0] = pos;
4700 regs->end[0] = (MATCHING_IN_FIRST_STRING
4701 ? ((regoff_t) (d - string1))
4702 : ((regoff_t) (d - string2 + size1)));
4705 /* Go through the first `min (num_regs, regs->num_regs)'
4706 registers, since that is all we initialized. */
4707 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4709 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4710 regs->start[mcnt] = regs->end[mcnt] = -1;
4714 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4716 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4719 } /* regs && !bufp->no_sub */
4721 /* If we have regs and the regs structure has more elements than
4722 were in the pattern, set the extra elements to -1. If we
4723 (re)allocated the registers, this is the case, because we
4724 always allocate enough to have at least one -1 at the end.
4726 We do this even when no_sub is set because some applications
4727 (XEmacs) reuse register structures which may contain stale
4728 information, and permit attempts to access those registers.
4730 It would be possible to require the caller to do this, but we'd
4731 have to change the API for this function to reflect that, and
4732 audit all callers. */
4733 if (regs && regs->num_regs > 0)
4734 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4735 regs->start[mcnt] = regs->end[mcnt] = -1;
4737 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4738 nfailure_points_pushed, nfailure_points_popped,
4739 nfailure_points_pushed - nfailure_points_popped);
4740 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4742 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4746 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4752 /* Otherwise match next pattern command. */
4753 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4755 /* Ignore these. Used to ignore the n of succeed_n's which
4756 currently have n == 0. */
4758 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4762 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4765 /* Match the next n pattern characters exactly. The following
4766 byte in the pattern defines n, and the n bytes after that
4767 are the characters to match. */
4770 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4772 /* This is written out as an if-else so we don't waste time
4773 testing `translate' inside the loop. */
4774 if (TRANSLATE_P (translate))
4779 Emchar pat_ch, buf_ch;
4783 pat_ch = charptr_emchar (p);
4784 buf_ch = charptr_emchar (d);
4785 if (RE_TRANSLATE (buf_ch) != pat_ch)
4788 pat_len = charcount_to_bytecount (p, 1);
4793 #else /* not MULE */
4795 if ((unsigned char) RE_TRANSLATE (*d++) != *p++)
4807 if (*d++ != *p++) goto fail;
4811 SET_REGS_MATCHED ();
4815 /* Match any character except possibly a newline or a null. */
4817 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4821 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4822 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4825 SET_REGS_MATCHED ();
4826 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4827 INC_CHARPTR (d); /* XEmacs change */
4834 REGISTER unsigned char c;
4835 re_bool not_p = (re_opcode_t) *(p - 1) == charset_not;
4837 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not_p ? "_not" : "");
4840 c = TRANSLATE (*d); /* The character to match. */
4842 /* Cast to `unsigned' instead of `unsigned char' in case the
4843 bit list is a full 32 bytes long. */
4844 if (c < (unsigned) (*p * BYTEWIDTH)
4845 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4850 if (!not_p) goto fail;
4852 SET_REGS_MATCHED ();
4853 INC_CHARPTR (d); /* XEmacs change */
4859 case charset_mule_not:
4862 re_bool not_p = (re_opcode_t) *(p - 1) == charset_mule_not;
4864 DEBUG_PRINT2 ("EXECUTING charset_mule%s.\n", not_p ? "_not" : "");
4867 c = charptr_emchar ((const Bufbyte *) d);
4868 c = TRANSLATE_EXTENDED_UNSAFE (c); /* The character to match. */
4870 if (EQ (Qt, unified_range_table_lookup (p, c, Qnil)))
4873 p += unified_range_table_bytes_used (p);
4875 if (!not_p) goto fail;
4877 SET_REGS_MATCHED ();
4884 /* The beginning of a group is represented by start_memory.
4885 The arguments are the register number in the next byte, and the
4886 number of groups inner to this one in the next. The text
4887 matched within the group is recorded (in the internal
4888 registers data structure) under the register number. */
4890 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4892 /* Find out if this group can match the empty string. */
4893 p1 = p; /* To send to group_match_null_string_p. */
4895 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4896 REG_MATCH_NULL_STRING_P (reg_info[*p])
4897 = group_match_null_string_p (&p1, pend, reg_info);
4899 /* Save the position in the string where we were the last time
4900 we were at this open-group operator in case the group is
4901 operated upon by a repetition operator, e.g., with `(a*)*b'
4902 against `ab'; then we want to ignore where we are now in
4903 the string in case this attempt to match fails. */
4904 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4905 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4907 DEBUG_PRINT2 (" old_regstart: %d\n",
4908 POINTER_TO_OFFSET (old_regstart[*p]));
4911 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4913 IS_ACTIVE (reg_info[*p]) = 1;
4914 MATCHED_SOMETHING (reg_info[*p]) = 0;
4916 /* Clear this whenever we change the register activity status. */
4917 set_regs_matched_done = 0;
4919 /* This is the new highest active register. */
4920 highest_active_reg = *p;
4922 /* If nothing was active before, this is the new lowest active
4924 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4925 lowest_active_reg = *p;
4927 /* Move past the register number and inner group count. */
4929 just_past_start_mem = p;
4934 /* The stop_memory opcode represents the end of a group. Its
4935 arguments are the same as start_memory's: the register
4936 number, and the number of inner groups. */
4938 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4940 /* We need to save the string position the last time we were at
4941 this close-group operator in case the group is operated
4942 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4943 against `aba'; then we want to ignore where we are now in
4944 the string in case this attempt to match fails. */
4945 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4946 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4948 DEBUG_PRINT2 (" old_regend: %d\n",
4949 POINTER_TO_OFFSET (old_regend[*p]));
4952 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4954 /* This register isn't active anymore. */
4955 IS_ACTIVE (reg_info[*p]) = 0;
4957 /* Clear this whenever we change the register activity status. */
4958 set_regs_matched_done = 0;
4960 /* If this was the only register active, nothing is active
4962 if (lowest_active_reg == highest_active_reg)
4964 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4965 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4968 { /* We must scan for the new highest active register, since
4969 it isn't necessarily one less than now: consider
4970 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4971 new highest active register is 1. */
4972 unsigned char r = *p - 1;
4973 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4976 /* If we end up at register zero, that means that we saved
4977 the registers as the result of an `on_failure_jump', not
4978 a `start_memory', and we jumped to past the innermost
4979 `stop_memory'. For example, in ((.)*) we save
4980 registers 1 and 2 as a result of the *, but when we pop
4981 back to the second ), we are at the stop_memory 1.
4982 Thus, nothing is active. */
4985 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4986 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4990 highest_active_reg = r;
4992 /* 98/9/21 jhod: We've also gotta set lowest_active_reg, don't we? */
4994 while (r < highest_active_reg && !IS_ACTIVE(reg_info[r]))
4996 lowest_active_reg = r;
5000 /* If just failed to match something this time around with a
5001 group that's operated on by a repetition operator, try to
5002 force exit from the ``loop'', and restore the register
5003 information for this group that we had before trying this
5005 if ((!MATCHED_SOMETHING (reg_info[*p])
5006 || just_past_start_mem == p - 1)
5009 re_bool is_a_jump_n = false;
5013 switch ((re_opcode_t) *p1++)
5017 case pop_failure_jump:
5018 case maybe_pop_jump:
5020 case dummy_failure_jump:
5021 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5031 /* If the next operation is a jump backwards in the pattern
5032 to an on_failure_jump right before the start_memory
5033 corresponding to this stop_memory, exit from the loop
5034 by forcing a failure after pushing on the stack the
5035 on_failure_jump's jump in the pattern, and d. */
5036 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
5037 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
5039 /* If this group ever matched anything, then restore
5040 what its registers were before trying this last
5041 failed match, e.g., with `(a*)*b' against `ab' for
5042 regstart[1], and, e.g., with `((a*)*(b*)*)*'
5043 against `aba' for regend[3].
5045 Also restore the registers for inner groups for,
5046 e.g., `((a*)(b*))*' against `aba' (register 3 would
5047 otherwise get trashed). */
5049 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
5053 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
5055 /* Restore this and inner groups' (if any) registers. */
5056 for (r = *p; r < *p + *(p + 1); r++)
5058 regstart[r] = old_regstart[r];
5060 /* xx why this test? */
5061 if (old_regend[r] >= regstart[r])
5062 regend[r] = old_regend[r];
5066 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5067 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
5073 /* Move past the register number and the inner group count. */
5078 /* \<digit> has been turned into a `duplicate' command which is
5079 followed by the numeric value of <digit> as the register number. */
5082 REGISTER re_char *d2, *dend2;
5083 int regno = *p++; /* Get which register to match against. */
5084 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5086 /* Can't back reference a group which we've never matched. */
5087 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5090 /* Where in input to try to start matching. */
5091 d2 = regstart[regno];
5093 /* Where to stop matching; if both the place to start and
5094 the place to stop matching are in the same string, then
5095 set to the place to stop, otherwise, for now have to use
5096 the end of the first string. */
5098 dend2 = ((FIRST_STRING_P (regstart[regno])
5099 == FIRST_STRING_P (regend[regno]))
5100 ? regend[regno] : end_match_1);
5103 /* If necessary, advance to next segment in register
5107 if (dend2 == end_match_2) break;
5108 if (dend2 == regend[regno]) break;
5110 /* End of string1 => advance to string2. */
5112 dend2 = regend[regno];
5114 /* At end of register contents => success */
5115 if (d2 == dend2) break;
5117 /* If necessary, advance to next segment in data. */
5120 /* How many characters left in this segment to match. */
5123 /* Want how many consecutive characters we can match in
5124 one shot, so, if necessary, adjust the count. */
5125 if (mcnt > dend2 - d2)
5128 /* Compare that many; failure if mismatch, else move
5130 if (TRANSLATE_P (translate)
5131 ? bcmp_translate ((unsigned char *) d,
5132 (unsigned char *) d2, mcnt, translate)
5133 : memcmp (d, d2, mcnt))
5135 d += mcnt, d2 += mcnt;
5137 /* Do this because we've match some characters. */
5138 SET_REGS_MATCHED ();
5144 /* begline matches the empty string at the beginning of the string
5145 (unless `not_bol' is set in `bufp'), and, if
5146 `newline_anchor' is set, after newlines. */
5148 DEBUG_PRINT1 ("EXECUTING begline.\n");
5150 if (AT_STRINGS_BEG (d))
5152 if (!bufp->not_bol) break;
5154 else if (d[-1] == '\n' && bufp->newline_anchor)
5158 /* In all other cases, we fail. */
5162 /* endline is the dual of begline. */
5164 DEBUG_PRINT1 ("EXECUTING endline.\n");
5166 if (AT_STRINGS_END (d))
5168 if (!bufp->not_eol) break;
5171 /* We have to ``prefetch'' the next character. */
5172 else if ((d == end1 ? *string2 : *d) == '\n'
5173 && bufp->newline_anchor)
5180 /* Match at the very beginning of the data. */
5182 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5183 if (AT_STRINGS_BEG (d))
5188 /* Match at the very end of the data. */
5190 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5191 if (AT_STRINGS_END (d))
5196 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5197 pushes NULL as the value for the string on the stack. Then
5198 `pop_failure_point' will keep the current value for the
5199 string, instead of restoring it. To see why, consider
5200 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5201 then the . fails against the \n. But the next thing we want
5202 to do is match the \n against the \n; if we restored the
5203 string value, we would be back at the foo.
5205 Because this is used only in specific cases, we don't need to
5206 check all the things that `on_failure_jump' does, to make
5207 sure the right things get saved on the stack. Hence we don't
5208 share its code. The only reason to push anything on the
5209 stack at all is that otherwise we would have to change
5210 `anychar's code to do something besides goto fail in this
5211 case; that seems worse than this. */
5212 case on_failure_keep_string_jump:
5213 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
5215 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5216 DEBUG_PRINT3 (" %d (to 0x%lx):\n", mcnt, (long) (p + mcnt));
5218 PUSH_FAILURE_POINT (p + mcnt, (unsigned char *) 0, -2);
5222 /* Uses of on_failure_jump:
5224 Each alternative starts with an on_failure_jump that points
5225 to the beginning of the next alternative. Each alternative
5226 except the last ends with a jump that in effect jumps past
5227 the rest of the alternatives. (They really jump to the
5228 ending jump of the following alternative, because tensioning
5229 these jumps is a hassle.)
5231 Repeats start with an on_failure_jump that points past both
5232 the repetition text and either the following jump or
5233 pop_failure_jump back to this on_failure_jump. */
5234 case on_failure_jump:
5236 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
5238 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5239 DEBUG_PRINT3 (" %d (to 0x%lx)", mcnt, (long) (p + mcnt));
5241 /* If this on_failure_jump comes right before a group (i.e.,
5242 the original * applied to a group), save the information
5243 for that group and all inner ones, so that if we fail back
5244 to this point, the group's information will be correct.
5245 For example, in \(a*\)*\1, we need the preceding group,
5246 and in \(\(a*\)b*\)\2, we need the inner group. */
5248 /* We can't use `p' to check ahead because we push
5249 a failure point to `p + mcnt' after we do this. */
5252 /* We need to skip no_op's before we look for the
5253 start_memory in case this on_failure_jump is happening as
5254 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5256 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5259 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5261 /* We have a new highest active register now. This will
5262 get reset at the start_memory we are about to get to,
5263 but we will have saved all the registers relevant to
5264 this repetition op, as described above. */
5265 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5266 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5267 lowest_active_reg = *(p1 + 1);
5270 DEBUG_PRINT1 (":\n");
5271 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5275 /* A smart repeat ends with `maybe_pop_jump'.
5276 We change it to either `pop_failure_jump' or `jump'. */
5277 case maybe_pop_jump:
5278 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5279 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5281 REGISTER unsigned char *p2 = p;
5283 /* Compare the beginning of the repeat with what in the
5284 pattern follows its end. If we can establish that there
5285 is nothing that they would both match, i.e., that we
5286 would have to backtrack because of (as in, e.g., `a*a')
5287 then we can change to pop_failure_jump, because we'll
5288 never have to backtrack.
5290 This is not true in the case of alternatives: in
5291 `(a|ab)*' we do need to backtrack to the `ab' alternative
5292 (e.g., if the string was `ab'). But instead of trying to
5293 detect that here, the alternative has put on a dummy
5294 failure point which is what we will end up popping. */
5296 /* Skip over open/close-group commands.
5297 If what follows this loop is a ...+ construct,
5298 look at what begins its body, since we will have to
5299 match at least one of that. */
5303 && ((re_opcode_t) *p2 == stop_memory
5304 || (re_opcode_t) *p2 == start_memory))
5306 else if (p2 + 6 < pend
5307 && (re_opcode_t) *p2 == dummy_failure_jump)
5314 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5315 to the `maybe_finalize_jump' of this case. Examine what
5318 /* If we're at the end of the pattern, we can change. */
5321 /* Consider what happens when matching ":\(.*\)"
5322 against ":/". I don't really understand this code
5324 p[-3] = (unsigned char) pop_failure_jump;
5326 (" End of pattern: change to `pop_failure_jump'.\n");
5329 else if ((re_opcode_t) *p2 == exactn
5330 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5332 REGISTER unsigned char c
5333 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5335 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
5337 p[-3] = (unsigned char) pop_failure_jump;
5338 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5342 else if ((re_opcode_t) p1[3] == charset
5343 || (re_opcode_t) p1[3] == charset_not)
5345 int not_p = (re_opcode_t) p1[3] == charset_not;
5347 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
5348 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5351 /* `not_p' is equal to 1 if c would match, which means
5352 that we can't change to pop_failure_jump. */
5355 p[-3] = (unsigned char) pop_failure_jump;
5356 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5360 else if ((re_opcode_t) *p2 == charset)
5363 REGISTER unsigned char c
5364 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5367 if ((re_opcode_t) p1[3] == exactn
5368 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
5369 && (p2[2 + p1[5] / BYTEWIDTH]
5370 & (1 << (p1[5] % BYTEWIDTH)))))
5372 p[-3] = (unsigned char) pop_failure_jump;
5373 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5377 else if ((re_opcode_t) p1[3] == charset_not)
5380 /* We win if the charset_not inside the loop
5381 lists every character listed in the charset after. */
5382 for (idx = 0; idx < (int) p2[1]; idx++)
5383 if (! (p2[2 + idx] == 0
5384 || (idx < (int) p1[4]
5385 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5390 p[-3] = (unsigned char) pop_failure_jump;
5391 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5394 else if ((re_opcode_t) p1[3] == charset)
5397 /* We win if the charset inside the loop
5398 has no overlap with the one after the loop. */
5400 idx < (int) p2[1] && idx < (int) p1[4];
5402 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5405 if (idx == p2[1] || idx == p1[4])
5407 p[-3] = (unsigned char) pop_failure_jump;
5408 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5413 p -= 2; /* Point at relative address again. */
5414 if ((re_opcode_t) p[-1] != pop_failure_jump)
5416 p[-1] = (unsigned char) jump;
5417 DEBUG_PRINT1 (" Match => jump.\n");
5418 goto unconditional_jump;
5420 /* Note fall through. */
5423 /* The end of a simple repeat has a pop_failure_jump back to
5424 its matching on_failure_jump, where the latter will push a
5425 failure point. The pop_failure_jump takes off failure
5426 points put on by this pop_failure_jump's matching
5427 on_failure_jump; we got through the pattern to here from the
5428 matching on_failure_jump, so didn't fail. */
5429 case pop_failure_jump:
5431 /* We need to pass separate storage for the lowest and
5432 highest registers, even though we don't care about the
5433 actual values. Otherwise, we will restore only one
5434 register from the stack, since lowest will == highest in
5435 `pop_failure_point'. */
5436 int dummy_low_reg, dummy_high_reg;
5437 unsigned char *pdummy;
5438 re_char *sdummy = NULL;
5440 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5441 POP_FAILURE_POINT (sdummy, pdummy,
5442 dummy_low_reg, dummy_high_reg,
5443 reg_dummy, reg_dummy, reg_info_dummy);
5445 /* Note fall through. */
5448 /* Unconditionally jump (without popping any failure points). */
5451 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5452 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5453 p += mcnt; /* Do the jump. */
5454 DEBUG_PRINT2 ("(to 0x%lx).\n", (long) p);
5458 /* We need this opcode so we can detect where alternatives end
5459 in `group_match_null_string_p' et al. */
5461 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5462 goto unconditional_jump;
5465 /* Normally, the on_failure_jump pushes a failure point, which
5466 then gets popped at pop_failure_jump. We will end up at
5467 pop_failure_jump, also, and with a pattern of, say, `a+', we
5468 are skipping over the on_failure_jump, so we have to push
5469 something meaningless for pop_failure_jump to pop. */
5470 case dummy_failure_jump:
5471 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5472 /* It doesn't matter what we push for the string here. What
5473 the code at `fail' tests is the value for the pattern. */
5474 PUSH_FAILURE_POINT ((unsigned char *) 0, (unsigned char *) 0, -2);
5475 goto unconditional_jump;
5478 /* At the end of an alternative, we need to push a dummy failure
5479 point in case we are followed by a `pop_failure_jump', because
5480 we don't want the failure point for the alternative to be
5481 popped. For example, matching `(a|ab)*' against `aab'
5482 requires that we match the `ab' alternative. */
5483 case push_dummy_failure:
5484 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5485 /* See comments just above at `dummy_failure_jump' about the
5487 PUSH_FAILURE_POINT ((unsigned char *) 0, (unsigned char *) 0, -2);
5490 /* Have to succeed matching what follows at least n times.
5491 After that, handle like `on_failure_jump'. */
5493 EXTRACT_NUMBER (mcnt, p + 2);
5494 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5497 /* Originally, this is how many times we HAVE to succeed. */
5502 STORE_NUMBER_AND_INCR (p, mcnt);
5503 DEBUG_PRINT3 (" Setting 0x%lx to %d.\n", (long) p, mcnt);
5507 DEBUG_PRINT2 (" Setting two bytes from 0x%lx to no_op.\n",
5509 p[2] = (unsigned char) no_op;
5510 p[3] = (unsigned char) no_op;
5516 EXTRACT_NUMBER (mcnt, p + 2);
5517 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5519 /* Originally, this is how many times we CAN jump. */
5523 STORE_NUMBER (p + 2, mcnt);
5524 goto unconditional_jump;
5526 /* If don't have to jump any more, skip over the rest of command. */
5533 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5535 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5537 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5538 DEBUG_PRINT3 (" Setting 0x%lx to %d.\n", (long) p1, mcnt);
5539 STORE_NUMBER (p1, mcnt);
5544 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5550 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5554 re_char *d_before = POS_BEFORE_GAP_UNSAFE (d);
5555 re_char *d_after = POS_AFTER_GAP_UNSAFE (d);
5557 /* emch1 is the character before d, syn1 is the syntax of emch1,
5558 emch2 is the character at d, and syn2 is the syntax of emch2. */
5559 Emchar emch1, emch2;
5565 DEC_CHARPTR (d_before);
5566 emch1 = charptr_emchar (d_before);
5567 emch2 = charptr_emchar (d_after);
5570 pos_before = SYNTAX_CACHE_BYTE_TO_CHAR (PTR_TO_OFFSET (d)) - 1;
5571 UPDATE_SYNTAX_CACHE (pos_before);
5573 syn1 = SYNTAX_FROM_CACHE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5576 UPDATE_SYNTAX_CACHE_FORWARD (pos_before + 1);
5578 syn2 = SYNTAX_FROM_CACHE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5581 result = ((syn1 == Sword) != (syn2 == Sword));
5583 if (result == should_succeed)
5589 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5591 goto matchwordbound;
5594 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5595 if (AT_STRINGS_END (d))
5598 /* XEmacs: this originally read:
5600 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
5604 re_char *dtmp = POS_AFTER_GAP_UNSAFE (d);
5605 Emchar emch = charptr_emchar (dtmp);
5607 int charpos = SYNTAX_CACHE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5608 UPDATE_SYNTAX_CACHE (charpos);
5610 if (SYNTAX_FROM_CACHE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5613 if (AT_STRINGS_BEG (d))
5615 dtmp = POS_BEFORE_GAP_UNSAFE (d);
5617 emch = charptr_emchar (dtmp);
5619 UPDATE_SYNTAX_CACHE_BACKWARD (charpos - 1);
5621 if (SYNTAX_FROM_CACHE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5628 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5629 if (AT_STRINGS_BEG (d))
5632 /* XEmacs: this originally read:
5634 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
5635 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
5638 The or condition is incorrect (reversed).
5643 int charpos = SYNTAX_CACHE_BYTE_TO_CHAR (PTR_TO_OFFSET (d)) - 1;
5644 UPDATE_SYNTAX_CACHE (charpos);
5646 dtmp = POS_BEFORE_GAP_UNSAFE (d);
5648 emch = charptr_emchar (dtmp);
5649 if (SYNTAX_FROM_CACHE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5652 if (AT_STRINGS_END (d))
5654 dtmp = POS_AFTER_GAP_UNSAFE (d);
5655 emch = charptr_emchar (dtmp);
5657 UPDATE_SYNTAX_CACHE_FORWARD (charpos + 1);
5659 if (SYNTAX_FROM_CACHE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5667 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5668 if (! (NILP (regex_match_object) || BUFFERP (regex_match_object))
5669 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5670 >= BUF_PT (regex_emacs_buffer)))
5675 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5676 if (! (NILP (regex_match_object) || BUFFERP (regex_match_object))
5677 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5678 != BUF_PT (regex_emacs_buffer)))
5683 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5684 if (! (NILP (regex_match_object) || BUFFERP (regex_match_object))
5685 || (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5686 <= BUF_PT (regex_emacs_buffer)))
5689 #if 0 /* not emacs19 */
5691 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5692 if (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d) + 1
5693 != BUF_PT (regex_emacs_buffer))
5696 #endif /* not emacs19 */
5699 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5704 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5716 int charpos = SYNTAX_CACHE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5717 UPDATE_SYNTAX_CACHE (charpos);
5721 emch = charptr_emchar ((const Bufbyte *) d);
5722 matches = (SYNTAX_FROM_CACHE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5723 emch) == (enum syntaxcode) mcnt);
5725 if (matches != should_succeed)
5727 SET_REGS_MATCHED ();
5732 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5734 goto matchnotsyntax;
5737 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5741 goto matchornotsyntax;
5744 /* 97/2/17 jhod Mule category code patch */
5753 emch = charptr_emchar ((const Bufbyte *) d);
5755 if (check_category_char(emch, regex_emacs_buffer->category_table,
5756 mcnt, should_succeed))
5758 SET_REGS_MATCHED ();
5762 case notcategoryspec:
5764 goto matchornotcategory;
5765 /* end of category patch */
5767 #else /* not emacs */
5769 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5771 if (!WORDCHAR_P_UNSAFE ((int) (*d)))
5773 SET_REGS_MATCHED ();
5778 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5780 if (!WORDCHAR_P_UNSAFE ((int) (*d)))
5782 SET_REGS_MATCHED ();
5790 continue; /* Successfully executed one pattern command; keep going. */
5793 /* We goto here if a matching operation fails. */
5795 if (!FAIL_STACK_EMPTY ())
5796 { /* A restart point is known. Restore to that state. */
5797 DEBUG_PRINT1 ("\nFAIL:\n");
5798 POP_FAILURE_POINT (d, p,
5799 lowest_active_reg, highest_active_reg,
5800 regstart, regend, reg_info);
5802 /* If this failure point is a dummy, try the next one. */
5806 /* If we failed to the end of the pattern, don't examine *p. */
5810 re_bool is_a_jump_n = false;
5812 /* If failed to a backwards jump that's part of a repetition
5813 loop, need to pop this failure point and use the next one. */
5814 switch ((re_opcode_t) *p)
5818 case maybe_pop_jump:
5819 case pop_failure_jump:
5822 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5825 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5827 && (re_opcode_t) *p1 == on_failure_jump))
5835 if (d >= string1 && d <= end1)
5839 break; /* Matching at this starting point really fails. */
5843 goto restore_best_regs;
5847 return -1; /* Failure to match. */
5850 /* Subroutine definitions for re_match_2. */
5853 /* We are passed P pointing to a register number after a start_memory.
5855 Return true if the pattern up to the corresponding stop_memory can
5856 match the empty string, and false otherwise.
5858 If we find the matching stop_memory, sets P to point to one past its number.
5859 Otherwise, sets P to an undefined byte less than or equal to END.
5861 We don't handle duplicates properly (yet). */
5864 group_match_null_string_p (unsigned char **p, unsigned char *end,
5865 register_info_type *reg_info)
5868 /* Point to after the args to the start_memory. */
5869 unsigned char *p1 = *p + 2;
5873 /* Skip over opcodes that can match nothing, and return true or
5874 false, as appropriate, when we get to one that can't, or to the
5875 matching stop_memory. */
5877 switch ((re_opcode_t) *p1)
5879 /* Could be either a loop or a series of alternatives. */
5880 case on_failure_jump:
5882 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5884 /* If the next operation is not a jump backwards in the
5889 /* Go through the on_failure_jumps of the alternatives,
5890 seeing if any of the alternatives cannot match nothing.
5891 The last alternative starts with only a jump,
5892 whereas the rest start with on_failure_jump and end
5893 with a jump, e.g., here is the pattern for `a|b|c':
5895 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5896 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5899 So, we have to first go through the first (n-1)
5900 alternatives and then deal with the last one separately. */
5903 /* Deal with the first (n-1) alternatives, which start
5904 with an on_failure_jump (see above) that jumps to right
5905 past a jump_past_alt. */
5907 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5909 /* `mcnt' holds how many bytes long the alternative
5910 is, including the ending `jump_past_alt' and
5913 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5917 /* Move to right after this alternative, including the
5921 /* Break if it's the beginning of an n-th alternative
5922 that doesn't begin with an on_failure_jump. */
5923 if ((re_opcode_t) *p1 != on_failure_jump)
5926 /* Still have to check that it's not an n-th
5927 alternative that starts with an on_failure_jump. */
5929 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5930 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5932 /* Get to the beginning of the n-th alternative. */
5938 /* Deal with the last alternative: go back and get number
5939 of the `jump_past_alt' just before it. `mcnt' contains
5940 the length of the alternative. */
5941 EXTRACT_NUMBER (mcnt, p1 - 2);
5943 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5946 p1 += mcnt; /* Get past the n-th alternative. */
5952 assert (p1[1] == **p);
5958 if (!common_op_match_null_string_p (&p1, end, reg_info))
5961 } /* while p1 < end */
5964 } /* group_match_null_string_p */
5967 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5968 It expects P to be the first byte of a single alternative and END one
5969 byte past the last. The alternative can contain groups. */
5972 alt_match_null_string_p (unsigned char *p, unsigned char *end,
5973 register_info_type *reg_info)
5976 unsigned char *p1 = p;
5980 /* Skip over opcodes that can match nothing, and break when we get
5981 to one that can't. */
5983 switch ((re_opcode_t) *p1)
5986 case on_failure_jump:
5988 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5993 if (!common_op_match_null_string_p (&p1, end, reg_info))
5996 } /* while p1 < end */
5999 } /* alt_match_null_string_p */
6002 /* Deals with the ops common to group_match_null_string_p and
6003 alt_match_null_string_p.
6005 Sets P to one after the op and its arguments, if any. */
6008 common_op_match_null_string_p (unsigned char **p, unsigned char *end,
6009 register_info_type *reg_info)
6014 unsigned char *p1 = *p;
6016 switch ((re_opcode_t) *p1++)
6036 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
6037 ret = group_match_null_string_p (&p1, end, reg_info);
6039 /* Have to set this here in case we're checking a group which
6040 contains a group and a back reference to it. */
6042 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
6043 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
6049 /* If this is an optimized succeed_n for zero times, make the jump. */
6051 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6059 /* Get to the number of times to succeed. */
6061 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6066 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6074 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
6082 /* All other opcodes mean we cannot match the empty string. */
6088 } /* common_op_match_null_string_p */
6091 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6092 bytes; nonzero otherwise. */
6095 bcmp_translate (re_char *s1, re_char *s2,
6096 REGISTER int len, RE_TRANSLATE_TYPE translate)
6098 REGISTER const unsigned char *p1 = s1, *p2 = s2;
6100 const unsigned char *p1_end = s1 + len;
6101 const unsigned char *p2_end = s2 + len;
6103 while (p1 != p1_end && p2 != p2_end)
6105 Emchar p1_ch, p2_ch;
6107 p1_ch = charptr_emchar (p1);
6108 p2_ch = charptr_emchar (p2);
6110 if (RE_TRANSLATE (p1_ch)
6111 != RE_TRANSLATE (p2_ch))
6116 #else /* not MULE */
6119 if (RE_TRANSLATE (*p1++) != RE_TRANSLATE (*p2++)) return 1;
6126 /* Entry points for GNU code. */
6128 /* re_compile_pattern is the GNU regular expression compiler: it
6129 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6130 Returns 0 if the pattern was valid, otherwise an error string.
6132 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6133 are set in BUFP on entry.
6135 We call regex_compile to do the actual compilation. */
6138 re_compile_pattern (const char *pattern, int length,
6139 struct re_pattern_buffer *bufp)
6143 /* GNU code is written to assume at least RE_NREGS registers will be set
6144 (and at least one extra will be -1). */
6145 bufp->regs_allocated = REGS_UNALLOCATED;
6147 /* And GNU code determines whether or not to get register information
6148 by passing null for the REGS argument to re_match, etc., not by
6152 /* Match anchors at newline. */
6153 bufp->newline_anchor = 1;
6155 ret = regex_compile ((unsigned char *) pattern, length, re_syntax_options, bufp);
6159 return gettext (re_error_msgid[(int) ret]);
6162 /* Entry points compatible with 4.2 BSD regex library. We don't define
6163 them unless specifically requested. */
6165 #ifdef _REGEX_RE_COMP
6167 /* BSD has one and only one pattern buffer. */
6168 static struct re_pattern_buffer re_comp_buf;
6171 re_comp (const char *s)
6177 if (!re_comp_buf.buffer)
6178 return gettext ("No previous regular expression");
6182 if (!re_comp_buf.buffer)
6184 re_comp_buf.buffer = (unsigned char *) malloc (200);
6185 if (re_comp_buf.buffer == NULL)
6186 return gettext (re_error_msgid[(int) REG_ESPACE]);
6187 re_comp_buf.allocated = 200;
6189 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6190 if (re_comp_buf.fastmap == NULL)
6191 return gettext (re_error_msgid[(int) REG_ESPACE]);
6194 /* Since `re_exec' always passes NULL for the `regs' argument, we
6195 don't need to initialize the pattern buffer fields which affect it. */
6197 /* Match anchors at newlines. */
6198 re_comp_buf.newline_anchor = 1;
6200 ret = regex_compile ((unsigned char *)s, strlen (s), re_syntax_options, &re_comp_buf);
6205 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6206 return (char *) gettext (re_error_msgid[(int) ret]);
6211 re_exec (const char *s)
6213 const int len = strlen (s);
6215 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6217 #endif /* _REGEX_RE_COMP */
6219 /* POSIX.2 functions. Don't define these for Emacs. */
6223 /* regcomp takes a regular expression as a string and compiles it.
6225 PREG is a regex_t *. We do not expect any fields to be initialized,
6226 since POSIX says we shouldn't. Thus, we set
6228 `buffer' to the compiled pattern;
6229 `used' to the length of the compiled pattern;
6230 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6231 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6232 RE_SYNTAX_POSIX_BASIC;
6233 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6234 `fastmap' and `fastmap_accurate' to zero;
6235 `re_nsub' to the number of subexpressions in PATTERN.
6237 PATTERN is the address of the pattern string.
6239 CFLAGS is a series of bits which affect compilation.
6241 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6242 use POSIX basic syntax.
6244 If REG_NEWLINE is set, then . and [^...] don't match newline.
6245 Also, regexec will try a match beginning after every newline.
6247 If REG_ICASE is set, then we considers upper- and lowercase
6248 versions of letters to be equivalent when matching.
6250 If REG_NOSUB is set, then when PREG is passed to regexec, that
6251 routine will report only success or failure, and nothing about the
6254 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6255 the return codes and their meanings.) */
6258 regcomp (regex_t *preg, const char *pattern, int cflags)
6262 = (cflags & REG_EXTENDED) ?
6263 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6265 /* regex_compile will allocate the space for the compiled pattern. */
6267 preg->allocated = 0;
6270 /* Don't bother to use a fastmap when searching. This simplifies the
6271 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6272 characters after newlines into the fastmap. This way, we just try
6276 if (cflags & REG_ICASE)
6280 preg->translate = (char *) malloc (CHAR_SET_SIZE);
6281 if (preg->translate == NULL)
6282 return (int) REG_ESPACE;
6284 /* Map uppercase characters to corresponding lowercase ones. */
6285 for (i = 0; i < CHAR_SET_SIZE; i++)
6286 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6289 preg->translate = NULL;
6291 /* If REG_NEWLINE is set, newlines are treated differently. */
6292 if (cflags & REG_NEWLINE)
6293 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6294 syntax &= ~RE_DOT_NEWLINE;
6295 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6296 /* It also changes the matching behavior. */
6297 preg->newline_anchor = 1;
6300 preg->newline_anchor = 0;
6302 preg->no_sub = !!(cflags & REG_NOSUB);
6304 /* POSIX says a null character in the pattern terminates it, so we
6305 can use strlen here in compiling the pattern. */
6306 ret = regex_compile ((unsigned char *) pattern, strlen (pattern), syntax, preg);
6308 /* POSIX doesn't distinguish between an unmatched open-group and an
6309 unmatched close-group: both are REG_EPAREN. */
6310 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6316 /* regexec searches for a given pattern, specified by PREG, in the
6319 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6320 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6321 least NMATCH elements, and we set them to the offsets of the
6322 corresponding matched substrings.
6324 EFLAGS specifies `execution flags' which affect matching: if
6325 REG_NOTBOL is set, then ^ does not match at the beginning of the
6326 string; if REG_NOTEOL is set, then $ does not match at the end.
6328 We return 0 if we find a match and REG_NOMATCH if not. */
6331 regexec (const regex_t *preg, const char *string, Element_count nmatch,
6332 regmatch_t pmatch[], int eflags)
6335 struct re_registers regs;
6336 regex_t private_preg;
6337 int len = strlen (string);
6338 re_bool want_reg_info = !preg->no_sub && nmatch > 0;
6340 private_preg = *preg;
6342 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6343 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6345 /* The user has told us exactly how many registers to return
6346 information about, via `nmatch'. We have to pass that on to the
6347 matching routines. */
6348 private_preg.regs_allocated = REGS_FIXED;
6352 regs.num_regs = nmatch;
6353 regs.start = TALLOC (nmatch, regoff_t);
6354 regs.end = TALLOC (nmatch, regoff_t);
6355 if (regs.start == NULL || regs.end == NULL)
6356 return (int) REG_NOMATCH;
6359 /* Perform the searching operation. */
6360 ret = re_search (&private_preg, string, len,
6361 /* start: */ 0, /* range: */ len,
6362 want_reg_info ? ®s : (struct re_registers *) 0);
6364 /* Copy the register information to the POSIX structure. */
6371 for (r = 0; r < nmatch; r++)
6373 pmatch[r].rm_so = regs.start[r];
6374 pmatch[r].rm_eo = regs.end[r];
6378 /* If we needed the temporary register info, free the space now. */
6383 /* We want zero return to mean success, unlike `re_search'. */
6384 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6388 /* Returns a message corresponding to an error code, ERRCODE, returned
6389 from either regcomp or regexec. We don't use PREG here. */
6392 regerror (int errcode, const regex_t *preg, char *errbuf,
6393 Memory_count errbuf_size)
6396 Memory_count msg_size;
6399 || (size_t) errcode >= (sizeof (re_error_msgid)
6400 / sizeof (re_error_msgid[0])))
6401 /* Only error codes returned by the rest of the code should be passed
6402 to this routine. If we are given anything else, or if other regex
6403 code generates an invalid error code, then the program has a bug.
6404 Dump core so we can fix it. */
6407 msg = gettext (re_error_msgid[errcode]);
6409 msg_size = strlen (msg) + 1; /* Includes the null. */
6411 if (errbuf_size != 0)
6413 if (msg_size > errbuf_size)
6415 strncpy (errbuf, msg, errbuf_size - 1);
6416 errbuf[errbuf_size - 1] = 0;
6419 strcpy (errbuf, msg);
6426 /* Free dynamically allocated space used by PREG. */
6429 regfree (regex_t *preg)
6431 if (preg->buffer != NULL)
6432 free (preg->buffer);
6433 preg->buffer = NULL;
6435 preg->allocated = 0;
6438 if (preg->fastmap != NULL)
6439 free (preg->fastmap);
6440 preg->fastmap = NULL;
6441 preg->fastmap_accurate = 0;
6443 if (preg->translate != NULL)
6444 free (preg->translate);
6445 preg->translate = NULL;
6448 #endif /* not emacs */
6452 make-backup-files: t
6454 trim-versions-without-asking: nil