*** empty log message ***
[coreutils.git] / lib / regex.c
blob22c4ddcc73a27f41d021d111c2bf534aef5aa39d
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 #if defined STDC_HEADERS && !defined emacs
43 # include <stddef.h>
44 #else
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
47 #endif
49 #define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
51 /* For platform which support the ISO C amendement 1 functionality we
52 support user defined character classes. */
53 #if defined _LIBC || WIDE_CHAR_SUPPORT
54 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
55 # include <wchar.h>
56 # include <wctype.h>
57 #endif
59 /* This is for multi byte string support. */
60 #ifdef MBS_SUPPORT
61 # define CHAR_TYPE wchar_t
62 # define US_CHAR_TYPE wchar_t/* unsigned character type */
63 # define COMPILED_BUFFER_VAR wc_buffer
64 # define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
65 # define CHAR_CLASS_SIZE ((__alignof__(wctype_t)+sizeof(wctype_t))/sizeof(CHAR_TYPE)+1)
66 # define PUT_CHAR(c) \
67 do { \
68 if (MB_CUR_MAX == 1) \
69 putchar (c); \
70 else \
71 printf ("%C", (wint_t) c); /* Should we use wide stream?? */ \
72 } while (0)
73 # define TRUE 1
74 # define FALSE 0
75 #else
76 # define CHAR_TYPE char
77 # define US_CHAR_TYPE unsigned char /* unsigned character type */
78 # define COMPILED_BUFFER_VAR bufp->buffer
79 # define OFFSET_ADDRESS_SIZE 2
80 # define PUT_CHAR(c) putchar (c)
81 #endif /* MBS_SUPPORT */
83 #ifdef _LIBC
84 /* We have to keep the namespace clean. */
85 # define regfree(preg) __regfree (preg)
86 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
87 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
88 # define regerror(errcode, preg, errbuf, errbuf_size) \
89 __regerror(errcode, preg, errbuf, errbuf_size)
90 # define re_set_registers(bu, re, nu, st, en) \
91 __re_set_registers (bu, re, nu, st, en)
92 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
93 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
94 # define re_match(bufp, string, size, pos, regs) \
95 __re_match (bufp, string, size, pos, regs)
96 # define re_search(bufp, string, size, startpos, range, regs) \
97 __re_search (bufp, string, size, startpos, range, regs)
98 # define re_compile_pattern(pattern, length, bufp) \
99 __re_compile_pattern (pattern, length, bufp)
100 # define re_set_syntax(syntax) __re_set_syntax (syntax)
101 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
102 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
103 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
105 # define btowc __btowc
107 /* We are also using some library internals. */
108 # include <locale/localeinfo.h>
109 # include <locale/elem-hash.h>
110 # include <langinfo.h>
111 # include <locale/coll-lookup.h>
112 #endif
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
117 # ifdef _LIBC
118 # undef gettext
119 # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
120 # endif
121 #else
122 # define gettext(msgid) (msgid)
123 #endif
125 #ifndef gettext_noop
126 /* This define is so xgettext can find the internationalizable
127 strings. */
128 # define gettext_noop(String) String
129 #endif
131 /* The `emacs' switch turns on certain matching commands
132 that make sense only in Emacs. */
133 #ifdef emacs
135 # include "lisp.h"
136 # include "buffer.h"
137 # include "syntax.h"
139 #else /* not emacs */
141 /* If we are not linking with Emacs proper,
142 we can't use the relocating allocator
143 even if config.h says that we can. */
144 # undef REL_ALLOC
146 # if defined STDC_HEADERS || defined _LIBC
147 # include <stdlib.h>
148 # else
149 char *malloc ();
150 char *realloc ();
151 # endif
153 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
154 If nothing else has been done, use the method below. */
155 # ifdef INHIBIT_STRING_HEADER
156 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
157 # if !defined bzero && !defined bcopy
158 # undef INHIBIT_STRING_HEADER
159 # endif
160 # endif
161 # endif
163 /* This is the normal way of making sure we have a bcopy and a bzero.
164 This is used in most programs--a few other programs avoid this
165 by defining INHIBIT_STRING_HEADER. */
166 # ifndef INHIBIT_STRING_HEADER
167 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
168 # include <string.h>
169 # ifndef bzero
170 # ifndef _LIBC
171 # define bzero(s, n) (memset (s, '\0', n), (s))
172 # else
173 # define bzero(s, n) __bzero (s, n)
174 # endif
175 # endif
176 # else
177 # include <strings.h>
178 # ifndef memcmp
179 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
180 # endif
181 # ifndef memcpy
182 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
183 # endif
184 # endif
185 # endif
187 /* Define the syntax stuff for \<, \>, etc. */
189 /* This must be nonzero for the wordchar and notwordchar pattern
190 commands in re_match_2. */
191 # ifndef Sword
192 # define Sword 1
193 # endif
195 # ifdef SWITCH_ENUM_BUG
196 # define SWITCH_ENUM_CAST(x) ((int)(x))
197 # else
198 # define SWITCH_ENUM_CAST(x) (x)
199 # endif
201 #endif /* not emacs */
203 #if defined _LIBC || HAVE_LIMITS_H
204 # include <limits.h>
205 #endif
207 #ifndef MB_LEN_MAX
208 # define MB_LEN_MAX 1
209 #endif
211 /* Get the interface, including the syntax bits. */
212 #include <regex.h>
214 /* isalpha etc. are used for the character classes. */
215 #include <ctype.h>
217 /* Jim Meyering writes:
219 "... Some ctype macros are valid only for character codes that
220 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
221 using /bin/cc or gcc but without giving an ansi option). So, all
222 ctype uses should be through macros like ISPRINT... If
223 STDC_HEADERS is defined, then autoconf has verified that the ctype
224 macros don't need to be guarded with references to isascii. ...
225 Defining isascii to 1 should let any compiler worth its salt
226 eliminate the && through constant folding."
227 Solaris defines some of these symbols so we must undefine them first. */
229 #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
230 # define IN_CTYPE_DOMAIN(c) 1
231 #else
232 # define IN_CTYPE_DOMAIN(c) isascii(c)
233 #endif
235 #ifdef isblank
236 # define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
237 #else
238 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
239 #endif
240 #ifdef isgraph
241 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
242 #else
243 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
244 #endif
246 #undef ISPRINT
247 #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
248 #define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
249 #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
250 #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
251 #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
252 #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
253 #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
254 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
255 #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
256 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
258 #ifdef _tolower
259 # define TOLOWER(c) _tolower(c)
260 #else
261 # define TOLOWER(c) tolower(c)
262 #endif
264 #ifndef NULL
265 # define NULL (void *)0
266 #endif
268 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
269 since ours (we hope) works properly with all combinations of
270 machines, compilers, `char' and `unsigned char' argument types.
271 (Per Bothner suggested the basic approach.) */
272 #undef SIGN_EXTEND_CHAR
273 #if __STDC__
274 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
275 #else /* not __STDC__ */
276 /* As in Harbison and Steele. */
277 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
278 #endif
280 #ifndef emacs
281 /* How many characters in the character set. */
282 # define CHAR_SET_SIZE 256
284 # ifdef SYNTAX_TABLE
286 extern char *re_syntax_table;
288 # else /* not SYNTAX_TABLE */
290 static char re_syntax_table[CHAR_SET_SIZE];
292 static void init_syntax_once PARAMS ((void));
294 static void
295 init_syntax_once ()
297 register int c;
298 static int done = 0;
300 if (done)
301 return;
302 bzero (re_syntax_table, sizeof re_syntax_table);
304 for (c = 0; c < CHAR_SET_SIZE; ++c)
305 if (ISALNUM (c))
306 re_syntax_table[c] = Sword;
308 re_syntax_table['_'] = Sword;
310 done = 1;
313 # endif /* not SYNTAX_TABLE */
315 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
317 #endif /* emacs */
319 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
320 use `alloca' instead of `malloc'. This is because using malloc in
321 re_search* or re_match* could cause memory leaks when C-g is used in
322 Emacs; also, malloc is slower and causes storage fragmentation. On
323 the other hand, malloc is more portable, and easier to debug.
325 Because we sometimes use alloca, some routines have to be macros,
326 not functions -- `alloca'-allocated space disappears at the end of the
327 function it is called in. */
329 #ifdef REGEX_MALLOC
331 # define REGEX_ALLOCATE malloc
332 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
333 # define REGEX_FREE free
335 #else /* not REGEX_MALLOC */
337 /* Emacs already defines alloca, sometimes. */
338 # ifndef alloca
340 /* Make alloca work the best possible way. */
341 # ifdef __GNUC__
342 # define alloca __builtin_alloca
343 # else /* not __GNUC__ */
344 # if HAVE_ALLOCA_H
345 # include <alloca.h>
346 # endif /* HAVE_ALLOCA_H */
347 # endif /* not __GNUC__ */
349 # endif /* not alloca */
351 # define REGEX_ALLOCATE alloca
353 /* Assumes a `char *destination' variable. */
354 # define REGEX_REALLOCATE(source, osize, nsize) \
355 (destination = (char *) alloca (nsize), \
356 memcpy (destination, source, osize))
358 /* No need to do anything to free, after alloca. */
359 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
361 #endif /* not REGEX_MALLOC */
363 /* Define how to allocate the failure stack. */
365 #if defined REL_ALLOC && defined REGEX_MALLOC
367 # define REGEX_ALLOCATE_STACK(size) \
368 r_alloc (&failure_stack_ptr, (size))
369 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
370 r_re_alloc (&failure_stack_ptr, (nsize))
371 # define REGEX_FREE_STACK(ptr) \
372 r_alloc_free (&failure_stack_ptr)
374 #else /* not using relocating allocator */
376 # ifdef REGEX_MALLOC
378 # define REGEX_ALLOCATE_STACK malloc
379 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
380 # define REGEX_FREE_STACK free
382 # else /* not REGEX_MALLOC */
384 # define REGEX_ALLOCATE_STACK alloca
386 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
387 REGEX_REALLOCATE (source, osize, nsize)
388 /* No need to explicitly free anything. */
389 # define REGEX_FREE_STACK(arg)
391 # endif /* not REGEX_MALLOC */
392 #endif /* not using relocating allocator */
395 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
396 `string1' or just past its end. This works if PTR is NULL, which is
397 a good thing. */
398 #define FIRST_STRING_P(ptr) \
399 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
401 /* (Re)Allocate N items of type T using malloc, or fail. */
402 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
403 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
404 #define RETALLOC_IF(addr, n, t) \
405 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
406 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
408 #define BYTEWIDTH 8 /* In bits. */
410 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
412 #undef MAX
413 #undef MIN
414 #define MAX(a, b) ((a) > (b) ? (a) : (b))
415 #define MIN(a, b) ((a) < (b) ? (a) : (b))
417 typedef char boolean;
418 #define false 0
419 #define true 1
421 static int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
422 const char *string1, int size1,
423 const char *string2, int size2,
424 int pos,
425 struct re_registers *regs,
426 int stop));
428 /* These are the command codes that appear in compiled regular
429 expressions. Some opcodes are followed by argument bytes. A
430 command code can specify any interpretation whatsoever for its
431 arguments. Zero bytes may appear in the compiled regular expression. */
433 typedef enum
435 no_op = 0,
437 /* Succeed right away--no more backtracking. */
438 succeed,
440 /* Followed by one byte giving n, then by n literal bytes. */
441 exactn,
443 #ifdef MBS_SUPPORT
444 /* Same as exactn, but contains binary data. */
445 exactn_bin,
446 #endif
448 /* Matches any (more or less) character. */
449 anychar,
451 /* Matches any one char belonging to specified set. First
452 following byte is number of bitmap bytes. Then come bytes
453 for a bitmap saying which chars are in. Bits in each byte
454 are ordered low-bit-first. A character is in the set if its
455 bit is 1. A character too large to have a bit in the map is
456 automatically not in the set. */
457 /* ifdef MBS_SUPPORT, following element is length of character
458 classes, length of collating symbols, length of equivalence
459 classes, length of character ranges, and length of characters.
460 Next, character class element, collating symbols elements,
461 equivalence class elements, range elements, and character
462 elements follow.
463 See regex_compile function. */
464 charset,
466 /* Same parameters as charset, but match any character that is
467 not one of those specified. */
468 charset_not,
470 /* Start remembering the text that is matched, for storing in a
471 register. Followed by one byte with the register number, in
472 the range 0 to one less than the pattern buffer's re_nsub
473 field. Then followed by one byte with the number of groups
474 inner to this one. (This last has to be part of the
475 start_memory only because we need it in the on_failure_jump
476 of re_match_2.) */
477 start_memory,
479 /* Stop remembering the text that is matched and store it in a
480 memory register. Followed by one byte with the register
481 number, in the range 0 to one less than `re_nsub' in the
482 pattern buffer, and one byte with the number of inner groups,
483 just like `start_memory'. (We need the number of inner
484 groups here because we don't have any easy way of finding the
485 corresponding start_memory when we're at a stop_memory.) */
486 stop_memory,
488 /* Match a duplicate of something remembered. Followed by one
489 byte containing the register number. */
490 duplicate,
492 /* Fail unless at beginning of line. */
493 begline,
495 /* Fail unless at end of line. */
496 endline,
498 /* Succeeds if at beginning of buffer (if emacs) or at beginning
499 of string to be matched (if not). */
500 begbuf,
502 /* Analogously, for end of buffer/string. */
503 endbuf,
505 /* Followed by two byte relative address to which to jump. */
506 jump,
508 /* Same as jump, but marks the end of an alternative. */
509 jump_past_alt,
511 /* Followed by two-byte relative address of place to resume at
512 in case of failure. */
513 /* ifdef MBS_SUPPORT, the size of address is 1. */
514 on_failure_jump,
516 /* Like on_failure_jump, but pushes a placeholder instead of the
517 current string position when executed. */
518 on_failure_keep_string_jump,
520 /* Throw away latest failure point and then jump to following
521 two-byte relative address. */
522 /* ifdef MBS_SUPPORT, the size of address is 1. */
523 pop_failure_jump,
525 /* Change to pop_failure_jump if know won't have to backtrack to
526 match; otherwise change to jump. This is used to jump
527 back to the beginning of a repeat. If what follows this jump
528 clearly won't match what the repeat does, such that we can be
529 sure that there is no use backtracking out of repetitions
530 already matched, then we change it to a pop_failure_jump.
531 Followed by two-byte address. */
532 /* ifdef MBS_SUPPORT, the size of address is 1. */
533 maybe_pop_jump,
535 /* Jump to following two-byte address, and push a dummy failure
536 point. This failure point will be thrown away if an attempt
537 is made to use it for a failure. A `+' construct makes this
538 before the first repeat. Also used as an intermediary kind
539 of jump when compiling an alternative. */
540 /* ifdef MBS_SUPPORT, the size of address is 1. */
541 dummy_failure_jump,
543 /* Push a dummy failure point and continue. Used at the end of
544 alternatives. */
545 push_dummy_failure,
547 /* Followed by two-byte relative address and two-byte number n.
548 After matching N times, jump to the address upon failure. */
549 /* ifdef MBS_SUPPORT, the size of address is 1. */
550 succeed_n,
552 /* Followed by two-byte relative address, and two-byte number n.
553 Jump to the address N times, then fail. */
554 /* ifdef MBS_SUPPORT, the size of address is 1. */
555 jump_n,
557 /* Set the following two-byte relative address to the
558 subsequent two-byte number. The address *includes* the two
559 bytes of number. */
560 /* ifdef MBS_SUPPORT, the size of address is 1. */
561 set_number_at,
563 wordchar, /* Matches any word-constituent character. */
564 notwordchar, /* Matches any char that is not a word-constituent. */
566 wordbeg, /* Succeeds if at word beginning. */
567 wordend, /* Succeeds if at word end. */
569 wordbound, /* Succeeds if at a word boundary. */
570 notwordbound /* Succeeds if not at a word boundary. */
572 #ifdef emacs
573 ,before_dot, /* Succeeds if before point. */
574 at_dot, /* Succeeds if at point. */
575 after_dot, /* Succeeds if after point. */
577 /* Matches any character whose syntax is specified. Followed by
578 a byte which contains a syntax code, e.g., Sword. */
579 syntaxspec,
581 /* Matches any character whose syntax is not that specified. */
582 notsyntaxspec
583 #endif /* emacs */
584 } re_opcode_t;
586 /* Common operations on the compiled pattern. */
588 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
589 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
591 #ifdef MBS_SUPPORT
592 # define STORE_NUMBER(destination, number) \
593 do { \
594 *(destination) = (US_CHAR_TYPE)(number); \
595 } while (0)
596 #else
597 # define STORE_NUMBER(destination, number) \
598 do { \
599 (destination)[0] = (number) & 0377; \
600 (destination)[1] = (number) >> 8; \
601 } while (0)
602 #endif /* MBS_SUPPORT */
604 /* Same as STORE_NUMBER, except increment DESTINATION to
605 the byte after where the number is stored. Therefore, DESTINATION
606 must be an lvalue. */
607 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
609 #define STORE_NUMBER_AND_INCR(destination, number) \
610 do { \
611 STORE_NUMBER (destination, number); \
612 (destination) += OFFSET_ADDRESS_SIZE; \
613 } while (0)
615 /* Put into DESTINATION a number stored in two contiguous bytes starting
616 at SOURCE. */
617 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
619 #ifdef MBS_SUPPORT
620 # define EXTRACT_NUMBER(destination, source) \
621 do { \
622 (destination) = *(source); \
623 } while (0)
624 #else
625 # define EXTRACT_NUMBER(destination, source) \
626 do { \
627 (destination) = *(source) & 0377; \
628 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
629 } while (0)
630 #endif
632 #ifdef DEBUG
633 static void extract_number _RE_ARGS ((int *dest, US_CHAR_TYPE *source));
634 static void
635 extract_number (dest, source)
636 int *dest;
637 US_CHAR_TYPE *source;
639 #ifdef MBS_SUPPORT
640 *dest = *source;
641 #else
642 int temp = SIGN_EXTEND_CHAR (*(source + 1));
643 *dest = *source & 0377;
644 *dest += temp << 8;
645 #endif
648 # ifndef EXTRACT_MACROS /* To debug the macros. */
649 # undef EXTRACT_NUMBER
650 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
651 # endif /* not EXTRACT_MACROS */
653 #endif /* DEBUG */
655 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
656 SOURCE must be an lvalue. */
658 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
659 do { \
660 EXTRACT_NUMBER (destination, source); \
661 (source) += OFFSET_ADDRESS_SIZE; \
662 } while (0)
664 #ifdef DEBUG
665 static void extract_number_and_incr _RE_ARGS ((int *destination,
666 US_CHAR_TYPE **source));
667 static void
668 extract_number_and_incr (destination, source)
669 int *destination;
670 US_CHAR_TYPE **source;
672 extract_number (destination, *source);
673 *source += OFFSET_ADDRESS_SIZE;
676 # ifndef EXTRACT_MACROS
677 # undef EXTRACT_NUMBER_AND_INCR
678 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
679 extract_number_and_incr (&dest, &src)
680 # endif /* not EXTRACT_MACROS */
682 #endif /* DEBUG */
684 /* If DEBUG is defined, Regex prints many voluminous messages about what
685 it is doing (if the variable `debug' is nonzero). If linked with the
686 main program in `iregex.c', you can enter patterns and strings
687 interactively. And if linked with the main program in `main.c' and
688 the other test files, you can run the already-written tests. */
690 #ifdef DEBUG
692 /* We use standard I/O for debugging. */
693 # include <stdio.h>
695 /* It is useful to test things that ``must'' be true when debugging. */
696 # include <assert.h>
698 static int debug;
700 # define DEBUG_STATEMENT(e) e
701 # define DEBUG_PRINT1(x) if (debug) printf (x)
702 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
703 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
704 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
705 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
706 if (debug) print_partial_compiled_pattern (s, e)
707 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
708 if (debug) print_double_string (w, s1, sz1, s2, sz2)
711 /* Print the fastmap in human-readable form. */
713 void
714 print_fastmap (fastmap)
715 char *fastmap;
717 unsigned was_a_range = 0;
718 unsigned i = 0;
720 while (i < (1 << BYTEWIDTH))
722 if (fastmap[i++])
724 was_a_range = 0;
725 putchar (i - 1);
726 while (i < (1 << BYTEWIDTH) && fastmap[i])
728 was_a_range = 1;
729 i++;
731 if (was_a_range)
733 printf ("-");
734 putchar (i - 1);
738 putchar ('\n');
742 /* Print a compiled pattern string in human-readable form, starting at
743 the START pointer into it and ending just before the pointer END. */
745 void
746 print_partial_compiled_pattern (start, end)
747 US_CHAR_TYPE *start;
748 US_CHAR_TYPE *end;
750 int mcnt, mcnt2;
751 US_CHAR_TYPE *p1;
752 US_CHAR_TYPE *p = start;
753 US_CHAR_TYPE *pend = end;
755 if (start == NULL)
757 printf ("(null)\n");
758 return;
761 /* Loop over pattern commands. */
762 while (p < pend)
764 #ifdef _LIBC
765 printf ("%td:\t", p - start);
766 #else
767 printf ("%ld:\t", (long int) (p - start));
768 #endif
770 switch ((re_opcode_t) *p++)
772 case no_op:
773 printf ("/no_op");
774 break;
776 case exactn:
777 mcnt = *p++;
778 printf ("/exactn/%d", mcnt);
781 putchar ('/');
782 PUT_CHAR (*p++);
784 while (--mcnt);
785 break;
787 #ifdef MBS_SUPPORT
788 case exactn_bin:
789 mcnt = *p++;
790 printf ("/exactn_bin/%d", mcnt);
793 printf("/%lx", (long int) *p++);
795 while (--mcnt);
796 break;
797 #endif /* MBS_SUPPORT */
799 case start_memory:
800 mcnt = *p++;
801 printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
802 break;
804 case stop_memory:
805 mcnt = *p++;
806 printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
807 break;
809 case duplicate:
810 printf ("/duplicate/%ld", (long int) *p++);
811 break;
813 case anychar:
814 printf ("/anychar");
815 break;
817 case charset:
818 case charset_not:
820 #ifdef MBS_SUPPORT
821 int i, length;
822 wchar_t *workp = p;
823 printf ("/charset [%s",
824 (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
825 p += 5;
826 length = *workp++; /* the length of char_classes */
827 for (i=0 ; i<length ; i++)
828 printf("[:%lx:]", (long int) *p++);
829 length = *workp++; /* the length of collating_symbol */
830 for (i=0 ; i<length ;)
832 printf("[.");
833 while(*p != 0)
834 PUT_CHAR((i++,*p++));
835 i++,p++;
836 printf(".]");
838 length = *workp++; /* the length of equivalence_class */
839 for (i=0 ; i<length ;)
841 printf("[=");
842 while(*p != 0)
843 PUT_CHAR((i++,*p++));
844 i++,p++;
845 printf("=]");
847 length = *workp++; /* the length of char_range */
848 for (i=0 ; i<length ; i++)
850 wchar_t range_start = *p++;
851 wchar_t range_end = *p++;
852 if (MB_CUR_MAX == 1)
853 printf("%c-%c", (char) range_start, (char) range_end);
854 else
855 printf("%C-%C", (wint_t) range_start, (wint_t) range_end);
857 length = *workp++; /* the length of char */
858 for (i=0 ; i<length ; i++)
859 if (MB_CUR_MAX == 1)
860 putchar (*p++);
861 else
862 printf("%C", (wint_t) *p++);
863 putchar (']');
864 #else
865 register int c, last = -100;
866 register int in_range = 0;
868 printf ("/charset [%s",
869 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
871 assert (p + *p < pend);
873 for (c = 0; c < 256; c++)
874 if (c / 8 < *p
875 && (p[1 + (c/8)] & (1 << (c % 8))))
877 /* Are we starting a range? */
878 if (last + 1 == c && ! in_range)
880 putchar ('-');
881 in_range = 1;
883 /* Have we broken a range? */
884 else if (last + 1 != c && in_range)
886 putchar (last);
887 in_range = 0;
890 if (! in_range)
891 putchar (c);
893 last = c;
896 if (in_range)
897 putchar (last);
899 putchar (']');
901 p += 1 + *p;
902 #endif /* MBS_SUPPORT */
904 break;
906 case begline:
907 printf ("/begline");
908 break;
910 case endline:
911 printf ("/endline");
912 break;
914 case on_failure_jump:
915 extract_number_and_incr (&mcnt, &p);
916 #ifdef _LIBC
917 printf ("/on_failure_jump to %td", p + mcnt - start);
918 #else
919 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
920 #endif
921 break;
923 case on_failure_keep_string_jump:
924 extract_number_and_incr (&mcnt, &p);
925 #ifdef _LIBC
926 printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
927 #else
928 printf ("/on_failure_keep_string_jump to %ld",
929 (long int) (p + mcnt - start));
930 #endif
931 break;
933 case dummy_failure_jump:
934 extract_number_and_incr (&mcnt, &p);
935 #ifdef _LIBC
936 printf ("/dummy_failure_jump to %td", p + mcnt - start);
937 #else
938 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
939 #endif
940 break;
942 case push_dummy_failure:
943 printf ("/push_dummy_failure");
944 break;
946 case maybe_pop_jump:
947 extract_number_and_incr (&mcnt, &p);
948 #ifdef _LIBC
949 printf ("/maybe_pop_jump to %td", p + mcnt - start);
950 #else
951 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
952 #endif
953 break;
955 case pop_failure_jump:
956 extract_number_and_incr (&mcnt, &p);
957 #ifdef _LIBC
958 printf ("/pop_failure_jump to %td", p + mcnt - start);
959 #else
960 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
961 #endif
962 break;
964 case jump_past_alt:
965 extract_number_and_incr (&mcnt, &p);
966 #ifdef _LIBC
967 printf ("/jump_past_alt to %td", p + mcnt - start);
968 #else
969 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
970 #endif
971 break;
973 case jump:
974 extract_number_and_incr (&mcnt, &p);
975 #ifdef _LIBC
976 printf ("/jump to %td", p + mcnt - start);
977 #else
978 printf ("/jump to %ld", (long int) (p + mcnt - start));
979 #endif
980 break;
982 case succeed_n:
983 extract_number_and_incr (&mcnt, &p);
984 p1 = p + mcnt;
985 extract_number_and_incr (&mcnt2, &p);
986 #ifdef _LIBC
987 printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
988 #else
989 printf ("/succeed_n to %ld, %d times",
990 (long int) (p1 - start), mcnt2);
991 #endif
992 break;
994 case jump_n:
995 extract_number_and_incr (&mcnt, &p);
996 p1 = p + mcnt;
997 extract_number_and_incr (&mcnt2, &p);
998 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
999 break;
1001 case set_number_at:
1002 extract_number_and_incr (&mcnt, &p);
1003 p1 = p + mcnt;
1004 extract_number_and_incr (&mcnt2, &p);
1005 #ifdef _LIBC
1006 printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1007 #else
1008 printf ("/set_number_at location %ld to %d",
1009 (long int) (p1 - start), mcnt2);
1010 #endif
1011 break;
1013 case wordbound:
1014 printf ("/wordbound");
1015 break;
1017 case notwordbound:
1018 printf ("/notwordbound");
1019 break;
1021 case wordbeg:
1022 printf ("/wordbeg");
1023 break;
1025 case wordend:
1026 printf ("/wordend");
1027 break;
1029 # ifdef emacs
1030 case before_dot:
1031 printf ("/before_dot");
1032 break;
1034 case at_dot:
1035 printf ("/at_dot");
1036 break;
1038 case after_dot:
1039 printf ("/after_dot");
1040 break;
1042 case syntaxspec:
1043 printf ("/syntaxspec");
1044 mcnt = *p++;
1045 printf ("/%d", mcnt);
1046 break;
1048 case notsyntaxspec:
1049 printf ("/notsyntaxspec");
1050 mcnt = *p++;
1051 printf ("/%d", mcnt);
1052 break;
1053 # endif /* emacs */
1055 case wordchar:
1056 printf ("/wordchar");
1057 break;
1059 case notwordchar:
1060 printf ("/notwordchar");
1061 break;
1063 case begbuf:
1064 printf ("/begbuf");
1065 break;
1067 case endbuf:
1068 printf ("/endbuf");
1069 break;
1071 default:
1072 printf ("?%ld", (long int) *(p-1));
1075 putchar ('\n');
1078 #ifdef _LIBC
1079 printf ("%td:\tend of pattern.\n", p - start);
1080 #else
1081 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1082 #endif
1086 void
1087 print_compiled_pattern (bufp)
1088 struct re_pattern_buffer *bufp;
1090 US_CHAR_TYPE *buffer = (US_CHAR_TYPE*) bufp->buffer;
1092 print_partial_compiled_pattern (buffer, buffer
1093 + bufp->used / sizeof(US_CHAR_TYPE));
1094 printf ("%ld bytes used/%ld bytes allocated.\n",
1095 bufp->used, bufp->allocated);
1097 if (bufp->fastmap_accurate && bufp->fastmap)
1099 printf ("fastmap: ");
1100 print_fastmap (bufp->fastmap);
1103 #ifdef _LIBC
1104 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1105 #else
1106 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1107 #endif
1108 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1109 printf ("can_be_null: %d\t", bufp->can_be_null);
1110 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1111 printf ("no_sub: %d\t", bufp->no_sub);
1112 printf ("not_bol: %d\t", bufp->not_bol);
1113 printf ("not_eol: %d\t", bufp->not_eol);
1114 printf ("syntax: %lx\n", bufp->syntax);
1115 /* Perhaps we should print the translate table? */
1119 void
1120 print_double_string (where, string1, size1, string2, size2)
1121 const CHAR_TYPE *where;
1122 const CHAR_TYPE *string1;
1123 const CHAR_TYPE *string2;
1124 int size1;
1125 int size2;
1127 int this_char;
1129 if (where == NULL)
1130 printf ("(null)");
1131 else
1133 if (FIRST_STRING_P (where))
1135 for (this_char = where - string1; this_char < size1; this_char++)
1136 PUT_CHAR (string1[this_char]);
1138 where = string2;
1141 for (this_char = where - string2; this_char < size2; this_char++)
1142 PUT_CHAR (string2[this_char]);
1146 void
1147 printchar (c)
1148 int c;
1150 putc (c, stderr);
1153 #else /* not DEBUG */
1155 # undef assert
1156 # define assert(e)
1158 # define DEBUG_STATEMENT(e)
1159 # define DEBUG_PRINT1(x)
1160 # define DEBUG_PRINT2(x1, x2)
1161 # define DEBUG_PRINT3(x1, x2, x3)
1162 # define DEBUG_PRINT4(x1, x2, x3, x4)
1163 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1164 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1166 #endif /* not DEBUG */
1168 #ifdef MBS_SUPPORT
1169 /* This convert a multibyte string to a wide character string.
1170 And write their correspondances to offset_buffer(see below)
1171 and write whether each wchar_t is binary data to is_binary.
1172 This assume invalid multibyte sequences as binary data.
1173 We assume offset_buffer and is_binary is already allocated
1174 enough space. */
1176 static size_t convert_mbs_to_wcs (CHAR_TYPE *dest, const unsigned char* src,
1177 size_t len, int *offset_buffer,
1178 char *is_binary);
1179 static size_t
1180 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1181 CHAR_TYPE *dest;
1182 const unsigned char* src;
1183 size_t len; /* the length of multibyte string. */
1185 /* It hold correspondances between src(char string) and
1186 dest(wchar_t string) for optimization.
1187 e.g. src = "xxxyzz"
1188 dest = {'X', 'Y', 'Z'}
1189 (each "xxx", "y" and "zz" represent one multibyte character
1190 corresponding to 'X', 'Y' and 'Z'.)
1191 offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1192 = {0, 3, 4, 6}
1194 int *offset_buffer;
1195 char *is_binary;
1197 wchar_t *pdest = dest;
1198 const unsigned char *psrc = src;
1199 size_t wc_count = 0;
1201 if (MB_CUR_MAX == 1)
1202 { /* We don't need conversion. */
1203 for ( ; wc_count < len ; ++wc_count)
1205 *pdest++ = *psrc++;
1206 is_binary[wc_count] = FALSE;
1207 offset_buffer[wc_count] = wc_count;
1209 offset_buffer[wc_count] = wc_count;
1211 else
1213 /* We need conversion. */
1214 mbstate_t mbs;
1215 int consumed;
1216 size_t mb_remain = len;
1217 size_t mb_count = 0;
1219 /* Initialize the conversion state. */
1220 memset (&mbs, 0, sizeof (mbstate_t));
1222 offset_buffer[0] = 0;
1223 for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1224 psrc += consumed)
1226 consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1228 if (consumed <= 0)
1229 /* failed to convert. maybe src contains binary data.
1230 So we consume 1 byte manualy. */
1232 *pdest = *psrc;
1233 consumed = 1;
1234 is_binary[wc_count] = TRUE;
1236 else
1237 is_binary[wc_count] = FALSE;
1238 /* In sjis encoding, we use yen sign as escape character in
1239 place of reverse solidus. So we convert 0x5c(yen sign in
1240 sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1241 solidus in UCS2). */
1242 if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1243 *pdest = (wchar_t) *psrc;
1245 offset_buffer[wc_count + 1] = mb_count += consumed;
1249 return wc_count;
1252 #endif /* MBS_SUPPORT */
1254 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1255 also be assigned to arbitrarily: each pattern buffer stores its own
1256 syntax, so it can be changed between regex compilations. */
1257 /* This has no initializer because initialized variables in Emacs
1258 become read-only after dumping. */
1259 reg_syntax_t re_syntax_options;
1262 /* Specify the precise syntax of regexps for compilation. This provides
1263 for compatibility for various utilities which historically have
1264 different, incompatible syntaxes.
1266 The argument SYNTAX is a bit mask comprised of the various bits
1267 defined in regex.h. We return the old syntax. */
1269 reg_syntax_t
1270 re_set_syntax (syntax)
1271 reg_syntax_t syntax;
1273 reg_syntax_t ret = re_syntax_options;
1275 re_syntax_options = syntax;
1276 #ifdef DEBUG
1277 if (syntax & RE_DEBUG)
1278 debug = 1;
1279 else if (debug) /* was on but now is not */
1280 debug = 0;
1281 #endif /* DEBUG */
1282 return ret;
1284 #ifdef _LIBC
1285 weak_alias (__re_set_syntax, re_set_syntax)
1286 #endif
1288 /* This table gives an error message for each of the error codes listed
1289 in regex.h. Obviously the order here has to be same as there.
1290 POSIX doesn't require that we do anything for REG_NOERROR,
1291 but why not be nice? */
1293 static const char re_error_msgid[] =
1295 #define REG_NOERROR_IDX 0
1296 gettext_noop ("Success") /* REG_NOERROR */
1297 "\0"
1298 #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1299 gettext_noop ("No match") /* REG_NOMATCH */
1300 "\0"
1301 #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1302 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1303 "\0"
1304 #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1305 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1306 "\0"
1307 #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1308 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1309 "\0"
1310 #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1311 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1312 "\0"
1313 #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1314 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1315 "\0"
1316 #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1317 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1318 "\0"
1319 #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1320 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1321 "\0"
1322 #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1323 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1324 "\0"
1325 #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1326 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1327 "\0"
1328 #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1329 gettext_noop ("Invalid range end") /* REG_ERANGE */
1330 "\0"
1331 #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1332 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1333 "\0"
1334 #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1335 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1336 "\0"
1337 #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1338 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1339 "\0"
1340 #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1341 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1342 "\0"
1343 #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1344 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1347 static const size_t re_error_msgid_idx[] =
1349 REG_NOERROR_IDX,
1350 REG_NOMATCH_IDX,
1351 REG_BADPAT_IDX,
1352 REG_ECOLLATE_IDX,
1353 REG_ECTYPE_IDX,
1354 REG_EESCAPE_IDX,
1355 REG_ESUBREG_IDX,
1356 REG_EBRACK_IDX,
1357 REG_EPAREN_IDX,
1358 REG_EBRACE_IDX,
1359 REG_BADBR_IDX,
1360 REG_ERANGE_IDX,
1361 REG_ESPACE_IDX,
1362 REG_BADRPT_IDX,
1363 REG_EEND_IDX,
1364 REG_ESIZE_IDX,
1365 REG_ERPAREN_IDX
1368 /* Avoiding alloca during matching, to placate r_alloc. */
1370 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1371 searching and matching functions should not call alloca. On some
1372 systems, alloca is implemented in terms of malloc, and if we're
1373 using the relocating allocator routines, then malloc could cause a
1374 relocation, which might (if the strings being searched are in the
1375 ralloc heap) shift the data out from underneath the regexp
1376 routines.
1378 Here's another reason to avoid allocation: Emacs
1379 processes input from X in a signal handler; processing X input may
1380 call malloc; if input arrives while a matching routine is calling
1381 malloc, then we're scrod. But Emacs can't just block input while
1382 calling matching routines; then we don't notice interrupts when
1383 they come in. So, Emacs blocks input around all regexp calls
1384 except the matching calls, which it leaves unprotected, in the
1385 faith that they will not malloc. */
1387 /* Normally, this is fine. */
1388 #define MATCH_MAY_ALLOCATE
1390 /* When using GNU C, we are not REALLY using the C alloca, no matter
1391 what config.h may say. So don't take precautions for it. */
1392 #ifdef __GNUC__
1393 # undef C_ALLOCA
1394 #endif
1396 /* The match routines may not allocate if (1) they would do it with malloc
1397 and (2) it's not safe for them to use malloc.
1398 Note that if REL_ALLOC is defined, matching would not use malloc for the
1399 failure stack, but we would still use it for the register vectors;
1400 so REL_ALLOC should not affect this. */
1401 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1402 # undef MATCH_MAY_ALLOCATE
1403 #endif
1406 /* Failure stack declarations and macros; both re_compile_fastmap and
1407 re_match_2 use a failure stack. These have to be macros because of
1408 REGEX_ALLOCATE_STACK. */
1411 /* Number of failure points for which to initially allocate space
1412 when matching. If this number is exceeded, we allocate more
1413 space, so it is not a hard limit. */
1414 #ifndef INIT_FAILURE_ALLOC
1415 # define INIT_FAILURE_ALLOC 5
1416 #endif
1418 /* Roughly the maximum number of failure points on the stack. Would be
1419 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1420 This is a variable only so users of regex can assign to it; we never
1421 change it ourselves. */
1423 #ifdef INT_IS_16BIT
1425 # if defined MATCH_MAY_ALLOCATE
1426 /* 4400 was enough to cause a crash on Alpha OSF/1,
1427 whose default stack limit is 2mb. */
1428 long int re_max_failures = 4000;
1429 # else
1430 long int re_max_failures = 2000;
1431 # endif
1433 union fail_stack_elt
1435 US_CHAR_TYPE *pointer;
1436 long int integer;
1439 typedef union fail_stack_elt fail_stack_elt_t;
1441 typedef struct
1443 fail_stack_elt_t *stack;
1444 unsigned long int size;
1445 unsigned long int avail; /* Offset of next open position. */
1446 } fail_stack_type;
1448 #else /* not INT_IS_16BIT */
1450 # if defined MATCH_MAY_ALLOCATE
1451 /* 4400 was enough to cause a crash on Alpha OSF/1,
1452 whose default stack limit is 2mb. */
1453 int re_max_failures = 4000;
1454 # else
1455 int re_max_failures = 2000;
1456 # endif
1458 union fail_stack_elt
1460 US_CHAR_TYPE *pointer;
1461 int integer;
1464 typedef union fail_stack_elt fail_stack_elt_t;
1466 typedef struct
1468 fail_stack_elt_t *stack;
1469 unsigned size;
1470 unsigned avail; /* Offset of next open position. */
1471 } fail_stack_type;
1473 #endif /* INT_IS_16BIT */
1475 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1476 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1477 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1480 /* Define macros to initialize and free the failure stack.
1481 Do `return -2' if the alloc fails. */
1483 #ifdef MATCH_MAY_ALLOCATE
1484 # define INIT_FAIL_STACK() \
1485 do { \
1486 fail_stack.stack = (fail_stack_elt_t *) \
1487 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1489 if (fail_stack.stack == NULL) \
1490 return -2; \
1492 fail_stack.size = INIT_FAILURE_ALLOC; \
1493 fail_stack.avail = 0; \
1494 } while (0)
1496 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1497 #else
1498 # define INIT_FAIL_STACK() \
1499 do { \
1500 fail_stack.avail = 0; \
1501 } while (0)
1503 # define RESET_FAIL_STACK()
1504 #endif
1507 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1509 Return 1 if succeeds, and 0 if either ran out of memory
1510 allocating space for it or it was already too large.
1512 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1514 #define DOUBLE_FAIL_STACK(fail_stack) \
1515 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1516 ? 0 \
1517 : ((fail_stack).stack = (fail_stack_elt_t *) \
1518 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1519 (fail_stack).size * sizeof (fail_stack_elt_t), \
1520 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1522 (fail_stack).stack == NULL \
1523 ? 0 \
1524 : ((fail_stack).size <<= 1, \
1525 1)))
1528 /* Push pointer POINTER on FAIL_STACK.
1529 Return 1 if was able to do so and 0 if ran out of memory allocating
1530 space to do so. */
1531 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1532 ((FAIL_STACK_FULL () \
1533 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1534 ? 0 \
1535 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1538 /* Push a pointer value onto the failure stack.
1539 Assumes the variable `fail_stack'. Probably should only
1540 be called from within `PUSH_FAILURE_POINT'. */
1541 #define PUSH_FAILURE_POINTER(item) \
1542 fail_stack.stack[fail_stack.avail++].pointer = (US_CHAR_TYPE *) (item)
1544 /* This pushes an integer-valued item onto the failure stack.
1545 Assumes the variable `fail_stack'. Probably should only
1546 be called from within `PUSH_FAILURE_POINT'. */
1547 #define PUSH_FAILURE_INT(item) \
1548 fail_stack.stack[fail_stack.avail++].integer = (item)
1550 /* Push a fail_stack_elt_t value onto the failure stack.
1551 Assumes the variable `fail_stack'. Probably should only
1552 be called from within `PUSH_FAILURE_POINT'. */
1553 #define PUSH_FAILURE_ELT(item) \
1554 fail_stack.stack[fail_stack.avail++] = (item)
1556 /* These three POP... operations complement the three PUSH... operations.
1557 All assume that `fail_stack' is nonempty. */
1558 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1559 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1560 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1562 /* Used to omit pushing failure point id's when we're not debugging. */
1563 #ifdef DEBUG
1564 # define DEBUG_PUSH PUSH_FAILURE_INT
1565 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1566 #else
1567 # define DEBUG_PUSH(item)
1568 # define DEBUG_POP(item_addr)
1569 #endif
1572 /* Push the information about the state we will need
1573 if we ever fail back to it.
1575 Requires variables fail_stack, regstart, regend, reg_info, and
1576 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1577 be declared.
1579 Does `return FAILURE_CODE' if runs out of memory. */
1581 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1582 do { \
1583 char *destination; \
1584 /* Must be int, so when we don't save any registers, the arithmetic \
1585 of 0 + -1 isn't done as unsigned. */ \
1586 /* Can't be int, since there is not a shred of a guarantee that int \
1587 is wide enough to hold a value of something to which pointer can \
1588 be assigned */ \
1589 active_reg_t this_reg; \
1591 DEBUG_STATEMENT (failure_id++); \
1592 DEBUG_STATEMENT (nfailure_points_pushed++); \
1593 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1594 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1595 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1597 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1598 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1600 /* Ensure we have enough space allocated for what we will push. */ \
1601 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1603 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1604 return failure_code; \
1606 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1607 (fail_stack).size); \
1608 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1611 /* Push the info, starting with the registers. */ \
1612 DEBUG_PRINT1 ("\n"); \
1614 if (1) \
1615 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1616 this_reg++) \
1618 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1619 DEBUG_STATEMENT (num_regs_pushed++); \
1621 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1622 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1624 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1625 PUSH_FAILURE_POINTER (regend[this_reg]); \
1627 DEBUG_PRINT2 (" info: %p\n ", \
1628 reg_info[this_reg].word.pointer); \
1629 DEBUG_PRINT2 (" match_null=%d", \
1630 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1631 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1632 DEBUG_PRINT2 (" matched_something=%d", \
1633 MATCHED_SOMETHING (reg_info[this_reg])); \
1634 DEBUG_PRINT2 (" ever_matched=%d", \
1635 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1636 DEBUG_PRINT1 ("\n"); \
1637 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1640 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1641 PUSH_FAILURE_INT (lowest_active_reg); \
1643 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1644 PUSH_FAILURE_INT (highest_active_reg); \
1646 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1647 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1648 PUSH_FAILURE_POINTER (pattern_place); \
1650 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1651 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1652 size2); \
1653 DEBUG_PRINT1 ("'\n"); \
1654 PUSH_FAILURE_POINTER (string_place); \
1656 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1657 DEBUG_PUSH (failure_id); \
1658 } while (0)
1660 /* This is the number of items that are pushed and popped on the stack
1661 for each register. */
1662 #define NUM_REG_ITEMS 3
1664 /* Individual items aside from the registers. */
1665 #ifdef DEBUG
1666 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1667 #else
1668 # define NUM_NONREG_ITEMS 4
1669 #endif
1671 /* We push at most this many items on the stack. */
1672 /* We used to use (num_regs - 1), which is the number of registers
1673 this regexp will save; but that was changed to 5
1674 to avoid stack overflow for a regexp with lots of parens. */
1675 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1677 /* We actually push this many items. */
1678 #define NUM_FAILURE_ITEMS \
1679 (((0 \
1680 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1681 * NUM_REG_ITEMS) \
1682 + NUM_NONREG_ITEMS)
1684 /* How many items can still be added to the stack without overflowing it. */
1685 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1688 /* Pops what PUSH_FAIL_STACK pushes.
1690 We restore into the parameters, all of which should be lvalues:
1691 STR -- the saved data position.
1692 PAT -- the saved pattern position.
1693 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1694 REGSTART, REGEND -- arrays of string positions.
1695 REG_INFO -- array of information about each subexpression.
1697 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1698 `pend', `string1', `size1', `string2', and `size2'. */
1699 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1701 DEBUG_STATEMENT (unsigned failure_id;) \
1702 active_reg_t this_reg; \
1703 const US_CHAR_TYPE *string_temp; \
1705 assert (!FAIL_STACK_EMPTY ()); \
1707 /* Remove failure points and point to how many regs pushed. */ \
1708 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1709 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1710 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1712 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1714 DEBUG_POP (&failure_id); \
1715 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1717 /* If the saved string location is NULL, it came from an \
1718 on_failure_keep_string_jump opcode, and we want to throw away the \
1719 saved NULL, thus retaining our current position in the string. */ \
1720 string_temp = POP_FAILURE_POINTER (); \
1721 if (string_temp != NULL) \
1722 str = (const CHAR_TYPE *) string_temp; \
1724 DEBUG_PRINT2 (" Popping string %p: `", str); \
1725 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1726 DEBUG_PRINT1 ("'\n"); \
1728 pat = (US_CHAR_TYPE *) POP_FAILURE_POINTER (); \
1729 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1730 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1732 /* Restore register info. */ \
1733 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1734 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1736 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1737 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1739 if (1) \
1740 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1742 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1744 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1745 DEBUG_PRINT2 (" info: %p\n", \
1746 reg_info[this_reg].word.pointer); \
1748 regend[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER (); \
1749 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1751 regstart[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER ();\
1752 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1754 else \
1756 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1758 reg_info[this_reg].word.integer = 0; \
1759 regend[this_reg] = 0; \
1760 regstart[this_reg] = 0; \
1762 highest_active_reg = high_reg; \
1765 set_regs_matched_done = 0; \
1766 DEBUG_STATEMENT (nfailure_points_popped++); \
1767 } /* POP_FAILURE_POINT */
1770 /* Structure for per-register (a.k.a. per-group) information.
1771 Other register information, such as the
1772 starting and ending positions (which are addresses), and the list of
1773 inner groups (which is a bits list) are maintained in separate
1774 variables.
1776 We are making a (strictly speaking) nonportable assumption here: that
1777 the compiler will pack our bit fields into something that fits into
1778 the type of `word', i.e., is something that fits into one item on the
1779 failure stack. */
1782 /* Declarations and macros for re_match_2. */
1784 typedef union
1786 fail_stack_elt_t word;
1787 struct
1789 /* This field is one if this group can match the empty string,
1790 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1791 #define MATCH_NULL_UNSET_VALUE 3
1792 unsigned match_null_string_p : 2;
1793 unsigned is_active : 1;
1794 unsigned matched_something : 1;
1795 unsigned ever_matched_something : 1;
1796 } bits;
1797 } register_info_type;
1799 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1800 #define IS_ACTIVE(R) ((R).bits.is_active)
1801 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1802 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1805 /* Call this when have matched a real character; it sets `matched' flags
1806 for the subexpressions which we are currently inside. Also records
1807 that those subexprs have matched. */
1808 #define SET_REGS_MATCHED() \
1809 do \
1811 if (!set_regs_matched_done) \
1813 active_reg_t r; \
1814 set_regs_matched_done = 1; \
1815 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1817 MATCHED_SOMETHING (reg_info[r]) \
1818 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1819 = 1; \
1823 while (0)
1825 /* Registers are set to a sentinel when they haven't yet matched. */
1826 static CHAR_TYPE reg_unset_dummy;
1827 #define REG_UNSET_VALUE (&reg_unset_dummy)
1828 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1830 /* Subroutine declarations and macros for regex_compile. */
1832 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1833 reg_syntax_t syntax,
1834 struct re_pattern_buffer *bufp));
1835 static void store_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc, int arg));
1836 static void store_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1837 int arg1, int arg2));
1838 static void insert_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1839 int arg, US_CHAR_TYPE *end));
1840 static void insert_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1841 int arg1, int arg2, US_CHAR_TYPE *end));
1842 static boolean at_begline_loc_p _RE_ARGS ((const CHAR_TYPE *pattern,
1843 const CHAR_TYPE *p,
1844 reg_syntax_t syntax));
1845 static boolean at_endline_loc_p _RE_ARGS ((const CHAR_TYPE *p,
1846 const CHAR_TYPE *pend,
1847 reg_syntax_t syntax));
1848 #ifdef MBS_SUPPORT
1849 static reg_errcode_t compile_range _RE_ARGS ((CHAR_TYPE range_start,
1850 const CHAR_TYPE **p_ptr,
1851 const CHAR_TYPE *pend,
1852 char *translate,
1853 reg_syntax_t syntax,
1854 US_CHAR_TYPE *b,
1855 CHAR_TYPE *char_set));
1856 static void insert_space _RE_ARGS ((int num, CHAR_TYPE *loc, CHAR_TYPE *end));
1857 #else
1858 static reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
1859 const CHAR_TYPE **p_ptr,
1860 const CHAR_TYPE *pend,
1861 char *translate,
1862 reg_syntax_t syntax,
1863 US_CHAR_TYPE *b));
1864 #endif /* MBS_SUPPORT */
1866 /* Fetch the next character in the uncompiled pattern---translating it
1867 if necessary. Also cast from a signed character in the constant
1868 string passed to us by the user to an unsigned char that we can use
1869 as an array index (in, e.g., `translate'). */
1870 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1871 because it is impossible to allocate 4GB array for some encodings
1872 which have 4 byte character_set like UCS4. */
1873 #ifndef PATFETCH
1874 # ifdef MBS_SUPPORT
1875 # define PATFETCH(c) \
1876 do {if (p == pend) return REG_EEND; \
1877 c = (US_CHAR_TYPE) *p++; \
1878 if (translate && (c <= 0xff)) c = (US_CHAR_TYPE) translate[c]; \
1879 } while (0)
1880 # else
1881 # define PATFETCH(c) \
1882 do {if (p == pend) return REG_EEND; \
1883 c = (unsigned char) *p++; \
1884 if (translate) c = (unsigned char) translate[c]; \
1885 } while (0)
1886 # endif /* MBS_SUPPORT */
1887 #endif
1889 /* Fetch the next character in the uncompiled pattern, with no
1890 translation. */
1891 #define PATFETCH_RAW(c) \
1892 do {if (p == pend) return REG_EEND; \
1893 c = (US_CHAR_TYPE) *p++; \
1894 } while (0)
1896 /* Go backwards one character in the pattern. */
1897 #define PATUNFETCH p--
1900 /* If `translate' is non-null, return translate[D], else just D. We
1901 cast the subscript to translate because some data is declared as
1902 `char *', to avoid warnings when a string constant is passed. But
1903 when we use a character as a subscript we must make it unsigned. */
1904 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1905 because it is impossible to allocate 4GB array for some encodings
1906 which have 4 byte character_set like UCS4. */
1907 #ifndef TRANSLATE
1908 # ifdef MBS_SUPPORT
1909 # define TRANSLATE(d) \
1910 ((translate && ((US_CHAR_TYPE) (d)) <= 0xff) \
1911 ? (char) translate[(unsigned char) (d)] : (d))
1912 #else
1913 # define TRANSLATE(d) \
1914 (translate ? (char) translate[(unsigned char) (d)] : (d))
1915 # endif /* MBS_SUPPORT */
1916 #endif
1919 /* Macros for outputting the compiled pattern into `buffer'. */
1921 /* If the buffer isn't allocated when it comes in, use this. */
1922 #define INIT_BUF_SIZE (32 * sizeof(US_CHAR_TYPE))
1924 /* Make sure we have at least N more bytes of space in buffer. */
1925 #ifdef MBS_SUPPORT
1926 # define GET_BUFFER_SPACE(n) \
1927 while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR \
1928 + (n)*sizeof(CHAR_TYPE)) > bufp->allocated) \
1929 EXTEND_BUFFER ()
1930 #else
1931 # define GET_BUFFER_SPACE(n) \
1932 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1933 EXTEND_BUFFER ()
1934 #endif /* MBS_SUPPORT */
1936 /* Make sure we have one more byte of buffer space and then add C to it. */
1937 #define BUF_PUSH(c) \
1938 do { \
1939 GET_BUFFER_SPACE (1); \
1940 *b++ = (US_CHAR_TYPE) (c); \
1941 } while (0)
1944 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1945 #define BUF_PUSH_2(c1, c2) \
1946 do { \
1947 GET_BUFFER_SPACE (2); \
1948 *b++ = (US_CHAR_TYPE) (c1); \
1949 *b++ = (US_CHAR_TYPE) (c2); \
1950 } while (0)
1953 /* As with BUF_PUSH_2, except for three bytes. */
1954 #define BUF_PUSH_3(c1, c2, c3) \
1955 do { \
1956 GET_BUFFER_SPACE (3); \
1957 *b++ = (US_CHAR_TYPE) (c1); \
1958 *b++ = (US_CHAR_TYPE) (c2); \
1959 *b++ = (US_CHAR_TYPE) (c3); \
1960 } while (0)
1962 /* Store a jump with opcode OP at LOC to location TO. We store a
1963 relative address offset by the three bytes the jump itself occupies. */
1964 #define STORE_JUMP(op, loc, to) \
1965 store_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
1967 /* Likewise, for a two-argument jump. */
1968 #define STORE_JUMP2(op, loc, to, arg) \
1969 store_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
1971 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1972 #define INSERT_JUMP(op, loc, to) \
1973 insert_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
1975 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1976 #define INSERT_JUMP2(op, loc, to, arg) \
1977 insert_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
1978 arg, b)
1981 /* This is not an arbitrary limit: the arguments which represent offsets
1982 into the pattern are two bytes long. So if 2^16 bytes turns out to
1983 be too small, many things would have to change. */
1984 /* Any other compiler which, like MSC, has allocation limit below 2^16
1985 bytes will have to use approach similar to what was done below for
1986 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1987 reallocating to 0 bytes. Such thing is not going to work too well.
1988 You have been warned!! */
1989 #if defined _MSC_VER && !defined WIN32
1990 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1991 The REALLOC define eliminates a flurry of conversion warnings,
1992 but is not required. */
1993 # define MAX_BUF_SIZE 65500L
1994 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1995 #else
1996 # define MAX_BUF_SIZE (1L << 16)
1997 # define REALLOC(p,s) realloc ((p), (s))
1998 #endif
2000 /* Extend the buffer by twice its current size via realloc and
2001 reset the pointers that pointed into the old block to point to the
2002 correct places in the new one. If extending the buffer results in it
2003 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
2004 #if __BOUNDED_POINTERS__
2005 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2006 # define MOVE_BUFFER_POINTER(P) \
2007 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2008 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
2009 else \
2011 SET_HIGH_BOUND (b); \
2012 SET_HIGH_BOUND (begalt); \
2013 if (fixup_alt_jump) \
2014 SET_HIGH_BOUND (fixup_alt_jump); \
2015 if (laststart) \
2016 SET_HIGH_BOUND (laststart); \
2017 if (pending_exact) \
2018 SET_HIGH_BOUND (pending_exact); \
2020 #else
2021 # define MOVE_BUFFER_POINTER(P) (P) += incr
2022 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
2023 #endif
2025 #ifdef MBS_SUPPORT
2026 # define EXTEND_BUFFER() \
2027 do { \
2028 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2029 int wchar_count; \
2030 if (bufp->allocated + sizeof(US_CHAR_TYPE) > MAX_BUF_SIZE) \
2031 return REG_ESIZE; \
2032 bufp->allocated <<= 1; \
2033 if (bufp->allocated > MAX_BUF_SIZE) \
2034 bufp->allocated = MAX_BUF_SIZE; \
2035 /* How many characters the new buffer can have? */ \
2036 wchar_count = bufp->allocated / sizeof(US_CHAR_TYPE); \
2037 if (wchar_count == 0) wchar_count = 1; \
2038 /* Truncate the buffer to CHAR_TYPE align. */ \
2039 bufp->allocated = wchar_count * sizeof(US_CHAR_TYPE); \
2040 RETALLOC (COMPILED_BUFFER_VAR, wchar_count, US_CHAR_TYPE); \
2041 bufp->buffer = (char*)COMPILED_BUFFER_VAR; \
2042 if (COMPILED_BUFFER_VAR == NULL) \
2043 return REG_ESPACE; \
2044 /* If the buffer moved, move all the pointers into it. */ \
2045 if (old_buffer != COMPILED_BUFFER_VAR) \
2047 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2048 MOVE_BUFFER_POINTER (b); \
2049 MOVE_BUFFER_POINTER (begalt); \
2050 if (fixup_alt_jump) \
2051 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2052 if (laststart) \
2053 MOVE_BUFFER_POINTER (laststart); \
2054 if (pending_exact) \
2055 MOVE_BUFFER_POINTER (pending_exact); \
2057 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2058 } while (0)
2059 #else
2060 # define EXTEND_BUFFER() \
2061 do { \
2062 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2063 if (bufp->allocated == MAX_BUF_SIZE) \
2064 return REG_ESIZE; \
2065 bufp->allocated <<= 1; \
2066 if (bufp->allocated > MAX_BUF_SIZE) \
2067 bufp->allocated = MAX_BUF_SIZE; \
2068 bufp->buffer = (US_CHAR_TYPE *) REALLOC (COMPILED_BUFFER_VAR, \
2069 bufp->allocated); \
2070 if (COMPILED_BUFFER_VAR == NULL) \
2071 return REG_ESPACE; \
2072 /* If the buffer moved, move all the pointers into it. */ \
2073 if (old_buffer != COMPILED_BUFFER_VAR) \
2075 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2076 MOVE_BUFFER_POINTER (b); \
2077 MOVE_BUFFER_POINTER (begalt); \
2078 if (fixup_alt_jump) \
2079 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2080 if (laststart) \
2081 MOVE_BUFFER_POINTER (laststart); \
2082 if (pending_exact) \
2083 MOVE_BUFFER_POINTER (pending_exact); \
2085 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2086 } while (0)
2087 #endif /* MBS_SUPPORT */
2089 /* Since we have one byte reserved for the register number argument to
2090 {start,stop}_memory, the maximum number of groups we can report
2091 things about is what fits in that byte. */
2092 #define MAX_REGNUM 255
2094 /* But patterns can have more than `MAX_REGNUM' registers. We just
2095 ignore the excess. */
2096 typedef unsigned regnum_t;
2099 /* Macros for the compile stack. */
2101 /* Since offsets can go either forwards or backwards, this type needs to
2102 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
2103 /* int may be not enough when sizeof(int) == 2. */
2104 typedef long pattern_offset_t;
2106 typedef struct
2108 pattern_offset_t begalt_offset;
2109 pattern_offset_t fixup_alt_jump;
2110 pattern_offset_t inner_group_offset;
2111 pattern_offset_t laststart_offset;
2112 regnum_t regnum;
2113 } compile_stack_elt_t;
2116 typedef struct
2118 compile_stack_elt_t *stack;
2119 unsigned size;
2120 unsigned avail; /* Offset of next open position. */
2121 } compile_stack_type;
2124 #define INIT_COMPILE_STACK_SIZE 32
2126 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
2127 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
2129 /* The next available element. */
2130 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2133 /* Set the bit for character C in a list. */
2134 #define SET_LIST_BIT(c) \
2135 (b[((unsigned char) (c)) / BYTEWIDTH] \
2136 |= 1 << (((unsigned char) c) % BYTEWIDTH))
2139 /* Get the next unsigned number in the uncompiled pattern. */
2140 #define GET_UNSIGNED_NUMBER(num) \
2142 while (p != pend) \
2144 PATFETCH (c); \
2145 if (c < '0' || c > '9') \
2146 break; \
2147 if (num <= RE_DUP_MAX) \
2149 if (num < 0) \
2150 num = 0; \
2151 num = num * 10 + c - '0'; \
2156 #if defined _LIBC || WIDE_CHAR_SUPPORT
2157 /* The GNU C library provides support for user-defined character classes
2158 and the functions from ISO C amendement 1. */
2159 # ifdef CHARCLASS_NAME_MAX
2160 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2161 # else
2162 /* This shouldn't happen but some implementation might still have this
2163 problem. Use a reasonable default value. */
2164 # define CHAR_CLASS_MAX_LENGTH 256
2165 # endif
2167 # ifdef _LIBC
2168 # define IS_CHAR_CLASS(string) __wctype (string)
2169 # else
2170 # define IS_CHAR_CLASS(string) wctype (string)
2171 # endif
2172 #else
2173 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
2175 # define IS_CHAR_CLASS(string) \
2176 (STREQ (string, "alpha") || STREQ (string, "upper") \
2177 || STREQ (string, "lower") || STREQ (string, "digit") \
2178 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
2179 || STREQ (string, "space") || STREQ (string, "print") \
2180 || STREQ (string, "punct") || STREQ (string, "graph") \
2181 || STREQ (string, "cntrl") || STREQ (string, "blank"))
2182 #endif
2184 #ifndef MATCH_MAY_ALLOCATE
2186 /* If we cannot allocate large objects within re_match_2_internal,
2187 we make the fail stack and register vectors global.
2188 The fail stack, we grow to the maximum size when a regexp
2189 is compiled.
2190 The register vectors, we adjust in size each time we
2191 compile a regexp, according to the number of registers it needs. */
2193 static fail_stack_type fail_stack;
2195 /* Size with which the following vectors are currently allocated.
2196 That is so we can make them bigger as needed,
2197 but never make them smaller. */
2198 static int regs_allocated_size;
2200 static const char ** regstart, ** regend;
2201 static const char ** old_regstart, ** old_regend;
2202 static const char **best_regstart, **best_regend;
2203 static register_info_type *reg_info;
2204 static const char **reg_dummy;
2205 static register_info_type *reg_info_dummy;
2207 /* Make the register vectors big enough for NUM_REGS registers,
2208 but don't make them smaller. */
2210 static
2211 regex_grow_registers (num_regs)
2212 int num_regs;
2214 if (num_regs > regs_allocated_size)
2216 RETALLOC_IF (regstart, num_regs, const char *);
2217 RETALLOC_IF (regend, num_regs, const char *);
2218 RETALLOC_IF (old_regstart, num_regs, const char *);
2219 RETALLOC_IF (old_regend, num_regs, const char *);
2220 RETALLOC_IF (best_regstart, num_regs, const char *);
2221 RETALLOC_IF (best_regend, num_regs, const char *);
2222 RETALLOC_IF (reg_info, num_regs, register_info_type);
2223 RETALLOC_IF (reg_dummy, num_regs, const char *);
2224 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
2226 regs_allocated_size = num_regs;
2230 #endif /* not MATCH_MAY_ALLOCATE */
2232 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2233 compile_stack,
2234 regnum_t regnum));
2236 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2237 Returns one of error codes defined in `regex.h', or zero for success.
2239 Assumes the `allocated' (and perhaps `buffer') and `translate'
2240 fields are set in BUFP on entry.
2242 If it succeeds, results are put in BUFP (if it returns an error, the
2243 contents of BUFP are undefined):
2244 `buffer' is the compiled pattern;
2245 `syntax' is set to SYNTAX;
2246 `used' is set to the length of the compiled pattern;
2247 `fastmap_accurate' is zero;
2248 `re_nsub' is the number of subexpressions in PATTERN;
2249 `not_bol' and `not_eol' are zero;
2251 The `fastmap' and `newline_anchor' fields are neither
2252 examined nor set. */
2254 /* Return, freeing storage we allocated. */
2255 #ifdef MBS_SUPPORT
2256 # define FREE_STACK_RETURN(value) \
2257 return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2258 #else
2259 # define FREE_STACK_RETURN(value) \
2260 return (free (compile_stack.stack), value)
2261 #endif /* MBS_SUPPORT */
2263 static reg_errcode_t
2264 #ifdef MBS_SUPPORT
2265 regex_compile (cpattern, csize, syntax, bufp)
2266 const char *cpattern;
2267 size_t csize;
2268 #else
2269 regex_compile (pattern, size, syntax, bufp)
2270 const char *pattern;
2271 size_t size;
2272 #endif /* MBS_SUPPORT */
2273 reg_syntax_t syntax;
2274 struct re_pattern_buffer *bufp;
2276 /* We fetch characters from PATTERN here. Even though PATTERN is
2277 `char *' (i.e., signed), we declare these variables as unsigned, so
2278 they can be reliably used as array indices. */
2279 register US_CHAR_TYPE c, c1;
2281 #ifdef MBS_SUPPORT
2282 /* A temporary space to keep wchar_t pattern and compiled pattern. */
2283 CHAR_TYPE *pattern, *COMPILED_BUFFER_VAR;
2284 size_t size;
2285 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
2286 int *mbs_offset = NULL;
2287 /* It hold whether each wchar_t is binary data or not. */
2288 char *is_binary = NULL;
2289 /* A flag whether exactn is handling binary data or not. */
2290 char is_exactn_bin = FALSE;
2291 #endif /* MBS_SUPPORT */
2293 /* A random temporary spot in PATTERN. */
2294 const CHAR_TYPE *p1;
2296 /* Points to the end of the buffer, where we should append. */
2297 register US_CHAR_TYPE *b;
2299 /* Keeps track of unclosed groups. */
2300 compile_stack_type compile_stack;
2302 /* Points to the current (ending) position in the pattern. */
2303 #ifdef MBS_SUPPORT
2304 const CHAR_TYPE *p;
2305 const CHAR_TYPE *pend;
2306 #else
2307 const CHAR_TYPE *p = pattern;
2308 const CHAR_TYPE *pend = pattern + size;
2309 #endif /* MBS_SUPPORT */
2311 /* How to translate the characters in the pattern. */
2312 RE_TRANSLATE_TYPE translate = bufp->translate;
2314 /* Address of the count-byte of the most recently inserted `exactn'
2315 command. This makes it possible to tell if a new exact-match
2316 character can be added to that command or if the character requires
2317 a new `exactn' command. */
2318 US_CHAR_TYPE *pending_exact = 0;
2320 /* Address of start of the most recently finished expression.
2321 This tells, e.g., postfix * where to find the start of its
2322 operand. Reset at the beginning of groups and alternatives. */
2323 US_CHAR_TYPE *laststart = 0;
2325 /* Address of beginning of regexp, or inside of last group. */
2326 US_CHAR_TYPE *begalt;
2328 /* Address of the place where a forward jump should go to the end of
2329 the containing expression. Each alternative of an `or' -- except the
2330 last -- ends with a forward jump of this sort. */
2331 US_CHAR_TYPE *fixup_alt_jump = 0;
2333 /* Counts open-groups as they are encountered. Remembered for the
2334 matching close-group on the compile stack, so the same register
2335 number is put in the stop_memory as the start_memory. */
2336 regnum_t regnum = 0;
2338 #ifdef MBS_SUPPORT
2339 /* Initialize the wchar_t PATTERN and offset_buffer. */
2340 p = pend = pattern = TALLOC(csize + 1, CHAR_TYPE);
2341 mbs_offset = TALLOC(csize + 1, int);
2342 is_binary = TALLOC(csize + 1, char);
2343 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2345 free(pattern);
2346 free(mbs_offset);
2347 free(is_binary);
2348 return REG_ESPACE;
2350 pattern[csize] = L'\0'; /* sentinel */
2351 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2352 pend = p + size;
2353 if (size < 0)
2355 free(pattern);
2356 free(mbs_offset);
2357 free(is_binary);
2358 return REG_BADPAT;
2360 #endif
2362 #ifdef DEBUG
2363 DEBUG_PRINT1 ("\nCompiling pattern: ");
2364 if (debug)
2366 unsigned debug_count;
2368 for (debug_count = 0; debug_count < size; debug_count++)
2369 PUT_CHAR (pattern[debug_count]);
2370 putchar ('\n');
2372 #endif /* DEBUG */
2374 /* Initialize the compile stack. */
2375 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2376 if (compile_stack.stack == NULL)
2378 #ifdef MBS_SUPPORT
2379 free(pattern);
2380 free(mbs_offset);
2381 free(is_binary);
2382 #endif
2383 return REG_ESPACE;
2386 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2387 compile_stack.avail = 0;
2389 /* Initialize the pattern buffer. */
2390 bufp->syntax = syntax;
2391 bufp->fastmap_accurate = 0;
2392 bufp->not_bol = bufp->not_eol = 0;
2394 /* Set `used' to zero, so that if we return an error, the pattern
2395 printer (for debugging) will think there's no pattern. We reset it
2396 at the end. */
2397 bufp->used = 0;
2399 /* Always count groups, whether or not bufp->no_sub is set. */
2400 bufp->re_nsub = 0;
2402 #if !defined emacs && !defined SYNTAX_TABLE
2403 /* Initialize the syntax table. */
2404 init_syntax_once ();
2405 #endif
2407 if (bufp->allocated == 0)
2409 if (bufp->buffer)
2410 { /* If zero allocated, but buffer is non-null, try to realloc
2411 enough space. This loses if buffer's address is bogus, but
2412 that is the user's responsibility. */
2413 #ifdef MBS_SUPPORT
2414 /* Free bufp->buffer and allocate an array for wchar_t pattern
2415 buffer. */
2416 free(bufp->buffer);
2417 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(US_CHAR_TYPE),
2418 US_CHAR_TYPE);
2419 #else
2420 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, US_CHAR_TYPE);
2421 #endif /* MBS_SUPPORT */
2423 else
2424 { /* Caller did not allocate a buffer. Do it for them. */
2425 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(US_CHAR_TYPE),
2426 US_CHAR_TYPE);
2429 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2430 #ifdef MBS_SUPPORT
2431 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2432 #endif /* MBS_SUPPORT */
2433 bufp->allocated = INIT_BUF_SIZE;
2435 #ifdef MBS_SUPPORT
2436 else
2437 COMPILED_BUFFER_VAR = (US_CHAR_TYPE*) bufp->buffer;
2438 #endif
2440 begalt = b = COMPILED_BUFFER_VAR;
2442 /* Loop through the uncompiled pattern until we're at the end. */
2443 while (p != pend)
2445 PATFETCH (c);
2447 switch (c)
2449 case '^':
2451 if ( /* If at start of pattern, it's an operator. */
2452 p == pattern + 1
2453 /* If context independent, it's an operator. */
2454 || syntax & RE_CONTEXT_INDEP_ANCHORS
2455 /* Otherwise, depends on what's come before. */
2456 || at_begline_loc_p (pattern, p, syntax))
2457 BUF_PUSH (begline);
2458 else
2459 goto normal_char;
2461 break;
2464 case '$':
2466 if ( /* If at end of pattern, it's an operator. */
2467 p == pend
2468 /* If context independent, it's an operator. */
2469 || syntax & RE_CONTEXT_INDEP_ANCHORS
2470 /* Otherwise, depends on what's next. */
2471 || at_endline_loc_p (p, pend, syntax))
2472 BUF_PUSH (endline);
2473 else
2474 goto normal_char;
2476 break;
2479 case '+':
2480 case '?':
2481 if ((syntax & RE_BK_PLUS_QM)
2482 || (syntax & RE_LIMITED_OPS))
2483 goto normal_char;
2484 handle_plus:
2485 case '*':
2486 /* If there is no previous pattern... */
2487 if (!laststart)
2489 if (syntax & RE_CONTEXT_INVALID_OPS)
2490 FREE_STACK_RETURN (REG_BADRPT);
2491 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2492 goto normal_char;
2496 /* Are we optimizing this jump? */
2497 boolean keep_string_p = false;
2499 /* 1 means zero (many) matches is allowed. */
2500 char zero_times_ok = 0, many_times_ok = 0;
2502 /* If there is a sequence of repetition chars, collapse it
2503 down to just one (the right one). We can't combine
2504 interval operators with these because of, e.g., `a{2}*',
2505 which should only match an even number of `a's. */
2507 for (;;)
2509 zero_times_ok |= c != '+';
2510 many_times_ok |= c != '?';
2512 if (p == pend)
2513 break;
2515 PATFETCH (c);
2517 if (c == '*'
2518 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2521 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2523 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2525 PATFETCH (c1);
2526 if (!(c1 == '+' || c1 == '?'))
2528 PATUNFETCH;
2529 PATUNFETCH;
2530 break;
2533 c = c1;
2535 else
2537 PATUNFETCH;
2538 break;
2541 /* If we get here, we found another repeat character. */
2544 /* Star, etc. applied to an empty pattern is equivalent
2545 to an empty pattern. */
2546 if (!laststart)
2547 break;
2549 /* Now we know whether or not zero matches is allowed
2550 and also whether or not two or more matches is allowed. */
2551 if (many_times_ok)
2552 { /* More than one repetition is allowed, so put in at the
2553 end a backward relative jump from `b' to before the next
2554 jump we're going to put in below (which jumps from
2555 laststart to after this jump).
2557 But if we are at the `*' in the exact sequence `.*\n',
2558 insert an unconditional jump backwards to the .,
2559 instead of the beginning of the loop. This way we only
2560 push a failure point once, instead of every time
2561 through the loop. */
2562 assert (p - 1 > pattern);
2564 /* Allocate the space for the jump. */
2565 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2567 /* We know we are not at the first character of the pattern,
2568 because laststart was nonzero. And we've already
2569 incremented `p', by the way, to be the character after
2570 the `*'. Do we have to do something analogous here
2571 for null bytes, because of RE_DOT_NOT_NULL? */
2572 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2573 && zero_times_ok
2574 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2575 && !(syntax & RE_DOT_NEWLINE))
2576 { /* We have .*\n. */
2577 STORE_JUMP (jump, b, laststart);
2578 keep_string_p = true;
2580 else
2581 /* Anything else. */
2582 STORE_JUMP (maybe_pop_jump, b, laststart -
2583 (1 + OFFSET_ADDRESS_SIZE));
2585 /* We've added more stuff to the buffer. */
2586 b += 1 + OFFSET_ADDRESS_SIZE;
2589 /* On failure, jump from laststart to b + 3, which will be the
2590 end of the buffer after this jump is inserted. */
2591 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2592 'b + 3'. */
2593 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2594 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2595 : on_failure_jump,
2596 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2597 pending_exact = 0;
2598 b += 1 + OFFSET_ADDRESS_SIZE;
2600 if (!zero_times_ok)
2602 /* At least one repetition is required, so insert a
2603 `dummy_failure_jump' before the initial
2604 `on_failure_jump' instruction of the loop. This
2605 effects a skip over that instruction the first time
2606 we hit that loop. */
2607 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2608 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2609 2 + 2 * OFFSET_ADDRESS_SIZE);
2610 b += 1 + OFFSET_ADDRESS_SIZE;
2613 break;
2616 case '.':
2617 laststart = b;
2618 BUF_PUSH (anychar);
2619 break;
2622 case '[':
2624 boolean had_char_class = false;
2625 #ifdef MBS_SUPPORT
2626 CHAR_TYPE range_start = 0xffffffff;
2627 #else
2628 unsigned int range_start = 0xffffffff;
2629 #endif
2630 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2632 #ifdef MBS_SUPPORT
2633 /* We assume a charset(_not) structure as a wchar_t array.
2634 charset[0] = (re_opcode_t) charset(_not)
2635 charset[1] = l (= length of char_classes)
2636 charset[2] = m (= length of collating_symbols)
2637 charset[3] = n (= length of equivalence_classes)
2638 charset[4] = o (= length of char_ranges)
2639 charset[5] = p (= length of chars)
2641 charset[6] = char_class (wctype_t)
2642 charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2644 charset[l+5] = char_class (wctype_t)
2646 charset[l+6] = collating_symbol (wchar_t)
2648 charset[l+m+5] = collating_symbol (wchar_t)
2649 ifdef _LIBC we use the index if
2650 _NL_COLLATE_SYMB_EXTRAMB instead of
2651 wchar_t string.
2653 charset[l+m+6] = equivalence_classes (wchar_t)
2655 charset[l+m+n+5] = equivalence_classes (wchar_t)
2656 ifdef _LIBC we use the index in
2657 _NL_COLLATE_WEIGHT instead of
2658 wchar_t string.
2660 charset[l+m+n+6] = range_start
2661 charset[l+m+n+7] = range_end
2663 charset[l+m+n+2o+4] = range_start
2664 charset[l+m+n+2o+5] = range_end
2665 ifdef _LIBC we use the value looked up
2666 in _NL_COLLATE_COLLSEQ instead of
2667 wchar_t character.
2669 charset[l+m+n+2o+6] = char
2671 charset[l+m+n+2o+p+5] = char
2675 /* We need at least 6 spaces: the opcode, the length of
2676 char_classes, the length of collating_symbols, the length of
2677 equivalence_classes, the length of char_ranges, the length of
2678 chars. */
2679 GET_BUFFER_SPACE (6);
2681 /* Save b as laststart. And We use laststart as the pointer
2682 to the first element of the charset here.
2683 In other words, laststart[i] indicates charset[i]. */
2684 laststart = b;
2686 /* We test `*p == '^' twice, instead of using an if
2687 statement, so we only need one BUF_PUSH. */
2688 BUF_PUSH (*p == '^' ? charset_not : charset);
2689 if (*p == '^')
2690 p++;
2692 /* Push the length of char_classes, the length of
2693 collating_symbols, the length of equivalence_classes, the
2694 length of char_ranges and the length of chars. */
2695 BUF_PUSH_3 (0, 0, 0);
2696 BUF_PUSH_2 (0, 0);
2698 /* Remember the first position in the bracket expression. */
2699 p1 = p;
2701 /* charset_not matches newline according to a syntax bit. */
2702 if ((re_opcode_t) b[-6] == charset_not
2703 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2705 BUF_PUSH('\n');
2706 laststart[5]++; /* Update the length of characters */
2709 /* Read in characters and ranges, setting map bits. */
2710 for (;;)
2712 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2714 PATFETCH (c);
2716 /* \ might escape characters inside [...] and [^...]. */
2717 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2719 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2721 PATFETCH (c1);
2722 BUF_PUSH(c1);
2723 laststart[5]++; /* Update the length of chars */
2724 range_start = c1;
2725 continue;
2728 /* Could be the end of the bracket expression. If it's
2729 not (i.e., when the bracket expression is `[]' so
2730 far), the ']' character bit gets set way below. */
2731 if (c == ']' && p != p1 + 1)
2732 break;
2734 /* Look ahead to see if it's a range when the last thing
2735 was a character class. */
2736 if (had_char_class && c == '-' && *p != ']')
2737 FREE_STACK_RETURN (REG_ERANGE);
2739 /* Look ahead to see if it's a range when the last thing
2740 was a character: if this is a hyphen not at the
2741 beginning or the end of a list, then it's the range
2742 operator. */
2743 if (c == '-'
2744 && !(p - 2 >= pattern && p[-2] == '[')
2745 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2746 && *p != ']')
2748 reg_errcode_t ret;
2749 /* Allocate the space for range_start and range_end. */
2750 GET_BUFFER_SPACE (2);
2751 /* Update the pointer to indicate end of buffer. */
2752 b += 2;
2753 ret = compile_range (range_start, &p, pend, translate,
2754 syntax, b, laststart);
2755 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2756 range_start = 0xffffffff;
2758 else if (p[0] == '-' && p[1] != ']')
2759 { /* This handles ranges made up of characters only. */
2760 reg_errcode_t ret;
2762 /* Move past the `-'. */
2763 PATFETCH (c1);
2764 /* Allocate the space for range_start and range_end. */
2765 GET_BUFFER_SPACE (2);
2766 /* Update the pointer to indicate end of buffer. */
2767 b += 2;
2768 ret = compile_range (c, &p, pend, translate, syntax, b,
2769 laststart);
2770 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2771 range_start = 0xffffffff;
2774 /* See if we're at the beginning of a possible character
2775 class. */
2776 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2777 { /* Leave room for the null. */
2778 char str[CHAR_CLASS_MAX_LENGTH + 1];
2780 PATFETCH (c);
2781 c1 = 0;
2783 /* If pattern is `[[:'. */
2784 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2786 for (;;)
2788 PATFETCH (c);
2789 if ((c == ':' && *p == ']') || p == pend)
2790 break;
2791 if (c1 < CHAR_CLASS_MAX_LENGTH)
2792 str[c1++] = c;
2793 else
2794 /* This is in any case an invalid class name. */
2795 str[0] = '\0';
2797 str[c1] = '\0';
2799 /* If isn't a word bracketed by `[:' and `:]':
2800 undo the ending character, the letters, and leave
2801 the leading `:' and `[' (but store them as character). */
2802 if (c == ':' && *p == ']')
2804 wctype_t wt;
2805 uintptr_t alignedp;
2807 /* Query the character class as wctype_t. */
2808 wt = IS_CHAR_CLASS (str);
2809 if (wt == 0)
2810 FREE_STACK_RETURN (REG_ECTYPE);
2812 /* Throw away the ] at the end of the character
2813 class. */
2814 PATFETCH (c);
2816 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2818 /* Allocate the space for character class. */
2819 GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2820 /* Update the pointer to indicate end of buffer. */
2821 b += CHAR_CLASS_SIZE;
2822 /* Move data which follow character classes
2823 not to violate the data. */
2824 insert_space(CHAR_CLASS_SIZE,
2825 laststart + 6 + laststart[1],
2826 b - 1);
2827 alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2828 + __alignof__(wctype_t) - 1)
2829 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2830 /* Store the character class. */
2831 *((wctype_t*)alignedp) = wt;
2832 /* Update length of char_classes */
2833 laststart[1] += CHAR_CLASS_SIZE;
2835 had_char_class = true;
2837 else
2839 c1++;
2840 while (c1--)
2841 PATUNFETCH;
2842 BUF_PUSH ('[');
2843 BUF_PUSH (':');
2844 laststart[5] += 2; /* Update the length of characters */
2845 range_start = ':';
2846 had_char_class = false;
2849 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2850 || *p == '.'))
2852 CHAR_TYPE str[128]; /* Should be large enough. */
2853 CHAR_TYPE delim = *p; /* '=' or '.' */
2854 # ifdef _LIBC
2855 uint32_t nrules =
2856 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2857 # endif
2858 PATFETCH (c);
2859 c1 = 0;
2861 /* If pattern is `[[=' or '[[.'. */
2862 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2864 for (;;)
2866 PATFETCH (c);
2867 if ((c == delim && *p == ']') || p == pend)
2868 break;
2869 if (c1 < sizeof (str) - 1)
2870 str[c1++] = c;
2871 else
2872 /* This is in any case an invalid class name. */
2873 str[0] = '\0';
2875 str[c1] = '\0';
2877 if (c == delim && *p == ']' && str[0] != '\0')
2879 unsigned int i, offset;
2880 /* If we have no collation data we use the default
2881 collation in which each character is in a class
2882 by itself. It also means that ASCII is the
2883 character set and therefore we cannot have character
2884 with more than one byte in the multibyte
2885 representation. */
2887 /* If not defined _LIBC, we push the name and
2888 `\0' for the sake of matching performance. */
2889 int datasize = c1 + 1;
2891 # ifdef _LIBC
2892 int32_t idx = 0;
2893 if (nrules == 0)
2894 # endif
2896 if (c1 != 1)
2897 FREE_STACK_RETURN (REG_ECOLLATE);
2899 # ifdef _LIBC
2900 else
2902 const int32_t *table;
2903 const int32_t *weights;
2904 const int32_t *extra;
2905 const int32_t *indirect;
2906 wint_t *cp;
2908 /* This #include defines a local function! */
2909 # include <locale/weightwc.h>
2911 if(delim == '=')
2913 /* We push the index for equivalence class. */
2914 cp = (wint_t*)str;
2916 table = (const int32_t *)
2917 _NL_CURRENT (LC_COLLATE,
2918 _NL_COLLATE_TABLEWC);
2919 weights = (const int32_t *)
2920 _NL_CURRENT (LC_COLLATE,
2921 _NL_COLLATE_WEIGHTWC);
2922 extra = (const int32_t *)
2923 _NL_CURRENT (LC_COLLATE,
2924 _NL_COLLATE_EXTRAWC);
2925 indirect = (const int32_t *)
2926 _NL_CURRENT (LC_COLLATE,
2927 _NL_COLLATE_INDIRECTWC);
2929 idx = findidx ((const wint_t**)&cp);
2930 if (idx == 0 || cp < (wint_t*) str + c1)
2931 /* This is no valid character. */
2932 FREE_STACK_RETURN (REG_ECOLLATE);
2934 str[0] = (wchar_t)idx;
2936 else /* delim == '.' */
2938 /* We push collation sequence value
2939 for collating symbol. */
2940 int32_t table_size;
2941 const int32_t *symb_table;
2942 const unsigned char *extra;
2943 int32_t idx;
2944 int32_t elem;
2945 int32_t second;
2946 int32_t hash;
2947 char char_str[c1];
2949 /* We have to convert the name to a single-byte
2950 string. This is possible since the names
2951 consist of ASCII characters and the internal
2952 representation is UCS4. */
2953 for (i = 0; i < c1; ++i)
2954 char_str[i] = str[i];
2956 table_size =
2957 _NL_CURRENT_WORD (LC_COLLATE,
2958 _NL_COLLATE_SYMB_HASH_SIZEMB);
2959 symb_table = (const int32_t *)
2960 _NL_CURRENT (LC_COLLATE,
2961 _NL_COLLATE_SYMB_TABLEMB);
2962 extra = (const unsigned char *)
2963 _NL_CURRENT (LC_COLLATE,
2964 _NL_COLLATE_SYMB_EXTRAMB);
2966 /* Locate the character in the hashing table. */
2967 hash = elem_hash (char_str, c1);
2969 idx = 0;
2970 elem = hash % table_size;
2971 second = hash % (table_size - 2);
2972 while (symb_table[2 * elem] != 0)
2974 /* First compare the hashing value. */
2975 if (symb_table[2 * elem] == hash
2976 && c1 == extra[symb_table[2 * elem + 1]]
2977 && memcmp (str,
2978 &extra[symb_table[2 * elem + 1]
2979 + 1], c1) == 0)
2981 /* Yep, this is the entry. */
2982 idx = symb_table[2 * elem + 1];
2983 idx += 1 + extra[idx];
2984 break;
2987 /* Next entry. */
2988 elem += second;
2991 if (symb_table[2 * elem] != 0)
2993 /* Compute the index of the byte sequence
2994 in the table. */
2995 idx += 1 + extra[idx];
2996 /* Adjust for the alignment. */
2997 idx = (idx + 3) & ~4;
2999 str[0] = (wchar_t) idx + 4;
3001 else if (symb_table[2 * elem] == 0 && c1 == 1)
3003 /* No valid character. Match it as a
3004 single byte character. */
3005 had_char_class = false;
3006 BUF_PUSH(str[0]);
3007 /* Update the length of characters */
3008 laststart[5]++;
3009 range_start = str[0];
3011 /* Throw away the ] at the end of the
3012 collating symbol. */
3013 PATFETCH (c);
3014 /* exit from the switch block. */
3015 continue;
3017 else
3018 FREE_STACK_RETURN (REG_ECOLLATE);
3020 datasize = 1;
3022 # endif
3023 /* Throw away the ] at the end of the equivalence
3024 class (or collating symbol). */
3025 PATFETCH (c);
3027 /* Allocate the space for the equivalence class
3028 (or collating symbol) (and '\0' if needed). */
3029 GET_BUFFER_SPACE(datasize);
3030 /* Update the pointer to indicate end of buffer. */
3031 b += datasize;
3033 if (delim == '=')
3034 { /* equivalence class */
3035 /* Calculate the offset of char_ranges,
3036 which is next to equivalence_classes. */
3037 offset = laststart[1] + laststart[2]
3038 + laststart[3] +6;
3039 /* Insert space. */
3040 insert_space(datasize, laststart + offset, b - 1);
3042 /* Write the equivalence_class and \0. */
3043 for (i = 0 ; i < datasize ; i++)
3044 laststart[offset + i] = str[i];
3046 /* Update the length of equivalence_classes. */
3047 laststart[3] += datasize;
3048 had_char_class = true;
3050 else /* delim == '.' */
3051 { /* collating symbol */
3052 /* Calculate the offset of the equivalence_classes,
3053 which is next to collating_symbols. */
3054 offset = laststart[1] + laststart[2] + 6;
3055 /* Insert space and write the collationg_symbol
3056 and \0. */
3057 insert_space(datasize, laststart + offset, b-1);
3058 for (i = 0 ; i < datasize ; i++)
3059 laststart[offset + i] = str[i];
3061 /* In re_match_2_internal if range_start < -1, we
3062 assume -range_start is the offset of the
3063 collating symbol which is specified as
3064 the character of the range start. So we assign
3065 -(laststart[1] + laststart[2] + 6) to
3066 range_start. */
3067 range_start = -(laststart[1] + laststart[2] + 6);
3068 /* Update the length of collating_symbol. */
3069 laststart[2] += datasize;
3070 had_char_class = false;
3073 else
3075 c1++;
3076 while (c1--)
3077 PATUNFETCH;
3078 BUF_PUSH ('[');
3079 BUF_PUSH (delim);
3080 laststart[5] += 2; /* Update the length of characters */
3081 range_start = delim;
3082 had_char_class = false;
3085 else
3087 had_char_class = false;
3088 BUF_PUSH(c);
3089 laststart[5]++; /* Update the length of characters */
3090 range_start = c;
3094 #else /* not MBS_SUPPORT */
3095 /* Ensure that we have enough space to push a charset: the
3096 opcode, the length count, and the bitset; 34 bytes in all. */
3097 GET_BUFFER_SPACE (34);
3099 laststart = b;
3101 /* We test `*p == '^' twice, instead of using an if
3102 statement, so we only need one BUF_PUSH. */
3103 BUF_PUSH (*p == '^' ? charset_not : charset);
3104 if (*p == '^')
3105 p++;
3107 /* Remember the first position in the bracket expression. */
3108 p1 = p;
3110 /* Push the number of bytes in the bitmap. */
3111 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3113 /* Clear the whole map. */
3114 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3116 /* charset_not matches newline according to a syntax bit. */
3117 if ((re_opcode_t) b[-2] == charset_not
3118 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3119 SET_LIST_BIT ('\n');
3121 /* Read in characters and ranges, setting map bits. */
3122 for (;;)
3124 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3126 PATFETCH (c);
3128 /* \ might escape characters inside [...] and [^...]. */
3129 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3131 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3133 PATFETCH (c1);
3134 SET_LIST_BIT (c1);
3135 range_start = c1;
3136 continue;
3139 /* Could be the end of the bracket expression. If it's
3140 not (i.e., when the bracket expression is `[]' so
3141 far), the ']' character bit gets set way below. */
3142 if (c == ']' && p != p1 + 1)
3143 break;
3145 /* Look ahead to see if it's a range when the last thing
3146 was a character class. */
3147 if (had_char_class && c == '-' && *p != ']')
3148 FREE_STACK_RETURN (REG_ERANGE);
3150 /* Look ahead to see if it's a range when the last thing
3151 was a character: if this is a hyphen not at the
3152 beginning or the end of a list, then it's the range
3153 operator. */
3154 if (c == '-'
3155 && !(p - 2 >= pattern && p[-2] == '[')
3156 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3157 && *p != ']')
3159 reg_errcode_t ret
3160 = compile_range (range_start, &p, pend, translate,
3161 syntax, b);
3162 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3163 range_start = 0xffffffff;
3166 else if (p[0] == '-' && p[1] != ']')
3167 { /* This handles ranges made up of characters only. */
3168 reg_errcode_t ret;
3170 /* Move past the `-'. */
3171 PATFETCH (c1);
3173 ret = compile_range (c, &p, pend, translate, syntax, b);
3174 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3175 range_start = 0xffffffff;
3178 /* See if we're at the beginning of a possible character
3179 class. */
3181 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3182 { /* Leave room for the null. */
3183 char str[CHAR_CLASS_MAX_LENGTH + 1];
3185 PATFETCH (c);
3186 c1 = 0;
3188 /* If pattern is `[[:'. */
3189 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3191 for (;;)
3193 PATFETCH (c);
3194 if ((c == ':' && *p == ']') || p == pend)
3195 break;
3196 if (c1 < CHAR_CLASS_MAX_LENGTH)
3197 str[c1++] = c;
3198 else
3199 /* This is in any case an invalid class name. */
3200 str[0] = '\0';
3202 str[c1] = '\0';
3204 /* If isn't a word bracketed by `[:' and `:]':
3205 undo the ending character, the letters, and leave
3206 the leading `:' and `[' (but set bits for them). */
3207 if (c == ':' && *p == ']')
3209 # if defined _LIBC || WIDE_CHAR_SUPPORT
3210 boolean is_lower = STREQ (str, "lower");
3211 boolean is_upper = STREQ (str, "upper");
3212 wctype_t wt;
3213 int ch;
3215 wt = IS_CHAR_CLASS (str);
3216 if (wt == 0)
3217 FREE_STACK_RETURN (REG_ECTYPE);
3219 /* Throw away the ] at the end of the character
3220 class. */
3221 PATFETCH (c);
3223 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3225 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3227 # ifdef _LIBC
3228 if (__iswctype (__btowc (ch), wt))
3229 SET_LIST_BIT (ch);
3230 # else
3231 if (iswctype (btowc (ch), wt))
3232 SET_LIST_BIT (ch);
3233 # endif
3235 if (translate && (is_upper || is_lower)
3236 && (ISUPPER (ch) || ISLOWER (ch)))
3237 SET_LIST_BIT (ch);
3240 had_char_class = true;
3241 # else
3242 int ch;
3243 boolean is_alnum = STREQ (str, "alnum");
3244 boolean is_alpha = STREQ (str, "alpha");
3245 boolean is_blank = STREQ (str, "blank");
3246 boolean is_cntrl = STREQ (str, "cntrl");
3247 boolean is_digit = STREQ (str, "digit");
3248 boolean is_graph = STREQ (str, "graph");
3249 boolean is_lower = STREQ (str, "lower");
3250 boolean is_print = STREQ (str, "print");
3251 boolean is_punct = STREQ (str, "punct");
3252 boolean is_space = STREQ (str, "space");
3253 boolean is_upper = STREQ (str, "upper");
3254 boolean is_xdigit = STREQ (str, "xdigit");
3256 if (!IS_CHAR_CLASS (str))
3257 FREE_STACK_RETURN (REG_ECTYPE);
3259 /* Throw away the ] at the end of the character
3260 class. */
3261 PATFETCH (c);
3263 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3265 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3267 /* This was split into 3 if's to
3268 avoid an arbitrary limit in some compiler. */
3269 if ( (is_alnum && ISALNUM (ch))
3270 || (is_alpha && ISALPHA (ch))
3271 || (is_blank && ISBLANK (ch))
3272 || (is_cntrl && ISCNTRL (ch)))
3273 SET_LIST_BIT (ch);
3274 if ( (is_digit && ISDIGIT (ch))
3275 || (is_graph && ISGRAPH (ch))
3276 || (is_lower && ISLOWER (ch))
3277 || (is_print && ISPRINT (ch)))
3278 SET_LIST_BIT (ch);
3279 if ( (is_punct && ISPUNCT (ch))
3280 || (is_space && ISSPACE (ch))
3281 || (is_upper && ISUPPER (ch))
3282 || (is_xdigit && ISXDIGIT (ch)))
3283 SET_LIST_BIT (ch);
3284 if ( translate && (is_upper || is_lower)
3285 && (ISUPPER (ch) || ISLOWER (ch)))
3286 SET_LIST_BIT (ch);
3288 had_char_class = true;
3289 # endif /* libc || wctype.h */
3291 else
3293 c1++;
3294 while (c1--)
3295 PATUNFETCH;
3296 SET_LIST_BIT ('[');
3297 SET_LIST_BIT (':');
3298 range_start = ':';
3299 had_char_class = false;
3302 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3304 unsigned char str[MB_LEN_MAX + 1];
3305 # ifdef _LIBC
3306 uint32_t nrules =
3307 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3308 # endif
3310 PATFETCH (c);
3311 c1 = 0;
3313 /* If pattern is `[[='. */
3314 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3316 for (;;)
3318 PATFETCH (c);
3319 if ((c == '=' && *p == ']') || p == pend)
3320 break;
3321 if (c1 < MB_LEN_MAX)
3322 str[c1++] = c;
3323 else
3324 /* This is in any case an invalid class name. */
3325 str[0] = '\0';
3327 str[c1] = '\0';
3329 if (c == '=' && *p == ']' && str[0] != '\0')
3331 /* If we have no collation data we use the default
3332 collation in which each character is in a class
3333 by itself. It also means that ASCII is the
3334 character set and therefore we cannot have character
3335 with more than one byte in the multibyte
3336 representation. */
3337 # ifdef _LIBC
3338 if (nrules == 0)
3339 # endif
3341 if (c1 != 1)
3342 FREE_STACK_RETURN (REG_ECOLLATE);
3344 /* Throw away the ] at the end of the equivalence
3345 class. */
3346 PATFETCH (c);
3348 /* Set the bit for the character. */
3349 SET_LIST_BIT (str[0]);
3351 # ifdef _LIBC
3352 else
3354 /* Try to match the byte sequence in `str' against
3355 those known to the collate implementation.
3356 First find out whether the bytes in `str' are
3357 actually from exactly one character. */
3358 const int32_t *table;
3359 const unsigned char *weights;
3360 const unsigned char *extra;
3361 const int32_t *indirect;
3362 int32_t idx;
3363 const unsigned char *cp = str;
3364 int ch;
3366 /* This #include defines a local function! */
3367 # include <locale/weight.h>
3369 table = (const int32_t *)
3370 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3371 weights = (const unsigned char *)
3372 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3373 extra = (const unsigned char *)
3374 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3375 indirect = (const int32_t *)
3376 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3378 idx = findidx (&cp);
3379 if (idx == 0 || cp < str + c1)
3380 /* This is no valid character. */
3381 FREE_STACK_RETURN (REG_ECOLLATE);
3383 /* Throw away the ] at the end of the equivalence
3384 class. */
3385 PATFETCH (c);
3387 /* Now we have to go throught the whole table
3388 and find all characters which have the same
3389 first level weight.
3391 XXX Note that this is not entirely correct.
3392 we would have to match multibyte sequences
3393 but this is not possible with the current
3394 implementation. */
3395 for (ch = 1; ch < 256; ++ch)
3396 /* XXX This test would have to be changed if we
3397 would allow matching multibyte sequences. */
3398 if (table[ch] > 0)
3400 int32_t idx2 = table[ch];
3401 size_t len = weights[idx2];
3403 /* Test whether the lenghts match. */
3404 if (weights[idx] == len)
3406 /* They do. New compare the bytes of
3407 the weight. */
3408 size_t cnt = 0;
3410 while (cnt < len
3411 && (weights[idx + 1 + cnt]
3412 == weights[idx2 + 1 + cnt]))
3413 ++cnt;
3415 if (cnt == len)
3416 /* They match. Mark the character as
3417 acceptable. */
3418 SET_LIST_BIT (ch);
3422 # endif
3423 had_char_class = true;
3425 else
3427 c1++;
3428 while (c1--)
3429 PATUNFETCH;
3430 SET_LIST_BIT ('[');
3431 SET_LIST_BIT ('=');
3432 range_start = '=';
3433 had_char_class = false;
3436 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3438 unsigned char str[128]; /* Should be large enough. */
3439 # ifdef _LIBC
3440 uint32_t nrules =
3441 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3442 # endif
3444 PATFETCH (c);
3445 c1 = 0;
3447 /* If pattern is `[[.'. */
3448 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3450 for (;;)
3452 PATFETCH (c);
3453 if ((c == '.' && *p == ']') || p == pend)
3454 break;
3455 if (c1 < sizeof (str))
3456 str[c1++] = c;
3457 else
3458 /* This is in any case an invalid class name. */
3459 str[0] = '\0';
3461 str[c1] = '\0';
3463 if (c == '.' && *p == ']' && str[0] != '\0')
3465 /* If we have no collation data we use the default
3466 collation in which each character is the name
3467 for its own class which contains only the one
3468 character. It also means that ASCII is the
3469 character set and therefore we cannot have character
3470 with more than one byte in the multibyte
3471 representation. */
3472 # ifdef _LIBC
3473 if (nrules == 0)
3474 # endif
3476 if (c1 != 1)
3477 FREE_STACK_RETURN (REG_ECOLLATE);
3479 /* Throw away the ] at the end of the equivalence
3480 class. */
3481 PATFETCH (c);
3483 /* Set the bit for the character. */
3484 SET_LIST_BIT (str[0]);
3485 range_start = ((const unsigned char *) str)[0];
3487 # ifdef _LIBC
3488 else
3490 /* Try to match the byte sequence in `str' against
3491 those known to the collate implementation.
3492 First find out whether the bytes in `str' are
3493 actually from exactly one character. */
3494 int32_t table_size;
3495 const int32_t *symb_table;
3496 const unsigned char *extra;
3497 int32_t idx;
3498 int32_t elem;
3499 int32_t second;
3500 int32_t hash;
3502 table_size =
3503 _NL_CURRENT_WORD (LC_COLLATE,
3504 _NL_COLLATE_SYMB_HASH_SIZEMB);
3505 symb_table = (const int32_t *)
3506 _NL_CURRENT (LC_COLLATE,
3507 _NL_COLLATE_SYMB_TABLEMB);
3508 extra = (const unsigned char *)
3509 _NL_CURRENT (LC_COLLATE,
3510 _NL_COLLATE_SYMB_EXTRAMB);
3512 /* Locate the character in the hashing table. */
3513 hash = elem_hash (str, c1);
3515 idx = 0;
3516 elem = hash % table_size;
3517 second = hash % (table_size - 2);
3518 while (symb_table[2 * elem] != 0)
3520 /* First compare the hashing value. */
3521 if (symb_table[2 * elem] == hash
3522 && c1 == extra[symb_table[2 * elem + 1]]
3523 && memcmp (str,
3524 &extra[symb_table[2 * elem + 1]
3525 + 1],
3526 c1) == 0)
3528 /* Yep, this is the entry. */
3529 idx = symb_table[2 * elem + 1];
3530 idx += 1 + extra[idx];
3531 break;
3534 /* Next entry. */
3535 elem += second;
3538 if (symb_table[2 * elem] == 0)
3539 /* This is no valid character. */
3540 FREE_STACK_RETURN (REG_ECOLLATE);
3542 /* Throw away the ] at the end of the equivalence
3543 class. */
3544 PATFETCH (c);
3546 /* Now add the multibyte character(s) we found
3547 to the accept list.
3549 XXX Note that this is not entirely correct.
3550 we would have to match multibyte sequences
3551 but this is not possible with the current
3552 implementation. Also, we have to match
3553 collating symbols, which expand to more than
3554 one file, as a whole and not allow the
3555 individual bytes. */
3556 c1 = extra[idx++];
3557 if (c1 == 1)
3558 range_start = extra[idx];
3559 while (c1-- > 0)
3561 SET_LIST_BIT (extra[idx]);
3562 ++idx;
3565 # endif
3566 had_char_class = false;
3568 else
3570 c1++;
3571 while (c1--)
3572 PATUNFETCH;
3573 SET_LIST_BIT ('[');
3574 SET_LIST_BIT ('.');
3575 range_start = '.';
3576 had_char_class = false;
3579 else
3581 had_char_class = false;
3582 SET_LIST_BIT (c);
3583 range_start = c;
3587 /* Discard any (non)matching list bytes that are all 0 at the
3588 end of the map. Decrease the map-length byte too. */
3589 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3590 b[-1]--;
3591 b += b[-1];
3592 #endif /* MBS_SUPPORT */
3594 break;
3597 case '(':
3598 if (syntax & RE_NO_BK_PARENS)
3599 goto handle_open;
3600 else
3601 goto normal_char;
3604 case ')':
3605 if (syntax & RE_NO_BK_PARENS)
3606 goto handle_close;
3607 else
3608 goto normal_char;
3611 case '\n':
3612 if (syntax & RE_NEWLINE_ALT)
3613 goto handle_alt;
3614 else
3615 goto normal_char;
3618 case '|':
3619 if (syntax & RE_NO_BK_VBAR)
3620 goto handle_alt;
3621 else
3622 goto normal_char;
3625 case '{':
3626 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3627 goto handle_interval;
3628 else
3629 goto normal_char;
3632 case '\\':
3633 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3635 /* Do not translate the character after the \, so that we can
3636 distinguish, e.g., \B from \b, even if we normally would
3637 translate, e.g., B to b. */
3638 PATFETCH_RAW (c);
3640 switch (c)
3642 case '(':
3643 if (syntax & RE_NO_BK_PARENS)
3644 goto normal_backslash;
3646 handle_open:
3647 bufp->re_nsub++;
3648 regnum++;
3650 if (COMPILE_STACK_FULL)
3652 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3653 compile_stack_elt_t);
3654 if (compile_stack.stack == NULL) return REG_ESPACE;
3656 compile_stack.size <<= 1;
3659 /* These are the values to restore when we hit end of this
3660 group. They are all relative offsets, so that if the
3661 whole pattern moves because of realloc, they will still
3662 be valid. */
3663 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3664 COMPILE_STACK_TOP.fixup_alt_jump
3665 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3666 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3667 COMPILE_STACK_TOP.regnum = regnum;
3669 /* We will eventually replace the 0 with the number of
3670 groups inner to this one. But do not push a
3671 start_memory for groups beyond the last one we can
3672 represent in the compiled pattern. */
3673 if (regnum <= MAX_REGNUM)
3675 COMPILE_STACK_TOP.inner_group_offset = b
3676 - COMPILED_BUFFER_VAR + 2;
3677 BUF_PUSH_3 (start_memory, regnum, 0);
3680 compile_stack.avail++;
3682 fixup_alt_jump = 0;
3683 laststart = 0;
3684 begalt = b;
3685 /* If we've reached MAX_REGNUM groups, then this open
3686 won't actually generate any code, so we'll have to
3687 clear pending_exact explicitly. */
3688 pending_exact = 0;
3689 break;
3692 case ')':
3693 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3695 if (COMPILE_STACK_EMPTY)
3697 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3698 goto normal_backslash;
3699 else
3700 FREE_STACK_RETURN (REG_ERPAREN);
3703 handle_close:
3704 if (fixup_alt_jump)
3705 { /* Push a dummy failure point at the end of the
3706 alternative for a possible future
3707 `pop_failure_jump' to pop. See comments at
3708 `push_dummy_failure' in `re_match_2'. */
3709 BUF_PUSH (push_dummy_failure);
3711 /* We allocated space for this jump when we assigned
3712 to `fixup_alt_jump', in the `handle_alt' case below. */
3713 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3716 /* See similar code for backslashed left paren above. */
3717 if (COMPILE_STACK_EMPTY)
3719 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3720 goto normal_char;
3721 else
3722 FREE_STACK_RETURN (REG_ERPAREN);
3725 /* Since we just checked for an empty stack above, this
3726 ``can't happen''. */
3727 assert (compile_stack.avail != 0);
3729 /* We don't just want to restore into `regnum', because
3730 later groups should continue to be numbered higher,
3731 as in `(ab)c(de)' -- the second group is #2. */
3732 regnum_t this_group_regnum;
3734 compile_stack.avail--;
3735 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3736 fixup_alt_jump
3737 = COMPILE_STACK_TOP.fixup_alt_jump
3738 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3739 : 0;
3740 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3741 this_group_regnum = COMPILE_STACK_TOP.regnum;
3742 /* If we've reached MAX_REGNUM groups, then this open
3743 won't actually generate any code, so we'll have to
3744 clear pending_exact explicitly. */
3745 pending_exact = 0;
3747 /* We're at the end of the group, so now we know how many
3748 groups were inside this one. */
3749 if (this_group_regnum <= MAX_REGNUM)
3751 US_CHAR_TYPE *inner_group_loc
3752 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3754 *inner_group_loc = regnum - this_group_regnum;
3755 BUF_PUSH_3 (stop_memory, this_group_regnum,
3756 regnum - this_group_regnum);
3759 break;
3762 case '|': /* `\|'. */
3763 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3764 goto normal_backslash;
3765 handle_alt:
3766 if (syntax & RE_LIMITED_OPS)
3767 goto normal_char;
3769 /* Insert before the previous alternative a jump which
3770 jumps to this alternative if the former fails. */
3771 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3772 INSERT_JUMP (on_failure_jump, begalt,
3773 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3774 pending_exact = 0;
3775 b += 1 + OFFSET_ADDRESS_SIZE;
3777 /* The alternative before this one has a jump after it
3778 which gets executed if it gets matched. Adjust that
3779 jump so it will jump to this alternative's analogous
3780 jump (put in below, which in turn will jump to the next
3781 (if any) alternative's such jump, etc.). The last such
3782 jump jumps to the correct final destination. A picture:
3783 _____ _____
3784 | | | |
3785 | v | v
3786 a | b | c
3788 If we are at `b', then fixup_alt_jump right now points to a
3789 three-byte space after `a'. We'll put in the jump, set
3790 fixup_alt_jump to right after `b', and leave behind three
3791 bytes which we'll fill in when we get to after `c'. */
3793 if (fixup_alt_jump)
3794 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3796 /* Mark and leave space for a jump after this alternative,
3797 to be filled in later either by next alternative or
3798 when know we're at the end of a series of alternatives. */
3799 fixup_alt_jump = b;
3800 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3801 b += 1 + OFFSET_ADDRESS_SIZE;
3803 laststart = 0;
3804 begalt = b;
3805 break;
3808 case '{':
3809 /* If \{ is a literal. */
3810 if (!(syntax & RE_INTERVALS)
3811 /* If we're at `\{' and it's not the open-interval
3812 operator. */
3813 || (syntax & RE_NO_BK_BRACES))
3814 goto normal_backslash;
3816 handle_interval:
3818 /* If got here, then the syntax allows intervals. */
3820 /* At least (most) this many matches must be made. */
3821 int lower_bound = -1, upper_bound = -1;
3823 /* Place in the uncompiled pattern (i.e., just after
3824 the '{') to go back to if the interval is invalid. */
3825 const CHAR_TYPE *beg_interval = p;
3827 if (p == pend)
3828 goto invalid_interval;
3830 GET_UNSIGNED_NUMBER (lower_bound);
3832 if (c == ',')
3834 GET_UNSIGNED_NUMBER (upper_bound);
3835 if (upper_bound < 0)
3836 upper_bound = RE_DUP_MAX;
3838 else
3839 /* Interval such as `{1}' => match exactly once. */
3840 upper_bound = lower_bound;
3842 if (! (0 <= lower_bound && lower_bound <= upper_bound))
3843 goto invalid_interval;
3845 if (!(syntax & RE_NO_BK_BRACES))
3847 if (c != '\\' || p == pend)
3848 goto invalid_interval;
3849 PATFETCH (c);
3852 if (c != '}')
3853 goto invalid_interval;
3855 /* If it's invalid to have no preceding re. */
3856 if (!laststart)
3858 if (syntax & RE_CONTEXT_INVALID_OPS
3859 && !(syntax & RE_INVALID_INTERVAL_ORD))
3860 FREE_STACK_RETURN (REG_BADRPT);
3861 else if (syntax & RE_CONTEXT_INDEP_OPS)
3862 laststart = b;
3863 else
3864 goto unfetch_interval;
3867 /* We just parsed a valid interval. */
3869 if (RE_DUP_MAX < upper_bound)
3870 FREE_STACK_RETURN (REG_BADBR);
3872 /* If the upper bound is zero, don't want to succeed at
3873 all; jump from `laststart' to `b + 3', which will be
3874 the end of the buffer after we insert the jump. */
3875 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE'
3876 instead of 'b + 3'. */
3877 if (upper_bound == 0)
3879 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3880 INSERT_JUMP (jump, laststart, b + 1
3881 + OFFSET_ADDRESS_SIZE);
3882 b += 1 + OFFSET_ADDRESS_SIZE;
3885 /* Otherwise, we have a nontrivial interval. When
3886 we're all done, the pattern will look like:
3887 set_number_at <jump count> <upper bound>
3888 set_number_at <succeed_n count> <lower bound>
3889 succeed_n <after jump addr> <succeed_n count>
3890 <body of loop>
3891 jump_n <succeed_n addr> <jump count>
3892 (The upper bound and `jump_n' are omitted if
3893 `upper_bound' is 1, though.) */
3894 else
3895 { /* If the upper bound is > 1, we need to insert
3896 more at the end of the loop. */
3897 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3898 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3900 GET_BUFFER_SPACE (nbytes);
3902 /* Initialize lower bound of the `succeed_n', even
3903 though it will be set during matching by its
3904 attendant `set_number_at' (inserted next),
3905 because `re_compile_fastmap' needs to know.
3906 Jump to the `jump_n' we might insert below. */
3907 INSERT_JUMP2 (succeed_n, laststart,
3908 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3909 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3910 , lower_bound);
3911 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3913 /* Code to initialize the lower bound. Insert
3914 before the `succeed_n'. The `5' is the last two
3915 bytes of this `set_number_at', plus 3 bytes of
3916 the following `succeed_n'. */
3917 /* ifdef MBS_SUPPORT, The '1+2*OFFSET_ADDRESS_SIZE'
3918 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3919 of the following `succeed_n'. */
3920 insert_op2 (set_number_at, laststart, 1
3921 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3922 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3924 if (upper_bound > 1)
3925 { /* More than one repetition is allowed, so
3926 append a backward jump to the `succeed_n'
3927 that starts this interval.
3929 When we've reached this during matching,
3930 we'll have matched the interval once, so
3931 jump back only `upper_bound - 1' times. */
3932 STORE_JUMP2 (jump_n, b, laststart
3933 + 2 * OFFSET_ADDRESS_SIZE + 1,
3934 upper_bound - 1);
3935 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3937 /* The location we want to set is the second
3938 parameter of the `jump_n'; that is `b-2' as
3939 an absolute address. `laststart' will be
3940 the `set_number_at' we're about to insert;
3941 `laststart+3' the number to set, the source
3942 for the relative address. But we are
3943 inserting into the middle of the pattern --
3944 so everything is getting moved up by 5.
3945 Conclusion: (b - 2) - (laststart + 3) + 5,
3946 i.e., b - laststart.
3948 We insert this at the beginning of the loop
3949 so that if we fail during matching, we'll
3950 reinitialize the bounds. */
3951 insert_op2 (set_number_at, laststart, b - laststart,
3952 upper_bound - 1, b);
3953 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3956 pending_exact = 0;
3957 break;
3959 invalid_interval:
3960 if (!(syntax & RE_INVALID_INTERVAL_ORD))
3961 FREE_STACK_RETURN (p == pend ? REG_EBRACE : REG_BADBR);
3962 unfetch_interval:
3963 /* Match the characters as literals. */
3964 p = beg_interval;
3965 c = '{';
3966 if (syntax & RE_NO_BK_BRACES)
3967 goto normal_char;
3968 else
3969 goto normal_backslash;
3972 #ifdef emacs
3973 /* There is no way to specify the before_dot and after_dot
3974 operators. rms says this is ok. --karl */
3975 case '=':
3976 BUF_PUSH (at_dot);
3977 break;
3979 case 's':
3980 laststart = b;
3981 PATFETCH (c);
3982 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3983 break;
3985 case 'S':
3986 laststart = b;
3987 PATFETCH (c);
3988 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3989 break;
3990 #endif /* emacs */
3993 case 'w':
3994 if (syntax & RE_NO_GNU_OPS)
3995 goto normal_char;
3996 laststart = b;
3997 BUF_PUSH (wordchar);
3998 break;
4001 case 'W':
4002 if (syntax & RE_NO_GNU_OPS)
4003 goto normal_char;
4004 laststart = b;
4005 BUF_PUSH (notwordchar);
4006 break;
4009 case '<':
4010 if (syntax & RE_NO_GNU_OPS)
4011 goto normal_char;
4012 BUF_PUSH (wordbeg);
4013 break;
4015 case '>':
4016 if (syntax & RE_NO_GNU_OPS)
4017 goto normal_char;
4018 BUF_PUSH (wordend);
4019 break;
4021 case 'b':
4022 if (syntax & RE_NO_GNU_OPS)
4023 goto normal_char;
4024 BUF_PUSH (wordbound);
4025 break;
4027 case 'B':
4028 if (syntax & RE_NO_GNU_OPS)
4029 goto normal_char;
4030 BUF_PUSH (notwordbound);
4031 break;
4033 case '`':
4034 if (syntax & RE_NO_GNU_OPS)
4035 goto normal_char;
4036 BUF_PUSH (begbuf);
4037 break;
4039 case '\'':
4040 if (syntax & RE_NO_GNU_OPS)
4041 goto normal_char;
4042 BUF_PUSH (endbuf);
4043 break;
4045 case '1': case '2': case '3': case '4': case '5':
4046 case '6': case '7': case '8': case '9':
4047 if (syntax & RE_NO_BK_REFS)
4048 goto normal_char;
4050 c1 = c - '0';
4052 if (c1 > regnum)
4053 FREE_STACK_RETURN (REG_ESUBREG);
4055 /* Can't back reference to a subexpression if inside of it. */
4056 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4057 goto normal_char;
4059 laststart = b;
4060 BUF_PUSH_2 (duplicate, c1);
4061 break;
4064 case '+':
4065 case '?':
4066 if (syntax & RE_BK_PLUS_QM)
4067 goto handle_plus;
4068 else
4069 goto normal_backslash;
4071 default:
4072 normal_backslash:
4073 /* You might think it would be useful for \ to mean
4074 not to translate; but if we don't translate it
4075 it will never match anything. */
4076 c = TRANSLATE (c);
4077 goto normal_char;
4079 break;
4082 default:
4083 /* Expects the character in `c'. */
4084 normal_char:
4085 /* If no exactn currently being built. */
4086 if (!pending_exact
4087 #ifdef MBS_SUPPORT
4088 /* If last exactn handle binary(or character) and
4089 new exactn handle character(or binary). */
4090 || is_exactn_bin != is_binary[p - 1 - pattern]
4091 #endif /* MBS_SUPPORT */
4093 /* If last exactn not at current position. */
4094 || pending_exact + *pending_exact + 1 != b
4096 /* We have only one byte following the exactn for the count. */
4097 || *pending_exact == (1 << BYTEWIDTH) - 1
4099 /* If followed by a repetition operator. */
4100 || *p == '*' || *p == '^'
4101 || ((syntax & RE_BK_PLUS_QM)
4102 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4103 : (*p == '+' || *p == '?'))
4104 || ((syntax & RE_INTERVALS)
4105 && ((syntax & RE_NO_BK_BRACES)
4106 ? *p == '{'
4107 : (p[0] == '\\' && p[1] == '{'))))
4109 /* Start building a new exactn. */
4111 laststart = b;
4113 #ifdef MBS_SUPPORT
4114 /* Is this exactn binary data or character? */
4115 is_exactn_bin = is_binary[p - 1 - pattern];
4116 if (is_exactn_bin)
4117 BUF_PUSH_2 (exactn_bin, 0);
4118 else
4119 BUF_PUSH_2 (exactn, 0);
4120 #else
4121 BUF_PUSH_2 (exactn, 0);
4122 #endif /* MBS_SUPPORT */
4123 pending_exact = b - 1;
4126 BUF_PUSH (c);
4127 (*pending_exact)++;
4128 break;
4129 } /* switch (c) */
4130 } /* while p != pend */
4133 /* Through the pattern now. */
4135 if (fixup_alt_jump)
4136 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4138 if (!COMPILE_STACK_EMPTY)
4139 FREE_STACK_RETURN (REG_EPAREN);
4141 /* If we don't want backtracking, force success
4142 the first time we reach the end of the compiled pattern. */
4143 if (syntax & RE_NO_POSIX_BACKTRACKING)
4144 BUF_PUSH (succeed);
4146 #ifdef MBS_SUPPORT
4147 free (pattern);
4148 free (mbs_offset);
4149 free (is_binary);
4150 #endif
4151 free (compile_stack.stack);
4153 /* We have succeeded; set the length of the buffer. */
4154 #ifdef MBS_SUPPORT
4155 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4156 #else
4157 bufp->used = b - bufp->buffer;
4158 #endif
4160 #ifdef DEBUG
4161 if (debug)
4163 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4164 print_compiled_pattern (bufp);
4166 #endif /* DEBUG */
4168 #ifndef MATCH_MAY_ALLOCATE
4169 /* Initialize the failure stack to the largest possible stack. This
4170 isn't necessary unless we're trying to avoid calling alloca in
4171 the search and match routines. */
4173 int num_regs = bufp->re_nsub + 1;
4175 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4176 is strictly greater than re_max_failures, the largest possible stack
4177 is 2 * re_max_failures failure points. */
4178 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4180 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4182 # ifdef emacs
4183 if (! fail_stack.stack)
4184 fail_stack.stack
4185 = (fail_stack_elt_t *) xmalloc (fail_stack.size
4186 * sizeof (fail_stack_elt_t));
4187 else
4188 fail_stack.stack
4189 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
4190 (fail_stack.size
4191 * sizeof (fail_stack_elt_t)));
4192 # else /* not emacs */
4193 if (! fail_stack.stack)
4194 fail_stack.stack
4195 = (fail_stack_elt_t *) malloc (fail_stack.size
4196 * sizeof (fail_stack_elt_t));
4197 else
4198 fail_stack.stack
4199 = (fail_stack_elt_t *) realloc (fail_stack.stack,
4200 (fail_stack.size
4201 * sizeof (fail_stack_elt_t)));
4202 # endif /* not emacs */
4205 regex_grow_registers (num_regs);
4207 #endif /* not MATCH_MAY_ALLOCATE */
4209 return REG_NOERROR;
4210 } /* regex_compile */
4212 /* Subroutines for `regex_compile'. */
4214 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4215 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4217 static void
4218 store_op1 (op, loc, arg)
4219 re_opcode_t op;
4220 US_CHAR_TYPE *loc;
4221 int arg;
4223 *loc = (US_CHAR_TYPE) op;
4224 STORE_NUMBER (loc + 1, arg);
4228 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4229 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4231 static void
4232 store_op2 (op, loc, arg1, arg2)
4233 re_opcode_t op;
4234 US_CHAR_TYPE *loc;
4235 int arg1, arg2;
4237 *loc = (US_CHAR_TYPE) op;
4238 STORE_NUMBER (loc + 1, arg1);
4239 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4243 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4244 for OP followed by two-byte integer parameter ARG. */
4245 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4247 static void
4248 insert_op1 (op, loc, arg, end)
4249 re_opcode_t op;
4250 US_CHAR_TYPE *loc;
4251 int arg;
4252 US_CHAR_TYPE *end;
4254 register US_CHAR_TYPE *pfrom = end;
4255 register US_CHAR_TYPE *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4257 while (pfrom != loc)
4258 *--pto = *--pfrom;
4260 store_op1 (op, loc, arg);
4264 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4265 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4267 static void
4268 insert_op2 (op, loc, arg1, arg2, end)
4269 re_opcode_t op;
4270 US_CHAR_TYPE *loc;
4271 int arg1, arg2;
4272 US_CHAR_TYPE *end;
4274 register US_CHAR_TYPE *pfrom = end;
4275 register US_CHAR_TYPE *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4277 while (pfrom != loc)
4278 *--pto = *--pfrom;
4280 store_op2 (op, loc, arg1, arg2);
4284 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4285 after an alternative or a begin-subexpression. We assume there is at
4286 least one character before the ^. */
4288 static boolean
4289 at_begline_loc_p (pattern, p, syntax)
4290 const CHAR_TYPE *pattern, *p;
4291 reg_syntax_t syntax;
4293 const CHAR_TYPE *prev = p - 2;
4294 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4296 return
4297 /* After a subexpression? */
4298 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4299 /* After an alternative? */
4300 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4304 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4305 at least one character after the $, i.e., `P < PEND'. */
4307 static boolean
4308 at_endline_loc_p (p, pend, syntax)
4309 const CHAR_TYPE *p, *pend;
4310 reg_syntax_t syntax;
4312 const CHAR_TYPE *next = p;
4313 boolean next_backslash = *next == '\\';
4314 const CHAR_TYPE *next_next = p + 1 < pend ? p + 1 : 0;
4316 return
4317 /* Before a subexpression? */
4318 (syntax & RE_NO_BK_PARENS ? *next == ')'
4319 : next_backslash && next_next && *next_next == ')')
4320 /* Before an alternative? */
4321 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4322 : next_backslash && next_next && *next_next == '|');
4326 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4327 false if it's not. */
4329 static boolean
4330 group_in_compile_stack (compile_stack, regnum)
4331 compile_stack_type compile_stack;
4332 regnum_t regnum;
4334 int this_element;
4336 for (this_element = compile_stack.avail - 1;
4337 this_element >= 0;
4338 this_element--)
4339 if (compile_stack.stack[this_element].regnum == regnum)
4340 return true;
4342 return false;
4345 #ifdef MBS_SUPPORT
4346 /* This insert space, which size is "num", into the pattern at "loc".
4347 "end" must point the end of the allocated buffer. */
4348 static void
4349 insert_space (num, loc, end)
4350 int num;
4351 CHAR_TYPE *loc;
4352 CHAR_TYPE *end;
4354 register CHAR_TYPE *pto = end;
4355 register CHAR_TYPE *pfrom = end - num;
4357 while (pfrom >= loc)
4358 *pto-- = *pfrom--;
4360 #endif /* MBS_SUPPORT */
4362 #ifdef MBS_SUPPORT
4363 static reg_errcode_t
4364 compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4365 char_set)
4366 CHAR_TYPE range_start_char;
4367 const CHAR_TYPE **p_ptr, *pend;
4368 CHAR_TYPE *char_set, *b;
4369 RE_TRANSLATE_TYPE translate;
4370 reg_syntax_t syntax;
4372 const CHAR_TYPE *p = *p_ptr;
4373 CHAR_TYPE range_start, range_end;
4374 reg_errcode_t ret;
4375 # ifdef _LIBC
4376 uint32_t nrules;
4377 uint32_t start_val, end_val;
4378 # endif
4379 if (p == pend)
4380 return REG_ERANGE;
4382 # ifdef _LIBC
4383 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4384 if (nrules != 0)
4386 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4387 _NL_COLLATE_COLLSEQWC);
4388 const unsigned char *extra = (const unsigned char *)
4389 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4391 if (range_start_char < -1)
4393 /* range_start is a collating symbol. */
4394 int32_t *wextra;
4395 /* Retreive the index and get collation sequence value. */
4396 wextra = (int32_t*)(extra + char_set[-range_start_char]);
4397 start_val = wextra[1 + *wextra];
4399 else
4400 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4402 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4404 /* Report an error if the range is empty and the syntax prohibits
4405 this. */
4406 ret = ((syntax & RE_NO_EMPTY_RANGES)
4407 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4409 /* Insert space to the end of the char_ranges. */
4410 insert_space(2, b - char_set[5] - 2, b - 1);
4411 *(b - char_set[5] - 2) = (wchar_t)start_val;
4412 *(b - char_set[5] - 1) = (wchar_t)end_val;
4413 char_set[4]++; /* ranges_index */
4415 else
4416 # endif
4418 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4419 range_start_char;
4420 range_end = TRANSLATE (p[0]);
4421 /* Report an error if the range is empty and the syntax prohibits
4422 this. */
4423 ret = ((syntax & RE_NO_EMPTY_RANGES)
4424 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4426 /* Insert space to the end of the char_ranges. */
4427 insert_space(2, b - char_set[5] - 2, b - 1);
4428 *(b - char_set[5] - 2) = range_start;
4429 *(b - char_set[5] - 1) = range_end;
4430 char_set[4]++; /* ranges_index */
4432 /* Have to increment the pointer into the pattern string, so the
4433 caller isn't still at the ending character. */
4434 (*p_ptr)++;
4436 return ret;
4438 #else
4439 /* Read the ending character of a range (in a bracket expression) from the
4440 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4441 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4442 Then we set the translation of all bits between the starting and
4443 ending characters (inclusive) in the compiled pattern B.
4445 Return an error code.
4447 We use these short variable names so we can use the same macros as
4448 `regex_compile' itself. */
4450 static reg_errcode_t
4451 compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4452 unsigned int range_start_char;
4453 const char **p_ptr, *pend;
4454 RE_TRANSLATE_TYPE translate;
4455 reg_syntax_t syntax;
4456 unsigned char *b;
4458 unsigned this_char;
4459 const char *p = *p_ptr;
4460 reg_errcode_t ret;
4461 # if _LIBC
4462 const unsigned char *collseq;
4463 unsigned int start_colseq;
4464 unsigned int end_colseq;
4465 # else
4466 unsigned end_char;
4467 # endif
4469 if (p == pend)
4470 return REG_ERANGE;
4472 /* Have to increment the pointer into the pattern string, so the
4473 caller isn't still at the ending character. */
4474 (*p_ptr)++;
4476 /* Report an error if the range is empty and the syntax prohibits this. */
4477 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4479 # if _LIBC
4480 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4481 _NL_COLLATE_COLLSEQMB);
4483 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4484 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4485 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4487 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4489 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4491 SET_LIST_BIT (TRANSLATE (this_char));
4492 ret = REG_NOERROR;
4495 # else
4496 /* Here we see why `this_char' has to be larger than an `unsigned
4497 char' -- we would otherwise go into an infinite loop, since all
4498 characters <= 0xff. */
4499 range_start_char = TRANSLATE (range_start_char);
4500 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4501 and some compilers cast it to int implicitly, so following for_loop
4502 may fall to (almost) infinite loop.
4503 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4504 To avoid this, we cast p[0] to unsigned int and truncate it. */
4505 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4507 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4509 SET_LIST_BIT (TRANSLATE (this_char));
4510 ret = REG_NOERROR;
4512 # endif
4514 return ret;
4516 #endif /* MBS_SUPPORT */
4518 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4519 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4520 characters can start a string that matches the pattern. This fastmap
4521 is used by re_search to skip quickly over impossible starting points.
4523 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4524 area as BUFP->fastmap.
4526 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4527 the pattern buffer.
4529 Returns 0 if we succeed, -2 if an internal error. */
4531 #ifdef MBS_SUPPORT
4532 /* local function for re_compile_fastmap.
4533 truncate wchar_t character to char. */
4534 static unsigned char truncate_wchar (CHAR_TYPE c);
4536 static unsigned char
4537 truncate_wchar (c)
4538 CHAR_TYPE c;
4540 unsigned char buf[MB_LEN_MAX];
4541 int retval = wctomb(buf, c);
4542 return retval > 0 ? buf[0] : (unsigned char)c;
4544 #endif /* MBS_SUPPORT */
4547 re_compile_fastmap (bufp)
4548 struct re_pattern_buffer *bufp;
4550 int j, k;
4551 #ifdef MATCH_MAY_ALLOCATE
4552 fail_stack_type fail_stack;
4553 #endif
4554 #ifndef REGEX_MALLOC
4555 char *destination;
4556 #endif
4558 register char *fastmap = bufp->fastmap;
4560 #ifdef MBS_SUPPORT
4561 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4562 pattern to (char*) in regex_compile. */
4563 US_CHAR_TYPE *pattern = (US_CHAR_TYPE*)bufp->buffer;
4564 register US_CHAR_TYPE *pend = (US_CHAR_TYPE*) (bufp->buffer + bufp->used);
4565 #else
4566 US_CHAR_TYPE *pattern = bufp->buffer;
4567 register US_CHAR_TYPE *pend = pattern + bufp->used;
4568 #endif /* MBS_SUPPORT */
4569 US_CHAR_TYPE *p = pattern;
4571 #ifdef REL_ALLOC
4572 /* This holds the pointer to the failure stack, when
4573 it is allocated relocatably. */
4574 fail_stack_elt_t *failure_stack_ptr;
4575 #endif
4577 /* Assume that each path through the pattern can be null until
4578 proven otherwise. We set this false at the bottom of switch
4579 statement, to which we get only if a particular path doesn't
4580 match the empty string. */
4581 boolean path_can_be_null = true;
4583 /* We aren't doing a `succeed_n' to begin with. */
4584 boolean succeed_n_p = false;
4586 assert (fastmap != NULL && p != NULL);
4588 INIT_FAIL_STACK ();
4589 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4590 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4591 bufp->can_be_null = 0;
4593 while (1)
4595 if (p == pend || *p == succeed)
4597 /* We have reached the (effective) end of pattern. */
4598 if (!FAIL_STACK_EMPTY ())
4600 bufp->can_be_null |= path_can_be_null;
4602 /* Reset for next path. */
4603 path_can_be_null = true;
4605 p = fail_stack.stack[--fail_stack.avail].pointer;
4607 continue;
4609 else
4610 break;
4613 /* We should never be about to go beyond the end of the pattern. */
4614 assert (p < pend);
4616 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4619 /* I guess the idea here is to simply not bother with a fastmap
4620 if a backreference is used, since it's too hard to figure out
4621 the fastmap for the corresponding group. Setting
4622 `can_be_null' stops `re_search_2' from using the fastmap, so
4623 that is all we do. */
4624 case duplicate:
4625 bufp->can_be_null = 1;
4626 goto done;
4629 /* Following are the cases which match a character. These end
4630 with `break'. */
4632 #ifdef MBS_SUPPORT
4633 case exactn:
4634 fastmap[truncate_wchar(p[1])] = 1;
4635 break;
4636 case exactn_bin:
4637 fastmap[p[1]] = 1;
4638 break;
4639 #else
4640 case exactn:
4641 fastmap[p[1]] = 1;
4642 break;
4643 #endif /* MBS_SUPPORT */
4646 #ifdef MBS_SUPPORT
4647 /* It is hard to distinguish fastmap from (multi byte) characters
4648 which depends on current locale. */
4649 case charset:
4650 case charset_not:
4651 case wordchar:
4652 case notwordchar:
4653 bufp->can_be_null = 1;
4654 goto done;
4655 #else
4656 case charset:
4657 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4658 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4659 fastmap[j] = 1;
4660 break;
4663 case charset_not:
4664 /* Chars beyond end of map must be allowed. */
4665 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4666 fastmap[j] = 1;
4668 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4669 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4670 fastmap[j] = 1;
4671 break;
4674 case wordchar:
4675 for (j = 0; j < (1 << BYTEWIDTH); j++)
4676 if (SYNTAX (j) == Sword)
4677 fastmap[j] = 1;
4678 break;
4681 case notwordchar:
4682 for (j = 0; j < (1 << BYTEWIDTH); j++)
4683 if (SYNTAX (j) != Sword)
4684 fastmap[j] = 1;
4685 break;
4686 #endif
4688 case anychar:
4690 int fastmap_newline = fastmap['\n'];
4692 /* `.' matches anything ... */
4693 for (j = 0; j < (1 << BYTEWIDTH); j++)
4694 fastmap[j] = 1;
4696 /* ... except perhaps newline. */
4697 if (!(bufp->syntax & RE_DOT_NEWLINE))
4698 fastmap['\n'] = fastmap_newline;
4700 /* Return if we have already set `can_be_null'; if we have,
4701 then the fastmap is irrelevant. Something's wrong here. */
4702 else if (bufp->can_be_null)
4703 goto done;
4705 /* Otherwise, have to check alternative paths. */
4706 break;
4709 #ifdef emacs
4710 case syntaxspec:
4711 k = *p++;
4712 for (j = 0; j < (1 << BYTEWIDTH); j++)
4713 if (SYNTAX (j) == (enum syntaxcode) k)
4714 fastmap[j] = 1;
4715 break;
4718 case notsyntaxspec:
4719 k = *p++;
4720 for (j = 0; j < (1 << BYTEWIDTH); j++)
4721 if (SYNTAX (j) != (enum syntaxcode) k)
4722 fastmap[j] = 1;
4723 break;
4726 /* All cases after this match the empty string. These end with
4727 `continue'. */
4730 case before_dot:
4731 case at_dot:
4732 case after_dot:
4733 continue;
4734 #endif /* emacs */
4737 case no_op:
4738 case begline:
4739 case endline:
4740 case begbuf:
4741 case endbuf:
4742 case wordbound:
4743 case notwordbound:
4744 case wordbeg:
4745 case wordend:
4746 case push_dummy_failure:
4747 continue;
4750 case jump_n:
4751 case pop_failure_jump:
4752 case maybe_pop_jump:
4753 case jump:
4754 case jump_past_alt:
4755 case dummy_failure_jump:
4756 EXTRACT_NUMBER_AND_INCR (j, p);
4757 p += j;
4758 if (j > 0)
4759 continue;
4761 /* Jump backward implies we just went through the body of a
4762 loop and matched nothing. Opcode jumped to should be
4763 `on_failure_jump' or `succeed_n'. Just treat it like an
4764 ordinary jump. For a * loop, it has pushed its failure
4765 point already; if so, discard that as redundant. */
4766 if ((re_opcode_t) *p != on_failure_jump
4767 && (re_opcode_t) *p != succeed_n)
4768 continue;
4770 p++;
4771 EXTRACT_NUMBER_AND_INCR (j, p);
4772 p += j;
4774 /* If what's on the stack is where we are now, pop it. */
4775 if (!FAIL_STACK_EMPTY ()
4776 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4777 fail_stack.avail--;
4779 continue;
4782 case on_failure_jump:
4783 case on_failure_keep_string_jump:
4784 handle_on_failure_jump:
4785 EXTRACT_NUMBER_AND_INCR (j, p);
4787 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4788 end of the pattern. We don't want to push such a point,
4789 since when we restore it above, entering the switch will
4790 increment `p' past the end of the pattern. We don't need
4791 to push such a point since we obviously won't find any more
4792 fastmap entries beyond `pend'. Such a pattern can match
4793 the null string, though. */
4794 if (p + j < pend)
4796 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4798 RESET_FAIL_STACK ();
4799 return -2;
4802 else
4803 bufp->can_be_null = 1;
4805 if (succeed_n_p)
4807 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4808 succeed_n_p = false;
4811 continue;
4814 case succeed_n:
4815 /* Get to the number of times to succeed. */
4816 p += OFFSET_ADDRESS_SIZE;
4818 /* Increment p past the n for when k != 0. */
4819 EXTRACT_NUMBER_AND_INCR (k, p);
4820 if (k == 0)
4822 p -= 2 * OFFSET_ADDRESS_SIZE;
4823 succeed_n_p = true; /* Spaghetti code alert. */
4824 goto handle_on_failure_jump;
4826 continue;
4829 case set_number_at:
4830 p += 2 * OFFSET_ADDRESS_SIZE;
4831 continue;
4834 case start_memory:
4835 case stop_memory:
4836 p += 2;
4837 continue;
4840 default:
4841 abort (); /* We have listed all the cases. */
4842 } /* switch *p++ */
4844 /* Getting here means we have found the possible starting
4845 characters for one path of the pattern -- and that the empty
4846 string does not match. We need not follow this path further.
4847 Instead, look at the next alternative (remembered on the
4848 stack), or quit if no more. The test at the top of the loop
4849 does these things. */
4850 path_can_be_null = false;
4851 p = pend;
4852 } /* while p */
4854 /* Set `can_be_null' for the last path (also the first path, if the
4855 pattern is empty). */
4856 bufp->can_be_null |= path_can_be_null;
4858 done:
4859 RESET_FAIL_STACK ();
4860 return 0;
4861 } /* re_compile_fastmap */
4862 #ifdef _LIBC
4863 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4864 #endif
4866 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4867 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4868 this memory for recording register information. STARTS and ENDS
4869 must be allocated using the malloc library routine, and must each
4870 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4872 If NUM_REGS == 0, then subsequent matches should allocate their own
4873 register data.
4875 Unless this function is called, the first search or match using
4876 PATTERN_BUFFER will allocate its own register data, without
4877 freeing the old data. */
4879 void
4880 re_set_registers (bufp, regs, num_regs, starts, ends)
4881 struct re_pattern_buffer *bufp;
4882 struct re_registers *regs;
4883 unsigned num_regs;
4884 regoff_t *starts, *ends;
4886 if (num_regs)
4888 bufp->regs_allocated = REGS_REALLOCATE;
4889 regs->num_regs = num_regs;
4890 regs->start = starts;
4891 regs->end = ends;
4893 else
4895 bufp->regs_allocated = REGS_UNALLOCATED;
4896 regs->num_regs = 0;
4897 regs->start = regs->end = (regoff_t *) 0;
4900 #ifdef _LIBC
4901 weak_alias (__re_set_registers, re_set_registers)
4902 #endif
4904 /* Searching routines. */
4906 /* Like re_search_2, below, but only one string is specified, and
4907 doesn't let you say where to stop matching. */
4910 re_search (bufp, string, size, startpos, range, regs)
4911 struct re_pattern_buffer *bufp;
4912 const char *string;
4913 int size, startpos, range;
4914 struct re_registers *regs;
4916 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4917 regs, size);
4919 #ifdef _LIBC
4920 weak_alias (__re_search, re_search)
4921 #endif
4924 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4925 virtual concatenation of STRING1 and STRING2, starting first at index
4926 STARTPOS, then at STARTPOS + 1, and so on.
4928 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4930 RANGE is how far to scan while trying to match. RANGE = 0 means try
4931 only at STARTPOS; in general, the last start tried is STARTPOS +
4932 RANGE.
4934 In REGS, return the indices of the virtual concatenation of STRING1
4935 and STRING2 that matched the entire BUFP->buffer and its contained
4936 subexpressions.
4938 Do not consider matching one past the index STOP in the virtual
4939 concatenation of STRING1 and STRING2.
4941 We return either the position in the strings at which the match was
4942 found, -1 if no match, or -2 if error (such as failure
4943 stack overflow). */
4946 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
4947 struct re_pattern_buffer *bufp;
4948 const char *string1, *string2;
4949 int size1, size2;
4950 int startpos;
4951 int range;
4952 struct re_registers *regs;
4953 int stop;
4955 int val;
4956 register char *fastmap = bufp->fastmap;
4957 register RE_TRANSLATE_TYPE translate = bufp->translate;
4958 int total_size = size1 + size2;
4959 int endpos = startpos + range;
4961 /* Check for out-of-range STARTPOS. */
4962 if (startpos < 0 || startpos > total_size)
4963 return -1;
4965 /* Fix up RANGE if it might eventually take us outside
4966 the virtual concatenation of STRING1 and STRING2.
4967 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4968 if (endpos < 0)
4969 range = 0 - startpos;
4970 else if (endpos > total_size)
4971 range = total_size - startpos;
4973 /* If the search isn't to be a backwards one, don't waste time in a
4974 search for a pattern that must be anchored. */
4975 if (bufp->used > 0 && range > 0
4976 && ((re_opcode_t) bufp->buffer[0] == begbuf
4977 /* `begline' is like `begbuf' if it cannot match at newlines. */
4978 || ((re_opcode_t) bufp->buffer[0] == begline
4979 && !bufp->newline_anchor)))
4981 if (startpos > 0)
4982 return -1;
4983 else
4984 range = 1;
4987 #ifdef emacs
4988 /* In a forward search for something that starts with \=.
4989 don't keep searching past point. */
4990 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4992 range = PT - startpos;
4993 if (range <= 0)
4994 return -1;
4996 #endif /* emacs */
4998 /* Update the fastmap now if not correct already. */
4999 if (fastmap && !bufp->fastmap_accurate)
5000 if (re_compile_fastmap (bufp) == -2)
5001 return -2;
5003 /* Loop through the string, looking for a place to start matching. */
5004 for (;;)
5006 /* If a fastmap is supplied, skip quickly over characters that
5007 cannot be the start of a match. If the pattern can match the
5008 null string, however, we don't need to skip characters; we want
5009 the first null string. */
5010 if (fastmap && startpos < total_size && !bufp->can_be_null)
5012 if (range > 0) /* Searching forwards. */
5014 register const char *d;
5015 register int lim = 0;
5016 int irange = range;
5018 if (startpos < size1 && startpos + range >= size1)
5019 lim = range - (size1 - startpos);
5021 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5023 /* Written out as an if-else to avoid testing `translate'
5024 inside the loop. */
5025 if (translate)
5026 while (range > lim
5027 && !fastmap[(unsigned char)
5028 translate[(unsigned char) *d++]])
5029 range--;
5030 else
5031 while (range > lim && !fastmap[(unsigned char) *d++])
5032 range--;
5034 startpos += irange - range;
5036 else /* Searching backwards. */
5038 register CHAR_TYPE c = (size1 == 0 || startpos >= size1
5039 ? string2[startpos - size1]
5040 : string1[startpos]);
5042 if (!fastmap[(unsigned char) TRANSLATE (c)])
5043 goto advance;
5047 /* If can't match the null string, and that's all we have left, fail. */
5048 if (range >= 0 && startpos == total_size && fastmap
5049 && !bufp->can_be_null)
5050 return -1;
5052 val = re_match_2_internal (bufp, string1, size1, string2, size2,
5053 startpos, regs, stop);
5054 #ifndef REGEX_MALLOC
5055 # ifdef C_ALLOCA
5056 alloca (0);
5057 # endif
5058 #endif
5060 if (val >= 0)
5061 return startpos;
5063 if (val == -2)
5064 return -2;
5066 advance:
5067 if (!range)
5068 break;
5069 else if (range > 0)
5071 range--;
5072 startpos++;
5074 else
5076 range++;
5077 startpos--;
5080 return -1;
5081 } /* re_search_2 */
5082 #ifdef _LIBC
5083 weak_alias (__re_search_2, re_search_2)
5084 #endif
5086 #ifdef MBS_SUPPORT
5087 /* This converts PTR, a pointer into one of the search wchar_t strings
5088 `string1' and `string2' into an multibyte string offset from the
5089 beginning of that string. We use mbs_offset to optimize.
5090 See convert_mbs_to_wcs. */
5091 # define POINTER_TO_OFFSET(ptr) \
5092 (FIRST_STRING_P (ptr) \
5093 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5094 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5095 + csize1)))
5096 #else
5097 /* This converts PTR, a pointer into one of the search strings `string1'
5098 and `string2' into an offset from the beginning of that string. */
5099 # define POINTER_TO_OFFSET(ptr) \
5100 (FIRST_STRING_P (ptr) \
5101 ? ((regoff_t) ((ptr) - string1)) \
5102 : ((regoff_t) ((ptr) - string2 + size1)))
5103 #endif /* MBS_SUPPORT */
5105 /* Macros for dealing with the split strings in re_match_2. */
5107 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5109 /* Call before fetching a character with *d. This switches over to
5110 string2 if necessary. */
5111 #define PREFETCH() \
5112 while (d == dend) \
5114 /* End of string2 => fail. */ \
5115 if (dend == end_match_2) \
5116 goto fail; \
5117 /* End of string1 => advance to string2. */ \
5118 d = string2; \
5119 dend = end_match_2; \
5123 /* Test if at very beginning or at very end of the virtual concatenation
5124 of `string1' and `string2'. If only one string, it's `string2'. */
5125 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5126 #define AT_STRINGS_END(d) ((d) == end2)
5129 /* Test if D points to a character which is word-constituent. We have
5130 two special cases to check for: if past the end of string1, look at
5131 the first character in string2; and if before the beginning of
5132 string2, look at the last character in string1. */
5133 #ifdef MBS_SUPPORT
5134 /* Use internationalized API instead of SYNTAX. */
5135 # define WORDCHAR_P(d) \
5136 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5137 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5138 #else
5139 # define WORDCHAR_P(d) \
5140 (SYNTAX ((d) == end1 ? *string2 \
5141 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5142 == Sword)
5143 #endif /* MBS_SUPPORT */
5145 /* Disabled due to a compiler bug -- see comment at case wordbound */
5146 #if 0
5147 /* Test if the character before D and the one at D differ with respect
5148 to being word-constituent. */
5149 #define AT_WORD_BOUNDARY(d) \
5150 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5151 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5152 #endif
5154 /* Free everything we malloc. */
5155 #ifdef MATCH_MAY_ALLOCATE
5156 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5157 # ifdef MBS_SUPPORT
5158 # define FREE_VARIABLES() \
5159 do { \
5160 REGEX_FREE_STACK (fail_stack.stack); \
5161 FREE_VAR (regstart); \
5162 FREE_VAR (regend); \
5163 FREE_VAR (old_regstart); \
5164 FREE_VAR (old_regend); \
5165 FREE_VAR (best_regstart); \
5166 FREE_VAR (best_regend); \
5167 FREE_VAR (reg_info); \
5168 FREE_VAR (reg_dummy); \
5169 FREE_VAR (reg_info_dummy); \
5170 FREE_VAR (string1); \
5171 FREE_VAR (string2); \
5172 FREE_VAR (mbs_offset1); \
5173 FREE_VAR (mbs_offset2); \
5174 } while (0)
5175 # else /* not MBS_SUPPORT */
5176 # define FREE_VARIABLES() \
5177 do { \
5178 REGEX_FREE_STACK (fail_stack.stack); \
5179 FREE_VAR (regstart); \
5180 FREE_VAR (regend); \
5181 FREE_VAR (old_regstart); \
5182 FREE_VAR (old_regend); \
5183 FREE_VAR (best_regstart); \
5184 FREE_VAR (best_regend); \
5185 FREE_VAR (reg_info); \
5186 FREE_VAR (reg_dummy); \
5187 FREE_VAR (reg_info_dummy); \
5188 } while (0)
5189 # endif /* MBS_SUPPORT */
5190 #else
5191 # define FREE_VAR(var) if (var) free (var); var = NULL
5192 # ifdef MBS_SUPPORT
5193 # define FREE_VARIABLES() \
5194 do { \
5195 FREE_VAR (string1); \
5196 FREE_VAR (string2); \
5197 FREE_VAR (mbs_offset1); \
5198 FREE_VAR (mbs_offset2); \
5199 } while (0)
5200 # else
5201 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5202 # endif /* MBS_SUPPORT */
5203 #endif /* not MATCH_MAY_ALLOCATE */
5205 /* These values must meet several constraints. They must not be valid
5206 register values; since we have a limit of 255 registers (because
5207 we use only one byte in the pattern for the register number), we can
5208 use numbers larger than 255. They must differ by 1, because of
5209 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5210 be larger than the value for the highest register, so we do not try
5211 to actually save any registers when none are active. */
5212 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5213 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5215 /* Matching routines. */
5217 #ifndef emacs /* Emacs never uses this. */
5218 /* re_match is like re_match_2 except it takes only a single string. */
5221 re_match (bufp, string, size, pos, regs)
5222 struct re_pattern_buffer *bufp;
5223 const char *string;
5224 int size, pos;
5225 struct re_registers *regs;
5227 int result = re_match_2_internal (bufp, NULL, 0, string, size,
5228 pos, regs, size);
5229 # ifndef REGEX_MALLOC
5230 # ifdef C_ALLOCA
5231 alloca (0);
5232 # endif
5233 # endif
5234 return result;
5236 # ifdef _LIBC
5237 weak_alias (__re_match, re_match)
5238 # endif
5239 #endif /* not emacs */
5241 static boolean group_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5242 US_CHAR_TYPE *end,
5243 register_info_type *reg_info));
5244 static boolean alt_match_null_string_p _RE_ARGS ((US_CHAR_TYPE *p,
5245 US_CHAR_TYPE *end,
5246 register_info_type *reg_info));
5247 static boolean common_op_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5248 US_CHAR_TYPE *end,
5249 register_info_type *reg_info));
5250 static int bcmp_translate _RE_ARGS ((const CHAR_TYPE *s1, const CHAR_TYPE *s2,
5251 int len, char *translate));
5253 /* re_match_2 matches the compiled pattern in BUFP against the
5254 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5255 and SIZE2, respectively). We start matching at POS, and stop
5256 matching at STOP.
5258 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5259 store offsets for the substring each group matched in REGS. See the
5260 documentation for exactly how many groups we fill.
5262 We return -1 if no match, -2 if an internal error (such as the
5263 failure stack overflowing). Otherwise, we return the length of the
5264 matched substring. */
5267 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5268 struct re_pattern_buffer *bufp;
5269 const char *string1, *string2;
5270 int size1, size2;
5271 int pos;
5272 struct re_registers *regs;
5273 int stop;
5275 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
5276 pos, regs, stop);
5277 #ifndef REGEX_MALLOC
5278 # ifdef C_ALLOCA
5279 alloca (0);
5280 # endif
5281 #endif
5282 return result;
5284 #ifdef _LIBC
5285 weak_alias (__re_match_2, re_match_2)
5286 #endif
5288 #ifdef MBS_SUPPORT
5290 static int count_mbs_length PARAMS ((int *, int));
5292 /* This check the substring (from 0, to length) of the multibyte string,
5293 to which offset_buffer correspond. And count how many wchar_t_characters
5294 the substring occupy. We use offset_buffer to optimization.
5295 See convert_mbs_to_wcs. */
5297 static int
5298 count_mbs_length(offset_buffer, length)
5299 int *offset_buffer;
5300 int length;
5302 int wcs_size;
5304 /* Check whether the size is valid. */
5305 if (length < 0)
5306 return -1;
5308 if (offset_buffer == NULL)
5309 return 0;
5311 for (wcs_size = 0 ; offset_buffer[wcs_size] != -1 ; wcs_size++)
5313 if (offset_buffer[wcs_size] == length)
5314 return wcs_size;
5315 if (offset_buffer[wcs_size] > length)
5316 /* It is a fragment of a wide character. */
5317 return -1;
5320 /* We reached at the sentinel. */
5321 return -1;
5323 #endif /* MBS_SUPPORT */
5325 /* This is a separate function so that we can force an alloca cleanup
5326 afterwards. */
5327 static int
5328 #ifdef MBS_SUPPORT
5329 re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos, regs, stop)
5330 struct re_pattern_buffer *bufp;
5331 const char *cstring1, *cstring2;
5332 int csize1, csize2;
5333 #else
5334 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
5335 struct re_pattern_buffer *bufp;
5336 const char *string1, *string2;
5337 int size1, size2;
5338 #endif
5339 int pos;
5340 struct re_registers *regs;
5341 int stop;
5343 /* General temporaries. */
5344 int mcnt;
5345 US_CHAR_TYPE *p1;
5346 #ifdef MBS_SUPPORT
5347 /* We need wchar_t* buffers correspond to string1, string2. */
5348 CHAR_TYPE *string1 = NULL, *string2 = NULL;
5349 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5350 int size1 = 0, size2 = 0;
5351 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5352 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5353 /* They hold whether each wchar_t is binary data or not. */
5354 char *is_binary = NULL;
5355 #endif /* MBS_SUPPORT */
5357 /* Just past the end of the corresponding string. */
5358 const CHAR_TYPE *end1, *end2;
5360 /* Pointers into string1 and string2, just past the last characters in
5361 each to consider matching. */
5362 const CHAR_TYPE *end_match_1, *end_match_2;
5364 /* Where we are in the data, and the end of the current string. */
5365 const CHAR_TYPE *d, *dend;
5367 /* Where we are in the pattern, and the end of the pattern. */
5368 #ifdef MBS_SUPPORT
5369 US_CHAR_TYPE *pattern, *p;
5370 register US_CHAR_TYPE *pend;
5371 #else
5372 US_CHAR_TYPE *p = bufp->buffer;
5373 register US_CHAR_TYPE *pend = p + bufp->used;
5374 #endif /* MBS_SUPPORT */
5376 /* Mark the opcode just after a start_memory, so we can test for an
5377 empty subpattern when we get to the stop_memory. */
5378 US_CHAR_TYPE *just_past_start_mem = 0;
5380 /* We use this to map every character in the string. */
5381 RE_TRANSLATE_TYPE translate = bufp->translate;
5383 /* Failure point stack. Each place that can handle a failure further
5384 down the line pushes a failure point on this stack. It consists of
5385 restart, regend, and reg_info for all registers corresponding to
5386 the subexpressions we're currently inside, plus the number of such
5387 registers, and, finally, two char *'s. The first char * is where
5388 to resume scanning the pattern; the second one is where to resume
5389 scanning the strings. If the latter is zero, the failure point is
5390 a ``dummy''; if a failure happens and the failure point is a dummy,
5391 it gets discarded and the next next one is tried. */
5392 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5393 fail_stack_type fail_stack;
5394 #endif
5395 #ifdef DEBUG
5396 static unsigned failure_id;
5397 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5398 #endif
5400 #ifdef REL_ALLOC
5401 /* This holds the pointer to the failure stack, when
5402 it is allocated relocatably. */
5403 fail_stack_elt_t *failure_stack_ptr;
5404 #endif
5406 /* We fill all the registers internally, independent of what we
5407 return, for use in backreferences. The number here includes
5408 an element for register zero. */
5409 size_t num_regs = bufp->re_nsub + 1;
5411 /* The currently active registers. */
5412 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5413 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5415 /* Information on the contents of registers. These are pointers into
5416 the input strings; they record just what was matched (on this
5417 attempt) by a subexpression part of the pattern, that is, the
5418 regnum-th regstart pointer points to where in the pattern we began
5419 matching and the regnum-th regend points to right after where we
5420 stopped matching the regnum-th subexpression. (The zeroth register
5421 keeps track of what the whole pattern matches.) */
5422 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5423 const CHAR_TYPE **regstart, **regend;
5424 #endif
5426 /* If a group that's operated upon by a repetition operator fails to
5427 match anything, then the register for its start will need to be
5428 restored because it will have been set to wherever in the string we
5429 are when we last see its open-group operator. Similarly for a
5430 register's end. */
5431 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5432 const CHAR_TYPE **old_regstart, **old_regend;
5433 #endif
5435 /* The is_active field of reg_info helps us keep track of which (possibly
5436 nested) subexpressions we are currently in. The matched_something
5437 field of reg_info[reg_num] helps us tell whether or not we have
5438 matched any of the pattern so far this time through the reg_num-th
5439 subexpression. These two fields get reset each time through any
5440 loop their register is in. */
5441 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5442 register_info_type *reg_info;
5443 #endif
5445 /* The following record the register info as found in the above
5446 variables when we find a match better than any we've seen before.
5447 This happens as we backtrack through the failure points, which in
5448 turn happens only if we have not yet matched the entire string. */
5449 unsigned best_regs_set = false;
5450 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5451 const CHAR_TYPE **best_regstart, **best_regend;
5452 #endif
5454 /* Logically, this is `best_regend[0]'. But we don't want to have to
5455 allocate space for that if we're not allocating space for anything
5456 else (see below). Also, we never need info about register 0 for
5457 any of the other register vectors, and it seems rather a kludge to
5458 treat `best_regend' differently than the rest. So we keep track of
5459 the end of the best match so far in a separate variable. We
5460 initialize this to NULL so that when we backtrack the first time
5461 and need to test it, it's not garbage. */
5462 const CHAR_TYPE *match_end = NULL;
5464 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5465 int set_regs_matched_done = 0;
5467 /* Used when we pop values we don't care about. */
5468 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5469 const CHAR_TYPE **reg_dummy;
5470 register_info_type *reg_info_dummy;
5471 #endif
5473 #ifdef DEBUG
5474 /* Counts the total number of registers pushed. */
5475 unsigned num_regs_pushed = 0;
5476 #endif
5478 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5480 INIT_FAIL_STACK ();
5482 #ifdef MATCH_MAY_ALLOCATE
5483 /* Do not bother to initialize all the register variables if there are
5484 no groups in the pattern, as it takes a fair amount of time. If
5485 there are groups, we include space for register 0 (the whole
5486 pattern), even though we never use it, since it simplifies the
5487 array indexing. We should fix this. */
5488 if (bufp->re_nsub)
5490 regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5491 regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5492 old_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5493 old_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5494 best_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5495 best_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5496 reg_info = REGEX_TALLOC (num_regs, register_info_type);
5497 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5498 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
5500 if (!(regstart && regend && old_regstart && old_regend && reg_info
5501 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5503 FREE_VARIABLES ();
5504 return -2;
5507 else
5509 /* We must initialize all our variables to NULL, so that
5510 `FREE_VARIABLES' doesn't try to free them. */
5511 regstart = regend = old_regstart = old_regend = best_regstart
5512 = best_regend = reg_dummy = NULL;
5513 reg_info = reg_info_dummy = (register_info_type *) NULL;
5515 #endif /* MATCH_MAY_ALLOCATE */
5517 /* The starting position is bogus. */
5518 #ifdef MBS_SUPPORT
5519 if (pos < 0 || pos > csize1 + csize2)
5520 #else
5521 if (pos < 0 || pos > size1 + size2)
5522 #endif
5524 FREE_VARIABLES ();
5525 return -1;
5528 #ifdef MBS_SUPPORT
5529 /* Allocate wchar_t array for string1 and string2 and
5530 fill them with converted string. */
5531 if (csize1 != 0)
5533 string1 = REGEX_TALLOC (csize1 + 1, CHAR_TYPE);
5534 mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5535 is_binary = REGEX_TALLOC (csize1 + 1, char);
5536 if (!string1 || !mbs_offset1 || !is_binary)
5538 FREE_VAR (string1);
5539 FREE_VAR (mbs_offset1);
5540 FREE_VAR (is_binary);
5541 return -2;
5543 size1 = convert_mbs_to_wcs(string1, cstring1, csize1,
5544 mbs_offset1, is_binary);
5545 string1[size1] = L'\0'; /* for a sentinel */
5546 FREE_VAR (is_binary);
5548 if (csize2 != 0)
5550 string2 = REGEX_TALLOC (csize2 + 1, CHAR_TYPE);
5551 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5552 is_binary = REGEX_TALLOC (csize2 + 1, char);
5553 if (!string2 || !mbs_offset2 || !is_binary)
5555 FREE_VAR (string1);
5556 FREE_VAR (mbs_offset1);
5557 FREE_VAR (string2);
5558 FREE_VAR (mbs_offset2);
5559 FREE_VAR (is_binary);
5560 return -2;
5562 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5563 mbs_offset2, is_binary);
5564 string2[size2] = L'\0'; /* for a sentinel */
5565 FREE_VAR (is_binary);
5568 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5569 pattern to (char*) in regex_compile. */
5570 p = pattern = (CHAR_TYPE*)bufp->buffer;
5571 pend = (CHAR_TYPE*)(bufp->buffer + bufp->used);
5573 #endif /* MBS_SUPPORT */
5575 /* Initialize subexpression text positions to -1 to mark ones that no
5576 start_memory/stop_memory has been seen for. Also initialize the
5577 register information struct. */
5578 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5580 regstart[mcnt] = regend[mcnt]
5581 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5583 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5584 IS_ACTIVE (reg_info[mcnt]) = 0;
5585 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5586 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5589 /* We move `string1' into `string2' if the latter's empty -- but not if
5590 `string1' is null. */
5591 if (size2 == 0 && string1 != NULL)
5593 string2 = string1;
5594 size2 = size1;
5595 string1 = 0;
5596 size1 = 0;
5598 end1 = string1 + size1;
5599 end2 = string2 + size2;
5601 /* Compute where to stop matching, within the two strings. */
5602 #ifdef MBS_SUPPORT
5603 if (stop <= csize1)
5605 mcnt = count_mbs_length(mbs_offset1, stop);
5606 end_match_1 = string1 + mcnt;
5607 end_match_2 = string2;
5609 else
5611 end_match_1 = end1;
5612 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5613 end_match_2 = string2 + mcnt;
5615 if (mcnt < 0)
5616 { /* count_mbs_length return error. */
5617 FREE_VARIABLES ();
5618 return -1;
5620 #else
5621 if (stop <= size1)
5623 end_match_1 = string1 + stop;
5624 end_match_2 = string2;
5626 else
5628 end_match_1 = end1;
5629 end_match_2 = string2 + stop - size1;
5631 #endif /* MBS_SUPPORT */
5633 /* `p' scans through the pattern as `d' scans through the data.
5634 `dend' is the end of the input string that `d' points within. `d'
5635 is advanced into the following input string whenever necessary, but
5636 this happens before fetching; therefore, at the beginning of the
5637 loop, `d' can be pointing at the end of a string, but it cannot
5638 equal `string2'. */
5639 #ifdef MBS_SUPPORT
5640 if (size1 > 0 && pos <= csize1)
5642 mcnt = count_mbs_length(mbs_offset1, pos);
5643 d = string1 + mcnt;
5644 dend = end_match_1;
5646 else
5648 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5649 d = string2 + mcnt;
5650 dend = end_match_2;
5653 if (mcnt < 0)
5654 { /* count_mbs_length return error. */
5655 FREE_VARIABLES ();
5656 return -1;
5658 #else
5659 if (size1 > 0 && pos <= size1)
5661 d = string1 + pos;
5662 dend = end_match_1;
5664 else
5666 d = string2 + pos - size1;
5667 dend = end_match_2;
5669 #endif /* MBS_SUPPORT */
5671 DEBUG_PRINT1 ("The compiled pattern is:\n");
5672 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5673 DEBUG_PRINT1 ("The string to match is: `");
5674 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5675 DEBUG_PRINT1 ("'\n");
5677 /* This loops over pattern commands. It exits by returning from the
5678 function if the match is complete, or it drops through if the match
5679 fails at this starting point in the input data. */
5680 for (;;)
5682 #ifdef _LIBC
5683 DEBUG_PRINT2 ("\n%p: ", p);
5684 #else
5685 DEBUG_PRINT2 ("\n0x%x: ", p);
5686 #endif
5688 if (p == pend)
5689 { /* End of pattern means we might have succeeded. */
5690 DEBUG_PRINT1 ("end of pattern ... ");
5692 /* If we haven't matched the entire string, and we want the
5693 longest match, try backtracking. */
5694 if (d != end_match_2)
5696 /* 1 if this match ends in the same string (string1 or string2)
5697 as the best previous match. */
5698 boolean same_str_p = (FIRST_STRING_P (match_end)
5699 == MATCHING_IN_FIRST_STRING);
5700 /* 1 if this match is the best seen so far. */
5701 boolean best_match_p;
5703 /* AIX compiler got confused when this was combined
5704 with the previous declaration. */
5705 if (same_str_p)
5706 best_match_p = d > match_end;
5707 else
5708 best_match_p = !MATCHING_IN_FIRST_STRING;
5710 DEBUG_PRINT1 ("backtracking.\n");
5712 if (!FAIL_STACK_EMPTY ())
5713 { /* More failure points to try. */
5715 /* If exceeds best match so far, save it. */
5716 if (!best_regs_set || best_match_p)
5718 best_regs_set = true;
5719 match_end = d;
5721 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5723 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5725 best_regstart[mcnt] = regstart[mcnt];
5726 best_regend[mcnt] = regend[mcnt];
5729 goto fail;
5732 /* If no failure points, don't restore garbage. And if
5733 last match is real best match, don't restore second
5734 best one. */
5735 else if (best_regs_set && !best_match_p)
5737 restore_best_regs:
5738 /* Restore best match. It may happen that `dend ==
5739 end_match_1' while the restored d is in string2.
5740 For example, the pattern `x.*y.*z' against the
5741 strings `x-' and `y-z-', if the two strings are
5742 not consecutive in memory. */
5743 DEBUG_PRINT1 ("Restoring best registers.\n");
5745 d = match_end;
5746 dend = ((d >= string1 && d <= end1)
5747 ? end_match_1 : end_match_2);
5749 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5751 regstart[mcnt] = best_regstart[mcnt];
5752 regend[mcnt] = best_regend[mcnt];
5755 } /* d != end_match_2 */
5757 succeed_label:
5758 DEBUG_PRINT1 ("Accepting match.\n");
5759 /* If caller wants register contents data back, do it. */
5760 if (regs && !bufp->no_sub)
5762 /* Have the register data arrays been allocated? */
5763 if (bufp->regs_allocated == REGS_UNALLOCATED)
5764 { /* No. So allocate them with malloc. We need one
5765 extra element beyond `num_regs' for the `-1' marker
5766 GNU code uses. */
5767 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5768 regs->start = TALLOC (regs->num_regs, regoff_t);
5769 regs->end = TALLOC (regs->num_regs, regoff_t);
5770 if (regs->start == NULL || regs->end == NULL)
5772 FREE_VARIABLES ();
5773 return -2;
5775 bufp->regs_allocated = REGS_REALLOCATE;
5777 else if (bufp->regs_allocated == REGS_REALLOCATE)
5778 { /* Yes. If we need more elements than were already
5779 allocated, reallocate them. If we need fewer, just
5780 leave it alone. */
5781 if (regs->num_regs < num_regs + 1)
5783 regs->num_regs = num_regs + 1;
5784 RETALLOC (regs->start, regs->num_regs, regoff_t);
5785 RETALLOC (regs->end, regs->num_regs, regoff_t);
5786 if (regs->start == NULL || regs->end == NULL)
5788 FREE_VARIABLES ();
5789 return -2;
5793 else
5795 /* These braces fend off a "empty body in an else-statement"
5796 warning under GCC when assert expands to nothing. */
5797 assert (bufp->regs_allocated == REGS_FIXED);
5800 /* Convert the pointer data in `regstart' and `regend' to
5801 indices. Register zero has to be set differently,
5802 since we haven't kept track of any info for it. */
5803 if (regs->num_regs > 0)
5805 regs->start[0] = pos;
5806 #ifdef MBS_SUPPORT
5807 if (MATCHING_IN_FIRST_STRING)
5808 regs->end[0] = mbs_offset1 != NULL ?
5809 mbs_offset1[d-string1] : 0;
5810 else
5811 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
5812 mbs_offset2[d-string2] : 0);
5813 #else
5814 regs->end[0] = (MATCHING_IN_FIRST_STRING
5815 ? ((regoff_t) (d - string1))
5816 : ((regoff_t) (d - string2 + size1)));
5817 #endif /* MBS_SUPPORT */
5820 /* Go through the first `min (num_regs, regs->num_regs)'
5821 registers, since that is all we initialized. */
5822 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
5823 mcnt++)
5825 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
5826 regs->start[mcnt] = regs->end[mcnt] = -1;
5827 else
5829 regs->start[mcnt]
5830 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
5831 regs->end[mcnt]
5832 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
5836 /* If the regs structure we return has more elements than
5837 were in the pattern, set the extra elements to -1. If
5838 we (re)allocated the registers, this is the case,
5839 because we always allocate enough to have at least one
5840 -1 at the end. */
5841 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
5842 regs->start[mcnt] = regs->end[mcnt] = -1;
5843 } /* regs && !bufp->no_sub */
5845 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5846 nfailure_points_pushed, nfailure_points_popped,
5847 nfailure_points_pushed - nfailure_points_popped);
5848 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5850 #ifdef MBS_SUPPORT
5851 if (MATCHING_IN_FIRST_STRING)
5852 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
5853 else
5854 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
5855 csize1;
5856 mcnt -= pos;
5857 #else
5858 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
5859 ? string1
5860 : string2 - size1);
5861 #endif /* MBS_SUPPORT */
5863 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5865 FREE_VARIABLES ();
5866 return mcnt;
5869 /* Otherwise match next pattern command. */
5870 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5872 /* Ignore these. Used to ignore the n of succeed_n's which
5873 currently have n == 0. */
5874 case no_op:
5875 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5876 break;
5878 case succeed:
5879 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5880 goto succeed_label;
5882 /* Match the next n pattern characters exactly. The following
5883 byte in the pattern defines n, and the n bytes after that
5884 are the characters to match. */
5885 case exactn:
5886 #ifdef MBS_SUPPORT
5887 case exactn_bin:
5888 #endif
5889 mcnt = *p++;
5890 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5892 /* This is written out as an if-else so we don't waste time
5893 testing `translate' inside the loop. */
5894 if (translate)
5898 PREFETCH ();
5899 #ifdef MBS_SUPPORT
5900 if (*d <= 0xff)
5902 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5903 != (US_CHAR_TYPE) *p++)
5904 goto fail;
5906 else
5908 if (*d++ != (CHAR_TYPE) *p++)
5909 goto fail;
5911 #else
5912 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5913 != (US_CHAR_TYPE) *p++)
5914 goto fail;
5915 #endif /* MBS_SUPPORT */
5917 while (--mcnt);
5919 else
5923 PREFETCH ();
5924 if (*d++ != (CHAR_TYPE) *p++) goto fail;
5926 while (--mcnt);
5928 SET_REGS_MATCHED ();
5929 break;
5932 /* Match any character except possibly a newline or a null. */
5933 case anychar:
5934 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5936 PREFETCH ();
5938 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
5939 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
5940 goto fail;
5942 SET_REGS_MATCHED ();
5943 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
5944 d++;
5945 break;
5948 case charset:
5949 case charset_not:
5951 register US_CHAR_TYPE c;
5952 #ifdef MBS_SUPPORT
5953 unsigned int i, char_class_length, coll_symbol_length,
5954 equiv_class_length, ranges_length, chars_length, length;
5955 CHAR_TYPE *workp, *workp2, *charset_top;
5956 #define WORK_BUFFER_SIZE 128
5957 CHAR_TYPE str_buf[WORK_BUFFER_SIZE];
5958 # ifdef _LIBC
5959 uint32_t nrules;
5960 # endif /* _LIBC */
5961 #endif /* MBS_SUPPORT */
5962 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5964 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5965 PREFETCH ();
5966 c = TRANSLATE (*d); /* The character to match. */
5967 #ifdef MBS_SUPPORT
5968 # ifdef _LIBC
5969 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
5970 # endif /* _LIBC */
5971 charset_top = p - 1;
5972 char_class_length = *p++;
5973 coll_symbol_length = *p++;
5974 equiv_class_length = *p++;
5975 ranges_length = *p++;
5976 chars_length = *p++;
5977 /* p points charset[6], so the address of the next instruction
5978 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
5979 where l=length of char_classes, m=length of collating_symbol,
5980 n=equivalence_class, o=length of char_range,
5981 p'=length of character. */
5982 workp = p;
5983 /* Update p to indicate the next instruction. */
5984 p += char_class_length + coll_symbol_length+ equiv_class_length +
5985 2*ranges_length + chars_length;
5987 /* match with char_class? */
5988 for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
5990 wctype_t wctype;
5991 uintptr_t alignedp = ((uintptr_t)workp
5992 + __alignof__(wctype_t) - 1)
5993 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
5994 wctype = *((wctype_t*)alignedp);
5995 workp += CHAR_CLASS_SIZE;
5996 if (iswctype((wint_t)c, wctype))
5997 goto char_set_matched;
6000 /* match with collating_symbol? */
6001 # ifdef _LIBC
6002 if (nrules != 0)
6004 const unsigned char *extra = (const unsigned char *)
6005 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6007 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6008 workp++)
6010 int32_t *wextra;
6011 wextra = (int32_t*)(extra + *workp++);
6012 for (i = 0; i < *wextra; ++i)
6013 if (TRANSLATE(d[i]) != wextra[1 + i])
6014 break;
6016 if (i == *wextra)
6018 /* Update d, however d will be incremented at
6019 char_set_matched:, we decrement d here. */
6020 d += i - 1;
6021 goto char_set_matched;
6025 else /* (nrules == 0) */
6026 # endif
6027 /* If we can't look up collation data, we use wcscoll
6028 instead. */
6030 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6032 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6033 length = wcslen(workp);
6035 /* If wcscoll(the collating symbol, whole string) > 0,
6036 any substring of the string never match with the
6037 collating symbol. */
6038 if (wcscoll(workp, d) > 0)
6040 workp += length + 1;
6041 continue;
6044 /* First, we compare the collating symbol with
6045 the first character of the string.
6046 If it don't match, we add the next character to
6047 the compare buffer in turn. */
6048 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6050 int match;
6051 if (d == dend)
6053 if (dend == end_match_2)
6054 break;
6055 d = string2;
6056 dend = end_match_2;
6059 /* add next character to the compare buffer. */
6060 str_buf[i] = TRANSLATE(*d);
6061 str_buf[i+1] = '\0';
6063 match = wcscoll(workp, str_buf);
6064 if (match == 0)
6065 goto char_set_matched;
6067 if (match < 0)
6068 /* (str_buf > workp) indicate (str_buf + X > workp),
6069 because for all X (str_buf + X > str_buf).
6070 So we don't need continue this loop. */
6071 break;
6073 /* Otherwise(str_buf < workp),
6074 (str_buf+next_character) may equals (workp).
6075 So we continue this loop. */
6077 /* not matched */
6078 d = backup_d;
6079 dend = backup_dend;
6080 workp += length + 1;
6083 /* match with equivalence_class? */
6084 # ifdef _LIBC
6085 if (nrules != 0)
6087 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6088 /* Try to match the equivalence class against
6089 those known to the collate implementation. */
6090 const int32_t *table;
6091 const int32_t *weights;
6092 const int32_t *extra;
6093 const int32_t *indirect;
6094 int32_t idx, idx2;
6095 wint_t *cp;
6096 size_t len;
6098 /* This #include defines a local function! */
6099 # include <locale/weightwc.h>
6101 table = (const int32_t *)
6102 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6103 weights = (const wint_t *)
6104 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6105 extra = (const wint_t *)
6106 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6107 indirect = (const int32_t *)
6108 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6110 /* Write 1 collating element to str_buf, and
6111 get its index. */
6112 idx2 = 0;
6114 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6116 cp = (wint_t*)str_buf;
6117 if (d == dend)
6119 if (dend == end_match_2)
6120 break;
6121 d = string2;
6122 dend = end_match_2;
6124 str_buf[i] = TRANSLATE(*(d+i));
6125 str_buf[i+1] = '\0'; /* sentinel */
6126 idx2 = findidx ((const wint_t**)&cp);
6129 /* Update d, however d will be incremented at
6130 char_set_matched:, we decrement d here. */
6131 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6132 if (d >= dend)
6134 if (dend == end_match_2)
6135 d = dend;
6136 else
6138 d = string2;
6139 dend = end_match_2;
6143 len = weights[idx2];
6145 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6146 workp++)
6148 idx = (int32_t)*workp;
6149 /* We already checked idx != 0 in regex_compile. */
6151 if (idx2 != 0 && len == weights[idx])
6153 int cnt = 0;
6154 while (cnt < len && (weights[idx + 1 + cnt]
6155 == weights[idx2 + 1 + cnt]))
6156 ++cnt;
6158 if (cnt == len)
6159 goto char_set_matched;
6162 /* not matched */
6163 d = backup_d;
6164 dend = backup_dend;
6166 else /* (nrules == 0) */
6167 # endif
6168 /* If we can't look up collation data, we use wcscoll
6169 instead. */
6171 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6173 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6174 length = wcslen(workp);
6176 /* If wcscoll(the collating symbol, whole string) > 0,
6177 any substring of the string never match with the
6178 collating symbol. */
6179 if (wcscoll(workp, d) > 0)
6181 workp += length + 1;
6182 break;
6185 /* First, we compare the equivalence class with
6186 the first character of the string.
6187 If it don't match, we add the next character to
6188 the compare buffer in turn. */
6189 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6191 int match;
6192 if (d == dend)
6194 if (dend == end_match_2)
6195 break;
6196 d = string2;
6197 dend = end_match_2;
6200 /* add next character to the compare buffer. */
6201 str_buf[i] = TRANSLATE(*d);
6202 str_buf[i+1] = '\0';
6204 match = wcscoll(workp, str_buf);
6206 if (match == 0)
6207 goto char_set_matched;
6209 if (match < 0)
6210 /* (str_buf > workp) indicate (str_buf + X > workp),
6211 because for all X (str_buf + X > str_buf).
6212 So we don't need continue this loop. */
6213 break;
6215 /* Otherwise(str_buf < workp),
6216 (str_buf+next_character) may equals (workp).
6217 So we continue this loop. */
6219 /* not matched */
6220 d = backup_d;
6221 dend = backup_dend;
6222 workp += length + 1;
6226 /* match with char_range? */
6227 #ifdef _LIBC
6228 if (nrules != 0)
6230 uint32_t collseqval;
6231 const char *collseq = (const char *)
6232 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6234 collseqval = collseq_table_lookup (collseq, c);
6236 for (; workp < p - chars_length ;)
6238 uint32_t start_val, end_val;
6240 /* We already compute the collation sequence value
6241 of the characters (or collating symbols). */
6242 start_val = (uint32_t) *workp++; /* range_start */
6243 end_val = (uint32_t) *workp++; /* range_end */
6245 if (start_val <= collseqval && collseqval <= end_val)
6246 goto char_set_matched;
6249 else
6250 #endif
6252 /* We set range_start_char at str_buf[0], range_end_char
6253 at str_buf[4], and compared char at str_buf[2]. */
6254 str_buf[1] = 0;
6255 str_buf[2] = c;
6256 str_buf[3] = 0;
6257 str_buf[5] = 0;
6258 for (; workp < p - chars_length ;)
6260 wchar_t *range_start_char, *range_end_char;
6262 /* match if (range_start_char <= c <= range_end_char). */
6264 /* If range_start(or end) < 0, we assume -range_start(end)
6265 is the offset of the collating symbol which is specified
6266 as the character of the range start(end). */
6268 /* range_start */
6269 if (*workp < 0)
6270 range_start_char = charset_top - (*workp++);
6271 else
6273 str_buf[0] = *workp++;
6274 range_start_char = str_buf;
6277 /* range_end */
6278 if (*workp < 0)
6279 range_end_char = charset_top - (*workp++);
6280 else
6282 str_buf[4] = *workp++;
6283 range_end_char = str_buf + 4;
6286 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6287 wcscoll(str_buf+2, range_end_char) <= 0)
6289 goto char_set_matched;
6293 /* match with char? */
6294 for (; workp < p ; workp++)
6295 if (c == *workp)
6296 goto char_set_matched;
6298 not = !not;
6300 char_set_matched:
6301 if (not) goto fail;
6302 #else
6303 /* Cast to `unsigned' instead of `unsigned char' in case the
6304 bit list is a full 32 bytes long. */
6305 if (c < (unsigned) (*p * BYTEWIDTH)
6306 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6307 not = !not;
6309 p += 1 + *p;
6311 if (!not) goto fail;
6312 #undef WORK_BUFFER_SIZE
6313 #endif /* MBS_SUPPORT */
6314 SET_REGS_MATCHED ();
6315 d++;
6316 break;
6320 /* The beginning of a group is represented by start_memory.
6321 The arguments are the register number in the next byte, and the
6322 number of groups inner to this one in the next. The text
6323 matched within the group is recorded (in the internal
6324 registers data structure) under the register number. */
6325 case start_memory:
6326 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6327 (long int) *p, (long int) p[1]);
6329 /* Find out if this group can match the empty string. */
6330 p1 = p; /* To send to group_match_null_string_p. */
6332 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6333 REG_MATCH_NULL_STRING_P (reg_info[*p])
6334 = group_match_null_string_p (&p1, pend, reg_info);
6336 /* Save the position in the string where we were the last time
6337 we were at this open-group operator in case the group is
6338 operated upon by a repetition operator, e.g., with `(a*)*b'
6339 against `ab'; then we want to ignore where we are now in
6340 the string in case this attempt to match fails. */
6341 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6342 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6343 : regstart[*p];
6344 DEBUG_PRINT2 (" old_regstart: %d\n",
6345 POINTER_TO_OFFSET (old_regstart[*p]));
6347 regstart[*p] = d;
6348 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6350 IS_ACTIVE (reg_info[*p]) = 1;
6351 MATCHED_SOMETHING (reg_info[*p]) = 0;
6353 /* Clear this whenever we change the register activity status. */
6354 set_regs_matched_done = 0;
6356 /* This is the new highest active register. */
6357 highest_active_reg = *p;
6359 /* If nothing was active before, this is the new lowest active
6360 register. */
6361 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6362 lowest_active_reg = *p;
6364 /* Move past the register number and inner group count. */
6365 p += 2;
6366 just_past_start_mem = p;
6368 break;
6371 /* The stop_memory opcode represents the end of a group. Its
6372 arguments are the same as start_memory's: the register
6373 number, and the number of inner groups. */
6374 case stop_memory:
6375 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6376 (long int) *p, (long int) p[1]);
6378 /* We need to save the string position the last time we were at
6379 this close-group operator in case the group is operated
6380 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6381 against `aba'; then we want to ignore where we are now in
6382 the string in case this attempt to match fails. */
6383 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6384 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6385 : regend[*p];
6386 DEBUG_PRINT2 (" old_regend: %d\n",
6387 POINTER_TO_OFFSET (old_regend[*p]));
6389 regend[*p] = d;
6390 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6392 /* This register isn't active anymore. */
6393 IS_ACTIVE (reg_info[*p]) = 0;
6395 /* Clear this whenever we change the register activity status. */
6396 set_regs_matched_done = 0;
6398 /* If this was the only register active, nothing is active
6399 anymore. */
6400 if (lowest_active_reg == highest_active_reg)
6402 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6403 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6405 else
6406 { /* We must scan for the new highest active register, since
6407 it isn't necessarily one less than now: consider
6408 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6409 new highest active register is 1. */
6410 US_CHAR_TYPE r = *p - 1;
6411 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6412 r--;
6414 /* If we end up at register zero, that means that we saved
6415 the registers as the result of an `on_failure_jump', not
6416 a `start_memory', and we jumped to past the innermost
6417 `stop_memory'. For example, in ((.)*) we save
6418 registers 1 and 2 as a result of the *, but when we pop
6419 back to the second ), we are at the stop_memory 1.
6420 Thus, nothing is active. */
6421 if (r == 0)
6423 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6424 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6426 else
6427 highest_active_reg = r;
6430 /* If just failed to match something this time around with a
6431 group that's operated on by a repetition operator, try to
6432 force exit from the ``loop'', and restore the register
6433 information for this group that we had before trying this
6434 last match. */
6435 if ((!MATCHED_SOMETHING (reg_info[*p])
6436 || just_past_start_mem == p - 1)
6437 && (p + 2) < pend)
6439 boolean is_a_jump_n = false;
6441 p1 = p + 2;
6442 mcnt = 0;
6443 switch ((re_opcode_t) *p1++)
6445 case jump_n:
6446 is_a_jump_n = true;
6447 case pop_failure_jump:
6448 case maybe_pop_jump:
6449 case jump:
6450 case dummy_failure_jump:
6451 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6452 if (is_a_jump_n)
6453 p1 += OFFSET_ADDRESS_SIZE;
6454 break;
6456 default:
6457 /* do nothing */ ;
6459 p1 += mcnt;
6461 /* If the next operation is a jump backwards in the pattern
6462 to an on_failure_jump right before the start_memory
6463 corresponding to this stop_memory, exit from the loop
6464 by forcing a failure after pushing on the stack the
6465 on_failure_jump's jump in the pattern, and d. */
6466 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6467 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6468 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6470 /* If this group ever matched anything, then restore
6471 what its registers were before trying this last
6472 failed match, e.g., with `(a*)*b' against `ab' for
6473 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6474 against `aba' for regend[3].
6476 Also restore the registers for inner groups for,
6477 e.g., `((a*)(b*))*' against `aba' (register 3 would
6478 otherwise get trashed). */
6480 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6482 unsigned r;
6484 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6486 /* Restore this and inner groups' (if any) registers. */
6487 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6488 r++)
6490 regstart[r] = old_regstart[r];
6492 /* xx why this test? */
6493 if (old_regend[r] >= regstart[r])
6494 regend[r] = old_regend[r];
6497 p1++;
6498 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6499 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6501 goto fail;
6505 /* Move past the register number and the inner group count. */
6506 p += 2;
6507 break;
6510 /* \<digit> has been turned into a `duplicate' command which is
6511 followed by the numeric value of <digit> as the register number. */
6512 case duplicate:
6514 register const CHAR_TYPE *d2, *dend2;
6515 int regno = *p++; /* Get which register to match against. */
6516 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6518 /* Can't back reference a group which we've never matched. */
6519 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6520 goto fail;
6522 /* Where in input to try to start matching. */
6523 d2 = regstart[regno];
6525 /* Where to stop matching; if both the place to start and
6526 the place to stop matching are in the same string, then
6527 set to the place to stop, otherwise, for now have to use
6528 the end of the first string. */
6530 dend2 = ((FIRST_STRING_P (regstart[regno])
6531 == FIRST_STRING_P (regend[regno]))
6532 ? regend[regno] : end_match_1);
6533 for (;;)
6535 /* If necessary, advance to next segment in register
6536 contents. */
6537 while (d2 == dend2)
6539 if (dend2 == end_match_2) break;
6540 if (dend2 == regend[regno]) break;
6542 /* End of string1 => advance to string2. */
6543 d2 = string2;
6544 dend2 = regend[regno];
6546 /* At end of register contents => success */
6547 if (d2 == dend2) break;
6549 /* If necessary, advance to next segment in data. */
6550 PREFETCH ();
6552 /* How many characters left in this segment to match. */
6553 mcnt = dend - d;
6555 /* Want how many consecutive characters we can match in
6556 one shot, so, if necessary, adjust the count. */
6557 if (mcnt > dend2 - d2)
6558 mcnt = dend2 - d2;
6560 /* Compare that many; failure if mismatch, else move
6561 past them. */
6562 if (translate
6563 ? bcmp_translate (d, d2, mcnt, translate)
6564 : memcmp (d, d2, mcnt*sizeof(US_CHAR_TYPE)))
6565 goto fail;
6566 d += mcnt, d2 += mcnt;
6568 /* Do this because we've match some characters. */
6569 SET_REGS_MATCHED ();
6572 break;
6575 /* begline matches the empty string at the beginning of the string
6576 (unless `not_bol' is set in `bufp'), and, if
6577 `newline_anchor' is set, after newlines. */
6578 case begline:
6579 DEBUG_PRINT1 ("EXECUTING begline.\n");
6581 if (AT_STRINGS_BEG (d))
6583 if (!bufp->not_bol) break;
6585 else if (d[-1] == '\n' && bufp->newline_anchor)
6587 break;
6589 /* In all other cases, we fail. */
6590 goto fail;
6593 /* endline is the dual of begline. */
6594 case endline:
6595 DEBUG_PRINT1 ("EXECUTING endline.\n");
6597 if (AT_STRINGS_END (d))
6599 if (!bufp->not_eol) break;
6602 /* We have to ``prefetch'' the next character. */
6603 else if ((d == end1 ? *string2 : *d) == '\n'
6604 && bufp->newline_anchor)
6606 break;
6608 goto fail;
6611 /* Match at the very beginning of the data. */
6612 case begbuf:
6613 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6614 if (AT_STRINGS_BEG (d))
6615 break;
6616 goto fail;
6619 /* Match at the very end of the data. */
6620 case endbuf:
6621 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6622 if (AT_STRINGS_END (d))
6623 break;
6624 goto fail;
6627 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6628 pushes NULL as the value for the string on the stack. Then
6629 `pop_failure_point' will keep the current value for the
6630 string, instead of restoring it. To see why, consider
6631 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6632 then the . fails against the \n. But the next thing we want
6633 to do is match the \n against the \n; if we restored the
6634 string value, we would be back at the foo.
6636 Because this is used only in specific cases, we don't need to
6637 check all the things that `on_failure_jump' does, to make
6638 sure the right things get saved on the stack. Hence we don't
6639 share its code. The only reason to push anything on the
6640 stack at all is that otherwise we would have to change
6641 `anychar's code to do something besides goto fail in this
6642 case; that seems worse than this. */
6643 case on_failure_keep_string_jump:
6644 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6646 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6647 #ifdef _LIBC
6648 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6649 #else
6650 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6651 #endif
6653 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6654 break;
6657 /* Uses of on_failure_jump:
6659 Each alternative starts with an on_failure_jump that points
6660 to the beginning of the next alternative. Each alternative
6661 except the last ends with a jump that in effect jumps past
6662 the rest of the alternatives. (They really jump to the
6663 ending jump of the following alternative, because tensioning
6664 these jumps is a hassle.)
6666 Repeats start with an on_failure_jump that points past both
6667 the repetition text and either the following jump or
6668 pop_failure_jump back to this on_failure_jump. */
6669 case on_failure_jump:
6670 on_failure:
6671 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6673 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6674 #ifdef _LIBC
6675 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6676 #else
6677 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6678 #endif
6680 /* If this on_failure_jump comes right before a group (i.e.,
6681 the original * applied to a group), save the information
6682 for that group and all inner ones, so that if we fail back
6683 to this point, the group's information will be correct.
6684 For example, in \(a*\)*\1, we need the preceding group,
6685 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6687 /* We can't use `p' to check ahead because we push
6688 a failure point to `p + mcnt' after we do this. */
6689 p1 = p;
6691 /* We need to skip no_op's before we look for the
6692 start_memory in case this on_failure_jump is happening as
6693 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6694 against aba. */
6695 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6696 p1++;
6698 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6700 /* We have a new highest active register now. This will
6701 get reset at the start_memory we are about to get to,
6702 but we will have saved all the registers relevant to
6703 this repetition op, as described above. */
6704 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6705 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6706 lowest_active_reg = *(p1 + 1);
6709 DEBUG_PRINT1 (":\n");
6710 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6711 break;
6714 /* A smart repeat ends with `maybe_pop_jump'.
6715 We change it to either `pop_failure_jump' or `jump'. */
6716 case maybe_pop_jump:
6717 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6718 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6720 register US_CHAR_TYPE *p2 = p;
6722 /* Compare the beginning of the repeat with what in the
6723 pattern follows its end. If we can establish that there
6724 is nothing that they would both match, i.e., that we
6725 would have to backtrack because of (as in, e.g., `a*a')
6726 then we can change to pop_failure_jump, because we'll
6727 never have to backtrack.
6729 This is not true in the case of alternatives: in
6730 `(a|ab)*' we do need to backtrack to the `ab' alternative
6731 (e.g., if the string was `ab'). But instead of trying to
6732 detect that here, the alternative has put on a dummy
6733 failure point which is what we will end up popping. */
6735 /* Skip over open/close-group commands.
6736 If what follows this loop is a ...+ construct,
6737 look at what begins its body, since we will have to
6738 match at least one of that. */
6739 while (1)
6741 if (p2 + 2 < pend
6742 && ((re_opcode_t) *p2 == stop_memory
6743 || (re_opcode_t) *p2 == start_memory))
6744 p2 += 3;
6745 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6746 && (re_opcode_t) *p2 == dummy_failure_jump)
6747 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6748 else
6749 break;
6752 p1 = p + mcnt;
6753 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
6754 to the `maybe_finalize_jump' of this case. Examine what
6755 follows. */
6757 /* If we're at the end of the pattern, we can change. */
6758 if (p2 == pend)
6760 /* Consider what happens when matching ":\(.*\)"
6761 against ":/". I don't really understand this code
6762 yet. */
6763 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6764 pop_failure_jump;
6765 DEBUG_PRINT1
6766 (" End of pattern: change to `pop_failure_jump'.\n");
6769 else if ((re_opcode_t) *p2 == exactn
6770 #ifdef MBS_SUPPORT
6771 || (re_opcode_t) *p2 == exactn_bin
6772 #endif
6773 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
6775 register US_CHAR_TYPE c
6776 = *p2 == (US_CHAR_TYPE) endline ? '\n' : p2[2];
6778 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
6779 #ifdef MBS_SUPPORT
6780 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
6781 #endif
6782 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
6784 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6785 pop_failure_jump;
6786 #ifdef MBS_SUPPORT
6787 if (MB_CUR_MAX != 1)
6788 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
6789 (wint_t) c,
6790 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
6791 else
6792 #endif
6793 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
6794 (char) c,
6795 (char) p1[3+OFFSET_ADDRESS_SIZE]);
6798 #ifndef MBS_SUPPORT
6799 else if ((re_opcode_t) p1[3] == charset
6800 || (re_opcode_t) p1[3] == charset_not)
6802 int not = (re_opcode_t) p1[3] == charset_not;
6804 if (c < (unsigned) (p1[4] * BYTEWIDTH)
6805 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6806 not = !not;
6808 /* `not' is equal to 1 if c would match, which means
6809 that we can't change to pop_failure_jump. */
6810 if (!not)
6812 p[-3] = (unsigned char) pop_failure_jump;
6813 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6816 #endif /* not MBS_SUPPORT */
6818 #ifndef MBS_SUPPORT
6819 else if ((re_opcode_t) *p2 == charset)
6821 /* We win if the first character of the loop is not part
6822 of the charset. */
6823 if ((re_opcode_t) p1[3] == exactn
6824 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
6825 && (p2[2 + p1[5] / BYTEWIDTH]
6826 & (1 << (p1[5] % BYTEWIDTH)))))
6828 p[-3] = (unsigned char) pop_failure_jump;
6829 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6832 else if ((re_opcode_t) p1[3] == charset_not)
6834 int idx;
6835 /* We win if the charset_not inside the loop
6836 lists every character listed in the charset after. */
6837 for (idx = 0; idx < (int) p2[1]; idx++)
6838 if (! (p2[2 + idx] == 0
6839 || (idx < (int) p1[4]
6840 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
6841 break;
6843 if (idx == p2[1])
6845 p[-3] = (unsigned char) pop_failure_jump;
6846 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6849 else if ((re_opcode_t) p1[3] == charset)
6851 int idx;
6852 /* We win if the charset inside the loop
6853 has no overlap with the one after the loop. */
6854 for (idx = 0;
6855 idx < (int) p2[1] && idx < (int) p1[4];
6856 idx++)
6857 if ((p2[2 + idx] & p1[5 + idx]) != 0)
6858 break;
6860 if (idx == p2[1] || idx == p1[4])
6862 p[-3] = (unsigned char) pop_failure_jump;
6863 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6867 #endif /* not MBS_SUPPORT */
6869 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
6870 if ((re_opcode_t) p[-1] != pop_failure_jump)
6872 p[-1] = (US_CHAR_TYPE) jump;
6873 DEBUG_PRINT1 (" Match => jump.\n");
6874 goto unconditional_jump;
6876 /* Note fall through. */
6879 /* The end of a simple repeat has a pop_failure_jump back to
6880 its matching on_failure_jump, where the latter will push a
6881 failure point. The pop_failure_jump takes off failure
6882 points put on by this pop_failure_jump's matching
6883 on_failure_jump; we got through the pattern to here from the
6884 matching on_failure_jump, so didn't fail. */
6885 case pop_failure_jump:
6887 /* We need to pass separate storage for the lowest and
6888 highest registers, even though we don't care about the
6889 actual values. Otherwise, we will restore only one
6890 register from the stack, since lowest will == highest in
6891 `pop_failure_point'. */
6892 active_reg_t dummy_low_reg, dummy_high_reg;
6893 US_CHAR_TYPE *pdummy = NULL;
6894 const CHAR_TYPE *sdummy = NULL;
6896 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
6897 POP_FAILURE_POINT (sdummy, pdummy,
6898 dummy_low_reg, dummy_high_reg,
6899 reg_dummy, reg_dummy, reg_info_dummy);
6901 /* Note fall through. */
6903 unconditional_jump:
6904 #ifdef _LIBC
6905 DEBUG_PRINT2 ("\n%p: ", p);
6906 #else
6907 DEBUG_PRINT2 ("\n0x%x: ", p);
6908 #endif
6909 /* Note fall through. */
6911 /* Unconditionally jump (without popping any failure points). */
6912 case jump:
6913 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
6914 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
6915 p += mcnt; /* Do the jump. */
6916 #ifdef _LIBC
6917 DEBUG_PRINT2 ("(to %p).\n", p);
6918 #else
6919 DEBUG_PRINT2 ("(to 0x%x).\n", p);
6920 #endif
6921 break;
6924 /* We need this opcode so we can detect where alternatives end
6925 in `group_match_null_string_p' et al. */
6926 case jump_past_alt:
6927 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
6928 goto unconditional_jump;
6931 /* Normally, the on_failure_jump pushes a failure point, which
6932 then gets popped at pop_failure_jump. We will end up at
6933 pop_failure_jump, also, and with a pattern of, say, `a+', we
6934 are skipping over the on_failure_jump, so we have to push
6935 something meaningless for pop_failure_jump to pop. */
6936 case dummy_failure_jump:
6937 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
6938 /* It doesn't matter what we push for the string here. What
6939 the code at `fail' tests is the value for the pattern. */
6940 PUSH_FAILURE_POINT (NULL, NULL, -2);
6941 goto unconditional_jump;
6944 /* At the end of an alternative, we need to push a dummy failure
6945 point in case we are followed by a `pop_failure_jump', because
6946 we don't want the failure point for the alternative to be
6947 popped. For example, matching `(a|ab)*' against `aab'
6948 requires that we match the `ab' alternative. */
6949 case push_dummy_failure:
6950 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
6951 /* See comments just above at `dummy_failure_jump' about the
6952 two zeroes. */
6953 PUSH_FAILURE_POINT (NULL, NULL, -2);
6954 break;
6956 /* Have to succeed matching what follows at least n times.
6957 After that, handle like `on_failure_jump'. */
6958 case succeed_n:
6959 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6960 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
6962 assert (mcnt >= 0);
6963 /* Originally, this is how many times we HAVE to succeed. */
6964 if (mcnt > 0)
6966 mcnt--;
6967 p += OFFSET_ADDRESS_SIZE;
6968 STORE_NUMBER_AND_INCR (p, mcnt);
6969 #ifdef _LIBC
6970 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
6971 , mcnt);
6972 #else
6973 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
6974 , mcnt);
6975 #endif
6977 else if (mcnt == 0)
6979 #ifdef _LIBC
6980 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
6981 p + OFFSET_ADDRESS_SIZE);
6982 #else
6983 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
6984 p + OFFSET_ADDRESS_SIZE);
6985 #endif /* _LIBC */
6987 #ifdef MBS_SUPPORT
6988 p[1] = (US_CHAR_TYPE) no_op;
6989 #else
6990 p[2] = (US_CHAR_TYPE) no_op;
6991 p[3] = (US_CHAR_TYPE) no_op;
6992 #endif /* MBS_SUPPORT */
6993 goto on_failure;
6995 break;
6997 case jump_n:
6998 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6999 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7001 /* Originally, this is how many times we CAN jump. */
7002 if (mcnt)
7004 mcnt--;
7005 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7007 #ifdef _LIBC
7008 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7009 mcnt);
7010 #else
7011 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7012 mcnt);
7013 #endif /* _LIBC */
7014 goto unconditional_jump;
7016 /* If don't have to jump any more, skip over the rest of command. */
7017 else
7018 p += 2 * OFFSET_ADDRESS_SIZE;
7019 break;
7021 case set_number_at:
7023 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7025 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7026 p1 = p + mcnt;
7027 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7028 #ifdef _LIBC
7029 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7030 #else
7031 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7032 #endif
7033 STORE_NUMBER (p1, mcnt);
7034 break;
7037 #if 0
7038 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7039 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7040 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7041 macro and introducing temporary variables works around the bug. */
7043 case wordbound:
7044 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7045 if (AT_WORD_BOUNDARY (d))
7046 break;
7047 goto fail;
7049 case notwordbound:
7050 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7051 if (AT_WORD_BOUNDARY (d))
7052 goto fail;
7053 break;
7054 #else
7055 case wordbound:
7057 boolean prevchar, thischar;
7059 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7060 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7061 break;
7063 prevchar = WORDCHAR_P (d - 1);
7064 thischar = WORDCHAR_P (d);
7065 if (prevchar != thischar)
7066 break;
7067 goto fail;
7070 case notwordbound:
7072 boolean prevchar, thischar;
7074 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7075 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7076 goto fail;
7078 prevchar = WORDCHAR_P (d - 1);
7079 thischar = WORDCHAR_P (d);
7080 if (prevchar != thischar)
7081 goto fail;
7082 break;
7084 #endif
7086 case wordbeg:
7087 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7088 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7089 break;
7090 goto fail;
7092 case wordend:
7093 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7094 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7095 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
7096 break;
7097 goto fail;
7099 #ifdef emacs
7100 case before_dot:
7101 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7102 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7103 goto fail;
7104 break;
7106 case at_dot:
7107 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7108 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7109 goto fail;
7110 break;
7112 case after_dot:
7113 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7114 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7115 goto fail;
7116 break;
7118 case syntaxspec:
7119 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7120 mcnt = *p++;
7121 goto matchsyntax;
7123 case wordchar:
7124 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7125 mcnt = (int) Sword;
7126 matchsyntax:
7127 PREFETCH ();
7128 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7129 d++;
7130 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7131 goto fail;
7132 SET_REGS_MATCHED ();
7133 break;
7135 case notsyntaxspec:
7136 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7137 mcnt = *p++;
7138 goto matchnotsyntax;
7140 case notwordchar:
7141 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7142 mcnt = (int) Sword;
7143 matchnotsyntax:
7144 PREFETCH ();
7145 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7146 d++;
7147 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7148 goto fail;
7149 SET_REGS_MATCHED ();
7150 break;
7152 #else /* not emacs */
7153 case wordchar:
7154 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7155 PREFETCH ();
7156 if (!WORDCHAR_P (d))
7157 goto fail;
7158 SET_REGS_MATCHED ();
7159 d++;
7160 break;
7162 case notwordchar:
7163 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7164 PREFETCH ();
7165 if (WORDCHAR_P (d))
7166 goto fail;
7167 SET_REGS_MATCHED ();
7168 d++;
7169 break;
7170 #endif /* not emacs */
7172 default:
7173 abort ();
7175 continue; /* Successfully executed one pattern command; keep going. */
7178 /* We goto here if a matching operation fails. */
7179 fail:
7180 if (!FAIL_STACK_EMPTY ())
7181 { /* A restart point is known. Restore to that state. */
7182 DEBUG_PRINT1 ("\nFAIL:\n");
7183 POP_FAILURE_POINT (d, p,
7184 lowest_active_reg, highest_active_reg,
7185 regstart, regend, reg_info);
7187 /* If this failure point is a dummy, try the next one. */
7188 if (!p)
7189 goto fail;
7191 /* If we failed to the end of the pattern, don't examine *p. */
7192 assert (p <= pend);
7193 if (p < pend)
7195 boolean is_a_jump_n = false;
7197 /* If failed to a backwards jump that's part of a repetition
7198 loop, need to pop this failure point and use the next one. */
7199 switch ((re_opcode_t) *p)
7201 case jump_n:
7202 is_a_jump_n = true;
7203 case maybe_pop_jump:
7204 case pop_failure_jump:
7205 case jump:
7206 p1 = p + 1;
7207 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7208 p1 += mcnt;
7210 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7211 || (!is_a_jump_n
7212 && (re_opcode_t) *p1 == on_failure_jump))
7213 goto fail;
7214 break;
7215 default:
7216 /* do nothing */ ;
7220 if (d >= string1 && d <= end1)
7221 dend = end_match_1;
7223 else
7224 break; /* Matching at this starting point really fails. */
7225 } /* for (;;) */
7227 if (best_regs_set)
7228 goto restore_best_regs;
7230 FREE_VARIABLES ();
7232 return -1; /* Failure to match. */
7233 } /* re_match_2 */
7235 /* Subroutine definitions for re_match_2. */
7238 /* We are passed P pointing to a register number after a start_memory.
7240 Return true if the pattern up to the corresponding stop_memory can
7241 match the empty string, and false otherwise.
7243 If we find the matching stop_memory, sets P to point to one past its number.
7244 Otherwise, sets P to an undefined byte less than or equal to END.
7246 We don't handle duplicates properly (yet). */
7248 static boolean
7249 group_match_null_string_p (p, end, reg_info)
7250 US_CHAR_TYPE **p, *end;
7251 register_info_type *reg_info;
7253 int mcnt;
7254 /* Point to after the args to the start_memory. */
7255 US_CHAR_TYPE *p1 = *p + 2;
7257 while (p1 < end)
7259 /* Skip over opcodes that can match nothing, and return true or
7260 false, as appropriate, when we get to one that can't, or to the
7261 matching stop_memory. */
7263 switch ((re_opcode_t) *p1)
7265 /* Could be either a loop or a series of alternatives. */
7266 case on_failure_jump:
7267 p1++;
7268 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7270 /* If the next operation is not a jump backwards in the
7271 pattern. */
7273 if (mcnt >= 0)
7275 /* Go through the on_failure_jumps of the alternatives,
7276 seeing if any of the alternatives cannot match nothing.
7277 The last alternative starts with only a jump,
7278 whereas the rest start with on_failure_jump and end
7279 with a jump, e.g., here is the pattern for `a|b|c':
7281 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7282 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7283 /exactn/1/c
7285 So, we have to first go through the first (n-1)
7286 alternatives and then deal with the last one separately. */
7289 /* Deal with the first (n-1) alternatives, which start
7290 with an on_failure_jump (see above) that jumps to right
7291 past a jump_past_alt. */
7293 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7294 jump_past_alt)
7296 /* `mcnt' holds how many bytes long the alternative
7297 is, including the ending `jump_past_alt' and
7298 its number. */
7300 if (!alt_match_null_string_p (p1, p1 + mcnt -
7301 (1 + OFFSET_ADDRESS_SIZE),
7302 reg_info))
7303 return false;
7305 /* Move to right after this alternative, including the
7306 jump_past_alt. */
7307 p1 += mcnt;
7309 /* Break if it's the beginning of an n-th alternative
7310 that doesn't begin with an on_failure_jump. */
7311 if ((re_opcode_t) *p1 != on_failure_jump)
7312 break;
7314 /* Still have to check that it's not an n-th
7315 alternative that starts with an on_failure_jump. */
7316 p1++;
7317 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7318 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7319 jump_past_alt)
7321 /* Get to the beginning of the n-th alternative. */
7322 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7323 break;
7327 /* Deal with the last alternative: go back and get number
7328 of the `jump_past_alt' just before it. `mcnt' contains
7329 the length of the alternative. */
7330 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7332 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
7333 return false;
7335 p1 += mcnt; /* Get past the n-th alternative. */
7336 } /* if mcnt > 0 */
7337 break;
7340 case stop_memory:
7341 assert (p1[1] == **p);
7342 *p = p1 + 2;
7343 return true;
7346 default:
7347 if (!common_op_match_null_string_p (&p1, end, reg_info))
7348 return false;
7350 } /* while p1 < end */
7352 return false;
7353 } /* group_match_null_string_p */
7356 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7357 It expects P to be the first byte of a single alternative and END one
7358 byte past the last. The alternative can contain groups. */
7360 static boolean
7361 alt_match_null_string_p (p, end, reg_info)
7362 US_CHAR_TYPE *p, *end;
7363 register_info_type *reg_info;
7365 int mcnt;
7366 US_CHAR_TYPE *p1 = p;
7368 while (p1 < end)
7370 /* Skip over opcodes that can match nothing, and break when we get
7371 to one that can't. */
7373 switch ((re_opcode_t) *p1)
7375 /* It's a loop. */
7376 case on_failure_jump:
7377 p1++;
7378 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7379 p1 += mcnt;
7380 break;
7382 default:
7383 if (!common_op_match_null_string_p (&p1, end, reg_info))
7384 return false;
7386 } /* while p1 < end */
7388 return true;
7389 } /* alt_match_null_string_p */
7392 /* Deals with the ops common to group_match_null_string_p and
7393 alt_match_null_string_p.
7395 Sets P to one after the op and its arguments, if any. */
7397 static boolean
7398 common_op_match_null_string_p (p, end, reg_info)
7399 US_CHAR_TYPE **p, *end;
7400 register_info_type *reg_info;
7402 int mcnt;
7403 boolean ret;
7404 int reg_no;
7405 US_CHAR_TYPE *p1 = *p;
7407 switch ((re_opcode_t) *p1++)
7409 case no_op:
7410 case begline:
7411 case endline:
7412 case begbuf:
7413 case endbuf:
7414 case wordbeg:
7415 case wordend:
7416 case wordbound:
7417 case notwordbound:
7418 #ifdef emacs
7419 case before_dot:
7420 case at_dot:
7421 case after_dot:
7422 #endif
7423 break;
7425 case start_memory:
7426 reg_no = *p1;
7427 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7428 ret = group_match_null_string_p (&p1, end, reg_info);
7430 /* Have to set this here in case we're checking a group which
7431 contains a group and a back reference to it. */
7433 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7434 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7436 if (!ret)
7437 return false;
7438 break;
7440 /* If this is an optimized succeed_n for zero times, make the jump. */
7441 case jump:
7442 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7443 if (mcnt >= 0)
7444 p1 += mcnt;
7445 else
7446 return false;
7447 break;
7449 case succeed_n:
7450 /* Get to the number of times to succeed. */
7451 p1 += OFFSET_ADDRESS_SIZE;
7452 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7454 if (mcnt == 0)
7456 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7457 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7458 p1 += mcnt;
7460 else
7461 return false;
7462 break;
7464 case duplicate:
7465 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7466 return false;
7467 break;
7469 case set_number_at:
7470 p1 += 2 * OFFSET_ADDRESS_SIZE;
7472 default:
7473 /* All other opcodes mean we cannot match the empty string. */
7474 return false;
7477 *p = p1;
7478 return true;
7479 } /* common_op_match_null_string_p */
7482 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7483 bytes; nonzero otherwise. */
7485 static int
7486 bcmp_translate (s1, s2, len, translate)
7487 const CHAR_TYPE *s1, *s2;
7488 register int len;
7489 RE_TRANSLATE_TYPE translate;
7491 register const US_CHAR_TYPE *p1 = (const US_CHAR_TYPE *) s1;
7492 register const US_CHAR_TYPE *p2 = (const US_CHAR_TYPE *) s2;
7493 while (len)
7495 #ifdef MBS_SUPPORT
7496 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7497 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7498 return 1;
7499 #else
7500 if (translate[*p1++] != translate[*p2++]) return 1;
7501 #endif /* MBS_SUPPORT */
7502 len--;
7504 return 0;
7507 /* Entry points for GNU code. */
7509 /* re_compile_pattern is the GNU regular expression compiler: it
7510 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7511 Returns 0 if the pattern was valid, otherwise an error string.
7513 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7514 are set in BUFP on entry.
7516 We call regex_compile to do the actual compilation. */
7518 const char *
7519 re_compile_pattern (pattern, length, bufp)
7520 const char *pattern;
7521 size_t length;
7522 struct re_pattern_buffer *bufp;
7524 reg_errcode_t ret;
7526 /* GNU code is written to assume at least RE_NREGS registers will be set
7527 (and at least one extra will be -1). */
7528 bufp->regs_allocated = REGS_UNALLOCATED;
7530 /* And GNU code determines whether or not to get register information
7531 by passing null for the REGS argument to re_match, etc., not by
7532 setting no_sub. */
7533 bufp->no_sub = 0;
7535 /* Match anchors at newline. */
7536 bufp->newline_anchor = 1;
7538 ret = regex_compile (pattern, length, re_syntax_options, bufp);
7540 if (!ret)
7541 return NULL;
7542 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7544 #ifdef _LIBC
7545 weak_alias (__re_compile_pattern, re_compile_pattern)
7546 #endif
7548 /* Entry points compatible with 4.2 BSD regex library. We don't define
7549 them unless specifically requested. */
7551 #if defined _REGEX_RE_COMP || defined _LIBC
7553 /* BSD has one and only one pattern buffer. */
7554 static struct re_pattern_buffer re_comp_buf;
7556 char *
7557 #ifdef _LIBC
7558 /* Make these definitions weak in libc, so POSIX programs can redefine
7559 these names if they don't use our functions, and still use
7560 regcomp/regexec below without link errors. */
7561 weak_function
7562 #endif
7563 re_comp (s)
7564 const char *s;
7566 reg_errcode_t ret;
7568 if (!s)
7570 if (!re_comp_buf.buffer)
7571 return gettext ("No previous regular expression");
7572 return 0;
7575 if (!re_comp_buf.buffer)
7577 re_comp_buf.buffer = (unsigned char *) malloc (200);
7578 if (re_comp_buf.buffer == NULL)
7579 return (char *) gettext (re_error_msgid
7580 + re_error_msgid_idx[(int) REG_ESPACE]);
7581 re_comp_buf.allocated = 200;
7583 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7584 if (re_comp_buf.fastmap == NULL)
7585 return (char *) gettext (re_error_msgid
7586 + re_error_msgid_idx[(int) REG_ESPACE]);
7589 /* Since `re_exec' always passes NULL for the `regs' argument, we
7590 don't need to initialize the pattern buffer fields which affect it. */
7592 /* Match anchors at newlines. */
7593 re_comp_buf.newline_anchor = 1;
7595 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7597 if (!ret)
7598 return NULL;
7600 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7601 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7606 #ifdef _LIBC
7607 weak_function
7608 #endif
7609 re_exec (s)
7610 const char *s;
7612 const int len = strlen (s);
7613 return
7614 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7617 #endif /* _REGEX_RE_COMP */
7619 /* POSIX.2 functions. Don't define these for Emacs. */
7621 #ifndef emacs
7623 /* regcomp takes a regular expression as a string and compiles it.
7625 PREG is a regex_t *. We do not expect any fields to be initialized,
7626 since POSIX says we shouldn't. Thus, we set
7628 `buffer' to the compiled pattern;
7629 `used' to the length of the compiled pattern;
7630 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7631 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7632 RE_SYNTAX_POSIX_BASIC;
7633 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7634 `fastmap' to an allocated space for the fastmap;
7635 `fastmap_accurate' to zero;
7636 `re_nsub' to the number of subexpressions in PATTERN.
7638 PATTERN is the address of the pattern string.
7640 CFLAGS is a series of bits which affect compilation.
7642 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7643 use POSIX basic syntax.
7645 If REG_NEWLINE is set, then . and [^...] don't match newline.
7646 Also, regexec will try a match beginning after every newline.
7648 If REG_ICASE is set, then we considers upper- and lowercase
7649 versions of letters to be equivalent when matching.
7651 If REG_NOSUB is set, then when PREG is passed to regexec, that
7652 routine will report only success or failure, and nothing about the
7653 registers.
7655 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7656 the return codes and their meanings.) */
7659 regcomp (preg, pattern, cflags)
7660 regex_t *preg;
7661 const char *pattern;
7662 int cflags;
7664 reg_errcode_t ret;
7665 reg_syntax_t syntax
7666 = (cflags & REG_EXTENDED) ?
7667 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7669 /* regex_compile will allocate the space for the compiled pattern. */
7670 preg->buffer = 0;
7671 preg->allocated = 0;
7672 preg->used = 0;
7674 /* Try to allocate space for the fastmap. */
7675 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7677 if (cflags & REG_ICASE)
7679 unsigned i;
7681 preg->translate
7682 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7683 * sizeof (*(RE_TRANSLATE_TYPE)0));
7684 if (preg->translate == NULL)
7685 return (int) REG_ESPACE;
7687 /* Map uppercase characters to corresponding lowercase ones. */
7688 for (i = 0; i < CHAR_SET_SIZE; i++)
7689 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7691 else
7692 preg->translate = NULL;
7694 /* If REG_NEWLINE is set, newlines are treated differently. */
7695 if (cflags & REG_NEWLINE)
7696 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7697 syntax &= ~RE_DOT_NEWLINE;
7698 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7699 /* It also changes the matching behavior. */
7700 preg->newline_anchor = 1;
7702 else
7703 preg->newline_anchor = 0;
7705 preg->no_sub = !!(cflags & REG_NOSUB);
7707 /* POSIX says a null character in the pattern terminates it, so we
7708 can use strlen here in compiling the pattern. */
7709 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
7711 /* POSIX doesn't distinguish between an unmatched open-group and an
7712 unmatched close-group: both are REG_EPAREN. */
7713 if (ret == REG_ERPAREN) ret = REG_EPAREN;
7715 if (ret == REG_NOERROR && preg->fastmap)
7717 /* Compute the fastmap now, since regexec cannot modify the pattern
7718 buffer. */
7719 if (re_compile_fastmap (preg) == -2)
7721 /* Some error occurred while computing the fastmap, just forget
7722 about it. */
7723 free (preg->fastmap);
7724 preg->fastmap = NULL;
7728 return (int) ret;
7730 #ifdef _LIBC
7731 weak_alias (__regcomp, regcomp)
7732 #endif
7735 /* regexec searches for a given pattern, specified by PREG, in the
7736 string STRING.
7738 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7739 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
7740 least NMATCH elements, and we set them to the offsets of the
7741 corresponding matched substrings.
7743 EFLAGS specifies `execution flags' which affect matching: if
7744 REG_NOTBOL is set, then ^ does not match at the beginning of the
7745 string; if REG_NOTEOL is set, then $ does not match at the end.
7747 We return 0 if we find a match and REG_NOMATCH if not. */
7750 regexec (preg, string, nmatch, pmatch, eflags)
7751 const regex_t *preg;
7752 const char *string;
7753 size_t nmatch;
7754 regmatch_t pmatch[];
7755 int eflags;
7757 int ret;
7758 struct re_registers regs;
7759 regex_t private_preg;
7760 int len = strlen (string);
7761 boolean want_reg_info = !preg->no_sub && nmatch > 0;
7763 private_preg = *preg;
7765 private_preg.not_bol = !!(eflags & REG_NOTBOL);
7766 private_preg.not_eol = !!(eflags & REG_NOTEOL);
7768 /* The user has told us exactly how many registers to return
7769 information about, via `nmatch'. We have to pass that on to the
7770 matching routines. */
7771 private_preg.regs_allocated = REGS_FIXED;
7773 if (want_reg_info)
7775 regs.num_regs = nmatch;
7776 regs.start = TALLOC (nmatch * 2, regoff_t);
7777 if (regs.start == NULL)
7778 return (int) REG_NOMATCH;
7779 regs.end = regs.start + nmatch;
7782 /* Perform the searching operation. */
7783 ret = re_search (&private_preg, string, len,
7784 /* start: */ 0, /* range: */ len,
7785 want_reg_info ? &regs : (struct re_registers *) 0);
7787 /* Copy the register information to the POSIX structure. */
7788 if (want_reg_info)
7790 if (ret >= 0)
7792 unsigned r;
7794 for (r = 0; r < nmatch; r++)
7796 pmatch[r].rm_so = regs.start[r];
7797 pmatch[r].rm_eo = regs.end[r];
7801 /* If we needed the temporary register info, free the space now. */
7802 free (regs.start);
7805 /* We want zero return to mean success, unlike `re_search'. */
7806 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
7808 #ifdef _LIBC
7809 weak_alias (__regexec, regexec)
7810 #endif
7813 /* Returns a message corresponding to an error code, ERRCODE, returned
7814 from either regcomp or regexec. We don't use PREG here. */
7816 size_t
7817 regerror (errcode, preg, errbuf, errbuf_size)
7818 int errcode;
7819 const regex_t *preg;
7820 char *errbuf;
7821 size_t errbuf_size;
7823 const char *msg;
7824 size_t msg_size;
7826 if (errcode < 0
7827 || errcode >= (int) (sizeof (re_error_msgid_idx)
7828 / sizeof (re_error_msgid_idx[0])))
7829 /* Only error codes returned by the rest of the code should be passed
7830 to this routine. If we are given anything else, or if other regex
7831 code generates an invalid error code, then the program has a bug.
7832 Dump core so we can fix it. */
7833 abort ();
7835 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
7837 msg_size = strlen (msg) + 1; /* Includes the null. */
7839 if (errbuf_size != 0)
7841 if (msg_size > errbuf_size)
7843 #if defined HAVE_MEMPCPY || defined _LIBC
7844 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
7845 #else
7846 memcpy (errbuf, msg, errbuf_size - 1);
7847 errbuf[errbuf_size - 1] = 0;
7848 #endif
7850 else
7851 memcpy (errbuf, msg, msg_size);
7854 return msg_size;
7856 #ifdef _LIBC
7857 weak_alias (__regerror, regerror)
7858 #endif
7861 /* Free dynamically allocated space used by PREG. */
7863 void
7864 regfree (preg)
7865 regex_t *preg;
7867 if (preg->buffer != NULL)
7868 free (preg->buffer);
7869 preg->buffer = NULL;
7871 preg->allocated = 0;
7872 preg->used = 0;
7874 if (preg->fastmap != NULL)
7875 free (preg->fastmap);
7876 preg->fastmap = NULL;
7877 preg->fastmap_accurate = 0;
7879 if (preg->translate != NULL)
7880 free (preg->translate);
7881 preg->translate = NULL;
7883 #ifdef _LIBC
7884 weak_alias (__regfree, regfree)
7885 #endif
7887 #endif /* not emacs */