1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P10003.2/D11.2, except for
4 internationalization features.)
6 Copyright (C) 1993, 1994, 1995 Free Software Foundation, Inc.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
34 /* We need this for `regex.h', and perhaps for the Emacs include files. */
35 #include <sys/types.h>
37 /* This is for other GNU distributions with internationalized messages. */
38 #if HAVE_LIBINTL_H || defined (_LIBC)
41 # define gettext(msgid) (msgid)
45 /* This define is so xgettext can find the internationalizable
47 #define gettext_noop(String) String
50 /* The `emacs' switch turns on certain matching commands
51 that make sense only in Emacs. */
60 /* If we are not linking with Emacs proper,
61 we can't use the relocating allocator
62 even if config.h says that we can. */
65 #if defined (STDC_HEADERS) || defined (_LIBC)
72 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
73 If nothing else has been done, use the method below. */
74 #ifdef INHIBIT_STRING_HEADER
75 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
76 #if !defined (bzero) && !defined (bcopy)
77 #undef INHIBIT_STRING_HEADER
82 /* This is the normal way of making sure we have a bcopy and a bzero.
83 This is used in most programs--a few other programs avoid this
84 by defining INHIBIT_STRING_HEADER. */
85 #ifndef INHIBIT_STRING_HEADER
86 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
89 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
92 #define bcopy(s, d, n) memcpy ((d), (s), (n))
95 #define bzero(s, n) memset ((s), 0, (n))
102 /* Define the syntax stuff for \<, \>, etc. */
104 /* This must be nonzero for the wordchar and notwordchar pattern
105 commands in re_match_2. */
110 #ifdef SWITCH_ENUM_BUG
111 #define SWITCH_ENUM_CAST(x) ((int)(x))
113 #define SWITCH_ENUM_CAST(x) (x)
118 extern char *re_syntax_table
;
120 #else /* not SYNTAX_TABLE */
122 /* How many characters in the character set. */
123 #define CHAR_SET_SIZE 256
125 static char re_syntax_table
[CHAR_SET_SIZE
];
136 bzero (re_syntax_table
, sizeof re_syntax_table
);
138 for (c
= 'a'; c
<= 'z'; c
++)
139 re_syntax_table
[c
] = Sword
;
141 for (c
= 'A'; c
<= 'Z'; c
++)
142 re_syntax_table
[c
] = Sword
;
144 for (c
= '0'; c
<= '9'; c
++)
145 re_syntax_table
[c
] = Sword
;
147 re_syntax_table
['_'] = Sword
;
152 #endif /* not SYNTAX_TABLE */
154 #define SYNTAX(c) re_syntax_table[c]
156 #endif /* not emacs */
158 /* Get the interface, including the syntax bits. */
161 /* isalpha etc. are used for the character classes. */
164 /* Jim Meyering writes:
166 "... Some ctype macros are valid only for character codes that
167 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
168 using /bin/cc or gcc but without giving an ansi option). So, all
169 ctype uses should be through macros like ISPRINT... If
170 STDC_HEADERS is defined, then autoconf has verified that the ctype
171 macros don't need to be guarded with references to isascii. ...
172 Defining isascii to 1 should let any compiler worth its salt
173 eliminate the && through constant folding." */
175 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
176 #define IN_CTYPE_DOMAIN(c) 1
178 #define IN_CTYPE_DOMAIN(c) isascii(c)
182 #define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
184 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
187 #define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
189 #define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
192 #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
193 #define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
194 #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
195 #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
196 #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
197 #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
198 #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
199 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
200 #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
201 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
204 #define NULL (void *)0
207 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
208 since ours (we hope) works properly with all combinations of
209 machines, compilers, `char' and `unsigned char' argument types.
210 (Per Bothner suggested the basic approach.) */
211 #undef SIGN_EXTEND_CHAR
213 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
214 #else /* not __STDC__ */
215 /* As in Harbison and Steele. */
216 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
219 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
220 use `alloca' instead of `malloc'. This is because using malloc in
221 re_search* or re_match* could cause memory leaks when C-g is used in
222 Emacs; also, malloc is slower and causes storage fragmentation. On
223 the other hand, malloc is more portable, and easier to debug.
225 Because we sometimes use alloca, some routines have to be macros,
226 not functions -- `alloca'-allocated space disappears at the end of the
227 function it is called in. */
231 #define REGEX_ALLOCATE malloc
232 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
233 #define REGEX_FREE free
235 #else /* not REGEX_MALLOC */
237 /* Emacs already defines alloca, sometimes. */
240 /* Make alloca work the best possible way. */
242 #define alloca __builtin_alloca
243 #else /* not __GNUC__ */
246 #else /* not __GNUC__ or HAVE_ALLOCA_H */
247 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
248 #ifndef _AIX /* Already did AIX, up at the top. */
250 #endif /* not _AIX */
252 #endif /* not HAVE_ALLOCA_H */
253 #endif /* not __GNUC__ */
255 #endif /* not alloca */
257 #define REGEX_ALLOCATE alloca
259 /* Assumes a `char *destination' variable. */
260 #define REGEX_REALLOCATE(source, osize, nsize) \
261 (destination = (char *) alloca (nsize), \
262 bcopy (source, destination, osize), \
265 /* No need to do anything to free, after alloca. */
266 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
268 #endif /* not REGEX_MALLOC */
270 /* Define how to allocate the failure stack. */
272 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
274 #define REGEX_ALLOCATE_STACK(size) \
275 r_alloc (&failure_stack_ptr, (size))
276 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
277 r_re_alloc (&failure_stack_ptr, (nsize))
278 #define REGEX_FREE_STACK(ptr) \
279 r_alloc_free (&failure_stack_ptr)
281 #else /* not using relocating allocator */
285 #define REGEX_ALLOCATE_STACK malloc
286 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
287 #define REGEX_FREE_STACK free
289 #else /* not REGEX_MALLOC */
291 #define REGEX_ALLOCATE_STACK alloca
293 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
294 REGEX_REALLOCATE (source, osize, nsize)
295 /* No need to explicitly free anything. */
296 #define REGEX_FREE_STACK(arg)
298 #endif /* not REGEX_MALLOC */
299 #endif /* not using relocating allocator */
302 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
303 `string1' or just past its end. This works if PTR is NULL, which is
305 #define FIRST_STRING_P(ptr) \
306 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
308 /* (Re)Allocate N items of type T using malloc, or fail. */
309 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
310 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
311 #define RETALLOC_IF(addr, n, t) \
312 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
313 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
315 #define BYTEWIDTH 8 /* In bits. */
317 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
321 #define MAX(a, b) ((a) > (b) ? (a) : (b))
322 #define MIN(a, b) ((a) < (b) ? (a) : (b))
324 typedef char boolean
;
328 static int re_match_2_internal ();
330 /* These are the command codes that appear in compiled regular
331 expressions. Some opcodes are followed by argument bytes. A
332 command code can specify any interpretation whatsoever for its
333 arguments. Zero bytes may appear in the compiled regular expression. */
339 /* Succeed right away--no more backtracking. */
342 /* Followed by one byte giving n, then by n literal bytes. */
345 /* Matches any (more or less) character. */
348 /* Matches any one char belonging to specified set. First
349 following byte is number of bitmap bytes. Then come bytes
350 for a bitmap saying which chars are in. Bits in each byte
351 are ordered low-bit-first. A character is in the set if its
352 bit is 1. A character too large to have a bit in the map is
353 automatically not in the set. */
356 /* Same parameters as charset, but match any character that is
357 not one of those specified. */
360 /* Start remembering the text that is matched, for storing in a
361 register. Followed by one byte with the register number, in
362 the range 0 to one less than the pattern buffer's re_nsub
363 field. Then followed by one byte with the number of groups
364 inner to this one. (This last has to be part of the
365 start_memory only because we need it in the on_failure_jump
369 /* Stop remembering the text that is matched and store it in a
370 memory register. Followed by one byte with the register
371 number, in the range 0 to one less than `re_nsub' in the
372 pattern buffer, and one byte with the number of inner groups,
373 just like `start_memory'. (We need the number of inner
374 groups here because we don't have any easy way of finding the
375 corresponding start_memory when we're at a stop_memory.) */
378 /* Match a duplicate of something remembered. Followed by one
379 byte containing the register number. */
382 /* Fail unless at beginning of line. */
385 /* Fail unless at end of line. */
388 /* Succeeds if at beginning of buffer (if emacs) or at beginning
389 of string to be matched (if not). */
392 /* Analogously, for end of buffer/string. */
395 /* Followed by two byte relative address to which to jump. */
398 /* Same as jump, but marks the end of an alternative. */
401 /* Followed by two-byte relative address of place to resume at
402 in case of failure. */
405 /* Like on_failure_jump, but pushes a placeholder instead of the
406 current string position when executed. */
407 on_failure_keep_string_jump
,
409 /* Throw away latest failure point and then jump to following
410 two-byte relative address. */
413 /* Change to pop_failure_jump if know won't have to backtrack to
414 match; otherwise change to jump. This is used to jump
415 back to the beginning of a repeat. If what follows this jump
416 clearly won't match what the repeat does, such that we can be
417 sure that there is no use backtracking out of repetitions
418 already matched, then we change it to a pop_failure_jump.
419 Followed by two-byte address. */
422 /* Jump to following two-byte address, and push a dummy failure
423 point. This failure point will be thrown away if an attempt
424 is made to use it for a failure. A `+' construct makes this
425 before the first repeat. Also used as an intermediary kind
426 of jump when compiling an alternative. */
429 /* Push a dummy failure point and continue. Used at the end of
433 /* Followed by two-byte relative address and two-byte number n.
434 After matching N times, jump to the address upon failure. */
437 /* Followed by two-byte relative address, and two-byte number n.
438 Jump to the address N times, then fail. */
441 /* Set the following two-byte relative address to the
442 subsequent two-byte number. The address *includes* the two
446 wordchar
, /* Matches any word-constituent character. */
447 notwordchar
, /* Matches any char that is not a word-constituent. */
449 wordbeg
, /* Succeeds if at word beginning. */
450 wordend
, /* Succeeds if at word end. */
452 wordbound
, /* Succeeds if at a word boundary. */
453 notwordbound
/* Succeeds if not at a word boundary. */
456 ,before_dot
, /* Succeeds if before point. */
457 at_dot
, /* Succeeds if at point. */
458 after_dot
, /* Succeeds if after point. */
460 /* Matches any character whose syntax is specified. Followed by
461 a byte which contains a syntax code, e.g., Sword. */
464 /* Matches any character whose syntax is not that specified. */
469 /* Common operations on the compiled pattern. */
471 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
473 #define STORE_NUMBER(destination, number) \
475 (destination)[0] = (number) & 0377; \
476 (destination)[1] = (number) >> 8; \
479 /* Same as STORE_NUMBER, except increment DESTINATION to
480 the byte after where the number is stored. Therefore, DESTINATION
481 must be an lvalue. */
483 #define STORE_NUMBER_AND_INCR(destination, number) \
485 STORE_NUMBER (destination, number); \
486 (destination) += 2; \
489 /* Put into DESTINATION a number stored in two contiguous bytes starting
492 #define EXTRACT_NUMBER(destination, source) \
494 (destination) = *(source) & 0377; \
495 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
500 extract_number (dest
, source
)
502 unsigned char *source
;
504 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
505 *dest
= *source
& 0377;
509 #ifndef EXTRACT_MACROS /* To debug the macros. */
510 #undef EXTRACT_NUMBER
511 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
512 #endif /* not EXTRACT_MACROS */
516 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
517 SOURCE must be an lvalue. */
519 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
521 EXTRACT_NUMBER (destination, source); \
527 extract_number_and_incr (destination
, source
)
529 unsigned char **source
;
531 extract_number (destination
, *source
);
535 #ifndef EXTRACT_MACROS
536 #undef EXTRACT_NUMBER_AND_INCR
537 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
538 extract_number_and_incr (&dest, &src)
539 #endif /* not EXTRACT_MACROS */
543 /* If DEBUG is defined, Regex prints many voluminous messages about what
544 it is doing (if the variable `debug' is nonzero). If linked with the
545 main program in `iregex.c', you can enter patterns and strings
546 interactively. And if linked with the main program in `main.c' and
547 the other test files, you can run the already-written tests. */
551 /* We use standard I/O for debugging. */
554 /* It is useful to test things that ``must'' be true when debugging. */
557 static int debug
= 0;
559 #define DEBUG_STATEMENT(e) e
560 #define DEBUG_PRINT1(x) if (debug) printf (x)
561 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
562 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
563 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
564 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
565 if (debug) print_partial_compiled_pattern (s, e)
566 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
567 if (debug) print_double_string (w, s1, sz1, s2, sz2)
570 /* Print the fastmap in human-readable form. */
573 print_fastmap (fastmap
)
576 unsigned was_a_range
= 0;
579 while (i
< (1 << BYTEWIDTH
))
585 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
601 /* Print a compiled pattern string in human-readable form, starting at
602 the START pointer into it and ending just before the pointer END. */
605 print_partial_compiled_pattern (start
, end
)
606 unsigned char *start
;
610 unsigned char *p
= start
;
611 unsigned char *pend
= end
;
619 /* Loop over pattern commands. */
622 printf ("%d:\t", p
- start
);
624 switch ((re_opcode_t
) *p
++)
632 printf ("/exactn/%d", mcnt
);
643 printf ("/start_memory/%d/%d", mcnt
, *p
++);
648 printf ("/stop_memory/%d/%d", mcnt
, *p
++);
652 printf ("/duplicate/%d", *p
++);
662 register int c
, last
= -100;
663 register int in_range
= 0;
665 printf ("/charset [%s",
666 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
668 assert (p
+ *p
< pend
);
670 for (c
= 0; c
< 256; c
++)
672 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
674 /* Are we starting a range? */
675 if (last
+ 1 == c
&& ! in_range
)
680 /* Have we broken a range? */
681 else if (last
+ 1 != c
&& in_range
)
710 case on_failure_jump
:
711 extract_number_and_incr (&mcnt
, &p
);
712 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
715 case on_failure_keep_string_jump
:
716 extract_number_and_incr (&mcnt
, &p
);
717 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
720 case dummy_failure_jump
:
721 extract_number_and_incr (&mcnt
, &p
);
722 printf ("/dummy_failure_jump to %d", p
+ mcnt
- start
);
725 case push_dummy_failure
:
726 printf ("/push_dummy_failure");
730 extract_number_and_incr (&mcnt
, &p
);
731 printf ("/maybe_pop_jump to %d", p
+ mcnt
- start
);
734 case pop_failure_jump
:
735 extract_number_and_incr (&mcnt
, &p
);
736 printf ("/pop_failure_jump to %d", p
+ mcnt
- start
);
740 extract_number_and_incr (&mcnt
, &p
);
741 printf ("/jump_past_alt to %d", p
+ mcnt
- start
);
745 extract_number_and_incr (&mcnt
, &p
);
746 printf ("/jump to %d", p
+ mcnt
- start
);
750 extract_number_and_incr (&mcnt
, &p
);
751 extract_number_and_incr (&mcnt2
, &p
);
752 printf ("/succeed_n to %d, %d times", p
+ mcnt
- start
, mcnt2
);
756 extract_number_and_incr (&mcnt
, &p
);
757 extract_number_and_incr (&mcnt2
, &p
);
758 printf ("/jump_n to %d, %d times", p
+ mcnt
- start
, mcnt2
);
762 extract_number_and_incr (&mcnt
, &p
);
763 extract_number_and_incr (&mcnt2
, &p
);
764 printf ("/set_number_at location %d to %d", p
+ mcnt
- start
, mcnt2
);
768 printf ("/wordbound");
772 printf ("/notwordbound");
784 printf ("/before_dot");
792 printf ("/after_dot");
796 printf ("/syntaxspec");
798 printf ("/%d", mcnt
);
802 printf ("/notsyntaxspec");
804 printf ("/%d", mcnt
);
809 printf ("/wordchar");
813 printf ("/notwordchar");
825 printf ("?%d", *(p
-1));
831 printf ("%d:\tend of pattern.\n", p
- start
);
836 print_compiled_pattern (bufp
)
837 struct re_pattern_buffer
*bufp
;
839 unsigned char *buffer
= bufp
->buffer
;
841 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
842 printf ("%d bytes used/%d bytes allocated.\n", bufp
->used
, bufp
->allocated
);
844 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
846 printf ("fastmap: ");
847 print_fastmap (bufp
->fastmap
);
850 printf ("re_nsub: %d\t", bufp
->re_nsub
);
851 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
852 printf ("can_be_null: %d\t", bufp
->can_be_null
);
853 printf ("newline_anchor: %d\n", bufp
->newline_anchor
);
854 printf ("no_sub: %d\t", bufp
->no_sub
);
855 printf ("not_bol: %d\t", bufp
->not_bol
);
856 printf ("not_eol: %d\t", bufp
->not_eol
);
857 printf ("syntax: %d\n", bufp
->syntax
);
858 /* Perhaps we should print the translate table? */
863 print_double_string (where
, string1
, size1
, string2
, size2
)
876 if (FIRST_STRING_P (where
))
878 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
879 putchar (string1
[this_char
]);
884 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
885 putchar (string2
[this_char
]);
889 #else /* not DEBUG */
894 #define DEBUG_STATEMENT(e)
895 #define DEBUG_PRINT1(x)
896 #define DEBUG_PRINT2(x1, x2)
897 #define DEBUG_PRINT3(x1, x2, x3)
898 #define DEBUG_PRINT4(x1, x2, x3, x4)
899 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
900 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
902 #endif /* not DEBUG */
904 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
905 also be assigned to arbitrarily: each pattern buffer stores its own
906 syntax, so it can be changed between regex compilations. */
907 /* This has no initializer because initialized variables in Emacs
908 become read-only after dumping. */
909 reg_syntax_t re_syntax_options
;
912 /* Specify the precise syntax of regexps for compilation. This provides
913 for compatibility for various utilities which historically have
914 different, incompatible syntaxes.
916 The argument SYNTAX is a bit mask comprised of the various bits
917 defined in regex.h. We return the old syntax. */
920 re_set_syntax (syntax
)
923 reg_syntax_t ret
= re_syntax_options
;
925 re_syntax_options
= syntax
;
929 /* This table gives an error message for each of the error codes listed
930 in regex.h. Obviously the order here has to be same as there.
931 POSIX doesn't require that we do anything for REG_NOERROR,
932 but why not be nice? */
934 static const char *re_error_msgid
[] =
936 gettext_noop ("Success"), /* REG_NOERROR */
937 gettext_noop ("No match"), /* REG_NOMATCH */
938 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
939 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
940 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
941 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
942 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
943 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
944 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
945 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
946 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
947 gettext_noop ("Invalid range end"), /* REG_ERANGE */
948 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
949 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
950 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
951 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
952 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
955 /* Avoiding alloca during matching, to placate r_alloc. */
957 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
958 searching and matching functions should not call alloca. On some
959 systems, alloca is implemented in terms of malloc, and if we're
960 using the relocating allocator routines, then malloc could cause a
961 relocation, which might (if the strings being searched are in the
962 ralloc heap) shift the data out from underneath the regexp
965 Here's another reason to avoid allocation: Emacs
966 processes input from X in a signal handler; processing X input may
967 call malloc; if input arrives while a matching routine is calling
968 malloc, then we're scrod. But Emacs can't just block input while
969 calling matching routines; then we don't notice interrupts when
970 they come in. So, Emacs blocks input around all regexp calls
971 except the matching calls, which it leaves unprotected, in the
972 faith that they will not malloc. */
974 /* Normally, this is fine. */
975 #define MATCH_MAY_ALLOCATE
977 /* When using GNU C, we are not REALLY using the C alloca, no matter
978 what config.h may say. So don't take precautions for it. */
983 /* The match routines may not allocate if (1) they would do it with malloc
984 and (2) it's not safe for them to use malloc.
985 Note that if REL_ALLOC is defined, matching would not use malloc for the
986 failure stack, but we would still use it for the register vectors;
987 so REL_ALLOC should not affect this. */
988 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
989 #undef MATCH_MAY_ALLOCATE
993 /* Failure stack declarations and macros; both re_compile_fastmap and
994 re_match_2 use a failure stack. These have to be macros because of
995 REGEX_ALLOCATE_STACK. */
998 /* Number of failure points for which to initially allocate space
999 when matching. If this number is exceeded, we allocate more
1000 space, so it is not a hard limit. */
1001 #ifndef INIT_FAILURE_ALLOC
1002 #define INIT_FAILURE_ALLOC 5
1005 /* Roughly the maximum number of failure points on the stack. Would be
1006 exactly that if always used MAX_FAILURE_SPACE each time we failed.
1007 This is a variable only so users of regex can assign to it; we never
1008 change it ourselves. */
1009 #if defined (MATCH_MAY_ALLOCATE)
1010 int re_max_failures
= 20000;
1012 int re_max_failures
= 2000;
1015 union fail_stack_elt
1017 unsigned char *pointer
;
1021 typedef union fail_stack_elt fail_stack_elt_t
;
1025 fail_stack_elt_t
*stack
;
1027 unsigned avail
; /* Offset of next open position. */
1030 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1031 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1032 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1035 /* Define macros to initialize and free the failure stack.
1036 Do `return -2' if the alloc fails. */
1038 #ifdef MATCH_MAY_ALLOCATE
1039 #define INIT_FAIL_STACK() \
1041 fail_stack.stack = (fail_stack_elt_t *) \
1042 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1044 if (fail_stack.stack == NULL) \
1047 fail_stack.size = INIT_FAILURE_ALLOC; \
1048 fail_stack.avail = 0; \
1051 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1053 #define INIT_FAIL_STACK() \
1055 fail_stack.avail = 0; \
1058 #define RESET_FAIL_STACK()
1062 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1064 Return 1 if succeeds, and 0 if either ran out of memory
1065 allocating space for it or it was already too large.
1067 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1069 #define DOUBLE_FAIL_STACK(fail_stack) \
1070 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
1072 : ((fail_stack).stack = (fail_stack_elt_t *) \
1073 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1074 (fail_stack).size * sizeof (fail_stack_elt_t), \
1075 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1077 (fail_stack).stack == NULL \
1079 : ((fail_stack).size <<= 1, \
1083 /* Push pointer POINTER on FAIL_STACK.
1084 Return 1 if was able to do so and 0 if ran out of memory allocating
1086 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1087 ((FAIL_STACK_FULL () \
1088 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1090 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1093 /* Push a pointer value onto the failure stack.
1094 Assumes the variable `fail_stack'. Probably should only
1095 be called from within `PUSH_FAILURE_POINT'. */
1096 #define PUSH_FAILURE_POINTER(item) \
1097 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1099 /* This pushes an integer-valued item onto the failure stack.
1100 Assumes the variable `fail_stack'. Probably should only
1101 be called from within `PUSH_FAILURE_POINT'. */
1102 #define PUSH_FAILURE_INT(item) \
1103 fail_stack.stack[fail_stack.avail++].integer = (item)
1105 /* Push a fail_stack_elt_t value onto the failure stack.
1106 Assumes the variable `fail_stack'. Probably should only
1107 be called from within `PUSH_FAILURE_POINT'. */
1108 #define PUSH_FAILURE_ELT(item) \
1109 fail_stack.stack[fail_stack.avail++] = (item)
1111 /* These three POP... operations complement the three PUSH... operations.
1112 All assume that `fail_stack' is nonempty. */
1113 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1114 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1115 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1117 /* Used to omit pushing failure point id's when we're not debugging. */
1119 #define DEBUG_PUSH PUSH_FAILURE_INT
1120 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1122 #define DEBUG_PUSH(item)
1123 #define DEBUG_POP(item_addr)
1127 /* Push the information about the state we will need
1128 if we ever fail back to it.
1130 Requires variables fail_stack, regstart, regend, reg_info, and
1131 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
1134 Does `return FAILURE_CODE' if runs out of memory. */
1136 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1138 char *destination; \
1139 /* Must be int, so when we don't save any registers, the arithmetic \
1140 of 0 + -1 isn't done as unsigned. */ \
1143 DEBUG_STATEMENT (failure_id++); \
1144 DEBUG_STATEMENT (nfailure_points_pushed++); \
1145 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1146 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1147 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1149 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1150 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1152 /* Ensure we have enough space allocated for what we will push. */ \
1153 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1155 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1156 return failure_code; \
1158 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1159 (fail_stack).size); \
1160 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1163 /* Push the info, starting with the registers. */ \
1164 DEBUG_PRINT1 ("\n"); \
1167 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1170 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1171 DEBUG_STATEMENT (num_regs_pushed++); \
1173 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1174 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1176 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1177 PUSH_FAILURE_POINTER (regend[this_reg]); \
1179 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
1180 DEBUG_PRINT2 (" match_null=%d", \
1181 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1182 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1183 DEBUG_PRINT2 (" matched_something=%d", \
1184 MATCHED_SOMETHING (reg_info[this_reg])); \
1185 DEBUG_PRINT2 (" ever_matched=%d", \
1186 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1187 DEBUG_PRINT1 ("\n"); \
1188 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1191 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1192 PUSH_FAILURE_INT (lowest_active_reg); \
1194 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1195 PUSH_FAILURE_INT (highest_active_reg); \
1197 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
1198 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1199 PUSH_FAILURE_POINTER (pattern_place); \
1201 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
1202 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1204 DEBUG_PRINT1 ("'\n"); \
1205 PUSH_FAILURE_POINTER (string_place); \
1207 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1208 DEBUG_PUSH (failure_id); \
1211 /* This is the number of items that are pushed and popped on the stack
1212 for each register. */
1213 #define NUM_REG_ITEMS 3
1215 /* Individual items aside from the registers. */
1217 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1219 #define NUM_NONREG_ITEMS 4
1222 /* We push at most this many items on the stack. */
1223 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1225 /* We actually push this many items. */
1226 #define NUM_FAILURE_ITEMS \
1228 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1232 /* How many items can still be added to the stack without overflowing it. */
1233 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1236 /* Pops what PUSH_FAIL_STACK pushes.
1238 We restore into the parameters, all of which should be lvalues:
1239 STR -- the saved data position.
1240 PAT -- the saved pattern position.
1241 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1242 REGSTART, REGEND -- arrays of string positions.
1243 REG_INFO -- array of information about each subexpression.
1245 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1246 `pend', `string1', `size1', `string2', and `size2'. */
1248 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1250 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
1252 const unsigned char *string_temp; \
1254 assert (!FAIL_STACK_EMPTY ()); \
1256 /* Remove failure points and point to how many regs pushed. */ \
1257 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1258 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1259 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1261 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1263 DEBUG_POP (&failure_id); \
1264 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1266 /* If the saved string location is NULL, it came from an \
1267 on_failure_keep_string_jump opcode, and we want to throw away the \
1268 saved NULL, thus retaining our current position in the string. */ \
1269 string_temp = POP_FAILURE_POINTER (); \
1270 if (string_temp != NULL) \
1271 str = (const char *) string_temp; \
1273 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
1274 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1275 DEBUG_PRINT1 ("'\n"); \
1277 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1278 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
1279 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1281 /* Restore register info. */ \
1282 high_reg = (unsigned) POP_FAILURE_INT (); \
1283 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1285 low_reg = (unsigned) POP_FAILURE_INT (); \
1286 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1289 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1291 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1293 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1294 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
1296 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1297 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1299 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1300 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1304 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1306 reg_info[this_reg].word.integer = 0; \
1307 regend[this_reg] = 0; \
1308 regstart[this_reg] = 0; \
1310 highest_active_reg = high_reg; \
1313 set_regs_matched_done = 0; \
1314 DEBUG_STATEMENT (nfailure_points_popped++); \
1315 } /* POP_FAILURE_POINT */
1319 /* Structure for per-register (a.k.a. per-group) information.
1320 Other register information, such as the
1321 starting and ending positions (which are addresses), and the list of
1322 inner groups (which is a bits list) are maintained in separate
1325 We are making a (strictly speaking) nonportable assumption here: that
1326 the compiler will pack our bit fields into something that fits into
1327 the type of `word', i.e., is something that fits into one item on the
1332 fail_stack_elt_t word
;
1335 /* This field is one if this group can match the empty string,
1336 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1337 #define MATCH_NULL_UNSET_VALUE 3
1338 unsigned match_null_string_p
: 2;
1339 unsigned is_active
: 1;
1340 unsigned matched_something
: 1;
1341 unsigned ever_matched_something
: 1;
1343 } register_info_type
;
1345 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1346 #define IS_ACTIVE(R) ((R).bits.is_active)
1347 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1348 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1351 /* Call this when have matched a real character; it sets `matched' flags
1352 for the subexpressions which we are currently inside. Also records
1353 that those subexprs have matched. */
1354 #define SET_REGS_MATCHED() \
1357 if (!set_regs_matched_done) \
1360 set_regs_matched_done = 1; \
1361 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1363 MATCHED_SOMETHING (reg_info[r]) \
1364 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1371 /* Registers are set to a sentinel when they haven't yet matched. */
1372 static char reg_unset_dummy
;
1373 #define REG_UNSET_VALUE (®_unset_dummy)
1374 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1376 /* Subroutine declarations and macros for regex_compile. */
1378 static void store_op1 (), store_op2 ();
1379 static void insert_op1 (), insert_op2 ();
1380 static boolean
at_begline_loc_p (), at_endline_loc_p ();
1381 static boolean
group_in_compile_stack ();
1382 static reg_errcode_t
compile_range ();
1384 /* Fetch the next character in the uncompiled pattern---translating it
1385 if necessary. Also cast from a signed character in the constant
1386 string passed to us by the user to an unsigned char that we can use
1387 as an array index (in, e.g., `translate'). */
1389 #define PATFETCH(c) \
1390 do {if (p == pend) return REG_EEND; \
1391 c = (unsigned char) *p++; \
1392 if (translate) c = (unsigned char) translate[c]; \
1396 /* Fetch the next character in the uncompiled pattern, with no
1398 #define PATFETCH_RAW(c) \
1399 do {if (p == pend) return REG_EEND; \
1400 c = (unsigned char) *p++; \
1403 /* Go backwards one character in the pattern. */
1404 #define PATUNFETCH p--
1407 /* If `translate' is non-null, return translate[D], else just D. We
1408 cast the subscript to translate because some data is declared as
1409 `char *', to avoid warnings when a string constant is passed. But
1410 when we use a character as a subscript we must make it unsigned. */
1412 #define TRANSLATE(d) \
1413 (translate ? (char) translate[(unsigned char) (d)] : (d))
1417 /* Macros for outputting the compiled pattern into `buffer'. */
1419 /* If the buffer isn't allocated when it comes in, use this. */
1420 #define INIT_BUF_SIZE 32
1422 /* Make sure we have at least N more bytes of space in buffer. */
1423 #define GET_BUFFER_SPACE(n) \
1424 while (b - bufp->buffer + (n) > bufp->allocated) \
1427 /* Make sure we have one more byte of buffer space and then add C to it. */
1428 #define BUF_PUSH(c) \
1430 GET_BUFFER_SPACE (1); \
1431 *b++ = (unsigned char) (c); \
1435 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1436 #define BUF_PUSH_2(c1, c2) \
1438 GET_BUFFER_SPACE (2); \
1439 *b++ = (unsigned char) (c1); \
1440 *b++ = (unsigned char) (c2); \
1444 /* As with BUF_PUSH_2, except for three bytes. */
1445 #define BUF_PUSH_3(c1, c2, c3) \
1447 GET_BUFFER_SPACE (3); \
1448 *b++ = (unsigned char) (c1); \
1449 *b++ = (unsigned char) (c2); \
1450 *b++ = (unsigned char) (c3); \
1454 /* Store a jump with opcode OP at LOC to location TO. We store a
1455 relative address offset by the three bytes the jump itself occupies. */
1456 #define STORE_JUMP(op, loc, to) \
1457 store_op1 (op, loc, (to) - (loc) - 3)
1459 /* Likewise, for a two-argument jump. */
1460 #define STORE_JUMP2(op, loc, to, arg) \
1461 store_op2 (op, loc, (to) - (loc) - 3, arg)
1463 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1464 #define INSERT_JUMP(op, loc, to) \
1465 insert_op1 (op, loc, (to) - (loc) - 3, b)
1467 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1468 #define INSERT_JUMP2(op, loc, to, arg) \
1469 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1472 /* This is not an arbitrary limit: the arguments which represent offsets
1473 into the pattern are two bytes long. So if 2^16 bytes turns out to
1474 be too small, many things would have to change. */
1475 #define MAX_BUF_SIZE (1L << 16)
1478 /* Extend the buffer by twice its current size via realloc and
1479 reset the pointers that pointed into the old block to point to the
1480 correct places in the new one. If extending the buffer results in it
1481 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1482 #define EXTEND_BUFFER() \
1484 unsigned char *old_buffer = bufp->buffer; \
1485 if (bufp->allocated == MAX_BUF_SIZE) \
1487 bufp->allocated <<= 1; \
1488 if (bufp->allocated > MAX_BUF_SIZE) \
1489 bufp->allocated = MAX_BUF_SIZE; \
1490 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1491 if (bufp->buffer == NULL) \
1492 return REG_ESPACE; \
1493 /* If the buffer moved, move all the pointers into it. */ \
1494 if (old_buffer != bufp->buffer) \
1496 b = (b - old_buffer) + bufp->buffer; \
1497 begalt = (begalt - old_buffer) + bufp->buffer; \
1498 if (fixup_alt_jump) \
1499 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1501 laststart = (laststart - old_buffer) + bufp->buffer; \
1502 if (pending_exact) \
1503 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1508 /* Since we have one byte reserved for the register number argument to
1509 {start,stop}_memory, the maximum number of groups we can report
1510 things about is what fits in that byte. */
1511 #define MAX_REGNUM 255
1513 /* But patterns can have more than `MAX_REGNUM' registers. We just
1514 ignore the excess. */
1515 typedef unsigned regnum_t
;
1518 /* Macros for the compile stack. */
1520 /* Since offsets can go either forwards or backwards, this type needs to
1521 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1522 typedef int pattern_offset_t
;
1526 pattern_offset_t begalt_offset
;
1527 pattern_offset_t fixup_alt_jump
;
1528 pattern_offset_t inner_group_offset
;
1529 pattern_offset_t laststart_offset
;
1531 } compile_stack_elt_t
;
1536 compile_stack_elt_t
*stack
;
1538 unsigned avail
; /* Offset of next open position. */
1539 } compile_stack_type
;
1542 #define INIT_COMPILE_STACK_SIZE 32
1544 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1545 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1547 /* The next available element. */
1548 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1551 /* Set the bit for character C in a list. */
1552 #define SET_LIST_BIT(c) \
1553 (b[((unsigned char) (c)) / BYTEWIDTH] \
1554 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1557 /* Get the next unsigned number in the uncompiled pattern. */
1558 #define GET_UNSIGNED_NUMBER(num) \
1562 while (ISDIGIT (c)) \
1566 num = num * 10 + c - '0'; \
1574 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1576 #define IS_CHAR_CLASS(string) \
1577 (STREQ (string, "alpha") || STREQ (string, "upper") \
1578 || STREQ (string, "lower") || STREQ (string, "digit") \
1579 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1580 || STREQ (string, "space") || STREQ (string, "print") \
1581 || STREQ (string, "punct") || STREQ (string, "graph") \
1582 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1584 #ifndef MATCH_MAY_ALLOCATE
1586 /* If we cannot allocate large objects within re_match_2_internal,
1587 we make the fail stack and register vectors global.
1588 The fail stack, we grow to the maximum size when a regexp
1590 The register vectors, we adjust in size each time we
1591 compile a regexp, according to the number of registers it needs. */
1593 static fail_stack_type fail_stack
;
1595 /* Size with which the following vectors are currently allocated.
1596 That is so we can make them bigger as needed,
1597 but never make them smaller. */
1598 static int regs_allocated_size
;
1600 static const char ** regstart
, ** regend
;
1601 static const char ** old_regstart
, ** old_regend
;
1602 static const char **best_regstart
, **best_regend
;
1603 static register_info_type
*reg_info
;
1604 static const char **reg_dummy
;
1605 static register_info_type
*reg_info_dummy
;
1607 /* Make the register vectors big enough for NUM_REGS registers,
1608 but don't make them smaller. */
1611 regex_grow_registers (num_regs
)
1614 if (num_regs
> regs_allocated_size
)
1616 RETALLOC_IF (regstart
, num_regs
, const char *);
1617 RETALLOC_IF (regend
, num_regs
, const char *);
1618 RETALLOC_IF (old_regstart
, num_regs
, const char *);
1619 RETALLOC_IF (old_regend
, num_regs
, const char *);
1620 RETALLOC_IF (best_regstart
, num_regs
, const char *);
1621 RETALLOC_IF (best_regend
, num_regs
, const char *);
1622 RETALLOC_IF (reg_info
, num_regs
, register_info_type
);
1623 RETALLOC_IF (reg_dummy
, num_regs
, const char *);
1624 RETALLOC_IF (reg_info_dummy
, num_regs
, register_info_type
);
1626 regs_allocated_size
= num_regs
;
1630 #endif /* not MATCH_MAY_ALLOCATE */
1632 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1633 Returns one of error codes defined in `regex.h', or zero for success.
1635 Assumes the `allocated' (and perhaps `buffer') and `translate'
1636 fields are set in BUFP on entry.
1638 If it succeeds, results are put in BUFP (if it returns an error, the
1639 contents of BUFP are undefined):
1640 `buffer' is the compiled pattern;
1641 `syntax' is set to SYNTAX;
1642 `used' is set to the length of the compiled pattern;
1643 `fastmap_accurate' is zero;
1644 `re_nsub' is the number of subexpressions in PATTERN;
1645 `not_bol' and `not_eol' are zero;
1647 The `fastmap' and `newline_anchor' fields are neither
1648 examined nor set. */
1650 /* Return, freeing storage we allocated. */
1651 #define FREE_STACK_RETURN(value) \
1652 return (free (compile_stack.stack), value)
1654 static reg_errcode_t
1655 regex_compile (pattern
, size
, syntax
, bufp
)
1656 const char *pattern
;
1658 reg_syntax_t syntax
;
1659 struct re_pattern_buffer
*bufp
;
1661 /* We fetch characters from PATTERN here. Even though PATTERN is
1662 `char *' (i.e., signed), we declare these variables as unsigned, so
1663 they can be reliably used as array indices. */
1664 register unsigned char c
, c1
;
1666 /* A random temporary spot in PATTERN. */
1669 /* Points to the end of the buffer, where we should append. */
1670 register unsigned char *b
;
1672 /* Keeps track of unclosed groups. */
1673 compile_stack_type compile_stack
;
1675 /* Points to the current (ending) position in the pattern. */
1676 const char *p
= pattern
;
1677 const char *pend
= pattern
+ size
;
1679 /* How to translate the characters in the pattern. */
1680 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
1682 /* Address of the count-byte of the most recently inserted `exactn'
1683 command. This makes it possible to tell if a new exact-match
1684 character can be added to that command or if the character requires
1685 a new `exactn' command. */
1686 unsigned char *pending_exact
= 0;
1688 /* Address of start of the most recently finished expression.
1689 This tells, e.g., postfix * where to find the start of its
1690 operand. Reset at the beginning of groups and alternatives. */
1691 unsigned char *laststart
= 0;
1693 /* Address of beginning of regexp, or inside of last group. */
1694 unsigned char *begalt
;
1696 /* Place in the uncompiled pattern (i.e., the {) to
1697 which to go back if the interval is invalid. */
1698 const char *beg_interval
;
1700 /* Address of the place where a forward jump should go to the end of
1701 the containing expression. Each alternative of an `or' -- except the
1702 last -- ends with a forward jump of this sort. */
1703 unsigned char *fixup_alt_jump
= 0;
1705 /* Counts open-groups as they are encountered. Remembered for the
1706 matching close-group on the compile stack, so the same register
1707 number is put in the stop_memory as the start_memory. */
1708 regnum_t regnum
= 0;
1711 DEBUG_PRINT1 ("\nCompiling pattern: ");
1714 unsigned debug_count
;
1716 for (debug_count
= 0; debug_count
< size
; debug_count
++)
1717 putchar (pattern
[debug_count
]);
1722 /* Initialize the compile stack. */
1723 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
1724 if (compile_stack
.stack
== NULL
)
1727 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
1728 compile_stack
.avail
= 0;
1730 /* Initialize the pattern buffer. */
1731 bufp
->syntax
= syntax
;
1732 bufp
->fastmap_accurate
= 0;
1733 bufp
->not_bol
= bufp
->not_eol
= 0;
1735 /* Set `used' to zero, so that if we return an error, the pattern
1736 printer (for debugging) will think there's no pattern. We reset it
1740 /* Always count groups, whether or not bufp->no_sub is set. */
1743 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1744 /* Initialize the syntax table. */
1745 init_syntax_once ();
1748 if (bufp
->allocated
== 0)
1751 { /* If zero allocated, but buffer is non-null, try to realloc
1752 enough space. This loses if buffer's address is bogus, but
1753 that is the user's responsibility. */
1754 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
1757 { /* Caller did not allocate a buffer. Do it for them. */
1758 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
1760 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
1762 bufp
->allocated
= INIT_BUF_SIZE
;
1765 begalt
= b
= bufp
->buffer
;
1767 /* Loop through the uncompiled pattern until we're at the end. */
1776 if ( /* If at start of pattern, it's an operator. */
1778 /* If context independent, it's an operator. */
1779 || syntax
& RE_CONTEXT_INDEP_ANCHORS
1780 /* Otherwise, depends on what's come before. */
1781 || at_begline_loc_p (pattern
, p
, syntax
))
1791 if ( /* If at end of pattern, it's an operator. */
1793 /* If context independent, it's an operator. */
1794 || syntax
& RE_CONTEXT_INDEP_ANCHORS
1795 /* Otherwise, depends on what's next. */
1796 || at_endline_loc_p (p
, pend
, syntax
))
1806 if ((syntax
& RE_BK_PLUS_QM
)
1807 || (syntax
& RE_LIMITED_OPS
))
1811 /* If there is no previous pattern... */
1814 if (syntax
& RE_CONTEXT_INVALID_OPS
)
1815 FREE_STACK_RETURN (REG_BADRPT
);
1816 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
1821 /* Are we optimizing this jump? */
1822 boolean keep_string_p
= false;
1824 /* 1 means zero (many) matches is allowed. */
1825 char zero_times_ok
= 0, many_times_ok
= 0;
1827 /* If there is a sequence of repetition chars, collapse it
1828 down to just one (the right one). We can't combine
1829 interval operators with these because of, e.g., `a{2}*',
1830 which should only match an even number of `a's. */
1834 zero_times_ok
|= c
!= '+';
1835 many_times_ok
|= c
!= '?';
1843 || (!(syntax
& RE_BK_PLUS_QM
) && (c
== '+' || c
== '?')))
1846 else if (syntax
& RE_BK_PLUS_QM
&& c
== '\\')
1848 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
1851 if (!(c1
== '+' || c1
== '?'))
1866 /* If we get here, we found another repeat character. */
1869 /* Star, etc. applied to an empty pattern is equivalent
1870 to an empty pattern. */
1874 /* Now we know whether or not zero matches is allowed
1875 and also whether or not two or more matches is allowed. */
1877 { /* More than one repetition is allowed, so put in at the
1878 end a backward relative jump from `b' to before the next
1879 jump we're going to put in below (which jumps from
1880 laststart to after this jump).
1882 But if we are at the `*' in the exact sequence `.*\n',
1883 insert an unconditional jump backwards to the .,
1884 instead of the beginning of the loop. This way we only
1885 push a failure point once, instead of every time
1886 through the loop. */
1887 assert (p
- 1 > pattern
);
1889 /* Allocate the space for the jump. */
1890 GET_BUFFER_SPACE (3);
1892 /* We know we are not at the first character of the pattern,
1893 because laststart was nonzero. And we've already
1894 incremented `p', by the way, to be the character after
1895 the `*'. Do we have to do something analogous here
1896 for null bytes, because of RE_DOT_NOT_NULL? */
1897 if (TRANSLATE (*(p
- 2)) == TRANSLATE ('.')
1899 && p
< pend
&& TRANSLATE (*p
) == TRANSLATE ('\n')
1900 && !(syntax
& RE_DOT_NEWLINE
))
1901 { /* We have .*\n. */
1902 STORE_JUMP (jump
, b
, laststart
);
1903 keep_string_p
= true;
1906 /* Anything else. */
1907 STORE_JUMP (maybe_pop_jump
, b
, laststart
- 3);
1909 /* We've added more stuff to the buffer. */
1913 /* On failure, jump from laststart to b + 3, which will be the
1914 end of the buffer after this jump is inserted. */
1915 GET_BUFFER_SPACE (3);
1916 INSERT_JUMP (keep_string_p
? on_failure_keep_string_jump
1924 /* At least one repetition is required, so insert a
1925 `dummy_failure_jump' before the initial
1926 `on_failure_jump' instruction of the loop. This
1927 effects a skip over that instruction the first time
1928 we hit that loop. */
1929 GET_BUFFER_SPACE (3);
1930 INSERT_JUMP (dummy_failure_jump
, laststart
, laststart
+ 6);
1945 boolean had_char_class
= false;
1947 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
1949 /* Ensure that we have enough space to push a charset: the
1950 opcode, the length count, and the bitset; 34 bytes in all. */
1951 GET_BUFFER_SPACE (34);
1955 /* We test `*p == '^' twice, instead of using an if
1956 statement, so we only need one BUF_PUSH. */
1957 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
1961 /* Remember the first position in the bracket expression. */
1964 /* Push the number of bytes in the bitmap. */
1965 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
1967 /* Clear the whole map. */
1968 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
1970 /* charset_not matches newline according to a syntax bit. */
1971 if ((re_opcode_t
) b
[-2] == charset_not
1972 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
1973 SET_LIST_BIT ('\n');
1975 /* Read in characters and ranges, setting map bits. */
1978 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
1982 /* \ might escape characters inside [...] and [^...]. */
1983 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
1985 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
1992 /* Could be the end of the bracket expression. If it's
1993 not (i.e., when the bracket expression is `[]' so
1994 far), the ']' character bit gets set way below. */
1995 if (c
== ']' && p
!= p1
+ 1)
1998 /* Look ahead to see if it's a range when the last thing
1999 was a character class. */
2000 if (had_char_class
&& c
== '-' && *p
!= ']')
2001 FREE_STACK_RETURN (REG_ERANGE
);
2003 /* Look ahead to see if it's a range when the last thing
2004 was a character: if this is a hyphen not at the
2005 beginning or the end of a list, then it's the range
2008 && !(p
- 2 >= pattern
&& p
[-2] == '[')
2009 && !(p
- 3 >= pattern
&& p
[-3] == '[' && p
[-2] == '^')
2013 = compile_range (&p
, pend
, translate
, syntax
, b
);
2014 if (ret
!= REG_NOERROR
) FREE_STACK_RETURN (ret
);
2017 else if (p
[0] == '-' && p
[1] != ']')
2018 { /* This handles ranges made up of characters only. */
2021 /* Move past the `-'. */
2024 ret
= compile_range (&p
, pend
, translate
, syntax
, b
);
2025 if (ret
!= REG_NOERROR
) FREE_STACK_RETURN (ret
);
2028 /* See if we're at the beginning of a possible character
2031 else if (syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2032 { /* Leave room for the null. */
2033 char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2038 /* If pattern is `[[:'. */
2039 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2044 if (c
== ':' || c
== ']' || p
== pend
2045 || c1
== CHAR_CLASS_MAX_LENGTH
)
2051 /* If isn't a word bracketed by `[:' and:`]':
2052 undo the ending character, the letters, and leave
2053 the leading `:' and `[' (but set bits for them). */
2054 if (c
== ':' && *p
== ']')
2057 boolean is_alnum
= STREQ (str
, "alnum");
2058 boolean is_alpha
= STREQ (str
, "alpha");
2059 boolean is_blank
= STREQ (str
, "blank");
2060 boolean is_cntrl
= STREQ (str
, "cntrl");
2061 boolean is_digit
= STREQ (str
, "digit");
2062 boolean is_graph
= STREQ (str
, "graph");
2063 boolean is_lower
= STREQ (str
, "lower");
2064 boolean is_print
= STREQ (str
, "print");
2065 boolean is_punct
= STREQ (str
, "punct");
2066 boolean is_space
= STREQ (str
, "space");
2067 boolean is_upper
= STREQ (str
, "upper");
2068 boolean is_xdigit
= STREQ (str
, "xdigit");
2070 if (!IS_CHAR_CLASS (str
))
2071 FREE_STACK_RETURN (REG_ECTYPE
);
2073 /* Throw away the ] at the end of the character
2077 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2079 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ch
++)
2081 /* This was split into 3 if's to
2082 avoid an arbitrary limit in some compiler. */
2083 if ( (is_alnum
&& ISALNUM (ch
))
2084 || (is_alpha
&& ISALPHA (ch
))
2085 || (is_blank
&& ISBLANK (ch
))
2086 || (is_cntrl
&& ISCNTRL (ch
)))
2088 if ( (is_digit
&& ISDIGIT (ch
))
2089 || (is_graph
&& ISGRAPH (ch
))
2090 || (is_lower
&& ISLOWER (ch
))
2091 || (is_print
&& ISPRINT (ch
)))
2093 if ( (is_punct
&& ISPUNCT (ch
))
2094 || (is_space
&& ISSPACE (ch
))
2095 || (is_upper
&& ISUPPER (ch
))
2096 || (is_xdigit
&& ISXDIGIT (ch
)))
2099 had_char_class
= true;
2108 had_char_class
= false;
2113 had_char_class
= false;
2118 /* Discard any (non)matching list bytes that are all 0 at the
2119 end of the map. Decrease the map-length byte too. */
2120 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2128 if (syntax
& RE_NO_BK_PARENS
)
2135 if (syntax
& RE_NO_BK_PARENS
)
2142 if (syntax
& RE_NEWLINE_ALT
)
2149 if (syntax
& RE_NO_BK_VBAR
)
2156 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2157 goto handle_interval
;
2163 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2165 /* Do not translate the character after the \, so that we can
2166 distinguish, e.g., \B from \b, even if we normally would
2167 translate, e.g., B to b. */
2173 if (syntax
& RE_NO_BK_PARENS
)
2174 goto normal_backslash
;
2180 if (COMPILE_STACK_FULL
)
2182 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
2183 compile_stack_elt_t
);
2184 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
2186 compile_stack
.size
<<= 1;
2189 /* These are the values to restore when we hit end of this
2190 group. They are all relative offsets, so that if the
2191 whole pattern moves because of realloc, they will still
2193 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
2194 COMPILE_STACK_TOP
.fixup_alt_jump
2195 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
2196 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
2197 COMPILE_STACK_TOP
.regnum
= regnum
;
2199 /* We will eventually replace the 0 with the number of
2200 groups inner to this one. But do not push a
2201 start_memory for groups beyond the last one we can
2202 represent in the compiled pattern. */
2203 if (regnum
<= MAX_REGNUM
)
2205 COMPILE_STACK_TOP
.inner_group_offset
= b
- bufp
->buffer
+ 2;
2206 BUF_PUSH_3 (start_memory
, regnum
, 0);
2209 compile_stack
.avail
++;
2214 /* If we've reached MAX_REGNUM groups, then this open
2215 won't actually generate any code, so we'll have to
2216 clear pending_exact explicitly. */
2222 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
2224 if (COMPILE_STACK_EMPTY
)
2225 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2226 goto normal_backslash
;
2228 FREE_STACK_RETURN (REG_ERPAREN
);
2232 { /* Push a dummy failure point at the end of the
2233 alternative for a possible future
2234 `pop_failure_jump' to pop. See comments at
2235 `push_dummy_failure' in `re_match_2'. */
2236 BUF_PUSH (push_dummy_failure
);
2238 /* We allocated space for this jump when we assigned
2239 to `fixup_alt_jump', in the `handle_alt' case below. */
2240 STORE_JUMP (jump_past_alt
, fixup_alt_jump
, b
- 1);
2243 /* See similar code for backslashed left paren above. */
2244 if (COMPILE_STACK_EMPTY
)
2245 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2248 FREE_STACK_RETURN (REG_ERPAREN
);
2250 /* Since we just checked for an empty stack above, this
2251 ``can't happen''. */
2252 assert (compile_stack
.avail
!= 0);
2254 /* We don't just want to restore into `regnum', because
2255 later groups should continue to be numbered higher,
2256 as in `(ab)c(de)' -- the second group is #2. */
2257 regnum_t this_group_regnum
;
2259 compile_stack
.avail
--;
2260 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
2262 = COMPILE_STACK_TOP
.fixup_alt_jump
2263 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
2265 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
2266 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
2267 /* If we've reached MAX_REGNUM groups, then this open
2268 won't actually generate any code, so we'll have to
2269 clear pending_exact explicitly. */
2272 /* We're at the end of the group, so now we know how many
2273 groups were inside this one. */
2274 if (this_group_regnum
<= MAX_REGNUM
)
2276 unsigned char *inner_group_loc
2277 = bufp
->buffer
+ COMPILE_STACK_TOP
.inner_group_offset
;
2279 *inner_group_loc
= regnum
- this_group_regnum
;
2280 BUF_PUSH_3 (stop_memory
, this_group_regnum
,
2281 regnum
- this_group_regnum
);
2287 case '|': /* `\|'. */
2288 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2289 goto normal_backslash
;
2291 if (syntax
& RE_LIMITED_OPS
)
2294 /* Insert before the previous alternative a jump which
2295 jumps to this alternative if the former fails. */
2296 GET_BUFFER_SPACE (3);
2297 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
2301 /* The alternative before this one has a jump after it
2302 which gets executed if it gets matched. Adjust that
2303 jump so it will jump to this alternative's analogous
2304 jump (put in below, which in turn will jump to the next
2305 (if any) alternative's such jump, etc.). The last such
2306 jump jumps to the correct final destination. A picture:
2312 If we are at `b', then fixup_alt_jump right now points to a
2313 three-byte space after `a'. We'll put in the jump, set
2314 fixup_alt_jump to right after `b', and leave behind three
2315 bytes which we'll fill in when we get to after `c'. */
2318 STORE_JUMP (jump_past_alt
, fixup_alt_jump
, b
);
2320 /* Mark and leave space for a jump after this alternative,
2321 to be filled in later either by next alternative or
2322 when know we're at the end of a series of alternatives. */
2324 GET_BUFFER_SPACE (3);
2333 /* If \{ is a literal. */
2334 if (!(syntax
& RE_INTERVALS
)
2335 /* If we're at `\{' and it's not the open-interval
2337 || ((syntax
& RE_INTERVALS
) && (syntax
& RE_NO_BK_BRACES
))
2338 || (p
- 2 == pattern
&& p
== pend
))
2339 goto normal_backslash
;
2343 /* If got here, then the syntax allows intervals. */
2345 /* At least (most) this many matches must be made. */
2346 int lower_bound
= -1, upper_bound
= -1;
2348 beg_interval
= p
- 1;
2352 if (syntax
& RE_NO_BK_BRACES
)
2353 goto unfetch_interval
;
2355 FREE_STACK_RETURN (REG_EBRACE
);
2358 GET_UNSIGNED_NUMBER (lower_bound
);
2362 GET_UNSIGNED_NUMBER (upper_bound
);
2363 if (upper_bound
< 0) upper_bound
= RE_DUP_MAX
;
2366 /* Interval such as `{1}' => match exactly once. */
2367 upper_bound
= lower_bound
;
2369 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
2370 || lower_bound
> upper_bound
)
2372 if (syntax
& RE_NO_BK_BRACES
)
2373 goto unfetch_interval
;
2375 FREE_STACK_RETURN (REG_BADBR
);
2378 if (!(syntax
& RE_NO_BK_BRACES
))
2380 if (c
!= '\\') FREE_STACK_RETURN (REG_EBRACE
);
2387 if (syntax
& RE_NO_BK_BRACES
)
2388 goto unfetch_interval
;
2390 FREE_STACK_RETURN (REG_BADBR
);
2393 /* We just parsed a valid interval. */
2395 /* If it's invalid to have no preceding re. */
2398 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2399 FREE_STACK_RETURN (REG_BADRPT
);
2400 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
2403 goto unfetch_interval
;
2406 /* If the upper bound is zero, don't want to succeed at
2407 all; jump from `laststart' to `b + 3', which will be
2408 the end of the buffer after we insert the jump. */
2409 if (upper_bound
== 0)
2411 GET_BUFFER_SPACE (3);
2412 INSERT_JUMP (jump
, laststart
, b
+ 3);
2416 /* Otherwise, we have a nontrivial interval. When
2417 we're all done, the pattern will look like:
2418 set_number_at <jump count> <upper bound>
2419 set_number_at <succeed_n count> <lower bound>
2420 succeed_n <after jump addr> <succeed_n count>
2422 jump_n <succeed_n addr> <jump count>
2423 (The upper bound and `jump_n' are omitted if
2424 `upper_bound' is 1, though.) */
2426 { /* If the upper bound is > 1, we need to insert
2427 more at the end of the loop. */
2428 unsigned nbytes
= 10 + (upper_bound
> 1) * 10;
2430 GET_BUFFER_SPACE (nbytes
);
2432 /* Initialize lower bound of the `succeed_n', even
2433 though it will be set during matching by its
2434 attendant `set_number_at' (inserted next),
2435 because `re_compile_fastmap' needs to know.
2436 Jump to the `jump_n' we might insert below. */
2437 INSERT_JUMP2 (succeed_n
, laststart
,
2438 b
+ 5 + (upper_bound
> 1) * 5,
2442 /* Code to initialize the lower bound. Insert
2443 before the `succeed_n'. The `5' is the last two
2444 bytes of this `set_number_at', plus 3 bytes of
2445 the following `succeed_n'. */
2446 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
2449 if (upper_bound
> 1)
2450 { /* More than one repetition is allowed, so
2451 append a backward jump to the `succeed_n'
2452 that starts this interval.
2454 When we've reached this during matching,
2455 we'll have matched the interval once, so
2456 jump back only `upper_bound - 1' times. */
2457 STORE_JUMP2 (jump_n
, b
, laststart
+ 5,
2461 /* The location we want to set is the second
2462 parameter of the `jump_n'; that is `b-2' as
2463 an absolute address. `laststart' will be
2464 the `set_number_at' we're about to insert;
2465 `laststart+3' the number to set, the source
2466 for the relative address. But we are
2467 inserting into the middle of the pattern --
2468 so everything is getting moved up by 5.
2469 Conclusion: (b - 2) - (laststart + 3) + 5,
2470 i.e., b - laststart.
2472 We insert this at the beginning of the loop
2473 so that if we fail during matching, we'll
2474 reinitialize the bounds. */
2475 insert_op2 (set_number_at
, laststart
, b
- laststart
,
2476 upper_bound
- 1, b
);
2481 beg_interval
= NULL
;
2486 /* If an invalid interval, match the characters as literals. */
2487 assert (beg_interval
);
2489 beg_interval
= NULL
;
2491 /* normal_char and normal_backslash need `c'. */
2494 if (!(syntax
& RE_NO_BK_BRACES
))
2496 if (p
> pattern
&& p
[-1] == '\\')
2497 goto normal_backslash
;
2502 /* There is no way to specify the before_dot and after_dot
2503 operators. rms says this is ok. --karl */
2511 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
2517 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
2524 BUF_PUSH (wordchar
);
2530 BUF_PUSH (notwordchar
);
2543 BUF_PUSH (wordbound
);
2547 BUF_PUSH (notwordbound
);
2558 case '1': case '2': case '3': case '4': case '5':
2559 case '6': case '7': case '8': case '9':
2560 if (syntax
& RE_NO_BK_REFS
)
2566 FREE_STACK_RETURN (REG_ESUBREG
);
2568 /* Can't back reference to a subexpression if inside of it. */
2569 if (group_in_compile_stack (compile_stack
, c1
))
2573 BUF_PUSH_2 (duplicate
, c1
);
2579 if (syntax
& RE_BK_PLUS_QM
)
2582 goto normal_backslash
;
2586 /* You might think it would be useful for \ to mean
2587 not to translate; but if we don't translate it
2588 it will never match anything. */
2596 /* Expects the character in `c'. */
2598 /* If no exactn currently being built. */
2601 /* If last exactn not at current position. */
2602 || pending_exact
+ *pending_exact
+ 1 != b
2604 /* We have only one byte following the exactn for the count. */
2605 || *pending_exact
== (1 << BYTEWIDTH
) - 1
2607 /* If followed by a repetition operator. */
2608 || *p
== '*' || *p
== '^'
2609 || ((syntax
& RE_BK_PLUS_QM
)
2610 ? *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
2611 : (*p
== '+' || *p
== '?'))
2612 || ((syntax
& RE_INTERVALS
)
2613 && ((syntax
& RE_NO_BK_BRACES
)
2615 : (p
[0] == '\\' && p
[1] == '{'))))
2617 /* Start building a new exactn. */
2621 BUF_PUSH_2 (exactn
, 0);
2622 pending_exact
= b
- 1;
2629 } /* while p != pend */
2632 /* Through the pattern now. */
2635 STORE_JUMP (jump_past_alt
, fixup_alt_jump
, b
);
2637 if (!COMPILE_STACK_EMPTY
)
2638 FREE_STACK_RETURN (REG_EPAREN
);
2640 /* If we don't want backtracking, force success
2641 the first time we reach the end of the compiled pattern. */
2642 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
2645 free (compile_stack
.stack
);
2647 /* We have succeeded; set the length of the buffer. */
2648 bufp
->used
= b
- bufp
->buffer
;
2653 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2654 print_compiled_pattern (bufp
);
2658 #ifndef MATCH_MAY_ALLOCATE
2659 /* Initialize the failure stack to the largest possible stack. This
2660 isn't necessary unless we're trying to avoid calling alloca in
2661 the search and match routines. */
2663 int num_regs
= bufp
->re_nsub
+ 1;
2665 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
2666 is strictly greater than re_max_failures, the largest possible stack
2667 is 2 * re_max_failures failure points. */
2668 if (fail_stack
.size
< (2 * re_max_failures
* MAX_FAILURE_ITEMS
))
2670 fail_stack
.size
= (2 * re_max_failures
* MAX_FAILURE_ITEMS
);
2673 if (! fail_stack
.stack
)
2675 = (fail_stack_elt_t
*) xmalloc (fail_stack
.size
2676 * sizeof (fail_stack_elt_t
));
2679 = (fail_stack_elt_t
*) xrealloc (fail_stack
.stack
,
2681 * sizeof (fail_stack_elt_t
)));
2682 #else /* not emacs */
2683 if (! fail_stack
.stack
)
2685 = (fail_stack_elt_t
*) malloc (fail_stack
.size
2686 * sizeof (fail_stack_elt_t
));
2689 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
2691 * sizeof (fail_stack_elt_t
)));
2692 #endif /* not emacs */
2695 regex_grow_registers (num_regs
);
2697 #endif /* not MATCH_MAY_ALLOCATE */
2700 } /* regex_compile */
2702 /* Subroutines for `regex_compile'. */
2704 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2707 store_op1 (op
, loc
, arg
)
2712 *loc
= (unsigned char) op
;
2713 STORE_NUMBER (loc
+ 1, arg
);
2717 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2720 store_op2 (op
, loc
, arg1
, arg2
)
2725 *loc
= (unsigned char) op
;
2726 STORE_NUMBER (loc
+ 1, arg1
);
2727 STORE_NUMBER (loc
+ 3, arg2
);
2731 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2732 for OP followed by two-byte integer parameter ARG. */
2735 insert_op1 (op
, loc
, arg
, end
)
2741 register unsigned char *pfrom
= end
;
2742 register unsigned char *pto
= end
+ 3;
2744 while (pfrom
!= loc
)
2747 store_op1 (op
, loc
, arg
);
2751 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2754 insert_op2 (op
, loc
, arg1
, arg2
, end
)
2760 register unsigned char *pfrom
= end
;
2761 register unsigned char *pto
= end
+ 5;
2763 while (pfrom
!= loc
)
2766 store_op2 (op
, loc
, arg1
, arg2
);
2770 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2771 after an alternative or a begin-subexpression. We assume there is at
2772 least one character before the ^. */
2775 at_begline_loc_p (pattern
, p
, syntax
)
2776 const char *pattern
, *p
;
2777 reg_syntax_t syntax
;
2779 const char *prev
= p
- 2;
2780 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
2783 /* After a subexpression? */
2784 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
2785 /* After an alternative? */
2786 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
));
2790 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2791 at least one character after the $, i.e., `P < PEND'. */
2794 at_endline_loc_p (p
, pend
, syntax
)
2795 const char *p
, *pend
;
2798 const char *next
= p
;
2799 boolean next_backslash
= *next
== '\\';
2800 const char *next_next
= p
+ 1 < pend
? p
+ 1 : 0;
2803 /* Before a subexpression? */
2804 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
2805 : next_backslash
&& next_next
&& *next_next
== ')')
2806 /* Before an alternative? */
2807 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
2808 : next_backslash
&& next_next
&& *next_next
== '|');
2812 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2813 false if it's not. */
2816 group_in_compile_stack (compile_stack
, regnum
)
2817 compile_stack_type compile_stack
;
2822 for (this_element
= compile_stack
.avail
- 1;
2825 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
2832 /* Read the ending character of a range (in a bracket expression) from the
2833 uncompiled pattern *P_PTR (which ends at PEND). We assume the
2834 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2835 Then we set the translation of all bits between the starting and
2836 ending characters (inclusive) in the compiled pattern B.
2838 Return an error code.
2840 We use these short variable names so we can use the same macros as
2841 `regex_compile' itself. */
2843 static reg_errcode_t
2844 compile_range (p_ptr
, pend
, translate
, syntax
, b
)
2845 const char **p_ptr
, *pend
;
2846 RE_TRANSLATE_TYPE translate
;
2847 reg_syntax_t syntax
;
2852 const char *p
= *p_ptr
;
2853 int range_start
, range_end
;
2858 /* Even though the pattern is a signed `char *', we need to fetch
2859 with unsigned char *'s; if the high bit of the pattern character
2860 is set, the range endpoints will be negative if we fetch using a
2863 We also want to fetch the endpoints without translating them; the
2864 appropriate translation is done in the bit-setting loop below. */
2865 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
2866 range_start
= ((const unsigned char *) p
)[-2];
2867 range_end
= ((const unsigned char *) p
)[0];
2869 /* Have to increment the pointer into the pattern string, so the
2870 caller isn't still at the ending character. */
2873 /* If the start is after the end, the range is empty. */
2874 if (range_start
> range_end
)
2875 return syntax
& RE_NO_EMPTY_RANGES
? REG_ERANGE
: REG_NOERROR
;
2877 /* Here we see why `this_char' has to be larger than an `unsigned
2878 char' -- the range is inclusive, so if `range_end' == 0xff
2879 (assuming 8-bit characters), we would otherwise go into an infinite
2880 loop, since all characters <= 0xff. */
2881 for (this_char
= range_start
; this_char
<= range_end
; this_char
++)
2883 SET_LIST_BIT (TRANSLATE (this_char
));
2889 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2890 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2891 characters can start a string that matches the pattern. This fastmap
2892 is used by re_search to skip quickly over impossible starting points.
2894 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2895 area as BUFP->fastmap.
2897 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2900 Returns 0 if we succeed, -2 if an internal error. */
2903 re_compile_fastmap (bufp
)
2904 struct re_pattern_buffer
*bufp
;
2907 #ifdef MATCH_MAY_ALLOCATE
2908 fail_stack_type fail_stack
;
2910 #ifndef REGEX_MALLOC
2913 /* We don't push any register information onto the failure stack. */
2914 unsigned num_regs
= 0;
2916 register char *fastmap
= bufp
->fastmap
;
2917 unsigned char *pattern
= bufp
->buffer
;
2918 unsigned long size
= bufp
->used
;
2919 unsigned char *p
= pattern
;
2920 register unsigned char *pend
= pattern
+ size
;
2922 /* This holds the pointer to the failure stack, when
2923 it is allocated relocatably. */
2925 fail_stack_elt_t
*failure_stack_ptr
;
2928 /* Assume that each path through the pattern can be null until
2929 proven otherwise. We set this false at the bottom of switch
2930 statement, to which we get only if a particular path doesn't
2931 match the empty string. */
2932 boolean path_can_be_null
= true;
2934 /* We aren't doing a `succeed_n' to begin with. */
2935 boolean succeed_n_p
= false;
2937 assert (fastmap
!= NULL
&& p
!= NULL
);
2940 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
2941 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
2942 bufp
->can_be_null
= 0;
2946 if (p
== pend
|| *p
== succeed
)
2948 /* We have reached the (effective) end of pattern. */
2949 if (!FAIL_STACK_EMPTY ())
2951 bufp
->can_be_null
|= path_can_be_null
;
2953 /* Reset for next path. */
2954 path_can_be_null
= true;
2956 p
= fail_stack
.stack
[--fail_stack
.avail
].pointer
;
2964 /* We should never be about to go beyond the end of the pattern. */
2967 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
2970 /* I guess the idea here is to simply not bother with a fastmap
2971 if a backreference is used, since it's too hard to figure out
2972 the fastmap for the corresponding group. Setting
2973 `can_be_null' stops `re_search_2' from using the fastmap, so
2974 that is all we do. */
2976 bufp
->can_be_null
= 1;
2980 /* Following are the cases which match a character. These end
2989 for (j
= *p
++ * BYTEWIDTH
- 1; j
>= 0; j
--)
2990 if (p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
)))
2996 /* Chars beyond end of map must be allowed. */
2997 for (j
= *p
* BYTEWIDTH
; j
< (1 << BYTEWIDTH
); j
++)
3000 for (j
= *p
++ * BYTEWIDTH
- 1; j
>= 0; j
--)
3001 if (!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))))
3007 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3008 if (SYNTAX (j
) == Sword
)
3014 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3015 if (SYNTAX (j
) != Sword
)
3022 int fastmap_newline
= fastmap
['\n'];
3024 /* `.' matches anything ... */
3025 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3028 /* ... except perhaps newline. */
3029 if (!(bufp
->syntax
& RE_DOT_NEWLINE
))
3030 fastmap
['\n'] = fastmap_newline
;
3032 /* Return if we have already set `can_be_null'; if we have,
3033 then the fastmap is irrelevant. Something's wrong here. */
3034 else if (bufp
->can_be_null
)
3037 /* Otherwise, have to check alternative paths. */
3044 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3045 if (SYNTAX (j
) == (enum syntaxcode
) k
)
3052 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3053 if (SYNTAX (j
) != (enum syntaxcode
) k
)
3058 /* All cases after this match the empty string. These end with
3078 case push_dummy_failure
:
3083 case pop_failure_jump
:
3084 case maybe_pop_jump
:
3087 case dummy_failure_jump
:
3088 EXTRACT_NUMBER_AND_INCR (j
, p
);
3093 /* Jump backward implies we just went through the body of a
3094 loop and matched nothing. Opcode jumped to should be
3095 `on_failure_jump' or `succeed_n'. Just treat it like an
3096 ordinary jump. For a * loop, it has pushed its failure
3097 point already; if so, discard that as redundant. */
3098 if ((re_opcode_t
) *p
!= on_failure_jump
3099 && (re_opcode_t
) *p
!= succeed_n
)
3103 EXTRACT_NUMBER_AND_INCR (j
, p
);
3106 /* If what's on the stack is where we are now, pop it. */
3107 if (!FAIL_STACK_EMPTY ()
3108 && fail_stack
.stack
[fail_stack
.avail
- 1].pointer
== p
)
3114 case on_failure_jump
:
3115 case on_failure_keep_string_jump
:
3116 handle_on_failure_jump
:
3117 EXTRACT_NUMBER_AND_INCR (j
, p
);
3119 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3120 end of the pattern. We don't want to push such a point,
3121 since when we restore it above, entering the switch will
3122 increment `p' past the end of the pattern. We don't need
3123 to push such a point since we obviously won't find any more
3124 fastmap entries beyond `pend'. Such a pattern can match
3125 the null string, though. */
3128 if (!PUSH_PATTERN_OP (p
+ j
, fail_stack
))
3130 RESET_FAIL_STACK ();
3135 bufp
->can_be_null
= 1;
3139 EXTRACT_NUMBER_AND_INCR (k
, p
); /* Skip the n. */
3140 succeed_n_p
= false;
3147 /* Get to the number of times to succeed. */
3150 /* Increment p past the n for when k != 0. */
3151 EXTRACT_NUMBER_AND_INCR (k
, p
);
3155 succeed_n_p
= true; /* Spaghetti code alert. */
3156 goto handle_on_failure_jump
;
3173 abort (); /* We have listed all the cases. */
3176 /* Getting here means we have found the possible starting
3177 characters for one path of the pattern -- and that the empty
3178 string does not match. We need not follow this path further.
3179 Instead, look at the next alternative (remembered on the
3180 stack), or quit if no more. The test at the top of the loop
3181 does these things. */
3182 path_can_be_null
= false;
3186 /* Set `can_be_null' for the last path (also the first path, if the
3187 pattern is empty). */
3188 bufp
->can_be_null
|= path_can_be_null
;
3191 RESET_FAIL_STACK ();
3193 } /* re_compile_fastmap */
3195 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3196 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3197 this memory for recording register information. STARTS and ENDS
3198 must be allocated using the malloc library routine, and must each
3199 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3201 If NUM_REGS == 0, then subsequent matches should allocate their own
3204 Unless this function is called, the first search or match using
3205 PATTERN_BUFFER will allocate its own register data, without
3206 freeing the old data. */
3209 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3210 struct re_pattern_buffer
*bufp
;
3211 struct re_registers
*regs
;
3213 regoff_t
*starts
, *ends
;
3217 bufp
->regs_allocated
= REGS_REALLOCATE
;
3218 regs
->num_regs
= num_regs
;
3219 regs
->start
= starts
;
3224 bufp
->regs_allocated
= REGS_UNALLOCATED
;
3226 regs
->start
= regs
->end
= (regoff_t
*) 0;
3230 /* Searching routines. */
3232 /* Like re_search_2, below, but only one string is specified, and
3233 doesn't let you say where to stop matching. */
3236 re_search (bufp
, string
, size
, startpos
, range
, regs
)
3237 struct re_pattern_buffer
*bufp
;
3239 int size
, startpos
, range
;
3240 struct re_registers
*regs
;
3242 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
3247 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3248 virtual concatenation of STRING1 and STRING2, starting first at index
3249 STARTPOS, then at STARTPOS + 1, and so on.
3251 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3253 RANGE is how far to scan while trying to match. RANGE = 0 means try
3254 only at STARTPOS; in general, the last start tried is STARTPOS +
3257 In REGS, return the indices of the virtual concatenation of STRING1
3258 and STRING2 that matched the entire BUFP->buffer and its contained
3261 Do not consider matching one past the index STOP in the virtual
3262 concatenation of STRING1 and STRING2.
3264 We return either the position in the strings at which the match was
3265 found, -1 if no match, or -2 if error (such as failure
3269 re_search_2 (bufp
, string1
, size1
, string2
, size2
, startpos
, range
, regs
, stop
)
3270 struct re_pattern_buffer
*bufp
;
3271 const char *string1
, *string2
;
3275 struct re_registers
*regs
;
3279 register char *fastmap
= bufp
->fastmap
;
3280 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3281 int total_size
= size1
+ size2
;
3282 int endpos
= startpos
+ range
;
3284 /* Check for out-of-range STARTPOS. */
3285 if (startpos
< 0 || startpos
> total_size
)
3288 /* Fix up RANGE if it might eventually take us outside
3289 the virtual concatenation of STRING1 and STRING2.
3290 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3292 range
= 0 - startpos
;
3293 else if (endpos
> total_size
)
3294 range
= total_size
- startpos
;
3296 /* If the search isn't to be a backwards one, don't waste time in a
3297 search for a pattern that must be anchored. */
3298 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
3307 /* In a forward search for something that starts with \=.
3308 don't keep searching past point. */
3309 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
3311 range
= PT
- startpos
;
3317 /* Update the fastmap now if not correct already. */
3318 if (fastmap
&& !bufp
->fastmap_accurate
)
3319 if (re_compile_fastmap (bufp
) == -2)
3322 /* Loop through the string, looking for a place to start matching. */
3325 /* If a fastmap is supplied, skip quickly over characters that
3326 cannot be the start of a match. If the pattern can match the
3327 null string, however, we don't need to skip characters; we want
3328 the first null string. */
3329 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
3331 if (range
> 0) /* Searching forwards. */
3333 register const char *d
;
3334 register int lim
= 0;
3337 if (startpos
< size1
&& startpos
+ range
>= size1
)
3338 lim
= range
- (size1
- startpos
);
3340 d
= (startpos
>= size1
? string2
- size1
: string1
) + startpos
;
3342 /* Written out as an if-else to avoid testing `translate'
3346 && !fastmap
[(unsigned char)
3347 translate
[(unsigned char) *d
++]])
3350 while (range
> lim
&& !fastmap
[(unsigned char) *d
++])
3353 startpos
+= irange
- range
;
3355 else /* Searching backwards. */
3357 register char c
= (size1
== 0 || startpos
>= size1
3358 ? string2
[startpos
- size1
]
3359 : string1
[startpos
]);
3361 if (!fastmap
[(unsigned char) TRANSLATE (c
)])
3366 /* If can't match the null string, and that's all we have left, fail. */
3367 if (range
>= 0 && startpos
== total_size
&& fastmap
3368 && !bufp
->can_be_null
)
3371 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3372 startpos
, regs
, stop
);
3373 #ifndef REGEX_MALLOC
3402 /* Declarations and macros for re_match_2. */
3404 static int bcmp_translate ();
3405 static boolean
alt_match_null_string_p (),
3406 common_op_match_null_string_p (),
3407 group_match_null_string_p ();
3409 /* This converts PTR, a pointer into one of the search strings `string1'
3410 and `string2' into an offset from the beginning of that string. */
3411 #define POINTER_TO_OFFSET(ptr) \
3412 (FIRST_STRING_P (ptr) \
3413 ? ((regoff_t) ((ptr) - string1)) \
3414 : ((regoff_t) ((ptr) - string2 + size1)))
3416 /* Macros for dealing with the split strings in re_match_2. */
3418 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3420 /* Call before fetching a character with *d. This switches over to
3421 string2 if necessary. */
3422 #define PREFETCH() \
3425 /* End of string2 => fail. */ \
3426 if (dend == end_match_2) \
3428 /* End of string1 => advance to string2. */ \
3430 dend = end_match_2; \
3434 /* Test if at very beginning or at very end of the virtual concatenation
3435 of `string1' and `string2'. If only one string, it's `string2'. */
3436 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3437 #define AT_STRINGS_END(d) ((d) == end2)
3440 /* Test if D points to a character which is word-constituent. We have
3441 two special cases to check for: if past the end of string1, look at
3442 the first character in string2; and if before the beginning of
3443 string2, look at the last character in string1. */
3444 #define WORDCHAR_P(d) \
3445 (SYNTAX ((d) == end1 ? *string2 \
3446 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3449 /* Disabled due to a compiler bug -- see comment at case wordbound */
3451 /* Test if the character before D and the one at D differ with respect
3452 to being word-constituent. */
3453 #define AT_WORD_BOUNDARY(d) \
3454 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3455 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3458 /* Free everything we malloc. */
3459 #ifdef MATCH_MAY_ALLOCATE
3460 #define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
3461 #define FREE_VARIABLES() \
3463 REGEX_FREE_STACK (fail_stack.stack); \
3464 FREE_VAR (regstart); \
3465 FREE_VAR (regend); \
3466 FREE_VAR (old_regstart); \
3467 FREE_VAR (old_regend); \
3468 FREE_VAR (best_regstart); \
3469 FREE_VAR (best_regend); \
3470 FREE_VAR (reg_info); \
3471 FREE_VAR (reg_dummy); \
3472 FREE_VAR (reg_info_dummy); \
3475 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
3476 #endif /* not MATCH_MAY_ALLOCATE */
3478 /* These values must meet several constraints. They must not be valid
3479 register values; since we have a limit of 255 registers (because
3480 we use only one byte in the pattern for the register number), we can
3481 use numbers larger than 255. They must differ by 1, because of
3482 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3483 be larger than the value for the highest register, so we do not try
3484 to actually save any registers when none are active. */
3485 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3486 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3488 /* Matching routines. */
3490 #ifndef emacs /* Emacs never uses this. */
3491 /* re_match is like re_match_2 except it takes only a single string. */
3494 re_match (bufp
, string
, size
, pos
, regs
)
3495 struct re_pattern_buffer
*bufp
;
3498 struct re_registers
*regs
;
3500 int result
= re_match_2_internal (bufp
, NULL
, 0, string
, size
,
3505 #endif /* not emacs */
3508 /* re_match_2 matches the compiled pattern in BUFP against the
3509 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3510 and SIZE2, respectively). We start matching at POS, and stop
3513 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3514 store offsets for the substring each group matched in REGS. See the
3515 documentation for exactly how many groups we fill.
3517 We return -1 if no match, -2 if an internal error (such as the
3518 failure stack overflowing). Otherwise, we return the length of the
3519 matched substring. */
3522 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
3523 struct re_pattern_buffer
*bufp
;
3524 const char *string1
, *string2
;
3527 struct re_registers
*regs
;
3530 int result
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3536 /* This is a separate function so that we can force an alloca cleanup
3539 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
3540 struct re_pattern_buffer
*bufp
;
3541 const char *string1
, *string2
;
3544 struct re_registers
*regs
;
3547 /* General temporaries. */
3551 /* Just past the end of the corresponding string. */
3552 const char *end1
, *end2
;
3554 /* Pointers into string1 and string2, just past the last characters in
3555 each to consider matching. */
3556 const char *end_match_1
, *end_match_2
;
3558 /* Where we are in the data, and the end of the current string. */
3559 const char *d
, *dend
;
3561 /* Where we are in the pattern, and the end of the pattern. */
3562 unsigned char *p
= bufp
->buffer
;
3563 register unsigned char *pend
= p
+ bufp
->used
;
3565 /* Mark the opcode just after a start_memory, so we can test for an
3566 empty subpattern when we get to the stop_memory. */
3567 unsigned char *just_past_start_mem
= 0;
3569 /* We use this to map every character in the string. */
3570 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3572 /* Failure point stack. Each place that can handle a failure further
3573 down the line pushes a failure point on this stack. It consists of
3574 restart, regend, and reg_info for all registers corresponding to
3575 the subexpressions we're currently inside, plus the number of such
3576 registers, and, finally, two char *'s. The first char * is where
3577 to resume scanning the pattern; the second one is where to resume
3578 scanning the strings. If the latter is zero, the failure point is
3579 a ``dummy''; if a failure happens and the failure point is a dummy,
3580 it gets discarded and the next next one is tried. */
3581 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3582 fail_stack_type fail_stack
;
3585 static unsigned failure_id
= 0;
3586 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
3589 /* This holds the pointer to the failure stack, when
3590 it is allocated relocatably. */
3592 fail_stack_elt_t
*failure_stack_ptr
;
3595 /* We fill all the registers internally, independent of what we
3596 return, for use in backreferences. The number here includes
3597 an element for register zero. */
3598 unsigned num_regs
= bufp
->re_nsub
+ 1;
3600 /* The currently active registers. */
3601 unsigned lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
3602 unsigned highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
3604 /* Information on the contents of registers. These are pointers into
3605 the input strings; they record just what was matched (on this
3606 attempt) by a subexpression part of the pattern, that is, the
3607 regnum-th regstart pointer points to where in the pattern we began
3608 matching and the regnum-th regend points to right after where we
3609 stopped matching the regnum-th subexpression. (The zeroth register
3610 keeps track of what the whole pattern matches.) */
3611 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3612 const char **regstart
, **regend
;
3615 /* If a group that's operated upon by a repetition operator fails to
3616 match anything, then the register for its start will need to be
3617 restored because it will have been set to wherever in the string we
3618 are when we last see its open-group operator. Similarly for a
3620 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3621 const char **old_regstart
, **old_regend
;
3624 /* The is_active field of reg_info helps us keep track of which (possibly
3625 nested) subexpressions we are currently in. The matched_something
3626 field of reg_info[reg_num] helps us tell whether or not we have
3627 matched any of the pattern so far this time through the reg_num-th
3628 subexpression. These two fields get reset each time through any
3629 loop their register is in. */
3630 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3631 register_info_type
*reg_info
;
3634 /* The following record the register info as found in the above
3635 variables when we find a match better than any we've seen before.
3636 This happens as we backtrack through the failure points, which in
3637 turn happens only if we have not yet matched the entire string. */
3638 unsigned best_regs_set
= false;
3639 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3640 const char **best_regstart
, **best_regend
;
3643 /* Logically, this is `best_regend[0]'. But we don't want to have to
3644 allocate space for that if we're not allocating space for anything
3645 else (see below). Also, we never need info about register 0 for
3646 any of the other register vectors, and it seems rather a kludge to
3647 treat `best_regend' differently than the rest. So we keep track of
3648 the end of the best match so far in a separate variable. We
3649 initialize this to NULL so that when we backtrack the first time
3650 and need to test it, it's not garbage. */
3651 const char *match_end
= NULL
;
3653 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
3654 int set_regs_matched_done
= 0;
3656 /* Used when we pop values we don't care about. */
3657 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3658 const char **reg_dummy
;
3659 register_info_type
*reg_info_dummy
;
3663 /* Counts the total number of registers pushed. */
3664 unsigned num_regs_pushed
= 0;
3667 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3671 #ifdef MATCH_MAY_ALLOCATE
3672 /* Do not bother to initialize all the register variables if there are
3673 no groups in the pattern, as it takes a fair amount of time. If
3674 there are groups, we include space for register 0 (the whole
3675 pattern), even though we never use it, since it simplifies the
3676 array indexing. We should fix this. */
3679 regstart
= REGEX_TALLOC (num_regs
, const char *);
3680 regend
= REGEX_TALLOC (num_regs
, const char *);
3681 old_regstart
= REGEX_TALLOC (num_regs
, const char *);
3682 old_regend
= REGEX_TALLOC (num_regs
, const char *);
3683 best_regstart
= REGEX_TALLOC (num_regs
, const char *);
3684 best_regend
= REGEX_TALLOC (num_regs
, const char *);
3685 reg_info
= REGEX_TALLOC (num_regs
, register_info_type
);
3686 reg_dummy
= REGEX_TALLOC (num_regs
, const char *);
3687 reg_info_dummy
= REGEX_TALLOC (num_regs
, register_info_type
);
3689 if (!(regstart
&& regend
&& old_regstart
&& old_regend
&& reg_info
3690 && best_regstart
&& best_regend
&& reg_dummy
&& reg_info_dummy
))
3698 /* We must initialize all our variables to NULL, so that
3699 `FREE_VARIABLES' doesn't try to free them. */
3700 regstart
= regend
= old_regstart
= old_regend
= best_regstart
3701 = best_regend
= reg_dummy
= NULL
;
3702 reg_info
= reg_info_dummy
= (register_info_type
*) NULL
;
3704 #endif /* MATCH_MAY_ALLOCATE */
3706 /* The starting position is bogus. */
3707 if (pos
< 0 || pos
> size1
+ size2
)
3713 /* Initialize subexpression text positions to -1 to mark ones that no
3714 start_memory/stop_memory has been seen for. Also initialize the
3715 register information struct. */
3716 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
3718 regstart
[mcnt
] = regend
[mcnt
]
3719 = old_regstart
[mcnt
] = old_regend
[mcnt
] = REG_UNSET_VALUE
;
3721 REG_MATCH_NULL_STRING_P (reg_info
[mcnt
]) = MATCH_NULL_UNSET_VALUE
;
3722 IS_ACTIVE (reg_info
[mcnt
]) = 0;
3723 MATCHED_SOMETHING (reg_info
[mcnt
]) = 0;
3724 EVER_MATCHED_SOMETHING (reg_info
[mcnt
]) = 0;
3727 /* We move `string1' into `string2' if the latter's empty -- but not if
3728 `string1' is null. */
3729 if (size2
== 0 && string1
!= NULL
)
3736 end1
= string1
+ size1
;
3737 end2
= string2
+ size2
;
3739 /* Compute where to stop matching, within the two strings. */
3742 end_match_1
= string1
+ stop
;
3743 end_match_2
= string2
;
3748 end_match_2
= string2
+ stop
- size1
;
3751 /* `p' scans through the pattern as `d' scans through the data.
3752 `dend' is the end of the input string that `d' points within. `d'
3753 is advanced into the following input string whenever necessary, but
3754 this happens before fetching; therefore, at the beginning of the
3755 loop, `d' can be pointing at the end of a string, but it cannot
3757 if (size1
> 0 && pos
<= size1
)
3764 d
= string2
+ pos
- size1
;
3768 DEBUG_PRINT1 ("The compiled pattern is: ");
3769 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
3770 DEBUG_PRINT1 ("The string to match is: `");
3771 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
3772 DEBUG_PRINT1 ("'\n");
3774 /* This loops over pattern commands. It exits by returning from the
3775 function if the match is complete, or it drops through if the match
3776 fails at this starting point in the input data. */
3779 DEBUG_PRINT2 ("\n0x%x: ", p
);
3782 { /* End of pattern means we might have succeeded. */
3783 DEBUG_PRINT1 ("end of pattern ... ");
3785 /* If we haven't matched the entire string, and we want the
3786 longest match, try backtracking. */
3787 if (d
!= end_match_2
)
3789 /* 1 if this match ends in the same string (string1 or string2)
3790 as the best previous match. */
3791 boolean same_str_p
= (FIRST_STRING_P (match_end
)
3792 == MATCHING_IN_FIRST_STRING
);
3793 /* 1 if this match is the best seen so far. */
3794 boolean best_match_p
;
3796 /* AIX compiler got confused when this was combined
3797 with the previous declaration. */
3799 best_match_p
= d
> match_end
;
3801 best_match_p
= !MATCHING_IN_FIRST_STRING
;
3803 DEBUG_PRINT1 ("backtracking.\n");
3805 if (!FAIL_STACK_EMPTY ())
3806 { /* More failure points to try. */
3808 /* If exceeds best match so far, save it. */
3809 if (!best_regs_set
|| best_match_p
)
3811 best_regs_set
= true;
3814 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3816 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
3818 best_regstart
[mcnt
] = regstart
[mcnt
];
3819 best_regend
[mcnt
] = regend
[mcnt
];
3825 /* If no failure points, don't restore garbage. And if
3826 last match is real best match, don't restore second
3828 else if (best_regs_set
&& !best_match_p
)
3831 /* Restore best match. It may happen that `dend ==
3832 end_match_1' while the restored d is in string2.
3833 For example, the pattern `x.*y.*z' against the
3834 strings `x-' and `y-z-', if the two strings are
3835 not consecutive in memory. */
3836 DEBUG_PRINT1 ("Restoring best registers.\n");
3839 dend
= ((d
>= string1
&& d
<= end1
)
3840 ? end_match_1
: end_match_2
);
3842 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
3844 regstart
[mcnt
] = best_regstart
[mcnt
];
3845 regend
[mcnt
] = best_regend
[mcnt
];
3848 } /* d != end_match_2 */
3851 DEBUG_PRINT1 ("Accepting match.\n");
3853 /* If caller wants register contents data back, do it. */
3854 if (regs
&& !bufp
->no_sub
)
3856 /* Have the register data arrays been allocated? */
3857 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
3858 { /* No. So allocate them with malloc. We need one
3859 extra element beyond `num_regs' for the `-1' marker
3861 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
3862 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
3863 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
3864 if (regs
->start
== NULL
|| regs
->end
== NULL
)
3869 bufp
->regs_allocated
= REGS_REALLOCATE
;
3871 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
3872 { /* Yes. If we need more elements than were already
3873 allocated, reallocate them. If we need fewer, just
3875 if (regs
->num_regs
< num_regs
+ 1)
3877 regs
->num_regs
= num_regs
+ 1;
3878 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
3879 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
3880 if (regs
->start
== NULL
|| regs
->end
== NULL
)
3889 /* These braces fend off a "empty body in an else-statement"
3890 warning under GCC when assert expands to nothing. */
3891 assert (bufp
->regs_allocated
== REGS_FIXED
);
3894 /* Convert the pointer data in `regstart' and `regend' to
3895 indices. Register zero has to be set differently,
3896 since we haven't kept track of any info for it. */
3897 if (regs
->num_regs
> 0)
3899 regs
->start
[0] = pos
;
3900 regs
->end
[0] = (MATCHING_IN_FIRST_STRING
3901 ? ((regoff_t
) (d
- string1
))
3902 : ((regoff_t
) (d
- string2
+ size1
)));
3905 /* Go through the first `min (num_regs, regs->num_regs)'
3906 registers, since that is all we initialized. */
3907 for (mcnt
= 1; mcnt
< MIN (num_regs
, regs
->num_regs
); mcnt
++)
3909 if (REG_UNSET (regstart
[mcnt
]) || REG_UNSET (regend
[mcnt
]))
3910 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
3914 = (regoff_t
) POINTER_TO_OFFSET (regstart
[mcnt
]);
3916 = (regoff_t
) POINTER_TO_OFFSET (regend
[mcnt
]);
3920 /* If the regs structure we return has more elements than
3921 were in the pattern, set the extra elements to -1. If
3922 we (re)allocated the registers, this is the case,
3923 because we always allocate enough to have at least one
3925 for (mcnt
= num_regs
; mcnt
< regs
->num_regs
; mcnt
++)
3926 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
3927 } /* regs && !bufp->no_sub */
3929 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3930 nfailure_points_pushed
, nfailure_points_popped
,
3931 nfailure_points_pushed
- nfailure_points_popped
);
3932 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
3934 mcnt
= d
- pos
- (MATCHING_IN_FIRST_STRING
3938 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
3944 /* Otherwise match next pattern command. */
3945 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3947 /* Ignore these. Used to ignore the n of succeed_n's which
3948 currently have n == 0. */
3950 DEBUG_PRINT1 ("EXECUTING no_op.\n");
3954 DEBUG_PRINT1 ("EXECUTING succeed.\n");
3957 /* Match the next n pattern characters exactly. The following
3958 byte in the pattern defines n, and the n bytes after that
3959 are the characters to match. */
3962 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
3964 /* This is written out as an if-else so we don't waste time
3965 testing `translate' inside the loop. */
3971 if ((unsigned char) translate
[(unsigned char) *d
++]
3972 != (unsigned char) *p
++)
3982 if (*d
++ != (char) *p
++) goto fail
;
3986 SET_REGS_MATCHED ();
3990 /* Match any character except possibly a newline or a null. */
3992 DEBUG_PRINT1 ("EXECUTING anychar.\n");
3996 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
) && TRANSLATE (*d
) == '\n')
3997 || (bufp
->syntax
& RE_DOT_NOT_NULL
&& TRANSLATE (*d
) == '\000'))
4000 SET_REGS_MATCHED ();
4001 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
4009 register unsigned char c
;
4010 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
4012 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4015 c
= TRANSLATE (*d
); /* The character to match. */
4017 /* Cast to `unsigned' instead of `unsigned char' in case the
4018 bit list is a full 32 bytes long. */
4019 if (c
< (unsigned) (*p
* BYTEWIDTH
)
4020 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4025 if (!not) goto fail
;
4027 SET_REGS_MATCHED ();
4033 /* The beginning of a group is represented by start_memory.
4034 The arguments are the register number in the next byte, and the
4035 number of groups inner to this one in the next. The text
4036 matched within the group is recorded (in the internal
4037 registers data structure) under the register number. */
4039 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p
, p
[1]);
4041 /* Find out if this group can match the empty string. */
4042 p1
= p
; /* To send to group_match_null_string_p. */
4044 if (REG_MATCH_NULL_STRING_P (reg_info
[*p
]) == MATCH_NULL_UNSET_VALUE
)
4045 REG_MATCH_NULL_STRING_P (reg_info
[*p
])
4046 = group_match_null_string_p (&p1
, pend
, reg_info
);
4048 /* Save the position in the string where we were the last time
4049 we were at this open-group operator in case the group is
4050 operated upon by a repetition operator, e.g., with `(a*)*b'
4051 against `ab'; then we want to ignore where we are now in
4052 the string in case this attempt to match fails. */
4053 old_regstart
[*p
] = REG_MATCH_NULL_STRING_P (reg_info
[*p
])
4054 ? REG_UNSET (regstart
[*p
]) ? d
: regstart
[*p
]
4056 DEBUG_PRINT2 (" old_regstart: %d\n",
4057 POINTER_TO_OFFSET (old_regstart
[*p
]));
4060 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
4062 IS_ACTIVE (reg_info
[*p
]) = 1;
4063 MATCHED_SOMETHING (reg_info
[*p
]) = 0;
4065 /* Clear this whenever we change the register activity status. */
4066 set_regs_matched_done
= 0;
4068 /* This is the new highest active register. */
4069 highest_active_reg
= *p
;
4071 /* If nothing was active before, this is the new lowest active
4073 if (lowest_active_reg
== NO_LOWEST_ACTIVE_REG
)
4074 lowest_active_reg
= *p
;
4076 /* Move past the register number and inner group count. */
4078 just_past_start_mem
= p
;
4083 /* The stop_memory opcode represents the end of a group. Its
4084 arguments are the same as start_memory's: the register
4085 number, and the number of inner groups. */
4087 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p
, p
[1]);
4089 /* We need to save the string position the last time we were at
4090 this close-group operator in case the group is operated
4091 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4092 against `aba'; then we want to ignore where we are now in
4093 the string in case this attempt to match fails. */
4094 old_regend
[*p
] = REG_MATCH_NULL_STRING_P (reg_info
[*p
])
4095 ? REG_UNSET (regend
[*p
]) ? d
: regend
[*p
]
4097 DEBUG_PRINT2 (" old_regend: %d\n",
4098 POINTER_TO_OFFSET (old_regend
[*p
]));
4101 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
4103 /* This register isn't active anymore. */
4104 IS_ACTIVE (reg_info
[*p
]) = 0;
4106 /* Clear this whenever we change the register activity status. */
4107 set_regs_matched_done
= 0;
4109 /* If this was the only register active, nothing is active
4111 if (lowest_active_reg
== highest_active_reg
)
4113 lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
4114 highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
4117 { /* We must scan for the new highest active register, since
4118 it isn't necessarily one less than now: consider
4119 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4120 new highest active register is 1. */
4121 unsigned char r
= *p
- 1;
4122 while (r
> 0 && !IS_ACTIVE (reg_info
[r
]))
4125 /* If we end up at register zero, that means that we saved
4126 the registers as the result of an `on_failure_jump', not
4127 a `start_memory', and we jumped to past the innermost
4128 `stop_memory'. For example, in ((.)*) we save
4129 registers 1 and 2 as a result of the *, but when we pop
4130 back to the second ), we are at the stop_memory 1.
4131 Thus, nothing is active. */
4134 lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
4135 highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
4138 highest_active_reg
= r
;
4141 /* If just failed to match something this time around with a
4142 group that's operated on by a repetition operator, try to
4143 force exit from the ``loop'', and restore the register
4144 information for this group that we had before trying this
4146 if ((!MATCHED_SOMETHING (reg_info
[*p
])
4147 || just_past_start_mem
== p
- 1)
4150 boolean is_a_jump_n
= false;
4154 switch ((re_opcode_t
) *p1
++)
4158 case pop_failure_jump
:
4159 case maybe_pop_jump
:
4161 case dummy_failure_jump
:
4162 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
4172 /* If the next operation is a jump backwards in the pattern
4173 to an on_failure_jump right before the start_memory
4174 corresponding to this stop_memory, exit from the loop
4175 by forcing a failure after pushing on the stack the
4176 on_failure_jump's jump in the pattern, and d. */
4177 if (mcnt
< 0 && (re_opcode_t
) *p1
== on_failure_jump
4178 && (re_opcode_t
) p1
[3] == start_memory
&& p1
[4] == *p
)
4180 /* If this group ever matched anything, then restore
4181 what its registers were before trying this last
4182 failed match, e.g., with `(a*)*b' against `ab' for
4183 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4184 against `aba' for regend[3].
4186 Also restore the registers for inner groups for,
4187 e.g., `((a*)(b*))*' against `aba' (register 3 would
4188 otherwise get trashed). */
4190 if (EVER_MATCHED_SOMETHING (reg_info
[*p
]))
4194 EVER_MATCHED_SOMETHING (reg_info
[*p
]) = 0;
4196 /* Restore this and inner groups' (if any) registers. */
4197 for (r
= *p
; r
< *p
+ *(p
+ 1); r
++)
4199 regstart
[r
] = old_regstart
[r
];
4201 /* xx why this test? */
4202 if (old_regend
[r
] >= regstart
[r
])
4203 regend
[r
] = old_regend
[r
];
4207 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
4208 PUSH_FAILURE_POINT (p1
+ mcnt
, d
, -2);
4214 /* Move past the register number and the inner group count. */
4219 /* \<digit> has been turned into a `duplicate' command which is
4220 followed by the numeric value of <digit> as the register number. */
4223 register const char *d2
, *dend2
;
4224 int regno
= *p
++; /* Get which register to match against. */
4225 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
4227 /* Can't back reference a group which we've never matched. */
4228 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
4231 /* Where in input to try to start matching. */
4232 d2
= regstart
[regno
];
4234 /* Where to stop matching; if both the place to start and
4235 the place to stop matching are in the same string, then
4236 set to the place to stop, otherwise, for now have to use
4237 the end of the first string. */
4239 dend2
= ((FIRST_STRING_P (regstart
[regno
])
4240 == FIRST_STRING_P (regend
[regno
]))
4241 ? regend
[regno
] : end_match_1
);
4244 /* If necessary, advance to next segment in register
4248 if (dend2
== end_match_2
) break;
4249 if (dend2
== regend
[regno
]) break;
4251 /* End of string1 => advance to string2. */
4253 dend2
= regend
[regno
];
4255 /* At end of register contents => success */
4256 if (d2
== dend2
) break;
4258 /* If necessary, advance to next segment in data. */
4261 /* How many characters left in this segment to match. */
4264 /* Want how many consecutive characters we can match in
4265 one shot, so, if necessary, adjust the count. */
4266 if (mcnt
> dend2
- d2
)
4269 /* Compare that many; failure if mismatch, else move
4272 ? bcmp_translate (d
, d2
, mcnt
, translate
)
4273 : bcmp (d
, d2
, mcnt
))
4275 d
+= mcnt
, d2
+= mcnt
;
4277 /* Do this because we've match some characters. */
4278 SET_REGS_MATCHED ();
4284 /* begline matches the empty string at the beginning of the string
4285 (unless `not_bol' is set in `bufp'), and, if
4286 `newline_anchor' is set, after newlines. */
4288 DEBUG_PRINT1 ("EXECUTING begline.\n");
4290 if (AT_STRINGS_BEG (d
))
4292 if (!bufp
->not_bol
) break;
4294 else if (d
[-1] == '\n' && bufp
->newline_anchor
)
4298 /* In all other cases, we fail. */
4302 /* endline is the dual of begline. */
4304 DEBUG_PRINT1 ("EXECUTING endline.\n");
4306 if (AT_STRINGS_END (d
))
4308 if (!bufp
->not_eol
) break;
4311 /* We have to ``prefetch'' the next character. */
4312 else if ((d
== end1
? *string2
: *d
) == '\n'
4313 && bufp
->newline_anchor
)
4320 /* Match at the very beginning of the data. */
4322 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4323 if (AT_STRINGS_BEG (d
))
4328 /* Match at the very end of the data. */
4330 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4331 if (AT_STRINGS_END (d
))
4336 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4337 pushes NULL as the value for the string on the stack. Then
4338 `pop_failure_point' will keep the current value for the
4339 string, instead of restoring it. To see why, consider
4340 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4341 then the . fails against the \n. But the next thing we want
4342 to do is match the \n against the \n; if we restored the
4343 string value, we would be back at the foo.
4345 Because this is used only in specific cases, we don't need to
4346 check all the things that `on_failure_jump' does, to make
4347 sure the right things get saved on the stack. Hence we don't
4348 share its code. The only reason to push anything on the
4349 stack at all is that otherwise we would have to change
4350 `anychar's code to do something besides goto fail in this
4351 case; that seems worse than this. */
4352 case on_failure_keep_string_jump
:
4353 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4355 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4356 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt
, p
+ mcnt
);
4358 PUSH_FAILURE_POINT (p
+ mcnt
, NULL
, -2);
4362 /* Uses of on_failure_jump:
4364 Each alternative starts with an on_failure_jump that points
4365 to the beginning of the next alternative. Each alternative
4366 except the last ends with a jump that in effect jumps past
4367 the rest of the alternatives. (They really jump to the
4368 ending jump of the following alternative, because tensioning
4369 these jumps is a hassle.)
4371 Repeats start with an on_failure_jump that points past both
4372 the repetition text and either the following jump or
4373 pop_failure_jump back to this on_failure_jump. */
4374 case on_failure_jump
:
4376 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4378 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4379 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt
, p
+ mcnt
);
4381 /* If this on_failure_jump comes right before a group (i.e.,
4382 the original * applied to a group), save the information
4383 for that group and all inner ones, so that if we fail back
4384 to this point, the group's information will be correct.
4385 For example, in \(a*\)*\1, we need the preceding group,
4386 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4388 /* We can't use `p' to check ahead because we push
4389 a failure point to `p + mcnt' after we do this. */
4392 /* We need to skip no_op's before we look for the
4393 start_memory in case this on_failure_jump is happening as
4394 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4396 while (p1
< pend
&& (re_opcode_t
) *p1
== no_op
)
4399 if (p1
< pend
&& (re_opcode_t
) *p1
== start_memory
)
4401 /* We have a new highest active register now. This will
4402 get reset at the start_memory we are about to get to,
4403 but we will have saved all the registers relevant to
4404 this repetition op, as described above. */
4405 highest_active_reg
= *(p1
+ 1) + *(p1
+ 2);
4406 if (lowest_active_reg
== NO_LOWEST_ACTIVE_REG
)
4407 lowest_active_reg
= *(p1
+ 1);
4410 DEBUG_PRINT1 (":\n");
4411 PUSH_FAILURE_POINT (p
+ mcnt
, d
, -2);
4415 /* A smart repeat ends with `maybe_pop_jump'.
4416 We change it to either `pop_failure_jump' or `jump'. */
4417 case maybe_pop_jump
:
4418 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4419 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt
);
4421 register unsigned char *p2
= p
;
4423 /* Compare the beginning of the repeat with what in the
4424 pattern follows its end. If we can establish that there
4425 is nothing that they would both match, i.e., that we
4426 would have to backtrack because of (as in, e.g., `a*a')
4427 then we can change to pop_failure_jump, because we'll
4428 never have to backtrack.
4430 This is not true in the case of alternatives: in
4431 `(a|ab)*' we do need to backtrack to the `ab' alternative
4432 (e.g., if the string was `ab'). But instead of trying to
4433 detect that here, the alternative has put on a dummy
4434 failure point which is what we will end up popping. */
4436 /* Skip over open/close-group commands.
4437 If what follows this loop is a ...+ construct,
4438 look at what begins its body, since we will have to
4439 match at least one of that. */
4443 && ((re_opcode_t
) *p2
== stop_memory
4444 || (re_opcode_t
) *p2
== start_memory
))
4446 else if (p2
+ 6 < pend
4447 && (re_opcode_t
) *p2
== dummy_failure_jump
)
4454 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4455 to the `maybe_finalize_jump' of this case. Examine what
4458 /* If we're at the end of the pattern, we can change. */
4461 /* Consider what happens when matching ":\(.*\)"
4462 against ":/". I don't really understand this code
4464 p
[-3] = (unsigned char) pop_failure_jump
;
4466 (" End of pattern: change to `pop_failure_jump'.\n");
4469 else if ((re_opcode_t
) *p2
== exactn
4470 || (bufp
->newline_anchor
&& (re_opcode_t
) *p2
== endline
))
4472 register unsigned char c
4473 = *p2
== (unsigned char) endline
? '\n' : p2
[2];
4475 if ((re_opcode_t
) p1
[3] == exactn
&& p1
[5] != c
)
4477 p
[-3] = (unsigned char) pop_failure_jump
;
4478 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4482 else if ((re_opcode_t
) p1
[3] == charset
4483 || (re_opcode_t
) p1
[3] == charset_not
)
4485 int not = (re_opcode_t
) p1
[3] == charset_not
;
4487 if (c
< (unsigned char) (p1
[4] * BYTEWIDTH
)
4488 && p1
[5 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4491 /* `not' is equal to 1 if c would match, which means
4492 that we can't change to pop_failure_jump. */
4495 p
[-3] = (unsigned char) pop_failure_jump
;
4496 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4500 else if ((re_opcode_t
) *p2
== charset
)
4503 register unsigned char c
4504 = *p2
== (unsigned char) endline
? '\n' : p2
[2];
4507 if ((re_opcode_t
) p1
[3] == exactn
4508 && ! ((int) p2
[1] * BYTEWIDTH
> (int) p1
[5]
4509 && (p2
[2 + p1
[5] / BYTEWIDTH
]
4510 & (1 << (p1
[5] % BYTEWIDTH
)))))
4512 p
[-3] = (unsigned char) pop_failure_jump
;
4513 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4517 else if ((re_opcode_t
) p1
[3] == charset_not
)
4520 /* We win if the charset_not inside the loop
4521 lists every character listed in the charset after. */
4522 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4523 if (! (p2
[2 + idx
] == 0
4524 || (idx
< (int) p1
[4]
4525 && ((p2
[2 + idx
] & ~ p1
[5 + idx
]) == 0))))
4530 p
[-3] = (unsigned char) pop_failure_jump
;
4531 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4534 else if ((re_opcode_t
) p1
[3] == charset
)
4537 /* We win if the charset inside the loop
4538 has no overlap with the one after the loop. */
4540 idx
< (int) p2
[1] && idx
< (int) p1
[4];
4542 if ((p2
[2 + idx
] & p1
[5 + idx
]) != 0)
4545 if (idx
== p2
[1] || idx
== p1
[4])
4547 p
[-3] = (unsigned char) pop_failure_jump
;
4548 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4553 p
-= 2; /* Point at relative address again. */
4554 if ((re_opcode_t
) p
[-1] != pop_failure_jump
)
4556 p
[-1] = (unsigned char) jump
;
4557 DEBUG_PRINT1 (" Match => jump.\n");
4558 goto unconditional_jump
;
4560 /* Note fall through. */
4563 /* The end of a simple repeat has a pop_failure_jump back to
4564 its matching on_failure_jump, where the latter will push a
4565 failure point. The pop_failure_jump takes off failure
4566 points put on by this pop_failure_jump's matching
4567 on_failure_jump; we got through the pattern to here from the
4568 matching on_failure_jump, so didn't fail. */
4569 case pop_failure_jump
:
4571 /* We need to pass separate storage for the lowest and
4572 highest registers, even though we don't care about the
4573 actual values. Otherwise, we will restore only one
4574 register from the stack, since lowest will == highest in
4575 `pop_failure_point'. */
4576 unsigned dummy_low_reg
, dummy_high_reg
;
4577 unsigned char *pdummy
;
4580 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4581 POP_FAILURE_POINT (sdummy
, pdummy
,
4582 dummy_low_reg
, dummy_high_reg
,
4583 reg_dummy
, reg_dummy
, reg_info_dummy
);
4585 /* Note fall through. */
4588 /* Unconditionally jump (without popping any failure points). */
4591 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
4592 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
4593 p
+= mcnt
; /* Do the jump. */
4594 DEBUG_PRINT2 ("(to 0x%x).\n", p
);
4598 /* We need this opcode so we can detect where alternatives end
4599 in `group_match_null_string_p' et al. */
4601 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4602 goto unconditional_jump
;
4605 /* Normally, the on_failure_jump pushes a failure point, which
4606 then gets popped at pop_failure_jump. We will end up at
4607 pop_failure_jump, also, and with a pattern of, say, `a+', we
4608 are skipping over the on_failure_jump, so we have to push
4609 something meaningless for pop_failure_jump to pop. */
4610 case dummy_failure_jump
:
4611 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4612 /* It doesn't matter what we push for the string here. What
4613 the code at `fail' tests is the value for the pattern. */
4614 PUSH_FAILURE_POINT (0, 0, -2);
4615 goto unconditional_jump
;
4618 /* At the end of an alternative, we need to push a dummy failure
4619 point in case we are followed by a `pop_failure_jump', because
4620 we don't want the failure point for the alternative to be
4621 popped. For example, matching `(a|ab)*' against `aab'
4622 requires that we match the `ab' alternative. */
4623 case push_dummy_failure
:
4624 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4625 /* See comments just above at `dummy_failure_jump' about the
4627 PUSH_FAILURE_POINT (0, 0, -2);
4630 /* Have to succeed matching what follows at least n times.
4631 After that, handle like `on_failure_jump'. */
4633 EXTRACT_NUMBER (mcnt
, p
+ 2);
4634 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
4637 /* Originally, this is how many times we HAVE to succeed. */
4642 STORE_NUMBER_AND_INCR (p
, mcnt
);
4643 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p
, mcnt
);
4647 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p
+2);
4648 p
[2] = (unsigned char) no_op
;
4649 p
[3] = (unsigned char) no_op
;
4655 EXTRACT_NUMBER (mcnt
, p
+ 2);
4656 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
4658 /* Originally, this is how many times we CAN jump. */
4662 STORE_NUMBER (p
+ 2, mcnt
);
4663 goto unconditional_jump
;
4665 /* If don't have to jump any more, skip over the rest of command. */
4672 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4674 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4676 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4677 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1
, mcnt
);
4678 STORE_NUMBER (p1
, mcnt
);
4683 /* The DEC Alpha C compiler 3.x generates incorrect code for the
4684 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4685 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4686 macro and introducing temporary variables works around the bug. */
4689 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4690 if (AT_WORD_BOUNDARY (d
))
4695 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4696 if (AT_WORD_BOUNDARY (d
))
4702 boolean prevchar
, thischar
;
4704 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4705 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
4708 prevchar
= WORDCHAR_P (d
- 1);
4709 thischar
= WORDCHAR_P (d
);
4710 if (prevchar
!= thischar
)
4717 boolean prevchar
, thischar
;
4719 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4720 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
4723 prevchar
= WORDCHAR_P (d
- 1);
4724 thischar
= WORDCHAR_P (d
);
4725 if (prevchar
!= thischar
)
4732 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4733 if (WORDCHAR_P (d
) && (AT_STRINGS_BEG (d
) || !WORDCHAR_P (d
- 1)))
4738 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4739 if (!AT_STRINGS_BEG (d
) && WORDCHAR_P (d
- 1)
4740 && (!WORDCHAR_P (d
) || AT_STRINGS_END (d
)))
4746 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4747 if (PTR_CHAR_POS ((unsigned char *) d
) >= point
)
4752 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4753 if (PTR_CHAR_POS ((unsigned char *) d
) != point
)
4758 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4759 if (PTR_CHAR_POS ((unsigned char *) d
) <= point
)
4764 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt
);
4769 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4773 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
4775 if (SYNTAX (d
[-1]) != (enum syntaxcode
) mcnt
)
4777 SET_REGS_MATCHED ();
4781 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt
);
4783 goto matchnotsyntax
;
4786 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4790 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
4792 if (SYNTAX (d
[-1]) == (enum syntaxcode
) mcnt
)
4794 SET_REGS_MATCHED ();
4797 #else /* not emacs */
4799 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4801 if (!WORDCHAR_P (d
))
4803 SET_REGS_MATCHED ();
4808 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4812 SET_REGS_MATCHED ();
4815 #endif /* not emacs */
4820 continue; /* Successfully executed one pattern command; keep going. */
4823 /* We goto here if a matching operation fails. */
4825 if (!FAIL_STACK_EMPTY ())
4826 { /* A restart point is known. Restore to that state. */
4827 DEBUG_PRINT1 ("\nFAIL:\n");
4828 POP_FAILURE_POINT (d
, p
,
4829 lowest_active_reg
, highest_active_reg
,
4830 regstart
, regend
, reg_info
);
4832 /* If this failure point is a dummy, try the next one. */
4836 /* If we failed to the end of the pattern, don't examine *p. */
4840 boolean is_a_jump_n
= false;
4842 /* If failed to a backwards jump that's part of a repetition
4843 loop, need to pop this failure point and use the next one. */
4844 switch ((re_opcode_t
) *p
)
4848 case maybe_pop_jump
:
4849 case pop_failure_jump
:
4852 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
4855 if ((is_a_jump_n
&& (re_opcode_t
) *p1
== succeed_n
)
4857 && (re_opcode_t
) *p1
== on_failure_jump
))
4865 if (d
>= string1
&& d
<= end1
)
4869 break; /* Matching at this starting point really fails. */
4873 goto restore_best_regs
;
4877 return -1; /* Failure to match. */
4880 /* Subroutine definitions for re_match_2. */
4883 /* We are passed P pointing to a register number after a start_memory.
4885 Return true if the pattern up to the corresponding stop_memory can
4886 match the empty string, and false otherwise.
4888 If we find the matching stop_memory, sets P to point to one past its number.
4889 Otherwise, sets P to an undefined byte less than or equal to END.
4891 We don't handle duplicates properly (yet). */
4894 group_match_null_string_p (p
, end
, reg_info
)
4895 unsigned char **p
, *end
;
4896 register_info_type
*reg_info
;
4899 /* Point to after the args to the start_memory. */
4900 unsigned char *p1
= *p
+ 2;
4904 /* Skip over opcodes that can match nothing, and return true or
4905 false, as appropriate, when we get to one that can't, or to the
4906 matching stop_memory. */
4908 switch ((re_opcode_t
) *p1
)
4910 /* Could be either a loop or a series of alternatives. */
4911 case on_failure_jump
:
4913 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
4915 /* If the next operation is not a jump backwards in the
4920 /* Go through the on_failure_jumps of the alternatives,
4921 seeing if any of the alternatives cannot match nothing.
4922 The last alternative starts with only a jump,
4923 whereas the rest start with on_failure_jump and end
4924 with a jump, e.g., here is the pattern for `a|b|c':
4926 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4927 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4930 So, we have to first go through the first (n-1)
4931 alternatives and then deal with the last one separately. */
4934 /* Deal with the first (n-1) alternatives, which start
4935 with an on_failure_jump (see above) that jumps to right
4936 past a jump_past_alt. */
4938 while ((re_opcode_t
) p1
[mcnt
-3] == jump_past_alt
)
4940 /* `mcnt' holds how many bytes long the alternative
4941 is, including the ending `jump_past_alt' and
4944 if (!alt_match_null_string_p (p1
, p1
+ mcnt
- 3,
4948 /* Move to right after this alternative, including the
4952 /* Break if it's the beginning of an n-th alternative
4953 that doesn't begin with an on_failure_jump. */
4954 if ((re_opcode_t
) *p1
!= on_failure_jump
)
4957 /* Still have to check that it's not an n-th
4958 alternative that starts with an on_failure_jump. */
4960 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
4961 if ((re_opcode_t
) p1
[mcnt
-3] != jump_past_alt
)
4963 /* Get to the beginning of the n-th alternative. */
4969 /* Deal with the last alternative: go back and get number
4970 of the `jump_past_alt' just before it. `mcnt' contains
4971 the length of the alternative. */
4972 EXTRACT_NUMBER (mcnt
, p1
- 2);
4974 if (!alt_match_null_string_p (p1
, p1
+ mcnt
, reg_info
))
4977 p1
+= mcnt
; /* Get past the n-th alternative. */
4983 assert (p1
[1] == **p
);
4989 if (!common_op_match_null_string_p (&p1
, end
, reg_info
))
4992 } /* while p1 < end */
4995 } /* group_match_null_string_p */
4998 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4999 It expects P to be the first byte of a single alternative and END one
5000 byte past the last. The alternative can contain groups. */
5003 alt_match_null_string_p (p
, end
, reg_info
)
5004 unsigned char *p
, *end
;
5005 register_info_type
*reg_info
;
5008 unsigned char *p1
= p
;
5012 /* Skip over opcodes that can match nothing, and break when we get
5013 to one that can't. */
5015 switch ((re_opcode_t
) *p1
)
5018 case on_failure_jump
:
5020 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5025 if (!common_op_match_null_string_p (&p1
, end
, reg_info
))
5028 } /* while p1 < end */
5031 } /* alt_match_null_string_p */
5034 /* Deals with the ops common to group_match_null_string_p and
5035 alt_match_null_string_p.
5037 Sets P to one after the op and its arguments, if any. */
5040 common_op_match_null_string_p (p
, end
, reg_info
)
5041 unsigned char **p
, *end
;
5042 register_info_type
*reg_info
;
5047 unsigned char *p1
= *p
;
5049 switch ((re_opcode_t
) *p1
++)
5069 assert (reg_no
> 0 && reg_no
<= MAX_REGNUM
);
5070 ret
= group_match_null_string_p (&p1
, end
, reg_info
);
5072 /* Have to set this here in case we're checking a group which
5073 contains a group and a back reference to it. */
5075 if (REG_MATCH_NULL_STRING_P (reg_info
[reg_no
]) == MATCH_NULL_UNSET_VALUE
)
5076 REG_MATCH_NULL_STRING_P (reg_info
[reg_no
]) = ret
;
5082 /* If this is an optimized succeed_n for zero times, make the jump. */
5084 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5092 /* Get to the number of times to succeed. */
5094 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5099 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5107 if (!REG_MATCH_NULL_STRING_P (reg_info
[*p1
]))
5115 /* All other opcodes mean we cannot match the empty string. */
5121 } /* common_op_match_null_string_p */
5124 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5125 bytes; nonzero otherwise. */
5128 bcmp_translate (s1
, s2
, len
, translate
)
5129 unsigned char *s1
, *s2
;
5131 RE_TRANSLATE_TYPE translate
;
5133 register unsigned char *p1
= s1
, *p2
= s2
;
5136 if (translate
[*p1
++] != translate
[*p2
++]) return 1;
5142 /* Entry points for GNU code. */
5144 /* re_compile_pattern is the GNU regular expression compiler: it
5145 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5146 Returns 0 if the pattern was valid, otherwise an error string.
5148 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5149 are set in BUFP on entry.
5151 We call regex_compile to do the actual compilation. */
5154 re_compile_pattern (pattern
, length
, bufp
)
5155 const char *pattern
;
5157 struct re_pattern_buffer
*bufp
;
5161 /* GNU code is written to assume at least RE_NREGS registers will be set
5162 (and at least one extra will be -1). */
5163 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5165 /* And GNU code determines whether or not to get register information
5166 by passing null for the REGS argument to re_match, etc., not by
5170 /* Match anchors at newline. */
5171 bufp
->newline_anchor
= 1;
5173 ret
= regex_compile (pattern
, length
, re_syntax_options
, bufp
);
5177 return gettext (re_error_msgid
[(int) ret
]);
5180 /* Entry points compatible with 4.2 BSD regex library. We don't define
5181 them unless specifically requested. */
5183 #ifdef _REGEX_RE_COMP
5185 /* BSD has one and only one pattern buffer. */
5186 static struct re_pattern_buffer re_comp_buf
;
5196 if (!re_comp_buf
.buffer
)
5197 return gettext ("No previous regular expression");
5201 if (!re_comp_buf
.buffer
)
5203 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
5204 if (re_comp_buf
.buffer
== NULL
)
5205 return gettext (re_error_msgid
[(int) REG_ESPACE
]);
5206 re_comp_buf
.allocated
= 200;
5208 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5209 if (re_comp_buf
.fastmap
== NULL
)
5210 return gettext (re_error_msgid
[(int) REG_ESPACE
]);
5213 /* Since `re_exec' always passes NULL for the `regs' argument, we
5214 don't need to initialize the pattern buffer fields which affect it. */
5216 /* Match anchors at newlines. */
5217 re_comp_buf
.newline_anchor
= 1;
5219 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
5224 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5225 return (char *) gettext (re_error_msgid
[(int) ret
]);
5233 const int len
= strlen (s
);
5235 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
5237 #endif /* _REGEX_RE_COMP */
5239 /* POSIX.2 functions. Don't define these for Emacs. */
5243 /* regcomp takes a regular expression as a string and compiles it.
5245 PREG is a regex_t *. We do not expect any fields to be initialized,
5246 since POSIX says we shouldn't. Thus, we set
5248 `buffer' to the compiled pattern;
5249 `used' to the length of the compiled pattern;
5250 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5251 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5252 RE_SYNTAX_POSIX_BASIC;
5253 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5254 `fastmap' and `fastmap_accurate' to zero;
5255 `re_nsub' to the number of subexpressions in PATTERN.
5257 PATTERN is the address of the pattern string.
5259 CFLAGS is a series of bits which affect compilation.
5261 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5262 use POSIX basic syntax.
5264 If REG_NEWLINE is set, then . and [^...] don't match newline.
5265 Also, regexec will try a match beginning after every newline.
5267 If REG_ICASE is set, then we considers upper- and lowercase
5268 versions of letters to be equivalent when matching.
5270 If REG_NOSUB is set, then when PREG is passed to regexec, that
5271 routine will report only success or failure, and nothing about the
5274 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5275 the return codes and their meanings.) */
5278 regcomp (preg
, pattern
, cflags
)
5280 const char *pattern
;
5285 = (cflags
& REG_EXTENDED
) ?
5286 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
5288 /* regex_compile will allocate the space for the compiled pattern. */
5290 preg
->allocated
= 0;
5293 /* Don't bother to use a fastmap when searching. This simplifies the
5294 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5295 characters after newlines into the fastmap. This way, we just try
5299 if (cflags
& REG_ICASE
)
5304 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
5305 * sizeof (*(RE_TRANSLATE_TYPE
)0));
5306 if (preg
->translate
== NULL
)
5307 return (int) REG_ESPACE
;
5309 /* Map uppercase characters to corresponding lowercase ones. */
5310 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
5311 preg
->translate
[i
] = ISUPPER (i
) ? tolower (i
) : i
;
5314 preg
->translate
= NULL
;
5316 /* If REG_NEWLINE is set, newlines are treated differently. */
5317 if (cflags
& REG_NEWLINE
)
5318 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5319 syntax
&= ~RE_DOT_NEWLINE
;
5320 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
5321 /* It also changes the matching behavior. */
5322 preg
->newline_anchor
= 1;
5325 preg
->newline_anchor
= 0;
5327 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
5329 /* POSIX says a null character in the pattern terminates it, so we
5330 can use strlen here in compiling the pattern. */
5331 ret
= regex_compile (pattern
, strlen (pattern
), syntax
, preg
);
5333 /* POSIX doesn't distinguish between an unmatched open-group and an
5334 unmatched close-group: both are REG_EPAREN. */
5335 if (ret
== REG_ERPAREN
) ret
= REG_EPAREN
;
5341 /* regexec searches for a given pattern, specified by PREG, in the
5344 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5345 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5346 least NMATCH elements, and we set them to the offsets of the
5347 corresponding matched substrings.
5349 EFLAGS specifies `execution flags' which affect matching: if
5350 REG_NOTBOL is set, then ^ does not match at the beginning of the
5351 string; if REG_NOTEOL is set, then $ does not match at the end.
5353 We return 0 if we find a match and REG_NOMATCH if not. */
5356 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
5357 const regex_t
*preg
;
5360 regmatch_t pmatch
[];
5364 struct re_registers regs
;
5365 regex_t private_preg
;
5366 int len
= strlen (string
);
5367 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0;
5369 private_preg
= *preg
;
5371 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
5372 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
5374 /* The user has told us exactly how many registers to return
5375 information about, via `nmatch'. We have to pass that on to the
5376 matching routines. */
5377 private_preg
.regs_allocated
= REGS_FIXED
;
5381 regs
.num_regs
= nmatch
;
5382 regs
.start
= TALLOC (nmatch
, regoff_t
);
5383 regs
.end
= TALLOC (nmatch
, regoff_t
);
5384 if (regs
.start
== NULL
|| regs
.end
== NULL
)
5385 return (int) REG_NOMATCH
;
5388 /* Perform the searching operation. */
5389 ret
= re_search (&private_preg
, string
, len
,
5390 /* start: */ 0, /* range: */ len
,
5391 want_reg_info
? ®s
: (struct re_registers
*) 0);
5393 /* Copy the register information to the POSIX structure. */
5400 for (r
= 0; r
< nmatch
; r
++)
5402 pmatch
[r
].rm_so
= regs
.start
[r
];
5403 pmatch
[r
].rm_eo
= regs
.end
[r
];
5407 /* If we needed the temporary register info, free the space now. */
5412 /* We want zero return to mean success, unlike `re_search'. */
5413 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
5417 /* Returns a message corresponding to an error code, ERRCODE, returned
5418 from either regcomp or regexec. We don't use PREG here. */
5421 regerror (errcode
, preg
, errbuf
, errbuf_size
)
5423 const regex_t
*preg
;
5431 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
5432 /* Only error codes returned by the rest of the code should be passed
5433 to this routine. If we are given anything else, or if other regex
5434 code generates an invalid error code, then the program has a bug.
5435 Dump core so we can fix it. */
5438 msg
= gettext (re_error_msgid
[errcode
]);
5440 msg_size
= strlen (msg
) + 1; /* Includes the null. */
5442 if (errbuf_size
!= 0)
5444 if (msg_size
> errbuf_size
)
5446 strncpy (errbuf
, msg
, errbuf_size
- 1);
5447 errbuf
[errbuf_size
- 1] = 0;
5450 strcpy (errbuf
, msg
);
5457 /* Free dynamically allocated space used by PREG. */
5463 if (preg
->buffer
!= NULL
)
5464 free (preg
->buffer
);
5465 preg
->buffer
= NULL
;
5467 preg
->allocated
= 0;
5470 if (preg
->fastmap
!= NULL
)
5471 free (preg
->fastmap
);
5472 preg
->fastmap
= NULL
;
5473 preg
->fastmap_accurate
= 0;
5475 if (preg
->translate
!= NULL
)
5476 free (preg
->translate
);
5477 preg
->translate
= NULL
;
5480 #endif /* not emacs */
5484 make-backup-files: t
5486 trim-versions-without-asking: nil