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) + 1)
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;
3746 = SYNTAX_TABLE_BYTE_TO_CHAR (startpos > 0 ? startpos : startpos + 1);
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++)])
3814 while (range > lim && !fastmap[(unsigned char) *d++])
3817 startpos += irange - range;
3819 else /* Searching backwards. */
3821 int room = (size1 == 0 || startpos >= size1
3822 ? size2 + size1 - startpos
3823 : size1 - startpos);
3825 buf_ch = STRING_CHAR (d, room);
3826 if (RE_TRANSLATE_P (translate))
3827 buf_ch = RE_TRANSLATE (translate, buf_ch);
3829 if (! (buf_ch >= 0400
3830 || fastmap[buf_ch]))
3835 /* If can't match the null string, and that's all we have left, fail. */
3836 if (range >= 0 && startpos == total_size && fastmap
3837 && !bufp->can_be_null)
3840 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3841 startpos, regs, stop);
3842 #ifndef REGEX_MALLOC
3859 /* Update STARTPOS to the next character boundary. */
3862 const unsigned char *p
3863 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3864 const unsigned char *pend
3865 = (const unsigned char *) STOP_ADDR_VSTRING (startpos);
3866 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
3884 /* Update STARTPOS to the previous character boundary. */
3887 const unsigned char *p
3888 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3891 /* Find the head of multibyte form. */
3892 while (!CHAR_HEAD_P (*p))
3897 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
3914 /* Declarations and macros for re_match_2. */
3916 static int bcmp_translate ();
3917 static boolean alt_match_null_string_p (),
3918 common_op_match_null_string_p (),
3919 group_match_null_string_p ();
3921 /* This converts PTR, a pointer into one of the search strings `string1'
3922 and `string2' into an offset from the beginning of that string. */
3923 #define POINTER_TO_OFFSET(ptr) \
3924 (FIRST_STRING_P (ptr) \
3925 ? ((regoff_t) ((ptr) - string1)) \
3926 : ((regoff_t) ((ptr) - string2 + size1)))
3928 /* Macros for dealing with the split strings in re_match_2. */
3930 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3932 /* Call before fetching a character with *d. This switches over to
3933 string2 if necessary. */
3934 #define PREFETCH() \
3937 /* End of string2 => fail. */ \
3938 if (dend == end_match_2) \
3940 /* End of string1 => advance to string2. */ \
3942 dend = end_match_2; \
3946 /* Test if at very beginning or at very end of the virtual concatenation
3947 of `string1' and `string2'. If only one string, it's `string2'. */
3948 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3949 #define AT_STRINGS_END(d) ((d) == end2)
3952 /* Test if D points to a character which is word-constituent. We have
3953 two special cases to check for: if past the end of string1, look at
3954 the first character in string2; and if before the beginning of
3955 string2, look at the last character in string1. */
3956 #define WORDCHAR_P(d) \
3957 (SYNTAX ((d) == end1 ? *string2 \
3958 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3961 /* Disabled due to a compiler bug -- see comment at case wordbound */
3963 /* The comment at case wordbound is following one, but we don't use
3964 AT_WORD_BOUNDARY anymore to support multibyte form.
3966 The DEC Alpha C compiler 3.x generates incorrect code for the
3967 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
3968 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
3969 macro and introducing temporary variables works around the bug. */
3972 /* Test if the character before D and the one at D differ with respect
3973 to being word-constituent. */
3974 #define AT_WORD_BOUNDARY(d) \
3975 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3976 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3979 /* Free everything we malloc. */
3980 #ifdef MATCH_MAY_ALLOCATE
3981 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
3982 #define FREE_VARIABLES() \
3984 REGEX_FREE_STACK (fail_stack.stack); \
3985 FREE_VAR (regstart); \
3986 FREE_VAR (regend); \
3987 FREE_VAR (old_regstart); \
3988 FREE_VAR (old_regend); \
3989 FREE_VAR (best_regstart); \
3990 FREE_VAR (best_regend); \
3991 FREE_VAR (reg_info); \
3992 FREE_VAR (reg_dummy); \
3993 FREE_VAR (reg_info_dummy); \
3996 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
3997 #endif /* not MATCH_MAY_ALLOCATE */
3999 /* These values must meet several constraints. They must not be valid
4000 register values; since we have a limit of 255 registers (because
4001 we use only one byte in the pattern for the register number), we can
4002 use numbers larger than 255. They must differ by 1, because of
4003 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4004 be larger than the value for the highest register, so we do not try
4005 to actually save any registers when none are active. */
4006 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4007 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4009 /* Matching routines. */
4011 #ifndef emacs /* Emacs never uses this. */
4012 /* re_match is like re_match_2 except it takes only a single string. */
4015 re_match (bufp, string, size, pos, regs)
4016 struct re_pattern_buffer *bufp;
4019 struct re_registers *regs;
4021 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4026 #endif /* not emacs */
4029 /* In Emacs, this is the string or buffer in which we
4030 are matching. It is used for looking up syntax properties. */
4031 Lisp_Object re_match_object;
4034 /* re_match_2 matches the compiled pattern in BUFP against the
4035 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4036 and SIZE2, respectively). We start matching at POS, and stop
4039 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4040 store offsets for the substring each group matched in REGS. See the
4041 documentation for exactly how many groups we fill.
4043 We return -1 if no match, -2 if an internal error (such as the
4044 failure stack overflowing). Otherwise, we return the length of the
4045 matched substring. */
4048 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4049 struct re_pattern_buffer *bufp;
4050 const char *string1, *string2;
4053 struct re_registers *regs;
4060 gl_state.object = re_match_object;
4061 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4062 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4065 result = re_match_2_internal (bufp, string1, size1, string2, size2,
4071 /* This is a separate function so that we can force an alloca cleanup
4074 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4075 struct re_pattern_buffer *bufp;
4076 const char *string1, *string2;
4079 struct re_registers *regs;
4082 /* General temporaries. */
4086 /* Just past the end of the corresponding string. */
4087 const char *end1, *end2;
4089 /* Pointers into string1 and string2, just past the last characters in
4090 each to consider matching. */
4091 const char *end_match_1, *end_match_2;
4093 /* Where we are in the data, and the end of the current string. */
4094 const char *d, *dend;
4096 /* Where we are in the pattern, and the end of the pattern. */
4097 unsigned char *p = bufp->buffer;
4098 register unsigned char *pend = p + bufp->used;
4100 /* Mark the opcode just after a start_memory, so we can test for an
4101 empty subpattern when we get to the stop_memory. */
4102 unsigned char *just_past_start_mem = 0;
4104 /* We use this to map every character in the string. */
4105 RE_TRANSLATE_TYPE translate = bufp->translate;
4107 /* Nonzero if we have to concern multibyte character. */
4108 int multibyte = bufp->multibyte;
4110 /* Failure point stack. Each place that can handle a failure further
4111 down the line pushes a failure point on this stack. It consists of
4112 restart, regend, and reg_info for all registers corresponding to
4113 the subexpressions we're currently inside, plus the number of such
4114 registers, and, finally, two char *'s. The first char * is where
4115 to resume scanning the pattern; the second one is where to resume
4116 scanning the strings. If the latter is zero, the failure point is
4117 a ``dummy''; if a failure happens and the failure point is a dummy,
4118 it gets discarded and the next next one is tried. */
4119 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4120 fail_stack_type fail_stack;
4123 static unsigned failure_id = 0;
4124 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4127 /* This holds the pointer to the failure stack, when
4128 it is allocated relocatably. */
4129 fail_stack_elt_t *failure_stack_ptr;
4131 /* We fill all the registers internally, independent of what we
4132 return, for use in backreferences. The number here includes
4133 an element for register zero. */
4134 unsigned num_regs = bufp->re_nsub + 1;
4136 /* The currently active registers. */
4137 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4138 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4140 /* Information on the contents of registers. These are pointers into
4141 the input strings; they record just what was matched (on this
4142 attempt) by a subexpression part of the pattern, that is, the
4143 regnum-th regstart pointer points to where in the pattern we began
4144 matching and the regnum-th regend points to right after where we
4145 stopped matching the regnum-th subexpression. (The zeroth register
4146 keeps track of what the whole pattern matches.) */
4147 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4148 const char **regstart, **regend;
4151 /* If a group that's operated upon by a repetition operator fails to
4152 match anything, then the register for its start will need to be
4153 restored because it will have been set to wherever in the string we
4154 are when we last see its open-group operator. Similarly for a
4156 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4157 const char **old_regstart, **old_regend;
4160 /* The is_active field of reg_info helps us keep track of which (possibly
4161 nested) subexpressions we are currently in. The matched_something
4162 field of reg_info[reg_num] helps us tell whether or not we have
4163 matched any of the pattern so far this time through the reg_num-th
4164 subexpression. These two fields get reset each time through any
4165 loop their register is in. */
4166 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4167 register_info_type *reg_info;
4170 /* The following record the register info as found in the above
4171 variables when we find a match better than any we've seen before.
4172 This happens as we backtrack through the failure points, which in
4173 turn happens only if we have not yet matched the entire string. */
4174 unsigned best_regs_set = false;
4175 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4176 const char **best_regstart, **best_regend;
4179 /* Logically, this is `best_regend[0]'. But we don't want to have to
4180 allocate space for that if we're not allocating space for anything
4181 else (see below). Also, we never need info about register 0 for
4182 any of the other register vectors, and it seems rather a kludge to
4183 treat `best_regend' differently than the rest. So we keep track of
4184 the end of the best match so far in a separate variable. We
4185 initialize this to NULL so that when we backtrack the first time
4186 and need to test it, it's not garbage. */
4187 const char *match_end = NULL;
4189 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4190 int set_regs_matched_done = 0;
4192 /* Used when we pop values we don't care about. */
4193 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4194 const char **reg_dummy;
4195 register_info_type *reg_info_dummy;
4199 /* Counts the total number of registers pushed. */
4200 unsigned num_regs_pushed = 0;
4203 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4207 #ifdef MATCH_MAY_ALLOCATE
4208 /* Do not bother to initialize all the register variables if there are
4209 no groups in the pattern, as it takes a fair amount of time. If
4210 there are groups, we include space for register 0 (the whole
4211 pattern), even though we never use it, since it simplifies the
4212 array indexing. We should fix this. */
4215 regstart = REGEX_TALLOC (num_regs, const char *);
4216 regend = REGEX_TALLOC (num_regs, const char *);
4217 old_regstart = REGEX_TALLOC (num_regs, const char *);
4218 old_regend = REGEX_TALLOC (num_regs, const char *);
4219 best_regstart = REGEX_TALLOC (num_regs, const char *);
4220 best_regend = REGEX_TALLOC (num_regs, const char *);
4221 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4222 reg_dummy = REGEX_TALLOC (num_regs, const char *);
4223 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4225 if (!(regstart && regend && old_regstart && old_regend && reg_info
4226 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4234 /* We must initialize all our variables to NULL, so that
4235 `FREE_VARIABLES' doesn't try to free them. */
4236 regstart = regend = old_regstart = old_regend = best_regstart
4237 = best_regend = reg_dummy = NULL;
4238 reg_info = reg_info_dummy = (register_info_type *) NULL;
4240 #endif /* MATCH_MAY_ALLOCATE */
4242 /* The starting position is bogus. */
4243 if (pos < 0 || pos > size1 + size2)
4249 /* Initialize subexpression text positions to -1 to mark ones that no
4250 start_memory/stop_memory has been seen for. Also initialize the
4251 register information struct. */
4252 for (mcnt = 1; mcnt < num_regs; mcnt++)
4254 regstart[mcnt] = regend[mcnt]
4255 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4257 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4258 IS_ACTIVE (reg_info[mcnt]) = 0;
4259 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4260 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4263 /* We move `string1' into `string2' if the latter's empty -- but not if
4264 `string1' is null. */
4265 if (size2 == 0 && string1 != NULL)
4272 end1 = string1 + size1;
4273 end2 = string2 + size2;
4275 /* Compute where to stop matching, within the two strings. */
4278 end_match_1 = string1 + stop;
4279 end_match_2 = string2;
4284 end_match_2 = string2 + stop - size1;
4287 /* `p' scans through the pattern as `d' scans through the data.
4288 `dend' is the end of the input string that `d' points within. `d'
4289 is advanced into the following input string whenever necessary, but
4290 this happens before fetching; therefore, at the beginning of the
4291 loop, `d' can be pointing at the end of a string, but it cannot
4293 if (size1 > 0 && pos <= size1)
4300 d = string2 + pos - size1;
4304 DEBUG_PRINT1 ("The compiled pattern is: ");
4305 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4306 DEBUG_PRINT1 ("The string to match is: `");
4307 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4308 DEBUG_PRINT1 ("'\n");
4310 /* This loops over pattern commands. It exits by returning from the
4311 function if the match is complete, or it drops through if the match
4312 fails at this starting point in the input data. */
4315 DEBUG_PRINT2 ("\n0x%x: ", p);
4318 { /* End of pattern means we might have succeeded. */
4319 DEBUG_PRINT1 ("end of pattern ... ");
4321 /* If we haven't matched the entire string, and we want the
4322 longest match, try backtracking. */
4323 if (d != end_match_2)
4325 /* 1 if this match ends in the same string (string1 or string2)
4326 as the best previous match. */
4327 boolean same_str_p = (FIRST_STRING_P (match_end)
4328 == MATCHING_IN_FIRST_STRING);
4329 /* 1 if this match is the best seen so far. */
4330 boolean best_match_p;
4332 /* AIX compiler got confused when this was combined
4333 with the previous declaration. */
4335 best_match_p = d > match_end;
4337 best_match_p = !MATCHING_IN_FIRST_STRING;
4339 DEBUG_PRINT1 ("backtracking.\n");
4341 if (!FAIL_STACK_EMPTY ())
4342 { /* More failure points to try. */
4344 /* If exceeds best match so far, save it. */
4345 if (!best_regs_set || best_match_p)
4347 best_regs_set = true;
4350 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4352 for (mcnt = 1; mcnt < num_regs; mcnt++)
4354 best_regstart[mcnt] = regstart[mcnt];
4355 best_regend[mcnt] = regend[mcnt];
4361 /* If no failure points, don't restore garbage. And if
4362 last match is real best match, don't restore second
4364 else if (best_regs_set && !best_match_p)
4367 /* Restore best match. It may happen that `dend ==
4368 end_match_1' while the restored d is in string2.
4369 For example, the pattern `x.*y.*z' against the
4370 strings `x-' and `y-z-', if the two strings are
4371 not consecutive in memory. */
4372 DEBUG_PRINT1 ("Restoring best registers.\n");
4375 dend = ((d >= string1 && d <= end1)
4376 ? end_match_1 : end_match_2);
4378 for (mcnt = 1; mcnt < num_regs; mcnt++)
4380 regstart[mcnt] = best_regstart[mcnt];
4381 regend[mcnt] = best_regend[mcnt];
4384 } /* d != end_match_2 */
4387 DEBUG_PRINT1 ("Accepting match.\n");
4389 /* If caller wants register contents data back, do it. */
4390 if (regs && !bufp->no_sub)
4392 /* Have the register data arrays been allocated? */
4393 if (bufp->regs_allocated == REGS_UNALLOCATED)
4394 { /* No. So allocate them with malloc. We need one
4395 extra element beyond `num_regs' for the `-1' marker
4397 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4398 regs->start = TALLOC (regs->num_regs, regoff_t);
4399 regs->end = TALLOC (regs->num_regs, regoff_t);
4400 if (regs->start == NULL || regs->end == NULL)
4405 bufp->regs_allocated = REGS_REALLOCATE;
4407 else if (bufp->regs_allocated == REGS_REALLOCATE)
4408 { /* Yes. If we need more elements than were already
4409 allocated, reallocate them. If we need fewer, just
4411 if (regs->num_regs < num_regs + 1)
4413 regs->num_regs = num_regs + 1;
4414 RETALLOC (regs->start, regs->num_regs, regoff_t);
4415 RETALLOC (regs->end, regs->num_regs, regoff_t);
4416 if (regs->start == NULL || regs->end == NULL)
4425 /* These braces fend off a "empty body in an else-statement"
4426 warning under GCC when assert expands to nothing. */
4427 assert (bufp->regs_allocated == REGS_FIXED);
4430 /* Convert the pointer data in `regstart' and `regend' to
4431 indices. Register zero has to be set differently,
4432 since we haven't kept track of any info for it. */
4433 if (regs->num_regs > 0)
4435 regs->start[0] = pos;
4436 regs->end[0] = (MATCHING_IN_FIRST_STRING
4437 ? ((regoff_t) (d - string1))
4438 : ((regoff_t) (d - string2 + size1)));
4441 /* Go through the first `min (num_regs, regs->num_regs)'
4442 registers, since that is all we initialized. */
4443 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4445 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4446 regs->start[mcnt] = regs->end[mcnt] = -1;
4450 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4452 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4456 /* If the regs structure we return has more elements than
4457 were in the pattern, set the extra elements to -1. If
4458 we (re)allocated the registers, this is the case,
4459 because we always allocate enough to have at least one
4461 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4462 regs->start[mcnt] = regs->end[mcnt] = -1;
4463 } /* regs && !bufp->no_sub */
4465 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4466 nfailure_points_pushed, nfailure_points_popped,
4467 nfailure_points_pushed - nfailure_points_popped);
4468 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4470 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4474 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4480 /* Otherwise match next pattern command. */
4481 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4483 /* Ignore these. Used to ignore the n of succeed_n's which
4484 currently have n == 0. */
4486 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4490 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4493 /* Match the next n pattern characters exactly. The following
4494 byte in the pattern defines n, and the n bytes after that
4495 are the characters to match. */
4498 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4500 /* This is written out as an if-else so we don't waste time
4501 testing `translate' inside the loop. */
4502 if (RE_TRANSLATE_P (translate))
4508 int pat_charlen, buf_charlen;
4509 unsigned int pat_ch, buf_ch;
4512 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
4513 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4515 if (RE_TRANSLATE (translate, buf_ch)
4521 mcnt -= pat_charlen;
4525 #endif /* not emacs */
4529 if ((unsigned char) RE_TRANSLATE (translate, (unsigned char) *d++)
4530 != (unsigned char) *p++)
4540 if (*d++ != (char) *p++) goto fail;
4544 SET_REGS_MATCHED ();
4548 /* Match any character except possibly a newline or a null. */
4552 unsigned int buf_ch;
4554 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4560 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4562 #endif /* not emacs */
4564 buf_ch = (unsigned char) *d;
4568 buf_ch = TRANSLATE (buf_ch);
4570 if ((!(bufp->syntax & RE_DOT_NEWLINE)
4572 || ((bufp->syntax & RE_DOT_NOT_NULL)
4573 && buf_ch == '\000'))
4576 SET_REGS_MATCHED ();
4577 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4586 register unsigned int c;
4587 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4590 /* Start of actual range_table, or end of bitmap if there is no
4592 unsigned char *range_table;
4594 /* Nonzero if there is range table. */
4595 int range_table_exists;
4597 /* Number of ranges of range table. Not in bytes. */
4600 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4603 c = (unsigned char) *d;
4605 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
4606 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
4607 if (range_table_exists)
4608 EXTRACT_NUMBER_AND_INCR (count, range_table);
4612 if (multibyte && BASE_LEADING_CODE_P (c))
4613 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
4615 if (SINGLE_BYTE_CHAR_P (c))
4616 { /* Lookup bitmap. */
4617 c = TRANSLATE (c); /* The character to match. */
4620 /* Cast to `unsigned' instead of `unsigned char' in
4621 case the bit list is a full 32 bytes long. */
4622 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
4623 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4626 else if (range_table_exists)
4627 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
4629 p = CHARSET_RANGE_TABLE_END (range_table, count);
4631 if (!not) goto fail;
4633 SET_REGS_MATCHED ();
4639 /* The beginning of a group is represented by start_memory.
4640 The arguments are the register number in the next byte, and the
4641 number of groups inner to this one in the next. The text
4642 matched within the group is recorded (in the internal
4643 registers data structure) under the register number. */
4645 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4647 /* Find out if this group can match the empty string. */
4648 p1 = p; /* To send to group_match_null_string_p. */
4650 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4651 REG_MATCH_NULL_STRING_P (reg_info[*p])
4652 = group_match_null_string_p (&p1, pend, reg_info);
4654 /* Save the position in the string where we were the last time
4655 we were at this open-group operator in case the group is
4656 operated upon by a repetition operator, e.g., with `(a*)*b'
4657 against `ab'; then we want to ignore where we are now in
4658 the string in case this attempt to match fails. */
4659 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4660 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4662 DEBUG_PRINT2 (" old_regstart: %d\n",
4663 POINTER_TO_OFFSET (old_regstart[*p]));
4666 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4668 IS_ACTIVE (reg_info[*p]) = 1;
4669 MATCHED_SOMETHING (reg_info[*p]) = 0;
4671 /* Clear this whenever we change the register activity status. */
4672 set_regs_matched_done = 0;
4674 /* This is the new highest active register. */
4675 highest_active_reg = *p;
4677 /* If nothing was active before, this is the new lowest active
4679 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4680 lowest_active_reg = *p;
4682 /* Move past the register number and inner group count. */
4684 just_past_start_mem = p;
4689 /* The stop_memory opcode represents the end of a group. Its
4690 arguments are the same as start_memory's: the register
4691 number, and the number of inner groups. */
4693 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4695 /* We need to save the string position the last time we were at
4696 this close-group operator in case the group is operated
4697 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4698 against `aba'; then we want to ignore where we are now in
4699 the string in case this attempt to match fails. */
4700 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4701 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4703 DEBUG_PRINT2 (" old_regend: %d\n",
4704 POINTER_TO_OFFSET (old_regend[*p]));
4707 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4709 /* This register isn't active anymore. */
4710 IS_ACTIVE (reg_info[*p]) = 0;
4712 /* Clear this whenever we change the register activity status. */
4713 set_regs_matched_done = 0;
4715 /* If this was the only register active, nothing is active
4717 if (lowest_active_reg == highest_active_reg)
4719 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4720 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4723 { /* We must scan for the new highest active register, since
4724 it isn't necessarily one less than now: consider
4725 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4726 new highest active register is 1. */
4727 unsigned char r = *p - 1;
4728 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4731 /* If we end up at register zero, that means that we saved
4732 the registers as the result of an `on_failure_jump', not
4733 a `start_memory', and we jumped to past the innermost
4734 `stop_memory'. For example, in ((.)*) we save
4735 registers 1 and 2 as a result of the *, but when we pop
4736 back to the second ), we are at the stop_memory 1.
4737 Thus, nothing is active. */
4740 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4741 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4744 highest_active_reg = r;
4747 /* If just failed to match something this time around with a
4748 group that's operated on by a repetition operator, try to
4749 force exit from the ``loop'', and restore the register
4750 information for this group that we had before trying this
4752 if ((!MATCHED_SOMETHING (reg_info[*p])
4753 || just_past_start_mem == p - 1)
4756 boolean is_a_jump_n = false;
4760 switch ((re_opcode_t) *p1++)
4764 case pop_failure_jump:
4765 case maybe_pop_jump:
4767 case dummy_failure_jump:
4768 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4778 /* If the next operation is a jump backwards in the pattern
4779 to an on_failure_jump right before the start_memory
4780 corresponding to this stop_memory, exit from the loop
4781 by forcing a failure after pushing on the stack the
4782 on_failure_jump's jump in the pattern, and d. */
4783 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4784 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4786 /* If this group ever matched anything, then restore
4787 what its registers were before trying this last
4788 failed match, e.g., with `(a*)*b' against `ab' for
4789 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4790 against `aba' for regend[3].
4792 Also restore the registers for inner groups for,
4793 e.g., `((a*)(b*))*' against `aba' (register 3 would
4794 otherwise get trashed). */
4796 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4800 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4802 /* Restore this and inner groups' (if any) registers. */
4803 for (r = *p; r < *p + *(p + 1); r++)
4805 regstart[r] = old_regstart[r];
4807 /* xx why this test? */
4808 if (old_regend[r] >= regstart[r])
4809 regend[r] = old_regend[r];
4813 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4814 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4820 /* Move past the register number and the inner group count. */
4825 /* \<digit> has been turned into a `duplicate' command which is
4826 followed by the numeric value of <digit> as the register number. */
4829 register const char *d2, *dend2;
4830 int regno = *p++; /* Get which register to match against. */
4831 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4833 /* Can't back reference a group which we've never matched. */
4834 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4837 /* Where in input to try to start matching. */
4838 d2 = regstart[regno];
4840 /* Where to stop matching; if both the place to start and
4841 the place to stop matching are in the same string, then
4842 set to the place to stop, otherwise, for now have to use
4843 the end of the first string. */
4845 dend2 = ((FIRST_STRING_P (regstart[regno])
4846 == FIRST_STRING_P (regend[regno]))
4847 ? regend[regno] : end_match_1);
4850 /* If necessary, advance to next segment in register
4854 if (dend2 == end_match_2) break;
4855 if (dend2 == regend[regno]) break;
4857 /* End of string1 => advance to string2. */
4859 dend2 = regend[regno];
4861 /* At end of register contents => success */
4862 if (d2 == dend2) break;
4864 /* If necessary, advance to next segment in data. */
4867 /* How many characters left in this segment to match. */
4870 /* Want how many consecutive characters we can match in
4871 one shot, so, if necessary, adjust the count. */
4872 if (mcnt > dend2 - d2)
4875 /* Compare that many; failure if mismatch, else move
4877 if (RE_TRANSLATE_P (translate)
4878 ? bcmp_translate (d, d2, mcnt, translate)
4879 : bcmp (d, d2, mcnt))
4881 d += mcnt, d2 += mcnt;
4883 /* Do this because we've match some characters. */
4884 SET_REGS_MATCHED ();
4890 /* begline matches the empty string at the beginning of the string
4891 (unless `not_bol' is set in `bufp'), and, if
4892 `newline_anchor' is set, after newlines. */
4894 DEBUG_PRINT1 ("EXECUTING begline.\n");
4896 if (AT_STRINGS_BEG (d))
4898 if (!bufp->not_bol) break;
4900 else if (d[-1] == '\n' && bufp->newline_anchor)
4904 /* In all other cases, we fail. */
4908 /* endline is the dual of begline. */
4910 DEBUG_PRINT1 ("EXECUTING endline.\n");
4912 if (AT_STRINGS_END (d))
4914 if (!bufp->not_eol) break;
4917 /* We have to ``prefetch'' the next character. */
4918 else if ((d == end1 ? *string2 : *d) == '\n'
4919 && bufp->newline_anchor)
4926 /* Match at the very beginning of the data. */
4928 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4929 if (AT_STRINGS_BEG (d))
4934 /* Match at the very end of the data. */
4936 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4937 if (AT_STRINGS_END (d))
4942 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4943 pushes NULL as the value for the string on the stack. Then
4944 `pop_failure_point' will keep the current value for the
4945 string, instead of restoring it. To see why, consider
4946 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4947 then the . fails against the \n. But the next thing we want
4948 to do is match the \n against the \n; if we restored the
4949 string value, we would be back at the foo.
4951 Because this is used only in specific cases, we don't need to
4952 check all the things that `on_failure_jump' does, to make
4953 sure the right things get saved on the stack. Hence we don't
4954 share its code. The only reason to push anything on the
4955 stack at all is that otherwise we would have to change
4956 `anychar's code to do something besides goto fail in this
4957 case; that seems worse than this. */
4958 case on_failure_keep_string_jump:
4959 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4961 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4962 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4964 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4968 /* Uses of on_failure_jump:
4970 Each alternative starts with an on_failure_jump that points
4971 to the beginning of the next alternative. Each alternative
4972 except the last ends with a jump that in effect jumps past
4973 the rest of the alternatives. (They really jump to the
4974 ending jump of the following alternative, because tensioning
4975 these jumps is a hassle.)
4977 Repeats start with an on_failure_jump that points past both
4978 the repetition text and either the following jump or
4979 pop_failure_jump back to this on_failure_jump. */
4980 case on_failure_jump:
4982 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4984 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4985 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4987 /* If this on_failure_jump comes right before a group (i.e.,
4988 the original * applied to a group), save the information
4989 for that group and all inner ones, so that if we fail back
4990 to this point, the group's information will be correct.
4991 For example, in \(a*\)*\1, we need the preceding group,
4992 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4994 /* We can't use `p' to check ahead because we push
4995 a failure point to `p + mcnt' after we do this. */
4998 /* We need to skip no_op's before we look for the
4999 start_memory in case this on_failure_jump is happening as
5000 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5002 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5005 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5007 /* We have a new highest active register now. This will
5008 get reset at the start_memory we are about to get to,
5009 but we will have saved all the registers relevant to
5010 this repetition op, as described above. */
5011 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5012 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5013 lowest_active_reg = *(p1 + 1);
5016 DEBUG_PRINT1 (":\n");
5017 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5021 /* A smart repeat ends with `maybe_pop_jump'.
5022 We change it to either `pop_failure_jump' or `jump'. */
5023 case maybe_pop_jump:
5024 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5025 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5027 register unsigned char *p2 = p;
5029 /* Compare the beginning of the repeat with what in the
5030 pattern follows its end. If we can establish that there
5031 is nothing that they would both match, i.e., that we
5032 would have to backtrack because of (as in, e.g., `a*a')
5033 then we can change to pop_failure_jump, because we'll
5034 never have to backtrack.
5036 This is not true in the case of alternatives: in
5037 `(a|ab)*' we do need to backtrack to the `ab' alternative
5038 (e.g., if the string was `ab'). But instead of trying to
5039 detect that here, the alternative has put on a dummy
5040 failure point which is what we will end up popping. */
5042 /* Skip over open/close-group commands.
5043 If what follows this loop is a ...+ construct,
5044 look at what begins its body, since we will have to
5045 match at least one of that. */
5049 && ((re_opcode_t) *p2 == stop_memory
5050 || (re_opcode_t) *p2 == start_memory))
5052 else if (p2 + 6 < pend
5053 && (re_opcode_t) *p2 == dummy_failure_jump)
5060 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5061 to the `maybe_finalize_jump' of this case. Examine what
5064 /* If we're at the end of the pattern, we can change. */
5067 /* Consider what happens when matching ":\(.*\)"
5068 against ":/". I don't really understand this code
5070 p[-3] = (unsigned char) pop_failure_jump;
5072 (" End of pattern: change to `pop_failure_jump'.\n");
5075 else if ((re_opcode_t) *p2 == exactn
5076 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5078 register unsigned int c
5079 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5081 if ((re_opcode_t) p1[3] == exactn)
5083 if (!(multibyte /* && (c != '\n') */
5084 && BASE_LEADING_CODE_P (c))
5086 : (STRING_CHAR (&p2[2], pend - &p2[2])
5087 != STRING_CHAR (&p1[5], pend - &p1[5])))
5089 p[-3] = (unsigned char) pop_failure_jump;
5090 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5095 else if ((re_opcode_t) p1[3] == charset
5096 || (re_opcode_t) p1[3] == charset_not)
5098 int not = (re_opcode_t) p1[3] == charset_not;
5100 if (multibyte /* && (c != '\n') */
5101 && BASE_LEADING_CODE_P (c))
5102 c = STRING_CHAR (&p2[2], pend - &p2[2]);
5104 /* Test if C is listed in charset (or charset_not)
5106 if (SINGLE_BYTE_CHAR_P (c))
5108 if (c < CHARSET_BITMAP_SIZE (&p1[3]) * BYTEWIDTH
5109 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5112 else if (CHARSET_RANGE_TABLE_EXISTS_P (&p1[3]))
5113 CHARSET_LOOKUP_RANGE_TABLE (not, c, &p1[3]);
5115 /* `not' is equal to 1 if c would match, which means
5116 that we can't change to pop_failure_jump. */
5119 p[-3] = (unsigned char) pop_failure_jump;
5120 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5124 else if ((re_opcode_t) *p2 == charset)
5126 if ((re_opcode_t) p1[3] == exactn)
5128 register unsigned int c = p1[5];
5131 if (multibyte && BASE_LEADING_CODE_P (c))
5132 c = STRING_CHAR (&p1[5], pend - &p1[5]);
5134 /* Test if C is listed in charset at `p2'. */
5135 if (SINGLE_BYTE_CHAR_P (c))
5137 if (c < CHARSET_BITMAP_SIZE (p2) * BYTEWIDTH
5138 && (p2[2 + c / BYTEWIDTH]
5139 & (1 << (c % BYTEWIDTH))))
5142 else if (CHARSET_RANGE_TABLE_EXISTS_P (p2))
5143 CHARSET_LOOKUP_RANGE_TABLE (not, c, p2);
5147 p[-3] = (unsigned char) pop_failure_jump;
5148 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5152 /* It is hard to list up all the character in charset
5153 P2 if it includes multibyte character. Give up in
5155 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
5157 /* Now, we are sure that P2 has no range table.
5158 So, for the size of bitmap in P2, `p2[1]' is
5159 enough. But P1 may have range table, so the
5160 size of bitmap table of P1 is extracted by
5161 using macro `CHARSET_BITMAP_SIZE'.
5163 Since we know that all the character listed in
5164 P2 is ASCII, it is enough to test only bitmap
5167 if ((re_opcode_t) p1[3] == charset_not)
5170 /* We win if the charset_not inside the loop lists
5171 every character listed in the charset after. */
5172 for (idx = 0; idx < (int) p2[1]; idx++)
5173 if (! (p2[2 + idx] == 0
5174 || (idx < CHARSET_BITMAP_SIZE (&p1[3])
5175 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5180 p[-3] = (unsigned char) pop_failure_jump;
5181 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5184 else if ((re_opcode_t) p1[3] == charset)
5187 /* We win if the charset inside the loop
5188 has no overlap with the one after the loop. */
5191 && idx < CHARSET_BITMAP_SIZE (&p1[3]));
5193 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5197 || idx == CHARSET_BITMAP_SIZE (&p1[3]))
5199 p[-3] = (unsigned char) pop_failure_jump;
5200 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5206 p -= 2; /* Point at relative address again. */
5207 if ((re_opcode_t) p[-1] != pop_failure_jump)
5209 p[-1] = (unsigned char) jump;
5210 DEBUG_PRINT1 (" Match => jump.\n");
5211 goto unconditional_jump;
5213 /* Note fall through. */
5216 /* The end of a simple repeat has a pop_failure_jump back to
5217 its matching on_failure_jump, where the latter will push a
5218 failure point. The pop_failure_jump takes off failure
5219 points put on by this pop_failure_jump's matching
5220 on_failure_jump; we got through the pattern to here from the
5221 matching on_failure_jump, so didn't fail. */
5222 case pop_failure_jump:
5224 /* We need to pass separate storage for the lowest and
5225 highest registers, even though we don't care about the
5226 actual values. Otherwise, we will restore only one
5227 register from the stack, since lowest will == highest in
5228 `pop_failure_point'. */
5229 unsigned dummy_low_reg, dummy_high_reg;
5230 unsigned char *pdummy;
5233 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5234 POP_FAILURE_POINT (sdummy, pdummy,
5235 dummy_low_reg, dummy_high_reg,
5236 reg_dummy, reg_dummy, reg_info_dummy);
5238 /* Note fall through. */
5241 /* Unconditionally jump (without popping any failure points). */
5244 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5245 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5246 p += mcnt; /* Do the jump. */
5247 DEBUG_PRINT2 ("(to 0x%x).\n", p);
5251 /* We need this opcode so we can detect where alternatives end
5252 in `group_match_null_string_p' et al. */
5254 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5255 goto unconditional_jump;
5258 /* Normally, the on_failure_jump pushes a failure point, which
5259 then gets popped at pop_failure_jump. We will end up at
5260 pop_failure_jump, also, and with a pattern of, say, `a+', we
5261 are skipping over the on_failure_jump, so we have to push
5262 something meaningless for pop_failure_jump to pop. */
5263 case dummy_failure_jump:
5264 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5265 /* It doesn't matter what we push for the string here. What
5266 the code at `fail' tests is the value for the pattern. */
5267 PUSH_FAILURE_POINT (0, 0, -2);
5268 goto unconditional_jump;
5271 /* At the end of an alternative, we need to push a dummy failure
5272 point in case we are followed by a `pop_failure_jump', because
5273 we don't want the failure point for the alternative to be
5274 popped. For example, matching `(a|ab)*' against `aab'
5275 requires that we match the `ab' alternative. */
5276 case push_dummy_failure:
5277 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5278 /* See comments just above at `dummy_failure_jump' about the
5280 PUSH_FAILURE_POINT (0, 0, -2);
5283 /* Have to succeed matching what follows at least n times.
5284 After that, handle like `on_failure_jump'. */
5286 EXTRACT_NUMBER (mcnt, p + 2);
5287 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5290 /* Originally, this is how many times we HAVE to succeed. */
5295 STORE_NUMBER_AND_INCR (p, mcnt);
5296 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
5300 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
5301 p[2] = (unsigned char) no_op;
5302 p[3] = (unsigned char) no_op;
5308 EXTRACT_NUMBER (mcnt, p + 2);
5309 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5311 /* Originally, this is how many times we CAN jump. */
5315 STORE_NUMBER (p + 2, mcnt);
5316 goto unconditional_jump;
5318 /* If don't have to jump any more, skip over the rest of command. */
5325 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5327 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5329 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5330 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
5331 STORE_NUMBER (p1, mcnt);
5336 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5338 /* We SUCCEED in one of the following cases: */
5340 /* Case 1: D is at the beginning or the end of string. */
5341 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5345 /* C1 is the character before D, S1 is the syntax of C1, C2
5346 is the character at D, and S2 is the syntax of C2. */
5348 int pos1 = PTR_TO_OFFSET (d - 1);
5351 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5352 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5354 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 ? pos1 : 1);
5355 UPDATE_SYNTAX_TABLE (charpos);
5359 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5363 if (/* Case 2: Only one of S1 and S2 is Sword. */
5364 ((s1 == Sword) != (s2 == Sword))
5365 /* Case 3: Both of S1 and S2 are Sword, and macro
5366 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5367 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5373 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5375 /* We FAIL in one of the following cases: */
5377 /* Case 1: D is at the beginning or the end of string. */
5378 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5382 /* C1 is the character before D, S1 is the syntax of C1, C2
5383 is the character at D, and S2 is the syntax of C2. */
5385 int pos1 = PTR_TO_OFFSET (d - 1);
5388 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5389 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5391 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5392 UPDATE_SYNTAX_TABLE (charpos);
5396 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5400 if (/* Case 2: Only one of S1 and S2 is Sword. */
5401 ((s1 == Sword) != (s2 == Sword))
5402 /* Case 3: Both of S1 and S2 are Sword, and macro
5403 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5404 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5410 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5412 /* We FAIL in one of the following cases: */
5414 /* Case 1: D is at the end of string. */
5415 if (AT_STRINGS_END (d))
5419 /* C1 is the character before D, S1 is the syntax of C1, C2
5420 is the character at D, and S2 is the syntax of C2. */
5422 int pos1 = PTR_TO_OFFSET (d);
5425 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5427 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5428 UPDATE_SYNTAX_TABLE (charpos);
5432 /* Case 2: S2 is not Sword. */
5436 /* Case 3: D is not at the beginning of string ... */
5437 if (!AT_STRINGS_BEG (d))
5439 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5441 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5445 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5447 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5454 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5456 /* We FAIL in one of the following cases: */
5458 /* Case 1: D is at the beginning of string. */
5459 if (AT_STRINGS_BEG (d))
5463 /* C1 is the character before D, S1 is the syntax of C1, C2
5464 is the character at D, and S2 is the syntax of C2. */
5466 int pos1 = PTR_TO_OFFSET (d);
5469 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5471 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 - 1);
5472 UPDATE_SYNTAX_TABLE (charpos);
5476 /* Case 2: S1 is not Sword. */
5480 /* Case 3: D is not at the end of string ... */
5481 if (!AT_STRINGS_END (d))
5483 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5485 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5489 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5491 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5499 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5500 if (PTR_BYTE_POS ((unsigned char *) d) >= PT_BYTE)
5505 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5506 if (PTR_BYTE_POS ((unsigned char *) d) != PT_BYTE)
5511 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5512 if (PTR_BYTE_POS ((unsigned char *) d) <= PT_BYTE)
5517 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5522 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5528 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5529 UPDATE_SYNTAX_TABLE (pos1);
5536 /* we must concern about multibyte form, ... */
5537 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5539 /* everything should be handled as ASCII, even though it
5540 looks like multibyte form. */
5543 if (SYNTAX (c) != (enum syntaxcode) mcnt)
5547 SET_REGS_MATCHED ();
5551 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5553 goto matchnotsyntax;
5556 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5562 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5563 UPDATE_SYNTAX_TABLE (pos1);
5570 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5574 if (SYNTAX (c) == (enum syntaxcode) mcnt)
5578 SET_REGS_MATCHED ();
5582 DEBUG_PRINT2 ("EXECUTING categoryspec %d.\n", *p);
5589 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5593 if (!CHAR_HAS_CATEGORY (c, mcnt))
5597 SET_REGS_MATCHED ();
5600 case notcategoryspec:
5601 DEBUG_PRINT2 ("EXECUTING notcategoryspec %d.\n", *p);
5608 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5612 if (CHAR_HAS_CATEGORY (c, mcnt))
5616 SET_REGS_MATCHED ();
5619 #else /* not emacs */
5621 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5623 if (!WORDCHAR_P (d))
5625 SET_REGS_MATCHED ();
5630 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5634 SET_REGS_MATCHED ();
5637 #endif /* not emacs */
5642 continue; /* Successfully executed one pattern command; keep going. */
5645 /* We goto here if a matching operation fails. */
5647 if (!FAIL_STACK_EMPTY ())
5648 { /* A restart point is known. Restore to that state. */
5649 DEBUG_PRINT1 ("\nFAIL:\n");
5650 POP_FAILURE_POINT (d, p,
5651 lowest_active_reg, highest_active_reg,
5652 regstart, regend, reg_info);
5654 /* If this failure point is a dummy, try the next one. */
5658 /* If we failed to the end of the pattern, don't examine *p. */
5662 boolean is_a_jump_n = false;
5664 /* If failed to a backwards jump that's part of a repetition
5665 loop, need to pop this failure point and use the next one. */
5666 switch ((re_opcode_t) *p)
5670 case maybe_pop_jump:
5671 case pop_failure_jump:
5674 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5677 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5679 && (re_opcode_t) *p1 == on_failure_jump))
5687 if (d >= string1 && d <= end1)
5691 break; /* Matching at this starting point really fails. */
5695 goto restore_best_regs;
5699 return -1; /* Failure to match. */
5702 /* Subroutine definitions for re_match_2. */
5705 /* We are passed P pointing to a register number after a start_memory.
5707 Return true if the pattern up to the corresponding stop_memory can
5708 match the empty string, and false otherwise.
5710 If we find the matching stop_memory, sets P to point to one past its number.
5711 Otherwise, sets P to an undefined byte less than or equal to END.
5713 We don't handle duplicates properly (yet). */
5716 group_match_null_string_p (p, end, reg_info)
5717 unsigned char **p, *end;
5718 register_info_type *reg_info;
5721 /* Point to after the args to the start_memory. */
5722 unsigned char *p1 = *p + 2;
5726 /* Skip over opcodes that can match nothing, and return true or
5727 false, as appropriate, when we get to one that can't, or to the
5728 matching stop_memory. */
5730 switch ((re_opcode_t) *p1)
5732 /* Could be either a loop or a series of alternatives. */
5733 case on_failure_jump:
5735 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5737 /* If the next operation is not a jump backwards in the
5742 /* Go through the on_failure_jumps of the alternatives,
5743 seeing if any of the alternatives cannot match nothing.
5744 The last alternative starts with only a jump,
5745 whereas the rest start with on_failure_jump and end
5746 with a jump, e.g., here is the pattern for `a|b|c':
5748 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5749 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5752 So, we have to first go through the first (n-1)
5753 alternatives and then deal with the last one separately. */
5756 /* Deal with the first (n-1) alternatives, which start
5757 with an on_failure_jump (see above) that jumps to right
5758 past a jump_past_alt. */
5760 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5762 /* `mcnt' holds how many bytes long the alternative
5763 is, including the ending `jump_past_alt' and
5766 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5770 /* Move to right after this alternative, including the
5774 /* Break if it's the beginning of an n-th alternative
5775 that doesn't begin with an on_failure_jump. */
5776 if ((re_opcode_t) *p1 != on_failure_jump)
5779 /* Still have to check that it's not an n-th
5780 alternative that starts with an on_failure_jump. */
5782 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5783 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5785 /* Get to the beginning of the n-th alternative. */
5791 /* Deal with the last alternative: go back and get number
5792 of the `jump_past_alt' just before it. `mcnt' contains
5793 the length of the alternative. */
5794 EXTRACT_NUMBER (mcnt, p1 - 2);
5796 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5799 p1 += mcnt; /* Get past the n-th alternative. */
5805 assert (p1[1] == **p);
5811 if (!common_op_match_null_string_p (&p1, end, reg_info))
5814 } /* while p1 < end */
5817 } /* group_match_null_string_p */
5820 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5821 It expects P to be the first byte of a single alternative and END one
5822 byte past the last. The alternative can contain groups. */
5825 alt_match_null_string_p (p, end, reg_info)
5826 unsigned char *p, *end;
5827 register_info_type *reg_info;
5830 unsigned char *p1 = p;
5834 /* Skip over opcodes that can match nothing, and break when we get
5835 to one that can't. */
5837 switch ((re_opcode_t) *p1)
5840 case on_failure_jump:
5842 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5847 if (!common_op_match_null_string_p (&p1, end, reg_info))
5850 } /* while p1 < end */
5853 } /* alt_match_null_string_p */
5856 /* Deals with the ops common to group_match_null_string_p and
5857 alt_match_null_string_p.
5859 Sets P to one after the op and its arguments, if any. */
5862 common_op_match_null_string_p (p, end, reg_info)
5863 unsigned char **p, *end;
5864 register_info_type *reg_info;
5869 unsigned char *p1 = *p;
5871 switch ((re_opcode_t) *p1++)
5891 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5892 ret = group_match_null_string_p (&p1, end, reg_info);
5894 /* Have to set this here in case we're checking a group which
5895 contains a group and a back reference to it. */
5897 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5898 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5904 /* If this is an optimized succeed_n for zero times, make the jump. */
5906 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5914 /* Get to the number of times to succeed. */
5916 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5921 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5929 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5937 /* All other opcodes mean we cannot match the empty string. */
5943 } /* common_op_match_null_string_p */
5946 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5947 bytes; nonzero otherwise. */
5950 bcmp_translate (s1, s2, len, translate)
5951 unsigned char *s1, *s2;
5953 RE_TRANSLATE_TYPE translate;
5955 register unsigned char *p1 = s1, *p2 = s2;
5956 unsigned char *p1_end = s1 + len;
5957 unsigned char *p2_end = s2 + len;
5959 while (p1 != p1_end && p2 != p2_end)
5961 int p1_charlen, p2_charlen;
5964 p1_ch = STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5965 p2_ch = STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5967 if (RE_TRANSLATE (translate, p1_ch)
5968 != RE_TRANSLATE (translate, p2_ch))
5971 p1 += p1_charlen, p2 += p2_charlen;
5974 if (p1 != p1_end || p2 != p2_end)
5980 /* Entry points for GNU code. */
5982 /* re_compile_pattern is the GNU regular expression compiler: it
5983 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5984 Returns 0 if the pattern was valid, otherwise an error string.
5986 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5987 are set in BUFP on entry.
5989 We call regex_compile to do the actual compilation. */
5992 re_compile_pattern (pattern, length, bufp)
5993 const char *pattern;
5995 struct re_pattern_buffer *bufp;
5999 /* GNU code is written to assume at least RE_NREGS registers will be set
6000 (and at least one extra will be -1). */
6001 bufp->regs_allocated = REGS_UNALLOCATED;
6003 /* And GNU code determines whether or not to get register information
6004 by passing null for the REGS argument to re_match, etc., not by
6008 /* Match anchors at newline. */
6009 bufp->newline_anchor = 1;
6011 ret = regex_compile (pattern, length, re_syntax_options, bufp);
6015 return gettext (re_error_msgid[(int) ret]);
6018 /* Entry points compatible with 4.2 BSD regex library. We don't define
6019 them unless specifically requested. */
6021 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
6023 /* BSD has one and only one pattern buffer. */
6024 static struct re_pattern_buffer re_comp_buf;
6028 /* Make these definitions weak in libc, so POSIX programs can redefine
6029 these names if they don't use our functions, and still use
6030 regcomp/regexec below without link errors. */
6040 if (!re_comp_buf.buffer)
6041 return gettext ("No previous regular expression");
6045 if (!re_comp_buf.buffer)
6047 re_comp_buf.buffer = (unsigned char *) malloc (200);
6048 if (re_comp_buf.buffer == NULL)
6049 return gettext (re_error_msgid[(int) REG_ESPACE]);
6050 re_comp_buf.allocated = 200;
6052 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6053 if (re_comp_buf.fastmap == NULL)
6054 return gettext (re_error_msgid[(int) REG_ESPACE]);
6057 /* Since `re_exec' always passes NULL for the `regs' argument, we
6058 don't need to initialize the pattern buffer fields which affect it. */
6060 /* Match anchors at newlines. */
6061 re_comp_buf.newline_anchor = 1;
6063 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6068 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6069 return (char *) gettext (re_error_msgid[(int) ret]);
6080 const int len = strlen (s);
6082 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6084 #endif /* _REGEX_RE_COMP */
6086 /* POSIX.2 functions. Don't define these for Emacs. */
6090 /* regcomp takes a regular expression as a string and compiles it.
6092 PREG is a regex_t *. We do not expect any fields to be initialized,
6093 since POSIX says we shouldn't. Thus, we set
6095 `buffer' to the compiled pattern;
6096 `used' to the length of the compiled pattern;
6097 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6098 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6099 RE_SYNTAX_POSIX_BASIC;
6100 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6101 `fastmap' and `fastmap_accurate' to zero;
6102 `re_nsub' to the number of subexpressions in PATTERN.
6104 PATTERN is the address of the pattern string.
6106 CFLAGS is a series of bits which affect compilation.
6108 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6109 use POSIX basic syntax.
6111 If REG_NEWLINE is set, then . and [^...] don't match newline.
6112 Also, regexec will try a match beginning after every newline.
6114 If REG_ICASE is set, then we considers upper- and lowercase
6115 versions of letters to be equivalent when matching.
6117 If REG_NOSUB is set, then when PREG is passed to regexec, that
6118 routine will report only success or failure, and nothing about the
6121 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6122 the return codes and their meanings.) */
6125 regcomp (preg, pattern, cflags)
6127 const char *pattern;
6132 = (cflags & REG_EXTENDED) ?
6133 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6135 /* regex_compile will allocate the space for the compiled pattern. */
6137 preg->allocated = 0;
6140 /* Don't bother to use a fastmap when searching. This simplifies the
6141 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6142 characters after newlines into the fastmap. This way, we just try
6146 if (cflags & REG_ICASE)
6151 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6152 * sizeof (*(RE_TRANSLATE_TYPE)0));
6153 if (preg->translate == NULL)
6154 return (int) REG_ESPACE;
6156 /* Map uppercase characters to corresponding lowercase ones. */
6157 for (i = 0; i < CHAR_SET_SIZE; i++)
6158 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6161 preg->translate = NULL;
6163 /* If REG_NEWLINE is set, newlines are treated differently. */
6164 if (cflags & REG_NEWLINE)
6165 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6166 syntax &= ~RE_DOT_NEWLINE;
6167 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6168 /* It also changes the matching behavior. */
6169 preg->newline_anchor = 1;
6172 preg->newline_anchor = 0;
6174 preg->no_sub = !!(cflags & REG_NOSUB);
6176 /* POSIX says a null character in the pattern terminates it, so we
6177 can use strlen here in compiling the pattern. */
6178 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
6180 /* POSIX doesn't distinguish between an unmatched open-group and an
6181 unmatched close-group: both are REG_EPAREN. */
6182 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6188 /* regexec searches for a given pattern, specified by PREG, in the
6191 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6192 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6193 least NMATCH elements, and we set them to the offsets of the
6194 corresponding matched substrings.
6196 EFLAGS specifies `execution flags' which affect matching: if
6197 REG_NOTBOL is set, then ^ does not match at the beginning of the
6198 string; if REG_NOTEOL is set, then $ does not match at the end.
6200 We return 0 if we find a match and REG_NOMATCH if not. */
6203 regexec (preg, string, nmatch, pmatch, eflags)
6204 const regex_t *preg;
6207 regmatch_t pmatch[];
6211 struct re_registers regs;
6212 regex_t private_preg;
6213 int len = strlen (string);
6214 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6216 private_preg = *preg;
6218 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6219 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6221 /* The user has told us exactly how many registers to return
6222 information about, via `nmatch'. We have to pass that on to the
6223 matching routines. */
6224 private_preg.regs_allocated = REGS_FIXED;
6228 regs.num_regs = nmatch;
6229 regs.start = TALLOC (nmatch, regoff_t);
6230 regs.end = TALLOC (nmatch, regoff_t);
6231 if (regs.start == NULL || regs.end == NULL)
6232 return (int) REG_NOMATCH;
6235 /* Perform the searching operation. */
6236 ret = re_search (&private_preg, string, len,
6237 /* start: */ 0, /* range: */ len,
6238 want_reg_info ? ®s : (struct re_registers *) 0);
6240 /* Copy the register information to the POSIX structure. */
6247 for (r = 0; r < nmatch; r++)
6249 pmatch[r].rm_so = regs.start[r];
6250 pmatch[r].rm_eo = regs.end[r];
6254 /* If we needed the temporary register info, free the space now. */
6259 /* We want zero return to mean success, unlike `re_search'. */
6260 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6264 /* Returns a message corresponding to an error code, ERRCODE, returned
6265 from either regcomp or regexec. We don't use PREG here. */
6268 regerror (errcode, preg, errbuf, errbuf_size)
6270 const regex_t *preg;
6278 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6279 /* Only error codes returned by the rest of the code should be passed
6280 to this routine. If we are given anything else, or if other regex
6281 code generates an invalid error code, then the program has a bug.
6282 Dump core so we can fix it. */
6285 msg = gettext (re_error_msgid[errcode]);
6287 msg_size = strlen (msg) + 1; /* Includes the null. */
6289 if (errbuf_size != 0)
6291 if (msg_size > errbuf_size)
6293 strncpy (errbuf, msg, errbuf_size - 1);
6294 errbuf[errbuf_size - 1] = 0;
6297 strcpy (errbuf, msg);
6304 /* Free dynamically allocated space used by PREG. */
6310 if (preg->buffer != NULL)
6311 free (preg->buffer);
6312 preg->buffer = NULL;
6314 preg->allocated = 0;
6317 if (preg->fastmap != NULL)
6318 free (preg->fastmap);
6319 preg->fastmap = NULL;
6320 preg->fastmap_accurate = 0;
6322 if (preg->translate != NULL)
6323 free (preg->translate);
6324 preg->translate = NULL;
6327 #endif /* not emacs */