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 */
50 /* We assume non-Mule if emacs isn't defined. */
55 /* We need this for `regex.h', and perhaps for the Emacs include files. */
56 #include <sys/types.h>
58 /* This is for other GNU distributions with internationalized messages. */
59 #if defined (I18N3) && (defined (HAVE_LIBINTL_H) || defined (_LIBC))
62 # define gettext(msgid) (msgid)
65 /* XEmacs: define this to add in a speedup for patterns anchored at
66 the beginning of a line. Keep the ifdefs so that it's easier to
67 tell where/why this code has diverged from v19. */
68 #define REGEX_BEGLINE_CHECK
70 /* XEmacs: the current mmap-based ralloc handles small blocks very
71 poorly, so we disable it here. */
73 #if (defined (REL_ALLOC) && defined (HAVE_MMAP)) || defined(DOUG_LEA_MALLOC)
77 /* The `emacs' switch turns on certain matching commands
78 that make sense only in Emacs. */
85 #if (defined (DEBUG_XEMACS) && !defined (DEBUG))
91 Lisp_Object Vthe_lisp_rangetab;
94 complex_vars_of_regex (void)
96 Vthe_lisp_rangetab = Fmake_range_table ();
97 staticpro (&Vthe_lisp_rangetab);
103 complex_vars_of_regex (void)
107 #endif /* not MULE */
109 #else /* not emacs */
111 /* If we are not linking with Emacs proper,
112 we can't use the relocating allocator
113 even if config.h says that we can. */
116 #if defined (STDC_HEADERS) || defined (_LIBC)
123 #define charptr_emchar(str) ((Emchar) (str)[0])
125 #if (LONGBITS > INTBITS)
126 # define EMACS_INT long
128 # define EMACS_INT int
133 #define INC_CHARPTR(p) ((p)++)
134 #define DEC_CHARPTR(p) ((p)--)
138 /* Define the syntax stuff for \<, \>, etc. */
140 /* This must be nonzero for the wordchar and notwordchar pattern
141 commands in re_match_2. */
148 extern char *re_syntax_table;
150 #else /* not SYNTAX_TABLE */
152 /* How many characters in the character set. */
153 #define CHAR_SET_SIZE 256
155 static char re_syntax_table[CHAR_SET_SIZE];
158 init_syntax_once (void)
164 CONST char *word_syntax_chars =
165 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
167 memset (re_syntax_table, 0, sizeof (re_syntax_table));
169 while (*word_syntax_chars)
170 re_syntax_table[(unsigned int)(*word_syntax_chars++)] = Sword;
176 #endif /* not SYNTAX_TABLE */
178 #define SYNTAX_UNSAFE(ignored, c) re_syntax_table[c]
180 #endif /* not emacs */
182 /* Under XEmacs, this is needed because we don't define it elsewhere. */
183 #ifdef SWITCH_ENUM_BUG
184 #define SWITCH_ENUM_CAST(x) ((int)(x))
186 #define SWITCH_ENUM_CAST(x) (x)
190 /* Get the interface, including the syntax bits. */
193 /* isalpha etc. are used for the character classes. */
196 /* Jim Meyering writes:
198 "... Some ctype macros are valid only for character codes that
199 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
200 using /bin/cc or gcc but without giving an ansi option). So, all
201 ctype uses should be through macros like ISPRINT... If
202 STDC_HEADERS is defined, then autoconf has verified that the ctype
203 macros don't need to be guarded with references to isascii. ...
204 Defining isascii to 1 should let any compiler worth its salt
205 eliminate the && through constant folding." */
207 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
208 #define ISASCII_1(c) 1
210 #define ISASCII_1(c) isascii(c)
214 /* The IS*() macros can be passed any character, including an extended
215 one. We need to make sure there are no crashes, which would occur
216 otherwise due to out-of-bounds array references. */
217 #define ISASCII(c) (((EMACS_UINT) (c)) < 0x100 && ISASCII_1 (c))
219 #define ISASCII(c) ISASCII_1 (c)
223 #define ISBLANK(c) (ISASCII (c) && isblank (c))
225 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
228 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
230 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
233 #define ISPRINT(c) (ISASCII (c) && isprint (c))
234 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
235 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
236 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
237 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
238 #define ISLOWER(c) (ISASCII (c) && islower (c))
239 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
240 #define ISSPACE(c) (ISASCII (c) && isspace (c))
241 #define ISUPPER(c) (ISASCII (c) && isupper (c))
242 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
245 #define NULL (void *)0
248 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
249 since ours (we hope) works properly with all combinations of
250 machines, compilers, `char' and `unsigned char' argument types.
251 (Per Bothner suggested the basic approach.) */
252 #undef SIGN_EXTEND_CHAR
254 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
255 #else /* not __STDC__ */
256 /* As in Harbison and Steele. */
257 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
260 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
261 use `alloca' instead of `malloc'. This is because using malloc in
262 re_search* or re_match* could cause memory leaks when C-g is used in
263 Emacs; also, malloc is slower and causes storage fragmentation. On
264 the other hand, malloc is more portable, and easier to debug.
266 Because we sometimes use alloca, some routines have to be macros,
267 not functions -- `alloca'-allocated space disappears at the end of the
268 function it is called in. */
272 #define REGEX_ALLOCATE malloc
273 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
274 #define REGEX_FREE free
276 #else /* not REGEX_MALLOC */
278 /* Emacs already defines alloca, sometimes. */
281 /* Make alloca work the best possible way. */
283 #define alloca __builtin_alloca
284 #else /* not __GNUC__ */
287 #else /* not __GNUC__ or HAVE_ALLOCA_H */
288 #ifndef _AIX /* Already did AIX, up at the top. */
290 #endif /* not _AIX */
291 #endif /* not HAVE_ALLOCA_H */
292 #endif /* not __GNUC__ */
294 #endif /* not alloca */
296 #define REGEX_ALLOCATE alloca
298 /* Assumes a `char *destination' variable. */
299 #define REGEX_REALLOCATE(source, osize, nsize) \
300 (destination = (char *) alloca (nsize), \
301 memmove (destination, source, osize), \
304 /* No need to do anything to free, after alloca. */
305 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
307 #endif /* not REGEX_MALLOC */
309 /* Define how to allocate the failure stack. */
312 #define REGEX_ALLOCATE_STACK(size) \
313 r_alloc ((char **) &failure_stack_ptr, (size))
314 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
315 r_re_alloc ((char **) &failure_stack_ptr, (nsize))
316 #define REGEX_FREE_STACK(ptr) \
317 r_alloc_free ((void **) &failure_stack_ptr)
319 #else /* not REL_ALLOC */
323 #define REGEX_ALLOCATE_STACK malloc
324 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
325 #define REGEX_FREE_STACK free
327 #else /* not REGEX_MALLOC */
329 #define REGEX_ALLOCATE_STACK alloca
331 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
332 REGEX_REALLOCATE (source, osize, nsize)
333 /* No need to explicitly free anything. */
334 #define REGEX_FREE_STACK(arg)
336 #endif /* not REGEX_MALLOC */
337 #endif /* not REL_ALLOC */
340 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
341 `string1' or just past its end. This works if PTR is NULL, which is
343 #define FIRST_STRING_P(ptr) \
344 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
346 /* (Re)Allocate N items of type T using malloc, or fail. */
347 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
348 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
349 #define RETALLOC_IF(addr, n, t) \
350 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
351 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
353 #define BYTEWIDTH 8 /* In bits. */
355 #define STREQ(s1, s2) (strcmp (s1, s2) == 0)
359 #define MAX(a, b) ((a) > (b) ? (a) : (b))
360 #define MIN(a, b) ((a) < (b) ? (a) : (b))
362 typedef char boolean;
367 /* These are the command codes that appear in compiled regular
368 expressions. Some opcodes are followed by argument bytes. A
369 command code can specify any interpretation whatsoever for its
370 arguments. Zero bytes may appear in the compiled regular expression. */
376 /* Succeed right away--no more backtracking. */
379 /* Followed by one byte giving n, then by n literal bytes. */
382 /* Matches any (more or less) character. */
385 /* Matches any one char belonging to specified set. First
386 following byte is number of bitmap bytes. Then come bytes
387 for a bitmap saying which chars are in. Bits in each byte
388 are ordered low-bit-first. A character is in the set if its
389 bit is 1. A character too large to have a bit in the map is
390 automatically not in the set. */
393 /* Same parameters as charset, but match any character that is
394 not one of those specified. */
397 /* Start remembering the text that is matched, for storing in a
398 register. Followed by one byte with the register number, in
399 the range 0 to one less than the pattern buffer's re_nsub
400 field. Then followed by one byte with the number of groups
401 inner to this one. (This last has to be part of the
402 start_memory only because we need it in the on_failure_jump
406 /* Stop remembering the text that is matched and store it in a
407 memory register. Followed by one byte with the register
408 number, in the range 0 to one less than `re_nsub' in the
409 pattern buffer, and one byte with the number of inner groups,
410 just like `start_memory'. (We need the number of inner
411 groups here because we don't have any easy way of finding the
412 corresponding start_memory when we're at a stop_memory.) */
415 /* Match a duplicate of something remembered. Followed by one
416 byte containing the register number. */
419 /* Fail unless at beginning of line. */
422 /* Fail unless at end of line. */
425 /* Succeeds if at beginning of buffer (if emacs) or at beginning
426 of string to be matched (if not). */
429 /* Analogously, for end of buffer/string. */
432 /* Followed by two byte relative address to which to jump. */
435 /* Same as jump, but marks the end of an alternative. */
438 /* Followed by two-byte relative address of place to resume at
439 in case of failure. */
442 /* Like on_failure_jump, but pushes a placeholder instead of the
443 current string position when executed. */
444 on_failure_keep_string_jump,
446 /* Throw away latest failure point and then jump to following
447 two-byte relative address. */
450 /* Change to pop_failure_jump if know won't have to backtrack to
451 match; otherwise change to jump. This is used to jump
452 back to the beginning of a repeat. If what follows this jump
453 clearly won't match what the repeat does, such that we can be
454 sure that there is no use backtracking out of repetitions
455 already matched, then we change it to a pop_failure_jump.
456 Followed by two-byte address. */
459 /* Jump to following two-byte address, and push a dummy failure
460 point. This failure point will be thrown away if an attempt
461 is made to use it for a failure. A `+' construct makes this
462 before the first repeat. Also used as an intermediary kind
463 of jump when compiling an alternative. */
466 /* Push a dummy failure point and continue. Used at the end of
470 /* Followed by two-byte relative address and two-byte number n.
471 After matching N times, jump to the address upon failure. */
474 /* Followed by two-byte relative address, and two-byte number n.
475 Jump to the address N times, then fail. */
478 /* Set the following two-byte relative address to the
479 subsequent two-byte number. The address *includes* the two
483 wordchar, /* Matches any word-constituent character. */
484 notwordchar, /* Matches any char that is not a word-constituent. */
486 wordbeg, /* Succeeds if at word beginning. */
487 wordend, /* Succeeds if at word end. */
489 wordbound, /* Succeeds if at a word boundary. */
490 notwordbound /* Succeeds if not at a word boundary. */
493 ,before_dot, /* Succeeds if before point. */
494 at_dot, /* Succeeds if at point. */
495 after_dot, /* Succeeds if after point. */
497 /* Matches any character whose syntax is specified. Followed by
498 a byte which contains a syntax code, e.g., Sword. */
501 /* Matches any character whose syntax is not that specified. */
507 /* need extra stuff to be able to properly work with XEmacs/Mule
508 characters (which may take up more than one byte) */
510 ,charset_mule, /* Matches any character belonging to specified set.
511 The set is stored in "unified range-table
512 format"; see rangetab.c. Unlike the `charset'
513 opcode, this can handle arbitrary characters. */
515 charset_mule_not /* Same parameters as charset_mule, but match any
516 character that is not one of those specified. */
518 /* 97/2/17 jhod: The following two were merged back in from the Mule
519 2.3 code to enable some language specific processing */
520 ,categoryspec, /* Matches entries in the character category tables */
521 notcategoryspec /* The opposite of the above */
526 /* Common operations on the compiled pattern. */
528 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
530 #define STORE_NUMBER(destination, number) \
532 (destination)[0] = (number) & 0377; \
533 (destination)[1] = (number) >> 8; \
536 /* Same as STORE_NUMBER, except increment DESTINATION to
537 the byte after where the number is stored. Therefore, DESTINATION
538 must be an lvalue. */
540 #define STORE_NUMBER_AND_INCR(destination, number) \
542 STORE_NUMBER (destination, number); \
543 (destination) += 2; \
546 /* Put into DESTINATION a number stored in two contiguous bytes starting
549 #define EXTRACT_NUMBER(destination, source) \
551 (destination) = *(source) & 0377; \
552 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
557 extract_number (int *dest, unsigned char *source)
559 int temp = SIGN_EXTEND_CHAR (*(source + 1));
560 *dest = *source & 0377;
564 #ifndef EXTRACT_MACROS /* To debug the macros. */
565 #undef EXTRACT_NUMBER
566 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
567 #endif /* not EXTRACT_MACROS */
571 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
572 SOURCE must be an lvalue. */
574 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
576 EXTRACT_NUMBER (destination, source); \
582 extract_number_and_incr (int *destination, unsigned char **source)
584 extract_number (destination, *source);
588 #ifndef EXTRACT_MACROS
589 #undef EXTRACT_NUMBER_AND_INCR
590 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
591 extract_number_and_incr (&dest, &src)
592 #endif /* not EXTRACT_MACROS */
596 /* If DEBUG is defined, Regex prints many voluminous messages about what
597 it is doing (if the variable `debug' is nonzero). If linked with the
598 main program in `iregex.c', you can enter patterns and strings
599 interactively. And if linked with the main program in `main.c' and
600 the other test files, you can run the already-written tests. */
604 /* We use standard I/O for debugging. */
608 /* XEmacs provides its own version of assert() */
609 /* It is useful to test things that ``must'' be true when debugging. */
613 static int debug = 0;
615 #define DEBUG_STATEMENT(e) e
616 #define DEBUG_PRINT1(x) if (debug) printf (x)
617 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
618 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
619 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
620 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
621 if (debug) print_partial_compiled_pattern (s, e)
622 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
623 if (debug) print_double_string (w, s1, sz1, s2, sz2)
626 /* Print the fastmap in human-readable form. */
629 print_fastmap (char *fastmap)
631 unsigned was_a_range = 0;
634 while (i < (1 << BYTEWIDTH))
640 while (i < (1 << BYTEWIDTH) && fastmap[i])
656 /* Print a compiled pattern string in human-readable form, starting at
657 the START pointer into it and ending just before the pointer END. */
660 print_partial_compiled_pattern (unsigned char *start, unsigned char *end)
663 unsigned char *p = start;
664 unsigned char *pend = end;
672 /* Loop over pattern commands. */
675 printf ("%ld:\t", (long)(p - start));
677 switch ((re_opcode_t) *p++)
685 printf ("/exactn/%d", mcnt);
696 printf ("/start_memory/%d/%d", mcnt, *p++);
701 printf ("/stop_memory/%d/%d", mcnt, *p++);
705 printf ("/duplicate/%d", *p++);
715 REGISTER int c, last = -100;
716 REGISTER int in_range = 0;
718 printf ("/charset [%s",
719 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
721 assert (p + *p < pend);
723 for (c = 0; c < 256; c++)
724 if (((unsigned char) (c / 8) < *p)
725 && (p[1 + (c/8)] & (1 << (c % 8))))
727 /* Are we starting a range? */
728 if (last + 1 == c && ! in_range)
733 /* Have we broken a range? */
734 else if (last + 1 != c && in_range)
757 case charset_mule_not:
761 printf ("/charset_mule [%s",
762 (re_opcode_t) *(p - 1) == charset_mule_not ? "^" : "");
763 nentries = unified_range_table_nentries (p);
764 for (i = 0; i < nentries; i++)
766 EMACS_INT first, last;
767 Lisp_Object dummy_val;
769 unified_range_table_get_range (p, i, &first, &last,
774 printf ("(0x%lx)", (long)first);
781 printf ("(0x%lx)", (long)last);
785 p += unified_range_table_bytes_used (p);
798 case on_failure_jump:
799 extract_number_and_incr (&mcnt, &p);
800 printf ("/on_failure_jump to %ld", (long)(p + mcnt - start));
803 case on_failure_keep_string_jump:
804 extract_number_and_incr (&mcnt, &p);
805 printf ("/on_failure_keep_string_jump to %ld", (long)(p + mcnt - start));
808 case dummy_failure_jump:
809 extract_number_and_incr (&mcnt, &p);
810 printf ("/dummy_failure_jump to %ld", (long)(p + mcnt - start));
813 case push_dummy_failure:
814 printf ("/push_dummy_failure");
818 extract_number_and_incr (&mcnt, &p);
819 printf ("/maybe_pop_jump to %ld", (long)(p + mcnt - start));
822 case pop_failure_jump:
823 extract_number_and_incr (&mcnt, &p);
824 printf ("/pop_failure_jump to %ld", (long)(p + mcnt - start));
828 extract_number_and_incr (&mcnt, &p);
829 printf ("/jump_past_alt to %ld", (long)(p + mcnt - start));
833 extract_number_and_incr (&mcnt, &p);
834 printf ("/jump to %ld", (long)(p + mcnt - start));
838 extract_number_and_incr (&mcnt, &p);
839 extract_number_and_incr (&mcnt2, &p);
840 printf ("/succeed_n to %ld, %d times", (long)(p + mcnt - start), mcnt2);
844 extract_number_and_incr (&mcnt, &p);
845 extract_number_and_incr (&mcnt2, &p);
846 printf ("/jump_n to %ld, %d times", (long)(p + mcnt - start), mcnt2);
850 extract_number_and_incr (&mcnt, &p);
851 extract_number_and_incr (&mcnt2, &p);
852 printf ("/set_number_at location %ld to %d", (long)(p + mcnt - start), mcnt2);
856 printf ("/wordbound");
860 printf ("/notwordbound");
872 printf ("/before_dot");
880 printf ("/after_dot");
884 printf ("/syntaxspec");
886 printf ("/%d", mcnt);
890 printf ("/notsyntaxspec");
892 printf ("/%d", mcnt);
896 /* 97/2/17 jhod Mule category patch */
898 printf ("/categoryspec");
900 printf ("/%d", mcnt);
903 case notcategoryspec:
904 printf ("/notcategoryspec");
906 printf ("/%d", mcnt);
908 /* end of category patch */
913 printf ("/wordchar");
917 printf ("/notwordchar");
929 printf ("?%d", *(p-1));
935 printf ("%ld:\tend of pattern.\n", (long)(p - start));
940 print_compiled_pattern (struct re_pattern_buffer *bufp)
942 unsigned char *buffer = bufp->buffer;
944 print_partial_compiled_pattern (buffer, buffer + bufp->used);
945 printf ("%ld bytes used/%ld bytes allocated.\n", bufp->used,
948 if (bufp->fastmap_accurate && bufp->fastmap)
950 printf ("fastmap: ");
951 print_fastmap (bufp->fastmap);
954 printf ("re_nsub: %ld\t", (long)bufp->re_nsub);
955 printf ("regs_alloc: %d\t", bufp->regs_allocated);
956 printf ("can_be_null: %d\t", bufp->can_be_null);
957 printf ("newline_anchor: %d\n", bufp->newline_anchor);
958 printf ("no_sub: %d\t", bufp->no_sub);
959 printf ("not_bol: %d\t", bufp->not_bol);
960 printf ("not_eol: %d\t", bufp->not_eol);
961 printf ("syntax: %d\n", bufp->syntax);
962 /* Perhaps we should print the translate table? */
963 /* and maybe the category table? */
968 print_double_string (CONST char *where, CONST char *string1, int size1,
969 CONST char *string2, int size2)
975 unsigned int this_char;
977 if (FIRST_STRING_P (where))
979 for (this_char = where - string1; this_char < size1; this_char++)
980 putchar (string1[this_char]);
985 for (this_char = where - string2; this_char < size2; this_char++)
986 putchar (string2[this_char]);
990 #else /* not DEBUG */
995 #define DEBUG_STATEMENT(e)
996 #define DEBUG_PRINT1(x)
997 #define DEBUG_PRINT2(x1, x2)
998 #define DEBUG_PRINT3(x1, x2, x3)
999 #define DEBUG_PRINT4(x1, x2, x3, x4)
1000 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1001 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1003 #endif /* not DEBUG */
1005 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1006 also be assigned to arbitrarily: each pattern buffer stores its own
1007 syntax, so it can be changed between regex compilations. */
1008 /* This has no initializer because initialized variables in Emacs
1009 become read-only after dumping. */
1010 reg_syntax_t re_syntax_options;
1013 /* Specify the precise syntax of regexps for compilation. This provides
1014 for compatibility for various utilities which historically have
1015 different, incompatible syntaxes.
1017 The argument SYNTAX is a bit mask comprised of the various bits
1018 defined in regex.h. We return the old syntax. */
1021 re_set_syntax (reg_syntax_t syntax)
1023 reg_syntax_t ret = re_syntax_options;
1025 re_syntax_options = syntax;
1029 /* This table gives an error message for each of the error codes listed
1030 in regex.h. Obviously the order here has to be same as there.
1031 POSIX doesn't require that we do anything for REG_NOERROR,
1032 but why not be nice? */
1034 static CONST char *re_error_msgid[] =
1036 "Success", /* REG_NOERROR */
1037 "No match", /* REG_NOMATCH */
1038 "Invalid regular expression", /* REG_BADPAT */
1039 "Invalid collation character", /* REG_ECOLLATE */
1040 "Invalid character class name", /* REG_ECTYPE */
1041 "Trailing backslash", /* REG_EESCAPE */
1042 "Invalid back reference", /* REG_ESUBREG */
1043 "Unmatched [ or [^", /* REG_EBRACK */
1044 "Unmatched ( or \\(", /* REG_EPAREN */
1045 "Unmatched \\{", /* REG_EBRACE */
1046 "Invalid content of \\{\\}", /* REG_BADBR */
1047 "Invalid range end", /* REG_ERANGE */
1048 "Memory exhausted", /* REG_ESPACE */
1049 "Invalid preceding regular expression", /* REG_BADRPT */
1050 "Premature end of regular expression", /* REG_EEND */
1051 "Regular expression too big", /* REG_ESIZE */
1052 "Unmatched ) or \\)", /* REG_ERPAREN */
1054 "Invalid syntax designator", /* REG_ESYNTAX */
1057 "Ranges may not span charsets", /* REG_ERANGESPAN */
1058 "Invalid category designator", /* REG_ECATEGORY */
1062 /* Avoiding alloca during matching, to placate r_alloc. */
1064 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1065 searching and matching functions should not call alloca. On some
1066 systems, alloca is implemented in terms of malloc, and if we're
1067 using the relocating allocator routines, then malloc could cause a
1068 relocation, which might (if the strings being searched are in the
1069 ralloc heap) shift the data out from underneath the regexp
1072 Here's another reason to avoid allocation: Emacs
1073 processes input from X in a signal handler; processing X input may
1074 call malloc; if input arrives while a matching routine is calling
1075 malloc, then we're scrod. But Emacs can't just block input while
1076 calling matching routines; then we don't notice interrupts when
1077 they come in. So, Emacs blocks input around all regexp calls
1078 except the matching calls, which it leaves unprotected, in the
1079 faith that they will not malloc. */
1081 /* Normally, this is fine. */
1082 #define MATCH_MAY_ALLOCATE
1084 /* When using GNU C, we are not REALLY using the C alloca, no matter
1085 what config.h may say. So don't take precautions for it. */
1090 /* The match routines may not allocate if (1) they would do it with malloc
1091 and (2) it's not safe for them to use malloc.
1092 Note that if REL_ALLOC is defined, matching would not use malloc for the
1093 failure stack, but we would still use it for the register vectors;
1094 so REL_ALLOC should not affect this. */
1095 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1096 #undef MATCH_MAY_ALLOCATE
1100 /* Failure stack declarations and macros; both re_compile_fastmap and
1101 re_match_2 use a failure stack. These have to be macros because of
1102 REGEX_ALLOCATE_STACK. */
1105 /* Number of failure points for which to initially allocate space
1106 when matching. If this number is exceeded, we allocate more
1107 space, so it is not a hard limit. */
1108 #ifndef INIT_FAILURE_ALLOC
1109 #define INIT_FAILURE_ALLOC 5
1112 /* Roughly the maximum number of failure points on the stack. Would be
1113 exactly that if always used MAX_FAILURE_SPACE each time we failed.
1114 This is a variable only so users of regex can assign to it; we never
1115 change it ourselves. */
1116 #if defined (MATCH_MAY_ALLOCATE)
1117 /* 4400 was enough to cause a crash on Alpha OSF/1,
1118 whose default stack limit is 2mb. */
1119 int re_max_failures = 20000;
1121 int re_max_failures = 2000;
1124 union fail_stack_elt
1126 unsigned char *pointer;
1130 typedef union fail_stack_elt fail_stack_elt_t;
1134 fail_stack_elt_t *stack;
1136 unsigned avail; /* Offset of next open position. */
1139 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1140 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1141 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1144 /* Define macros to initialize and free the failure stack.
1145 Do `return -2' if the alloc fails. */
1147 #ifdef MATCH_MAY_ALLOCATE
1148 #define INIT_FAIL_STACK() \
1150 fail_stack.stack = (fail_stack_elt_t *) \
1151 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1153 if (fail_stack.stack == NULL) \
1156 fail_stack.size = INIT_FAILURE_ALLOC; \
1157 fail_stack.avail = 0; \
1160 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1162 #define INIT_FAIL_STACK() \
1164 fail_stack.avail = 0; \
1167 #define RESET_FAIL_STACK()
1171 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1173 Return 1 if succeeds, and 0 if either ran out of memory
1174 allocating space for it or it was already too large.
1176 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1178 #define DOUBLE_FAIL_STACK(fail_stack) \
1179 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
1181 : ((fail_stack).stack = (fail_stack_elt_t *) \
1182 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1183 (fail_stack).size * sizeof (fail_stack_elt_t), \
1184 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1186 (fail_stack).stack == NULL \
1188 : ((fail_stack).size <<= 1, \
1192 /* Push pointer POINTER on FAIL_STACK.
1193 Return 1 if was able to do so and 0 if ran out of memory allocating
1195 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1196 ((FAIL_STACK_FULL () \
1197 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1199 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1202 /* Push a pointer value onto the failure stack.
1203 Assumes the variable `fail_stack'. Probably should only
1204 be called from within `PUSH_FAILURE_POINT'. */
1205 #define PUSH_FAILURE_POINTER(item) \
1206 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1208 /* This pushes an integer-valued item onto the failure stack.
1209 Assumes the variable `fail_stack'. Probably should only
1210 be called from within `PUSH_FAILURE_POINT'. */
1211 #define PUSH_FAILURE_INT(item) \
1212 fail_stack.stack[fail_stack.avail++].integer = (item)
1214 /* Push a fail_stack_elt_t value onto the failure stack.
1215 Assumes the variable `fail_stack'. Probably should only
1216 be called from within `PUSH_FAILURE_POINT'. */
1217 #define PUSH_FAILURE_ELT(item) \
1218 fail_stack.stack[fail_stack.avail++] = (item)
1220 /* These three POP... operations complement the three PUSH... operations.
1221 All assume that `fail_stack' is nonempty. */
1222 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1223 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1224 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1226 /* Used to omit pushing failure point id's when we're not debugging. */
1228 #define DEBUG_PUSH PUSH_FAILURE_INT
1229 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1231 #define DEBUG_PUSH(item)
1232 #define DEBUG_POP(item_addr)
1236 /* Push the information about the state we will need
1237 if we ever fail back to it.
1239 Requires variables fail_stack, regstart, regend, reg_info, and
1240 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
1243 Does `return FAILURE_CODE' if runs out of memory. */
1245 #if !defined (REGEX_MALLOC) && !defined (REL_ALLOC)
1246 #define DECLARE_DESTINATION char *destination;
1248 #define DECLARE_DESTINATION
1251 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1253 DECLARE_DESTINATION \
1254 /* Must be int, so when we don't save any registers, the arithmetic \
1255 of 0 + -1 isn't done as unsigned. */ \
1258 DEBUG_STATEMENT (failure_id++); \
1259 DEBUG_STATEMENT (nfailure_points_pushed++); \
1260 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1261 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1262 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1264 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1265 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1267 /* Ensure we have enough space allocated for what we will push. */ \
1268 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1270 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1271 return failure_code; \
1273 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1274 (fail_stack).size); \
1275 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1278 /* Push the info, starting with the registers. */ \
1279 DEBUG_PRINT1 ("\n"); \
1281 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1284 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1285 DEBUG_STATEMENT (num_regs_pushed++); \
1287 DEBUG_PRINT2 (" start: 0x%lx\n", (long) regstart[this_reg]); \
1288 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1290 DEBUG_PRINT2 (" end: 0x%lx\n", (long) regend[this_reg]); \
1291 PUSH_FAILURE_POINTER (regend[this_reg]); \
1293 DEBUG_PRINT2 (" info: 0x%lx\n ", \
1294 * (long *) (®_info[this_reg])); \
1295 DEBUG_PRINT2 (" match_null=%d", \
1296 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1297 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1298 DEBUG_PRINT2 (" matched_something=%d", \
1299 MATCHED_SOMETHING (reg_info[this_reg])); \
1300 DEBUG_PRINT2 (" ever_matched=%d", \
1301 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1302 DEBUG_PRINT1 ("\n"); \
1303 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1306 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1307 PUSH_FAILURE_INT (lowest_active_reg); \
1309 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1310 PUSH_FAILURE_INT (highest_active_reg); \
1312 DEBUG_PRINT2 (" Pushing pattern 0x%lx: ", (long) pattern_place); \
1313 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1314 PUSH_FAILURE_POINTER (pattern_place); \
1316 DEBUG_PRINT2 (" Pushing string 0x%lx: `", (long) string_place); \
1317 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1319 DEBUG_PRINT1 ("'\n"); \
1320 PUSH_FAILURE_POINTER (string_place); \
1322 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1323 DEBUG_PUSH (failure_id); \
1326 /* This is the number of items that are pushed and popped on the stack
1327 for each register. */
1328 #define NUM_REG_ITEMS 3
1330 /* Individual items aside from the registers. */
1332 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1334 #define NUM_NONREG_ITEMS 4
1337 /* We push at most this many items on the stack. */
1338 /* We used to use (num_regs - 1), which is the number of registers
1339 this regexp will save; but that was changed to 5
1340 to avoid stack overflow for a regexp with lots of parens. */
1341 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1343 /* We actually push this many items. */
1344 #define NUM_FAILURE_ITEMS \
1345 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
1348 /* How many items can still be added to the stack without overflowing it. */
1349 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1352 /* Pops what PUSH_FAIL_STACK pushes.
1354 We restore into the parameters, all of which should be lvalues:
1355 STR -- the saved data position.
1356 PAT -- the saved pattern position.
1357 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1358 REGSTART, REGEND -- arrays of string positions.
1359 REG_INFO -- array of information about each subexpression.
1361 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1362 `pend', `string1', `size1', `string2', and `size2'. */
1364 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1366 DEBUG_STATEMENT (fail_stack_elt_t ffailure_id;) \
1368 CONST unsigned char *string_temp; \
1370 assert (!FAIL_STACK_EMPTY ()); \
1372 /* Remove failure points and point to how many regs pushed. */ \
1373 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1374 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1375 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1377 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1379 DEBUG_POP (&ffailure_id.integer); \
1380 DEBUG_PRINT2 (" Popping failure id: %u\n", \
1381 * (unsigned int *) &ffailure_id); \
1383 /* If the saved string location is NULL, it came from an \
1384 on_failure_keep_string_jump opcode, and we want to throw away the \
1385 saved NULL, thus retaining our current position in the string. */ \
1386 string_temp = POP_FAILURE_POINTER (); \
1387 if (string_temp != NULL) \
1388 str = (CONST char *) string_temp; \
1390 DEBUG_PRINT2 (" Popping string 0x%lx: `", (long) str); \
1391 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1392 DEBUG_PRINT1 ("'\n"); \
1394 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1395 DEBUG_PRINT2 (" Popping pattern 0x%lx: ", (long) pat); \
1396 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1398 /* Restore register info. */ \
1399 high_reg = (unsigned) POP_FAILURE_INT (); \
1400 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1402 low_reg = (unsigned) POP_FAILURE_INT (); \
1403 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1405 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1407 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1409 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1410 DEBUG_PRINT2 (" info: 0x%lx\n", \
1411 * (long *) ®_info[this_reg]); \
1413 regend[this_reg] = (CONST char *) POP_FAILURE_POINTER (); \
1414 DEBUG_PRINT2 (" end: 0x%lx\n", (long) regend[this_reg]); \
1416 regstart[this_reg] = (CONST char *) POP_FAILURE_POINTER (); \
1417 DEBUG_PRINT2 (" start: 0x%lx\n", (long) regstart[this_reg]); \
1420 set_regs_matched_done = 0; \
1421 DEBUG_STATEMENT (nfailure_points_popped++); \
1422 } /* POP_FAILURE_POINT */
1426 /* Structure for per-register (a.k.a. per-group) information.
1427 Other register information, such as the
1428 starting and ending positions (which are addresses), and the list of
1429 inner groups (which is a bits list) are maintained in separate
1432 We are making a (strictly speaking) nonportable assumption here: that
1433 the compiler will pack our bit fields into something that fits into
1434 the type of `word', i.e., is something that fits into one item on the
1439 fail_stack_elt_t word;
1442 /* This field is one if this group can match the empty string,
1443 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1444 #define MATCH_NULL_UNSET_VALUE 3
1445 unsigned match_null_string_p : 2;
1446 unsigned is_active : 1;
1447 unsigned matched_something : 1;
1448 unsigned ever_matched_something : 1;
1450 } register_info_type;
1452 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1453 #define IS_ACTIVE(R) ((R).bits.is_active)
1454 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1455 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1458 /* Call this when have matched a real character; it sets `matched' flags
1459 for the subexpressions which we are currently inside. Also records
1460 that those subexprs have matched. */
1461 #define SET_REGS_MATCHED() \
1464 if (!set_regs_matched_done) \
1467 set_regs_matched_done = 1; \
1468 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1470 MATCHED_SOMETHING (reg_info[r]) \
1471 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1478 /* Registers are set to a sentinel when they haven't yet matched. */
1479 static char reg_unset_dummy;
1480 #define REG_UNSET_VALUE (®_unset_dummy)
1481 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1483 /* Subroutine declarations and macros for regex_compile. */
1485 /* Fetch the next character in the uncompiled pattern---translating it
1486 if necessary. Also cast from a signed character in the constant
1487 string passed to us by the user to an unsigned char that we can use
1488 as an array index (in, e.g., `translate'). */
1489 #define PATFETCH(c) \
1490 do {if (p == pend) return REG_EEND; \
1491 assert (p < pend); \
1492 c = (unsigned char) *p++; \
1493 if (translate) c = (unsigned char) translate[c]; \
1496 /* Fetch the next character in the uncompiled pattern, with no
1498 #define PATFETCH_RAW(c) \
1499 do {if (p == pend) return REG_EEND; \
1500 assert (p < pend); \
1501 c = (unsigned char) *p++; \
1504 /* Go backwards one character in the pattern. */
1505 #define PATUNFETCH p--
1509 #define PATFETCH_EXTENDED(emch) \
1510 do {if (p == pend) return REG_EEND; \
1511 assert (p < pend); \
1512 emch = charptr_emchar ((CONST Bufbyte *) p); \
1514 if (translate && emch < 0x80) \
1515 emch = (Emchar) (unsigned char) translate[emch]; \
1518 #define PATFETCH_RAW_EXTENDED(emch) \
1519 do {if (p == pend) return REG_EEND; \
1520 assert (p < pend); \
1521 emch = charptr_emchar ((CONST Bufbyte *) p); \
1525 #define PATUNFETCH_EXTENDED DEC_CHARPTR (p)
1527 #define PATFETCH_EITHER(emch) \
1529 if (has_extended_chars) \
1530 PATFETCH_EXTENDED (emch); \
1535 #define PATFETCH_RAW_EITHER(emch) \
1537 if (has_extended_chars) \
1538 PATFETCH_RAW_EXTENDED (emch); \
1540 PATFETCH_RAW (emch); \
1543 #define PATUNFETCH_EITHER \
1545 if (has_extended_chars) \
1546 PATUNFETCH_EXTENDED (emch); \
1548 PATUNFETCH (emch); \
1551 #else /* not MULE */
1553 #define PATFETCH_EITHER(emch) PATFETCH (emch)
1554 #define PATFETCH_RAW_EITHER(emch) PATFETCH_RAW (emch)
1555 #define PATUNFETCH_EITHER PATUNFETCH
1557 #endif /* not MULE */
1559 /* If `translate' is non-null, return translate[D], else just D. We
1560 cast the subscript to translate because some data is declared as
1561 `char *', to avoid warnings when a string constant is passed. But
1562 when we use a character as a subscript we must make it unsigned. */
1563 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
1567 #define TRANSLATE_EXTENDED_UNSAFE(emch) \
1568 (translate && emch < 0x80 ? translate[emch] : (emch))
1572 /* Macros for outputting the compiled pattern into `buffer'. */
1574 /* If the buffer isn't allocated when it comes in, use this. */
1575 #define INIT_BUF_SIZE 32
1577 /* Make sure we have at least N more bytes of space in buffer. */
1578 #define GET_BUFFER_SPACE(n) \
1579 while (b - bufp->buffer + (n) > bufp->allocated) \
1582 /* Make sure we have one more byte of buffer space and then add C to it. */
1583 #define BUF_PUSH(c) \
1585 GET_BUFFER_SPACE (1); \
1586 *b++ = (unsigned char) (c); \
1590 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1591 #define BUF_PUSH_2(c1, c2) \
1593 GET_BUFFER_SPACE (2); \
1594 *b++ = (unsigned char) (c1); \
1595 *b++ = (unsigned char) (c2); \
1599 /* As with BUF_PUSH_2, except for three bytes. */
1600 #define BUF_PUSH_3(c1, c2, c3) \
1602 GET_BUFFER_SPACE (3); \
1603 *b++ = (unsigned char) (c1); \
1604 *b++ = (unsigned char) (c2); \
1605 *b++ = (unsigned char) (c3); \
1609 /* Store a jump with opcode OP at LOC to location TO. We store a
1610 relative address offset by the three bytes the jump itself occupies. */
1611 #define STORE_JUMP(op, loc, to) \
1612 store_op1 (op, loc, (to) - (loc) - 3)
1614 /* Likewise, for a two-argument jump. */
1615 #define STORE_JUMP2(op, loc, to, arg) \
1616 store_op2 (op, loc, (to) - (loc) - 3, arg)
1618 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1619 #define INSERT_JUMP(op, loc, to) \
1620 insert_op1 (op, loc, (to) - (loc) - 3, b)
1622 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1623 #define INSERT_JUMP2(op, loc, to, arg) \
1624 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1627 /* This is not an arbitrary limit: the arguments which represent offsets
1628 into the pattern are two bytes long. So if 2^16 bytes turns out to
1629 be too small, many things would have to change. */
1630 #define MAX_BUF_SIZE (1L << 16)
1633 /* Extend the buffer by twice its current size via realloc and
1634 reset the pointers that pointed into the old block to point to the
1635 correct places in the new one. If extending the buffer results in it
1636 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1637 #define EXTEND_BUFFER() \
1639 unsigned char *old_buffer = bufp->buffer; \
1640 if (bufp->allocated == MAX_BUF_SIZE) \
1642 bufp->allocated <<= 1; \
1643 if (bufp->allocated > MAX_BUF_SIZE) \
1644 bufp->allocated = MAX_BUF_SIZE; \
1645 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1646 if (bufp->buffer == NULL) \
1647 return REG_ESPACE; \
1648 /* If the buffer moved, move all the pointers into it. */ \
1649 if (old_buffer != bufp->buffer) \
1651 b = (b - old_buffer) + bufp->buffer; \
1652 begalt = (begalt - old_buffer) + bufp->buffer; \
1653 if (fixup_alt_jump) \
1654 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1656 laststart = (laststart - old_buffer) + bufp->buffer; \
1657 if (pending_exact) \
1658 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1663 /* Since we have one byte reserved for the register number argument to
1664 {start,stop}_memory, the maximum number of groups we can report
1665 things about is what fits in that byte. */
1666 #define MAX_REGNUM 255
1668 /* But patterns can have more than `MAX_REGNUM' registers. We just
1669 ignore the excess. */
1670 typedef unsigned regnum_t;
1673 /* Macros for the compile stack. */
1675 /* Since offsets can go either forwards or backwards, this type needs to
1676 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1677 typedef int pattern_offset_t;
1681 pattern_offset_t begalt_offset;
1682 pattern_offset_t fixup_alt_jump;
1683 pattern_offset_t inner_group_offset;
1684 pattern_offset_t laststart_offset;
1686 } compile_stack_elt_t;
1691 compile_stack_elt_t *stack;
1693 unsigned avail; /* Offset of next open position. */
1694 } compile_stack_type;
1697 #define INIT_COMPILE_STACK_SIZE 32
1699 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1700 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1702 /* The next available element. */
1703 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1706 /* Set the bit for character C in a bit vector. */
1707 #define SET_LIST_BIT(c) \
1708 (b[((unsigned char) (c)) / BYTEWIDTH] \
1709 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1713 /* Set the "bit" for character C in a range table. */
1714 #define SET_RANGETAB_BIT(c) put_range_table (rtab, c, c, Qt)
1716 /* Set the "bit" for character c in the appropriate table. */
1717 #define SET_EITHER_BIT(c) \
1719 if (has_extended_chars) \
1720 SET_RANGETAB_BIT (c); \
1725 #else /* not MULE */
1727 #define SET_EITHER_BIT(c) SET_LIST_BIT (c)
1732 /* Get the next unsigned number in the uncompiled pattern. */
1733 #define GET_UNSIGNED_NUMBER(num) \
1737 while (ISDIGIT (c)) \
1741 num = num * 10 + c - '0'; \
1749 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1751 #define IS_CHAR_CLASS(string) \
1752 (STREQ (string, "alpha") || STREQ (string, "upper") \
1753 || STREQ (string, "lower") || STREQ (string, "digit") \
1754 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1755 || STREQ (string, "space") || STREQ (string, "print") \
1756 || STREQ (string, "punct") || STREQ (string, "graph") \
1757 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1759 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1760 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1761 static void insert_op1 (re_opcode_t op, unsigned char *loc, int arg,
1762 unsigned char *end);
1763 static void insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2,
1764 unsigned char *end);
1765 static boolean at_begline_loc_p (CONST char *pattern, CONST char *p,
1766 reg_syntax_t syntax);
1767 static boolean at_endline_loc_p (CONST char *p, CONST char *pend, int syntax);
1768 static boolean group_in_compile_stack (compile_stack_type compile_stack,
1770 static reg_errcode_t compile_range (CONST char **p_ptr, CONST char *pend,
1771 char *translate, reg_syntax_t syntax,
1774 static reg_errcode_t compile_extended_range (CONST char **p_ptr,
1777 reg_syntax_t syntax,
1780 static boolean group_match_null_string_p (unsigned char **p,
1782 register_info_type *reg_info);
1783 static boolean alt_match_null_string_p (unsigned char *p, unsigned char *end,
1784 register_info_type *reg_info);
1785 static boolean common_op_match_null_string_p (unsigned char **p,
1787 register_info_type *reg_info);
1788 static int bcmp_translate (CONST unsigned char *s1, CONST unsigned char *s2,
1789 REGISTER int len, char *translate);
1790 static int re_match_2_internal (struct re_pattern_buffer *bufp,
1791 CONST char *string1, int size1,
1792 CONST char *string2, int size2, int pos,
1793 struct re_registers *regs, int stop);
1795 #ifndef MATCH_MAY_ALLOCATE
1797 /* If we cannot allocate large objects within re_match_2_internal,
1798 we make the fail stack and register vectors global.
1799 The fail stack, we grow to the maximum size when a regexp
1801 The register vectors, we adjust in size each time we
1802 compile a regexp, according to the number of registers it needs. */
1804 static fail_stack_type fail_stack;
1806 /* Size with which the following vectors are currently allocated.
1807 That is so we can make them bigger as needed,
1808 but never make them smaller. */
1809 static int regs_allocated_size;
1811 static CONST char ** regstart, ** regend;
1812 static CONST char ** old_regstart, ** old_regend;
1813 static CONST char **best_regstart, **best_regend;
1814 static register_info_type *reg_info;
1815 static CONST char **reg_dummy;
1816 static register_info_type *reg_info_dummy;
1818 /* Make the register vectors big enough for NUM_REGS registers,
1819 but don't make them smaller. */
1822 regex_grow_registers (int num_regs)
1824 if (num_regs > regs_allocated_size)
1826 RETALLOC_IF (regstart, num_regs, CONST char *);
1827 RETALLOC_IF (regend, num_regs, CONST char *);
1828 RETALLOC_IF (old_regstart, num_regs, CONST char *);
1829 RETALLOC_IF (old_regend, num_regs, CONST char *);
1830 RETALLOC_IF (best_regstart, num_regs, CONST char *);
1831 RETALLOC_IF (best_regend, num_regs, CONST char *);
1832 RETALLOC_IF (reg_info, num_regs, register_info_type);
1833 RETALLOC_IF (reg_dummy, num_regs, CONST char *);
1834 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1836 regs_allocated_size = num_regs;
1840 #endif /* not MATCH_MAY_ALLOCATE */
1842 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1843 Returns one of error codes defined in `regex.h', or zero for success.
1845 Assumes the `allocated' (and perhaps `buffer') and `translate'
1846 fields are set in BUFP on entry.
1848 If it succeeds, results are put in BUFP (if it returns an error, the
1849 contents of BUFP are undefined):
1850 `buffer' is the compiled pattern;
1851 `syntax' is set to SYNTAX;
1852 `used' is set to the length of the compiled pattern;
1853 `fastmap_accurate' is zero;
1854 `re_nsub' is the number of subexpressions in PATTERN;
1855 `not_bol' and `not_eol' are zero;
1857 The `fastmap' and `newline_anchor' fields are neither
1858 examined nor set. */
1860 /* Return, freeing storage we allocated. */
1861 #define FREE_STACK_RETURN(value) \
1862 return (free (compile_stack.stack), value)
1864 static reg_errcode_t
1865 regex_compile (CONST char *pattern, int size, reg_syntax_t syntax,
1866 struct re_pattern_buffer *bufp)
1868 /* We fetch characters from PATTERN here. We declare these as int
1869 (or possibly long) so that chars above 127 can be used as
1870 array indices. The macros that fetch a character from the pattern
1871 make sure to coerce to unsigned char before assigning, so we won't
1872 get bitten by negative numbers here. */
1873 /* XEmacs change: used to be unsigned char. */
1874 REGISTER EMACS_INT c, c1;
1876 /* A random temporary spot in PATTERN. */
1879 /* Points to the end of the buffer, where we should append. */
1880 REGISTER unsigned char *b;
1882 /* Keeps track of unclosed groups. */
1883 compile_stack_type compile_stack;
1885 /* Points to the current (ending) position in the pattern. */
1886 CONST char *p = pattern;
1887 CONST char *pend = pattern + size;
1889 /* How to translate the characters in the pattern. */
1890 char *translate = bufp->translate;
1892 /* Address of the count-byte of the most recently inserted `exactn'
1893 command. This makes it possible to tell if a new exact-match
1894 character can be added to that command or if the character requires
1895 a new `exactn' command. */
1896 unsigned char *pending_exact = 0;
1898 /* Address of start of the most recently finished expression.
1899 This tells, e.g., postfix * where to find the start of its
1900 operand. Reset at the beginning of groups and alternatives. */
1901 unsigned char *laststart = 0;
1903 /* Address of beginning of regexp, or inside of last group. */
1904 unsigned char *begalt;
1906 /* Place in the uncompiled pattern (i.e., the {) to
1907 which to go back if the interval is invalid. */
1908 CONST char *beg_interval;
1910 /* Address of the place where a forward jump should go to the end of
1911 the containing expression. Each alternative of an `or' -- except the
1912 last -- ends with a forward jump of this sort. */
1913 unsigned char *fixup_alt_jump = 0;
1915 /* Counts open-groups as they are encountered. Remembered for the
1916 matching close-group on the compile stack, so the same register
1917 number is put in the stop_memory as the start_memory. */
1918 regnum_t regnum = 0;
1921 DEBUG_PRINT1 ("\nCompiling pattern: ");
1924 unsigned debug_count;
1926 for (debug_count = 0; debug_count < size; debug_count++)
1927 putchar (pattern[debug_count]);
1932 /* Initialize the compile stack. */
1933 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1934 if (compile_stack.stack == NULL)
1937 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1938 compile_stack.avail = 0;
1940 /* Initialize the pattern buffer. */
1941 bufp->syntax = syntax;
1942 bufp->fastmap_accurate = 0;
1943 bufp->not_bol = bufp->not_eol = 0;
1945 /* Set `used' to zero, so that if we return an error, the pattern
1946 printer (for debugging) will think there's no pattern. We reset it
1950 /* Always count groups, whether or not bufp->no_sub is set. */
1953 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1954 /* Initialize the syntax table. */
1955 init_syntax_once ();
1958 if (bufp->allocated == 0)
1961 { /* If zero allocated, but buffer is non-null, try to realloc
1962 enough space. This loses if buffer's address is bogus, but
1963 that is the user's responsibility. */
1964 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1967 { /* Caller did not allocate a buffer. Do it for them. */
1968 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1970 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1972 bufp->allocated = INIT_BUF_SIZE;
1975 begalt = b = bufp->buffer;
1977 /* Loop through the uncompiled pattern until we're at the end. */
1986 if ( /* If at start of pattern, it's an operator. */
1988 /* If context independent, it's an operator. */
1989 || syntax & RE_CONTEXT_INDEP_ANCHORS
1990 /* Otherwise, depends on what's come before. */
1991 || at_begline_loc_p (pattern, p, syntax))
2001 if ( /* If at end of pattern, it's an operator. */
2003 /* If context independent, it's an operator. */
2004 || syntax & RE_CONTEXT_INDEP_ANCHORS
2005 /* Otherwise, depends on what's next. */
2006 || at_endline_loc_p (p, pend, syntax))
2016 if ((syntax & RE_BK_PLUS_QM)
2017 || (syntax & RE_LIMITED_OPS))
2021 /* If there is no previous pattern... */
2024 if (syntax & RE_CONTEXT_INVALID_OPS)
2025 FREE_STACK_RETURN (REG_BADRPT);
2026 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2031 /* true means zero/many matches are allowed. */
2032 boolean zero_times_ok = c != '+';
2033 boolean many_times_ok = c != '?';
2035 /* true means match shortest string possible. */
2036 boolean minimal = false;
2038 /* If there is a sequence of repetition chars, collapse it
2039 down to just one (the right one). We can't combine
2040 interval operators with these because of, e.g., `a{2}*',
2041 which should only match an even number of `a's. */
2046 if (c == '*' || (!(syntax & RE_BK_PLUS_QM)
2047 && (c == '+' || c == '?')))
2050 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2052 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2055 if (!(c1 == '+' || c1 == '?'))
2070 /* If we get here, we found another repeat character. */
2071 if (!(syntax & RE_NO_MINIMAL_MATCHING))
2073 /* `*?' and `+?' and `??' are okay (and mean match
2074 minimally), but other sequences (such as `*??' and
2075 `+++') are rejected (reserved for future use). */
2076 if (minimal || c != '?')
2077 FREE_STACK_RETURN (REG_BADRPT);
2082 zero_times_ok |= c != '+';
2083 many_times_ok |= c != '?';
2087 /* Star, etc. applied to an empty pattern is equivalent
2088 to an empty pattern. */
2092 /* Now we know whether zero matches is allowed
2093 and whether two or more matches is allowed
2094 and whether we want minimal or maximal matching. */
2100 0: /on_failure_jump to 6
2105 GET_BUFFER_SPACE (6);
2106 INSERT_JUMP (jump, laststart, b + 3);
2108 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2111 else if (zero_times_ok)
2116 6: /on_failure_jump to 3
2119 GET_BUFFER_SPACE (6);
2120 INSERT_JUMP (jump, laststart, b + 3);
2122 STORE_JUMP (on_failure_jump, b, laststart + 3);
2129 3: /on_failure_jump to 0
2132 GET_BUFFER_SPACE (3);
2133 STORE_JUMP (on_failure_jump, b, laststart);
2139 /* Are we optimizing this jump? */
2140 boolean keep_string_p = false;
2143 { /* More than one repetition is allowed, so put in at the
2144 end a backward relative jump from `b' to before the next
2145 jump we're going to put in below (which jumps from
2146 laststart to after this jump).
2148 But if we are at the `*' in the exact sequence `.*\n',
2149 insert an unconditional jump backwards to the .,
2150 instead of the beginning of the loop. This way we only
2151 push a failure point once, instead of every time
2152 through the loop. */
2153 assert (p - 1 > pattern);
2155 /* Allocate the space for the jump. */
2156 GET_BUFFER_SPACE (3);
2158 /* We know we are not at the first character of the
2159 pattern, because laststart was nonzero. And we've
2160 already incremented `p', by the way, to be the
2161 character after the `*'. Do we have to do something
2162 analogous here for null bytes, because of
2164 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2166 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2167 && !(syntax & RE_DOT_NEWLINE))
2168 { /* We have .*\n. */
2169 STORE_JUMP (jump, b, laststart);
2170 keep_string_p = true;
2173 /* Anything else. */
2174 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2176 /* We've added more stuff to the buffer. */
2180 /* On failure, jump from laststart to b + 3, which will be the
2181 end of the buffer after this jump is inserted. */
2182 GET_BUFFER_SPACE (3);
2183 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2190 /* At least one repetition is required, so insert a
2191 `dummy_failure_jump' before the initial
2192 `on_failure_jump' instruction of the loop. This
2193 effects a skip over that instruction the first time
2194 we hit that loop. */
2195 GET_BUFFER_SPACE (3);
2196 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2213 /* XEmacs change: this whole section */
2214 boolean had_char_class = false;
2216 boolean has_extended_chars = false;
2217 REGISTER Lisp_Object rtab = Qnil;
2220 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2222 /* Ensure that we have enough space to push a charset: the
2223 opcode, the length count, and the bitset; 34 bytes in all. */
2224 GET_BUFFER_SPACE (34);
2228 /* We test `*p == '^' twice, instead of using an if
2229 statement, so we only need one BUF_PUSH. */
2230 BUF_PUSH (*p == '^' ? charset_not : charset);
2234 /* Remember the first position in the bracket expression. */
2237 /* Push the number of bytes in the bitmap. */
2238 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2240 /* Clear the whole map. */
2241 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2243 /* charset_not matches newline according to a syntax bit. */
2244 if ((re_opcode_t) b[-2] == charset_not
2245 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2246 SET_LIST_BIT ('\n');
2249 start_over_with_extended:
2250 if (has_extended_chars)
2252 /* There are extended chars here, which means we need to start
2253 over and shift to unified range-table format. */
2254 if (b[-2] == charset)
2255 b[-2] = charset_mule;
2257 b[-2] = charset_mule_not;
2259 p = p1; /* go back to the beginning of the charset, after
2261 rtab = Vthe_lisp_rangetab;
2262 Fclear_range_table (rtab);
2264 /* charset_not matches newline according to a syntax bit. */
2265 if ((re_opcode_t) b[-1] == charset_mule_not
2266 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2267 SET_EITHER_BIT ('\n');
2271 /* Read in characters and ranges, setting map bits. */
2274 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2276 PATFETCH_EITHER (c);
2279 if (c >= 0x80 && !has_extended_chars)
2281 has_extended_chars = 1;
2282 /* Frumble-bumble, we've found some extended chars.
2283 Need to start over, process everything using
2284 the general extended-char mechanism, and need
2285 to use charset_mule and charset_mule_not instead
2286 of charset and charset_not. */
2287 goto start_over_with_extended;
2290 /* \ might escape characters inside [...] and [^...]. */
2291 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2293 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2295 PATFETCH_EITHER (c1);
2297 if (c1 >= 0x80 && !has_extended_chars)
2299 has_extended_chars = 1;
2300 goto start_over_with_extended;
2303 SET_EITHER_BIT (c1);
2307 /* Could be the end of the bracket expression. If it's
2308 not (i.e., when the bracket expression is `[]' so
2309 far), the ']' character bit gets set way below. */
2310 if (c == ']' && p != p1 + 1)
2313 /* Look ahead to see if it's a range when the last thing
2314 was a character class. */
2315 if (had_char_class && c == '-' && *p != ']')
2316 FREE_STACK_RETURN (REG_ERANGE);
2318 /* Look ahead to see if it's a range when the last thing
2319 was a character: if this is a hyphen not at the
2320 beginning or the end of a list, then it's the range
2323 && !(p - 2 >= pattern && p[-2] == '[')
2324 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2330 if (* (unsigned char *) p >= 0x80 && !has_extended_chars)
2332 has_extended_chars = 1;
2333 goto start_over_with_extended;
2335 if (has_extended_chars)
2336 ret = compile_extended_range (&p, pend, translate,
2340 ret = compile_range (&p, pend, translate, syntax, b);
2341 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2344 else if (p[0] == '-' && p[1] != ']')
2345 { /* This handles ranges made up of characters only. */
2348 /* Move past the `-'. */
2352 if (* (unsigned char *) p >= 0x80 && !has_extended_chars)
2354 has_extended_chars = 1;
2355 goto start_over_with_extended;
2357 if (has_extended_chars)
2358 ret = compile_extended_range (&p, pend, translate,
2362 ret = compile_range (&p, pend, translate, syntax, b);
2363 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2366 /* See if we're at the beginning of a possible character
2369 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2370 { /* Leave room for the null. */
2371 char str[CHAR_CLASS_MAX_LENGTH + 1];
2376 /* If pattern is `[[:'. */
2377 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2381 /* Do not do PATFETCH_EITHER() here. We want
2382 to just see if the bytes match particular
2383 strings, and we put them all back if not.
2385 #### May need to be changed once trt tables
2388 if (c == ':' || c == ']' || p == pend
2389 || c1 == CHAR_CLASS_MAX_LENGTH)
2395 /* If isn't a word bracketed by `[:' and:`]':
2396 undo the ending character, the letters, and leave
2397 the leading `:' and `[' (but set bits for them). */
2398 if (c == ':' && *p == ']')
2401 boolean is_alnum = STREQ (str, "alnum");
2402 boolean is_alpha = STREQ (str, "alpha");
2403 boolean is_blank = STREQ (str, "blank");
2404 boolean is_cntrl = STREQ (str, "cntrl");
2405 boolean is_digit = STREQ (str, "digit");
2406 boolean is_graph = STREQ (str, "graph");
2407 boolean is_lower = STREQ (str, "lower");
2408 boolean is_print = STREQ (str, "print");
2409 boolean is_punct = STREQ (str, "punct");
2410 boolean is_space = STREQ (str, "space");
2411 boolean is_upper = STREQ (str, "upper");
2412 boolean is_xdigit = STREQ (str, "xdigit");
2414 if (!IS_CHAR_CLASS (str))
2415 FREE_STACK_RETURN (REG_ECTYPE);
2417 /* Throw away the ] at the end of the character
2421 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2423 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2425 /* This was split into 3 if's to
2426 avoid an arbitrary limit in some compiler. */
2427 if ( (is_alnum && ISALNUM (ch))
2428 || (is_alpha && ISALPHA (ch))
2429 || (is_blank && ISBLANK (ch))
2430 || (is_cntrl && ISCNTRL (ch)))
2431 SET_EITHER_BIT (ch);
2432 if ( (is_digit && ISDIGIT (ch))
2433 || (is_graph && ISGRAPH (ch))
2434 || (is_lower && ISLOWER (ch))
2435 || (is_print && ISPRINT (ch)))
2436 SET_EITHER_BIT (ch);
2437 if ( (is_punct && ISPUNCT (ch))
2438 || (is_space && ISSPACE (ch))
2439 || (is_upper && ISUPPER (ch))
2440 || (is_xdigit && ISXDIGIT (ch)))
2441 SET_EITHER_BIT (ch);
2443 had_char_class = true;
2450 SET_EITHER_BIT ('[');
2451 SET_EITHER_BIT (':');
2452 had_char_class = false;
2457 had_char_class = false;
2463 if (has_extended_chars)
2465 /* We have a range table, not a bit vector. */
2467 unified_range_table_bytes_needed (rtab);
2468 GET_BUFFER_SPACE (bytes_needed);
2469 unified_range_table_copy_data (rtab, b);
2470 b += unified_range_table_bytes_used (b);
2474 /* Discard any (non)matching list bytes that are all 0 at the
2475 end of the map. Decrease the map-length byte too. */
2476 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2484 if (syntax & RE_NO_BK_PARENS)
2491 if (syntax & RE_NO_BK_PARENS)
2498 if (syntax & RE_NEWLINE_ALT)
2505 if (syntax & RE_NO_BK_VBAR)
2512 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2513 goto handle_interval;
2519 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2521 /* Do not translate the character after the \, so that we can
2522 distinguish, e.g., \B from \b, even if we normally would
2523 translate, e.g., B to b. */
2529 if (syntax & RE_NO_BK_PARENS)
2530 goto normal_backslash;
2536 if (!(syntax & RE_NO_SHY_GROUPS)
2538 && TRANSLATE(*p) == TRANSLATE('?'))
2544 case ':': /* shy groups */
2548 /* All others are reserved for future constructs. */
2550 FREE_STACK_RETURN (REG_BADPAT);
2559 if (COMPILE_STACK_FULL)
2561 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2562 compile_stack_elt_t);
2563 if (compile_stack.stack == NULL) return REG_ESPACE;
2565 compile_stack.size <<= 1;
2568 /* These are the values to restore when we hit end of this
2569 group. They are all relative offsets, so that if the
2570 whole pattern moves because of realloc, they will still
2572 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2573 COMPILE_STACK_TOP.fixup_alt_jump
2574 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2575 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2576 COMPILE_STACK_TOP.regnum = r;
2578 /* We will eventually replace the 0 with the number of
2579 groups inner to this one. But do not push a
2580 start_memory for groups beyond the last one we can
2581 represent in the compiled pattern. */
2582 if (r <= MAX_REGNUM)
2584 COMPILE_STACK_TOP.inner_group_offset
2585 = b - bufp->buffer + 2;
2586 BUF_PUSH_3 (start_memory, r, 0);
2589 compile_stack.avail++;
2594 /* If we've reached MAX_REGNUM groups, then this open
2595 won't actually generate any code, so we'll have to
2596 clear pending_exact explicitly. */
2603 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2605 if (COMPILE_STACK_EMPTY) {
2606 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2607 goto normal_backslash;
2609 FREE_STACK_RETURN (REG_ERPAREN);
2614 { /* Push a dummy failure point at the end of the
2615 alternative for a possible future
2616 `pop_failure_jump' to pop. See comments at
2617 `push_dummy_failure' in `re_match_2'. */
2618 BUF_PUSH (push_dummy_failure);
2620 /* We allocated space for this jump when we assigned
2621 to `fixup_alt_jump', in the `handle_alt' case below. */
2622 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2625 /* See similar code for backslashed left paren above. */
2626 if (COMPILE_STACK_EMPTY) {
2627 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2630 FREE_STACK_RETURN (REG_ERPAREN);
2633 /* Since we just checked for an empty stack above, this
2634 ``can't happen''. */
2635 assert (compile_stack.avail != 0);
2637 /* We don't just want to restore into `regnum', because
2638 later groups should continue to be numbered higher,
2639 as in `(ab)c(de)' -- the second group is #2. */
2640 regnum_t this_group_regnum;
2642 compile_stack.avail--;
2643 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2645 = COMPILE_STACK_TOP.fixup_alt_jump
2646 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2648 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2649 this_group_regnum = COMPILE_STACK_TOP.regnum;
2650 /* If we've reached MAX_REGNUM groups, then this open
2651 won't actually generate any code, so we'll have to
2652 clear pending_exact explicitly. */
2655 /* We're at the end of the group, so now we know how many
2656 groups were inside this one. */
2657 if (this_group_regnum <= MAX_REGNUM)
2659 unsigned char *inner_group_loc
2660 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2662 *inner_group_loc = regnum - this_group_regnum;
2663 BUF_PUSH_3 (stop_memory, this_group_regnum,
2664 regnum - this_group_regnum);
2670 case '|': /* `\|'. */
2671 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2672 goto normal_backslash;
2674 if (syntax & RE_LIMITED_OPS)
2677 /* Insert before the previous alternative a jump which
2678 jumps to this alternative if the former fails. */
2679 GET_BUFFER_SPACE (3);
2680 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2684 /* The alternative before this one has a jump after it
2685 which gets executed if it gets matched. Adjust that
2686 jump so it will jump to this alternative's analogous
2687 jump (put in below, which in turn will jump to the next
2688 (if any) alternative's such jump, etc.). The last such
2689 jump jumps to the correct final destination. A picture:
2695 If we are at `b', then fixup_alt_jump right now points to a
2696 three-byte space after `a'. We'll put in the jump, set
2697 fixup_alt_jump to right after `b', and leave behind three
2698 bytes which we'll fill in when we get to after `c'. */
2701 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2703 /* Mark and leave space for a jump after this alternative,
2704 to be filled in later either by next alternative or
2705 when know we're at the end of a series of alternatives. */
2707 GET_BUFFER_SPACE (3);
2716 /* If \{ is a literal. */
2717 if (!(syntax & RE_INTERVALS)
2718 /* If we're at `\{' and it's not the open-interval
2720 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2721 || (p - 2 == pattern && p == pend))
2722 goto normal_backslash;
2726 /* If got here, then the syntax allows intervals. */
2728 /* At least (most) this many matches must be made. */
2729 int lower_bound = -1, upper_bound = -1;
2731 beg_interval = p - 1;
2735 if (syntax & RE_NO_BK_BRACES)
2736 goto unfetch_interval;
2738 FREE_STACK_RETURN (REG_EBRACE);
2741 GET_UNSIGNED_NUMBER (lower_bound);
2745 GET_UNSIGNED_NUMBER (upper_bound);
2746 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2749 /* Interval such as `{1}' => match exactly once. */
2750 upper_bound = lower_bound;
2752 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2753 || lower_bound > upper_bound)
2755 if (syntax & RE_NO_BK_BRACES)
2756 goto unfetch_interval;
2758 FREE_STACK_RETURN (REG_BADBR);
2761 if (!(syntax & RE_NO_BK_BRACES))
2763 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2770 if (syntax & RE_NO_BK_BRACES)
2771 goto unfetch_interval;
2773 FREE_STACK_RETURN (REG_BADBR);
2776 /* We just parsed a valid interval. */
2778 /* If it's invalid to have no preceding re. */
2781 if (syntax & RE_CONTEXT_INVALID_OPS)
2782 FREE_STACK_RETURN (REG_BADRPT);
2783 else if (syntax & RE_CONTEXT_INDEP_OPS)
2786 goto unfetch_interval;
2789 /* If the upper bound is zero, don't want to succeed at
2790 all; jump from `laststart' to `b + 3', which will be
2791 the end of the buffer after we insert the jump. */
2792 if (upper_bound == 0)
2794 GET_BUFFER_SPACE (3);
2795 INSERT_JUMP (jump, laststart, b + 3);
2799 /* Otherwise, we have a nontrivial interval. When
2800 we're all done, the pattern will look like:
2801 set_number_at <jump count> <upper bound>
2802 set_number_at <succeed_n count> <lower bound>
2803 succeed_n <after jump addr> <succeed_n count>
2805 jump_n <succeed_n addr> <jump count>
2806 (The upper bound and `jump_n' are omitted if
2807 `upper_bound' is 1, though.) */
2809 { /* If the upper bound is > 1, we need to insert
2810 more at the end of the loop. */
2811 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2813 GET_BUFFER_SPACE (nbytes);
2815 /* Initialize lower bound of the `succeed_n', even
2816 though it will be set during matching by its
2817 attendant `set_number_at' (inserted next),
2818 because `re_compile_fastmap' needs to know.
2819 Jump to the `jump_n' we might insert below. */
2820 INSERT_JUMP2 (succeed_n, laststart,
2821 b + 5 + (upper_bound > 1) * 5,
2825 /* Code to initialize the lower bound. Insert
2826 before the `succeed_n'. The `5' is the last two
2827 bytes of this `set_number_at', plus 3 bytes of
2828 the following `succeed_n'. */
2829 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2832 if (upper_bound > 1)
2833 { /* More than one repetition is allowed, so
2834 append a backward jump to the `succeed_n'
2835 that starts this interval.
2837 When we've reached this during matching,
2838 we'll have matched the interval once, so
2839 jump back only `upper_bound - 1' times. */
2840 STORE_JUMP2 (jump_n, b, laststart + 5,
2844 /* The location we want to set is the second
2845 parameter of the `jump_n'; that is `b-2' as
2846 an absolute address. `laststart' will be
2847 the `set_number_at' we're about to insert;
2848 `laststart+3' the number to set, the source
2849 for the relative address. But we are
2850 inserting into the middle of the pattern --
2851 so everything is getting moved up by 5.
2852 Conclusion: (b - 2) - (laststart + 3) + 5,
2853 i.e., b - laststart.
2855 We insert this at the beginning of the loop
2856 so that if we fail during matching, we'll
2857 reinitialize the bounds. */
2858 insert_op2 (set_number_at, laststart, b - laststart,
2859 upper_bound - 1, b);
2864 beg_interval = NULL;
2869 /* If an invalid interval, match the characters as literals. */
2870 assert (beg_interval);
2872 beg_interval = NULL;
2874 /* normal_char and normal_backslash need `c'. */
2877 if (!(syntax & RE_NO_BK_BRACES))
2879 if (p > pattern && p[-1] == '\\')
2880 goto normal_backslash;
2885 /* There is no way to specify the before_dot and after_dot
2886 operators. rms says this is ok. --karl */
2894 /* XEmacs addition */
2895 if (c >= 0x80 || syntax_spec_code[c] == 0377)
2896 FREE_STACK_RETURN (REG_ESYNTAX);
2897 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2903 /* XEmacs addition */
2904 if (c >= 0x80 || syntax_spec_code[c] == 0377)
2905 FREE_STACK_RETURN (REG_ESYNTAX);
2906 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2910 /* 97.2.17 jhod merged in to XEmacs from mule-2.3 */
2914 if (c < 32 || c > 127)
2915 FREE_STACK_RETURN (REG_ECATEGORY);
2916 BUF_PUSH_2 (categoryspec, c);
2922 if (c < 32 || c > 127)
2923 FREE_STACK_RETURN (REG_ECATEGORY);
2924 BUF_PUSH_2 (notcategoryspec, c);
2926 /* end of category patch */
2933 BUF_PUSH (wordchar);
2939 BUF_PUSH (notwordchar);
2952 BUF_PUSH (wordbound);
2956 BUF_PUSH (notwordbound);
2967 case '1': case '2': case '3': case '4': case '5':
2968 case '6': case '7': case '8': case '9':
2969 if (syntax & RE_NO_BK_REFS)
2975 FREE_STACK_RETURN (REG_ESUBREG);
2977 /* Can't back reference to a subexpression if inside of it. */
2978 if (group_in_compile_stack (compile_stack, c1))
2982 BUF_PUSH_2 (duplicate, c1);
2988 if (syntax & RE_BK_PLUS_QM)
2991 goto normal_backslash;
2995 /* You might think it would be useful for \ to mean
2996 not to translate; but if we don't translate it,
2997 it will never match anything. */
3005 /* Expects the character in `c'. */
3006 /* `p' points to the location after where `c' came from. */
3009 /* XEmacs: modifications here for Mule. */
3010 /* `q' points to the beginning of the next char. */
3011 CONST char *q = p - 1;
3014 /* If no exactn currently being built. */
3017 /* If last exactn not at current position. */
3018 || pending_exact + *pending_exact + 1 != b
3020 /* We have only one byte following the exactn for the count. */
3021 || ((unsigned int) (*pending_exact + (q - p)) >=
3022 ((unsigned int) (1 << BYTEWIDTH) - 1))
3024 /* If followed by a repetition operator. */
3025 || *q == '*' || *q == '^'
3026 || ((syntax & RE_BK_PLUS_QM)
3027 ? *q == '\\' && (q[1] == '+' || q[1] == '?')
3028 : (*q == '+' || *q == '?'))
3029 || ((syntax & RE_INTERVALS)
3030 && ((syntax & RE_NO_BK_BRACES)
3032 : (q[0] == '\\' && q[1] == '{'))))
3034 /* Start building a new exactn. */
3038 BUF_PUSH_2 (exactn, 0);
3039 pending_exact = b - 1;
3054 } /* while p != pend */
3057 /* Through the pattern now. */
3060 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3062 if (!COMPILE_STACK_EMPTY)
3063 FREE_STACK_RETURN (REG_EPAREN);
3065 /* If we don't want backtracking, force success
3066 the first time we reach the end of the compiled pattern. */
3067 if (syntax & RE_NO_POSIX_BACKTRACKING)
3070 free (compile_stack.stack);
3072 /* We have succeeded; set the length of the buffer. */
3073 bufp->used = b - bufp->buffer;
3078 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3079 print_compiled_pattern (bufp);
3083 #ifndef MATCH_MAY_ALLOCATE
3084 /* Initialize the failure stack to the largest possible stack. This
3085 isn't necessary unless we're trying to avoid calling alloca in
3086 the search and match routines. */
3088 int num_regs = bufp->re_nsub + 1;
3090 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
3091 is strictly greater than re_max_failures, the largest possible stack
3092 is 2 * re_max_failures failure points. */
3093 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
3095 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
3098 if (! fail_stack.stack)
3100 = (fail_stack_elt_t *) xmalloc (fail_stack.size
3101 * sizeof (fail_stack_elt_t));
3104 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
3106 * sizeof (fail_stack_elt_t)));
3107 #else /* not emacs */
3108 if (! fail_stack.stack)
3110 = (fail_stack_elt_t *) malloc (fail_stack.size
3111 * sizeof (fail_stack_elt_t));
3114 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3116 * sizeof (fail_stack_elt_t)));
3117 #endif /* not emacs */
3120 regex_grow_registers (num_regs);
3122 #endif /* not MATCH_MAY_ALLOCATE */
3125 } /* regex_compile */
3127 /* Subroutines for `regex_compile'. */
3129 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3132 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3134 *loc = (unsigned char) op;
3135 STORE_NUMBER (loc + 1, arg);
3139 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3142 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3144 *loc = (unsigned char) op;
3145 STORE_NUMBER (loc + 1, arg1);
3146 STORE_NUMBER (loc + 3, arg2);
3150 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3151 for OP followed by two-byte integer parameter ARG. */
3154 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3156 REGISTER unsigned char *pfrom = end;
3157 REGISTER unsigned char *pto = end + 3;
3159 while (pfrom != loc)
3162 store_op1 (op, loc, arg);
3166 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3169 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2,
3172 REGISTER unsigned char *pfrom = end;
3173 REGISTER unsigned char *pto = end + 5;
3175 while (pfrom != loc)
3178 store_op2 (op, loc, arg1, arg2);
3182 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3183 after an alternative or a begin-subexpression. We assume there is at
3184 least one character before the ^. */
3187 at_begline_loc_p (CONST char *pattern, CONST char *p, reg_syntax_t syntax)
3189 CONST char *prev = p - 2;
3190 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3193 /* After a subexpression? */
3194 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3195 /* After an alternative? */
3196 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3200 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3201 at least one character after the $, i.e., `P < PEND'. */
3204 at_endline_loc_p (CONST char *p, CONST char *pend, int syntax)
3206 CONST char *next = p;
3207 boolean next_backslash = *next == '\\';
3208 CONST char *next_next = p + 1 < pend ? p + 1 : 0;
3211 /* Before a subexpression? */
3212 (syntax & RE_NO_BK_PARENS ? *next == ')'
3213 : next_backslash && next_next && *next_next == ')')
3214 /* Before an alternative? */
3215 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3216 : next_backslash && next_next && *next_next == '|');
3220 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3221 false if it's not. */
3224 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3228 for (this_element = compile_stack.avail - 1;
3231 if (compile_stack.stack[this_element].regnum == regnum)
3238 /* Read the ending character of a range (in a bracket expression) from the
3239 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3240 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3241 Then we set the translation of all bits between the starting and
3242 ending characters (inclusive) in the compiled pattern B.
3244 Return an error code.
3246 We use these short variable names so we can use the same macros as
3247 `regex_compile' itself. */
3249 static reg_errcode_t
3250 compile_range (CONST char **p_ptr, CONST char *pend, char *translate,
3251 reg_syntax_t syntax, unsigned char *b)
3255 CONST char *p = *p_ptr;
3256 int range_start, range_end;
3261 /* Even though the pattern is a signed `char *', we need to fetch
3262 with unsigned char *'s; if the high bit of the pattern character
3263 is set, the range endpoints will be negative if we fetch using a
3266 We also want to fetch the endpoints without translating them; the
3267 appropriate translation is done in the bit-setting loop below. */
3268 /* The SVR4 compiler on the 3B2 had trouble with unsigned CONST char *. */
3269 range_start = ((CONST unsigned char *) p)[-2];
3270 range_end = ((CONST unsigned char *) p)[0];
3272 /* Have to increment the pointer into the pattern string, so the
3273 caller isn't still at the ending character. */
3276 /* If the start is after the end, the range is empty. */
3277 if (range_start > range_end)
3278 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3280 /* Here we see why `this_char' has to be larger than an `unsigned
3281 char' -- the range is inclusive, so if `range_end' == 0xff
3282 (assuming 8-bit characters), we would otherwise go into an infinite
3283 loop, since all characters <= 0xff. */
3284 for (this_char = range_start; this_char <= range_end; this_char++)
3286 SET_LIST_BIT (TRANSLATE (this_char));
3294 static reg_errcode_t
3295 compile_extended_range (CONST char **p_ptr, CONST char *pend, char *translate,
3296 reg_syntax_t syntax, Lisp_Object rtab)
3298 Emchar this_char, range_start, range_end;
3304 p = (CONST Bufbyte *) *p_ptr;
3305 range_end = charptr_emchar (p);
3306 p--; /* back to '-' */
3307 DEC_CHARPTR (p); /* back to start of range */
3308 /* We also want to fetch the endpoints without translating them; the
3309 appropriate translation is done in the bit-setting loop below. */
3310 range_start = charptr_emchar (p);
3311 INC_CHARPTR (*p_ptr);
3313 /* If the start is after the end, the range is empty. */
3314 if (range_start > range_end)
3315 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3317 /* Can't have ranges spanning different charsets, except maybe for
3318 ranges entirely within the first 256 chars. */
3320 if ((range_start >= 0x100 || range_end >= 0x100)
3322 && CHAR_CHARSET_ID (range_start) != CHAR_CHARSET_ID (range_end)
3324 && CHAR_LEADING_BYTE (range_start) != CHAR_LEADING_BYTE (range_end)
3327 return REG_ERANGESPAN;
3329 /* As advertised, translations only work over the 0 - 0x7F range.
3330 Making this kind of stuff work generally is much harder.
3331 Iterating over the whole range like this would be way efficient
3332 if the range encompasses 10,000 chars or something. You'd have
3333 to do something like this:
3337 map over translation table in [range_start, range_end] of
3338 (put the mapped range in a;
3339 put the translation in b)
3340 invert the range in a and truncate to [range_start, range_end]
3341 compute the union of a, b
3342 union the result into rtab
3344 for (this_char = range_start;
3345 this_char <= range_end && this_char < 0x80; this_char++)
3347 SET_RANGETAB_BIT (TRANSLATE (this_char));
3350 if (this_char <= range_end)
3351 put_range_table (rtab, this_char, range_end, Qt);
3358 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3359 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3360 characters can start a string that matches the pattern. This fastmap
3361 is used by re_search to skip quickly over impossible starting points.
3363 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3364 area as BUFP->fastmap.
3366 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3369 Returns 0 if we succeed, -2 if an internal error. */
3372 re_compile_fastmap (struct re_pattern_buffer *bufp)
3375 #ifdef MATCH_MAY_ALLOCATE
3376 fail_stack_type fail_stack;
3379 /* We don't push any register information onto the failure stack. */
3381 REGISTER char *fastmap = bufp->fastmap;
3382 unsigned char *pattern = bufp->buffer;
3383 unsigned long size = bufp->used;
3384 unsigned char *p = pattern;
3385 REGISTER unsigned char *pend = pattern + size;
3388 /* This holds the pointer to the failure stack, when
3389 it is allocated relocatably. */
3390 fail_stack_elt_t *failure_stack_ptr;
3393 /* Assume that each path through the pattern can be null until
3394 proven otherwise. We set this false at the bottom of switch
3395 statement, to which we get only if a particular path doesn't
3396 match the empty string. */
3397 boolean path_can_be_null = true;
3399 /* We aren't doing a `succeed_n' to begin with. */
3400 boolean succeed_n_p = false;
3402 assert (fastmap != NULL && p != NULL);
3405 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3406 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3407 bufp->can_be_null = 0;
3411 if (p == pend || *p == succeed)
3413 /* We have reached the (effective) end of pattern. */
3414 if (!FAIL_STACK_EMPTY ())
3416 bufp->can_be_null |= path_can_be_null;
3418 /* Reset for next path. */
3419 path_can_be_null = true;
3421 p = fail_stack.stack[--fail_stack.avail].pointer;
3429 /* We should never be about to go beyond the end of the pattern. */
3432 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3435 /* I guess the idea here is to simply not bother with a fastmap
3436 if a backreference is used, since it's too hard to figure out
3437 the fastmap for the corresponding group. Setting
3438 `can_be_null' stops `re_search_2' from using the fastmap, so
3439 that is all we do. */
3441 bufp->can_be_null = 1;
3445 /* Following are the cases which match a character. These end
3454 /* XEmacs: Under Mule, these bit vectors will
3455 only contain values for characters below 0x80. */
3456 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3457 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3463 /* Chars beyond end of map must be allowed. */
3465 for (j = *p * BYTEWIDTH; j < 0x80; j++)
3467 /* And all extended characters must be allowed, too. */
3468 for (j = 0x80; j < 0xA0; j++)
3471 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3475 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3476 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3486 nentries = unified_range_table_nentries (p);
3487 for (i = 0; i < nentries; i++)
3489 EMACS_INT first, last;
3490 Lisp_Object dummy_val;
3492 Bufbyte strr[MAX_EMCHAR_LEN];
3494 unified_range_table_get_range (p, i, &first, &last,
3496 for (jj = first; jj <= last && jj < 0x80; jj++)
3498 /* Ranges below 0x100 can span charsets, but there
3499 are only two (Control-1 and Latin-1), and
3500 either first or last has to be in them. */
3501 set_charptr_emchar (strr, first);
3505 set_charptr_emchar (strr, last);
3512 case charset_mule_not:
3517 nentries = unified_range_table_nentries (p);
3518 for (i = 0; i < nentries; i++)
3520 EMACS_INT first, last;
3521 Lisp_Object dummy_val;
3523 int smallest_prev = 0;
3525 unified_range_table_get_range (p, i, &first, &last,
3527 for (jj = smallest_prev; jj < first && jj < 0x80; jj++)
3529 smallest_prev = last + 1;
3530 if (smallest_prev >= 0x80)
3533 /* Calculating which leading bytes are actually allowed
3534 here is rather difficult, so we just punt and allow
3536 for (i = 0x80; i < 0xA0; i++)
3548 for (j = 0; j < (1 << BYTEWIDTH); j++)
3551 (regex_emacs_buffer->mirror_syntax_table), j) == Sword)
3560 goto matchnotsyntax;
3562 for (j = 0; j < (1 << BYTEWIDTH); j++)
3565 (regex_emacs_buffer->mirror_syntax_table), j) != Sword)
3573 int fastmap_newline = fastmap['\n'];
3575 /* `.' matches anything ... */
3577 /* "anything" only includes bytes that can be the
3578 first byte of a character. */
3579 for (j = 0; j < 0xA0; j++)
3582 for (j = 0; j < (1 << BYTEWIDTH); j++)
3586 /* ... except perhaps newline. */
3587 if (!(bufp->syntax & RE_DOT_NEWLINE))
3588 fastmap['\n'] = fastmap_newline;
3590 /* Return if we have already set `can_be_null'; if we have,
3591 then the fastmap is irrelevant. Something's wrong here. */
3592 else if (bufp->can_be_null)
3595 /* Otherwise, have to check alternative paths. */
3604 for (j = 0; j < 0x80; j++)
3607 (regex_emacs_buffer->mirror_syntax_table), j) ==
3608 (enum syntaxcode) k)
3610 for (j = 0x80; j < 0xA0; j++)
3613 if (LEADING_BYTE_PREFIX_P(j))
3614 /* too complicated to calculate this right */
3622 cset = CHARSET_BY_LEADING_BYTE (j);
3623 if (CHARSETP (cset))
3625 if (charset_syntax (regex_emacs_buffer, cset,
3627 == Sword || multi_p)
3635 for (j = 0; j < (1 << BYTEWIDTH); j++)
3638 (regex_emacs_buffer->mirror_syntax_table), j) ==
3639 (enum syntaxcode) k)
3649 for (j = 0; j < 0x80; j++)
3652 (regex_emacs_buffer->mirror_syntax_table), j) !=
3653 (enum syntaxcode) k)
3655 for (j = 0x80; j < 0xA0; j++)
3658 if (LEADING_BYTE_PREFIX_P(j))
3659 /* too complicated to calculate this right */
3667 cset = CHARSET_BY_LEADING_BYTE (j);
3668 if (CHARSETP (cset))
3670 if (charset_syntax (regex_emacs_buffer, cset,
3672 != Sword || multi_p)
3680 for (j = 0; j < (1 << BYTEWIDTH); j++)
3683 (regex_emacs_buffer->mirror_syntax_table), j) !=
3684 (enum syntaxcode) k)
3690 /* 97/2/17 jhod category patch */
3692 case notcategoryspec:
3693 bufp->can_be_null = 1;
3695 /* end if category patch */
3698 /* All cases after this match the empty string. These end with
3706 #endif /* not emacs */
3718 case push_dummy_failure:
3723 case pop_failure_jump:
3724 case maybe_pop_jump:
3727 case dummy_failure_jump:
3728 EXTRACT_NUMBER_AND_INCR (j, p);
3733 /* Jump backward implies we just went through the body of a
3734 loop and matched nothing. Opcode jumped to should be
3735 `on_failure_jump' or `succeed_n'. Just treat it like an
3736 ordinary jump. For a * loop, it has pushed its failure
3737 point already; if so, discard that as redundant. */
3738 if ((re_opcode_t) *p != on_failure_jump
3739 && (re_opcode_t) *p != succeed_n)
3743 EXTRACT_NUMBER_AND_INCR (j, p);
3746 /* If what's on the stack is where we are now, pop it. */
3747 if (!FAIL_STACK_EMPTY ()
3748 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3754 case on_failure_jump:
3755 case on_failure_keep_string_jump:
3756 handle_on_failure_jump:
3757 EXTRACT_NUMBER_AND_INCR (j, p);
3759 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3760 end of the pattern. We don't want to push such a point,
3761 since when we restore it above, entering the switch will
3762 increment `p' past the end of the pattern. We don't need
3763 to push such a point since we obviously won't find any more
3764 fastmap entries beyond `pend'. Such a pattern can match
3765 the null string, though. */
3768 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3770 RESET_FAIL_STACK ();
3775 bufp->can_be_null = 1;
3779 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3780 succeed_n_p = false;
3787 /* Get to the number of times to succeed. */
3790 /* Increment p past the n for when k != 0. */
3791 EXTRACT_NUMBER_AND_INCR (k, p);
3795 succeed_n_p = true; /* Spaghetti code alert. */
3796 goto handle_on_failure_jump;
3813 abort (); /* We have listed all the cases. */
3816 /* Getting here means we have found the possible starting
3817 characters for one path of the pattern -- and that the empty
3818 string does not match. We need not follow this path further.
3819 Instead, look at the next alternative (remembered on the
3820 stack), or quit if no more. The test at the top of the loop
3821 does these things. */
3822 path_can_be_null = false;
3826 /* Set `can_be_null' for the last path (also the first path, if the
3827 pattern is empty). */
3828 bufp->can_be_null |= path_can_be_null;
3831 RESET_FAIL_STACK ();
3833 } /* re_compile_fastmap */
3835 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3836 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3837 this memory for recording register information. STARTS and ENDS
3838 must be allocated using the malloc library routine, and must each
3839 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3841 If NUM_REGS == 0, then subsequent matches should allocate their own
3844 Unless this function is called, the first search or match using
3845 PATTERN_BUFFER will allocate its own register data, without
3846 freeing the old data. */
3849 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs,
3850 unsigned num_regs, regoff_t *starts, regoff_t *ends)
3854 bufp->regs_allocated = REGS_REALLOCATE;
3855 regs->num_regs = num_regs;
3856 regs->start = starts;
3861 bufp->regs_allocated = REGS_UNALLOCATED;
3863 regs->start = regs->end = (regoff_t *) 0;
3867 /* Searching routines. */
3869 /* Like re_search_2, below, but only one string is specified, and
3870 doesn't let you say where to stop matching. */
3873 re_search (struct re_pattern_buffer *bufp, CONST char *string, int size,
3874 int startpos, int range, struct re_registers *regs)
3876 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3881 /* Snarfed from src/lisp.h, needed for compiling [ce]tags. */
3882 # define bytecount_to_charcount(ptr, len) (len)
3883 # define charcount_to_bytecount(ptr, len) (len)
3884 typedef int Charcount;
3887 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3888 virtual concatenation of STRING1 and STRING2, starting first at index
3889 STARTPOS, then at STARTPOS + 1, and so on.
3891 With MULE, STARTPOS is a byte position, not a char position. And the
3892 search will increment STARTPOS by the width of the current leading
3895 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3897 RANGE is how far to scan while trying to match. RANGE = 0 means try
3898 only at STARTPOS; in general, the last start tried is STARTPOS +
3901 With MULE, RANGE is a byte position, not a char position. The last
3902 start tried is the character starting <= STARTPOS + RANGE.
3904 In REGS, return the indices of the virtual concatenation of STRING1
3905 and STRING2 that matched the entire BUFP->buffer and its contained
3908 Do not consider matching one past the index STOP in the virtual
3909 concatenation of STRING1 and STRING2.
3911 We return either the position in the strings at which the match was
3912 found, -1 if no match, or -2 if error (such as failure
3916 re_search_2 (struct re_pattern_buffer *bufp, CONST char *string1,
3917 int size1, CONST char *string2, int size2, int startpos,
3918 int range, struct re_registers *regs, int stop)
3921 REGISTER char *fastmap = bufp->fastmap;
3922 REGISTER char *translate = bufp->translate;
3923 int total_size = size1 + size2;
3924 int endpos = startpos + range;
3925 #ifdef REGEX_BEGLINE_CHECK
3926 int anchored_at_begline = 0;
3928 CONST unsigned char *d;
3931 /* Check for out-of-range STARTPOS. */
3932 if (startpos < 0 || startpos > total_size)
3935 /* Fix up RANGE if it might eventually take us outside
3936 the virtual concatenation of STRING1 and STRING2. */
3938 range = 0 - startpos;
3939 else if (endpos > total_size)
3940 range = total_size - startpos;
3942 /* If the search isn't to be a backwards one, don't waste time in a
3943 search for a pattern that must be anchored. */
3944 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3950 d = ((CONST unsigned char *)
3951 (startpos >= size1 ? string2 - size1 : string1) + startpos);
3952 range = charcount_to_bytecount (d, 1);
3956 /* Update the fastmap now if not correct already. */
3957 if (fastmap && !bufp->fastmap_accurate)
3958 if (re_compile_fastmap (bufp) == -2)
3961 #ifdef REGEX_BEGLINE_CHECK
3965 while (i < bufp->used)
3967 if (bufp->buffer[i] == start_memory ||
3968 bufp->buffer[i] == stop_memory)
3973 anchored_at_begline = i < bufp->used && bufp->buffer[i] == begline;
3977 /* Loop through the string, looking for a place to start matching. */
3980 #ifdef REGEX_BEGLINE_CHECK
3981 /* If the regex is anchored at the beginning of a line (i.e. with a ^),
3982 then we can speed things up by skipping to the next beginning-of-
3984 if (anchored_at_begline && startpos > 0 && startpos != size1 &&
3987 /* whose stupid idea was it anyway to make this
3988 function take two strings to match?? */
3992 if (startpos < size1 && startpos + range >= size1)
3993 lim = range - (size1 - startpos);
3995 d = ((CONST unsigned char *)
3996 (startpos >= size1 ? string2 - size1 : string1) + startpos);
3997 DEC_CHARPTR(d); /* Ok, since startpos != size1. */
3998 d_size = charcount_to_bytecount (d, 1);
4002 while (range > lim && (*d >= 0x80 || translate[*d] != '\n'))
4004 while (range > lim && translate[*d] != '\n')
4007 d += d_size; /* Speedier INC_CHARPTR(d) */
4008 d_size = charcount_to_bytecount (d, 1);
4012 while (range > lim && *d != '\n')
4014 d += d_size; /* Speedier INC_CHARPTR(d) */
4015 d_size = charcount_to_bytecount (d, 1);
4019 startpos += irange - range;
4021 #endif /* REGEX_BEGLINE_CHECK */
4023 /* If a fastmap is supplied, skip quickly over characters that
4024 cannot be the start of a match. If the pattern can match the
4025 null string, however, we don't need to skip characters; we want
4026 the first null string. */
4027 if (fastmap && startpos < total_size && !bufp->can_be_null)
4029 if (range > 0) /* Searching forwards. */
4034 if (startpos < size1 && startpos + range >= size1)
4035 lim = range - (size1 - startpos);
4037 d = ((CONST unsigned char *)
4038 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4040 /* Written out as an if-else to avoid testing `translate'
4043 while (range > lim &&
4047 !fastmap[(unsigned char)translate[*d]])
4049 d_size = charcount_to_bytecount (d, 1);
4051 d += d_size; /* Speedier INC_CHARPTR(d) */
4054 while (range > lim && !fastmap[*d])
4056 d_size = charcount_to_bytecount (d, 1);
4058 d += d_size; /* Speedier INC_CHARPTR(d) */
4061 startpos += irange - range;
4063 else /* Searching backwards. */
4065 unsigned char c = (size1 == 0 || startpos >= size1
4066 ? string2[startpos - size1]
4067 : string1[startpos]);
4069 if (c < 0x80 && !fastmap[(unsigned char) TRANSLATE (c)])
4071 if (!fastmap[(unsigned char) TRANSLATE (c)])
4077 /* If can't match the null string, and that's all we have left, fail. */
4078 if (range >= 0 && startpos == total_size && fastmap
4079 && !bufp->can_be_null)
4082 #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
4083 if (!no_quit_in_re_search)
4086 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4087 startpos, regs, stop);
4088 #ifndef REGEX_MALLOC
4105 d = ((CONST unsigned char *)
4106 (startpos >= size1 ? string2 - size1 : string1) + startpos);
4107 d_size = charcount_to_bytecount (d, 1);
4113 /* Note startpos > size1 not >=. If we are on the
4114 string1/string2 boundary, we want to backup into string1. */
4115 d = ((CONST unsigned char *)
4116 (startpos > size1 ? string2 - size1 : string1) + startpos);
4118 d_size = charcount_to_bytecount (d, 1);
4126 /* Declarations and macros for re_match_2. */
4128 /* This converts PTR, a pointer into one of the search strings `string1'
4129 and `string2' into an offset from the beginning of that string. */
4130 #define POINTER_TO_OFFSET(ptr) \
4131 (FIRST_STRING_P (ptr) \
4132 ? ((regoff_t) ((ptr) - string1)) \
4133 : ((regoff_t) ((ptr) - string2 + size1)))
4135 /* Macros for dealing with the split strings in re_match_2. */
4137 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
4139 /* Call before fetching a character with *d. This switches over to
4140 string2 if necessary. */
4141 #define PREFETCH() \
4144 /* End of string2 => fail. */ \
4145 if (dend == end_match_2) \
4147 /* End of string1 => advance to string2. */ \
4149 dend = end_match_2; \
4153 /* Test if at very beginning or at very end of the virtual concatenation
4154 of `string1' and `string2'. If only one string, it's `string2'. */
4155 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4156 #define AT_STRINGS_END(d) ((d) == end2)
4159 If the given position straddles the string gap, return the equivalent
4160 position that is before or after the gap, respectively; otherwise,
4161 return the same position. */
4162 #define POS_BEFORE_GAP_UNSAFE(d) ((d) == string2 ? end1 : (d))
4163 #define POS_AFTER_GAP_UNSAFE(d) ((d) == end1 ? string2 : (d))
4165 /* Test if CH is a word-constituent character. (XEmacs change) */
4166 #define WORDCHAR_P_UNSAFE(ch) \
4167 (SYNTAX_UNSAFE (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table), \
4170 /* Free everything we malloc. */
4171 #ifdef MATCH_MAY_ALLOCATE
4172 #define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
4173 #define FREE_VARIABLES() \
4175 REGEX_FREE_STACK (fail_stack.stack); \
4176 FREE_VAR (regstart); \
4177 FREE_VAR (regend); \
4178 FREE_VAR (old_regstart); \
4179 FREE_VAR (old_regend); \
4180 FREE_VAR (best_regstart); \
4181 FREE_VAR (best_regend); \
4182 FREE_VAR (reg_info); \
4183 FREE_VAR (reg_dummy); \
4184 FREE_VAR (reg_info_dummy); \
4187 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4188 #endif /* not MATCH_MAY_ALLOCATE */
4190 /* These values must meet several constraints. They must not be valid
4191 register values; since we have a limit of 255 registers (because
4192 we use only one byte in the pattern for the register number), we can
4193 use numbers larger than 255. They must differ by 1, because of
4194 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4195 be larger than the value for the highest register, so we do not try
4196 to actually save any registers when none are active. */
4197 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4198 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4200 /* Matching routines. */
4202 #ifndef emacs /* Emacs never uses this. */
4203 /* re_match is like re_match_2 except it takes only a single string. */
4206 re_match (struct re_pattern_buffer *bufp, CONST char *string, int size,
4207 int pos, struct re_registers *regs)
4209 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4214 #endif /* not emacs */
4217 /* re_match_2 matches the compiled pattern in BUFP against the
4218 (virtual) concatenation of STRING1 and STRING2 (of length SIZE1 and
4219 SIZE2, respectively). We start matching at POS, and stop matching
4222 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4223 store offsets for the substring each group matched in REGS. See the
4224 documentation for exactly how many groups we fill.
4226 We return -1 if no match, -2 if an internal error (such as the
4227 failure stack overflowing). Otherwise, we return the length of the
4228 matched substring. */
4231 re_match_2 (struct re_pattern_buffer *bufp, CONST char *string1,
4232 int size1, CONST char *string2, int size2, int pos,
4233 struct re_registers *regs, int stop)
4235 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
4241 /* This is a separate function so that we can force an alloca cleanup
4244 re_match_2_internal (struct re_pattern_buffer *bufp, CONST char *string1,
4245 int size1, CONST char *string2, int size2, int pos,
4246 struct re_registers *regs, int stop)
4248 /* General temporaries. */
4251 int should_succeed; /* XEmacs change */
4253 /* Just past the end of the corresponding string. */
4254 CONST char *end1, *end2;
4256 /* Pointers into string1 and string2, just past the last characters in
4257 each to consider matching. */
4258 CONST char *end_match_1, *end_match_2;
4260 /* Where we are in the data, and the end of the current string. */
4261 CONST char *d, *dend;
4263 /* Where we are in the pattern, and the end of the pattern. */
4264 unsigned char *p = bufp->buffer;
4265 REGISTER unsigned char *pend = p + bufp->used;
4267 /* Mark the opcode just after a start_memory, so we can test for an
4268 empty subpattern when we get to the stop_memory. */
4269 unsigned char *just_past_start_mem = 0;
4271 /* We use this to map every character in the string. */
4272 char *translate = bufp->translate;
4274 /* Failure point stack. Each place that can handle a failure further
4275 down the line pushes a failure point on this stack. It consists of
4276 restart, regend, and reg_info for all registers corresponding to
4277 the subexpressions we're currently inside, plus the number of such
4278 registers, and, finally, two char *'s. The first char * is where
4279 to resume scanning the pattern; the second one is where to resume
4280 scanning the strings. If the latter is zero, the failure point is
4281 a ``dummy''; if a failure happens and the failure point is a dummy,
4282 it gets discarded and the next one is tried. */
4283 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4284 fail_stack_type fail_stack;
4287 static unsigned failure_id;
4288 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4292 /* This holds the pointer to the failure stack, when
4293 it is allocated relocatably. */
4294 fail_stack_elt_t *failure_stack_ptr;
4297 /* We fill all the registers internally, independent of what we
4298 return, for use in backreferences. The number here includes
4299 an element for register zero. */
4300 unsigned num_regs = bufp->re_nsub + 1;
4302 /* The currently active registers. */
4303 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4304 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4306 /* Information on the contents of registers. These are pointers into
4307 the input strings; they record just what was matched (on this
4308 attempt) by a subexpression part of the pattern, that is, the
4309 regnum-th regstart pointer points to where in the pattern we began
4310 matching and the regnum-th regend points to right after where we
4311 stopped matching the regnum-th subexpression. (The zeroth register
4312 keeps track of what the whole pattern matches.) */
4313 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4314 CONST char **regstart, **regend;
4317 /* If a group that's operated upon by a repetition operator fails to
4318 match anything, then the register for its start will need to be
4319 restored because it will have been set to wherever in the string we
4320 are when we last see its open-group operator. Similarly for a
4322 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4323 CONST char **old_regstart, **old_regend;
4326 /* The is_active field of reg_info helps us keep track of which (possibly
4327 nested) subexpressions we are currently in. The matched_something
4328 field of reg_info[reg_num] helps us tell whether or not we have
4329 matched any of the pattern so far this time through the reg_num-th
4330 subexpression. These two fields get reset each time through any
4331 loop their register is in. */
4332 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4333 register_info_type *reg_info;
4336 /* The following record the register info as found in the above
4337 variables when we find a match better than any we've seen before.
4338 This happens as we backtrack through the failure points, which in
4339 turn happens only if we have not yet matched the entire string. */
4340 unsigned best_regs_set = false;
4341 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4342 CONST char **best_regstart, **best_regend;
4345 /* Logically, this is `best_regend[0]'. But we don't want to have to
4346 allocate space for that if we're not allocating space for anything
4347 else (see below). Also, we never need info about register 0 for
4348 any of the other register vectors, and it seems rather a kludge to
4349 treat `best_regend' differently than the rest. So we keep track of
4350 the end of the best match so far in a separate variable. We
4351 initialize this to NULL so that when we backtrack the first time
4352 and need to test it, it's not garbage. */
4353 CONST char *match_end = NULL;
4355 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4356 int set_regs_matched_done = 0;
4358 /* Used when we pop values we don't care about. */
4359 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4360 CONST char **reg_dummy;
4361 register_info_type *reg_info_dummy;
4365 /* Counts the total number of registers pushed. */
4366 unsigned num_regs_pushed = 0;
4369 /* 1 if this match ends in the same string (string1 or string2)
4370 as the best previous match. */
4373 /* 1 if this match is the best seen so far. */
4374 boolean best_match_p;
4376 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4380 #ifdef MATCH_MAY_ALLOCATE
4381 /* Do not bother to initialize all the register variables if there are
4382 no groups in the pattern, as it takes a fair amount of time. If
4383 there are groups, we include space for register 0 (the whole
4384 pattern), even though we never use it, since it simplifies the
4385 array indexing. We should fix this. */
4388 regstart = REGEX_TALLOC (num_regs, CONST char *);
4389 regend = REGEX_TALLOC (num_regs, CONST char *);
4390 old_regstart = REGEX_TALLOC (num_regs, CONST char *);
4391 old_regend = REGEX_TALLOC (num_regs, CONST char *);
4392 best_regstart = REGEX_TALLOC (num_regs, CONST char *);
4393 best_regend = REGEX_TALLOC (num_regs, CONST char *);
4394 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4395 reg_dummy = REGEX_TALLOC (num_regs, CONST char *);
4396 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4398 if (!(regstart && regend && old_regstart && old_regend && reg_info
4399 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4407 /* We must initialize all our variables to NULL, so that
4408 `FREE_VARIABLES' doesn't try to free them. */
4409 regstart = regend = old_regstart = old_regend = best_regstart
4410 = best_regend = reg_dummy = NULL;
4411 reg_info = reg_info_dummy = (register_info_type *) NULL;
4413 #endif /* MATCH_MAY_ALLOCATE */
4415 /* The starting position is bogus. */
4416 if (pos < 0 || pos > size1 + size2)
4422 /* Initialize subexpression text positions to -1 to mark ones that no
4423 start_memory/stop_memory has been seen for. Also initialize the
4424 register information struct. */
4425 for (mcnt = 1; mcnt < num_regs; mcnt++)
4427 regstart[mcnt] = regend[mcnt]
4428 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4430 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4431 IS_ACTIVE (reg_info[mcnt]) = 0;
4432 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4433 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4436 /* We move `string1' into `string2' if the latter's empty -- but not if
4437 `string1' is null. */
4438 if (size2 == 0 && string1 != NULL)
4445 end1 = string1 + size1;
4446 end2 = string2 + size2;
4448 /* Compute where to stop matching, within the two strings. */
4451 end_match_1 = string1 + stop;
4452 end_match_2 = string2;
4457 end_match_2 = string2 + stop - size1;
4460 /* `p' scans through the pattern as `d' scans through the data.
4461 `dend' is the end of the input string that `d' points within. `d'
4462 is advanced into the following input string whenever necessary, but
4463 this happens before fetching; therefore, at the beginning of the
4464 loop, `d' can be pointing at the end of a string, but it cannot
4466 if (size1 > 0 && pos <= size1)
4473 d = string2 + pos - size1;
4477 DEBUG_PRINT1 ("The compiled pattern is: ");
4478 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4479 DEBUG_PRINT1 ("The string to match is: `");
4480 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4481 DEBUG_PRINT1 ("'\n");
4483 /* This loops over pattern commands. It exits by returning from the
4484 function if the match is complete, or it drops through if the match
4485 fails at this starting point in the input data. */
4488 DEBUG_PRINT2 ("\n0x%lx: ", (long) p);
4489 #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
4490 if (!no_quit_in_re_search)
4495 { /* End of pattern means we might have succeeded. */
4496 DEBUG_PRINT1 ("end of pattern ... ");
4498 /* If we haven't matched the entire string, and we want the
4499 longest match, try backtracking. */
4500 if (d != end_match_2)
4502 same_str_p = (FIRST_STRING_P (match_end)
4503 == MATCHING_IN_FIRST_STRING);
4505 /* AIX compiler got confused when this was combined
4506 with the previous declaration. */
4508 best_match_p = d > match_end;
4510 best_match_p = !MATCHING_IN_FIRST_STRING;
4512 DEBUG_PRINT1 ("backtracking.\n");
4514 if (!FAIL_STACK_EMPTY ())
4515 { /* More failure points to try. */
4517 /* If exceeds best match so far, save it. */
4518 if (!best_regs_set || best_match_p)
4520 best_regs_set = true;
4523 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4525 for (mcnt = 1; mcnt < num_regs; mcnt++)
4527 best_regstart[mcnt] = regstart[mcnt];
4528 best_regend[mcnt] = regend[mcnt];
4534 /* If no failure points, don't restore garbage. And if
4535 last match is real best match, don't restore second
4537 else if (best_regs_set && !best_match_p)
4540 /* Restore best match. It may happen that `dend ==
4541 end_match_1' while the restored d is in string2.
4542 For example, the pattern `x.*y.*z' against the
4543 strings `x-' and `y-z-', if the two strings are
4544 not consecutive in memory. */
4545 DEBUG_PRINT1 ("Restoring best registers.\n");
4548 dend = ((d >= string1 && d <= end1)
4549 ? end_match_1 : end_match_2);
4551 for (mcnt = 1; mcnt < num_regs; mcnt++)
4553 regstart[mcnt] = best_regstart[mcnt];
4554 regend[mcnt] = best_regend[mcnt];
4557 } /* d != end_match_2 */
4560 DEBUG_PRINT1 ("Accepting match.\n");
4562 /* If caller wants register contents data back, do it. */
4563 if (regs && !bufp->no_sub)
4565 /* Have the register data arrays been allocated? */
4566 if (bufp->regs_allocated == REGS_UNALLOCATED)
4567 { /* No. So allocate them with malloc. We need one
4568 extra element beyond `num_regs' for the `-1' marker
4570 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4571 regs->start = TALLOC (regs->num_regs, regoff_t);
4572 regs->end = TALLOC (regs->num_regs, regoff_t);
4573 if (regs->start == NULL || regs->end == NULL)
4578 bufp->regs_allocated = REGS_REALLOCATE;
4580 else if (bufp->regs_allocated == REGS_REALLOCATE)
4581 { /* Yes. If we need more elements than were already
4582 allocated, reallocate them. If we need fewer, just
4584 if (regs->num_regs < num_regs + 1)
4586 regs->num_regs = num_regs + 1;
4587 RETALLOC (regs->start, regs->num_regs, regoff_t);
4588 RETALLOC (regs->end, regs->num_regs, regoff_t);
4589 if (regs->start == NULL || regs->end == NULL)
4598 /* These braces fend off a "empty body in an else-statement"
4599 warning under GCC when assert expands to nothing. */
4600 assert (bufp->regs_allocated == REGS_FIXED);
4603 /* Convert the pointer data in `regstart' and `regend' to
4604 indices. Register zero has to be set differently,
4605 since we haven't kept track of any info for it. */
4606 if (regs->num_regs > 0)
4608 regs->start[0] = pos;
4609 regs->end[0] = (MATCHING_IN_FIRST_STRING
4610 ? ((regoff_t) (d - string1))
4611 : ((regoff_t) (d - string2 + size1)));
4614 /* Go through the first `min (num_regs, regs->num_regs)'
4615 registers, since that is all we initialized. */
4616 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4618 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4619 regs->start[mcnt] = regs->end[mcnt] = -1;
4623 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4625 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4629 /* If the regs structure we return has more elements than
4630 were in the pattern, set the extra elements to -1. If
4631 we (re)allocated the registers, this is the case,
4632 because we always allocate enough to have at least one
4634 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4635 regs->start[mcnt] = regs->end[mcnt] = -1;
4636 } /* regs && !bufp->no_sub */
4638 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4639 nfailure_points_pushed, nfailure_points_popped,
4640 nfailure_points_pushed - nfailure_points_popped);
4641 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4643 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4647 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4653 /* Otherwise match next pattern command. */
4654 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4656 /* Ignore these. Used to ignore the n of succeed_n's which
4657 currently have n == 0. */
4659 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4663 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4666 /* Match the next n pattern characters exactly. The following
4667 byte in the pattern defines n, and the n bytes after that
4668 are the characters to match. */
4671 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4673 /* This is written out as an if-else so we don't waste time
4674 testing `translate' inside the loop. */
4680 if (translate[(unsigned char) *d++] != (char) *p++)
4690 if (*d++ != (char) *p++) goto fail;
4694 SET_REGS_MATCHED ();
4698 /* Match any character except possibly a newline or a null. */
4700 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4704 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4705 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4708 SET_REGS_MATCHED ();
4709 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4710 INC_CHARPTR (d); /* XEmacs change */
4717 REGISTER unsigned char c;
4718 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4720 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4723 c = TRANSLATE (*d); /* The character to match. */
4725 /* Cast to `unsigned' instead of `unsigned char' in case the
4726 bit list is a full 32 bytes long. */
4727 if (c < (unsigned) (*p * BYTEWIDTH)
4728 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4733 if (!not) goto fail;
4735 SET_REGS_MATCHED ();
4736 INC_CHARPTR (d); /* XEmacs change */
4742 case charset_mule_not:
4745 boolean not = (re_opcode_t) *(p - 1) == charset_mule_not;
4747 DEBUG_PRINT2 ("EXECUTING charset_mule%s.\n", not ? "_not" : "");
4750 c = charptr_emchar ((CONST Bufbyte *) d);
4751 c = TRANSLATE_EXTENDED_UNSAFE (c); /* The character to match. */
4753 if (EQ (Qt, unified_range_table_lookup (p, c, Qnil)))
4756 p += unified_range_table_bytes_used (p);
4758 if (!not) goto fail;
4760 SET_REGS_MATCHED ();
4767 /* The beginning of a group is represented by start_memory.
4768 The arguments are the register number in the next byte, and the
4769 number of groups inner to this one in the next. The text
4770 matched within the group is recorded (in the internal
4771 registers data structure) under the register number. */
4773 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4775 /* Find out if this group can match the empty string. */
4776 p1 = p; /* To send to group_match_null_string_p. */
4778 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4779 REG_MATCH_NULL_STRING_P (reg_info[*p])
4780 = group_match_null_string_p (&p1, pend, reg_info);
4782 /* Save the position in the string where we were the last time
4783 we were at this open-group operator in case the group is
4784 operated upon by a repetition operator, e.g., with `(a*)*b'
4785 against `ab'; then we want to ignore where we are now in
4786 the string in case this attempt to match fails. */
4787 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4788 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4790 DEBUG_PRINT2 (" old_regstart: %d\n",
4791 POINTER_TO_OFFSET (old_regstart[*p]));
4794 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4796 IS_ACTIVE (reg_info[*p]) = 1;
4797 MATCHED_SOMETHING (reg_info[*p]) = 0;
4799 /* Clear this whenever we change the register activity status. */
4800 set_regs_matched_done = 0;
4802 /* This is the new highest active register. */
4803 highest_active_reg = *p;
4805 /* If nothing was active before, this is the new lowest active
4807 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4808 lowest_active_reg = *p;
4810 /* Move past the register number and inner group count. */
4812 just_past_start_mem = p;
4817 /* The stop_memory opcode represents the end of a group. Its
4818 arguments are the same as start_memory's: the register
4819 number, and the number of inner groups. */
4821 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4823 /* We need to save the string position the last time we were at
4824 this close-group operator in case the group is operated
4825 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4826 against `aba'; then we want to ignore where we are now in
4827 the string in case this attempt to match fails. */
4828 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4829 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4831 DEBUG_PRINT2 (" old_regend: %d\n",
4832 POINTER_TO_OFFSET (old_regend[*p]));
4835 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4837 /* This register isn't active anymore. */
4838 IS_ACTIVE (reg_info[*p]) = 0;
4840 /* Clear this whenever we change the register activity status. */
4841 set_regs_matched_done = 0;
4843 /* If this was the only register active, nothing is active
4845 if (lowest_active_reg == highest_active_reg)
4847 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4848 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4851 { /* We must scan for the new highest active register, since
4852 it isn't necessarily one less than now: consider
4853 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4854 new highest active register is 1. */
4855 unsigned char r = *p - 1;
4856 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4859 /* If we end up at register zero, that means that we saved
4860 the registers as the result of an `on_failure_jump', not
4861 a `start_memory', and we jumped to past the innermost
4862 `stop_memory'. For example, in ((.)*) we save
4863 registers 1 and 2 as a result of the *, but when we pop
4864 back to the second ), we are at the stop_memory 1.
4865 Thus, nothing is active. */
4868 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4869 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4873 highest_active_reg = r;
4875 /* 98/9/21 jhod: We've also gotta set lowest_active_reg, don't we? */
4877 while (r < highest_active_reg && !IS_ACTIVE(reg_info[r]))
4879 lowest_active_reg = r;
4883 /* If just failed to match something this time around with a
4884 group that's operated on by a repetition operator, try to
4885 force exit from the ``loop'', and restore the register
4886 information for this group that we had before trying this
4888 if ((!MATCHED_SOMETHING (reg_info[*p])
4889 || just_past_start_mem == p - 1)
4892 boolean is_a_jump_n = false;
4896 switch ((re_opcode_t) *p1++)
4900 case pop_failure_jump:
4901 case maybe_pop_jump:
4903 case dummy_failure_jump:
4904 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4914 /* If the next operation is a jump backwards in the pattern
4915 to an on_failure_jump right before the start_memory
4916 corresponding to this stop_memory, exit from the loop
4917 by forcing a failure after pushing on the stack the
4918 on_failure_jump's jump in the pattern, and d. */
4919 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4920 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4922 /* If this group ever matched anything, then restore
4923 what its registers were before trying this last
4924 failed match, e.g., with `(a*)*b' against `ab' for
4925 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4926 against `aba' for regend[3].
4928 Also restore the registers for inner groups for,
4929 e.g., `((a*)(b*))*' against `aba' (register 3 would
4930 otherwise get trashed). */
4932 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4936 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4938 /* Restore this and inner groups' (if any) registers. */
4939 for (r = *p; r < *p + *(p + 1); r++)
4941 regstart[r] = old_regstart[r];
4943 /* xx why this test? */
4944 if (old_regend[r] >= regstart[r])
4945 regend[r] = old_regend[r];
4949 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4950 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4956 /* Move past the register number and the inner group count. */
4961 /* \<digit> has been turned into a `duplicate' command which is
4962 followed by the numeric value of <digit> as the register number. */
4965 REGISTER CONST char *d2, *dend2;
4966 int regno = *p++; /* Get which register to match against. */
4967 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4969 /* Can't back reference a group which we've never matched. */
4970 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4973 /* Where in input to try to start matching. */
4974 d2 = regstart[regno];
4976 /* Where to stop matching; if both the place to start and
4977 the place to stop matching are in the same string, then
4978 set to the place to stop, otherwise, for now have to use
4979 the end of the first string. */
4981 dend2 = ((FIRST_STRING_P (regstart[regno])
4982 == FIRST_STRING_P (regend[regno]))
4983 ? regend[regno] : end_match_1);
4986 /* If necessary, advance to next segment in register
4990 if (dend2 == end_match_2) break;
4991 if (dend2 == regend[regno]) break;
4993 /* End of string1 => advance to string2. */
4995 dend2 = regend[regno];
4997 /* At end of register contents => success */
4998 if (d2 == dend2) break;
5000 /* If necessary, advance to next segment in data. */
5003 /* How many characters left in this segment to match. */
5006 /* Want how many consecutive characters we can match in
5007 one shot, so, if necessary, adjust the count. */
5008 if (mcnt > dend2 - d2)
5011 /* Compare that many; failure if mismatch, else move
5014 ? bcmp_translate ((unsigned char *) d,
5015 (unsigned char *) d2, mcnt, translate)
5016 : memcmp (d, d2, mcnt))
5018 d += mcnt, d2 += mcnt;
5020 /* Do this because we've match some characters. */
5021 SET_REGS_MATCHED ();
5027 /* begline matches the empty string at the beginning of the string
5028 (unless `not_bol' is set in `bufp'), and, if
5029 `newline_anchor' is set, after newlines. */
5031 DEBUG_PRINT1 ("EXECUTING begline.\n");
5033 if (AT_STRINGS_BEG (d))
5035 if (!bufp->not_bol) break;
5037 else if (d[-1] == '\n' && bufp->newline_anchor)
5041 /* In all other cases, we fail. */
5045 /* endline is the dual of begline. */
5047 DEBUG_PRINT1 ("EXECUTING endline.\n");
5049 if (AT_STRINGS_END (d))
5051 if (!bufp->not_eol) break;
5054 /* We have to ``prefetch'' the next character. */
5055 else if ((d == end1 ? *string2 : *d) == '\n'
5056 && bufp->newline_anchor)
5063 /* Match at the very beginning of the data. */
5065 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5066 if (AT_STRINGS_BEG (d))
5071 /* Match at the very end of the data. */
5073 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5074 if (AT_STRINGS_END (d))
5079 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5080 pushes NULL as the value for the string on the stack. Then
5081 `pop_failure_point' will keep the current value for the
5082 string, instead of restoring it. To see why, consider
5083 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5084 then the . fails against the \n. But the next thing we want
5085 to do is match the \n against the \n; if we restored the
5086 string value, we would be back at the foo.
5088 Because this is used only in specific cases, we don't need to
5089 check all the things that `on_failure_jump' does, to make
5090 sure the right things get saved on the stack. Hence we don't
5091 share its code. The only reason to push anything on the
5092 stack at all is that otherwise we would have to change
5093 `anychar's code to do something besides goto fail in this
5094 case; that seems worse than this. */
5095 case on_failure_keep_string_jump:
5096 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
5098 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5099 DEBUG_PRINT3 (" %d (to 0x%lx):\n", mcnt, (long) (p + mcnt));
5101 PUSH_FAILURE_POINT (p + mcnt, (char *) 0, -2);
5105 /* Uses of on_failure_jump:
5107 Each alternative starts with an on_failure_jump that points
5108 to the beginning of the next alternative. Each alternative
5109 except the last ends with a jump that in effect jumps past
5110 the rest of the alternatives. (They really jump to the
5111 ending jump of the following alternative, because tensioning
5112 these jumps is a hassle.)
5114 Repeats start with an on_failure_jump that points past both
5115 the repetition text and either the following jump or
5116 pop_failure_jump back to this on_failure_jump. */
5117 case on_failure_jump:
5119 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
5121 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5122 DEBUG_PRINT3 (" %d (to 0x%lx)", mcnt, (long) (p + mcnt));
5124 /* If this on_failure_jump comes right before a group (i.e.,
5125 the original * applied to a group), save the information
5126 for that group and all inner ones, so that if we fail back
5127 to this point, the group's information will be correct.
5128 For example, in \(a*\)*\1, we need the preceding group,
5129 and in \(\(a*\)b*\)\2, we need the inner group. */
5131 /* We can't use `p' to check ahead because we push
5132 a failure point to `p + mcnt' after we do this. */
5135 /* We need to skip no_op's before we look for the
5136 start_memory in case this on_failure_jump is happening as
5137 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5139 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5142 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5144 /* We have a new highest active register now. This will
5145 get reset at the start_memory we are about to get to,
5146 but we will have saved all the registers relevant to
5147 this repetition op, as described above. */
5148 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5149 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5150 lowest_active_reg = *(p1 + 1);
5153 DEBUG_PRINT1 (":\n");
5154 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5158 /* A smart repeat ends with `maybe_pop_jump'.
5159 We change it to either `pop_failure_jump' or `jump'. */
5160 case maybe_pop_jump:
5161 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5162 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5164 REGISTER unsigned char *p2 = p;
5166 /* Compare the beginning of the repeat with what in the
5167 pattern follows its end. If we can establish that there
5168 is nothing that they would both match, i.e., that we
5169 would have to backtrack because of (as in, e.g., `a*a')
5170 then we can change to pop_failure_jump, because we'll
5171 never have to backtrack.
5173 This is not true in the case of alternatives: in
5174 `(a|ab)*' we do need to backtrack to the `ab' alternative
5175 (e.g., if the string was `ab'). But instead of trying to
5176 detect that here, the alternative has put on a dummy
5177 failure point which is what we will end up popping. */
5179 /* Skip over open/close-group commands.
5180 If what follows this loop is a ...+ construct,
5181 look at what begins its body, since we will have to
5182 match at least one of that. */
5186 && ((re_opcode_t) *p2 == stop_memory
5187 || (re_opcode_t) *p2 == start_memory))
5189 else if (p2 + 6 < pend
5190 && (re_opcode_t) *p2 == dummy_failure_jump)
5197 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5198 to the `maybe_finalize_jump' of this case. Examine what
5201 /* If we're at the end of the pattern, we can change. */
5204 /* Consider what happens when matching ":\(.*\)"
5205 against ":/". I don't really understand this code
5207 p[-3] = (unsigned char) pop_failure_jump;
5209 (" End of pattern: change to `pop_failure_jump'.\n");
5212 else if ((re_opcode_t) *p2 == exactn
5213 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5215 REGISTER unsigned char c
5216 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5218 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
5220 p[-3] = (unsigned char) pop_failure_jump;
5221 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5225 else if ((re_opcode_t) p1[3] == charset
5226 || (re_opcode_t) p1[3] == charset_not)
5228 int not = (re_opcode_t) p1[3] == charset_not;
5230 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
5231 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5234 /* `not' is equal to 1 if c would match, which means
5235 that we can't change to pop_failure_jump. */
5238 p[-3] = (unsigned char) pop_failure_jump;
5239 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5243 else if ((re_opcode_t) *p2 == charset)
5246 REGISTER unsigned char c
5247 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5250 if ((re_opcode_t) p1[3] == exactn
5251 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
5252 && (p2[2 + p1[5] / BYTEWIDTH]
5253 & (1 << (p1[5] % BYTEWIDTH)))))
5255 p[-3] = (unsigned char) pop_failure_jump;
5256 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5260 else if ((re_opcode_t) p1[3] == charset_not)
5263 /* We win if the charset_not inside the loop
5264 lists every character listed in the charset after. */
5265 for (idx = 0; idx < (int) p2[1]; idx++)
5266 if (! (p2[2 + idx] == 0
5267 || (idx < (int) p1[4]
5268 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5273 p[-3] = (unsigned char) pop_failure_jump;
5274 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5277 else if ((re_opcode_t) p1[3] == charset)
5280 /* We win if the charset inside the loop
5281 has no overlap with the one after the loop. */
5283 idx < (int) p2[1] && idx < (int) p1[4];
5285 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5288 if (idx == p2[1] || idx == p1[4])
5290 p[-3] = (unsigned char) pop_failure_jump;
5291 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5296 p -= 2; /* Point at relative address again. */
5297 if ((re_opcode_t) p[-1] != pop_failure_jump)
5299 p[-1] = (unsigned char) jump;
5300 DEBUG_PRINT1 (" Match => jump.\n");
5301 goto unconditional_jump;
5303 /* Note fall through. */
5306 /* The end of a simple repeat has a pop_failure_jump back to
5307 its matching on_failure_jump, where the latter will push a
5308 failure point. The pop_failure_jump takes off failure
5309 points put on by this pop_failure_jump's matching
5310 on_failure_jump; we got through the pattern to here from the
5311 matching on_failure_jump, so didn't fail. */
5312 case pop_failure_jump:
5314 /* We need to pass separate storage for the lowest and
5315 highest registers, even though we don't care about the
5316 actual values. Otherwise, we will restore only one
5317 register from the stack, since lowest will == highest in
5318 `pop_failure_point'. */
5319 unsigned dummy_low_reg, dummy_high_reg;
5320 unsigned char *pdummy;
5321 CONST char *sdummy = NULL;
5323 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5324 POP_FAILURE_POINT (sdummy, pdummy,
5325 dummy_low_reg, dummy_high_reg,
5326 reg_dummy, reg_dummy, reg_info_dummy);
5328 /* Note fall through. */
5331 /* Unconditionally jump (without popping any failure points). */
5334 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5335 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5336 p += mcnt; /* Do the jump. */
5337 DEBUG_PRINT2 ("(to 0x%lx).\n", (long) p);
5341 /* We need this opcode so we can detect where alternatives end
5342 in `group_match_null_string_p' et al. */
5344 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5345 goto unconditional_jump;
5348 /* Normally, the on_failure_jump pushes a failure point, which
5349 then gets popped at pop_failure_jump. We will end up at
5350 pop_failure_jump, also, and with a pattern of, say, `a+', we
5351 are skipping over the on_failure_jump, so we have to push
5352 something meaningless for pop_failure_jump to pop. */
5353 case dummy_failure_jump:
5354 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5355 /* It doesn't matter what we push for the string here. What
5356 the code at `fail' tests is the value for the pattern. */
5357 PUSH_FAILURE_POINT ((unsigned char *) 0, (char *) 0, -2);
5358 goto unconditional_jump;
5361 /* At the end of an alternative, we need to push a dummy failure
5362 point in case we are followed by a `pop_failure_jump', because
5363 we don't want the failure point for the alternative to be
5364 popped. For example, matching `(a|ab)*' against `aab'
5365 requires that we match the `ab' alternative. */
5366 case push_dummy_failure:
5367 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5368 /* See comments just above at `dummy_failure_jump' about the
5370 PUSH_FAILURE_POINT ((unsigned char *) 0, (char *) 0, -2);
5373 /* Have to succeed matching what follows at least n times.
5374 After that, handle like `on_failure_jump'. */
5376 EXTRACT_NUMBER (mcnt, p + 2);
5377 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5380 /* Originally, this is how many times we HAVE to succeed. */
5385 STORE_NUMBER_AND_INCR (p, mcnt);
5386 DEBUG_PRINT3 (" Setting 0x%lx to %d.\n", (long) p, mcnt);
5390 DEBUG_PRINT2 (" Setting two bytes from 0x%lx to no_op.\n",
5392 p[2] = (unsigned char) no_op;
5393 p[3] = (unsigned char) no_op;
5399 EXTRACT_NUMBER (mcnt, p + 2);
5400 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5402 /* Originally, this is how many times we CAN jump. */
5406 STORE_NUMBER (p + 2, mcnt);
5407 goto unconditional_jump;
5409 /* If don't have to jump any more, skip over the rest of command. */
5416 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5418 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5420 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5421 DEBUG_PRINT3 (" Setting 0x%lx to %d.\n", (long) p1, mcnt);
5422 STORE_NUMBER (p1, mcnt);
5427 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5433 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5437 CONST unsigned char *d_before =
5438 (CONST unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5439 CONST unsigned char *d_after =
5440 (CONST unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5441 Emchar emch1, emch2;
5443 DEC_CHARPTR (d_before);
5444 emch1 = charptr_emchar (d_before);
5445 emch2 = charptr_emchar (d_after);
5446 result = (WORDCHAR_P_UNSAFE (emch1) !=
5447 WORDCHAR_P_UNSAFE (emch2));
5449 if (result == should_succeed)
5455 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5457 goto matchwordbound;
5460 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5462 /* XEmacs: this originally read:
5464 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
5468 CONST unsigned char *dtmp =
5469 (CONST unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5470 Emchar emch = charptr_emchar (dtmp);
5471 if (!WORDCHAR_P_UNSAFE (emch))
5473 if (AT_STRINGS_BEG (d))
5475 dtmp = (CONST unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5477 emch = charptr_emchar (dtmp);
5478 if (!WORDCHAR_P_UNSAFE (emch))
5484 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5486 /* XEmacs: this originally read:
5488 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
5489 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
5492 The or condition is incorrect (reversed).
5494 CONST unsigned char *dtmp;
5496 if (AT_STRINGS_BEG (d))
5498 dtmp = (CONST unsigned char *) POS_BEFORE_GAP_UNSAFE (d);
5500 emch = charptr_emchar (dtmp);
5501 if (!WORDCHAR_P_UNSAFE (emch))
5503 if (AT_STRINGS_END (d))
5505 dtmp = (CONST unsigned char *) POS_AFTER_GAP_UNSAFE (d);
5506 emch = charptr_emchar (dtmp);
5507 if (!WORDCHAR_P_UNSAFE (emch))
5514 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5515 if (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d) >=
5516 BUF_PT (regex_emacs_buffer))
5521 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5522 if (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5523 != BUF_PT (regex_emacs_buffer))
5528 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5529 if (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d)
5530 <= BUF_PT (regex_emacs_buffer))
5533 #if 0 /* not emacs19 */
5535 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5536 if (BUF_PTR_BYTE_POS (regex_emacs_buffer, (unsigned char *) d) + 1
5537 != BUF_PT (regex_emacs_buffer))
5540 #endif /* not emacs19 */
5543 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5548 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5558 emch = charptr_emchar ((CONST Bufbyte *) d);
5559 matches = (SYNTAX_UNSAFE
5560 (XCHAR_TABLE (regex_emacs_buffer->mirror_syntax_table),
5561 emch) == (enum syntaxcode) mcnt);
5563 if (matches != should_succeed)
5565 SET_REGS_MATCHED ();
5570 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5572 goto matchnotsyntax;
5575 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5579 goto matchornotsyntax;
5582 /* 97/2/17 jhod Mule category code patch */
5591 emch = charptr_emchar ((CONST Bufbyte *) d);
5593 if (check_category_char(emch, regex_emacs_buffer->category_table,
5594 mcnt, should_succeed))
5596 SET_REGS_MATCHED ();
5600 case notcategoryspec:
5602 goto matchornotcategory;
5603 /* end of category patch */
5605 #else /* not emacs */
5607 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5609 if (!WORDCHAR_P_UNSAFE ((int) (*d)))
5611 SET_REGS_MATCHED ();
5616 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5618 if (!WORDCHAR_P_UNSAFE ((int) (*d)))
5620 SET_REGS_MATCHED ();
5623 #endif /* not emacs */
5628 continue; /* Successfully executed one pattern command; keep going. */
5631 /* We goto here if a matching operation fails. */
5633 if (!FAIL_STACK_EMPTY ())
5634 { /* A restart point is known. Restore to that state. */
5635 DEBUG_PRINT1 ("\nFAIL:\n");
5636 POP_FAILURE_POINT (d, p,
5637 lowest_active_reg, highest_active_reg,
5638 regstart, regend, reg_info);
5640 /* If this failure point is a dummy, try the next one. */
5644 /* If we failed to the end of the pattern, don't examine *p. */
5648 boolean is_a_jump_n = false;
5650 /* If failed to a backwards jump that's part of a repetition
5651 loop, need to pop this failure point and use the next one. */
5652 switch ((re_opcode_t) *p)
5656 case maybe_pop_jump:
5657 case pop_failure_jump:
5660 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5663 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5665 && (re_opcode_t) *p1 == on_failure_jump))
5673 if (d >= string1 && d <= end1)
5677 break; /* Matching at this starting point really fails. */
5681 goto restore_best_regs;
5685 return -1; /* Failure to match. */
5688 /* Subroutine definitions for re_match_2. */
5691 /* We are passed P pointing to a register number after a start_memory.
5693 Return true if the pattern up to the corresponding stop_memory can
5694 match the empty string, and false otherwise.
5696 If we find the matching stop_memory, sets P to point to one past its number.
5697 Otherwise, sets P to an undefined byte less than or equal to END.
5699 We don't handle duplicates properly (yet). */
5702 group_match_null_string_p (unsigned char **p, unsigned char *end,
5703 register_info_type *reg_info)
5706 /* Point to after the args to the start_memory. */
5707 unsigned char *p1 = *p + 2;
5711 /* Skip over opcodes that can match nothing, and return true or
5712 false, as appropriate, when we get to one that can't, or to the
5713 matching stop_memory. */
5715 switch ((re_opcode_t) *p1)
5717 /* Could be either a loop or a series of alternatives. */
5718 case on_failure_jump:
5720 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5722 /* If the next operation is not a jump backwards in the
5727 /* Go through the on_failure_jumps of the alternatives,
5728 seeing if any of the alternatives cannot match nothing.
5729 The last alternative starts with only a jump,
5730 whereas the rest start with on_failure_jump and end
5731 with a jump, e.g., here is the pattern for `a|b|c':
5733 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5734 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5737 So, we have to first go through the first (n-1)
5738 alternatives and then deal with the last one separately. */
5741 /* Deal with the first (n-1) alternatives, which start
5742 with an on_failure_jump (see above) that jumps to right
5743 past a jump_past_alt. */
5745 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5747 /* `mcnt' holds how many bytes long the alternative
5748 is, including the ending `jump_past_alt' and
5751 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5755 /* Move to right after this alternative, including the
5759 /* Break if it's the beginning of an n-th alternative
5760 that doesn't begin with an on_failure_jump. */
5761 if ((re_opcode_t) *p1 != on_failure_jump)
5764 /* Still have to check that it's not an n-th
5765 alternative that starts with an on_failure_jump. */
5767 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5768 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5770 /* Get to the beginning of the n-th alternative. */
5776 /* Deal with the last alternative: go back and get number
5777 of the `jump_past_alt' just before it. `mcnt' contains
5778 the length of the alternative. */
5779 EXTRACT_NUMBER (mcnt, p1 - 2);
5781 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5784 p1 += mcnt; /* Get past the n-th alternative. */
5790 assert (p1[1] == **p);
5796 if (!common_op_match_null_string_p (&p1, end, reg_info))
5799 } /* while p1 < end */
5802 } /* group_match_null_string_p */
5805 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5806 It expects P to be the first byte of a single alternative and END one
5807 byte past the last. The alternative can contain groups. */
5810 alt_match_null_string_p (unsigned char *p, unsigned char *end,
5811 register_info_type *reg_info)
5814 unsigned char *p1 = p;
5818 /* Skip over opcodes that can match nothing, and break when we get
5819 to one that can't. */
5821 switch ((re_opcode_t) *p1)
5824 case on_failure_jump:
5826 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5831 if (!common_op_match_null_string_p (&p1, end, reg_info))
5834 } /* while p1 < end */
5837 } /* alt_match_null_string_p */
5840 /* Deals with the ops common to group_match_null_string_p and
5841 alt_match_null_string_p.
5843 Sets P to one after the op and its arguments, if any. */
5846 common_op_match_null_string_p (unsigned char **p, unsigned char *end,
5847 register_info_type *reg_info)
5852 unsigned char *p1 = *p;
5854 switch ((re_opcode_t) *p1++)
5874 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5875 ret = group_match_null_string_p (&p1, end, reg_info);
5877 /* Have to set this here in case we're checking a group which
5878 contains a group and a back reference to it. */
5880 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5881 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5887 /* If this is an optimized succeed_n for zero times, make the jump. */
5889 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5897 /* Get to the number of times to succeed. */
5899 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5904 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5912 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5920 /* All other opcodes mean we cannot match the empty string. */
5926 } /* common_op_match_null_string_p */
5929 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5930 bytes; nonzero otherwise. */
5933 bcmp_translate (CONST unsigned char *s1, CONST unsigned char *s2,
5934 REGISTER int len, char *translate)
5936 REGISTER CONST unsigned char *p1 = s1, *p2 = s2;
5939 if (translate[*p1++] != translate[*p2++]) return 1;
5945 /* Entry points for GNU code. */
5947 /* re_compile_pattern is the GNU regular expression compiler: it
5948 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5949 Returns 0 if the pattern was valid, otherwise an error string.
5951 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5952 are set in BUFP on entry.
5954 We call regex_compile to do the actual compilation. */
5957 re_compile_pattern (CONST char *pattern, int length,
5958 struct re_pattern_buffer *bufp)
5962 /* GNU code is written to assume at least RE_NREGS registers will be set
5963 (and at least one extra will be -1). */
5964 bufp->regs_allocated = REGS_UNALLOCATED;
5966 /* And GNU code determines whether or not to get register information
5967 by passing null for the REGS argument to re_match, etc., not by
5971 /* Match anchors at newline. */
5972 bufp->newline_anchor = 1;
5974 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5978 return gettext (re_error_msgid[(int) ret]);
5981 /* Entry points compatible with 4.2 BSD regex library. We don't define
5982 them unless specifically requested. */
5984 #ifdef _REGEX_RE_COMP
5986 /* BSD has one and only one pattern buffer. */
5987 static struct re_pattern_buffer re_comp_buf;
5990 re_comp (CONST char *s)
5996 if (!re_comp_buf.buffer)
5997 return gettext ("No previous regular expression");
6001 if (!re_comp_buf.buffer)
6003 re_comp_buf.buffer = (unsigned char *) malloc (200);
6004 if (re_comp_buf.buffer == NULL)
6005 return gettext (re_error_msgid[(int) REG_ESPACE]);
6006 re_comp_buf.allocated = 200;
6008 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6009 if (re_comp_buf.fastmap == NULL)
6010 return gettext (re_error_msgid[(int) REG_ESPACE]);
6013 /* Since `re_exec' always passes NULL for the `regs' argument, we
6014 don't need to initialize the pattern buffer fields which affect it. */
6016 /* Match anchors at newlines. */
6017 re_comp_buf.newline_anchor = 1;
6019 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6024 /* Yes, we're discarding `CONST' here if !HAVE_LIBINTL. */
6025 return (char *) gettext (re_error_msgid[(int) ret]);
6030 re_exec (CONST char *s)
6032 CONST int len = strlen (s);
6034 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6036 #endif /* _REGEX_RE_COMP */
6038 /* POSIX.2 functions. Don't define these for Emacs. */
6042 /* regcomp takes a regular expression as a string and compiles it.
6044 PREG is a regex_t *. We do not expect any fields to be initialized,
6045 since POSIX says we shouldn't. Thus, we set
6047 `buffer' to the compiled pattern;
6048 `used' to the length of the compiled pattern;
6049 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6050 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6051 RE_SYNTAX_POSIX_BASIC;
6052 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6053 `fastmap' and `fastmap_accurate' to zero;
6054 `re_nsub' to the number of subexpressions in PATTERN.
6056 PATTERN is the address of the pattern string.
6058 CFLAGS is a series of bits which affect compilation.
6060 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6061 use POSIX basic syntax.
6063 If REG_NEWLINE is set, then . and [^...] don't match newline.
6064 Also, regexec will try a match beginning after every newline.
6066 If REG_ICASE is set, then we considers upper- and lowercase
6067 versions of letters to be equivalent when matching.
6069 If REG_NOSUB is set, then when PREG is passed to regexec, that
6070 routine will report only success or failure, and nothing about the
6073 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6074 the return codes and their meanings.) */
6077 regcomp (regex_t *preg, CONST char *pattern, int cflags)
6081 = (cflags & REG_EXTENDED) ?
6082 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6084 /* regex_compile will allocate the space for the compiled pattern. */
6086 preg->allocated = 0;
6089 /* Don't bother to use a fastmap when searching. This simplifies the
6090 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6091 characters after newlines into the fastmap. This way, we just try
6095 if (cflags & REG_ICASE)
6099 preg->translate = (char *) malloc (CHAR_SET_SIZE);
6100 if (preg->translate == NULL)
6101 return (int) REG_ESPACE;
6103 /* Map uppercase characters to corresponding lowercase ones. */
6104 for (i = 0; i < CHAR_SET_SIZE; i++)
6105 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6108 preg->translate = NULL;
6110 /* If REG_NEWLINE is set, newlines are treated differently. */
6111 if (cflags & REG_NEWLINE)
6112 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6113 syntax &= ~RE_DOT_NEWLINE;
6114 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6115 /* It also changes the matching behavior. */
6116 preg->newline_anchor = 1;
6119 preg->newline_anchor = 0;
6121 preg->no_sub = !!(cflags & REG_NOSUB);
6123 /* POSIX says a null character in the pattern terminates it, so we
6124 can use strlen here in compiling the pattern. */
6125 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
6127 /* POSIX doesn't distinguish between an unmatched open-group and an
6128 unmatched close-group: both are REG_EPAREN. */
6129 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6135 /* regexec searches for a given pattern, specified by PREG, in the
6138 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6139 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6140 least NMATCH elements, and we set them to the offsets of the
6141 corresponding matched substrings.
6143 EFLAGS specifies `execution flags' which affect matching: if
6144 REG_NOTBOL is set, then ^ does not match at the beginning of the
6145 string; if REG_NOTEOL is set, then $ does not match at the end.
6147 We return 0 if we find a match and REG_NOMATCH if not. */
6150 regexec (CONST regex_t *preg, CONST char *string, size_t nmatch,
6151 regmatch_t pmatch[], int eflags)
6154 struct re_registers regs;
6155 regex_t private_preg;
6156 int len = strlen (string);
6157 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6159 private_preg = *preg;
6161 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6162 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6164 /* The user has told us exactly how many registers to return
6165 information about, via `nmatch'. We have to pass that on to the
6166 matching routines. */
6167 private_preg.regs_allocated = REGS_FIXED;
6171 regs.num_regs = nmatch;
6172 regs.start = TALLOC (nmatch, regoff_t);
6173 regs.end = TALLOC (nmatch, regoff_t);
6174 if (regs.start == NULL || regs.end == NULL)
6175 return (int) REG_NOMATCH;
6178 /* Perform the searching operation. */
6179 ret = re_search (&private_preg, string, len,
6180 /* start: */ 0, /* range: */ len,
6181 want_reg_info ? ®s : (struct re_registers *) 0);
6183 /* Copy the register information to the POSIX structure. */
6190 for (r = 0; r < nmatch; r++)
6192 pmatch[r].rm_so = regs.start[r];
6193 pmatch[r].rm_eo = regs.end[r];
6197 /* If we needed the temporary register info, free the space now. */
6202 /* We want zero return to mean success, unlike `re_search'. */
6203 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6207 /* Returns a message corresponding to an error code, ERRCODE, returned
6208 from either regcomp or regexec. We don't use PREG here. */
6211 regerror (int errcode, CONST regex_t *preg, char *errbuf, size_t errbuf_size)
6217 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6218 /* Only error codes returned by the rest of the code should be passed
6219 to this routine. If we are given anything else, or if other regex
6220 code generates an invalid error code, then the program has a bug.
6221 Dump core so we can fix it. */
6224 msg = gettext (re_error_msgid[errcode]);
6226 msg_size = strlen (msg) + 1; /* Includes the null. */
6228 if (errbuf_size != 0)
6230 if (msg_size > errbuf_size)
6232 strncpy (errbuf, msg, errbuf_size - 1);
6233 errbuf[errbuf_size - 1] = 0;
6236 strcpy (errbuf, msg);
6243 /* Free dynamically allocated space used by PREG. */
6246 regfree (regex_t *preg)
6248 if (preg->buffer != NULL)
6249 free (preg->buffer);
6250 preg->buffer = NULL;
6252 preg->allocated = 0;
6255 if (preg->fastmap != NULL)
6256 free (preg->fastmap);
6257 preg->fastmap = NULL;
6258 preg->fastmap_accurate = 0;
6260 if (preg->translate != NULL)
6261 free (preg->translate);
6262 preg->translate = NULL;
6265 #endif /* not emacs */
6269 make-backup-files: t
6271 trim-versions-without-asking: nil