* stdlib/Makefile (tests): Don't run tst-fmtmsg when
[glibc.git] / posix / regex.c
blob2b1a62b799514e34a2b026cb39b7487f2d319263
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
294 init_syntax_once ()
296 register int c;
297 static int done = 0;
299 if (done)
300 return;
301 bzero (re_syntax_table, sizeof re_syntax_table);
303 for (c = 0; c < CHAR_SET_SIZE; ++c)
304 if (ISALNUM (c))
305 re_syntax_table[c] = Sword;
307 re_syntax_table['_'] = Sword;
309 done = 1;
312 # endif /* not SYNTAX_TABLE */
314 # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
316 #endif /* emacs */
318 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
319 use `alloca' instead of `malloc'. This is because using malloc in
320 re_search* or re_match* could cause memory leaks when C-g is used in
321 Emacs; also, malloc is slower and causes storage fragmentation. On
322 the other hand, malloc is more portable, and easier to debug.
324 Because we sometimes use alloca, some routines have to be macros,
325 not functions -- `alloca'-allocated space disappears at the end of the
326 function it is called in. */
328 #ifdef REGEX_MALLOC
330 # define REGEX_ALLOCATE malloc
331 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
332 # define REGEX_FREE free
334 #else /* not REGEX_MALLOC */
336 /* Emacs already defines alloca, sometimes. */
337 # ifndef alloca
339 /* Make alloca work the best possible way. */
340 # ifdef __GNUC__
341 # define alloca __builtin_alloca
342 # else /* not __GNUC__ */
343 # if HAVE_ALLOCA_H
344 # include <alloca.h>
345 # endif /* HAVE_ALLOCA_H */
346 # endif /* not __GNUC__ */
348 # endif /* not alloca */
350 # define REGEX_ALLOCATE alloca
352 /* Assumes a `char *destination' variable. */
353 # define REGEX_REALLOCATE(source, osize, nsize) \
354 (destination = (char *) alloca (nsize), \
355 memcpy (destination, source, osize))
357 /* No need to do anything to free, after alloca. */
358 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
360 #endif /* not REGEX_MALLOC */
362 /* Define how to allocate the failure stack. */
364 #if defined REL_ALLOC && defined REGEX_MALLOC
366 # define REGEX_ALLOCATE_STACK(size) \
367 r_alloc (&failure_stack_ptr, (size))
368 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
369 r_re_alloc (&failure_stack_ptr, (nsize))
370 # define REGEX_FREE_STACK(ptr) \
371 r_alloc_free (&failure_stack_ptr)
373 #else /* not using relocating allocator */
375 # ifdef REGEX_MALLOC
377 # define REGEX_ALLOCATE_STACK malloc
378 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
379 # define REGEX_FREE_STACK free
381 # else /* not REGEX_MALLOC */
383 # define REGEX_ALLOCATE_STACK alloca
385 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
386 REGEX_REALLOCATE (source, osize, nsize)
387 /* No need to explicitly free anything. */
388 # define REGEX_FREE_STACK(arg)
390 # endif /* not REGEX_MALLOC */
391 #endif /* not using relocating allocator */
394 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
395 `string1' or just past its end. This works if PTR is NULL, which is
396 a good thing. */
397 #define FIRST_STRING_P(ptr) \
398 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
400 /* (Re)Allocate N items of type T using malloc, or fail. */
401 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
402 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
403 #define RETALLOC_IF(addr, n, t) \
404 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
405 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
407 #define BYTEWIDTH 8 /* In bits. */
409 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
411 #undef MAX
412 #undef MIN
413 #define MAX(a, b) ((a) > (b) ? (a) : (b))
414 #define MIN(a, b) ((a) < (b) ? (a) : (b))
416 typedef char boolean;
417 #define false 0
418 #define true 1
420 static int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
421 const char *string1, int size1,
422 const char *string2, int size2,
423 int pos,
424 struct re_registers *regs,
425 int stop));
427 /* These are the command codes that appear in compiled regular
428 expressions. Some opcodes are followed by argument bytes. A
429 command code can specify any interpretation whatsoever for its
430 arguments. Zero bytes may appear in the compiled regular expression. */
432 typedef enum
434 no_op = 0,
436 /* Succeed right away--no more backtracking. */
437 succeed,
439 /* Followed by one byte giving n, then by n literal bytes. */
440 exactn,
442 #ifdef MBS_SUPPORT
443 /* Same as exactn, but contains binary data. */
444 exactn_bin,
445 #endif
447 /* Matches any (more or less) character. */
448 anychar,
450 /* Matches any one char belonging to specified set. First
451 following byte is number of bitmap bytes. Then come bytes
452 for a bitmap saying which chars are in. Bits in each byte
453 are ordered low-bit-first. A character is in the set if its
454 bit is 1. A character too large to have a bit in the map is
455 automatically not in the set. */
456 /* ifdef MBS_SUPPORT, following element is length of character
457 classes, length of collating symbols, length of equivalence
458 classes, length of character ranges, and length of characters.
459 Next, character class element, collating symbols elements,
460 equivalence class elements, range elements, and character
461 elements follow.
462 See regex_compile function. */
463 charset,
465 /* Same parameters as charset, but match any character that is
466 not one of those specified. */
467 charset_not,
469 /* Start remembering the text that is matched, for storing in a
470 register. Followed by one byte with the register number, in
471 the range 0 to one less than the pattern buffer's re_nsub
472 field. Then followed by one byte with the number of groups
473 inner to this one. (This last has to be part of the
474 start_memory only because we need it in the on_failure_jump
475 of re_match_2.) */
476 start_memory,
478 /* Stop remembering the text that is matched and store it in a
479 memory register. Followed by one byte with the register
480 number, in the range 0 to one less than `re_nsub' in the
481 pattern buffer, and one byte with the number of inner groups,
482 just like `start_memory'. (We need the number of inner
483 groups here because we don't have any easy way of finding the
484 corresponding start_memory when we're at a stop_memory.) */
485 stop_memory,
487 /* Match a duplicate of something remembered. Followed by one
488 byte containing the register number. */
489 duplicate,
491 /* Fail unless at beginning of line. */
492 begline,
494 /* Fail unless at end of line. */
495 endline,
497 /* Succeeds if at beginning of buffer (if emacs) or at beginning
498 of string to be matched (if not). */
499 begbuf,
501 /* Analogously, for end of buffer/string. */
502 endbuf,
504 /* Followed by two byte relative address to which to jump. */
505 jump,
507 /* Same as jump, but marks the end of an alternative. */
508 jump_past_alt,
510 /* Followed by two-byte relative address of place to resume at
511 in case of failure. */
512 /* ifdef MBS_SUPPORT, the size of address is 1. */
513 on_failure_jump,
515 /* Like on_failure_jump, but pushes a placeholder instead of the
516 current string position when executed. */
517 on_failure_keep_string_jump,
519 /* Throw away latest failure point and then jump to following
520 two-byte relative address. */
521 /* ifdef MBS_SUPPORT, the size of address is 1. */
522 pop_failure_jump,
524 /* Change to pop_failure_jump if know won't have to backtrack to
525 match; otherwise change to jump. This is used to jump
526 back to the beginning of a repeat. If what follows this jump
527 clearly won't match what the repeat does, such that we can be
528 sure that there is no use backtracking out of repetitions
529 already matched, then we change it to a pop_failure_jump.
530 Followed by two-byte address. */
531 /* ifdef MBS_SUPPORT, the size of address is 1. */
532 maybe_pop_jump,
534 /* Jump to following two-byte address, and push a dummy failure
535 point. This failure point will be thrown away if an attempt
536 is made to use it for a failure. A `+' construct makes this
537 before the first repeat. Also used as an intermediary kind
538 of jump when compiling an alternative. */
539 /* ifdef MBS_SUPPORT, the size of address is 1. */
540 dummy_failure_jump,
542 /* Push a dummy failure point and continue. Used at the end of
543 alternatives. */
544 push_dummy_failure,
546 /* Followed by two-byte relative address and two-byte number n.
547 After matching N times, jump to the address upon failure. */
548 /* ifdef MBS_SUPPORT, the size of address is 1. */
549 succeed_n,
551 /* Followed by two-byte relative address, and two-byte number n.
552 Jump to the address N times, then fail. */
553 /* ifdef MBS_SUPPORT, the size of address is 1. */
554 jump_n,
556 /* Set the following two-byte relative address to the
557 subsequent two-byte number. The address *includes* the two
558 bytes of number. */
559 /* ifdef MBS_SUPPORT, the size of address is 1. */
560 set_number_at,
562 wordchar, /* Matches any word-constituent character. */
563 notwordchar, /* Matches any char that is not a word-constituent. */
565 wordbeg, /* Succeeds if at word beginning. */
566 wordend, /* Succeeds if at word end. */
568 wordbound, /* Succeeds if at a word boundary. */
569 notwordbound /* Succeeds if not at a word boundary. */
571 #ifdef emacs
572 ,before_dot, /* Succeeds if before point. */
573 at_dot, /* Succeeds if at point. */
574 after_dot, /* Succeeds if after point. */
576 /* Matches any character whose syntax is specified. Followed by
577 a byte which contains a syntax code, e.g., Sword. */
578 syntaxspec,
580 /* Matches any character whose syntax is not that specified. */
581 notsyntaxspec
582 #endif /* emacs */
583 } re_opcode_t;
585 /* Common operations on the compiled pattern. */
587 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
588 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
590 #ifdef MBS_SUPPORT
591 # define STORE_NUMBER(destination, number) \
592 do { \
593 *(destination) = (US_CHAR_TYPE)(number); \
594 } while (0)
595 #else
596 # define STORE_NUMBER(destination, number) \
597 do { \
598 (destination)[0] = (number) & 0377; \
599 (destination)[1] = (number) >> 8; \
600 } while (0)
601 #endif /* MBS_SUPPORT */
603 /* Same as STORE_NUMBER, except increment DESTINATION to
604 the byte after where the number is stored. Therefore, DESTINATION
605 must be an lvalue. */
606 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
608 #define STORE_NUMBER_AND_INCR(destination, number) \
609 do { \
610 STORE_NUMBER (destination, number); \
611 (destination) += OFFSET_ADDRESS_SIZE; \
612 } while (0)
614 /* Put into DESTINATION a number stored in two contiguous bytes starting
615 at SOURCE. */
616 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element. */
618 #ifdef MBS_SUPPORT
619 # define EXTRACT_NUMBER(destination, source) \
620 do { \
621 (destination) = *(source); \
622 } while (0)
623 #else
624 # define EXTRACT_NUMBER(destination, source) \
625 do { \
626 (destination) = *(source) & 0377; \
627 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
628 } while (0)
629 #endif
631 #ifdef DEBUG
632 static void extract_number _RE_ARGS ((int *dest, US_CHAR_TYPE *source));
633 static void
634 extract_number (dest, source)
635 int *dest;
636 US_CHAR_TYPE *source;
638 #ifdef MBS_SUPPORT
639 *dest = *source;
640 #else
641 int temp = SIGN_EXTEND_CHAR (*(source + 1));
642 *dest = *source & 0377;
643 *dest += temp << 8;
644 #endif
647 # ifndef EXTRACT_MACROS /* To debug the macros. */
648 # undef EXTRACT_NUMBER
649 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
650 # endif /* not EXTRACT_MACROS */
652 #endif /* DEBUG */
654 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
655 SOURCE must be an lvalue. */
657 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
658 do { \
659 EXTRACT_NUMBER (destination, source); \
660 (source) += OFFSET_ADDRESS_SIZE; \
661 } while (0)
663 #ifdef DEBUG
664 static void extract_number_and_incr _RE_ARGS ((int *destination,
665 US_CHAR_TYPE **source));
666 static void
667 extract_number_and_incr (destination, source)
668 int *destination;
669 US_CHAR_TYPE **source;
671 extract_number (destination, *source);
672 *source += OFFSET_ADDRESS_SIZE;
675 # ifndef EXTRACT_MACROS
676 # undef EXTRACT_NUMBER_AND_INCR
677 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
678 extract_number_and_incr (&dest, &src)
679 # endif /* not EXTRACT_MACROS */
681 #endif /* DEBUG */
683 /* If DEBUG is defined, Regex prints many voluminous messages about what
684 it is doing (if the variable `debug' is nonzero). If linked with the
685 main program in `iregex.c', you can enter patterns and strings
686 interactively. And if linked with the main program in `main.c' and
687 the other test files, you can run the already-written tests. */
689 #ifdef DEBUG
691 /* We use standard I/O for debugging. */
692 # include <stdio.h>
694 /* It is useful to test things that ``must'' be true when debugging. */
695 # include <assert.h>
697 static int debug;
699 # define DEBUG_STATEMENT(e) e
700 # define DEBUG_PRINT1(x) if (debug) printf (x)
701 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
702 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
703 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
704 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
705 if (debug) print_partial_compiled_pattern (s, e)
706 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
707 if (debug) print_double_string (w, s1, sz1, s2, sz2)
710 /* Print the fastmap in human-readable form. */
712 void
713 print_fastmap (fastmap)
714 char *fastmap;
716 unsigned was_a_range = 0;
717 unsigned i = 0;
719 while (i < (1 << BYTEWIDTH))
721 if (fastmap[i++])
723 was_a_range = 0;
724 putchar (i - 1);
725 while (i < (1 << BYTEWIDTH) && fastmap[i])
727 was_a_range = 1;
728 i++;
730 if (was_a_range)
732 printf ("-");
733 putchar (i - 1);
737 putchar ('\n');
741 /* Print a compiled pattern string in human-readable form, starting at
742 the START pointer into it and ending just before the pointer END. */
744 void
745 print_partial_compiled_pattern (start, end)
746 US_CHAR_TYPE *start;
747 US_CHAR_TYPE *end;
749 int mcnt, mcnt2;
750 US_CHAR_TYPE *p1;
751 US_CHAR_TYPE *p = start;
752 US_CHAR_TYPE *pend = end;
754 if (start == NULL)
756 printf ("(null)\n");
757 return;
760 /* Loop over pattern commands. */
761 while (p < pend)
763 #ifdef _LIBC
764 printf ("%td:\t", p - start);
765 #else
766 printf ("%ld:\t", (long int) (p - start));
767 #endif
769 switch ((re_opcode_t) *p++)
771 case no_op:
772 printf ("/no_op");
773 break;
775 case exactn:
776 mcnt = *p++;
777 printf ("/exactn/%d", mcnt);
780 putchar ('/');
781 PUT_CHAR (*p++);
783 while (--mcnt);
784 break;
786 #ifdef MBS_SUPPORT
787 case exactn_bin:
788 mcnt = *p++;
789 printf ("/exactn_bin/%d", mcnt);
792 printf("/%lx", (long int) *p++);
794 while (--mcnt);
795 break;
796 #endif /* MBS_SUPPORT */
798 case start_memory:
799 mcnt = *p++;
800 printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
801 break;
803 case stop_memory:
804 mcnt = *p++;
805 printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
806 break;
808 case duplicate:
809 printf ("/duplicate/%ld", (long int) *p++);
810 break;
812 case anychar:
813 printf ("/anychar");
814 break;
816 case charset:
817 case charset_not:
819 #ifdef MBS_SUPPORT
820 int i, length;
821 wchar_t *workp = p;
822 printf ("/charset [%s",
823 (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
824 p += 5;
825 length = *workp++; /* the length of char_classes */
826 for (i=0 ; i<length ; i++)
827 printf("[:%lx:]", (long int) *p++);
828 length = *workp++; /* the length of collating_symbol */
829 for (i=0 ; i<length ;)
831 printf("[.");
832 while(*p != 0)
833 PUT_CHAR((i++,*p++));
834 i++,p++;
835 printf(".]");
837 length = *workp++; /* the length of equivalence_class */
838 for (i=0 ; i<length ;)
840 printf("[=");
841 while(*p != 0)
842 PUT_CHAR((i++,*p++));
843 i++,p++;
844 printf("=]");
846 length = *workp++; /* the length of char_range */
847 for (i=0 ; i<length ; i++)
849 wchar_t range_start = *p++;
850 wchar_t range_end = *p++;
851 if (MB_CUR_MAX == 1)
852 printf("%c-%c", (char) range_start, (char) range_end);
853 else
854 printf("%C-%C", (wint_t) range_start, (wint_t) range_end);
856 length = *workp++; /* the length of char */
857 for (i=0 ; i<length ; i++)
858 if (MB_CUR_MAX == 1)
859 putchar (*p++);
860 else
861 printf("%C", (wint_t) *p++);
862 putchar (']');
863 #else
864 register int c, last = -100;
865 register int in_range = 0;
867 printf ("/charset [%s",
868 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
870 assert (p + *p < pend);
872 for (c = 0; c < 256; c++)
873 if (c / 8 < *p
874 && (p[1 + (c/8)] & (1 << (c % 8))))
876 /* Are we starting a range? */
877 if (last + 1 == c && ! in_range)
879 putchar ('-');
880 in_range = 1;
882 /* Have we broken a range? */
883 else if (last + 1 != c && in_range)
885 putchar (last);
886 in_range = 0;
889 if (! in_range)
890 putchar (c);
892 last = c;
895 if (in_range)
896 putchar (last);
898 putchar (']');
900 p += 1 + *p;
901 #endif /* MBS_SUPPORT */
903 break;
905 case begline:
906 printf ("/begline");
907 break;
909 case endline:
910 printf ("/endline");
911 break;
913 case on_failure_jump:
914 extract_number_and_incr (&mcnt, &p);
915 #ifdef _LIBC
916 printf ("/on_failure_jump to %td", p + mcnt - start);
917 #else
918 printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
919 #endif
920 break;
922 case on_failure_keep_string_jump:
923 extract_number_and_incr (&mcnt, &p);
924 #ifdef _LIBC
925 printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
926 #else
927 printf ("/on_failure_keep_string_jump to %ld",
928 (long int) (p + mcnt - start));
929 #endif
930 break;
932 case dummy_failure_jump:
933 extract_number_and_incr (&mcnt, &p);
934 #ifdef _LIBC
935 printf ("/dummy_failure_jump to %td", p + mcnt - start);
936 #else
937 printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
938 #endif
939 break;
941 case push_dummy_failure:
942 printf ("/push_dummy_failure");
943 break;
945 case maybe_pop_jump:
946 extract_number_and_incr (&mcnt, &p);
947 #ifdef _LIBC
948 printf ("/maybe_pop_jump to %td", p + mcnt - start);
949 #else
950 printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
951 #endif
952 break;
954 case pop_failure_jump:
955 extract_number_and_incr (&mcnt, &p);
956 #ifdef _LIBC
957 printf ("/pop_failure_jump to %td", p + mcnt - start);
958 #else
959 printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
960 #endif
961 break;
963 case jump_past_alt:
964 extract_number_and_incr (&mcnt, &p);
965 #ifdef _LIBC
966 printf ("/jump_past_alt to %td", p + mcnt - start);
967 #else
968 printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
969 #endif
970 break;
972 case jump:
973 extract_number_and_incr (&mcnt, &p);
974 #ifdef _LIBC
975 printf ("/jump to %td", p + mcnt - start);
976 #else
977 printf ("/jump to %ld", (long int) (p + mcnt - start));
978 #endif
979 break;
981 case succeed_n:
982 extract_number_and_incr (&mcnt, &p);
983 p1 = p + mcnt;
984 extract_number_and_incr (&mcnt2, &p);
985 #ifdef _LIBC
986 printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
987 #else
988 printf ("/succeed_n to %ld, %d times",
989 (long int) (p1 - start), mcnt2);
990 #endif
991 break;
993 case jump_n:
994 extract_number_and_incr (&mcnt, &p);
995 p1 = p + mcnt;
996 extract_number_and_incr (&mcnt2, &p);
997 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
998 break;
1000 case set_number_at:
1001 extract_number_and_incr (&mcnt, &p);
1002 p1 = p + mcnt;
1003 extract_number_and_incr (&mcnt2, &p);
1004 #ifdef _LIBC
1005 printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1006 #else
1007 printf ("/set_number_at location %ld to %d",
1008 (long int) (p1 - start), mcnt2);
1009 #endif
1010 break;
1012 case wordbound:
1013 printf ("/wordbound");
1014 break;
1016 case notwordbound:
1017 printf ("/notwordbound");
1018 break;
1020 case wordbeg:
1021 printf ("/wordbeg");
1022 break;
1024 case wordend:
1025 printf ("/wordend");
1026 break;
1028 # ifdef emacs
1029 case before_dot:
1030 printf ("/before_dot");
1031 break;
1033 case at_dot:
1034 printf ("/at_dot");
1035 break;
1037 case after_dot:
1038 printf ("/after_dot");
1039 break;
1041 case syntaxspec:
1042 printf ("/syntaxspec");
1043 mcnt = *p++;
1044 printf ("/%d", mcnt);
1045 break;
1047 case notsyntaxspec:
1048 printf ("/notsyntaxspec");
1049 mcnt = *p++;
1050 printf ("/%d", mcnt);
1051 break;
1052 # endif /* emacs */
1054 case wordchar:
1055 printf ("/wordchar");
1056 break;
1058 case notwordchar:
1059 printf ("/notwordchar");
1060 break;
1062 case begbuf:
1063 printf ("/begbuf");
1064 break;
1066 case endbuf:
1067 printf ("/endbuf");
1068 break;
1070 default:
1071 printf ("?%ld", (long int) *(p-1));
1074 putchar ('\n');
1077 #ifdef _LIBC
1078 printf ("%td:\tend of pattern.\n", p - start);
1079 #else
1080 printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1081 #endif
1085 void
1086 print_compiled_pattern (bufp)
1087 struct re_pattern_buffer *bufp;
1089 US_CHAR_TYPE *buffer = (US_CHAR_TYPE*) bufp->buffer;
1091 print_partial_compiled_pattern (buffer, buffer
1092 + bufp->used / sizeof(US_CHAR_TYPE));
1093 printf ("%ld bytes used/%ld bytes allocated.\n",
1094 bufp->used, bufp->allocated);
1096 if (bufp->fastmap_accurate && bufp->fastmap)
1098 printf ("fastmap: ");
1099 print_fastmap (bufp->fastmap);
1102 #ifdef _LIBC
1103 printf ("re_nsub: %Zd\t", bufp->re_nsub);
1104 #else
1105 printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1106 #endif
1107 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1108 printf ("can_be_null: %d\t", bufp->can_be_null);
1109 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1110 printf ("no_sub: %d\t", bufp->no_sub);
1111 printf ("not_bol: %d\t", bufp->not_bol);
1112 printf ("not_eol: %d\t", bufp->not_eol);
1113 printf ("syntax: %lx\n", bufp->syntax);
1114 /* Perhaps we should print the translate table? */
1118 void
1119 print_double_string (where, string1, size1, string2, size2)
1120 const CHAR_TYPE *where;
1121 const CHAR_TYPE *string1;
1122 const CHAR_TYPE *string2;
1123 int size1;
1124 int size2;
1126 int this_char;
1128 if (where == NULL)
1129 printf ("(null)");
1130 else
1132 if (FIRST_STRING_P (where))
1134 for (this_char = where - string1; this_char < size1; this_char++)
1135 PUT_CHAR (string1[this_char]);
1137 where = string2;
1140 for (this_char = where - string2; this_char < size2; this_char++)
1141 PUT_CHAR (string2[this_char]);
1145 void
1146 printchar (c)
1147 int c;
1149 putc (c, stderr);
1152 #else /* not DEBUG */
1154 # undef assert
1155 # define assert(e)
1157 # define DEBUG_STATEMENT(e)
1158 # define DEBUG_PRINT1(x)
1159 # define DEBUG_PRINT2(x1, x2)
1160 # define DEBUG_PRINT3(x1, x2, x3)
1161 # define DEBUG_PRINT4(x1, x2, x3, x4)
1162 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1163 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1165 #endif /* not DEBUG */
1167 #ifdef MBS_SUPPORT
1168 /* This convert a multibyte string to a wide character string.
1169 And write their correspondances to offset_buffer(see below)
1170 and write whether each wchar_t is binary data to is_binary.
1171 This assume invalid multibyte sequences as binary data.
1172 We assume offset_buffer and is_binary is already allocated
1173 enough space. */
1175 static size_t convert_mbs_to_wcs (CHAR_TYPE *dest, const unsigned char* src,
1176 size_t len, int *offset_buffer,
1177 char *is_binary);
1178 static size_t
1179 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1180 CHAR_TYPE *dest;
1181 const unsigned char* src;
1182 size_t len; /* the length of multibyte string. */
1184 /* It hold correspondances between src(char string) and
1185 dest(wchar_t string) for optimization.
1186 e.g. src = "xxxyzz"
1187 dest = {'X', 'Y', 'Z'}
1188 (each "xxx", "y" and "zz" represent one multibyte character
1189 corresponding to 'X', 'Y' and 'Z'.)
1190 offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1191 = {0, 3, 4, 6}
1193 int *offset_buffer;
1194 char *is_binary;
1196 wchar_t *pdest = dest;
1197 const unsigned char *psrc = src;
1198 size_t wc_count = 0;
1200 if (MB_CUR_MAX == 1)
1201 { /* We don't need conversion. */
1202 for ( ; wc_count < len ; ++wc_count)
1204 *pdest++ = *psrc++;
1205 is_binary[wc_count] = FALSE;
1206 offset_buffer[wc_count] = wc_count;
1208 offset_buffer[wc_count] = wc_count;
1210 else
1212 /* We need conversion. */
1213 mbstate_t mbs;
1214 int consumed;
1215 size_t mb_remain = len;
1216 size_t mb_count = 0;
1218 /* Initialize the conversion state. */
1219 memset (&mbs, 0, sizeof (mbstate_t));
1221 offset_buffer[0] = 0;
1222 for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1223 psrc += consumed)
1225 consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1227 if (consumed <= 0)
1228 /* failed to convert. maybe src contains binary data.
1229 So we consume 1 byte manualy. */
1231 *pdest = *psrc;
1232 consumed = 1;
1233 is_binary[wc_count] = TRUE;
1235 else
1236 is_binary[wc_count] = FALSE;
1237 /* In sjis encoding, we use yen sign as escape character in
1238 place of reverse solidus. So we convert 0x5c(yen sign in
1239 sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1240 solidus in UCS2). */
1241 if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1242 *pdest = (wchar_t) *psrc;
1244 offset_buffer[wc_count + 1] = mb_count += consumed;
1248 return wc_count;
1251 #endif /* MBS_SUPPORT */
1253 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1254 also be assigned to arbitrarily: each pattern buffer stores its own
1255 syntax, so it can be changed between regex compilations. */
1256 /* This has no initializer because initialized variables in Emacs
1257 become read-only after dumping. */
1258 reg_syntax_t re_syntax_options;
1261 /* Specify the precise syntax of regexps for compilation. This provides
1262 for compatibility for various utilities which historically have
1263 different, incompatible syntaxes.
1265 The argument SYNTAX is a bit mask comprised of the various bits
1266 defined in regex.h. We return the old syntax. */
1268 reg_syntax_t
1269 re_set_syntax (syntax)
1270 reg_syntax_t syntax;
1272 reg_syntax_t ret = re_syntax_options;
1274 re_syntax_options = syntax;
1275 #ifdef DEBUG
1276 if (syntax & RE_DEBUG)
1277 debug = 1;
1278 else if (debug) /* was on but now is not */
1279 debug = 0;
1280 #endif /* DEBUG */
1281 return ret;
1283 #ifdef _LIBC
1284 weak_alias (__re_set_syntax, re_set_syntax)
1285 #endif
1287 /* This table gives an error message for each of the error codes listed
1288 in regex.h. Obviously the order here has to be same as there.
1289 POSIX doesn't require that we do anything for REG_NOERROR,
1290 but why not be nice? */
1292 static const char re_error_msgid[] =
1294 #define REG_NOERROR_IDX 0
1295 gettext_noop ("Success") /* REG_NOERROR */
1296 "\0"
1297 #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1298 gettext_noop ("No match") /* REG_NOMATCH */
1299 "\0"
1300 #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1301 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1302 "\0"
1303 #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1304 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1305 "\0"
1306 #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1307 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1308 "\0"
1309 #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1310 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1311 "\0"
1312 #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1313 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1314 "\0"
1315 #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1316 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1317 "\0"
1318 #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1319 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1320 "\0"
1321 #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1322 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1323 "\0"
1324 #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1325 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1326 "\0"
1327 #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1328 gettext_noop ("Invalid range end") /* REG_ERANGE */
1329 "\0"
1330 #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1331 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1332 "\0"
1333 #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1334 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1335 "\0"
1336 #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1337 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1338 "\0"
1339 #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1340 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1341 "\0"
1342 #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1343 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1346 static const size_t re_error_msgid_idx[] =
1348 REG_NOERROR_IDX,
1349 REG_NOMATCH_IDX,
1350 REG_BADPAT_IDX,
1351 REG_ECOLLATE_IDX,
1352 REG_ECTYPE_IDX,
1353 REG_EESCAPE_IDX,
1354 REG_ESUBREG_IDX,
1355 REG_EBRACK_IDX,
1356 REG_EPAREN_IDX,
1357 REG_EBRACE_IDX,
1358 REG_BADBR_IDX,
1359 REG_ERANGE_IDX,
1360 REG_ESPACE_IDX,
1361 REG_BADRPT_IDX,
1362 REG_EEND_IDX,
1363 REG_ESIZE_IDX,
1364 REG_ERPAREN_IDX
1367 /* Avoiding alloca during matching, to placate r_alloc. */
1369 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1370 searching and matching functions should not call alloca. On some
1371 systems, alloca is implemented in terms of malloc, and if we're
1372 using the relocating allocator routines, then malloc could cause a
1373 relocation, which might (if the strings being searched are in the
1374 ralloc heap) shift the data out from underneath the regexp
1375 routines.
1377 Here's another reason to avoid allocation: Emacs
1378 processes input from X in a signal handler; processing X input may
1379 call malloc; if input arrives while a matching routine is calling
1380 malloc, then we're scrod. But Emacs can't just block input while
1381 calling matching routines; then we don't notice interrupts when
1382 they come in. So, Emacs blocks input around all regexp calls
1383 except the matching calls, which it leaves unprotected, in the
1384 faith that they will not malloc. */
1386 /* Normally, this is fine. */
1387 #define MATCH_MAY_ALLOCATE
1389 /* When using GNU C, we are not REALLY using the C alloca, no matter
1390 what config.h may say. So don't take precautions for it. */
1391 #ifdef __GNUC__
1392 # undef C_ALLOCA
1393 #endif
1395 /* The match routines may not allocate if (1) they would do it with malloc
1396 and (2) it's not safe for them to use malloc.
1397 Note that if REL_ALLOC is defined, matching would not use malloc for the
1398 failure stack, but we would still use it for the register vectors;
1399 so REL_ALLOC should not affect this. */
1400 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1401 # undef MATCH_MAY_ALLOCATE
1402 #endif
1405 /* Failure stack declarations and macros; both re_compile_fastmap and
1406 re_match_2 use a failure stack. These have to be macros because of
1407 REGEX_ALLOCATE_STACK. */
1410 /* Number of failure points for which to initially allocate space
1411 when matching. If this number is exceeded, we allocate more
1412 space, so it is not a hard limit. */
1413 #ifndef INIT_FAILURE_ALLOC
1414 # define INIT_FAILURE_ALLOC 5
1415 #endif
1417 /* Roughly the maximum number of failure points on the stack. Would be
1418 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1419 This is a variable only so users of regex can assign to it; we never
1420 change it ourselves. */
1422 #ifdef INT_IS_16BIT
1424 # if defined MATCH_MAY_ALLOCATE
1425 /* 4400 was enough to cause a crash on Alpha OSF/1,
1426 whose default stack limit is 2mb. */
1427 long int re_max_failures = 4000;
1428 # else
1429 long int re_max_failures = 2000;
1430 # endif
1432 union fail_stack_elt
1434 US_CHAR_TYPE *pointer;
1435 long int integer;
1438 typedef union fail_stack_elt fail_stack_elt_t;
1440 typedef struct
1442 fail_stack_elt_t *stack;
1443 unsigned long int size;
1444 unsigned long int avail; /* Offset of next open position. */
1445 } fail_stack_type;
1447 #else /* not INT_IS_16BIT */
1449 # if defined MATCH_MAY_ALLOCATE
1450 /* 4400 was enough to cause a crash on Alpha OSF/1,
1451 whose default stack limit is 2mb. */
1452 int re_max_failures = 4000;
1453 # else
1454 int re_max_failures = 2000;
1455 # endif
1457 union fail_stack_elt
1459 US_CHAR_TYPE *pointer;
1460 int integer;
1463 typedef union fail_stack_elt fail_stack_elt_t;
1465 typedef struct
1467 fail_stack_elt_t *stack;
1468 unsigned size;
1469 unsigned avail; /* Offset of next open position. */
1470 } fail_stack_type;
1472 #endif /* INT_IS_16BIT */
1474 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1475 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1476 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1479 /* Define macros to initialize and free the failure stack.
1480 Do `return -2' if the alloc fails. */
1482 #ifdef MATCH_MAY_ALLOCATE
1483 # define INIT_FAIL_STACK() \
1484 do { \
1485 fail_stack.stack = (fail_stack_elt_t *) \
1486 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1488 if (fail_stack.stack == NULL) \
1489 return -2; \
1491 fail_stack.size = INIT_FAILURE_ALLOC; \
1492 fail_stack.avail = 0; \
1493 } while (0)
1495 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1496 #else
1497 # define INIT_FAIL_STACK() \
1498 do { \
1499 fail_stack.avail = 0; \
1500 } while (0)
1502 # define RESET_FAIL_STACK()
1503 #endif
1506 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1508 Return 1 if succeeds, and 0 if either ran out of memory
1509 allocating space for it or it was already too large.
1511 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1513 #define DOUBLE_FAIL_STACK(fail_stack) \
1514 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1515 ? 0 \
1516 : ((fail_stack).stack = (fail_stack_elt_t *) \
1517 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1518 (fail_stack).size * sizeof (fail_stack_elt_t), \
1519 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1521 (fail_stack).stack == NULL \
1522 ? 0 \
1523 : ((fail_stack).size <<= 1, \
1524 1)))
1527 /* Push pointer POINTER on FAIL_STACK.
1528 Return 1 if was able to do so and 0 if ran out of memory allocating
1529 space to do so. */
1530 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1531 ((FAIL_STACK_FULL () \
1532 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1533 ? 0 \
1534 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1537 /* Push a pointer value onto the failure stack.
1538 Assumes the variable `fail_stack'. Probably should only
1539 be called from within `PUSH_FAILURE_POINT'. */
1540 #define PUSH_FAILURE_POINTER(item) \
1541 fail_stack.stack[fail_stack.avail++].pointer = (US_CHAR_TYPE *) (item)
1543 /* This pushes an integer-valued item onto the failure stack.
1544 Assumes the variable `fail_stack'. Probably should only
1545 be called from within `PUSH_FAILURE_POINT'. */
1546 #define PUSH_FAILURE_INT(item) \
1547 fail_stack.stack[fail_stack.avail++].integer = (item)
1549 /* Push a fail_stack_elt_t value onto the failure stack.
1550 Assumes the variable `fail_stack'. Probably should only
1551 be called from within `PUSH_FAILURE_POINT'. */
1552 #define PUSH_FAILURE_ELT(item) \
1553 fail_stack.stack[fail_stack.avail++] = (item)
1555 /* These three POP... operations complement the three PUSH... operations.
1556 All assume that `fail_stack' is nonempty. */
1557 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1558 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1559 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1561 /* Used to omit pushing failure point id's when we're not debugging. */
1562 #ifdef DEBUG
1563 # define DEBUG_PUSH PUSH_FAILURE_INT
1564 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1565 #else
1566 # define DEBUG_PUSH(item)
1567 # define DEBUG_POP(item_addr)
1568 #endif
1571 /* Push the information about the state we will need
1572 if we ever fail back to it.
1574 Requires variables fail_stack, regstart, regend, reg_info, and
1575 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1576 be declared.
1578 Does `return FAILURE_CODE' if runs out of memory. */
1580 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1581 do { \
1582 char *destination; \
1583 /* Must be int, so when we don't save any registers, the arithmetic \
1584 of 0 + -1 isn't done as unsigned. */ \
1585 /* Can't be int, since there is not a shred of a guarantee that int \
1586 is wide enough to hold a value of something to which pointer can \
1587 be assigned */ \
1588 active_reg_t this_reg; \
1590 DEBUG_STATEMENT (failure_id++); \
1591 DEBUG_STATEMENT (nfailure_points_pushed++); \
1592 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1593 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1594 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1596 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1597 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1599 /* Ensure we have enough space allocated for what we will push. */ \
1600 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1602 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1603 return failure_code; \
1605 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1606 (fail_stack).size); \
1607 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1610 /* Push the info, starting with the registers. */ \
1611 DEBUG_PRINT1 ("\n"); \
1613 if (1) \
1614 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1615 this_reg++) \
1617 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1618 DEBUG_STATEMENT (num_regs_pushed++); \
1620 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1621 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1623 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1624 PUSH_FAILURE_POINTER (regend[this_reg]); \
1626 DEBUG_PRINT2 (" info: %p\n ", \
1627 reg_info[this_reg].word.pointer); \
1628 DEBUG_PRINT2 (" match_null=%d", \
1629 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1630 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1631 DEBUG_PRINT2 (" matched_something=%d", \
1632 MATCHED_SOMETHING (reg_info[this_reg])); \
1633 DEBUG_PRINT2 (" ever_matched=%d", \
1634 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1635 DEBUG_PRINT1 ("\n"); \
1636 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1639 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1640 PUSH_FAILURE_INT (lowest_active_reg); \
1642 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1643 PUSH_FAILURE_INT (highest_active_reg); \
1645 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1646 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1647 PUSH_FAILURE_POINTER (pattern_place); \
1649 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1650 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1651 size2); \
1652 DEBUG_PRINT1 ("'\n"); \
1653 PUSH_FAILURE_POINTER (string_place); \
1655 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1656 DEBUG_PUSH (failure_id); \
1657 } while (0)
1659 /* This is the number of items that are pushed and popped on the stack
1660 for each register. */
1661 #define NUM_REG_ITEMS 3
1663 /* Individual items aside from the registers. */
1664 #ifdef DEBUG
1665 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1666 #else
1667 # define NUM_NONREG_ITEMS 4
1668 #endif
1670 /* We push at most this many items on the stack. */
1671 /* We used to use (num_regs - 1), which is the number of registers
1672 this regexp will save; but that was changed to 5
1673 to avoid stack overflow for a regexp with lots of parens. */
1674 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1676 /* We actually push this many items. */
1677 #define NUM_FAILURE_ITEMS \
1678 (((0 \
1679 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1680 * NUM_REG_ITEMS) \
1681 + NUM_NONREG_ITEMS)
1683 /* How many items can still be added to the stack without overflowing it. */
1684 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1687 /* Pops what PUSH_FAIL_STACK pushes.
1689 We restore into the parameters, all of which should be lvalues:
1690 STR -- the saved data position.
1691 PAT -- the saved pattern position.
1692 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1693 REGSTART, REGEND -- arrays of string positions.
1694 REG_INFO -- array of information about each subexpression.
1696 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1697 `pend', `string1', `size1', `string2', and `size2'. */
1698 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1700 DEBUG_STATEMENT (unsigned failure_id;) \
1701 active_reg_t this_reg; \
1702 const US_CHAR_TYPE *string_temp; \
1704 assert (!FAIL_STACK_EMPTY ()); \
1706 /* Remove failure points and point to how many regs pushed. */ \
1707 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1708 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1709 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1711 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1713 DEBUG_POP (&failure_id); \
1714 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1716 /* If the saved string location is NULL, it came from an \
1717 on_failure_keep_string_jump opcode, and we want to throw away the \
1718 saved NULL, thus retaining our current position in the string. */ \
1719 string_temp = POP_FAILURE_POINTER (); \
1720 if (string_temp != NULL) \
1721 str = (const CHAR_TYPE *) string_temp; \
1723 DEBUG_PRINT2 (" Popping string %p: `", str); \
1724 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1725 DEBUG_PRINT1 ("'\n"); \
1727 pat = (US_CHAR_TYPE *) POP_FAILURE_POINTER (); \
1728 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1729 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1731 /* Restore register info. */ \
1732 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1733 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1735 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1736 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1738 if (1) \
1739 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1741 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1743 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1744 DEBUG_PRINT2 (" info: %p\n", \
1745 reg_info[this_reg].word.pointer); \
1747 regend[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER (); \
1748 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1750 regstart[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER ();\
1751 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1753 else \
1755 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1757 reg_info[this_reg].word.integer = 0; \
1758 regend[this_reg] = 0; \
1759 regstart[this_reg] = 0; \
1761 highest_active_reg = high_reg; \
1764 set_regs_matched_done = 0; \
1765 DEBUG_STATEMENT (nfailure_points_popped++); \
1766 } /* POP_FAILURE_POINT */
1769 /* Structure for per-register (a.k.a. per-group) information.
1770 Other register information, such as the
1771 starting and ending positions (which are addresses), and the list of
1772 inner groups (which is a bits list) are maintained in separate
1773 variables.
1775 We are making a (strictly speaking) nonportable assumption here: that
1776 the compiler will pack our bit fields into something that fits into
1777 the type of `word', i.e., is something that fits into one item on the
1778 failure stack. */
1781 /* Declarations and macros for re_match_2. */
1783 typedef union
1785 fail_stack_elt_t word;
1786 struct
1788 /* This field is one if this group can match the empty string,
1789 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1790 #define MATCH_NULL_UNSET_VALUE 3
1791 unsigned match_null_string_p : 2;
1792 unsigned is_active : 1;
1793 unsigned matched_something : 1;
1794 unsigned ever_matched_something : 1;
1795 } bits;
1796 } register_info_type;
1798 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1799 #define IS_ACTIVE(R) ((R).bits.is_active)
1800 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1801 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1804 /* Call this when have matched a real character; it sets `matched' flags
1805 for the subexpressions which we are currently inside. Also records
1806 that those subexprs have matched. */
1807 #define SET_REGS_MATCHED() \
1808 do \
1810 if (!set_regs_matched_done) \
1812 active_reg_t r; \
1813 set_regs_matched_done = 1; \
1814 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1816 MATCHED_SOMETHING (reg_info[r]) \
1817 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1818 = 1; \
1822 while (0)
1824 /* Registers are set to a sentinel when they haven't yet matched. */
1825 static CHAR_TYPE reg_unset_dummy;
1826 #define REG_UNSET_VALUE (&reg_unset_dummy)
1827 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1829 /* Subroutine declarations and macros for regex_compile. */
1831 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1832 reg_syntax_t syntax,
1833 struct re_pattern_buffer *bufp));
1834 static void store_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc, int arg));
1835 static void store_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1836 int arg1, int arg2));
1837 static void insert_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1838 int arg, US_CHAR_TYPE *end));
1839 static void insert_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1840 int arg1, int arg2, US_CHAR_TYPE *end));
1841 static boolean at_begline_loc_p _RE_ARGS ((const CHAR_TYPE *pattern,
1842 const CHAR_TYPE *p,
1843 reg_syntax_t syntax));
1844 static boolean at_endline_loc_p _RE_ARGS ((const CHAR_TYPE *p,
1845 const CHAR_TYPE *pend,
1846 reg_syntax_t syntax));
1847 #ifdef MBS_SUPPORT
1848 static reg_errcode_t compile_range _RE_ARGS ((CHAR_TYPE range_start,
1849 const CHAR_TYPE **p_ptr,
1850 const CHAR_TYPE *pend,
1851 char *translate,
1852 reg_syntax_t syntax,
1853 US_CHAR_TYPE *b,
1854 CHAR_TYPE *char_set));
1855 static void insert_space _RE_ARGS ((int num, CHAR_TYPE *loc, CHAR_TYPE *end));
1856 #else
1857 static reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
1858 const CHAR_TYPE **p_ptr,
1859 const CHAR_TYPE *pend,
1860 char *translate,
1861 reg_syntax_t syntax,
1862 US_CHAR_TYPE *b));
1863 #endif /* MBS_SUPPORT */
1865 /* Fetch the next character in the uncompiled pattern---translating it
1866 if necessary. Also cast from a signed character in the constant
1867 string passed to us by the user to an unsigned char that we can use
1868 as an array index (in, e.g., `translate'). */
1869 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1870 because it is impossible to allocate 4GB array for some encodings
1871 which have 4 byte character_set like UCS4. */
1872 #ifndef PATFETCH
1873 # ifdef MBS_SUPPORT
1874 # define PATFETCH(c) \
1875 do {if (p == pend) return REG_EEND; \
1876 c = (US_CHAR_TYPE) *p++; \
1877 if (translate && (c <= 0xff)) c = (US_CHAR_TYPE) translate[c]; \
1878 } while (0)
1879 # else
1880 # define PATFETCH(c) \
1881 do {if (p == pend) return REG_EEND; \
1882 c = (unsigned char) *p++; \
1883 if (translate) c = (unsigned char) translate[c]; \
1884 } while (0)
1885 # endif /* MBS_SUPPORT */
1886 #endif
1888 /* Fetch the next character in the uncompiled pattern, with no
1889 translation. */
1890 #define PATFETCH_RAW(c) \
1891 do {if (p == pend) return REG_EEND; \
1892 c = (US_CHAR_TYPE) *p++; \
1893 } while (0)
1895 /* Go backwards one character in the pattern. */
1896 #define PATUNFETCH p--
1899 /* If `translate' is non-null, return translate[D], else just D. We
1900 cast the subscript to translate because some data is declared as
1901 `char *', to avoid warnings when a string constant is passed. But
1902 when we use a character as a subscript we must make it unsigned. */
1903 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1904 because it is impossible to allocate 4GB array for some encodings
1905 which have 4 byte character_set like UCS4. */
1906 #ifndef TRANSLATE
1907 # ifdef MBS_SUPPORT
1908 # define TRANSLATE(d) \
1909 (translate && (sizeof(d) <= 1)? (char) translate[(unsigned char) (d)] : (d))
1910 #else
1911 # define TRANSLATE(d) \
1912 (translate ? (char) translate[(unsigned char) (d)] : (d))
1913 # endif /* MBS_SUPPORT */
1914 #endif
1917 /* Macros for outputting the compiled pattern into `buffer'. */
1919 /* If the buffer isn't allocated when it comes in, use this. */
1920 #define INIT_BUF_SIZE (32 * sizeof(US_CHAR_TYPE))
1922 /* Make sure we have at least N more bytes of space in buffer. */
1923 #ifdef MBS_SUPPORT
1924 # define GET_BUFFER_SPACE(n) \
1925 while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR \
1926 + (n)*sizeof(CHAR_TYPE)) > bufp->allocated) \
1927 EXTEND_BUFFER ()
1928 #else
1929 # define GET_BUFFER_SPACE(n) \
1930 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1931 EXTEND_BUFFER ()
1932 #endif /* MBS_SUPPORT */
1934 /* Make sure we have one more byte of buffer space and then add C to it. */
1935 #define BUF_PUSH(c) \
1936 do { \
1937 GET_BUFFER_SPACE (1); \
1938 *b++ = (US_CHAR_TYPE) (c); \
1939 } while (0)
1942 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1943 #define BUF_PUSH_2(c1, c2) \
1944 do { \
1945 GET_BUFFER_SPACE (2); \
1946 *b++ = (US_CHAR_TYPE) (c1); \
1947 *b++ = (US_CHAR_TYPE) (c2); \
1948 } while (0)
1951 /* As with BUF_PUSH_2, except for three bytes. */
1952 #define BUF_PUSH_3(c1, c2, c3) \
1953 do { \
1954 GET_BUFFER_SPACE (3); \
1955 *b++ = (US_CHAR_TYPE) (c1); \
1956 *b++ = (US_CHAR_TYPE) (c2); \
1957 *b++ = (US_CHAR_TYPE) (c3); \
1958 } while (0)
1960 /* Store a jump with opcode OP at LOC to location TO. We store a
1961 relative address offset by the three bytes the jump itself occupies. */
1962 #define STORE_JUMP(op, loc, to) \
1963 store_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
1965 /* Likewise, for a two-argument jump. */
1966 #define STORE_JUMP2(op, loc, to, arg) \
1967 store_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
1969 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1970 #define INSERT_JUMP(op, loc, to) \
1971 insert_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
1973 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1974 #define INSERT_JUMP2(op, loc, to, arg) \
1975 insert_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
1976 arg, b)
1979 /* This is not an arbitrary limit: the arguments which represent offsets
1980 into the pattern are two bytes long. So if 2^16 bytes turns out to
1981 be too small, many things would have to change. */
1982 /* Any other compiler which, like MSC, has allocation limit below 2^16
1983 bytes will have to use approach similar to what was done below for
1984 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1985 reallocating to 0 bytes. Such thing is not going to work too well.
1986 You have been warned!! */
1987 #if defined _MSC_VER && !defined WIN32
1988 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1989 The REALLOC define eliminates a flurry of conversion warnings,
1990 but is not required. */
1991 # define MAX_BUF_SIZE 65500L
1992 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1993 #else
1994 # define MAX_BUF_SIZE (1L << 16)
1995 # define REALLOC(p,s) realloc ((p), (s))
1996 #endif
1998 /* Extend the buffer by twice its current size via realloc and
1999 reset the pointers that pointed into the old block to point to the
2000 correct places in the new one. If extending the buffer results in it
2001 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
2002 #if __BOUNDED_POINTERS__
2003 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2004 # define MOVE_BUFFER_POINTER(P) \
2005 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2006 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
2007 else \
2009 SET_HIGH_BOUND (b); \
2010 SET_HIGH_BOUND (begalt); \
2011 if (fixup_alt_jump) \
2012 SET_HIGH_BOUND (fixup_alt_jump); \
2013 if (laststart) \
2014 SET_HIGH_BOUND (laststart); \
2015 if (pending_exact) \
2016 SET_HIGH_BOUND (pending_exact); \
2018 #else
2019 # define MOVE_BUFFER_POINTER(P) (P) += incr
2020 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
2021 #endif
2023 #ifdef MBS_SUPPORT
2024 # define EXTEND_BUFFER() \
2025 do { \
2026 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2027 int wchar_count; \
2028 if (bufp->allocated + sizeof(US_CHAR_TYPE) > MAX_BUF_SIZE) \
2029 return REG_ESIZE; \
2030 bufp->allocated <<= 1; \
2031 if (bufp->allocated > MAX_BUF_SIZE) \
2032 bufp->allocated = MAX_BUF_SIZE; \
2033 /* How many characters the new buffer can have? */ \
2034 wchar_count = bufp->allocated / sizeof(US_CHAR_TYPE); \
2035 if (wchar_count == 0) wchar_count = 1; \
2036 /* Truncate the buffer to CHAR_TYPE align. */ \
2037 bufp->allocated = wchar_count * sizeof(US_CHAR_TYPE); \
2038 RETALLOC (COMPILED_BUFFER_VAR, wchar_count, US_CHAR_TYPE); \
2039 bufp->buffer = (char*)COMPILED_BUFFER_VAR; \
2040 if (COMPILED_BUFFER_VAR == NULL) \
2041 return REG_ESPACE; \
2042 /* If the buffer moved, move all the pointers into it. */ \
2043 if (old_buffer != COMPILED_BUFFER_VAR) \
2045 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2046 MOVE_BUFFER_POINTER (b); \
2047 MOVE_BUFFER_POINTER (begalt); \
2048 if (fixup_alt_jump) \
2049 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2050 if (laststart) \
2051 MOVE_BUFFER_POINTER (laststart); \
2052 if (pending_exact) \
2053 MOVE_BUFFER_POINTER (pending_exact); \
2055 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2056 } while (0)
2057 #else
2058 # define EXTEND_BUFFER() \
2059 do { \
2060 US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR; \
2061 if (bufp->allocated == MAX_BUF_SIZE) \
2062 return REG_ESIZE; \
2063 bufp->allocated <<= 1; \
2064 if (bufp->allocated > MAX_BUF_SIZE) \
2065 bufp->allocated = MAX_BUF_SIZE; \
2066 bufp->buffer = (US_CHAR_TYPE *) REALLOC (COMPILED_BUFFER_VAR, \
2067 bufp->allocated); \
2068 if (COMPILED_BUFFER_VAR == NULL) \
2069 return REG_ESPACE; \
2070 /* If the buffer moved, move all the pointers into it. */ \
2071 if (old_buffer != COMPILED_BUFFER_VAR) \
2073 int incr = COMPILED_BUFFER_VAR - old_buffer; \
2074 MOVE_BUFFER_POINTER (b); \
2075 MOVE_BUFFER_POINTER (begalt); \
2076 if (fixup_alt_jump) \
2077 MOVE_BUFFER_POINTER (fixup_alt_jump); \
2078 if (laststart) \
2079 MOVE_BUFFER_POINTER (laststart); \
2080 if (pending_exact) \
2081 MOVE_BUFFER_POINTER (pending_exact); \
2083 ELSE_EXTEND_BUFFER_HIGH_BOUND \
2084 } while (0)
2085 #endif /* MBS_SUPPORT */
2087 /* Since we have one byte reserved for the register number argument to
2088 {start,stop}_memory, the maximum number of groups we can report
2089 things about is what fits in that byte. */
2090 #define MAX_REGNUM 255
2092 /* But patterns can have more than `MAX_REGNUM' registers. We just
2093 ignore the excess. */
2094 typedef unsigned regnum_t;
2097 /* Macros for the compile stack. */
2099 /* Since offsets can go either forwards or backwards, this type needs to
2100 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
2101 /* int may be not enough when sizeof(int) == 2. */
2102 typedef long pattern_offset_t;
2104 typedef struct
2106 pattern_offset_t begalt_offset;
2107 pattern_offset_t fixup_alt_jump;
2108 pattern_offset_t inner_group_offset;
2109 pattern_offset_t laststart_offset;
2110 regnum_t regnum;
2111 } compile_stack_elt_t;
2114 typedef struct
2116 compile_stack_elt_t *stack;
2117 unsigned size;
2118 unsigned avail; /* Offset of next open position. */
2119 } compile_stack_type;
2122 #define INIT_COMPILE_STACK_SIZE 32
2124 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
2125 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
2127 /* The next available element. */
2128 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2131 /* Set the bit for character C in a list. */
2132 #define SET_LIST_BIT(c) \
2133 (b[((unsigned char) (c)) / BYTEWIDTH] \
2134 |= 1 << (((unsigned char) c) % BYTEWIDTH))
2137 /* Get the next unsigned number in the uncompiled pattern. */
2138 #define GET_UNSIGNED_NUMBER(num) \
2139 { if (p != pend) \
2141 PATFETCH (c); \
2142 while ('0' <= c && c <= '9') \
2144 if (num < 0) \
2145 num = 0; \
2146 num = num * 10 + c - '0'; \
2147 if (p == pend) \
2148 break; \
2149 PATFETCH (c); \
2154 #if defined _LIBC || WIDE_CHAR_SUPPORT
2155 /* The GNU C library provides support for user-defined character classes
2156 and the functions from ISO C amendement 1. */
2157 # ifdef CHARCLASS_NAME_MAX
2158 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2159 # else
2160 /* This shouldn't happen but some implementation might still have this
2161 problem. Use a reasonable default value. */
2162 # define CHAR_CLASS_MAX_LENGTH 256
2163 # endif
2165 # ifdef _LIBC
2166 # define IS_CHAR_CLASS(string) __wctype (string)
2167 # else
2168 # define IS_CHAR_CLASS(string) wctype (string)
2169 # endif
2170 #else
2171 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
2173 # define IS_CHAR_CLASS(string) \
2174 (STREQ (string, "alpha") || STREQ (string, "upper") \
2175 || STREQ (string, "lower") || STREQ (string, "digit") \
2176 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
2177 || STREQ (string, "space") || STREQ (string, "print") \
2178 || STREQ (string, "punct") || STREQ (string, "graph") \
2179 || STREQ (string, "cntrl") || STREQ (string, "blank"))
2180 #endif
2182 #ifndef MATCH_MAY_ALLOCATE
2184 /* If we cannot allocate large objects within re_match_2_internal,
2185 we make the fail stack and register vectors global.
2186 The fail stack, we grow to the maximum size when a regexp
2187 is compiled.
2188 The register vectors, we adjust in size each time we
2189 compile a regexp, according to the number of registers it needs. */
2191 static fail_stack_type fail_stack;
2193 /* Size with which the following vectors are currently allocated.
2194 That is so we can make them bigger as needed,
2195 but never make them smaller. */
2196 static int regs_allocated_size;
2198 static const char ** regstart, ** regend;
2199 static const char ** old_regstart, ** old_regend;
2200 static const char **best_regstart, **best_regend;
2201 static register_info_type *reg_info;
2202 static const char **reg_dummy;
2203 static register_info_type *reg_info_dummy;
2205 /* Make the register vectors big enough for NUM_REGS registers,
2206 but don't make them smaller. */
2208 static
2209 regex_grow_registers (num_regs)
2210 int num_regs;
2212 if (num_regs > regs_allocated_size)
2214 RETALLOC_IF (regstart, num_regs, const char *);
2215 RETALLOC_IF (regend, num_regs, const char *);
2216 RETALLOC_IF (old_regstart, num_regs, const char *);
2217 RETALLOC_IF (old_regend, num_regs, const char *);
2218 RETALLOC_IF (best_regstart, num_regs, const char *);
2219 RETALLOC_IF (best_regend, num_regs, const char *);
2220 RETALLOC_IF (reg_info, num_regs, register_info_type);
2221 RETALLOC_IF (reg_dummy, num_regs, const char *);
2222 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
2224 regs_allocated_size = num_regs;
2228 #endif /* not MATCH_MAY_ALLOCATE */
2230 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2231 compile_stack,
2232 regnum_t regnum));
2234 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2235 Returns one of error codes defined in `regex.h', or zero for success.
2237 Assumes the `allocated' (and perhaps `buffer') and `translate'
2238 fields are set in BUFP on entry.
2240 If it succeeds, results are put in BUFP (if it returns an error, the
2241 contents of BUFP are undefined):
2242 `buffer' is the compiled pattern;
2243 `syntax' is set to SYNTAX;
2244 `used' is set to the length of the compiled pattern;
2245 `fastmap_accurate' is zero;
2246 `re_nsub' is the number of subexpressions in PATTERN;
2247 `not_bol' and `not_eol' are zero;
2249 The `fastmap' and `newline_anchor' fields are neither
2250 examined nor set. */
2252 /* Return, freeing storage we allocated. */
2253 #ifdef MBS_SUPPORT
2254 # define FREE_STACK_RETURN(value) \
2255 return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2256 #else
2257 # define FREE_STACK_RETURN(value) \
2258 return (free (compile_stack.stack), value)
2259 #endif /* MBS_SUPPORT */
2261 static reg_errcode_t
2262 #ifdef MBS_SUPPORT
2263 regex_compile (cpattern, csize, syntax, bufp)
2264 const char *cpattern;
2265 size_t csize;
2266 #else
2267 regex_compile (pattern, size, syntax, bufp)
2268 const char *pattern;
2269 size_t size;
2270 #endif /* MBS_SUPPORT */
2271 reg_syntax_t syntax;
2272 struct re_pattern_buffer *bufp;
2274 /* We fetch characters from PATTERN here. Even though PATTERN is
2275 `char *' (i.e., signed), we declare these variables as unsigned, so
2276 they can be reliably used as array indices. */
2277 register US_CHAR_TYPE c, c1;
2279 #ifdef MBS_SUPPORT
2280 /* A temporary space to keep wchar_t pattern and compiled pattern. */
2281 CHAR_TYPE *pattern, *COMPILED_BUFFER_VAR;
2282 size_t size;
2283 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
2284 int *mbs_offset = NULL;
2285 /* It hold whether each wchar_t is binary data or not. */
2286 char *is_binary = NULL;
2287 /* A flag whether exactn is handling binary data or not. */
2288 char is_exactn_bin = FALSE;
2289 #endif /* MBS_SUPPORT */
2291 /* A random temporary spot in PATTERN. */
2292 const CHAR_TYPE *p1;
2294 /* Points to the end of the buffer, where we should append. */
2295 register US_CHAR_TYPE *b;
2297 /* Keeps track of unclosed groups. */
2298 compile_stack_type compile_stack;
2300 /* Points to the current (ending) position in the pattern. */
2301 #ifdef MBS_SUPPORT
2302 const CHAR_TYPE *p;
2303 const CHAR_TYPE *pend;
2304 #else
2305 const CHAR_TYPE *p = pattern;
2306 const CHAR_TYPE *pend = pattern + size;
2307 #endif /* MBS_SUPPORT */
2309 /* How to translate the characters in the pattern. */
2310 RE_TRANSLATE_TYPE translate = bufp->translate;
2312 /* Address of the count-byte of the most recently inserted `exactn'
2313 command. This makes it possible to tell if a new exact-match
2314 character can be added to that command or if the character requires
2315 a new `exactn' command. */
2316 US_CHAR_TYPE *pending_exact = 0;
2318 /* Address of start of the most recently finished expression.
2319 This tells, e.g., postfix * where to find the start of its
2320 operand. Reset at the beginning of groups and alternatives. */
2321 US_CHAR_TYPE *laststart = 0;
2323 /* Address of beginning of regexp, or inside of last group. */
2324 US_CHAR_TYPE *begalt;
2326 /* Place in the uncompiled pattern (i.e., the {) to
2327 which to go back if the interval is invalid. */
2328 #ifdef MBS_SUPPORT
2329 const US_CHAR_TYPE *beg_interval;
2330 #else
2331 const char *beg_interval;
2332 #endif /* MBS_SUPPORT */
2334 /* Address of the place where a forward jump should go to the end of
2335 the containing expression. Each alternative of an `or' -- except the
2336 last -- ends with a forward jump of this sort. */
2337 US_CHAR_TYPE *fixup_alt_jump = 0;
2339 /* Counts open-groups as they are encountered. Remembered for the
2340 matching close-group on the compile stack, so the same register
2341 number is put in the stop_memory as the start_memory. */
2342 regnum_t regnum = 0;
2344 #ifdef MBS_SUPPORT
2345 /* Initialize the wchar_t PATTERN and offset_buffer. */
2346 p = pend = pattern = TALLOC(csize, CHAR_TYPE);
2347 mbs_offset = TALLOC(csize + 1, int);
2348 is_binary = TALLOC(csize + 1, char);
2349 if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2351 if (pattern) free(pattern);
2352 if (mbs_offset) free(mbs_offset);
2353 if (is_binary) free(is_binary);
2354 return REG_ESPACE;
2356 size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2357 pend = p + size;
2358 if (size < 0)
2360 if (pattern) free(pattern);
2361 if (mbs_offset) free(mbs_offset);
2362 if (is_binary) free(is_binary);
2363 return REG_BADPAT;
2365 #endif
2367 #ifdef DEBUG
2368 DEBUG_PRINT1 ("\nCompiling pattern: ");
2369 if (debug)
2371 unsigned debug_count;
2373 for (debug_count = 0; debug_count < size; debug_count++)
2374 PUT_CHAR (pattern[debug_count]);
2375 putchar ('\n');
2377 #endif /* DEBUG */
2379 /* Initialize the compile stack. */
2380 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2381 if (compile_stack.stack == NULL)
2383 #ifdef MBS_SUPPORT
2384 if (pattern) free(pattern);
2385 if (mbs_offset) free(mbs_offset);
2386 if (is_binary) free(is_binary);
2387 #endif
2388 return REG_ESPACE;
2391 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2392 compile_stack.avail = 0;
2394 /* Initialize the pattern buffer. */
2395 bufp->syntax = syntax;
2396 bufp->fastmap_accurate = 0;
2397 bufp->not_bol = bufp->not_eol = 0;
2399 /* Set `used' to zero, so that if we return an error, the pattern
2400 printer (for debugging) will think there's no pattern. We reset it
2401 at the end. */
2402 bufp->used = 0;
2404 /* Always count groups, whether or not bufp->no_sub is set. */
2405 bufp->re_nsub = 0;
2407 #if !defined emacs && !defined SYNTAX_TABLE
2408 /* Initialize the syntax table. */
2409 init_syntax_once ();
2410 #endif
2412 if (bufp->allocated == 0)
2414 if (bufp->buffer)
2415 { /* If zero allocated, but buffer is non-null, try to realloc
2416 enough space. This loses if buffer's address is bogus, but
2417 that is the user's responsibility. */
2418 #ifdef MBS_SUPPORT
2419 /* Free bufp->buffer and allocate an array for wchar_t pattern
2420 buffer. */
2421 free(bufp->buffer);
2422 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(US_CHAR_TYPE),
2423 US_CHAR_TYPE);
2424 #else
2425 RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, US_CHAR_TYPE);
2426 #endif /* MBS_SUPPORT */
2428 else
2429 { /* Caller did not allocate a buffer. Do it for them. */
2430 COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(US_CHAR_TYPE),
2431 US_CHAR_TYPE);
2434 if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2435 #ifdef MBS_SUPPORT
2436 bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2437 #endif /* MBS_SUPPORT */
2438 bufp->allocated = INIT_BUF_SIZE;
2440 #ifdef MBS_SUPPORT
2441 else
2442 COMPILED_BUFFER_VAR = (US_CHAR_TYPE*) bufp->buffer;
2443 #endif
2445 begalt = b = COMPILED_BUFFER_VAR;
2447 /* Loop through the uncompiled pattern until we're at the end. */
2448 while (p != pend)
2450 PATFETCH (c);
2452 switch (c)
2454 case '^':
2456 if ( /* If at start of pattern, it's an operator. */
2457 p == pattern + 1
2458 /* If context independent, it's an operator. */
2459 || syntax & RE_CONTEXT_INDEP_ANCHORS
2460 /* Otherwise, depends on what's come before. */
2461 || at_begline_loc_p (pattern, p, syntax))
2462 BUF_PUSH (begline);
2463 else
2464 goto normal_char;
2466 break;
2469 case '$':
2471 if ( /* If at end of pattern, it's an operator. */
2472 p == pend
2473 /* If context independent, it's an operator. */
2474 || syntax & RE_CONTEXT_INDEP_ANCHORS
2475 /* Otherwise, depends on what's next. */
2476 || at_endline_loc_p (p, pend, syntax))
2477 BUF_PUSH (endline);
2478 else
2479 goto normal_char;
2481 break;
2484 case '+':
2485 case '?':
2486 if ((syntax & RE_BK_PLUS_QM)
2487 || (syntax & RE_LIMITED_OPS))
2488 goto normal_char;
2489 handle_plus:
2490 case '*':
2491 /* If there is no previous pattern... */
2492 if (!laststart)
2494 if (syntax & RE_CONTEXT_INVALID_OPS)
2495 FREE_STACK_RETURN (REG_BADRPT);
2496 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2497 goto normal_char;
2501 /* Are we optimizing this jump? */
2502 boolean keep_string_p = false;
2504 /* 1 means zero (many) matches is allowed. */
2505 char zero_times_ok = 0, many_times_ok = 0;
2507 /* If there is a sequence of repetition chars, collapse it
2508 down to just one (the right one). We can't combine
2509 interval operators with these because of, e.g., `a{2}*',
2510 which should only match an even number of `a's. */
2512 for (;;)
2514 zero_times_ok |= c != '+';
2515 many_times_ok |= c != '?';
2517 if (p == pend)
2518 break;
2520 PATFETCH (c);
2522 if (c == '*'
2523 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2526 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2528 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2530 PATFETCH (c1);
2531 if (!(c1 == '+' || c1 == '?'))
2533 PATUNFETCH;
2534 PATUNFETCH;
2535 break;
2538 c = c1;
2540 else
2542 PATUNFETCH;
2543 break;
2546 /* If we get here, we found another repeat character. */
2549 /* Star, etc. applied to an empty pattern is equivalent
2550 to an empty pattern. */
2551 if (!laststart)
2552 break;
2554 /* Now we know whether or not zero matches is allowed
2555 and also whether or not two or more matches is allowed. */
2556 if (many_times_ok)
2557 { /* More than one repetition is allowed, so put in at the
2558 end a backward relative jump from `b' to before the next
2559 jump we're going to put in below (which jumps from
2560 laststart to after this jump).
2562 But if we are at the `*' in the exact sequence `.*\n',
2563 insert an unconditional jump backwards to the .,
2564 instead of the beginning of the loop. This way we only
2565 push a failure point once, instead of every time
2566 through the loop. */
2567 assert (p - 1 > pattern);
2569 /* Allocate the space for the jump. */
2570 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2572 /* We know we are not at the first character of the pattern,
2573 because laststart was nonzero. And we've already
2574 incremented `p', by the way, to be the character after
2575 the `*'. Do we have to do something analogous here
2576 for null bytes, because of RE_DOT_NOT_NULL? */
2577 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2578 && zero_times_ok
2579 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2580 && !(syntax & RE_DOT_NEWLINE))
2581 { /* We have .*\n. */
2582 STORE_JUMP (jump, b, laststart);
2583 keep_string_p = true;
2585 else
2586 /* Anything else. */
2587 STORE_JUMP (maybe_pop_jump, b, laststart -
2588 (1 + OFFSET_ADDRESS_SIZE));
2590 /* We've added more stuff to the buffer. */
2591 b += 1 + OFFSET_ADDRESS_SIZE;
2594 /* On failure, jump from laststart to b + 3, which will be the
2595 end of the buffer after this jump is inserted. */
2596 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2597 'b + 3'. */
2598 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2599 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2600 : on_failure_jump,
2601 laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2602 pending_exact = 0;
2603 b += 1 + OFFSET_ADDRESS_SIZE;
2605 if (!zero_times_ok)
2607 /* At least one repetition is required, so insert a
2608 `dummy_failure_jump' before the initial
2609 `on_failure_jump' instruction of the loop. This
2610 effects a skip over that instruction the first time
2611 we hit that loop. */
2612 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2613 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2614 2 + 2 * OFFSET_ADDRESS_SIZE);
2615 b += 1 + OFFSET_ADDRESS_SIZE;
2618 break;
2621 case '.':
2622 laststart = b;
2623 BUF_PUSH (anychar);
2624 break;
2627 case '[':
2629 boolean had_char_class = false;
2630 #ifdef MBS_SUPPORT
2631 CHAR_TYPE range_start = 0xffffffff;
2632 #else
2633 unsigned int range_start = 0xffffffff;
2634 #endif
2635 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2637 #ifdef MBS_SUPPORT
2638 /* We assume a charset(_not) structure as a wchar_t array.
2639 charset[0] = (re_opcode_t) charset(_not)
2640 charset[1] = l (= length of char_classes)
2641 charset[2] = m (= length of collating_symbols)
2642 charset[3] = n (= length of equivalence_classes)
2643 charset[4] = o (= length of char_ranges)
2644 charset[5] = p (= length of chars)
2646 charset[6] = char_class (wctype_t)
2647 charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2649 charset[l+5] = char_class (wctype_t)
2651 charset[l+6] = collating_symbol (wchar_t)
2653 charset[l+m+5] = collating_symbol (wchar_t)
2654 ifdef _LIBC we use the index if
2655 _NL_COLLATE_SYMB_EXTRAMB instead of
2656 wchar_t string.
2658 charset[l+m+6] = equivalence_classes (wchar_t)
2660 charset[l+m+n+5] = equivalence_classes (wchar_t)
2661 ifdef _LIBC we use the index in
2662 _NL_COLLATE_WEIGHT instead of
2663 wchar_t string.
2665 charset[l+m+n+6] = range_start
2666 charset[l+m+n+7] = range_end
2668 charset[l+m+n+2o+4] = range_start
2669 charset[l+m+n+2o+5] = range_end
2670 ifdef _LIBC we use the value looked up
2671 in _NL_COLLATE_COLLSEQ instead of
2672 wchar_t character.
2674 charset[l+m+n+2o+6] = char
2676 charset[l+m+n+2o+p+5] = char
2680 /* We need at least 6 spaces: the opcode, the length of
2681 char_classes, the length of collating_symbols, the length of
2682 equivalence_classes, the length of char_ranges, the length of
2683 chars. */
2684 GET_BUFFER_SPACE (6);
2686 /* Save b as laststart. And We use laststart as the pointer
2687 to the first element of the charset here.
2688 In other words, laststart[i] indicates charset[i]. */
2689 laststart = b;
2691 /* We test `*p == '^' twice, instead of using an if
2692 statement, so we only need one BUF_PUSH. */
2693 BUF_PUSH (*p == '^' ? charset_not : charset);
2694 if (*p == '^')
2695 p++;
2697 /* Push the length of char_classes, the length of
2698 collating_symbols, the length of equivalence_classes, the
2699 length of char_ranges and the length of chars. */
2700 BUF_PUSH_3 (0, 0, 0);
2701 BUF_PUSH_2 (0, 0);
2703 /* Remember the first position in the bracket expression. */
2704 p1 = p;
2706 /* charset_not matches newline according to a syntax bit. */
2707 if ((re_opcode_t) b[-6] == charset_not
2708 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2710 BUF_PUSH('\n');
2711 laststart[5]++; /* Update the length of characters */
2714 /* Read in characters and ranges, setting map bits. */
2715 for (;;)
2717 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2719 PATFETCH (c);
2721 /* \ might escape characters inside [...] and [^...]. */
2722 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2724 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2726 PATFETCH (c1);
2727 BUF_PUSH(c1);
2728 laststart[5]++; /* Update the length of chars */
2729 range_start = c1;
2730 continue;
2733 /* Could be the end of the bracket expression. If it's
2734 not (i.e., when the bracket expression is `[]' so
2735 far), the ']' character bit gets set way below. */
2736 if (c == ']' && p != p1 + 1)
2737 break;
2739 /* Look ahead to see if it's a range when the last thing
2740 was a character class. */
2741 if (had_char_class && c == '-' && *p != ']')
2742 FREE_STACK_RETURN (REG_ERANGE);
2744 /* Look ahead to see if it's a range when the last thing
2745 was a character: if this is a hyphen not at the
2746 beginning or the end of a list, then it's the range
2747 operator. */
2748 if (c == '-'
2749 && !(p - 2 >= pattern && p[-2] == '[')
2750 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2751 && *p != ']')
2753 reg_errcode_t ret;
2754 /* Allocate the space for range_start and range_end. */
2755 GET_BUFFER_SPACE (2);
2756 /* Update the pointer to indicate end of buffer. */
2757 b += 2;
2758 ret = compile_range (range_start, &p, pend, translate,
2759 syntax, b, laststart);
2760 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2761 range_start = 0xffffffff;
2763 else if (p[0] == '-' && p[1] != ']')
2764 { /* This handles ranges made up of characters only. */
2765 reg_errcode_t ret;
2767 /* Move past the `-'. */
2768 PATFETCH (c1);
2769 /* Allocate the space for range_start and range_end. */
2770 GET_BUFFER_SPACE (2);
2771 /* Update the pointer to indicate end of buffer. */
2772 b += 2;
2773 ret = compile_range (c, &p, pend, translate, syntax, b,
2774 laststart);
2775 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2776 range_start = 0xffffffff;
2779 /* See if we're at the beginning of a possible character
2780 class. */
2781 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2782 { /* Leave room for the null. */
2783 char str[CHAR_CLASS_MAX_LENGTH + 1];
2785 PATFETCH (c);
2786 c1 = 0;
2788 /* If pattern is `[[:'. */
2789 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2791 for (;;)
2793 PATFETCH (c);
2794 if ((c == ':' && *p == ']') || p == pend)
2795 break;
2796 if (c1 < CHAR_CLASS_MAX_LENGTH)
2797 str[c1++] = c;
2798 else
2799 /* This is in any case an invalid class name. */
2800 str[0] = '\0';
2802 str[c1] = '\0';
2804 /* If isn't a word bracketed by `[:' and `:]':
2805 undo the ending character, the letters, and leave
2806 the leading `:' and `[' (but store them as character). */
2807 if (c == ':' && *p == ']')
2809 wctype_t wt;
2810 uintptr_t alignedp;
2812 /* Query the character class as wctype_t. */
2813 wt = IS_CHAR_CLASS (str);
2814 if (wt == 0)
2815 FREE_STACK_RETURN (REG_ECTYPE);
2817 /* Throw away the ] at the end of the character
2818 class. */
2819 PATFETCH (c);
2821 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2823 /* Allocate the space for character class. */
2824 GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2825 /* Update the pointer to indicate end of buffer. */
2826 b += CHAR_CLASS_SIZE;
2827 /* Move data which follow character classes
2828 not to violate the data. */
2829 insert_space(CHAR_CLASS_SIZE,
2830 laststart + 6 + laststart[1],
2831 b - 1);
2832 alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2833 + __alignof__(wctype_t) - 1)
2834 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2835 /* Store the character class. */
2836 *((wctype_t*)alignedp) = wt;
2837 /* Update length of char_classes */
2838 laststart[1] += CHAR_CLASS_SIZE;
2840 had_char_class = true;
2842 else
2844 c1++;
2845 while (c1--)
2846 PATUNFETCH;
2847 BUF_PUSH ('[');
2848 BUF_PUSH (':');
2849 laststart[5] += 2; /* Update the length of characters */
2850 range_start = ':';
2851 had_char_class = false;
2854 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2855 || *p == '.'))
2857 CHAR_TYPE str[128]; /* Should be large enough. */
2858 CHAR_TYPE delim = *p; /* '=' or '.' */
2859 # ifdef _LIBC
2860 uint32_t nrules =
2861 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2862 # endif
2863 PATFETCH (c);
2864 c1 = 0;
2866 /* If pattern is `[[=' or '[[.'. */
2867 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2869 for (;;)
2871 PATFETCH (c);
2872 if ((c == delim && *p == ']') || p == pend)
2873 break;
2874 if (c1 < sizeof (str) - 1)
2875 str[c1++] = c;
2876 else
2877 /* This is in any case an invalid class name. */
2878 str[0] = '\0';
2880 str[c1] = '\0';
2882 if (c == delim && *p == ']' && str[0] != '\0')
2884 unsigned int i, offset;
2885 /* If we have no collation data we use the default
2886 collation in which each character is in a class
2887 by itself. It also means that ASCII is the
2888 character set and therefore we cannot have character
2889 with more than one byte in the multibyte
2890 representation. */
2892 /* If not defined _LIBC, we push the name and
2893 `\0' for the sake of matching performance. */
2894 int datasize = c1 + 1;
2896 # ifdef _LIBC
2897 int32_t idx = 0;
2898 if (nrules == 0)
2899 # endif
2901 if (c1 != 1)
2902 FREE_STACK_RETURN (REG_ECOLLATE);
2904 # ifdef _LIBC
2905 else
2907 const int32_t *table;
2908 const int32_t *weights;
2909 const int32_t *extra;
2910 const int32_t *indirect;
2911 wint_t *cp;
2913 /* This #include defines a local function! */
2914 # include <locale/weightwc.h>
2916 if(delim == '=')
2918 /* We push the index for equivalence class. */
2919 cp = (wint_t*)str;
2921 table = (const int32_t *)
2922 _NL_CURRENT (LC_COLLATE,
2923 _NL_COLLATE_TABLEWC);
2924 weights = (const int32_t *)
2925 _NL_CURRENT (LC_COLLATE,
2926 _NL_COLLATE_WEIGHTWC);
2927 extra = (const int32_t *)
2928 _NL_CURRENT (LC_COLLATE,
2929 _NL_COLLATE_EXTRAWC);
2930 indirect = (const int32_t *)
2931 _NL_CURRENT (LC_COLLATE,
2932 _NL_COLLATE_INDIRECTWC);
2934 idx = findidx ((const wint_t**)&cp);
2935 if (idx == 0 || cp < (wint_t*) str + c1)
2936 /* This is no valid character. */
2937 FREE_STACK_RETURN (REG_ECOLLATE);
2939 str[0] = (wchar_t)idx;
2941 else /* delim == '.' */
2943 /* We push collation sequence value
2944 for collating symbol. */
2945 int32_t table_size;
2946 const int32_t *symb_table;
2947 const unsigned char *extra;
2948 int32_t idx;
2949 int32_t elem;
2950 int32_t second;
2951 int32_t hash;
2952 char char_str[c1];
2954 /* We have to convert the name to a single-byte
2955 string. This is possible since the names
2956 consist of ASCII characters and the internal
2957 representation is UCS4. */
2958 for (i = 0; i < c1; ++i)
2959 char_str[i] = str[i];
2961 table_size =
2962 _NL_CURRENT_WORD (LC_COLLATE,
2963 _NL_COLLATE_SYMB_HASH_SIZEMB);
2964 symb_table = (const int32_t *)
2965 _NL_CURRENT (LC_COLLATE,
2966 _NL_COLLATE_SYMB_TABLEMB);
2967 extra = (const unsigned char *)
2968 _NL_CURRENT (LC_COLLATE,
2969 _NL_COLLATE_SYMB_EXTRAMB);
2971 /* Locate the character in the hashing table. */
2972 hash = elem_hash (char_str, c1);
2974 idx = 0;
2975 elem = hash % table_size;
2976 second = hash % (table_size - 2);
2977 while (symb_table[2 * elem] != 0)
2979 /* First compare the hashing value. */
2980 if (symb_table[2 * elem] == hash
2981 && c1 == extra[symb_table[2 * elem + 1]]
2982 && memcmp (str,
2983 &extra[symb_table[2 * elem + 1]
2984 + 1], c1) == 0)
2986 /* Yep, this is the entry. */
2987 idx = symb_table[2 * elem + 1];
2988 idx += 1 + extra[idx];
2989 break;
2992 /* Next entry. */
2993 elem += second;
2996 if (symb_table[2 * elem] != 0)
2998 /* Compute the index of the byte sequence
2999 in the table. */
3000 idx += 1 + extra[idx];
3001 /* Adjust for the alignment. */
3002 idx = (idx + 3) & ~4;
3004 str[0] = (wchar_t) idx + 4;
3006 else if (symb_table[2 * elem] == 0 && c1 == 1)
3008 /* No valid character. Match it as a
3009 single byte character. */
3010 had_char_class = false;
3011 BUF_PUSH(str[0]);
3012 /* Update the length of characters */
3013 laststart[5]++;
3014 range_start = str[0];
3016 /* Throw away the ] at the end of the
3017 collating symbol. */
3018 PATFETCH (c);
3019 /* exit from the switch block. */
3020 continue;
3022 else
3023 FREE_STACK_RETURN (REG_ECOLLATE);
3025 datasize = 1;
3027 # endif
3028 /* Throw away the ] at the end of the equivalence
3029 class (or collating symbol). */
3030 PATFETCH (c);
3032 /* Allocate the space for the equivalence class
3033 (or collating symbol) (and '\0' if needed). */
3034 GET_BUFFER_SPACE(datasize);
3035 /* Update the pointer to indicate end of buffer. */
3036 b += datasize;
3038 if (delim == '=')
3039 { /* equivalence class */
3040 /* Calculate the offset of char_ranges,
3041 which is next to equivalence_classes. */
3042 offset = laststart[1] + laststart[2]
3043 + laststart[3] +6;
3044 /* Insert space. */
3045 insert_space(datasize, laststart + offset, b - 1);
3047 /* Write the equivalence_class and \0. */
3048 for (i = 0 ; i < datasize ; i++)
3049 laststart[offset + i] = str[i];
3051 /* Update the length of equivalence_classes. */
3052 laststart[3] += datasize;
3053 had_char_class = true;
3055 else /* delim == '.' */
3056 { /* collating symbol */
3057 /* Calculate the offset of the equivalence_classes,
3058 which is next to collating_symbols. */
3059 offset = laststart[1] + laststart[2] + 6;
3060 /* Insert space and write the collationg_symbol
3061 and \0. */
3062 insert_space(datasize, laststart + offset, b-1);
3063 for (i = 0 ; i < datasize ; i++)
3064 laststart[offset + i] = str[i];
3066 /* In re_match_2_internal if range_start < -1, we
3067 assume -range_start is the offset of the
3068 collating symbol which is specified as
3069 the character of the range start. So we assign
3070 -(laststart[1] + laststart[2] + 6) to
3071 range_start. */
3072 range_start = -(laststart[1] + laststart[2] + 6);
3073 /* Update the length of collating_symbol. */
3074 laststart[2] += datasize;
3075 had_char_class = false;
3078 else
3080 c1++;
3081 while (c1--)
3082 PATUNFETCH;
3083 BUF_PUSH ('[');
3084 BUF_PUSH (delim);
3085 laststart[5] += 2; /* Update the length of characters */
3086 range_start = delim;
3087 had_char_class = false;
3090 else
3092 had_char_class = false;
3093 BUF_PUSH(c);
3094 laststart[5]++; /* Update the length of characters */
3095 range_start = c;
3099 #else /* not MBS_SUPPORT */
3100 /* Ensure that we have enough space to push a charset: the
3101 opcode, the length count, and the bitset; 34 bytes in all. */
3102 GET_BUFFER_SPACE (34);
3104 laststart = b;
3106 /* We test `*p == '^' twice, instead of using an if
3107 statement, so we only need one BUF_PUSH. */
3108 BUF_PUSH (*p == '^' ? charset_not : charset);
3109 if (*p == '^')
3110 p++;
3112 /* Remember the first position in the bracket expression. */
3113 p1 = p;
3115 /* Push the number of bytes in the bitmap. */
3116 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3118 /* Clear the whole map. */
3119 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3121 /* charset_not matches newline according to a syntax bit. */
3122 if ((re_opcode_t) b[-2] == charset_not
3123 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3124 SET_LIST_BIT ('\n');
3126 /* Read in characters and ranges, setting map bits. */
3127 for (;;)
3129 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3131 PATFETCH (c);
3133 /* \ might escape characters inside [...] and [^...]. */
3134 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3136 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3138 PATFETCH (c1);
3139 SET_LIST_BIT (c1);
3140 range_start = c1;
3141 continue;
3144 /* Could be the end of the bracket expression. If it's
3145 not (i.e., when the bracket expression is `[]' so
3146 far), the ']' character bit gets set way below. */
3147 if (c == ']' && p != p1 + 1)
3148 break;
3150 /* Look ahead to see if it's a range when the last thing
3151 was a character class. */
3152 if (had_char_class && c == '-' && *p != ']')
3153 FREE_STACK_RETURN (REG_ERANGE);
3155 /* Look ahead to see if it's a range when the last thing
3156 was a character: if this is a hyphen not at the
3157 beginning or the end of a list, then it's the range
3158 operator. */
3159 if (c == '-'
3160 && !(p - 2 >= pattern && p[-2] == '[')
3161 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3162 && *p != ']')
3164 reg_errcode_t ret
3165 = compile_range (range_start, &p, pend, translate,
3166 syntax, b);
3167 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3168 range_start = 0xffffffff;
3171 else if (p[0] == '-' && p[1] != ']')
3172 { /* This handles ranges made up of characters only. */
3173 reg_errcode_t ret;
3175 /* Move past the `-'. */
3176 PATFETCH (c1);
3178 ret = compile_range (c, &p, pend, translate, syntax, b);
3179 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3180 range_start = 0xffffffff;
3183 /* See if we're at the beginning of a possible character
3184 class. */
3186 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3187 { /* Leave room for the null. */
3188 char str[CHAR_CLASS_MAX_LENGTH + 1];
3190 PATFETCH (c);
3191 c1 = 0;
3193 /* If pattern is `[[:'. */
3194 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3196 for (;;)
3198 PATFETCH (c);
3199 if ((c == ':' && *p == ']') || p == pend)
3200 break;
3201 if (c1 < CHAR_CLASS_MAX_LENGTH)
3202 str[c1++] = c;
3203 else
3204 /* This is in any case an invalid class name. */
3205 str[0] = '\0';
3207 str[c1] = '\0';
3209 /* If isn't a word bracketed by `[:' and `:]':
3210 undo the ending character, the letters, and leave
3211 the leading `:' and `[' (but set bits for them). */
3212 if (c == ':' && *p == ']')
3214 # if defined _LIBC || WIDE_CHAR_SUPPORT
3215 boolean is_lower = STREQ (str, "lower");
3216 boolean is_upper = STREQ (str, "upper");
3217 wctype_t wt;
3218 int ch;
3220 wt = IS_CHAR_CLASS (str);
3221 if (wt == 0)
3222 FREE_STACK_RETURN (REG_ECTYPE);
3224 /* Throw away the ] at the end of the character
3225 class. */
3226 PATFETCH (c);
3228 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3230 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3232 # ifdef _LIBC
3233 if (__iswctype (__btowc (ch), wt))
3234 SET_LIST_BIT (ch);
3235 # else
3236 if (iswctype (btowc (ch), wt))
3237 SET_LIST_BIT (ch);
3238 # endif
3240 if (translate && (is_upper || is_lower)
3241 && (ISUPPER (ch) || ISLOWER (ch)))
3242 SET_LIST_BIT (ch);
3245 had_char_class = true;
3246 # else
3247 int ch;
3248 boolean is_alnum = STREQ (str, "alnum");
3249 boolean is_alpha = STREQ (str, "alpha");
3250 boolean is_blank = STREQ (str, "blank");
3251 boolean is_cntrl = STREQ (str, "cntrl");
3252 boolean is_digit = STREQ (str, "digit");
3253 boolean is_graph = STREQ (str, "graph");
3254 boolean is_lower = STREQ (str, "lower");
3255 boolean is_print = STREQ (str, "print");
3256 boolean is_punct = STREQ (str, "punct");
3257 boolean is_space = STREQ (str, "space");
3258 boolean is_upper = STREQ (str, "upper");
3259 boolean is_xdigit = STREQ (str, "xdigit");
3261 if (!IS_CHAR_CLASS (str))
3262 FREE_STACK_RETURN (REG_ECTYPE);
3264 /* Throw away the ] at the end of the character
3265 class. */
3266 PATFETCH (c);
3268 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3270 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3272 /* This was split into 3 if's to
3273 avoid an arbitrary limit in some compiler. */
3274 if ( (is_alnum && ISALNUM (ch))
3275 || (is_alpha && ISALPHA (ch))
3276 || (is_blank && ISBLANK (ch))
3277 || (is_cntrl && ISCNTRL (ch)))
3278 SET_LIST_BIT (ch);
3279 if ( (is_digit && ISDIGIT (ch))
3280 || (is_graph && ISGRAPH (ch))
3281 || (is_lower && ISLOWER (ch))
3282 || (is_print && ISPRINT (ch)))
3283 SET_LIST_BIT (ch);
3284 if ( (is_punct && ISPUNCT (ch))
3285 || (is_space && ISSPACE (ch))
3286 || (is_upper && ISUPPER (ch))
3287 || (is_xdigit && ISXDIGIT (ch)))
3288 SET_LIST_BIT (ch);
3289 if ( translate && (is_upper || is_lower)
3290 && (ISUPPER (ch) || ISLOWER (ch)))
3291 SET_LIST_BIT (ch);
3293 had_char_class = true;
3294 # endif /* libc || wctype.h */
3296 else
3298 c1++;
3299 while (c1--)
3300 PATUNFETCH;
3301 SET_LIST_BIT ('[');
3302 SET_LIST_BIT (':');
3303 range_start = ':';
3304 had_char_class = false;
3307 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3309 unsigned char str[MB_LEN_MAX + 1];
3310 # ifdef _LIBC
3311 uint32_t nrules =
3312 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3313 # endif
3315 PATFETCH (c);
3316 c1 = 0;
3318 /* If pattern is `[[='. */
3319 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3321 for (;;)
3323 PATFETCH (c);
3324 if ((c == '=' && *p == ']') || p == pend)
3325 break;
3326 if (c1 < MB_LEN_MAX)
3327 str[c1++] = c;
3328 else
3329 /* This is in any case an invalid class name. */
3330 str[0] = '\0';
3332 str[c1] = '\0';
3334 if (c == '=' && *p == ']' && str[0] != '\0')
3336 /* If we have no collation data we use the default
3337 collation in which each character is in a class
3338 by itself. It also means that ASCII is the
3339 character set and therefore we cannot have character
3340 with more than one byte in the multibyte
3341 representation. */
3342 # ifdef _LIBC
3343 if (nrules == 0)
3344 # endif
3346 if (c1 != 1)
3347 FREE_STACK_RETURN (REG_ECOLLATE);
3349 /* Throw away the ] at the end of the equivalence
3350 class. */
3351 PATFETCH (c);
3353 /* Set the bit for the character. */
3354 SET_LIST_BIT (str[0]);
3356 # ifdef _LIBC
3357 else
3359 /* Try to match the byte sequence in `str' against
3360 those known to the collate implementation.
3361 First find out whether the bytes in `str' are
3362 actually from exactly one character. */
3363 const int32_t *table;
3364 const unsigned char *weights;
3365 const unsigned char *extra;
3366 const int32_t *indirect;
3367 int32_t idx;
3368 const unsigned char *cp = str;
3369 int ch;
3371 /* This #include defines a local function! */
3372 # include <locale/weight.h>
3374 table = (const int32_t *)
3375 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3376 weights = (const unsigned char *)
3377 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3378 extra = (const unsigned char *)
3379 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3380 indirect = (const int32_t *)
3381 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3383 idx = findidx (&cp);
3384 if (idx == 0 || cp < str + c1)
3385 /* This is no valid character. */
3386 FREE_STACK_RETURN (REG_ECOLLATE);
3388 /* Throw away the ] at the end of the equivalence
3389 class. */
3390 PATFETCH (c);
3392 /* Now we have to go throught the whole table
3393 and find all characters which have the same
3394 first level weight.
3396 XXX Note that this is not entirely correct.
3397 we would have to match multibyte sequences
3398 but this is not possible with the current
3399 implementation. */
3400 for (ch = 1; ch < 256; ++ch)
3401 /* XXX This test would have to be changed if we
3402 would allow matching multibyte sequences. */
3403 if (table[ch] > 0)
3405 int32_t idx2 = table[ch];
3406 size_t len = weights[idx2];
3408 /* Test whether the lenghts match. */
3409 if (weights[idx] == len)
3411 /* They do. New compare the bytes of
3412 the weight. */
3413 size_t cnt = 0;
3415 while (cnt < len
3416 && (weights[idx + 1 + cnt]
3417 == weights[idx2 + 1 + cnt]))
3418 ++cnt;
3420 if (cnt == len)
3421 /* They match. Mark the character as
3422 acceptable. */
3423 SET_LIST_BIT (ch);
3427 # endif
3428 had_char_class = true;
3430 else
3432 c1++;
3433 while (c1--)
3434 PATUNFETCH;
3435 SET_LIST_BIT ('[');
3436 SET_LIST_BIT ('=');
3437 range_start = '=';
3438 had_char_class = false;
3441 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3443 unsigned char str[128]; /* Should be large enough. */
3444 # ifdef _LIBC
3445 uint32_t nrules =
3446 _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3447 # endif
3449 PATFETCH (c);
3450 c1 = 0;
3452 /* If pattern is `[[.'. */
3453 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3455 for (;;)
3457 PATFETCH (c);
3458 if ((c == '.' && *p == ']') || p == pend)
3459 break;
3460 if (c1 < sizeof (str))
3461 str[c1++] = c;
3462 else
3463 /* This is in any case an invalid class name. */
3464 str[0] = '\0';
3466 str[c1] = '\0';
3468 if (c == '.' && *p == ']' && str[0] != '\0')
3470 /* If we have no collation data we use the default
3471 collation in which each character is the name
3472 for its own class which contains only the one
3473 character. It also means that ASCII is the
3474 character set and therefore we cannot have character
3475 with more than one byte in the multibyte
3476 representation. */
3477 # ifdef _LIBC
3478 if (nrules == 0)
3479 # endif
3481 if (c1 != 1)
3482 FREE_STACK_RETURN (REG_ECOLLATE);
3484 /* Throw away the ] at the end of the equivalence
3485 class. */
3486 PATFETCH (c);
3488 /* Set the bit for the character. */
3489 SET_LIST_BIT (str[0]);
3490 range_start = ((const unsigned char *) str)[0];
3492 # ifdef _LIBC
3493 else
3495 /* Try to match the byte sequence in `str' against
3496 those known to the collate implementation.
3497 First find out whether the bytes in `str' are
3498 actually from exactly one character. */
3499 int32_t table_size;
3500 const int32_t *symb_table;
3501 const unsigned char *extra;
3502 int32_t idx;
3503 int32_t elem;
3504 int32_t second;
3505 int32_t hash;
3507 table_size =
3508 _NL_CURRENT_WORD (LC_COLLATE,
3509 _NL_COLLATE_SYMB_HASH_SIZEMB);
3510 symb_table = (const int32_t *)
3511 _NL_CURRENT (LC_COLLATE,
3512 _NL_COLLATE_SYMB_TABLEMB);
3513 extra = (const unsigned char *)
3514 _NL_CURRENT (LC_COLLATE,
3515 _NL_COLLATE_SYMB_EXTRAMB);
3517 /* Locate the character in the hashing table. */
3518 hash = elem_hash (str, c1);
3520 idx = 0;
3521 elem = hash % table_size;
3522 second = hash % (table_size - 2);
3523 while (symb_table[2 * elem] != 0)
3525 /* First compare the hashing value. */
3526 if (symb_table[2 * elem] == hash
3527 && c1 == extra[symb_table[2 * elem + 1]]
3528 && memcmp (str,
3529 &extra[symb_table[2 * elem + 1]
3530 + 1],
3531 c1) == 0)
3533 /* Yep, this is the entry. */
3534 idx = symb_table[2 * elem + 1];
3535 idx += 1 + extra[idx];
3536 break;
3539 /* Next entry. */
3540 elem += second;
3543 if (symb_table[2 * elem] == 0)
3544 /* This is no valid character. */
3545 FREE_STACK_RETURN (REG_ECOLLATE);
3547 /* Throw away the ] at the end of the equivalence
3548 class. */
3549 PATFETCH (c);
3551 /* Now add the multibyte character(s) we found
3552 to the accept list.
3554 XXX Note that this is not entirely correct.
3555 we would have to match multibyte sequences
3556 but this is not possible with the current
3557 implementation. Also, we have to match
3558 collating symbols, which expand to more than
3559 one file, as a whole and not allow the
3560 individual bytes. */
3561 c1 = extra[idx++];
3562 if (c1 == 1)
3563 range_start = extra[idx];
3564 while (c1-- > 0)
3566 SET_LIST_BIT (extra[idx]);
3567 ++idx;
3570 # endif
3571 had_char_class = false;
3573 else
3575 c1++;
3576 while (c1--)
3577 PATUNFETCH;
3578 SET_LIST_BIT ('[');
3579 SET_LIST_BIT ('.');
3580 range_start = '.';
3581 had_char_class = false;
3584 else
3586 had_char_class = false;
3587 SET_LIST_BIT (c);
3588 range_start = c;
3592 /* Discard any (non)matching list bytes that are all 0 at the
3593 end of the map. Decrease the map-length byte too. */
3594 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3595 b[-1]--;
3596 b += b[-1];
3597 #endif /* MBS_SUPPORT */
3599 break;
3602 case '(':
3603 if (syntax & RE_NO_BK_PARENS)
3604 goto handle_open;
3605 else
3606 goto normal_char;
3609 case ')':
3610 if (syntax & RE_NO_BK_PARENS)
3611 goto handle_close;
3612 else
3613 goto normal_char;
3616 case '\n':
3617 if (syntax & RE_NEWLINE_ALT)
3618 goto handle_alt;
3619 else
3620 goto normal_char;
3623 case '|':
3624 if (syntax & RE_NO_BK_VBAR)
3625 goto handle_alt;
3626 else
3627 goto normal_char;
3630 case '{':
3631 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3632 goto handle_interval;
3633 else
3634 goto normal_char;
3637 case '\\':
3638 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3640 /* Do not translate the character after the \, so that we can
3641 distinguish, e.g., \B from \b, even if we normally would
3642 translate, e.g., B to b. */
3643 PATFETCH_RAW (c);
3645 switch (c)
3647 case '(':
3648 if (syntax & RE_NO_BK_PARENS)
3649 goto normal_backslash;
3651 handle_open:
3652 bufp->re_nsub++;
3653 regnum++;
3655 if (COMPILE_STACK_FULL)
3657 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3658 compile_stack_elt_t);
3659 if (compile_stack.stack == NULL) return REG_ESPACE;
3661 compile_stack.size <<= 1;
3664 /* These are the values to restore when we hit end of this
3665 group. They are all relative offsets, so that if the
3666 whole pattern moves because of realloc, they will still
3667 be valid. */
3668 COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3669 COMPILE_STACK_TOP.fixup_alt_jump
3670 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3671 COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3672 COMPILE_STACK_TOP.regnum = regnum;
3674 /* We will eventually replace the 0 with the number of
3675 groups inner to this one. But do not push a
3676 start_memory for groups beyond the last one we can
3677 represent in the compiled pattern. */
3678 if (regnum <= MAX_REGNUM)
3680 COMPILE_STACK_TOP.inner_group_offset = b
3681 - COMPILED_BUFFER_VAR + 2;
3682 BUF_PUSH_3 (start_memory, regnum, 0);
3685 compile_stack.avail++;
3687 fixup_alt_jump = 0;
3688 laststart = 0;
3689 begalt = b;
3690 /* If we've reached MAX_REGNUM groups, then this open
3691 won't actually generate any code, so we'll have to
3692 clear pending_exact explicitly. */
3693 pending_exact = 0;
3694 break;
3697 case ')':
3698 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3700 if (COMPILE_STACK_EMPTY)
3702 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3703 goto normal_backslash;
3704 else
3705 FREE_STACK_RETURN (REG_ERPAREN);
3708 handle_close:
3709 if (fixup_alt_jump)
3710 { /* Push a dummy failure point at the end of the
3711 alternative for a possible future
3712 `pop_failure_jump' to pop. See comments at
3713 `push_dummy_failure' in `re_match_2'. */
3714 BUF_PUSH (push_dummy_failure);
3716 /* We allocated space for this jump when we assigned
3717 to `fixup_alt_jump', in the `handle_alt' case below. */
3718 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3721 /* See similar code for backslashed left paren above. */
3722 if (COMPILE_STACK_EMPTY)
3724 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3725 goto normal_char;
3726 else
3727 FREE_STACK_RETURN (REG_ERPAREN);
3730 /* Since we just checked for an empty stack above, this
3731 ``can't happen''. */
3732 assert (compile_stack.avail != 0);
3734 /* We don't just want to restore into `regnum', because
3735 later groups should continue to be numbered higher,
3736 as in `(ab)c(de)' -- the second group is #2. */
3737 regnum_t this_group_regnum;
3739 compile_stack.avail--;
3740 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3741 fixup_alt_jump
3742 = COMPILE_STACK_TOP.fixup_alt_jump
3743 ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3744 : 0;
3745 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3746 this_group_regnum = COMPILE_STACK_TOP.regnum;
3747 /* If we've reached MAX_REGNUM groups, then this open
3748 won't actually generate any code, so we'll have to
3749 clear pending_exact explicitly. */
3750 pending_exact = 0;
3752 /* We're at the end of the group, so now we know how many
3753 groups were inside this one. */
3754 if (this_group_regnum <= MAX_REGNUM)
3756 US_CHAR_TYPE *inner_group_loc
3757 = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3759 *inner_group_loc = regnum - this_group_regnum;
3760 BUF_PUSH_3 (stop_memory, this_group_regnum,
3761 regnum - this_group_regnum);
3764 break;
3767 case '|': /* `\|'. */
3768 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3769 goto normal_backslash;
3770 handle_alt:
3771 if (syntax & RE_LIMITED_OPS)
3772 goto normal_char;
3774 /* Insert before the previous alternative a jump which
3775 jumps to this alternative if the former fails. */
3776 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3777 INSERT_JUMP (on_failure_jump, begalt,
3778 b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3779 pending_exact = 0;
3780 b += 1 + OFFSET_ADDRESS_SIZE;
3782 /* The alternative before this one has a jump after it
3783 which gets executed if it gets matched. Adjust that
3784 jump so it will jump to this alternative's analogous
3785 jump (put in below, which in turn will jump to the next
3786 (if any) alternative's such jump, etc.). The last such
3787 jump jumps to the correct final destination. A picture:
3788 _____ _____
3789 | | | |
3790 | v | v
3791 a | b | c
3793 If we are at `b', then fixup_alt_jump right now points to a
3794 three-byte space after `a'. We'll put in the jump, set
3795 fixup_alt_jump to right after `b', and leave behind three
3796 bytes which we'll fill in when we get to after `c'. */
3798 if (fixup_alt_jump)
3799 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3801 /* Mark and leave space for a jump after this alternative,
3802 to be filled in later either by next alternative or
3803 when know we're at the end of a series of alternatives. */
3804 fixup_alt_jump = b;
3805 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3806 b += 1 + OFFSET_ADDRESS_SIZE;
3808 laststart = 0;
3809 begalt = b;
3810 break;
3813 case '{':
3814 /* If \{ is a literal. */
3815 if (!(syntax & RE_INTERVALS)
3816 /* If we're at `\{' and it's not the open-interval
3817 operator. */
3818 || (syntax & RE_NO_BK_BRACES))
3819 goto normal_backslash;
3821 handle_interval:
3823 /* If got here, then the syntax allows intervals. */
3825 /* At least (most) this many matches must be made. */
3826 int lower_bound = -1, upper_bound = -1;
3827 beg_interval = p - 1;
3829 if (p == pend)
3831 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3832 goto unfetch_interval;
3833 else
3834 FREE_STACK_RETURN (REG_EBRACE);
3837 GET_UNSIGNED_NUMBER (lower_bound);
3839 if (c == ',')
3841 GET_UNSIGNED_NUMBER (upper_bound);
3842 if ((!(syntax & RE_NO_BK_BRACES) && c != '\\')
3843 || ((syntax & RE_NO_BK_BRACES) && c != '}'))
3844 FREE_STACK_RETURN (REG_BADBR);
3846 if (upper_bound < 0)
3847 upper_bound = RE_DUP_MAX;
3849 else
3850 /* Interval such as `{1}' => match exactly once. */
3851 upper_bound = lower_bound;
3853 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3854 || lower_bound > upper_bound)
3856 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3857 goto unfetch_interval;
3858 else
3859 FREE_STACK_RETURN (REG_BADBR);
3862 if (!(syntax & RE_NO_BK_BRACES))
3864 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
3866 PATFETCH (c);
3869 if (c != '}')
3871 if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
3872 goto unfetch_interval;
3873 else
3874 FREE_STACK_RETURN (REG_BADBR);
3877 /* We just parsed a valid interval. */
3879 /* If it's invalid to have no preceding re. */
3880 if (!laststart)
3882 if (syntax & RE_CONTEXT_INVALID_OPS)
3883 FREE_STACK_RETURN (REG_BADRPT);
3884 else if (syntax & RE_CONTEXT_INDEP_OPS)
3885 laststart = b;
3886 else
3887 goto unfetch_interval;
3890 /* If the upper bound is zero, don't want to succeed at
3891 all; jump from `laststart' to `b + 3', which will be
3892 the end of the buffer after we insert the jump. */
3893 /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE'
3894 instead of 'b + 3'. */
3895 if (upper_bound == 0)
3897 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3898 INSERT_JUMP (jump, laststart, b + 1
3899 + OFFSET_ADDRESS_SIZE);
3900 b += 1 + OFFSET_ADDRESS_SIZE;
3903 /* Otherwise, we have a nontrivial interval. When
3904 we're all done, the pattern will look like:
3905 set_number_at <jump count> <upper bound>
3906 set_number_at <succeed_n count> <lower bound>
3907 succeed_n <after jump addr> <succeed_n count>
3908 <body of loop>
3909 jump_n <succeed_n addr> <jump count>
3910 (The upper bound and `jump_n' are omitted if
3911 `upper_bound' is 1, though.) */
3912 else
3913 { /* If the upper bound is > 1, we need to insert
3914 more at the end of the loop. */
3915 unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3916 (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3918 GET_BUFFER_SPACE (nbytes);
3920 /* Initialize lower bound of the `succeed_n', even
3921 though it will be set during matching by its
3922 attendant `set_number_at' (inserted next),
3923 because `re_compile_fastmap' needs to know.
3924 Jump to the `jump_n' we might insert below. */
3925 INSERT_JUMP2 (succeed_n, laststart,
3926 b + 1 + 2 * OFFSET_ADDRESS_SIZE
3927 + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3928 , lower_bound);
3929 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3931 /* Code to initialize the lower bound. Insert
3932 before the `succeed_n'. The `5' is the last two
3933 bytes of this `set_number_at', plus 3 bytes of
3934 the following `succeed_n'. */
3935 /* ifdef MBS_SUPPORT, The '1+2*OFFSET_ADDRESS_SIZE'
3936 is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3937 of the following `succeed_n'. */
3938 insert_op2 (set_number_at, laststart, 1
3939 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3940 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3942 if (upper_bound > 1)
3943 { /* More than one repetition is allowed, so
3944 append a backward jump to the `succeed_n'
3945 that starts this interval.
3947 When we've reached this during matching,
3948 we'll have matched the interval once, so
3949 jump back only `upper_bound - 1' times. */
3950 STORE_JUMP2 (jump_n, b, laststart
3951 + 2 * OFFSET_ADDRESS_SIZE + 1,
3952 upper_bound - 1);
3953 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3955 /* The location we want to set is the second
3956 parameter of the `jump_n'; that is `b-2' as
3957 an absolute address. `laststart' will be
3958 the `set_number_at' we're about to insert;
3959 `laststart+3' the number to set, the source
3960 for the relative address. But we are
3961 inserting into the middle of the pattern --
3962 so everything is getting moved up by 5.
3963 Conclusion: (b - 2) - (laststart + 3) + 5,
3964 i.e., b - laststart.
3966 We insert this at the beginning of the loop
3967 so that if we fail during matching, we'll
3968 reinitialize the bounds. */
3969 insert_op2 (set_number_at, laststart, b - laststart,
3970 upper_bound - 1, b);
3971 b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3974 pending_exact = 0;
3975 beg_interval = NULL;
3977 break;
3979 unfetch_interval:
3980 /* If an invalid interval, match the characters as literals. */
3981 assert (beg_interval);
3982 p = beg_interval;
3983 beg_interval = NULL;
3985 /* normal_char and normal_backslash need `c'. */
3986 PATFETCH (c);
3988 if (!(syntax & RE_NO_BK_BRACES))
3990 if (p > pattern && p[-1] == '\\')
3991 goto normal_backslash;
3993 goto normal_char;
3995 #ifdef emacs
3996 /* There is no way to specify the before_dot and after_dot
3997 operators. rms says this is ok. --karl */
3998 case '=':
3999 BUF_PUSH (at_dot);
4000 break;
4002 case 's':
4003 laststart = b;
4004 PATFETCH (c);
4005 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
4006 break;
4008 case 'S':
4009 laststart = b;
4010 PATFETCH (c);
4011 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
4012 break;
4013 #endif /* emacs */
4016 case 'w':
4017 if (syntax & RE_NO_GNU_OPS)
4018 goto normal_char;
4019 laststart = b;
4020 BUF_PUSH (wordchar);
4021 break;
4024 case 'W':
4025 if (syntax & RE_NO_GNU_OPS)
4026 goto normal_char;
4027 laststart = b;
4028 BUF_PUSH (notwordchar);
4029 break;
4032 case '<':
4033 if (syntax & RE_NO_GNU_OPS)
4034 goto normal_char;
4035 BUF_PUSH (wordbeg);
4036 break;
4038 case '>':
4039 if (syntax & RE_NO_GNU_OPS)
4040 goto normal_char;
4041 BUF_PUSH (wordend);
4042 break;
4044 case 'b':
4045 if (syntax & RE_NO_GNU_OPS)
4046 goto normal_char;
4047 BUF_PUSH (wordbound);
4048 break;
4050 case 'B':
4051 if (syntax & RE_NO_GNU_OPS)
4052 goto normal_char;
4053 BUF_PUSH (notwordbound);
4054 break;
4056 case '`':
4057 if (syntax & RE_NO_GNU_OPS)
4058 goto normal_char;
4059 BUF_PUSH (begbuf);
4060 break;
4062 case '\'':
4063 if (syntax & RE_NO_GNU_OPS)
4064 goto normal_char;
4065 BUF_PUSH (endbuf);
4066 break;
4068 case '1': case '2': case '3': case '4': case '5':
4069 case '6': case '7': case '8': case '9':
4070 if (syntax & RE_NO_BK_REFS)
4071 goto normal_char;
4073 c1 = c - '0';
4075 if (c1 > regnum)
4076 FREE_STACK_RETURN (REG_ESUBREG);
4078 /* Can't back reference to a subexpression if inside of it. */
4079 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4080 goto normal_char;
4082 laststart = b;
4083 BUF_PUSH_2 (duplicate, c1);
4084 break;
4087 case '+':
4088 case '?':
4089 if (syntax & RE_BK_PLUS_QM)
4090 goto handle_plus;
4091 else
4092 goto normal_backslash;
4094 default:
4095 normal_backslash:
4096 /* You might think it would be useful for \ to mean
4097 not to translate; but if we don't translate it
4098 it will never match anything. */
4099 c = TRANSLATE (c);
4100 goto normal_char;
4102 break;
4105 default:
4106 /* Expects the character in `c'. */
4107 normal_char:
4108 /* If no exactn currently being built. */
4109 if (!pending_exact
4110 #ifdef MBS_SUPPORT
4111 /* If last exactn handle binary(or character) and
4112 new exactn handle character(or binary). */
4113 || is_exactn_bin != is_binary[p - 1 - pattern]
4114 #endif /* MBS_SUPPORT */
4116 /* If last exactn not at current position. */
4117 || pending_exact + *pending_exact + 1 != b
4119 /* We have only one byte following the exactn for the count. */
4120 || *pending_exact == (1 << BYTEWIDTH) - 1
4122 /* If followed by a repetition operator. */
4123 || *p == '*' || *p == '^'
4124 || ((syntax & RE_BK_PLUS_QM)
4125 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4126 : (*p == '+' || *p == '?'))
4127 || ((syntax & RE_INTERVALS)
4128 && ((syntax & RE_NO_BK_BRACES)
4129 ? *p == '{'
4130 : (p[0] == '\\' && p[1] == '{'))))
4132 /* Start building a new exactn. */
4134 laststart = b;
4136 #ifdef MBS_SUPPORT
4137 /* Is this exactn binary data or character? */
4138 is_exactn_bin = is_binary[p - 1 - pattern];
4139 if (is_exactn_bin)
4140 BUF_PUSH_2 (exactn_bin, 0);
4141 else
4142 BUF_PUSH_2 (exactn, 0);
4143 #else
4144 BUF_PUSH_2 (exactn, 0);
4145 #endif /* MBS_SUPPORT */
4146 pending_exact = b - 1;
4149 BUF_PUSH (c);
4150 (*pending_exact)++;
4151 break;
4152 } /* switch (c) */
4153 } /* while p != pend */
4156 /* Through the pattern now. */
4158 if (fixup_alt_jump)
4159 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4161 if (!COMPILE_STACK_EMPTY)
4162 FREE_STACK_RETURN (REG_EPAREN);
4164 /* If we don't want backtracking, force success
4165 the first time we reach the end of the compiled pattern. */
4166 if (syntax & RE_NO_POSIX_BACKTRACKING)
4167 BUF_PUSH (succeed);
4169 #ifdef MBS_SUPPORT
4170 free (pattern);
4171 free (mbs_offset);
4172 free (is_binary);
4173 #endif
4174 free (compile_stack.stack);
4176 /* We have succeeded; set the length of the buffer. */
4177 #ifdef MBS_SUPPORT
4178 bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4179 #else
4180 bufp->used = b - bufp->buffer;
4181 #endif
4183 #ifdef DEBUG
4184 if (debug)
4186 DEBUG_PRINT1 ("\nCompiled pattern: \n");
4187 print_compiled_pattern (bufp);
4189 #endif /* DEBUG */
4191 #ifndef MATCH_MAY_ALLOCATE
4192 /* Initialize the failure stack to the largest possible stack. This
4193 isn't necessary unless we're trying to avoid calling alloca in
4194 the search and match routines. */
4196 int num_regs = bufp->re_nsub + 1;
4198 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4199 is strictly greater than re_max_failures, the largest possible stack
4200 is 2 * re_max_failures failure points. */
4201 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4203 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4205 # ifdef emacs
4206 if (! fail_stack.stack)
4207 fail_stack.stack
4208 = (fail_stack_elt_t *) xmalloc (fail_stack.size
4209 * sizeof (fail_stack_elt_t));
4210 else
4211 fail_stack.stack
4212 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
4213 (fail_stack.size
4214 * sizeof (fail_stack_elt_t)));
4215 # else /* not emacs */
4216 if (! fail_stack.stack)
4217 fail_stack.stack
4218 = (fail_stack_elt_t *) malloc (fail_stack.size
4219 * sizeof (fail_stack_elt_t));
4220 else
4221 fail_stack.stack
4222 = (fail_stack_elt_t *) realloc (fail_stack.stack,
4223 (fail_stack.size
4224 * sizeof (fail_stack_elt_t)));
4225 # endif /* not emacs */
4228 regex_grow_registers (num_regs);
4230 #endif /* not MATCH_MAY_ALLOCATE */
4232 return REG_NOERROR;
4233 } /* regex_compile */
4235 /* Subroutines for `regex_compile'. */
4237 /* Store OP at LOC followed by two-byte integer parameter ARG. */
4238 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4240 static void
4241 store_op1 (op, loc, arg)
4242 re_opcode_t op;
4243 US_CHAR_TYPE *loc;
4244 int arg;
4246 *loc = (US_CHAR_TYPE) op;
4247 STORE_NUMBER (loc + 1, arg);
4251 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
4252 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4254 static void
4255 store_op2 (op, loc, arg1, arg2)
4256 re_opcode_t op;
4257 US_CHAR_TYPE *loc;
4258 int arg1, arg2;
4260 *loc = (US_CHAR_TYPE) op;
4261 STORE_NUMBER (loc + 1, arg1);
4262 STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4266 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4267 for OP followed by two-byte integer parameter ARG. */
4268 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4270 static void
4271 insert_op1 (op, loc, arg, end)
4272 re_opcode_t op;
4273 US_CHAR_TYPE *loc;
4274 int arg;
4275 US_CHAR_TYPE *end;
4277 register US_CHAR_TYPE *pfrom = end;
4278 register US_CHAR_TYPE *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4280 while (pfrom != loc)
4281 *--pto = *--pfrom;
4283 store_op1 (op, loc, arg);
4287 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
4288 /* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t. */
4290 static void
4291 insert_op2 (op, loc, arg1, arg2, end)
4292 re_opcode_t op;
4293 US_CHAR_TYPE *loc;
4294 int arg1, arg2;
4295 US_CHAR_TYPE *end;
4297 register US_CHAR_TYPE *pfrom = end;
4298 register US_CHAR_TYPE *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4300 while (pfrom != loc)
4301 *--pto = *--pfrom;
4303 store_op2 (op, loc, arg1, arg2);
4307 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
4308 after an alternative or a begin-subexpression. We assume there is at
4309 least one character before the ^. */
4311 static boolean
4312 at_begline_loc_p (pattern, p, syntax)
4313 const CHAR_TYPE *pattern, *p;
4314 reg_syntax_t syntax;
4316 const CHAR_TYPE *prev = p - 2;
4317 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4319 return
4320 /* After a subexpression? */
4321 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4322 /* After an alternative? */
4323 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4327 /* The dual of at_begline_loc_p. This one is for $. We assume there is
4328 at least one character after the $, i.e., `P < PEND'. */
4330 static boolean
4331 at_endline_loc_p (p, pend, syntax)
4332 const CHAR_TYPE *p, *pend;
4333 reg_syntax_t syntax;
4335 const CHAR_TYPE *next = p;
4336 boolean next_backslash = *next == '\\';
4337 const CHAR_TYPE *next_next = p + 1 < pend ? p + 1 : 0;
4339 return
4340 /* Before a subexpression? */
4341 (syntax & RE_NO_BK_PARENS ? *next == ')'
4342 : next_backslash && next_next && *next_next == ')')
4343 /* Before an alternative? */
4344 || (syntax & RE_NO_BK_VBAR ? *next == '|'
4345 : next_backslash && next_next && *next_next == '|');
4349 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4350 false if it's not. */
4352 static boolean
4353 group_in_compile_stack (compile_stack, regnum)
4354 compile_stack_type compile_stack;
4355 regnum_t regnum;
4357 int this_element;
4359 for (this_element = compile_stack.avail - 1;
4360 this_element >= 0;
4361 this_element--)
4362 if (compile_stack.stack[this_element].regnum == regnum)
4363 return true;
4365 return false;
4368 #ifdef MBS_SUPPORT
4369 /* This insert space, which size is "num", into the pattern at "loc".
4370 "end" must point the end of the allocated buffer. */
4371 static void
4372 insert_space (num, loc, end)
4373 int num;
4374 CHAR_TYPE *loc;
4375 CHAR_TYPE *end;
4377 register CHAR_TYPE *pto = end;
4378 register CHAR_TYPE *pfrom = end - num;
4380 while (pfrom >= loc)
4381 *pto-- = *pfrom--;
4383 #endif /* MBS_SUPPORT */
4385 #ifdef MBS_SUPPORT
4386 static reg_errcode_t
4387 compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4388 char_set)
4389 CHAR_TYPE range_start_char;
4390 const CHAR_TYPE **p_ptr, *pend;
4391 CHAR_TYPE *char_set, *b;
4392 RE_TRANSLATE_TYPE translate;
4393 reg_syntax_t syntax;
4395 const CHAR_TYPE *p = *p_ptr;
4396 CHAR_TYPE range_start, range_end;
4397 reg_errcode_t ret;
4398 # ifdef _LIBC
4399 uint32_t nrules;
4400 uint32_t start_val, end_val;
4401 # endif
4402 if (p == pend)
4403 return REG_ERANGE;
4405 # ifdef _LIBC
4406 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4407 if (nrules != 0)
4409 const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4410 _NL_COLLATE_COLLSEQWC);
4411 const unsigned char *extra = (const unsigned char *)
4412 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4414 if (range_start_char < -1)
4416 /* range_start is a collating symbol. */
4417 int32_t *wextra;
4418 /* Retreive the index and get collation sequence value. */
4419 wextra = (int32_t*)(extra + char_set[-range_start_char]);
4420 start_val = wextra[1 + *wextra];
4422 else
4423 start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4425 end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4427 /* Report an error if the range is empty and the syntax prohibits
4428 this. */
4429 ret = ((syntax & RE_NO_EMPTY_RANGES)
4430 && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4432 /* Insert space to the end of the char_ranges. */
4433 insert_space(2, b - char_set[5] - 2, b - 1);
4434 *(b - char_set[5] - 2) = (wchar_t)start_val;
4435 *(b - char_set[5] - 1) = (wchar_t)end_val;
4436 char_set[4]++; /* ranges_index */
4438 else
4439 # endif
4441 range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4442 range_start_char;
4443 range_end = TRANSLATE (p[0]);
4444 /* Report an error if the range is empty and the syntax prohibits
4445 this. */
4446 ret = ((syntax & RE_NO_EMPTY_RANGES)
4447 && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4449 /* Insert space to the end of the char_ranges. */
4450 insert_space(2, b - char_set[5] - 2, b - 1);
4451 *(b - char_set[5] - 2) = range_start;
4452 *(b - char_set[5] - 1) = range_end;
4453 char_set[4]++; /* ranges_index */
4455 /* Have to increment the pointer into the pattern string, so the
4456 caller isn't still at the ending character. */
4457 (*p_ptr)++;
4459 return ret;
4461 #else
4462 /* Read the ending character of a range (in a bracket expression) from the
4463 uncompiled pattern *P_PTR (which ends at PEND). We assume the
4464 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
4465 Then we set the translation of all bits between the starting and
4466 ending characters (inclusive) in the compiled pattern B.
4468 Return an error code.
4470 We use these short variable names so we can use the same macros as
4471 `regex_compile' itself. */
4473 static reg_errcode_t
4474 compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4475 unsigned int range_start_char;
4476 const char **p_ptr, *pend;
4477 RE_TRANSLATE_TYPE translate;
4478 reg_syntax_t syntax;
4479 unsigned char *b;
4481 unsigned this_char;
4482 const char *p = *p_ptr;
4483 reg_errcode_t ret;
4484 # if _LIBC
4485 const unsigned char *collseq;
4486 unsigned int start_colseq;
4487 unsigned int end_colseq;
4488 # else
4489 unsigned end_char;
4490 # endif
4492 if (p == pend)
4493 return REG_ERANGE;
4495 /* Have to increment the pointer into the pattern string, so the
4496 caller isn't still at the ending character. */
4497 (*p_ptr)++;
4499 /* Report an error if the range is empty and the syntax prohibits this. */
4500 ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4502 # if _LIBC
4503 collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4504 _NL_COLLATE_COLLSEQMB);
4506 start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4507 end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4508 for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4510 unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4512 if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4514 SET_LIST_BIT (TRANSLATE (this_char));
4515 ret = REG_NOERROR;
4518 # else
4519 /* Here we see why `this_char' has to be larger than an `unsigned
4520 char' -- we would otherwise go into an infinite loop, since all
4521 characters <= 0xff. */
4522 range_start_char = TRANSLATE (range_start_char);
4523 /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4524 and some compilers cast it to int implicitly, so following for_loop
4525 may fall to (almost) infinite loop.
4526 e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4527 To avoid this, we cast p[0] to unsigned int and truncate it. */
4528 end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4530 for (this_char = range_start_char; this_char <= end_char; ++this_char)
4532 SET_LIST_BIT (TRANSLATE (this_char));
4533 ret = REG_NOERROR;
4535 # endif
4537 return ret;
4539 #endif /* MBS_SUPPORT */
4541 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4542 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4543 characters can start a string that matches the pattern. This fastmap
4544 is used by re_search to skip quickly over impossible starting points.
4546 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4547 area as BUFP->fastmap.
4549 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4550 the pattern buffer.
4552 Returns 0 if we succeed, -2 if an internal error. */
4554 #ifdef MBS_SUPPORT
4555 /* local function for re_compile_fastmap.
4556 truncate wchar_t character to char. */
4557 static unsigned char truncate_wchar (CHAR_TYPE c);
4559 static unsigned char
4560 truncate_wchar (c)
4561 CHAR_TYPE c;
4563 unsigned char buf[MB_LEN_MAX];
4564 int retval = wctomb(buf, c);
4565 return retval > 0 ? buf[0] : (unsigned char)c;
4567 #endif /* MBS_SUPPORT */
4570 re_compile_fastmap (bufp)
4571 struct re_pattern_buffer *bufp;
4573 int j, k;
4574 #ifdef MATCH_MAY_ALLOCATE
4575 fail_stack_type fail_stack;
4576 #endif
4577 #ifndef REGEX_MALLOC
4578 char *destination;
4579 #endif
4581 register char *fastmap = bufp->fastmap;
4583 #ifdef MBS_SUPPORT
4584 /* We need to cast pattern to (wchar_t*), because we casted this compiled
4585 pattern to (char*) in regex_compile. */
4586 US_CHAR_TYPE *pattern = (US_CHAR_TYPE*)bufp->buffer;
4587 register US_CHAR_TYPE *pend = (US_CHAR_TYPE*) (bufp->buffer + bufp->used);
4588 #else
4589 US_CHAR_TYPE *pattern = bufp->buffer;
4590 register US_CHAR_TYPE *pend = pattern + bufp->used;
4591 #endif /* MBS_SUPPORT */
4592 US_CHAR_TYPE *p = pattern;
4594 #ifdef REL_ALLOC
4595 /* This holds the pointer to the failure stack, when
4596 it is allocated relocatably. */
4597 fail_stack_elt_t *failure_stack_ptr;
4598 #endif
4600 /* Assume that each path through the pattern can be null until
4601 proven otherwise. We set this false at the bottom of switch
4602 statement, to which we get only if a particular path doesn't
4603 match the empty string. */
4604 boolean path_can_be_null = true;
4606 /* We aren't doing a `succeed_n' to begin with. */
4607 boolean succeed_n_p = false;
4609 assert (fastmap != NULL && p != NULL);
4611 INIT_FAIL_STACK ();
4612 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4613 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4614 bufp->can_be_null = 0;
4616 while (1)
4618 if (p == pend || *p == succeed)
4620 /* We have reached the (effective) end of pattern. */
4621 if (!FAIL_STACK_EMPTY ())
4623 bufp->can_be_null |= path_can_be_null;
4625 /* Reset for next path. */
4626 path_can_be_null = true;
4628 p = fail_stack.stack[--fail_stack.avail].pointer;
4630 continue;
4632 else
4633 break;
4636 /* We should never be about to go beyond the end of the pattern. */
4637 assert (p < pend);
4639 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4642 /* I guess the idea here is to simply not bother with a fastmap
4643 if a backreference is used, since it's too hard to figure out
4644 the fastmap for the corresponding group. Setting
4645 `can_be_null' stops `re_search_2' from using the fastmap, so
4646 that is all we do. */
4647 case duplicate:
4648 bufp->can_be_null = 1;
4649 goto done;
4652 /* Following are the cases which match a character. These end
4653 with `break'. */
4655 #ifdef MBS_SUPPORT
4656 case exactn:
4657 fastmap[truncate_wchar(p[1])] = 1;
4658 break;
4659 case exactn_bin:
4660 fastmap[p[1]] = 1;
4661 break;
4662 #else
4663 case exactn:
4664 fastmap[p[1]] = 1;
4665 break;
4666 #endif /* MBS_SUPPORT */
4669 #ifdef MBS_SUPPORT
4670 /* It is hard to distinguish fastmap from (multi byte) characters
4671 which depends on current locale. */
4672 case charset:
4673 case charset_not:
4674 case wordchar:
4675 case notwordchar:
4676 bufp->can_be_null = 1;
4677 goto done;
4678 #else
4679 case charset:
4680 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4681 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4682 fastmap[j] = 1;
4683 break;
4686 case charset_not:
4687 /* Chars beyond end of map must be allowed. */
4688 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4689 fastmap[j] = 1;
4691 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4692 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4693 fastmap[j] = 1;
4694 break;
4697 case wordchar:
4698 for (j = 0; j < (1 << BYTEWIDTH); j++)
4699 if (SYNTAX (j) == Sword)
4700 fastmap[j] = 1;
4701 break;
4704 case notwordchar:
4705 for (j = 0; j < (1 << BYTEWIDTH); j++)
4706 if (SYNTAX (j) != Sword)
4707 fastmap[j] = 1;
4708 break;
4709 #endif
4711 case anychar:
4713 int fastmap_newline = fastmap['\n'];
4715 /* `.' matches anything ... */
4716 for (j = 0; j < (1 << BYTEWIDTH); j++)
4717 fastmap[j] = 1;
4719 /* ... except perhaps newline. */
4720 if (!(bufp->syntax & RE_DOT_NEWLINE))
4721 fastmap['\n'] = fastmap_newline;
4723 /* Return if we have already set `can_be_null'; if we have,
4724 then the fastmap is irrelevant. Something's wrong here. */
4725 else if (bufp->can_be_null)
4726 goto done;
4728 /* Otherwise, have to check alternative paths. */
4729 break;
4732 #ifdef emacs
4733 case syntaxspec:
4734 k = *p++;
4735 for (j = 0; j < (1 << BYTEWIDTH); j++)
4736 if (SYNTAX (j) == (enum syntaxcode) k)
4737 fastmap[j] = 1;
4738 break;
4741 case notsyntaxspec:
4742 k = *p++;
4743 for (j = 0; j < (1 << BYTEWIDTH); j++)
4744 if (SYNTAX (j) != (enum syntaxcode) k)
4745 fastmap[j] = 1;
4746 break;
4749 /* All cases after this match the empty string. These end with
4750 `continue'. */
4753 case before_dot:
4754 case at_dot:
4755 case after_dot:
4756 continue;
4757 #endif /* emacs */
4760 case no_op:
4761 case begline:
4762 case endline:
4763 case begbuf:
4764 case endbuf:
4765 case wordbound:
4766 case notwordbound:
4767 case wordbeg:
4768 case wordend:
4769 case push_dummy_failure:
4770 continue;
4773 case jump_n:
4774 case pop_failure_jump:
4775 case maybe_pop_jump:
4776 case jump:
4777 case jump_past_alt:
4778 case dummy_failure_jump:
4779 EXTRACT_NUMBER_AND_INCR (j, p);
4780 p += j;
4781 if (j > 0)
4782 continue;
4784 /* Jump backward implies we just went through the body of a
4785 loop and matched nothing. Opcode jumped to should be
4786 `on_failure_jump' or `succeed_n'. Just treat it like an
4787 ordinary jump. For a * loop, it has pushed its failure
4788 point already; if so, discard that as redundant. */
4789 if ((re_opcode_t) *p != on_failure_jump
4790 && (re_opcode_t) *p != succeed_n)
4791 continue;
4793 p++;
4794 EXTRACT_NUMBER_AND_INCR (j, p);
4795 p += j;
4797 /* If what's on the stack is where we are now, pop it. */
4798 if (!FAIL_STACK_EMPTY ()
4799 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4800 fail_stack.avail--;
4802 continue;
4805 case on_failure_jump:
4806 case on_failure_keep_string_jump:
4807 handle_on_failure_jump:
4808 EXTRACT_NUMBER_AND_INCR (j, p);
4810 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4811 end of the pattern. We don't want to push such a point,
4812 since when we restore it above, entering the switch will
4813 increment `p' past the end of the pattern. We don't need
4814 to push such a point since we obviously won't find any more
4815 fastmap entries beyond `pend'. Such a pattern can match
4816 the null string, though. */
4817 if (p + j < pend)
4819 if (!PUSH_PATTERN_OP (p + j, fail_stack))
4821 RESET_FAIL_STACK ();
4822 return -2;
4825 else
4826 bufp->can_be_null = 1;
4828 if (succeed_n_p)
4830 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
4831 succeed_n_p = false;
4834 continue;
4837 case succeed_n:
4838 /* Get to the number of times to succeed. */
4839 p += OFFSET_ADDRESS_SIZE;
4841 /* Increment p past the n for when k != 0. */
4842 EXTRACT_NUMBER_AND_INCR (k, p);
4843 if (k == 0)
4845 p -= 2 * OFFSET_ADDRESS_SIZE;
4846 succeed_n_p = true; /* Spaghetti code alert. */
4847 goto handle_on_failure_jump;
4849 continue;
4852 case set_number_at:
4853 p += 2 * OFFSET_ADDRESS_SIZE;
4854 continue;
4857 case start_memory:
4858 case stop_memory:
4859 p += 2;
4860 continue;
4863 default:
4864 abort (); /* We have listed all the cases. */
4865 } /* switch *p++ */
4867 /* Getting here means we have found the possible starting
4868 characters for one path of the pattern -- and that the empty
4869 string does not match. We need not follow this path further.
4870 Instead, look at the next alternative (remembered on the
4871 stack), or quit if no more. The test at the top of the loop
4872 does these things. */
4873 path_can_be_null = false;
4874 p = pend;
4875 } /* while p */
4877 /* Set `can_be_null' for the last path (also the first path, if the
4878 pattern is empty). */
4879 bufp->can_be_null |= path_can_be_null;
4881 done:
4882 RESET_FAIL_STACK ();
4883 return 0;
4884 } /* re_compile_fastmap */
4885 #ifdef _LIBC
4886 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4887 #endif
4889 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4890 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4891 this memory for recording register information. STARTS and ENDS
4892 must be allocated using the malloc library routine, and must each
4893 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4895 If NUM_REGS == 0, then subsequent matches should allocate their own
4896 register data.
4898 Unless this function is called, the first search or match using
4899 PATTERN_BUFFER will allocate its own register data, without
4900 freeing the old data. */
4902 void
4903 re_set_registers (bufp, regs, num_regs, starts, ends)
4904 struct re_pattern_buffer *bufp;
4905 struct re_registers *regs;
4906 unsigned num_regs;
4907 regoff_t *starts, *ends;
4909 if (num_regs)
4911 bufp->regs_allocated = REGS_REALLOCATE;
4912 regs->num_regs = num_regs;
4913 regs->start = starts;
4914 regs->end = ends;
4916 else
4918 bufp->regs_allocated = REGS_UNALLOCATED;
4919 regs->num_regs = 0;
4920 regs->start = regs->end = (regoff_t *) 0;
4923 #ifdef _LIBC
4924 weak_alias (__re_set_registers, re_set_registers)
4925 #endif
4927 /* Searching routines. */
4929 /* Like re_search_2, below, but only one string is specified, and
4930 doesn't let you say where to stop matching. */
4933 re_search (bufp, string, size, startpos, range, regs)
4934 struct re_pattern_buffer *bufp;
4935 const char *string;
4936 int size, startpos, range;
4937 struct re_registers *regs;
4939 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4940 regs, size);
4942 #ifdef _LIBC
4943 weak_alias (__re_search, re_search)
4944 #endif
4947 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4948 virtual concatenation of STRING1 and STRING2, starting first at index
4949 STARTPOS, then at STARTPOS + 1, and so on.
4951 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4953 RANGE is how far to scan while trying to match. RANGE = 0 means try
4954 only at STARTPOS; in general, the last start tried is STARTPOS +
4955 RANGE.
4957 In REGS, return the indices of the virtual concatenation of STRING1
4958 and STRING2 that matched the entire BUFP->buffer and its contained
4959 subexpressions.
4961 Do not consider matching one past the index STOP in the virtual
4962 concatenation of STRING1 and STRING2.
4964 We return either the position in the strings at which the match was
4965 found, -1 if no match, or -2 if error (such as failure
4966 stack overflow). */
4969 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
4970 struct re_pattern_buffer *bufp;
4971 const char *string1, *string2;
4972 int size1, size2;
4973 int startpos;
4974 int range;
4975 struct re_registers *regs;
4976 int stop;
4978 int val;
4979 register char *fastmap = bufp->fastmap;
4980 register RE_TRANSLATE_TYPE translate = bufp->translate;
4981 int total_size = size1 + size2;
4982 int endpos = startpos + range;
4984 /* Check for out-of-range STARTPOS. */
4985 if (startpos < 0 || startpos > total_size)
4986 return -1;
4988 /* Fix up RANGE if it might eventually take us outside
4989 the virtual concatenation of STRING1 and STRING2.
4990 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4991 if (endpos < 0)
4992 range = 0 - startpos;
4993 else if (endpos > total_size)
4994 range = total_size - startpos;
4996 /* If the search isn't to be a backwards one, don't waste time in a
4997 search for a pattern that must be anchored. */
4998 if (bufp->used > 0 && range > 0
4999 && ((re_opcode_t) bufp->buffer[0] == begbuf
5000 /* `begline' is like `begbuf' if it cannot match at newlines. */
5001 || ((re_opcode_t) bufp->buffer[0] == begline
5002 && !bufp->newline_anchor)))
5004 if (startpos > 0)
5005 return -1;
5006 else
5007 range = 1;
5010 #ifdef emacs
5011 /* In a forward search for something that starts with \=.
5012 don't keep searching past point. */
5013 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5015 range = PT - startpos;
5016 if (range <= 0)
5017 return -1;
5019 #endif /* emacs */
5021 /* Update the fastmap now if not correct already. */
5022 if (fastmap && !bufp->fastmap_accurate)
5023 if (re_compile_fastmap (bufp) == -2)
5024 return -2;
5026 /* Loop through the string, looking for a place to start matching. */
5027 for (;;)
5029 /* If a fastmap is supplied, skip quickly over characters that
5030 cannot be the start of a match. If the pattern can match the
5031 null string, however, we don't need to skip characters; we want
5032 the first null string. */
5033 if (fastmap && startpos < total_size && !bufp->can_be_null)
5035 if (range > 0) /* Searching forwards. */
5037 register const char *d;
5038 register int lim = 0;
5039 int irange = range;
5041 if (startpos < size1 && startpos + range >= size1)
5042 lim = range - (size1 - startpos);
5044 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5046 /* Written out as an if-else to avoid testing `translate'
5047 inside the loop. */
5048 if (translate)
5049 while (range > lim
5050 && !fastmap[(unsigned char)
5051 translate[(unsigned char) *d++]])
5052 range--;
5053 else
5054 while (range > lim && !fastmap[(unsigned char) *d++])
5055 range--;
5057 startpos += irange - range;
5059 else /* Searching backwards. */
5061 register char c = (size1 == 0 || startpos >= size1
5062 ? string2[startpos - size1]
5063 : string1[startpos]);
5065 if (!fastmap[(unsigned char) TRANSLATE (c)])
5066 goto advance;
5070 /* If can't match the null string, and that's all we have left, fail. */
5071 if (range >= 0 && startpos == total_size && fastmap
5072 && !bufp->can_be_null)
5073 return -1;
5075 val = re_match_2_internal (bufp, string1, size1, string2, size2,
5076 startpos, regs, stop);
5077 #ifndef REGEX_MALLOC
5078 # ifdef C_ALLOCA
5079 alloca (0);
5080 # endif
5081 #endif
5083 if (val >= 0)
5084 return startpos;
5086 if (val == -2)
5087 return -2;
5089 advance:
5090 if (!range)
5091 break;
5092 else if (range > 0)
5094 range--;
5095 startpos++;
5097 else
5099 range++;
5100 startpos--;
5103 return -1;
5104 } /* re_search_2 */
5105 #ifdef _LIBC
5106 weak_alias (__re_search_2, re_search_2)
5107 #endif
5109 #ifdef MBS_SUPPORT
5110 /* This converts PTR, a pointer into one of the search wchar_t strings
5111 `string1' and `string2' into an multibyte string offset from the
5112 beginning of that string. We use mbs_offset to optimize.
5113 See convert_mbs_to_wcs. */
5114 # define POINTER_TO_OFFSET(ptr) \
5115 (FIRST_STRING_P (ptr) \
5116 ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0)) \
5117 : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0) \
5118 + csize1)))
5119 #else
5120 /* This converts PTR, a pointer into one of the search strings `string1'
5121 and `string2' into an offset from the beginning of that string. */
5122 # define POINTER_TO_OFFSET(ptr) \
5123 (FIRST_STRING_P (ptr) \
5124 ? ((regoff_t) ((ptr) - string1)) \
5125 : ((regoff_t) ((ptr) - string2 + size1)))
5126 #endif /* MBS_SUPPORT */
5128 /* Macros for dealing with the split strings in re_match_2. */
5130 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
5132 /* Call before fetching a character with *d. This switches over to
5133 string2 if necessary. */
5134 #define PREFETCH() \
5135 while (d == dend) \
5137 /* End of string2 => fail. */ \
5138 if (dend == end_match_2) \
5139 goto fail; \
5140 /* End of string1 => advance to string2. */ \
5141 d = string2; \
5142 dend = end_match_2; \
5146 /* Test if at very beginning or at very end of the virtual concatenation
5147 of `string1' and `string2'. If only one string, it's `string2'. */
5148 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5149 #define AT_STRINGS_END(d) ((d) == end2)
5152 /* Test if D points to a character which is word-constituent. We have
5153 two special cases to check for: if past the end of string1, look at
5154 the first character in string2; and if before the beginning of
5155 string2, look at the last character in string1. */
5156 #ifdef MBS_SUPPORT
5157 /* Use internationalized API instead of SYNTAX. */
5158 # define WORDCHAR_P(d) \
5159 (iswalnum ((wint_t)((d) == end1 ? *string2 \
5160 : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5161 #else
5162 # define WORDCHAR_P(d) \
5163 (SYNTAX ((d) == end1 ? *string2 \
5164 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
5165 == Sword)
5166 #endif /* MBS_SUPPORT */
5168 /* Disabled due to a compiler bug -- see comment at case wordbound */
5169 #if 0
5170 /* Test if the character before D and the one at D differ with respect
5171 to being word-constituent. */
5172 #define AT_WORD_BOUNDARY(d) \
5173 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
5174 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5175 #endif
5177 /* Free everything we malloc. */
5178 #ifdef MATCH_MAY_ALLOCATE
5179 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5180 # ifdef MBS_SUPPORT
5181 # define FREE_VARIABLES() \
5182 do { \
5183 REGEX_FREE_STACK (fail_stack.stack); \
5184 FREE_VAR (regstart); \
5185 FREE_VAR (regend); \
5186 FREE_VAR (old_regstart); \
5187 FREE_VAR (old_regend); \
5188 FREE_VAR (best_regstart); \
5189 FREE_VAR (best_regend); \
5190 FREE_VAR (reg_info); \
5191 FREE_VAR (reg_dummy); \
5192 FREE_VAR (reg_info_dummy); \
5193 FREE_VAR (string1); \
5194 FREE_VAR (string2); \
5195 FREE_VAR (mbs_offset1); \
5196 FREE_VAR (mbs_offset2); \
5197 } while (0)
5198 # else /* not MBS_SUPPORT */
5199 # define FREE_VARIABLES() \
5200 do { \
5201 REGEX_FREE_STACK (fail_stack.stack); \
5202 FREE_VAR (regstart); \
5203 FREE_VAR (regend); \
5204 FREE_VAR (old_regstart); \
5205 FREE_VAR (old_regend); \
5206 FREE_VAR (best_regstart); \
5207 FREE_VAR (best_regend); \
5208 FREE_VAR (reg_info); \
5209 FREE_VAR (reg_dummy); \
5210 FREE_VAR (reg_info_dummy); \
5211 } while (0)
5212 # endif /* MBS_SUPPORT */
5213 #else
5214 # define FREE_VAR(var) if (var) free (var); var = NULL
5215 # ifdef MBS_SUPPORT
5216 # define FREE_VARIABLES() \
5217 do { \
5218 FREE_VAR (string1); \
5219 FREE_VAR (string2); \
5220 FREE_VAR (mbs_offset1); \
5221 FREE_VAR (mbs_offset2); \
5222 } while (0)
5223 # else
5224 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
5225 # endif /* MBS_SUPPORT */
5226 #endif /* not MATCH_MAY_ALLOCATE */
5228 /* These values must meet several constraints. They must not be valid
5229 register values; since we have a limit of 255 registers (because
5230 we use only one byte in the pattern for the register number), we can
5231 use numbers larger than 255. They must differ by 1, because of
5232 NUM_FAILURE_ITEMS above. And the value for the lowest register must
5233 be larger than the value for the highest register, so we do not try
5234 to actually save any registers when none are active. */
5235 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5236 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5238 /* Matching routines. */
5240 #ifndef emacs /* Emacs never uses this. */
5241 /* re_match is like re_match_2 except it takes only a single string. */
5244 re_match (bufp, string, size, pos, regs)
5245 struct re_pattern_buffer *bufp;
5246 const char *string;
5247 int size, pos;
5248 struct re_registers *regs;
5250 int result = re_match_2_internal (bufp, NULL, 0, string, size,
5251 pos, regs, size);
5252 # ifndef REGEX_MALLOC
5253 # ifdef C_ALLOCA
5254 alloca (0);
5255 # endif
5256 # endif
5257 return result;
5259 # ifdef _LIBC
5260 weak_alias (__re_match, re_match)
5261 # endif
5262 #endif /* not emacs */
5264 static boolean group_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5265 US_CHAR_TYPE *end,
5266 register_info_type *reg_info));
5267 static boolean alt_match_null_string_p _RE_ARGS ((US_CHAR_TYPE *p,
5268 US_CHAR_TYPE *end,
5269 register_info_type *reg_info));
5270 static boolean common_op_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5271 US_CHAR_TYPE *end,
5272 register_info_type *reg_info));
5273 static int bcmp_translate _RE_ARGS ((const CHAR_TYPE *s1, const CHAR_TYPE *s2,
5274 int len, char *translate));
5276 /* re_match_2 matches the compiled pattern in BUFP against the
5277 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5278 and SIZE2, respectively). We start matching at POS, and stop
5279 matching at STOP.
5281 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5282 store offsets for the substring each group matched in REGS. See the
5283 documentation for exactly how many groups we fill.
5285 We return -1 if no match, -2 if an internal error (such as the
5286 failure stack overflowing). Otherwise, we return the length of the
5287 matched substring. */
5290 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5291 struct re_pattern_buffer *bufp;
5292 const char *string1, *string2;
5293 int size1, size2;
5294 int pos;
5295 struct re_registers *regs;
5296 int stop;
5298 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
5299 pos, regs, stop);
5300 #ifndef REGEX_MALLOC
5301 # ifdef C_ALLOCA
5302 alloca (0);
5303 # endif
5304 #endif
5305 return result;
5307 #ifdef _LIBC
5308 weak_alias (__re_match_2, re_match_2)
5309 #endif
5311 #ifdef MBS_SUPPORT
5312 /* This check the substring (from 0, to length) of the multibyte string,
5313 to which offset_buffer correspond. And count how many wchar_t_characters
5314 the substring occupy. We use offset_buffer to optimization.
5315 See convert_mbs_to_wcs. */
5316 static int
5317 count_mbs_length(offset_buffer, length)
5318 int *offset_buffer;
5319 int length;
5321 int wcs_size;
5323 /* Check whether the size is valid. */
5324 if (length < 0)
5325 return -1;
5327 if (offset_buffer == NULL)
5328 return 0;
5330 for (wcs_size = 0 ; offset_buffer[wcs_size] != -1 ; wcs_size++)
5332 if (offset_buffer[wcs_size] == length)
5333 return wcs_size;
5334 if (offset_buffer[wcs_size] > length)
5335 /* It is a fragment of a wide character. */
5336 return -1;
5339 /* We reached at the sentinel. */
5340 return -1;
5342 #endif /* MBS_SUPPORT */
5344 /* This is a separate function so that we can force an alloca cleanup
5345 afterwards. */
5346 static int
5347 #ifdef MBS_SUPPORT
5348 re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos, regs, stop)
5349 struct re_pattern_buffer *bufp;
5350 const char *cstring1, *cstring2;
5351 int csize1, csize2;
5352 #else
5353 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
5354 struct re_pattern_buffer *bufp;
5355 const char *string1, *string2;
5356 int size1, size2;
5357 #endif
5358 int pos;
5359 struct re_registers *regs;
5360 int stop;
5362 /* General temporaries. */
5363 int mcnt;
5364 US_CHAR_TYPE *p1;
5365 #ifdef MBS_SUPPORT
5366 /* We need wchar_t* buffers correspond to string1, string2. */
5367 CHAR_TYPE *string1 = NULL, *string2 = NULL;
5368 /* We need the size of wchar_t buffers correspond to csize1, csize2. */
5369 int size1 = 0, size2 = 0;
5370 /* offset buffer for optimizatoin. See convert_mbs_to_wc. */
5371 int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5372 /* They hold whether each wchar_t is binary data or not. */
5373 char *is_binary = NULL;
5374 #endif /* MBS_SUPPORT */
5376 /* Just past the end of the corresponding string. */
5377 const CHAR_TYPE *end1, *end2;
5379 /* Pointers into string1 and string2, just past the last characters in
5380 each to consider matching. */
5381 const CHAR_TYPE *end_match_1, *end_match_2;
5383 /* Where we are in the data, and the end of the current string. */
5384 const CHAR_TYPE *d, *dend;
5386 /* Where we are in the pattern, and the end of the pattern. */
5387 #ifdef MBS_SUPPORT
5388 US_CHAR_TYPE *pattern, *p;
5389 register US_CHAR_TYPE *pend;
5390 #else
5391 US_CHAR_TYPE *p = bufp->buffer;
5392 register US_CHAR_TYPE *pend = p + bufp->used;
5393 #endif /* MBS_SUPPORT */
5395 /* Mark the opcode just after a start_memory, so we can test for an
5396 empty subpattern when we get to the stop_memory. */
5397 US_CHAR_TYPE *just_past_start_mem = 0;
5399 /* We use this to map every character in the string. */
5400 RE_TRANSLATE_TYPE translate = bufp->translate;
5402 /* Failure point stack. Each place that can handle a failure further
5403 down the line pushes a failure point on this stack. It consists of
5404 restart, regend, and reg_info for all registers corresponding to
5405 the subexpressions we're currently inside, plus the number of such
5406 registers, and, finally, two char *'s. The first char * is where
5407 to resume scanning the pattern; the second one is where to resume
5408 scanning the strings. If the latter is zero, the failure point is
5409 a ``dummy''; if a failure happens and the failure point is a dummy,
5410 it gets discarded and the next next one is tried. */
5411 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5412 fail_stack_type fail_stack;
5413 #endif
5414 #ifdef DEBUG
5415 static unsigned failure_id;
5416 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5417 #endif
5419 #ifdef REL_ALLOC
5420 /* This holds the pointer to the failure stack, when
5421 it is allocated relocatably. */
5422 fail_stack_elt_t *failure_stack_ptr;
5423 #endif
5425 /* We fill all the registers internally, independent of what we
5426 return, for use in backreferences. The number here includes
5427 an element for register zero. */
5428 size_t num_regs = bufp->re_nsub + 1;
5430 /* The currently active registers. */
5431 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5432 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5434 /* Information on the contents of registers. These are pointers into
5435 the input strings; they record just what was matched (on this
5436 attempt) by a subexpression part of the pattern, that is, the
5437 regnum-th regstart pointer points to where in the pattern we began
5438 matching and the regnum-th regend points to right after where we
5439 stopped matching the regnum-th subexpression. (The zeroth register
5440 keeps track of what the whole pattern matches.) */
5441 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5442 const CHAR_TYPE **regstart, **regend;
5443 #endif
5445 /* If a group that's operated upon by a repetition operator fails to
5446 match anything, then the register for its start will need to be
5447 restored because it will have been set to wherever in the string we
5448 are when we last see its open-group operator. Similarly for a
5449 register's end. */
5450 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5451 const CHAR_TYPE **old_regstart, **old_regend;
5452 #endif
5454 /* The is_active field of reg_info helps us keep track of which (possibly
5455 nested) subexpressions we are currently in. The matched_something
5456 field of reg_info[reg_num] helps us tell whether or not we have
5457 matched any of the pattern so far this time through the reg_num-th
5458 subexpression. These two fields get reset each time through any
5459 loop their register is in. */
5460 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5461 register_info_type *reg_info;
5462 #endif
5464 /* The following record the register info as found in the above
5465 variables when we find a match better than any we've seen before.
5466 This happens as we backtrack through the failure points, which in
5467 turn happens only if we have not yet matched the entire string. */
5468 unsigned best_regs_set = false;
5469 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5470 const CHAR_TYPE **best_regstart, **best_regend;
5471 #endif
5473 /* Logically, this is `best_regend[0]'. But we don't want to have to
5474 allocate space for that if we're not allocating space for anything
5475 else (see below). Also, we never need info about register 0 for
5476 any of the other register vectors, and it seems rather a kludge to
5477 treat `best_regend' differently than the rest. So we keep track of
5478 the end of the best match so far in a separate variable. We
5479 initialize this to NULL so that when we backtrack the first time
5480 and need to test it, it's not garbage. */
5481 const CHAR_TYPE *match_end = NULL;
5483 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
5484 int set_regs_matched_done = 0;
5486 /* Used when we pop values we don't care about. */
5487 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5488 const CHAR_TYPE **reg_dummy;
5489 register_info_type *reg_info_dummy;
5490 #endif
5492 #ifdef DEBUG
5493 /* Counts the total number of registers pushed. */
5494 unsigned num_regs_pushed = 0;
5495 #endif
5497 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5499 INIT_FAIL_STACK ();
5501 #ifdef MATCH_MAY_ALLOCATE
5502 /* Do not bother to initialize all the register variables if there are
5503 no groups in the pattern, as it takes a fair amount of time. If
5504 there are groups, we include space for register 0 (the whole
5505 pattern), even though we never use it, since it simplifies the
5506 array indexing. We should fix this. */
5507 if (bufp->re_nsub)
5509 regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5510 regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5511 old_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5512 old_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5513 best_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5514 best_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5515 reg_info = REGEX_TALLOC (num_regs, register_info_type);
5516 reg_dummy = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5517 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
5519 if (!(regstart && regend && old_regstart && old_regend && reg_info
5520 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5522 FREE_VARIABLES ();
5523 return -2;
5526 else
5528 /* We must initialize all our variables to NULL, so that
5529 `FREE_VARIABLES' doesn't try to free them. */
5530 regstart = regend = old_regstart = old_regend = best_regstart
5531 = best_regend = reg_dummy = NULL;
5532 reg_info = reg_info_dummy = (register_info_type *) NULL;
5534 #endif /* MATCH_MAY_ALLOCATE */
5536 /* The starting position is bogus. */
5537 #ifdef MBS_SUPPORT
5538 if (pos < 0 || pos > csize1 + csize2)
5539 #else
5540 if (pos < 0 || pos > size1 + size2)
5541 #endif
5543 FREE_VARIABLES ();
5544 return -1;
5547 #ifdef MBS_SUPPORT
5548 /* Allocate wchar_t array for string1 and string2 and
5549 fill them with converted string. */
5550 if (csize1 != 0)
5552 string1 = REGEX_TALLOC (csize1 + 1, CHAR_TYPE);
5553 mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5554 is_binary = REGEX_TALLOC (csize1 + 1, char);
5555 if (!string1 || !mbs_offset1 || !is_binary)
5557 FREE_VAR (string1);
5558 FREE_VAR (mbs_offset1);
5559 FREE_VAR (is_binary);
5560 return -2;
5562 size1 = convert_mbs_to_wcs(string1, cstring1, csize1,
5563 mbs_offset1, is_binary);
5564 string1[size1] = L'\0'; /* for a sentinel */
5565 FREE_VAR (is_binary);
5567 if (csize2 != 0)
5569 string2 = REGEX_TALLOC (csize2 + 1, CHAR_TYPE);
5570 mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5571 is_binary = REGEX_TALLOC (csize2 + 1, char);
5572 if (!string2 || !mbs_offset2 || !is_binary)
5574 FREE_VAR (string1);
5575 FREE_VAR (mbs_offset1);
5576 FREE_VAR (string2);
5577 FREE_VAR (mbs_offset2);
5578 FREE_VAR (is_binary);
5579 return -2;
5581 size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5582 mbs_offset2, is_binary);
5583 string2[size2] = L'\0'; /* for a sentinel */
5584 FREE_VAR (is_binary);
5587 /* We need to cast pattern to (wchar_t*), because we casted this compiled
5588 pattern to (char*) in regex_compile. */
5589 p = pattern = (CHAR_TYPE*)bufp->buffer;
5590 pend = (CHAR_TYPE*)(bufp->buffer + bufp->used);
5592 #endif /* MBS_SUPPORT */
5594 /* Initialize subexpression text positions to -1 to mark ones that no
5595 start_memory/stop_memory has been seen for. Also initialize the
5596 register information struct. */
5597 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5599 regstart[mcnt] = regend[mcnt]
5600 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5602 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5603 IS_ACTIVE (reg_info[mcnt]) = 0;
5604 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5605 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5608 /* We move `string1' into `string2' if the latter's empty -- but not if
5609 `string1' is null. */
5610 if (size2 == 0 && string1 != NULL)
5612 string2 = string1;
5613 size2 = size1;
5614 string1 = 0;
5615 size1 = 0;
5617 end1 = string1 + size1;
5618 end2 = string2 + size2;
5620 /* Compute where to stop matching, within the two strings. */
5621 #ifdef MBS_SUPPORT
5622 if (stop <= csize1)
5624 mcnt = count_mbs_length(mbs_offset1, stop);
5625 end_match_1 = string1 + mcnt;
5626 end_match_2 = string2;
5628 else
5630 end_match_1 = end1;
5631 mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5632 end_match_2 = string2 + mcnt;
5634 if (mcnt < 0)
5635 { /* count_mbs_length return error. */
5636 FREE_VARIABLES ();
5637 return -1;
5639 #else
5640 if (stop <= size1)
5642 end_match_1 = string1 + stop;
5643 end_match_2 = string2;
5645 else
5647 end_match_1 = end1;
5648 end_match_2 = string2 + stop - size1;
5650 #endif /* MBS_SUPPORT */
5652 /* `p' scans through the pattern as `d' scans through the data.
5653 `dend' is the end of the input string that `d' points within. `d'
5654 is advanced into the following input string whenever necessary, but
5655 this happens before fetching; therefore, at the beginning of the
5656 loop, `d' can be pointing at the end of a string, but it cannot
5657 equal `string2'. */
5658 #ifdef MBS_SUPPORT
5659 if (size1 > 0 && pos <= csize1)
5661 mcnt = count_mbs_length(mbs_offset1, pos);
5662 d = string1 + mcnt;
5663 dend = end_match_1;
5665 else
5667 mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5668 d = string2 + mcnt;
5669 dend = end_match_2;
5672 if (mcnt < 0)
5673 { /* count_mbs_length return error. */
5674 FREE_VARIABLES ();
5675 return -1;
5677 #else
5678 if (size1 > 0 && pos <= size1)
5680 d = string1 + pos;
5681 dend = end_match_1;
5683 else
5685 d = string2 + pos - size1;
5686 dend = end_match_2;
5688 #endif /* MBS_SUPPORT */
5690 DEBUG_PRINT1 ("The compiled pattern is:\n");
5691 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5692 DEBUG_PRINT1 ("The string to match is: `");
5693 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5694 DEBUG_PRINT1 ("'\n");
5696 /* This loops over pattern commands. It exits by returning from the
5697 function if the match is complete, or it drops through if the match
5698 fails at this starting point in the input data. */
5699 for (;;)
5701 #ifdef _LIBC
5702 DEBUG_PRINT2 ("\n%p: ", p);
5703 #else
5704 DEBUG_PRINT2 ("\n0x%x: ", p);
5705 #endif
5707 if (p == pend)
5708 { /* End of pattern means we might have succeeded. */
5709 DEBUG_PRINT1 ("end of pattern ... ");
5711 /* If we haven't matched the entire string, and we want the
5712 longest match, try backtracking. */
5713 if (d != end_match_2)
5715 /* 1 if this match ends in the same string (string1 or string2)
5716 as the best previous match. */
5717 boolean same_str_p = (FIRST_STRING_P (match_end)
5718 == MATCHING_IN_FIRST_STRING);
5719 /* 1 if this match is the best seen so far. */
5720 boolean best_match_p;
5722 /* AIX compiler got confused when this was combined
5723 with the previous declaration. */
5724 if (same_str_p)
5725 best_match_p = d > match_end;
5726 else
5727 best_match_p = !MATCHING_IN_FIRST_STRING;
5729 DEBUG_PRINT1 ("backtracking.\n");
5731 if (!FAIL_STACK_EMPTY ())
5732 { /* More failure points to try. */
5734 /* If exceeds best match so far, save it. */
5735 if (!best_regs_set || best_match_p)
5737 best_regs_set = true;
5738 match_end = d;
5740 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5742 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5744 best_regstart[mcnt] = regstart[mcnt];
5745 best_regend[mcnt] = regend[mcnt];
5748 goto fail;
5751 /* If no failure points, don't restore garbage. And if
5752 last match is real best match, don't restore second
5753 best one. */
5754 else if (best_regs_set && !best_match_p)
5756 restore_best_regs:
5757 /* Restore best match. It may happen that `dend ==
5758 end_match_1' while the restored d is in string2.
5759 For example, the pattern `x.*y.*z' against the
5760 strings `x-' and `y-z-', if the two strings are
5761 not consecutive in memory. */
5762 DEBUG_PRINT1 ("Restoring best registers.\n");
5764 d = match_end;
5765 dend = ((d >= string1 && d <= end1)
5766 ? end_match_1 : end_match_2);
5768 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5770 regstart[mcnt] = best_regstart[mcnt];
5771 regend[mcnt] = best_regend[mcnt];
5774 } /* d != end_match_2 */
5776 succeed_label:
5777 DEBUG_PRINT1 ("Accepting match.\n");
5778 /* If caller wants register contents data back, do it. */
5779 if (regs && !bufp->no_sub)
5781 /* Have the register data arrays been allocated? */
5782 if (bufp->regs_allocated == REGS_UNALLOCATED)
5783 { /* No. So allocate them with malloc. We need one
5784 extra element beyond `num_regs' for the `-1' marker
5785 GNU code uses. */
5786 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5787 regs->start = TALLOC (regs->num_regs, regoff_t);
5788 regs->end = TALLOC (regs->num_regs, regoff_t);
5789 if (regs->start == NULL || regs->end == NULL)
5791 FREE_VARIABLES ();
5792 return -2;
5794 bufp->regs_allocated = REGS_REALLOCATE;
5796 else if (bufp->regs_allocated == REGS_REALLOCATE)
5797 { /* Yes. If we need more elements than were already
5798 allocated, reallocate them. If we need fewer, just
5799 leave it alone. */
5800 if (regs->num_regs < num_regs + 1)
5802 regs->num_regs = num_regs + 1;
5803 RETALLOC (regs->start, regs->num_regs, regoff_t);
5804 RETALLOC (regs->end, regs->num_regs, regoff_t);
5805 if (regs->start == NULL || regs->end == NULL)
5807 FREE_VARIABLES ();
5808 return -2;
5812 else
5814 /* These braces fend off a "empty body in an else-statement"
5815 warning under GCC when assert expands to nothing. */
5816 assert (bufp->regs_allocated == REGS_FIXED);
5819 /* Convert the pointer data in `regstart' and `regend' to
5820 indices. Register zero has to be set differently,
5821 since we haven't kept track of any info for it. */
5822 if (regs->num_regs > 0)
5824 regs->start[0] = pos;
5825 #ifdef MBS_SUPPORT
5826 if (MATCHING_IN_FIRST_STRING)
5827 regs->end[0] = mbs_offset1 != NULL ?
5828 mbs_offset1[d-string1] : 0;
5829 else
5830 regs->end[0] = csize1 + (mbs_offset2 != NULL ?
5831 mbs_offset2[d-string2] : 0);
5832 #else
5833 regs->end[0] = (MATCHING_IN_FIRST_STRING
5834 ? ((regoff_t) (d - string1))
5835 : ((regoff_t) (d - string2 + size1)));
5836 #endif /* MBS_SUPPORT */
5839 /* Go through the first `min (num_regs, regs->num_regs)'
5840 registers, since that is all we initialized. */
5841 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
5842 mcnt++)
5844 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
5845 regs->start[mcnt] = regs->end[mcnt] = -1;
5846 else
5848 regs->start[mcnt]
5849 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
5850 regs->end[mcnt]
5851 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
5855 /* If the regs structure we return has more elements than
5856 were in the pattern, set the extra elements to -1. If
5857 we (re)allocated the registers, this is the case,
5858 because we always allocate enough to have at least one
5859 -1 at the end. */
5860 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
5861 regs->start[mcnt] = regs->end[mcnt] = -1;
5862 } /* regs && !bufp->no_sub */
5864 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5865 nfailure_points_pushed, nfailure_points_popped,
5866 nfailure_points_pushed - nfailure_points_popped);
5867 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5869 #ifdef MBS_SUPPORT
5870 if (MATCHING_IN_FIRST_STRING)
5871 mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
5872 else
5873 mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
5874 csize1;
5875 mcnt -= pos;
5876 #else
5877 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
5878 ? string1
5879 : string2 - size1);
5880 #endif /* MBS_SUPPORT */
5882 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5884 FREE_VARIABLES ();
5885 return mcnt;
5888 /* Otherwise match next pattern command. */
5889 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5891 /* Ignore these. Used to ignore the n of succeed_n's which
5892 currently have n == 0. */
5893 case no_op:
5894 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5895 break;
5897 case succeed:
5898 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5899 goto succeed_label;
5901 /* Match the next n pattern characters exactly. The following
5902 byte in the pattern defines n, and the n bytes after that
5903 are the characters to match. */
5904 case exactn:
5905 #ifdef MBS_SUPPORT
5906 case exactn_bin:
5907 #endif
5908 mcnt = *p++;
5909 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5911 /* This is written out as an if-else so we don't waste time
5912 testing `translate' inside the loop. */
5913 if (translate)
5917 PREFETCH ();
5918 #ifdef MBS_SUPPORT
5919 if (*d <= 0xff)
5921 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5922 != (US_CHAR_TYPE) *p++)
5923 goto fail;
5925 else
5927 if (*d++ != (CHAR_TYPE) *p++)
5928 goto fail;
5930 #else
5931 if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5932 != (US_CHAR_TYPE) *p++)
5933 goto fail;
5934 #endif /* MBS_SUPPORT */
5936 while (--mcnt);
5938 else
5942 PREFETCH ();
5943 if (*d++ != (CHAR_TYPE) *p++) goto fail;
5945 while (--mcnt);
5947 SET_REGS_MATCHED ();
5948 break;
5951 /* Match any character except possibly a newline or a null. */
5952 case anychar:
5953 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5955 PREFETCH ();
5957 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
5958 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
5959 goto fail;
5961 SET_REGS_MATCHED ();
5962 DEBUG_PRINT2 (" Matched `%ld'.\n", (long int) *d);
5963 d++;
5964 break;
5967 case charset:
5968 case charset_not:
5970 register US_CHAR_TYPE c;
5971 #ifdef MBS_SUPPORT
5972 unsigned int i, char_class_length, coll_symbol_length,
5973 equiv_class_length, ranges_length, chars_length, length;
5974 CHAR_TYPE *workp, *workp2, *charset_top;
5975 #define WORK_BUFFER_SIZE 128
5976 CHAR_TYPE str_buf[WORK_BUFFER_SIZE];
5977 # ifdef _LIBC
5978 uint32_t nrules;
5979 # endif /* _LIBC */
5980 #endif /* MBS_SUPPORT */
5981 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5983 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5984 PREFETCH ();
5985 c = TRANSLATE (*d); /* The character to match. */
5986 #ifdef MBS_SUPPORT
5987 # ifdef _LIBC
5988 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
5989 # endif /* _LIBC */
5990 charset_top = p - 1;
5991 char_class_length = *p++;
5992 coll_symbol_length = *p++;
5993 equiv_class_length = *p++;
5994 ranges_length = *p++;
5995 chars_length = *p++;
5996 /* p points charset[6], so the address of the next instruction
5997 (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
5998 where l=length of char_classes, m=length of collating_symbol,
5999 n=equivalence_class, o=length of char_range,
6000 p'=length of character. */
6001 workp = p;
6002 /* Update p to indicate the next instruction. */
6003 p += char_class_length + coll_symbol_length+ equiv_class_length +
6004 2*ranges_length + chars_length;
6006 /* match with char_class? */
6007 for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
6009 wctype_t wctype;
6010 uintptr_t alignedp = ((uintptr_t)workp
6011 + __alignof__(wctype_t) - 1)
6012 & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6013 wctype = *((wctype_t*)alignedp);
6014 workp += CHAR_CLASS_SIZE;
6015 if (iswctype((wint_t)c, wctype))
6016 goto char_set_matched;
6019 /* match with collating_symbol? */
6020 # ifdef _LIBC
6021 if (nrules != 0)
6023 const unsigned char *extra = (const unsigned char *)
6024 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6026 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6027 workp++)
6029 int32_t *wextra;
6030 wextra = (int32_t*)(extra + *workp++);
6031 for (i = 0; i < *wextra; ++i)
6032 if (TRANSLATE(d[i]) != wextra[1 + i])
6033 break;
6035 if (i == *wextra)
6037 /* Update d, however d will be incremented at
6038 char_set_matched:, we decrement d here. */
6039 d += i - 1;
6040 goto char_set_matched;
6044 else /* (nrules == 0) */
6045 # endif
6046 /* If we can't look up collation data, we use wcscoll
6047 instead. */
6049 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6051 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6052 length = wcslen(workp);
6054 /* If wcscoll(the collating symbol, whole string) > 0,
6055 any substring of the string never match with the
6056 collating symbol. */
6057 if (wcscoll(workp, d) > 0)
6059 workp += length + 1;
6060 continue;
6063 /* First, we compare the collating symbol with
6064 the first character of the string.
6065 If it don't match, we add the next character to
6066 the compare buffer in turn. */
6067 for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6069 int match;
6070 if (d == dend)
6072 if (dend == end_match_2)
6073 break;
6074 d = string2;
6075 dend = end_match_2;
6078 /* add next character to the compare buffer. */
6079 str_buf[i] = TRANSLATE(*d);
6080 str_buf[i+1] = '\0';
6082 match = wcscoll(workp, str_buf);
6083 if (match == 0)
6084 goto char_set_matched;
6086 if (match < 0)
6087 /* (str_buf > workp) indicate (str_buf + X > workp),
6088 because for all X (str_buf + X > str_buf).
6089 So we don't need continue this loop. */
6090 break;
6092 /* Otherwise(str_buf < workp),
6093 (str_buf+next_character) may equals (workp).
6094 So we continue this loop. */
6096 /* not matched */
6097 d = backup_d;
6098 dend = backup_dend;
6099 workp += length + 1;
6102 /* match with equivalence_class? */
6103 # ifdef _LIBC
6104 if (nrules != 0)
6106 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6107 /* Try to match the equivalence class against
6108 those known to the collate implementation. */
6109 const int32_t *table;
6110 const int32_t *weights;
6111 const int32_t *extra;
6112 const int32_t *indirect;
6113 int32_t idx, idx2;
6114 wint_t *cp;
6115 size_t len;
6117 /* This #include defines a local function! */
6118 # include <locale/weightwc.h>
6120 table = (const int32_t *)
6121 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6122 weights = (const wint_t *)
6123 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6124 extra = (const wint_t *)
6125 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6126 indirect = (const int32_t *)
6127 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6129 /* Write 1 collating element to str_buf, and
6130 get its index. */
6131 idx2 = 0;
6133 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6135 cp = (wint_t*)str_buf;
6136 if (d == dend)
6138 if (dend == end_match_2)
6139 break;
6140 d = string2;
6141 dend = end_match_2;
6143 str_buf[i] = TRANSLATE(*(d+i));
6144 str_buf[i+1] = '\0'; /* sentinel */
6145 idx2 = findidx ((const wint_t**)&cp);
6148 /* Update d, however d will be incremented at
6149 char_set_matched:, we decrement d here. */
6150 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6151 if (d >= dend)
6153 if (dend == end_match_2)
6154 d = dend;
6155 else
6157 d = string2;
6158 dend = end_match_2;
6162 len = weights[idx2];
6164 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6165 workp++)
6167 idx = (int32_t)*workp;
6168 /* We already checked idx != 0 in regex_compile. */
6170 if (idx2 != 0 && len == weights[idx])
6172 int cnt = 0;
6173 while (cnt < len && (weights[idx + 1 + cnt]
6174 == weights[idx2 + 1 + cnt]))
6175 ++cnt;
6177 if (cnt == len)
6178 goto char_set_matched;
6181 /* not matched */
6182 d = backup_d;
6183 dend = backup_dend;
6185 else /* (nrules == 0) */
6186 # endif
6187 /* If we can't look up collation data, we use wcscoll
6188 instead. */
6190 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6192 const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6193 length = wcslen(workp);
6195 /* If wcscoll(the collating symbol, whole string) > 0,
6196 any substring of the string never match with the
6197 collating symbol. */
6198 if (wcscoll(workp, d) > 0)
6200 workp += length + 1;
6201 break;
6204 /* First, we compare the equivalence class with
6205 the first character of the string.
6206 If it don't match, we add the next character to
6207 the compare buffer in turn. */
6208 for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6210 int match;
6211 if (d == dend)
6213 if (dend == end_match_2)
6214 break;
6215 d = string2;
6216 dend = end_match_2;
6219 /* add next character to the compare buffer. */
6220 str_buf[i] = TRANSLATE(*d);
6221 str_buf[i+1] = '\0';
6223 match = wcscoll(workp, str_buf);
6225 if (match == 0)
6226 goto char_set_matched;
6228 if (match < 0)
6229 /* (str_buf > workp) indicate (str_buf + X > workp),
6230 because for all X (str_buf + X > str_buf).
6231 So we don't need continue this loop. */
6232 break;
6234 /* Otherwise(str_buf < workp),
6235 (str_buf+next_character) may equals (workp).
6236 So we continue this loop. */
6238 /* not matched */
6239 d = backup_d;
6240 dend = backup_dend;
6241 workp += length + 1;
6245 /* match with char_range? */
6246 #ifdef _LIBC
6247 if (nrules != 0)
6249 uint32_t collseqval;
6250 const char *collseq = (const char *)
6251 _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6253 collseqval = collseq_table_lookup (collseq, c);
6255 for (; workp < p - chars_length ;)
6257 uint32_t start_val, end_val;
6259 /* We already compute the collation sequence value
6260 of the characters (or collating symbols). */
6261 start_val = (uint32_t) *workp++; /* range_start */
6262 end_val = (uint32_t) *workp++; /* range_end */
6264 if (start_val <= collseqval && collseqval <= end_val)
6265 goto char_set_matched;
6268 else
6269 #endif
6271 /* We set range_start_char at str_buf[0], range_end_char
6272 at str_buf[4], and compared char at str_buf[2]. */
6273 str_buf[1] = 0;
6274 str_buf[2] = c;
6275 str_buf[3] = 0;
6276 str_buf[5] = 0;
6277 for (; workp < p - chars_length ;)
6279 wchar_t *range_start_char, *range_end_char;
6281 /* match if (range_start_char <= c <= range_end_char). */
6283 /* If range_start(or end) < 0, we assume -range_start(end)
6284 is the offset of the collating symbol which is specified
6285 as the character of the range start(end). */
6287 /* range_start */
6288 if (*workp < 0)
6289 range_start_char = charset_top - (*workp++);
6290 else
6292 str_buf[0] = *workp++;
6293 range_start_char = str_buf;
6296 /* range_end */
6297 if (*workp < 0)
6298 range_end_char = charset_top - (*workp++);
6299 else
6301 str_buf[4] = *workp++;
6302 range_end_char = str_buf + 4;
6305 if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6306 wcscoll(str_buf+2, range_end_char) <= 0)
6308 goto char_set_matched;
6312 /* match with char? */
6313 for (; workp < p ; workp++)
6314 if (c == *workp)
6315 goto char_set_matched;
6317 not = !not;
6319 char_set_matched:
6320 if (not) goto fail;
6321 #else
6322 /* Cast to `unsigned' instead of `unsigned char' in case the
6323 bit list is a full 32 bytes long. */
6324 if (c < (unsigned) (*p * BYTEWIDTH)
6325 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6326 not = !not;
6328 p += 1 + *p;
6330 if (!not) goto fail;
6331 #undef WORK_BUFFER_SIZE
6332 #endif /* MBS_SUPPORT */
6333 SET_REGS_MATCHED ();
6334 d++;
6335 break;
6339 /* The beginning of a group is represented by start_memory.
6340 The arguments are the register number in the next byte, and the
6341 number of groups inner to this one in the next. The text
6342 matched within the group is recorded (in the internal
6343 registers data structure) under the register number. */
6344 case start_memory:
6345 DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6346 (long int) *p, (long int) p[1]);
6348 /* Find out if this group can match the empty string. */
6349 p1 = p; /* To send to group_match_null_string_p. */
6351 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6352 REG_MATCH_NULL_STRING_P (reg_info[*p])
6353 = group_match_null_string_p (&p1, pend, reg_info);
6355 /* Save the position in the string where we were the last time
6356 we were at this open-group operator in case the group is
6357 operated upon by a repetition operator, e.g., with `(a*)*b'
6358 against `ab'; then we want to ignore where we are now in
6359 the string in case this attempt to match fails. */
6360 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6361 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6362 : regstart[*p];
6363 DEBUG_PRINT2 (" old_regstart: %d\n",
6364 POINTER_TO_OFFSET (old_regstart[*p]));
6366 regstart[*p] = d;
6367 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6369 IS_ACTIVE (reg_info[*p]) = 1;
6370 MATCHED_SOMETHING (reg_info[*p]) = 0;
6372 /* Clear this whenever we change the register activity status. */
6373 set_regs_matched_done = 0;
6375 /* This is the new highest active register. */
6376 highest_active_reg = *p;
6378 /* If nothing was active before, this is the new lowest active
6379 register. */
6380 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6381 lowest_active_reg = *p;
6383 /* Move past the register number and inner group count. */
6384 p += 2;
6385 just_past_start_mem = p;
6387 break;
6390 /* The stop_memory opcode represents the end of a group. Its
6391 arguments are the same as start_memory's: the register
6392 number, and the number of inner groups. */
6393 case stop_memory:
6394 DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6395 (long int) *p, (long int) p[1]);
6397 /* We need to save the string position the last time we were at
6398 this close-group operator in case the group is operated
6399 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6400 against `aba'; then we want to ignore where we are now in
6401 the string in case this attempt to match fails. */
6402 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6403 ? REG_UNSET (regend[*p]) ? d : regend[*p]
6404 : regend[*p];
6405 DEBUG_PRINT2 (" old_regend: %d\n",
6406 POINTER_TO_OFFSET (old_regend[*p]));
6408 regend[*p] = d;
6409 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6411 /* This register isn't active anymore. */
6412 IS_ACTIVE (reg_info[*p]) = 0;
6414 /* Clear this whenever we change the register activity status. */
6415 set_regs_matched_done = 0;
6417 /* If this was the only register active, nothing is active
6418 anymore. */
6419 if (lowest_active_reg == highest_active_reg)
6421 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6422 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6424 else
6425 { /* We must scan for the new highest active register, since
6426 it isn't necessarily one less than now: consider
6427 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
6428 new highest active register is 1. */
6429 US_CHAR_TYPE r = *p - 1;
6430 while (r > 0 && !IS_ACTIVE (reg_info[r]))
6431 r--;
6433 /* If we end up at register zero, that means that we saved
6434 the registers as the result of an `on_failure_jump', not
6435 a `start_memory', and we jumped to past the innermost
6436 `stop_memory'. For example, in ((.)*) we save
6437 registers 1 and 2 as a result of the *, but when we pop
6438 back to the second ), we are at the stop_memory 1.
6439 Thus, nothing is active. */
6440 if (r == 0)
6442 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6443 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6445 else
6446 highest_active_reg = r;
6449 /* If just failed to match something this time around with a
6450 group that's operated on by a repetition operator, try to
6451 force exit from the ``loop'', and restore the register
6452 information for this group that we had before trying this
6453 last match. */
6454 if ((!MATCHED_SOMETHING (reg_info[*p])
6455 || just_past_start_mem == p - 1)
6456 && (p + 2) < pend)
6458 boolean is_a_jump_n = false;
6460 p1 = p + 2;
6461 mcnt = 0;
6462 switch ((re_opcode_t) *p1++)
6464 case jump_n:
6465 is_a_jump_n = true;
6466 case pop_failure_jump:
6467 case maybe_pop_jump:
6468 case jump:
6469 case dummy_failure_jump:
6470 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6471 if (is_a_jump_n)
6472 p1 += OFFSET_ADDRESS_SIZE;
6473 break;
6475 default:
6476 /* do nothing */ ;
6478 p1 += mcnt;
6480 /* If the next operation is a jump backwards in the pattern
6481 to an on_failure_jump right before the start_memory
6482 corresponding to this stop_memory, exit from the loop
6483 by forcing a failure after pushing on the stack the
6484 on_failure_jump's jump in the pattern, and d. */
6485 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6486 && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6487 && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6489 /* If this group ever matched anything, then restore
6490 what its registers were before trying this last
6491 failed match, e.g., with `(a*)*b' against `ab' for
6492 regstart[1], and, e.g., with `((a*)*(b*)*)*'
6493 against `aba' for regend[3].
6495 Also restore the registers for inner groups for,
6496 e.g., `((a*)(b*))*' against `aba' (register 3 would
6497 otherwise get trashed). */
6499 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6501 unsigned r;
6503 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6505 /* Restore this and inner groups' (if any) registers. */
6506 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6507 r++)
6509 regstart[r] = old_regstart[r];
6511 /* xx why this test? */
6512 if (old_regend[r] >= regstart[r])
6513 regend[r] = old_regend[r];
6516 p1++;
6517 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6518 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6520 goto fail;
6524 /* Move past the register number and the inner group count. */
6525 p += 2;
6526 break;
6529 /* \<digit> has been turned into a `duplicate' command which is
6530 followed by the numeric value of <digit> as the register number. */
6531 case duplicate:
6533 register const CHAR_TYPE *d2, *dend2;
6534 int regno = *p++; /* Get which register to match against. */
6535 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6537 /* Can't back reference a group which we've never matched. */
6538 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6539 goto fail;
6541 /* Where in input to try to start matching. */
6542 d2 = regstart[regno];
6544 /* Where to stop matching; if both the place to start and
6545 the place to stop matching are in the same string, then
6546 set to the place to stop, otherwise, for now have to use
6547 the end of the first string. */
6549 dend2 = ((FIRST_STRING_P (regstart[regno])
6550 == FIRST_STRING_P (regend[regno]))
6551 ? regend[regno] : end_match_1);
6552 for (;;)
6554 /* If necessary, advance to next segment in register
6555 contents. */
6556 while (d2 == dend2)
6558 if (dend2 == end_match_2) break;
6559 if (dend2 == regend[regno]) break;
6561 /* End of string1 => advance to string2. */
6562 d2 = string2;
6563 dend2 = regend[regno];
6565 /* At end of register contents => success */
6566 if (d2 == dend2) break;
6568 /* If necessary, advance to next segment in data. */
6569 PREFETCH ();
6571 /* How many characters left in this segment to match. */
6572 mcnt = dend - d;
6574 /* Want how many consecutive characters we can match in
6575 one shot, so, if necessary, adjust the count. */
6576 if (mcnt > dend2 - d2)
6577 mcnt = dend2 - d2;
6579 /* Compare that many; failure if mismatch, else move
6580 past them. */
6581 if (translate
6582 ? bcmp_translate (d, d2, mcnt, translate)
6583 : memcmp (d, d2, mcnt*sizeof(US_CHAR_TYPE)))
6584 goto fail;
6585 d += mcnt, d2 += mcnt;
6587 /* Do this because we've match some characters. */
6588 SET_REGS_MATCHED ();
6591 break;
6594 /* begline matches the empty string at the beginning of the string
6595 (unless `not_bol' is set in `bufp'), and, if
6596 `newline_anchor' is set, after newlines. */
6597 case begline:
6598 DEBUG_PRINT1 ("EXECUTING begline.\n");
6600 if (AT_STRINGS_BEG (d))
6602 if (!bufp->not_bol) break;
6604 else if (d[-1] == '\n' && bufp->newline_anchor)
6606 break;
6608 /* In all other cases, we fail. */
6609 goto fail;
6612 /* endline is the dual of begline. */
6613 case endline:
6614 DEBUG_PRINT1 ("EXECUTING endline.\n");
6616 if (AT_STRINGS_END (d))
6618 if (!bufp->not_eol) break;
6621 /* We have to ``prefetch'' the next character. */
6622 else if ((d == end1 ? *string2 : *d) == '\n'
6623 && bufp->newline_anchor)
6625 break;
6627 goto fail;
6630 /* Match at the very beginning of the data. */
6631 case begbuf:
6632 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6633 if (AT_STRINGS_BEG (d))
6634 break;
6635 goto fail;
6638 /* Match at the very end of the data. */
6639 case endbuf:
6640 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6641 if (AT_STRINGS_END (d))
6642 break;
6643 goto fail;
6646 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
6647 pushes NULL as the value for the string on the stack. Then
6648 `pop_failure_point' will keep the current value for the
6649 string, instead of restoring it. To see why, consider
6650 matching `foo\nbar' against `.*\n'. The .* matches the foo;
6651 then the . fails against the \n. But the next thing we want
6652 to do is match the \n against the \n; if we restored the
6653 string value, we would be back at the foo.
6655 Because this is used only in specific cases, we don't need to
6656 check all the things that `on_failure_jump' does, to make
6657 sure the right things get saved on the stack. Hence we don't
6658 share its code. The only reason to push anything on the
6659 stack at all is that otherwise we would have to change
6660 `anychar's code to do something besides goto fail in this
6661 case; that seems worse than this. */
6662 case on_failure_keep_string_jump:
6663 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6665 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6666 #ifdef _LIBC
6667 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6668 #else
6669 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6670 #endif
6672 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6673 break;
6676 /* Uses of on_failure_jump:
6678 Each alternative starts with an on_failure_jump that points
6679 to the beginning of the next alternative. Each alternative
6680 except the last ends with a jump that in effect jumps past
6681 the rest of the alternatives. (They really jump to the
6682 ending jump of the following alternative, because tensioning
6683 these jumps is a hassle.)
6685 Repeats start with an on_failure_jump that points past both
6686 the repetition text and either the following jump or
6687 pop_failure_jump back to this on_failure_jump. */
6688 case on_failure_jump:
6689 on_failure:
6690 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6692 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6693 #ifdef _LIBC
6694 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6695 #else
6696 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6697 #endif
6699 /* If this on_failure_jump comes right before a group (i.e.,
6700 the original * applied to a group), save the information
6701 for that group and all inner ones, so that if we fail back
6702 to this point, the group's information will be correct.
6703 For example, in \(a*\)*\1, we need the preceding group,
6704 and in \(zz\(a*\)b*\)\2, we need the inner group. */
6706 /* We can't use `p' to check ahead because we push
6707 a failure point to `p + mcnt' after we do this. */
6708 p1 = p;
6710 /* We need to skip no_op's before we look for the
6711 start_memory in case this on_failure_jump is happening as
6712 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6713 against aba. */
6714 while (p1 < pend && (re_opcode_t) *p1 == no_op)
6715 p1++;
6717 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6719 /* We have a new highest active register now. This will
6720 get reset at the start_memory we are about to get to,
6721 but we will have saved all the registers relevant to
6722 this repetition op, as described above. */
6723 highest_active_reg = *(p1 + 1) + *(p1 + 2);
6724 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6725 lowest_active_reg = *(p1 + 1);
6728 DEBUG_PRINT1 (":\n");
6729 PUSH_FAILURE_POINT (p + mcnt, d, -2);
6730 break;
6733 /* A smart repeat ends with `maybe_pop_jump'.
6734 We change it to either `pop_failure_jump' or `jump'. */
6735 case maybe_pop_jump:
6736 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6737 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6739 register US_CHAR_TYPE *p2 = p;
6741 /* Compare the beginning of the repeat with what in the
6742 pattern follows its end. If we can establish that there
6743 is nothing that they would both match, i.e., that we
6744 would have to backtrack because of (as in, e.g., `a*a')
6745 then we can change to pop_failure_jump, because we'll
6746 never have to backtrack.
6748 This is not true in the case of alternatives: in
6749 `(a|ab)*' we do need to backtrack to the `ab' alternative
6750 (e.g., if the string was `ab'). But instead of trying to
6751 detect that here, the alternative has put on a dummy
6752 failure point which is what we will end up popping. */
6754 /* Skip over open/close-group commands.
6755 If what follows this loop is a ...+ construct,
6756 look at what begins its body, since we will have to
6757 match at least one of that. */
6758 while (1)
6760 if (p2 + 2 < pend
6761 && ((re_opcode_t) *p2 == stop_memory
6762 || (re_opcode_t) *p2 == start_memory))
6763 p2 += 3;
6764 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6765 && (re_opcode_t) *p2 == dummy_failure_jump)
6766 p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6767 else
6768 break;
6771 p1 = p + mcnt;
6772 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
6773 to the `maybe_finalize_jump' of this case. Examine what
6774 follows. */
6776 /* If we're at the end of the pattern, we can change. */
6777 if (p2 == pend)
6779 /* Consider what happens when matching ":\(.*\)"
6780 against ":/". I don't really understand this code
6781 yet. */
6782 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6783 pop_failure_jump;
6784 DEBUG_PRINT1
6785 (" End of pattern: change to `pop_failure_jump'.\n");
6788 else if ((re_opcode_t) *p2 == exactn
6789 #ifdef MBS_SUPPORT
6790 || (re_opcode_t) *p2 == exactn_bin
6791 #endif
6792 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
6794 register US_CHAR_TYPE c
6795 = *p2 == (US_CHAR_TYPE) endline ? '\n' : p2[2];
6797 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
6798 #ifdef MBS_SUPPORT
6799 || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
6800 #endif
6801 ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
6803 p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6804 pop_failure_jump;
6805 #ifdef MBS_SUPPORT
6806 if (MB_CUR_MAX != 1)
6807 DEBUG_PRINT3 (" %C != %C => pop_failure_jump.\n",
6808 (wint_t) c,
6809 (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
6810 else
6811 #endif
6812 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
6813 (char) c,
6814 (char) p1[3+OFFSET_ADDRESS_SIZE]);
6817 #ifndef MBS_SUPPORT
6818 else if ((re_opcode_t) p1[3] == charset
6819 || (re_opcode_t) p1[3] == charset_not)
6821 int not = (re_opcode_t) p1[3] == charset_not;
6823 if (c < (unsigned) (p1[4] * BYTEWIDTH)
6824 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6825 not = !not;
6827 /* `not' is equal to 1 if c would match, which means
6828 that we can't change to pop_failure_jump. */
6829 if (!not)
6831 p[-3] = (unsigned char) pop_failure_jump;
6832 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6835 #endif /* not MBS_SUPPORT */
6837 #ifndef MBS_SUPPORT
6838 else if ((re_opcode_t) *p2 == charset)
6840 /* We win if the first character of the loop is not part
6841 of the charset. */
6842 if ((re_opcode_t) p1[3] == exactn
6843 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
6844 && (p2[2 + p1[5] / BYTEWIDTH]
6845 & (1 << (p1[5] % BYTEWIDTH)))))
6847 p[-3] = (unsigned char) pop_failure_jump;
6848 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6851 else if ((re_opcode_t) p1[3] == charset_not)
6853 int idx;
6854 /* We win if the charset_not inside the loop
6855 lists every character listed in the charset after. */
6856 for (idx = 0; idx < (int) p2[1]; idx++)
6857 if (! (p2[2 + idx] == 0
6858 || (idx < (int) p1[4]
6859 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
6860 break;
6862 if (idx == p2[1])
6864 p[-3] = (unsigned char) pop_failure_jump;
6865 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6868 else if ((re_opcode_t) p1[3] == charset)
6870 int idx;
6871 /* We win if the charset inside the loop
6872 has no overlap with the one after the loop. */
6873 for (idx = 0;
6874 idx < (int) p2[1] && idx < (int) p1[4];
6875 idx++)
6876 if ((p2[2 + idx] & p1[5 + idx]) != 0)
6877 break;
6879 if (idx == p2[1] || idx == p1[4])
6881 p[-3] = (unsigned char) pop_failure_jump;
6882 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
6886 #endif /* not MBS_SUPPORT */
6888 p -= OFFSET_ADDRESS_SIZE; /* Point at relative address again. */
6889 if ((re_opcode_t) p[-1] != pop_failure_jump)
6891 p[-1] = (US_CHAR_TYPE) jump;
6892 DEBUG_PRINT1 (" Match => jump.\n");
6893 goto unconditional_jump;
6895 /* Note fall through. */
6898 /* The end of a simple repeat has a pop_failure_jump back to
6899 its matching on_failure_jump, where the latter will push a
6900 failure point. The pop_failure_jump takes off failure
6901 points put on by this pop_failure_jump's matching
6902 on_failure_jump; we got through the pattern to here from the
6903 matching on_failure_jump, so didn't fail. */
6904 case pop_failure_jump:
6906 /* We need to pass separate storage for the lowest and
6907 highest registers, even though we don't care about the
6908 actual values. Otherwise, we will restore only one
6909 register from the stack, since lowest will == highest in
6910 `pop_failure_point'. */
6911 active_reg_t dummy_low_reg, dummy_high_reg;
6912 US_CHAR_TYPE *pdummy = NULL;
6913 const CHAR_TYPE *sdummy = NULL;
6915 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
6916 POP_FAILURE_POINT (sdummy, pdummy,
6917 dummy_low_reg, dummy_high_reg,
6918 reg_dummy, reg_dummy, reg_info_dummy);
6920 /* Note fall through. */
6922 unconditional_jump:
6923 #ifdef _LIBC
6924 DEBUG_PRINT2 ("\n%p: ", p);
6925 #else
6926 DEBUG_PRINT2 ("\n0x%x: ", p);
6927 #endif
6928 /* Note fall through. */
6930 /* Unconditionally jump (without popping any failure points). */
6931 case jump:
6932 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
6933 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
6934 p += mcnt; /* Do the jump. */
6935 #ifdef _LIBC
6936 DEBUG_PRINT2 ("(to %p).\n", p);
6937 #else
6938 DEBUG_PRINT2 ("(to 0x%x).\n", p);
6939 #endif
6940 break;
6943 /* We need this opcode so we can detect where alternatives end
6944 in `group_match_null_string_p' et al. */
6945 case jump_past_alt:
6946 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
6947 goto unconditional_jump;
6950 /* Normally, the on_failure_jump pushes a failure point, which
6951 then gets popped at pop_failure_jump. We will end up at
6952 pop_failure_jump, also, and with a pattern of, say, `a+', we
6953 are skipping over the on_failure_jump, so we have to push
6954 something meaningless for pop_failure_jump to pop. */
6955 case dummy_failure_jump:
6956 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
6957 /* It doesn't matter what we push for the string here. What
6958 the code at `fail' tests is the value for the pattern. */
6959 PUSH_FAILURE_POINT (NULL, NULL, -2);
6960 goto unconditional_jump;
6963 /* At the end of an alternative, we need to push a dummy failure
6964 point in case we are followed by a `pop_failure_jump', because
6965 we don't want the failure point for the alternative to be
6966 popped. For example, matching `(a|ab)*' against `aab'
6967 requires that we match the `ab' alternative. */
6968 case push_dummy_failure:
6969 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
6970 /* See comments just above at `dummy_failure_jump' about the
6971 two zeroes. */
6972 PUSH_FAILURE_POINT (NULL, NULL, -2);
6973 break;
6975 /* Have to succeed matching what follows at least n times.
6976 After that, handle like `on_failure_jump'. */
6977 case succeed_n:
6978 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6979 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
6981 assert (mcnt >= 0);
6982 /* Originally, this is how many times we HAVE to succeed. */
6983 if (mcnt > 0)
6985 mcnt--;
6986 p += OFFSET_ADDRESS_SIZE;
6987 STORE_NUMBER_AND_INCR (p, mcnt);
6988 #ifdef _LIBC
6989 DEBUG_PRINT3 (" Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
6990 , mcnt);
6991 #else
6992 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
6993 , mcnt);
6994 #endif
6996 else if (mcnt == 0)
6998 #ifdef _LIBC
6999 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n",
7000 p + OFFSET_ADDRESS_SIZE);
7001 #else
7002 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n",
7003 p + OFFSET_ADDRESS_SIZE);
7004 #endif /* _LIBC */
7006 #ifdef MBS_SUPPORT
7007 p[1] = (US_CHAR_TYPE) no_op;
7008 #else
7009 p[2] = (US_CHAR_TYPE) no_op;
7010 p[3] = (US_CHAR_TYPE) no_op;
7011 #endif /* MBS_SUPPORT */
7012 goto on_failure;
7014 break;
7016 case jump_n:
7017 EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7018 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7020 /* Originally, this is how many times we CAN jump. */
7021 if (mcnt)
7023 mcnt--;
7024 STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7026 #ifdef _LIBC
7027 DEBUG_PRINT3 (" Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7028 mcnt);
7029 #else
7030 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7031 mcnt);
7032 #endif /* _LIBC */
7033 goto unconditional_jump;
7035 /* If don't have to jump any more, skip over the rest of command. */
7036 else
7037 p += 2 * OFFSET_ADDRESS_SIZE;
7038 break;
7040 case set_number_at:
7042 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7044 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7045 p1 = p + mcnt;
7046 EXTRACT_NUMBER_AND_INCR (mcnt, p);
7047 #ifdef _LIBC
7048 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
7049 #else
7050 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
7051 #endif
7052 STORE_NUMBER (p1, mcnt);
7053 break;
7056 #if 0
7057 /* The DEC Alpha C compiler 3.x generates incorrect code for the
7058 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
7059 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
7060 macro and introducing temporary variables works around the bug. */
7062 case wordbound:
7063 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7064 if (AT_WORD_BOUNDARY (d))
7065 break;
7066 goto fail;
7068 case notwordbound:
7069 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7070 if (AT_WORD_BOUNDARY (d))
7071 goto fail;
7072 break;
7073 #else
7074 case wordbound:
7076 boolean prevchar, thischar;
7078 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7079 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7080 break;
7082 prevchar = WORDCHAR_P (d - 1);
7083 thischar = WORDCHAR_P (d);
7084 if (prevchar != thischar)
7085 break;
7086 goto fail;
7089 case notwordbound:
7091 boolean prevchar, thischar;
7093 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7094 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7095 goto fail;
7097 prevchar = WORDCHAR_P (d - 1);
7098 thischar = WORDCHAR_P (d);
7099 if (prevchar != thischar)
7100 goto fail;
7101 break;
7103 #endif
7105 case wordbeg:
7106 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7107 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7108 break;
7109 goto fail;
7111 case wordend:
7112 DEBUG_PRINT1 ("EXECUTING wordend.\n");
7113 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7114 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
7115 break;
7116 goto fail;
7118 #ifdef emacs
7119 case before_dot:
7120 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7121 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7122 goto fail;
7123 break;
7125 case at_dot:
7126 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7127 if (PTR_CHAR_POS ((unsigned char *) d) != point)
7128 goto fail;
7129 break;
7131 case after_dot:
7132 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7133 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7134 goto fail;
7135 break;
7137 case syntaxspec:
7138 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7139 mcnt = *p++;
7140 goto matchsyntax;
7142 case wordchar:
7143 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7144 mcnt = (int) Sword;
7145 matchsyntax:
7146 PREFETCH ();
7147 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7148 d++;
7149 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7150 goto fail;
7151 SET_REGS_MATCHED ();
7152 break;
7154 case notsyntaxspec:
7155 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7156 mcnt = *p++;
7157 goto matchnotsyntax;
7159 case notwordchar:
7160 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7161 mcnt = (int) Sword;
7162 matchnotsyntax:
7163 PREFETCH ();
7164 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
7165 d++;
7166 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7167 goto fail;
7168 SET_REGS_MATCHED ();
7169 break;
7171 #else /* not emacs */
7172 case wordchar:
7173 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7174 PREFETCH ();
7175 if (!WORDCHAR_P (d))
7176 goto fail;
7177 SET_REGS_MATCHED ();
7178 d++;
7179 break;
7181 case notwordchar:
7182 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7183 PREFETCH ();
7184 if (WORDCHAR_P (d))
7185 goto fail;
7186 SET_REGS_MATCHED ();
7187 d++;
7188 break;
7189 #endif /* not emacs */
7191 default:
7192 abort ();
7194 continue; /* Successfully executed one pattern command; keep going. */
7197 /* We goto here if a matching operation fails. */
7198 fail:
7199 if (!FAIL_STACK_EMPTY ())
7200 { /* A restart point is known. Restore to that state. */
7201 DEBUG_PRINT1 ("\nFAIL:\n");
7202 POP_FAILURE_POINT (d, p,
7203 lowest_active_reg, highest_active_reg,
7204 regstart, regend, reg_info);
7206 /* If this failure point is a dummy, try the next one. */
7207 if (!p)
7208 goto fail;
7210 /* If we failed to the end of the pattern, don't examine *p. */
7211 assert (p <= pend);
7212 if (p < pend)
7214 boolean is_a_jump_n = false;
7216 /* If failed to a backwards jump that's part of a repetition
7217 loop, need to pop this failure point and use the next one. */
7218 switch ((re_opcode_t) *p)
7220 case jump_n:
7221 is_a_jump_n = true;
7222 case maybe_pop_jump:
7223 case pop_failure_jump:
7224 case jump:
7225 p1 = p + 1;
7226 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7227 p1 += mcnt;
7229 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7230 || (!is_a_jump_n
7231 && (re_opcode_t) *p1 == on_failure_jump))
7232 goto fail;
7233 break;
7234 default:
7235 /* do nothing */ ;
7239 if (d >= string1 && d <= end1)
7240 dend = end_match_1;
7242 else
7243 break; /* Matching at this starting point really fails. */
7244 } /* for (;;) */
7246 if (best_regs_set)
7247 goto restore_best_regs;
7249 FREE_VARIABLES ();
7251 return -1; /* Failure to match. */
7252 } /* re_match_2 */
7254 /* Subroutine definitions for re_match_2. */
7257 /* We are passed P pointing to a register number after a start_memory.
7259 Return true if the pattern up to the corresponding stop_memory can
7260 match the empty string, and false otherwise.
7262 If we find the matching stop_memory, sets P to point to one past its number.
7263 Otherwise, sets P to an undefined byte less than or equal to END.
7265 We don't handle duplicates properly (yet). */
7267 static boolean
7268 group_match_null_string_p (p, end, reg_info)
7269 US_CHAR_TYPE **p, *end;
7270 register_info_type *reg_info;
7272 int mcnt;
7273 /* Point to after the args to the start_memory. */
7274 US_CHAR_TYPE *p1 = *p + 2;
7276 while (p1 < end)
7278 /* Skip over opcodes that can match nothing, and return true or
7279 false, as appropriate, when we get to one that can't, or to the
7280 matching stop_memory. */
7282 switch ((re_opcode_t) *p1)
7284 /* Could be either a loop or a series of alternatives. */
7285 case on_failure_jump:
7286 p1++;
7287 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7289 /* If the next operation is not a jump backwards in the
7290 pattern. */
7292 if (mcnt >= 0)
7294 /* Go through the on_failure_jumps of the alternatives,
7295 seeing if any of the alternatives cannot match nothing.
7296 The last alternative starts with only a jump,
7297 whereas the rest start with on_failure_jump and end
7298 with a jump, e.g., here is the pattern for `a|b|c':
7300 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7301 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7302 /exactn/1/c
7304 So, we have to first go through the first (n-1)
7305 alternatives and then deal with the last one separately. */
7308 /* Deal with the first (n-1) alternatives, which start
7309 with an on_failure_jump (see above) that jumps to right
7310 past a jump_past_alt. */
7312 while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7313 jump_past_alt)
7315 /* `mcnt' holds how many bytes long the alternative
7316 is, including the ending `jump_past_alt' and
7317 its number. */
7319 if (!alt_match_null_string_p (p1, p1 + mcnt -
7320 (1 + OFFSET_ADDRESS_SIZE),
7321 reg_info))
7322 return false;
7324 /* Move to right after this alternative, including the
7325 jump_past_alt. */
7326 p1 += mcnt;
7328 /* Break if it's the beginning of an n-th alternative
7329 that doesn't begin with an on_failure_jump. */
7330 if ((re_opcode_t) *p1 != on_failure_jump)
7331 break;
7333 /* Still have to check that it's not an n-th
7334 alternative that starts with an on_failure_jump. */
7335 p1++;
7336 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7337 if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7338 jump_past_alt)
7340 /* Get to the beginning of the n-th alternative. */
7341 p1 -= 1 + OFFSET_ADDRESS_SIZE;
7342 break;
7346 /* Deal with the last alternative: go back and get number
7347 of the `jump_past_alt' just before it. `mcnt' contains
7348 the length of the alternative. */
7349 EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7351 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
7352 return false;
7354 p1 += mcnt; /* Get past the n-th alternative. */
7355 } /* if mcnt > 0 */
7356 break;
7359 case stop_memory:
7360 assert (p1[1] == **p);
7361 *p = p1 + 2;
7362 return true;
7365 default:
7366 if (!common_op_match_null_string_p (&p1, end, reg_info))
7367 return false;
7369 } /* while p1 < end */
7371 return false;
7372 } /* group_match_null_string_p */
7375 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7376 It expects P to be the first byte of a single alternative and END one
7377 byte past the last. The alternative can contain groups. */
7379 static boolean
7380 alt_match_null_string_p (p, end, reg_info)
7381 US_CHAR_TYPE *p, *end;
7382 register_info_type *reg_info;
7384 int mcnt;
7385 US_CHAR_TYPE *p1 = p;
7387 while (p1 < end)
7389 /* Skip over opcodes that can match nothing, and break when we get
7390 to one that can't. */
7392 switch ((re_opcode_t) *p1)
7394 /* It's a loop. */
7395 case on_failure_jump:
7396 p1++;
7397 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7398 p1 += mcnt;
7399 break;
7401 default:
7402 if (!common_op_match_null_string_p (&p1, end, reg_info))
7403 return false;
7405 } /* while p1 < end */
7407 return true;
7408 } /* alt_match_null_string_p */
7411 /* Deals with the ops common to group_match_null_string_p and
7412 alt_match_null_string_p.
7414 Sets P to one after the op and its arguments, if any. */
7416 static boolean
7417 common_op_match_null_string_p (p, end, reg_info)
7418 US_CHAR_TYPE **p, *end;
7419 register_info_type *reg_info;
7421 int mcnt;
7422 boolean ret;
7423 int reg_no;
7424 US_CHAR_TYPE *p1 = *p;
7426 switch ((re_opcode_t) *p1++)
7428 case no_op:
7429 case begline:
7430 case endline:
7431 case begbuf:
7432 case endbuf:
7433 case wordbeg:
7434 case wordend:
7435 case wordbound:
7436 case notwordbound:
7437 #ifdef emacs
7438 case before_dot:
7439 case at_dot:
7440 case after_dot:
7441 #endif
7442 break;
7444 case start_memory:
7445 reg_no = *p1;
7446 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7447 ret = group_match_null_string_p (&p1, end, reg_info);
7449 /* Have to set this here in case we're checking a group which
7450 contains a group and a back reference to it. */
7452 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7453 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7455 if (!ret)
7456 return false;
7457 break;
7459 /* If this is an optimized succeed_n for zero times, make the jump. */
7460 case jump:
7461 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7462 if (mcnt >= 0)
7463 p1 += mcnt;
7464 else
7465 return false;
7466 break;
7468 case succeed_n:
7469 /* Get to the number of times to succeed. */
7470 p1 += OFFSET_ADDRESS_SIZE;
7471 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7473 if (mcnt == 0)
7475 p1 -= 2 * OFFSET_ADDRESS_SIZE;
7476 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7477 p1 += mcnt;
7479 else
7480 return false;
7481 break;
7483 case duplicate:
7484 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7485 return false;
7486 break;
7488 case set_number_at:
7489 p1 += 2 * OFFSET_ADDRESS_SIZE;
7491 default:
7492 /* All other opcodes mean we cannot match the empty string. */
7493 return false;
7496 *p = p1;
7497 return true;
7498 } /* common_op_match_null_string_p */
7501 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7502 bytes; nonzero otherwise. */
7504 static int
7505 bcmp_translate (s1, s2, len, translate)
7506 const CHAR_TYPE *s1, *s2;
7507 register int len;
7508 RE_TRANSLATE_TYPE translate;
7510 register const US_CHAR_TYPE *p1 = (const US_CHAR_TYPE *) s1;
7511 register const US_CHAR_TYPE *p2 = (const US_CHAR_TYPE *) s2;
7512 while (len)
7514 #ifdef MBS_SUPPORT
7515 if (((*p1<=0xff)?translate[*p1++]:*p1++)
7516 != ((*p2<=0xff)?translate[*p2++]:*p2++))
7517 return 1;
7518 #else
7519 if (translate[*p1++] != translate[*p2++]) return 1;
7520 #endif /* MBS_SUPPORT */
7521 len--;
7523 return 0;
7526 /* Entry points for GNU code. */
7528 /* re_compile_pattern is the GNU regular expression compiler: it
7529 compiles PATTERN (of length SIZE) and puts the result in BUFP.
7530 Returns 0 if the pattern was valid, otherwise an error string.
7532 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7533 are set in BUFP on entry.
7535 We call regex_compile to do the actual compilation. */
7537 const char *
7538 re_compile_pattern (pattern, length, bufp)
7539 const char *pattern;
7540 size_t length;
7541 struct re_pattern_buffer *bufp;
7543 reg_errcode_t ret;
7545 /* GNU code is written to assume at least RE_NREGS registers will be set
7546 (and at least one extra will be -1). */
7547 bufp->regs_allocated = REGS_UNALLOCATED;
7549 /* And GNU code determines whether or not to get register information
7550 by passing null for the REGS argument to re_match, etc., not by
7551 setting no_sub. */
7552 bufp->no_sub = 0;
7554 /* Match anchors at newline. */
7555 bufp->newline_anchor = 1;
7557 ret = regex_compile (pattern, length, re_syntax_options, bufp);
7559 if (!ret)
7560 return NULL;
7561 return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7563 #ifdef _LIBC
7564 weak_alias (__re_compile_pattern, re_compile_pattern)
7565 #endif
7567 /* Entry points compatible with 4.2 BSD regex library. We don't define
7568 them unless specifically requested. */
7570 #if defined _REGEX_RE_COMP || defined _LIBC
7572 /* BSD has one and only one pattern buffer. */
7573 static struct re_pattern_buffer re_comp_buf;
7575 char *
7576 #ifdef _LIBC
7577 /* Make these definitions weak in libc, so POSIX programs can redefine
7578 these names if they don't use our functions, and still use
7579 regcomp/regexec below without link errors. */
7580 weak_function
7581 #endif
7582 re_comp (s)
7583 const char *s;
7585 reg_errcode_t ret;
7587 if (!s)
7589 if (!re_comp_buf.buffer)
7590 return gettext ("No previous regular expression");
7591 return 0;
7594 if (!re_comp_buf.buffer)
7596 re_comp_buf.buffer = (unsigned char *) malloc (200);
7597 if (re_comp_buf.buffer == NULL)
7598 return (char *) gettext (re_error_msgid
7599 + re_error_msgid_idx[(int) REG_ESPACE]);
7600 re_comp_buf.allocated = 200;
7602 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7603 if (re_comp_buf.fastmap == NULL)
7604 return (char *) gettext (re_error_msgid
7605 + re_error_msgid_idx[(int) REG_ESPACE]);
7608 /* Since `re_exec' always passes NULL for the `regs' argument, we
7609 don't need to initialize the pattern buffer fields which affect it. */
7611 /* Match anchors at newlines. */
7612 re_comp_buf.newline_anchor = 1;
7614 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7616 if (!ret)
7617 return NULL;
7619 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
7620 return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7625 #ifdef _LIBC
7626 weak_function
7627 #endif
7628 re_exec (s)
7629 const char *s;
7631 const int len = strlen (s);
7632 return
7633 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7636 #endif /* _REGEX_RE_COMP */
7638 /* POSIX.2 functions. Don't define these for Emacs. */
7640 #ifndef emacs
7642 /* regcomp takes a regular expression as a string and compiles it.
7644 PREG is a regex_t *. We do not expect any fields to be initialized,
7645 since POSIX says we shouldn't. Thus, we set
7647 `buffer' to the compiled pattern;
7648 `used' to the length of the compiled pattern;
7649 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7650 REG_EXTENDED bit in CFLAGS is set; otherwise, to
7651 RE_SYNTAX_POSIX_BASIC;
7652 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7653 `fastmap' to an allocated space for the fastmap;
7654 `fastmap_accurate' to zero;
7655 `re_nsub' to the number of subexpressions in PATTERN.
7657 PATTERN is the address of the pattern string.
7659 CFLAGS is a series of bits which affect compilation.
7661 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7662 use POSIX basic syntax.
7664 If REG_NEWLINE is set, then . and [^...] don't match newline.
7665 Also, regexec will try a match beginning after every newline.
7667 If REG_ICASE is set, then we considers upper- and lowercase
7668 versions of letters to be equivalent when matching.
7670 If REG_NOSUB is set, then when PREG is passed to regexec, that
7671 routine will report only success or failure, and nothing about the
7672 registers.
7674 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
7675 the return codes and their meanings.) */
7678 regcomp (preg, pattern, cflags)
7679 regex_t *preg;
7680 const char *pattern;
7681 int cflags;
7683 reg_errcode_t ret;
7684 reg_syntax_t syntax
7685 = (cflags & REG_EXTENDED) ?
7686 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7688 /* regex_compile will allocate the space for the compiled pattern. */
7689 preg->buffer = 0;
7690 preg->allocated = 0;
7691 preg->used = 0;
7693 /* Try to allocate space for the fastmap. */
7694 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7696 if (cflags & REG_ICASE)
7698 unsigned i;
7700 preg->translate
7701 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7702 * sizeof (*(RE_TRANSLATE_TYPE)0));
7703 if (preg->translate == NULL)
7704 return (int) REG_ESPACE;
7706 /* Map uppercase characters to corresponding lowercase ones. */
7707 for (i = 0; i < CHAR_SET_SIZE; i++)
7708 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7710 else
7711 preg->translate = NULL;
7713 /* If REG_NEWLINE is set, newlines are treated differently. */
7714 if (cflags & REG_NEWLINE)
7715 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
7716 syntax &= ~RE_DOT_NEWLINE;
7717 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7718 /* It also changes the matching behavior. */
7719 preg->newline_anchor = 1;
7721 else
7722 preg->newline_anchor = 0;
7724 preg->no_sub = !!(cflags & REG_NOSUB);
7726 /* POSIX says a null character in the pattern terminates it, so we
7727 can use strlen here in compiling the pattern. */
7728 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
7730 /* POSIX doesn't distinguish between an unmatched open-group and an
7731 unmatched close-group: both are REG_EPAREN. */
7732 if (ret == REG_ERPAREN) ret = REG_EPAREN;
7734 if (ret == REG_NOERROR && preg->fastmap)
7736 /* Compute the fastmap now, since regexec cannot modify the pattern
7737 buffer. */
7738 if (re_compile_fastmap (preg) == -2)
7740 /* Some error occurred while computing the fastmap, just forget
7741 about it. */
7742 free (preg->fastmap);
7743 preg->fastmap = NULL;
7747 return (int) ret;
7749 #ifdef _LIBC
7750 weak_alias (__regcomp, regcomp)
7751 #endif
7754 /* regexec searches for a given pattern, specified by PREG, in the
7755 string STRING.
7757 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7758 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
7759 least NMATCH elements, and we set them to the offsets of the
7760 corresponding matched substrings.
7762 EFLAGS specifies `execution flags' which affect matching: if
7763 REG_NOTBOL is set, then ^ does not match at the beginning of the
7764 string; if REG_NOTEOL is set, then $ does not match at the end.
7766 We return 0 if we find a match and REG_NOMATCH if not. */
7769 regexec (preg, string, nmatch, pmatch, eflags)
7770 const regex_t *preg;
7771 const char *string;
7772 size_t nmatch;
7773 regmatch_t pmatch[];
7774 int eflags;
7776 int ret;
7777 struct re_registers regs;
7778 regex_t private_preg;
7779 int len = strlen (string);
7780 boolean want_reg_info = !preg->no_sub && nmatch > 0;
7782 private_preg = *preg;
7784 private_preg.not_bol = !!(eflags & REG_NOTBOL);
7785 private_preg.not_eol = !!(eflags & REG_NOTEOL);
7787 /* The user has told us exactly how many registers to return
7788 information about, via `nmatch'. We have to pass that on to the
7789 matching routines. */
7790 private_preg.regs_allocated = REGS_FIXED;
7792 if (want_reg_info)
7794 regs.num_regs = nmatch;
7795 regs.start = TALLOC (nmatch * 2, regoff_t);
7796 if (regs.start == NULL)
7797 return (int) REG_NOMATCH;
7798 regs.end = regs.start + nmatch;
7801 /* Perform the searching operation. */
7802 ret = re_search (&private_preg, string, len,
7803 /* start: */ 0, /* range: */ len,
7804 want_reg_info ? &regs : (struct re_registers *) 0);
7806 /* Copy the register information to the POSIX structure. */
7807 if (want_reg_info)
7809 if (ret >= 0)
7811 unsigned r;
7813 for (r = 0; r < nmatch; r++)
7815 pmatch[r].rm_so = regs.start[r];
7816 pmatch[r].rm_eo = regs.end[r];
7820 /* If we needed the temporary register info, free the space now. */
7821 free (regs.start);
7824 /* We want zero return to mean success, unlike `re_search'. */
7825 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
7827 #ifdef _LIBC
7828 weak_alias (__regexec, regexec)
7829 #endif
7832 /* Returns a message corresponding to an error code, ERRCODE, returned
7833 from either regcomp or regexec. We don't use PREG here. */
7835 size_t
7836 regerror (errcode, preg, errbuf, errbuf_size)
7837 int errcode;
7838 const regex_t *preg;
7839 char *errbuf;
7840 size_t errbuf_size;
7842 const char *msg;
7843 size_t msg_size;
7845 if (errcode < 0
7846 || errcode >= (int) (sizeof (re_error_msgid_idx)
7847 / sizeof (re_error_msgid_idx[0])))
7848 /* Only error codes returned by the rest of the code should be passed
7849 to this routine. If we are given anything else, or if other regex
7850 code generates an invalid error code, then the program has a bug.
7851 Dump core so we can fix it. */
7852 abort ();
7854 msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
7856 msg_size = strlen (msg) + 1; /* Includes the null. */
7858 if (errbuf_size != 0)
7860 if (msg_size > errbuf_size)
7862 #if defined HAVE_MEMPCPY || defined _LIBC
7863 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
7864 #else
7865 memcpy (errbuf, msg, errbuf_size - 1);
7866 errbuf[errbuf_size - 1] = 0;
7867 #endif
7869 else
7870 memcpy (errbuf, msg, msg_size);
7873 return msg_size;
7875 #ifdef _LIBC
7876 weak_alias (__regerror, regerror)
7877 #endif
7880 /* Free dynamically allocated space used by PREG. */
7882 void
7883 regfree (preg)
7884 regex_t *preg;
7886 if (preg->buffer != NULL)
7887 free (preg->buffer);
7888 preg->buffer = NULL;
7890 preg->allocated = 0;
7891 preg->used = 0;
7893 if (preg->fastmap != NULL)
7894 free (preg->fastmap);
7895 preg->fastmap = NULL;
7896 preg->fastmap_accurate = 0;
7898 if (preg->translate != NULL)
7899 free (preg->translate);
7900 preg->translate = NULL;
7902 #ifdef _LIBC
7903 weak_alias (__regfree, regfree)
7904 #endif
7906 #endif /* not emacs */