1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P10003.2/D11.2, except for
3 internationalization features.)
5 Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
30 /* Converts the pointer to the char to BEG-based offset from the start. */
31 #define PTR_TO_OFFSET(d) \
32 POS_AS_IN_BUFFER (MATCHING_IN_FIRST_STRING \
33 ? (d) - string1 : (d) - (string2 - size1))
34 #define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
40 /* We need this for `regex.h', and perhaps for the Emacs include files. */
41 #include <sys/types.h>
43 /* This is for other GNU distributions with internationalized messages. */
44 #if HAVE_LIBINTL_H || defined (_LIBC)
47 # define gettext(msgid) (msgid)
51 /* This define is so xgettext can find the internationalizable
53 #define gettext_noop(String) String
56 /* The `emacs' switch turns on certain matching commands
57 that make sense only in Emacs. */
63 /* Make syntax table lookup grant data in gl_state. */
64 #define SYNTAX_ENTRY_VIA_PROPERTY
70 #define malloc xmalloc
71 #define realloc xrealloc
76 /* If we are not linking with Emacs proper,
77 we can't use the relocating allocator
78 even if config.h says that we can. */
81 #if defined (STDC_HEADERS) || defined (_LIBC)
88 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
89 If nothing else has been done, use the method below. */
90 #ifdef INHIBIT_STRING_HEADER
91 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
92 #if !defined (bzero) && !defined (bcopy)
93 #undef INHIBIT_STRING_HEADER
98 /* This is the normal way of making sure we have a bcopy and a bzero.
99 This is used in most programs--a few other programs avoid this
100 by defining INHIBIT_STRING_HEADER. */
101 #ifndef INHIBIT_STRING_HEADER
102 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
105 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
108 #define bcopy(s, d, n) memcpy ((d), (s), (n))
111 #define bzero(s, n) memset ((s), 0, (n))
118 /* Define the syntax stuff for \<, \>, etc. */
120 /* This must be nonzero for the wordchar and notwordchar pattern
121 commands in re_match_2. */
126 #ifdef SWITCH_ENUM_BUG
127 #define SWITCH_ENUM_CAST(x) ((int)(x))
129 #define SWITCH_ENUM_CAST(x) (x)
134 extern char *re_syntax_table;
136 #else /* not SYNTAX_TABLE */
138 /* How many characters in the character set. */
139 #define CHAR_SET_SIZE 256
141 static char re_syntax_table[CHAR_SET_SIZE];
152 bzero (re_syntax_table, sizeof re_syntax_table);
154 for (c = 'a'; c <= 'z'; c++)
155 re_syntax_table[c] = Sword;
157 for (c = 'A'; c <= 'Z'; c++)
158 re_syntax_table[c] = Sword;
160 for (c = '0'; c <= '9'; c++)
161 re_syntax_table[c] = Sword;
163 re_syntax_table['_'] = Sword;
168 #endif /* not SYNTAX_TABLE */
170 #define SYNTAX(c) re_syntax_table[c]
172 /* Dummy macros for non-Emacs environments. */
173 #define BASE_LEADING_CODE_P(c) (0)
174 #define WORD_BOUNDARY_P(c1, c2) (0)
175 #define CHAR_HEAD_P(p) (1)
176 #define SINGLE_BYTE_CHAR_P(c) (1)
177 #define SAME_CHARSET_P(c1, c2) (1)
178 #define MULTIBYTE_FORM_LENGTH(p, s) (1)
179 #define STRING_CHAR(p, s) (*(p))
180 #define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
181 #define GET_CHAR_AFTER_2(c, p, str1, end1, str2, end2) \
182 (c = ((p) == (end1) ? *(str2) : *(p)))
183 #define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
184 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
185 #endif /* not emacs */
187 /* Get the interface, including the syntax bits. */
190 /* isalpha etc. are used for the character classes. */
193 /* Jim Meyering writes:
195 "... Some ctype macros are valid only for character codes that
196 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
197 using /bin/cc or gcc but without giving an ansi option). So, all
198 ctype uses should be through macros like ISPRINT... If
199 STDC_HEADERS is defined, then autoconf has verified that the ctype
200 macros don't need to be guarded with references to isascii. ...
201 Defining isascii to 1 should let any compiler worth its salt
202 eliminate the && through constant folding." */
204 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
207 #define ISASCII(c) isascii(c)
211 #define ISBLANK(c) (ISASCII (c) && isblank (c))
213 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
216 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
218 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
221 #define ISPRINT(c) (ISASCII (c) && isprint (c))
222 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
223 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
224 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
225 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
226 #define ISLOWER(c) (ISASCII (c) && islower (c))
227 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
228 #define ISSPACE(c) (ISASCII (c) && isspace (c))
229 #define ISUPPER(c) (ISASCII (c) && isupper (c))
230 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
233 #define NULL (void *)0
236 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
237 since ours (we hope) works properly with all combinations of
238 machines, compilers, `char' and `unsigned char' argument types.
239 (Per Bothner suggested the basic approach.) */
240 #undef SIGN_EXTEND_CHAR
242 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
243 #else /* not __STDC__ */
244 /* As in Harbison and Steele. */
245 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
248 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
249 use `alloca' instead of `malloc'. This is because using malloc in
250 re_search* or re_match* could cause memory leaks when C-g is used in
251 Emacs; also, malloc is slower and causes storage fragmentation. On
252 the other hand, malloc is more portable, and easier to debug.
254 Because we sometimes use alloca, some routines have to be macros,
255 not functions -- `alloca'-allocated space disappears at the end of the
256 function it is called in. */
260 #define REGEX_ALLOCATE malloc
261 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
262 #define REGEX_FREE free
264 #else /* not REGEX_MALLOC */
266 /* Emacs already defines alloca, sometimes. */
269 /* Make alloca work the best possible way. */
271 #define alloca __builtin_alloca
272 #else /* not __GNUC__ */
275 #else /* not __GNUC__ or HAVE_ALLOCA_H */
276 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
277 #ifndef _AIX /* Already did AIX, up at the top. */
279 #endif /* not _AIX */
281 #endif /* not HAVE_ALLOCA_H */
282 #endif /* not __GNUC__ */
284 #endif /* not alloca */
286 #define REGEX_ALLOCATE alloca
288 /* Assumes a `char *destination' variable. */
289 #define REGEX_REALLOCATE(source, osize, nsize) \
290 (destination = (char *) alloca (nsize), \
291 bcopy (source, destination, osize), \
294 /* No need to do anything to free, after alloca. */
295 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
297 #endif /* not REGEX_MALLOC */
299 /* Define how to allocate the failure stack. */
301 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
303 #define REGEX_ALLOCATE_STACK(size) \
304 r_alloc (&failure_stack_ptr, (size))
305 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
306 r_re_alloc (&failure_stack_ptr, (nsize))
307 #define REGEX_FREE_STACK(ptr) \
308 r_alloc_free (&failure_stack_ptr)
310 #else /* not using relocating allocator */
314 #define REGEX_ALLOCATE_STACK malloc
315 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
316 #define REGEX_FREE_STACK free
318 #else /* not REGEX_MALLOC */
320 #define REGEX_ALLOCATE_STACK alloca
322 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
323 REGEX_REALLOCATE (source, osize, nsize)
324 /* No need to explicitly free anything. */
325 #define REGEX_FREE_STACK(arg)
327 #endif /* not REGEX_MALLOC */
328 #endif /* not using relocating allocator */
331 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
332 `string1' or just past its end. This works if PTR is NULL, which is
334 #define FIRST_STRING_P(ptr) \
335 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
337 /* (Re)Allocate N items of type T using malloc, or fail. */
338 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
339 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
340 #define RETALLOC_IF(addr, n, t) \
341 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
342 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
344 #define BYTEWIDTH 8 /* In bits. */
346 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
350 #define MAX(a, b) ((a) > (b) ? (a) : (b))
351 #define MIN(a, b) ((a) < (b) ? (a) : (b))
353 typedef char boolean;
357 static int re_match_2_internal ();
359 /* These are the command codes that appear in compiled regular
360 expressions. Some opcodes are followed by argument bytes. A
361 command code can specify any interpretation whatsoever for its
362 arguments. Zero bytes may appear in the compiled regular expression. */
368 /* Succeed right away--no more backtracking. */
371 /* Followed by one byte giving n, then by n literal bytes. */
374 /* Matches any (more or less) character. */
377 /* Matches any one char belonging to specified set. First
378 following byte is number of bitmap bytes. Then come bytes
379 for a bitmap saying which chars are in. Bits in each byte
380 are ordered low-bit-first. A character is in the set if its
381 bit is 1. A character too large to have a bit in the map is
382 automatically not in the set. */
385 /* Same parameters as charset, but match any character that is
386 not one of those specified. */
389 /* Start remembering the text that is matched, for storing in a
390 register. Followed by one byte with the register number, in
391 the range 0 to one less than the pattern buffer's re_nsub
392 field. Then followed by one byte with the number of groups
393 inner to this one. (This last has to be part of the
394 start_memory only because we need it in the on_failure_jump
398 /* Stop remembering the text that is matched and store it in a
399 memory register. Followed by one byte with the register
400 number, in the range 0 to one less than `re_nsub' in the
401 pattern buffer, and one byte with the number of inner groups,
402 just like `start_memory'. (We need the number of inner
403 groups here because we don't have any easy way of finding the
404 corresponding start_memory when we're at a stop_memory.) */
407 /* Match a duplicate of something remembered. Followed by one
408 byte containing the register number. */
411 /* Fail unless at beginning of line. */
414 /* Fail unless at end of line. */
417 /* Succeeds if at beginning of buffer (if emacs) or at beginning
418 of string to be matched (if not). */
421 /* Analogously, for end of buffer/string. */
424 /* Followed by two byte relative address to which to jump. */
427 /* Same as jump, but marks the end of an alternative. */
430 /* Followed by two-byte relative address of place to resume at
431 in case of failure. */
434 /* Like on_failure_jump, but pushes a placeholder instead of the
435 current string position when executed. */
436 on_failure_keep_string_jump,
438 /* Throw away latest failure point and then jump to following
439 two-byte relative address. */
442 /* Change to pop_failure_jump if know won't have to backtrack to
443 match; otherwise change to jump. This is used to jump
444 back to the beginning of a repeat. If what follows this jump
445 clearly won't match what the repeat does, such that we can be
446 sure that there is no use backtracking out of repetitions
447 already matched, then we change it to a pop_failure_jump.
448 Followed by two-byte address. */
451 /* Jump to following two-byte address, and push a dummy failure
452 point. This failure point will be thrown away if an attempt
453 is made to use it for a failure. A `+' construct makes this
454 before the first repeat. Also used as an intermediary kind
455 of jump when compiling an alternative. */
458 /* Push a dummy failure point and continue. Used at the end of
462 /* Followed by two-byte relative address and two-byte number n.
463 After matching N times, jump to the address upon failure. */
466 /* Followed by two-byte relative address, and two-byte number n.
467 Jump to the address N times, then fail. */
470 /* Set the following two-byte relative address to the
471 subsequent two-byte number. The address *includes* the two
475 wordchar, /* Matches any word-constituent character. */
476 notwordchar, /* Matches any char that is not a word-constituent. */
478 wordbeg, /* Succeeds if at word beginning. */
479 wordend, /* Succeeds if at word end. */
481 wordbound, /* Succeeds if at a word boundary. */
482 notwordbound /* Succeeds if not at a word boundary. */
485 ,before_dot, /* Succeeds if before point. */
486 at_dot, /* Succeeds if at point. */
487 after_dot, /* Succeeds if after point. */
489 /* Matches any character whose syntax is specified. Followed by
490 a byte which contains a syntax code, e.g., Sword. */
493 /* Matches any character whose syntax is not that specified. */
496 /* Matches any character whose category-set contains the specified
497 category. The operator is followed by a byte which contains a
498 category code (mnemonic ASCII character). */
501 /* Matches any character whose category-set does not contain the
502 specified category. The operator is followed by a byte which
503 contains the category code (mnemonic ASCII character). */
508 /* Common operations on the compiled pattern. */
510 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
512 #define STORE_NUMBER(destination, number) \
514 (destination)[0] = (number) & 0377; \
515 (destination)[1] = (number) >> 8; \
518 /* Same as STORE_NUMBER, except increment DESTINATION to
519 the byte after where the number is stored. Therefore, DESTINATION
520 must be an lvalue. */
522 #define STORE_NUMBER_AND_INCR(destination, number) \
524 STORE_NUMBER (destination, number); \
525 (destination) += 2; \
528 /* Put into DESTINATION a number stored in two contiguous bytes starting
531 #define EXTRACT_NUMBER(destination, source) \
533 (destination) = *(source) & 0377; \
534 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
539 extract_number (dest, source)
541 unsigned char *source;
543 int temp = SIGN_EXTEND_CHAR (*(source + 1));
544 *dest = *source & 0377;
548 #ifndef EXTRACT_MACROS /* To debug the macros. */
549 #undef EXTRACT_NUMBER
550 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
551 #endif /* not EXTRACT_MACROS */
555 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
556 SOURCE must be an lvalue. */
558 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
560 EXTRACT_NUMBER (destination, source); \
566 extract_number_and_incr (destination, source)
568 unsigned char **source;
570 extract_number (destination, *source);
574 #ifndef EXTRACT_MACROS
575 #undef EXTRACT_NUMBER_AND_INCR
576 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
577 extract_number_and_incr (&dest, &src)
578 #endif /* not EXTRACT_MACROS */
582 /* Store a multibyte character in three contiguous bytes starting
583 DESTINATION, and increment DESTINATION to the byte after where the
584 character is stored. Therefore, DESTINATION must be an lvalue. */
586 #define STORE_CHARACTER_AND_INCR(destination, character) \
588 (destination)[0] = (character) & 0377; \
589 (destination)[1] = ((character) >> 8) & 0377; \
590 (destination)[2] = (character) >> 16; \
591 (destination) += 3; \
594 /* Put into DESTINATION a character stored in three contiguous bytes
595 starting at SOURCE. */
597 #define EXTRACT_CHARACTER(destination, source) \
599 (destination) = ((source)[0] \
600 | ((source)[1] << 8) \
601 | ((source)[2] << 16)); \
605 /* Macros for charset. */
607 /* Size of bitmap of charset P in bytes. P is a start of charset,
608 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
609 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
611 /* Nonzero if charset P has range table. */
612 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
614 /* Return the address of range table of charset P. But not the start
615 of table itself, but the before where the number of ranges is
616 stored. `2 +' means to skip re_opcode_t and size of bitmap. */
617 #define CHARSET_RANGE_TABLE(p) (&(p)[2 + CHARSET_BITMAP_SIZE (p)])
619 /* Test if C is listed in the bitmap of charset P. */
620 #define CHARSET_LOOKUP_BITMAP(p, c) \
621 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
622 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
624 /* Return the address of end of RANGE_TABLE. COUNT is number of
625 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
626 is start of range and end of range. `* 3' is size of each start
628 #define CHARSET_RANGE_TABLE_END(range_table, count) \
629 ((range_table) + (count) * 2 * 3)
631 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
632 COUNT is number of ranges in RANGE_TABLE. */
633 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
636 int range_start, range_end; \
638 unsigned char *range_table_end \
639 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
641 for (p = (range_table); p < range_table_end; p += 2 * 3) \
643 EXTRACT_CHARACTER (range_start, p); \
644 EXTRACT_CHARACTER (range_end, p + 3); \
646 if (range_start <= (c) && (c) <= range_end) \
655 /* Test if C is in range table of CHARSET. The flag NOT is negated if
656 C is listed in it. */
657 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
660 /* Number of ranges in range table. */ \
662 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
664 EXTRACT_NUMBER_AND_INCR (count, range_table); \
665 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
669 /* If DEBUG is defined, Regex prints many voluminous messages about what
670 it is doing (if the variable `debug' is nonzero). If linked with the
671 main program in `iregex.c', you can enter patterns and strings
672 interactively. And if linked with the main program in `main.c' and
673 the other test files, you can run the already-written tests. */
677 /* We use standard I/O for debugging. */
680 /* It is useful to test things that ``must'' be true when debugging. */
683 static int debug = 0;
685 #define DEBUG_STATEMENT(e) e
686 #define DEBUG_PRINT1(x) if (debug) printf (x)
687 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
688 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
689 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
690 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
691 if (debug) print_partial_compiled_pattern (s, e)
692 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
693 if (debug) print_double_string (w, s1, sz1, s2, sz2)
696 /* Print the fastmap in human-readable form. */
699 print_fastmap (fastmap)
702 unsigned was_a_range = 0;
705 while (i < (1 << BYTEWIDTH))
711 while (i < (1 << BYTEWIDTH) && fastmap[i])
727 /* Print a compiled pattern string in human-readable form, starting at
728 the START pointer into it and ending just before the pointer END. */
731 print_partial_compiled_pattern (start, end)
732 unsigned char *start;
736 unsigned char *p = start;
737 unsigned char *pend = end;
745 /* Loop over pattern commands. */
748 printf ("%d:\t", p - start);
750 switch ((re_opcode_t) *p++)
758 printf ("/exactn/%d", mcnt);
769 printf ("/start_memory/%d/%d", mcnt, *p++);
774 printf ("/stop_memory/%d/%d", mcnt, *p++);
778 printf ("/duplicate/%d", *p++);
788 register int c, last = -100;
789 register int in_range = 0;
791 printf ("/charset [%s",
792 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
794 assert (p + *p < pend);
796 for (c = 0; c < 256; c++)
798 && (p[1 + (c/8)] & (1 << (c % 8))))
800 /* Are we starting a range? */
801 if (last + 1 == c && ! in_range)
806 /* Have we broken a range? */
807 else if (last + 1 != c && in_range)
836 case on_failure_jump:
837 extract_number_and_incr (&mcnt, &p);
838 printf ("/on_failure_jump to %d", p + mcnt - start);
841 case on_failure_keep_string_jump:
842 extract_number_and_incr (&mcnt, &p);
843 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
846 case dummy_failure_jump:
847 extract_number_and_incr (&mcnt, &p);
848 printf ("/dummy_failure_jump to %d", p + mcnt - start);
851 case push_dummy_failure:
852 printf ("/push_dummy_failure");
856 extract_number_and_incr (&mcnt, &p);
857 printf ("/maybe_pop_jump to %d", p + mcnt - start);
860 case pop_failure_jump:
861 extract_number_and_incr (&mcnt, &p);
862 printf ("/pop_failure_jump to %d", p + mcnt - start);
866 extract_number_and_incr (&mcnt, &p);
867 printf ("/jump_past_alt to %d", p + mcnt - start);
871 extract_number_and_incr (&mcnt, &p);
872 printf ("/jump to %d", p + mcnt - start);
876 extract_number_and_incr (&mcnt, &p);
877 extract_number_and_incr (&mcnt2, &p);
878 printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
882 extract_number_and_incr (&mcnt, &p);
883 extract_number_and_incr (&mcnt2, &p);
884 printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
888 extract_number_and_incr (&mcnt, &p);
889 extract_number_and_incr (&mcnt2, &p);
890 printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
894 printf ("/wordbound");
898 printf ("/notwordbound");
910 printf ("/before_dot");
918 printf ("/after_dot");
922 printf ("/syntaxspec");
924 printf ("/%d", mcnt);
928 printf ("/notsyntaxspec");
930 printf ("/%d", mcnt);
935 printf ("/wordchar");
939 printf ("/notwordchar");
951 printf ("?%d", *(p-1));
957 printf ("%d:\tend of pattern.\n", p - start);
962 print_compiled_pattern (bufp)
963 struct re_pattern_buffer *bufp;
965 unsigned char *buffer = bufp->buffer;
967 print_partial_compiled_pattern (buffer, buffer + bufp->used);
968 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
970 if (bufp->fastmap_accurate && bufp->fastmap)
972 printf ("fastmap: ");
973 print_fastmap (bufp->fastmap);
976 printf ("re_nsub: %d\t", bufp->re_nsub);
977 printf ("regs_alloc: %d\t", bufp->regs_allocated);
978 printf ("can_be_null: %d\t", bufp->can_be_null);
979 printf ("newline_anchor: %d\n", bufp->newline_anchor);
980 printf ("no_sub: %d\t", bufp->no_sub);
981 printf ("not_bol: %d\t", bufp->not_bol);
982 printf ("not_eol: %d\t", bufp->not_eol);
983 printf ("syntax: %d\n", bufp->syntax);
984 /* Perhaps we should print the translate table? */
989 print_double_string (where, string1, size1, string2, size2)
1002 if (FIRST_STRING_P (where))
1004 for (this_char = where - string1; this_char < size1; this_char++)
1005 putchar (string1[this_char]);
1010 for (this_char = where - string2; this_char < size2; this_char++)
1011 putchar (string2[this_char]);
1015 #else /* not DEBUG */
1020 #define DEBUG_STATEMENT(e)
1021 #define DEBUG_PRINT1(x)
1022 #define DEBUG_PRINT2(x1, x2)
1023 #define DEBUG_PRINT3(x1, x2, x3)
1024 #define DEBUG_PRINT4(x1, x2, x3, x4)
1025 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1026 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1028 #endif /* not DEBUG */
1030 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1031 also be assigned to arbitrarily: each pattern buffer stores its own
1032 syntax, so it can be changed between regex compilations. */
1033 /* This has no initializer because initialized variables in Emacs
1034 become read-only after dumping. */
1035 reg_syntax_t re_syntax_options;
1038 /* Specify the precise syntax of regexps for compilation. This provides
1039 for compatibility for various utilities which historically have
1040 different, incompatible syntaxes.
1042 The argument SYNTAX is a bit mask comprised of the various bits
1043 defined in regex.h. We return the old syntax. */
1046 re_set_syntax (syntax)
1047 reg_syntax_t syntax;
1049 reg_syntax_t ret = re_syntax_options;
1051 re_syntax_options = syntax;
1055 /* This table gives an error message for each of the error codes listed
1056 in regex.h. Obviously the order here has to be same as there.
1057 POSIX doesn't require that we do anything for REG_NOERROR,
1058 but why not be nice? */
1060 static const char *re_error_msgid[] =
1062 gettext_noop ("Success"), /* REG_NOERROR */
1063 gettext_noop ("No match"), /* REG_NOMATCH */
1064 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1065 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1066 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1067 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1068 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1069 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1070 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1071 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1072 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1073 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1074 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1075 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1076 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1077 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1078 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1081 /* Avoiding alloca during matching, to placate r_alloc. */
1083 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1084 searching and matching functions should not call alloca. On some
1085 systems, alloca is implemented in terms of malloc, and if we're
1086 using the relocating allocator routines, then malloc could cause a
1087 relocation, which might (if the strings being searched are in the
1088 ralloc heap) shift the data out from underneath the regexp
1091 Here's another reason to avoid allocation: Emacs
1092 processes input from X in a signal handler; processing X input may
1093 call malloc; if input arrives while a matching routine is calling
1094 malloc, then we're scrod. But Emacs can't just block input while
1095 calling matching routines; then we don't notice interrupts when
1096 they come in. So, Emacs blocks input around all regexp calls
1097 except the matching calls, which it leaves unprotected, in the
1098 faith that they will not malloc. */
1100 /* Normally, this is fine. */
1101 #define MATCH_MAY_ALLOCATE
1103 /* When using GNU C, we are not REALLY using the C alloca, no matter
1104 what config.h may say. So don't take precautions for it. */
1109 /* The match routines may not allocate if (1) they would do it with malloc
1110 and (2) it's not safe for them to use malloc.
1111 Note that if REL_ALLOC is defined, matching would not use malloc for the
1112 failure stack, but we would still use it for the register vectors;
1113 so REL_ALLOC should not affect this. */
1114 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1115 #undef MATCH_MAY_ALLOCATE
1119 /* Failure stack declarations and macros; both re_compile_fastmap and
1120 re_match_2 use a failure stack. These have to be macros because of
1121 REGEX_ALLOCATE_STACK. */
1124 /* Approximate number of failure points for which to initially allocate space
1125 when matching. If this number is exceeded, we allocate more
1126 space, so it is not a hard limit. */
1127 #ifndef INIT_FAILURE_ALLOC
1128 #define INIT_FAILURE_ALLOC 20
1131 /* Roughly the maximum number of failure points on the stack. Would be
1132 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1133 This is a variable only so users of regex can assign to it; we never
1134 change it ourselves. */
1135 #if defined (MATCH_MAY_ALLOCATE)
1136 /* Note that 4400 is enough to cause a crash on Alpha OSF/1,
1137 whose default stack limit is 2mb. In order for a larger
1138 value to work reliably, you have to try to make it accord
1139 with the process stack limit. */
1140 int re_max_failures = 40000;
1142 int re_max_failures = 4000;
1145 union fail_stack_elt
1147 unsigned char *pointer;
1151 typedef union fail_stack_elt fail_stack_elt_t;
1155 fail_stack_elt_t *stack;
1157 unsigned avail; /* Offset of next open position. */
1160 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1161 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1162 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1165 /* Define macros to initialize and free the failure stack.
1166 Do `return -2' if the alloc fails. */
1168 #ifdef MATCH_MAY_ALLOCATE
1169 #define INIT_FAIL_STACK() \
1171 fail_stack.stack = (fail_stack_elt_t *) \
1172 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1173 * sizeof (fail_stack_elt_t)); \
1175 if (fail_stack.stack == NULL) \
1178 fail_stack.size = INIT_FAILURE_ALLOC; \
1179 fail_stack.avail = 0; \
1182 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1184 #define INIT_FAIL_STACK() \
1186 fail_stack.avail = 0; \
1189 #define RESET_FAIL_STACK()
1193 /* Double the size of FAIL_STACK, up to a limit
1194 which allows approximately `re_max_failures' items.
1196 Return 1 if succeeds, and 0 if either ran out of memory
1197 allocating space for it or it was already too large.
1199 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1201 /* Factor to increase the failure stack size by
1202 when we increase it.
1203 This used to be 2, but 2 was too wasteful
1204 because the old discarded stacks added up to as much space
1205 were as ultimate, maximum-size stack. */
1206 #define FAIL_STACK_GROWTH_FACTOR 4
1208 #define GROW_FAIL_STACK(fail_stack) \
1209 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1210 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1212 : ((fail_stack).stack \
1213 = (fail_stack_elt_t *) \
1214 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1215 (fail_stack).size * sizeof (fail_stack_elt_t), \
1216 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1217 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1218 * FAIL_STACK_GROWTH_FACTOR))), \
1220 (fail_stack).stack == NULL \
1222 : ((fail_stack).size \
1223 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1224 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1225 * FAIL_STACK_GROWTH_FACTOR)) \
1226 / sizeof (fail_stack_elt_t)), \
1230 /* Push pointer POINTER on FAIL_STACK.
1231 Return 1 if was able to do so and 0 if ran out of memory allocating
1233 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1234 ((FAIL_STACK_FULL () \
1235 && !GROW_FAIL_STACK (FAIL_STACK)) \
1237 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1240 /* Push a pointer value onto the failure stack.
1241 Assumes the variable `fail_stack'. Probably should only
1242 be called from within `PUSH_FAILURE_POINT'. */
1243 #define PUSH_FAILURE_POINTER(item) \
1244 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1246 /* This pushes an integer-valued item onto the failure stack.
1247 Assumes the variable `fail_stack'. Probably should only
1248 be called from within `PUSH_FAILURE_POINT'. */
1249 #define PUSH_FAILURE_INT(item) \
1250 fail_stack.stack[fail_stack.avail++].integer = (item)
1252 /* Push a fail_stack_elt_t value onto the failure stack.
1253 Assumes the variable `fail_stack'. Probably should only
1254 be called from within `PUSH_FAILURE_POINT'. */
1255 #define PUSH_FAILURE_ELT(item) \
1256 fail_stack.stack[fail_stack.avail++] = (item)
1258 /* These three POP... operations complement the three PUSH... operations.
1259 All assume that `fail_stack' is nonempty. */
1260 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1261 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1262 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1264 /* Used to omit pushing failure point id's when we're not debugging. */
1266 #define DEBUG_PUSH PUSH_FAILURE_INT
1267 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1269 #define DEBUG_PUSH(item)
1270 #define DEBUG_POP(item_addr)
1274 /* Push the information about the state we will need
1275 if we ever fail back to it.
1277 Requires variables fail_stack, regstart, regend, reg_info, and
1278 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1281 Does `return FAILURE_CODE' if runs out of memory. */
1283 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1285 char *destination; \
1286 /* Must be int, so when we don't save any registers, the arithmetic \
1287 of 0 + -1 isn't done as unsigned. */ \
1290 DEBUG_STATEMENT (failure_id++); \
1291 DEBUG_STATEMENT (nfailure_points_pushed++); \
1292 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1293 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1294 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1296 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1297 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1299 /* Ensure we have enough space allocated for what we will push. */ \
1300 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1302 if (!GROW_FAIL_STACK (fail_stack)) \
1303 return failure_code; \
1305 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1306 (fail_stack).size); \
1307 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1310 /* Push the info, starting with the registers. */ \
1311 DEBUG_PRINT1 ("\n"); \
1314 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1317 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1318 DEBUG_STATEMENT (num_regs_pushed++); \
1320 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1321 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1323 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1324 PUSH_FAILURE_POINTER (regend[this_reg]); \
1326 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
1327 DEBUG_PRINT2 (" match_null=%d", \
1328 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1329 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1330 DEBUG_PRINT2 (" matched_something=%d", \
1331 MATCHED_SOMETHING (reg_info[this_reg])); \
1332 DEBUG_PRINT2 (" ever_matched=%d", \
1333 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1334 DEBUG_PRINT1 ("\n"); \
1335 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1338 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1339 PUSH_FAILURE_INT (lowest_active_reg); \
1341 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1342 PUSH_FAILURE_INT (highest_active_reg); \
1344 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
1345 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1346 PUSH_FAILURE_POINTER (pattern_place); \
1348 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
1349 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1351 DEBUG_PRINT1 ("'\n"); \
1352 PUSH_FAILURE_POINTER (string_place); \
1354 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1355 DEBUG_PUSH (failure_id); \
1358 /* This is the number of items that are pushed and popped on the stack
1359 for each register. */
1360 #define NUM_REG_ITEMS 3
1362 /* Individual items aside from the registers. */
1364 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1366 #define NUM_NONREG_ITEMS 4
1369 /* Estimate the size of data pushed by a typical failure stack entry.
1370 An estimate is all we need, because all we use this for
1371 is to choose a limit for how big to make the failure stack. */
1373 #define TYPICAL_FAILURE_SIZE 20
1375 /* This is how many items we actually use for a failure point.
1376 It depends on the regexp. */
1377 #define NUM_FAILURE_ITEMS \
1379 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1383 /* How many items can still be added to the stack without overflowing it. */
1384 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1387 /* Pops what PUSH_FAIL_STACK pushes.
1389 We restore into the parameters, all of which should be lvalues:
1390 STR -- the saved data position.
1391 PAT -- the saved pattern position.
1392 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1393 REGSTART, REGEND -- arrays of string positions.
1394 REG_INFO -- array of information about each subexpression.
1396 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1397 `pend', `string1', `size1', `string2', and `size2'. */
1399 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1401 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
1403 const unsigned char *string_temp; \
1405 assert (!FAIL_STACK_EMPTY ()); \
1407 /* Remove failure points and point to how many regs pushed. */ \
1408 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1409 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1410 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1412 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1414 DEBUG_POP (&failure_id); \
1415 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1417 /* If the saved string location is NULL, it came from an \
1418 on_failure_keep_string_jump opcode, and we want to throw away the \
1419 saved NULL, thus retaining our current position in the string. */ \
1420 string_temp = POP_FAILURE_POINTER (); \
1421 if (string_temp != NULL) \
1422 str = (const char *) string_temp; \
1424 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
1425 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1426 DEBUG_PRINT1 ("'\n"); \
1428 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1429 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
1430 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1432 /* Restore register info. */ \
1433 high_reg = (unsigned) POP_FAILURE_INT (); \
1434 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1436 low_reg = (unsigned) POP_FAILURE_INT (); \
1437 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1440 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1442 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1444 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1445 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
1447 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1448 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1450 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1451 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1455 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1457 reg_info[this_reg].word.integer = 0; \
1458 regend[this_reg] = 0; \
1459 regstart[this_reg] = 0; \
1461 highest_active_reg = high_reg; \
1464 set_regs_matched_done = 0; \
1465 DEBUG_STATEMENT (nfailure_points_popped++); \
1466 } /* POP_FAILURE_POINT */
1470 /* Structure for per-register (a.k.a. per-group) information.
1471 Other register information, such as the
1472 starting and ending positions (which are addresses), and the list of
1473 inner groups (which is a bits list) are maintained in separate
1476 We are making a (strictly speaking) nonportable assumption here: that
1477 the compiler will pack our bit fields into something that fits into
1478 the type of `word', i.e., is something that fits into one item on the
1483 fail_stack_elt_t word;
1486 /* This field is one if this group can match the empty string,
1487 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1488 #define MATCH_NULL_UNSET_VALUE 3
1489 unsigned match_null_string_p : 2;
1490 unsigned is_active : 1;
1491 unsigned matched_something : 1;
1492 unsigned ever_matched_something : 1;
1494 } register_info_type;
1496 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1497 #define IS_ACTIVE(R) ((R).bits.is_active)
1498 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1499 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1502 /* Call this when have matched a real character; it sets `matched' flags
1503 for the subexpressions which we are currently inside. Also records
1504 that those subexprs have matched. */
1505 #define SET_REGS_MATCHED() \
1508 if (!set_regs_matched_done) \
1511 set_regs_matched_done = 1; \
1512 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1514 MATCHED_SOMETHING (reg_info[r]) \
1515 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1522 /* Registers are set to a sentinel when they haven't yet matched. */
1523 static char reg_unset_dummy;
1524 #define REG_UNSET_VALUE (®_unset_dummy)
1525 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1527 /* Subroutine declarations and macros for regex_compile. */
1529 static void store_op1 (), store_op2 ();
1530 static void insert_op1 (), insert_op2 ();
1531 static boolean at_begline_loc_p (), at_endline_loc_p ();
1532 static boolean group_in_compile_stack ();
1533 static reg_errcode_t compile_range ();
1535 /* Fetch the next character in the uncompiled pattern---translating it
1536 if necessary. Also cast from a signed character in the constant
1537 string passed to us by the user to an unsigned char that we can use
1538 as an array index (in, e.g., `translate'). */
1540 #define PATFETCH(c) \
1541 do {if (p == pend) return REG_EEND; \
1542 c = (unsigned char) *p++; \
1543 if (RE_TRANSLATE_P (translate)) c = RE_TRANSLATE (translate, c); \
1547 /* Fetch the next character in the uncompiled pattern, with no
1549 #define PATFETCH_RAW(c) \
1550 do {if (p == pend) return REG_EEND; \
1551 c = (unsigned char) *p++; \
1554 /* Go backwards one character in the pattern. */
1555 #define PATUNFETCH p--
1558 /* If `translate' is non-null, return translate[D], else just D. We
1559 cast the subscript to translate because some data is declared as
1560 `char *', to avoid warnings when a string constant is passed. But
1561 when we use a character as a subscript we must make it unsigned. */
1563 #define TRANSLATE(d) \
1564 (RE_TRANSLATE_P (translate) \
1565 ? (unsigned) RE_TRANSLATE (translate, (unsigned) (d)) : (d))
1569 /* Macros for outputting the compiled pattern into `buffer'. */
1571 /* If the buffer isn't allocated when it comes in, use this. */
1572 #define INIT_BUF_SIZE 32
1574 /* Make sure we have at least N more bytes of space in buffer. */
1575 #define GET_BUFFER_SPACE(n) \
1576 while (b - bufp->buffer + (n) > bufp->allocated) \
1579 /* Make sure we have one more byte of buffer space and then add C to it. */
1580 #define BUF_PUSH(c) \
1582 GET_BUFFER_SPACE (1); \
1583 *b++ = (unsigned char) (c); \
1587 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1588 #define BUF_PUSH_2(c1, c2) \
1590 GET_BUFFER_SPACE (2); \
1591 *b++ = (unsigned char) (c1); \
1592 *b++ = (unsigned char) (c2); \
1596 /* As with BUF_PUSH_2, except for three bytes. */
1597 #define BUF_PUSH_3(c1, c2, c3) \
1599 GET_BUFFER_SPACE (3); \
1600 *b++ = (unsigned char) (c1); \
1601 *b++ = (unsigned char) (c2); \
1602 *b++ = (unsigned char) (c3); \
1606 /* Store a jump with opcode OP at LOC to location TO. We store a
1607 relative address offset by the three bytes the jump itself occupies. */
1608 #define STORE_JUMP(op, loc, to) \
1609 store_op1 (op, loc, (to) - (loc) - 3)
1611 /* Likewise, for a two-argument jump. */
1612 #define STORE_JUMP2(op, loc, to, arg) \
1613 store_op2 (op, loc, (to) - (loc) - 3, arg)
1615 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1616 #define INSERT_JUMP(op, loc, to) \
1617 insert_op1 (op, loc, (to) - (loc) - 3, b)
1619 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1620 #define INSERT_JUMP2(op, loc, to, arg) \
1621 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1624 /* This is not an arbitrary limit: the arguments which represent offsets
1625 into the pattern are two bytes long. So if 2^16 bytes turns out to
1626 be too small, many things would have to change. */
1627 #define MAX_BUF_SIZE (1L << 16)
1630 /* Extend the buffer by twice its current size via realloc and
1631 reset the pointers that pointed into the old block to point to the
1632 correct places in the new one. If extending the buffer results in it
1633 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1634 #define EXTEND_BUFFER() \
1636 unsigned char *old_buffer = bufp->buffer; \
1637 if (bufp->allocated == MAX_BUF_SIZE) \
1639 bufp->allocated <<= 1; \
1640 if (bufp->allocated > MAX_BUF_SIZE) \
1641 bufp->allocated = MAX_BUF_SIZE; \
1642 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1643 if (bufp->buffer == NULL) \
1644 return REG_ESPACE; \
1645 /* If the buffer moved, move all the pointers into it. */ \
1646 if (old_buffer != bufp->buffer) \
1648 b = (b - old_buffer) + bufp->buffer; \
1649 begalt = (begalt - old_buffer) + bufp->buffer; \
1650 if (fixup_alt_jump) \
1651 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1653 laststart = (laststart - old_buffer) + bufp->buffer; \
1654 if (pending_exact) \
1655 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1660 /* Since we have one byte reserved for the register number argument to
1661 {start,stop}_memory, the maximum number of groups we can report
1662 things about is what fits in that byte. */
1663 #define MAX_REGNUM 255
1665 /* But patterns can have more than `MAX_REGNUM' registers. We just
1666 ignore the excess. */
1667 typedef unsigned regnum_t;
1670 /* Macros for the compile stack. */
1672 /* Since offsets can go either forwards or backwards, this type needs to
1673 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1674 typedef int pattern_offset_t;
1678 pattern_offset_t begalt_offset;
1679 pattern_offset_t fixup_alt_jump;
1680 pattern_offset_t inner_group_offset;
1681 pattern_offset_t laststart_offset;
1683 } compile_stack_elt_t;
1688 compile_stack_elt_t *stack;
1690 unsigned avail; /* Offset of next open position. */
1691 } compile_stack_type;
1694 #define INIT_COMPILE_STACK_SIZE 32
1696 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1697 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1699 /* The next available element. */
1700 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1703 /* Structure to manage work area for range table. */
1704 struct range_table_work_area
1706 int *table; /* actual work area. */
1707 int allocated; /* allocated size for work area in bytes. */
1708 int used; /* actually used size in words. */
1711 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1712 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1714 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1716 (work_area).allocated += 16 * sizeof (int); \
1717 if ((work_area).table) \
1719 = (int *) realloc ((work_area).table, (work_area).allocated); \
1722 = (int *) malloc ((work_area).allocated); \
1723 if ((work_area).table == 0) \
1724 FREE_STACK_RETURN (REG_ESPACE); \
1728 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1729 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1731 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1732 (work_area).table[(work_area).used++] = (range_start); \
1733 (work_area).table[(work_area).used++] = (range_end); \
1736 /* Free allocated memory for WORK_AREA. */
1737 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1739 if ((work_area).table) \
1740 free ((work_area).table); \
1743 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0)
1744 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1745 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1748 /* Set the bit for character C in a list. */
1749 #define SET_LIST_BIT(c) \
1750 (b[((unsigned char) (c)) / BYTEWIDTH] \
1751 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1754 /* Get the next unsigned number in the uncompiled pattern. */
1755 #define GET_UNSIGNED_NUMBER(num) \
1759 while (ISDIGIT (c)) \
1763 num = num * 10 + c - '0'; \
1771 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1773 #define IS_CHAR_CLASS(string) \
1774 (STREQ (string, "alpha") || STREQ (string, "upper") \
1775 || STREQ (string, "lower") || STREQ (string, "digit") \
1776 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1777 || STREQ (string, "space") || STREQ (string, "print") \
1778 || STREQ (string, "punct") || STREQ (string, "graph") \
1779 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1781 #ifndef MATCH_MAY_ALLOCATE
1783 /* If we cannot allocate large objects within re_match_2_internal,
1784 we make the fail stack and register vectors global.
1785 The fail stack, we grow to the maximum size when a regexp
1787 The register vectors, we adjust in size each time we
1788 compile a regexp, according to the number of registers it needs. */
1790 static fail_stack_type fail_stack;
1792 /* Size with which the following vectors are currently allocated.
1793 That is so we can make them bigger as needed,
1794 but never make them smaller. */
1795 static int regs_allocated_size;
1797 static const char ** regstart, ** regend;
1798 static const char ** old_regstart, ** old_regend;
1799 static const char **best_regstart, **best_regend;
1800 static register_info_type *reg_info;
1801 static const char **reg_dummy;
1802 static register_info_type *reg_info_dummy;
1804 /* Make the register vectors big enough for NUM_REGS registers,
1805 but don't make them smaller. */
1808 regex_grow_registers (num_regs)
1811 if (num_regs > regs_allocated_size)
1813 RETALLOC_IF (regstart, num_regs, const char *);
1814 RETALLOC_IF (regend, num_regs, const char *);
1815 RETALLOC_IF (old_regstart, num_regs, const char *);
1816 RETALLOC_IF (old_regend, num_regs, const char *);
1817 RETALLOC_IF (best_regstart, num_regs, const char *);
1818 RETALLOC_IF (best_regend, num_regs, const char *);
1819 RETALLOC_IF (reg_info, num_regs, register_info_type);
1820 RETALLOC_IF (reg_dummy, num_regs, const char *);
1821 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1823 regs_allocated_size = num_regs;
1827 #endif /* not MATCH_MAY_ALLOCATE */
1829 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1830 Returns one of error codes defined in `regex.h', or zero for success.
1832 Assumes the `allocated' (and perhaps `buffer') and `translate'
1833 fields are set in BUFP on entry.
1835 If it succeeds, results are put in BUFP (if it returns an error, the
1836 contents of BUFP are undefined):
1837 `buffer' is the compiled pattern;
1838 `syntax' is set to SYNTAX;
1839 `used' is set to the length of the compiled pattern;
1840 `fastmap_accurate' is zero;
1841 `re_nsub' is the number of subexpressions in PATTERN;
1842 `not_bol' and `not_eol' are zero;
1844 The `fastmap' and `newline_anchor' fields are neither
1845 examined nor set. */
1847 /* Return, freeing storage we allocated. */
1848 #define FREE_STACK_RETURN(value) \
1850 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1851 free (compile_stack.stack); \
1855 static reg_errcode_t
1856 regex_compile (pattern, size, syntax, bufp)
1857 const char *pattern;
1859 reg_syntax_t syntax;
1860 struct re_pattern_buffer *bufp;
1862 /* We fetch characters from PATTERN here. Even though PATTERN is
1863 `char *' (i.e., signed), we declare these variables as unsigned, so
1864 they can be reliably used as array indices. */
1865 register unsigned int c, c1;
1867 /* A random temporary spot in PATTERN. */
1870 /* Points to the end of the buffer, where we should append. */
1871 register unsigned char *b;
1873 /* Keeps track of unclosed groups. */
1874 compile_stack_type compile_stack;
1876 /* Points to the current (ending) position in the pattern. */
1877 const char *p = pattern;
1878 const char *pend = pattern + size;
1880 /* How to translate the characters in the pattern. */
1881 RE_TRANSLATE_TYPE translate = bufp->translate;
1883 /* Address of the count-byte of the most recently inserted `exactn'
1884 command. This makes it possible to tell if a new exact-match
1885 character can be added to that command or if the character requires
1886 a new `exactn' command. */
1887 unsigned char *pending_exact = 0;
1889 /* Address of start of the most recently finished expression.
1890 This tells, e.g., postfix * where to find the start of its
1891 operand. Reset at the beginning of groups and alternatives. */
1892 unsigned char *laststart = 0;
1894 /* Address of beginning of regexp, or inside of last group. */
1895 unsigned char *begalt;
1897 /* Place in the uncompiled pattern (i.e., the {) to
1898 which to go back if the interval is invalid. */
1899 const char *beg_interval;
1901 /* Address of the place where a forward jump should go to the end of
1902 the containing expression. Each alternative of an `or' -- except the
1903 last -- ends with a forward jump of this sort. */
1904 unsigned char *fixup_alt_jump = 0;
1906 /* Counts open-groups as they are encountered. Remembered for the
1907 matching close-group on the compile stack, so the same register
1908 number is put in the stop_memory as the start_memory. */
1909 regnum_t regnum = 0;
1911 /* Work area for range table of charset. */
1912 struct range_table_work_area range_table_work;
1915 DEBUG_PRINT1 ("\nCompiling pattern: ");
1918 unsigned debug_count;
1920 for (debug_count = 0; debug_count < size; debug_count++)
1921 putchar (pattern[debug_count]);
1926 /* Initialize the compile stack. */
1927 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1928 if (compile_stack.stack == NULL)
1931 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1932 compile_stack.avail = 0;
1934 range_table_work.table = 0;
1935 range_table_work.allocated = 0;
1937 /* Initialize the pattern buffer. */
1938 bufp->syntax = syntax;
1939 bufp->fastmap_accurate = 0;
1940 bufp->not_bol = bufp->not_eol = 0;
1942 /* Set `used' to zero, so that if we return an error, the pattern
1943 printer (for debugging) will think there's no pattern. We reset it
1947 /* Always count groups, whether or not bufp->no_sub is set. */
1951 /* bufp->multibyte is set before regex_compile is called, so don't alter
1953 #else /* not emacs */
1954 /* Nothing is recognized as a multibyte character. */
1955 bufp->multibyte = 0;
1958 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1959 /* Initialize the syntax table. */
1960 init_syntax_once ();
1963 if (bufp->allocated == 0)
1966 { /* If zero allocated, but buffer is non-null, try to realloc
1967 enough space. This loses if buffer's address is bogus, but
1968 that is the user's responsibility. */
1969 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1972 { /* Caller did not allocate a buffer. Do it for them. */
1973 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1975 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1977 bufp->allocated = INIT_BUF_SIZE;
1980 begalt = b = bufp->buffer;
1982 /* Loop through the uncompiled pattern until we're at the end. */
1991 if ( /* If at start of pattern, it's an operator. */
1993 /* If context independent, it's an operator. */
1994 || syntax & RE_CONTEXT_INDEP_ANCHORS
1995 /* Otherwise, depends on what's come before. */
1996 || at_begline_loc_p (pattern, p, syntax))
2006 if ( /* If at end of pattern, it's an operator. */
2008 /* If context independent, it's an operator. */
2009 || syntax & RE_CONTEXT_INDEP_ANCHORS
2010 /* Otherwise, depends on what's next. */
2011 || at_endline_loc_p (p, pend, syntax))
2021 if ((syntax & RE_BK_PLUS_QM)
2022 || (syntax & RE_LIMITED_OPS))
2026 /* If there is no previous pattern... */
2029 if (syntax & RE_CONTEXT_INVALID_OPS)
2030 FREE_STACK_RETURN (REG_BADRPT);
2031 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2036 /* Are we optimizing this jump? */
2037 boolean keep_string_p = false;
2039 /* 1 means zero (many) matches is allowed. */
2040 char zero_times_ok = 0, many_times_ok = 0;
2042 /* If there is a sequence of repetition chars, collapse it
2043 down to just one (the right one). We can't combine
2044 interval operators with these because of, e.g., `a{2}*',
2045 which should only match an even number of `a's. */
2049 zero_times_ok |= c != '+';
2050 many_times_ok |= c != '?';
2058 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2061 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2063 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2066 if (!(c1 == '+' || c1 == '?'))
2081 /* If we get here, we found another repeat character. */
2084 /* Star, etc. applied to an empty pattern is equivalent
2085 to an empty pattern. */
2089 /* Now we know whether or not zero matches is allowed
2090 and also whether or not two or more matches is allowed. */
2092 { /* More than one repetition is allowed, so put in at the
2093 end a backward relative jump from `b' to before the next
2094 jump we're going to put in below (which jumps from
2095 laststart to after this jump).
2097 But if we are at the `*' in the exact sequence `.*\n',
2098 insert an unconditional jump backwards to the .,
2099 instead of the beginning of the loop. This way we only
2100 push a failure point once, instead of every time
2101 through the loop. */
2102 assert (p - 1 > pattern);
2104 /* Allocate the space for the jump. */
2105 GET_BUFFER_SPACE (3);
2107 /* We know we are not at the first character of the pattern,
2108 because laststart was nonzero. And we've already
2109 incremented `p', by the way, to be the character after
2110 the `*'. Do we have to do something analogous here
2111 for null bytes, because of RE_DOT_NOT_NULL? */
2112 if (TRANSLATE ((unsigned char)*(p - 2)) == TRANSLATE ('.')
2115 && TRANSLATE ((unsigned char)*p) == TRANSLATE ('\n')
2116 && !(syntax & RE_DOT_NEWLINE))
2117 { /* We have .*\n. */
2118 STORE_JUMP (jump, b, laststart);
2119 keep_string_p = true;
2122 /* Anything else. */
2123 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2125 /* We've added more stuff to the buffer. */
2129 /* On failure, jump from laststart to b + 3, which will be the
2130 end of the buffer after this jump is inserted. */
2131 GET_BUFFER_SPACE (3);
2132 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2140 /* At least one repetition is required, so insert a
2141 `dummy_failure_jump' before the initial
2142 `on_failure_jump' instruction of the loop. This
2143 effects a skip over that instruction the first time
2144 we hit that loop. */
2145 GET_BUFFER_SPACE (3);
2146 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2161 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2163 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2165 /* Ensure that we have enough space to push a charset: the
2166 opcode, the length count, and the bitset; 34 bytes in all. */
2167 GET_BUFFER_SPACE (34);
2171 /* We test `*p == '^' twice, instead of using an if
2172 statement, so we only need one BUF_PUSH. */
2173 BUF_PUSH (*p == '^' ? charset_not : charset);
2177 /* Remember the first position in the bracket expression. */
2180 /* Push the number of bytes in the bitmap. */
2181 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2183 /* Clear the whole map. */
2184 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2186 /* charset_not matches newline according to a syntax bit. */
2187 if ((re_opcode_t) b[-2] == charset_not
2188 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2189 SET_LIST_BIT ('\n');
2191 /* Read in characters and ranges, setting map bits. */
2195 boolean escaped_char = false;
2197 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2201 /* \ might escape characters inside [...] and [^...]. */
2202 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2204 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2207 escaped_char = true;
2211 /* Could be the end of the bracket expression. If it's
2212 not (i.e., when the bracket expression is `[]' so
2213 far), the ']' character bit gets set way below. */
2214 if (c == ']' && p != p1 + 1)
2218 /* If C indicates start of multibyte char, get the
2219 actual character code in C, and set the pattern
2220 pointer P to the next character boundary. */
2221 if (bufp->multibyte && BASE_LEADING_CODE_P (c))
2224 c = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2227 /* What should we do for the character which is
2228 greater than 0x7F, but not BASE_LEADING_CODE_P?
2231 /* See if we're at the beginning of a possible character
2234 else if (!escaped_char &&
2235 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2237 /* Leave room for the null. */
2238 char str[CHAR_CLASS_MAX_LENGTH + 1];
2243 /* If pattern is `[[:'. */
2244 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2249 if (c == ':' || c == ']' || p == pend
2250 || c1 == CHAR_CLASS_MAX_LENGTH)
2256 /* If isn't a word bracketed by `[:' and `:]':
2257 undo the ending character, the letters, and
2258 leave the leading `:' and `[' (but set bits for
2260 if (c == ':' && *p == ']')
2263 boolean is_alnum = STREQ (str, "alnum");
2264 boolean is_alpha = STREQ (str, "alpha");
2265 boolean is_blank = STREQ (str, "blank");
2266 boolean is_cntrl = STREQ (str, "cntrl");
2267 boolean is_digit = STREQ (str, "digit");
2268 boolean is_graph = STREQ (str, "graph");
2269 boolean is_lower = STREQ (str, "lower");
2270 boolean is_print = STREQ (str, "print");
2271 boolean is_punct = STREQ (str, "punct");
2272 boolean is_space = STREQ (str, "space");
2273 boolean is_upper = STREQ (str, "upper");
2274 boolean is_xdigit = STREQ (str, "xdigit");
2276 if (!IS_CHAR_CLASS (str))
2277 FREE_STACK_RETURN (REG_ECTYPE);
2279 /* Throw away the ] at the end of the character
2283 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2285 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2287 int translated = TRANSLATE (ch);
2288 /* This was split into 3 if's to
2289 avoid an arbitrary limit in some compiler. */
2290 if ( (is_alnum && ISALNUM (ch))
2291 || (is_alpha && ISALPHA (ch))
2292 || (is_blank && ISBLANK (ch))
2293 || (is_cntrl && ISCNTRL (ch)))
2294 SET_LIST_BIT (translated);
2295 if ( (is_digit && ISDIGIT (ch))
2296 || (is_graph && ISGRAPH (ch))
2297 || (is_lower && ISLOWER (ch))
2298 || (is_print && ISPRINT (ch)))
2299 SET_LIST_BIT (translated);
2300 if ( (is_punct && ISPUNCT (ch))
2301 || (is_space && ISSPACE (ch))
2302 || (is_upper && ISUPPER (ch))
2303 || (is_xdigit && ISXDIGIT (ch)))
2304 SET_LIST_BIT (translated);
2307 /* Repeat the loop. */
2317 /* Because the `:' may starts the range, we
2318 can't simply set bit and repeat the loop.
2319 Instead, just set it to C and handle below. */
2324 if (p < pend && p[0] == '-' && p[1] != ']')
2327 /* Discard the `-'. */
2330 /* Fetch the character which ends the range. */
2332 if (bufp->multibyte && BASE_LEADING_CODE_P (c1))
2335 c1 = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2339 if (SINGLE_BYTE_CHAR_P (c)
2340 && ! SINGLE_BYTE_CHAR_P (c1))
2342 /* Handle a range such as \177-\377 in multibyte mode.
2343 Split that into two ranges,,
2344 the low one ending at 0237, and the high one
2345 starting at ...040. */
2346 int c1_base = (c1 & ~0177) | 040;
2347 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2350 else if (!SAME_CHARSET_P (c, c1))
2351 FREE_STACK_RETURN (REG_ERANGE);
2354 /* Range from C to C. */
2357 /* Set the range ... */
2358 if (SINGLE_BYTE_CHAR_P (c))
2359 /* ... into bitmap. */
2362 int range_start = c, range_end = c1;
2364 /* If the start is after the end, the range is empty. */
2365 if (range_start > range_end)
2367 if (syntax & RE_NO_EMPTY_RANGES)
2368 FREE_STACK_RETURN (REG_ERANGE);
2369 /* Else, repeat the loop. */
2373 for (this_char = range_start; this_char <= range_end;
2375 SET_LIST_BIT (TRANSLATE (this_char));
2379 /* ... into range table. */
2380 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2383 /* Discard any (non)matching list bytes that are all 0 at the
2384 end of the map. Decrease the map-length byte too. */
2385 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2389 /* Build real range table from work area. */
2390 if (RANGE_TABLE_WORK_USED (range_table_work))
2393 int used = RANGE_TABLE_WORK_USED (range_table_work);
2395 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2396 bytes for COUNT and three bytes for each character. */
2397 GET_BUFFER_SPACE (2 + used * 3);
2399 /* Indicate the existence of range table. */
2400 laststart[1] |= 0x80;
2402 STORE_NUMBER_AND_INCR (b, used / 2);
2403 for (i = 0; i < used; i++)
2404 STORE_CHARACTER_AND_INCR
2405 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2412 if (syntax & RE_NO_BK_PARENS)
2419 if (syntax & RE_NO_BK_PARENS)
2426 if (syntax & RE_NEWLINE_ALT)
2433 if (syntax & RE_NO_BK_VBAR)
2440 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2441 goto handle_interval;
2447 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2449 /* Do not translate the character after the \, so that we can
2450 distinguish, e.g., \B from \b, even if we normally would
2451 translate, e.g., B to b. */
2457 if (syntax & RE_NO_BK_PARENS)
2458 goto normal_backslash;
2464 if (COMPILE_STACK_FULL)
2466 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2467 compile_stack_elt_t);
2468 if (compile_stack.stack == NULL) return REG_ESPACE;
2470 compile_stack.size <<= 1;
2473 /* These are the values to restore when we hit end of this
2474 group. They are all relative offsets, so that if the
2475 whole pattern moves because of realloc, they will still
2477 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2478 COMPILE_STACK_TOP.fixup_alt_jump
2479 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2480 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2481 COMPILE_STACK_TOP.regnum = regnum;
2483 /* We will eventually replace the 0 with the number of
2484 groups inner to this one. But do not push a
2485 start_memory for groups beyond the last one we can
2486 represent in the compiled pattern. */
2487 if (regnum <= MAX_REGNUM)
2489 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2490 BUF_PUSH_3 (start_memory, regnum, 0);
2493 compile_stack.avail++;
2498 /* If we've reached MAX_REGNUM groups, then this open
2499 won't actually generate any code, so we'll have to
2500 clear pending_exact explicitly. */
2506 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2508 if (COMPILE_STACK_EMPTY)
2509 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2510 goto normal_backslash;
2512 FREE_STACK_RETURN (REG_ERPAREN);
2516 { /* Push a dummy failure point at the end of the
2517 alternative for a possible future
2518 `pop_failure_jump' to pop. See comments at
2519 `push_dummy_failure' in `re_match_2'. */
2520 BUF_PUSH (push_dummy_failure);
2522 /* We allocated space for this jump when we assigned
2523 to `fixup_alt_jump', in the `handle_alt' case below. */
2524 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2527 /* See similar code for backslashed left paren above. */
2528 if (COMPILE_STACK_EMPTY)
2529 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2532 FREE_STACK_RETURN (REG_ERPAREN);
2534 /* Since we just checked for an empty stack above, this
2535 ``can't happen''. */
2536 assert (compile_stack.avail != 0);
2538 /* We don't just want to restore into `regnum', because
2539 later groups should continue to be numbered higher,
2540 as in `(ab)c(de)' -- the second group is #2. */
2541 regnum_t this_group_regnum;
2543 compile_stack.avail--;
2544 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2546 = COMPILE_STACK_TOP.fixup_alt_jump
2547 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2549 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2550 this_group_regnum = COMPILE_STACK_TOP.regnum;
2551 /* If we've reached MAX_REGNUM groups, then this open
2552 won't actually generate any code, so we'll have to
2553 clear pending_exact explicitly. */
2556 /* We're at the end of the group, so now we know how many
2557 groups were inside this one. */
2558 if (this_group_regnum <= MAX_REGNUM)
2560 unsigned char *inner_group_loc
2561 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2563 *inner_group_loc = regnum - this_group_regnum;
2564 BUF_PUSH_3 (stop_memory, this_group_regnum,
2565 regnum - this_group_regnum);
2571 case '|': /* `\|'. */
2572 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2573 goto normal_backslash;
2575 if (syntax & RE_LIMITED_OPS)
2578 /* Insert before the previous alternative a jump which
2579 jumps to this alternative if the former fails. */
2580 GET_BUFFER_SPACE (3);
2581 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2585 /* The alternative before this one has a jump after it
2586 which gets executed if it gets matched. Adjust that
2587 jump so it will jump to this alternative's analogous
2588 jump (put in below, which in turn will jump to the next
2589 (if any) alternative's such jump, etc.). The last such
2590 jump jumps to the correct final destination. A picture:
2596 If we are at `b', then fixup_alt_jump right now points to a
2597 three-byte space after `a'. We'll put in the jump, set
2598 fixup_alt_jump to right after `b', and leave behind three
2599 bytes which we'll fill in when we get to after `c'. */
2602 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2604 /* Mark and leave space for a jump after this alternative,
2605 to be filled in later either by next alternative or
2606 when know we're at the end of a series of alternatives. */
2608 GET_BUFFER_SPACE (3);
2617 /* If \{ is a literal. */
2618 if (!(syntax & RE_INTERVALS)
2619 /* If we're at `\{' and it's not the open-interval
2621 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2622 || (p - 2 == pattern && p == pend))
2623 goto normal_backslash;
2627 /* If got here, then the syntax allows intervals. */
2629 /* At least (most) this many matches must be made. */
2630 int lower_bound = -1, upper_bound = -1;
2632 beg_interval = p - 1;
2636 if (syntax & RE_NO_BK_BRACES)
2637 goto unfetch_interval;
2639 FREE_STACK_RETURN (REG_EBRACE);
2642 GET_UNSIGNED_NUMBER (lower_bound);
2646 GET_UNSIGNED_NUMBER (upper_bound);
2647 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2650 /* Interval such as `{1}' => match exactly once. */
2651 upper_bound = lower_bound;
2653 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2654 || lower_bound > upper_bound)
2656 if (syntax & RE_NO_BK_BRACES)
2657 goto unfetch_interval;
2659 FREE_STACK_RETURN (REG_BADBR);
2662 if (!(syntax & RE_NO_BK_BRACES))
2664 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2671 if (syntax & RE_NO_BK_BRACES)
2672 goto unfetch_interval;
2674 FREE_STACK_RETURN (REG_BADBR);
2677 /* We just parsed a valid interval. */
2679 /* If it's invalid to have no preceding re. */
2682 if (syntax & RE_CONTEXT_INVALID_OPS)
2683 FREE_STACK_RETURN (REG_BADRPT);
2684 else if (syntax & RE_CONTEXT_INDEP_OPS)
2687 goto unfetch_interval;
2690 /* If the upper bound is zero, don't want to succeed at
2691 all; jump from `laststart' to `b + 3', which will be
2692 the end of the buffer after we insert the jump. */
2693 if (upper_bound == 0)
2695 GET_BUFFER_SPACE (3);
2696 INSERT_JUMP (jump, laststart, b + 3);
2700 /* Otherwise, we have a nontrivial interval. When
2701 we're all done, the pattern will look like:
2702 set_number_at <jump count> <upper bound>
2703 set_number_at <succeed_n count> <lower bound>
2704 succeed_n <after jump addr> <succeed_n count>
2706 jump_n <succeed_n addr> <jump count>
2707 (The upper bound and `jump_n' are omitted if
2708 `upper_bound' is 1, though.) */
2710 { /* If the upper bound is > 1, we need to insert
2711 more at the end of the loop. */
2712 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2714 GET_BUFFER_SPACE (nbytes);
2716 /* Initialize lower bound of the `succeed_n', even
2717 though it will be set during matching by its
2718 attendant `set_number_at' (inserted next),
2719 because `re_compile_fastmap' needs to know.
2720 Jump to the `jump_n' we might insert below. */
2721 INSERT_JUMP2 (succeed_n, laststart,
2722 b + 5 + (upper_bound > 1) * 5,
2726 /* Code to initialize the lower bound. Insert
2727 before the `succeed_n'. The `5' is the last two
2728 bytes of this `set_number_at', plus 3 bytes of
2729 the following `succeed_n'. */
2730 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2733 if (upper_bound > 1)
2734 { /* More than one repetition is allowed, so
2735 append a backward jump to the `succeed_n'
2736 that starts this interval.
2738 When we've reached this during matching,
2739 we'll have matched the interval once, so
2740 jump back only `upper_bound - 1' times. */
2741 STORE_JUMP2 (jump_n, b, laststart + 5,
2745 /* The location we want to set is the second
2746 parameter of the `jump_n'; that is `b-2' as
2747 an absolute address. `laststart' will be
2748 the `set_number_at' we're about to insert;
2749 `laststart+3' the number to set, the source
2750 for the relative address. But we are
2751 inserting into the middle of the pattern --
2752 so everything is getting moved up by 5.
2753 Conclusion: (b - 2) - (laststart + 3) + 5,
2754 i.e., b - laststart.
2756 We insert this at the beginning of the loop
2757 so that if we fail during matching, we'll
2758 reinitialize the bounds. */
2759 insert_op2 (set_number_at, laststart, b - laststart,
2760 upper_bound - 1, b);
2765 beg_interval = NULL;
2770 /* If an invalid interval, match the characters as literals. */
2771 assert (beg_interval);
2773 beg_interval = NULL;
2775 /* normal_char and normal_backslash need `c'. */
2778 if (!(syntax & RE_NO_BK_BRACES))
2780 if (p > pattern && p[-1] == '\\')
2781 goto normal_backslash;
2786 /* There is no way to specify the before_dot and after_dot
2787 operators. rms says this is ok. --karl */
2795 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2801 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2807 BUF_PUSH_2 (categoryspec, c);
2813 BUF_PUSH_2 (notcategoryspec, c);
2820 BUF_PUSH (wordchar);
2826 BUF_PUSH (notwordchar);
2839 BUF_PUSH (wordbound);
2843 BUF_PUSH (notwordbound);
2854 case '1': case '2': case '3': case '4': case '5':
2855 case '6': case '7': case '8': case '9':
2856 if (syntax & RE_NO_BK_REFS)
2862 FREE_STACK_RETURN (REG_ESUBREG);
2864 /* Can't back reference to a subexpression if inside of it. */
2865 if (group_in_compile_stack (compile_stack, c1))
2869 BUF_PUSH_2 (duplicate, c1);
2875 if (syntax & RE_BK_PLUS_QM)
2878 goto normal_backslash;
2882 /* You might think it would be useful for \ to mean
2883 not to translate; but if we don't translate it
2884 it will never match anything. */
2892 /* Expects the character in `c'. */
2894 p1 = p - 1; /* P1 points the head of C. */
2896 if (bufp->multibyte)
2897 /* Set P to the next character boundary. */
2898 p += MULTIBYTE_FORM_LENGTH (p1, pend - p1) - 1;
2900 /* If no exactn currently being built. */
2903 /* If last exactn not at current position. */
2904 || pending_exact + *pending_exact + 1 != b
2906 /* We have only one byte following the exactn for the count. */
2907 || *pending_exact >= (1 << BYTEWIDTH) - (p - p1)
2909 /* If followed by a repetition operator. */
2910 || (p != pend && (*p == '*' || *p == '^'))
2911 || ((syntax & RE_BK_PLUS_QM)
2912 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
2913 : p != pend && (*p == '+' || *p == '?'))
2914 || ((syntax & RE_INTERVALS)
2915 && ((syntax & RE_NO_BK_BRACES)
2916 ? p != pend && *p == '{'
2917 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
2919 /* Start building a new exactn. */
2923 BUF_PUSH_2 (exactn, 0);
2924 pending_exact = b - 1;
2927 /* Here, C may translated, therefore C may not equal to *P1. */
2935 /* Rest of multibyte form should be copied literally. */
2936 c = *(unsigned char *)p1;
2940 } /* while p != pend */
2943 /* Through the pattern now. */
2946 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2948 if (!COMPILE_STACK_EMPTY)
2949 FREE_STACK_RETURN (REG_EPAREN);
2951 /* If we don't want backtracking, force success
2952 the first time we reach the end of the compiled pattern. */
2953 if (syntax & RE_NO_POSIX_BACKTRACKING)
2956 free (compile_stack.stack);
2958 /* We have succeeded; set the length of the buffer. */
2959 bufp->used = b - bufp->buffer;
2964 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2965 print_compiled_pattern (bufp);
2969 #ifndef MATCH_MAY_ALLOCATE
2970 /* Initialize the failure stack to the largest possible stack. This
2971 isn't necessary unless we're trying to avoid calling alloca in
2972 the search and match routines. */
2974 int num_regs = bufp->re_nsub + 1;
2976 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
2978 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
2981 if (! fail_stack.stack)
2983 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2984 * sizeof (fail_stack_elt_t));
2987 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2989 * sizeof (fail_stack_elt_t)));
2990 #else /* not emacs */
2991 if (! fail_stack.stack)
2993 = (fail_stack_elt_t *) malloc (fail_stack.size
2994 * sizeof (fail_stack_elt_t));
2997 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2999 * sizeof (fail_stack_elt_t)));
3000 #endif /* not emacs */
3003 regex_grow_registers (num_regs);
3005 #endif /* not MATCH_MAY_ALLOCATE */
3008 } /* regex_compile */
3010 /* Subroutines for `regex_compile'. */
3012 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3015 store_op1 (op, loc, arg)
3020 *loc = (unsigned char) op;
3021 STORE_NUMBER (loc + 1, arg);
3025 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3028 store_op2 (op, loc, arg1, arg2)
3033 *loc = (unsigned char) op;
3034 STORE_NUMBER (loc + 1, arg1);
3035 STORE_NUMBER (loc + 3, arg2);
3039 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3040 for OP followed by two-byte integer parameter ARG. */
3043 insert_op1 (op, loc, arg, end)
3049 register unsigned char *pfrom = end;
3050 register unsigned char *pto = end + 3;
3052 while (pfrom != loc)
3055 store_op1 (op, loc, arg);
3059 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3062 insert_op2 (op, loc, arg1, arg2, end)
3068 register unsigned char *pfrom = end;
3069 register unsigned char *pto = end + 5;
3071 while (pfrom != loc)
3074 store_op2 (op, loc, arg1, arg2);
3078 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3079 after an alternative or a begin-subexpression. We assume there is at
3080 least one character before the ^. */
3083 at_begline_loc_p (pattern, p, syntax)
3084 const char *pattern, *p;
3085 reg_syntax_t syntax;
3087 const char *prev = p - 2;
3088 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3091 /* After a subexpression? */
3092 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3093 /* After an alternative? */
3094 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3098 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3099 at least one character after the $, i.e., `P < PEND'. */
3102 at_endline_loc_p (p, pend, syntax)
3103 const char *p, *pend;
3106 const char *next = p;
3107 boolean next_backslash = *next == '\\';
3108 const char *next_next = p + 1 < pend ? p + 1 : 0;
3111 /* Before a subexpression? */
3112 (syntax & RE_NO_BK_PARENS ? *next == ')'
3113 : next_backslash && next_next && *next_next == ')')
3114 /* Before an alternative? */
3115 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3116 : next_backslash && next_next && *next_next == '|');
3120 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3121 false if it's not. */
3124 group_in_compile_stack (compile_stack, regnum)
3125 compile_stack_type compile_stack;
3130 for (this_element = compile_stack.avail - 1;
3133 if (compile_stack.stack[this_element].regnum == regnum)
3139 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3140 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3141 characters can start a string that matches the pattern. This fastmap
3142 is used by re_search to skip quickly over impossible starting points.
3144 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3145 area as BUFP->fastmap.
3147 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3150 Returns 0 if we succeed, -2 if an internal error. */
3153 re_compile_fastmap (bufp)
3154 struct re_pattern_buffer *bufp;
3157 #ifdef MATCH_MAY_ALLOCATE
3158 fail_stack_type fail_stack;
3160 #ifndef REGEX_MALLOC
3163 /* We don't push any register information onto the failure stack. */
3164 unsigned num_regs = 0;
3166 register char *fastmap = bufp->fastmap;
3167 unsigned char *pattern = bufp->buffer;
3168 unsigned long size = bufp->used;
3169 unsigned char *p = pattern;
3170 register unsigned char *pend = pattern + size;
3172 /* This holds the pointer to the failure stack, when
3173 it is allocated relocatably. */
3174 fail_stack_elt_t *failure_stack_ptr;
3176 /* Assume that each path through the pattern can be null until
3177 proven otherwise. We set this false at the bottom of switch
3178 statement, to which we get only if a particular path doesn't
3179 match the empty string. */
3180 boolean path_can_be_null = true;
3182 /* We aren't doing a `succeed_n' to begin with. */
3183 boolean succeed_n_p = false;
3185 /* If all elements for base leading-codes in fastmap is set, this
3186 flag is set true. */
3187 boolean match_any_multibyte_characters = false;
3189 /* Maximum code of simple (single byte) character. */
3190 int simple_char_max;
3192 assert (fastmap != NULL && p != NULL);
3195 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3196 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3197 bufp->can_be_null = 0;
3201 if (p == pend || *p == succeed)
3203 /* We have reached the (effective) end of pattern. */
3204 if (!FAIL_STACK_EMPTY ())
3206 bufp->can_be_null |= path_can_be_null;
3208 /* Reset for next path. */
3209 path_can_be_null = true;
3211 p = fail_stack.stack[--fail_stack.avail].pointer;
3219 /* We should never be about to go beyond the end of the pattern. */
3222 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3225 /* I guess the idea here is to simply not bother with a fastmap
3226 if a backreference is used, since it's too hard to figure out
3227 the fastmap for the corresponding group. Setting
3228 `can_be_null' stops `re_search_2' from using the fastmap, so
3229 that is all we do. */
3231 bufp->can_be_null = 1;
3235 /* Following are the cases which match a character. These end
3245 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3246 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3252 /* Chars beyond end of map must be allowed. */
3253 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3256 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3257 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3263 for (j = 0; j < (1 << BYTEWIDTH); j++)
3264 if (SYNTAX (j) == Sword)
3270 for (j = 0; j < (1 << BYTEWIDTH); j++)
3271 if (SYNTAX (j) != Sword)
3276 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3278 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3281 if (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3282 && match_any_multibyte_characters == false)
3284 /* Set fastmap[I] 1 where I is a base leading code of each
3285 multibyte character in the range table. */
3288 /* Make P points the range table. */
3289 p += CHARSET_BITMAP_SIZE (&p[-2]);
3291 /* Extract the number of ranges in range table into
3293 EXTRACT_NUMBER_AND_INCR (count, p);
3294 for (; count > 0; count--, p += 2 * 3) /* XXX */
3296 /* Extract the start of each range. */
3297 EXTRACT_CHARACTER (c, p);
3298 j = CHAR_CHARSET (c);
3299 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3306 /* Chars beyond end of map must be allowed. End of map is
3307 `127' if bufp->multibyte is nonzero. */
3308 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3309 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3310 j < simple_char_max; j++)
3313 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3315 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3318 if (bufp->multibyte)
3319 /* Any character set can possibly contain a character
3320 which doesn't match the specified set of characters. */
3322 set_fastmap_for_multibyte_characters:
3323 if (match_any_multibyte_characters == false)
3325 for (j = 0x80; j < 0xA0; j++) /* XXX */
3326 if (BASE_LEADING_CODE_P (j))
3328 match_any_multibyte_characters = true;
3335 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3336 for (j = 0; j < simple_char_max; j++)
3337 if (SYNTAX (j) == Sword)
3340 if (bufp->multibyte)
3341 /* Any character set can possibly contain a character
3342 whose syntax is `Sword'. */
3343 goto set_fastmap_for_multibyte_characters;
3348 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3349 for (j = 0; j < simple_char_max; j++)
3350 if (SYNTAX (j) != Sword)
3353 if (bufp->multibyte)
3354 /* Any character set can possibly contain a character
3355 whose syntax is not `Sword'. */
3356 goto set_fastmap_for_multibyte_characters;
3362 int fastmap_newline = fastmap['\n'];
3364 /* `.' matches anything (but if bufp->multibyte is
3365 nonzero, matches `\000' .. `\127' and possible multibyte
3367 if (bufp->multibyte)
3369 simple_char_max = 0x80;
3371 for (j = 0x80; j < 0xA0; j++)
3372 if (BASE_LEADING_CODE_P (j))
3374 match_any_multibyte_characters = true;
3377 simple_char_max = (1 << BYTEWIDTH);
3379 for (j = 0; j < simple_char_max; j++)
3382 /* ... except perhaps newline. */
3383 if (!(bufp->syntax & RE_DOT_NEWLINE))
3384 fastmap['\n'] = fastmap_newline;
3386 /* Return if we have already set `can_be_null'; if we have,
3387 then the fastmap is irrelevant. Something's wrong here. */
3388 else if (bufp->can_be_null)
3391 /* Otherwise, have to check alternative paths. */
3402 /* This match depends on text properties. These end with
3403 aborting optimizations. */
3404 bufp->can_be_null = 1;
3408 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3409 for (j = 0; j < simple_char_max; j++)
3410 if (SYNTAX (j) == (enum syntaxcode) k)
3413 if (bufp->multibyte)
3414 /* Any character set can possibly contain a character
3415 whose syntax is K. */
3416 goto set_fastmap_for_multibyte_characters;
3421 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3422 for (j = 0; j < simple_char_max; j++)
3423 if (SYNTAX (j) != (enum syntaxcode) k)
3426 if (bufp->multibyte)
3427 /* Any character set can possibly contain a character
3428 whose syntax is not K. */
3429 goto set_fastmap_for_multibyte_characters;
3436 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3437 for (j = 0; j < simple_char_max; j++)
3438 if (CHAR_HAS_CATEGORY (j, k))
3441 if (bufp->multibyte)
3442 /* Any character set can possibly contain a character
3443 whose category is K. */
3444 goto set_fastmap_for_multibyte_characters;
3448 case notcategoryspec:
3450 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3451 for (j = 0; j < simple_char_max; j++)
3452 if (!CHAR_HAS_CATEGORY (j, k))
3455 if (bufp->multibyte)
3456 /* Any character set can possibly contain a character
3457 whose category is not K. */
3458 goto set_fastmap_for_multibyte_characters;
3461 /* All cases after this match the empty string. These end with
3483 case push_dummy_failure:
3488 case pop_failure_jump:
3489 case maybe_pop_jump:
3492 case dummy_failure_jump:
3493 EXTRACT_NUMBER_AND_INCR (j, p);
3498 /* Jump backward implies we just went through the body of a
3499 loop and matched nothing. Opcode jumped to should be
3500 `on_failure_jump' or `succeed_n'. Just treat it like an
3501 ordinary jump. For a * loop, it has pushed its failure
3502 point already; if so, discard that as redundant. */
3503 if ((re_opcode_t) *p != on_failure_jump
3504 && (re_opcode_t) *p != succeed_n)
3508 EXTRACT_NUMBER_AND_INCR (j, p);
3511 /* If what's on the stack is where we are now, pop it. */
3512 if (!FAIL_STACK_EMPTY ()
3513 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3519 case on_failure_jump:
3520 case on_failure_keep_string_jump:
3521 handle_on_failure_jump:
3522 EXTRACT_NUMBER_AND_INCR (j, p);
3524 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3525 end of the pattern. We don't want to push such a point,
3526 since when we restore it above, entering the switch will
3527 increment `p' past the end of the pattern. We don't need
3528 to push such a point since we obviously won't find any more
3529 fastmap entries beyond `pend'. Such a pattern can match
3530 the null string, though. */
3533 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3535 RESET_FAIL_STACK ();
3540 bufp->can_be_null = 1;
3544 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3545 succeed_n_p = false;
3552 /* Get to the number of times to succeed. */
3555 /* Increment p past the n for when k != 0. */
3556 EXTRACT_NUMBER_AND_INCR (k, p);
3560 succeed_n_p = true; /* Spaghetti code alert. */
3561 goto handle_on_failure_jump;
3578 abort (); /* We have listed all the cases. */
3581 /* Getting here means we have found the possible starting
3582 characters for one path of the pattern -- and that the empty
3583 string does not match. We need not follow this path further.
3584 Instead, look at the next alternative (remembered on the
3585 stack), or quit if no more. The test at the top of the loop
3586 does these things. */
3587 path_can_be_null = false;
3591 /* Set `can_be_null' for the last path (also the first path, if the
3592 pattern is empty). */
3593 bufp->can_be_null |= path_can_be_null;
3596 RESET_FAIL_STACK ();
3598 } /* re_compile_fastmap */
3600 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3601 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3602 this memory for recording register information. STARTS and ENDS
3603 must be allocated using the malloc library routine, and must each
3604 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3606 If NUM_REGS == 0, then subsequent matches should allocate their own
3609 Unless this function is called, the first search or match using
3610 PATTERN_BUFFER will allocate its own register data, without
3611 freeing the old data. */
3614 re_set_registers (bufp, regs, num_regs, starts, ends)
3615 struct re_pattern_buffer *bufp;
3616 struct re_registers *regs;
3618 regoff_t *starts, *ends;
3622 bufp->regs_allocated = REGS_REALLOCATE;
3623 regs->num_regs = num_regs;
3624 regs->start = starts;
3629 bufp->regs_allocated = REGS_UNALLOCATED;
3631 regs->start = regs->end = (regoff_t *) 0;
3635 /* Searching routines. */
3637 /* Like re_search_2, below, but only one string is specified, and
3638 doesn't let you say where to stop matching. */
3641 re_search (bufp, string, size, startpos, range, regs)
3642 struct re_pattern_buffer *bufp;
3644 int size, startpos, range;
3645 struct re_registers *regs;
3647 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3651 /* End address of virtual concatenation of string. */
3652 #define STOP_ADDR_VSTRING(P) \
3653 (((P) >= size1 ? string2 + size2 : string1 + size1))
3655 /* Address of POS in the concatenation of virtual string. */
3656 #define POS_ADDR_VSTRING(POS) \
3657 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3659 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3660 virtual concatenation of STRING1 and STRING2, starting first at index
3661 STARTPOS, then at STARTPOS + 1, and so on.
3663 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3665 RANGE is how far to scan while trying to match. RANGE = 0 means try
3666 only at STARTPOS; in general, the last start tried is STARTPOS +
3669 In REGS, return the indices of the virtual concatenation of STRING1
3670 and STRING2 that matched the entire BUFP->buffer and its contained
3673 Do not consider matching one past the index STOP in the virtual
3674 concatenation of STRING1 and STRING2.
3676 We return either the position in the strings at which the match was
3677 found, -1 if no match, or -2 if error (such as failure
3681 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3682 struct re_pattern_buffer *bufp;
3683 const char *string1, *string2;
3687 struct re_registers *regs;
3691 register char *fastmap = bufp->fastmap;
3692 register RE_TRANSLATE_TYPE translate = bufp->translate;
3693 int total_size = size1 + size2;
3694 int endpos = startpos + range;
3695 int anchored_start = 0;
3697 /* Nonzero if we have to concern multibyte character. */
3698 int multibyte = bufp->multibyte;
3700 /* Check for out-of-range STARTPOS. */
3701 if (startpos < 0 || startpos > total_size)
3704 /* Fix up RANGE if it might eventually take us outside
3705 the virtual concatenation of STRING1 and STRING2.
3706 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3708 range = 0 - startpos;
3709 else if (endpos > total_size)
3710 range = total_size - startpos;
3712 /* If the search isn't to be a backwards one, don't waste time in a
3713 search for a pattern anchored at beginning of buffer. */
3714 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3723 /* In a forward search for something that starts with \=.
3724 don't keep searching past point. */
3725 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3727 range = PT_BYTE - BEGV_BYTE - startpos;
3733 /* Update the fastmap now if not correct already. */
3734 if (fastmap && !bufp->fastmap_accurate)
3735 if (re_compile_fastmap (bufp) == -2)
3738 /* See whether the pattern is anchored. */
3739 if (bufp->buffer[0] == begline)
3743 gl_state.object = re_match_object;
3745 int adjpos = NILP (re_match_object) || BUFFERP (re_match_object);
3746 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (startpos + adjpos);
3748 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
3752 /* Loop through the string, looking for a place to start matching. */
3755 /* If the pattern is anchored,
3756 skip quickly past places we cannot match.
3757 We don't bother to treat startpos == 0 specially
3758 because that case doesn't repeat. */
3759 if (anchored_start && startpos > 0)
3761 if (! (bufp->newline_anchor
3762 && ((startpos <= size1 ? string1[startpos - 1]
3763 : string2[startpos - size1 - 1])
3768 /* If a fastmap is supplied, skip quickly over characters that
3769 cannot be the start of a match. If the pattern can match the
3770 null string, however, we don't need to skip characters; we want
3771 the first null string. */
3772 if (fastmap && startpos < total_size && !bufp->can_be_null)
3774 register const char *d;
3775 register unsigned int buf_ch;
3777 d = POS_ADDR_VSTRING (startpos);
3779 if (range > 0) /* Searching forwards. */
3781 register int lim = 0;
3784 if (startpos < size1 && startpos + range >= size1)
3785 lim = range - (size1 - startpos);
3787 /* Written out as an if-else to avoid testing `translate'
3789 if (RE_TRANSLATE_P (translate))
3796 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
3799 buf_ch = RE_TRANSLATE (translate, buf_ch);
3804 range -= buf_charlen;
3809 && !fastmap[(unsigned char)
3810 RE_TRANSLATE (translate, (unsigned char) *d)])
3817 while (range > lim && !fastmap[(unsigned char) *d])
3823 startpos += irange - range;
3825 else /* Searching backwards. */
3827 int room = (size1 == 0 || startpos >= size1
3828 ? size2 + size1 - startpos
3829 : size1 - startpos);
3831 buf_ch = STRING_CHAR (d, room);
3832 if (RE_TRANSLATE_P (translate))
3833 buf_ch = RE_TRANSLATE (translate, buf_ch);
3835 if (! (buf_ch >= 0400
3836 || fastmap[buf_ch]))
3841 /* If can't match the null string, and that's all we have left, fail. */
3842 if (range >= 0 && startpos == total_size && fastmap
3843 && !bufp->can_be_null)
3846 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3847 startpos, regs, stop);
3848 #ifndef REGEX_MALLOC
3865 /* Update STARTPOS to the next character boundary. */
3868 const unsigned char *p
3869 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3870 const unsigned char *pend
3871 = (const unsigned char *) STOP_ADDR_VSTRING (startpos);
3872 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
3890 /* Update STARTPOS to the previous character boundary. */
3893 const unsigned char *p
3894 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3897 /* Find the head of multibyte form. */
3898 while (!CHAR_HEAD_P (*p))
3903 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
3920 /* Declarations and macros for re_match_2. */
3922 static int bcmp_translate ();
3923 static boolean alt_match_null_string_p (),
3924 common_op_match_null_string_p (),
3925 group_match_null_string_p ();
3927 /* This converts PTR, a pointer into one of the search strings `string1'
3928 and `string2' into an offset from the beginning of that string. */
3929 #define POINTER_TO_OFFSET(ptr) \
3930 (FIRST_STRING_P (ptr) \
3931 ? ((regoff_t) ((ptr) - string1)) \
3932 : ((regoff_t) ((ptr) - string2 + size1)))
3934 /* Macros for dealing with the split strings in re_match_2. */
3936 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3938 /* Call before fetching a character with *d. This switches over to
3939 string2 if necessary. */
3940 #define PREFETCH() \
3943 /* End of string2 => fail. */ \
3944 if (dend == end_match_2) \
3946 /* End of string1 => advance to string2. */ \
3948 dend = end_match_2; \
3952 /* Test if at very beginning or at very end of the virtual concatenation
3953 of `string1' and `string2'. If only one string, it's `string2'. */
3954 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3955 #define AT_STRINGS_END(d) ((d) == end2)
3958 /* Test if D points to a character which is word-constituent. We have
3959 two special cases to check for: if past the end of string1, look at
3960 the first character in string2; and if before the beginning of
3961 string2, look at the last character in string1. */
3962 #define WORDCHAR_P(d) \
3963 (SYNTAX ((d) == end1 ? *string2 \
3964 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3967 /* Disabled due to a compiler bug -- see comment at case wordbound */
3969 /* The comment at case wordbound is following one, but we don't use
3970 AT_WORD_BOUNDARY anymore to support multibyte form.
3972 The DEC Alpha C compiler 3.x generates incorrect code for the
3973 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
3974 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
3975 macro and introducing temporary variables works around the bug. */
3978 /* Test if the character before D and the one at D differ with respect
3979 to being word-constituent. */
3980 #define AT_WORD_BOUNDARY(d) \
3981 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3982 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3985 /* Free everything we malloc. */
3986 #ifdef MATCH_MAY_ALLOCATE
3987 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
3988 #define FREE_VARIABLES() \
3990 REGEX_FREE_STACK (fail_stack.stack); \
3991 FREE_VAR (regstart); \
3992 FREE_VAR (regend); \
3993 FREE_VAR (old_regstart); \
3994 FREE_VAR (old_regend); \
3995 FREE_VAR (best_regstart); \
3996 FREE_VAR (best_regend); \
3997 FREE_VAR (reg_info); \
3998 FREE_VAR (reg_dummy); \
3999 FREE_VAR (reg_info_dummy); \
4002 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4003 #endif /* not MATCH_MAY_ALLOCATE */
4005 /* These values must meet several constraints. They must not be valid
4006 register values; since we have a limit of 255 registers (because
4007 we use only one byte in the pattern for the register number), we can
4008 use numbers larger than 255. They must differ by 1, because of
4009 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4010 be larger than the value for the highest register, so we do not try
4011 to actually save any registers when none are active. */
4012 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4013 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4015 /* Matching routines. */
4017 #ifndef emacs /* Emacs never uses this. */
4018 /* re_match is like re_match_2 except it takes only a single string. */
4021 re_match (bufp, string, size, pos, regs)
4022 struct re_pattern_buffer *bufp;
4025 struct re_registers *regs;
4027 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4032 #endif /* not emacs */
4035 /* In Emacs, this is the string or buffer in which we
4036 are matching. It is used for looking up syntax properties. */
4037 Lisp_Object re_match_object;
4040 /* re_match_2 matches the compiled pattern in BUFP against the
4041 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4042 and SIZE2, respectively). We start matching at POS, and stop
4045 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4046 store offsets for the substring each group matched in REGS. See the
4047 documentation for exactly how many groups we fill.
4049 We return -1 if no match, -2 if an internal error (such as the
4050 failure stack overflowing). Otherwise, we return the length of the
4051 matched substring. */
4054 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4055 struct re_pattern_buffer *bufp;
4056 const char *string1, *string2;
4059 struct re_registers *regs;
4066 int adjpos = NILP (re_match_object) || BUFFERP (re_match_object);
4067 gl_state.object = re_match_object;
4068 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos + adjpos);
4069 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4072 result = re_match_2_internal (bufp, string1, size1, string2, size2,
4078 /* This is a separate function so that we can force an alloca cleanup
4081 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4082 struct re_pattern_buffer *bufp;
4083 const char *string1, *string2;
4086 struct re_registers *regs;
4089 /* General temporaries. */
4093 /* Just past the end of the corresponding string. */
4094 const char *end1, *end2;
4096 /* Pointers into string1 and string2, just past the last characters in
4097 each to consider matching. */
4098 const char *end_match_1, *end_match_2;
4100 /* Where we are in the data, and the end of the current string. */
4101 const char *d, *dend;
4103 /* Where we are in the pattern, and the end of the pattern. */
4104 unsigned char *p = bufp->buffer;
4105 register unsigned char *pend = p + bufp->used;
4107 /* Mark the opcode just after a start_memory, so we can test for an
4108 empty subpattern when we get to the stop_memory. */
4109 unsigned char *just_past_start_mem = 0;
4111 /* We use this to map every character in the string. */
4112 RE_TRANSLATE_TYPE translate = bufp->translate;
4114 /* Nonzero if we have to concern multibyte character. */
4115 int multibyte = bufp->multibyte;
4117 /* Failure point stack. Each place that can handle a failure further
4118 down the line pushes a failure point on this stack. It consists of
4119 restart, regend, and reg_info for all registers corresponding to
4120 the subexpressions we're currently inside, plus the number of such
4121 registers, and, finally, two char *'s. The first char * is where
4122 to resume scanning the pattern; the second one is where to resume
4123 scanning the strings. If the latter is zero, the failure point is
4124 a ``dummy''; if a failure happens and the failure point is a dummy,
4125 it gets discarded and the next next one is tried. */
4126 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4127 fail_stack_type fail_stack;
4130 static unsigned failure_id = 0;
4131 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4134 /* This holds the pointer to the failure stack, when
4135 it is allocated relocatably. */
4136 fail_stack_elt_t *failure_stack_ptr;
4138 /* We fill all the registers internally, independent of what we
4139 return, for use in backreferences. The number here includes
4140 an element for register zero. */
4141 unsigned num_regs = bufp->re_nsub + 1;
4143 /* The currently active registers. */
4144 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4145 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4147 /* Information on the contents of registers. These are pointers into
4148 the input strings; they record just what was matched (on this
4149 attempt) by a subexpression part of the pattern, that is, the
4150 regnum-th regstart pointer points to where in the pattern we began
4151 matching and the regnum-th regend points to right after where we
4152 stopped matching the regnum-th subexpression. (The zeroth register
4153 keeps track of what the whole pattern matches.) */
4154 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4155 const char **regstart, **regend;
4158 /* If a group that's operated upon by a repetition operator fails to
4159 match anything, then the register for its start will need to be
4160 restored because it will have been set to wherever in the string we
4161 are when we last see its open-group operator. Similarly for a
4163 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4164 const char **old_regstart, **old_regend;
4167 /* The is_active field of reg_info helps us keep track of which (possibly
4168 nested) subexpressions we are currently in. The matched_something
4169 field of reg_info[reg_num] helps us tell whether or not we have
4170 matched any of the pattern so far this time through the reg_num-th
4171 subexpression. These two fields get reset each time through any
4172 loop their register is in. */
4173 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4174 register_info_type *reg_info;
4177 /* The following record the register info as found in the above
4178 variables when we find a match better than any we've seen before.
4179 This happens as we backtrack through the failure points, which in
4180 turn happens only if we have not yet matched the entire string. */
4181 unsigned best_regs_set = false;
4182 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4183 const char **best_regstart, **best_regend;
4186 /* Logically, this is `best_regend[0]'. But we don't want to have to
4187 allocate space for that if we're not allocating space for anything
4188 else (see below). Also, we never need info about register 0 for
4189 any of the other register vectors, and it seems rather a kludge to
4190 treat `best_regend' differently than the rest. So we keep track of
4191 the end of the best match so far in a separate variable. We
4192 initialize this to NULL so that when we backtrack the first time
4193 and need to test it, it's not garbage. */
4194 const char *match_end = NULL;
4196 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4197 int set_regs_matched_done = 0;
4199 /* Used when we pop values we don't care about. */
4200 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4201 const char **reg_dummy;
4202 register_info_type *reg_info_dummy;
4206 /* Counts the total number of registers pushed. */
4207 unsigned num_regs_pushed = 0;
4210 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4214 #ifdef MATCH_MAY_ALLOCATE
4215 /* Do not bother to initialize all the register variables if there are
4216 no groups in the pattern, as it takes a fair amount of time. If
4217 there are groups, we include space for register 0 (the whole
4218 pattern), even though we never use it, since it simplifies the
4219 array indexing. We should fix this. */
4222 regstart = REGEX_TALLOC (num_regs, const char *);
4223 regend = REGEX_TALLOC (num_regs, const char *);
4224 old_regstart = REGEX_TALLOC (num_regs, const char *);
4225 old_regend = REGEX_TALLOC (num_regs, const char *);
4226 best_regstart = REGEX_TALLOC (num_regs, const char *);
4227 best_regend = REGEX_TALLOC (num_regs, const char *);
4228 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4229 reg_dummy = REGEX_TALLOC (num_regs, const char *);
4230 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4232 if (!(regstart && regend && old_regstart && old_regend && reg_info
4233 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4241 /* We must initialize all our variables to NULL, so that
4242 `FREE_VARIABLES' doesn't try to free them. */
4243 regstart = regend = old_regstart = old_regend = best_regstart
4244 = best_regend = reg_dummy = NULL;
4245 reg_info = reg_info_dummy = (register_info_type *) NULL;
4247 #endif /* MATCH_MAY_ALLOCATE */
4249 /* The starting position is bogus. */
4250 if (pos < 0 || pos > size1 + size2)
4256 /* Initialize subexpression text positions to -1 to mark ones that no
4257 start_memory/stop_memory has been seen for. Also initialize the
4258 register information struct. */
4259 for (mcnt = 1; mcnt < num_regs; mcnt++)
4261 regstart[mcnt] = regend[mcnt]
4262 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4264 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4265 IS_ACTIVE (reg_info[mcnt]) = 0;
4266 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4267 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4270 /* We move `string1' into `string2' if the latter's empty -- but not if
4271 `string1' is null. */
4272 if (size2 == 0 && string1 != NULL)
4279 end1 = string1 + size1;
4280 end2 = string2 + size2;
4282 /* Compute where to stop matching, within the two strings. */
4285 end_match_1 = string1 + stop;
4286 end_match_2 = string2;
4291 end_match_2 = string2 + stop - size1;
4294 /* `p' scans through the pattern as `d' scans through the data.
4295 `dend' is the end of the input string that `d' points within. `d'
4296 is advanced into the following input string whenever necessary, but
4297 this happens before fetching; therefore, at the beginning of the
4298 loop, `d' can be pointing at the end of a string, but it cannot
4300 if (size1 > 0 && pos <= size1)
4307 d = string2 + pos - size1;
4311 DEBUG_PRINT1 ("The compiled pattern is: ");
4312 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4313 DEBUG_PRINT1 ("The string to match is: `");
4314 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4315 DEBUG_PRINT1 ("'\n");
4317 /* This loops over pattern commands. It exits by returning from the
4318 function if the match is complete, or it drops through if the match
4319 fails at this starting point in the input data. */
4322 DEBUG_PRINT2 ("\n0x%x: ", p);
4325 { /* End of pattern means we might have succeeded. */
4326 DEBUG_PRINT1 ("end of pattern ... ");
4328 /* If we haven't matched the entire string, and we want the
4329 longest match, try backtracking. */
4330 if (d != end_match_2)
4332 /* 1 if this match ends in the same string (string1 or string2)
4333 as the best previous match. */
4334 boolean same_str_p = (FIRST_STRING_P (match_end)
4335 == MATCHING_IN_FIRST_STRING);
4336 /* 1 if this match is the best seen so far. */
4337 boolean best_match_p;
4339 /* AIX compiler got confused when this was combined
4340 with the previous declaration. */
4342 best_match_p = d > match_end;
4344 best_match_p = !MATCHING_IN_FIRST_STRING;
4346 DEBUG_PRINT1 ("backtracking.\n");
4348 if (!FAIL_STACK_EMPTY ())
4349 { /* More failure points to try. */
4351 /* If exceeds best match so far, save it. */
4352 if (!best_regs_set || best_match_p)
4354 best_regs_set = true;
4357 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4359 for (mcnt = 1; mcnt < num_regs; mcnt++)
4361 best_regstart[mcnt] = regstart[mcnt];
4362 best_regend[mcnt] = regend[mcnt];
4368 /* If no failure points, don't restore garbage. And if
4369 last match is real best match, don't restore second
4371 else if (best_regs_set && !best_match_p)
4374 /* Restore best match. It may happen that `dend ==
4375 end_match_1' while the restored d is in string2.
4376 For example, the pattern `x.*y.*z' against the
4377 strings `x-' and `y-z-', if the two strings are
4378 not consecutive in memory. */
4379 DEBUG_PRINT1 ("Restoring best registers.\n");
4382 dend = ((d >= string1 && d <= end1)
4383 ? end_match_1 : end_match_2);
4385 for (mcnt = 1; mcnt < num_regs; mcnt++)
4387 regstart[mcnt] = best_regstart[mcnt];
4388 regend[mcnt] = best_regend[mcnt];
4391 } /* d != end_match_2 */
4394 DEBUG_PRINT1 ("Accepting match.\n");
4396 /* If caller wants register contents data back, do it. */
4397 if (regs && !bufp->no_sub)
4399 /* Have the register data arrays been allocated? */
4400 if (bufp->regs_allocated == REGS_UNALLOCATED)
4401 { /* No. So allocate them with malloc. We need one
4402 extra element beyond `num_regs' for the `-1' marker
4404 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4405 regs->start = TALLOC (regs->num_regs, regoff_t);
4406 regs->end = TALLOC (regs->num_regs, regoff_t);
4407 if (regs->start == NULL || regs->end == NULL)
4412 bufp->regs_allocated = REGS_REALLOCATE;
4414 else if (bufp->regs_allocated == REGS_REALLOCATE)
4415 { /* Yes. If we need more elements than were already
4416 allocated, reallocate them. If we need fewer, just
4418 if (regs->num_regs < num_regs + 1)
4420 regs->num_regs = num_regs + 1;
4421 RETALLOC (regs->start, regs->num_regs, regoff_t);
4422 RETALLOC (regs->end, regs->num_regs, regoff_t);
4423 if (regs->start == NULL || regs->end == NULL)
4432 /* These braces fend off a "empty body in an else-statement"
4433 warning under GCC when assert expands to nothing. */
4434 assert (bufp->regs_allocated == REGS_FIXED);
4437 /* Convert the pointer data in `regstart' and `regend' to
4438 indices. Register zero has to be set differently,
4439 since we haven't kept track of any info for it. */
4440 if (regs->num_regs > 0)
4442 regs->start[0] = pos;
4443 regs->end[0] = (MATCHING_IN_FIRST_STRING
4444 ? ((regoff_t) (d - string1))
4445 : ((regoff_t) (d - string2 + size1)));
4448 /* Go through the first `min (num_regs, regs->num_regs)'
4449 registers, since that is all we initialized. */
4450 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4452 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4453 regs->start[mcnt] = regs->end[mcnt] = -1;
4457 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4459 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4463 /* If the regs structure we return has more elements than
4464 were in the pattern, set the extra elements to -1. If
4465 we (re)allocated the registers, this is the case,
4466 because we always allocate enough to have at least one
4468 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4469 regs->start[mcnt] = regs->end[mcnt] = -1;
4470 } /* regs && !bufp->no_sub */
4472 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4473 nfailure_points_pushed, nfailure_points_popped,
4474 nfailure_points_pushed - nfailure_points_popped);
4475 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4477 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4481 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4487 /* Otherwise match next pattern command. */
4488 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4490 /* Ignore these. Used to ignore the n of succeed_n's which
4491 currently have n == 0. */
4493 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4497 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4500 /* Match the next n pattern characters exactly. The following
4501 byte in the pattern defines n, and the n bytes after that
4502 are the characters to match. */
4505 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4507 /* This is written out as an if-else so we don't waste time
4508 testing `translate' inside the loop. */
4509 if (RE_TRANSLATE_P (translate))
4515 int pat_charlen, buf_charlen;
4516 unsigned int pat_ch, buf_ch;
4519 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
4520 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4522 if (RE_TRANSLATE (translate, buf_ch)
4528 mcnt -= pat_charlen;
4532 #endif /* not emacs */
4536 if ((unsigned char) RE_TRANSLATE (translate, (unsigned char) *d)
4537 != (unsigned char) *p++)
4548 if (*d++ != (char) *p++) goto fail;
4552 SET_REGS_MATCHED ();
4556 /* Match any character except possibly a newline or a null. */
4560 unsigned int buf_ch;
4562 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4568 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4570 #endif /* not emacs */
4572 buf_ch = (unsigned char) *d;
4576 buf_ch = TRANSLATE (buf_ch);
4578 if ((!(bufp->syntax & RE_DOT_NEWLINE)
4580 || ((bufp->syntax & RE_DOT_NOT_NULL)
4581 && buf_ch == '\000'))
4584 SET_REGS_MATCHED ();
4585 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4594 register unsigned int c;
4595 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4598 /* Start of actual range_table, or end of bitmap if there is no
4600 unsigned char *range_table;
4602 /* Nonzero if there is range table. */
4603 int range_table_exists;
4605 /* Number of ranges of range table. Not in bytes. */
4608 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4611 c = (unsigned char) *d;
4613 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
4614 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
4615 if (range_table_exists)
4616 EXTRACT_NUMBER_AND_INCR (count, range_table);
4620 if (multibyte && BASE_LEADING_CODE_P (c))
4621 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
4623 if (SINGLE_BYTE_CHAR_P (c))
4624 { /* Lookup bitmap. */
4625 c = TRANSLATE (c); /* The character to match. */
4628 /* Cast to `unsigned' instead of `unsigned char' in
4629 case the bit list is a full 32 bytes long. */
4630 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
4631 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4634 else if (range_table_exists)
4635 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
4637 p = CHARSET_RANGE_TABLE_END (range_table, count);
4639 if (!not) goto fail;
4641 SET_REGS_MATCHED ();
4647 /* The beginning of a group is represented by start_memory.
4648 The arguments are the register number in the next byte, and the
4649 number of groups inner to this one in the next. The text
4650 matched within the group is recorded (in the internal
4651 registers data structure) under the register number. */
4653 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4655 /* Find out if this group can match the empty string. */
4656 p1 = p; /* To send to group_match_null_string_p. */
4658 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4659 REG_MATCH_NULL_STRING_P (reg_info[*p])
4660 = group_match_null_string_p (&p1, pend, reg_info);
4662 /* Save the position in the string where we were the last time
4663 we were at this open-group operator in case the group is
4664 operated upon by a repetition operator, e.g., with `(a*)*b'
4665 against `ab'; then we want to ignore where we are now in
4666 the string in case this attempt to match fails. */
4667 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4668 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4670 DEBUG_PRINT2 (" old_regstart: %d\n",
4671 POINTER_TO_OFFSET (old_regstart[*p]));
4674 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4676 IS_ACTIVE (reg_info[*p]) = 1;
4677 MATCHED_SOMETHING (reg_info[*p]) = 0;
4679 /* Clear this whenever we change the register activity status. */
4680 set_regs_matched_done = 0;
4682 /* This is the new highest active register. */
4683 highest_active_reg = *p;
4685 /* If nothing was active before, this is the new lowest active
4687 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4688 lowest_active_reg = *p;
4690 /* Move past the register number and inner group count. */
4692 just_past_start_mem = p;
4697 /* The stop_memory opcode represents the end of a group. Its
4698 arguments are the same as start_memory's: the register
4699 number, and the number of inner groups. */
4701 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4703 /* We need to save the string position the last time we were at
4704 this close-group operator in case the group is operated
4705 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4706 against `aba'; then we want to ignore where we are now in
4707 the string in case this attempt to match fails. */
4708 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4709 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4711 DEBUG_PRINT2 (" old_regend: %d\n",
4712 POINTER_TO_OFFSET (old_regend[*p]));
4715 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4717 /* This register isn't active anymore. */
4718 IS_ACTIVE (reg_info[*p]) = 0;
4720 /* Clear this whenever we change the register activity status. */
4721 set_regs_matched_done = 0;
4723 /* If this was the only register active, nothing is active
4725 if (lowest_active_reg == highest_active_reg)
4727 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4728 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4731 { /* We must scan for the new highest active register, since
4732 it isn't necessarily one less than now: consider
4733 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4734 new highest active register is 1. */
4735 unsigned char r = *p - 1;
4736 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4739 /* If we end up at register zero, that means that we saved
4740 the registers as the result of an `on_failure_jump', not
4741 a `start_memory', and we jumped to past the innermost
4742 `stop_memory'. For example, in ((.)*) we save
4743 registers 1 and 2 as a result of the *, but when we pop
4744 back to the second ), we are at the stop_memory 1.
4745 Thus, nothing is active. */
4748 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4749 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4752 highest_active_reg = r;
4755 /* If just failed to match something this time around with a
4756 group that's operated on by a repetition operator, try to
4757 force exit from the ``loop'', and restore the register
4758 information for this group that we had before trying this
4760 if ((!MATCHED_SOMETHING (reg_info[*p])
4761 || just_past_start_mem == p - 1)
4764 boolean is_a_jump_n = false;
4768 switch ((re_opcode_t) *p1++)
4772 case pop_failure_jump:
4773 case maybe_pop_jump:
4775 case dummy_failure_jump:
4776 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4786 /* If the next operation is a jump backwards in the pattern
4787 to an on_failure_jump right before the start_memory
4788 corresponding to this stop_memory, exit from the loop
4789 by forcing a failure after pushing on the stack the
4790 on_failure_jump's jump in the pattern, and d. */
4791 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4792 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4794 /* If this group ever matched anything, then restore
4795 what its registers were before trying this last
4796 failed match, e.g., with `(a*)*b' against `ab' for
4797 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4798 against `aba' for regend[3].
4800 Also restore the registers for inner groups for,
4801 e.g., `((a*)(b*))*' against `aba' (register 3 would
4802 otherwise get trashed). */
4804 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4808 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4810 /* Restore this and inner groups' (if any) registers. */
4811 for (r = *p; r < *p + *(p + 1); r++)
4813 regstart[r] = old_regstart[r];
4815 /* xx why this test? */
4816 if (old_regend[r] >= regstart[r])
4817 regend[r] = old_regend[r];
4821 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4822 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4828 /* Move past the register number and the inner group count. */
4833 /* \<digit> has been turned into a `duplicate' command which is
4834 followed by the numeric value of <digit> as the register number. */
4837 register const char *d2, *dend2;
4838 int regno = *p++; /* Get which register to match against. */
4839 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4841 /* Can't back reference a group which we've never matched. */
4842 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4845 /* Where in input to try to start matching. */
4846 d2 = regstart[regno];
4848 /* Where to stop matching; if both the place to start and
4849 the place to stop matching are in the same string, then
4850 set to the place to stop, otherwise, for now have to use
4851 the end of the first string. */
4853 dend2 = ((FIRST_STRING_P (regstart[regno])
4854 == FIRST_STRING_P (regend[regno]))
4855 ? regend[regno] : end_match_1);
4858 /* If necessary, advance to next segment in register
4862 if (dend2 == end_match_2) break;
4863 if (dend2 == regend[regno]) break;
4865 /* End of string1 => advance to string2. */
4867 dend2 = regend[regno];
4869 /* At end of register contents => success */
4870 if (d2 == dend2) break;
4872 /* If necessary, advance to next segment in data. */
4875 /* How many characters left in this segment to match. */
4878 /* Want how many consecutive characters we can match in
4879 one shot, so, if necessary, adjust the count. */
4880 if (mcnt > dend2 - d2)
4883 /* Compare that many; failure if mismatch, else move
4885 if (RE_TRANSLATE_P (translate)
4886 ? bcmp_translate (d, d2, mcnt, translate)
4887 : bcmp (d, d2, mcnt))
4889 d += mcnt, d2 += mcnt;
4891 /* Do this because we've match some characters. */
4892 SET_REGS_MATCHED ();
4898 /* begline matches the empty string at the beginning of the string
4899 (unless `not_bol' is set in `bufp'), and, if
4900 `newline_anchor' is set, after newlines. */
4902 DEBUG_PRINT1 ("EXECUTING begline.\n");
4904 if (AT_STRINGS_BEG (d))
4906 if (!bufp->not_bol) break;
4908 else if (d[-1] == '\n' && bufp->newline_anchor)
4912 /* In all other cases, we fail. */
4916 /* endline is the dual of begline. */
4918 DEBUG_PRINT1 ("EXECUTING endline.\n");
4920 if (AT_STRINGS_END (d))
4922 if (!bufp->not_eol) break;
4925 /* We have to ``prefetch'' the next character. */
4926 else if ((d == end1 ? *string2 : *d) == '\n'
4927 && bufp->newline_anchor)
4934 /* Match at the very beginning of the data. */
4936 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4937 if (AT_STRINGS_BEG (d))
4942 /* Match at the very end of the data. */
4944 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4945 if (AT_STRINGS_END (d))
4950 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4951 pushes NULL as the value for the string on the stack. Then
4952 `pop_failure_point' will keep the current value for the
4953 string, instead of restoring it. To see why, consider
4954 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4955 then the . fails against the \n. But the next thing we want
4956 to do is match the \n against the \n; if we restored the
4957 string value, we would be back at the foo.
4959 Because this is used only in specific cases, we don't need to
4960 check all the things that `on_failure_jump' does, to make
4961 sure the right things get saved on the stack. Hence we don't
4962 share its code. The only reason to push anything on the
4963 stack at all is that otherwise we would have to change
4964 `anychar's code to do something besides goto fail in this
4965 case; that seems worse than this. */
4966 case on_failure_keep_string_jump:
4967 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4969 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4970 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4972 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4976 /* Uses of on_failure_jump:
4978 Each alternative starts with an on_failure_jump that points
4979 to the beginning of the next alternative. Each alternative
4980 except the last ends with a jump that in effect jumps past
4981 the rest of the alternatives. (They really jump to the
4982 ending jump of the following alternative, because tensioning
4983 these jumps is a hassle.)
4985 Repeats start with an on_failure_jump that points past both
4986 the repetition text and either the following jump or
4987 pop_failure_jump back to this on_failure_jump. */
4988 case on_failure_jump:
4990 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4992 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4993 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4995 /* If this on_failure_jump comes right before a group (i.e.,
4996 the original * applied to a group), save the information
4997 for that group and all inner ones, so that if we fail back
4998 to this point, the group's information will be correct.
4999 For example, in \(a*\)*\1, we need the preceding group,
5000 and in \(zz\(a*\)b*\)\2, we need the inner group. */
5002 /* We can't use `p' to check ahead because we push
5003 a failure point to `p + mcnt' after we do this. */
5006 /* We need to skip no_op's before we look for the
5007 start_memory in case this on_failure_jump is happening as
5008 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5010 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5013 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5015 /* We have a new highest active register now. This will
5016 get reset at the start_memory we are about to get to,
5017 but we will have saved all the registers relevant to
5018 this repetition op, as described above. */
5019 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5020 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5021 lowest_active_reg = *(p1 + 1);
5024 DEBUG_PRINT1 (":\n");
5025 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5029 /* A smart repeat ends with `maybe_pop_jump'.
5030 We change it to either `pop_failure_jump' or `jump'. */
5031 case maybe_pop_jump:
5032 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5033 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5035 register unsigned char *p2 = p;
5037 /* Compare the beginning of the repeat with what in the
5038 pattern follows its end. If we can establish that there
5039 is nothing that they would both match, i.e., that we
5040 would have to backtrack because of (as in, e.g., `a*a')
5041 then we can change to pop_failure_jump, because we'll
5042 never have to backtrack.
5044 This is not true in the case of alternatives: in
5045 `(a|ab)*' we do need to backtrack to the `ab' alternative
5046 (e.g., if the string was `ab'). But instead of trying to
5047 detect that here, the alternative has put on a dummy
5048 failure point which is what we will end up popping. */
5050 /* Skip over open/close-group commands.
5051 If what follows this loop is a ...+ construct,
5052 look at what begins its body, since we will have to
5053 match at least one of that. */
5057 && ((re_opcode_t) *p2 == stop_memory
5058 || (re_opcode_t) *p2 == start_memory))
5060 else if (p2 + 6 < pend
5061 && (re_opcode_t) *p2 == dummy_failure_jump)
5068 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5069 to the `maybe_finalize_jump' of this case. Examine what
5072 /* If we're at the end of the pattern, we can change. */
5075 /* Consider what happens when matching ":\(.*\)"
5076 against ":/". I don't really understand this code
5078 p[-3] = (unsigned char) pop_failure_jump;
5080 (" End of pattern: change to `pop_failure_jump'.\n");
5083 else if ((re_opcode_t) *p2 == exactn
5084 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5086 register unsigned int c
5087 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5089 if ((re_opcode_t) p1[3] == exactn)
5091 if (!(multibyte /* && (c != '\n') */
5092 && BASE_LEADING_CODE_P (c))
5094 : (STRING_CHAR (&p2[2], pend - &p2[2])
5095 != STRING_CHAR (&p1[5], pend - &p1[5])))
5097 p[-3] = (unsigned char) pop_failure_jump;
5098 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5103 else if ((re_opcode_t) p1[3] == charset
5104 || (re_opcode_t) p1[3] == charset_not)
5106 int not = (re_opcode_t) p1[3] == charset_not;
5108 if (multibyte /* && (c != '\n') */
5109 && BASE_LEADING_CODE_P (c))
5110 c = STRING_CHAR (&p2[2], pend - &p2[2]);
5112 /* Test if C is listed in charset (or charset_not)
5114 if (SINGLE_BYTE_CHAR_P (c))
5116 if (c < CHARSET_BITMAP_SIZE (&p1[3]) * BYTEWIDTH
5117 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5120 else if (CHARSET_RANGE_TABLE_EXISTS_P (&p1[3]))
5121 CHARSET_LOOKUP_RANGE_TABLE (not, c, &p1[3]);
5123 /* `not' is equal to 1 if c would match, which means
5124 that we can't change to pop_failure_jump. */
5127 p[-3] = (unsigned char) pop_failure_jump;
5128 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5132 else if ((re_opcode_t) *p2 == charset)
5134 if ((re_opcode_t) p1[3] == exactn)
5136 register unsigned int c = p1[5];
5139 if (multibyte && BASE_LEADING_CODE_P (c))
5140 c = STRING_CHAR (&p1[5], pend - &p1[5]);
5142 /* Test if C is listed in charset at `p2'. */
5143 if (SINGLE_BYTE_CHAR_P (c))
5145 if (c < CHARSET_BITMAP_SIZE (p2) * BYTEWIDTH
5146 && (p2[2 + c / BYTEWIDTH]
5147 & (1 << (c % BYTEWIDTH))))
5150 else if (CHARSET_RANGE_TABLE_EXISTS_P (p2))
5151 CHARSET_LOOKUP_RANGE_TABLE (not, c, p2);
5155 p[-3] = (unsigned char) pop_failure_jump;
5156 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5160 /* It is hard to list up all the character in charset
5161 P2 if it includes multibyte character. Give up in
5163 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
5165 /* Now, we are sure that P2 has no range table.
5166 So, for the size of bitmap in P2, `p2[1]' is
5167 enough. But P1 may have range table, so the
5168 size of bitmap table of P1 is extracted by
5169 using macro `CHARSET_BITMAP_SIZE'.
5171 Since we know that all the character listed in
5172 P2 is ASCII, it is enough to test only bitmap
5175 if ((re_opcode_t) p1[3] == charset_not)
5178 /* We win if the charset_not inside the loop lists
5179 every character listed in the charset after. */
5180 for (idx = 0; idx < (int) p2[1]; idx++)
5181 if (! (p2[2 + idx] == 0
5182 || (idx < CHARSET_BITMAP_SIZE (&p1[3])
5183 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5188 p[-3] = (unsigned char) pop_failure_jump;
5189 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5192 else if ((re_opcode_t) p1[3] == charset)
5195 /* We win if the charset inside the loop
5196 has no overlap with the one after the loop. */
5199 && idx < CHARSET_BITMAP_SIZE (&p1[3]));
5201 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5205 || idx == CHARSET_BITMAP_SIZE (&p1[3]))
5207 p[-3] = (unsigned char) pop_failure_jump;
5208 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5214 p -= 2; /* Point at relative address again. */
5215 if ((re_opcode_t) p[-1] != pop_failure_jump)
5217 p[-1] = (unsigned char) jump;
5218 DEBUG_PRINT1 (" Match => jump.\n");
5219 goto unconditional_jump;
5221 /* Note fall through. */
5224 /* The end of a simple repeat has a pop_failure_jump back to
5225 its matching on_failure_jump, where the latter will push a
5226 failure point. The pop_failure_jump takes off failure
5227 points put on by this pop_failure_jump's matching
5228 on_failure_jump; we got through the pattern to here from the
5229 matching on_failure_jump, so didn't fail. */
5230 case pop_failure_jump:
5232 /* We need to pass separate storage for the lowest and
5233 highest registers, even though we don't care about the
5234 actual values. Otherwise, we will restore only one
5235 register from the stack, since lowest will == highest in
5236 `pop_failure_point'. */
5237 unsigned dummy_low_reg, dummy_high_reg;
5238 unsigned char *pdummy;
5241 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5242 POP_FAILURE_POINT (sdummy, pdummy,
5243 dummy_low_reg, dummy_high_reg,
5244 reg_dummy, reg_dummy, reg_info_dummy);
5246 /* Note fall through. */
5249 /* Unconditionally jump (without popping any failure points). */
5252 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5253 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5254 p += mcnt; /* Do the jump. */
5255 DEBUG_PRINT2 ("(to 0x%x).\n", p);
5259 /* We need this opcode so we can detect where alternatives end
5260 in `group_match_null_string_p' et al. */
5262 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5263 goto unconditional_jump;
5266 /* Normally, the on_failure_jump pushes a failure point, which
5267 then gets popped at pop_failure_jump. We will end up at
5268 pop_failure_jump, also, and with a pattern of, say, `a+', we
5269 are skipping over the on_failure_jump, so we have to push
5270 something meaningless for pop_failure_jump to pop. */
5271 case dummy_failure_jump:
5272 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5273 /* It doesn't matter what we push for the string here. What
5274 the code at `fail' tests is the value for the pattern. */
5275 PUSH_FAILURE_POINT (0, 0, -2);
5276 goto unconditional_jump;
5279 /* At the end of an alternative, we need to push a dummy failure
5280 point in case we are followed by a `pop_failure_jump', because
5281 we don't want the failure point for the alternative to be
5282 popped. For example, matching `(a|ab)*' against `aab'
5283 requires that we match the `ab' alternative. */
5284 case push_dummy_failure:
5285 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5286 /* See comments just above at `dummy_failure_jump' about the
5288 PUSH_FAILURE_POINT (0, 0, -2);
5291 /* Have to succeed matching what follows at least n times.
5292 After that, handle like `on_failure_jump'. */
5294 EXTRACT_NUMBER (mcnt, p + 2);
5295 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5298 /* Originally, this is how many times we HAVE to succeed. */
5303 STORE_NUMBER_AND_INCR (p, mcnt);
5304 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
5308 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
5309 p[2] = (unsigned char) no_op;
5310 p[3] = (unsigned char) no_op;
5316 EXTRACT_NUMBER (mcnt, p + 2);
5317 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5319 /* Originally, this is how many times we CAN jump. */
5323 STORE_NUMBER (p + 2, mcnt);
5324 goto unconditional_jump;
5326 /* If don't have to jump any more, skip over the rest of command. */
5333 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5335 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5337 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5338 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
5339 STORE_NUMBER (p1, mcnt);
5344 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5346 /* We SUCCEED in one of the following cases: */
5348 /* Case 1: D is at the beginning or the end of string. */
5349 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5353 /* C1 is the character before D, S1 is the syntax of C1, C2
5354 is the character at D, and S2 is the syntax of C2. */
5356 int pos1 = PTR_TO_OFFSET (d - 1);
5359 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5360 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5362 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5363 UPDATE_SYNTAX_TABLE (charpos);
5367 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5371 if (/* Case 2: Only one of S1 and S2 is Sword. */
5372 ((s1 == Sword) != (s2 == Sword))
5373 /* Case 3: Both of S1 and S2 are Sword, and macro
5374 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5375 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5381 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5383 /* We FAIL in one of the following cases: */
5385 /* Case 1: D is at the beginning or the end of string. */
5386 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5390 /* C1 is the character before D, S1 is the syntax of C1, C2
5391 is the character at D, and S2 is the syntax of C2. */
5393 int pos1 = PTR_TO_OFFSET (d - 1);
5396 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5397 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5399 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5400 UPDATE_SYNTAX_TABLE (charpos);
5404 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5408 if (/* Case 2: Only one of S1 and S2 is Sword. */
5409 ((s1 == Sword) != (s2 == Sword))
5410 /* Case 3: Both of S1 and S2 are Sword, and macro
5411 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5412 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5418 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5420 /* We FAIL in one of the following cases: */
5422 /* Case 1: D is at the end of string. */
5423 if (AT_STRINGS_END (d))
5427 /* C1 is the character before D, S1 is the syntax of C1, C2
5428 is the character at D, and S2 is the syntax of C2. */
5430 int pos1 = PTR_TO_OFFSET (d);
5433 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5435 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5436 UPDATE_SYNTAX_TABLE (charpos);
5440 /* Case 2: S2 is not Sword. */
5444 /* Case 3: D is not at the beginning of string ... */
5445 if (!AT_STRINGS_BEG (d))
5447 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5449 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5453 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5455 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5462 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5464 /* We FAIL in one of the following cases: */
5466 /* Case 1: D is at the beginning of string. */
5467 if (AT_STRINGS_BEG (d))
5471 /* C1 is the character before D, S1 is the syntax of C1, C2
5472 is the character at D, and S2 is the syntax of C2. */
5474 int pos1 = PTR_TO_OFFSET (d);
5477 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5479 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 - 1);
5480 UPDATE_SYNTAX_TABLE (charpos);
5484 /* Case 2: S1 is not Sword. */
5488 /* Case 3: D is not at the end of string ... */
5489 if (!AT_STRINGS_END (d))
5491 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5493 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5497 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5499 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5507 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5508 if (PTR_BYTE_POS ((unsigned char *) d) >= PT_BYTE)
5513 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5514 if (PTR_BYTE_POS ((unsigned char *) d) != PT_BYTE)
5519 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5520 if (PTR_BYTE_POS ((unsigned char *) d) <= PT_BYTE)
5525 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5530 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5536 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5537 UPDATE_SYNTAX_TABLE (pos1);
5544 /* we must concern about multibyte form, ... */
5545 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5547 /* everything should be handled as ASCII, even though it
5548 looks like multibyte form. */
5551 if (SYNTAX (c) != (enum syntaxcode) mcnt)
5555 SET_REGS_MATCHED ();
5559 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5561 goto matchnotsyntax;
5564 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5570 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5571 UPDATE_SYNTAX_TABLE (pos1);
5578 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5582 if (SYNTAX (c) == (enum syntaxcode) mcnt)
5586 SET_REGS_MATCHED ();
5590 DEBUG_PRINT2 ("EXECUTING categoryspec %d.\n", *p);
5597 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5601 if (!CHAR_HAS_CATEGORY (c, mcnt))
5605 SET_REGS_MATCHED ();
5608 case notcategoryspec:
5609 DEBUG_PRINT2 ("EXECUTING notcategoryspec %d.\n", *p);
5616 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5620 if (CHAR_HAS_CATEGORY (c, mcnt))
5624 SET_REGS_MATCHED ();
5627 #else /* not emacs */
5629 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5631 if (!WORDCHAR_P (d))
5633 SET_REGS_MATCHED ();
5638 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5642 SET_REGS_MATCHED ();
5645 #endif /* not emacs */
5650 continue; /* Successfully executed one pattern command; keep going. */
5653 /* We goto here if a matching operation fails. */
5655 if (!FAIL_STACK_EMPTY ())
5656 { /* A restart point is known. Restore to that state. */
5657 DEBUG_PRINT1 ("\nFAIL:\n");
5658 POP_FAILURE_POINT (d, p,
5659 lowest_active_reg, highest_active_reg,
5660 regstart, regend, reg_info);
5662 /* If this failure point is a dummy, try the next one. */
5666 /* If we failed to the end of the pattern, don't examine *p. */
5670 boolean is_a_jump_n = false;
5672 /* If failed to a backwards jump that's part of a repetition
5673 loop, need to pop this failure point and use the next one. */
5674 switch ((re_opcode_t) *p)
5678 case maybe_pop_jump:
5679 case pop_failure_jump:
5682 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5685 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5687 && (re_opcode_t) *p1 == on_failure_jump))
5695 if (d >= string1 && d <= end1)
5699 break; /* Matching at this starting point really fails. */
5703 goto restore_best_regs;
5707 return -1; /* Failure to match. */
5710 /* Subroutine definitions for re_match_2. */
5713 /* We are passed P pointing to a register number after a start_memory.
5715 Return true if the pattern up to the corresponding stop_memory can
5716 match the empty string, and false otherwise.
5718 If we find the matching stop_memory, sets P to point to one past its number.
5719 Otherwise, sets P to an undefined byte less than or equal to END.
5721 We don't handle duplicates properly (yet). */
5724 group_match_null_string_p (p, end, reg_info)
5725 unsigned char **p, *end;
5726 register_info_type *reg_info;
5729 /* Point to after the args to the start_memory. */
5730 unsigned char *p1 = *p + 2;
5734 /* Skip over opcodes that can match nothing, and return true or
5735 false, as appropriate, when we get to one that can't, or to the
5736 matching stop_memory. */
5738 switch ((re_opcode_t) *p1)
5740 /* Could be either a loop or a series of alternatives. */
5741 case on_failure_jump:
5743 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5745 /* If the next operation is not a jump backwards in the
5750 /* Go through the on_failure_jumps of the alternatives,
5751 seeing if any of the alternatives cannot match nothing.
5752 The last alternative starts with only a jump,
5753 whereas the rest start with on_failure_jump and end
5754 with a jump, e.g., here is the pattern for `a|b|c':
5756 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5757 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5760 So, we have to first go through the first (n-1)
5761 alternatives and then deal with the last one separately. */
5764 /* Deal with the first (n-1) alternatives, which start
5765 with an on_failure_jump (see above) that jumps to right
5766 past a jump_past_alt. */
5768 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5770 /* `mcnt' holds how many bytes long the alternative
5771 is, including the ending `jump_past_alt' and
5774 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5778 /* Move to right after this alternative, including the
5782 /* Break if it's the beginning of an n-th alternative
5783 that doesn't begin with an on_failure_jump. */
5784 if ((re_opcode_t) *p1 != on_failure_jump)
5787 /* Still have to check that it's not an n-th
5788 alternative that starts with an on_failure_jump. */
5790 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5791 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5793 /* Get to the beginning of the n-th alternative. */
5799 /* Deal with the last alternative: go back and get number
5800 of the `jump_past_alt' just before it. `mcnt' contains
5801 the length of the alternative. */
5802 EXTRACT_NUMBER (mcnt, p1 - 2);
5804 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5807 p1 += mcnt; /* Get past the n-th alternative. */
5813 assert (p1[1] == **p);
5819 if (!common_op_match_null_string_p (&p1, end, reg_info))
5822 } /* while p1 < end */
5825 } /* group_match_null_string_p */
5828 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5829 It expects P to be the first byte of a single alternative and END one
5830 byte past the last. The alternative can contain groups. */
5833 alt_match_null_string_p (p, end, reg_info)
5834 unsigned char *p, *end;
5835 register_info_type *reg_info;
5838 unsigned char *p1 = p;
5842 /* Skip over opcodes that can match nothing, and break when we get
5843 to one that can't. */
5845 switch ((re_opcode_t) *p1)
5848 case on_failure_jump:
5850 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5855 if (!common_op_match_null_string_p (&p1, end, reg_info))
5858 } /* while p1 < end */
5861 } /* alt_match_null_string_p */
5864 /* Deals with the ops common to group_match_null_string_p and
5865 alt_match_null_string_p.
5867 Sets P to one after the op and its arguments, if any. */
5870 common_op_match_null_string_p (p, end, reg_info)
5871 unsigned char **p, *end;
5872 register_info_type *reg_info;
5877 unsigned char *p1 = *p;
5879 switch ((re_opcode_t) *p1++)
5899 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5900 ret = group_match_null_string_p (&p1, end, reg_info);
5902 /* Have to set this here in case we're checking a group which
5903 contains a group and a back reference to it. */
5905 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5906 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5912 /* If this is an optimized succeed_n for zero times, make the jump. */
5914 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5922 /* Get to the number of times to succeed. */
5924 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5929 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5937 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5945 /* All other opcodes mean we cannot match the empty string. */
5951 } /* common_op_match_null_string_p */
5954 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5955 bytes; nonzero otherwise. */
5958 bcmp_translate (s1, s2, len, translate)
5959 unsigned char *s1, *s2;
5961 RE_TRANSLATE_TYPE translate;
5963 register unsigned char *p1 = s1, *p2 = s2;
5964 unsigned char *p1_end = s1 + len;
5965 unsigned char *p2_end = s2 + len;
5967 while (p1 != p1_end && p2 != p2_end)
5969 int p1_charlen, p2_charlen;
5972 p1_ch = STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5973 p2_ch = STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5975 if (RE_TRANSLATE (translate, p1_ch)
5976 != RE_TRANSLATE (translate, p2_ch))
5979 p1 += p1_charlen, p2 += p2_charlen;
5982 if (p1 != p1_end || p2 != p2_end)
5988 /* Entry points for GNU code. */
5990 /* re_compile_pattern is the GNU regular expression compiler: it
5991 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5992 Returns 0 if the pattern was valid, otherwise an error string.
5994 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5995 are set in BUFP on entry.
5997 We call regex_compile to do the actual compilation. */
6000 re_compile_pattern (pattern, length, bufp)
6001 const char *pattern;
6003 struct re_pattern_buffer *bufp;
6007 /* GNU code is written to assume at least RE_NREGS registers will be set
6008 (and at least one extra will be -1). */
6009 bufp->regs_allocated = REGS_UNALLOCATED;
6011 /* And GNU code determines whether or not to get register information
6012 by passing null for the REGS argument to re_match, etc., not by
6016 /* Match anchors at newline. */
6017 bufp->newline_anchor = 1;
6019 ret = regex_compile (pattern, length, re_syntax_options, bufp);
6023 return gettext (re_error_msgid[(int) ret]);
6026 /* Entry points compatible with 4.2 BSD regex library. We don't define
6027 them unless specifically requested. */
6029 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
6031 /* BSD has one and only one pattern buffer. */
6032 static struct re_pattern_buffer re_comp_buf;
6036 /* Make these definitions weak in libc, so POSIX programs can redefine
6037 these names if they don't use our functions, and still use
6038 regcomp/regexec below without link errors. */
6048 if (!re_comp_buf.buffer)
6049 return gettext ("No previous regular expression");
6053 if (!re_comp_buf.buffer)
6055 re_comp_buf.buffer = (unsigned char *) malloc (200);
6056 if (re_comp_buf.buffer == NULL)
6057 return gettext (re_error_msgid[(int) REG_ESPACE]);
6058 re_comp_buf.allocated = 200;
6060 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6061 if (re_comp_buf.fastmap == NULL)
6062 return gettext (re_error_msgid[(int) REG_ESPACE]);
6065 /* Since `re_exec' always passes NULL for the `regs' argument, we
6066 don't need to initialize the pattern buffer fields which affect it. */
6068 /* Match anchors at newlines. */
6069 re_comp_buf.newline_anchor = 1;
6071 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6076 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6077 return (char *) gettext (re_error_msgid[(int) ret]);
6088 const int len = strlen (s);
6090 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6092 #endif /* _REGEX_RE_COMP */
6094 /* POSIX.2 functions. Don't define these for Emacs. */
6098 /* regcomp takes a regular expression as a string and compiles it.
6100 PREG is a regex_t *. We do not expect any fields to be initialized,
6101 since POSIX says we shouldn't. Thus, we set
6103 `buffer' to the compiled pattern;
6104 `used' to the length of the compiled pattern;
6105 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6106 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6107 RE_SYNTAX_POSIX_BASIC;
6108 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6109 `fastmap' and `fastmap_accurate' to zero;
6110 `re_nsub' to the number of subexpressions in PATTERN.
6112 PATTERN is the address of the pattern string.
6114 CFLAGS is a series of bits which affect compilation.
6116 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6117 use POSIX basic syntax.
6119 If REG_NEWLINE is set, then . and [^...] don't match newline.
6120 Also, regexec will try a match beginning after every newline.
6122 If REG_ICASE is set, then we considers upper- and lowercase
6123 versions of letters to be equivalent when matching.
6125 If REG_NOSUB is set, then when PREG is passed to regexec, that
6126 routine will report only success or failure, and nothing about the
6129 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6130 the return codes and their meanings.) */
6133 regcomp (preg, pattern, cflags)
6135 const char *pattern;
6140 = (cflags & REG_EXTENDED) ?
6141 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6143 /* regex_compile will allocate the space for the compiled pattern. */
6145 preg->allocated = 0;
6148 /* Don't bother to use a fastmap when searching. This simplifies the
6149 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6150 characters after newlines into the fastmap. This way, we just try
6154 if (cflags & REG_ICASE)
6159 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6160 * sizeof (*(RE_TRANSLATE_TYPE)0));
6161 if (preg->translate == NULL)
6162 return (int) REG_ESPACE;
6164 /* Map uppercase characters to corresponding lowercase ones. */
6165 for (i = 0; i < CHAR_SET_SIZE; i++)
6166 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6169 preg->translate = NULL;
6171 /* If REG_NEWLINE is set, newlines are treated differently. */
6172 if (cflags & REG_NEWLINE)
6173 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6174 syntax &= ~RE_DOT_NEWLINE;
6175 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6176 /* It also changes the matching behavior. */
6177 preg->newline_anchor = 1;
6180 preg->newline_anchor = 0;
6182 preg->no_sub = !!(cflags & REG_NOSUB);
6184 /* POSIX says a null character in the pattern terminates it, so we
6185 can use strlen here in compiling the pattern. */
6186 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
6188 /* POSIX doesn't distinguish between an unmatched open-group and an
6189 unmatched close-group: both are REG_EPAREN. */
6190 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6196 /* regexec searches for a given pattern, specified by PREG, in the
6199 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6200 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6201 least NMATCH elements, and we set them to the offsets of the
6202 corresponding matched substrings.
6204 EFLAGS specifies `execution flags' which affect matching: if
6205 REG_NOTBOL is set, then ^ does not match at the beginning of the
6206 string; if REG_NOTEOL is set, then $ does not match at the end.
6208 We return 0 if we find a match and REG_NOMATCH if not. */
6211 regexec (preg, string, nmatch, pmatch, eflags)
6212 const regex_t *preg;
6215 regmatch_t pmatch[];
6219 struct re_registers regs;
6220 regex_t private_preg;
6221 int len = strlen (string);
6222 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6224 private_preg = *preg;
6226 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6227 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6229 /* The user has told us exactly how many registers to return
6230 information about, via `nmatch'. We have to pass that on to the
6231 matching routines. */
6232 private_preg.regs_allocated = REGS_FIXED;
6236 regs.num_regs = nmatch;
6237 regs.start = TALLOC (nmatch, regoff_t);
6238 regs.end = TALLOC (nmatch, regoff_t);
6239 if (regs.start == NULL || regs.end == NULL)
6240 return (int) REG_NOMATCH;
6243 /* Perform the searching operation. */
6244 ret = re_search (&private_preg, string, len,
6245 /* start: */ 0, /* range: */ len,
6246 want_reg_info ? ®s : (struct re_registers *) 0);
6248 /* Copy the register information to the POSIX structure. */
6255 for (r = 0; r < nmatch; r++)
6257 pmatch[r].rm_so = regs.start[r];
6258 pmatch[r].rm_eo = regs.end[r];
6262 /* If we needed the temporary register info, free the space now. */
6267 /* We want zero return to mean success, unlike `re_search'. */
6268 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6272 /* Returns a message corresponding to an error code, ERRCODE, returned
6273 from either regcomp or regexec. We don't use PREG here. */
6276 regerror (errcode, preg, errbuf, errbuf_size)
6278 const regex_t *preg;
6286 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6287 /* Only error codes returned by the rest of the code should be passed
6288 to this routine. If we are given anything else, or if other regex
6289 code generates an invalid error code, then the program has a bug.
6290 Dump core so we can fix it. */
6293 msg = gettext (re_error_msgid[errcode]);
6295 msg_size = strlen (msg) + 1; /* Includes the null. */
6297 if (errbuf_size != 0)
6299 if (msg_size > errbuf_size)
6301 strncpy (errbuf, msg, errbuf_size - 1);
6302 errbuf[errbuf_size - 1] = 0;
6305 strcpy (errbuf, msg);
6312 /* Free dynamically allocated space used by PREG. */
6318 if (preg->buffer != NULL)
6319 free (preg->buffer);
6320 preg->buffer = NULL;
6322 preg->allocated = 0;
6325 if (preg->fastmap != NULL)
6326 free (preg->fastmap);
6327 preg->fastmap = NULL;
6328 preg->fastmap_accurate = 0;
6330 if (preg->translate != NULL)
6331 free (preg->translate);
6332 preg->translate = NULL;
6335 #endif /* not emacs */