Update.
[glibc.git] / posix / regex.c
blobfc25bb0c14ca9b83f5bd528718fe89adeba93097
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 (MC_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 #undef ISASCII
230 #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
231 # define ISASCII(c) 1
232 #else
233 # define ISASCII(c) isascii(c)
234 #endif
236 #ifdef isblank
237 # define ISBLANK(c) (ISASCII (c) && isblank (c))
238 #else
239 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
240 #endif
241 #ifdef isgraph
242 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
243 #else
244 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
245 #endif
247 #undef ISPRINT
248 #define ISPRINT(c) (ISASCII (c) && isprint (c))
249 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
250 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
251 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
252 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
253 #define ISLOWER(c) (ISASCII (c) && islower (c))
254 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
255 #define ISSPACE(c) (ISASCII (c) && isspace (c))
256 #define ISUPPER(c) (ISASCII (c) && isupper (c))
257 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
259 #ifdef _tolower
260 # define TOLOWER(c) _tolower(c)
261 #else
262 # define TOLOWER(c) tolower(c)
263 #endif
265 #ifndef NULL
266 # define NULL (void *)0
267 #endif
269 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
270 since ours (we hope) works properly with all combinations of
271 machines, compilers, `char' and `unsigned char' argument types.
272 (Per Bothner suggested the basic approach.) */
273 #undef SIGN_EXTEND_CHAR
274 #if __STDC__
275 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
276 #else /* not __STDC__ */
277 /* As in Harbison and Steele. */
278 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
279 #endif
281 #ifndef emacs
282 /* How many characters in the character set. */
283 # define CHAR_SET_SIZE 256
285 # ifdef SYNTAX_TABLE
287 extern char *re_syntax_table;
289 # else /* not SYNTAX_TABLE */
291 static char re_syntax_table[CHAR_SET_SIZE];
293 static void init_syntax_once PARAMS ((void));
295 static void
296 init_syntax_once ()
298 register int c;
299 static int done = 0;
301 if (done)
302 return;
303 bzero (re_syntax_table, sizeof re_syntax_table);
305 for (c = 0; c < CHAR_SET_SIZE; ++c)
306 if (ISALNUM (c))
307 re_syntax_table[c] = Sword;
309 re_syntax_table['_'] = Sword;
311 done = 1;
314 # endif /* not SYNTAX_TABLE */
316 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
318 #endif /* emacs */
320 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
321 use `alloca' instead of `malloc'. This is because using malloc in
322 re_search* or re_match* could cause memory leaks when C-g is used in
323 Emacs; also, malloc is slower and causes storage fragmentation. On
324 the other hand, malloc is more portable, and easier to debug.
326 Because we sometimes use alloca, some routines have to be macros,
327 not functions -- `alloca'-allocated space disappears at the end of the
328 function it is called in. */
330 #ifdef REGEX_MALLOC
332 # define REGEX_ALLOCATE malloc
333 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
334 # define REGEX_FREE free
336 #else /* not REGEX_MALLOC */
338 /* Emacs already defines alloca, sometimes. */
339 # ifndef alloca
341 /* Make alloca work the best possible way. */
342 # ifdef __GNUC__
343 # define alloca __builtin_alloca
344 # else /* not __GNUC__ */
345 # if HAVE_ALLOCA_H
346 # include <alloca.h>
347 # endif /* HAVE_ALLOCA_H */
348 # endif /* not __GNUC__ */
350 # endif /* not alloca */
352 # define REGEX_ALLOCATE alloca
354 /* Assumes a `char *destination' variable. */
355 # define REGEX_REALLOCATE(source, osize, nsize) \
356 (destination = (char *) alloca (nsize), \
357 memcpy (destination, source, osize))
359 /* No need to do anything to free, after alloca. */
360 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
362 #endif /* not REGEX_MALLOC */
364 /* Define how to allocate the failure stack. */
366 #if defined REL_ALLOC && defined REGEX_MALLOC
368 # define REGEX_ALLOCATE_STACK(size) \
369 r_alloc (&failure_stack_ptr, (size))
370 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
371 r_re_alloc (&failure_stack_ptr, (nsize))
372 # define REGEX_FREE_STACK(ptr) \
373 r_alloc_free (&failure_stack_ptr)
375 #else /* not using relocating allocator */
377 # ifdef REGEX_MALLOC
379 # define REGEX_ALLOCATE_STACK malloc
380 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
381 # define REGEX_FREE_STACK free
383 # else /* not REGEX_MALLOC */
385 # define REGEX_ALLOCATE_STACK alloca
387 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
388 REGEX_REALLOCATE (source, osize, nsize)
389 /* No need to explicitly free anything. */
390 # define REGEX_FREE_STACK(arg)
392 # endif /* not REGEX_MALLOC */
393 #endif /* not using relocating allocator */
396 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
397 `string1' or just past its end. This works if PTR is NULL, which is
398 a good thing. */
399 #define FIRST_STRING_P(ptr) \
400 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
402 /* (Re)Allocate N items of type T using malloc, or fail. */
403 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
404 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
405 #define RETALLOC_IF(addr, n, t) \
406 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
407 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
409 #define BYTEWIDTH 8 /* In bits. */
411 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
413 #undef MAX
414 #undef MIN
415 #define MAX(a, b) ((a) > (b) ? (a) : (b))
416 #define MIN(a, b) ((a) < (b) ? (a) : (b))
418 typedef char boolean;
419 #define false 0
420 #define true 1
422 static int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
423 const char *string1, int size1,
424 const char *string2, int size2,
425 int pos,
426 struct re_registers *regs,
427 int stop));
429 /* These are the command codes that appear in compiled regular
430 expressions. Some opcodes are followed by argument bytes. A
431 command code can specify any interpretation whatsoever for its
432 arguments. Zero bytes may appear in the compiled regular expression. */
434 typedef enum
436 no_op = 0,
438 /* Succeed right away--no more backtracking. */
439 succeed,
441 /* Followed by one byte giving n, then by n literal bytes. */
442 exactn,
444 #ifdef MBS_SUPPORT
445 /* Same as exactn, but contains binary data. */
446 exactn_bin,
447 #endif
449 /* Matches any (more or less) character. */
450 anychar,
452 /* Matches any one char belonging to specified set. First
453 following byte is number of bitmap bytes. Then come bytes
454 for a bitmap saying which chars are in. Bits in each byte
455 are ordered low-bit-first. A character is in the set if its
456 bit is 1. A character too large to have a bit in the map is
457 automatically not in the set. */
458 /* ifdef MBS_SUPPORT, following element is length of character
459 classes, length of collating symbols, length of equivalence
460 classes, length of character ranges, and length of characters.
461 Next, character class element, collating symbols elements,
462 equivalence class elements, range elements, and character
463 elements follow.
464 See regex_compile function. */
465 charset,
467 /* Same parameters as charset, but match any character that is
468 not one of those specified. */
469 charset_not,
471 /* Start remembering the text that is matched, for storing in a
472 register. Followed by one byte with the register number, in
473 the range 0 to one less than the pattern buffer's re_nsub
474 field. Then followed by one byte with the number of groups
475 inner to this one. (This last has to be part of the
476 start_memory only because we need it in the on_failure_jump
477 of re_match_2.) */
478 start_memory,
480 /* Stop remembering the text that is matched and store it in a
481 memory register. Followed by one byte with the register
482 number, in the range 0 to one less than `re_nsub' in the
483 pattern buffer, and one byte with the number of inner groups,
484 just like `start_memory'. (We need the number of inner
485 groups here because we don't have any easy way of finding the
486 corresponding start_memory when we're at a stop_memory.) */
487 stop_memory,
489 /* Match a duplicate of something remembered. Followed by one
490 byte containing the register number. */
491 duplicate,
493 /* Fail unless at beginning of line. */
494 begline,
496 /* Fail unless at end of line. */
497 endline,
499 /* Succeeds if at beginning of buffer (if emacs) or at beginning
500 of string to be matched (if not). */
501 begbuf,
503 /* Analogously, for end of buffer/string. */
504 endbuf,
506 /* Followed by two byte relative address to which to jump. */
507 jump,
509 /* Same as jump, but marks the end of an alternative. */
510 jump_past_alt,
512 /* Followed by two-byte relative address of place to resume at
513 in case of failure. */
514 /* ifdef MBS_SUPPORT, the size of address is 1. */
515 on_failure_jump,
517 /* Like on_failure_jump, but pushes a placeholder instead of the
518 current string position when executed. */
519 on_failure_keep_string_jump,
521 /* Throw away latest failure point and then jump to following
522 two-byte relative address. */
523 /* ifdef MBS_SUPPORT, the size of address is 1. */
524 pop_failure_jump,
526 /* Change to pop_failure_jump if know won't have to backtrack to
527 match; otherwise change to jump. This is used to jump
528 back to the beginning of a repeat. If what follows this jump
529 clearly won't match what the repeat does, such that we can be
530 sure that there is no use backtracking out of repetitions
531 already matched, then we change it to a pop_failure_jump.
532 Followed by two-byte address. */
533 /* ifdef MBS_SUPPORT, the size of address is 1. */
534 maybe_pop_jump,
536 /* Jump to following two-byte address, and push a dummy failure
537 point. This failure point will be thrown away if an attempt
538 is made to use it for a failure. A `+' construct makes this
539 before the first repeat. Also used as an intermediary kind
540 of jump when compiling an alternative. */
541 /* ifdef MBS_SUPPORT, the size of address is 1. */
542 dummy_failure_jump,
544 /* Push a dummy failure point and continue. Used at the end of
545 alternatives. */
546 push_dummy_failure,
548 /* Followed by two-byte relative address and two-byte number n.
549 After matching N times, jump to the address upon failure. */
550 /* ifdef MBS_SUPPORT, the size of address is 1. */
551 succeed_n,
553 /* Followed by two-byte relative address, and two-byte number n.
554 Jump to the address N times, then fail. */
555 /* ifdef MBS_SUPPORT, the size of address is 1. */
556 jump_n,
558 /* Set the following two-byte relative address to the
559 subsequent two-byte number. The address *includes* the two
560 bytes of number. */
561 /* ifdef MBS_SUPPORT, the size of address is 1. */
562 set_number_at,
564 wordchar, /* Matches any word-constituent character. */
565 notwordchar, /* Matches any char that is not a word-constituent. */
567 wordbeg, /* Succeeds if at word beginning. */
568 wordend, /* Succeeds if at word end. */
570 wordbound, /* Succeeds if at a word boundary. */
571 notwordbound /* Succeeds if not at a word boundary. */
573 #ifdef emacs
574 ,before_dot, /* Succeeds if before point. */
575 at_dot, /* Succeeds if at point. */
576 after_dot, /* Succeeds if after point. */
578 /* Matches any character whose syntax is specified. Followed by
579 a byte which contains a syntax code, e.g., Sword. */
580 syntaxspec,
582 /* Matches any character whose syntax is not that specified. */
583 notsyntaxspec
584 #endif /* emacs */
585 } re_opcode_t;
587 /* Common operations on the compiled pattern. */
589 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
590 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
592 #ifdef MBS_SUPPORT
593 # define STORE_NUMBER(destination, number) \
594 do { \
595 *(destination) = (US_CHAR_TYPE)(number); \
596 } while (0)
597 #else
598 # define STORE_NUMBER(destination, number) \
599 do { \
600 (destination)[0] = (number) & 0377; \
601 (destination)[1] = (number) >> 8; \
602 } while (0)
603 #endif /* MBS_SUPPORT */
605 /* Same as STORE_NUMBER, except increment DESTINATION to
606 the byte after where the number is stored. Therefore, DESTINATION
607 must be an lvalue. */
608 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
610 #define STORE_NUMBER_AND_INCR(destination, number) \
611 do { \
612 STORE_NUMBER (destination, number); \
613 (destination) += OFFSET_ADDRESS_SIZE; \
614 } while (0)
616 /* Put into DESTINATION a number stored in two contiguous bytes starting
617 at SOURCE. */
618 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
620 #ifdef MBS_SUPPORT
621 # define EXTRACT_NUMBER(destination, source) \
622 do { \
623 (destination) = *(source); \
624 } while (0)
625 #else
626 # define EXTRACT_NUMBER(destination, source) \
627 do { \
628 (destination) = *(source) & 0377; \
629 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
630 } while (0)
631 #endif
633 #ifdef DEBUG
634 static void extract_number _RE_ARGS ((int *dest, US_CHAR_TYPE *source));
635 static void
636 extract_number (dest, source)
637 int *dest;
638 US_CHAR_TYPE *source;
640 #ifdef MBS_SUPPORT
641 *dest = *source;
642 #else
643 int temp = SIGN_EXTEND_CHAR (*(source + 1));
644 *dest = *source & 0377;
645 *dest += temp << 8;
646 #endif
649 # ifndef EXTRACT_MACROS /* To debug the macros. */
650 # undef EXTRACT_NUMBER
651 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
652 # endif /* not EXTRACT_MACROS */
654 #endif /* DEBUG */
656 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
657 SOURCE must be an lvalue. */
659 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
660 do { \
661 EXTRACT_NUMBER (destination, source); \
662 (source) += OFFSET_ADDRESS_SIZE; \
663 } while (0)
665 #ifdef DEBUG
666 static void extract_number_and_incr _RE_ARGS ((int *destination,
667 US_CHAR_TYPE **source));
668 static void
669 extract_number_and_incr (destination, source)
670 int *destination;
671 US_CHAR_TYPE **source;
673 extract_number (destination, *source);
674 *source += OFFSET_ADDRESS_SIZE;
677 # ifndef EXTRACT_MACROS
678 # undef EXTRACT_NUMBER_AND_INCR
679 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
680 extract_number_and_incr (&dest, &src)
681 # endif /* not EXTRACT_MACROS */
683 #endif /* DEBUG */
685 /* If DEBUG is defined, Regex prints many voluminous messages about what
686 it is doing (if the variable `debug' is nonzero). If linked with the
687 main program in `iregex.c', you can enter patterns and strings
688 interactively. And if linked with the main program in `main.c' and
689 the other test files, you can run the already-written tests. */
691 #ifdef DEBUG
693 /* We use standard I/O for debugging. */
694 # include <stdio.h>
696 /* It is useful to test things that ``must'' be true when debugging. */
697 # include <assert.h>
699 static int debug;
701 # define DEBUG_STATEMENT(e) e
702 # define DEBUG_PRINT1(x) if (debug) printf (x)
703 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
704 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
705 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
706 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
707 if (debug) print_partial_compiled_pattern (s, e)
708 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
709 if (debug) print_double_string (w, s1, sz1, s2, sz2)
712 /* Print the fastmap in human-readable form. */
714 void
715 print_fastmap (fastmap)
716 char *fastmap;
718 unsigned was_a_range = 0;
719 unsigned i = 0;
721 while (i < (1 << BYTEWIDTH))
723 if (fastmap[i++])
725 was_a_range = 0;
726 putchar (i - 1);
727 while (i < (1 << BYTEWIDTH) && fastmap[i])
729 was_a_range = 1;
730 i++;
732 if (was_a_range)
734 printf ("-");
735 putchar (i - 1);
739 putchar ('\n');
743 /* Print a compiled pattern string in human-readable form, starting at
744 the START pointer into it and ending just before the pointer END. */
746 void
747 print_partial_compiled_pattern (start, end)
748 US_CHAR_TYPE *start;
749 US_CHAR_TYPE *end;
751 int mcnt, mcnt2;
752 US_CHAR_TYPE *p1;
753 US_CHAR_TYPE *p = start;
754 US_CHAR_TYPE *pend = end;
756 if (start == NULL)
758 printf ("(null)\n");
759 return;
762 /* Loop over pattern commands. */
763 while (p < pend)
765 #ifdef _LIBC
766 printf ("%td:\t", p - start);
767 #else
768 printf ("%ld:\t", (long int) (p - start));
769 #endif
771 switch ((re_opcode_t) *p++)
773 case no_op:
774 printf ("/no_op");
775 break;
777 case exactn:
778 mcnt = *p++;
779 printf ("/exactn/%d", mcnt);
782 putchar ('/');
783 PUT_CHAR (*p++);
785 while (--mcnt);
786 break;
788 #ifdef MBS_SUPPORT
789 case exactn_bin:
790 mcnt = *p++;
791 printf ("/exactn_bin/%d", mcnt);
794 printf("/%lx", (long int) *p++);
796 while (--mcnt);
797 break;
798 #endif /* MBS_SUPPORT */
800 case start_memory:
801 mcnt = *p++;
802 printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
803 break;
805 case stop_memory:
806 mcnt = *p++;
807 printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
808 break;
810 case duplicate:
811 printf ("/duplicate/%ld", (long int) *p++);
812 break;
814 case anychar:
815 printf ("/anychar");
816 break;
818 case charset:
819 case charset_not:
821 #ifdef MBS_SUPPORT
822 int i, length;
823 wchar_t *workp = p;
824 printf ("/charset [%s",
825 (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
826 p += 5;
827 length = *workp++; /* the length of char_classes */
828 for (i=0 ; i<length ; i++)
829 printf("[:%lx:]", (long int) *p++);
830 length = *workp++; /* the length of collating_symbol */
831 for (i=0 ; i<length ;)
833 printf("[.");
834 while(*p != 0)
835 PUT_CHAR((i++,*p++));
836 i++,p++;
837 printf(".]");
839 length = *workp++; /* the length of equivalence_class */
840 for (i=0 ; i<length ;)
842 printf("[=");
843 while(*p != 0)
844 PUT_CHAR((i++,*p++));
845 i++,p++;
846 printf("=]");
848 length = *workp++; /* the length of char_range */
849 for (i=0 ; i<length ; i++)
851 wchar_t range_start = *p++;
852 wchar_t range_end = *p++;
853 if (MB_CUR_MAX == 1)
854 printf("%c-%c", (char) range_start, (char) range_end);
855 else
856 printf("%C-%C", (wint_t) range_start, (wint_t) range_end);
858 length = *workp++; /* the length of char */
859 for (i=0 ; i<length ; i++)
860 if (MB_CUR_MAX == 1)
861 putchar (*p++);
862 else
863 printf("%C", (wint_t) *p++);
864 putchar (']');
865 #else
866 register int c, last = -100;
867 register int in_range = 0;
869 printf ("/charset [%s",
870 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
872 assert (p + *p < pend);
874 for (c = 0; c < 256; c++)
875 if (c / 8 < *p
876 && (p[1 + (c/8)] & (1 << (c % 8))))
878 /* Are we starting a range? */
879 if (last + 1 == c && ! in_range)
881 putchar ('-');
882 in_range = 1;
884 /* Have we broken a range? */
885 else if (last + 1 != c && in_range)
887 putchar (last);
888 in_range = 0;
891 if (! in_range)
892 putchar (c);
894 last = c;
897 if (in_range)
898 putchar (last);
900 putchar (']');
902 p += 1 + *p;
903 #endif /* MBS_SUPPORT */
905 break;
907 case begline:
908 printf ("/begline");
909 break;
911 case endline:
912 printf ("/endline");
913 break;
915 case on_failure_jump:
916 extract_number_and_incr (&mcnt, &p);
917 #ifdef _LIBC
918 printf ("/on_failure_jump to %td", p + mcnt - start);
919 #else
920 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
921 #endif
922 break;
924 case on_failure_keep_string_jump:
925 extract_number_and_incr (&mcnt, &p);
926 #ifdef _LIBC
927 printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
928 #else
929 printf ("/on_failure_keep_string_jump to %ld",
930 (long int) (p + mcnt - start));
931 #endif
932 break;
934 case dummy_failure_jump:
935 extract_number_and_incr (&mcnt, &p);
936 #ifdef _LIBC
937 printf ("/dummy_failure_jump to %td", p + mcnt - start);
938 #else
939 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
940 #endif
941 break;
943 case push_dummy_failure:
944 printf ("/push_dummy_failure");
945 break;
947 case maybe_pop_jump:
948 extract_number_and_incr (&mcnt, &p);
949 #ifdef _LIBC
950 printf ("/maybe_pop_jump to %td", p + mcnt - start);
951 #else
952 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
953 #endif
954 break;
956 case pop_failure_jump:
957 extract_number_and_incr (&mcnt, &p);
958 #ifdef _LIBC
959 printf ("/pop_failure_jump to %td", p + mcnt - start);
960 #else
961 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
962 #endif
963 break;
965 case jump_past_alt:
966 extract_number_and_incr (&mcnt, &p);
967 #ifdef _LIBC
968 printf ("/jump_past_alt to %td", p + mcnt - start);
969 #else
970 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
971 #endif
972 break;
974 case jump:
975 extract_number_and_incr (&mcnt, &p);
976 #ifdef _LIBC
977 printf ("/jump to %td", p + mcnt - start);
978 #else
979 printf ("/jump to %ld", (long int) (p + mcnt - start));
980 #endif
981 break;
983 case succeed_n:
984 extract_number_and_incr (&mcnt, &p);
985 p1 = p + mcnt;
986 extract_number_and_incr (&mcnt2, &p);
987 #ifdef _LIBC
988 printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
989 #else
990 printf ("/succeed_n to %ld, %d times",
991 (long int) (p1 - start), mcnt2);
992 #endif
993 break;
995 case jump_n:
996 extract_number_and_incr (&mcnt, &p);
997 p1 = p + mcnt;
998 extract_number_and_incr (&mcnt2, &p);
999 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
1000 break;
1002 case set_number_at:
1003 extract_number_and_incr (&mcnt, &p);
1004 p1 = p + mcnt;
1005 extract_number_and_incr (&mcnt2, &p);
1006 #ifdef _LIBC
1007 printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1008 #else
1009 printf ("/set_number_at location %ld to %d",
1010 (long int) (p1 - start), mcnt2);
1011 #endif
1012 break;
1014 case wordbound:
1015 printf ("/wordbound");
1016 break;
1018 case notwordbound:
1019 printf ("/notwordbound");
1020 break;
1022 case wordbeg:
1023 printf ("/wordbeg");
1024 break;
1026 case wordend:
1027 printf ("/wordend");
1028 break;
1030 # ifdef emacs
1031 case before_dot:
1032 printf ("/before_dot");
1033 break;
1035 case at_dot:
1036 printf ("/at_dot");
1037 break;
1039 case after_dot:
1040 printf ("/after_dot");
1041 break;
1043 case syntaxspec:
1044 printf ("/syntaxspec");
1045 mcnt = *p++;
1046 printf ("/%d", mcnt);
1047 break;
1049 case notsyntaxspec:
1050 printf ("/notsyntaxspec");
1051 mcnt = *p++;
1052 printf ("/%d", mcnt);
1053 break;
1054 # endif /* emacs */
1056 case wordchar:
1057 printf ("/wordchar");
1058 break;
1060 case notwordchar:
1061 printf ("/notwordchar");
1062 break;
1064 case begbuf:
1065 printf ("/begbuf");
1066 break;
1068 case endbuf:
1069 printf ("/endbuf");
1070 break;
1072 default:
1073 printf ("?%ld", (long int) *(p-1));
1076 putchar ('\n');
1079 #ifdef _LIBC
1080 printf ("%td:\tend of pattern.\n", p - start);
1081 #else
1082 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1083 #endif
1087 void
1088 print_compiled_pattern (bufp)
1089 struct re_pattern_buffer *bufp;
1091 US_CHAR_TYPE *buffer = (US_CHAR_TYPE*) bufp->buffer;
1093 print_partial_compiled_pattern (buffer, buffer
1094 + bufp->used / sizeof(US_CHAR_TYPE));
1095 printf ("%ld bytes used/%ld bytes allocated.\n",
1096 bufp->used, bufp->allocated);
1098 if (bufp->fastmap_accurate && bufp->fastmap)
1100 printf ("fastmap: ");
1101 print_fastmap (bufp->fastmap);
1104 #ifdef _LIBC
1105 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1106 #else
1107 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1108 #endif
1109 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1110 printf ("can_be_null: %d\t", bufp->can_be_null);
1111 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1112 printf ("no_sub: %d\t", bufp->no_sub);
1113 printf ("not_bol: %d\t", bufp->not_bol);
1114 printf ("not_eol: %d\t", bufp->not_eol);
1115 printf ("syntax: %lx\n", bufp->syntax);
1116 /* Perhaps we should print the translate table? */
1120 void
1121 print_double_string (where, string1, size1, string2, size2)
1122 const CHAR_TYPE *where;
1123 const CHAR_TYPE *string1;
1124 const CHAR_TYPE *string2;
1125 int size1;
1126 int size2;
1128 int this_char;
1130 if (where == NULL)
1131 printf ("(null)");
1132 else
1134 if (FIRST_STRING_P (where))
1136 for (this_char = where - string1; this_char < size1; this_char++)
1137 PUT_CHAR (string1[this_char]);
1139 where = string2;
1142 for (this_char = where - string2; this_char < size2; this_char++)
1143 PUT_CHAR (string2[this_char]);
1147 void
1148 printchar (c)
1149 int c;
1151 putc (c, stderr);
1154 #else /* not DEBUG */
1156 # undef assert
1157 # define assert(e)
1159 # define DEBUG_STATEMENT(e)
1160 # define DEBUG_PRINT1(x)
1161 # define DEBUG_PRINT2(x1, x2)
1162 # define DEBUG_PRINT3(x1, x2, x3)
1163 # define DEBUG_PRINT4(x1, x2, x3, x4)
1164 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1165 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1167 #endif /* not DEBUG */
1169 #ifdef MBS_SUPPORT
1170 /* This convert a multibyte string to a wide character string.
1171 And write their correspondances to offset_buffer(see below)
1172 and write whether each wchar_t is binary data to is_binary.
1173 This assume invalid multibyte sequences as binary data.
1174 We assume offset_buffer and is_binary is already allocated
1175 enough space. */
1177 static size_t convert_mbs_to_wcs (CHAR_TYPE *dest, const unsigned char* src,
1178 size_t len, int *offset_buffer,
1179 char *is_binary);
1180 static size_t
1181 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1182 CHAR_TYPE *dest;
1183 const unsigned char* src;
1184 size_t len; /* the length of multibyte string. */
1186 /* It hold correspondances between src(char string) and
1187 dest(wchar_t string) for optimization.
1188 e.g. src = "xxxyzz"
1189 dest = {'X', 'Y', 'Z'}
1190 (each "xxx", "y" and "zz" represent one multibyte character
1191 corresponding to 'X', 'Y' and 'Z'.)
1192 offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1193 = {0, 3, 4, 6}
1195 int *offset_buffer;
1196 char *is_binary;
1198 wchar_t *pdest = dest;
1199 const unsigned char *psrc = src;
1200 size_t wc_count = 0;
1202 if (MB_CUR_MAX == 1)
1203 { /* We don't need conversion. */
1204 for ( ; wc_count < len ; ++wc_count)
1206 *pdest++ = *psrc++;
1207 is_binary[wc_count] = FALSE;
1208 offset_buffer[wc_count] = wc_count;
1210 offset_buffer[wc_count] = wc_count;
1212 else
1214 /* We need conversion. */
1215 mbstate_t mbs;
1216 int consumed;
1217 size_t mb_remain = len;
1218 size_t mb_count = 0;
1220 /* Initialize the conversion state. */
1221 memset (&mbs, 0, sizeof (mbstate_t));
1223 offset_buffer[0] = 0;
1224 for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1225 psrc += consumed)
1227 consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1229 if (consumed <= 0)
1230 /* failed to convert. maybe src contains binary data.
1231 So we consume 1 byte manualy. */
1233 *pdest = *psrc;
1234 consumed = 1;
1235 is_binary[wc_count] = TRUE;
1237 else
1238 is_binary[wc_count] = FALSE;
1239 /* In sjis encoding, we use yen sign as escape character in
1240 place of reverse solidus. So we convert 0x5c(yen sign in
1241 sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1242 solidus in UCS2). */
1243 if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1244 *pdest = (wchar_t) *psrc;
1246 offset_buffer[wc_count + 1] = mb_count += consumed;
1250 return wc_count;
1253 #endif /* MBS_SUPPORT */
1255 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1256 also be assigned to arbitrarily: each pattern buffer stores its own
1257 syntax, so it can be changed between regex compilations. */
1258 /* This has no initializer because initialized variables in Emacs
1259 become read-only after dumping. */
1260 reg_syntax_t re_syntax_options;
1263 /* Specify the precise syntax of regexps for compilation. This provides
1264 for compatibility for various utilities which historically have
1265 different, incompatible syntaxes.
1267 The argument SYNTAX is a bit mask comprised of the various bits
1268 defined in regex.h. We return the old syntax. */
1270 reg_syntax_t
1271 re_set_syntax (syntax)
1272 reg_syntax_t syntax;
1274 reg_syntax_t ret = re_syntax_options;
1276 re_syntax_options = syntax;
1277 #ifdef DEBUG
1278 if (syntax & RE_DEBUG)
1279 debug = 1;
1280 else if (debug) /* was on but now is not */
1281 debug = 0;
1282 #endif /* DEBUG */
1283 return ret;
1285 #ifdef _LIBC
1286 weak_alias (__re_set_syntax, re_set_syntax)
1287 #endif
1289 /* This table gives an error message for each of the error codes listed
1290 in regex.h. Obviously the order here has to be same as there.
1291 POSIX doesn't require that we do anything for REG_NOERROR,
1292 but why not be nice? */
1294 static const char re_error_msgid[] =
1296 #define REG_NOERROR_IDX 0
1297 gettext_noop ("Success") /* REG_NOERROR */
1298 "\0"
1299 #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1300 gettext_noop ("No match") /* REG_NOMATCH */
1301 "\0"
1302 #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1303 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1304 "\0"
1305 #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1306 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1307 "\0"
1308 #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1309 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1310 "\0"
1311 #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1312 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1313 "\0"
1314 #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1315 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1316 "\0"
1317 #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1318 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1319 "\0"
1320 #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1321 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1322 "\0"
1323 #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1324 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1325 "\0"
1326 #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1327 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1328 "\0"
1329 #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1330 gettext_noop ("Invalid range end") /* REG_ERANGE */
1331 "\0"
1332 #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1333 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1334 "\0"
1335 #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1336 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1337 "\0"
1338 #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1339 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1340 "\0"
1341 #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1342 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1343 "\0"
1344 #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1345 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1348 static const size_t re_error_msgid_idx[] =
1350 REG_NOERROR_IDX,
1351 REG_NOMATCH_IDX,
1352 REG_BADPAT_IDX,
1353 REG_ECOLLATE_IDX,
1354 REG_ECTYPE_IDX,
1355 REG_EESCAPE_IDX,
1356 REG_ESUBREG_IDX,
1357 REG_EBRACK_IDX,
1358 REG_EPAREN_IDX,
1359 REG_EBRACE_IDX,
1360 REG_BADBR_IDX,
1361 REG_ERANGE_IDX,
1362 REG_ESPACE_IDX,
1363 REG_BADRPT_IDX,
1364 REG_EEND_IDX,
1365 REG_ESIZE_IDX,
1366 REG_ERPAREN_IDX
1369 /* Avoiding alloca during matching, to placate r_alloc. */
1371 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1372 searching and matching functions should not call alloca. On some
1373 systems, alloca is implemented in terms of malloc, and if we're
1374 using the relocating allocator routines, then malloc could cause a
1375 relocation, which might (if the strings being searched are in the
1376 ralloc heap) shift the data out from underneath the regexp
1377 routines.
1379 Here's another reason to avoid allocation: Emacs
1380 processes input from X in a signal handler; processing X input may
1381 call malloc; if input arrives while a matching routine is calling
1382 malloc, then we're scrod. But Emacs can't just block input while
1383 calling matching routines; then we don't notice interrupts when
1384 they come in. So, Emacs blocks input around all regexp calls
1385 except the matching calls, which it leaves unprotected, in the
1386 faith that they will not malloc. */
1388 /* Normally, this is fine. */
1389 #define MATCH_MAY_ALLOCATE
1391 /* When using GNU C, we are not REALLY using the C alloca, no matter
1392 what config.h may say. So don't take precautions for it. */
1393 #ifdef __GNUC__
1394 # undef C_ALLOCA
1395 #endif
1397 /* The match routines may not allocate if (1) they would do it with malloc
1398 and (2) it's not safe for them to use malloc.
1399 Note that if REL_ALLOC is defined, matching would not use malloc for the
1400 failure stack, but we would still use it for the register vectors;
1401 so REL_ALLOC should not affect this. */
1402 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1403 # undef MATCH_MAY_ALLOCATE
1404 #endif
1407 /* Failure stack declarations and macros; both re_compile_fastmap and
1408 re_match_2 use a failure stack. These have to be macros because of
1409 REGEX_ALLOCATE_STACK. */
1412 /* Number of failure points for which to initially allocate space
1413 when matching. If this number is exceeded, we allocate more
1414 space, so it is not a hard limit. */
1415 #ifndef INIT_FAILURE_ALLOC
1416 # define INIT_FAILURE_ALLOC 5
1417 #endif
1419 /* Roughly the maximum number of failure points on the stack. Would be
1420 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1421 This is a variable only so users of regex can assign to it; we never
1422 change it ourselves. */
1424 #ifdef INT_IS_16BIT
1426 # if defined MATCH_MAY_ALLOCATE
1427 /* 4400 was enough to cause a crash on Alpha OSF/1,
1428 whose default stack limit is 2mb. */
1429 long int re_max_failures = 4000;
1430 # else
1431 long int re_max_failures = 2000;
1432 # endif
1434 union fail_stack_elt
1436 US_CHAR_TYPE *pointer;
1437 long int integer;
1440 typedef union fail_stack_elt fail_stack_elt_t;
1442 typedef struct
1444 fail_stack_elt_t *stack;
1445 unsigned long int size;
1446 unsigned long int avail; /* Offset of next open position. */
1447 } fail_stack_type;
1449 #else /* not INT_IS_16BIT */
1451 # if defined MATCH_MAY_ALLOCATE
1452 /* 4400 was enough to cause a crash on Alpha OSF/1,
1453 whose default stack limit is 2mb. */
1454 int re_max_failures = 4000;
1455 # else
1456 int re_max_failures = 2000;
1457 # endif
1459 union fail_stack_elt
1461 US_CHAR_TYPE *pointer;
1462 int integer;
1465 typedef union fail_stack_elt fail_stack_elt_t;
1467 typedef struct
1469 fail_stack_elt_t *stack;
1470 unsigned size;
1471 unsigned avail; /* Offset of next open position. */
1472 } fail_stack_type;
1474 #endif /* INT_IS_16BIT */
1476 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1477 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1478 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1481 /* Define macros to initialize and free the failure stack.
1482 Do `return -2' if the alloc fails. */
1484 #ifdef MATCH_MAY_ALLOCATE
1485 # define INIT_FAIL_STACK() \
1486 do { \
1487 fail_stack.stack = (fail_stack_elt_t *) \
1488 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1490 if (fail_stack.stack == NULL) \
1491 return -2; \
1493 fail_stack.size = INIT_FAILURE_ALLOC; \
1494 fail_stack.avail = 0; \
1495 } while (0)
1497 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1498 #else
1499 # define INIT_FAIL_STACK() \
1500 do { \
1501 fail_stack.avail = 0; \
1502 } while (0)
1504 # define RESET_FAIL_STACK()
1505 #endif
1508 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1510 Return 1 if succeeds, and 0 if either ran out of memory
1511 allocating space for it or it was already too large.
1513 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1515 #define DOUBLE_FAIL_STACK(fail_stack) \
1516 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1517 ? 0 \
1518 : ((fail_stack).stack = (fail_stack_elt_t *) \
1519 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1520 (fail_stack).size * sizeof (fail_stack_elt_t), \
1521 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1523 (fail_stack).stack == NULL \
1524 ? 0 \
1525 : ((fail_stack).size <<= 1, \
1526 1)))
1529 /* Push pointer POINTER on FAIL_STACK.
1530 Return 1 if was able to do so and 0 if ran out of memory allocating
1531 space to do so. */
1532 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1533 ((FAIL_STACK_FULL () \
1534 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1535 ? 0 \
1536 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1539 /* Push a pointer value onto the failure stack.
1540 Assumes the variable `fail_stack'. Probably should only
1541 be called from within `PUSH_FAILURE_POINT'. */
1542 #define PUSH_FAILURE_POINTER(item) \
1543 fail_stack.stack[fail_stack.avail++].pointer = (US_CHAR_TYPE *) (item)
1545 /* This pushes an integer-valued item onto the failure stack.
1546 Assumes the variable `fail_stack'. Probably should only
1547 be called from within `PUSH_FAILURE_POINT'. */
1548 #define PUSH_FAILURE_INT(item) \
1549 fail_stack.stack[fail_stack.avail++].integer = (item)
1551 /* Push a fail_stack_elt_t value onto the failure stack.
1552 Assumes the variable `fail_stack'. Probably should only
1553 be called from within `PUSH_FAILURE_POINT'. */
1554 #define PUSH_FAILURE_ELT(item) \
1555 fail_stack.stack[fail_stack.avail++] = (item)
1557 /* These three POP... operations complement the three PUSH... operations.
1558 All assume that `fail_stack' is nonempty. */
1559 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1560 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1561 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1563 /* Used to omit pushing failure point id's when we're not debugging. */
1564 #ifdef DEBUG
1565 # define DEBUG_PUSH PUSH_FAILURE_INT
1566 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1567 #else
1568 # define DEBUG_PUSH(item)
1569 # define DEBUG_POP(item_addr)
1570 #endif
1573 /* Push the information about the state we will need
1574 if we ever fail back to it.
1576 Requires variables fail_stack, regstart, regend, reg_info, and
1577 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1578 be declared.
1580 Does `return FAILURE_CODE' if runs out of memory. */
1582 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1583 do { \
1584 char *destination; \
1585 /* Must be int, so when we don't save any registers, the arithmetic \
1586 of 0 + -1 isn't done as unsigned. */ \
1587 /* Can't be int, since there is not a shred of a guarantee that int \
1588 is wide enough to hold a value of something to which pointer can \
1589 be assigned */ \
1590 active_reg_t this_reg; \
1592 DEBUG_STATEMENT (failure_id++); \
1593 DEBUG_STATEMENT (nfailure_points_pushed++); \
1594 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1595 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1596 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1598 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1599 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1601 /* Ensure we have enough space allocated for what we will push. */ \
1602 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1604 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1605 return failure_code; \
1607 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1608 (fail_stack).size); \
1609 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1612 /* Push the info, starting with the registers. */ \
1613 DEBUG_PRINT1 ("\n"); \
1615 if (1) \
1616 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1617 this_reg++) \
1619 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1620 DEBUG_STATEMENT (num_regs_pushed++); \
1622 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1623 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1625 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1626 PUSH_FAILURE_POINTER (regend[this_reg]); \
1628 DEBUG_PRINT2 (" info: %p\n ", \
1629 reg_info[this_reg].word.pointer); \
1630 DEBUG_PRINT2 (" match_null=%d", \
1631 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1632 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1633 DEBUG_PRINT2 (" matched_something=%d", \
1634 MATCHED_SOMETHING (reg_info[this_reg])); \
1635 DEBUG_PRINT2 (" ever_matched=%d", \
1636 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1637 DEBUG_PRINT1 ("\n"); \
1638 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1641 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1642 PUSH_FAILURE_INT (lowest_active_reg); \
1644 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1645 PUSH_FAILURE_INT (highest_active_reg); \
1647 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1648 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1649 PUSH_FAILURE_POINTER (pattern_place); \
1651 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1652 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1653 size2); \
1654 DEBUG_PRINT1 ("'\n"); \
1655 PUSH_FAILURE_POINTER (string_place); \
1657 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1658 DEBUG_PUSH (failure_id); \
1659 } while (0)
1661 /* This is the number of items that are pushed and popped on the stack
1662 for each register. */
1663 #define NUM_REG_ITEMS 3
1665 /* Individual items aside from the registers. */
1666 #ifdef DEBUG
1667 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1668 #else
1669 # define NUM_NONREG_ITEMS 4
1670 #endif
1672 /* We push at most this many items on the stack. */
1673 /* We used to use (num_regs - 1), which is the number of registers
1674 this regexp will save; but that was changed to 5
1675 to avoid stack overflow for a regexp with lots of parens. */
1676 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1678 /* We actually push this many items. */
1679 #define NUM_FAILURE_ITEMS \
1680 (((0 \
1681 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1682 * NUM_REG_ITEMS) \
1683 + NUM_NONREG_ITEMS)
1685 /* How many items can still be added to the stack without overflowing it. */
1686 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1689 /* Pops what PUSH_FAIL_STACK pushes.
1691 We restore into the parameters, all of which should be lvalues:
1692 STR -- the saved data position.
1693 PAT -- the saved pattern position.
1694 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1695 REGSTART, REGEND -- arrays of string positions.
1696 REG_INFO -- array of information about each subexpression.
1698 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1699 `pend', `string1', `size1', `string2', and `size2'. */
1700 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1702 DEBUG_STATEMENT (unsigned failure_id;) \
1703 active_reg_t this_reg; \
1704 const US_CHAR_TYPE *string_temp; \
1706 assert (!FAIL_STACK_EMPTY ()); \
1708 /* Remove failure points and point to how many regs pushed. */ \
1709 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1710 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1711 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1713 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1715 DEBUG_POP (&failure_id); \
1716 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1718 /* If the saved string location is NULL, it came from an \
1719 on_failure_keep_string_jump opcode, and we want to throw away the \
1720 saved NULL, thus retaining our current position in the string. */ \
1721 string_temp = POP_FAILURE_POINTER (); \
1722 if (string_temp != NULL) \
1723 str = (const CHAR_TYPE *) string_temp; \
1725 DEBUG_PRINT2 (" Popping string %p: `", str); \
1726 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1727 DEBUG_PRINT1 ("'\n"); \
1729 pat = (US_CHAR_TYPE *) POP_FAILURE_POINTER (); \
1730 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1731 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1733 /* Restore register info. */ \
1734 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1735 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1737 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1738 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1740 if (1) \
1741 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1743 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1745 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1746 DEBUG_PRINT2 (" info: %p\n", \
1747 reg_info[this_reg].word.pointer); \
1749 regend[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER (); \
1750 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1752 regstart[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER ();\
1753 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1755 else \
1757 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1759 reg_info[this_reg].word.integer = 0; \
1760 regend[this_reg] = 0; \
1761 regstart[this_reg] = 0; \
1763 highest_active_reg = high_reg; \
1766 set_regs_matched_done = 0; \
1767 DEBUG_STATEMENT (nfailure_points_popped++); \
1768 } /* POP_FAILURE_POINT */
1771 /* Structure for per-register (a.k.a. per-group) information.
1772 Other register information, such as the
1773 starting and ending positions (which are addresses), and the list of
1774 inner groups (which is a bits list) are maintained in separate
1775 variables.
1777 We are making a (strictly speaking) nonportable assumption here: that
1778 the compiler will pack our bit fields into something that fits into
1779 the type of `word', i.e., is something that fits into one item on the
1780 failure stack. */
1783 /* Declarations and macros for re_match_2. */
1785 typedef union
1787 fail_stack_elt_t word;
1788 struct
1790 /* This field is one if this group can match the empty string,
1791 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1792 #define MATCH_NULL_UNSET_VALUE 3
1793 unsigned match_null_string_p : 2;
1794 unsigned is_active : 1;
1795 unsigned matched_something : 1;
1796 unsigned ever_matched_something : 1;
1797 } bits;
1798 } register_info_type;
1800 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1801 #define IS_ACTIVE(R) ((R).bits.is_active)
1802 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1803 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1806 /* Call this when have matched a real character; it sets `matched' flags
1807 for the subexpressions which we are currently inside. Also records
1808 that those subexprs have matched. */
1809 #define SET_REGS_MATCHED() \
1810 do \
1812 if (!set_regs_matched_done) \
1814 active_reg_t r; \
1815 set_regs_matched_done = 1; \
1816 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1818 MATCHED_SOMETHING (reg_info[r]) \
1819 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1820 = 1; \
1824 while (0)
1826 /* Registers are set to a sentinel when they haven't yet matched. */
1827 static CHAR_TYPE reg_unset_dummy;
1828 #define REG_UNSET_VALUE (&reg_unset_dummy)
1829 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1831 /* Subroutine declarations and macros for regex_compile. */
1833 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1834 reg_syntax_t syntax,
1835 struct re_pattern_buffer *bufp));
1836 static void store_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc, int arg));
1837 static void store_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1838 int arg1, int arg2));
1839 static void insert_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1840 int arg, US_CHAR_TYPE *end));
1841 static void insert_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1842 int arg1, int arg2, US_CHAR_TYPE *end));
1843 static boolean at_begline_loc_p _RE_ARGS ((const CHAR_TYPE *pattern,
1844 const CHAR_TYPE *p,
1845 reg_syntax_t syntax));
1846 static boolean at_endline_loc_p _RE_ARGS ((const CHAR_TYPE *p,
1847 const CHAR_TYPE *pend,
1848 reg_syntax_t syntax));
1849 #ifdef MBS_SUPPORT
1850 static reg_errcode_t compile_range _RE_ARGS ((CHAR_TYPE range_start,
1851 const CHAR_TYPE **p_ptr,
1852 const CHAR_TYPE *pend,
1853 char *translate,
1854 reg_syntax_t syntax,
1855 US_CHAR_TYPE *b,
1856 CHAR_TYPE *char_set));
1857 static void insert_space _RE_ARGS ((int num, CHAR_TYPE *loc, CHAR_TYPE *end));
1858 #else
1859 static reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
1860 const CHAR_TYPE **p_ptr,
1861 const CHAR_TYPE *pend,
1862 char *translate,
1863 reg_syntax_t syntax,
1864 US_CHAR_TYPE *b));
1865 #endif /* MBS_SUPPORT */
1867 /* Fetch the next character in the uncompiled pattern---translating it
1868 if necessary. Also cast from a signed character in the constant
1869 string passed to us by the user to an unsigned char that we can use
1870 as an array index (in, e.g., `translate'). */
1871 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1872 because it is impossible to allocate 4GB array for some encodings
1873 which have 4 byte character_set like UCS4. */
1874 #ifndef PATFETCH
1875 # ifdef MBS_SUPPORT
1876 # define PATFETCH(c) \
1877 do {if (p == pend) return REG_EEND; \
1878 c = (US_CHAR_TYPE) *p++; \
1879 if (translate && (c <= 0xff)) c = (US_CHAR_TYPE) translate[c]; \
1880 } while (0)
1881 # else
1882 # define PATFETCH(c) \
1883 do {if (p == pend) return REG_EEND; \
1884 c = (unsigned char) *p++; \
1885 if (translate) c = (unsigned char) translate[c]; \
1886 } while (0)
1887 # endif /* MBS_SUPPORT */
1888 #endif
1890 /* Fetch the next character in the uncompiled pattern, with no
1891 translation. */
1892 #define PATFETCH_RAW(c) \
1893 do {if (p == pend) return REG_EEND; \
1894 c = (US_CHAR_TYPE) *p++; \
1895 } while (0)
1897 /* Go backwards one character in the pattern. */
1898 #define PATUNFETCH p--
1901 /* If `translate' is non-null, return translate[D], else just D. We
1902 cast the subscript to translate because some data is declared as
1903 `char *', to avoid warnings when a string constant is passed. But
1904 when we use a character as a subscript we must make it unsigned. */
1905 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1906 because it is impossible to allocate 4GB array for some encodings
1907 which have 4 byte character_set like UCS4. */
1908 #ifndef TRANSLATE
1909 # ifdef MBS_SUPPORT
1910 # define TRANSLATE(d) \
1911 ((translate && ((US_CHAR_TYPE) (d)) <= 0xff) \
1912 ? (char) translate[(unsigned char) (d)] : (d))
1913 #else
1914 # define TRANSLATE(d) \
1915 (translate ? (char) translate[(unsigned char) (d)] : (d))
1916 # endif /* MBS_SUPPORT */
1917 #endif
1920 /* Macros for outputting the compiled pattern into `buffer'. */
1922 /* If the buffer isn't allocated when it comes in, use this. */
1923 #define INIT_BUF_SIZE (32 * sizeof(US_CHAR_TYPE))
1925 /* Make sure we have at least N more bytes of space in buffer. */
1926 #ifdef MBS_SUPPORT
1927 # define GET_BUFFER_SPACE(n) \
1928 while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR \
1929 + (n)*sizeof(CHAR_TYPE)) > bufp->allocated) \
1930 EXTEND_BUFFER ()
1931 #else
1932 # define GET_BUFFER_SPACE(n) \
1933 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1934 EXTEND_BUFFER ()
1935 #endif /* MBS_SUPPORT */
1937 /* Make sure we have one more byte of buffer space and then add C to it. */
1938 #define BUF_PUSH(c) \
1939 do { \
1940 GET_BUFFER_SPACE (1); \
1941 *b++ = (US_CHAR_TYPE) (c); \
1942 } while (0)
1945 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1946 #define BUF_PUSH_2(c1, c2) \
1947 do { \
1948 GET_BUFFER_SPACE (2); \
1949 *b++ = (US_CHAR_TYPE) (c1); \
1950 *b++ = (US_CHAR_TYPE) (c2); \
1951 } while (0)
1954 /* As with BUF_PUSH_2, except for three bytes. */
1955 #define BUF_PUSH_3(c1, c2, c3) \
1956 do { \
1957 GET_BUFFER_SPACE (3); \
1958 *b++ = (US_CHAR_TYPE) (c1); \
1959 *b++ = (US_CHAR_TYPE) (c2); \
1960 *b++ = (US_CHAR_TYPE) (c3); \
1961 } while (0)
1963 /* Store a jump with opcode OP at LOC to location TO. We store a
1964 relative address offset by the three bytes the jump itself occupies. */
1965 #define STORE_JUMP(op, loc, to) \
1966 store_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
1968 /* Likewise, for a two-argument jump. */
1969 #define STORE_JUMP2(op, loc, to, arg) \
1970 store_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
1972 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1973 #define INSERT_JUMP(op, loc, to) \
1974 insert_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
1976 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1977 #define INSERT_JUMP2(op, loc, to, arg) \
1978 insert_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
1979 arg, b)
1982 /* This is not an arbitrary limit: the arguments which represent offsets
1983 into the pattern are two bytes long. So if 2^16 bytes turns out to
1984 be too small, many things would have to change. */
1985 /* Any other compiler which, like MSC, has allocation limit below 2^16
1986 bytes will have to use approach similar to what was done below for
1987 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1988 reallocating to 0 bytes. Such thing is not going to work too well.
1989 You have been warned!! */
1990 #if defined _MSC_VER && !defined WIN32
1991 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1992 The REALLOC define eliminates a flurry of conversion warnings,
1993 but is not required. */
1994 # define MAX_BUF_SIZE 65500L
1995 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1996 #else
1997 # define MAX_BUF_SIZE (1L << 16)
1998 # define REALLOC(p,s) realloc ((p), (s))
1999 #endif
2001 /* Extend the buffer by twice its current size via realloc and
2002 reset the pointers that pointed into the old block to point to the
2003 correct places in the new one. If extending the buffer results in it
2004 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
2005 #if __BOUNDED_POINTERS__
2006 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2007 # define MOVE_BUFFER_POINTER(P) \
2008 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2009 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
2010 else \
2012 SET_HIGH_BOUND (b); \
2013 SET_HIGH_BOUND (begalt); \
2014 if (fixup_alt_jump) \
2015 SET_HIGH_BOUND (fixup_alt_jump); \
2016 if (laststart) \
2017 SET_HIGH_BOUND (laststart); \
2018 if (pending_exact) \
2019 SET_HIGH_BOUND (pending_exact); \
2021 #else
2022 # define MOVE_BUFFER_POINTER(P) (P) += incr
2023 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
2024 #endif
2026 #ifdef MBS_SUPPORT
2027 # define EXTEND_BUFFER() \
2028 do { \
2029 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2030 int wchar_count; \
2031 if (bufp->allocated + sizeof(US_CHAR_TYPE) > MAX_BUF_SIZE) \
2032 return REG_ESIZE; \
2033 bufp->allocated <<= 1; \
2034 if (bufp->allocated > MAX_BUF_SIZE) \
2035 bufp->allocated = MAX_BUF_SIZE; \
2036 /* How many characters the new buffer can have? */ \
2037 wchar_count = bufp->allocated / sizeof(US_CHAR_TYPE); \
2038 if (wchar_count == 0) wchar_count = 1; \
2039 /* Truncate the buffer to CHAR_TYPE align. */ \
2040 bufp->allocated = wchar_count * sizeof(US_CHAR_TYPE); \
2041 RETALLOC (COMPILED_BUFFER_VAR, wchar_count, US_CHAR_TYPE); \
2042 bufp->buffer = (char*)COMPILED_BUFFER_VAR; \
2043 if (COMPILED_BUFFER_VAR == NULL) \
2044 return REG_ESPACE; \
2045 /* If the buffer moved, move all the pointers into it. */ \
2046 if (old_buffer != COMPILED_BUFFER_VAR) \
2048 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2049 MOVE_BUFFER_POINTER (b); \
2050 MOVE_BUFFER_POINTER (begalt); \
2051 if (fixup_alt_jump) \
2052 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2053 if (laststart) \
2054 MOVE_BUFFER_POINTER (laststart); \
2055 if (pending_exact) \
2056 MOVE_BUFFER_POINTER (pending_exact); \
2058 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2059 } while (0)
2060 #else
2061 # define EXTEND_BUFFER() \
2062 do { \
2063 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2064 if (bufp->allocated == MAX_BUF_SIZE) \
2065 return REG_ESIZE; \
2066 bufp->allocated <<= 1; \
2067 if (bufp->allocated > MAX_BUF_SIZE) \
2068 bufp->allocated = MAX_BUF_SIZE; \
2069 bufp->buffer = (US_CHAR_TYPE *) REALLOC (COMPILED_BUFFER_VAR, \
2070 bufp->allocated); \
2071 if (COMPILED_BUFFER_VAR == NULL) \
2072 return REG_ESPACE; \
2073 /* If the buffer moved, move all the pointers into it. */ \
2074 if (old_buffer != COMPILED_BUFFER_VAR) \
2076 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2077 MOVE_BUFFER_POINTER (b); \
2078 MOVE_BUFFER_POINTER (begalt); \
2079 if (fixup_alt_jump) \
2080 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2081 if (laststart) \
2082 MOVE_BUFFER_POINTER (laststart); \
2083 if (pending_exact) \
2084 MOVE_BUFFER_POINTER (pending_exact); \
2086 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2087 } while (0)
2088 #endif /* MBS_SUPPORT */
2090 /* Since we have one byte reserved for the register number argument to
2091 {start,stop}_memory, the maximum number of groups we can report
2092 things about is what fits in that byte. */
2093 #define MAX_REGNUM 255
2095 /* But patterns can have more than `MAX_REGNUM' registers. We just
2096 ignore the excess. */
2097 typedef unsigned regnum_t;
2100 /* Macros for the compile stack. */
2102 /* Since offsets can go either forwards or backwards, this type needs to
2103 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
2104 /* int may be not enough when sizeof(int) == 2. */
2105 typedef long pattern_offset_t;
2107 typedef struct
2109 pattern_offset_t begalt_offset;
2110 pattern_offset_t fixup_alt_jump;
2111 pattern_offset_t inner_group_offset;
2112 pattern_offset_t laststart_offset;
2113 regnum_t regnum;
2114 } compile_stack_elt_t;
2117 typedef struct
2119 compile_stack_elt_t *stack;
2120 unsigned size;
2121 unsigned avail; /* Offset of next open position. */
2122 } compile_stack_type;
2125 #define INIT_COMPILE_STACK_SIZE 32
2127 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
2128 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
2130 /* The next available element. */
2131 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2134 /* Set the bit for character C in a list. */
2135 #define SET_LIST_BIT(c) \
2136 (b[((unsigned char) (c)) / BYTEWIDTH] \
2137 |= 1 << (((unsigned char) c) % BYTEWIDTH))
2140 /* Get the next unsigned number in the uncompiled pattern. */
2141 #define GET_UNSIGNED_NUMBER(num) \
2142 { if (p != pend) \
2144 PATFETCH (c); \
2145 while ('0' <= c && c <= '9') \
2147 if (num < 0) \
2148 num = 0; \
2149 num = num * 10 + c - '0'; \
2150 if (p == pend) \
2151 break; \
2152 PATFETCH (c); \
2157 #if defined _LIBC || WIDE_CHAR_SUPPORT
2158 /* The GNU C library provides support for user-defined character classes
2159 and the functions from ISO C amendement 1. */
2160 # ifdef CHARCLASS_NAME_MAX
2161 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2162 # else
2163 /* This shouldn't happen but some implementation might still have this
2164 problem. Use a reasonable default value. */
2165 # define CHAR_CLASS_MAX_LENGTH 256
2166 # endif
2168 # ifdef _LIBC
2169 # define IS_CHAR_CLASS(string) __wctype (string)
2170 # else
2171 # define IS_CHAR_CLASS(string) wctype (string)
2172 # endif
2173 #else
2174 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
2176 # define IS_CHAR_CLASS(string) \
2177 (STREQ (string, "alpha") || STREQ (string, "upper") \
2178 || STREQ (string, "lower") || STREQ (string, "digit") \
2179 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
2180 || STREQ (string, "space") || STREQ (string, "print") \
2181 || STREQ (string, "punct") || STREQ (string, "graph") \
2182 || STREQ (string, "cntrl") || STREQ (string, "blank"))
2183 #endif
2185 #ifndef MATCH_MAY_ALLOCATE
2187 /* If we cannot allocate large objects within re_match_2_internal,
2188 we make the fail stack and register vectors global.
2189 The fail stack, we grow to the maximum size when a regexp
2190 is compiled.
2191 The register vectors, we adjust in size each time we
2192 compile a regexp, according to the number of registers it needs. */
2194 static fail_stack_type fail_stack;
2196 /* Size with which the following vectors are currently allocated.
2197 That is so we can make them bigger as needed,
2198 but never make them smaller. */
2199 static int regs_allocated_size;
2201 static const char ** regstart, ** regend;
2202 static const char ** old_regstart, ** old_regend;
2203 static const char **best_regstart, **best_regend;
2204 static register_info_type *reg_info;
2205 static const char **reg_dummy;
2206 static register_info_type *reg_info_dummy;
2208 /* Make the register vectors big enough for NUM_REGS registers,
2209 but don't make them smaller. */
2211 static
2212 regex_grow_registers (num_regs)
2213 int num_regs;
2215 if (num_regs > regs_allocated_size)
2217 RETALLOC_IF (regstart, num_regs, const char *);
2218 RETALLOC_IF (regend, num_regs, const char *);
2219 RETALLOC_IF (old_regstart, num_regs, const char *);
2220 RETALLOC_IF (old_regend, num_regs, const char *);
2221 RETALLOC_IF (best_regstart, num_regs, const char *);
2222 RETALLOC_IF (best_regend, num_regs, const char *);
2223 RETALLOC_IF (reg_info, num_regs, register_info_type);
2224 RETALLOC_IF (reg_dummy, num_regs, const char *);
2225 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
2227 regs_allocated_size = num_regs;
2231 #endif /* not MATCH_MAY_ALLOCATE */
2233 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2234 compile_stack,
2235 regnum_t regnum));
2237 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2238 Returns one of error codes defined in `regex.h', or zero for success.
2240 Assumes the `allocated' (and perhaps `buffer') and `translate'
2241 fields are set in BUFP on entry.
2243 If it succeeds, results are put in BUFP (if it returns an error, the
2244 contents of BUFP are undefined):
2245 `buffer' is the compiled pattern;
2246 `syntax' is set to SYNTAX;
2247 `used' is set to the length of the compiled pattern;
2248 `fastmap_accurate' is zero;
2249 `re_nsub' is the number of subexpressions in PATTERN;
2250 `not_bol' and `not_eol' are zero;
2252 The `fastmap' and `newline_anchor' fields are neither
2253 examined nor set. */
2255 /* Return, freeing storage we allocated. */
2256 #ifdef MBS_SUPPORT
2257 # define FREE_STACK_RETURN(value) \
2258 return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2259 #else
2260 # define FREE_STACK_RETURN(value) \
2261 return (free (compile_stack.stack), value)
2262 #endif /* MBS_SUPPORT */
2264 static reg_errcode_t
2265 #ifdef MBS_SUPPORT
2266 regex_compile (cpattern, csize, syntax, bufp)
2267 const char *cpattern;
2268 size_t csize;
2269 #else
2270 regex_compile (pattern, size, syntax, bufp)
2271 const char *pattern;
2272 size_t size;
2273 #endif /* MBS_SUPPORT */
2274 reg_syntax_t syntax;
2275 struct re_pattern_buffer *bufp;
2277 /* We fetch characters from PATTERN here. Even though PATTERN is
2278 `char *' (i.e., signed), we declare these variables as unsigned, so
2279 they can be reliably used as array indices. */
2280 register US_CHAR_TYPE c, c1;
2282 #ifdef MBS_SUPPORT
2283 /* A temporary space to keep wchar_t pattern and compiled pattern. */
2284 CHAR_TYPE *pattern, *COMPILED_BUFFER_VAR;
2285 size_t size;
2286 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
2287 int *mbs_offset = NULL;
2288 /* It hold whether each wchar_t is binary data or not. */
2289 char *is_binary = NULL;
2290 /* A flag whether exactn is handling binary data or not. */
2291 char is_exactn_bin = FALSE;
2292 #endif /* MBS_SUPPORT */
2294 /* A random temporary spot in PATTERN. */
2295 const CHAR_TYPE *p1;
2297 /* Points to the end of the buffer, where we should append. */
2298 register US_CHAR_TYPE *b;
2300 /* Keeps track of unclosed groups. */
2301 compile_stack_type compile_stack;
2303 /* Points to the current (ending) position in the pattern. */
2304 #ifdef MBS_SUPPORT
2305 const CHAR_TYPE *p;
2306 const CHAR_TYPE *pend;
2307 #else
2308 const CHAR_TYPE *p = pattern;
2309 const CHAR_TYPE *pend = pattern + size;
2310 #endif /* MBS_SUPPORT */
2312 /* How to translate the characters in the pattern. */
2313 RE_TRANSLATE_TYPE translate = bufp->translate;
2315 /* Address of the count-byte of the most recently inserted `exactn'
2316 command. This makes it possible to tell if a new exact-match
2317 character can be added to that command or if the character requires
2318 a new `exactn' command. */
2319 US_CHAR_TYPE *pending_exact = 0;
2321 /* Address of start of the most recently finished expression.
2322 This tells, e.g., postfix * where to find the start of its
2323 operand. Reset at the beginning of groups and alternatives. */
2324 US_CHAR_TYPE *laststart = 0;
2326 /* Address of beginning of regexp, or inside of last group. */
2327 US_CHAR_TYPE *begalt;
2329 /* Place in the uncompiled pattern (i.e., the {) to
2330 which to go back if the interval is invalid. */
2331 #ifdef MBS_SUPPORT
2332 const US_CHAR_TYPE *beg_interval;
2333 #else
2334 const char *beg_interval;
2335 #endif /* MBS_SUPPORT */
2337 /* Address of the place where a forward jump should go to the end of
2338 the containing expression. Each alternative of an `or' -- except the
2339 last -- ends with a forward jump of this sort. */
2340 US_CHAR_TYPE *fixup_alt_jump = 0;
2342 /* Counts open-groups as they are encountered. Remembered for the
2343 matching close-group on the compile stack, so the same register
2344 number is put in the stop_memory as the start_memory. */
2345 regnum_t regnum = 0;
2347 #ifdef MBS_SUPPORT
2348 /* Initialize the wchar_t PATTERN and offset_buffer. */
2349 p = pend = pattern = TALLOC(csize, CHAR_TYPE);
2350 mbs_offset = TALLOC(csize + 1, int);
2351 is_binary = TALLOC(csize + 1, char);
2352 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2354 if (pattern) free(pattern);
2355 if (mbs_offset) free(mbs_offset);
2356 if (is_binary) free(is_binary);
2357 return REG_ESPACE;
2359 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2360 pend = p + size;
2361 if (size < 0)
2363 if (pattern) free(pattern);
2364 if (mbs_offset) free(mbs_offset);
2365 if (is_binary) free(is_binary);
2366 return REG_BADPAT;
2368 #endif
2370 #ifdef DEBUG
2371 DEBUG_PRINT1 ("\nCompiling pattern: ");
2372 if (debug)
2374 unsigned debug_count;
2376 for (debug_count = 0; debug_count < size; debug_count++)
2377 PUT_CHAR (pattern[debug_count]);
2378 putchar ('\n');
2380 #endif /* DEBUG */
2382 /* Initialize the compile stack. */
2383 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2384 if (compile_stack.stack == NULL)
2386 #ifdef MBS_SUPPORT
2387 if (pattern) free(pattern);
2388 if (mbs_offset) free(mbs_offset);
2389 if (is_binary) free(is_binary);
2390 #endif
2391 return REG_ESPACE;
2394 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2395 compile_stack.avail = 0;
2397 /* Initialize the pattern buffer. */
2398 bufp->syntax = syntax;
2399 bufp->fastmap_accurate = 0;
2400 bufp->not_bol = bufp->not_eol = 0;
2402 /* Set `used' to zero, so that if we return an error, the pattern
2403 printer (for debugging) will think there's no pattern. We reset it
2404 at the end. */
2405 bufp->used = 0;
2407 /* Always count groups, whether or not bufp->no_sub is set. */
2408 bufp->re_nsub = 0;
2410 #if !defined emacs && !defined SYNTAX_TABLE
2411 /* Initialize the syntax table. */
2412 init_syntax_once ();
2413 #endif
2415 if (bufp->allocated == 0)
2417 if (bufp->buffer)
2418 { /* If zero allocated, but buffer is non-null, try to realloc
2419 enough space. This loses if buffer's address is bogus, but
2420 that is the user's responsibility. */
2421 #ifdef MBS_SUPPORT
2422 /* Free bufp->buffer and allocate an array for wchar_t pattern
2423 buffer. */
2424 free(bufp->buffer);
2425 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(US_CHAR_TYPE),
2426 US_CHAR_TYPE);
2427 #else
2428 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, US_CHAR_TYPE);
2429 #endif /* MBS_SUPPORT */
2431 else
2432 { /* Caller did not allocate a buffer. Do it for them. */
2433 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(US_CHAR_TYPE),
2434 US_CHAR_TYPE);
2437 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2438 #ifdef MBS_SUPPORT
2439 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2440 #endif /* MBS_SUPPORT */
2441 bufp->allocated = INIT_BUF_SIZE;
2443 #ifdef MBS_SUPPORT
2444 else
2445 COMPILED_BUFFER_VAR = (US_CHAR_TYPE*) bufp->buffer;
2446 #endif
2448 begalt = b = COMPILED_BUFFER_VAR;
2450 /* Loop through the uncompiled pattern until we're at the end. */
2451 while (p != pend)
2453 PATFETCH (c);
2455 switch (c)
2457 case '^':
2459 if ( /* If at start of pattern, it's an operator. */
2460 p == pattern + 1
2461 /* If context independent, it's an operator. */
2462 || syntax & RE_CONTEXT_INDEP_ANCHORS
2463 /* Otherwise, depends on what's come before. */
2464 || at_begline_loc_p (pattern, p, syntax))
2465 BUF_PUSH (begline);
2466 else
2467 goto normal_char;
2469 break;
2472 case '$':
2474 if ( /* If at end of pattern, it's an operator. */
2475 p == pend
2476 /* If context independent, it's an operator. */
2477 || syntax & RE_CONTEXT_INDEP_ANCHORS
2478 /* Otherwise, depends on what's next. */
2479 || at_endline_loc_p (p, pend, syntax))
2480 BUF_PUSH (endline);
2481 else
2482 goto normal_char;
2484 break;
2487 case '+':
2488 case '?':
2489 if ((syntax & RE_BK_PLUS_QM)
2490 || (syntax & RE_LIMITED_OPS))
2491 goto normal_char;
2492 handle_plus:
2493 case '*':
2494 /* If there is no previous pattern... */
2495 if (!laststart)
2497 if (syntax & RE_CONTEXT_INVALID_OPS)
2498 FREE_STACK_RETURN (REG_BADRPT);
2499 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2500 goto normal_char;
2504 /* Are we optimizing this jump? */
2505 boolean keep_string_p = false;
2507 /* 1 means zero (many) matches is allowed. */
2508 char zero_times_ok = 0, many_times_ok = 0;
2510 /* If there is a sequence of repetition chars, collapse it
2511 down to just one (the right one). We can't combine
2512 interval operators with these because of, e.g., `a{2}*',
2513 which should only match an even number of `a's. */
2515 for (;;)
2517 zero_times_ok |= c != '+';
2518 many_times_ok |= c != '?';
2520 if (p == pend)
2521 break;
2523 PATFETCH (c);
2525 if (c == '*'
2526 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2529 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2531 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2533 PATFETCH (c1);
2534 if (!(c1 == '+' || c1 == '?'))
2536 PATUNFETCH;
2537 PATUNFETCH;
2538 break;
2541 c = c1;
2543 else
2545 PATUNFETCH;
2546 break;
2549 /* If we get here, we found another repeat character. */
2552 /* Star, etc. applied to an empty pattern is equivalent
2553 to an empty pattern. */
2554 if (!laststart)
2555 break;
2557 /* Now we know whether or not zero matches is allowed
2558 and also whether or not two or more matches is allowed. */
2559 if (many_times_ok)
2560 { /* More than one repetition is allowed, so put in at the
2561 end a backward relative jump from `b' to before the next
2562 jump we're going to put in below (which jumps from
2563 laststart to after this jump).
2565 But if we are at the `*' in the exact sequence `.*\n',
2566 insert an unconditional jump backwards to the .,
2567 instead of the beginning of the loop. This way we only
2568 push a failure point once, instead of every time
2569 through the loop. */
2570 assert (p - 1 > pattern);
2572 /* Allocate the space for the jump. */
2573 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2575 /* We know we are not at the first character of the pattern,
2576 because laststart was nonzero. And we've already
2577 incremented `p', by the way, to be the character after
2578 the `*'. Do we have to do something analogous here
2579 for null bytes, because of RE_DOT_NOT_NULL? */
2580 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2581 && zero_times_ok
2582 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2583 && !(syntax & RE_DOT_NEWLINE))
2584 { /* We have .*\n. */
2585 STORE_JUMP (jump, b, laststart);
2586 keep_string_p = true;
2588 else
2589 /* Anything else. */
2590 STORE_JUMP (maybe_pop_jump, b, laststart -
2591 (1 + OFFSET_ADDRESS_SIZE));
2593 /* We've added more stuff to the buffer. */
2594 b += 1 + OFFSET_ADDRESS_SIZE;
2597 /* On failure, jump from laststart to b + 3, which will be the
2598 end of the buffer after this jump is inserted. */
2599 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2600 'b + 3'. */
2601 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2602 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2603 : on_failure_jump,
2604 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2605 pending_exact = 0;
2606 b += 1 + OFFSET_ADDRESS_SIZE;
2608 if (!zero_times_ok)
2610 /* At least one repetition is required, so insert a
2611 `dummy_failure_jump' before the initial
2612 `on_failure_jump' instruction of the loop. This
2613 effects a skip over that instruction the first time
2614 we hit that loop. */
2615 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2616 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2617 2 + 2 * OFFSET_ADDRESS_SIZE);
2618 b += 1 + OFFSET_ADDRESS_SIZE;
2621 break;
2624 case '.':
2625 laststart = b;
2626 BUF_PUSH (anychar);
2627 break;
2630 case '[':
2632 boolean had_char_class = false;
2633 #ifdef MBS_SUPPORT
2634 CHAR_TYPE range_start = 0xffffffff;
2635 #else
2636 unsigned int range_start = 0xffffffff;
2637 #endif
2638 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2640 #ifdef MBS_SUPPORT
2641 /* We assume a charset(_not) structure as a wchar_t array.
2642 charset[0] = (re_opcode_t) charset(_not)
2643 charset[1] = l (= length of char_classes)
2644 charset[2] = m (= length of collating_symbols)
2645 charset[3] = n (= length of equivalence_classes)
2646 charset[4] = o (= length of char_ranges)
2647 charset[5] = p (= length of chars)
2649 charset[6] = char_class (wctype_t)
2650 charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2652 charset[l+5] = char_class (wctype_t)
2654 charset[l+6] = collating_symbol (wchar_t)
2656 charset[l+m+5] = collating_symbol (wchar_t)
2657 ifdef _LIBC we use the index if
2658 _NL_COLLATE_SYMB_EXTRAMB instead of
2659 wchar_t string.
2661 charset[l+m+6] = equivalence_classes (wchar_t)
2663 charset[l+m+n+5] = equivalence_classes (wchar_t)
2664 ifdef _LIBC we use the index in
2665 _NL_COLLATE_WEIGHT instead of
2666 wchar_t string.
2668 charset[l+m+n+6] = range_start
2669 charset[l+m+n+7] = range_end
2671 charset[l+m+n+2o+4] = range_start
2672 charset[l+m+n+2o+5] = range_end
2673 ifdef _LIBC we use the value looked up
2674 in _NL_COLLATE_COLLSEQ instead of
2675 wchar_t character.
2677 charset[l+m+n+2o+6] = char
2679 charset[l+m+n+2o+p+5] = char
2683 /* We need at least 6 spaces: the opcode, the length of
2684 char_classes, the length of collating_symbols, the length of
2685 equivalence_classes, the length of char_ranges, the length of
2686 chars. */
2687 GET_BUFFER_SPACE (6);
2689 /* Save b as laststart. And We use laststart as the pointer
2690 to the first element of the charset here.
2691 In other words, laststart[i] indicates charset[i]. */
2692 laststart = b;
2694 /* We test `*p == '^' twice, instead of using an if
2695 statement, so we only need one BUF_PUSH. */
2696 BUF_PUSH (*p == '^' ? charset_not : charset);
2697 if (*p == '^')
2698 p++;
2700 /* Push the length of char_classes, the length of
2701 collating_symbols, the length of equivalence_classes, the
2702 length of char_ranges and the length of chars. */
2703 BUF_PUSH_3 (0, 0, 0);
2704 BUF_PUSH_2 (0, 0);
2706 /* Remember the first position in the bracket expression. */
2707 p1 = p;
2709 /* charset_not matches newline according to a syntax bit. */
2710 if ((re_opcode_t) b[-6] == charset_not
2711 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2713 BUF_PUSH('\n');
2714 laststart[5]++; /* Update the length of characters */
2717 /* Read in characters and ranges, setting map bits. */
2718 for (;;)
2720 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2722 PATFETCH (c);
2724 /* \ might escape characters inside [...] and [^...]. */
2725 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2727 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2729 PATFETCH (c1);
2730 BUF_PUSH(c1);
2731 laststart[5]++; /* Update the length of chars */
2732 range_start = c1;
2733 continue;
2736 /* Could be the end of the bracket expression. If it's
2737 not (i.e., when the bracket expression is `[]' so
2738 far), the ']' character bit gets set way below. */
2739 if (c == ']' && p != p1 + 1)
2740 break;
2742 /* Look ahead to see if it's a range when the last thing
2743 was a character class. */
2744 if (had_char_class && c == '-' && *p != ']')
2745 FREE_STACK_RETURN (REG_ERANGE);
2747 /* Look ahead to see if it's a range when the last thing
2748 was a character: if this is a hyphen not at the
2749 beginning or the end of a list, then it's the range
2750 operator. */
2751 if (c == '-'
2752 && !(p - 2 >= pattern && p[-2] == '[')
2753 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2754 && *p != ']')
2756 reg_errcode_t ret;
2757 /* Allocate the space for range_start and range_end. */
2758 GET_BUFFER_SPACE (2);
2759 /* Update the pointer to indicate end of buffer. */
2760 b += 2;
2761 ret = compile_range (range_start, &p, pend, translate,
2762 syntax, b, laststart);
2763 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2764 range_start = 0xffffffff;
2766 else if (p[0] == '-' && p[1] != ']')
2767 { /* This handles ranges made up of characters only. */
2768 reg_errcode_t ret;
2770 /* Move past the `-'. */
2771 PATFETCH (c1);
2772 /* Allocate the space for range_start and range_end. */
2773 GET_BUFFER_SPACE (2);
2774 /* Update the pointer to indicate end of buffer. */
2775 b += 2;
2776 ret = compile_range (c, &p, pend, translate, syntax, b,
2777 laststart);
2778 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2779 range_start = 0xffffffff;
2782 /* See if we're at the beginning of a possible character
2783 class. */
2784 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2785 { /* Leave room for the null. */
2786 char str[CHAR_CLASS_MAX_LENGTH + 1];
2788 PATFETCH (c);
2789 c1 = 0;
2791 /* If pattern is `[[:'. */
2792 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2794 for (;;)
2796 PATFETCH (c);
2797 if ((c == ':' && *p == ']') || p == pend)
2798 break;
2799 if (c1 < CHAR_CLASS_MAX_LENGTH)
2800 str[c1++] = c;
2801 else
2802 /* This is in any case an invalid class name. */
2803 str[0] = '\0';
2805 str[c1] = '\0';
2807 /* If isn't a word bracketed by `[:' and `:]':
2808 undo the ending character, the letters, and leave
2809 the leading `:' and `[' (but store them as character). */
2810 if (c == ':' && *p == ']')
2812 wctype_t wt;
2813 uintptr_t alignedp;
2815 /* Query the character class as wctype_t. */
2816 wt = IS_CHAR_CLASS (str);
2817 if (wt == 0)
2818 FREE_STACK_RETURN (REG_ECTYPE);
2820 /* Throw away the ] at the end of the character
2821 class. */
2822 PATFETCH (c);
2824 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2826 /* Allocate the space for character class. */
2827 GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2828 /* Update the pointer to indicate end of buffer. */
2829 b += CHAR_CLASS_SIZE;
2830 /* Move data which follow character classes
2831 not to violate the data. */
2832 insert_space(CHAR_CLASS_SIZE,
2833 laststart + 6 + laststart[1],
2834 b - 1);
2835 alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2836 + __alignof__(wctype_t) - 1)
2837 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2838 /* Store the character class. */
2839 *((wctype_t*)alignedp) = wt;
2840 /* Update length of char_classes */
2841 laststart[1] += CHAR_CLASS_SIZE;
2843 had_char_class = true;
2845 else
2847 c1++;
2848 while (c1--)
2849 PATUNFETCH;
2850 BUF_PUSH ('[');
2851 BUF_PUSH (':');
2852 laststart[5] += 2; /* Update the length of characters */
2853 range_start = ':';
2854 had_char_class = false;
2857 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2858 || *p == '.'))
2860 CHAR_TYPE str[128]; /* Should be large enough. */
2861 CHAR_TYPE delim = *p; /* '=' or '.' */
2862 # ifdef _LIBC
2863 uint32_t nrules =
2864 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2865 # endif
2866 PATFETCH (c);
2867 c1 = 0;
2869 /* If pattern is `[[=' or '[[.'. */
2870 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2872 for (;;)
2874 PATFETCH (c);
2875 if ((c == delim && *p == ']') || p == pend)
2876 break;
2877 if (c1 < sizeof (str) - 1)
2878 str[c1++] = c;
2879 else
2880 /* This is in any case an invalid class name. */
2881 str[0] = '\0';
2883 str[c1] = '\0';
2885 if (c == delim && *p == ']' && str[0] != '\0')
2887 unsigned int i, offset;
2888 /* If we have no collation data we use the default
2889 collation in which each character is in a class
2890 by itself. It also means that ASCII is the
2891 character set and therefore we cannot have character
2892 with more than one byte in the multibyte
2893 representation. */
2895 /* If not defined _LIBC, we push the name and
2896 `\0' for the sake of matching performance. */
2897 int datasize = c1 + 1;
2899 # ifdef _LIBC
2900 int32_t idx = 0;
2901 if (nrules == 0)
2902 # endif
2904 if (c1 != 1)
2905 FREE_STACK_RETURN (REG_ECOLLATE);
2907 # ifdef _LIBC
2908 else
2910 const int32_t *table;
2911 const int32_t *weights;
2912 const int32_t *extra;
2913 const int32_t *indirect;
2914 wint_t *cp;
2916 /* This #include defines a local function! */
2917 # include <locale/weightwc.h>
2919 if(delim == '=')
2921 /* We push the index for equivalence class. */
2922 cp = (wint_t*)str;
2924 table = (const int32_t *)
2925 _NL_CURRENT (LC_COLLATE,
2926 _NL_COLLATE_TABLEWC);
2927 weights = (const int32_t *)
2928 _NL_CURRENT (LC_COLLATE,
2929 _NL_COLLATE_WEIGHTWC);
2930 extra = (const int32_t *)
2931 _NL_CURRENT (LC_COLLATE,
2932 _NL_COLLATE_EXTRAWC);
2933 indirect = (const int32_t *)
2934 _NL_CURRENT (LC_COLLATE,
2935 _NL_COLLATE_INDIRECTWC);
2937 idx = findidx ((const wint_t**)&cp);
2938 if (idx == 0 || cp < (wint_t*) str + c1)
2939 /* This is no valid character. */
2940 FREE_STACK_RETURN (REG_ECOLLATE);
2942 str[0] = (wchar_t)idx;
2944 else /* delim == '.' */
2946 /* We push collation sequence value
2947 for collating symbol. */
2948 int32_t table_size;
2949 const int32_t *symb_table;
2950 const unsigned char *extra;
2951 int32_t idx;
2952 int32_t elem;
2953 int32_t second;
2954 int32_t hash;
2955 char char_str[c1];
2957 /* We have to convert the name to a single-byte
2958 string. This is possible since the names
2959 consist of ASCII characters and the internal
2960 representation is UCS4. */
2961 for (i = 0; i < c1; ++i)
2962 char_str[i] = str[i];
2964 table_size =
2965 _NL_CURRENT_WORD (LC_COLLATE,
2966 _NL_COLLATE_SYMB_HASH_SIZEMB);
2967 symb_table = (const int32_t *)
2968 _NL_CURRENT (LC_COLLATE,
2969 _NL_COLLATE_SYMB_TABLEMB);
2970 extra = (const unsigned char *)
2971 _NL_CURRENT (LC_COLLATE,
2972 _NL_COLLATE_SYMB_EXTRAMB);
2974 /* Locate the character in the hashing table. */
2975 hash = elem_hash (char_str, c1);
2977 idx = 0;
2978 elem = hash % table_size;
2979 second = hash % (table_size - 2);
2980 while (symb_table[2 * elem] != 0)
2982 /* First compare the hashing value. */
2983 if (symb_table[2 * elem] == hash
2984 && c1 == extra[symb_table[2 * elem + 1]]
2985 && memcmp (str,
2986 &extra[symb_table[2 * elem + 1]
2987 + 1], c1) == 0)
2989 /* Yep, this is the entry. */
2990 idx = symb_table[2 * elem + 1];
2991 idx += 1 + extra[idx];
2992 break;
2995 /* Next entry. */
2996 elem += second;
2999 if (symb_table[2 * elem] != 0)
3001 /* Compute the index of the byte sequence
3002 in the table. */
3003 idx += 1 + extra[idx];
3004 /* Adjust for the alignment. */
3005 idx = (idx + 3) & ~4;
3007 str[0] = (wchar_t) idx + 4;
3009 else if (symb_table[2 * elem] == 0 && c1 == 1)
3011 /* No valid character. Match it as a
3012 single byte character. */
3013 had_char_class = false;
3014 BUF_PUSH(str[0]);
3015 /* Update the length of characters */
3016 laststart[5]++;
3017 range_start = str[0];
3019 /* Throw away the ] at the end of the
3020 collating symbol. */
3021 PATFETCH (c);
3022 /* exit from the switch block. */
3023 continue;
3025 else
3026 FREE_STACK_RETURN (REG_ECOLLATE);
3028 datasize = 1;
3030 # endif
3031 /* Throw away the ] at the end of the equivalence
3032 class (or collating symbol). */
3033 PATFETCH (c);
3035 /* Allocate the space for the equivalence class
3036 (or collating symbol) (and '\0' if needed). */
3037 GET_BUFFER_SPACE(datasize);
3038 /* Update the pointer to indicate end of buffer. */
3039 b += datasize;
3041 if (delim == '=')
3042 { /* equivalence class */
3043 /* Calculate the offset of char_ranges,
3044 which is next to equivalence_classes. */
3045 offset = laststart[1] + laststart[2]
3046 + laststart[3] +6;
3047 /* Insert space. */
3048 insert_space(datasize, laststart + offset, b - 1);
3050 /* Write the equivalence_class and \0. */
3051 for (i = 0 ; i < datasize ; i++)
3052 laststart[offset + i] = str[i];
3054 /* Update the length of equivalence_classes. */
3055 laststart[3] += datasize;
3056 had_char_class = true;
3058 else /* delim == '.' */
3059 { /* collating symbol */
3060 /* Calculate the offset of the equivalence_classes,
3061 which is next to collating_symbols. */
3062 offset = laststart[1] + laststart[2] + 6;
3063 /* Insert space and write the collationg_symbol
3064 and \0. */
3065 insert_space(datasize, laststart + offset, b-1);
3066 for (i = 0 ; i < datasize ; i++)
3067 laststart[offset + i] = str[i];
3069 /* In re_match_2_internal if range_start < -1, we
3070 assume -range_start is the offset of the
3071 collating symbol which is specified as
3072 the character of the range start. So we assign
3073 -(laststart[1] + laststart[2] + 6) to
3074 range_start. */
3075 range_start = -(laststart[1] + laststart[2] + 6);
3076 /* Update the length of collating_symbol. */
3077 laststart[2] += datasize;
3078 had_char_class = false;
3081 else
3083 c1++;
3084 while (c1--)
3085 PATUNFETCH;
3086 BUF_PUSH ('[');
3087 BUF_PUSH (delim);
3088 laststart[5] += 2; /* Update the length of characters */
3089 range_start = delim;
3090 had_char_class = false;
3093 else
3095 had_char_class = false;
3096 BUF_PUSH(c);
3097 laststart[5]++; /* Update the length of characters */
3098 range_start = c;
3102 #else /* not MBS_SUPPORT */
3103 /* Ensure that we have enough space to push a charset: the
3104 opcode, the length count, and the bitset; 34 bytes in all. */
3105 GET_BUFFER_SPACE (34);
3107 laststart = b;
3109 /* We test `*p == '^' twice, instead of using an if
3110 statement, so we only need one BUF_PUSH. */
3111 BUF_PUSH (*p == '^' ? charset_not : charset);
3112 if (*p == '^')
3113 p++;
3115 /* Remember the first position in the bracket expression. */
3116 p1 = p;
3118 /* Push the number of bytes in the bitmap. */
3119 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3121 /* Clear the whole map. */
3122 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3124 /* charset_not matches newline according to a syntax bit. */
3125 if ((re_opcode_t) b[-2] == charset_not
3126 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3127 SET_LIST_BIT ('\n');
3129 /* Read in characters and ranges, setting map bits. */
3130 for (;;)
3132 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3134 PATFETCH (c);
3136 /* \ might escape characters inside [...] and [^...]. */
3137 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3139 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3141 PATFETCH (c1);
3142 SET_LIST_BIT (c1);
3143 range_start = c1;
3144 continue;
3147 /* Could be the end of the bracket expression. If it's
3148 not (i.e., when the bracket expression is `[]' so
3149 far), the ']' character bit gets set way below. */
3150 if (c == ']' && p != p1 + 1)
3151 break;
3153 /* Look ahead to see if it's a range when the last thing
3154 was a character class. */
3155 if (had_char_class && c == '-' && *p != ']')
3156 FREE_STACK_RETURN (REG_ERANGE);
3158 /* Look ahead to see if it's a range when the last thing
3159 was a character: if this is a hyphen not at the
3160 beginning or the end of a list, then it's the range
3161 operator. */
3162 if (c == '-'
3163 && !(p - 2 >= pattern && p[-2] == '[')
3164 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3165 && *p != ']')
3167 reg_errcode_t ret
3168 = compile_range (range_start, &p, pend, translate,
3169 syntax, b);
3170 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3171 range_start = 0xffffffff;
3174 else if (p[0] == '-' && p[1] != ']')
3175 { /* This handles ranges made up of characters only. */
3176 reg_errcode_t ret;
3178 /* Move past the `-'. */
3179 PATFETCH (c1);
3181 ret = compile_range (c, &p, pend, translate, syntax, b);
3182 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3183 range_start = 0xffffffff;
3186 /* See if we're at the beginning of a possible character
3187 class. */
3189 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3190 { /* Leave room for the null. */
3191 char str[CHAR_CLASS_MAX_LENGTH + 1];
3193 PATFETCH (c);
3194 c1 = 0;
3196 /* If pattern is `[[:'. */
3197 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3199 for (;;)
3201 PATFETCH (c);
3202 if ((c == ':' && *p == ']') || p == pend)
3203 break;
3204 if (c1 < CHAR_CLASS_MAX_LENGTH)
3205 str[c1++] = c;
3206 else
3207 /* This is in any case an invalid class name. */
3208 str[0] = '\0';
3210 str[c1] = '\0';
3212 /* If isn't a word bracketed by `[:' and `:]':
3213 undo the ending character, the letters, and leave
3214 the leading `:' and `[' (but set bits for them). */
3215 if (c == ':' && *p == ']')
3217 # if defined _LIBC || WIDE_CHAR_SUPPORT
3218 boolean is_lower = STREQ (str, "lower");
3219 boolean is_upper = STREQ (str, "upper");
3220 wctype_t wt;
3221 int ch;
3223 wt = IS_CHAR_CLASS (str);
3224 if (wt == 0)
3225 FREE_STACK_RETURN (REG_ECTYPE);
3227 /* Throw away the ] at the end of the character
3228 class. */
3229 PATFETCH (c);
3231 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3233 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3235 # ifdef _LIBC
3236 if (__iswctype (__btowc (ch), wt))
3237 SET_LIST_BIT (ch);
3238 # else
3239 if (iswctype (btowc (ch), wt))
3240 SET_LIST_BIT (ch);
3241 # endif
3243 if (translate && (is_upper || is_lower)
3244 && (ISUPPER (ch) || ISLOWER (ch)))
3245 SET_LIST_BIT (ch);
3248 had_char_class = true;
3249 # else
3250 int ch;
3251 boolean is_alnum = STREQ (str, "alnum");
3252 boolean is_alpha = STREQ (str, "alpha");
3253 boolean is_blank = STREQ (str, "blank");
3254 boolean is_cntrl = STREQ (str, "cntrl");
3255 boolean is_digit = STREQ (str, "digit");
3256 boolean is_graph = STREQ (str, "graph");
3257 boolean is_lower = STREQ (str, "lower");
3258 boolean is_print = STREQ (str, "print");
3259 boolean is_punct = STREQ (str, "punct");
3260 boolean is_space = STREQ (str, "space");
3261 boolean is_upper = STREQ (str, "upper");
3262 boolean is_xdigit = STREQ (str, "xdigit");
3264 if (!IS_CHAR_CLASS (str))
3265 FREE_STACK_RETURN (REG_ECTYPE);
3267 /* Throw away the ] at the end of the character
3268 class. */
3269 PATFETCH (c);
3271 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3273 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3275 /* This was split into 3 if's to
3276 avoid an arbitrary limit in some compiler. */
3277 if ( (is_alnum && ISALNUM (ch))
3278 || (is_alpha && ISALPHA (ch))
3279 || (is_blank && ISBLANK (ch))
3280 || (is_cntrl && ISCNTRL (ch)))
3281 SET_LIST_BIT (ch);
3282 if ( (is_digit && ISDIGIT (ch))
3283 || (is_graph && ISGRAPH (ch))
3284 || (is_lower && ISLOWER (ch))
3285 || (is_print && ISPRINT (ch)))
3286 SET_LIST_BIT (ch);
3287 if ( (is_punct && ISPUNCT (ch))
3288 || (is_space && ISSPACE (ch))
3289 || (is_upper && ISUPPER (ch))
3290 || (is_xdigit && ISXDIGIT (ch)))
3291 SET_LIST_BIT (ch);
3292 if ( translate && (is_upper || is_lower)
3293 && (ISUPPER (ch) || ISLOWER (ch)))
3294 SET_LIST_BIT (ch);
3296 had_char_class = true;
3297 # endif /* libc || wctype.h */
3299 else
3301 c1++;
3302 while (c1--)
3303 PATUNFETCH;
3304 SET_LIST_BIT ('[');
3305 SET_LIST_BIT (':');
3306 range_start = ':';
3307 had_char_class = false;
3310 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3312 unsigned char str[MB_LEN_MAX + 1];
3313 # ifdef _LIBC
3314 uint32_t nrules =
3315 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3316 # endif
3318 PATFETCH (c);
3319 c1 = 0;
3321 /* If pattern is `[[='. */
3322 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3324 for (;;)
3326 PATFETCH (c);
3327 if ((c == '=' && *p == ']') || p == pend)
3328 break;
3329 if (c1 < MB_LEN_MAX)
3330 str[c1++] = c;
3331 else
3332 /* This is in any case an invalid class name. */
3333 str[0] = '\0';
3335 str[c1] = '\0';
3337 if (c == '=' && *p == ']' && str[0] != '\0')
3339 /* If we have no collation data we use the default
3340 collation in which each character is in a class
3341 by itself. It also means that ASCII is the
3342 character set and therefore we cannot have character
3343 with more than one byte in the multibyte
3344 representation. */
3345 # ifdef _LIBC
3346 if (nrules == 0)
3347 # endif
3349 if (c1 != 1)
3350 FREE_STACK_RETURN (REG_ECOLLATE);
3352 /* Throw away the ] at the end of the equivalence
3353 class. */
3354 PATFETCH (c);
3356 /* Set the bit for the character. */
3357 SET_LIST_BIT (str[0]);
3359 # ifdef _LIBC
3360 else
3362 /* Try to match the byte sequence in `str' against
3363 those known to the collate implementation.
3364 First find out whether the bytes in `str' are
3365 actually from exactly one character. */
3366 const int32_t *table;
3367 const unsigned char *weights;
3368 const unsigned char *extra;
3369 const int32_t *indirect;
3370 int32_t idx;
3371 const unsigned char *cp = str;
3372 int ch;
3374 /* This #include defines a local function! */
3375 # include <locale/weight.h>
3377 table = (const int32_t *)
3378 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3379 weights = (const unsigned char *)
3380 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3381 extra = (const unsigned char *)
3382 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3383 indirect = (const int32_t *)
3384 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3386 idx = findidx (&cp);
3387 if (idx == 0 || cp < str + c1)
3388 /* This is no valid character. */
3389 FREE_STACK_RETURN (REG_ECOLLATE);
3391 /* Throw away the ] at the end of the equivalence
3392 class. */
3393 PATFETCH (c);
3395 /* Now we have to go throught the whole table
3396 and find all characters which have the same
3397 first level weight.
3399 XXX Note that this is not entirely correct.
3400 we would have to match multibyte sequences
3401 but this is not possible with the current
3402 implementation. */
3403 for (ch = 1; ch < 256; ++ch)
3404 /* XXX This test would have to be changed if we
3405 would allow matching multibyte sequences. */
3406 if (table[ch] > 0)
3408 int32_t idx2 = table[ch];
3409 size_t len = weights[idx2];
3411 /* Test whether the lenghts match. */
3412 if (weights[idx] == len)
3414 /* They do. New compare the bytes of
3415 the weight. */
3416 size_t cnt = 0;
3418 while (cnt < len
3419 && (weights[idx + 1 + cnt]
3420 == weights[idx2 + 1 + cnt]))
3421 ++cnt;
3423 if (cnt == len)
3424 /* They match. Mark the character as
3425 acceptable. */
3426 SET_LIST_BIT (ch);
3430 # endif
3431 had_char_class = true;
3433 else
3435 c1++;
3436 while (c1--)
3437 PATUNFETCH;
3438 SET_LIST_BIT ('[');
3439 SET_LIST_BIT ('=');
3440 range_start = '=';
3441 had_char_class = false;
3444 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3446 unsigned char str[128]; /* Should be large enough. */
3447 # ifdef _LIBC
3448 uint32_t nrules =
3449 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3450 # endif
3452 PATFETCH (c);
3453 c1 = 0;
3455 /* If pattern is `[[.'. */
3456 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3458 for (;;)
3460 PATFETCH (c);
3461 if ((c == '.' && *p == ']') || p == pend)
3462 break;
3463 if (c1 < sizeof (str))
3464 str[c1++] = c;
3465 else
3466 /* This is in any case an invalid class name. */
3467 str[0] = '\0';
3469 str[c1] = '\0';
3471 if (c == '.' && *p == ']' && str[0] != '\0')
3473 /* If we have no collation data we use the default
3474 collation in which each character is the name
3475 for its own class which contains only the one
3476 character. It also means that ASCII is the
3477 character set and therefore we cannot have character
3478 with more than one byte in the multibyte
3479 representation. */
3480 # ifdef _LIBC
3481 if (nrules == 0)
3482 # endif
3484 if (c1 != 1)
3485 FREE_STACK_RETURN (REG_ECOLLATE);
3487 /* Throw away the ] at the end of the equivalence
3488 class. */
3489 PATFETCH (c);
3491 /* Set the bit for the character. */
3492 SET_LIST_BIT (str[0]);
3493 range_start = ((const unsigned char *) str)[0];
3495 # ifdef _LIBC
3496 else
3498 /* Try to match the byte sequence in `str' against
3499 those known to the collate implementation.
3500 First find out whether the bytes in `str' are
3501 actually from exactly one character. */
3502 int32_t table_size;
3503 const int32_t *symb_table;
3504 const unsigned char *extra;
3505 int32_t idx;
3506 int32_t elem;
3507 int32_t second;
3508 int32_t hash;
3510 table_size =
3511 _NL_CURRENT_WORD (LC_COLLATE,
3512 _NL_COLLATE_SYMB_HASH_SIZEMB);
3513 symb_table = (const int32_t *)
3514 _NL_CURRENT (LC_COLLATE,
3515 _NL_COLLATE_SYMB_TABLEMB);
3516 extra = (const unsigned char *)
3517 _NL_CURRENT (LC_COLLATE,
3518 _NL_COLLATE_SYMB_EXTRAMB);
3520 /* Locate the character in the hashing table. */
3521 hash = elem_hash (str, c1);
3523 idx = 0;
3524 elem = hash % table_size;
3525 second = hash % (table_size - 2);
3526 while (symb_table[2 * elem] != 0)
3528 /* First compare the hashing value. */
3529 if (symb_table[2 * elem] == hash
3530 && c1 == extra[symb_table[2 * elem + 1]]
3531 && memcmp (str,
3532 &extra[symb_table[2 * elem + 1]
3533 + 1],
3534 c1) == 0)
3536 /* Yep, this is the entry. */
3537 idx = symb_table[2 * elem + 1];
3538 idx += 1 + extra[idx];
3539 break;
3542 /* Next entry. */
3543 elem += second;
3546 if (symb_table[2 * elem] == 0)
3547 /* This is no valid character. */
3548 FREE_STACK_RETURN (REG_ECOLLATE);
3550 /* Throw away the ] at the end of the equivalence
3551 class. */
3552 PATFETCH (c);
3554 /* Now add the multibyte character(s) we found
3555 to the accept list.
3557 XXX Note that this is not entirely correct.
3558 we would have to match multibyte sequences
3559 but this is not possible with the current
3560 implementation. Also, we have to match
3561 collating symbols, which expand to more than
3562 one file, as a whole and not allow the
3563 individual bytes. */
3564 c1 = extra[idx++];
3565 if (c1 == 1)
3566 range_start = extra[idx];
3567 while (c1-- > 0)
3569 SET_LIST_BIT (extra[idx]);
3570 ++idx;
3573 # endif
3574 had_char_class = false;
3576 else
3578 c1++;
3579 while (c1--)
3580 PATUNFETCH;
3581 SET_LIST_BIT ('[');
3582 SET_LIST_BIT ('.');
3583 range_start = '.';
3584 had_char_class = false;
3587 else
3589 had_char_class = false;
3590 SET_LIST_BIT (c);
3591 range_start = c;
3595 /* Discard any (non)matching list bytes that are all 0 at the
3596 end of the map. Decrease the map-length byte too. */
3597 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3598 b[-1]--;
3599 b += b[-1];
3600 #endif /* MBS_SUPPORT */
3602 break;
3605 case '(':
3606 if (syntax & RE_NO_BK_PARENS)
3607 goto handle_open;
3608 else
3609 goto normal_char;
3612 case ')':
3613 if (syntax & RE_NO_BK_PARENS)
3614 goto handle_close;
3615 else
3616 goto normal_char;
3619 case '\n':
3620 if (syntax & RE_NEWLINE_ALT)
3621 goto handle_alt;
3622 else
3623 goto normal_char;
3626 case '|':
3627 if (syntax & RE_NO_BK_VBAR)
3628 goto handle_alt;
3629 else
3630 goto normal_char;
3633 case '{':
3634 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3635 goto handle_interval;
3636 else
3637 goto normal_char;
3640 case '\\':
3641 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3643 /* Do not translate the character after the \, so that we can
3644 distinguish, e.g., \B from \b, even if we normally would
3645 translate, e.g., B to b. */
3646 PATFETCH_RAW (c);
3648 switch (c)
3650 case '(':
3651 if (syntax & RE_NO_BK_PARENS)
3652 goto normal_backslash;
3654 handle_open:
3655 bufp->re_nsub++;
3656 regnum++;
3658 if (COMPILE_STACK_FULL)
3660 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3661 compile_stack_elt_t);
3662 if (compile_stack.stack == NULL) return REG_ESPACE;
3664 compile_stack.size <<= 1;
3667 /* These are the values to restore when we hit end of this
3668 group. They are all relative offsets, so that if the
3669 whole pattern moves because of realloc, they will still
3670 be valid. */
3671 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3672 COMPILE_STACK_TOP.fixup_alt_jump
3673 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3674 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3675 COMPILE_STACK_TOP.regnum = regnum;
3677 /* We will eventually replace the 0 with the number of
3678 groups inner to this one. But do not push a
3679 start_memory for groups beyond the last one we can
3680 represent in the compiled pattern. */
3681 if (regnum <= MAX_REGNUM)
3683 COMPILE_STACK_TOP.inner_group_offset = b
3684 - COMPILED_BUFFER_VAR + 2;
3685 BUF_PUSH_3 (start_memory, regnum, 0);
3688 compile_stack.avail++;
3690 fixup_alt_jump = 0;
3691 laststart = 0;
3692 begalt = b;
3693 /* If we've reached MAX_REGNUM groups, then this open
3694 won't actually generate any code, so we'll have to
3695 clear pending_exact explicitly. */
3696 pending_exact = 0;
3697 break;
3700 case ')':
3701 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3703 if (COMPILE_STACK_EMPTY)
3705 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3706 goto normal_backslash;
3707 else
3708 FREE_STACK_RETURN (REG_ERPAREN);
3711 handle_close:
3712 if (fixup_alt_jump)
3713 { /* Push a dummy failure point at the end of the
3714 alternative for a possible future
3715 `pop_failure_jump' to pop. See comments at
3716 `push_dummy_failure' in `re_match_2'. */
3717 BUF_PUSH (push_dummy_failure);
3719 /* We allocated space for this jump when we assigned
3720 to `fixup_alt_jump', in the `handle_alt' case below. */
3721 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3724 /* See similar code for backslashed left paren above. */
3725 if (COMPILE_STACK_EMPTY)
3727 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3728 goto normal_char;
3729 else
3730 FREE_STACK_RETURN (REG_ERPAREN);
3733 /* Since we just checked for an empty stack above, this
3734 ``can't happen''. */
3735 assert (compile_stack.avail != 0);
3737 /* We don't just want to restore into `regnum', because
3738 later groups should continue to be numbered higher,
3739 as in `(ab)c(de)' -- the second group is #2. */
3740 regnum_t this_group_regnum;
3742 compile_stack.avail--;
3743 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3744 fixup_alt_jump
3745 = COMPILE_STACK_TOP.fixup_alt_jump
3746 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3747 : 0;
3748 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3749 this_group_regnum = COMPILE_STACK_TOP.regnum;
3750 /* If we've reached MAX_REGNUM groups, then this open
3751 won't actually generate any code, so we'll have to
3752 clear pending_exact explicitly. */
3753 pending_exact = 0;
3755 /* We're at the end of the group, so now we know how many
3756 groups were inside this one. */
3757 if (this_group_regnum <= MAX_REGNUM)
3759 US_CHAR_TYPE *inner_group_loc
3760 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3762 *inner_group_loc = regnum - this_group_regnum;
3763 BUF_PUSH_3 (stop_memory, this_group_regnum,
3764 regnum - this_group_regnum);
3767 break;
3770 case '|': /* `\|'. */
3771 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3772 goto normal_backslash;
3773 handle_alt:
3774 if (syntax & RE_LIMITED_OPS)
3775 goto normal_char;
3777 /* Insert before the previous alternative a jump which
3778 jumps to this alternative if the former fails. */
3779 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3780 INSERT_JUMP (on_failure_jump, begalt,
3781 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3782 pending_exact = 0;
3783 b += 1 + OFFSET_ADDRESS_SIZE;
3785 /* The alternative before this one has a jump after it
3786 which gets executed if it gets matched. Adjust that
3787 jump so it will jump to this alternative's analogous
3788 jump (put in below, which in turn will jump to the next
3789 (if any) alternative's such jump, etc.). The last such
3790 jump jumps to the correct final destination. A picture:
3791 _____ _____
3792 | | | |
3793 | v | v
3794 a | b | c
3796 If we are at `b', then fixup_alt_jump right now points to a
3797 three-byte space after `a'. We'll put in the jump, set
3798 fixup_alt_jump to right after `b', and leave behind three
3799 bytes which we'll fill in when we get to after `c'. */
3801 if (fixup_alt_jump)
3802 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3804 /* Mark and leave space for a jump after this alternative,
3805 to be filled in later either by next alternative or
3806 when know we're at the end of a series of alternatives. */
3807 fixup_alt_jump = b;
3808 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3809 b += 1 + OFFSET_ADDRESS_SIZE;
3811 laststart = 0;
3812 begalt = b;
3813 break;
3816 case '{':
3817 /* If \{ is a literal. */
3818 if (!(syntax & RE_INTERVALS)
3819 /* If we're at `\{' and it's not the open-interval
3820 operator. */
3821 || (syntax & RE_NO_BK_BRACES))
3822 goto normal_backslash;
3824 handle_interval:
3826 /* If got here, then the syntax allows intervals. */
3828 /* At least (most) this many matches must be made. */
3829 int lower_bound = -1, upper_bound = -1;
3830 beg_interval = p - 1;
3832 if (p == pend)
3834 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3835 goto unfetch_interval;
3836 else
3837 FREE_STACK_RETURN (REG_EBRACE);
3840 GET_UNSIGNED_NUMBER (lower_bound);
3842 if (c == ',')
3844 GET_UNSIGNED_NUMBER (upper_bound);
3845 if ((!(syntax & RE_NO_BK_BRACES) && c != '\\')
3846 || ((syntax & RE_NO_BK_BRACES) && c != '}'))
3847 FREE_STACK_RETURN (REG_BADBR);
3849 if (upper_bound < 0)
3850 upper_bound = RE_DUP_MAX;
3852 else
3853 /* Interval such as `{1}' => match exactly once. */
3854 upper_bound = lower_bound;
3856 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3857 || lower_bound > upper_bound)
3859 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3860 goto unfetch_interval;
3861 else
3862 FREE_STACK_RETURN (REG_BADBR);
3865 if (!(syntax & RE_NO_BK_BRACES))
3867 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
3869 PATFETCH (c);
3872 if (c != '}')
3874 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3875 goto unfetch_interval;
3876 else
3877 FREE_STACK_RETURN (REG_BADBR);
3880 /* We just parsed a valid interval. */
3882 /* If it's invalid to have no preceding re. */
3883 if (!laststart)
3885 if (syntax & RE_CONTEXT_INVALID_OPS)
3886 FREE_STACK_RETURN (REG_BADRPT);
3887 else if (syntax & RE_CONTEXT_INDEP_OPS)
3888 laststart = b;
3889 else
3890 goto unfetch_interval;
3893 /* If the upper bound is zero, don't want to succeed at
3894 all; jump from `laststart' to `b + 3', which will be
3895 the end of the buffer after we insert the jump. */
3896 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE'
3897 instead of 'b + 3'. */
3898 if (upper_bound == 0)
3900 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3901 INSERT_JUMP (jump, laststart, b + 1
3902 + OFFSET_ADDRESS_SIZE);
3903 b += 1 + OFFSET_ADDRESS_SIZE;
3906 /* Otherwise, we have a nontrivial interval. When
3907 we're all done, the pattern will look like:
3908 set_number_at <jump count> <upper bound>
3909 set_number_at <succeed_n count> <lower bound>
3910 succeed_n <after jump addr> <succeed_n count>
3911 <body of loop>
3912 jump_n <succeed_n addr> <jump count>
3913 (The upper bound and `jump_n' are omitted if
3914 `upper_bound' is 1, though.) */
3915 else
3916 { /* If the upper bound is > 1, we need to insert
3917 more at the end of the loop. */
3918 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3919 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3921 GET_BUFFER_SPACE (nbytes);
3923 /* Initialize lower bound of the `succeed_n', even
3924 though it will be set during matching by its
3925 attendant `set_number_at' (inserted next),
3926 because `re_compile_fastmap' needs to know.
3927 Jump to the `jump_n' we might insert below. */
3928 INSERT_JUMP2 (succeed_n, laststart,
3929 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3930 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3931 , lower_bound);
3932 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3934 /* Code to initialize the lower bound. Insert
3935 before the `succeed_n'. The `5' is the last two
3936 bytes of this `set_number_at', plus 3 bytes of
3937 the following `succeed_n'. */
3938 /* ifdef MBS_SUPPORT, The '1+2*OFFSET_ADDRESS_SIZE'
3939 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3940 of the following `succeed_n'. */
3941 insert_op2 (set_number_at, laststart, 1
3942 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3943 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3945 if (upper_bound > 1)
3946 { /* More than one repetition is allowed, so
3947 append a backward jump to the `succeed_n'
3948 that starts this interval.
3950 When we've reached this during matching,
3951 we'll have matched the interval once, so
3952 jump back only `upper_bound - 1' times. */
3953 STORE_JUMP2 (jump_n, b, laststart
3954 + 2 * OFFSET_ADDRESS_SIZE + 1,
3955 upper_bound - 1);
3956 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3958 /* The location we want to set is the second
3959 parameter of the `jump_n'; that is `b-2' as
3960 an absolute address. `laststart' will be
3961 the `set_number_at' we're about to insert;
3962 `laststart+3' the number to set, the source
3963 for the relative address. But we are
3964 inserting into the middle of the pattern --
3965 so everything is getting moved up by 5.
3966 Conclusion: (b - 2) - (laststart + 3) + 5,
3967 i.e., b - laststart.
3969 We insert this at the beginning of the loop
3970 so that if we fail during matching, we'll
3971 reinitialize the bounds. */
3972 insert_op2 (set_number_at, laststart, b - laststart,
3973 upper_bound - 1, b);
3974 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3977 pending_exact = 0;
3978 beg_interval = NULL;
3980 break;
3982 unfetch_interval:
3983 /* If an invalid interval, match the characters as literals. */
3984 assert (beg_interval);
3985 p = beg_interval;
3986 beg_interval = NULL;
3988 /* normal_char and normal_backslash need `c'. */
3989 PATFETCH (c);
3991 if (!(syntax & RE_NO_BK_BRACES))
3993 if (p > pattern && p[-1] == '\\')
3994 goto normal_backslash;
3996 goto normal_char;
3998 #ifdef emacs
3999 /* There is no way to specify the before_dot and after_dot
4000 operators. rms says this is ok. --karl */
4001 case '=':
4002 BUF_PUSH (at_dot);
4003 break;
4005 case 's':
4006 laststart = b;
4007 PATFETCH (c);
4008 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
4009 break;
4011 case 'S':
4012 laststart = b;
4013 PATFETCH (c);
4014 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
4015 break;
4016 #endif /* emacs */
4019 case 'w':
4020 if (syntax & RE_NO_GNU_OPS)
4021 goto normal_char;
4022 laststart = b;
4023 BUF_PUSH (wordchar);
4024 break;
4027 case 'W':
4028 if (syntax & RE_NO_GNU_OPS)
4029 goto normal_char;
4030 laststart = b;
4031 BUF_PUSH (notwordchar);
4032 break;
4035 case '<':
4036 if (syntax & RE_NO_GNU_OPS)
4037 goto normal_char;
4038 BUF_PUSH (wordbeg);
4039 break;
4041 case '>':
4042 if (syntax & RE_NO_GNU_OPS)
4043 goto normal_char;
4044 BUF_PUSH (wordend);
4045 break;
4047 case 'b':
4048 if (syntax & RE_NO_GNU_OPS)
4049 goto normal_char;
4050 BUF_PUSH (wordbound);
4051 break;
4053 case 'B':
4054 if (syntax & RE_NO_GNU_OPS)
4055 goto normal_char;
4056 BUF_PUSH (notwordbound);
4057 break;
4059 case '`':
4060 if (syntax & RE_NO_GNU_OPS)
4061 goto normal_char;
4062 BUF_PUSH (begbuf);
4063 break;
4065 case '\'':
4066 if (syntax & RE_NO_GNU_OPS)
4067 goto normal_char;
4068 BUF_PUSH (endbuf);
4069 break;
4071 case '1': case '2': case '3': case '4': case '5':
4072 case '6': case '7': case '8': case '9':
4073 if (syntax & RE_NO_BK_REFS)
4074 goto normal_char;
4076 c1 = c - '0';
4078 if (c1 > regnum)
4079 FREE_STACK_RETURN (REG_ESUBREG);
4081 /* Can't back reference to a subexpression if inside of it. */
4082 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4083 goto normal_char;
4085 laststart = b;
4086 BUF_PUSH_2 (duplicate, c1);
4087 break;
4090 case '+':
4091 case '?':
4092 if (syntax & RE_BK_PLUS_QM)
4093 goto handle_plus;
4094 else
4095 goto normal_backslash;
4097 default:
4098 normal_backslash:
4099 /* You might think it would be useful for \ to mean
4100 not to translate; but if we don't translate it
4101 it will never match anything. */
4102 c = TRANSLATE (c);
4103 goto normal_char;
4105 break;
4108 default:
4109 /* Expects the character in `c'. */
4110 normal_char:
4111 /* If no exactn currently being built. */
4112 if (!pending_exact
4113 #ifdef MBS_SUPPORT
4114 /* If last exactn handle binary(or character) and
4115 new exactn handle character(or binary). */
4116 || is_exactn_bin != is_binary[p - 1 - pattern]
4117 #endif /* MBS_SUPPORT */
4119 /* If last exactn not at current position. */
4120 || pending_exact + *pending_exact + 1 != b
4122 /* We have only one byte following the exactn for the count. */
4123 || *pending_exact == (1 << BYTEWIDTH) - 1
4125 /* If followed by a repetition operator. */
4126 || *p == '*' || *p == '^'
4127 || ((syntax & RE_BK_PLUS_QM)
4128 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4129 : (*p == '+' || *p == '?'))
4130 || ((syntax & RE_INTERVALS)
4131 && ((syntax & RE_NO_BK_BRACES)
4132 ? *p == '{'
4133 : (p[0] == '\\' && p[1] == '{'))))
4135 /* Start building a new exactn. */
4137 laststart = b;
4139 #ifdef MBS_SUPPORT
4140 /* Is this exactn binary data or character? */
4141 is_exactn_bin = is_binary[p - 1 - pattern];
4142 if (is_exactn_bin)
4143 BUF_PUSH_2 (exactn_bin, 0);
4144 else
4145 BUF_PUSH_2 (exactn, 0);
4146 #else
4147 BUF_PUSH_2 (exactn, 0);
4148 #endif /* MBS_SUPPORT */
4149 pending_exact = b - 1;
4152 BUF_PUSH (c);
4153 (*pending_exact)++;
4154 break;
4155 } /* switch (c) */
4156 } /* while p != pend */
4159 /* Through the pattern now. */
4161 if (fixup_alt_jump)
4162 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4164 if (!COMPILE_STACK_EMPTY)
4165 FREE_STACK_RETURN (REG_EPAREN);
4167 /* If we don't want backtracking, force success
4168 the first time we reach the end of the compiled pattern. */
4169 if (syntax & RE_NO_POSIX_BACKTRACKING)
4170 BUF_PUSH (succeed);
4172 #ifdef MBS_SUPPORT
4173 free (pattern);
4174 free (mbs_offset);
4175 free (is_binary);
4176 #endif
4177 free (compile_stack.stack);
4179 /* We have succeeded; set the length of the buffer. */
4180 #ifdef MBS_SUPPORT
4181 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4182 #else
4183 bufp->used = b - bufp->buffer;
4184 #endif
4186 #ifdef DEBUG
4187 if (debug)
4189 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4190 print_compiled_pattern (bufp);
4192 #endif /* DEBUG */
4194 #ifndef MATCH_MAY_ALLOCATE
4195 /* Initialize the failure stack to the largest possible stack. This
4196 isn't necessary unless we're trying to avoid calling alloca in
4197 the search and match routines. */
4199 int num_regs = bufp->re_nsub + 1;
4201 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4202 is strictly greater than re_max_failures, the largest possible stack
4203 is 2 * re_max_failures failure points. */
4204 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4206 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4208 # ifdef emacs
4209 if (! fail_stack.stack)
4210 fail_stack.stack
4211 = (fail_stack_elt_t *) xmalloc (fail_stack.size
4212 * sizeof (fail_stack_elt_t));
4213 else
4214 fail_stack.stack
4215 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
4216 (fail_stack.size
4217 * sizeof (fail_stack_elt_t)));
4218 # else /* not emacs */
4219 if (! fail_stack.stack)
4220 fail_stack.stack
4221 = (fail_stack_elt_t *) malloc (fail_stack.size
4222 * sizeof (fail_stack_elt_t));
4223 else
4224 fail_stack.stack
4225 = (fail_stack_elt_t *) realloc (fail_stack.stack,
4226 (fail_stack.size
4227 * sizeof (fail_stack_elt_t)));
4228 # endif /* not emacs */
4231 regex_grow_registers (num_regs);
4233 #endif /* not MATCH_MAY_ALLOCATE */
4235 return REG_NOERROR;
4236 } /* regex_compile */
4238 /* Subroutines for `regex_compile'. */
4240 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4241 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4243 static void
4244 store_op1 (op, loc, arg)
4245 re_opcode_t op;
4246 US_CHAR_TYPE *loc;
4247 int arg;
4249 *loc = (US_CHAR_TYPE) op;
4250 STORE_NUMBER (loc + 1, arg);
4254 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4255 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4257 static void
4258 store_op2 (op, loc, arg1, arg2)
4259 re_opcode_t op;
4260 US_CHAR_TYPE *loc;
4261 int arg1, arg2;
4263 *loc = (US_CHAR_TYPE) op;
4264 STORE_NUMBER (loc + 1, arg1);
4265 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4269 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4270 for OP followed by two-byte integer parameter ARG. */
4271 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4273 static void
4274 insert_op1 (op, loc, arg, end)
4275 re_opcode_t op;
4276 US_CHAR_TYPE *loc;
4277 int arg;
4278 US_CHAR_TYPE *end;
4280 register US_CHAR_TYPE *pfrom = end;
4281 register US_CHAR_TYPE *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4283 while (pfrom != loc)
4284 *--pto = *--pfrom;
4286 store_op1 (op, loc, arg);
4290 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4291 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4293 static void
4294 insert_op2 (op, loc, arg1, arg2, end)
4295 re_opcode_t op;
4296 US_CHAR_TYPE *loc;
4297 int arg1, arg2;
4298 US_CHAR_TYPE *end;
4300 register US_CHAR_TYPE *pfrom = end;
4301 register US_CHAR_TYPE *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4303 while (pfrom != loc)
4304 *--pto = *--pfrom;
4306 store_op2 (op, loc, arg1, arg2);
4310 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4311 after an alternative or a begin-subexpression. We assume there is at
4312 least one character before the ^. */
4314 static boolean
4315 at_begline_loc_p (pattern, p, syntax)
4316 const CHAR_TYPE *pattern, *p;
4317 reg_syntax_t syntax;
4319 const CHAR_TYPE *prev = p - 2;
4320 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4322 return
4323 /* After a subexpression? */
4324 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4325 /* After an alternative? */
4326 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4330 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4331 at least one character after the $, i.e., `P < PEND'. */
4333 static boolean
4334 at_endline_loc_p (p, pend, syntax)
4335 const CHAR_TYPE *p, *pend;
4336 reg_syntax_t syntax;
4338 const CHAR_TYPE *next = p;
4339 boolean next_backslash = *next == '\\';
4340 const CHAR_TYPE *next_next = p + 1 < pend ? p + 1 : 0;
4342 return
4343 /* Before a subexpression? */
4344 (syntax & RE_NO_BK_PARENS ? *next == ')'
4345 : next_backslash && next_next && *next_next == ')')
4346 /* Before an alternative? */
4347 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4348 : next_backslash && next_next && *next_next == '|');
4352 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4353 false if it's not. */
4355 static boolean
4356 group_in_compile_stack (compile_stack, regnum)
4357 compile_stack_type compile_stack;
4358 regnum_t regnum;
4360 int this_element;
4362 for (this_element = compile_stack.avail - 1;
4363 this_element >= 0;
4364 this_element--)
4365 if (compile_stack.stack[this_element].regnum == regnum)
4366 return true;
4368 return false;
4371 #ifdef MBS_SUPPORT
4372 /* This insert space, which size is "num", into the pattern at "loc".
4373 "end" must point the end of the allocated buffer. */
4374 static void
4375 insert_space (num, loc, end)
4376 int num;
4377 CHAR_TYPE *loc;
4378 CHAR_TYPE *end;
4380 register CHAR_TYPE *pto = end;
4381 register CHAR_TYPE *pfrom = end - num;
4383 while (pfrom >= loc)
4384 *pto-- = *pfrom--;
4386 #endif /* MBS_SUPPORT */
4388 #ifdef MBS_SUPPORT
4389 static reg_errcode_t
4390 compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4391 char_set)
4392 CHAR_TYPE range_start_char;
4393 const CHAR_TYPE **p_ptr, *pend;
4394 CHAR_TYPE *char_set, *b;
4395 RE_TRANSLATE_TYPE translate;
4396 reg_syntax_t syntax;
4398 const CHAR_TYPE *p = *p_ptr;
4399 CHAR_TYPE range_start, range_end;
4400 reg_errcode_t ret;
4401 # ifdef _LIBC
4402 uint32_t nrules;
4403 uint32_t start_val, end_val;
4404 # endif
4405 if (p == pend)
4406 return REG_ERANGE;
4408 # ifdef _LIBC
4409 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4410 if (nrules != 0)
4412 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4413 _NL_COLLATE_COLLSEQWC);
4414 const unsigned char *extra = (const unsigned char *)
4415 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4417 if (range_start_char < -1)
4419 /* range_start is a collating symbol. */
4420 int32_t *wextra;
4421 /* Retreive the index and get collation sequence value. */
4422 wextra = (int32_t*)(extra + char_set[-range_start_char]);
4423 start_val = wextra[1 + *wextra];
4425 else
4426 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4428 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4430 /* Report an error if the range is empty and the syntax prohibits
4431 this. */
4432 ret = ((syntax & RE_NO_EMPTY_RANGES)
4433 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4435 /* Insert space to the end of the char_ranges. */
4436 insert_space(2, b - char_set[5] - 2, b - 1);
4437 *(b - char_set[5] - 2) = (wchar_t)start_val;
4438 *(b - char_set[5] - 1) = (wchar_t)end_val;
4439 char_set[4]++; /* ranges_index */
4441 else
4442 # endif
4444 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4445 range_start_char;
4446 range_end = TRANSLATE (p[0]);
4447 /* Report an error if the range is empty and the syntax prohibits
4448 this. */
4449 ret = ((syntax & RE_NO_EMPTY_RANGES)
4450 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4452 /* Insert space to the end of the char_ranges. */
4453 insert_space(2, b - char_set[5] - 2, b - 1);
4454 *(b - char_set[5] - 2) = range_start;
4455 *(b - char_set[5] - 1) = range_end;
4456 char_set[4]++; /* ranges_index */
4458 /* Have to increment the pointer into the pattern string, so the
4459 caller isn't still at the ending character. */
4460 (*p_ptr)++;
4462 return ret;
4464 #else
4465 /* Read the ending character of a range (in a bracket expression) from the
4466 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4467 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4468 Then we set the translation of all bits between the starting and
4469 ending characters (inclusive) in the compiled pattern B.
4471 Return an error code.
4473 We use these short variable names so we can use the same macros as
4474 `regex_compile' itself. */
4476 static reg_errcode_t
4477 compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4478 unsigned int range_start_char;
4479 const char **p_ptr, *pend;
4480 RE_TRANSLATE_TYPE translate;
4481 reg_syntax_t syntax;
4482 unsigned char *b;
4484 unsigned this_char;
4485 const char *p = *p_ptr;
4486 reg_errcode_t ret;
4487 # if _LIBC
4488 const unsigned char *collseq;
4489 unsigned int start_colseq;
4490 unsigned int end_colseq;
4491 # else
4492 unsigned end_char;
4493 # endif
4495 if (p == pend)
4496 return REG_ERANGE;
4498 /* Have to increment the pointer into the pattern string, so the
4499 caller isn't still at the ending character. */
4500 (*p_ptr)++;
4502 /* Report an error if the range is empty and the syntax prohibits this. */
4503 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4505 # if _LIBC
4506 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4507 _NL_COLLATE_COLLSEQMB);
4509 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4510 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4511 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4513 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4515 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4517 SET_LIST_BIT (TRANSLATE (this_char));
4518 ret = REG_NOERROR;
4521 # else
4522 /* Here we see why `this_char' has to be larger than an `unsigned
4523 char' -- we would otherwise go into an infinite loop, since all
4524 characters <= 0xff. */
4525 range_start_char = TRANSLATE (range_start_char);
4526 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4527 and some compilers cast it to int implicitly, so following for_loop
4528 may fall to (almost) infinite loop.
4529 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4530 To avoid this, we cast p[0] to unsigned int and truncate it. */
4531 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4533 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4535 SET_LIST_BIT (TRANSLATE (this_char));
4536 ret = REG_NOERROR;
4538 # endif
4540 return ret;
4542 #endif /* MBS_SUPPORT */
4544 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4545 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4546 characters can start a string that matches the pattern. This fastmap
4547 is used by re_search to skip quickly over impossible starting points.
4549 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4550 area as BUFP->fastmap.
4552 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4553 the pattern buffer.
4555 Returns 0 if we succeed, -2 if an internal error. */
4557 #ifdef MBS_SUPPORT
4558 /* local function for re_compile_fastmap.
4559 truncate wchar_t character to char. */
4560 static unsigned char truncate_wchar (CHAR_TYPE c);
4562 static unsigned char
4563 truncate_wchar (c)
4564 CHAR_TYPE c;
4566 unsigned char buf[MB_LEN_MAX];
4567 int retval = wctomb(buf, c);
4568 return retval > 0 ? buf[0] : (unsigned char)c;
4570 #endif /* MBS_SUPPORT */
4573 re_compile_fastmap (bufp)
4574 struct re_pattern_buffer *bufp;
4576 int j, k;
4577 #ifdef MATCH_MAY_ALLOCATE
4578 fail_stack_type fail_stack;
4579 #endif
4580 #ifndef REGEX_MALLOC
4581 char *destination;
4582 #endif
4584 register char *fastmap = bufp->fastmap;
4586 #ifdef MBS_SUPPORT
4587 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4588 pattern to (char*) in regex_compile. */
4589 US_CHAR_TYPE *pattern = (US_CHAR_TYPE*)bufp->buffer;
4590 register US_CHAR_TYPE *pend = (US_CHAR_TYPE*) (bufp->buffer + bufp->used);
4591 #else
4592 US_CHAR_TYPE *pattern = bufp->buffer;
4593 register US_CHAR_TYPE *pend = pattern + bufp->used;
4594 #endif /* MBS_SUPPORT */
4595 US_CHAR_TYPE *p = pattern;
4597 #ifdef REL_ALLOC
4598 /* This holds the pointer to the failure stack, when
4599 it is allocated relocatably. */
4600 fail_stack_elt_t *failure_stack_ptr;
4601 #endif
4603 /* Assume that each path through the pattern can be null until
4604 proven otherwise. We set this false at the bottom of switch
4605 statement, to which we get only if a particular path doesn't
4606 match the empty string. */
4607 boolean path_can_be_null = true;
4609 /* We aren't doing a `succeed_n' to begin with. */
4610 boolean succeed_n_p = false;
4612 assert (fastmap != NULL && p != NULL);
4614 INIT_FAIL_STACK ();
4615 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4616 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4617 bufp->can_be_null = 0;
4619 while (1)
4621 if (p == pend || *p == succeed)
4623 /* We have reached the (effective) end of pattern. */
4624 if (!FAIL_STACK_EMPTY ())
4626 bufp->can_be_null |= path_can_be_null;
4628 /* Reset for next path. */
4629 path_can_be_null = true;
4631 p = fail_stack.stack[--fail_stack.avail].pointer;
4633 continue;
4635 else
4636 break;
4639 /* We should never be about to go beyond the end of the pattern. */
4640 assert (p < pend);
4642 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4645 /* I guess the idea here is to simply not bother with a fastmap
4646 if a backreference is used, since it's too hard to figure out
4647 the fastmap for the corresponding group. Setting
4648 `can_be_null' stops `re_search_2' from using the fastmap, so
4649 that is all we do. */
4650 case duplicate:
4651 bufp->can_be_null = 1;
4652 goto done;
4655 /* Following are the cases which match a character. These end
4656 with `break'. */
4658 #ifdef MBS_SUPPORT
4659 case exactn:
4660 fastmap[truncate_wchar(p[1])] = 1;
4661 break;
4662 case exactn_bin:
4663 fastmap[p[1]] = 1;
4664 break;
4665 #else
4666 case exactn:
4667 fastmap[p[1]] = 1;
4668 break;
4669 #endif /* MBS_SUPPORT */
4672 #ifdef MBS_SUPPORT
4673 /* It is hard to distinguish fastmap from (multi byte) characters
4674 which depends on current locale. */
4675 case charset:
4676 case charset_not:
4677 case wordchar:
4678 case notwordchar:
4679 bufp->can_be_null = 1;
4680 goto done;
4681 #else
4682 case charset:
4683 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4684 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4685 fastmap[j] = 1;
4686 break;
4689 case charset_not:
4690 /* Chars beyond end of map must be allowed. */
4691 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4692 fastmap[j] = 1;
4694 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4695 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4696 fastmap[j] = 1;
4697 break;
4700 case wordchar:
4701 for (j = 0; j < (1 << BYTEWIDTH); j++)
4702 if (SYNTAX (j) == Sword)
4703 fastmap[j] = 1;
4704 break;
4707 case notwordchar:
4708 for (j = 0; j < (1 << BYTEWIDTH); j++)
4709 if (SYNTAX (j) != Sword)
4710 fastmap[j] = 1;
4711 break;
4712 #endif
4714 case anychar:
4716 int fastmap_newline = fastmap['\n'];
4718 /* `.' matches anything ... */
4719 for (j = 0; j < (1 << BYTEWIDTH); j++)
4720 fastmap[j] = 1;
4722 /* ... except perhaps newline. */
4723 if (!(bufp->syntax & RE_DOT_NEWLINE))
4724 fastmap['\n'] = fastmap_newline;
4726 /* Return if we have already set `can_be_null'; if we have,
4727 then the fastmap is irrelevant. Something's wrong here. */
4728 else if (bufp->can_be_null)
4729 goto done;
4731 /* Otherwise, have to check alternative paths. */
4732 break;
4735 #ifdef emacs
4736 case syntaxspec:
4737 k = *p++;
4738 for (j = 0; j < (1 << BYTEWIDTH); j++)
4739 if (SYNTAX (j) == (enum syntaxcode) k)
4740 fastmap[j] = 1;
4741 break;
4744 case notsyntaxspec:
4745 k = *p++;
4746 for (j = 0; j < (1 << BYTEWIDTH); j++)
4747 if (SYNTAX (j) != (enum syntaxcode) k)
4748 fastmap[j] = 1;
4749 break;
4752 /* All cases after this match the empty string. These end with
4753 `continue'. */
4756 case before_dot:
4757 case at_dot:
4758 case after_dot:
4759 continue;
4760 #endif /* emacs */
4763 case no_op:
4764 case begline:
4765 case endline:
4766 case begbuf:
4767 case endbuf:
4768 case wordbound:
4769 case notwordbound:
4770 case wordbeg:
4771 case wordend:
4772 case push_dummy_failure:
4773 continue;
4776 case jump_n:
4777 case pop_failure_jump:
4778 case maybe_pop_jump:
4779 case jump:
4780 case jump_past_alt:
4781 case dummy_failure_jump:
4782 EXTRACT_NUMBER_AND_INCR (j, p);
4783 p += j;
4784 if (j > 0)
4785 continue;
4787 /* Jump backward implies we just went through the body of a
4788 loop and matched nothing. Opcode jumped to should be
4789 `on_failure_jump' or `succeed_n'. Just treat it like an
4790 ordinary jump. For a * loop, it has pushed its failure
4791 point already; if so, discard that as redundant. */
4792 if ((re_opcode_t) *p != on_failure_jump
4793 && (re_opcode_t) *p != succeed_n)
4794 continue;
4796 p++;
4797 EXTRACT_NUMBER_AND_INCR (j, p);
4798 p += j;
4800 /* If what's on the stack is where we are now, pop it. */
4801 if (!FAIL_STACK_EMPTY ()
4802 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4803 fail_stack.avail--;
4805 continue;
4808 case on_failure_jump:
4809 case on_failure_keep_string_jump:
4810 handle_on_failure_jump:
4811 EXTRACT_NUMBER_AND_INCR (j, p);
4813 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4814 end of the pattern. We don't want to push such a point,
4815 since when we restore it above, entering the switch will
4816 increment `p' past the end of the pattern. We don't need
4817 to push such a point since we obviously won't find any more
4818 fastmap entries beyond `pend'. Such a pattern can match
4819 the null string, though. */
4820 if (p + j < pend)
4822 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4824 RESET_FAIL_STACK ();
4825 return -2;
4828 else
4829 bufp->can_be_null = 1;
4831 if (succeed_n_p)
4833 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4834 succeed_n_p = false;
4837 continue;
4840 case succeed_n:
4841 /* Get to the number of times to succeed. */
4842 p += OFFSET_ADDRESS_SIZE;
4844 /* Increment p past the n for when k != 0. */
4845 EXTRACT_NUMBER_AND_INCR (k, p);
4846 if (k == 0)
4848 p -= 2 * OFFSET_ADDRESS_SIZE;
4849 succeed_n_p = true; /* Spaghetti code alert. */
4850 goto handle_on_failure_jump;
4852 continue;
4855 case set_number_at:
4856 p += 2 * OFFSET_ADDRESS_SIZE;
4857 continue;
4860 case start_memory:
4861 case stop_memory:
4862 p += 2;
4863 continue;
4866 default:
4867 abort (); /* We have listed all the cases. */
4868 } /* switch *p++ */
4870 /* Getting here means we have found the possible starting
4871 characters for one path of the pattern -- and that the empty
4872 string does not match. We need not follow this path further.
4873 Instead, look at the next alternative (remembered on the
4874 stack), or quit if no more. The test at the top of the loop
4875 does these things. */
4876 path_can_be_null = false;
4877 p = pend;
4878 } /* while p */
4880 /* Set `can_be_null' for the last path (also the first path, if the
4881 pattern is empty). */
4882 bufp->can_be_null |= path_can_be_null;
4884 done:
4885 RESET_FAIL_STACK ();
4886 return 0;
4887 } /* re_compile_fastmap */
4888 #ifdef _LIBC
4889 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4890 #endif
4892 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4893 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4894 this memory for recording register information. STARTS and ENDS
4895 must be allocated using the malloc library routine, and must each
4896 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4898 If NUM_REGS == 0, then subsequent matches should allocate their own
4899 register data.
4901 Unless this function is called, the first search or match using
4902 PATTERN_BUFFER will allocate its own register data, without
4903 freeing the old data. */
4905 void
4906 re_set_registers (bufp, regs, num_regs, starts, ends)
4907 struct re_pattern_buffer *bufp;
4908 struct re_registers *regs;
4909 unsigned num_regs;
4910 regoff_t *starts, *ends;
4912 if (num_regs)
4914 bufp->regs_allocated = REGS_REALLOCATE;
4915 regs->num_regs = num_regs;
4916 regs->start = starts;
4917 regs->end = ends;
4919 else
4921 bufp->regs_allocated = REGS_UNALLOCATED;
4922 regs->num_regs = 0;
4923 regs->start = regs->end = (regoff_t *) 0;
4926 #ifdef _LIBC
4927 weak_alias (__re_set_registers, re_set_registers)
4928 #endif
4930 /* Searching routines. */
4932 /* Like re_search_2, below, but only one string is specified, and
4933 doesn't let you say where to stop matching. */
4936 re_search (bufp, string, size, startpos, range, regs)
4937 struct re_pattern_buffer *bufp;
4938 const char *string;
4939 int size, startpos, range;
4940 struct re_registers *regs;
4942 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4943 regs, size);
4945 #ifdef _LIBC
4946 weak_alias (__re_search, re_search)
4947 #endif
4950 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4951 virtual concatenation of STRING1 and STRING2, starting first at index
4952 STARTPOS, then at STARTPOS + 1, and so on.
4954 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4956 RANGE is how far to scan while trying to match. RANGE = 0 means try
4957 only at STARTPOS; in general, the last start tried is STARTPOS +
4958 RANGE.
4960 In REGS, return the indices of the virtual concatenation of STRING1
4961 and STRING2 that matched the entire BUFP->buffer and its contained
4962 subexpressions.
4964 Do not consider matching one past the index STOP in the virtual
4965 concatenation of STRING1 and STRING2.
4967 We return either the position in the strings at which the match was
4968 found, -1 if no match, or -2 if error (such as failure
4969 stack overflow). */
4972 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
4973 struct re_pattern_buffer *bufp;
4974 const char *string1, *string2;
4975 int size1, size2;
4976 int startpos;
4977 int range;
4978 struct re_registers *regs;
4979 int stop;
4981 int val;
4982 register char *fastmap = bufp->fastmap;
4983 register RE_TRANSLATE_TYPE translate = bufp->translate;
4984 int total_size = size1 + size2;
4985 int endpos = startpos + range;
4987 /* Check for out-of-range STARTPOS. */
4988 if (startpos < 0 || startpos > total_size)
4989 return -1;
4991 /* Fix up RANGE if it might eventually take us outside
4992 the virtual concatenation of STRING1 and STRING2.
4993 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4994 if (endpos < 0)
4995 range = 0 - startpos;
4996 else if (endpos > total_size)
4997 range = total_size - startpos;
4999 /* If the search isn't to be a backwards one, don't waste time in a
5000 search for a pattern that must be anchored. */
5001 if (bufp->used > 0 && range > 0
5002 && ((re_opcode_t) bufp->buffer[0] == begbuf
5003 /* `begline' is like `begbuf' if it cannot match at newlines. */
5004 || ((re_opcode_t) bufp->buffer[0] == begline
5005 && !bufp->newline_anchor)))
5007 if (startpos > 0)
5008 return -1;
5009 else
5010 range = 1;
5013 #ifdef emacs
5014 /* In a forward search for something that starts with \=.
5015 don't keep searching past point. */
5016 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5018 range = PT - startpos;
5019 if (range <= 0)
5020 return -1;
5022 #endif /* emacs */
5024 /* Update the fastmap now if not correct already. */
5025 if (fastmap && !bufp->fastmap_accurate)
5026 if (re_compile_fastmap (bufp) == -2)
5027 return -2;
5029 /* Loop through the string, looking for a place to start matching. */
5030 for (;;)
5032 /* If a fastmap is supplied, skip quickly over characters that
5033 cannot be the start of a match. If the pattern can match the
5034 null string, however, we don't need to skip characters; we want
5035 the first null string. */
5036 if (fastmap && startpos < total_size && !bufp->can_be_null)
5038 if (range > 0) /* Searching forwards. */
5040 register const char *d;
5041 register int lim = 0;
5042 int irange = range;
5044 if (startpos < size1 && startpos + range >= size1)
5045 lim = range - (size1 - startpos);
5047 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5049 /* Written out as an if-else to avoid testing `translate'
5050 inside the loop. */
5051 if (translate)
5052 while (range > lim
5053 && !fastmap[(unsigned char)
5054 translate[(unsigned char) *d++]])
5055 range--;
5056 else
5057 while (range > lim && !fastmap[(unsigned char) *d++])
5058 range--;
5060 startpos += irange - range;
5062 else /* Searching backwards. */
5064 register CHAR_TYPE c = (size1 == 0 || startpos >= size1
5065 ? string2[startpos - size1]
5066 : string1[startpos]);
5068 if (!fastmap[(unsigned char) TRANSLATE (c)])
5069 goto advance;
5073 /* If can't match the null string, and that's all we have left, fail. */
5074 if (range >= 0 && startpos == total_size && fastmap
5075 && !bufp->can_be_null)
5076 return -1;
5078 val = re_match_2_internal (bufp, string1, size1, string2, size2,
5079 startpos, regs, stop);
5080 #ifndef REGEX_MALLOC
5081 # ifdef C_ALLOCA
5082 alloca (0);
5083 # endif
5084 #endif
5086 if (val >= 0)
5087 return startpos;
5089 if (val == -2)
5090 return -2;
5092 advance:
5093 if (!range)
5094 break;
5095 else if (range > 0)
5097 range--;
5098 startpos++;
5100 else
5102 range++;
5103 startpos--;
5106 return -1;
5107 } /* re_search_2 */
5108 #ifdef _LIBC
5109 weak_alias (__re_search_2, re_search_2)
5110 #endif
5112 #ifdef MBS_SUPPORT
5113 /* This converts PTR, a pointer into one of the search wchar_t strings
5114 `string1' and `string2' into an multibyte string offset from the
5115 beginning of that string. We use mbs_offset to optimize.
5116 See convert_mbs_to_wcs. */
5117 # define POINTER_TO_OFFSET(ptr) \
5118 (FIRST_STRING_P (ptr) \
5119 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5120 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5121 + csize1)))
5122 #else
5123 /* This converts PTR, a pointer into one of the search strings `string1'
5124 and `string2' into an offset from the beginning of that string. */
5125 # define POINTER_TO_OFFSET(ptr) \
5126 (FIRST_STRING_P (ptr) \
5127 ? ((regoff_t) ((ptr) - string1)) \
5128 : ((regoff_t) ((ptr) - string2 + size1)))
5129 #endif /* MBS_SUPPORT */
5131 /* Macros for dealing with the split strings in re_match_2. */
5133 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5135 /* Call before fetching a character with *d. This switches over to
5136 string2 if necessary. */
5137 #define PREFETCH() \
5138 while (d == dend) \
5140 /* End of string2 => fail. */ \
5141 if (dend == end_match_2) \
5142 goto fail; \
5143 /* End of string1 => advance to string2. */ \
5144 d = string2; \
5145 dend = end_match_2; \
5149 /* Test if at very beginning or at very end of the virtual concatenation
5150 of `string1' and `string2'. If only one string, it's `string2'. */
5151 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5152 #define AT_STRINGS_END(d) ((d) == end2)
5155 /* Test if D points to a character which is word-constituent. We have
5156 two special cases to check for: if past the end of string1, look at
5157 the first character in string2; and if before the beginning of
5158 string2, look at the last character in string1. */
5159 #ifdef MBS_SUPPORT
5160 /* Use internationalized API instead of SYNTAX. */
5161 # define WORDCHAR_P(d) \
5162 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5163 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5164 #else
5165 # define WORDCHAR_P(d) \
5166 (SYNTAX ((d) == end1 ? *string2 \
5167 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5168 == Sword)
5169 #endif /* MBS_SUPPORT */
5171 /* Disabled due to a compiler bug -- see comment at case wordbound */
5172 #if 0
5173 /* Test if the character before D and the one at D differ with respect
5174 to being word-constituent. */
5175 #define AT_WORD_BOUNDARY(d) \
5176 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5177 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5178 #endif
5180 /* Free everything we malloc. */
5181 #ifdef MATCH_MAY_ALLOCATE
5182 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5183 # ifdef MBS_SUPPORT
5184 # define FREE_VARIABLES() \
5185 do { \
5186 REGEX_FREE_STACK (fail_stack.stack); \
5187 FREE_VAR (regstart); \
5188 FREE_VAR (regend); \
5189 FREE_VAR (old_regstart); \
5190 FREE_VAR (old_regend); \
5191 FREE_VAR (best_regstart); \
5192 FREE_VAR (best_regend); \
5193 FREE_VAR (reg_info); \
5194 FREE_VAR (reg_dummy); \
5195 FREE_VAR (reg_info_dummy); \
5196 FREE_VAR (string1); \
5197 FREE_VAR (string2); \
5198 FREE_VAR (mbs_offset1); \
5199 FREE_VAR (mbs_offset2); \
5200 } while (0)
5201 # else /* not MBS_SUPPORT */
5202 # define FREE_VARIABLES() \
5203 do { \
5204 REGEX_FREE_STACK (fail_stack.stack); \
5205 FREE_VAR (regstart); \
5206 FREE_VAR (regend); \
5207 FREE_VAR (old_regstart); \
5208 FREE_VAR (old_regend); \
5209 FREE_VAR (best_regstart); \
5210 FREE_VAR (best_regend); \
5211 FREE_VAR (reg_info); \
5212 FREE_VAR (reg_dummy); \
5213 FREE_VAR (reg_info_dummy); \
5214 } while (0)
5215 # endif /* MBS_SUPPORT */
5216 #else
5217 # define FREE_VAR(var) if (var) free (var); var = NULL
5218 # ifdef MBS_SUPPORT
5219 # define FREE_VARIABLES() \
5220 do { \
5221 FREE_VAR (string1); \
5222 FREE_VAR (string2); \
5223 FREE_VAR (mbs_offset1); \
5224 FREE_VAR (mbs_offset2); \
5225 } while (0)
5226 # else
5227 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5228 # endif /* MBS_SUPPORT */
5229 #endif /* not MATCH_MAY_ALLOCATE */
5231 /* These values must meet several constraints. They must not be valid
5232 register values; since we have a limit of 255 registers (because
5233 we use only one byte in the pattern for the register number), we can
5234 use numbers larger than 255. They must differ by 1, because of
5235 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5236 be larger than the value for the highest register, so we do not try
5237 to actually save any registers when none are active. */
5238 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5239 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5241 /* Matching routines. */
5243 #ifndef emacs /* Emacs never uses this. */
5244 /* re_match is like re_match_2 except it takes only a single string. */
5247 re_match (bufp, string, size, pos, regs)
5248 struct re_pattern_buffer *bufp;
5249 const char *string;
5250 int size, pos;
5251 struct re_registers *regs;
5253 int result = re_match_2_internal (bufp, NULL, 0, string, size,
5254 pos, regs, size);
5255 # ifndef REGEX_MALLOC
5256 # ifdef C_ALLOCA
5257 alloca (0);
5258 # endif
5259 # endif
5260 return result;
5262 # ifdef _LIBC
5263 weak_alias (__re_match, re_match)
5264 # endif
5265 #endif /* not emacs */
5267 static boolean group_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5268 US_CHAR_TYPE *end,
5269 register_info_type *reg_info));
5270 static boolean alt_match_null_string_p _RE_ARGS ((US_CHAR_TYPE *p,
5271 US_CHAR_TYPE *end,
5272 register_info_type *reg_info));
5273 static boolean common_op_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5274 US_CHAR_TYPE *end,
5275 register_info_type *reg_info));
5276 static int bcmp_translate _RE_ARGS ((const CHAR_TYPE *s1, const CHAR_TYPE *s2,
5277 int len, char *translate));
5279 /* re_match_2 matches the compiled pattern in BUFP against the
5280 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5281 and SIZE2, respectively). We start matching at POS, and stop
5282 matching at STOP.
5284 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5285 store offsets for the substring each group matched in REGS. See the
5286 documentation for exactly how many groups we fill.
5288 We return -1 if no match, -2 if an internal error (such as the
5289 failure stack overflowing). Otherwise, we return the length of the
5290 matched substring. */
5293 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5294 struct re_pattern_buffer *bufp;
5295 const char *string1, *string2;
5296 int size1, size2;
5297 int pos;
5298 struct re_registers *regs;
5299 int stop;
5301 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
5302 pos, regs, stop);
5303 #ifndef REGEX_MALLOC
5304 # ifdef C_ALLOCA
5305 alloca (0);
5306 # endif
5307 #endif
5308 return result;
5310 #ifdef _LIBC
5311 weak_alias (__re_match_2, re_match_2)
5312 #endif
5314 #ifdef MBS_SUPPORT
5316 static int count_mbs_length PARAMS ((int *, int));
5318 /* This check the substring (from 0, to length) of the multibyte string,
5319 to which offset_buffer correspond. And count how many wchar_t_characters
5320 the substring occupy. We use offset_buffer to optimization.
5321 See convert_mbs_to_wcs. */
5323 static int
5324 count_mbs_length(offset_buffer, length)
5325 int *offset_buffer;
5326 int length;
5328 int wcs_size;
5330 /* Check whether the size is valid. */
5331 if (length < 0)
5332 return -1;
5334 if (offset_buffer == NULL)
5335 return 0;
5337 for (wcs_size = 0 ; offset_buffer[wcs_size] != -1 ; wcs_size++)
5339 if (offset_buffer[wcs_size] == length)
5340 return wcs_size;
5341 if (offset_buffer[wcs_size] > length)
5342 /* It is a fragment of a wide character. */
5343 return -1;
5346 /* We reached at the sentinel. */
5347 return -1;
5349 #endif /* MBS_SUPPORT */
5351 /* This is a separate function so that we can force an alloca cleanup
5352 afterwards. */
5353 static int
5354 #ifdef MBS_SUPPORT
5355 re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos, regs, stop)
5356 struct re_pattern_buffer *bufp;
5357 const char *cstring1, *cstring2;
5358 int csize1, csize2;
5359 #else
5360 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
5361 struct re_pattern_buffer *bufp;
5362 const char *string1, *string2;
5363 int size1, size2;
5364 #endif
5365 int pos;
5366 struct re_registers *regs;
5367 int stop;
5369 /* General temporaries. */
5370 int mcnt;
5371 US_CHAR_TYPE *p1;
5372 #ifdef MBS_SUPPORT
5373 /* We need wchar_t* buffers correspond to string1, string2. */
5374 CHAR_TYPE *string1 = NULL, *string2 = NULL;
5375 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5376 int size1 = 0, size2 = 0;
5377 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5378 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5379 /* They hold whether each wchar_t is binary data or not. */
5380 char *is_binary = NULL;
5381 #endif /* MBS_SUPPORT */
5383 /* Just past the end of the corresponding string. */
5384 const CHAR_TYPE *end1, *end2;
5386 /* Pointers into string1 and string2, just past the last characters in
5387 each to consider matching. */
5388 const CHAR_TYPE *end_match_1, *end_match_2;
5390 /* Where we are in the data, and the end of the current string. */
5391 const CHAR_TYPE *d, *dend;
5393 /* Where we are in the pattern, and the end of the pattern. */
5394 #ifdef MBS_SUPPORT
5395 US_CHAR_TYPE *pattern, *p;
5396 register US_CHAR_TYPE *pend;
5397 #else
5398 US_CHAR_TYPE *p = bufp->buffer;
5399 register US_CHAR_TYPE *pend = p + bufp->used;
5400 #endif /* MBS_SUPPORT */
5402 /* Mark the opcode just after a start_memory, so we can test for an
5403 empty subpattern when we get to the stop_memory. */
5404 US_CHAR_TYPE *just_past_start_mem = 0;
5406 /* We use this to map every character in the string. */
5407 RE_TRANSLATE_TYPE translate = bufp->translate;
5409 /* Failure point stack. Each place that can handle a failure further
5410 down the line pushes a failure point on this stack. It consists of
5411 restart, regend, and reg_info for all registers corresponding to
5412 the subexpressions we're currently inside, plus the number of such
5413 registers, and, finally, two char *'s. The first char * is where
5414 to resume scanning the pattern; the second one is where to resume
5415 scanning the strings. If the latter is zero, the failure point is
5416 a ``dummy''; if a failure happens and the failure point is a dummy,
5417 it gets discarded and the next next one is tried. */
5418 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5419 fail_stack_type fail_stack;
5420 #endif
5421 #ifdef DEBUG
5422 static unsigned failure_id;
5423 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5424 #endif
5426 #ifdef REL_ALLOC
5427 /* This holds the pointer to the failure stack, when
5428 it is allocated relocatably. */
5429 fail_stack_elt_t *failure_stack_ptr;
5430 #endif
5432 /* We fill all the registers internally, independent of what we
5433 return, for use in backreferences. The number here includes
5434 an element for register zero. */
5435 size_t num_regs = bufp->re_nsub + 1;
5437 /* The currently active registers. */
5438 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5439 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5441 /* Information on the contents of registers. These are pointers into
5442 the input strings; they record just what was matched (on this
5443 attempt) by a subexpression part of the pattern, that is, the
5444 regnum-th regstart pointer points to where in the pattern we began
5445 matching and the regnum-th regend points to right after where we
5446 stopped matching the regnum-th subexpression. (The zeroth register
5447 keeps track of what the whole pattern matches.) */
5448 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5449 const CHAR_TYPE **regstart, **regend;
5450 #endif
5452 /* If a group that's operated upon by a repetition operator fails to
5453 match anything, then the register for its start will need to be
5454 restored because it will have been set to wherever in the string we
5455 are when we last see its open-group operator. Similarly for a
5456 register's end. */
5457 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5458 const CHAR_TYPE **old_regstart, **old_regend;
5459 #endif
5461 /* The is_active field of reg_info helps us keep track of which (possibly
5462 nested) subexpressions we are currently in. The matched_something
5463 field of reg_info[reg_num] helps us tell whether or not we have
5464 matched any of the pattern so far this time through the reg_num-th
5465 subexpression. These two fields get reset each time through any
5466 loop their register is in. */
5467 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5468 register_info_type *reg_info;
5469 #endif
5471 /* The following record the register info as found in the above
5472 variables when we find a match better than any we've seen before.
5473 This happens as we backtrack through the failure points, which in
5474 turn happens only if we have not yet matched the entire string. */
5475 unsigned best_regs_set = false;
5476 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5477 const CHAR_TYPE **best_regstart, **best_regend;
5478 #endif
5480 /* Logically, this is `best_regend[0]'. But we don't want to have to
5481 allocate space for that if we're not allocating space for anything
5482 else (see below). Also, we never need info about register 0 for
5483 any of the other register vectors, and it seems rather a kludge to
5484 treat `best_regend' differently than the rest. So we keep track of
5485 the end of the best match so far in a separate variable. We
5486 initialize this to NULL so that when we backtrack the first time
5487 and need to test it, it's not garbage. */
5488 const CHAR_TYPE *match_end = NULL;
5490 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5491 int set_regs_matched_done = 0;
5493 /* Used when we pop values we don't care about. */
5494 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5495 const CHAR_TYPE **reg_dummy;
5496 register_info_type *reg_info_dummy;
5497 #endif
5499 #ifdef DEBUG
5500 /* Counts the total number of registers pushed. */
5501 unsigned num_regs_pushed = 0;
5502 #endif
5504 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5506 INIT_FAIL_STACK ();
5508 #ifdef MATCH_MAY_ALLOCATE
5509 /* Do not bother to initialize all the register variables if there are
5510 no groups in the pattern, as it takes a fair amount of time. If
5511 there are groups, we include space for register 0 (the whole
5512 pattern), even though we never use it, since it simplifies the
5513 array indexing. We should fix this. */
5514 if (bufp->re_nsub)
5516 regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5517 regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5518 old_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5519 old_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5520 best_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5521 best_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5522 reg_info = REGEX_TALLOC (num_regs, register_info_type);
5523 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5524 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
5526 if (!(regstart && regend && old_regstart && old_regend && reg_info
5527 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5529 FREE_VARIABLES ();
5530 return -2;
5533 else
5535 /* We must initialize all our variables to NULL, so that
5536 `FREE_VARIABLES' doesn't try to free them. */
5537 regstart = regend = old_regstart = old_regend = best_regstart
5538 = best_regend = reg_dummy = NULL;
5539 reg_info = reg_info_dummy = (register_info_type *) NULL;
5541 #endif /* MATCH_MAY_ALLOCATE */
5543 /* The starting position is bogus. */
5544 #ifdef MBS_SUPPORT
5545 if (pos < 0 || pos > csize1 + csize2)
5546 #else
5547 if (pos < 0 || pos > size1 + size2)
5548 #endif
5550 FREE_VARIABLES ();
5551 return -1;
5554 #ifdef MBS_SUPPORT
5555 /* Allocate wchar_t array for string1 and string2 and
5556 fill them with converted string. */
5557 if (csize1 != 0)
5559 string1 = REGEX_TALLOC (csize1 + 1, CHAR_TYPE);
5560 mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5561 is_binary = REGEX_TALLOC (csize1 + 1, char);
5562 if (!string1 || !mbs_offset1 || !is_binary)
5564 FREE_VAR (string1);
5565 FREE_VAR (mbs_offset1);
5566 FREE_VAR (is_binary);
5567 return -2;
5569 size1 = convert_mbs_to_wcs(string1, cstring1, csize1,
5570 mbs_offset1, is_binary);
5571 string1[size1] = L'\0'; /* for a sentinel */
5572 FREE_VAR (is_binary);
5574 if (csize2 != 0)
5576 string2 = REGEX_TALLOC (csize2 + 1, CHAR_TYPE);
5577 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5578 is_binary = REGEX_TALLOC (csize2 + 1, char);
5579 if (!string2 || !mbs_offset2 || !is_binary)
5581 FREE_VAR (string1);
5582 FREE_VAR (mbs_offset1);
5583 FREE_VAR (string2);
5584 FREE_VAR (mbs_offset2);
5585 FREE_VAR (is_binary);
5586 return -2;
5588 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5589 mbs_offset2, is_binary);
5590 string2[size2] = L'\0'; /* for a sentinel */
5591 FREE_VAR (is_binary);
5594 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5595 pattern to (char*) in regex_compile. */
5596 p = pattern = (CHAR_TYPE*)bufp->buffer;
5597 pend = (CHAR_TYPE*)(bufp->buffer + bufp->used);
5599 #endif /* MBS_SUPPORT */
5601 /* Initialize subexpression text positions to -1 to mark ones that no
5602 start_memory/stop_memory has been seen for. Also initialize the
5603 register information struct. */
5604 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5606 regstart[mcnt] = regend[mcnt]
5607 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5609 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5610 IS_ACTIVE (reg_info[mcnt]) = 0;
5611 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5612 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5615 /* We move `string1' into `string2' if the latter's empty -- but not if
5616 `string1' is null. */
5617 if (size2 == 0 && string1 != NULL)
5619 string2 = string1;
5620 size2 = size1;
5621 string1 = 0;
5622 size1 = 0;
5624 end1 = string1 + size1;
5625 end2 = string2 + size2;
5627 /* Compute where to stop matching, within the two strings. */
5628 #ifdef MBS_SUPPORT
5629 if (stop <= csize1)
5631 mcnt = count_mbs_length(mbs_offset1, stop);
5632 end_match_1 = string1 + mcnt;
5633 end_match_2 = string2;
5635 else
5637 end_match_1 = end1;
5638 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5639 end_match_2 = string2 + mcnt;
5641 if (mcnt < 0)
5642 { /* count_mbs_length return error. */
5643 FREE_VARIABLES ();
5644 return -1;
5646 #else
5647 if (stop <= size1)
5649 end_match_1 = string1 + stop;
5650 end_match_2 = string2;
5652 else
5654 end_match_1 = end1;
5655 end_match_2 = string2 + stop - size1;
5657 #endif /* MBS_SUPPORT */
5659 /* `p' scans through the pattern as `d' scans through the data.
5660 `dend' is the end of the input string that `d' points within. `d'
5661 is advanced into the following input string whenever necessary, but
5662 this happens before fetching; therefore, at the beginning of the
5663 loop, `d' can be pointing at the end of a string, but it cannot
5664 equal `string2'. */
5665 #ifdef MBS_SUPPORT
5666 if (size1 > 0 && pos <= csize1)
5668 mcnt = count_mbs_length(mbs_offset1, pos);
5669 d = string1 + mcnt;
5670 dend = end_match_1;
5672 else
5674 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5675 d = string2 + mcnt;
5676 dend = end_match_2;
5679 if (mcnt < 0)
5680 { /* count_mbs_length return error. */
5681 FREE_VARIABLES ();
5682 return -1;
5684 #else
5685 if (size1 > 0 && pos <= size1)
5687 d = string1 + pos;
5688 dend = end_match_1;
5690 else
5692 d = string2 + pos - size1;
5693 dend = end_match_2;
5695 #endif /* MBS_SUPPORT */
5697 DEBUG_PRINT1 ("The compiled pattern is:\n");
5698 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5699 DEBUG_PRINT1 ("The string to match is: `");
5700 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5701 DEBUG_PRINT1 ("'\n");
5703 /* This loops over pattern commands. It exits by returning from the
5704 function if the match is complete, or it drops through if the match
5705 fails at this starting point in the input data. */
5706 for (;;)
5708 #ifdef _LIBC
5709 DEBUG_PRINT2 ("\n%p: ", p);
5710 #else
5711 DEBUG_PRINT2 ("\n0x%x: ", p);
5712 #endif
5714 if (p == pend)
5715 { /* End of pattern means we might have succeeded. */
5716 DEBUG_PRINT1 ("end of pattern ... ");
5718 /* If we haven't matched the entire string, and we want the
5719 longest match, try backtracking. */
5720 if (d != end_match_2)
5722 /* 1 if this match ends in the same string (string1 or string2)
5723 as the best previous match. */
5724 boolean same_str_p = (FIRST_STRING_P (match_end)
5725 == MATCHING_IN_FIRST_STRING);
5726 /* 1 if this match is the best seen so far. */
5727 boolean best_match_p;
5729 /* AIX compiler got confused when this was combined
5730 with the previous declaration. */
5731 if (same_str_p)
5732 best_match_p = d > match_end;
5733 else
5734 best_match_p = !MATCHING_IN_FIRST_STRING;
5736 DEBUG_PRINT1 ("backtracking.\n");
5738 if (!FAIL_STACK_EMPTY ())
5739 { /* More failure points to try. */
5741 /* If exceeds best match so far, save it. */
5742 if (!best_regs_set || best_match_p)
5744 best_regs_set = true;
5745 match_end = d;
5747 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5749 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5751 best_regstart[mcnt] = regstart[mcnt];
5752 best_regend[mcnt] = regend[mcnt];
5755 goto fail;
5758 /* If no failure points, don't restore garbage. And if
5759 last match is real best match, don't restore second
5760 best one. */
5761 else if (best_regs_set && !best_match_p)
5763 restore_best_regs:
5764 /* Restore best match. It may happen that `dend ==
5765 end_match_1' while the restored d is in string2.
5766 For example, the pattern `x.*y.*z' against the
5767 strings `x-' and `y-z-', if the two strings are
5768 not consecutive in memory. */
5769 DEBUG_PRINT1 ("Restoring best registers.\n");
5771 d = match_end;
5772 dend = ((d >= string1 && d <= end1)
5773 ? end_match_1 : end_match_2);
5775 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5777 regstart[mcnt] = best_regstart[mcnt];
5778 regend[mcnt] = best_regend[mcnt];
5781 } /* d != end_match_2 */
5783 succeed_label:
5784 DEBUG_PRINT1 ("Accepting match.\n");
5785 /* If caller wants register contents data back, do it. */
5786 if (regs && !bufp->no_sub)
5788 /* Have the register data arrays been allocated? */
5789 if (bufp->regs_allocated == REGS_UNALLOCATED)
5790 { /* No. So allocate them with malloc. We need one
5791 extra element beyond `num_regs' for the `-1' marker
5792 GNU code uses. */
5793 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5794 regs->start = TALLOC (regs->num_regs, regoff_t);
5795 regs->end = TALLOC (regs->num_regs, regoff_t);
5796 if (regs->start == NULL || regs->end == NULL)
5798 FREE_VARIABLES ();
5799 return -2;
5801 bufp->regs_allocated = REGS_REALLOCATE;
5803 else if (bufp->regs_allocated == REGS_REALLOCATE)
5804 { /* Yes. If we need more elements than were already
5805 allocated, reallocate them. If we need fewer, just
5806 leave it alone. */
5807 if (regs->num_regs < num_regs + 1)
5809 regs->num_regs = num_regs + 1;
5810 RETALLOC (regs->start, regs->num_regs, regoff_t);
5811 RETALLOC (regs->end, regs->num_regs, regoff_t);
5812 if (regs->start == NULL || regs->end == NULL)
5814 FREE_VARIABLES ();
5815 return -2;
5819 else
5821 /* These braces fend off a "empty body in an else-statement"
5822 warning under GCC when assert expands to nothing. */
5823 assert (bufp->regs_allocated == REGS_FIXED);
5826 /* Convert the pointer data in `regstart' and `regend' to
5827 indices. Register zero has to be set differently,
5828 since we haven't kept track of any info for it. */
5829 if (regs->num_regs > 0)
5831 regs->start[0] = pos;
5832 #ifdef MBS_SUPPORT
5833 if (MATCHING_IN_FIRST_STRING)
5834 regs->end[0] = mbs_offset1 != NULL ?
5835 mbs_offset1[d-string1] : 0;
5836 else
5837 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
5838 mbs_offset2[d-string2] : 0);
5839 #else
5840 regs->end[0] = (MATCHING_IN_FIRST_STRING
5841 ? ((regoff_t) (d - string1))
5842 : ((regoff_t) (d - string2 + size1)));
5843 #endif /* MBS_SUPPORT */
5846 /* Go through the first `min (num_regs, regs->num_regs)'
5847 registers, since that is all we initialized. */
5848 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
5849 mcnt++)
5851 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
5852 regs->start[mcnt] = regs->end[mcnt] = -1;
5853 else
5855 regs->start[mcnt]
5856 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
5857 regs->end[mcnt]
5858 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
5862 /* If the regs structure we return has more elements than
5863 were in the pattern, set the extra elements to -1. If
5864 we (re)allocated the registers, this is the case,
5865 because we always allocate enough to have at least one
5866 -1 at the end. */
5867 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
5868 regs->start[mcnt] = regs->end[mcnt] = -1;
5869 } /* regs && !bufp->no_sub */
5871 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5872 nfailure_points_pushed, nfailure_points_popped,
5873 nfailure_points_pushed - nfailure_points_popped);
5874 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5876 #ifdef MBS_SUPPORT
5877 if (MATCHING_IN_FIRST_STRING)
5878 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
5879 else
5880 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
5881 csize1;
5882 mcnt -= pos;
5883 #else
5884 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
5885 ? string1
5886 : string2 - size1);
5887 #endif /* MBS_SUPPORT */
5889 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5891 FREE_VARIABLES ();
5892 return mcnt;
5895 /* Otherwise match next pattern command. */
5896 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5898 /* Ignore these. Used to ignore the n of succeed_n's which
5899 currently have n == 0. */
5900 case no_op:
5901 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5902 break;
5904 case succeed:
5905 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5906 goto succeed_label;
5908 /* Match the next n pattern characters exactly. The following
5909 byte in the pattern defines n, and the n bytes after that
5910 are the characters to match. */
5911 case exactn:
5912 #ifdef MBS_SUPPORT
5913 case exactn_bin:
5914 #endif
5915 mcnt = *p++;
5916 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5918 /* This is written out as an if-else so we don't waste time
5919 testing `translate' inside the loop. */
5920 if (translate)
5924 PREFETCH ();
5925 #ifdef MBS_SUPPORT
5926 if (*d <= 0xff)
5928 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5929 != (US_CHAR_TYPE) *p++)
5930 goto fail;
5932 else
5934 if (*d++ != (CHAR_TYPE) *p++)
5935 goto fail;
5937 #else
5938 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5939 != (US_CHAR_TYPE) *p++)
5940 goto fail;
5941 #endif /* MBS_SUPPORT */
5943 while (--mcnt);
5945 else
5949 PREFETCH ();
5950 if (*d++ != (CHAR_TYPE) *p++) goto fail;
5952 while (--mcnt);
5954 SET_REGS_MATCHED ();
5955 break;
5958 /* Match any character except possibly a newline or a null. */
5959 case anychar:
5960 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5962 PREFETCH ();
5964 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
5965 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
5966 goto fail;
5968 SET_REGS_MATCHED ();
5969 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
5970 d++;
5971 break;
5974 case charset:
5975 case charset_not:
5977 register US_CHAR_TYPE c;
5978 #ifdef MBS_SUPPORT
5979 unsigned int i, char_class_length, coll_symbol_length,
5980 equiv_class_length, ranges_length, chars_length, length;
5981 CHAR_TYPE *workp, *workp2, *charset_top;
5982 #define WORK_BUFFER_SIZE 128
5983 CHAR_TYPE str_buf[WORK_BUFFER_SIZE];
5984 # ifdef _LIBC
5985 uint32_t nrules;
5986 # endif /* _LIBC */
5987 #endif /* MBS_SUPPORT */
5988 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5990 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5991 PREFETCH ();
5992 c = TRANSLATE (*d); /* The character to match. */
5993 #ifdef MBS_SUPPORT
5994 # ifdef _LIBC
5995 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
5996 # endif /* _LIBC */
5997 charset_top = p - 1;
5998 char_class_length = *p++;
5999 coll_symbol_length = *p++;
6000 equiv_class_length = *p++;
6001 ranges_length = *p++;
6002 chars_length = *p++;
6003 /* p points charset[6], so the address of the next instruction
6004 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
6005 where l=length of char_classes, m=length of collating_symbol,
6006 n=equivalence_class, o=length of char_range,
6007 p'=length of character. */
6008 workp = p;
6009 /* Update p to indicate the next instruction. */
6010 p += char_class_length + coll_symbol_length+ equiv_class_length +
6011 2*ranges_length + chars_length;
6013 /* match with char_class? */
6014 for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
6016 wctype_t wctype;
6017 uintptr_t alignedp = ((uintptr_t)workp
6018 + __alignof__(wctype_t) - 1)
6019 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6020 wctype = *((wctype_t*)alignedp);
6021 workp += CHAR_CLASS_SIZE;
6022 if (iswctype((wint_t)c, wctype))
6023 goto char_set_matched;
6026 /* match with collating_symbol? */
6027 # ifdef _LIBC
6028 if (nrules != 0)
6030 const unsigned char *extra = (const unsigned char *)
6031 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6033 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6034 workp++)
6036 int32_t *wextra;
6037 wextra = (int32_t*)(extra + *workp++);
6038 for (i = 0; i < *wextra; ++i)
6039 if (TRANSLATE(d[i]) != wextra[1 + i])
6040 break;
6042 if (i == *wextra)
6044 /* Update d, however d will be incremented at
6045 char_set_matched:, we decrement d here. */
6046 d += i - 1;
6047 goto char_set_matched;
6051 else /* (nrules == 0) */
6052 # endif
6053 /* If we can't look up collation data, we use wcscoll
6054 instead. */
6056 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6058 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6059 length = wcslen(workp);
6061 /* If wcscoll(the collating symbol, whole string) > 0,
6062 any substring of the string never match with the
6063 collating symbol. */
6064 if (wcscoll(workp, d) > 0)
6066 workp += length + 1;
6067 continue;
6070 /* First, we compare the collating symbol with
6071 the first character of the string.
6072 If it don't match, we add the next character to
6073 the compare buffer in turn. */
6074 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6076 int match;
6077 if (d == dend)
6079 if (dend == end_match_2)
6080 break;
6081 d = string2;
6082 dend = end_match_2;
6085 /* add next character to the compare buffer. */
6086 str_buf[i] = TRANSLATE(*d);
6087 str_buf[i+1] = '\0';
6089 match = wcscoll(workp, str_buf);
6090 if (match == 0)
6091 goto char_set_matched;
6093 if (match < 0)
6094 /* (str_buf > workp) indicate (str_buf + X > workp),
6095 because for all X (str_buf + X > str_buf).
6096 So we don't need continue this loop. */
6097 break;
6099 /* Otherwise(str_buf < workp),
6100 (str_buf+next_character) may equals (workp).
6101 So we continue this loop. */
6103 /* not matched */
6104 d = backup_d;
6105 dend = backup_dend;
6106 workp += length + 1;
6109 /* match with equivalence_class? */
6110 # ifdef _LIBC
6111 if (nrules != 0)
6113 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6114 /* Try to match the equivalence class against
6115 those known to the collate implementation. */
6116 const int32_t *table;
6117 const int32_t *weights;
6118 const int32_t *extra;
6119 const int32_t *indirect;
6120 int32_t idx, idx2;
6121 wint_t *cp;
6122 size_t len;
6124 /* This #include defines a local function! */
6125 # include <locale/weightwc.h>
6127 table = (const int32_t *)
6128 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6129 weights = (const wint_t *)
6130 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6131 extra = (const wint_t *)
6132 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6133 indirect = (const int32_t *)
6134 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6136 /* Write 1 collating element to str_buf, and
6137 get its index. */
6138 idx2 = 0;
6140 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6142 cp = (wint_t*)str_buf;
6143 if (d == dend)
6145 if (dend == end_match_2)
6146 break;
6147 d = string2;
6148 dend = end_match_2;
6150 str_buf[i] = TRANSLATE(*(d+i));
6151 str_buf[i+1] = '\0'; /* sentinel */
6152 idx2 = findidx ((const wint_t**)&cp);
6155 /* Update d, however d will be incremented at
6156 char_set_matched:, we decrement d here. */
6157 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6158 if (d >= dend)
6160 if (dend == end_match_2)
6161 d = dend;
6162 else
6164 d = string2;
6165 dend = end_match_2;
6169 len = weights[idx2];
6171 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6172 workp++)
6174 idx = (int32_t)*workp;
6175 /* We already checked idx != 0 in regex_compile. */
6177 if (idx2 != 0 && len == weights[idx])
6179 int cnt = 0;
6180 while (cnt < len && (weights[idx + 1 + cnt]
6181 == weights[idx2 + 1 + cnt]))
6182 ++cnt;
6184 if (cnt == len)
6185 goto char_set_matched;
6188 /* not matched */
6189 d = backup_d;
6190 dend = backup_dend;
6192 else /* (nrules == 0) */
6193 # endif
6194 /* If we can't look up collation data, we use wcscoll
6195 instead. */
6197 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6199 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6200 length = wcslen(workp);
6202 /* If wcscoll(the collating symbol, whole string) > 0,
6203 any substring of the string never match with the
6204 collating symbol. */
6205 if (wcscoll(workp, d) > 0)
6207 workp += length + 1;
6208 break;
6211 /* First, we compare the equivalence class with
6212 the first character of the string.
6213 If it don't match, we add the next character to
6214 the compare buffer in turn. */
6215 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6217 int match;
6218 if (d == dend)
6220 if (dend == end_match_2)
6221 break;
6222 d = string2;
6223 dend = end_match_2;
6226 /* add next character to the compare buffer. */
6227 str_buf[i] = TRANSLATE(*d);
6228 str_buf[i+1] = '\0';
6230 match = wcscoll(workp, str_buf);
6232 if (match == 0)
6233 goto char_set_matched;
6235 if (match < 0)
6236 /* (str_buf > workp) indicate (str_buf + X > workp),
6237 because for all X (str_buf + X > str_buf).
6238 So we don't need continue this loop. */
6239 break;
6241 /* Otherwise(str_buf < workp),
6242 (str_buf+next_character) may equals (workp).
6243 So we continue this loop. */
6245 /* not matched */
6246 d = backup_d;
6247 dend = backup_dend;
6248 workp += length + 1;
6252 /* match with char_range? */
6253 #ifdef _LIBC
6254 if (nrules != 0)
6256 uint32_t collseqval;
6257 const char *collseq = (const char *)
6258 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6260 collseqval = collseq_table_lookup (collseq, c);
6262 for (; workp < p - chars_length ;)
6264 uint32_t start_val, end_val;
6266 /* We already compute the collation sequence value
6267 of the characters (or collating symbols). */
6268 start_val = (uint32_t) *workp++; /* range_start */
6269 end_val = (uint32_t) *workp++; /* range_end */
6271 if (start_val <= collseqval && collseqval <= end_val)
6272 goto char_set_matched;
6275 else
6276 #endif
6278 /* We set range_start_char at str_buf[0], range_end_char
6279 at str_buf[4], and compared char at str_buf[2]. */
6280 str_buf[1] = 0;
6281 str_buf[2] = c;
6282 str_buf[3] = 0;
6283 str_buf[5] = 0;
6284 for (; workp < p - chars_length ;)
6286 wchar_t *range_start_char, *range_end_char;
6288 /* match if (range_start_char <= c <= range_end_char). */
6290 /* If range_start(or end) < 0, we assume -range_start(end)
6291 is the offset of the collating symbol which is specified
6292 as the character of the range start(end). */
6294 /* range_start */
6295 if (*workp < 0)
6296 range_start_char = charset_top - (*workp++);
6297 else
6299 str_buf[0] = *workp++;
6300 range_start_char = str_buf;
6303 /* range_end */
6304 if (*workp < 0)
6305 range_end_char = charset_top - (*workp++);
6306 else
6308 str_buf[4] = *workp++;
6309 range_end_char = str_buf + 4;
6312 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6313 wcscoll(str_buf+2, range_end_char) <= 0)
6315 goto char_set_matched;
6319 /* match with char? */
6320 for (; workp < p ; workp++)
6321 if (c == *workp)
6322 goto char_set_matched;
6324 not = !not;
6326 char_set_matched:
6327 if (not) goto fail;
6328 #else
6329 /* Cast to `unsigned' instead of `unsigned char' in case the
6330 bit list is a full 32 bytes long. */
6331 if (c < (unsigned) (*p * BYTEWIDTH)
6332 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6333 not = !not;
6335 p += 1 + *p;
6337 if (!not) goto fail;
6338 #undef WORK_BUFFER_SIZE
6339 #endif /* MBS_SUPPORT */
6340 SET_REGS_MATCHED ();
6341 d++;
6342 break;
6346 /* The beginning of a group is represented by start_memory.
6347 The arguments are the register number in the next byte, and the
6348 number of groups inner to this one in the next. The text
6349 matched within the group is recorded (in the internal
6350 registers data structure) under the register number. */
6351 case start_memory:
6352 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6353 (long int) *p, (long int) p[1]);
6355 /* Find out if this group can match the empty string. */
6356 p1 = p; /* To send to group_match_null_string_p. */
6358 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6359 REG_MATCH_NULL_STRING_P (reg_info[*p])
6360 = group_match_null_string_p (&p1, pend, reg_info);
6362 /* Save the position in the string where we were the last time
6363 we were at this open-group operator in case the group is
6364 operated upon by a repetition operator, e.g., with `(a*)*b'
6365 against `ab'; then we want to ignore where we are now in
6366 the string in case this attempt to match fails. */
6367 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6368 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6369 : regstart[*p];
6370 DEBUG_PRINT2 (" old_regstart: %d\n",
6371 POINTER_TO_OFFSET (old_regstart[*p]));
6373 regstart[*p] = d;
6374 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6376 IS_ACTIVE (reg_info[*p]) = 1;
6377 MATCHED_SOMETHING (reg_info[*p]) = 0;
6379 /* Clear this whenever we change the register activity status. */
6380 set_regs_matched_done = 0;
6382 /* This is the new highest active register. */
6383 highest_active_reg = *p;
6385 /* If nothing was active before, this is the new lowest active
6386 register. */
6387 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6388 lowest_active_reg = *p;
6390 /* Move past the register number and inner group count. */
6391 p += 2;
6392 just_past_start_mem = p;
6394 break;
6397 /* The stop_memory opcode represents the end of a group. Its
6398 arguments are the same as start_memory's: the register
6399 number, and the number of inner groups. */
6400 case stop_memory:
6401 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6402 (long int) *p, (long int) p[1]);
6404 /* We need to save the string position the last time we were at
6405 this close-group operator in case the group is operated
6406 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6407 against `aba'; then we want to ignore where we are now in
6408 the string in case this attempt to match fails. */
6409 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6410 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6411 : regend[*p];
6412 DEBUG_PRINT2 (" old_regend: %d\n",
6413 POINTER_TO_OFFSET (old_regend[*p]));
6415 regend[*p] = d;
6416 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6418 /* This register isn't active anymore. */
6419 IS_ACTIVE (reg_info[*p]) = 0;
6421 /* Clear this whenever we change the register activity status. */
6422 set_regs_matched_done = 0;
6424 /* If this was the only register active, nothing is active
6425 anymore. */
6426 if (lowest_active_reg == highest_active_reg)
6428 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6429 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6431 else
6432 { /* We must scan for the new highest active register, since
6433 it isn't necessarily one less than now: consider
6434 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6435 new highest active register is 1. */
6436 US_CHAR_TYPE r = *p - 1;
6437 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6438 r--;
6440 /* If we end up at register zero, that means that we saved
6441 the registers as the result of an `on_failure_jump', not
6442 a `start_memory', and we jumped to past the innermost
6443 `stop_memory'. For example, in ((.)*) we save
6444 registers 1 and 2 as a result of the *, but when we pop
6445 back to the second ), we are at the stop_memory 1.
6446 Thus, nothing is active. */
6447 if (r == 0)
6449 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6450 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6452 else
6453 highest_active_reg = r;
6456 /* If just failed to match something this time around with a
6457 group that's operated on by a repetition operator, try to
6458 force exit from the ``loop'', and restore the register
6459 information for this group that we had before trying this
6460 last match. */
6461 if ((!MATCHED_SOMETHING (reg_info[*p])
6462 || just_past_start_mem == p - 1)
6463 && (p + 2) < pend)
6465 boolean is_a_jump_n = false;
6467 p1 = p + 2;
6468 mcnt = 0;
6469 switch ((re_opcode_t) *p1++)
6471 case jump_n:
6472 is_a_jump_n = true;
6473 case pop_failure_jump:
6474 case maybe_pop_jump:
6475 case jump:
6476 case dummy_failure_jump:
6477 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6478 if (is_a_jump_n)
6479 p1 += OFFSET_ADDRESS_SIZE;
6480 break;
6482 default:
6483 /* do nothing */ ;
6485 p1 += mcnt;
6487 /* If the next operation is a jump backwards in the pattern
6488 to an on_failure_jump right before the start_memory
6489 corresponding to this stop_memory, exit from the loop
6490 by forcing a failure after pushing on the stack the
6491 on_failure_jump's jump in the pattern, and d. */
6492 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6493 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6494 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6496 /* If this group ever matched anything, then restore
6497 what its registers were before trying this last
6498 failed match, e.g., with `(a*)*b' against `ab' for
6499 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6500 against `aba' for regend[3].
6502 Also restore the registers for inner groups for,
6503 e.g., `((a*)(b*))*' against `aba' (register 3 would
6504 otherwise get trashed). */
6506 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6508 unsigned r;
6510 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6512 /* Restore this and inner groups' (if any) registers. */
6513 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6514 r++)
6516 regstart[r] = old_regstart[r];
6518 /* xx why this test? */
6519 if (old_regend[r] >= regstart[r])
6520 regend[r] = old_regend[r];
6523 p1++;
6524 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6525 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6527 goto fail;
6531 /* Move past the register number and the inner group count. */
6532 p += 2;
6533 break;
6536 /* \<digit> has been turned into a `duplicate' command which is
6537 followed by the numeric value of <digit> as the register number. */
6538 case duplicate:
6540 register const CHAR_TYPE *d2, *dend2;
6541 int regno = *p++; /* Get which register to match against. */
6542 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6544 /* Can't back reference a group which we've never matched. */
6545 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6546 goto fail;
6548 /* Where in input to try to start matching. */
6549 d2 = regstart[regno];
6551 /* Where to stop matching; if both the place to start and
6552 the place to stop matching are in the same string, then
6553 set to the place to stop, otherwise, for now have to use
6554 the end of the first string. */
6556 dend2 = ((FIRST_STRING_P (regstart[regno])
6557 == FIRST_STRING_P (regend[regno]))
6558 ? regend[regno] : end_match_1);
6559 for (;;)
6561 /* If necessary, advance to next segment in register
6562 contents. */
6563 while (d2 == dend2)
6565 if (dend2 == end_match_2) break;
6566 if (dend2 == regend[regno]) break;
6568 /* End of string1 => advance to string2. */
6569 d2 = string2;
6570 dend2 = regend[regno];
6572 /* At end of register contents => success */
6573 if (d2 == dend2) break;
6575 /* If necessary, advance to next segment in data. */
6576 PREFETCH ();
6578 /* How many characters left in this segment to match. */
6579 mcnt = dend - d;
6581 /* Want how many consecutive characters we can match in
6582 one shot, so, if necessary, adjust the count. */
6583 if (mcnt > dend2 - d2)
6584 mcnt = dend2 - d2;
6586 /* Compare that many; failure if mismatch, else move
6587 past them. */
6588 if (translate
6589 ? bcmp_translate (d, d2, mcnt, translate)
6590 : memcmp (d, d2, mcnt*sizeof(US_CHAR_TYPE)))
6591 goto fail;
6592 d += mcnt, d2 += mcnt;
6594 /* Do this because we've match some characters. */
6595 SET_REGS_MATCHED ();
6598 break;
6601 /* begline matches the empty string at the beginning of the string
6602 (unless `not_bol' is set in `bufp'), and, if
6603 `newline_anchor' is set, after newlines. */
6604 case begline:
6605 DEBUG_PRINT1 ("EXECUTING begline.\n");
6607 if (AT_STRINGS_BEG (d))
6609 if (!bufp->not_bol) break;
6611 else if (d[-1] == '\n' && bufp->newline_anchor)
6613 break;
6615 /* In all other cases, we fail. */
6616 goto fail;
6619 /* endline is the dual of begline. */
6620 case endline:
6621 DEBUG_PRINT1 ("EXECUTING endline.\n");
6623 if (AT_STRINGS_END (d))
6625 if (!bufp->not_eol) break;
6628 /* We have to ``prefetch'' the next character. */
6629 else if ((d == end1 ? *string2 : *d) == '\n'
6630 && bufp->newline_anchor)
6632 break;
6634 goto fail;
6637 /* Match at the very beginning of the data. */
6638 case begbuf:
6639 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6640 if (AT_STRINGS_BEG (d))
6641 break;
6642 goto fail;
6645 /* Match at the very end of the data. */
6646 case endbuf:
6647 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6648 if (AT_STRINGS_END (d))
6649 break;
6650 goto fail;
6653 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6654 pushes NULL as the value for the string on the stack. Then
6655 `pop_failure_point' will keep the current value for the
6656 string, instead of restoring it. To see why, consider
6657 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6658 then the . fails against the \n. But the next thing we want
6659 to do is match the \n against the \n; if we restored the
6660 string value, we would be back at the foo.
6662 Because this is used only in specific cases, we don't need to
6663 check all the things that `on_failure_jump' does, to make
6664 sure the right things get saved on the stack. Hence we don't
6665 share its code. The only reason to push anything on the
6666 stack at all is that otherwise we would have to change
6667 `anychar's code to do something besides goto fail in this
6668 case; that seems worse than this. */
6669 case on_failure_keep_string_jump:
6670 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6672 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6673 #ifdef _LIBC
6674 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6675 #else
6676 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6677 #endif
6679 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6680 break;
6683 /* Uses of on_failure_jump:
6685 Each alternative starts with an on_failure_jump that points
6686 to the beginning of the next alternative. Each alternative
6687 except the last ends with a jump that in effect jumps past
6688 the rest of the alternatives. (They really jump to the
6689 ending jump of the following alternative, because tensioning
6690 these jumps is a hassle.)
6692 Repeats start with an on_failure_jump that points past both
6693 the repetition text and either the following jump or
6694 pop_failure_jump back to this on_failure_jump. */
6695 case on_failure_jump:
6696 on_failure:
6697 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6699 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6700 #ifdef _LIBC
6701 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6702 #else
6703 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6704 #endif
6706 /* If this on_failure_jump comes right before a group (i.e.,
6707 the original * applied to a group), save the information
6708 for that group and all inner ones, so that if we fail back
6709 to this point, the group's information will be correct.
6710 For example, in \(a*\)*\1, we need the preceding group,
6711 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6713 /* We can't use `p' to check ahead because we push
6714 a failure point to `p + mcnt' after we do this. */
6715 p1 = p;
6717 /* We need to skip no_op's before we look for the
6718 start_memory in case this on_failure_jump is happening as
6719 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6720 against aba. */
6721 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6722 p1++;
6724 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6726 /* We have a new highest active register now. This will
6727 get reset at the start_memory we are about to get to,
6728 but we will have saved all the registers relevant to
6729 this repetition op, as described above. */
6730 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6731 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6732 lowest_active_reg = *(p1 + 1);
6735 DEBUG_PRINT1 (":\n");
6736 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6737 break;
6740 /* A smart repeat ends with `maybe_pop_jump'.
6741 We change it to either `pop_failure_jump' or `jump'. */
6742 case maybe_pop_jump:
6743 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6744 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6746 register US_CHAR_TYPE *p2 = p;
6748 /* Compare the beginning of the repeat with what in the
6749 pattern follows its end. If we can establish that there
6750 is nothing that they would both match, i.e., that we
6751 would have to backtrack because of (as in, e.g., `a*a')
6752 then we can change to pop_failure_jump, because we'll
6753 never have to backtrack.
6755 This is not true in the case of alternatives: in
6756 `(a|ab)*' we do need to backtrack to the `ab' alternative
6757 (e.g., if the string was `ab'). But instead of trying to
6758 detect that here, the alternative has put on a dummy
6759 failure point which is what we will end up popping. */
6761 /* Skip over open/close-group commands.
6762 If what follows this loop is a ...+ construct,
6763 look at what begins its body, since we will have to
6764 match at least one of that. */
6765 while (1)
6767 if (p2 + 2 < pend
6768 && ((re_opcode_t) *p2 == stop_memory
6769 || (re_opcode_t) *p2 == start_memory))
6770 p2 += 3;
6771 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6772 && (re_opcode_t) *p2 == dummy_failure_jump)
6773 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6774 else
6775 break;
6778 p1 = p + mcnt;
6779 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
6780 to the `maybe_finalize_jump' of this case. Examine what
6781 follows. */
6783 /* If we're at the end of the pattern, we can change. */
6784 if (p2 == pend)
6786 /* Consider what happens when matching ":\(.*\)"
6787 against ":/". I don't really understand this code
6788 yet. */
6789 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6790 pop_failure_jump;
6791 DEBUG_PRINT1
6792 (" End of pattern: change to `pop_failure_jump'.\n");
6795 else if ((re_opcode_t) *p2 == exactn
6796 #ifdef MBS_SUPPORT
6797 || (re_opcode_t) *p2 == exactn_bin
6798 #endif
6799 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
6801 register US_CHAR_TYPE c
6802 = *p2 == (US_CHAR_TYPE) endline ? '\n' : p2[2];
6804 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
6805 #ifdef MBS_SUPPORT
6806 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
6807 #endif
6808 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
6810 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6811 pop_failure_jump;
6812 #ifdef MBS_SUPPORT
6813 if (MB_CUR_MAX != 1)
6814 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
6815 (wint_t) c,
6816 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
6817 else
6818 #endif
6819 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
6820 (char) c,
6821 (char) p1[3+OFFSET_ADDRESS_SIZE]);
6824 #ifndef MBS_SUPPORT
6825 else if ((re_opcode_t) p1[3] == charset
6826 || (re_opcode_t) p1[3] == charset_not)
6828 int not = (re_opcode_t) p1[3] == charset_not;
6830 if (c < (unsigned) (p1[4] * BYTEWIDTH)
6831 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6832 not = !not;
6834 /* `not' is equal to 1 if c would match, which means
6835 that we can't change to pop_failure_jump. */
6836 if (!not)
6838 p[-3] = (unsigned char) pop_failure_jump;
6839 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6842 #endif /* not MBS_SUPPORT */
6844 #ifndef MBS_SUPPORT
6845 else if ((re_opcode_t) *p2 == charset)
6847 /* We win if the first character of the loop is not part
6848 of the charset. */
6849 if ((re_opcode_t) p1[3] == exactn
6850 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
6851 && (p2[2 + p1[5] / BYTEWIDTH]
6852 & (1 << (p1[5] % BYTEWIDTH)))))
6854 p[-3] = (unsigned char) pop_failure_jump;
6855 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6858 else if ((re_opcode_t) p1[3] == charset_not)
6860 int idx;
6861 /* We win if the charset_not inside the loop
6862 lists every character listed in the charset after. */
6863 for (idx = 0; idx < (int) p2[1]; idx++)
6864 if (! (p2[2 + idx] == 0
6865 || (idx < (int) p1[4]
6866 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
6867 break;
6869 if (idx == p2[1])
6871 p[-3] = (unsigned char) pop_failure_jump;
6872 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6875 else if ((re_opcode_t) p1[3] == charset)
6877 int idx;
6878 /* We win if the charset inside the loop
6879 has no overlap with the one after the loop. */
6880 for (idx = 0;
6881 idx < (int) p2[1] && idx < (int) p1[4];
6882 idx++)
6883 if ((p2[2 + idx] & p1[5 + idx]) != 0)
6884 break;
6886 if (idx == p2[1] || idx == p1[4])
6888 p[-3] = (unsigned char) pop_failure_jump;
6889 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6893 #endif /* not MBS_SUPPORT */
6895 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
6896 if ((re_opcode_t) p[-1] != pop_failure_jump)
6898 p[-1] = (US_CHAR_TYPE) jump;
6899 DEBUG_PRINT1 (" Match => jump.\n");
6900 goto unconditional_jump;
6902 /* Note fall through. */
6905 /* The end of a simple repeat has a pop_failure_jump back to
6906 its matching on_failure_jump, where the latter will push a
6907 failure point. The pop_failure_jump takes off failure
6908 points put on by this pop_failure_jump's matching
6909 on_failure_jump; we got through the pattern to here from the
6910 matching on_failure_jump, so didn't fail. */
6911 case pop_failure_jump:
6913 /* We need to pass separate storage for the lowest and
6914 highest registers, even though we don't care about the
6915 actual values. Otherwise, we will restore only one
6916 register from the stack, since lowest will == highest in
6917 `pop_failure_point'. */
6918 active_reg_t dummy_low_reg, dummy_high_reg;
6919 US_CHAR_TYPE *pdummy = NULL;
6920 const CHAR_TYPE *sdummy = NULL;
6922 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
6923 POP_FAILURE_POINT (sdummy, pdummy,
6924 dummy_low_reg, dummy_high_reg,
6925 reg_dummy, reg_dummy, reg_info_dummy);
6927 /* Note fall through. */
6929 unconditional_jump:
6930 #ifdef _LIBC
6931 DEBUG_PRINT2 ("\n%p: ", p);
6932 #else
6933 DEBUG_PRINT2 ("\n0x%x: ", p);
6934 #endif
6935 /* Note fall through. */
6937 /* Unconditionally jump (without popping any failure points). */
6938 case jump:
6939 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
6940 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
6941 p += mcnt; /* Do the jump. */
6942 #ifdef _LIBC
6943 DEBUG_PRINT2 ("(to %p).\n", p);
6944 #else
6945 DEBUG_PRINT2 ("(to 0x%x).\n", p);
6946 #endif
6947 break;
6950 /* We need this opcode so we can detect where alternatives end
6951 in `group_match_null_string_p' et al. */
6952 case jump_past_alt:
6953 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
6954 goto unconditional_jump;
6957 /* Normally, the on_failure_jump pushes a failure point, which
6958 then gets popped at pop_failure_jump. We will end up at
6959 pop_failure_jump, also, and with a pattern of, say, `a+', we
6960 are skipping over the on_failure_jump, so we have to push
6961 something meaningless for pop_failure_jump to pop. */
6962 case dummy_failure_jump:
6963 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
6964 /* It doesn't matter what we push for the string here. What
6965 the code at `fail' tests is the value for the pattern. */
6966 PUSH_FAILURE_POINT (NULL, NULL, -2);
6967 goto unconditional_jump;
6970 /* At the end of an alternative, we need to push a dummy failure
6971 point in case we are followed by a `pop_failure_jump', because
6972 we don't want the failure point for the alternative to be
6973 popped. For example, matching `(a|ab)*' against `aab'
6974 requires that we match the `ab' alternative. */
6975 case push_dummy_failure:
6976 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
6977 /* See comments just above at `dummy_failure_jump' about the
6978 two zeroes. */
6979 PUSH_FAILURE_POINT (NULL, NULL, -2);
6980 break;
6982 /* Have to succeed matching what follows at least n times.
6983 After that, handle like `on_failure_jump'. */
6984 case succeed_n:
6985 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6986 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
6988 assert (mcnt >= 0);
6989 /* Originally, this is how many times we HAVE to succeed. */
6990 if (mcnt > 0)
6992 mcnt--;
6993 p += OFFSET_ADDRESS_SIZE;
6994 STORE_NUMBER_AND_INCR (p, mcnt);
6995 #ifdef _LIBC
6996 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
6997 , mcnt);
6998 #else
6999 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
7000 , mcnt);
7001 #endif
7003 else if (mcnt == 0)
7005 #ifdef _LIBC
7006 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
7007 p + OFFSET_ADDRESS_SIZE);
7008 #else
7009 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
7010 p + OFFSET_ADDRESS_SIZE);
7011 #endif /* _LIBC */
7013 #ifdef MBS_SUPPORT
7014 p[1] = (US_CHAR_TYPE) no_op;
7015 #else
7016 p[2] = (US_CHAR_TYPE) no_op;
7017 p[3] = (US_CHAR_TYPE) no_op;
7018 #endif /* MBS_SUPPORT */
7019 goto on_failure;
7021 break;
7023 case jump_n:
7024 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7025 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7027 /* Originally, this is how many times we CAN jump. */
7028 if (mcnt)
7030 mcnt--;
7031 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7033 #ifdef _LIBC
7034 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7035 mcnt);
7036 #else
7037 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7038 mcnt);
7039 #endif /* _LIBC */
7040 goto unconditional_jump;
7042 /* If don't have to jump any more, skip over the rest of command. */
7043 else
7044 p += 2 * OFFSET_ADDRESS_SIZE;
7045 break;
7047 case set_number_at:
7049 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7051 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7052 p1 = p + mcnt;
7053 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7054 #ifdef _LIBC
7055 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7056 #else
7057 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7058 #endif
7059 STORE_NUMBER (p1, mcnt);
7060 break;
7063 #if 0
7064 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7065 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7066 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7067 macro and introducing temporary variables works around the bug. */
7069 case wordbound:
7070 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7071 if (AT_WORD_BOUNDARY (d))
7072 break;
7073 goto fail;
7075 case notwordbound:
7076 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7077 if (AT_WORD_BOUNDARY (d))
7078 goto fail;
7079 break;
7080 #else
7081 case wordbound:
7083 boolean prevchar, thischar;
7085 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7086 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7087 break;
7089 prevchar = WORDCHAR_P (d - 1);
7090 thischar = WORDCHAR_P (d);
7091 if (prevchar != thischar)
7092 break;
7093 goto fail;
7096 case notwordbound:
7098 boolean prevchar, thischar;
7100 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7101 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7102 goto fail;
7104 prevchar = WORDCHAR_P (d - 1);
7105 thischar = WORDCHAR_P (d);
7106 if (prevchar != thischar)
7107 goto fail;
7108 break;
7110 #endif
7112 case wordbeg:
7113 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7114 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7115 break;
7116 goto fail;
7118 case wordend:
7119 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7120 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7121 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
7122 break;
7123 goto fail;
7125 #ifdef emacs
7126 case before_dot:
7127 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7128 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7129 goto fail;
7130 break;
7132 case at_dot:
7133 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7134 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7135 goto fail;
7136 break;
7138 case after_dot:
7139 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7140 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7141 goto fail;
7142 break;
7144 case syntaxspec:
7145 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7146 mcnt = *p++;
7147 goto matchsyntax;
7149 case wordchar:
7150 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7151 mcnt = (int) Sword;
7152 matchsyntax:
7153 PREFETCH ();
7154 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7155 d++;
7156 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7157 goto fail;
7158 SET_REGS_MATCHED ();
7159 break;
7161 case notsyntaxspec:
7162 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7163 mcnt = *p++;
7164 goto matchnotsyntax;
7166 case notwordchar:
7167 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7168 mcnt = (int) Sword;
7169 matchnotsyntax:
7170 PREFETCH ();
7171 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7172 d++;
7173 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7174 goto fail;
7175 SET_REGS_MATCHED ();
7176 break;
7178 #else /* not emacs */
7179 case wordchar:
7180 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7181 PREFETCH ();
7182 if (!WORDCHAR_P (d))
7183 goto fail;
7184 SET_REGS_MATCHED ();
7185 d++;
7186 break;
7188 case notwordchar:
7189 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7190 PREFETCH ();
7191 if (WORDCHAR_P (d))
7192 goto fail;
7193 SET_REGS_MATCHED ();
7194 d++;
7195 break;
7196 #endif /* not emacs */
7198 default:
7199 abort ();
7201 continue; /* Successfully executed one pattern command; keep going. */
7204 /* We goto here if a matching operation fails. */
7205 fail:
7206 if (!FAIL_STACK_EMPTY ())
7207 { /* A restart point is known. Restore to that state. */
7208 DEBUG_PRINT1 ("\nFAIL:\n");
7209 POP_FAILURE_POINT (d, p,
7210 lowest_active_reg, highest_active_reg,
7211 regstart, regend, reg_info);
7213 /* If this failure point is a dummy, try the next one. */
7214 if (!p)
7215 goto fail;
7217 /* If we failed to the end of the pattern, don't examine *p. */
7218 assert (p <= pend);
7219 if (p < pend)
7221 boolean is_a_jump_n = false;
7223 /* If failed to a backwards jump that's part of a repetition
7224 loop, need to pop this failure point and use the next one. */
7225 switch ((re_opcode_t) *p)
7227 case jump_n:
7228 is_a_jump_n = true;
7229 case maybe_pop_jump:
7230 case pop_failure_jump:
7231 case jump:
7232 p1 = p + 1;
7233 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7234 p1 += mcnt;
7236 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7237 || (!is_a_jump_n
7238 && (re_opcode_t) *p1 == on_failure_jump))
7239 goto fail;
7240 break;
7241 default:
7242 /* do nothing */ ;
7246 if (d >= string1 && d <= end1)
7247 dend = end_match_1;
7249 else
7250 break; /* Matching at this starting point really fails. */
7251 } /* for (;;) */
7253 if (best_regs_set)
7254 goto restore_best_regs;
7256 FREE_VARIABLES ();
7258 return -1; /* Failure to match. */
7259 } /* re_match_2 */
7261 /* Subroutine definitions for re_match_2. */
7264 /* We are passed P pointing to a register number after a start_memory.
7266 Return true if the pattern up to the corresponding stop_memory can
7267 match the empty string, and false otherwise.
7269 If we find the matching stop_memory, sets P to point to one past its number.
7270 Otherwise, sets P to an undefined byte less than or equal to END.
7272 We don't handle duplicates properly (yet). */
7274 static boolean
7275 group_match_null_string_p (p, end, reg_info)
7276 US_CHAR_TYPE **p, *end;
7277 register_info_type *reg_info;
7279 int mcnt;
7280 /* Point to after the args to the start_memory. */
7281 US_CHAR_TYPE *p1 = *p + 2;
7283 while (p1 < end)
7285 /* Skip over opcodes that can match nothing, and return true or
7286 false, as appropriate, when we get to one that can't, or to the
7287 matching stop_memory. */
7289 switch ((re_opcode_t) *p1)
7291 /* Could be either a loop or a series of alternatives. */
7292 case on_failure_jump:
7293 p1++;
7294 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7296 /* If the next operation is not a jump backwards in the
7297 pattern. */
7299 if (mcnt >= 0)
7301 /* Go through the on_failure_jumps of the alternatives,
7302 seeing if any of the alternatives cannot match nothing.
7303 The last alternative starts with only a jump,
7304 whereas the rest start with on_failure_jump and end
7305 with a jump, e.g., here is the pattern for `a|b|c':
7307 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7308 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7309 /exactn/1/c
7311 So, we have to first go through the first (n-1)
7312 alternatives and then deal with the last one separately. */
7315 /* Deal with the first (n-1) alternatives, which start
7316 with an on_failure_jump (see above) that jumps to right
7317 past a jump_past_alt. */
7319 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7320 jump_past_alt)
7322 /* `mcnt' holds how many bytes long the alternative
7323 is, including the ending `jump_past_alt' and
7324 its number. */
7326 if (!alt_match_null_string_p (p1, p1 + mcnt -
7327 (1 + OFFSET_ADDRESS_SIZE),
7328 reg_info))
7329 return false;
7331 /* Move to right after this alternative, including the
7332 jump_past_alt. */
7333 p1 += mcnt;
7335 /* Break if it's the beginning of an n-th alternative
7336 that doesn't begin with an on_failure_jump. */
7337 if ((re_opcode_t) *p1 != on_failure_jump)
7338 break;
7340 /* Still have to check that it's not an n-th
7341 alternative that starts with an on_failure_jump. */
7342 p1++;
7343 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7344 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7345 jump_past_alt)
7347 /* Get to the beginning of the n-th alternative. */
7348 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7349 break;
7353 /* Deal with the last alternative: go back and get number
7354 of the `jump_past_alt' just before it. `mcnt' contains
7355 the length of the alternative. */
7356 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7358 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
7359 return false;
7361 p1 += mcnt; /* Get past the n-th alternative. */
7362 } /* if mcnt > 0 */
7363 break;
7366 case stop_memory:
7367 assert (p1[1] == **p);
7368 *p = p1 + 2;
7369 return true;
7372 default:
7373 if (!common_op_match_null_string_p (&p1, end, reg_info))
7374 return false;
7376 } /* while p1 < end */
7378 return false;
7379 } /* group_match_null_string_p */
7382 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7383 It expects P to be the first byte of a single alternative and END one
7384 byte past the last. The alternative can contain groups. */
7386 static boolean
7387 alt_match_null_string_p (p, end, reg_info)
7388 US_CHAR_TYPE *p, *end;
7389 register_info_type *reg_info;
7391 int mcnt;
7392 US_CHAR_TYPE *p1 = p;
7394 while (p1 < end)
7396 /* Skip over opcodes that can match nothing, and break when we get
7397 to one that can't. */
7399 switch ((re_opcode_t) *p1)
7401 /* It's a loop. */
7402 case on_failure_jump:
7403 p1++;
7404 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7405 p1 += mcnt;
7406 break;
7408 default:
7409 if (!common_op_match_null_string_p (&p1, end, reg_info))
7410 return false;
7412 } /* while p1 < end */
7414 return true;
7415 } /* alt_match_null_string_p */
7418 /* Deals with the ops common to group_match_null_string_p and
7419 alt_match_null_string_p.
7421 Sets P to one after the op and its arguments, if any. */
7423 static boolean
7424 common_op_match_null_string_p (p, end, reg_info)
7425 US_CHAR_TYPE **p, *end;
7426 register_info_type *reg_info;
7428 int mcnt;
7429 boolean ret;
7430 int reg_no;
7431 US_CHAR_TYPE *p1 = *p;
7433 switch ((re_opcode_t) *p1++)
7435 case no_op:
7436 case begline:
7437 case endline:
7438 case begbuf:
7439 case endbuf:
7440 case wordbeg:
7441 case wordend:
7442 case wordbound:
7443 case notwordbound:
7444 #ifdef emacs
7445 case before_dot:
7446 case at_dot:
7447 case after_dot:
7448 #endif
7449 break;
7451 case start_memory:
7452 reg_no = *p1;
7453 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7454 ret = group_match_null_string_p (&p1, end, reg_info);
7456 /* Have to set this here in case we're checking a group which
7457 contains a group and a back reference to it. */
7459 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7460 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7462 if (!ret)
7463 return false;
7464 break;
7466 /* If this is an optimized succeed_n for zero times, make the jump. */
7467 case jump:
7468 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7469 if (mcnt >= 0)
7470 p1 += mcnt;
7471 else
7472 return false;
7473 break;
7475 case succeed_n:
7476 /* Get to the number of times to succeed. */
7477 p1 += OFFSET_ADDRESS_SIZE;
7478 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7480 if (mcnt == 0)
7482 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7483 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7484 p1 += mcnt;
7486 else
7487 return false;
7488 break;
7490 case duplicate:
7491 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7492 return false;
7493 break;
7495 case set_number_at:
7496 p1 += 2 * OFFSET_ADDRESS_SIZE;
7498 default:
7499 /* All other opcodes mean we cannot match the empty string. */
7500 return false;
7503 *p = p1;
7504 return true;
7505 } /* common_op_match_null_string_p */
7508 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7509 bytes; nonzero otherwise. */
7511 static int
7512 bcmp_translate (s1, s2, len, translate)
7513 const CHAR_TYPE *s1, *s2;
7514 register int len;
7515 RE_TRANSLATE_TYPE translate;
7517 register const US_CHAR_TYPE *p1 = (const US_CHAR_TYPE *) s1;
7518 register const US_CHAR_TYPE *p2 = (const US_CHAR_TYPE *) s2;
7519 while (len)
7521 #ifdef MBS_SUPPORT
7522 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7523 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7524 return 1;
7525 #else
7526 if (translate[*p1++] != translate[*p2++]) return 1;
7527 #endif /* MBS_SUPPORT */
7528 len--;
7530 return 0;
7533 /* Entry points for GNU code. */
7535 /* re_compile_pattern is the GNU regular expression compiler: it
7536 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7537 Returns 0 if the pattern was valid, otherwise an error string.
7539 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7540 are set in BUFP on entry.
7542 We call regex_compile to do the actual compilation. */
7544 const char *
7545 re_compile_pattern (pattern, length, bufp)
7546 const char *pattern;
7547 size_t length;
7548 struct re_pattern_buffer *bufp;
7550 reg_errcode_t ret;
7552 /* GNU code is written to assume at least RE_NREGS registers will be set
7553 (and at least one extra will be -1). */
7554 bufp->regs_allocated = REGS_UNALLOCATED;
7556 /* And GNU code determines whether or not to get register information
7557 by passing null for the REGS argument to re_match, etc., not by
7558 setting no_sub. */
7559 bufp->no_sub = 0;
7561 /* Match anchors at newline. */
7562 bufp->newline_anchor = 1;
7564 ret = regex_compile (pattern, length, re_syntax_options, bufp);
7566 if (!ret)
7567 return NULL;
7568 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7570 #ifdef _LIBC
7571 weak_alias (__re_compile_pattern, re_compile_pattern)
7572 #endif
7574 /* Entry points compatible with 4.2 BSD regex library. We don't define
7575 them unless specifically requested. */
7577 #if defined _REGEX_RE_COMP || defined _LIBC
7579 /* BSD has one and only one pattern buffer. */
7580 static struct re_pattern_buffer re_comp_buf;
7582 char *
7583 #ifdef _LIBC
7584 /* Make these definitions weak in libc, so POSIX programs can redefine
7585 these names if they don't use our functions, and still use
7586 regcomp/regexec below without link errors. */
7587 weak_function
7588 #endif
7589 re_comp (s)
7590 const char *s;
7592 reg_errcode_t ret;
7594 if (!s)
7596 if (!re_comp_buf.buffer)
7597 return gettext ("No previous regular expression");
7598 return 0;
7601 if (!re_comp_buf.buffer)
7603 re_comp_buf.buffer = (unsigned char *) malloc (200);
7604 if (re_comp_buf.buffer == NULL)
7605 return (char *) gettext (re_error_msgid
7606 + re_error_msgid_idx[(int) REG_ESPACE]);
7607 re_comp_buf.allocated = 200;
7609 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7610 if (re_comp_buf.fastmap == NULL)
7611 return (char *) gettext (re_error_msgid
7612 + re_error_msgid_idx[(int) REG_ESPACE]);
7615 /* Since `re_exec' always passes NULL for the `regs' argument, we
7616 don't need to initialize the pattern buffer fields which affect it. */
7618 /* Match anchors at newlines. */
7619 re_comp_buf.newline_anchor = 1;
7621 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7623 if (!ret)
7624 return NULL;
7626 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7627 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7632 #ifdef _LIBC
7633 weak_function
7634 #endif
7635 re_exec (s)
7636 const char *s;
7638 const int len = strlen (s);
7639 return
7640 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7643 #endif /* _REGEX_RE_COMP */
7645 /* POSIX.2 functions. Don't define these for Emacs. */
7647 #ifndef emacs
7649 /* regcomp takes a regular expression as a string and compiles it.
7651 PREG is a regex_t *. We do not expect any fields to be initialized,
7652 since POSIX says we shouldn't. Thus, we set
7654 `buffer' to the compiled pattern;
7655 `used' to the length of the compiled pattern;
7656 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7657 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7658 RE_SYNTAX_POSIX_BASIC;
7659 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7660 `fastmap' to an allocated space for the fastmap;
7661 `fastmap_accurate' to zero;
7662 `re_nsub' to the number of subexpressions in PATTERN.
7664 PATTERN is the address of the pattern string.
7666 CFLAGS is a series of bits which affect compilation.
7668 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7669 use POSIX basic syntax.
7671 If REG_NEWLINE is set, then . and [^...] don't match newline.
7672 Also, regexec will try a match beginning after every newline.
7674 If REG_ICASE is set, then we considers upper- and lowercase
7675 versions of letters to be equivalent when matching.
7677 If REG_NOSUB is set, then when PREG is passed to regexec, that
7678 routine will report only success or failure, and nothing about the
7679 registers.
7681 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7682 the return codes and their meanings.) */
7685 regcomp (preg, pattern, cflags)
7686 regex_t *preg;
7687 const char *pattern;
7688 int cflags;
7690 reg_errcode_t ret;
7691 reg_syntax_t syntax
7692 = (cflags & REG_EXTENDED) ?
7693 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7695 /* regex_compile will allocate the space for the compiled pattern. */
7696 preg->buffer = 0;
7697 preg->allocated = 0;
7698 preg->used = 0;
7700 /* Try to allocate space for the fastmap. */
7701 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7703 if (cflags & REG_ICASE)
7705 unsigned i;
7707 preg->translate
7708 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7709 * sizeof (*(RE_TRANSLATE_TYPE)0));
7710 if (preg->translate == NULL)
7711 return (int) REG_ESPACE;
7713 /* Map uppercase characters to corresponding lowercase ones. */
7714 for (i = 0; i < CHAR_SET_SIZE; i++)
7715 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7717 else
7718 preg->translate = NULL;
7720 /* If REG_NEWLINE is set, newlines are treated differently. */
7721 if (cflags & REG_NEWLINE)
7722 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7723 syntax &= ~RE_DOT_NEWLINE;
7724 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7725 /* It also changes the matching behavior. */
7726 preg->newline_anchor = 1;
7728 else
7729 preg->newline_anchor = 0;
7731 preg->no_sub = !!(cflags & REG_NOSUB);
7733 /* POSIX says a null character in the pattern terminates it, so we
7734 can use strlen here in compiling the pattern. */
7735 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
7737 /* POSIX doesn't distinguish between an unmatched open-group and an
7738 unmatched close-group: both are REG_EPAREN. */
7739 if (ret == REG_ERPAREN) ret = REG_EPAREN;
7741 if (ret == REG_NOERROR && preg->fastmap)
7743 /* Compute the fastmap now, since regexec cannot modify the pattern
7744 buffer. */
7745 if (re_compile_fastmap (preg) == -2)
7747 /* Some error occurred while computing the fastmap, just forget
7748 about it. */
7749 free (preg->fastmap);
7750 preg->fastmap = NULL;
7754 return (int) ret;
7756 #ifdef _LIBC
7757 weak_alias (__regcomp, regcomp)
7758 #endif
7761 /* regexec searches for a given pattern, specified by PREG, in the
7762 string STRING.
7764 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7765 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
7766 least NMATCH elements, and we set them to the offsets of the
7767 corresponding matched substrings.
7769 EFLAGS specifies `execution flags' which affect matching: if
7770 REG_NOTBOL is set, then ^ does not match at the beginning of the
7771 string; if REG_NOTEOL is set, then $ does not match at the end.
7773 We return 0 if we find a match and REG_NOMATCH if not. */
7776 regexec (preg, string, nmatch, pmatch, eflags)
7777 const regex_t *preg;
7778 const char *string;
7779 size_t nmatch;
7780 regmatch_t pmatch[];
7781 int eflags;
7783 int ret;
7784 struct re_registers regs;
7785 regex_t private_preg;
7786 int len = strlen (string);
7787 boolean want_reg_info = !preg->no_sub && nmatch > 0;
7789 private_preg = *preg;
7791 private_preg.not_bol = !!(eflags & REG_NOTBOL);
7792 private_preg.not_eol = !!(eflags & REG_NOTEOL);
7794 /* The user has told us exactly how many registers to return
7795 information about, via `nmatch'. We have to pass that on to the
7796 matching routines. */
7797 private_preg.regs_allocated = REGS_FIXED;
7799 if (want_reg_info)
7801 regs.num_regs = nmatch;
7802 regs.start = TALLOC (nmatch * 2, regoff_t);
7803 if (regs.start == NULL)
7804 return (int) REG_NOMATCH;
7805 regs.end = regs.start + nmatch;
7808 /* Perform the searching operation. */
7809 ret = re_search (&private_preg, string, len,
7810 /* start: */ 0, /* range: */ len,
7811 want_reg_info ? &regs : (struct re_registers *) 0);
7813 /* Copy the register information to the POSIX structure. */
7814 if (want_reg_info)
7816 if (ret >= 0)
7818 unsigned r;
7820 for (r = 0; r < nmatch; r++)
7822 pmatch[r].rm_so = regs.start[r];
7823 pmatch[r].rm_eo = regs.end[r];
7827 /* If we needed the temporary register info, free the space now. */
7828 free (regs.start);
7831 /* We want zero return to mean success, unlike `re_search'. */
7832 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
7834 #ifdef _LIBC
7835 weak_alias (__regexec, regexec)
7836 #endif
7839 /* Returns a message corresponding to an error code, ERRCODE, returned
7840 from either regcomp or regexec. We don't use PREG here. */
7842 size_t
7843 regerror (errcode, preg, errbuf, errbuf_size)
7844 int errcode;
7845 const regex_t *preg;
7846 char *errbuf;
7847 size_t errbuf_size;
7849 const char *msg;
7850 size_t msg_size;
7852 if (errcode < 0
7853 || errcode >= (int) (sizeof (re_error_msgid_idx)
7854 / sizeof (re_error_msgid_idx[0])))
7855 /* Only error codes returned by the rest of the code should be passed
7856 to this routine. If we are given anything else, or if other regex
7857 code generates an invalid error code, then the program has a bug.
7858 Dump core so we can fix it. */
7859 abort ();
7861 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
7863 msg_size = strlen (msg) + 1; /* Includes the null. */
7865 if (errbuf_size != 0)
7867 if (msg_size > errbuf_size)
7869 #if defined HAVE_MEMPCPY || defined _LIBC
7870 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
7871 #else
7872 memcpy (errbuf, msg, errbuf_size - 1);
7873 errbuf[errbuf_size - 1] = 0;
7874 #endif
7876 else
7877 memcpy (errbuf, msg, msg_size);
7880 return msg_size;
7882 #ifdef _LIBC
7883 weak_alias (__regerror, regerror)
7884 #endif
7887 /* Free dynamically allocated space used by PREG. */
7889 void
7890 regfree (preg)
7891 regex_t *preg;
7893 if (preg->buffer != NULL)
7894 free (preg->buffer);
7895 preg->buffer = NULL;
7897 preg->allocated = 0;
7898 preg->used = 0;
7900 if (preg->fastmap != NULL)
7901 free (preg->fastmap);
7902 preg->fastmap = NULL;
7903 preg->fastmap_accurate = 0;
7905 if (preg->translate != NULL)
7906 free (preg->translate);
7907 preg->translate = NULL;
7909 #ifdef _LIBC
7910 weak_alias (__regfree, regfree)
7911 #endif
7913 #endif /* not emacs */