Update.
[glibc.git] / posix / regex.c
bloba2f20103cc2d9bee3beabd4ac9553803fcacf102
1 /* Extended regular expression matching and search library,
2 version 0.12.
3 (Implements POSIX draft P1003.2/D11.2, except for some of the
4 internationalization features.)
5 Copyright (C) 1993-1999, 2000, 2001 Free Software Foundation, Inc.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined _AIX && !defined REGEX_MALLOC
24 #pragma alloca
25 #endif
27 #undef _GNU_SOURCE
28 #define _GNU_SOURCE
30 #ifdef HAVE_CONFIG_H
31 # include <config.h>
32 #endif
34 #ifndef PARAMS
35 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
36 # define PARAMS(args) args
37 # else
38 # define PARAMS(args) ()
39 # endif /* GCC. */
40 #endif /* Not PARAMS. */
42 #ifndef INSIDE_RECURSION
44 # if defined STDC_HEADERS && !defined emacs
45 # include <stddef.h>
46 # else
47 /* We need this for `regex.h', and perhaps for the Emacs include files. */
48 # include <sys/types.h>
49 # endif
51 # define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
53 /* For platform which support the ISO C amendement 1 functionality we
54 support user defined character classes. */
55 # if defined _LIBC || WIDE_CHAR_SUPPORT
56 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
57 # include <wchar.h>
58 # include <wctype.h>
59 # endif
61 # ifdef _LIBC
62 /* We have to keep the namespace clean. */
63 # define regfree(preg) __regfree (preg)
64 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
65 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
66 # define regerror(errcode, preg, errbuf, errbuf_size) \
67 __regerror(errcode, preg, errbuf, errbuf_size)
68 # define re_set_registers(bu, re, nu, st, en) \
69 __re_set_registers (bu, re, nu, st, en)
70 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
71 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
72 # define re_match(bufp, string, size, pos, regs) \
73 __re_match (bufp, string, size, pos, regs)
74 # define re_search(bufp, string, size, startpos, range, regs) \
75 __re_search (bufp, string, size, startpos, range, regs)
76 # define re_compile_pattern(pattern, length, bufp) \
77 __re_compile_pattern (pattern, length, bufp)
78 # define re_set_syntax(syntax) __re_set_syntax (syntax)
79 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
80 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
81 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
83 # define btowc __btowc
85 /* We are also using some library internals. */
86 # include <locale/localeinfo.h>
87 # include <locale/elem-hash.h>
88 # include <langinfo.h>
89 # include <locale/coll-lookup.h>
90 # endif
92 /* This is for other GNU distributions with internationalized messages. */
93 # if HAVE_LIBINTL_H || defined _LIBC
94 # include <libintl.h>
95 # ifdef _LIBC
96 # undef gettext
97 # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
98 # endif
99 # else
100 # define gettext(msgid) (msgid)
101 # endif
103 # ifndef gettext_noop
104 /* This define is so xgettext can find the internationalizable
105 strings. */
106 # define gettext_noop(String) String
107 # endif
109 /* The `emacs' switch turns on certain matching commands
110 that make sense only in Emacs. */
111 # ifdef emacs
113 # include "lisp.h"
114 # include "buffer.h"
115 # include "syntax.h"
117 # else /* not emacs */
119 /* If we are not linking with Emacs proper,
120 we can't use the relocating allocator
121 even if config.h says that we can. */
122 # undef REL_ALLOC
124 # if defined STDC_HEADERS || defined _LIBC
125 # include <stdlib.h>
126 # else
127 char *malloc ();
128 char *realloc ();
129 # endif
131 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
132 If nothing else has been done, use the method below. */
133 # ifdef INHIBIT_STRING_HEADER
134 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
135 # if !defined bzero && !defined bcopy
136 # undef INHIBIT_STRING_HEADER
137 # endif
138 # endif
139 # endif
141 /* This is the normal way of making sure we have a bcopy and a bzero.
142 This is used in most programs--a few other programs avoid this
143 by defining INHIBIT_STRING_HEADER. */
144 # ifndef INHIBIT_STRING_HEADER
145 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
146 # include <string.h>
147 # ifndef bzero
148 # ifndef _LIBC
149 # define bzero(s, n) (memset (s, '\0', n), (s))
150 # else
151 # define bzero(s, n) __bzero (s, n)
152 # endif
153 # endif
154 # else
155 # include <strings.h>
156 # ifndef memcmp
157 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
158 # endif
159 # ifndef memcpy
160 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
161 # endif
162 # endif
163 # endif
165 /* Define the syntax stuff for \<, \>, etc. */
167 /* This must be nonzero for the wordchar and notwordchar pattern
168 commands in re_match_2. */
169 # ifndef Sword
170 # define Sword 1
171 # endif
173 # ifdef SWITCH_ENUM_BUG
174 # define SWITCH_ENUM_CAST(x) ((int)(x))
175 # else
176 # define SWITCH_ENUM_CAST(x) (x)
177 # endif
179 # endif /* not emacs */
181 # if defined _LIBC || HAVE_LIMITS_H
182 # include <limits.h>
183 # endif
185 # ifndef MB_LEN_MAX
186 # define MB_LEN_MAX 1
187 # endif
189 /* Get the interface, including the syntax bits. */
190 # include <regex.h>
192 /* isalpha etc. are used for the character classes. */
193 # include <ctype.h>
195 /* Jim Meyering writes:
197 "... Some ctype macros are valid only for character codes that
198 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
199 using /bin/cc or gcc but without giving an ansi option). So, all
200 ctype uses should be through macros like ISPRINT... If
201 STDC_HEADERS is defined, then autoconf has verified that the ctype
202 macros don't need to be guarded with references to isascii. ...
203 Defining isascii to 1 should let any compiler worth its salt
204 eliminate the && through constant folding."
205 Solaris defines some of these symbols so we must undefine them first. */
207 # undef ISASCII
208 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
209 # define ISASCII(c) 1
210 # else
211 # define ISASCII(c) isascii(c)
212 # endif
214 # ifdef isblank
215 # define ISBLANK(c) (ISASCII (c) && isblank (c))
216 # else
217 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
218 # endif
219 # ifdef isgraph
220 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
221 # else
222 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
223 # endif
225 # undef ISPRINT
226 # define ISPRINT(c) (ISASCII (c) && isprint (c))
227 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
228 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
229 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
230 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
231 # define ISLOWER(c) (ISASCII (c) && islower (c))
232 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
233 # define ISSPACE(c) (ISASCII (c) && isspace (c))
234 # define ISUPPER(c) (ISASCII (c) && isupper (c))
235 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
237 # ifdef _tolower
238 # define TOLOWER(c) _tolower(c)
239 # else
240 # define TOLOWER(c) tolower(c)
241 # endif
243 # ifndef NULL
244 # define NULL (void *)0
245 # endif
247 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
248 since ours (we hope) works properly with all combinations of
249 machines, compilers, `char' and `unsigned char' argument types.
250 (Per Bothner suggested the basic approach.) */
251 # undef SIGN_EXTEND_CHAR
252 # if __STDC__
253 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
254 # else /* not __STDC__ */
255 /* As in Harbison and Steele. */
256 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
257 # endif
259 # ifndef emacs
260 /* How many characters in the character set. */
261 # define CHAR_SET_SIZE 256
263 # ifdef SYNTAX_TABLE
265 extern char *re_syntax_table;
267 # else /* not SYNTAX_TABLE */
269 static char re_syntax_table[CHAR_SET_SIZE];
271 static void init_syntax_once PARAMS ((void));
273 static void
274 init_syntax_once ()
276 register int c;
277 static int done = 0;
279 if (done)
280 return;
281 bzero (re_syntax_table, sizeof re_syntax_table);
283 for (c = 0; c < CHAR_SET_SIZE; ++c)
284 if (ISALNUM (c))
285 re_syntax_table[c] = Sword;
287 re_syntax_table['_'] = Sword;
289 done = 1;
292 # endif /* not SYNTAX_TABLE */
294 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
296 # endif /* emacs */
298 /* Integer type for pointers. */
299 # if !defined _LIBC
300 typedef unsigned long int uintptr_t;
301 # endif
303 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
304 use `alloca' instead of `malloc'. This is because using malloc in
305 re_search* or re_match* could cause memory leaks when C-g is used in
306 Emacs; also, malloc is slower and causes storage fragmentation. On
307 the other hand, malloc is more portable, and easier to debug.
309 Because we sometimes use alloca, some routines have to be macros,
310 not functions -- `alloca'-allocated space disappears at the end of the
311 function it is called in. */
313 # ifdef REGEX_MALLOC
315 # define REGEX_ALLOCATE malloc
316 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
317 # define REGEX_FREE free
319 # else /* not REGEX_MALLOC */
321 /* Emacs already defines alloca, sometimes. */
322 # ifndef alloca
324 /* Make alloca work the best possible way. */
325 # ifdef __GNUC__
326 # define alloca __builtin_alloca
327 # else /* not __GNUC__ */
328 # if HAVE_ALLOCA_H
329 # include <alloca.h>
330 # endif /* HAVE_ALLOCA_H */
331 # endif /* not __GNUC__ */
333 # endif /* not alloca */
335 # define REGEX_ALLOCATE alloca
337 /* Assumes a `char *destination' variable. */
338 # define REGEX_REALLOCATE(source, osize, nsize) \
339 (destination = (char *) alloca (nsize), \
340 memcpy (destination, source, osize))
342 /* No need to do anything to free, after alloca. */
343 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
345 # endif /* not REGEX_MALLOC */
347 /* Define how to allocate the failure stack. */
349 # if defined REL_ALLOC && defined REGEX_MALLOC
351 # define REGEX_ALLOCATE_STACK(size) \
352 r_alloc (&failure_stack_ptr, (size))
353 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
354 r_re_alloc (&failure_stack_ptr, (nsize))
355 # define REGEX_FREE_STACK(ptr) \
356 r_alloc_free (&failure_stack_ptr)
358 # else /* not using relocating allocator */
360 # ifdef REGEX_MALLOC
362 # define REGEX_ALLOCATE_STACK malloc
363 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
364 # define REGEX_FREE_STACK free
366 # else /* not REGEX_MALLOC */
368 # define REGEX_ALLOCATE_STACK alloca
370 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
371 REGEX_REALLOCATE (source, osize, nsize)
372 /* No need to explicitly free anything. */
373 # define REGEX_FREE_STACK(arg)
375 # endif /* not REGEX_MALLOC */
376 # endif /* not using relocating allocator */
379 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
380 `string1' or just past its end. This works if PTR is NULL, which is
381 a good thing. */
382 # define FIRST_STRING_P(ptr) \
383 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
385 /* (Re)Allocate N items of type T using malloc, or fail. */
386 # define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
387 # define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
388 # define RETALLOC_IF(addr, n, t) \
389 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
390 # define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
392 # define BYTEWIDTH 8 /* In bits. */
394 # define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
396 # undef MAX
397 # undef MIN
398 # define MAX(a, b) ((a) > (b) ? (a) : (b))
399 # define MIN(a, b) ((a) < (b) ? (a) : (b))
401 typedef char boolean;
402 # define false 0
403 # define true 1
405 static reg_errcode_t byte_regex_compile _RE_ARGS ((const char *pattern, size_t size,
406 reg_syntax_t syntax,
407 struct re_pattern_buffer *bufp));
408 static reg_errcode_t wcs_regex_compile _RE_ARGS ((const char *pattern, size_t size,
409 reg_syntax_t syntax,
410 struct re_pattern_buffer *bufp));
412 static int byte_re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
413 const char *string1, int size1,
414 const char *string2, int size2,
415 int pos,
416 struct re_registers *regs,
417 int stop));
418 static int wcs_re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
419 const char *cstring1, int csize1,
420 const char *cstring2, int csize2,
421 int pos,
422 struct re_registers *regs,
423 int stop,
424 wchar_t *string1, int size1,
425 wchar_t *string2, int size2,
426 int *mbs_offset1, int *mbs_offset2));
427 static int byte_re_search_2 PARAMS ((struct re_pattern_buffer *bufp,
428 const char *string1, int size1,
429 const char *string2, int size2,
430 int startpos, int range,
431 struct re_registers *regs, int stop));
432 static int wcs_re_search_2 PARAMS ((struct re_pattern_buffer *bufp,
433 const char *string1, int size1,
434 const char *string2, int size2,
435 int startpos, int range,
436 struct re_registers *regs, int stop));
437 static int byte_re_compile_fastmap PARAMS ((struct re_pattern_buffer *bufp));
438 static int wcs_re_compile_fastmap PARAMS ((struct re_pattern_buffer *bufp));
441 /* These are the command codes that appear in compiled regular
442 expressions. Some opcodes are followed by argument bytes. A
443 command code can specify any interpretation whatsoever for its
444 arguments. Zero bytes may appear in the compiled regular expression. */
446 typedef enum
448 no_op = 0,
450 /* Succeed right away--no more backtracking. */
451 succeed,
453 /* Followed by one byte giving n, then by n literal bytes. */
454 exactn,
456 # ifdef MBS_SUPPORT
457 /* Same as exactn, but contains binary data. */
458 exactn_bin,
459 # endif
461 /* Matches any (more or less) character. */
462 anychar,
464 /* Matches any one char belonging to specified set. First
465 following byte is number of bitmap bytes. Then come bytes
466 for a bitmap saying which chars are in. Bits in each byte
467 are ordered low-bit-first. A character is in the set if its
468 bit is 1. A character too large to have a bit in the map is
469 automatically not in the set. */
470 /* ifdef MBS_SUPPORT, following element is length of character
471 classes, length of collating symbols, length of equivalence
472 classes, length of character ranges, and length of characters.
473 Next, character class element, collating symbols elements,
474 equivalence class elements, range elements, and character
475 elements follow.
476 See regex_compile function. */
477 charset,
479 /* Same parameters as charset, but match any character that is
480 not one of those specified. */
481 charset_not,
483 /* Start remembering the text that is matched, for storing in a
484 register. Followed by one byte with the register number, in
485 the range 0 to one less than the pattern buffer's re_nsub
486 field. Then followed by one byte with the number of groups
487 inner to this one. (This last has to be part of the
488 start_memory only because we need it in the on_failure_jump
489 of re_match_2.) */
490 start_memory,
492 /* Stop remembering the text that is matched and store it in a
493 memory register. Followed by one byte with the register
494 number, in the range 0 to one less than `re_nsub' in the
495 pattern buffer, and one byte with the number of inner groups,
496 just like `start_memory'. (We need the number of inner
497 groups here because we don't have any easy way of finding the
498 corresponding start_memory when we're at a stop_memory.) */
499 stop_memory,
501 /* Match a duplicate of something remembered. Followed by one
502 byte containing the register number. */
503 duplicate,
505 /* Fail unless at beginning of line. */
506 begline,
508 /* Fail unless at end of line. */
509 endline,
511 /* Succeeds if at beginning of buffer (if emacs) or at beginning
512 of string to be matched (if not). */
513 begbuf,
515 /* Analogously, for end of buffer/string. */
516 endbuf,
518 /* Followed by two byte relative address to which to jump. */
519 jump,
521 /* Same as jump, but marks the end of an alternative. */
522 jump_past_alt,
524 /* Followed by two-byte relative address of place to resume at
525 in case of failure. */
526 /* ifdef MBS_SUPPORT, the size of address is 1. */
527 on_failure_jump,
529 /* Like on_failure_jump, but pushes a placeholder instead of the
530 current string position when executed. */
531 on_failure_keep_string_jump,
533 /* Throw away latest failure point and then jump to following
534 two-byte relative address. */
535 /* ifdef MBS_SUPPORT, the size of address is 1. */
536 pop_failure_jump,
538 /* Change to pop_failure_jump if know won't have to backtrack to
539 match; otherwise change to jump. This is used to jump
540 back to the beginning of a repeat. If what follows this jump
541 clearly won't match what the repeat does, such that we can be
542 sure that there is no use backtracking out of repetitions
543 already matched, then we change it to a pop_failure_jump.
544 Followed by two-byte address. */
545 /* ifdef MBS_SUPPORT, the size of address is 1. */
546 maybe_pop_jump,
548 /* Jump to following two-byte address, and push a dummy failure
549 point. This failure point will be thrown away if an attempt
550 is made to use it for a failure. A `+' construct makes this
551 before the first repeat. Also used as an intermediary kind
552 of jump when compiling an alternative. */
553 /* ifdef MBS_SUPPORT, the size of address is 1. */
554 dummy_failure_jump,
556 /* Push a dummy failure point and continue. Used at the end of
557 alternatives. */
558 push_dummy_failure,
560 /* Followed by two-byte relative address and two-byte number n.
561 After matching N times, jump to the address upon failure. */
562 /* ifdef MBS_SUPPORT, the size of address is 1. */
563 succeed_n,
565 /* Followed by two-byte relative address, and two-byte number n.
566 Jump to the address N times, then fail. */
567 /* ifdef MBS_SUPPORT, the size of address is 1. */
568 jump_n,
570 /* Set the following two-byte relative address to the
571 subsequent two-byte number. The address *includes* the two
572 bytes of number. */
573 /* ifdef MBS_SUPPORT, the size of address is 1. */
574 set_number_at,
576 wordchar, /* Matches any word-constituent character. */
577 notwordchar, /* Matches any char that is not a word-constituent. */
579 wordbeg, /* Succeeds if at word beginning. */
580 wordend, /* Succeeds if at word end. */
582 wordbound, /* Succeeds if at a word boundary. */
583 notwordbound /* Succeeds if not at a word boundary. */
585 # ifdef emacs
586 ,before_dot, /* Succeeds if before point. */
587 at_dot, /* Succeeds if at point. */
588 after_dot, /* Succeeds if after point. */
590 /* Matches any character whose syntax is specified. Followed by
591 a byte which contains a syntax code, e.g., Sword. */
592 syntaxspec,
594 /* Matches any character whose syntax is not that specified. */
595 notsyntaxspec
596 # endif /* emacs */
597 } re_opcode_t;
598 #endif /* not INSIDE_RECURSION */
601 #ifdef BYTE
602 # define CHAR_T char
603 # define UCHAR_T unsigned char
604 # define COMPILED_BUFFER_VAR bufp->buffer
605 # define OFFSET_ADDRESS_SIZE 2
606 # define PREFIX(name) byte_##name
607 # define ARG_PREFIX(name) name
608 # define PUT_CHAR(c) putchar (c)
609 #elif defined WCHAR
610 # define CHAR_T wchar_t
611 # define UCHAR_T wchar_t
612 # define COMPILED_BUFFER_VAR wc_buffer
613 # define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
614 # define CHAR_CLASS_SIZE ((__alignof__(wctype_t)+sizeof(wctype_t))/sizeof(CHAR_T)+1)
615 # define PREFIX(name) wcs_##name
616 # define ARG_PREFIX(name) c##name
617 /* Should we use wide stream?? */
618 # define PUT_CHAR(c) printf ("%C", c);
619 # define TRUE 1
620 # define FALSE 0
621 #else
622 # ifdef MBS_SUPPORT
623 # define WCHAR
624 # define INSIDE_RECURSION
625 # include "regex.c"
626 # undef INSIDE_RECURSION
627 # endif
628 # define BYTE
629 # define INSIDE_RECURSION
630 # include "regex.c"
631 # undef INSIDE_RECURSION
632 #endif
634 #ifdef INSIDE_RECURSION
635 /* Common operations on the compiled pattern. */
637 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
638 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
640 # ifdef WCHAR
641 # define STORE_NUMBER(destination, number) \
642 do { \
643 *(destination) = (UCHAR_T)(number); \
644 } while (0)
645 # else /* BYTE */
646 # define STORE_NUMBER(destination, number) \
647 do { \
648 (destination)[0] = (number) & 0377; \
649 (destination)[1] = (number) >> 8; \
650 } while (0)
651 # endif /* WCHAR */
653 /* Same as STORE_NUMBER, except increment DESTINATION to
654 the byte after where the number is stored. Therefore, DESTINATION
655 must be an lvalue. */
656 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
658 # define STORE_NUMBER_AND_INCR(destination, number) \
659 do { \
660 STORE_NUMBER (destination, number); \
661 (destination) += OFFSET_ADDRESS_SIZE; \
662 } while (0)
664 /* Put into DESTINATION a number stored in two contiguous bytes starting
665 at SOURCE. */
666 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
668 # ifdef WCHAR
669 # define EXTRACT_NUMBER(destination, source) \
670 do { \
671 (destination) = *(source); \
672 } while (0)
673 # else /* BYTE */
674 # define EXTRACT_NUMBER(destination, source) \
675 do { \
676 (destination) = *(source) & 0377; \
677 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
678 } while (0)
679 # endif
681 # ifdef DEBUG
682 static void PREFIX(extract_number) _RE_ARGS ((int *dest, UCHAR_T *source));
683 static void
684 PREFIX(extract_number) (dest, source)
685 int *dest;
686 UCHAR_T *source;
688 # ifdef WCHAR
689 *dest = *source;
690 # else /* BYTE */
691 int temp = SIGN_EXTEND_CHAR (*(source + 1));
692 *dest = *source & 0377;
693 *dest += temp << 8;
694 # endif
697 # ifndef EXTRACT_MACROS /* To debug the macros. */
698 # undef EXTRACT_NUMBER
699 # define EXTRACT_NUMBER(dest, src) PREFIX(extract_number) (&dest, src)
700 # endif /* not EXTRACT_MACROS */
702 # endif /* DEBUG */
704 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
705 SOURCE must be an lvalue. */
707 # define EXTRACT_NUMBER_AND_INCR(destination, source) \
708 do { \
709 EXTRACT_NUMBER (destination, source); \
710 (source) += OFFSET_ADDRESS_SIZE; \
711 } while (0)
713 # ifdef DEBUG
714 static void PREFIX(extract_number_and_incr) _RE_ARGS ((int *destination,
715 UCHAR_T **source));
716 static void
717 PREFIX(extract_number_and_incr) (destination, source)
718 int *destination;
719 UCHAR_T **source;
721 PREFIX(extract_number) (destination, *source);
722 *source += OFFSET_ADDRESS_SIZE;
725 # ifndef EXTRACT_MACROS
726 # undef EXTRACT_NUMBER_AND_INCR
727 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
728 PREFIX(extract_number_and_incr) (&dest, &src)
729 # endif /* not EXTRACT_MACROS */
731 # endif /* DEBUG */
735 /* If DEBUG is defined, Regex prints many voluminous messages about what
736 it is doing (if the variable `debug' is nonzero). If linked with the
737 main program in `iregex.c', you can enter patterns and strings
738 interactively. And if linked with the main program in `main.c' and
739 the other test files, you can run the already-written tests. */
741 # ifdef DEBUG
743 # ifndef DEFINED_ONCE
745 /* We use standard I/O for debugging. */
746 # include <stdio.h>
748 /* It is useful to test things that ``must'' be true when debugging. */
749 # include <assert.h>
751 static int debug;
753 # define DEBUG_STATEMENT(e) e
754 # define DEBUG_PRINT1(x) if (debug) printf (x)
755 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
756 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
757 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
758 # endif /* not DEFINED_ONCE */
760 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
761 if (debug) PREFIX(print_partial_compiled_pattern) (s, e)
762 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
763 if (debug) PREFIX(print_double_string) (w, s1, sz1, s2, sz2)
766 /* Print the fastmap in human-readable form. */
768 # ifndef DEFINED_ONCE
769 void
770 print_fastmap (fastmap)
771 char *fastmap;
773 unsigned was_a_range = 0;
774 unsigned i = 0;
776 while (i < (1 << BYTEWIDTH))
778 if (fastmap[i++])
780 was_a_range = 0;
781 putchar (i - 1);
782 while (i < (1 << BYTEWIDTH) && fastmap[i])
784 was_a_range = 1;
785 i++;
787 if (was_a_range)
789 printf ("-");
790 putchar (i - 1);
794 putchar ('\n');
796 # endif /* not DEFINED_ONCE */
799 /* Print a compiled pattern string in human-readable form, starting at
800 the START pointer into it and ending just before the pointer END. */
802 void
803 PREFIX(print_partial_compiled_pattern) (start, end)
804 UCHAR_T *start;
805 UCHAR_T *end;
807 int mcnt, mcnt2;
808 UCHAR_T *p1;
809 UCHAR_T *p = start;
810 UCHAR_T *pend = end;
812 if (start == NULL)
814 printf ("(null)\n");
815 return;
818 /* Loop over pattern commands. */
819 while (p < pend)
821 # ifdef _LIBC
822 printf ("%td:\t", p - start);
823 # else
824 printf ("%ld:\t", (long int) (p - start));
825 # endif
827 switch ((re_opcode_t) *p++)
829 case no_op:
830 printf ("/no_op");
831 break;
833 case exactn:
834 mcnt = *p++;
835 printf ("/exactn/%d", mcnt);
838 putchar ('/');
839 PUT_CHAR (*p++);
841 while (--mcnt);
842 break;
844 # ifdef MBS_SUPPORT
845 case exactn_bin:
846 mcnt = *p++;
847 printf ("/exactn_bin/%d", mcnt);
850 printf("/%lx", (long int) *p++);
852 while (--mcnt);
853 break;
854 # endif /* MBS_SUPPORT */
856 case start_memory:
857 mcnt = *p++;
858 printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
859 break;
861 case stop_memory:
862 mcnt = *p++;
863 printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
864 break;
866 case duplicate:
867 printf ("/duplicate/%ld", (long int) *p++);
868 break;
870 case anychar:
871 printf ("/anychar");
872 break;
874 case charset:
875 case charset_not:
877 # ifdef WCHAR
878 int i, length;
879 wchar_t *workp = p;
880 printf ("/charset [%s",
881 (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
882 p += 5;
883 length = *workp++; /* the length of char_classes */
884 for (i=0 ; i<length ; i++)
885 printf("[:%lx:]", (long int) *p++);
886 length = *workp++; /* the length of collating_symbol */
887 for (i=0 ; i<length ;)
889 printf("[.");
890 while(*p != 0)
891 PUT_CHAR((i++,*p++));
892 i++,p++;
893 printf(".]");
895 length = *workp++; /* the length of equivalence_class */
896 for (i=0 ; i<length ;)
898 printf("[=");
899 while(*p != 0)
900 PUT_CHAR((i++,*p++));
901 i++,p++;
902 printf("=]");
904 length = *workp++; /* the length of char_range */
905 for (i=0 ; i<length ; i++)
907 wchar_t range_start = *p++;
908 wchar_t range_end = *p++;
909 printf("%C-%C", range_start, range_end);
911 length = *workp++; /* the length of char */
912 for (i=0 ; i<length ; i++)
913 printf("%C", *p++);
914 putchar (']');
915 # else
916 register int c, last = -100;
917 register int in_range = 0;
919 printf ("/charset [%s",
920 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
922 assert (p + *p < pend);
924 for (c = 0; c < 256; c++)
925 if (c / 8 < *p
926 && (p[1 + (c/8)] & (1 << (c % 8))))
928 /* Are we starting a range? */
929 if (last + 1 == c && ! in_range)
931 putchar ('-');
932 in_range = 1;
934 /* Have we broken a range? */
935 else if (last + 1 != c && in_range)
937 putchar (last);
938 in_range = 0;
941 if (! in_range)
942 putchar (c);
944 last = c;
947 if (in_range)
948 putchar (last);
950 putchar (']');
952 p += 1 + *p;
953 # endif /* WCHAR */
955 break;
957 case begline:
958 printf ("/begline");
959 break;
961 case endline:
962 printf ("/endline");
963 break;
965 case on_failure_jump:
966 PREFIX(extract_number_and_incr) (&mcnt, &p);
967 # ifdef _LIBC
968 printf ("/on_failure_jump to %td", p + mcnt - start);
969 # else
970 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
971 # endif
972 break;
974 case on_failure_keep_string_jump:
975 PREFIX(extract_number_and_incr) (&mcnt, &p);
976 # ifdef _LIBC
977 printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
978 # else
979 printf ("/on_failure_keep_string_jump to %ld",
980 (long int) (p + mcnt - start));
981 # endif
982 break;
984 case dummy_failure_jump:
985 PREFIX(extract_number_and_incr) (&mcnt, &p);
986 # ifdef _LIBC
987 printf ("/dummy_failure_jump to %td", p + mcnt - start);
988 # else
989 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
990 # endif
991 break;
993 case push_dummy_failure:
994 printf ("/push_dummy_failure");
995 break;
997 case maybe_pop_jump:
998 PREFIX(extract_number_and_incr) (&mcnt, &p);
999 # ifdef _LIBC
1000 printf ("/maybe_pop_jump to %td", p + mcnt - start);
1001 # else
1002 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
1003 # endif
1004 break;
1006 case pop_failure_jump:
1007 PREFIX(extract_number_and_incr) (&mcnt, &p);
1008 # ifdef _LIBC
1009 printf ("/pop_failure_jump to %td", p + mcnt - start);
1010 # else
1011 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
1012 # endif
1013 break;
1015 case jump_past_alt:
1016 PREFIX(extract_number_and_incr) (&mcnt, &p);
1017 # ifdef _LIBC
1018 printf ("/jump_past_alt to %td", p + mcnt - start);
1019 # else
1020 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
1021 # endif
1022 break;
1024 case jump:
1025 PREFIX(extract_number_and_incr) (&mcnt, &p);
1026 # ifdef _LIBC
1027 printf ("/jump to %td", p + mcnt - start);
1028 # else
1029 printf ("/jump to %ld", (long int) (p + mcnt - start));
1030 # endif
1031 break;
1033 case succeed_n:
1034 PREFIX(extract_number_and_incr) (&mcnt, &p);
1035 p1 = p + mcnt;
1036 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1037 # ifdef _LIBC
1038 printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
1039 # else
1040 printf ("/succeed_n to %ld, %d times",
1041 (long int) (p1 - start), mcnt2);
1042 # endif
1043 break;
1045 case jump_n:
1046 PREFIX(extract_number_and_incr) (&mcnt, &p);
1047 p1 = p + mcnt;
1048 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1049 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
1050 break;
1052 case set_number_at:
1053 PREFIX(extract_number_and_incr) (&mcnt, &p);
1054 p1 = p + mcnt;
1055 PREFIX(extract_number_and_incr) (&mcnt2, &p);
1056 # ifdef _LIBC
1057 printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1058 # else
1059 printf ("/set_number_at location %ld to %d",
1060 (long int) (p1 - start), mcnt2);
1061 # endif
1062 break;
1064 case wordbound:
1065 printf ("/wordbound");
1066 break;
1068 case notwordbound:
1069 printf ("/notwordbound");
1070 break;
1072 case wordbeg:
1073 printf ("/wordbeg");
1074 break;
1076 case wordend:
1077 printf ("/wordend");
1078 break;
1080 # ifdef emacs
1081 case before_dot:
1082 printf ("/before_dot");
1083 break;
1085 case at_dot:
1086 printf ("/at_dot");
1087 break;
1089 case after_dot:
1090 printf ("/after_dot");
1091 break;
1093 case syntaxspec:
1094 printf ("/syntaxspec");
1095 mcnt = *p++;
1096 printf ("/%d", mcnt);
1097 break;
1099 case notsyntaxspec:
1100 printf ("/notsyntaxspec");
1101 mcnt = *p++;
1102 printf ("/%d", mcnt);
1103 break;
1104 # endif /* emacs */
1106 case wordchar:
1107 printf ("/wordchar");
1108 break;
1110 case notwordchar:
1111 printf ("/notwordchar");
1112 break;
1114 case begbuf:
1115 printf ("/begbuf");
1116 break;
1118 case endbuf:
1119 printf ("/endbuf");
1120 break;
1122 default:
1123 printf ("?%ld", (long int) *(p-1));
1126 putchar ('\n');
1129 # ifdef _LIBC
1130 printf ("%td:\tend of pattern.\n", p - start);
1131 # else
1132 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1133 # endif
1137 void
1138 PREFIX(print_compiled_pattern) (bufp)
1139 struct re_pattern_buffer *bufp;
1141 UCHAR_T *buffer = (UCHAR_T*) bufp->buffer;
1143 PREFIX(print_partial_compiled_pattern) (buffer, buffer
1144 + bufp->used / sizeof(UCHAR_T));
1145 printf ("%ld bytes used/%ld bytes allocated.\n",
1146 bufp->used, bufp->allocated);
1148 if (bufp->fastmap_accurate && bufp->fastmap)
1150 printf ("fastmap: ");
1151 print_fastmap (bufp->fastmap);
1154 # ifdef _LIBC
1155 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1156 # else
1157 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1158 # endif
1159 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1160 printf ("can_be_null: %d\t", bufp->can_be_null);
1161 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1162 printf ("no_sub: %d\t", bufp->no_sub);
1163 printf ("not_bol: %d\t", bufp->not_bol);
1164 printf ("not_eol: %d\t", bufp->not_eol);
1165 printf ("syntax: %lx\n", bufp->syntax);
1166 /* Perhaps we should print the translate table? */
1170 void
1171 PREFIX(print_double_string) (where, string1, size1, string2, size2)
1172 const CHAR_T *where;
1173 const CHAR_T *string1;
1174 const CHAR_T *string2;
1175 int size1;
1176 int size2;
1178 int this_char;
1180 if (where == NULL)
1181 printf ("(null)");
1182 else
1184 if (FIRST_STRING_P (where))
1186 for (this_char = where - string1; this_char < size1; this_char++)
1187 PUT_CHAR (string1[this_char]);
1189 where = string2;
1192 for (this_char = where - string2; this_char < size2; this_char++)
1193 PUT_CHAR (string2[this_char]);
1197 # ifndef DEFINED_ONCE
1198 void
1199 printchar (c)
1200 int c;
1202 putc (c, stderr);
1204 # endif
1206 # else /* not DEBUG */
1208 # ifndef DEFINED_ONCE
1209 # undef assert
1210 # define assert(e)
1212 # define DEBUG_STATEMENT(e)
1213 # define DEBUG_PRINT1(x)
1214 # define DEBUG_PRINT2(x1, x2)
1215 # define DEBUG_PRINT3(x1, x2, x3)
1216 # define DEBUG_PRINT4(x1, x2, x3, x4)
1217 # endif /* not DEFINED_ONCE */
1218 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1219 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1221 # endif /* not DEBUG */
1225 # ifdef WCHAR
1226 /* This convert a multibyte string to a wide character string.
1227 And write their correspondances to offset_buffer(see below)
1228 and write whether each wchar_t is binary data to is_binary.
1229 This assume invalid multibyte sequences as binary data.
1230 We assume offset_buffer and is_binary is already allocated
1231 enough space. */
1233 static size_t convert_mbs_to_wcs (CHAR_T *dest, const unsigned char* src,
1234 size_t len, int *offset_buffer,
1235 char *is_binary);
1236 static size_t
1237 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1238 CHAR_T *dest;
1239 const unsigned char* src;
1240 size_t len; /* the length of multibyte string. */
1242 /* It hold correspondances between src(char string) and
1243 dest(wchar_t string) for optimization.
1244 e.g. src = "xxxyzz"
1245 dest = {'X', 'Y', 'Z'}
1246 (each "xxx", "y" and "zz" represent one multibyte character
1247 corresponding to 'X', 'Y' and 'Z'.)
1248 offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1249 = {0, 3, 4, 6}
1251 int *offset_buffer;
1252 char *is_binary;
1254 wchar_t *pdest = dest;
1255 const unsigned char *psrc = src;
1256 size_t wc_count = 0;
1258 mbstate_t mbs;
1259 int i, consumed;
1260 size_t mb_remain = len;
1261 size_t mb_count = 0;
1263 /* Initialize the conversion state. */
1264 memset (&mbs, 0, sizeof (mbstate_t));
1266 offset_buffer[0] = 0;
1267 for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1268 psrc += consumed)
1270 consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1272 if (consumed <= 0)
1273 /* failed to convert. maybe src contains binary data.
1274 So we consume 1 byte manualy. */
1276 *pdest = *psrc;
1277 consumed = 1;
1278 is_binary[wc_count] = TRUE;
1280 else
1281 is_binary[wc_count] = FALSE;
1282 /* In sjis encoding, we use yen sign as escape character in
1283 place of reverse solidus. So we convert 0x5c(yen sign in
1284 sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1285 solidus in UCS2). */
1286 if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1287 *pdest = (wchar_t) *psrc;
1289 offset_buffer[wc_count + 1] = mb_count += consumed;
1292 /* Fill remain of the buffer with sentinel. */
1293 for (i = wc_count + 1 ; i <= len ; i++)
1294 offset_buffer[i] = mb_count + 1;
1296 return wc_count;
1299 # endif /* WCHAR */
1301 #else /* not INSIDE_RECURSION */
1303 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1304 also be assigned to arbitrarily: each pattern buffer stores its own
1305 syntax, so it can be changed between regex compilations. */
1306 /* This has no initializer because initialized variables in Emacs
1307 become read-only after dumping. */
1308 reg_syntax_t re_syntax_options;
1311 /* Specify the precise syntax of regexps for compilation. This provides
1312 for compatibility for various utilities which historically have
1313 different, incompatible syntaxes.
1315 The argument SYNTAX is a bit mask comprised of the various bits
1316 defined in regex.h. We return the old syntax. */
1318 reg_syntax_t
1319 re_set_syntax (syntax)
1320 reg_syntax_t syntax;
1322 reg_syntax_t ret = re_syntax_options;
1324 re_syntax_options = syntax;
1325 # ifdef DEBUG
1326 if (syntax & RE_DEBUG)
1327 debug = 1;
1328 else if (debug) /* was on but now is not */
1329 debug = 0;
1330 # endif /* DEBUG */
1331 return ret;
1333 # ifdef _LIBC
1334 weak_alias (__re_set_syntax, re_set_syntax)
1335 # endif
1337 /* This table gives an error message for each of the error codes listed
1338 in regex.h. Obviously the order here has to be same as there.
1339 POSIX doesn't require that we do anything for REG_NOERROR,
1340 but why not be nice? */
1342 static const char re_error_msgid[] =
1344 # define REG_NOERROR_IDX 0
1345 gettext_noop ("Success") /* REG_NOERROR */
1346 "\0"
1347 # define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1348 gettext_noop ("No match") /* REG_NOMATCH */
1349 "\0"
1350 # define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1351 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1352 "\0"
1353 # define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1354 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1355 "\0"
1356 # define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1357 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1358 "\0"
1359 # define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1360 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1361 "\0"
1362 # define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1363 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1364 "\0"
1365 # define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1366 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1367 "\0"
1368 # define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1369 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1370 "\0"
1371 # define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1372 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1373 "\0"
1374 # define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1375 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1376 "\0"
1377 # define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1378 gettext_noop ("Invalid range end") /* REG_ERANGE */
1379 "\0"
1380 # define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1381 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1382 "\0"
1383 # define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1384 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1385 "\0"
1386 # define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1387 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1388 "\0"
1389 # define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1390 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1391 "\0"
1392 # define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1393 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1396 static const size_t re_error_msgid_idx[] =
1398 REG_NOERROR_IDX,
1399 REG_NOMATCH_IDX,
1400 REG_BADPAT_IDX,
1401 REG_ECOLLATE_IDX,
1402 REG_ECTYPE_IDX,
1403 REG_EESCAPE_IDX,
1404 REG_ESUBREG_IDX,
1405 REG_EBRACK_IDX,
1406 REG_EPAREN_IDX,
1407 REG_EBRACE_IDX,
1408 REG_BADBR_IDX,
1409 REG_ERANGE_IDX,
1410 REG_ESPACE_IDX,
1411 REG_BADRPT_IDX,
1412 REG_EEND_IDX,
1413 REG_ESIZE_IDX,
1414 REG_ERPAREN_IDX
1417 #endif /* INSIDE_RECURSION */
1419 #ifndef DEFINED_ONCE
1420 /* Avoiding alloca during matching, to placate r_alloc. */
1422 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1423 searching and matching functions should not call alloca. On some
1424 systems, alloca is implemented in terms of malloc, and if we're
1425 using the relocating allocator routines, then malloc could cause a
1426 relocation, which might (if the strings being searched are in the
1427 ralloc heap) shift the data out from underneath the regexp
1428 routines.
1430 Here's another reason to avoid allocation: Emacs
1431 processes input from X in a signal handler; processing X input may
1432 call malloc; if input arrives while a matching routine is calling
1433 malloc, then we're scrod. But Emacs can't just block input while
1434 calling matching routines; then we don't notice interrupts when
1435 they come in. So, Emacs blocks input around all regexp calls
1436 except the matching calls, which it leaves unprotected, in the
1437 faith that they will not malloc. */
1439 /* Normally, this is fine. */
1440 # define MATCH_MAY_ALLOCATE
1442 /* When using GNU C, we are not REALLY using the C alloca, no matter
1443 what config.h may say. So don't take precautions for it. */
1444 # ifdef __GNUC__
1445 # undef C_ALLOCA
1446 # endif
1448 /* The match routines may not allocate if (1) they would do it with malloc
1449 and (2) it's not safe for them to use malloc.
1450 Note that if REL_ALLOC is defined, matching would not use malloc for the
1451 failure stack, but we would still use it for the register vectors;
1452 so REL_ALLOC should not affect this. */
1453 # if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1454 # undef MATCH_MAY_ALLOCATE
1455 # endif
1456 #endif /* not DEFINED_ONCE */
1458 #ifdef INSIDE_RECURSION
1459 /* Failure stack declarations and macros; both re_compile_fastmap and
1460 re_match_2 use a failure stack. These have to be macros because of
1461 REGEX_ALLOCATE_STACK. */
1464 /* Number of failure points for which to initially allocate space
1465 when matching. If this number is exceeded, we allocate more
1466 space, so it is not a hard limit. */
1467 # ifndef INIT_FAILURE_ALLOC
1468 # define INIT_FAILURE_ALLOC 5
1469 # endif
1471 /* Roughly the maximum number of failure points on the stack. Would be
1472 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1473 This is a variable only so users of regex can assign to it; we never
1474 change it ourselves. */
1476 # ifdef INT_IS_16BIT
1478 # ifndef DEFINED_ONCE
1479 # if defined MATCH_MAY_ALLOCATE
1480 /* 4400 was enough to cause a crash on Alpha OSF/1,
1481 whose default stack limit is 2mb. */
1482 long int re_max_failures = 4000;
1483 # else
1484 long int re_max_failures = 2000;
1485 # endif
1486 # endif
1488 union PREFIX(fail_stack_elt)
1490 UCHAR_T *pointer;
1491 long int integer;
1494 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1496 typedef struct
1498 PREFIX(fail_stack_elt_t) *stack;
1499 unsigned long int size;
1500 unsigned long int avail; /* Offset of next open position. */
1501 } PREFIX(fail_stack_type);
1503 # else /* not INT_IS_16BIT */
1505 # ifndef DEFINED_ONCE
1506 # if defined MATCH_MAY_ALLOCATE
1507 /* 4400 was enough to cause a crash on Alpha OSF/1,
1508 whose default stack limit is 2mb. */
1509 int re_max_failures = 4000;
1510 # else
1511 int re_max_failures = 2000;
1512 # endif
1513 # endif
1515 union PREFIX(fail_stack_elt)
1517 UCHAR_T *pointer;
1518 int integer;
1521 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1523 typedef struct
1525 PREFIX(fail_stack_elt_t) *stack;
1526 unsigned size;
1527 unsigned avail; /* Offset of next open position. */
1528 } PREFIX(fail_stack_type);
1530 # endif /* INT_IS_16BIT */
1532 # ifndef DEFINED_ONCE
1533 # define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1534 # define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1535 # define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1536 # endif
1539 /* Define macros to initialize and free the failure stack.
1540 Do `return -2' if the alloc fails. */
1542 # ifdef MATCH_MAY_ALLOCATE
1543 # define INIT_FAIL_STACK() \
1544 do { \
1545 fail_stack.stack = (PREFIX(fail_stack_elt_t) *) \
1546 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (PREFIX(fail_stack_elt_t))); \
1548 if (fail_stack.stack == NULL) \
1549 return -2; \
1551 fail_stack.size = INIT_FAILURE_ALLOC; \
1552 fail_stack.avail = 0; \
1553 } while (0)
1555 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1556 # else
1557 # define INIT_FAIL_STACK() \
1558 do { \
1559 fail_stack.avail = 0; \
1560 } while (0)
1562 # define RESET_FAIL_STACK()
1563 # endif
1566 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1568 Return 1 if succeeds, and 0 if either ran out of memory
1569 allocating space for it or it was already too large.
1571 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1573 # define DOUBLE_FAIL_STACK(fail_stack) \
1574 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1575 ? 0 \
1576 : ((fail_stack).stack = (PREFIX(fail_stack_elt_t) *) \
1577 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1578 (fail_stack).size * sizeof (PREFIX(fail_stack_elt_t)), \
1579 ((fail_stack).size << 1) * sizeof (PREFIX(fail_stack_elt_t))),\
1581 (fail_stack).stack == NULL \
1582 ? 0 \
1583 : ((fail_stack).size <<= 1, \
1584 1)))
1587 /* Push pointer POINTER on FAIL_STACK.
1588 Return 1 if was able to do so and 0 if ran out of memory allocating
1589 space to do so. */
1590 # define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1591 ((FAIL_STACK_FULL () \
1592 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1593 ? 0 \
1594 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1597 /* Push a pointer value onto the failure stack.
1598 Assumes the variable `fail_stack'. Probably should only
1599 be called from within `PUSH_FAILURE_POINT'. */
1600 # define PUSH_FAILURE_POINTER(item) \
1601 fail_stack.stack[fail_stack.avail++].pointer = (UCHAR_T *) (item)
1603 /* This pushes an integer-valued item onto the failure stack.
1604 Assumes the variable `fail_stack'. Probably should only
1605 be called from within `PUSH_FAILURE_POINT'. */
1606 # define PUSH_FAILURE_INT(item) \
1607 fail_stack.stack[fail_stack.avail++].integer = (item)
1609 /* Push a fail_stack_elt_t value onto the failure stack.
1610 Assumes the variable `fail_stack'. Probably should only
1611 be called from within `PUSH_FAILURE_POINT'. */
1612 # define PUSH_FAILURE_ELT(item) \
1613 fail_stack.stack[fail_stack.avail++] = (item)
1615 /* These three POP... operations complement the three PUSH... operations.
1616 All assume that `fail_stack' is nonempty. */
1617 # define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1618 # define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1619 # define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1621 /* Used to omit pushing failure point id's when we're not debugging. */
1622 # ifdef DEBUG
1623 # define DEBUG_PUSH PUSH_FAILURE_INT
1624 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1625 # else
1626 # define DEBUG_PUSH(item)
1627 # define DEBUG_POP(item_addr)
1628 # endif
1631 /* Push the information about the state we will need
1632 if we ever fail back to it.
1634 Requires variables fail_stack, regstart, regend, reg_info, and
1635 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1636 be declared.
1638 Does `return FAILURE_CODE' if runs out of memory. */
1640 # define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1641 do { \
1642 char *destination; \
1643 /* Must be int, so when we don't save any registers, the arithmetic \
1644 of 0 + -1 isn't done as unsigned. */ \
1645 /* Can't be int, since there is not a shred of a guarantee that int \
1646 is wide enough to hold a value of something to which pointer can \
1647 be assigned */ \
1648 active_reg_t this_reg; \
1650 DEBUG_STATEMENT (failure_id++); \
1651 DEBUG_STATEMENT (nfailure_points_pushed++); \
1652 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1653 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1654 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1656 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1657 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1659 /* Ensure we have enough space allocated for what we will push. */ \
1660 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1662 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1663 return failure_code; \
1665 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1666 (fail_stack).size); \
1667 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1670 /* Push the info, starting with the registers. */ \
1671 DEBUG_PRINT1 ("\n"); \
1673 if (1) \
1674 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1675 this_reg++) \
1677 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1678 DEBUG_STATEMENT (num_regs_pushed++); \
1680 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1681 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1683 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1684 PUSH_FAILURE_POINTER (regend[this_reg]); \
1686 DEBUG_PRINT2 (" info: %p\n ", \
1687 reg_info[this_reg].word.pointer); \
1688 DEBUG_PRINT2 (" match_null=%d", \
1689 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1690 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1691 DEBUG_PRINT2 (" matched_something=%d", \
1692 MATCHED_SOMETHING (reg_info[this_reg])); \
1693 DEBUG_PRINT2 (" ever_matched=%d", \
1694 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1695 DEBUG_PRINT1 ("\n"); \
1696 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1699 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1700 PUSH_FAILURE_INT (lowest_active_reg); \
1702 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1703 PUSH_FAILURE_INT (highest_active_reg); \
1705 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1706 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1707 PUSH_FAILURE_POINTER (pattern_place); \
1709 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1710 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1711 size2); \
1712 DEBUG_PRINT1 ("'\n"); \
1713 PUSH_FAILURE_POINTER (string_place); \
1715 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1716 DEBUG_PUSH (failure_id); \
1717 } while (0)
1719 # ifndef DEFINED_ONCE
1720 /* This is the number of items that are pushed and popped on the stack
1721 for each register. */
1722 # define NUM_REG_ITEMS 3
1724 /* Individual items aside from the registers. */
1725 # ifdef DEBUG
1726 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1727 # else
1728 # define NUM_NONREG_ITEMS 4
1729 # endif
1731 /* We push at most this many items on the stack. */
1732 /* We used to use (num_regs - 1), which is the number of registers
1733 this regexp will save; but that was changed to 5
1734 to avoid stack overflow for a regexp with lots of parens. */
1735 # define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1737 /* We actually push this many items. */
1738 # define NUM_FAILURE_ITEMS \
1739 (((0 \
1740 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1741 * NUM_REG_ITEMS) \
1742 + NUM_NONREG_ITEMS)
1744 /* How many items can still be added to the stack without overflowing it. */
1745 # define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1746 # endif /* not DEFINED_ONCE */
1749 /* Pops what PUSH_FAIL_STACK pushes.
1751 We restore into the parameters, all of which should be lvalues:
1752 STR -- the saved data position.
1753 PAT -- the saved pattern position.
1754 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1755 REGSTART, REGEND -- arrays of string positions.
1756 REG_INFO -- array of information about each subexpression.
1758 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1759 `pend', `string1', `size1', `string2', and `size2'. */
1760 # define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1762 DEBUG_STATEMENT (unsigned failure_id;) \
1763 active_reg_t this_reg; \
1764 const UCHAR_T *string_temp; \
1766 assert (!FAIL_STACK_EMPTY ()); \
1768 /* Remove failure points and point to how many regs pushed. */ \
1769 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1770 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1771 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1773 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1775 DEBUG_POP (&failure_id); \
1776 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1778 /* If the saved string location is NULL, it came from an \
1779 on_failure_keep_string_jump opcode, and we want to throw away the \
1780 saved NULL, thus retaining our current position in the string. */ \
1781 string_temp = POP_FAILURE_POINTER (); \
1782 if (string_temp != NULL) \
1783 str = (const CHAR_T *) string_temp; \
1785 DEBUG_PRINT2 (" Popping string %p: `", str); \
1786 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1787 DEBUG_PRINT1 ("'\n"); \
1789 pat = (UCHAR_T *) POP_FAILURE_POINTER (); \
1790 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1791 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1793 /* Restore register info. */ \
1794 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1795 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1797 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1798 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1800 if (1) \
1801 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1803 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1805 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1806 DEBUG_PRINT2 (" info: %p\n", \
1807 reg_info[this_reg].word.pointer); \
1809 regend[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER (); \
1810 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1812 regstart[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER (); \
1813 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1815 else \
1817 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1819 reg_info[this_reg].word.integer = 0; \
1820 regend[this_reg] = 0; \
1821 regstart[this_reg] = 0; \
1823 highest_active_reg = high_reg; \
1826 set_regs_matched_done = 0; \
1827 DEBUG_STATEMENT (nfailure_points_popped++); \
1828 } /* POP_FAILURE_POINT */
1830 /* Structure for per-register (a.k.a. per-group) information.
1831 Other register information, such as the
1832 starting and ending positions (which are addresses), and the list of
1833 inner groups (which is a bits list) are maintained in separate
1834 variables.
1836 We are making a (strictly speaking) nonportable assumption here: that
1837 the compiler will pack our bit fields into something that fits into
1838 the type of `word', i.e., is something that fits into one item on the
1839 failure stack. */
1842 /* Declarations and macros for re_match_2. */
1844 typedef union
1846 PREFIX(fail_stack_elt_t) word;
1847 struct
1849 /* This field is one if this group can match the empty string,
1850 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1851 # define MATCH_NULL_UNSET_VALUE 3
1852 unsigned match_null_string_p : 2;
1853 unsigned is_active : 1;
1854 unsigned matched_something : 1;
1855 unsigned ever_matched_something : 1;
1856 } bits;
1857 } PREFIX(register_info_type);
1859 # ifndef DEFINED_ONCE
1860 # define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1861 # define IS_ACTIVE(R) ((R).bits.is_active)
1862 # define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1863 # define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1866 /* Call this when have matched a real character; it sets `matched' flags
1867 for the subexpressions which we are currently inside. Also records
1868 that those subexprs have matched. */
1869 # define SET_REGS_MATCHED() \
1870 do \
1872 if (!set_regs_matched_done) \
1874 active_reg_t r; \
1875 set_regs_matched_done = 1; \
1876 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1878 MATCHED_SOMETHING (reg_info[r]) \
1879 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1880 = 1; \
1884 while (0)
1885 # endif /* not DEFINED_ONCE */
1887 /* Registers are set to a sentinel when they haven't yet matched. */
1888 static CHAR_T PREFIX(reg_unset_dummy);
1889 # define REG_UNSET_VALUE (&PREFIX(reg_unset_dummy))
1890 # define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1892 /* Subroutine declarations and macros for regex_compile. */
1893 static void PREFIX(store_op1) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc, int arg));
1894 static void PREFIX(store_op2) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1895 int arg1, int arg2));
1896 static void PREFIX(insert_op1) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1897 int arg, UCHAR_T *end));
1898 static void PREFIX(insert_op2) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1899 int arg1, int arg2, UCHAR_T *end));
1900 static boolean PREFIX(at_begline_loc_p) _RE_ARGS ((const CHAR_T *pattern,
1901 const CHAR_T *p,
1902 reg_syntax_t syntax));
1903 static boolean PREFIX(at_endline_loc_p) _RE_ARGS ((const CHAR_T *p,
1904 const CHAR_T *pend,
1905 reg_syntax_t syntax));
1906 # ifdef WCHAR
1907 static reg_errcode_t wcs_compile_range _RE_ARGS ((CHAR_T range_start,
1908 const CHAR_T **p_ptr,
1909 const CHAR_T *pend,
1910 char *translate,
1911 reg_syntax_t syntax,
1912 UCHAR_T *b,
1913 CHAR_T *char_set));
1914 static void insert_space _RE_ARGS ((int num, CHAR_T *loc, CHAR_T *end));
1915 # else /* BYTE */
1916 static reg_errcode_t byte_compile_range _RE_ARGS ((unsigned int range_start,
1917 const char **p_ptr,
1918 const char *pend,
1919 char *translate,
1920 reg_syntax_t syntax,
1921 unsigned char *b));
1922 # endif /* WCHAR */
1924 /* Fetch the next character in the uncompiled pattern---translating it
1925 if necessary. Also cast from a signed character in the constant
1926 string passed to us by the user to an unsigned char that we can use
1927 as an array index (in, e.g., `translate'). */
1928 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1929 because it is impossible to allocate 4GB array for some encodings
1930 which have 4 byte character_set like UCS4. */
1931 # ifndef PATFETCH
1932 # ifdef WCHAR
1933 # define PATFETCH(c) \
1934 do {if (p == pend) return REG_EEND; \
1935 c = (UCHAR_T) *p++; \
1936 if (translate && (c <= 0xff)) c = (UCHAR_T) translate[c]; \
1937 } while (0)
1938 # else /* BYTE */
1939 # define PATFETCH(c) \
1940 do {if (p == pend) return REG_EEND; \
1941 c = (unsigned char) *p++; \
1942 if (translate) c = (unsigned char) translate[c]; \
1943 } while (0)
1944 # endif /* WCHAR */
1945 # endif
1947 /* Fetch the next character in the uncompiled pattern, with no
1948 translation. */
1949 # define PATFETCH_RAW(c) \
1950 do {if (p == pend) return REG_EEND; \
1951 c = (UCHAR_T) *p++; \
1952 } while (0)
1954 /* Go backwards one character in the pattern. */
1955 # define PATUNFETCH p--
1958 /* If `translate' is non-null, return translate[D], else just D. We
1959 cast the subscript to translate because some data is declared as
1960 `char *', to avoid warnings when a string constant is passed. But
1961 when we use a character as a subscript we must make it unsigned. */
1962 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1963 because it is impossible to allocate 4GB array for some encodings
1964 which have 4 byte character_set like UCS4. */
1966 # ifndef TRANSLATE
1967 # ifdef WCHAR
1968 # define TRANSLATE(d) \
1969 ((translate && ((UCHAR_T) (d)) <= 0xff) \
1970 ? (char) translate[(unsigned char) (d)] : (d))
1971 # else /* BYTE */
1972 # define TRANSLATE(d) \
1973 (translate ? (char) translate[(unsigned char) (d)] : (d))
1974 # endif /* WCHAR */
1975 # endif
1978 /* Macros for outputting the compiled pattern into `buffer'. */
1980 /* If the buffer isn't allocated when it comes in, use this. */
1981 # define INIT_BUF_SIZE (32 * sizeof(UCHAR_T))
1983 /* Make sure we have at least N more bytes of space in buffer. */
1984 # ifdef WCHAR
1985 # define GET_BUFFER_SPACE(n) \
1986 while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR \
1987 + (n)*sizeof(CHAR_T)) > bufp->allocated) \
1988 EXTEND_BUFFER ()
1989 # else /* BYTE */
1990 # define GET_BUFFER_SPACE(n) \
1991 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1992 EXTEND_BUFFER ()
1993 # endif /* WCHAR */
1995 /* Make sure we have one more byte of buffer space and then add C to it. */
1996 # define BUF_PUSH(c) \
1997 do { \
1998 GET_BUFFER_SPACE (1); \
1999 *b++ = (UCHAR_T) (c); \
2000 } while (0)
2003 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
2004 # define BUF_PUSH_2(c1, c2) \
2005 do { \
2006 GET_BUFFER_SPACE (2); \
2007 *b++ = (UCHAR_T) (c1); \
2008 *b++ = (UCHAR_T) (c2); \
2009 } while (0)
2012 /* As with BUF_PUSH_2, except for three bytes. */
2013 # define BUF_PUSH_3(c1, c2, c3) \
2014 do { \
2015 GET_BUFFER_SPACE (3); \
2016 *b++ = (UCHAR_T) (c1); \
2017 *b++ = (UCHAR_T) (c2); \
2018 *b++ = (UCHAR_T) (c3); \
2019 } while (0)
2021 /* Store a jump with opcode OP at LOC to location TO. We store a
2022 relative address offset by the three bytes the jump itself occupies. */
2023 # define STORE_JUMP(op, loc, to) \
2024 PREFIX(store_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
2026 /* Likewise, for a two-argument jump. */
2027 # define STORE_JUMP2(op, loc, to, arg) \
2028 PREFIX(store_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
2030 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
2031 # define INSERT_JUMP(op, loc, to) \
2032 PREFIX(insert_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
2034 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
2035 # define INSERT_JUMP2(op, loc, to, arg) \
2036 PREFIX(insert_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
2037 arg, b)
2039 /* This is not an arbitrary limit: the arguments which represent offsets
2040 into the pattern are two bytes long. So if 2^16 bytes turns out to
2041 be too small, many things would have to change. */
2042 /* Any other compiler which, like MSC, has allocation limit below 2^16
2043 bytes will have to use approach similar to what was done below for
2044 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
2045 reallocating to 0 bytes. Such thing is not going to work too well.
2046 You have been warned!! */
2047 # ifndef DEFINED_ONCE
2048 # if defined _MSC_VER && !defined WIN32
2049 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
2050 The REALLOC define eliminates a flurry of conversion warnings,
2051 but is not required. */
2052 # define MAX_BUF_SIZE 65500L
2053 # define REALLOC(p,s) realloc ((p), (size_t) (s))
2054 # else
2055 # define MAX_BUF_SIZE (1L << 16)
2056 # define REALLOC(p,s) realloc ((p), (s))
2057 # endif
2059 /* Extend the buffer by twice its current size via realloc and
2060 reset the pointers that pointed into the old block to point to the
2061 correct places in the new one. If extending the buffer results in it
2062 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
2063 # if __BOUNDED_POINTERS__
2064 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2065 # define MOVE_BUFFER_POINTER(P) \
2066 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2067 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
2068 else \
2070 SET_HIGH_BOUND (b); \
2071 SET_HIGH_BOUND (begalt); \
2072 if (fixup_alt_jump) \
2073 SET_HIGH_BOUND (fixup_alt_jump); \
2074 if (laststart) \
2075 SET_HIGH_BOUND (laststart); \
2076 if (pending_exact) \
2077 SET_HIGH_BOUND (pending_exact); \
2079 # else
2080 # define MOVE_BUFFER_POINTER(P) (P) += incr
2081 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
2082 # endif
2083 # endif /* not DEFINED_ONCE */
2085 # ifdef WCHAR
2086 # define EXTEND_BUFFER() \
2087 do { \
2088 UCHAR_T *old_buffer = COMPILED_BUFFER_VAR; \
2089 int wchar_count; \
2090 if (bufp->allocated + sizeof(UCHAR_T) > MAX_BUF_SIZE) \
2091 return REG_ESIZE; \
2092 bufp->allocated <<= 1; \
2093 if (bufp->allocated > MAX_BUF_SIZE) \
2094 bufp->allocated = MAX_BUF_SIZE; \
2095 /* How many characters the new buffer can have? */ \
2096 wchar_count = bufp->allocated / sizeof(UCHAR_T); \
2097 if (wchar_count == 0) wchar_count = 1; \
2098 /* Truncate the buffer to CHAR_T align. */ \
2099 bufp->allocated = wchar_count * sizeof(UCHAR_T); \
2100 RETALLOC (COMPILED_BUFFER_VAR, wchar_count, UCHAR_T); \
2101 bufp->buffer = (char*)COMPILED_BUFFER_VAR; \
2102 if (COMPILED_BUFFER_VAR == NULL) \
2103 return REG_ESPACE; \
2104 /* If the buffer moved, move all the pointers into it. */ \
2105 if (old_buffer != COMPILED_BUFFER_VAR) \
2107 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2108 MOVE_BUFFER_POINTER (b); \
2109 MOVE_BUFFER_POINTER (begalt); \
2110 if (fixup_alt_jump) \
2111 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2112 if (laststart) \
2113 MOVE_BUFFER_POINTER (laststart); \
2114 if (pending_exact) \
2115 MOVE_BUFFER_POINTER (pending_exact); \
2117 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2118 } while (0)
2119 # else /* BYTE */
2120 # define EXTEND_BUFFER() \
2121 do { \
2122 UCHAR_T *old_buffer = COMPILED_BUFFER_VAR; \
2123 if (bufp->allocated == MAX_BUF_SIZE) \
2124 return REG_ESIZE; \
2125 bufp->allocated <<= 1; \
2126 if (bufp->allocated > MAX_BUF_SIZE) \
2127 bufp->allocated = MAX_BUF_SIZE; \
2128 bufp->buffer = (UCHAR_T *) REALLOC (COMPILED_BUFFER_VAR, \
2129 bufp->allocated); \
2130 if (COMPILED_BUFFER_VAR == NULL) \
2131 return REG_ESPACE; \
2132 /* If the buffer moved, move all the pointers into it. */ \
2133 if (old_buffer != COMPILED_BUFFER_VAR) \
2135 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2136 MOVE_BUFFER_POINTER (b); \
2137 MOVE_BUFFER_POINTER (begalt); \
2138 if (fixup_alt_jump) \
2139 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2140 if (laststart) \
2141 MOVE_BUFFER_POINTER (laststart); \
2142 if (pending_exact) \
2143 MOVE_BUFFER_POINTER (pending_exact); \
2145 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2146 } while (0)
2147 # endif /* WCHAR */
2149 # ifndef DEFINED_ONCE
2150 /* Since we have one byte reserved for the register number argument to
2151 {start,stop}_memory, the maximum number of groups we can report
2152 things about is what fits in that byte. */
2153 # define MAX_REGNUM 255
2155 /* But patterns can have more than `MAX_REGNUM' registers. We just
2156 ignore the excess. */
2157 typedef unsigned regnum_t;
2160 /* Macros for the compile stack. */
2162 /* Since offsets can go either forwards or backwards, this type needs to
2163 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
2164 /* int may be not enough when sizeof(int) == 2. */
2165 typedef long pattern_offset_t;
2167 typedef struct
2169 pattern_offset_t begalt_offset;
2170 pattern_offset_t fixup_alt_jump;
2171 pattern_offset_t inner_group_offset;
2172 pattern_offset_t laststart_offset;
2173 regnum_t regnum;
2174 } compile_stack_elt_t;
2177 typedef struct
2179 compile_stack_elt_t *stack;
2180 unsigned size;
2181 unsigned avail; /* Offset of next open position. */
2182 } compile_stack_type;
2185 # define INIT_COMPILE_STACK_SIZE 32
2187 # define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
2188 # define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
2190 /* The next available element. */
2191 # define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2193 # endif /* not DEFINED_ONCE */
2195 /* Set the bit for character C in a list. */
2196 # ifndef DEFINED_ONCE
2197 # define SET_LIST_BIT(c) \
2198 (b[((unsigned char) (c)) / BYTEWIDTH] \
2199 |= 1 << (((unsigned char) c) % BYTEWIDTH))
2200 # endif /* DEFINED_ONCE */
2202 /* Get the next unsigned number in the uncompiled pattern. */
2203 # define GET_UNSIGNED_NUMBER(num) \
2205 while (p != pend) \
2207 PATFETCH (c); \
2208 if (c < '0' || c > '9') \
2209 break; \
2210 if (num <= RE_DUP_MAX) \
2212 if (num < 0) \
2213 num = 0; \
2214 num = num * 10 + c - '0'; \
2219 # ifndef DEFINED_ONCE
2220 # if defined _LIBC || WIDE_CHAR_SUPPORT
2221 /* The GNU C library provides support for user-defined character classes
2222 and the functions from ISO C amendement 1. */
2223 # ifdef CHARCLASS_NAME_MAX
2224 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2225 # else
2226 /* This shouldn't happen but some implementation might still have this
2227 problem. Use a reasonable default value. */
2228 # define CHAR_CLASS_MAX_LENGTH 256
2229 # endif
2231 # ifdef _LIBC
2232 # define IS_CHAR_CLASS(string) __wctype (string)
2233 # else
2234 # define IS_CHAR_CLASS(string) wctype (string)
2235 # endif
2236 # else
2237 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
2239 # define IS_CHAR_CLASS(string) \
2240 (STREQ (string, "alpha") || STREQ (string, "upper") \
2241 || STREQ (string, "lower") || STREQ (string, "digit") \
2242 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
2243 || STREQ (string, "space") || STREQ (string, "print") \
2244 || STREQ (string, "punct") || STREQ (string, "graph") \
2245 || STREQ (string, "cntrl") || STREQ (string, "blank"))
2246 # endif
2247 # endif /* DEFINED_ONCE */
2249 # ifndef MATCH_MAY_ALLOCATE
2251 /* If we cannot allocate large objects within re_match_2_internal,
2252 we make the fail stack and register vectors global.
2253 The fail stack, we grow to the maximum size when a regexp
2254 is compiled.
2255 The register vectors, we adjust in size each time we
2256 compile a regexp, according to the number of registers it needs. */
2258 static PREFIX(fail_stack_type) fail_stack;
2260 /* Size with which the following vectors are currently allocated.
2261 That is so we can make them bigger as needed,
2262 but never make them smaller. */
2263 # ifdef DEFINED_ONCE
2264 static int regs_allocated_size;
2266 static const char ** regstart, ** regend;
2267 static const char ** old_regstart, ** old_regend;
2268 static const char **best_regstart, **best_regend;
2269 static const char **reg_dummy;
2270 # endif /* DEFINED_ONCE */
2272 static PREFIX(register_info_type) *PREFIX(reg_info);
2273 static PREFIX(register_info_type) *PREFIX(reg_info_dummy);
2275 /* Make the register vectors big enough for NUM_REGS registers,
2276 but don't make them smaller. */
2278 static void
2279 PREFIX(regex_grow_registers) (num_regs)
2280 int num_regs;
2282 if (num_regs > regs_allocated_size)
2284 RETALLOC_IF (regstart, num_regs, const char *);
2285 RETALLOC_IF (regend, num_regs, const char *);
2286 RETALLOC_IF (old_regstart, num_regs, const char *);
2287 RETALLOC_IF (old_regend, num_regs, const char *);
2288 RETALLOC_IF (best_regstart, num_regs, const char *);
2289 RETALLOC_IF (best_regend, num_regs, const char *);
2290 RETALLOC_IF (PREFIX(reg_info), num_regs, PREFIX(register_info_type));
2291 RETALLOC_IF (reg_dummy, num_regs, const char *);
2292 RETALLOC_IF (PREFIX(reg_info_dummy), num_regs, PREFIX(register_info_type));
2294 regs_allocated_size = num_regs;
2298 # endif /* not MATCH_MAY_ALLOCATE */
2300 # ifndef DEFINED_ONCE
2301 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2302 compile_stack,
2303 regnum_t regnum));
2304 # endif /* not DEFINED_ONCE */
2306 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2307 Returns one of error codes defined in `regex.h', or zero for success.
2309 Assumes the `allocated' (and perhaps `buffer') and `translate'
2310 fields are set in BUFP on entry.
2312 If it succeeds, results are put in BUFP (if it returns an error, the
2313 contents of BUFP are undefined):
2314 `buffer' is the compiled pattern;
2315 `syntax' is set to SYNTAX;
2316 `used' is set to the length of the compiled pattern;
2317 `fastmap_accurate' is zero;
2318 `re_nsub' is the number of subexpressions in PATTERN;
2319 `not_bol' and `not_eol' are zero;
2321 The `fastmap' and `newline_anchor' fields are neither
2322 examined nor set. */
2324 /* Return, freeing storage we allocated. */
2325 # ifdef WCHAR
2326 # define FREE_STACK_RETURN(value) \
2327 return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2328 # else
2329 # define FREE_STACK_RETURN(value) \
2330 return (free (compile_stack.stack), value)
2331 # endif /* WCHAR */
2333 static reg_errcode_t
2334 PREFIX(regex_compile) (ARG_PREFIX(pattern), ARG_PREFIX(size), syntax, bufp)
2335 const char *ARG_PREFIX(pattern);
2336 size_t ARG_PREFIX(size);
2337 reg_syntax_t syntax;
2338 struct re_pattern_buffer *bufp;
2340 /* We fetch characters from PATTERN here. Even though PATTERN is
2341 `char *' (i.e., signed), we declare these variables as unsigned, so
2342 they can be reliably used as array indices. */
2343 register UCHAR_T c, c1;
2345 #ifdef WCHAR
2346 /* A temporary space to keep wchar_t pattern and compiled pattern. */
2347 CHAR_T *pattern, *COMPILED_BUFFER_VAR;
2348 size_t size;
2349 /* offset buffer for optimization. See convert_mbs_to_wc. */
2350 int *mbs_offset = NULL;
2351 /* It hold whether each wchar_t is binary data or not. */
2352 char *is_binary = NULL;
2353 /* A flag whether exactn is handling binary data or not. */
2354 char is_exactn_bin = FALSE;
2355 #endif /* WCHAR */
2357 /* A random temporary spot in PATTERN. */
2358 const CHAR_T *p1;
2360 /* Points to the end of the buffer, where we should append. */
2361 register UCHAR_T *b;
2363 /* Keeps track of unclosed groups. */
2364 compile_stack_type compile_stack;
2366 /* Points to the current (ending) position in the pattern. */
2367 #ifdef WCHAR
2368 const CHAR_T *p;
2369 const CHAR_T *pend;
2370 #else /* BYTE */
2371 const CHAR_T *p = pattern;
2372 const CHAR_T *pend = pattern + size;
2373 #endif /* WCHAR */
2375 /* How to translate the characters in the pattern. */
2376 RE_TRANSLATE_TYPE translate = bufp->translate;
2378 /* Address of the count-byte of the most recently inserted `exactn'
2379 command. This makes it possible to tell if a new exact-match
2380 character can be added to that command or if the character requires
2381 a new `exactn' command. */
2382 UCHAR_T *pending_exact = 0;
2384 /* Address of start of the most recently finished expression.
2385 This tells, e.g., postfix * where to find the start of its
2386 operand. Reset at the beginning of groups and alternatives. */
2387 UCHAR_T *laststart = 0;
2389 /* Address of beginning of regexp, or inside of last group. */
2390 UCHAR_T *begalt;
2392 /* Address of the place where a forward jump should go to the end of
2393 the containing expression. Each alternative of an `or' -- except the
2394 last -- ends with a forward jump of this sort. */
2395 UCHAR_T *fixup_alt_jump = 0;
2397 /* Counts open-groups as they are encountered. Remembered for the
2398 matching close-group on the compile stack, so the same register
2399 number is put in the stop_memory as the start_memory. */
2400 regnum_t regnum = 0;
2402 #ifdef WCHAR
2403 /* Initialize the wchar_t PATTERN and offset_buffer. */
2404 p = pend = pattern = TALLOC(csize + 1, CHAR_T);
2405 mbs_offset = TALLOC(csize + 1, int);
2406 is_binary = TALLOC(csize + 1, char);
2407 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2409 free(pattern);
2410 free(mbs_offset);
2411 free(is_binary);
2412 return REG_ESPACE;
2414 pattern[csize] = L'\0'; /* sentinel */
2415 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2416 pend = p + size;
2417 if (size < 0)
2419 free(pattern);
2420 free(mbs_offset);
2421 free(is_binary);
2422 return REG_BADPAT;
2424 #endif
2426 #ifdef DEBUG
2427 DEBUG_PRINT1 ("\nCompiling pattern: ");
2428 if (debug)
2430 unsigned debug_count;
2432 for (debug_count = 0; debug_count < size; debug_count++)
2433 PUT_CHAR (pattern[debug_count]);
2434 putchar ('\n');
2436 #endif /* DEBUG */
2438 /* Initialize the compile stack. */
2439 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2440 if (compile_stack.stack == NULL)
2442 #ifdef WCHAR
2443 free(pattern);
2444 free(mbs_offset);
2445 free(is_binary);
2446 #endif
2447 return REG_ESPACE;
2450 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2451 compile_stack.avail = 0;
2453 /* Initialize the pattern buffer. */
2454 bufp->syntax = syntax;
2455 bufp->fastmap_accurate = 0;
2456 bufp->not_bol = bufp->not_eol = 0;
2458 /* Set `used' to zero, so that if we return an error, the pattern
2459 printer (for debugging) will think there's no pattern. We reset it
2460 at the end. */
2461 bufp->used = 0;
2463 /* Always count groups, whether or not bufp->no_sub is set. */
2464 bufp->re_nsub = 0;
2466 #if !defined emacs && !defined SYNTAX_TABLE
2467 /* Initialize the syntax table. */
2468 init_syntax_once ();
2469 #endif
2471 if (bufp->allocated == 0)
2473 if (bufp->buffer)
2474 { /* If zero allocated, but buffer is non-null, try to realloc
2475 enough space. This loses if buffer's address is bogus, but
2476 that is the user's responsibility. */
2477 #ifdef WCHAR
2478 /* Free bufp->buffer and allocate an array for wchar_t pattern
2479 buffer. */
2480 free(bufp->buffer);
2481 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(UCHAR_T),
2482 UCHAR_T);
2483 #else
2484 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, UCHAR_T);
2485 #endif /* WCHAR */
2487 else
2488 { /* Caller did not allocate a buffer. Do it for them. */
2489 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(UCHAR_T),
2490 UCHAR_T);
2493 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2494 #ifdef WCHAR
2495 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2496 #endif /* WCHAR */
2497 bufp->allocated = INIT_BUF_SIZE;
2499 #ifdef WCHAR
2500 else
2501 COMPILED_BUFFER_VAR = (UCHAR_T*) bufp->buffer;
2502 #endif
2504 begalt = b = COMPILED_BUFFER_VAR;
2506 /* Loop through the uncompiled pattern until we're at the end. */
2507 while (p != pend)
2509 PATFETCH (c);
2511 switch (c)
2513 case '^':
2515 if ( /* If at start of pattern, it's an operator. */
2516 p == pattern + 1
2517 /* If context independent, it's an operator. */
2518 || syntax & RE_CONTEXT_INDEP_ANCHORS
2519 /* Otherwise, depends on what's come before. */
2520 || PREFIX(at_begline_loc_p) (pattern, p, syntax))
2521 BUF_PUSH (begline);
2522 else
2523 goto normal_char;
2525 break;
2528 case '$':
2530 if ( /* If at end of pattern, it's an operator. */
2531 p == pend
2532 /* If context independent, it's an operator. */
2533 || syntax & RE_CONTEXT_INDEP_ANCHORS
2534 /* Otherwise, depends on what's next. */
2535 || PREFIX(at_endline_loc_p) (p, pend, syntax))
2536 BUF_PUSH (endline);
2537 else
2538 goto normal_char;
2540 break;
2543 case '+':
2544 case '?':
2545 if ((syntax & RE_BK_PLUS_QM)
2546 || (syntax & RE_LIMITED_OPS))
2547 goto normal_char;
2548 handle_plus:
2549 case '*':
2550 /* If there is no previous pattern... */
2551 if (!laststart)
2553 if (syntax & RE_CONTEXT_INVALID_OPS)
2554 FREE_STACK_RETURN (REG_BADRPT);
2555 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2556 goto normal_char;
2560 /* Are we optimizing this jump? */
2561 boolean keep_string_p = false;
2563 /* 1 means zero (many) matches is allowed. */
2564 char zero_times_ok = 0, many_times_ok = 0;
2566 /* If there is a sequence of repetition chars, collapse it
2567 down to just one (the right one). We can't combine
2568 interval operators with these because of, e.g., `a{2}*',
2569 which should only match an even number of `a's. */
2571 for (;;)
2573 zero_times_ok |= c != '+';
2574 many_times_ok |= c != '?';
2576 if (p == pend)
2577 break;
2579 PATFETCH (c);
2581 if (c == '*'
2582 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2585 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2587 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2589 PATFETCH (c1);
2590 if (!(c1 == '+' || c1 == '?'))
2592 PATUNFETCH;
2593 PATUNFETCH;
2594 break;
2597 c = c1;
2599 else
2601 PATUNFETCH;
2602 break;
2605 /* If we get here, we found another repeat character. */
2608 /* Star, etc. applied to an empty pattern is equivalent
2609 to an empty pattern. */
2610 if (!laststart)
2611 break;
2613 /* Now we know whether or not zero matches is allowed
2614 and also whether or not two or more matches is allowed. */
2615 if (many_times_ok)
2616 { /* More than one repetition is allowed, so put in at the
2617 end a backward relative jump from `b' to before the next
2618 jump we're going to put in below (which jumps from
2619 laststart to after this jump).
2621 But if we are at the `*' in the exact sequence `.*\n',
2622 insert an unconditional jump backwards to the .,
2623 instead of the beginning of the loop. This way we only
2624 push a failure point once, instead of every time
2625 through the loop. */
2626 assert (p - 1 > pattern);
2628 /* Allocate the space for the jump. */
2629 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2631 /* We know we are not at the first character of the pattern,
2632 because laststart was nonzero. And we've already
2633 incremented `p', by the way, to be the character after
2634 the `*'. Do we have to do something analogous here
2635 for null bytes, because of RE_DOT_NOT_NULL? */
2636 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2637 && zero_times_ok
2638 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2639 && !(syntax & RE_DOT_NEWLINE))
2640 { /* We have .*\n. */
2641 STORE_JUMP (jump, b, laststart);
2642 keep_string_p = true;
2644 else
2645 /* Anything else. */
2646 STORE_JUMP (maybe_pop_jump, b, laststart -
2647 (1 + OFFSET_ADDRESS_SIZE));
2649 /* We've added more stuff to the buffer. */
2650 b += 1 + OFFSET_ADDRESS_SIZE;
2653 /* On failure, jump from laststart to b + 3, which will be the
2654 end of the buffer after this jump is inserted. */
2655 /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2656 'b + 3'. */
2657 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2658 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2659 : on_failure_jump,
2660 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2661 pending_exact = 0;
2662 b += 1 + OFFSET_ADDRESS_SIZE;
2664 if (!zero_times_ok)
2666 /* At least one repetition is required, so insert a
2667 `dummy_failure_jump' before the initial
2668 `on_failure_jump' instruction of the loop. This
2669 effects a skip over that instruction the first time
2670 we hit that loop. */
2671 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2672 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2673 2 + 2 * OFFSET_ADDRESS_SIZE);
2674 b += 1 + OFFSET_ADDRESS_SIZE;
2677 break;
2680 case '.':
2681 laststart = b;
2682 BUF_PUSH (anychar);
2683 break;
2686 case '[':
2688 boolean had_char_class = false;
2689 #ifdef WCHAR
2690 CHAR_T range_start = 0xffffffff;
2691 #else
2692 unsigned int range_start = 0xffffffff;
2693 #endif
2694 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2696 #ifdef WCHAR
2697 /* We assume a charset(_not) structure as a wchar_t array.
2698 charset[0] = (re_opcode_t) charset(_not)
2699 charset[1] = l (= length of char_classes)
2700 charset[2] = m (= length of collating_symbols)
2701 charset[3] = n (= length of equivalence_classes)
2702 charset[4] = o (= length of char_ranges)
2703 charset[5] = p (= length of chars)
2705 charset[6] = char_class (wctype_t)
2706 charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2708 charset[l+5] = char_class (wctype_t)
2710 charset[l+6] = collating_symbol (wchar_t)
2712 charset[l+m+5] = collating_symbol (wchar_t)
2713 ifdef _LIBC we use the index if
2714 _NL_COLLATE_SYMB_EXTRAMB instead of
2715 wchar_t string.
2717 charset[l+m+6] = equivalence_classes (wchar_t)
2719 charset[l+m+n+5] = equivalence_classes (wchar_t)
2720 ifdef _LIBC we use the index in
2721 _NL_COLLATE_WEIGHT instead of
2722 wchar_t string.
2724 charset[l+m+n+6] = range_start
2725 charset[l+m+n+7] = range_end
2727 charset[l+m+n+2o+4] = range_start
2728 charset[l+m+n+2o+5] = range_end
2729 ifdef _LIBC we use the value looked up
2730 in _NL_COLLATE_COLLSEQ instead of
2731 wchar_t character.
2733 charset[l+m+n+2o+6] = char
2735 charset[l+m+n+2o+p+5] = char
2739 /* We need at least 6 spaces: the opcode, the length of
2740 char_classes, the length of collating_symbols, the length of
2741 equivalence_classes, the length of char_ranges, the length of
2742 chars. */
2743 GET_BUFFER_SPACE (6);
2745 /* Save b as laststart. And We use laststart as the pointer
2746 to the first element of the charset here.
2747 In other words, laststart[i] indicates charset[i]. */
2748 laststart = b;
2750 /* We test `*p == '^' twice, instead of using an if
2751 statement, so we only need one BUF_PUSH. */
2752 BUF_PUSH (*p == '^' ? charset_not : charset);
2753 if (*p == '^')
2754 p++;
2756 /* Push the length of char_classes, the length of
2757 collating_symbols, the length of equivalence_classes, the
2758 length of char_ranges and the length of chars. */
2759 BUF_PUSH_3 (0, 0, 0);
2760 BUF_PUSH_2 (0, 0);
2762 /* Remember the first position in the bracket expression. */
2763 p1 = p;
2765 /* charset_not matches newline according to a syntax bit. */
2766 if ((re_opcode_t) b[-6] == charset_not
2767 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2769 BUF_PUSH('\n');
2770 laststart[5]++; /* Update the length of characters */
2773 /* Read in characters and ranges, setting map bits. */
2774 for (;;)
2776 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2778 PATFETCH (c);
2780 /* \ might escape characters inside [...] and [^...]. */
2781 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2783 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2785 PATFETCH (c1);
2786 BUF_PUSH(c1);
2787 laststart[5]++; /* Update the length of chars */
2788 range_start = c1;
2789 continue;
2792 /* Could be the end of the bracket expression. If it's
2793 not (i.e., when the bracket expression is `[]' so
2794 far), the ']' character bit gets set way below. */
2795 if (c == ']' && p != p1 + 1)
2796 break;
2798 /* Look ahead to see if it's a range when the last thing
2799 was a character class. */
2800 if (had_char_class && c == '-' && *p != ']')
2801 FREE_STACK_RETURN (REG_ERANGE);
2803 /* Look ahead to see if it's a range when the last thing
2804 was a character: if this is a hyphen not at the
2805 beginning or the end of a list, then it's the range
2806 operator. */
2807 if (c == '-'
2808 && !(p - 2 >= pattern && p[-2] == '[')
2809 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2810 && *p != ']')
2812 reg_errcode_t ret;
2813 /* Allocate the space for range_start and range_end. */
2814 GET_BUFFER_SPACE (2);
2815 /* Update the pointer to indicate end of buffer. */
2816 b += 2;
2817 ret = wcs_compile_range (range_start, &p, pend, translate,
2818 syntax, b, laststart);
2819 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2820 range_start = 0xffffffff;
2822 else if (p[0] == '-' && p[1] != ']')
2823 { /* This handles ranges made up of characters only. */
2824 reg_errcode_t ret;
2826 /* Move past the `-'. */
2827 PATFETCH (c1);
2828 /* Allocate the space for range_start and range_end. */
2829 GET_BUFFER_SPACE (2);
2830 /* Update the pointer to indicate end of buffer. */
2831 b += 2;
2832 ret = wcs_compile_range (c, &p, pend, translate, syntax, b,
2833 laststart);
2834 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2835 range_start = 0xffffffff;
2838 /* See if we're at the beginning of a possible character
2839 class. */
2840 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2841 { /* Leave room for the null. */
2842 char str[CHAR_CLASS_MAX_LENGTH + 1];
2844 PATFETCH (c);
2845 c1 = 0;
2847 /* If pattern is `[[:'. */
2848 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2850 for (;;)
2852 PATFETCH (c);
2853 if ((c == ':' && *p == ']') || p == pend)
2854 break;
2855 if (c1 < CHAR_CLASS_MAX_LENGTH)
2856 str[c1++] = c;
2857 else
2858 /* This is in any case an invalid class name. */
2859 str[0] = '\0';
2861 str[c1] = '\0';
2863 /* If isn't a word bracketed by `[:' and `:]':
2864 undo the ending character, the letters, and leave
2865 the leading `:' and `[' (but store them as character). */
2866 if (c == ':' && *p == ']')
2868 wctype_t wt;
2869 uintptr_t alignedp;
2871 /* Query the character class as wctype_t. */
2872 wt = IS_CHAR_CLASS (str);
2873 if (wt == 0)
2874 FREE_STACK_RETURN (REG_ECTYPE);
2876 /* Throw away the ] at the end of the character
2877 class. */
2878 PATFETCH (c);
2880 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2882 /* Allocate the space for character class. */
2883 GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2884 /* Update the pointer to indicate end of buffer. */
2885 b += CHAR_CLASS_SIZE;
2886 /* Move data which follow character classes
2887 not to violate the data. */
2888 insert_space(CHAR_CLASS_SIZE,
2889 laststart + 6 + laststart[1],
2890 b - 1);
2891 alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2892 + __alignof__(wctype_t) - 1)
2893 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2894 /* Store the character class. */
2895 *((wctype_t*)alignedp) = wt;
2896 /* Update length of char_classes */
2897 laststart[1] += CHAR_CLASS_SIZE;
2899 had_char_class = true;
2901 else
2903 c1++;
2904 while (c1--)
2905 PATUNFETCH;
2906 BUF_PUSH ('[');
2907 BUF_PUSH (':');
2908 laststart[5] += 2; /* Update the length of characters */
2909 range_start = ':';
2910 had_char_class = false;
2913 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2914 || *p == '.'))
2916 CHAR_T str[128]; /* Should be large enough. */
2917 CHAR_T delim = *p; /* '=' or '.' */
2918 # ifdef _LIBC
2919 uint32_t nrules =
2920 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2921 # endif
2922 PATFETCH (c);
2923 c1 = 0;
2925 /* If pattern is `[[=' or '[[.'. */
2926 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2928 for (;;)
2930 PATFETCH (c);
2931 if ((c == delim && *p == ']') || p == pend)
2932 break;
2933 if (c1 < sizeof (str) - 1)
2934 str[c1++] = c;
2935 else
2936 /* This is in any case an invalid class name. */
2937 str[0] = '\0';
2939 str[c1] = '\0';
2941 if (c == delim && *p == ']' && str[0] != '\0')
2943 unsigned int i, offset;
2944 /* If we have no collation data we use the default
2945 collation in which each character is in a class
2946 by itself. It also means that ASCII is the
2947 character set and therefore we cannot have character
2948 with more than one byte in the multibyte
2949 representation. */
2951 /* If not defined _LIBC, we push the name and
2952 `\0' for the sake of matching performance. */
2953 int datasize = c1 + 1;
2955 # ifdef _LIBC
2956 int32_t idx = 0;
2957 if (nrules == 0)
2958 # endif
2960 if (c1 != 1)
2961 FREE_STACK_RETURN (REG_ECOLLATE);
2963 # ifdef _LIBC
2964 else
2966 const int32_t *table;
2967 const int32_t *weights;
2968 const int32_t *extra;
2969 const int32_t *indirect;
2970 wint_t *cp;
2972 /* This #include defines a local function! */
2973 # include <locale/weightwc.h>
2975 if(delim == '=')
2977 /* We push the index for equivalence class. */
2978 cp = (wint_t*)str;
2980 table = (const int32_t *)
2981 _NL_CURRENT (LC_COLLATE,
2982 _NL_COLLATE_TABLEWC);
2983 weights = (const int32_t *)
2984 _NL_CURRENT (LC_COLLATE,
2985 _NL_COLLATE_WEIGHTWC);
2986 extra = (const int32_t *)
2987 _NL_CURRENT (LC_COLLATE,
2988 _NL_COLLATE_EXTRAWC);
2989 indirect = (const int32_t *)
2990 _NL_CURRENT (LC_COLLATE,
2991 _NL_COLLATE_INDIRECTWC);
2993 idx = findidx ((const wint_t**)&cp);
2994 if (idx == 0 || cp < (wint_t*) str + c1)
2995 /* This is no valid character. */
2996 FREE_STACK_RETURN (REG_ECOLLATE);
2998 str[0] = (wchar_t)idx;
3000 else /* delim == '.' */
3002 /* We push collation sequence value
3003 for collating symbol. */
3004 int32_t table_size;
3005 const int32_t *symb_table;
3006 const unsigned char *extra;
3007 int32_t idx;
3008 int32_t elem;
3009 int32_t second;
3010 int32_t hash;
3011 char char_str[c1];
3013 /* We have to convert the name to a single-byte
3014 string. This is possible since the names
3015 consist of ASCII characters and the internal
3016 representation is UCS4. */
3017 for (i = 0; i < c1; ++i)
3018 char_str[i] = str[i];
3020 table_size =
3021 _NL_CURRENT_WORD (LC_COLLATE,
3022 _NL_COLLATE_SYMB_HASH_SIZEMB);
3023 symb_table = (const int32_t *)
3024 _NL_CURRENT (LC_COLLATE,
3025 _NL_COLLATE_SYMB_TABLEMB);
3026 extra = (const unsigned char *)
3027 _NL_CURRENT (LC_COLLATE,
3028 _NL_COLLATE_SYMB_EXTRAMB);
3030 /* Locate the character in the hashing table. */
3031 hash = elem_hash (char_str, c1);
3033 idx = 0;
3034 elem = hash % table_size;
3035 second = hash % (table_size - 2);
3036 while (symb_table[2 * elem] != 0)
3038 /* First compare the hashing value. */
3039 if (symb_table[2 * elem] == hash
3040 && c1 == extra[symb_table[2 * elem + 1]]
3041 && memcmp (str,
3042 &extra[symb_table[2 * elem + 1]
3043 + 1], c1) == 0)
3045 /* Yep, this is the entry. */
3046 idx = symb_table[2 * elem + 1];
3047 idx += 1 + extra[idx];
3048 break;
3051 /* Next entry. */
3052 elem += second;
3055 if (symb_table[2 * elem] != 0)
3057 /* Compute the index of the byte sequence
3058 in the table. */
3059 idx += 1 + extra[idx];
3060 /* Adjust for the alignment. */
3061 idx = (idx + 3) & ~4;
3063 str[0] = (wchar_t) idx + 4;
3065 else if (symb_table[2 * elem] == 0 && c1 == 1)
3067 /* No valid character. Match it as a
3068 single byte character. */
3069 had_char_class = false;
3070 BUF_PUSH(str[0]);
3071 /* Update the length of characters */
3072 laststart[5]++;
3073 range_start = str[0];
3075 /* Throw away the ] at the end of the
3076 collating symbol. */
3077 PATFETCH (c);
3078 /* exit from the switch block. */
3079 continue;
3081 else
3082 FREE_STACK_RETURN (REG_ECOLLATE);
3084 datasize = 1;
3086 # endif
3087 /* Throw away the ] at the end of the equivalence
3088 class (or collating symbol). */
3089 PATFETCH (c);
3091 /* Allocate the space for the equivalence class
3092 (or collating symbol) (and '\0' if needed). */
3093 GET_BUFFER_SPACE(datasize);
3094 /* Update the pointer to indicate end of buffer. */
3095 b += datasize;
3097 if (delim == '=')
3098 { /* equivalence class */
3099 /* Calculate the offset of char_ranges,
3100 which is next to equivalence_classes. */
3101 offset = laststart[1] + laststart[2]
3102 + laststart[3] +6;
3103 /* Insert space. */
3104 insert_space(datasize, laststart + offset, b - 1);
3106 /* Write the equivalence_class and \0. */
3107 for (i = 0 ; i < datasize ; i++)
3108 laststart[offset + i] = str[i];
3110 /* Update the length of equivalence_classes. */
3111 laststart[3] += datasize;
3112 had_char_class = true;
3114 else /* delim == '.' */
3115 { /* collating symbol */
3116 /* Calculate the offset of the equivalence_classes,
3117 which is next to collating_symbols. */
3118 offset = laststart[1] + laststart[2] + 6;
3119 /* Insert space and write the collationg_symbol
3120 and \0. */
3121 insert_space(datasize, laststart + offset, b-1);
3122 for (i = 0 ; i < datasize ; i++)
3123 laststart[offset + i] = str[i];
3125 /* In re_match_2_internal if range_start < -1, we
3126 assume -range_start is the offset of the
3127 collating symbol which is specified as
3128 the character of the range start. So we assign
3129 -(laststart[1] + laststart[2] + 6) to
3130 range_start. */
3131 range_start = -(laststart[1] + laststart[2] + 6);
3132 /* Update the length of collating_symbol. */
3133 laststart[2] += datasize;
3134 had_char_class = false;
3137 else
3139 c1++;
3140 while (c1--)
3141 PATUNFETCH;
3142 BUF_PUSH ('[');
3143 BUF_PUSH (delim);
3144 laststart[5] += 2; /* Update the length of characters */
3145 range_start = delim;
3146 had_char_class = false;
3149 else
3151 had_char_class = false;
3152 BUF_PUSH(c);
3153 laststart[5]++; /* Update the length of characters */
3154 range_start = c;
3158 #else /* BYTE */
3159 /* Ensure that we have enough space to push a charset: the
3160 opcode, the length count, and the bitset; 34 bytes in all. */
3161 GET_BUFFER_SPACE (34);
3163 laststart = b;
3165 /* We test `*p == '^' twice, instead of using an if
3166 statement, so we only need one BUF_PUSH. */
3167 BUF_PUSH (*p == '^' ? charset_not : charset);
3168 if (*p == '^')
3169 p++;
3171 /* Remember the first position in the bracket expression. */
3172 p1 = p;
3174 /* Push the number of bytes in the bitmap. */
3175 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3177 /* Clear the whole map. */
3178 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3180 /* charset_not matches newline according to a syntax bit. */
3181 if ((re_opcode_t) b[-2] == charset_not
3182 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3183 SET_LIST_BIT ('\n');
3185 /* Read in characters and ranges, setting map bits. */
3186 for (;;)
3188 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3190 PATFETCH (c);
3192 /* \ might escape characters inside [...] and [^...]. */
3193 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3195 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3197 PATFETCH (c1);
3198 SET_LIST_BIT (c1);
3199 range_start = c1;
3200 continue;
3203 /* Could be the end of the bracket expression. If it's
3204 not (i.e., when the bracket expression is `[]' so
3205 far), the ']' character bit gets set way below. */
3206 if (c == ']' && p != p1 + 1)
3207 break;
3209 /* Look ahead to see if it's a range when the last thing
3210 was a character class. */
3211 if (had_char_class && c == '-' && *p != ']')
3212 FREE_STACK_RETURN (REG_ERANGE);
3214 /* Look ahead to see if it's a range when the last thing
3215 was a character: if this is a hyphen not at the
3216 beginning or the end of a list, then it's the range
3217 operator. */
3218 if (c == '-'
3219 && !(p - 2 >= pattern && p[-2] == '[')
3220 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3221 && *p != ']')
3223 reg_errcode_t ret
3224 = byte_compile_range (range_start, &p, pend, translate,
3225 syntax, b);
3226 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3227 range_start = 0xffffffff;
3230 else if (p[0] == '-' && p[1] != ']')
3231 { /* This handles ranges made up of characters only. */
3232 reg_errcode_t ret;
3234 /* Move past the `-'. */
3235 PATFETCH (c1);
3237 ret = byte_compile_range (c, &p, pend, translate, syntax, b);
3238 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3239 range_start = 0xffffffff;
3242 /* See if we're at the beginning of a possible character
3243 class. */
3245 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3246 { /* Leave room for the null. */
3247 char str[CHAR_CLASS_MAX_LENGTH + 1];
3249 PATFETCH (c);
3250 c1 = 0;
3252 /* If pattern is `[[:'. */
3253 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3255 for (;;)
3257 PATFETCH (c);
3258 if ((c == ':' && *p == ']') || p == pend)
3259 break;
3260 if (c1 < CHAR_CLASS_MAX_LENGTH)
3261 str[c1++] = c;
3262 else
3263 /* This is in any case an invalid class name. */
3264 str[0] = '\0';
3266 str[c1] = '\0';
3268 /* If isn't a word bracketed by `[:' and `:]':
3269 undo the ending character, the letters, and leave
3270 the leading `:' and `[' (but set bits for them). */
3271 if (c == ':' && *p == ']')
3273 # if defined _LIBC || WIDE_CHAR_SUPPORT
3274 boolean is_lower = STREQ (str, "lower");
3275 boolean is_upper = STREQ (str, "upper");
3276 wctype_t wt;
3277 int ch;
3279 wt = IS_CHAR_CLASS (str);
3280 if (wt == 0)
3281 FREE_STACK_RETURN (REG_ECTYPE);
3283 /* Throw away the ] at the end of the character
3284 class. */
3285 PATFETCH (c);
3287 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3289 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3291 # ifdef _LIBC
3292 if (__iswctype (__btowc (ch), wt))
3293 SET_LIST_BIT (ch);
3294 # else
3295 if (iswctype (btowc (ch), wt))
3296 SET_LIST_BIT (ch);
3297 # endif
3299 if (translate && (is_upper || is_lower)
3300 && (ISUPPER (ch) || ISLOWER (ch)))
3301 SET_LIST_BIT (ch);
3304 had_char_class = true;
3305 # else
3306 int ch;
3307 boolean is_alnum = STREQ (str, "alnum");
3308 boolean is_alpha = STREQ (str, "alpha");
3309 boolean is_blank = STREQ (str, "blank");
3310 boolean is_cntrl = STREQ (str, "cntrl");
3311 boolean is_digit = STREQ (str, "digit");
3312 boolean is_graph = STREQ (str, "graph");
3313 boolean is_lower = STREQ (str, "lower");
3314 boolean is_print = STREQ (str, "print");
3315 boolean is_punct = STREQ (str, "punct");
3316 boolean is_space = STREQ (str, "space");
3317 boolean is_upper = STREQ (str, "upper");
3318 boolean is_xdigit = STREQ (str, "xdigit");
3320 if (!IS_CHAR_CLASS (str))
3321 FREE_STACK_RETURN (REG_ECTYPE);
3323 /* Throw away the ] at the end of the character
3324 class. */
3325 PATFETCH (c);
3327 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3329 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3331 /* This was split into 3 if's to
3332 avoid an arbitrary limit in some compiler. */
3333 if ( (is_alnum && ISALNUM (ch))
3334 || (is_alpha && ISALPHA (ch))
3335 || (is_blank && ISBLANK (ch))
3336 || (is_cntrl && ISCNTRL (ch)))
3337 SET_LIST_BIT (ch);
3338 if ( (is_digit && ISDIGIT (ch))
3339 || (is_graph && ISGRAPH (ch))
3340 || (is_lower && ISLOWER (ch))
3341 || (is_print && ISPRINT (ch)))
3342 SET_LIST_BIT (ch);
3343 if ( (is_punct && ISPUNCT (ch))
3344 || (is_space && ISSPACE (ch))
3345 || (is_upper && ISUPPER (ch))
3346 || (is_xdigit && ISXDIGIT (ch)))
3347 SET_LIST_BIT (ch);
3348 if ( translate && (is_upper || is_lower)
3349 && (ISUPPER (ch) || ISLOWER (ch)))
3350 SET_LIST_BIT (ch);
3352 had_char_class = true;
3353 # endif /* libc || wctype.h */
3355 else
3357 c1++;
3358 while (c1--)
3359 PATUNFETCH;
3360 SET_LIST_BIT ('[');
3361 SET_LIST_BIT (':');
3362 range_start = ':';
3363 had_char_class = false;
3366 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3368 unsigned char str[MB_LEN_MAX + 1];
3369 # ifdef _LIBC
3370 uint32_t nrules =
3371 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3372 # endif
3374 PATFETCH (c);
3375 c1 = 0;
3377 /* If pattern is `[[='. */
3378 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3380 for (;;)
3382 PATFETCH (c);
3383 if ((c == '=' && *p == ']') || p == pend)
3384 break;
3385 if (c1 < MB_LEN_MAX)
3386 str[c1++] = c;
3387 else
3388 /* This is in any case an invalid class name. */
3389 str[0] = '\0';
3391 str[c1] = '\0';
3393 if (c == '=' && *p == ']' && str[0] != '\0')
3395 /* If we have no collation data we use the default
3396 collation in which each character is in a class
3397 by itself. It also means that ASCII is the
3398 character set and therefore we cannot have character
3399 with more than one byte in the multibyte
3400 representation. */
3401 # ifdef _LIBC
3402 if (nrules == 0)
3403 # endif
3405 if (c1 != 1)
3406 FREE_STACK_RETURN (REG_ECOLLATE);
3408 /* Throw away the ] at the end of the equivalence
3409 class. */
3410 PATFETCH (c);
3412 /* Set the bit for the character. */
3413 SET_LIST_BIT (str[0]);
3415 # ifdef _LIBC
3416 else
3418 /* Try to match the byte sequence in `str' against
3419 those known to the collate implementation.
3420 First find out whether the bytes in `str' are
3421 actually from exactly one character. */
3422 const int32_t *table;
3423 const unsigned char *weights;
3424 const unsigned char *extra;
3425 const int32_t *indirect;
3426 int32_t idx;
3427 const unsigned char *cp = str;
3428 int ch;
3430 /* This #include defines a local function! */
3431 # include <locale/weight.h>
3433 table = (const int32_t *)
3434 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3435 weights = (const unsigned char *)
3436 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3437 extra = (const unsigned char *)
3438 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3439 indirect = (const int32_t *)
3440 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3442 idx = findidx (&cp);
3443 if (idx == 0 || cp < str + c1)
3444 /* This is no valid character. */
3445 FREE_STACK_RETURN (REG_ECOLLATE);
3447 /* Throw away the ] at the end of the equivalence
3448 class. */
3449 PATFETCH (c);
3451 /* Now we have to go throught the whole table
3452 and find all characters which have the same
3453 first level weight.
3455 XXX Note that this is not entirely correct.
3456 we would have to match multibyte sequences
3457 but this is not possible with the current
3458 implementation. */
3459 for (ch = 1; ch < 256; ++ch)
3460 /* XXX This test would have to be changed if we
3461 would allow matching multibyte sequences. */
3462 if (table[ch] > 0)
3464 int32_t idx2 = table[ch];
3465 size_t len = weights[idx2];
3467 /* Test whether the lenghts match. */
3468 if (weights[idx] == len)
3470 /* They do. New compare the bytes of
3471 the weight. */
3472 size_t cnt = 0;
3474 while (cnt < len
3475 && (weights[idx + 1 + cnt]
3476 == weights[idx2 + 1 + cnt]))
3477 ++cnt;
3479 if (cnt == len)
3480 /* They match. Mark the character as
3481 acceptable. */
3482 SET_LIST_BIT (ch);
3486 # endif
3487 had_char_class = true;
3489 else
3491 c1++;
3492 while (c1--)
3493 PATUNFETCH;
3494 SET_LIST_BIT ('[');
3495 SET_LIST_BIT ('=');
3496 range_start = '=';
3497 had_char_class = false;
3500 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3502 unsigned char str[128]; /* Should be large enough. */
3503 # ifdef _LIBC
3504 uint32_t nrules =
3505 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3506 # endif
3508 PATFETCH (c);
3509 c1 = 0;
3511 /* If pattern is `[[.'. */
3512 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3514 for (;;)
3516 PATFETCH (c);
3517 if ((c == '.' && *p == ']') || p == pend)
3518 break;
3519 if (c1 < sizeof (str))
3520 str[c1++] = c;
3521 else
3522 /* This is in any case an invalid class name. */
3523 str[0] = '\0';
3525 str[c1] = '\0';
3527 if (c == '.' && *p == ']' && str[0] != '\0')
3529 /* If we have no collation data we use the default
3530 collation in which each character is the name
3531 for its own class which contains only the one
3532 character. It also means that ASCII is the
3533 character set and therefore we cannot have character
3534 with more than one byte in the multibyte
3535 representation. */
3536 # ifdef _LIBC
3537 if (nrules == 0)
3538 # endif
3540 if (c1 != 1)
3541 FREE_STACK_RETURN (REG_ECOLLATE);
3543 /* Throw away the ] at the end of the equivalence
3544 class. */
3545 PATFETCH (c);
3547 /* Set the bit for the character. */
3548 SET_LIST_BIT (str[0]);
3549 range_start = ((const unsigned char *) str)[0];
3551 # ifdef _LIBC
3552 else
3554 /* Try to match the byte sequence in `str' against
3555 those known to the collate implementation.
3556 First find out whether the bytes in `str' are
3557 actually from exactly one character. */
3558 int32_t table_size;
3559 const int32_t *symb_table;
3560 const unsigned char *extra;
3561 int32_t idx;
3562 int32_t elem;
3563 int32_t second;
3564 int32_t hash;
3566 table_size =
3567 _NL_CURRENT_WORD (LC_COLLATE,
3568 _NL_COLLATE_SYMB_HASH_SIZEMB);
3569 symb_table = (const int32_t *)
3570 _NL_CURRENT (LC_COLLATE,
3571 _NL_COLLATE_SYMB_TABLEMB);
3572 extra = (const unsigned char *)
3573 _NL_CURRENT (LC_COLLATE,
3574 _NL_COLLATE_SYMB_EXTRAMB);
3576 /* Locate the character in the hashing table. */
3577 hash = elem_hash (str, c1);
3579 idx = 0;
3580 elem = hash % table_size;
3581 second = hash % (table_size - 2);
3582 while (symb_table[2 * elem] != 0)
3584 /* First compare the hashing value. */
3585 if (symb_table[2 * elem] == hash
3586 && c1 == extra[symb_table[2 * elem + 1]]
3587 && memcmp (str,
3588 &extra[symb_table[2 * elem + 1]
3589 + 1],
3590 c1) == 0)
3592 /* Yep, this is the entry. */
3593 idx = symb_table[2 * elem + 1];
3594 idx += 1 + extra[idx];
3595 break;
3598 /* Next entry. */
3599 elem += second;
3602 if (symb_table[2 * elem] == 0)
3603 /* This is no valid character. */
3604 FREE_STACK_RETURN (REG_ECOLLATE);
3606 /* Throw away the ] at the end of the equivalence
3607 class. */
3608 PATFETCH (c);
3610 /* Now add the multibyte character(s) we found
3611 to the accept list.
3613 XXX Note that this is not entirely correct.
3614 we would have to match multibyte sequences
3615 but this is not possible with the current
3616 implementation. Also, we have to match
3617 collating symbols, which expand to more than
3618 one file, as a whole and not allow the
3619 individual bytes. */
3620 c1 = extra[idx++];
3621 if (c1 == 1)
3622 range_start = extra[idx];
3623 while (c1-- > 0)
3625 SET_LIST_BIT (extra[idx]);
3626 ++idx;
3629 # endif
3630 had_char_class = false;
3632 else
3634 c1++;
3635 while (c1--)
3636 PATUNFETCH;
3637 SET_LIST_BIT ('[');
3638 SET_LIST_BIT ('.');
3639 range_start = '.';
3640 had_char_class = false;
3643 else
3645 had_char_class = false;
3646 SET_LIST_BIT (c);
3647 range_start = c;
3651 /* Discard any (non)matching list bytes that are all 0 at the
3652 end of the map. Decrease the map-length byte too. */
3653 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3654 b[-1]--;
3655 b += b[-1];
3656 #endif /* WCHAR */
3658 break;
3661 case '(':
3662 if (syntax & RE_NO_BK_PARENS)
3663 goto handle_open;
3664 else
3665 goto normal_char;
3668 case ')':
3669 if (syntax & RE_NO_BK_PARENS)
3670 goto handle_close;
3671 else
3672 goto normal_char;
3675 case '\n':
3676 if (syntax & RE_NEWLINE_ALT)
3677 goto handle_alt;
3678 else
3679 goto normal_char;
3682 case '|':
3683 if (syntax & RE_NO_BK_VBAR)
3684 goto handle_alt;
3685 else
3686 goto normal_char;
3689 case '{':
3690 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3691 goto handle_interval;
3692 else
3693 goto normal_char;
3696 case '\\':
3697 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3699 /* Do not translate the character after the \, so that we can
3700 distinguish, e.g., \B from \b, even if we normally would
3701 translate, e.g., B to b. */
3702 PATFETCH_RAW (c);
3704 switch (c)
3706 case '(':
3707 if (syntax & RE_NO_BK_PARENS)
3708 goto normal_backslash;
3710 handle_open:
3711 bufp->re_nsub++;
3712 regnum++;
3714 if (COMPILE_STACK_FULL)
3716 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3717 compile_stack_elt_t);
3718 if (compile_stack.stack == NULL) return REG_ESPACE;
3720 compile_stack.size <<= 1;
3723 /* These are the values to restore when we hit end of this
3724 group. They are all relative offsets, so that if the
3725 whole pattern moves because of realloc, they will still
3726 be valid. */
3727 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3728 COMPILE_STACK_TOP.fixup_alt_jump
3729 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3730 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3731 COMPILE_STACK_TOP.regnum = regnum;
3733 /* We will eventually replace the 0 with the number of
3734 groups inner to this one. But do not push a
3735 start_memory for groups beyond the last one we can
3736 represent in the compiled pattern. */
3737 if (regnum <= MAX_REGNUM)
3739 COMPILE_STACK_TOP.inner_group_offset = b
3740 - COMPILED_BUFFER_VAR + 2;
3741 BUF_PUSH_3 (start_memory, regnum, 0);
3744 compile_stack.avail++;
3746 fixup_alt_jump = 0;
3747 laststart = 0;
3748 begalt = b;
3749 /* If we've reached MAX_REGNUM groups, then this open
3750 won't actually generate any code, so we'll have to
3751 clear pending_exact explicitly. */
3752 pending_exact = 0;
3753 break;
3756 case ')':
3757 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3759 if (COMPILE_STACK_EMPTY)
3761 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3762 goto normal_backslash;
3763 else
3764 FREE_STACK_RETURN (REG_ERPAREN);
3767 handle_close:
3768 if (fixup_alt_jump)
3769 { /* Push a dummy failure point at the end of the
3770 alternative for a possible future
3771 `pop_failure_jump' to pop. See comments at
3772 `push_dummy_failure' in `re_match_2'. */
3773 BUF_PUSH (push_dummy_failure);
3775 /* We allocated space for this jump when we assigned
3776 to `fixup_alt_jump', in the `handle_alt' case below. */
3777 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3780 /* See similar code for backslashed left paren above. */
3781 if (COMPILE_STACK_EMPTY)
3783 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3784 goto normal_char;
3785 else
3786 FREE_STACK_RETURN (REG_ERPAREN);
3789 /* Since we just checked for an empty stack above, this
3790 ``can't happen''. */
3791 assert (compile_stack.avail != 0);
3793 /* We don't just want to restore into `regnum', because
3794 later groups should continue to be numbered higher,
3795 as in `(ab)c(de)' -- the second group is #2. */
3796 regnum_t this_group_regnum;
3798 compile_stack.avail--;
3799 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3800 fixup_alt_jump
3801 = COMPILE_STACK_TOP.fixup_alt_jump
3802 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3803 : 0;
3804 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3805 this_group_regnum = COMPILE_STACK_TOP.regnum;
3806 /* If we've reached MAX_REGNUM groups, then this open
3807 won't actually generate any code, so we'll have to
3808 clear pending_exact explicitly. */
3809 pending_exact = 0;
3811 /* We're at the end of the group, so now we know how many
3812 groups were inside this one. */
3813 if (this_group_regnum <= MAX_REGNUM)
3815 UCHAR_T *inner_group_loc
3816 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3818 *inner_group_loc = regnum - this_group_regnum;
3819 BUF_PUSH_3 (stop_memory, this_group_regnum,
3820 regnum - this_group_regnum);
3823 break;
3826 case '|': /* `\|'. */
3827 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3828 goto normal_backslash;
3829 handle_alt:
3830 if (syntax & RE_LIMITED_OPS)
3831 goto normal_char;
3833 /* Insert before the previous alternative a jump which
3834 jumps to this alternative if the former fails. */
3835 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3836 INSERT_JUMP (on_failure_jump, begalt,
3837 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3838 pending_exact = 0;
3839 b += 1 + OFFSET_ADDRESS_SIZE;
3841 /* The alternative before this one has a jump after it
3842 which gets executed if it gets matched. Adjust that
3843 jump so it will jump to this alternative's analogous
3844 jump (put in below, which in turn will jump to the next
3845 (if any) alternative's such jump, etc.). The last such
3846 jump jumps to the correct final destination. A picture:
3847 _____ _____
3848 | | | |
3849 | v | v
3850 a | b | c
3852 If we are at `b', then fixup_alt_jump right now points to a
3853 three-byte space after `a'. We'll put in the jump, set
3854 fixup_alt_jump to right after `b', and leave behind three
3855 bytes which we'll fill in when we get to after `c'. */
3857 if (fixup_alt_jump)
3858 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3860 /* Mark and leave space for a jump after this alternative,
3861 to be filled in later either by next alternative or
3862 when know we're at the end of a series of alternatives. */
3863 fixup_alt_jump = b;
3864 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3865 b += 1 + OFFSET_ADDRESS_SIZE;
3867 laststart = 0;
3868 begalt = b;
3869 break;
3872 case '{':
3873 /* If \{ is a literal. */
3874 if (!(syntax & RE_INTERVALS)
3875 /* If we're at `\{' and it's not the open-interval
3876 operator. */
3877 || (syntax & RE_NO_BK_BRACES))
3878 goto normal_backslash;
3880 handle_interval:
3882 /* If got here, then the syntax allows intervals. */
3884 /* At least (most) this many matches must be made. */
3885 int lower_bound = -1, upper_bound = -1;
3887 /* Place in the uncompiled pattern (i.e., just after
3888 the '{') to go back to if the interval is invalid. */
3889 const CHAR_T *beg_interval = p;
3891 if (p == pend)
3892 goto invalid_interval;
3894 GET_UNSIGNED_NUMBER (lower_bound);
3896 if (c == ',')
3898 GET_UNSIGNED_NUMBER (upper_bound);
3899 if (upper_bound < 0)
3900 upper_bound = RE_DUP_MAX;
3902 else
3903 /* Interval such as `{1}' => match exactly once. */
3904 upper_bound = lower_bound;
3906 if (! (0 <= lower_bound && lower_bound <= upper_bound))
3907 goto invalid_interval;
3909 if (!(syntax & RE_NO_BK_BRACES))
3911 if (c != '\\' || p == pend)
3912 goto invalid_interval;
3913 PATFETCH (c);
3916 if (c != '}')
3917 goto invalid_interval;
3919 /* If it's invalid to have no preceding re. */
3920 if (!laststart)
3922 if (syntax & RE_CONTEXT_INVALID_OPS
3923 && !(syntax & RE_INVALID_INTERVAL_ORD))
3924 FREE_STACK_RETURN (REG_BADRPT);
3925 else if (syntax & RE_CONTEXT_INDEP_OPS)
3926 laststart = b;
3927 else
3928 goto unfetch_interval;
3931 /* We just parsed a valid interval. */
3933 if (RE_DUP_MAX < upper_bound)
3934 FREE_STACK_RETURN (REG_BADBR);
3936 /* If the upper bound is zero, don't want to succeed at
3937 all; jump from `laststart' to `b + 3', which will be
3938 the end of the buffer after we insert the jump. */
3939 /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE'
3940 instead of 'b + 3'. */
3941 if (upper_bound == 0)
3943 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3944 INSERT_JUMP (jump, laststart, b + 1
3945 + OFFSET_ADDRESS_SIZE);
3946 b += 1 + OFFSET_ADDRESS_SIZE;
3949 /* Otherwise, we have a nontrivial interval. When
3950 we're all done, the pattern will look like:
3951 set_number_at <jump count> <upper bound>
3952 set_number_at <succeed_n count> <lower bound>
3953 succeed_n <after jump addr> <succeed_n count>
3954 <body of loop>
3955 jump_n <succeed_n addr> <jump count>
3956 (The upper bound and `jump_n' are omitted if
3957 `upper_bound' is 1, though.) */
3958 else
3959 { /* If the upper bound is > 1, we need to insert
3960 more at the end of the loop. */
3961 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3962 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3964 GET_BUFFER_SPACE (nbytes);
3966 /* Initialize lower bound of the `succeed_n', even
3967 though it will be set during matching by its
3968 attendant `set_number_at' (inserted next),
3969 because `re_compile_fastmap' needs to know.
3970 Jump to the `jump_n' we might insert below. */
3971 INSERT_JUMP2 (succeed_n, laststart,
3972 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3973 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3974 , lower_bound);
3975 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3977 /* Code to initialize the lower bound. Insert
3978 before the `succeed_n'. The `5' is the last two
3979 bytes of this `set_number_at', plus 3 bytes of
3980 the following `succeed_n'. */
3981 /* ifdef WCHAR, The '1+2*OFFSET_ADDRESS_SIZE'
3982 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3983 of the following `succeed_n'. */
3984 PREFIX(insert_op2) (set_number_at, laststart, 1
3985 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3986 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3988 if (upper_bound > 1)
3989 { /* More than one repetition is allowed, so
3990 append a backward jump to the `succeed_n'
3991 that starts this interval.
3993 When we've reached this during matching,
3994 we'll have matched the interval once, so
3995 jump back only `upper_bound - 1' times. */
3996 STORE_JUMP2 (jump_n, b, laststart
3997 + 2 * OFFSET_ADDRESS_SIZE + 1,
3998 upper_bound - 1);
3999 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
4001 /* The location we want to set is the second
4002 parameter of the `jump_n'; that is `b-2' as
4003 an absolute address. `laststart' will be
4004 the `set_number_at' we're about to insert;
4005 `laststart+3' the number to set, the source
4006 for the relative address. But we are
4007 inserting into the middle of the pattern --
4008 so everything is getting moved up by 5.
4009 Conclusion: (b - 2) - (laststart + 3) + 5,
4010 i.e., b - laststart.
4012 We insert this at the beginning of the loop
4013 so that if we fail during matching, we'll
4014 reinitialize the bounds. */
4015 PREFIX(insert_op2) (set_number_at, laststart,
4016 b - laststart,
4017 upper_bound - 1, b);
4018 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
4021 pending_exact = 0;
4022 break;
4024 invalid_interval:
4025 if (!(syntax & RE_INVALID_INTERVAL_ORD))
4026 FREE_STACK_RETURN (p == pend ? REG_EBRACE : REG_BADBR);
4027 unfetch_interval:
4028 /* Match the characters as literals. */
4029 p = beg_interval;
4030 c = '{';
4031 if (syntax & RE_NO_BK_BRACES)
4032 goto normal_char;
4033 else
4034 goto normal_backslash;
4037 #ifdef emacs
4038 /* There is no way to specify the before_dot and after_dot
4039 operators. rms says this is ok. --karl */
4040 case '=':
4041 BUF_PUSH (at_dot);
4042 break;
4044 case 's':
4045 laststart = b;
4046 PATFETCH (c);
4047 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
4048 break;
4050 case 'S':
4051 laststart = b;
4052 PATFETCH (c);
4053 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
4054 break;
4055 #endif /* emacs */
4058 case 'w':
4059 if (syntax & RE_NO_GNU_OPS)
4060 goto normal_char;
4061 laststart = b;
4062 BUF_PUSH (wordchar);
4063 break;
4066 case 'W':
4067 if (syntax & RE_NO_GNU_OPS)
4068 goto normal_char;
4069 laststart = b;
4070 BUF_PUSH (notwordchar);
4071 break;
4074 case '<':
4075 if (syntax & RE_NO_GNU_OPS)
4076 goto normal_char;
4077 BUF_PUSH (wordbeg);
4078 break;
4080 case '>':
4081 if (syntax & RE_NO_GNU_OPS)
4082 goto normal_char;
4083 BUF_PUSH (wordend);
4084 break;
4086 case 'b':
4087 if (syntax & RE_NO_GNU_OPS)
4088 goto normal_char;
4089 BUF_PUSH (wordbound);
4090 break;
4092 case 'B':
4093 if (syntax & RE_NO_GNU_OPS)
4094 goto normal_char;
4095 BUF_PUSH (notwordbound);
4096 break;
4098 case '`':
4099 if (syntax & RE_NO_GNU_OPS)
4100 goto normal_char;
4101 BUF_PUSH (begbuf);
4102 break;
4104 case '\'':
4105 if (syntax & RE_NO_GNU_OPS)
4106 goto normal_char;
4107 BUF_PUSH (endbuf);
4108 break;
4110 case '1': case '2': case '3': case '4': case '5':
4111 case '6': case '7': case '8': case '9':
4112 if (syntax & RE_NO_BK_REFS)
4113 goto normal_char;
4115 c1 = c - '0';
4117 if (c1 > regnum)
4118 FREE_STACK_RETURN (REG_ESUBREG);
4120 /* Can't back reference to a subexpression if inside of it. */
4121 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4122 goto normal_char;
4124 laststart = b;
4125 BUF_PUSH_2 (duplicate, c1);
4126 break;
4129 case '+':
4130 case '?':
4131 if (syntax & RE_BK_PLUS_QM)
4132 goto handle_plus;
4133 else
4134 goto normal_backslash;
4136 default:
4137 normal_backslash:
4138 /* You might think it would be useful for \ to mean
4139 not to translate; but if we don't translate it
4140 it will never match anything. */
4141 c = TRANSLATE (c);
4142 goto normal_char;
4144 break;
4147 default:
4148 /* Expects the character in `c'. */
4149 normal_char:
4150 /* If no exactn currently being built. */
4151 if (!pending_exact
4152 #ifdef WCHAR
4153 /* If last exactn handle binary(or character) and
4154 new exactn handle character(or binary). */
4155 || is_exactn_bin != is_binary[p - 1 - pattern]
4156 #endif /* WCHAR */
4158 /* If last exactn not at current position. */
4159 || pending_exact + *pending_exact + 1 != b
4161 /* We have only one byte following the exactn for the count. */
4162 || *pending_exact == (1 << BYTEWIDTH) - 1
4164 /* If followed by a repetition operator. */
4165 || *p == '*' || *p == '^'
4166 || ((syntax & RE_BK_PLUS_QM)
4167 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4168 : (*p == '+' || *p == '?'))
4169 || ((syntax & RE_INTERVALS)
4170 && ((syntax & RE_NO_BK_BRACES)
4171 ? *p == '{'
4172 : (p[0] == '\\' && p[1] == '{'))))
4174 /* Start building a new exactn. */
4176 laststart = b;
4178 #ifdef WCHAR
4179 /* Is this exactn binary data or character? */
4180 is_exactn_bin = is_binary[p - 1 - pattern];
4181 if (is_exactn_bin)
4182 BUF_PUSH_2 (exactn_bin, 0);
4183 else
4184 BUF_PUSH_2 (exactn, 0);
4185 #else
4186 BUF_PUSH_2 (exactn, 0);
4187 #endif /* WCHAR */
4188 pending_exact = b - 1;
4191 BUF_PUSH (c);
4192 (*pending_exact)++;
4193 break;
4194 } /* switch (c) */
4195 } /* while p != pend */
4198 /* Through the pattern now. */
4200 if (fixup_alt_jump)
4201 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4203 if (!COMPILE_STACK_EMPTY)
4204 FREE_STACK_RETURN (REG_EPAREN);
4206 /* If we don't want backtracking, force success
4207 the first time we reach the end of the compiled pattern. */
4208 if (syntax & RE_NO_POSIX_BACKTRACKING)
4209 BUF_PUSH (succeed);
4211 #ifdef WCHAR
4212 free (pattern);
4213 free (mbs_offset);
4214 free (is_binary);
4215 #endif
4216 free (compile_stack.stack);
4218 /* We have succeeded; set the length of the buffer. */
4219 #ifdef WCHAR
4220 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4221 #else
4222 bufp->used = b - bufp->buffer;
4223 #endif
4225 #ifdef DEBUG
4226 if (debug)
4228 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4229 PREFIX(print_compiled_pattern) (bufp);
4231 #endif /* DEBUG */
4233 #ifndef MATCH_MAY_ALLOCATE
4234 /* Initialize the failure stack to the largest possible stack. This
4235 isn't necessary unless we're trying to avoid calling alloca in
4236 the search and match routines. */
4238 int num_regs = bufp->re_nsub + 1;
4240 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4241 is strictly greater than re_max_failures, the largest possible stack
4242 is 2 * re_max_failures failure points. */
4243 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4245 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4247 # ifdef emacs
4248 if (! fail_stack.stack)
4249 fail_stack.stack
4250 = (PREFIX(fail_stack_elt_t) *) xmalloc (fail_stack.size
4251 * sizeof (PREFIX(fail_stack_elt_t)));
4252 else
4253 fail_stack.stack
4254 = (PREFIX(fail_stack_elt_t) *) xrealloc (fail_stack.stack,
4255 (fail_stack.size
4256 * sizeof (PREFIX(fail_stack_elt_t))));
4257 # else /* not emacs */
4258 if (! fail_stack.stack)
4259 fail_stack.stack
4260 = (PREFIX(fail_stack_elt_t) *) malloc (fail_stack.size
4261 * sizeof (PREFIX(fail_stack_elt_t)));
4262 else
4263 fail_stack.stack
4264 = (PREFIX(fail_stack_elt_t) *) realloc (fail_stack.stack,
4265 (fail_stack.size
4266 * sizeof (PREFIX(fail_stack_elt_t))));
4267 # endif /* not emacs */
4270 PREFIX(regex_grow_registers) (num_regs);
4272 #endif /* not MATCH_MAY_ALLOCATE */
4274 return REG_NOERROR;
4275 } /* regex_compile */
4277 /* Subroutines for `regex_compile'. */
4279 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4280 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4282 static void
4283 PREFIX(store_op1) (op, loc, arg)
4284 re_opcode_t op;
4285 UCHAR_T *loc;
4286 int arg;
4288 *loc = (UCHAR_T) op;
4289 STORE_NUMBER (loc + 1, arg);
4293 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4294 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4296 static void
4297 PREFIX(store_op2) (op, loc, arg1, arg2)
4298 re_opcode_t op;
4299 UCHAR_T *loc;
4300 int arg1, arg2;
4302 *loc = (UCHAR_T) op;
4303 STORE_NUMBER (loc + 1, arg1);
4304 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4308 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4309 for OP followed by two-byte integer parameter ARG. */
4310 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4312 static void
4313 PREFIX(insert_op1) (op, loc, arg, end)
4314 re_opcode_t op;
4315 UCHAR_T *loc;
4316 int arg;
4317 UCHAR_T *end;
4319 register UCHAR_T *pfrom = end;
4320 register UCHAR_T *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4322 while (pfrom != loc)
4323 *--pto = *--pfrom;
4325 PREFIX(store_op1) (op, loc, arg);
4329 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4330 /* ifdef WCHAR, integer parameter is 1 wchar_t. */
4332 static void
4333 PREFIX(insert_op2) (op, loc, arg1, arg2, end)
4334 re_opcode_t op;
4335 UCHAR_T *loc;
4336 int arg1, arg2;
4337 UCHAR_T *end;
4339 register UCHAR_T *pfrom = end;
4340 register UCHAR_T *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4342 while (pfrom != loc)
4343 *--pto = *--pfrom;
4345 PREFIX(store_op2) (op, loc, arg1, arg2);
4349 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4350 after an alternative or a begin-subexpression. We assume there is at
4351 least one character before the ^. */
4353 static boolean
4354 PREFIX(at_begline_loc_p) (pattern, p, syntax)
4355 const CHAR_T *pattern, *p;
4356 reg_syntax_t syntax;
4358 const CHAR_T *prev = p - 2;
4359 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4361 return
4362 /* After a subexpression? */
4363 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4364 /* After an alternative? */
4365 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4369 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4370 at least one character after the $, i.e., `P < PEND'. */
4372 static boolean
4373 PREFIX(at_endline_loc_p) (p, pend, syntax)
4374 const CHAR_T *p, *pend;
4375 reg_syntax_t syntax;
4377 const CHAR_T *next = p;
4378 boolean next_backslash = *next == '\\';
4379 const CHAR_T *next_next = p + 1 < pend ? p + 1 : 0;
4381 return
4382 /* Before a subexpression? */
4383 (syntax & RE_NO_BK_PARENS ? *next == ')'
4384 : next_backslash && next_next && *next_next == ')')
4385 /* Before an alternative? */
4386 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4387 : next_backslash && next_next && *next_next == '|');
4390 #else /* not INSIDE_RECURSION */
4392 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4393 false if it's not. */
4395 static boolean
4396 group_in_compile_stack (compile_stack, regnum)
4397 compile_stack_type compile_stack;
4398 regnum_t regnum;
4400 int this_element;
4402 for (this_element = compile_stack.avail - 1;
4403 this_element >= 0;
4404 this_element--)
4405 if (compile_stack.stack[this_element].regnum == regnum)
4406 return true;
4408 return false;
4410 #endif /* not INSIDE_RECURSION */
4412 #ifdef INSIDE_RECURSION
4414 #ifdef WCHAR
4415 /* This insert space, which size is "num", into the pattern at "loc".
4416 "end" must point the end of the allocated buffer. */
4417 static void
4418 insert_space (num, loc, end)
4419 int num;
4420 CHAR_T *loc;
4421 CHAR_T *end;
4423 register CHAR_T *pto = end;
4424 register CHAR_T *pfrom = end - num;
4426 while (pfrom >= loc)
4427 *pto-- = *pfrom--;
4429 #endif /* WCHAR */
4431 #ifdef WCHAR
4432 static reg_errcode_t
4433 wcs_compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4434 char_set)
4435 CHAR_T range_start_char;
4436 const CHAR_T **p_ptr, *pend;
4437 CHAR_T *char_set, *b;
4438 RE_TRANSLATE_TYPE translate;
4439 reg_syntax_t syntax;
4441 const CHAR_T *p = *p_ptr;
4442 CHAR_T range_start, range_end;
4443 reg_errcode_t ret;
4444 # ifdef _LIBC
4445 uint32_t nrules;
4446 uint32_t start_val, end_val;
4447 # endif
4448 if (p == pend)
4449 return REG_ERANGE;
4451 # ifdef _LIBC
4452 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4453 if (nrules != 0)
4455 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4456 _NL_COLLATE_COLLSEQWC);
4457 const unsigned char *extra = (const unsigned char *)
4458 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4460 if (range_start_char < -1)
4462 /* range_start is a collating symbol. */
4463 int32_t *wextra;
4464 /* Retreive the index and get collation sequence value. */
4465 wextra = (int32_t*)(extra + char_set[-range_start_char]);
4466 start_val = wextra[1 + *wextra];
4468 else
4469 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4471 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4473 /* Report an error if the range is empty and the syntax prohibits
4474 this. */
4475 ret = ((syntax & RE_NO_EMPTY_RANGES)
4476 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4478 /* Insert space to the end of the char_ranges. */
4479 insert_space(2, b - char_set[5] - 2, b - 1);
4480 *(b - char_set[5] - 2) = (wchar_t)start_val;
4481 *(b - char_set[5] - 1) = (wchar_t)end_val;
4482 char_set[4]++; /* ranges_index */
4484 else
4485 # endif
4487 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4488 range_start_char;
4489 range_end = TRANSLATE (p[0]);
4490 /* Report an error if the range is empty and the syntax prohibits
4491 this. */
4492 ret = ((syntax & RE_NO_EMPTY_RANGES)
4493 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4495 /* Insert space to the end of the char_ranges. */
4496 insert_space(2, b - char_set[5] - 2, b - 1);
4497 *(b - char_set[5] - 2) = range_start;
4498 *(b - char_set[5] - 1) = range_end;
4499 char_set[4]++; /* ranges_index */
4501 /* Have to increment the pointer into the pattern string, so the
4502 caller isn't still at the ending character. */
4503 (*p_ptr)++;
4505 return ret;
4507 #else /* BYTE */
4508 /* Read the ending character of a range (in a bracket expression) from the
4509 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4510 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4511 Then we set the translation of all bits between the starting and
4512 ending characters (inclusive) in the compiled pattern B.
4514 Return an error code.
4516 We use these short variable names so we can use the same macros as
4517 `regex_compile' itself. */
4519 static reg_errcode_t
4520 byte_compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4521 unsigned int range_start_char;
4522 const char **p_ptr, *pend;
4523 RE_TRANSLATE_TYPE translate;
4524 reg_syntax_t syntax;
4525 unsigned char *b;
4527 unsigned this_char;
4528 const char *p = *p_ptr;
4529 reg_errcode_t ret;
4530 # if _LIBC
4531 const unsigned char *collseq;
4532 unsigned int start_colseq;
4533 unsigned int end_colseq;
4534 # else
4535 unsigned end_char;
4536 # endif
4538 if (p == pend)
4539 return REG_ERANGE;
4541 /* Have to increment the pointer into the pattern string, so the
4542 caller isn't still at the ending character. */
4543 (*p_ptr)++;
4545 /* Report an error if the range is empty and the syntax prohibits this. */
4546 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4548 # if _LIBC
4549 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4550 _NL_COLLATE_COLLSEQMB);
4552 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4553 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4554 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4556 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4558 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4560 SET_LIST_BIT (TRANSLATE (this_char));
4561 ret = REG_NOERROR;
4564 # else
4565 /* Here we see why `this_char' has to be larger than an `unsigned
4566 char' -- we would otherwise go into an infinite loop, since all
4567 characters <= 0xff. */
4568 range_start_char = TRANSLATE (range_start_char);
4569 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4570 and some compilers cast it to int implicitly, so following for_loop
4571 may fall to (almost) infinite loop.
4572 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4573 To avoid this, we cast p[0] to unsigned int and truncate it. */
4574 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4576 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4578 SET_LIST_BIT (TRANSLATE (this_char));
4579 ret = REG_NOERROR;
4581 # endif
4583 return ret;
4585 #endif /* WCHAR */
4587 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4588 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4589 characters can start a string that matches the pattern. This fastmap
4590 is used by re_search to skip quickly over impossible starting points.
4592 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4593 area as BUFP->fastmap.
4595 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4596 the pattern buffer.
4598 Returns 0 if we succeed, -2 if an internal error. */
4600 #ifdef WCHAR
4601 /* local function for re_compile_fastmap.
4602 truncate wchar_t character to char. */
4603 static unsigned char truncate_wchar (CHAR_T c);
4605 static unsigned char
4606 truncate_wchar (c)
4607 CHAR_T c;
4609 unsigned char buf[MB_LEN_MAX];
4610 int retval = wctomb(buf, c);
4611 return retval > 0 ? buf[0] : (unsigned char)c;
4613 #endif /* WCHAR */
4615 static int
4616 PREFIX(re_compile_fastmap) (bufp)
4617 struct re_pattern_buffer *bufp;
4619 int j, k;
4620 #ifdef MATCH_MAY_ALLOCATE
4621 PREFIX(fail_stack_type) fail_stack;
4622 #endif
4623 #ifndef REGEX_MALLOC
4624 char *destination;
4625 #endif
4627 register char *fastmap = bufp->fastmap;
4629 #ifdef WCHAR
4630 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4631 pattern to (char*) in regex_compile. */
4632 UCHAR_T *pattern = (UCHAR_T*)bufp->buffer;
4633 register UCHAR_T *pend = (UCHAR_T*) (bufp->buffer + bufp->used);
4634 #else /* BYTE */
4635 UCHAR_T *pattern = bufp->buffer;
4636 register UCHAR_T *pend = pattern + bufp->used;
4637 #endif /* WCHAR */
4638 UCHAR_T *p = pattern;
4640 #ifdef REL_ALLOC
4641 /* This holds the pointer to the failure stack, when
4642 it is allocated relocatably. */
4643 fail_stack_elt_t *failure_stack_ptr;
4644 #endif
4646 /* Assume that each path through the pattern can be null until
4647 proven otherwise. We set this false at the bottom of switch
4648 statement, to which we get only if a particular path doesn't
4649 match the empty string. */
4650 boolean path_can_be_null = true;
4652 /* We aren't doing a `succeed_n' to begin with. */
4653 boolean succeed_n_p = false;
4655 assert (fastmap != NULL && p != NULL);
4657 INIT_FAIL_STACK ();
4658 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4659 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4660 bufp->can_be_null = 0;
4662 while (1)
4664 if (p == pend || *p == succeed)
4666 /* We have reached the (effective) end of pattern. */
4667 if (!FAIL_STACK_EMPTY ())
4669 bufp->can_be_null |= path_can_be_null;
4671 /* Reset for next path. */
4672 path_can_be_null = true;
4674 p = fail_stack.stack[--fail_stack.avail].pointer;
4676 continue;
4678 else
4679 break;
4682 /* We should never be about to go beyond the end of the pattern. */
4683 assert (p < pend);
4685 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4688 /* I guess the idea here is to simply not bother with a fastmap
4689 if a backreference is used, since it's too hard to figure out
4690 the fastmap for the corresponding group. Setting
4691 `can_be_null' stops `re_search_2' from using the fastmap, so
4692 that is all we do. */
4693 case duplicate:
4694 bufp->can_be_null = 1;
4695 goto done;
4698 /* Following are the cases which match a character. These end
4699 with `break'. */
4701 #ifdef WCHAR
4702 case exactn:
4703 fastmap[truncate_wchar(p[1])] = 1;
4704 break;
4705 #else /* BYTE */
4706 case exactn:
4707 fastmap[p[1]] = 1;
4708 break;
4709 #endif /* WCHAR */
4710 #ifdef MBS_SUPPORT
4711 case exactn_bin:
4712 fastmap[p[1]] = 1;
4713 break;
4714 #endif
4716 #ifdef WCHAR
4717 /* It is hard to distinguish fastmap from (multi byte) characters
4718 which depends on current locale. */
4719 case charset:
4720 case charset_not:
4721 case wordchar:
4722 case notwordchar:
4723 bufp->can_be_null = 1;
4724 goto done;
4725 #else /* BYTE */
4726 case charset:
4727 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4728 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4729 fastmap[j] = 1;
4730 break;
4733 case charset_not:
4734 /* Chars beyond end of map must be allowed. */
4735 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4736 fastmap[j] = 1;
4738 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4739 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4740 fastmap[j] = 1;
4741 break;
4744 case wordchar:
4745 for (j = 0; j < (1 << BYTEWIDTH); j++)
4746 if (SYNTAX (j) == Sword)
4747 fastmap[j] = 1;
4748 break;
4751 case notwordchar:
4752 for (j = 0; j < (1 << BYTEWIDTH); j++)
4753 if (SYNTAX (j) != Sword)
4754 fastmap[j] = 1;
4755 break;
4756 #endif /* WCHAR */
4758 case anychar:
4760 int fastmap_newline = fastmap['\n'];
4762 /* `.' matches anything ... */
4763 for (j = 0; j < (1 << BYTEWIDTH); j++)
4764 fastmap[j] = 1;
4766 /* ... except perhaps newline. */
4767 if (!(bufp->syntax & RE_DOT_NEWLINE))
4768 fastmap['\n'] = fastmap_newline;
4770 /* Return if we have already set `can_be_null'; if we have,
4771 then the fastmap is irrelevant. Something's wrong here. */
4772 else if (bufp->can_be_null)
4773 goto done;
4775 /* Otherwise, have to check alternative paths. */
4776 break;
4779 #ifdef emacs
4780 case syntaxspec:
4781 k = *p++;
4782 for (j = 0; j < (1 << BYTEWIDTH); j++)
4783 if (SYNTAX (j) == (enum syntaxcode) k)
4784 fastmap[j] = 1;
4785 break;
4788 case notsyntaxspec:
4789 k = *p++;
4790 for (j = 0; j < (1 << BYTEWIDTH); j++)
4791 if (SYNTAX (j) != (enum syntaxcode) k)
4792 fastmap[j] = 1;
4793 break;
4796 /* All cases after this match the empty string. These end with
4797 `continue'. */
4800 case before_dot:
4801 case at_dot:
4802 case after_dot:
4803 continue;
4804 #endif /* emacs */
4807 case no_op:
4808 case begline:
4809 case endline:
4810 case begbuf:
4811 case endbuf:
4812 case wordbound:
4813 case notwordbound:
4814 case wordbeg:
4815 case wordend:
4816 case push_dummy_failure:
4817 continue;
4820 case jump_n:
4821 case pop_failure_jump:
4822 case maybe_pop_jump:
4823 case jump:
4824 case jump_past_alt:
4825 case dummy_failure_jump:
4826 EXTRACT_NUMBER_AND_INCR (j, p);
4827 p += j;
4828 if (j > 0)
4829 continue;
4831 /* Jump backward implies we just went through the body of a
4832 loop and matched nothing. Opcode jumped to should be
4833 `on_failure_jump' or `succeed_n'. Just treat it like an
4834 ordinary jump. For a * loop, it has pushed its failure
4835 point already; if so, discard that as redundant. */
4836 if ((re_opcode_t) *p != on_failure_jump
4837 && (re_opcode_t) *p != succeed_n)
4838 continue;
4840 p++;
4841 EXTRACT_NUMBER_AND_INCR (j, p);
4842 p += j;
4844 /* If what's on the stack is where we are now, pop it. */
4845 if (!FAIL_STACK_EMPTY ()
4846 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4847 fail_stack.avail--;
4849 continue;
4852 case on_failure_jump:
4853 case on_failure_keep_string_jump:
4854 handle_on_failure_jump:
4855 EXTRACT_NUMBER_AND_INCR (j, p);
4857 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4858 end of the pattern. We don't want to push such a point,
4859 since when we restore it above, entering the switch will
4860 increment `p' past the end of the pattern. We don't need
4861 to push such a point since we obviously won't find any more
4862 fastmap entries beyond `pend'. Such a pattern can match
4863 the null string, though. */
4864 if (p + j < pend)
4866 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4868 RESET_FAIL_STACK ();
4869 return -2;
4872 else
4873 bufp->can_be_null = 1;
4875 if (succeed_n_p)
4877 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4878 succeed_n_p = false;
4881 continue;
4884 case succeed_n:
4885 /* Get to the number of times to succeed. */
4886 p += OFFSET_ADDRESS_SIZE;
4888 /* Increment p past the n for when k != 0. */
4889 EXTRACT_NUMBER_AND_INCR (k, p);
4890 if (k == 0)
4892 p -= 2 * OFFSET_ADDRESS_SIZE;
4893 succeed_n_p = true; /* Spaghetti code alert. */
4894 goto handle_on_failure_jump;
4896 continue;
4899 case set_number_at:
4900 p += 2 * OFFSET_ADDRESS_SIZE;
4901 continue;
4904 case start_memory:
4905 case stop_memory:
4906 p += 2;
4907 continue;
4910 default:
4911 abort (); /* We have listed all the cases. */
4912 } /* switch *p++ */
4914 /* Getting here means we have found the possible starting
4915 characters for one path of the pattern -- and that the empty
4916 string does not match. We need not follow this path further.
4917 Instead, look at the next alternative (remembered on the
4918 stack), or quit if no more. The test at the top of the loop
4919 does these things. */
4920 path_can_be_null = false;
4921 p = pend;
4922 } /* while p */
4924 /* Set `can_be_null' for the last path (also the first path, if the
4925 pattern is empty). */
4926 bufp->can_be_null |= path_can_be_null;
4928 done:
4929 RESET_FAIL_STACK ();
4930 return 0;
4933 #else /* not INSIDE_RECURSION */
4936 re_compile_fastmap (bufp)
4937 struct re_pattern_buffer *bufp;
4939 # ifdef MBS_SUPPORT
4940 if (MB_CUR_MAX != 1)
4941 return wcs_re_compile_fastmap(bufp);
4942 else
4943 # endif
4944 return byte_re_compile_fastmap(bufp);
4945 } /* re_compile_fastmap */
4946 #ifdef _LIBC
4947 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4948 #endif
4951 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4952 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4953 this memory for recording register information. STARTS and ENDS
4954 must be allocated using the malloc library routine, and must each
4955 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4957 If NUM_REGS == 0, then subsequent matches should allocate their own
4958 register data.
4960 Unless this function is called, the first search or match using
4961 PATTERN_BUFFER will allocate its own register data, without
4962 freeing the old data. */
4964 void
4965 re_set_registers (bufp, regs, num_regs, starts, ends)
4966 struct re_pattern_buffer *bufp;
4967 struct re_registers *regs;
4968 unsigned num_regs;
4969 regoff_t *starts, *ends;
4971 if (num_regs)
4973 bufp->regs_allocated = REGS_REALLOCATE;
4974 regs->num_regs = num_regs;
4975 regs->start = starts;
4976 regs->end = ends;
4978 else
4980 bufp->regs_allocated = REGS_UNALLOCATED;
4981 regs->num_regs = 0;
4982 regs->start = regs->end = (regoff_t *) 0;
4985 #ifdef _LIBC
4986 weak_alias (__re_set_registers, re_set_registers)
4987 #endif
4989 /* Searching routines. */
4991 /* Like re_search_2, below, but only one string is specified, and
4992 doesn't let you say where to stop matching. */
4995 re_search (bufp, string, size, startpos, range, regs)
4996 struct re_pattern_buffer *bufp;
4997 const char *string;
4998 int size, startpos, range;
4999 struct re_registers *regs;
5001 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
5002 regs, size);
5004 #ifdef _LIBC
5005 weak_alias (__re_search, re_search)
5006 #endif
5009 /* Using the compiled pattern in BUFP->buffer, first tries to match the
5010 virtual concatenation of STRING1 and STRING2, starting first at index
5011 STARTPOS, then at STARTPOS + 1, and so on.
5013 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
5015 RANGE is how far to scan while trying to match. RANGE = 0 means try
5016 only at STARTPOS; in general, the last start tried is STARTPOS +
5017 RANGE.
5019 In REGS, return the indices of the virtual concatenation of STRING1
5020 and STRING2 that matched the entire BUFP->buffer and its contained
5021 subexpressions.
5023 Do not consider matching one past the index STOP in the virtual
5024 concatenation of STRING1 and STRING2.
5026 We return either the position in the strings at which the match was
5027 found, -1 if no match, or -2 if error (such as failure
5028 stack overflow). */
5031 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
5032 struct re_pattern_buffer *bufp;
5033 const char *string1, *string2;
5034 int size1, size2;
5035 int startpos;
5036 int range;
5037 struct re_registers *regs;
5038 int stop;
5040 # ifdef MBS_SUPPORT
5041 if (MB_CUR_MAX != 1)
5042 return wcs_re_search_2 (bufp, string1, size1, string2, size2, startpos,
5043 range, regs, stop);
5044 else
5045 # endif
5046 return byte_re_search_2 (bufp, string1, size1, string2, size2, startpos,
5047 range, regs, stop);
5048 } /* re_search_2 */
5049 #ifdef _LIBC
5050 weak_alias (__re_search_2, re_search_2)
5051 #endif
5053 #endif /* not INSIDE_RECURSION */
5055 #ifdef INSIDE_RECURSION
5057 #ifdef MATCH_MAY_ALLOCATE
5058 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5059 #else
5060 # define FREE_VAR(var) if (var) free (var); var = NULL
5061 #endif
5063 #ifdef WCHAR
5064 # define FREE_WCS_BUFFERS() \
5065 do { \
5066 FREE_VAR (string1); \
5067 FREE_VAR (string2); \
5068 FREE_VAR (mbs_offset1); \
5069 FREE_VAR (mbs_offset2); \
5070 } while (0)
5072 #endif
5074 static int
5075 PREFIX(re_search_2) (bufp, string1, size1, string2, size2, startpos, range,
5076 regs, stop)
5077 struct re_pattern_buffer *bufp;
5078 const char *string1, *string2;
5079 int size1, size2;
5080 int startpos;
5081 int range;
5082 struct re_registers *regs;
5083 int stop;
5085 int val;
5086 register char *fastmap = bufp->fastmap;
5087 register RE_TRANSLATE_TYPE translate = bufp->translate;
5088 int total_size = size1 + size2;
5089 int endpos = startpos + range;
5090 #ifdef WCHAR
5091 /* We need wchar_t* buffers correspond to cstring1, cstring2. */
5092 wchar_t *wcs_string1 = NULL, *wcs_string2 = NULL;
5093 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5094 int wcs_size1 = 0, wcs_size2 = 0;
5095 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5096 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5097 /* They hold whether each wchar_t is binary data or not. */
5098 char *is_binary = NULL;
5099 #endif /* WCHAR */
5101 /* Check for out-of-range STARTPOS. */
5102 if (startpos < 0 || startpos > total_size)
5103 return -1;
5105 /* Fix up RANGE if it might eventually take us outside
5106 the virtual concatenation of STRING1 and STRING2.
5107 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
5108 if (endpos < 0)
5109 range = 0 - startpos;
5110 else if (endpos > total_size)
5111 range = total_size - startpos;
5113 /* If the search isn't to be a backwards one, don't waste time in a
5114 search for a pattern that must be anchored. */
5115 if (bufp->used > 0 && range > 0
5116 && ((re_opcode_t) bufp->buffer[0] == begbuf
5117 /* `begline' is like `begbuf' if it cannot match at newlines. */
5118 || ((re_opcode_t) bufp->buffer[0] == begline
5119 && !bufp->newline_anchor)))
5121 if (startpos > 0)
5122 return -1;
5123 else
5124 range = 1;
5127 #ifdef emacs
5128 /* In a forward search for something that starts with \=.
5129 don't keep searching past point. */
5130 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5132 range = PT - startpos;
5133 if (range <= 0)
5134 return -1;
5136 #endif /* emacs */
5138 /* Update the fastmap now if not correct already. */
5139 if (fastmap && !bufp->fastmap_accurate)
5140 if (re_compile_fastmap (bufp) == -2)
5141 return -2;
5143 #ifdef WCHAR
5144 /* Allocate wchar_t array for wcs_string1 and wcs_string2 and
5145 fill them with converted string. */
5146 if (size1 != 0)
5148 wcs_string1 = REGEX_TALLOC (size1 + 1, CHAR_T);
5149 mbs_offset1 = REGEX_TALLOC (size1 + 1, int);
5150 is_binary = REGEX_TALLOC (size1 + 1, char);
5151 if (!wcs_string1 || !mbs_offset1 || !is_binary)
5153 FREE_VAR (wcs_string1);
5154 FREE_VAR (mbs_offset1);
5155 FREE_VAR (is_binary);
5156 return -2;
5158 wcs_size1 = convert_mbs_to_wcs(wcs_string1, string1, size1,
5159 mbs_offset1, is_binary);
5160 wcs_string1[wcs_size1] = L'\0'; /* for a sentinel */
5161 FREE_VAR (is_binary);
5163 if (size2 != 0)
5165 wcs_string2 = REGEX_TALLOC (size2 + 1, CHAR_T);
5166 mbs_offset2 = REGEX_TALLOC (size2 + 1, int);
5167 is_binary = REGEX_TALLOC (size2 + 1, char);
5168 if (!wcs_string2 || !mbs_offset2 || !is_binary)
5170 FREE_WCS_BUFFERS ();
5171 FREE_VAR (is_binary);
5172 return -2;
5174 wcs_size2 = convert_mbs_to_wcs(wcs_string2, string2, size2,
5175 mbs_offset2, is_binary);
5176 wcs_string2[wcs_size2] = L'\0'; /* for a sentinel */
5177 FREE_VAR (is_binary);
5179 #endif /* WCHAR */
5182 /* Loop through the string, looking for a place to start matching. */
5183 for (;;)
5185 /* If a fastmap is supplied, skip quickly over characters that
5186 cannot be the start of a match. If the pattern can match the
5187 null string, however, we don't need to skip characters; we want
5188 the first null string. */
5189 if (fastmap && startpos < total_size && !bufp->can_be_null)
5191 if (range > 0) /* Searching forwards. */
5193 register const char *d;
5194 register int lim = 0;
5195 int irange = range;
5197 if (startpos < size1 && startpos + range >= size1)
5198 lim = range - (size1 - startpos);
5200 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5202 /* Written out as an if-else to avoid testing `translate'
5203 inside the loop. */
5204 if (translate)
5205 while (range > lim
5206 && !fastmap[(unsigned char)
5207 translate[(unsigned char) *d++]])
5208 range--;
5209 else
5210 while (range > lim && !fastmap[(unsigned char) *d++])
5211 range--;
5213 startpos += irange - range;
5215 else /* Searching backwards. */
5217 register CHAR_T c = (size1 == 0 || startpos >= size1
5218 ? string2[startpos - size1]
5219 : string1[startpos]);
5221 if (!fastmap[(unsigned char) TRANSLATE (c)])
5222 goto advance;
5226 /* If can't match the null string, and that's all we have left, fail. */
5227 if (range >= 0 && startpos == total_size && fastmap
5228 && !bufp->can_be_null)
5230 #ifdef WCHAR
5231 FREE_WCS_BUFFERS ();
5232 #endif
5233 return -1;
5236 #ifdef WCHAR
5237 val = wcs_re_match_2_internal (bufp, string1, size1, string2,
5238 size2, startpos, regs, stop,
5239 wcs_string1, wcs_size1,
5240 wcs_string2, wcs_size2,
5241 mbs_offset1, mbs_offset2);
5242 #else /* BYTE */
5243 val = byte_re_match_2_internal (bufp, string1, size1, string2,
5244 size2, startpos, regs, stop);
5245 #endif /* BYTE */
5247 #ifndef REGEX_MALLOC
5248 # ifdef C_ALLOCA
5249 alloca (0);
5250 # endif
5251 #endif
5253 if (val >= 0)
5255 #ifdef WCHAR
5256 FREE_WCS_BUFFERS ();
5257 #endif
5258 return startpos;
5261 if (val == -2)
5263 #ifdef WCHAR
5264 FREE_WCS_BUFFERS ();
5265 #endif
5266 return -2;
5269 advance:
5270 if (!range)
5271 break;
5272 else if (range > 0)
5274 range--;
5275 startpos++;
5277 else
5279 range++;
5280 startpos--;
5283 #ifdef WCHAR
5284 FREE_WCS_BUFFERS ();
5285 #endif
5286 return -1;
5289 #ifdef WCHAR
5290 /* This converts PTR, a pointer into one of the search wchar_t strings
5291 `string1' and `string2' into an multibyte string offset from the
5292 beginning of that string. We use mbs_offset to optimize.
5293 See convert_mbs_to_wcs. */
5294 # define POINTER_TO_OFFSET(ptr) \
5295 (FIRST_STRING_P (ptr) \
5296 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5297 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5298 + csize1)))
5299 #else /* BYTE */
5300 /* This converts PTR, a pointer into one of the search strings `string1'
5301 and `string2' into an offset from the beginning of that string. */
5302 # define POINTER_TO_OFFSET(ptr) \
5303 (FIRST_STRING_P (ptr) \
5304 ? ((regoff_t) ((ptr) - string1)) \
5305 : ((regoff_t) ((ptr) - string2 + size1)))
5306 #endif /* WCHAR */
5308 /* Macros for dealing with the split strings in re_match_2. */
5310 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5312 /* Call before fetching a character with *d. This switches over to
5313 string2 if necessary. */
5314 #define PREFETCH() \
5315 while (d == dend) \
5317 /* End of string2 => fail. */ \
5318 if (dend == end_match_2) \
5319 goto fail; \
5320 /* End of string1 => advance to string2. */ \
5321 d = string2; \
5322 dend = end_match_2; \
5325 /* Test if at very beginning or at very end of the virtual concatenation
5326 of `string1' and `string2'. If only one string, it's `string2'. */
5327 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5328 #define AT_STRINGS_END(d) ((d) == end2)
5331 /* Test if D points to a character which is word-constituent. We have
5332 two special cases to check for: if past the end of string1, look at
5333 the first character in string2; and if before the beginning of
5334 string2, look at the last character in string1. */
5335 #ifdef WCHAR
5336 /* Use internationalized API instead of SYNTAX. */
5337 # define WORDCHAR_P(d) \
5338 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5339 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5340 #else /* BYTE */
5341 # define WORDCHAR_P(d) \
5342 (SYNTAX ((d) == end1 ? *string2 \
5343 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5344 == Sword)
5345 #endif /* WCHAR */
5347 /* Disabled due to a compiler bug -- see comment at case wordbound */
5348 #if 0
5349 /* Test if the character before D and the one at D differ with respect
5350 to being word-constituent. */
5351 #define AT_WORD_BOUNDARY(d) \
5352 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5353 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5354 #endif
5356 /* Free everything we malloc. */
5357 #ifdef MATCH_MAY_ALLOCATE
5358 # ifdef WCHAR
5359 # define FREE_VARIABLES() \
5360 do { \
5361 REGEX_FREE_STACK (fail_stack.stack); \
5362 FREE_VAR (regstart); \
5363 FREE_VAR (regend); \
5364 FREE_VAR (old_regstart); \
5365 FREE_VAR (old_regend); \
5366 FREE_VAR (best_regstart); \
5367 FREE_VAR (best_regend); \
5368 FREE_VAR (reg_info); \
5369 FREE_VAR (reg_dummy); \
5370 FREE_VAR (reg_info_dummy); \
5371 if (!cant_free_wcs_buf) \
5373 FREE_VAR (string1); \
5374 FREE_VAR (string2); \
5375 FREE_VAR (mbs_offset1); \
5376 FREE_VAR (mbs_offset2); \
5378 } while (0)
5379 # else /* BYTE */
5380 # define FREE_VARIABLES() \
5381 do { \
5382 REGEX_FREE_STACK (fail_stack.stack); \
5383 FREE_VAR (regstart); \
5384 FREE_VAR (regend); \
5385 FREE_VAR (old_regstart); \
5386 FREE_VAR (old_regend); \
5387 FREE_VAR (best_regstart); \
5388 FREE_VAR (best_regend); \
5389 FREE_VAR (reg_info); \
5390 FREE_VAR (reg_dummy); \
5391 FREE_VAR (reg_info_dummy); \
5392 } while (0)
5393 # endif /* WCHAR */
5394 #else
5395 # ifdef WCHAR
5396 # define FREE_VARIABLES() \
5397 do { \
5398 if (!cant_free_wcs_buf) \
5400 FREE_VAR (string1); \
5401 FREE_VAR (string2); \
5402 FREE_VAR (mbs_offset1); \
5403 FREE_VAR (mbs_offset2); \
5405 } while (0)
5406 # else /* BYTE */
5407 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5408 # endif /* WCHAR */
5409 #endif /* not MATCH_MAY_ALLOCATE */
5411 /* These values must meet several constraints. They must not be valid
5412 register values; since we have a limit of 255 registers (because
5413 we use only one byte in the pattern for the register number), we can
5414 use numbers larger than 255. They must differ by 1, because of
5415 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5416 be larger than the value for the highest register, so we do not try
5417 to actually save any registers when none are active. */
5418 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5419 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5421 #else /* not INSIDE_RECURSION */
5422 /* Matching routines. */
5424 #ifndef emacs /* Emacs never uses this. */
5425 /* re_match is like re_match_2 except it takes only a single string. */
5428 re_match (bufp, string, size, pos, regs)
5429 struct re_pattern_buffer *bufp;
5430 const char *string;
5431 int size, pos;
5432 struct re_registers *regs;
5434 int result;
5435 # ifdef MBS_SUPPORT
5436 if (MB_CUR_MAX != 1)
5437 result = wcs_re_match_2_internal (bufp, NULL, 0, string, size,
5438 pos, regs, size,
5439 NULL, 0, NULL, 0, NULL, NULL);
5440 else
5441 # endif
5442 result = byte_re_match_2_internal (bufp, NULL, 0, string, size,
5443 pos, regs, size);
5444 # ifndef REGEX_MALLOC
5445 # ifdef C_ALLOCA
5446 alloca (0);
5447 # endif
5448 # endif
5449 return result;
5451 # ifdef _LIBC
5452 weak_alias (__re_match, re_match)
5453 # endif
5454 #endif /* not emacs */
5456 #endif /* not INSIDE_RECURSION */
5458 #ifdef INSIDE_RECURSION
5459 static boolean PREFIX(group_match_null_string_p) _RE_ARGS ((UCHAR_T **p,
5460 UCHAR_T *end,
5461 PREFIX(register_info_type) *reg_info));
5462 static boolean PREFIX(alt_match_null_string_p) _RE_ARGS ((UCHAR_T *p,
5463 UCHAR_T *end,
5464 PREFIX(register_info_type) *reg_info));
5465 static boolean PREFIX(common_op_match_null_string_p) _RE_ARGS ((UCHAR_T **p,
5466 UCHAR_T *end,
5467 PREFIX(register_info_type) *reg_info));
5468 static int PREFIX(bcmp_translate) _RE_ARGS ((const CHAR_T *s1, const CHAR_T *s2,
5469 int len, char *translate));
5470 #else /* not INSIDE_RECURSION */
5472 /* re_match_2 matches the compiled pattern in BUFP against the
5473 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5474 and SIZE2, respectively). We start matching at POS, and stop
5475 matching at STOP.
5477 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5478 store offsets for the substring each group matched in REGS. See the
5479 documentation for exactly how many groups we fill.
5481 We return -1 if no match, -2 if an internal error (such as the
5482 failure stack overflowing). Otherwise, we return the length of the
5483 matched substring. */
5486 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5487 struct re_pattern_buffer *bufp;
5488 const char *string1, *string2;
5489 int size1, size2;
5490 int pos;
5491 struct re_registers *regs;
5492 int stop;
5494 int result;
5495 # ifdef MBS_SUPPORT
5496 if (MB_CUR_MAX != 1)
5497 result = wcs_re_match_2_internal (bufp, string1, size1, string2, size2,
5498 pos, regs, stop,
5499 NULL, 0, NULL, 0, NULL, NULL);
5500 else
5501 # endif
5502 result = byte_re_match_2_internal (bufp, string1, size1, string2, size2,
5503 pos, regs, stop);
5505 #ifndef REGEX_MALLOC
5506 # ifdef C_ALLOCA
5507 alloca (0);
5508 # endif
5509 #endif
5510 return result;
5512 #ifdef _LIBC
5513 weak_alias (__re_match_2, re_match_2)
5514 #endif
5516 #endif /* not INSIDE_RECURSION */
5518 #ifdef INSIDE_RECURSION
5520 #ifdef WCHAR
5521 static int count_mbs_length PARAMS ((int *, int));
5523 /* This check the substring (from 0, to length) of the multibyte string,
5524 to which offset_buffer correspond. And count how many wchar_t_characters
5525 the substring occupy. We use offset_buffer to optimization.
5526 See convert_mbs_to_wcs. */
5528 static int
5529 count_mbs_length(offset_buffer, length)
5530 int *offset_buffer;
5531 int length;
5533 int upper, lower;
5535 /* Check whether the size is valid. */
5536 if (length < 0)
5537 return -1;
5539 if (offset_buffer == NULL)
5540 return 0;
5542 /* If there are no multibyte character, offset_buffer[i] == i.
5543 Optmize for this case. */
5544 if (offset_buffer[length] == length)
5545 return length;
5547 /* Set up upper with length. (because for all i, offset_buffer[i] >= i) */
5548 upper = length;
5549 lower = 0;
5551 while (true)
5553 int middle = (lower + upper) / 2;
5554 if (middle == lower || middle == upper)
5555 break;
5556 if (offset_buffer[middle] > length)
5557 upper = middle;
5558 else if (offset_buffer[middle] < length)
5559 lower = middle;
5560 else
5561 return middle;
5564 return -1;
5566 #endif /* WCHAR */
5568 /* This is a separate function so that we can force an alloca cleanup
5569 afterwards. */
5570 #ifdef WCHAR
5571 static int
5572 wcs_re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos,
5573 regs, stop, string1, size1, string2, size2,
5574 mbs_offset1, mbs_offset2)
5575 struct re_pattern_buffer *bufp;
5576 const char *cstring1, *cstring2;
5577 int csize1, csize2;
5578 int pos;
5579 struct re_registers *regs;
5580 int stop;
5581 /* string1 == string2 == NULL means string1/2, size1/2 and
5582 mbs_offset1/2 need seting up in this function. */
5583 /* We need wchar_t* buffers correspond to cstring1, cstring2. */
5584 wchar_t *string1, *string2;
5585 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5586 int size1, size2;
5587 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5588 int *mbs_offset1, *mbs_offset2;
5589 #else /* BYTE */
5590 static int
5591 byte_re_match_2_internal (bufp, string1, size1,string2, size2, pos,
5592 regs, stop)
5593 struct re_pattern_buffer *bufp;
5594 const char *string1, *string2;
5595 int size1, size2;
5596 int pos;
5597 struct re_registers *regs;
5598 int stop;
5599 #endif /* BYTE */
5601 /* General temporaries. */
5602 int mcnt;
5603 UCHAR_T *p1;
5604 #ifdef WCHAR
5605 /* They hold whether each wchar_t is binary data or not. */
5606 char *is_binary = NULL;
5607 /* If true, we can't free string1/2, mbs_offset1/2. */
5608 int cant_free_wcs_buf = 1;
5609 #endif /* WCHAR */
5611 /* Just past the end of the corresponding string. */
5612 const CHAR_T *end1, *end2;
5614 /* Pointers into string1 and string2, just past the last characters in
5615 each to consider matching. */
5616 const CHAR_T *end_match_1, *end_match_2;
5618 /* Where we are in the data, and the end of the current string. */
5619 const CHAR_T *d, *dend;
5621 /* Where we are in the pattern, and the end of the pattern. */
5622 #ifdef WCHAR
5623 UCHAR_T *pattern, *p;
5624 register UCHAR_T *pend;
5625 #else /* BYTE */
5626 UCHAR_T *p = bufp->buffer;
5627 register UCHAR_T *pend = p + bufp->used;
5628 #endif /* WCHAR */
5630 /* Mark the opcode just after a start_memory, so we can test for an
5631 empty subpattern when we get to the stop_memory. */
5632 UCHAR_T *just_past_start_mem = 0;
5634 /* We use this to map every character in the string. */
5635 RE_TRANSLATE_TYPE translate = bufp->translate;
5637 /* Failure point stack. Each place that can handle a failure further
5638 down the line pushes a failure point on this stack. It consists of
5639 restart, regend, and reg_info for all registers corresponding to
5640 the subexpressions we're currently inside, plus the number of such
5641 registers, and, finally, two char *'s. The first char * is where
5642 to resume scanning the pattern; the second one is where to resume
5643 scanning the strings. If the latter is zero, the failure point is
5644 a ``dummy''; if a failure happens and the failure point is a dummy,
5645 it gets discarded and the next next one is tried. */
5646 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5647 PREFIX(fail_stack_type) fail_stack;
5648 #endif
5649 #ifdef DEBUG
5650 static unsigned failure_id;
5651 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5652 #endif
5654 #ifdef REL_ALLOC
5655 /* This holds the pointer to the failure stack, when
5656 it is allocated relocatably. */
5657 fail_stack_elt_t *failure_stack_ptr;
5658 #endif
5660 /* We fill all the registers internally, independent of what we
5661 return, for use in backreferences. The number here includes
5662 an element for register zero. */
5663 size_t num_regs = bufp->re_nsub + 1;
5665 /* The currently active registers. */
5666 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5667 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5669 /* Information on the contents of registers. These are pointers into
5670 the input strings; they record just what was matched (on this
5671 attempt) by a subexpression part of the pattern, that is, the
5672 regnum-th regstart pointer points to where in the pattern we began
5673 matching and the regnum-th regend points to right after where we
5674 stopped matching the regnum-th subexpression. (The zeroth register
5675 keeps track of what the whole pattern matches.) */
5676 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5677 const CHAR_T **regstart, **regend;
5678 #endif
5680 /* If a group that's operated upon by a repetition operator fails to
5681 match anything, then the register for its start will need to be
5682 restored because it will have been set to wherever in the string we
5683 are when we last see its open-group operator. Similarly for a
5684 register's end. */
5685 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5686 const CHAR_T **old_regstart, **old_regend;
5687 #endif
5689 /* The is_active field of reg_info helps us keep track of which (possibly
5690 nested) subexpressions we are currently in. The matched_something
5691 field of reg_info[reg_num] helps us tell whether or not we have
5692 matched any of the pattern so far this time through the reg_num-th
5693 subexpression. These two fields get reset each time through any
5694 loop their register is in. */
5695 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5696 PREFIX(register_info_type) *reg_info;
5697 #endif
5699 /* The following record the register info as found in the above
5700 variables when we find a match better than any we've seen before.
5701 This happens as we backtrack through the failure points, which in
5702 turn happens only if we have not yet matched the entire string. */
5703 unsigned best_regs_set = false;
5704 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5705 const CHAR_T **best_regstart, **best_regend;
5706 #endif
5708 /* Logically, this is `best_regend[0]'. But we don't want to have to
5709 allocate space for that if we're not allocating space for anything
5710 else (see below). Also, we never need info about register 0 for
5711 any of the other register vectors, and it seems rather a kludge to
5712 treat `best_regend' differently than the rest. So we keep track of
5713 the end of the best match so far in a separate variable. We
5714 initialize this to NULL so that when we backtrack the first time
5715 and need to test it, it's not garbage. */
5716 const CHAR_T *match_end = NULL;
5718 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5719 int set_regs_matched_done = 0;
5721 /* Used when we pop values we don't care about. */
5722 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5723 const CHAR_T **reg_dummy;
5724 PREFIX(register_info_type) *reg_info_dummy;
5725 #endif
5727 #ifdef DEBUG
5728 /* Counts the total number of registers pushed. */
5729 unsigned num_regs_pushed = 0;
5730 #endif
5732 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5734 INIT_FAIL_STACK ();
5736 #ifdef MATCH_MAY_ALLOCATE
5737 /* Do not bother to initialize all the register variables if there are
5738 no groups in the pattern, as it takes a fair amount of time. If
5739 there are groups, we include space for register 0 (the whole
5740 pattern), even though we never use it, since it simplifies the
5741 array indexing. We should fix this. */
5742 if (bufp->re_nsub)
5744 regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5745 regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5746 old_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5747 old_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5748 best_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5749 best_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5750 reg_info = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5751 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_T *);
5752 reg_info_dummy = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5754 if (!(regstart && regend && old_regstart && old_regend && reg_info
5755 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5757 FREE_VARIABLES ();
5758 return -2;
5761 else
5763 /* We must initialize all our variables to NULL, so that
5764 `FREE_VARIABLES' doesn't try to free them. */
5765 regstart = regend = old_regstart = old_regend = best_regstart
5766 = best_regend = reg_dummy = NULL;
5767 reg_info = reg_info_dummy = (PREFIX(register_info_type) *) NULL;
5769 #endif /* MATCH_MAY_ALLOCATE */
5771 /* The starting position is bogus. */
5772 #ifdef WCHAR
5773 if (pos < 0 || pos > csize1 + csize2)
5774 #else /* BYTE */
5775 if (pos < 0 || pos > size1 + size2)
5776 #endif
5778 FREE_VARIABLES ();
5779 return -1;
5782 #ifdef WCHAR
5783 /* Allocate wchar_t array for string1 and string2 and
5784 fill them with converted string. */
5785 if (string1 == NULL && string2 == NULL)
5787 /* We need seting up buffers here. */
5789 /* We must free wcs buffers in this function. */
5790 cant_free_wcs_buf = 0;
5792 if (csize1 != 0)
5794 string1 = REGEX_TALLOC (csize1 + 1, CHAR_T);
5795 mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5796 is_binary = REGEX_TALLOC (csize1 + 1, char);
5797 if (!string1 || !mbs_offset1 || !is_binary)
5799 FREE_VAR (string1);
5800 FREE_VAR (mbs_offset1);
5801 FREE_VAR (is_binary);
5802 return -2;
5805 if (csize2 != 0)
5807 string2 = REGEX_TALLOC (csize2 + 1, CHAR_T);
5808 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5809 is_binary = REGEX_TALLOC (csize2 + 1, char);
5810 if (!string2 || !mbs_offset2 || !is_binary)
5812 FREE_VAR (string1);
5813 FREE_VAR (mbs_offset1);
5814 FREE_VAR (string2);
5815 FREE_VAR (mbs_offset2);
5816 FREE_VAR (is_binary);
5817 return -2;
5819 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5820 mbs_offset2, is_binary);
5821 string2[size2] = L'\0'; /* for a sentinel */
5822 FREE_VAR (is_binary);
5826 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5827 pattern to (char*) in regex_compile. */
5828 p = pattern = (CHAR_T*)bufp->buffer;
5829 pend = (CHAR_T*)(bufp->buffer + bufp->used);
5831 #endif /* WCHAR */
5833 /* Initialize subexpression text positions to -1 to mark ones that no
5834 start_memory/stop_memory has been seen for. Also initialize the
5835 register information struct. */
5836 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5838 regstart[mcnt] = regend[mcnt]
5839 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5841 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5842 IS_ACTIVE (reg_info[mcnt]) = 0;
5843 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5844 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5847 /* We move `string1' into `string2' if the latter's empty -- but not if
5848 `string1' is null. */
5849 if (size2 == 0 && string1 != NULL)
5851 string2 = string1;
5852 size2 = size1;
5853 string1 = 0;
5854 size1 = 0;
5855 #ifdef WCHAR
5856 mbs_offset2 = mbs_offset1;
5857 csize2 = csize1;
5858 mbs_offset1 = NULL;
5859 csize1 = 0;
5860 #endif
5862 end1 = string1 + size1;
5863 end2 = string2 + size2;
5865 /* Compute where to stop matching, within the two strings. */
5866 #ifdef WCHAR
5867 if (stop <= csize1)
5869 mcnt = count_mbs_length(mbs_offset1, stop);
5870 end_match_1 = string1 + mcnt;
5871 end_match_2 = string2;
5873 else
5875 if (stop > csize1 + csize2)
5876 stop = csize1 + csize2;
5877 end_match_1 = end1;
5878 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5879 end_match_2 = string2 + mcnt;
5881 if (mcnt < 0)
5882 { /* count_mbs_length return error. */
5883 FREE_VARIABLES ();
5884 return -1;
5886 #else
5887 if (stop <= size1)
5889 end_match_1 = string1 + stop;
5890 end_match_2 = string2;
5892 else
5894 end_match_1 = end1;
5895 end_match_2 = string2 + stop - size1;
5897 #endif /* WCHAR */
5899 /* `p' scans through the pattern as `d' scans through the data.
5900 `dend' is the end of the input string that `d' points within. `d'
5901 is advanced into the following input string whenever necessary, but
5902 this happens before fetching; therefore, at the beginning of the
5903 loop, `d' can be pointing at the end of a string, but it cannot
5904 equal `string2'. */
5905 #ifdef WCHAR
5906 if (size1 > 0 && pos <= csize1)
5908 mcnt = count_mbs_length(mbs_offset1, pos);
5909 d = string1 + mcnt;
5910 dend = end_match_1;
5912 else
5914 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5915 d = string2 + mcnt;
5916 dend = end_match_2;
5919 if (mcnt < 0)
5920 { /* count_mbs_length return error. */
5921 FREE_VARIABLES ();
5922 return -1;
5924 #else
5925 if (size1 > 0 && pos <= size1)
5927 d = string1 + pos;
5928 dend = end_match_1;
5930 else
5932 d = string2 + pos - size1;
5933 dend = end_match_2;
5935 #endif /* WCHAR */
5937 DEBUG_PRINT1 ("The compiled pattern is:\n");
5938 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5939 DEBUG_PRINT1 ("The string to match is: `");
5940 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5941 DEBUG_PRINT1 ("'\n");
5943 /* This loops over pattern commands. It exits by returning from the
5944 function if the match is complete, or it drops through if the match
5945 fails at this starting point in the input data. */
5946 for (;;)
5948 #ifdef _LIBC
5949 DEBUG_PRINT2 ("\n%p: ", p);
5950 #else
5951 DEBUG_PRINT2 ("\n0x%x: ", p);
5952 #endif
5954 if (p == pend)
5955 { /* End of pattern means we might have succeeded. */
5956 DEBUG_PRINT1 ("end of pattern ... ");
5958 /* If we haven't matched the entire string, and we want the
5959 longest match, try backtracking. */
5960 if (d != end_match_2)
5962 /* 1 if this match ends in the same string (string1 or string2)
5963 as the best previous match. */
5964 boolean same_str_p = (FIRST_STRING_P (match_end)
5965 == MATCHING_IN_FIRST_STRING);
5966 /* 1 if this match is the best seen so far. */
5967 boolean best_match_p;
5969 /* AIX compiler got confused when this was combined
5970 with the previous declaration. */
5971 if (same_str_p)
5972 best_match_p = d > match_end;
5973 else
5974 best_match_p = !MATCHING_IN_FIRST_STRING;
5976 DEBUG_PRINT1 ("backtracking.\n");
5978 if (!FAIL_STACK_EMPTY ())
5979 { /* More failure points to try. */
5981 /* If exceeds best match so far, save it. */
5982 if (!best_regs_set || best_match_p)
5984 best_regs_set = true;
5985 match_end = d;
5987 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5989 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5991 best_regstart[mcnt] = regstart[mcnt];
5992 best_regend[mcnt] = regend[mcnt];
5995 goto fail;
5998 /* If no failure points, don't restore garbage. And if
5999 last match is real best match, don't restore second
6000 best one. */
6001 else if (best_regs_set && !best_match_p)
6003 restore_best_regs:
6004 /* Restore best match. It may happen that `dend ==
6005 end_match_1' while the restored d is in string2.
6006 For example, the pattern `x.*y.*z' against the
6007 strings `x-' and `y-z-', if the two strings are
6008 not consecutive in memory. */
6009 DEBUG_PRINT1 ("Restoring best registers.\n");
6011 d = match_end;
6012 dend = ((d >= string1 && d <= end1)
6013 ? end_match_1 : end_match_2);
6015 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
6017 regstart[mcnt] = best_regstart[mcnt];
6018 regend[mcnt] = best_regend[mcnt];
6021 } /* d != end_match_2 */
6023 succeed_label:
6024 DEBUG_PRINT1 ("Accepting match.\n");
6025 /* If caller wants register contents data back, do it. */
6026 if (regs && !bufp->no_sub)
6028 /* Have the register data arrays been allocated? */
6029 if (bufp->regs_allocated == REGS_UNALLOCATED)
6030 { /* No. So allocate them with malloc. We need one
6031 extra element beyond `num_regs' for the `-1' marker
6032 GNU code uses. */
6033 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
6034 regs->start = TALLOC (regs->num_regs, regoff_t);
6035 regs->end = TALLOC (regs->num_regs, regoff_t);
6036 if (regs->start == NULL || regs->end == NULL)
6038 FREE_VARIABLES ();
6039 return -2;
6041 bufp->regs_allocated = REGS_REALLOCATE;
6043 else if (bufp->regs_allocated == REGS_REALLOCATE)
6044 { /* Yes. If we need more elements than were already
6045 allocated, reallocate them. If we need fewer, just
6046 leave it alone. */
6047 if (regs->num_regs < num_regs + 1)
6049 regs->num_regs = num_regs + 1;
6050 RETALLOC (regs->start, regs->num_regs, regoff_t);
6051 RETALLOC (regs->end, regs->num_regs, regoff_t);
6052 if (regs->start == NULL || regs->end == NULL)
6054 FREE_VARIABLES ();
6055 return -2;
6059 else
6061 /* These braces fend off a "empty body in an else-statement"
6062 warning under GCC when assert expands to nothing. */
6063 assert (bufp->regs_allocated == REGS_FIXED);
6066 /* Convert the pointer data in `regstart' and `regend' to
6067 indices. Register zero has to be set differently,
6068 since we haven't kept track of any info for it. */
6069 if (regs->num_regs > 0)
6071 regs->start[0] = pos;
6072 #ifdef WCHAR
6073 if (MATCHING_IN_FIRST_STRING)
6074 regs->end[0] = mbs_offset1 != NULL ?
6075 mbs_offset1[d-string1] : 0;
6076 else
6077 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
6078 mbs_offset2[d-string2] : 0);
6079 #else
6080 regs->end[0] = (MATCHING_IN_FIRST_STRING
6081 ? ((regoff_t) (d - string1))
6082 : ((regoff_t) (d - string2 + size1)));
6083 #endif /* WCHAR */
6086 /* Go through the first `min (num_regs, regs->num_regs)'
6087 registers, since that is all we initialized. */
6088 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
6089 mcnt++)
6091 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
6092 regs->start[mcnt] = regs->end[mcnt] = -1;
6093 else
6095 regs->start[mcnt]
6096 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
6097 regs->end[mcnt]
6098 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
6102 /* If the regs structure we return has more elements than
6103 were in the pattern, set the extra elements to -1. If
6104 we (re)allocated the registers, this is the case,
6105 because we always allocate enough to have at least one
6106 -1 at the end. */
6107 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
6108 regs->start[mcnt] = regs->end[mcnt] = -1;
6109 } /* regs && !bufp->no_sub */
6111 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
6112 nfailure_points_pushed, nfailure_points_popped,
6113 nfailure_points_pushed - nfailure_points_popped);
6114 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
6116 #ifdef WCHAR
6117 if (MATCHING_IN_FIRST_STRING)
6118 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
6119 else
6120 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
6121 csize1;
6122 mcnt -= pos;
6123 #else
6124 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
6125 ? string1
6126 : string2 - size1);
6127 #endif /* WCHAR */
6129 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
6131 FREE_VARIABLES ();
6132 return mcnt;
6135 /* Otherwise match next pattern command. */
6136 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
6138 /* Ignore these. Used to ignore the n of succeed_n's which
6139 currently have n == 0. */
6140 case no_op:
6141 DEBUG_PRINT1 ("EXECUTING no_op.\n");
6142 break;
6144 case succeed:
6145 DEBUG_PRINT1 ("EXECUTING succeed.\n");
6146 goto succeed_label;
6148 /* Match the next n pattern characters exactly. The following
6149 byte in the pattern defines n, and the n bytes after that
6150 are the characters to match. */
6151 case exactn:
6152 #ifdef MBS_SUPPORT
6153 case exactn_bin:
6154 #endif
6155 mcnt = *p++;
6156 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
6158 /* This is written out as an if-else so we don't waste time
6159 testing `translate' inside the loop. */
6160 if (translate)
6164 PREFETCH ();
6165 #ifdef WCHAR
6166 if (*d <= 0xff)
6168 if ((UCHAR_T) translate[(unsigned char) *d++]
6169 != (UCHAR_T) *p++)
6170 goto fail;
6172 else
6174 if (*d++ != (CHAR_T) *p++)
6175 goto fail;
6177 #else
6178 if ((UCHAR_T) translate[(unsigned char) *d++]
6179 != (UCHAR_T) *p++)
6180 goto fail;
6181 #endif /* WCHAR */
6183 while (--mcnt);
6185 else
6189 PREFETCH ();
6190 if (*d++ != (CHAR_T) *p++) goto fail;
6192 while (--mcnt);
6194 SET_REGS_MATCHED ();
6195 break;
6198 /* Match any character except possibly a newline or a null. */
6199 case anychar:
6200 DEBUG_PRINT1 ("EXECUTING anychar.\n");
6202 PREFETCH ();
6204 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
6205 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
6206 goto fail;
6208 SET_REGS_MATCHED ();
6209 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
6210 d++;
6211 break;
6214 case charset:
6215 case charset_not:
6217 register UCHAR_T c;
6218 #ifdef WCHAR
6219 unsigned int i, char_class_length, coll_symbol_length,
6220 equiv_class_length, ranges_length, chars_length, length;
6221 CHAR_T *workp, *workp2, *charset_top;
6222 #define WORK_BUFFER_SIZE 128
6223 CHAR_T str_buf[WORK_BUFFER_SIZE];
6224 # ifdef _LIBC
6225 uint32_t nrules;
6226 # endif /* _LIBC */
6227 #endif /* WCHAR */
6228 boolean not = (re_opcode_t) *(p - 1) == charset_not;
6230 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
6231 PREFETCH ();
6232 c = TRANSLATE (*d); /* The character to match. */
6233 #ifdef WCHAR
6234 # ifdef _LIBC
6235 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
6236 # endif /* _LIBC */
6237 charset_top = p - 1;
6238 char_class_length = *p++;
6239 coll_symbol_length = *p++;
6240 equiv_class_length = *p++;
6241 ranges_length = *p++;
6242 chars_length = *p++;
6243 /* p points charset[6], so the address of the next instruction
6244 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
6245 where l=length of char_classes, m=length of collating_symbol,
6246 n=equivalence_class, o=length of char_range,
6247 p'=length of character. */
6248 workp = p;
6249 /* Update p to indicate the next instruction. */
6250 p += char_class_length + coll_symbol_length+ equiv_class_length +
6251 2*ranges_length + chars_length;
6253 /* match with char_class? */
6254 for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
6256 wctype_t wctype;
6257 uintptr_t alignedp = ((uintptr_t)workp
6258 + __alignof__(wctype_t) - 1)
6259 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6260 wctype = *((wctype_t*)alignedp);
6261 workp += CHAR_CLASS_SIZE;
6262 if (iswctype((wint_t)c, wctype))
6263 goto char_set_matched;
6266 /* match with collating_symbol? */
6267 # ifdef _LIBC
6268 if (nrules != 0)
6270 const unsigned char *extra = (const unsigned char *)
6271 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6273 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6274 workp++)
6276 int32_t *wextra;
6277 wextra = (int32_t*)(extra + *workp++);
6278 for (i = 0; i < *wextra; ++i)
6279 if (TRANSLATE(d[i]) != wextra[1 + i])
6280 break;
6282 if (i == *wextra)
6284 /* Update d, however d will be incremented at
6285 char_set_matched:, we decrement d here. */
6286 d += i - 1;
6287 goto char_set_matched;
6291 else /* (nrules == 0) */
6292 # endif
6293 /* If we can't look up collation data, we use wcscoll
6294 instead. */
6296 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6298 const CHAR_T *backup_d = d, *backup_dend = dend;
6299 length = wcslen(workp);
6301 /* If wcscoll(the collating symbol, whole string) > 0,
6302 any substring of the string never match with the
6303 collating symbol. */
6304 if (wcscoll(workp, d) > 0)
6306 workp += length + 1;
6307 continue;
6310 /* First, we compare the collating symbol with
6311 the first character of the string.
6312 If it don't match, we add the next character to
6313 the compare buffer in turn. */
6314 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6316 int match;
6317 if (d == dend)
6319 if (dend == end_match_2)
6320 break;
6321 d = string2;
6322 dend = end_match_2;
6325 /* add next character to the compare buffer. */
6326 str_buf[i] = TRANSLATE(*d);
6327 str_buf[i+1] = '\0';
6329 match = wcscoll(workp, str_buf);
6330 if (match == 0)
6331 goto char_set_matched;
6333 if (match < 0)
6334 /* (str_buf > workp) indicate (str_buf + X > workp),
6335 because for all X (str_buf + X > str_buf).
6336 So we don't need continue this loop. */
6337 break;
6339 /* Otherwise(str_buf < workp),
6340 (str_buf+next_character) may equals (workp).
6341 So we continue this loop. */
6343 /* not matched */
6344 d = backup_d;
6345 dend = backup_dend;
6346 workp += length + 1;
6349 /* match with equivalence_class? */
6350 # ifdef _LIBC
6351 if (nrules != 0)
6353 const CHAR_T *backup_d = d, *backup_dend = dend;
6354 /* Try to match the equivalence class against
6355 those known to the collate implementation. */
6356 const int32_t *table;
6357 const int32_t *weights;
6358 const int32_t *extra;
6359 const int32_t *indirect;
6360 int32_t idx, idx2;
6361 wint_t *cp;
6362 size_t len;
6364 /* This #include defines a local function! */
6365 # include <locale/weightwc.h>
6367 table = (const int32_t *)
6368 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6369 weights = (const wint_t *)
6370 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6371 extra = (const wint_t *)
6372 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6373 indirect = (const int32_t *)
6374 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6376 /* Write 1 collating element to str_buf, and
6377 get its index. */
6378 idx2 = 0;
6380 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6382 cp = (wint_t*)str_buf;
6383 if (d == dend)
6385 if (dend == end_match_2)
6386 break;
6387 d = string2;
6388 dend = end_match_2;
6390 str_buf[i] = TRANSLATE(*(d+i));
6391 str_buf[i+1] = '\0'; /* sentinel */
6392 idx2 = findidx ((const wint_t**)&cp);
6395 /* Update d, however d will be incremented at
6396 char_set_matched:, we decrement d here. */
6397 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6398 if (d >= dend)
6400 if (dend == end_match_2)
6401 d = dend;
6402 else
6404 d = string2;
6405 dend = end_match_2;
6409 len = weights[idx2];
6411 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6412 workp++)
6414 idx = (int32_t)*workp;
6415 /* We already checked idx != 0 in regex_compile. */
6417 if (idx2 != 0 && len == weights[idx])
6419 int cnt = 0;
6420 while (cnt < len && (weights[idx + 1 + cnt]
6421 == weights[idx2 + 1 + cnt]))
6422 ++cnt;
6424 if (cnt == len)
6425 goto char_set_matched;
6428 /* not matched */
6429 d = backup_d;
6430 dend = backup_dend;
6432 else /* (nrules == 0) */
6433 # endif
6434 /* If we can't look up collation data, we use wcscoll
6435 instead. */
6437 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6439 const CHAR_T *backup_d = d, *backup_dend = dend;
6440 length = wcslen(workp);
6442 /* If wcscoll(the collating symbol, whole string) > 0,
6443 any substring of the string never match with the
6444 collating symbol. */
6445 if (wcscoll(workp, d) > 0)
6447 workp += length + 1;
6448 break;
6451 /* First, we compare the equivalence class with
6452 the first character of the string.
6453 If it don't match, we add the next character to
6454 the compare buffer in turn. */
6455 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6457 int match;
6458 if (d == dend)
6460 if (dend == end_match_2)
6461 break;
6462 d = string2;
6463 dend = end_match_2;
6466 /* add next character to the compare buffer. */
6467 str_buf[i] = TRANSLATE(*d);
6468 str_buf[i+1] = '\0';
6470 match = wcscoll(workp, str_buf);
6472 if (match == 0)
6473 goto char_set_matched;
6475 if (match < 0)
6476 /* (str_buf > workp) indicate (str_buf + X > workp),
6477 because for all X (str_buf + X > str_buf).
6478 So we don't need continue this loop. */
6479 break;
6481 /* Otherwise(str_buf < workp),
6482 (str_buf+next_character) may equals (workp).
6483 So we continue this loop. */
6485 /* not matched */
6486 d = backup_d;
6487 dend = backup_dend;
6488 workp += length + 1;
6492 /* match with char_range? */
6493 #ifdef _LIBC
6494 if (nrules != 0)
6496 uint32_t collseqval;
6497 const char *collseq = (const char *)
6498 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6500 collseqval = collseq_table_lookup (collseq, c);
6502 for (; workp < p - chars_length ;)
6504 uint32_t start_val, end_val;
6506 /* We already compute the collation sequence value
6507 of the characters (or collating symbols). */
6508 start_val = (uint32_t) *workp++; /* range_start */
6509 end_val = (uint32_t) *workp++; /* range_end */
6511 if (start_val <= collseqval && collseqval <= end_val)
6512 goto char_set_matched;
6515 else
6516 #endif
6518 /* We set range_start_char at str_buf[0], range_end_char
6519 at str_buf[4], and compared char at str_buf[2]. */
6520 str_buf[1] = 0;
6521 str_buf[2] = c;
6522 str_buf[3] = 0;
6523 str_buf[5] = 0;
6524 for (; workp < p - chars_length ;)
6526 wchar_t *range_start_char, *range_end_char;
6528 /* match if (range_start_char <= c <= range_end_char). */
6530 /* If range_start(or end) < 0, we assume -range_start(end)
6531 is the offset of the collating symbol which is specified
6532 as the character of the range start(end). */
6534 /* range_start */
6535 if (*workp < 0)
6536 range_start_char = charset_top - (*workp++);
6537 else
6539 str_buf[0] = *workp++;
6540 range_start_char = str_buf;
6543 /* range_end */
6544 if (*workp < 0)
6545 range_end_char = charset_top - (*workp++);
6546 else
6548 str_buf[4] = *workp++;
6549 range_end_char = str_buf + 4;
6552 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6553 wcscoll(str_buf+2, range_end_char) <= 0)
6555 goto char_set_matched;
6559 /* match with char? */
6560 for (; workp < p ; workp++)
6561 if (c == *workp)
6562 goto char_set_matched;
6564 not = !not;
6566 char_set_matched:
6567 if (not) goto fail;
6568 #else
6569 /* Cast to `unsigned' instead of `unsigned char' in case the
6570 bit list is a full 32 bytes long. */
6571 if (c < (unsigned) (*p * BYTEWIDTH)
6572 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6573 not = !not;
6575 p += 1 + *p;
6577 if (!not) goto fail;
6578 #undef WORK_BUFFER_SIZE
6579 #endif /* WCHAR */
6580 SET_REGS_MATCHED ();
6581 d++;
6582 break;
6586 /* The beginning of a group is represented by start_memory.
6587 The arguments are the register number in the next byte, and the
6588 number of groups inner to this one in the next. The text
6589 matched within the group is recorded (in the internal
6590 registers data structure) under the register number. */
6591 case start_memory:
6592 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6593 (long int) *p, (long int) p[1]);
6595 /* Find out if this group can match the empty string. */
6596 p1 = p; /* To send to group_match_null_string_p. */
6598 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6599 REG_MATCH_NULL_STRING_P (reg_info[*p])
6600 = PREFIX(group_match_null_string_p) (&p1, pend, reg_info);
6602 /* Save the position in the string where we were the last time
6603 we were at this open-group operator in case the group is
6604 operated upon by a repetition operator, e.g., with `(a*)*b'
6605 against `ab'; then we want to ignore where we are now in
6606 the string in case this attempt to match fails. */
6607 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6608 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6609 : regstart[*p];
6610 DEBUG_PRINT2 (" old_regstart: %d\n",
6611 POINTER_TO_OFFSET (old_regstart[*p]));
6613 regstart[*p] = d;
6614 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6616 IS_ACTIVE (reg_info[*p]) = 1;
6617 MATCHED_SOMETHING (reg_info[*p]) = 0;
6619 /* Clear this whenever we change the register activity status. */
6620 set_regs_matched_done = 0;
6622 /* This is the new highest active register. */
6623 highest_active_reg = *p;
6625 /* If nothing was active before, this is the new lowest active
6626 register. */
6627 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6628 lowest_active_reg = *p;
6630 /* Move past the register number and inner group count. */
6631 p += 2;
6632 just_past_start_mem = p;
6634 break;
6637 /* The stop_memory opcode represents the end of a group. Its
6638 arguments are the same as start_memory's: the register
6639 number, and the number of inner groups. */
6640 case stop_memory:
6641 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6642 (long int) *p, (long int) p[1]);
6644 /* We need to save the string position the last time we were at
6645 this close-group operator in case the group is operated
6646 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6647 against `aba'; then we want to ignore where we are now in
6648 the string in case this attempt to match fails. */
6649 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6650 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6651 : regend[*p];
6652 DEBUG_PRINT2 (" old_regend: %d\n",
6653 POINTER_TO_OFFSET (old_regend[*p]));
6655 regend[*p] = d;
6656 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6658 /* This register isn't active anymore. */
6659 IS_ACTIVE (reg_info[*p]) = 0;
6661 /* Clear this whenever we change the register activity status. */
6662 set_regs_matched_done = 0;
6664 /* If this was the only register active, nothing is active
6665 anymore. */
6666 if (lowest_active_reg == highest_active_reg)
6668 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6669 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6671 else
6672 { /* We must scan for the new highest active register, since
6673 it isn't necessarily one less than now: consider
6674 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6675 new highest active register is 1. */
6676 UCHAR_T r = *p - 1;
6677 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6678 r--;
6680 /* If we end up at register zero, that means that we saved
6681 the registers as the result of an `on_failure_jump', not
6682 a `start_memory', and we jumped to past the innermost
6683 `stop_memory'. For example, in ((.)*) we save
6684 registers 1 and 2 as a result of the *, but when we pop
6685 back to the second ), we are at the stop_memory 1.
6686 Thus, nothing is active. */
6687 if (r == 0)
6689 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6690 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6692 else
6693 highest_active_reg = r;
6696 /* If just failed to match something this time around with a
6697 group that's operated on by a repetition operator, try to
6698 force exit from the ``loop'', and restore the register
6699 information for this group that we had before trying this
6700 last match. */
6701 if ((!MATCHED_SOMETHING (reg_info[*p])
6702 || just_past_start_mem == p - 1)
6703 && (p + 2) < pend)
6705 boolean is_a_jump_n = false;
6707 p1 = p + 2;
6708 mcnt = 0;
6709 switch ((re_opcode_t) *p1++)
6711 case jump_n:
6712 is_a_jump_n = true;
6713 case pop_failure_jump:
6714 case maybe_pop_jump:
6715 case jump:
6716 case dummy_failure_jump:
6717 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6718 if (is_a_jump_n)
6719 p1 += OFFSET_ADDRESS_SIZE;
6720 break;
6722 default:
6723 /* do nothing */ ;
6725 p1 += mcnt;
6727 /* If the next operation is a jump backwards in the pattern
6728 to an on_failure_jump right before the start_memory
6729 corresponding to this stop_memory, exit from the loop
6730 by forcing a failure after pushing on the stack the
6731 on_failure_jump's jump in the pattern, and d. */
6732 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6733 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6734 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6736 /* If this group ever matched anything, then restore
6737 what its registers were before trying this last
6738 failed match, e.g., with `(a*)*b' against `ab' for
6739 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6740 against `aba' for regend[3].
6742 Also restore the registers for inner groups for,
6743 e.g., `((a*)(b*))*' against `aba' (register 3 would
6744 otherwise get trashed). */
6746 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6748 unsigned r;
6750 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6752 /* Restore this and inner groups' (if any) registers. */
6753 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6754 r++)
6756 regstart[r] = old_regstart[r];
6758 /* xx why this test? */
6759 if (old_regend[r] >= regstart[r])
6760 regend[r] = old_regend[r];
6763 p1++;
6764 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6765 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6767 goto fail;
6771 /* Move past the register number and the inner group count. */
6772 p += 2;
6773 break;
6776 /* \<digit> has been turned into a `duplicate' command which is
6777 followed by the numeric value of <digit> as the register number. */
6778 case duplicate:
6780 register const CHAR_T *d2, *dend2;
6781 int regno = *p++; /* Get which register to match against. */
6782 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6784 /* Can't back reference a group which we've never matched. */
6785 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6786 goto fail;
6788 /* Where in input to try to start matching. */
6789 d2 = regstart[regno];
6791 /* Where to stop matching; if both the place to start and
6792 the place to stop matching are in the same string, then
6793 set to the place to stop, otherwise, for now have to use
6794 the end of the first string. */
6796 dend2 = ((FIRST_STRING_P (regstart[regno])
6797 == FIRST_STRING_P (regend[regno]))
6798 ? regend[regno] : end_match_1);
6799 for (;;)
6801 /* If necessary, advance to next segment in register
6802 contents. */
6803 while (d2 == dend2)
6805 if (dend2 == end_match_2) break;
6806 if (dend2 == regend[regno]) break;
6808 /* End of string1 => advance to string2. */
6809 d2 = string2;
6810 dend2 = regend[regno];
6812 /* At end of register contents => success */
6813 if (d2 == dend2) break;
6815 /* If necessary, advance to next segment in data. */
6816 PREFETCH ();
6818 /* How many characters left in this segment to match. */
6819 mcnt = dend - d;
6821 /* Want how many consecutive characters we can match in
6822 one shot, so, if necessary, adjust the count. */
6823 if (mcnt > dend2 - d2)
6824 mcnt = dend2 - d2;
6826 /* Compare that many; failure if mismatch, else move
6827 past them. */
6828 if (translate
6829 ? PREFIX(bcmp_translate) (d, d2, mcnt, translate)
6830 : memcmp (d, d2, mcnt*sizeof(UCHAR_T)))
6831 goto fail;
6832 d += mcnt, d2 += mcnt;
6834 /* Do this because we've match some characters. */
6835 SET_REGS_MATCHED ();
6838 break;
6841 /* begline matches the empty string at the beginning of the string
6842 (unless `not_bol' is set in `bufp'), and, if
6843 `newline_anchor' is set, after newlines. */
6844 case begline:
6845 DEBUG_PRINT1 ("EXECUTING begline.\n");
6847 if (AT_STRINGS_BEG (d))
6849 if (!bufp->not_bol) break;
6851 else if (d[-1] == '\n' && bufp->newline_anchor)
6853 break;
6855 /* In all other cases, we fail. */
6856 goto fail;
6859 /* endline is the dual of begline. */
6860 case endline:
6861 DEBUG_PRINT1 ("EXECUTING endline.\n");
6863 if (AT_STRINGS_END (d))
6865 if (!bufp->not_eol) break;
6868 /* We have to ``prefetch'' the next character. */
6869 else if ((d == end1 ? *string2 : *d) == '\n'
6870 && bufp->newline_anchor)
6872 break;
6874 goto fail;
6877 /* Match at the very beginning of the data. */
6878 case begbuf:
6879 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6880 if (AT_STRINGS_BEG (d))
6881 break;
6882 goto fail;
6885 /* Match at the very end of the data. */
6886 case endbuf:
6887 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6888 if (AT_STRINGS_END (d))
6889 break;
6890 goto fail;
6893 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6894 pushes NULL as the value for the string on the stack. Then
6895 `pop_failure_point' will keep the current value for the
6896 string, instead of restoring it. To see why, consider
6897 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6898 then the . fails against the \n. But the next thing we want
6899 to do is match the \n against the \n; if we restored the
6900 string value, we would be back at the foo.
6902 Because this is used only in specific cases, we don't need to
6903 check all the things that `on_failure_jump' does, to make
6904 sure the right things get saved on the stack. Hence we don't
6905 share its code. The only reason to push anything on the
6906 stack at all is that otherwise we would have to change
6907 `anychar's code to do something besides goto fail in this
6908 case; that seems worse than this. */
6909 case on_failure_keep_string_jump:
6910 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6912 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6913 #ifdef _LIBC
6914 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6915 #else
6916 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6917 #endif
6919 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6920 break;
6923 /* Uses of on_failure_jump:
6925 Each alternative starts with an on_failure_jump that points
6926 to the beginning of the next alternative. Each alternative
6927 except the last ends with a jump that in effect jumps past
6928 the rest of the alternatives. (They really jump to the
6929 ending jump of the following alternative, because tensioning
6930 these jumps is a hassle.)
6932 Repeats start with an on_failure_jump that points past both
6933 the repetition text and either the following jump or
6934 pop_failure_jump back to this on_failure_jump. */
6935 case on_failure_jump:
6936 on_failure:
6937 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6939 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6940 #ifdef _LIBC
6941 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6942 #else
6943 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6944 #endif
6946 /* If this on_failure_jump comes right before a group (i.e.,
6947 the original * applied to a group), save the information
6948 for that group and all inner ones, so that if we fail back
6949 to this point, the group's information will be correct.
6950 For example, in \(a*\)*\1, we need the preceding group,
6951 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6953 /* We can't use `p' to check ahead because we push
6954 a failure point to `p + mcnt' after we do this. */
6955 p1 = p;
6957 /* We need to skip no_op's before we look for the
6958 start_memory in case this on_failure_jump is happening as
6959 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6960 against aba. */
6961 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6962 p1++;
6964 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6966 /* We have a new highest active register now. This will
6967 get reset at the start_memory we are about to get to,
6968 but we will have saved all the registers relevant to
6969 this repetition op, as described above. */
6970 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6971 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6972 lowest_active_reg = *(p1 + 1);
6975 DEBUG_PRINT1 (":\n");
6976 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6977 break;
6980 /* A smart repeat ends with `maybe_pop_jump'.
6981 We change it to either `pop_failure_jump' or `jump'. */
6982 case maybe_pop_jump:
6983 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6984 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6986 register UCHAR_T *p2 = p;
6988 /* Compare the beginning of the repeat with what in the
6989 pattern follows its end. If we can establish that there
6990 is nothing that they would both match, i.e., that we
6991 would have to backtrack because of (as in, e.g., `a*a')
6992 then we can change to pop_failure_jump, because we'll
6993 never have to backtrack.
6995 This is not true in the case of alternatives: in
6996 `(a|ab)*' we do need to backtrack to the `ab' alternative
6997 (e.g., if the string was `ab'). But instead of trying to
6998 detect that here, the alternative has put on a dummy
6999 failure point which is what we will end up popping. */
7001 /* Skip over open/close-group commands.
7002 If what follows this loop is a ...+ construct,
7003 look at what begins its body, since we will have to
7004 match at least one of that. */
7005 while (1)
7007 if (p2 + 2 < pend
7008 && ((re_opcode_t) *p2 == stop_memory
7009 || (re_opcode_t) *p2 == start_memory))
7010 p2 += 3;
7011 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
7012 && (re_opcode_t) *p2 == dummy_failure_jump)
7013 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
7014 else
7015 break;
7018 p1 = p + mcnt;
7019 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
7020 to the `maybe_finalize_jump' of this case. Examine what
7021 follows. */
7023 /* If we're at the end of the pattern, we can change. */
7024 if (p2 == pend)
7026 /* Consider what happens when matching ":\(.*\)"
7027 against ":/". I don't really understand this code
7028 yet. */
7029 p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
7030 pop_failure_jump;
7031 DEBUG_PRINT1
7032 (" End of pattern: change to `pop_failure_jump'.\n");
7035 else if ((re_opcode_t) *p2 == exactn
7036 #ifdef MBS_SUPPORT
7037 || (re_opcode_t) *p2 == exactn_bin
7038 #endif
7039 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
7041 register UCHAR_T c
7042 = *p2 == (UCHAR_T) endline ? '\n' : p2[2];
7044 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
7045 #ifdef MBS_SUPPORT
7046 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
7047 #endif
7048 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
7050 p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
7051 pop_failure_jump;
7052 #ifdef WCHAR
7053 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
7054 (wint_t) c,
7055 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
7056 #else
7057 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
7058 (char) c,
7059 (char) p1[3+OFFSET_ADDRESS_SIZE]);
7060 #endif
7063 #ifndef WCHAR
7064 else if ((re_opcode_t) p1[3] == charset
7065 || (re_opcode_t) p1[3] == charset_not)
7067 int not = (re_opcode_t) p1[3] == charset_not;
7069 if (c < (unsigned) (p1[4] * BYTEWIDTH)
7070 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
7071 not = !not;
7073 /* `not' is equal to 1 if c would match, which means
7074 that we can't change to pop_failure_jump. */
7075 if (!not)
7077 p[-3] = (unsigned char) pop_failure_jump;
7078 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
7081 #endif /* not WCHAR */
7083 #ifndef WCHAR
7084 else if ((re_opcode_t) *p2 == charset)
7086 /* We win if the first character of the loop is not part
7087 of the charset. */
7088 if ((re_opcode_t) p1[3] == exactn
7089 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
7090 && (p2[2 + p1[5] / BYTEWIDTH]
7091 & (1 << (p1[5] % BYTEWIDTH)))))
7093 p[-3] = (unsigned char) pop_failure_jump;
7094 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
7097 else if ((re_opcode_t) p1[3] == charset_not)
7099 int idx;
7100 /* We win if the charset_not inside the loop
7101 lists every character listed in the charset after. */
7102 for (idx = 0; idx < (int) p2[1]; idx++)
7103 if (! (p2[2 + idx] == 0
7104 || (idx < (int) p1[4]
7105 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
7106 break;
7108 if (idx == p2[1])
7110 p[-3] = (unsigned char) pop_failure_jump;
7111 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
7114 else if ((re_opcode_t) p1[3] == charset)
7116 int idx;
7117 /* We win if the charset inside the loop
7118 has no overlap with the one after the loop. */
7119 for (idx = 0;
7120 idx < (int) p2[1] && idx < (int) p1[4];
7121 idx++)
7122 if ((p2[2 + idx] & p1[5 + idx]) != 0)
7123 break;
7125 if (idx == p2[1] || idx == p1[4])
7127 p[-3] = (unsigned char) pop_failure_jump;
7128 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
7132 #endif /* not WCHAR */
7134 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
7135 if ((re_opcode_t) p[-1] != pop_failure_jump)
7137 p[-1] = (UCHAR_T) jump;
7138 DEBUG_PRINT1 (" Match => jump.\n");
7139 goto unconditional_jump;
7141 /* Note fall through. */
7144 /* The end of a simple repeat has a pop_failure_jump back to
7145 its matching on_failure_jump, where the latter will push a
7146 failure point. The pop_failure_jump takes off failure
7147 points put on by this pop_failure_jump's matching
7148 on_failure_jump; we got through the pattern to here from the
7149 matching on_failure_jump, so didn't fail. */
7150 case pop_failure_jump:
7152 /* We need to pass separate storage for the lowest and
7153 highest registers, even though we don't care about the
7154 actual values. Otherwise, we will restore only one
7155 register from the stack, since lowest will == highest in
7156 `pop_failure_point'. */
7157 active_reg_t dummy_low_reg, dummy_high_reg;
7158 UCHAR_T *pdummy = NULL;
7159 const CHAR_T *sdummy = NULL;
7161 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
7162 POP_FAILURE_POINT (sdummy, pdummy,
7163 dummy_low_reg, dummy_high_reg,
7164 reg_dummy, reg_dummy, reg_info_dummy);
7166 /* Note fall through. */
7168 unconditional_jump:
7169 #ifdef _LIBC
7170 DEBUG_PRINT2 ("\n%p: ", p);
7171 #else
7172 DEBUG_PRINT2 ("\n0x%x: ", p);
7173 #endif
7174 /* Note fall through. */
7176 /* Unconditionally jump (without popping any failure points). */
7177 case jump:
7178 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
7179 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
7180 p += mcnt; /* Do the jump. */
7181 #ifdef _LIBC
7182 DEBUG_PRINT2 ("(to %p).\n", p);
7183 #else
7184 DEBUG_PRINT2 ("(to 0x%x).\n", p);
7185 #endif
7186 break;
7189 /* We need this opcode so we can detect where alternatives end
7190 in `group_match_null_string_p' et al. */
7191 case jump_past_alt:
7192 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
7193 goto unconditional_jump;
7196 /* Normally, the on_failure_jump pushes a failure point, which
7197 then gets popped at pop_failure_jump. We will end up at
7198 pop_failure_jump, also, and with a pattern of, say, `a+', we
7199 are skipping over the on_failure_jump, so we have to push
7200 something meaningless for pop_failure_jump to pop. */
7201 case dummy_failure_jump:
7202 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
7203 /* It doesn't matter what we push for the string here. What
7204 the code at `fail' tests is the value for the pattern. */
7205 PUSH_FAILURE_POINT (NULL, NULL, -2);
7206 goto unconditional_jump;
7209 /* At the end of an alternative, we need to push a dummy failure
7210 point in case we are followed by a `pop_failure_jump', because
7211 we don't want the failure point for the alternative to be
7212 popped. For example, matching `(a|ab)*' against `aab'
7213 requires that we match the `ab' alternative. */
7214 case push_dummy_failure:
7215 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
7216 /* See comments just above at `dummy_failure_jump' about the
7217 two zeroes. */
7218 PUSH_FAILURE_POINT (NULL, NULL, -2);
7219 break;
7221 /* Have to succeed matching what follows at least n times.
7222 After that, handle like `on_failure_jump'. */
7223 case succeed_n:
7224 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7225 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
7227 assert (mcnt >= 0);
7228 /* Originally, this is how many times we HAVE to succeed. */
7229 if (mcnt > 0)
7231 mcnt--;
7232 p += OFFSET_ADDRESS_SIZE;
7233 STORE_NUMBER_AND_INCR (p, mcnt);
7234 #ifdef _LIBC
7235 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
7236 , mcnt);
7237 #else
7238 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
7239 , mcnt);
7240 #endif
7242 else if (mcnt == 0)
7244 #ifdef _LIBC
7245 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
7246 p + OFFSET_ADDRESS_SIZE);
7247 #else
7248 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
7249 p + OFFSET_ADDRESS_SIZE);
7250 #endif /* _LIBC */
7252 #ifdef WCHAR
7253 p[1] = (UCHAR_T) no_op;
7254 #else
7255 p[2] = (UCHAR_T) no_op;
7256 p[3] = (UCHAR_T) no_op;
7257 #endif /* WCHAR */
7258 goto on_failure;
7260 break;
7262 case jump_n:
7263 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7264 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7266 /* Originally, this is how many times we CAN jump. */
7267 if (mcnt)
7269 mcnt--;
7270 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7272 #ifdef _LIBC
7273 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7274 mcnt);
7275 #else
7276 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7277 mcnt);
7278 #endif /* _LIBC */
7279 goto unconditional_jump;
7281 /* If don't have to jump any more, skip over the rest of command. */
7282 else
7283 p += 2 * OFFSET_ADDRESS_SIZE;
7284 break;
7286 case set_number_at:
7288 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7290 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7291 p1 = p + mcnt;
7292 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7293 #ifdef _LIBC
7294 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7295 #else
7296 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7297 #endif
7298 STORE_NUMBER (p1, mcnt);
7299 break;
7302 #if 0
7303 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7304 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7305 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7306 macro and introducing temporary variables works around the bug. */
7308 case wordbound:
7309 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7310 if (AT_WORD_BOUNDARY (d))
7311 break;
7312 goto fail;
7314 case notwordbound:
7315 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7316 if (AT_WORD_BOUNDARY (d))
7317 goto fail;
7318 break;
7319 #else
7320 case wordbound:
7322 boolean prevchar, thischar;
7324 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7325 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7326 break;
7328 prevchar = WORDCHAR_P (d - 1);
7329 thischar = WORDCHAR_P (d);
7330 if (prevchar != thischar)
7331 break;
7332 goto fail;
7335 case notwordbound:
7337 boolean prevchar, thischar;
7339 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7340 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7341 goto fail;
7343 prevchar = WORDCHAR_P (d - 1);
7344 thischar = WORDCHAR_P (d);
7345 if (prevchar != thischar)
7346 goto fail;
7347 break;
7349 #endif
7351 case wordbeg:
7352 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7353 if (!AT_STRINGS_END (d) && WORDCHAR_P (d)
7354 && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7355 break;
7356 goto fail;
7358 case wordend:
7359 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7360 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7361 && (AT_STRINGS_END (d) || !WORDCHAR_P (d)))
7362 break;
7363 goto fail;
7365 #ifdef emacs
7366 case before_dot:
7367 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7368 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7369 goto fail;
7370 break;
7372 case at_dot:
7373 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7374 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7375 goto fail;
7376 break;
7378 case after_dot:
7379 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7380 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7381 goto fail;
7382 break;
7384 case syntaxspec:
7385 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7386 mcnt = *p++;
7387 goto matchsyntax;
7389 case wordchar:
7390 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7391 mcnt = (int) Sword;
7392 matchsyntax:
7393 PREFETCH ();
7394 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7395 d++;
7396 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7397 goto fail;
7398 SET_REGS_MATCHED ();
7399 break;
7401 case notsyntaxspec:
7402 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7403 mcnt = *p++;
7404 goto matchnotsyntax;
7406 case notwordchar:
7407 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7408 mcnt = (int) Sword;
7409 matchnotsyntax:
7410 PREFETCH ();
7411 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7412 d++;
7413 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7414 goto fail;
7415 SET_REGS_MATCHED ();
7416 break;
7418 #else /* not emacs */
7419 case wordchar:
7420 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7421 PREFETCH ();
7422 if (!WORDCHAR_P (d))
7423 goto fail;
7424 SET_REGS_MATCHED ();
7425 d++;
7426 break;
7428 case notwordchar:
7429 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7430 PREFETCH ();
7431 if (WORDCHAR_P (d))
7432 goto fail;
7433 SET_REGS_MATCHED ();
7434 d++;
7435 break;
7436 #endif /* not emacs */
7438 default:
7439 abort ();
7441 continue; /* Successfully executed one pattern command; keep going. */
7444 /* We goto here if a matching operation fails. */
7445 fail:
7446 if (!FAIL_STACK_EMPTY ())
7447 { /* A restart point is known. Restore to that state. */
7448 DEBUG_PRINT1 ("\nFAIL:\n");
7449 POP_FAILURE_POINT (d, p,
7450 lowest_active_reg, highest_active_reg,
7451 regstart, regend, reg_info);
7453 /* If this failure point is a dummy, try the next one. */
7454 if (!p)
7455 goto fail;
7457 /* If we failed to the end of the pattern, don't examine *p. */
7458 assert (p <= pend);
7459 if (p < pend)
7461 boolean is_a_jump_n = false;
7463 /* If failed to a backwards jump that's part of a repetition
7464 loop, need to pop this failure point and use the next one. */
7465 switch ((re_opcode_t) *p)
7467 case jump_n:
7468 is_a_jump_n = true;
7469 case maybe_pop_jump:
7470 case pop_failure_jump:
7471 case jump:
7472 p1 = p + 1;
7473 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7474 p1 += mcnt;
7476 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7477 || (!is_a_jump_n
7478 && (re_opcode_t) *p1 == on_failure_jump))
7479 goto fail;
7480 break;
7481 default:
7482 /* do nothing */ ;
7486 if (d >= string1 && d <= end1)
7487 dend = end_match_1;
7489 else
7490 break; /* Matching at this starting point really fails. */
7491 } /* for (;;) */
7493 if (best_regs_set)
7494 goto restore_best_regs;
7496 FREE_VARIABLES ();
7498 return -1; /* Failure to match. */
7499 } /* re_match_2 */
7501 /* Subroutine definitions for re_match_2. */
7504 /* We are passed P pointing to a register number after a start_memory.
7506 Return true if the pattern up to the corresponding stop_memory can
7507 match the empty string, and false otherwise.
7509 If we find the matching stop_memory, sets P to point to one past its number.
7510 Otherwise, sets P to an undefined byte less than or equal to END.
7512 We don't handle duplicates properly (yet). */
7514 static boolean
7515 PREFIX(group_match_null_string_p) (p, end, reg_info)
7516 UCHAR_T **p, *end;
7517 PREFIX(register_info_type) *reg_info;
7519 int mcnt;
7520 /* Point to after the args to the start_memory. */
7521 UCHAR_T *p1 = *p + 2;
7523 while (p1 < end)
7525 /* Skip over opcodes that can match nothing, and return true or
7526 false, as appropriate, when we get to one that can't, or to the
7527 matching stop_memory. */
7529 switch ((re_opcode_t) *p1)
7531 /* Could be either a loop or a series of alternatives. */
7532 case on_failure_jump:
7533 p1++;
7534 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7536 /* If the next operation is not a jump backwards in the
7537 pattern. */
7539 if (mcnt >= 0)
7541 /* Go through the on_failure_jumps of the alternatives,
7542 seeing if any of the alternatives cannot match nothing.
7543 The last alternative starts with only a jump,
7544 whereas the rest start with on_failure_jump and end
7545 with a jump, e.g., here is the pattern for `a|b|c':
7547 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7548 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7549 /exactn/1/c
7551 So, we have to first go through the first (n-1)
7552 alternatives and then deal with the last one separately. */
7555 /* Deal with the first (n-1) alternatives, which start
7556 with an on_failure_jump (see above) that jumps to right
7557 past a jump_past_alt. */
7559 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7560 jump_past_alt)
7562 /* `mcnt' holds how many bytes long the alternative
7563 is, including the ending `jump_past_alt' and
7564 its number. */
7566 if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt -
7567 (1 + OFFSET_ADDRESS_SIZE),
7568 reg_info))
7569 return false;
7571 /* Move to right after this alternative, including the
7572 jump_past_alt. */
7573 p1 += mcnt;
7575 /* Break if it's the beginning of an n-th alternative
7576 that doesn't begin with an on_failure_jump. */
7577 if ((re_opcode_t) *p1 != on_failure_jump)
7578 break;
7580 /* Still have to check that it's not an n-th
7581 alternative that starts with an on_failure_jump. */
7582 p1++;
7583 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7584 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7585 jump_past_alt)
7587 /* Get to the beginning of the n-th alternative. */
7588 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7589 break;
7593 /* Deal with the last alternative: go back and get number
7594 of the `jump_past_alt' just before it. `mcnt' contains
7595 the length of the alternative. */
7596 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7598 if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt, reg_info))
7599 return false;
7601 p1 += mcnt; /* Get past the n-th alternative. */
7602 } /* if mcnt > 0 */
7603 break;
7606 case stop_memory:
7607 assert (p1[1] == **p);
7608 *p = p1 + 2;
7609 return true;
7612 default:
7613 if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7614 return false;
7616 } /* while p1 < end */
7618 return false;
7619 } /* group_match_null_string_p */
7622 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7623 It expects P to be the first byte of a single alternative and END one
7624 byte past the last. The alternative can contain groups. */
7626 static boolean
7627 PREFIX(alt_match_null_string_p) (p, end, reg_info)
7628 UCHAR_T *p, *end;
7629 PREFIX(register_info_type) *reg_info;
7631 int mcnt;
7632 UCHAR_T *p1 = p;
7634 while (p1 < end)
7636 /* Skip over opcodes that can match nothing, and break when we get
7637 to one that can't. */
7639 switch ((re_opcode_t) *p1)
7641 /* It's a loop. */
7642 case on_failure_jump:
7643 p1++;
7644 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7645 p1 += mcnt;
7646 break;
7648 default:
7649 if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7650 return false;
7652 } /* while p1 < end */
7654 return true;
7655 } /* alt_match_null_string_p */
7658 /* Deals with the ops common to group_match_null_string_p and
7659 alt_match_null_string_p.
7661 Sets P to one after the op and its arguments, if any. */
7663 static boolean
7664 PREFIX(common_op_match_null_string_p) (p, end, reg_info)
7665 UCHAR_T **p, *end;
7666 PREFIX(register_info_type) *reg_info;
7668 int mcnt;
7669 boolean ret;
7670 int reg_no;
7671 UCHAR_T *p1 = *p;
7673 switch ((re_opcode_t) *p1++)
7675 case no_op:
7676 case begline:
7677 case endline:
7678 case begbuf:
7679 case endbuf:
7680 case wordbeg:
7681 case wordend:
7682 case wordbound:
7683 case notwordbound:
7684 #ifdef emacs
7685 case before_dot:
7686 case at_dot:
7687 case after_dot:
7688 #endif
7689 break;
7691 case start_memory:
7692 reg_no = *p1;
7693 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7694 ret = PREFIX(group_match_null_string_p) (&p1, end, reg_info);
7696 /* Have to set this here in case we're checking a group which
7697 contains a group and a back reference to it. */
7699 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7700 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7702 if (!ret)
7703 return false;
7704 break;
7706 /* If this is an optimized succeed_n for zero times, make the jump. */
7707 case jump:
7708 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7709 if (mcnt >= 0)
7710 p1 += mcnt;
7711 else
7712 return false;
7713 break;
7715 case succeed_n:
7716 /* Get to the number of times to succeed. */
7717 p1 += OFFSET_ADDRESS_SIZE;
7718 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7720 if (mcnt == 0)
7722 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7723 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7724 p1 += mcnt;
7726 else
7727 return false;
7728 break;
7730 case duplicate:
7731 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7732 return false;
7733 break;
7735 case set_number_at:
7736 p1 += 2 * OFFSET_ADDRESS_SIZE;
7738 default:
7739 /* All other opcodes mean we cannot match the empty string. */
7740 return false;
7743 *p = p1;
7744 return true;
7745 } /* common_op_match_null_string_p */
7748 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7749 bytes; nonzero otherwise. */
7751 static int
7752 PREFIX(bcmp_translate) (s1, s2, len, translate)
7753 const CHAR_T *s1, *s2;
7754 register int len;
7755 RE_TRANSLATE_TYPE translate;
7757 register const UCHAR_T *p1 = (const UCHAR_T *) s1;
7758 register const UCHAR_T *p2 = (const UCHAR_T *) s2;
7759 while (len)
7761 #ifdef WCHAR
7762 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7763 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7764 return 1;
7765 #else /* BYTE */
7766 if (translate[*p1++] != translate[*p2++]) return 1;
7767 #endif /* WCHAR */
7768 len--;
7770 return 0;
7774 #else /* not INSIDE_RECURSION */
7776 /* Entry points for GNU code. */
7778 /* re_compile_pattern is the GNU regular expression compiler: it
7779 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7780 Returns 0 if the pattern was valid, otherwise an error string.
7782 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7783 are set in BUFP on entry.
7785 We call regex_compile to do the actual compilation. */
7787 const char *
7788 re_compile_pattern (pattern, length, bufp)
7789 const char *pattern;
7790 size_t length;
7791 struct re_pattern_buffer *bufp;
7793 reg_errcode_t ret;
7795 /* GNU code is written to assume at least RE_NREGS registers will be set
7796 (and at least one extra will be -1). */
7797 bufp->regs_allocated = REGS_UNALLOCATED;
7799 /* And GNU code determines whether or not to get register information
7800 by passing null for the REGS argument to re_match, etc., not by
7801 setting no_sub. */
7802 bufp->no_sub = 0;
7804 /* Match anchors at newline. */
7805 bufp->newline_anchor = 1;
7807 # ifdef MBS_SUPPORT
7808 if (MB_CUR_MAX != 1)
7809 ret = wcs_regex_compile (pattern, length, re_syntax_options, bufp);
7810 else
7811 # endif
7812 ret = byte_regex_compile (pattern, length, re_syntax_options, bufp);
7814 if (!ret)
7815 return NULL;
7816 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7818 #ifdef _LIBC
7819 weak_alias (__re_compile_pattern, re_compile_pattern)
7820 #endif
7822 /* Entry points compatible with 4.2 BSD regex library. We don't define
7823 them unless specifically requested. */
7825 #if defined _REGEX_RE_COMP || defined _LIBC
7827 /* BSD has one and only one pattern buffer. */
7828 static struct re_pattern_buffer re_comp_buf;
7830 char *
7831 #ifdef _LIBC
7832 /* Make these definitions weak in libc, so POSIX programs can redefine
7833 these names if they don't use our functions, and still use
7834 regcomp/regexec below without link errors. */
7835 weak_function
7836 #endif
7837 re_comp (s)
7838 const char *s;
7840 reg_errcode_t ret;
7842 if (!s)
7844 if (!re_comp_buf.buffer)
7845 return gettext ("No previous regular expression");
7846 return 0;
7849 if (!re_comp_buf.buffer)
7851 re_comp_buf.buffer = (unsigned char *) malloc (200);
7852 if (re_comp_buf.buffer == NULL)
7853 return (char *) gettext (re_error_msgid
7854 + re_error_msgid_idx[(int) REG_ESPACE]);
7855 re_comp_buf.allocated = 200;
7857 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7858 if (re_comp_buf.fastmap == NULL)
7859 return (char *) gettext (re_error_msgid
7860 + re_error_msgid_idx[(int) REG_ESPACE]);
7863 /* Since `re_exec' always passes NULL for the `regs' argument, we
7864 don't need to initialize the pattern buffer fields which affect it. */
7866 /* Match anchors at newlines. */
7867 re_comp_buf.newline_anchor = 1;
7869 # ifdef MBS_SUPPORT
7870 if (MB_CUR_MAX != 1)
7871 ret = wcs_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7872 else
7873 # endif
7874 ret = byte_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7876 if (!ret)
7877 return NULL;
7879 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7880 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7885 #ifdef _LIBC
7886 weak_function
7887 #endif
7888 re_exec (s)
7889 const char *s;
7891 const int len = strlen (s);
7892 return
7893 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7896 #endif /* _REGEX_RE_COMP */
7898 /* POSIX.2 functions. Don't define these for Emacs. */
7900 #ifndef emacs
7902 /* regcomp takes a regular expression as a string and compiles it.
7904 PREG is a regex_t *. We do not expect any fields to be initialized,
7905 since POSIX says we shouldn't. Thus, we set
7907 `buffer' to the compiled pattern;
7908 `used' to the length of the compiled pattern;
7909 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7910 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7911 RE_SYNTAX_POSIX_BASIC;
7912 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7913 `fastmap' to an allocated space for the fastmap;
7914 `fastmap_accurate' to zero;
7915 `re_nsub' to the number of subexpressions in PATTERN.
7917 PATTERN is the address of the pattern string.
7919 CFLAGS is a series of bits which affect compilation.
7921 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7922 use POSIX basic syntax.
7924 If REG_NEWLINE is set, then . and [^...] don't match newline.
7925 Also, regexec will try a match beginning after every newline.
7927 If REG_ICASE is set, then we considers upper- and lowercase
7928 versions of letters to be equivalent when matching.
7930 If REG_NOSUB is set, then when PREG is passed to regexec, that
7931 routine will report only success or failure, and nothing about the
7932 registers.
7934 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7935 the return codes and their meanings.) */
7938 regcomp (preg, pattern, cflags)
7939 regex_t *preg;
7940 const char *pattern;
7941 int cflags;
7943 reg_errcode_t ret;
7944 reg_syntax_t syntax
7945 = (cflags & REG_EXTENDED) ?
7946 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7948 /* regex_compile will allocate the space for the compiled pattern. */
7949 preg->buffer = 0;
7950 preg->allocated = 0;
7951 preg->used = 0;
7953 /* Try to allocate space for the fastmap. */
7954 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7956 if (cflags & REG_ICASE)
7958 unsigned i;
7960 preg->translate
7961 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7962 * sizeof (*(RE_TRANSLATE_TYPE)0));
7963 if (preg->translate == NULL)
7964 return (int) REG_ESPACE;
7966 /* Map uppercase characters to corresponding lowercase ones. */
7967 for (i = 0; i < CHAR_SET_SIZE; i++)
7968 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7970 else
7971 preg->translate = NULL;
7973 /* If REG_NEWLINE is set, newlines are treated differently. */
7974 if (cflags & REG_NEWLINE)
7975 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7976 syntax &= ~RE_DOT_NEWLINE;
7977 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7978 /* It also changes the matching behavior. */
7979 preg->newline_anchor = 1;
7981 else
7982 preg->newline_anchor = 0;
7984 preg->no_sub = !!(cflags & REG_NOSUB);
7986 /* POSIX says a null character in the pattern terminates it, so we
7987 can use strlen here in compiling the pattern. */
7988 # ifdef MBS_SUPPORT
7989 if (MB_CUR_MAX != 1)
7990 ret = wcs_regex_compile (pattern, strlen (pattern), syntax, preg);
7991 else
7992 # endif
7993 ret = byte_regex_compile (pattern, strlen (pattern), syntax, preg);
7995 /* POSIX doesn't distinguish between an unmatched open-group and an
7996 unmatched close-group: both are REG_EPAREN. */
7997 if (ret == REG_ERPAREN) ret = REG_EPAREN;
7999 if (ret == REG_NOERROR && preg->fastmap)
8001 /* Compute the fastmap now, since regexec cannot modify the pattern
8002 buffer. */
8003 if (re_compile_fastmap (preg) == -2)
8005 /* Some error occurred while computing the fastmap, just forget
8006 about it. */
8007 free (preg->fastmap);
8008 preg->fastmap = NULL;
8012 return (int) ret;
8014 #ifdef _LIBC
8015 weak_alias (__regcomp, regcomp)
8016 #endif
8019 /* regexec searches for a given pattern, specified by PREG, in the
8020 string STRING.
8022 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
8023 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
8024 least NMATCH elements, and we set them to the offsets of the
8025 corresponding matched substrings.
8027 EFLAGS specifies `execution flags' which affect matching: if
8028 REG_NOTBOL is set, then ^ does not match at the beginning of the
8029 string; if REG_NOTEOL is set, then $ does not match at the end.
8031 We return 0 if we find a match and REG_NOMATCH if not. */
8034 regexec (preg, string, nmatch, pmatch, eflags)
8035 const regex_t *preg;
8036 const char *string;
8037 size_t nmatch;
8038 regmatch_t pmatch[];
8039 int eflags;
8041 int ret;
8042 struct re_registers regs;
8043 regex_t private_preg;
8044 int len = strlen (string);
8045 boolean want_reg_info = !preg->no_sub && nmatch > 0;
8047 private_preg = *preg;
8049 private_preg.not_bol = !!(eflags & REG_NOTBOL);
8050 private_preg.not_eol = !!(eflags & REG_NOTEOL);
8052 /* The user has told us exactly how many registers to return
8053 information about, via `nmatch'. We have to pass that on to the
8054 matching routines. */
8055 private_preg.regs_allocated = REGS_FIXED;
8057 if (want_reg_info)
8059 regs.num_regs = nmatch;
8060 regs.start = TALLOC (nmatch * 2, regoff_t);
8061 if (regs.start == NULL)
8062 return (int) REG_NOMATCH;
8063 regs.end = regs.start + nmatch;
8066 /* Perform the searching operation. */
8067 ret = re_search (&private_preg, string, len,
8068 /* start: */ 0, /* range: */ len,
8069 want_reg_info ? &regs : (struct re_registers *) 0);
8071 /* Copy the register information to the POSIX structure. */
8072 if (want_reg_info)
8074 if (ret >= 0)
8076 unsigned r;
8078 for (r = 0; r < nmatch; r++)
8080 pmatch[r].rm_so = regs.start[r];
8081 pmatch[r].rm_eo = regs.end[r];
8085 /* If we needed the temporary register info, free the space now. */
8086 free (regs.start);
8089 /* We want zero return to mean success, unlike `re_search'. */
8090 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
8092 #ifdef _LIBC
8093 weak_alias (__regexec, regexec)
8094 #endif
8097 /* Returns a message corresponding to an error code, ERRCODE, returned
8098 from either regcomp or regexec. We don't use PREG here. */
8100 size_t
8101 regerror (errcode, preg, errbuf, errbuf_size)
8102 int errcode;
8103 const regex_t *preg;
8104 char *errbuf;
8105 size_t errbuf_size;
8107 const char *msg;
8108 size_t msg_size;
8110 if (errcode < 0
8111 || errcode >= (int) (sizeof (re_error_msgid_idx)
8112 / sizeof (re_error_msgid_idx[0])))
8113 /* Only error codes returned by the rest of the code should be passed
8114 to this routine. If we are given anything else, or if other regex
8115 code generates an invalid error code, then the program has a bug.
8116 Dump core so we can fix it. */
8117 abort ();
8119 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
8121 msg_size = strlen (msg) + 1; /* Includes the null. */
8123 if (errbuf_size != 0)
8125 if (msg_size > errbuf_size)
8127 #if defined HAVE_MEMPCPY || defined _LIBC
8128 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
8129 #else
8130 memcpy (errbuf, msg, errbuf_size - 1);
8131 errbuf[errbuf_size - 1] = 0;
8132 #endif
8134 else
8135 memcpy (errbuf, msg, msg_size);
8138 return msg_size;
8140 #ifdef _LIBC
8141 weak_alias (__regerror, regerror)
8142 #endif
8145 /* Free dynamically allocated space used by PREG. */
8147 void
8148 regfree (preg)
8149 regex_t *preg;
8151 if (preg->buffer != NULL)
8152 free (preg->buffer);
8153 preg->buffer = NULL;
8155 preg->allocated = 0;
8156 preg->used = 0;
8158 if (preg->fastmap != NULL)
8159 free (preg->fastmap);
8160 preg->fastmap = NULL;
8161 preg->fastmap_accurate = 0;
8163 if (preg->translate != NULL)
8164 free (preg->translate);
8165 preg->translate = NULL;
8167 #ifdef _LIBC
8168 weak_alias (__regfree, regfree)
8169 #endif
8171 #endif /* not emacs */
8173 #endif /* not INSIDE_RECURSION */
8176 #undef STORE_NUMBER
8177 #undef STORE_NUMBER_AND_INCR
8178 #undef EXTRACT_NUMBER
8179 #undef EXTRACT_NUMBER_AND_INCR
8181 #undef DEBUG_PRINT_COMPILED_PATTERN
8182 #undef DEBUG_PRINT_DOUBLE_STRING
8184 #undef INIT_FAIL_STACK
8185 #undef RESET_FAIL_STACK
8186 #undef DOUBLE_FAIL_STACK
8187 #undef PUSH_PATTERN_OP
8188 #undef PUSH_FAILURE_POINTER
8189 #undef PUSH_FAILURE_INT
8190 #undef PUSH_FAILURE_ELT
8191 #undef POP_FAILURE_POINTER
8192 #undef POP_FAILURE_INT
8193 #undef POP_FAILURE_ELT
8194 #undef DEBUG_PUSH
8195 #undef DEBUG_POP
8196 #undef PUSH_FAILURE_POINT
8197 #undef POP_FAILURE_POINT
8199 #undef REG_UNSET_VALUE
8200 #undef REG_UNSET
8202 #undef PATFETCH
8203 #undef PATFETCH_RAW
8204 #undef PATUNFETCH
8205 #undef TRANSLATE
8207 #undef INIT_BUF_SIZE
8208 #undef GET_BUFFER_SPACE
8209 #undef BUF_PUSH
8210 #undef BUF_PUSH_2
8211 #undef BUF_PUSH_3
8212 #undef STORE_JUMP
8213 #undef STORE_JUMP2
8214 #undef INSERT_JUMP
8215 #undef INSERT_JUMP2
8216 #undef EXTEND_BUFFER
8217 #undef GET_UNSIGNED_NUMBER
8218 #undef FREE_STACK_RETURN
8220 # undef POINTER_TO_OFFSET
8221 # undef MATCHING_IN_FRST_STRING
8222 # undef PREFETCH
8223 # undef AT_STRINGS_BEG
8224 # undef AT_STRINGS_END
8225 # undef WORDCHAR_P
8226 # undef FREE_VAR
8227 # undef FREE_VARIABLES
8228 # undef NO_HIGHEST_ACTIVE_REG
8229 # undef NO_LOWEST_ACTIVE_REG
8231 # undef CHAR_T
8232 # undef UCHAR_T
8233 # undef COMPILED_BUFFER_VAR
8234 # undef OFFSET_ADDRESS_SIZE
8235 # undef CHAR_CLASS_SIZE
8236 # undef PREFIX
8237 # undef ARG_PREFIX
8238 # undef PUT_CHAR
8239 # undef BYTE
8240 # undef WCHAR
8242 # define DEFINED_ONCE