(jm_PREREQ): Add jm_PREREQ_SIG2STR.
[gnulib.git] / regex.c
blob591d6f14e12bf1094376b66b8943aa351e07b9fc
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993,94,95,96,97,98,99,2000 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 This program 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
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20 USA. */
22 /* TODO:
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
26 need to modify the compiled regexp so that re_match can be reentrant.
27 - get rid of on_failure_jump_smart by doing the optimization in re_comp
28 rather than at run-time, so that re_match can be reentrant.
31 /* AIX requires this to be the first thing in the file. */
32 #if defined _AIX && !defined REGEX_MALLOC
33 #pragma alloca
34 #endif
36 #undef _GNU_SOURCE
37 #define _GNU_SOURCE
39 #ifdef HAVE_CONFIG_H
40 # include <config.h>
41 #endif
43 #if defined STDC_HEADERS && !defined emacs
44 # include <stddef.h>
45 #else
46 /* We need this for `regex.h', and perhaps for the Emacs include files. */
47 # include <sys/types.h>
48 #endif
50 /* Whether to use ISO C Amendment 1 wide char functions.
51 Those should not be used for Emacs since it uses its own. */
52 #if defined _LIBC
53 #define WIDE_CHAR_SUPPORT 1
54 #else
55 #define WIDE_CHAR_SUPPORT \
56 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
57 #endif
59 /* For platform which support the ISO C amendement 1 functionality we
60 support user defined character classes. */
61 #if WIDE_CHAR_SUPPORT
62 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
63 # include <wchar.h>
64 # include <wctype.h>
65 #endif
67 #ifdef _LIBC
68 /* We have to keep the namespace clean. */
69 # define regfree(preg) __regfree (preg)
70 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
71 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
72 # define regerror(errcode, preg, errbuf, errbuf_size) \
73 __regerror(errcode, preg, errbuf, errbuf_size)
74 # define re_set_registers(bu, re, nu, st, en) \
75 __re_set_registers (bu, re, nu, st, en)
76 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
77 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
78 # define re_match(bufp, string, size, pos, regs) \
79 __re_match (bufp, string, size, pos, regs)
80 # define re_search(bufp, string, size, startpos, range, regs) \
81 __re_search (bufp, string, size, startpos, range, regs)
82 # define re_compile_pattern(pattern, length, bufp) \
83 __re_compile_pattern (pattern, length, bufp)
84 # define re_set_syntax(syntax) __re_set_syntax (syntax)
85 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
86 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
87 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
89 /* Make sure we call libc's function even if the user overrides them. */
90 # define btowc __btowc
91 # define iswctype __iswctype
92 # define wctype __wctype
94 # define WEAK_ALIAS(a,b) weak_alias (a, b)
96 /* We are also using some library internals. */
97 # include <locale/localeinfo.h>
98 # include <locale/elem-hash.h>
99 # include <langinfo.h>
100 #else
101 # define WEAK_ALIAS(a,b)
102 #endif
104 /* This is for other GNU distributions with internationalized messages. */
105 #if HAVE_LIBINTL_H || defined _LIBC
106 # include <libintl.h>
107 #else
108 # define gettext(msgid) (msgid)
109 #endif
111 #ifndef gettext_noop
112 /* This define is so xgettext can find the internationalizable
113 strings. */
114 # define gettext_noop(String) String
115 #endif
117 /* The `emacs' switch turns on certain matching commands
118 that make sense only in Emacs. */
119 #ifdef emacs
121 # include "lisp.h"
122 # include "buffer.h"
124 /* Make syntax table lookup grant data in gl_state. */
125 # define SYNTAX_ENTRY_VIA_PROPERTY
127 # include "syntax.h"
128 # include "charset.h"
129 # include "category.h"
131 # ifdef malloc
132 # undef malloc
133 # endif
134 # define malloc xmalloc
135 # ifdef realloc
136 # undef realloc
137 # endif
138 # define realloc xrealloc
139 # ifdef free
140 # undef free
141 # endif
142 # define free xfree
144 /* Converts the pointer to the char to BEG-based offset from the start. */
145 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
146 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
148 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
149 # define RE_STRING_CHAR(p, s) \
150 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
151 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
152 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
154 /* Set C a (possibly multibyte) character before P. P points into a
155 string which is the virtual concatenation of STR1 (which ends at
156 END1) or STR2 (which ends at END2). */
157 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
158 do { \
159 if (multibyte) \
161 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
162 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
163 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
164 c = STRING_CHAR (dtemp, (p) - dtemp); \
166 else \
167 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
168 } while (0)
171 #else /* not emacs */
173 /* If we are not linking with Emacs proper,
174 we can't use the relocating allocator
175 even if config.h says that we can. */
176 # undef REL_ALLOC
178 # if defined STDC_HEADERS || defined _LIBC
179 # include <stdlib.h>
180 # else
181 char *malloc ();
182 char *realloc ();
183 # endif
185 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
186 If nothing else has been done, use the method below. */
187 # ifdef INHIBIT_STRING_HEADER
188 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
189 # if !defined bzero && !defined bcopy
190 # undef INHIBIT_STRING_HEADER
191 # endif
192 # endif
193 # endif
195 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
196 This is used in most programs--a few other programs avoid this
197 by defining INHIBIT_STRING_HEADER. */
198 # ifndef INHIBIT_STRING_HEADER
199 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
200 # include <string.h>
201 # ifndef bzero
202 # ifndef _LIBC
203 # define bzero(s, n) (memset (s, '\0', n), (s))
204 # else
205 # define bzero(s, n) __bzero (s, n)
206 # endif
207 # endif
208 # else
209 # include <strings.h>
210 # ifndef memcmp
211 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
212 # endif
213 # ifndef memcpy
214 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
215 # endif
216 # endif
217 # endif
219 /* Define the syntax stuff for \<, \>, etc. */
221 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
222 enum syntaxcode { Swhitespace = 0, Sword = 1 };
224 # ifdef SWITCH_ENUM_BUG
225 # define SWITCH_ENUM_CAST(x) ((int)(x))
226 # else
227 # define SWITCH_ENUM_CAST(x) (x)
228 # endif
230 /* Dummy macros for non-Emacs environments. */
231 # define BASE_LEADING_CODE_P(c) (0)
232 # define CHAR_CHARSET(c) 0
233 # define CHARSET_LEADING_CODE_BASE(c) 0
234 # define MAX_MULTIBYTE_LENGTH 1
235 # define RE_MULTIBYTE_P(x) 0
236 # define WORD_BOUNDARY_P(c1, c2) (0)
237 # define CHAR_HEAD_P(p) (1)
238 # define SINGLE_BYTE_CHAR_P(c) (1)
239 # define SAME_CHARSET_P(c1, c2) (1)
240 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
241 # define STRING_CHAR(p, s) (*(p))
242 # define RE_STRING_CHAR STRING_CHAR
243 # define CHAR_STRING(c, s) (*(s) = (c), 1)
244 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
245 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
246 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
247 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
248 # define MAKE_CHAR(charset, c1, c2) (c1)
249 #endif /* not emacs */
251 #ifndef RE_TRANSLATE
252 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
253 # define RE_TRANSLATE_P(TBL) (TBL)
254 #endif
256 /* Get the interface, including the syntax bits. */
257 #include "regex.h"
259 /* isalpha etc. are used for the character classes. */
260 #include <ctype.h>
262 #ifdef emacs
264 /* 1 if C is an ASCII character. */
265 # define IS_REAL_ASCII(c) ((c) < 0200)
267 /* 1 if C is a unibyte character. */
268 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
270 /* The Emacs definitions should not be directly affected by locales. */
272 /* In Emacs, these are only used for single-byte characters. */
273 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
274 # define ISCNTRL(c) ((c) < ' ')
275 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
276 || ((c) >= 'a' && (c) <= 'f') \
277 || ((c) >= 'A' && (c) <= 'F'))
279 /* This is only used for single-byte characters. */
280 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
282 /* The rest must handle multibyte characters. */
284 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
285 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
286 : 1)
288 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
289 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
290 : 1)
292 # define ISALNUM(c) (IS_REAL_ASCII (c) \
293 ? (((c) >= 'a' && (c) <= 'z') \
294 || ((c) >= 'A' && (c) <= 'Z') \
295 || ((c) >= '0' && (c) <= '9')) \
296 : SYNTAX (c) == Sword)
298 # define ISALPHA(c) (IS_REAL_ASCII (c) \
299 ? (((c) >= 'a' && (c) <= 'z') \
300 || ((c) >= 'A' && (c) <= 'Z')) \
301 : SYNTAX (c) == Sword)
303 # define ISLOWER(c) (LOWERCASEP (c))
305 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
306 ? ((c) > ' ' && (c) < 0177 \
307 && !(((c) >= 'a' && (c) <= 'z') \
308 || ((c) >= 'A' && (c) <= 'Z') \
309 || ((c) >= '0' && (c) <= '9'))) \
310 : SYNTAX (c) != Sword)
312 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
314 # define ISUPPER(c) (UPPERCASEP (c))
316 # define ISWORD(c) (SYNTAX (c) == Sword)
318 #else /* not emacs */
320 /* Jim Meyering writes:
322 "... Some ctype macros are valid only for character codes that
323 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
324 using /bin/cc or gcc but without giving an ansi option). So, all
325 ctype uses should be through macros like ISPRINT... If
326 STDC_HEADERS is defined, then autoconf has verified that the ctype
327 macros don't need to be guarded with references to isascii. ...
328 Defining isascii to 1 should let any compiler worth its salt
329 eliminate the && through constant folding."
330 Solaris defines some of these symbols so we must undefine them first. */
332 # undef ISASCII
333 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
334 # define ISASCII(c) 1
335 # else
336 # define ISASCII(c) isascii(c)
337 # endif
339 /* 1 if C is an ASCII character. */
340 # define IS_REAL_ASCII(c) ((c) < 0200)
342 /* This distinction is not meaningful, except in Emacs. */
343 # define ISUNIBYTE(c) 1
345 # ifdef isblank
346 # define ISBLANK(c) (ISASCII (c) && isblank (c))
347 # else
348 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
349 # endif
350 # ifdef isgraph
351 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
352 # else
353 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
354 # endif
356 # undef ISPRINT
357 # define ISPRINT(c) (ISASCII (c) && isprint (c))
358 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
359 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
360 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
361 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
362 # define ISLOWER(c) (ISASCII (c) && islower (c))
363 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
364 # define ISSPACE(c) (ISASCII (c) && isspace (c))
365 # define ISUPPER(c) (ISASCII (c) && isupper (c))
366 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
368 # define ISWORD(c) ISALPHA(c)
370 # ifdef _tolower
371 # define TOLOWER(c) _tolower(c)
372 # else
373 # define TOLOWER(c) tolower(c)
374 # endif
376 /* How many characters in the character set. */
377 # define CHAR_SET_SIZE 256
379 # ifdef SYNTAX_TABLE
381 extern char *re_syntax_table;
383 # else /* not SYNTAX_TABLE */
385 static char re_syntax_table[CHAR_SET_SIZE];
387 static void
388 init_syntax_once ()
390 register int c;
391 static int done = 0;
393 if (done)
394 return;
396 bzero (re_syntax_table, sizeof re_syntax_table);
398 for (c = 0; c < CHAR_SET_SIZE; ++c)
399 if (ISALNUM (c))
400 re_syntax_table[c] = Sword;
402 re_syntax_table['_'] = Sword;
404 done = 1;
407 # endif /* not SYNTAX_TABLE */
409 # define SYNTAX(c) re_syntax_table[(c)]
411 #endif /* not emacs */
413 #ifndef NULL
414 # define NULL (void *)0
415 #endif
417 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
418 since ours (we hope) works properly with all combinations of
419 machines, compilers, `char' and `unsigned char' argument types.
420 (Per Bothner suggested the basic approach.) */
421 #undef SIGN_EXTEND_CHAR
422 #if __STDC__
423 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
424 #else /* not __STDC__ */
425 /* As in Harbison and Steele. */
426 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
427 #endif
429 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
430 use `alloca' instead of `malloc'. This is because using malloc in
431 re_search* or re_match* could cause memory leaks when C-g is used in
432 Emacs; also, malloc is slower and causes storage fragmentation. On
433 the other hand, malloc is more portable, and easier to debug.
435 Because we sometimes use alloca, some routines have to be macros,
436 not functions -- `alloca'-allocated space disappears at the end of the
437 function it is called in. */
439 #ifdef REGEX_MALLOC
441 # define REGEX_ALLOCATE malloc
442 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
443 # define REGEX_FREE free
445 #else /* not REGEX_MALLOC */
447 /* Emacs already defines alloca, sometimes. */
448 # ifndef alloca
450 /* Make alloca work the best possible way. */
451 # ifdef __GNUC__
452 # define alloca __builtin_alloca
453 # else /* not __GNUC__ */
454 # if HAVE_ALLOCA_H
455 # include <alloca.h>
456 # endif /* HAVE_ALLOCA_H */
457 # endif /* not __GNUC__ */
459 # endif /* not alloca */
461 # define REGEX_ALLOCATE alloca
463 /* Assumes a `char *destination' variable. */
464 # define REGEX_REALLOCATE(source, osize, nsize) \
465 (destination = (char *) alloca (nsize), \
466 memcpy (destination, source, osize))
468 /* No need to do anything to free, after alloca. */
469 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
471 #endif /* not REGEX_MALLOC */
473 /* Define how to allocate the failure stack. */
475 #if defined REL_ALLOC && defined REGEX_MALLOC
477 # define REGEX_ALLOCATE_STACK(size) \
478 r_alloc (&failure_stack_ptr, (size))
479 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
480 r_re_alloc (&failure_stack_ptr, (nsize))
481 # define REGEX_FREE_STACK(ptr) \
482 r_alloc_free (&failure_stack_ptr)
484 #else /* not using relocating allocator */
486 # ifdef REGEX_MALLOC
488 # define REGEX_ALLOCATE_STACK malloc
489 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
490 # define REGEX_FREE_STACK free
492 # else /* not REGEX_MALLOC */
494 # define REGEX_ALLOCATE_STACK alloca
496 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
497 REGEX_REALLOCATE (source, osize, nsize)
498 /* No need to explicitly free anything. */
499 # define REGEX_FREE_STACK(arg) ((void)0)
501 # endif /* not REGEX_MALLOC */
502 #endif /* not using relocating allocator */
505 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
506 `string1' or just past its end. This works if PTR is NULL, which is
507 a good thing. */
508 #define FIRST_STRING_P(ptr) \
509 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
511 /* (Re)Allocate N items of type T using malloc, or fail. */
512 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
513 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
514 #define RETALLOC_IF(addr, n, t) \
515 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
516 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
518 #define BYTEWIDTH 8 /* In bits. */
520 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
522 #undef MAX
523 #undef MIN
524 #define MAX(a, b) ((a) > (b) ? (a) : (b))
525 #define MIN(a, b) ((a) < (b) ? (a) : (b))
527 /* Type of source-pattern and string chars. */
528 typedef const unsigned char re_char;
530 typedef char boolean;
531 #define false 0
532 #define true 1
534 static int re_match_2_internal _RE_ARGS ((struct re_pattern_buffer *bufp,
535 re_char *string1, int size1,
536 re_char *string2, int size2,
537 int pos,
538 struct re_registers *regs,
539 int stop));
541 /* These are the command codes that appear in compiled regular
542 expressions. Some opcodes are followed by argument bytes. A
543 command code can specify any interpretation whatsoever for its
544 arguments. Zero bytes may appear in the compiled regular expression. */
546 typedef enum
548 no_op = 0,
550 /* Succeed right away--no more backtracking. */
551 succeed,
553 /* Followed by one byte giving n, then by n literal bytes. */
554 exactn,
556 /* Matches any (more or less) character. */
557 anychar,
559 /* Matches any one char belonging to specified set. First
560 following byte is number of bitmap bytes. Then come bytes
561 for a bitmap saying which chars are in. Bits in each byte
562 are ordered low-bit-first. A character is in the set if its
563 bit is 1. A character too large to have a bit in the map is
564 automatically not in the set.
566 If the length byte has the 0x80 bit set, then that stuff
567 is followed by a range table:
568 2 bytes of flags for character sets (low 8 bits, high 8 bits)
569 See RANGE_TABLE_WORK_BITS below.
570 2 bytes, the number of pairs that follow (upto 32767)
571 pairs, each 2 multibyte characters,
572 each multibyte character represented as 3 bytes. */
573 charset,
575 /* Same parameters as charset, but match any character that is
576 not one of those specified. */
577 charset_not,
579 /* Start remembering the text that is matched, for storing in a
580 register. Followed by one byte with the register number, in
581 the range 0 to one less than the pattern buffer's re_nsub
582 field. */
583 start_memory,
585 /* Stop remembering the text that is matched and store it in a
586 memory register. Followed by one byte with the register
587 number, in the range 0 to one less than `re_nsub' in the
588 pattern buffer. */
589 stop_memory,
591 /* Match a duplicate of something remembered. Followed by one
592 byte containing the register number. */
593 duplicate,
595 /* Fail unless at beginning of line. */
596 begline,
598 /* Fail unless at end of line. */
599 endline,
601 /* Succeeds if at beginning of buffer (if emacs) or at beginning
602 of string to be matched (if not). */
603 begbuf,
605 /* Analogously, for end of buffer/string. */
606 endbuf,
608 /* Followed by two byte relative address to which to jump. */
609 jump,
611 /* Followed by two-byte relative address of place to resume at
612 in case of failure. */
613 on_failure_jump,
615 /* Like on_failure_jump, but pushes a placeholder instead of the
616 current string position when executed. */
617 on_failure_keep_string_jump,
619 /* Just like `on_failure_jump', except that it checks that we
620 don't get stuck in an infinite loop (matching an empty string
621 indefinitely). */
622 on_failure_jump_loop,
624 /* Just like `on_failure_jump_loop', except that it checks for
625 a different kind of loop (the kind that shows up with non-greedy
626 operators). This operation has to be immediately preceded
627 by a `no_op'. */
628 on_failure_jump_nastyloop,
630 /* A smart `on_failure_jump' used for greedy * and + operators.
631 It analyses the loop before which it is put and if the
632 loop does not require backtracking, it changes itself to
633 `on_failure_keep_string_jump' and short-circuits the loop,
634 else it just defaults to changing itself into `on_failure_jump'.
635 It assumes that it is pointing to just past a `jump'. */
636 on_failure_jump_smart,
638 /* Followed by two-byte relative address and two-byte number n.
639 After matching N times, jump to the address upon failure.
640 Does not work if N starts at 0: use on_failure_jump_loop
641 instead. */
642 succeed_n,
644 /* Followed by two-byte relative address, and two-byte number n.
645 Jump to the address N times, then fail. */
646 jump_n,
648 /* Set the following two-byte relative address to the
649 subsequent two-byte number. The address *includes* the two
650 bytes of number. */
651 set_number_at,
653 wordbeg, /* Succeeds if at word beginning. */
654 wordend, /* Succeeds if at word end. */
656 wordbound, /* Succeeds if at a word boundary. */
657 notwordbound, /* Succeeds if not at a word boundary. */
659 /* Matches any character whose syntax is specified. Followed by
660 a byte which contains a syntax code, e.g., Sword. */
661 syntaxspec,
663 /* Matches any character whose syntax is not that specified. */
664 notsyntaxspec
666 #ifdef emacs
667 ,before_dot, /* Succeeds if before point. */
668 at_dot, /* Succeeds if at point. */
669 after_dot, /* Succeeds if after point. */
671 /* Matches any character whose category-set contains the specified
672 category. The operator is followed by a byte which contains a
673 category code (mnemonic ASCII character). */
674 categoryspec,
676 /* Matches any character whose category-set does not contain the
677 specified category. The operator is followed by a byte which
678 contains the category code (mnemonic ASCII character). */
679 notcategoryspec
680 #endif /* emacs */
681 } re_opcode_t;
683 /* Common operations on the compiled pattern. */
685 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
687 #define STORE_NUMBER(destination, number) \
688 do { \
689 (destination)[0] = (number) & 0377; \
690 (destination)[1] = (number) >> 8; \
691 } while (0)
693 /* Same as STORE_NUMBER, except increment DESTINATION to
694 the byte after where the number is stored. Therefore, DESTINATION
695 must be an lvalue. */
697 #define STORE_NUMBER_AND_INCR(destination, number) \
698 do { \
699 STORE_NUMBER (destination, number); \
700 (destination) += 2; \
701 } while (0)
703 /* Put into DESTINATION a number stored in two contiguous bytes starting
704 at SOURCE. */
706 #define EXTRACT_NUMBER(destination, source) \
707 do { \
708 (destination) = *(source) & 0377; \
709 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
710 } while (0)
712 #ifdef DEBUG
713 static void extract_number _RE_ARGS ((int *dest, re_char *source));
714 static void
715 extract_number (dest, source)
716 int *dest;
717 re_char *source;
719 int temp = SIGN_EXTEND_CHAR (*(source + 1));
720 *dest = *source & 0377;
721 *dest += temp << 8;
724 # ifndef EXTRACT_MACROS /* To debug the macros. */
725 # undef EXTRACT_NUMBER
726 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
727 # endif /* not EXTRACT_MACROS */
729 #endif /* DEBUG */
731 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
732 SOURCE must be an lvalue. */
734 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
735 do { \
736 EXTRACT_NUMBER (destination, source); \
737 (source) += 2; \
738 } while (0)
740 #ifdef DEBUG
741 static void extract_number_and_incr _RE_ARGS ((int *destination,
742 re_char **source));
743 static void
744 extract_number_and_incr (destination, source)
745 int *destination;
746 re_char **source;
748 extract_number (destination, *source);
749 *source += 2;
752 # ifndef EXTRACT_MACROS
753 # undef EXTRACT_NUMBER_AND_INCR
754 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
755 extract_number_and_incr (&dest, &src)
756 # endif /* not EXTRACT_MACROS */
758 #endif /* DEBUG */
760 /* Store a multibyte character in three contiguous bytes starting
761 DESTINATION, and increment DESTINATION to the byte after where the
762 character is stored. Therefore, DESTINATION must be an lvalue. */
764 #define STORE_CHARACTER_AND_INCR(destination, character) \
765 do { \
766 (destination)[0] = (character) & 0377; \
767 (destination)[1] = ((character) >> 8) & 0377; \
768 (destination)[2] = (character) >> 16; \
769 (destination) += 3; \
770 } while (0)
772 /* Put into DESTINATION a character stored in three contiguous bytes
773 starting at SOURCE. */
775 #define EXTRACT_CHARACTER(destination, source) \
776 do { \
777 (destination) = ((source)[0] \
778 | ((source)[1] << 8) \
779 | ((source)[2] << 16)); \
780 } while (0)
783 /* Macros for charset. */
785 /* Size of bitmap of charset P in bytes. P is a start of charset,
786 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
787 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
789 /* Nonzero if charset P has range table. */
790 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
792 /* Return the address of range table of charset P. But not the start
793 of table itself, but the before where the number of ranges is
794 stored. `2 +' means to skip re_opcode_t and size of bitmap,
795 and the 2 bytes of flags at the start of the range table. */
796 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
798 /* Extract the bit flags that start a range table. */
799 #define CHARSET_RANGE_TABLE_BITS(p) \
800 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
801 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
803 /* Test if C is listed in the bitmap of charset P. */
804 #define CHARSET_LOOKUP_BITMAP(p, c) \
805 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
806 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
808 /* Return the address of end of RANGE_TABLE. COUNT is number of
809 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
810 is start of range and end of range. `* 3' is size of each start
811 and end. */
812 #define CHARSET_RANGE_TABLE_END(range_table, count) \
813 ((range_table) + (count) * 2 * 3)
815 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
816 COUNT is number of ranges in RANGE_TABLE. */
817 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
818 do \
820 re_wchar_t range_start, range_end; \
821 re_char *p; \
822 re_char *range_table_end \
823 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
825 for (p = (range_table); p < range_table_end; p += 2 * 3) \
827 EXTRACT_CHARACTER (range_start, p); \
828 EXTRACT_CHARACTER (range_end, p + 3); \
830 if (range_start <= (c) && (c) <= range_end) \
832 (not) = !(not); \
833 break; \
837 while (0)
839 /* Test if C is in range table of CHARSET. The flag NOT is negated if
840 C is listed in it. */
841 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
842 do \
844 /* Number of ranges in range table. */ \
845 int count; \
846 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
848 EXTRACT_NUMBER_AND_INCR (count, range_table); \
849 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
851 while (0)
853 /* If DEBUG is defined, Regex prints many voluminous messages about what
854 it is doing (if the variable `debug' is nonzero). If linked with the
855 main program in `iregex.c', you can enter patterns and strings
856 interactively. And if linked with the main program in `main.c' and
857 the other test files, you can run the already-written tests. */
859 #ifdef DEBUG
861 /* We use standard I/O for debugging. */
862 # include <stdio.h>
864 /* It is useful to test things that ``must'' be true when debugging. */
865 # include <assert.h>
867 static int debug = -100000;
869 # define DEBUG_STATEMENT(e) e
870 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
871 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
872 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
873 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
874 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
875 if (debug > 0) print_partial_compiled_pattern (s, e)
876 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
877 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
880 /* Print the fastmap in human-readable form. */
882 void
883 print_fastmap (fastmap)
884 char *fastmap;
886 unsigned was_a_range = 0;
887 unsigned i = 0;
889 while (i < (1 << BYTEWIDTH))
891 if (fastmap[i++])
893 was_a_range = 0;
894 putchar (i - 1);
895 while (i < (1 << BYTEWIDTH) && fastmap[i])
897 was_a_range = 1;
898 i++;
900 if (was_a_range)
902 printf ("-");
903 putchar (i - 1);
907 putchar ('\n');
911 /* Print a compiled pattern string in human-readable form, starting at
912 the START pointer into it and ending just before the pointer END. */
914 void
915 print_partial_compiled_pattern (start, end)
916 re_char *start;
917 re_char *end;
919 int mcnt, mcnt2;
920 re_char *p = start;
921 re_char *pend = end;
923 if (start == NULL)
925 printf ("(null)\n");
926 return;
929 /* Loop over pattern commands. */
930 while (p < pend)
932 printf ("%d:\t", p - start);
934 switch ((re_opcode_t) *p++)
936 case no_op:
937 printf ("/no_op");
938 break;
940 case succeed:
941 printf ("/succeed");
942 break;
944 case exactn:
945 mcnt = *p++;
946 printf ("/exactn/%d", mcnt);
949 putchar ('/');
950 putchar (*p++);
952 while (--mcnt);
953 break;
955 case start_memory:
956 printf ("/start_memory/%d", *p++);
957 break;
959 case stop_memory:
960 printf ("/stop_memory/%d", *p++);
961 break;
963 case duplicate:
964 printf ("/duplicate/%d", *p++);
965 break;
967 case anychar:
968 printf ("/anychar");
969 break;
971 case charset:
972 case charset_not:
974 register int c, last = -100;
975 register int in_range = 0;
976 int length = CHARSET_BITMAP_SIZE (p - 1);
977 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
979 printf ("/charset [%s",
980 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
982 assert (p + *p < pend);
984 for (c = 0; c < 256; c++)
985 if (c / 8 < length
986 && (p[1 + (c/8)] & (1 << (c % 8))))
988 /* Are we starting a range? */
989 if (last + 1 == c && ! in_range)
991 putchar ('-');
992 in_range = 1;
994 /* Have we broken a range? */
995 else if (last + 1 != c && in_range)
997 putchar (last);
998 in_range = 0;
1001 if (! in_range)
1002 putchar (c);
1004 last = c;
1007 if (in_range)
1008 putchar (last);
1010 putchar (']');
1012 p += 1 + length;
1014 if (has_range_table)
1016 int count;
1017 printf ("has-range-table");
1019 /* ??? Should print the range table; for now, just skip it. */
1020 p += 2; /* skip range table bits */
1021 EXTRACT_NUMBER_AND_INCR (count, p);
1022 p = CHARSET_RANGE_TABLE_END (p, count);
1025 break;
1027 case begline:
1028 printf ("/begline");
1029 break;
1031 case endline:
1032 printf ("/endline");
1033 break;
1035 case on_failure_jump:
1036 extract_number_and_incr (&mcnt, &p);
1037 printf ("/on_failure_jump to %d", p + mcnt - start);
1038 break;
1040 case on_failure_keep_string_jump:
1041 extract_number_and_incr (&mcnt, &p);
1042 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
1043 break;
1045 case on_failure_jump_nastyloop:
1046 extract_number_and_incr (&mcnt, &p);
1047 printf ("/on_failure_jump_nastyloop to %d", p + mcnt - start);
1048 break;
1050 case on_failure_jump_loop:
1051 extract_number_and_incr (&mcnt, &p);
1052 printf ("/on_failure_jump_loop to %d", p + mcnt - start);
1053 break;
1055 case on_failure_jump_smart:
1056 extract_number_and_incr (&mcnt, &p);
1057 printf ("/on_failure_jump_smart to %d", p + mcnt - start);
1058 break;
1060 case jump:
1061 extract_number_and_incr (&mcnt, &p);
1062 printf ("/jump to %d", p + mcnt - start);
1063 break;
1065 case succeed_n:
1066 extract_number_and_incr (&mcnt, &p);
1067 extract_number_and_incr (&mcnt2, &p);
1068 printf ("/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1069 break;
1071 case jump_n:
1072 extract_number_and_incr (&mcnt, &p);
1073 extract_number_and_incr (&mcnt2, &p);
1074 printf ("/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1075 break;
1077 case set_number_at:
1078 extract_number_and_incr (&mcnt, &p);
1079 extract_number_and_incr (&mcnt2, &p);
1080 printf ("/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1081 break;
1083 case wordbound:
1084 printf ("/wordbound");
1085 break;
1087 case notwordbound:
1088 printf ("/notwordbound");
1089 break;
1091 case wordbeg:
1092 printf ("/wordbeg");
1093 break;
1095 case wordend:
1096 printf ("/wordend");
1098 case syntaxspec:
1099 printf ("/syntaxspec");
1100 mcnt = *p++;
1101 printf ("/%d", mcnt);
1102 break;
1104 case notsyntaxspec:
1105 printf ("/notsyntaxspec");
1106 mcnt = *p++;
1107 printf ("/%d", mcnt);
1108 break;
1110 # ifdef emacs
1111 case before_dot:
1112 printf ("/before_dot");
1113 break;
1115 case at_dot:
1116 printf ("/at_dot");
1117 break;
1119 case after_dot:
1120 printf ("/after_dot");
1121 break;
1123 case categoryspec:
1124 printf ("/categoryspec");
1125 mcnt = *p++;
1126 printf ("/%d", mcnt);
1127 break;
1129 case notcategoryspec:
1130 printf ("/notcategoryspec");
1131 mcnt = *p++;
1132 printf ("/%d", mcnt);
1133 break;
1134 # endif /* emacs */
1136 case begbuf:
1137 printf ("/begbuf");
1138 break;
1140 case endbuf:
1141 printf ("/endbuf");
1142 break;
1144 default:
1145 printf ("?%d", *(p-1));
1148 putchar ('\n');
1151 printf ("%d:\tend of pattern.\n", p - start);
1155 void
1156 print_compiled_pattern (bufp)
1157 struct re_pattern_buffer *bufp;
1159 re_char *buffer = bufp->buffer;
1161 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1162 printf ("%ld bytes used/%ld bytes allocated.\n",
1163 bufp->used, bufp->allocated);
1165 if (bufp->fastmap_accurate && bufp->fastmap)
1167 printf ("fastmap: ");
1168 print_fastmap (bufp->fastmap);
1171 printf ("re_nsub: %d\t", bufp->re_nsub);
1172 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1173 printf ("can_be_null: %d\t", bufp->can_be_null);
1174 printf ("no_sub: %d\t", bufp->no_sub);
1175 printf ("not_bol: %d\t", bufp->not_bol);
1176 printf ("not_eol: %d\t", bufp->not_eol);
1177 printf ("syntax: %lx\n", bufp->syntax);
1178 fflush (stdout);
1179 /* Perhaps we should print the translate table? */
1183 void
1184 print_double_string (where, string1, size1, string2, size2)
1185 re_char *where;
1186 re_char *string1;
1187 re_char *string2;
1188 int size1;
1189 int size2;
1191 int this_char;
1193 if (where == NULL)
1194 printf ("(null)");
1195 else
1197 if (FIRST_STRING_P (where))
1199 for (this_char = where - string1; this_char < size1; this_char++)
1200 putchar (string1[this_char]);
1202 where = string2;
1205 for (this_char = where - string2; this_char < size2; this_char++)
1206 putchar (string2[this_char]);
1210 #else /* not DEBUG */
1212 # undef assert
1213 # define assert(e)
1215 # define DEBUG_STATEMENT(e)
1216 # define DEBUG_PRINT1(x)
1217 # define DEBUG_PRINT2(x1, x2)
1218 # define DEBUG_PRINT3(x1, x2, x3)
1219 # define DEBUG_PRINT4(x1, x2, x3, x4)
1220 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1221 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1223 #endif /* not DEBUG */
1225 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1226 also be assigned to arbitrarily: each pattern buffer stores its own
1227 syntax, so it can be changed between regex compilations. */
1228 /* This has no initializer because initialized variables in Emacs
1229 become read-only after dumping. */
1230 reg_syntax_t re_syntax_options;
1233 /* Specify the precise syntax of regexps for compilation. This provides
1234 for compatibility for various utilities which historically have
1235 different, incompatible syntaxes.
1237 The argument SYNTAX is a bit mask comprised of the various bits
1238 defined in regex.h. We return the old syntax. */
1240 reg_syntax_t
1241 re_set_syntax (syntax)
1242 reg_syntax_t syntax;
1244 reg_syntax_t ret = re_syntax_options;
1246 re_syntax_options = syntax;
1247 return ret;
1249 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1251 /* This table gives an error message for each of the error codes listed
1252 in regex.h. Obviously the order here has to be same as there.
1253 POSIX doesn't require that we do anything for REG_NOERROR,
1254 but why not be nice? */
1256 static const char *re_error_msgid[] =
1258 gettext_noop ("Success"), /* REG_NOERROR */
1259 gettext_noop ("No match"), /* REG_NOMATCH */
1260 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1261 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1262 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1263 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1264 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1265 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1266 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1267 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1268 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1269 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1270 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1271 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1272 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1273 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1274 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1277 /* Avoiding alloca during matching, to placate r_alloc. */
1279 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1280 searching and matching functions should not call alloca. On some
1281 systems, alloca is implemented in terms of malloc, and if we're
1282 using the relocating allocator routines, then malloc could cause a
1283 relocation, which might (if the strings being searched are in the
1284 ralloc heap) shift the data out from underneath the regexp
1285 routines.
1287 Here's another reason to avoid allocation: Emacs
1288 processes input from X in a signal handler; processing X input may
1289 call malloc; if input arrives while a matching routine is calling
1290 malloc, then we're scrod. But Emacs can't just block input while
1291 calling matching routines; then we don't notice interrupts when
1292 they come in. So, Emacs blocks input around all regexp calls
1293 except the matching calls, which it leaves unprotected, in the
1294 faith that they will not malloc. */
1296 /* Normally, this is fine. */
1297 #define MATCH_MAY_ALLOCATE
1299 /* When using GNU C, we are not REALLY using the C alloca, no matter
1300 what config.h may say. So don't take precautions for it. */
1301 #ifdef __GNUC__
1302 # undef C_ALLOCA
1303 #endif
1305 /* The match routines may not allocate if (1) they would do it with malloc
1306 and (2) it's not safe for them to use malloc.
1307 Note that if REL_ALLOC is defined, matching would not use malloc for the
1308 failure stack, but we would still use it for the register vectors;
1309 so REL_ALLOC should not affect this. */
1310 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1311 # undef MATCH_MAY_ALLOCATE
1312 #endif
1315 /* Failure stack declarations and macros; both re_compile_fastmap and
1316 re_match_2 use a failure stack. These have to be macros because of
1317 REGEX_ALLOCATE_STACK. */
1320 /* Approximate number of failure points for which to initially allocate space
1321 when matching. If this number is exceeded, we allocate more
1322 space, so it is not a hard limit. */
1323 #ifndef INIT_FAILURE_ALLOC
1324 # define INIT_FAILURE_ALLOC 20
1325 #endif
1327 /* Roughly the maximum number of failure points on the stack. Would be
1328 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1329 This is a variable only so users of regex can assign to it; we never
1330 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1331 before using it, so it should probably be a byte-count instead. */
1332 # if defined MATCH_MAY_ALLOCATE
1333 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1334 whose default stack limit is 2mb. In order for a larger
1335 value to work reliably, you have to try to make it accord
1336 with the process stack limit. */
1337 size_t re_max_failures = 40000;
1338 # else
1339 size_t re_max_failures = 4000;
1340 # endif
1342 union fail_stack_elt
1344 re_char *pointer;
1345 /* This should be the biggest `int' that's no bigger than a pointer. */
1346 long integer;
1349 typedef union fail_stack_elt fail_stack_elt_t;
1351 typedef struct
1353 fail_stack_elt_t *stack;
1354 size_t size;
1355 size_t avail; /* Offset of next open position. */
1356 size_t frame; /* Offset of the cur constructed frame. */
1357 } fail_stack_type;
1359 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1360 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1363 /* Define macros to initialize and free the failure stack.
1364 Do `return -2' if the alloc fails. */
1366 #ifdef MATCH_MAY_ALLOCATE
1367 # define INIT_FAIL_STACK() \
1368 do { \
1369 fail_stack.stack = (fail_stack_elt_t *) \
1370 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1371 * sizeof (fail_stack_elt_t)); \
1373 if (fail_stack.stack == NULL) \
1374 return -2; \
1376 fail_stack.size = INIT_FAILURE_ALLOC; \
1377 fail_stack.avail = 0; \
1378 fail_stack.frame = 0; \
1379 } while (0)
1381 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1382 #else
1383 # define INIT_FAIL_STACK() \
1384 do { \
1385 fail_stack.avail = 0; \
1386 fail_stack.frame = 0; \
1387 } while (0)
1389 # define RESET_FAIL_STACK() ((void)0)
1390 #endif
1393 /* Double the size of FAIL_STACK, up to a limit
1394 which allows approximately `re_max_failures' items.
1396 Return 1 if succeeds, and 0 if either ran out of memory
1397 allocating space for it or it was already too large.
1399 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1401 /* Factor to increase the failure stack size by
1402 when we increase it.
1403 This used to be 2, but 2 was too wasteful
1404 because the old discarded stacks added up to as much space
1405 were as ultimate, maximum-size stack. */
1406 #define FAIL_STACK_GROWTH_FACTOR 4
1408 #define GROW_FAIL_STACK(fail_stack) \
1409 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1410 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1411 ? 0 \
1412 : ((fail_stack).stack \
1413 = (fail_stack_elt_t *) \
1414 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1415 (fail_stack).size * sizeof (fail_stack_elt_t), \
1416 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1417 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1418 * FAIL_STACK_GROWTH_FACTOR))), \
1420 (fail_stack).stack == NULL \
1421 ? 0 \
1422 : ((fail_stack).size \
1423 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1424 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1425 * FAIL_STACK_GROWTH_FACTOR)) \
1426 / sizeof (fail_stack_elt_t)), \
1427 1)))
1430 /* Push a pointer value onto the failure stack.
1431 Assumes the variable `fail_stack'. Probably should only
1432 be called from within `PUSH_FAILURE_POINT'. */
1433 #define PUSH_FAILURE_POINTER(item) \
1434 fail_stack.stack[fail_stack.avail++].pointer = (item)
1436 /* This pushes an integer-valued item onto the failure stack.
1437 Assumes the variable `fail_stack'. Probably should only
1438 be called from within `PUSH_FAILURE_POINT'. */
1439 #define PUSH_FAILURE_INT(item) \
1440 fail_stack.stack[fail_stack.avail++].integer = (item)
1442 /* Push a fail_stack_elt_t value onto the failure stack.
1443 Assumes the variable `fail_stack'. Probably should only
1444 be called from within `PUSH_FAILURE_POINT'. */
1445 #define PUSH_FAILURE_ELT(item) \
1446 fail_stack.stack[fail_stack.avail++] = (item)
1448 /* These three POP... operations complement the three PUSH... operations.
1449 All assume that `fail_stack' is nonempty. */
1450 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1451 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1452 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1454 /* Individual items aside from the registers. */
1455 #define NUM_NONREG_ITEMS 3
1457 /* Used to examine the stack (to detect infinite loops). */
1458 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1459 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1460 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1461 #define TOP_FAILURE_HANDLE() fail_stack.frame
1464 #define ENSURE_FAIL_STACK(space) \
1465 while (REMAINING_AVAIL_SLOTS <= space) { \
1466 if (!GROW_FAIL_STACK (fail_stack)) \
1467 return -2; \
1468 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1469 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1472 /* Push register NUM onto the stack. */
1473 #define PUSH_FAILURE_REG(num) \
1474 do { \
1475 char *destination; \
1476 ENSURE_FAIL_STACK(3); \
1477 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1478 num, regstart[num], regend[num]); \
1479 PUSH_FAILURE_POINTER (regstart[num]); \
1480 PUSH_FAILURE_POINTER (regend[num]); \
1481 PUSH_FAILURE_INT (num); \
1482 } while (0)
1484 /* Change the counter's value to VAL, but make sure that it will
1485 be reset when backtracking. */
1486 #define PUSH_NUMBER(ptr,val) \
1487 do { \
1488 char *destination; \
1489 int c; \
1490 ENSURE_FAIL_STACK(3); \
1491 EXTRACT_NUMBER (c, ptr); \
1492 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1493 PUSH_FAILURE_INT (c); \
1494 PUSH_FAILURE_POINTER (ptr); \
1495 PUSH_FAILURE_INT (-1); \
1496 STORE_NUMBER (ptr, val); \
1497 } while (0)
1499 /* Pop a saved register off the stack. */
1500 #define POP_FAILURE_REG_OR_COUNT() \
1501 do { \
1502 int reg = POP_FAILURE_INT (); \
1503 if (reg == -1) \
1505 /* It's a counter. */ \
1506 /* Here, we discard `const', making re_match non-reentrant. */ \
1507 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1508 reg = POP_FAILURE_INT (); \
1509 STORE_NUMBER (ptr, reg); \
1510 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1512 else \
1514 regend[reg] = POP_FAILURE_POINTER (); \
1515 regstart[reg] = POP_FAILURE_POINTER (); \
1516 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1517 reg, regstart[reg], regend[reg]); \
1519 } while (0)
1521 /* Discard a saved register off the stack. */
1522 #define DISCARD_FAILURE_REG_OR_COUNT() \
1523 do { \
1524 int reg = POP_FAILURE_INT (); \
1525 if (reg == -1) \
1527 /* It's a counter. */ \
1528 POP_FAILURE_POINTER (); \
1529 reg = POP_FAILURE_INT (); \
1530 DEBUG_PRINT3 (" Discard counter %p = %d\n", ptr, reg); \
1532 else \
1534 POP_FAILURE_POINTER (); \
1535 POP_FAILURE_POINTER (); \
1536 DEBUG_PRINT4 (" Discard reg %d (spanning %p -> %p)\n", \
1537 reg, regstart[reg], regend[reg]); \
1539 } while (0)
1541 /* Check that we are not stuck in an infinite loop. */
1542 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1543 do { \
1544 int failure = TOP_FAILURE_HANDLE (); \
1545 /* Check for infinite matching loops */ \
1546 while (failure > 0 \
1547 && (FAILURE_STR (failure) == string_place \
1548 || FAILURE_STR (failure) == NULL)) \
1550 assert (FAILURE_PAT (failure) >= bufp->buffer \
1551 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1552 if (FAILURE_PAT (failure) == pat_cur) \
1554 while (fail_stack.frame < fail_stack.avail) \
1555 DISCARD_FAILURE_REG_OR_COUNT (); \
1556 goto fail; \
1558 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1559 failure = NEXT_FAILURE_HANDLE(failure); \
1561 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1562 } while (0)
1564 /* Push the information about the state we will need
1565 if we ever fail back to it.
1567 Requires variables fail_stack, regstart, regend and
1568 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1569 declared.
1571 Does `return FAILURE_CODE' if runs out of memory. */
1573 #define PUSH_FAILURE_POINT(pattern, string_place) \
1574 do { \
1575 char *destination; \
1576 /* Must be int, so when we don't save any registers, the arithmetic \
1577 of 0 + -1 isn't done as unsigned. */ \
1579 DEBUG_STATEMENT (nfailure_points_pushed++); \
1580 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1581 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1582 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1584 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1586 DEBUG_PRINT1 ("\n"); \
1588 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1589 PUSH_FAILURE_INT (fail_stack.frame); \
1591 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1592 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1593 DEBUG_PRINT1 ("'\n"); \
1594 PUSH_FAILURE_POINTER (string_place); \
1596 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1597 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1598 PUSH_FAILURE_POINTER (pattern); \
1600 /* Close the frame by moving the frame pointer past it. */ \
1601 fail_stack.frame = fail_stack.avail; \
1602 } while (0)
1604 /* Estimate the size of data pushed by a typical failure stack entry.
1605 An estimate is all we need, because all we use this for
1606 is to choose a limit for how big to make the failure stack. */
1607 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1608 #define TYPICAL_FAILURE_SIZE 20
1610 /* How many items can still be added to the stack without overflowing it. */
1611 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1614 /* Pops what PUSH_FAIL_STACK pushes.
1616 We restore into the parameters, all of which should be lvalues:
1617 STR -- the saved data position.
1618 PAT -- the saved pattern position.
1619 REGSTART, REGEND -- arrays of string positions.
1621 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1622 `pend', `string1', `size1', `string2', and `size2'. */
1624 #define POP_FAILURE_POINT(str, pat) \
1625 do { \
1626 assert (!FAIL_STACK_EMPTY ()); \
1628 /* Remove failure points and point to how many regs pushed. */ \
1629 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1630 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1631 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1633 /* Pop the saved registers. */ \
1634 while (fail_stack.frame < fail_stack.avail) \
1635 POP_FAILURE_REG_OR_COUNT (); \
1637 pat = POP_FAILURE_POINTER (); \
1638 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1639 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1641 /* If the saved string location is NULL, it came from an \
1642 on_failure_keep_string_jump opcode, and we want to throw away the \
1643 saved NULL, thus retaining our current position in the string. */ \
1644 str = POP_FAILURE_POINTER (); \
1645 DEBUG_PRINT2 (" Popping string %p: `", str); \
1646 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1647 DEBUG_PRINT1 ("'\n"); \
1649 fail_stack.frame = POP_FAILURE_INT (); \
1650 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1652 assert (fail_stack.avail >= 0); \
1653 assert (fail_stack.frame <= fail_stack.avail); \
1655 DEBUG_STATEMENT (nfailure_points_popped++); \
1656 } while (0) /* POP_FAILURE_POINT */
1660 /* Registers are set to a sentinel when they haven't yet matched. */
1661 #define REG_UNSET(e) ((e) == NULL)
1663 /* Subroutine declarations and macros for regex_compile. */
1665 static reg_errcode_t regex_compile _RE_ARGS ((re_char *pattern, size_t size,
1666 reg_syntax_t syntax,
1667 struct re_pattern_buffer *bufp));
1668 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1669 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1670 int arg1, int arg2));
1671 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1672 int arg, unsigned char *end));
1673 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1674 int arg1, int arg2, unsigned char *end));
1675 static boolean at_begline_loc_p _RE_ARGS ((re_char *pattern,
1676 re_char *p,
1677 reg_syntax_t syntax));
1678 static boolean at_endline_loc_p _RE_ARGS ((re_char *p,
1679 re_char *pend,
1680 reg_syntax_t syntax));
1681 static re_char *skip_one_char _RE_ARGS ((re_char *p));
1682 static int analyse_first _RE_ARGS ((re_char *p, re_char *pend,
1683 char *fastmap, const int multibyte));
1685 /* Fetch the next character in the uncompiled pattern---translating it
1686 if necessary. */
1687 #define PATFETCH(c) \
1688 do { \
1689 PATFETCH_RAW (c); \
1690 c = TRANSLATE (c); \
1691 } while (0)
1693 /* Fetch the next character in the uncompiled pattern, with no
1694 translation. */
1695 #define PATFETCH_RAW(c) \
1696 do { \
1697 int len; \
1698 if (p == pend) return REG_EEND; \
1699 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1700 p += len; \
1701 } while (0)
1704 /* If `translate' is non-null, return translate[D], else just D. We
1705 cast the subscript to translate because some data is declared as
1706 `char *', to avoid warnings when a string constant is passed. But
1707 when we use a character as a subscript we must make it unsigned. */
1708 #ifndef TRANSLATE
1709 # define TRANSLATE(d) \
1710 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1711 #endif
1714 /* Macros for outputting the compiled pattern into `buffer'. */
1716 /* If the buffer isn't allocated when it comes in, use this. */
1717 #define INIT_BUF_SIZE 32
1719 /* Make sure we have at least N more bytes of space in buffer. */
1720 #define GET_BUFFER_SPACE(n) \
1721 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1722 EXTEND_BUFFER ()
1724 /* Make sure we have one more byte of buffer space and then add C to it. */
1725 #define BUF_PUSH(c) \
1726 do { \
1727 GET_BUFFER_SPACE (1); \
1728 *b++ = (unsigned char) (c); \
1729 } while (0)
1732 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1733 #define BUF_PUSH_2(c1, c2) \
1734 do { \
1735 GET_BUFFER_SPACE (2); \
1736 *b++ = (unsigned char) (c1); \
1737 *b++ = (unsigned char) (c2); \
1738 } while (0)
1741 /* As with BUF_PUSH_2, except for three bytes. */
1742 #define BUF_PUSH_3(c1, c2, c3) \
1743 do { \
1744 GET_BUFFER_SPACE (3); \
1745 *b++ = (unsigned char) (c1); \
1746 *b++ = (unsigned char) (c2); \
1747 *b++ = (unsigned char) (c3); \
1748 } while (0)
1751 /* Store a jump with opcode OP at LOC to location TO. We store a
1752 relative address offset by the three bytes the jump itself occupies. */
1753 #define STORE_JUMP(op, loc, to) \
1754 store_op1 (op, loc, (to) - (loc) - 3)
1756 /* Likewise, for a two-argument jump. */
1757 #define STORE_JUMP2(op, loc, to, arg) \
1758 store_op2 (op, loc, (to) - (loc) - 3, arg)
1760 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1761 #define INSERT_JUMP(op, loc, to) \
1762 insert_op1 (op, loc, (to) - (loc) - 3, b)
1764 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1765 #define INSERT_JUMP2(op, loc, to, arg) \
1766 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1769 /* This is not an arbitrary limit: the arguments which represent offsets
1770 into the pattern are two bytes long. So if 2^16 bytes turns out to
1771 be too small, many things would have to change. */
1772 /* Any other compiler which, like MSC, has allocation limit below 2^16
1773 bytes will have to use approach similar to what was done below for
1774 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1775 reallocating to 0 bytes. Such thing is not going to work too well.
1776 You have been warned!! */
1777 #if defined _MSC_VER && !defined WIN32
1778 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1779 # define MAX_BUF_SIZE 65500L
1780 #else
1781 # define MAX_BUF_SIZE (1L << 16)
1782 #endif
1784 /* Extend the buffer by twice its current size via realloc and
1785 reset the pointers that pointed into the old block to point to the
1786 correct places in the new one. If extending the buffer results in it
1787 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1788 #if __BOUNDED_POINTERS__
1789 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1790 # define MOVE_BUFFER_POINTER(P) \
1791 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1792 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1793 else \
1795 SET_HIGH_BOUND (b); \
1796 SET_HIGH_BOUND (begalt); \
1797 if (fixup_alt_jump) \
1798 SET_HIGH_BOUND (fixup_alt_jump); \
1799 if (laststart) \
1800 SET_HIGH_BOUND (laststart); \
1801 if (pending_exact) \
1802 SET_HIGH_BOUND (pending_exact); \
1804 #else
1805 # define MOVE_BUFFER_POINTER(P) (P) += incr
1806 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1807 #endif
1808 #define EXTEND_BUFFER() \
1809 do { \
1810 re_char *old_buffer = bufp->buffer; \
1811 if (bufp->allocated == MAX_BUF_SIZE) \
1812 return REG_ESIZE; \
1813 bufp->allocated <<= 1; \
1814 if (bufp->allocated > MAX_BUF_SIZE) \
1815 bufp->allocated = MAX_BUF_SIZE; \
1816 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1817 if (bufp->buffer == NULL) \
1818 return REG_ESPACE; \
1819 /* If the buffer moved, move all the pointers into it. */ \
1820 if (old_buffer != bufp->buffer) \
1822 int incr = bufp->buffer - old_buffer; \
1823 MOVE_BUFFER_POINTER (b); \
1824 MOVE_BUFFER_POINTER (begalt); \
1825 if (fixup_alt_jump) \
1826 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1827 if (laststart) \
1828 MOVE_BUFFER_POINTER (laststart); \
1829 if (pending_exact) \
1830 MOVE_BUFFER_POINTER (pending_exact); \
1832 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1833 } while (0)
1836 /* Since we have one byte reserved for the register number argument to
1837 {start,stop}_memory, the maximum number of groups we can report
1838 things about is what fits in that byte. */
1839 #define MAX_REGNUM 255
1841 /* But patterns can have more than `MAX_REGNUM' registers. We just
1842 ignore the excess. */
1843 typedef unsigned regnum_t;
1846 /* Macros for the compile stack. */
1848 /* Since offsets can go either forwards or backwards, this type needs to
1849 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1850 /* int may be not enough when sizeof(int) == 2. */
1851 typedef long pattern_offset_t;
1853 typedef struct
1855 pattern_offset_t begalt_offset;
1856 pattern_offset_t fixup_alt_jump;
1857 pattern_offset_t laststart_offset;
1858 regnum_t regnum;
1859 } compile_stack_elt_t;
1862 typedef struct
1864 compile_stack_elt_t *stack;
1865 unsigned size;
1866 unsigned avail; /* Offset of next open position. */
1867 } compile_stack_type;
1870 #define INIT_COMPILE_STACK_SIZE 32
1872 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1873 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1875 /* The next available element. */
1876 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1879 /* Structure to manage work area for range table. */
1880 struct range_table_work_area
1882 int *table; /* actual work area. */
1883 int allocated; /* allocated size for work area in bytes. */
1884 int used; /* actually used size in words. */
1885 int bits; /* flag to record character classes */
1888 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1889 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1890 do { \
1891 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1893 (work_area).allocated += 16 * sizeof (int); \
1894 if ((work_area).table) \
1895 (work_area).table \
1896 = (int *) realloc ((work_area).table, (work_area).allocated); \
1897 else \
1898 (work_area).table \
1899 = (int *) malloc ((work_area).allocated); \
1900 if ((work_area).table == 0) \
1901 FREE_STACK_RETURN (REG_ESPACE); \
1903 } while (0)
1905 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1906 (work_area).bits |= (bit)
1908 /* Bits used to implement the multibyte-part of the various character classes
1909 such as [:alnum:] in a charset's range table. */
1910 #define BIT_WORD 0x1
1911 #define BIT_LOWER 0x2
1912 #define BIT_PUNCT 0x4
1913 #define BIT_SPACE 0x8
1914 #define BIT_UPPER 0x10
1915 #define BIT_MULTIBYTE 0x20
1917 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1918 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1919 do { \
1920 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1921 (work_area).table[(work_area).used++] = (range_start); \
1922 (work_area).table[(work_area).used++] = (range_end); \
1923 } while (0)
1925 /* Free allocated memory for WORK_AREA. */
1926 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1927 do { \
1928 if ((work_area).table) \
1929 free ((work_area).table); \
1930 } while (0)
1932 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1933 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1934 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1935 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1938 /* Set the bit for character C in a list. */
1939 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1942 /* Get the next unsigned number in the uncompiled pattern. */
1943 #define GET_UNSIGNED_NUMBER(num) \
1944 do { if (p != pend) \
1946 PATFETCH (c); \
1947 if (c == ' ') \
1948 FREE_STACK_RETURN (REG_BADBR); \
1949 while ('0' <= c && c <= '9') \
1951 int prev; \
1952 if (num < 0) \
1953 num = 0; \
1954 prev = num; \
1955 num = num * 10 + c - '0'; \
1956 if (num / 10 != prev) \
1957 FREE_STACK_RETURN (REG_BADBR); \
1958 if (p == pend) \
1959 break; \
1960 PATFETCH (c); \
1962 if (c == ' ') \
1963 FREE_STACK_RETURN (REG_BADBR); \
1965 } while (0)
1967 #if WIDE_CHAR_SUPPORT
1968 /* The GNU C library provides support for user-defined character classes
1969 and the functions from ISO C amendement 1. */
1970 # ifdef CHARCLASS_NAME_MAX
1971 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1972 # else
1973 /* This shouldn't happen but some implementation might still have this
1974 problem. Use a reasonable default value. */
1975 # define CHAR_CLASS_MAX_LENGTH 256
1976 # endif
1977 typedef wctype_t re_wctype_t;
1978 typedef wchar_t re_wchar_t;
1979 # define re_wctype wctype
1980 # define re_iswctype iswctype
1981 # define re_wctype_to_bit(cc) 0
1982 #else
1983 # define CHAR_CLASS_MAX_LENGTH 9 /* Namely, `multibyte'. */
1984 # define btowc(c) c
1986 /* Character classes. */
1987 typedef enum { RECC_ERROR = 0,
1988 RECC_ALNUM, RECC_ALPHA, RECC_WORD,
1989 RECC_GRAPH, RECC_PRINT,
1990 RECC_LOWER, RECC_UPPER,
1991 RECC_PUNCT, RECC_CNTRL,
1992 RECC_DIGIT, RECC_XDIGIT,
1993 RECC_BLANK, RECC_SPACE,
1994 RECC_MULTIBYTE, RECC_NONASCII,
1995 RECC_ASCII, RECC_UNIBYTE
1996 } re_wctype_t;
1998 typedef int re_wchar_t;
2000 /* Map a string to the char class it names (if any). */
2001 static re_wctype_t
2002 re_wctype (str)
2003 re_char *str;
2005 const char *string = str;
2006 if (STREQ (string, "alnum")) return RECC_ALNUM;
2007 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2008 else if (STREQ (string, "word")) return RECC_WORD;
2009 else if (STREQ (string, "ascii")) return RECC_ASCII;
2010 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2011 else if (STREQ (string, "graph")) return RECC_GRAPH;
2012 else if (STREQ (string, "lower")) return RECC_LOWER;
2013 else if (STREQ (string, "print")) return RECC_PRINT;
2014 else if (STREQ (string, "punct")) return RECC_PUNCT;
2015 else if (STREQ (string, "space")) return RECC_SPACE;
2016 else if (STREQ (string, "upper")) return RECC_UPPER;
2017 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2018 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2019 else if (STREQ (string, "digit")) return RECC_DIGIT;
2020 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2021 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2022 else if (STREQ (string, "blank")) return RECC_BLANK;
2023 else return 0;
2026 /* True iff CH is in the char class CC. */
2027 static boolean
2028 re_iswctype (ch, cc)
2029 int ch;
2030 re_wctype_t cc;
2032 switch (cc)
2034 case RECC_ALNUM: return ISALNUM (ch);
2035 case RECC_ALPHA: return ISALPHA (ch);
2036 case RECC_BLANK: return ISBLANK (ch);
2037 case RECC_CNTRL: return ISCNTRL (ch);
2038 case RECC_DIGIT: return ISDIGIT (ch);
2039 case RECC_GRAPH: return ISGRAPH (ch);
2040 case RECC_LOWER: return ISLOWER (ch);
2041 case RECC_PRINT: return ISPRINT (ch);
2042 case RECC_PUNCT: return ISPUNCT (ch);
2043 case RECC_SPACE: return ISSPACE (ch);
2044 case RECC_UPPER: return ISUPPER (ch);
2045 case RECC_XDIGIT: return ISXDIGIT (ch);
2046 case RECC_ASCII: return IS_REAL_ASCII (ch);
2047 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2048 case RECC_UNIBYTE: return ISUNIBYTE (ch);
2049 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2050 case RECC_WORD: return ISWORD (ch);
2051 case RECC_ERROR: return false;
2052 default:
2053 abort();
2057 /* Return a bit-pattern to use in the range-table bits to match multibyte
2058 chars of class CC. */
2059 static int
2060 re_wctype_to_bit (cc)
2061 re_wctype_t cc;
2063 switch (cc)
2065 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2066 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2067 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2068 case RECC_LOWER: return BIT_LOWER;
2069 case RECC_UPPER: return BIT_UPPER;
2070 case RECC_PUNCT: return BIT_PUNCT;
2071 case RECC_SPACE: return BIT_SPACE;
2072 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2073 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2074 default:
2075 abort();
2078 #endif
2080 /* Explicit quit checking is only used on NTemacs. */
2081 #if defined WINDOWSNT && defined emacs && defined QUIT
2082 extern int immediate_quit;
2083 # define IMMEDIATE_QUIT_CHECK \
2084 do { \
2085 if (immediate_quit) QUIT; \
2086 } while (0)
2087 #else
2088 # define IMMEDIATE_QUIT_CHECK ((void)0)
2089 #endif
2091 #ifndef MATCH_MAY_ALLOCATE
2093 /* If we cannot allocate large objects within re_match_2_internal,
2094 we make the fail stack and register vectors global.
2095 The fail stack, we grow to the maximum size when a regexp
2096 is compiled.
2097 The register vectors, we adjust in size each time we
2098 compile a regexp, according to the number of registers it needs. */
2100 static fail_stack_type fail_stack;
2102 /* Size with which the following vectors are currently allocated.
2103 That is so we can make them bigger as needed,
2104 but never make them smaller. */
2105 static int regs_allocated_size;
2107 static re_char ** regstart, ** regend;
2108 static re_char **best_regstart, **best_regend;
2110 /* Make the register vectors big enough for NUM_REGS registers,
2111 but don't make them smaller. */
2113 static
2114 regex_grow_registers (num_regs)
2115 int num_regs;
2117 if (num_regs > regs_allocated_size)
2119 RETALLOC_IF (regstart, num_regs, re_char *);
2120 RETALLOC_IF (regend, num_regs, re_char *);
2121 RETALLOC_IF (best_regstart, num_regs, re_char *);
2122 RETALLOC_IF (best_regend, num_regs, re_char *);
2124 regs_allocated_size = num_regs;
2128 #endif /* not MATCH_MAY_ALLOCATE */
2130 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2131 compile_stack,
2132 regnum_t regnum));
2134 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2135 Returns one of error codes defined in `regex.h', or zero for success.
2137 Assumes the `allocated' (and perhaps `buffer') and `translate'
2138 fields are set in BUFP on entry.
2140 If it succeeds, results are put in BUFP (if it returns an error, the
2141 contents of BUFP are undefined):
2142 `buffer' is the compiled pattern;
2143 `syntax' is set to SYNTAX;
2144 `used' is set to the length of the compiled pattern;
2145 `fastmap_accurate' is zero;
2146 `re_nsub' is the number of subexpressions in PATTERN;
2147 `not_bol' and `not_eol' are zero;
2149 The `fastmap' field is neither examined nor set. */
2151 /* Insert the `jump' from the end of last alternative to "here".
2152 The space for the jump has already been allocated. */
2153 #define FIXUP_ALT_JUMP() \
2154 do { \
2155 if (fixup_alt_jump) \
2156 STORE_JUMP (jump, fixup_alt_jump, b); \
2157 } while (0)
2160 /* Return, freeing storage we allocated. */
2161 #define FREE_STACK_RETURN(value) \
2162 do { \
2163 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2164 free (compile_stack.stack); \
2165 return value; \
2166 } while (0)
2168 static reg_errcode_t
2169 regex_compile (pattern, size, syntax, bufp)
2170 re_char *pattern;
2171 size_t size;
2172 reg_syntax_t syntax;
2173 struct re_pattern_buffer *bufp;
2175 /* We fetch characters from PATTERN here. */
2176 register re_wchar_t c, c1;
2178 /* A random temporary spot in PATTERN. */
2179 re_char *p1;
2181 /* Points to the end of the buffer, where we should append. */
2182 register unsigned char *b;
2184 /* Keeps track of unclosed groups. */
2185 compile_stack_type compile_stack;
2187 /* Points to the current (ending) position in the pattern. */
2188 #ifdef AIX
2189 /* `const' makes AIX compiler fail. */
2190 unsigned char *p = pattern;
2191 #else
2192 re_char *p = pattern;
2193 #endif
2194 re_char *pend = pattern + size;
2196 /* How to translate the characters in the pattern. */
2197 RE_TRANSLATE_TYPE translate = bufp->translate;
2199 /* Address of the count-byte of the most recently inserted `exactn'
2200 command. This makes it possible to tell if a new exact-match
2201 character can be added to that command or if the character requires
2202 a new `exactn' command. */
2203 unsigned char *pending_exact = 0;
2205 /* Address of start of the most recently finished expression.
2206 This tells, e.g., postfix * where to find the start of its
2207 operand. Reset at the beginning of groups and alternatives. */
2208 unsigned char *laststart = 0;
2210 /* Address of beginning of regexp, or inside of last group. */
2211 unsigned char *begalt;
2213 /* Place in the uncompiled pattern (i.e., the {) to
2214 which to go back if the interval is invalid. */
2215 re_char *beg_interval;
2217 /* Address of the place where a forward jump should go to the end of
2218 the containing expression. Each alternative of an `or' -- except the
2219 last -- ends with a forward jump of this sort. */
2220 unsigned char *fixup_alt_jump = 0;
2222 /* Counts open-groups as they are encountered. Remembered for the
2223 matching close-group on the compile stack, so the same register
2224 number is put in the stop_memory as the start_memory. */
2225 regnum_t regnum = 0;
2227 /* Work area for range table of charset. */
2228 struct range_table_work_area range_table_work;
2230 /* If the object matched can contain multibyte characters. */
2231 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2233 #ifdef DEBUG
2234 debug++;
2235 DEBUG_PRINT1 ("\nCompiling pattern: ");
2236 if (debug > 0)
2238 unsigned debug_count;
2240 for (debug_count = 0; debug_count < size; debug_count++)
2241 putchar (pattern[debug_count]);
2242 putchar ('\n');
2244 #endif /* DEBUG */
2246 /* Initialize the compile stack. */
2247 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2248 if (compile_stack.stack == NULL)
2249 return REG_ESPACE;
2251 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2252 compile_stack.avail = 0;
2254 range_table_work.table = 0;
2255 range_table_work.allocated = 0;
2257 /* Initialize the pattern buffer. */
2258 bufp->syntax = syntax;
2259 bufp->fastmap_accurate = 0;
2260 bufp->not_bol = bufp->not_eol = 0;
2262 /* Set `used' to zero, so that if we return an error, the pattern
2263 printer (for debugging) will think there's no pattern. We reset it
2264 at the end. */
2265 bufp->used = 0;
2267 /* Always count groups, whether or not bufp->no_sub is set. */
2268 bufp->re_nsub = 0;
2270 #if !defined emacs && !defined SYNTAX_TABLE
2271 /* Initialize the syntax table. */
2272 init_syntax_once ();
2273 #endif
2275 if (bufp->allocated == 0)
2277 if (bufp->buffer)
2278 { /* If zero allocated, but buffer is non-null, try to realloc
2279 enough space. This loses if buffer's address is bogus, but
2280 that is the user's responsibility. */
2281 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2283 else
2284 { /* Caller did not allocate a buffer. Do it for them. */
2285 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2287 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2289 bufp->allocated = INIT_BUF_SIZE;
2292 begalt = b = bufp->buffer;
2294 /* Loop through the uncompiled pattern until we're at the end. */
2295 while (p != pend)
2297 PATFETCH (c);
2299 switch (c)
2301 case '^':
2303 if ( /* If at start of pattern, it's an operator. */
2304 p == pattern + 1
2305 /* If context independent, it's an operator. */
2306 || syntax & RE_CONTEXT_INDEP_ANCHORS
2307 /* Otherwise, depends on what's come before. */
2308 || at_begline_loc_p (pattern, p, syntax))
2309 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2310 else
2311 goto normal_char;
2313 break;
2316 case '$':
2318 if ( /* If at end of pattern, it's an operator. */
2319 p == pend
2320 /* If context independent, it's an operator. */
2321 || syntax & RE_CONTEXT_INDEP_ANCHORS
2322 /* Otherwise, depends on what's next. */
2323 || at_endline_loc_p (p, pend, syntax))
2324 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2325 else
2326 goto normal_char;
2328 break;
2331 case '+':
2332 case '?':
2333 if ((syntax & RE_BK_PLUS_QM)
2334 || (syntax & RE_LIMITED_OPS))
2335 goto normal_char;
2336 handle_plus:
2337 case '*':
2338 /* If there is no previous pattern... */
2339 if (!laststart)
2341 if (syntax & RE_CONTEXT_INVALID_OPS)
2342 FREE_STACK_RETURN (REG_BADRPT);
2343 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2344 goto normal_char;
2348 /* 1 means zero (many) matches is allowed. */
2349 boolean zero_times_ok = 0, many_times_ok = 0;
2350 boolean greedy = 1;
2352 /* If there is a sequence of repetition chars, collapse it
2353 down to just one (the right one). We can't combine
2354 interval operators with these because of, e.g., `a{2}*',
2355 which should only match an even number of `a's. */
2357 for (;;)
2359 if ((syntax & RE_FRUGAL)
2360 && c == '?' && (zero_times_ok || many_times_ok))
2361 greedy = 0;
2362 else
2364 zero_times_ok |= c != '+';
2365 many_times_ok |= c != '?';
2368 if (p == pend)
2369 break;
2370 else if (*p == '*'
2371 || (!(syntax & RE_BK_PLUS_QM)
2372 && (*p == '+' || *p == '?')))
2374 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2376 if (p+1 == pend)
2377 FREE_STACK_RETURN (REG_EESCAPE);
2378 if (p[1] == '+' || p[1] == '?')
2379 PATFETCH (c); /* Gobble up the backslash. */
2380 else
2381 break;
2383 else
2384 break;
2385 /* If we get here, we found another repeat character. */
2386 PATFETCH (c);
2389 /* Star, etc. applied to an empty pattern is equivalent
2390 to an empty pattern. */
2391 if (!laststart || laststart == b)
2392 break;
2394 /* Now we know whether or not zero matches is allowed
2395 and also whether or not two or more matches is allowed. */
2396 if (greedy)
2398 if (many_times_ok)
2400 boolean simple = skip_one_char (laststart) == b;
2401 unsigned int startoffset = 0;
2402 re_opcode_t ofj =
2403 /* Check if the loop can match the empty string. */
2404 (simple || !analyse_first (laststart, b, NULL, 0)) ?
2405 on_failure_jump : on_failure_jump_loop;
2406 assert (skip_one_char (laststart) <= b);
2408 if (!zero_times_ok && simple)
2409 { /* Since simple * loops can be made faster by using
2410 on_failure_keep_string_jump, we turn simple P+
2411 into PP* if P is simple. */
2412 unsigned char *p1, *p2;
2413 startoffset = b - laststart;
2414 GET_BUFFER_SPACE (startoffset);
2415 p1 = b; p2 = laststart;
2416 while (p2 < p1)
2417 *b++ = *p2++;
2418 zero_times_ok = 1;
2421 GET_BUFFER_SPACE (6);
2422 if (!zero_times_ok)
2423 /* A + loop. */
2424 STORE_JUMP (ofj, b, b + 6);
2425 else
2426 /* Simple * loops can use on_failure_keep_string_jump
2427 depending on what follows. But since we don't know
2428 that yet, we leave the decision up to
2429 on_failure_jump_smart. */
2430 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2431 laststart + startoffset, b + 6);
2432 b += 3;
2433 STORE_JUMP (jump, b, laststart + startoffset);
2434 b += 3;
2436 else
2438 /* A simple ? pattern. */
2439 assert (zero_times_ok);
2440 GET_BUFFER_SPACE (3);
2441 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2442 b += 3;
2445 else /* not greedy */
2446 { /* I wish the greedy and non-greedy cases could be merged. */
2448 GET_BUFFER_SPACE (7); /* We might use less. */
2449 if (many_times_ok)
2451 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2453 /* The non-greedy multiple match looks like a repeat..until:
2454 we only need a conditional jump at the end of the loop */
2455 if (emptyp) BUF_PUSH (no_op);
2456 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2457 : on_failure_jump, b, laststart);
2458 b += 3;
2459 if (zero_times_ok)
2461 /* The repeat...until naturally matches one or more.
2462 To also match zero times, we need to first jump to
2463 the end of the loop (its conditional jump). */
2464 INSERT_JUMP (jump, laststart, b);
2465 b += 3;
2468 else
2470 /* non-greedy a?? */
2471 INSERT_JUMP (jump, laststart, b + 3);
2472 b += 3;
2473 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2474 b += 3;
2478 pending_exact = 0;
2479 break;
2482 case '.':
2483 laststart = b;
2484 BUF_PUSH (anychar);
2485 break;
2488 case '[':
2490 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2492 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2494 /* Ensure that we have enough space to push a charset: the
2495 opcode, the length count, and the bitset; 34 bytes in all. */
2496 GET_BUFFER_SPACE (34);
2498 laststart = b;
2500 /* We test `*p == '^' twice, instead of using an if
2501 statement, so we only need one BUF_PUSH. */
2502 BUF_PUSH (*p == '^' ? charset_not : charset);
2503 if (*p == '^')
2504 p++;
2506 /* Remember the first position in the bracket expression. */
2507 p1 = p;
2509 /* Push the number of bytes in the bitmap. */
2510 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2512 /* Clear the whole map. */
2513 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2515 /* charset_not matches newline according to a syntax bit. */
2516 if ((re_opcode_t) b[-2] == charset_not
2517 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2518 SET_LIST_BIT ('\n');
2520 /* Read in characters and ranges, setting map bits. */
2521 for (;;)
2523 boolean escaped_char = false;
2524 const unsigned char *p2 = p;
2526 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2528 PATFETCH (c);
2530 /* \ might escape characters inside [...] and [^...]. */
2531 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2533 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2535 PATFETCH (c);
2536 escaped_char = true;
2538 else
2540 /* Could be the end of the bracket expression. If it's
2541 not (i.e., when the bracket expression is `[]' so
2542 far), the ']' character bit gets set way below. */
2543 if (c == ']' && p2 != p1)
2544 break;
2547 /* What should we do for the character which is
2548 greater than 0x7F, but not BASE_LEADING_CODE_P?
2549 XXX */
2551 /* See if we're at the beginning of a possible character
2552 class. */
2554 if (!escaped_char &&
2555 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2557 /* Leave room for the null. */
2558 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2559 const unsigned char *class_beg;
2561 PATFETCH (c);
2562 c1 = 0;
2563 class_beg = p;
2565 /* If pattern is `[[:'. */
2566 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2568 for (;;)
2570 PATFETCH (c);
2571 if ((c == ':' && *p == ']') || p == pend)
2572 break;
2573 if (c1 < CHAR_CLASS_MAX_LENGTH)
2574 str[c1++] = c;
2575 else
2576 /* This is in any case an invalid class name. */
2577 str[0] = '\0';
2579 str[c1] = '\0';
2581 /* If isn't a word bracketed by `[:' and `:]':
2582 undo the ending character, the letters, and
2583 leave the leading `:' and `[' (but set bits for
2584 them). */
2585 if (c == ':' && *p == ']')
2587 int ch;
2588 re_wctype_t cc;
2590 cc = re_wctype (str);
2592 if (cc == 0)
2593 FREE_STACK_RETURN (REG_ECTYPE);
2595 /* Throw away the ] at the end of the character
2596 class. */
2597 PATFETCH (c);
2599 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2601 /* Most character classes in a multibyte match
2602 just set a flag. Exceptions are is_blank,
2603 is_digit, is_cntrl, and is_xdigit, since
2604 they can only match ASCII characters. We
2605 don't need to handle them for multibyte.
2606 They are distinguished by a negative wctype. */
2608 if (multibyte)
2609 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work,
2610 re_wctype_to_bit (cc));
2612 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
2614 int translated = TRANSLATE (ch);
2615 if (re_iswctype (btowc (ch), cc))
2616 SET_LIST_BIT (translated);
2619 /* Repeat the loop. */
2620 continue;
2622 else
2624 /* Go back to right after the "[:". */
2625 p = class_beg;
2626 SET_LIST_BIT ('[');
2628 /* Because the `:' may starts the range, we
2629 can't simply set bit and repeat the loop.
2630 Instead, just set it to C and handle below. */
2631 c = ':';
2635 if (p < pend && p[0] == '-' && p[1] != ']')
2638 /* Discard the `-'. */
2639 PATFETCH (c1);
2641 /* Fetch the character which ends the range. */
2642 PATFETCH (c1);
2644 if (SINGLE_BYTE_CHAR_P (c))
2646 if (! SINGLE_BYTE_CHAR_P (c1))
2648 /* Handle a range starting with a
2649 character of less than 256, and ending
2650 with a character of not less than 256.
2651 Split that into two ranges, the low one
2652 ending at 0377, and the high one
2653 starting at the smallest character in
2654 the charset of C1 and ending at C1. */
2655 int charset = CHAR_CHARSET (c1);
2656 int c2 = MAKE_CHAR (charset, 0, 0);
2658 SET_RANGE_TABLE_WORK_AREA (range_table_work,
2659 c2, c1);
2660 c1 = 0377;
2663 else if (!SAME_CHARSET_P (c, c1))
2664 FREE_STACK_RETURN (REG_ERANGE);
2666 else
2667 /* Range from C to C. */
2668 c1 = c;
2670 /* Set the range ... */
2671 if (SINGLE_BYTE_CHAR_P (c))
2672 /* ... into bitmap. */
2674 re_wchar_t this_char;
2675 int range_start = c, range_end = c1;
2677 /* If the start is after the end, the range is empty. */
2678 if (range_start > range_end)
2680 if (syntax & RE_NO_EMPTY_RANGES)
2681 FREE_STACK_RETURN (REG_ERANGE);
2682 /* Else, repeat the loop. */
2684 else
2686 for (this_char = range_start; this_char <= range_end;
2687 this_char++)
2688 SET_LIST_BIT (TRANSLATE (this_char));
2691 else
2692 /* ... into range table. */
2693 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2696 /* Discard any (non)matching list bytes that are all 0 at the
2697 end of the map. Decrease the map-length byte too. */
2698 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2699 b[-1]--;
2700 b += b[-1];
2702 /* Build real range table from work area. */
2703 if (RANGE_TABLE_WORK_USED (range_table_work)
2704 || RANGE_TABLE_WORK_BITS (range_table_work))
2706 int i;
2707 int used = RANGE_TABLE_WORK_USED (range_table_work);
2709 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2710 bytes for flags, two for COUNT, and three bytes for
2711 each character. */
2712 GET_BUFFER_SPACE (4 + used * 3);
2714 /* Indicate the existence of range table. */
2715 laststart[1] |= 0x80;
2717 /* Store the character class flag bits into the range table.
2718 If not in emacs, these flag bits are always 0. */
2719 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
2720 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
2722 STORE_NUMBER_AND_INCR (b, used / 2);
2723 for (i = 0; i < used; i++)
2724 STORE_CHARACTER_AND_INCR
2725 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2728 break;
2731 case '(':
2732 if (syntax & RE_NO_BK_PARENS)
2733 goto handle_open;
2734 else
2735 goto normal_char;
2738 case ')':
2739 if (syntax & RE_NO_BK_PARENS)
2740 goto handle_close;
2741 else
2742 goto normal_char;
2745 case '\n':
2746 if (syntax & RE_NEWLINE_ALT)
2747 goto handle_alt;
2748 else
2749 goto normal_char;
2752 case '|':
2753 if (syntax & RE_NO_BK_VBAR)
2754 goto handle_alt;
2755 else
2756 goto normal_char;
2759 case '{':
2760 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2761 goto handle_interval;
2762 else
2763 goto normal_char;
2766 case '\\':
2767 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2769 /* Do not translate the character after the \, so that we can
2770 distinguish, e.g., \B from \b, even if we normally would
2771 translate, e.g., B to b. */
2772 PATFETCH_RAW (c);
2774 switch (c)
2776 case '(':
2777 if (syntax & RE_NO_BK_PARENS)
2778 goto normal_backslash;
2780 handle_open:
2782 int shy = 0;
2783 if (p+1 < pend)
2785 /* Look for a special (?...) construct */
2786 if ((syntax & RE_SHY_GROUPS) && *p == '?')
2788 PATFETCH (c); /* Gobble up the '?'. */
2789 PATFETCH (c);
2790 switch (c)
2792 case ':': shy = 1; break;
2793 default:
2794 /* Only (?:...) is supported right now. */
2795 FREE_STACK_RETURN (REG_BADPAT);
2800 if (!shy)
2802 bufp->re_nsub++;
2803 regnum++;
2806 if (COMPILE_STACK_FULL)
2808 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2809 compile_stack_elt_t);
2810 if (compile_stack.stack == NULL) return REG_ESPACE;
2812 compile_stack.size <<= 1;
2815 /* These are the values to restore when we hit end of this
2816 group. They are all relative offsets, so that if the
2817 whole pattern moves because of realloc, they will still
2818 be valid. */
2819 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2820 COMPILE_STACK_TOP.fixup_alt_jump
2821 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2822 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2823 COMPILE_STACK_TOP.regnum = shy ? -regnum : regnum;
2825 /* Do not push a
2826 start_memory for groups beyond the last one we can
2827 represent in the compiled pattern. */
2828 if (regnum <= MAX_REGNUM && !shy)
2829 BUF_PUSH_2 (start_memory, regnum);
2831 compile_stack.avail++;
2833 fixup_alt_jump = 0;
2834 laststart = 0;
2835 begalt = b;
2836 /* If we've reached MAX_REGNUM groups, then this open
2837 won't actually generate any code, so we'll have to
2838 clear pending_exact explicitly. */
2839 pending_exact = 0;
2840 break;
2843 case ')':
2844 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2846 if (COMPILE_STACK_EMPTY)
2848 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2849 goto normal_backslash;
2850 else
2851 FREE_STACK_RETURN (REG_ERPAREN);
2854 handle_close:
2855 FIXUP_ALT_JUMP ();
2857 /* See similar code for backslashed left paren above. */
2858 if (COMPILE_STACK_EMPTY)
2860 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2861 goto normal_char;
2862 else
2863 FREE_STACK_RETURN (REG_ERPAREN);
2866 /* Since we just checked for an empty stack above, this
2867 ``can't happen''. */
2868 assert (compile_stack.avail != 0);
2870 /* We don't just want to restore into `regnum', because
2871 later groups should continue to be numbered higher,
2872 as in `(ab)c(de)' -- the second group is #2. */
2873 regnum_t this_group_regnum;
2875 compile_stack.avail--;
2876 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2877 fixup_alt_jump
2878 = COMPILE_STACK_TOP.fixup_alt_jump
2879 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2880 : 0;
2881 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2882 this_group_regnum = COMPILE_STACK_TOP.regnum;
2883 /* If we've reached MAX_REGNUM groups, then this open
2884 won't actually generate any code, so we'll have to
2885 clear pending_exact explicitly. */
2886 pending_exact = 0;
2888 /* We're at the end of the group, so now we know how many
2889 groups were inside this one. */
2890 if (this_group_regnum <= MAX_REGNUM && this_group_regnum > 0)
2891 BUF_PUSH_2 (stop_memory, this_group_regnum);
2893 break;
2896 case '|': /* `\|'. */
2897 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2898 goto normal_backslash;
2899 handle_alt:
2900 if (syntax & RE_LIMITED_OPS)
2901 goto normal_char;
2903 /* Insert before the previous alternative a jump which
2904 jumps to this alternative if the former fails. */
2905 GET_BUFFER_SPACE (3);
2906 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2907 pending_exact = 0;
2908 b += 3;
2910 /* The alternative before this one has a jump after it
2911 which gets executed if it gets matched. Adjust that
2912 jump so it will jump to this alternative's analogous
2913 jump (put in below, which in turn will jump to the next
2914 (if any) alternative's such jump, etc.). The last such
2915 jump jumps to the correct final destination. A picture:
2916 _____ _____
2917 | | | |
2918 | v | v
2919 a | b | c
2921 If we are at `b', then fixup_alt_jump right now points to a
2922 three-byte space after `a'. We'll put in the jump, set
2923 fixup_alt_jump to right after `b', and leave behind three
2924 bytes which we'll fill in when we get to after `c'. */
2926 FIXUP_ALT_JUMP ();
2928 /* Mark and leave space for a jump after this alternative,
2929 to be filled in later either by next alternative or
2930 when know we're at the end of a series of alternatives. */
2931 fixup_alt_jump = b;
2932 GET_BUFFER_SPACE (3);
2933 b += 3;
2935 laststart = 0;
2936 begalt = b;
2937 break;
2940 case '{':
2941 /* If \{ is a literal. */
2942 if (!(syntax & RE_INTERVALS)
2943 /* If we're at `\{' and it's not the open-interval
2944 operator. */
2945 || (syntax & RE_NO_BK_BRACES))
2946 goto normal_backslash;
2948 handle_interval:
2950 /* If got here, then the syntax allows intervals. */
2952 /* At least (most) this many matches must be made. */
2953 int lower_bound = 0, upper_bound = -1;
2955 beg_interval = p;
2957 if (p == pend)
2958 FREE_STACK_RETURN (REG_EBRACE);
2960 GET_UNSIGNED_NUMBER (lower_bound);
2962 if (c == ',')
2963 GET_UNSIGNED_NUMBER (upper_bound);
2964 else
2965 /* Interval such as `{1}' => match exactly once. */
2966 upper_bound = lower_bound;
2968 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2969 || (upper_bound >= 0 && lower_bound > upper_bound))
2970 FREE_STACK_RETURN (REG_BADBR);
2972 if (!(syntax & RE_NO_BK_BRACES))
2974 if (c != '\\')
2975 FREE_STACK_RETURN (REG_BADBR);
2977 PATFETCH (c);
2980 if (c != '}')
2981 FREE_STACK_RETURN (REG_BADBR);
2983 /* We just parsed a valid interval. */
2985 /* If it's invalid to have no preceding re. */
2986 if (!laststart)
2988 if (syntax & RE_CONTEXT_INVALID_OPS)
2989 FREE_STACK_RETURN (REG_BADRPT);
2990 else if (syntax & RE_CONTEXT_INDEP_OPS)
2991 laststart = b;
2992 else
2993 goto unfetch_interval;
2996 if (upper_bound == 0)
2997 /* If the upper bound is zero, just drop the sub pattern
2998 altogether. */
2999 b = laststart;
3000 else if (lower_bound == 1 && upper_bound == 1)
3001 /* Just match it once: nothing to do here. */
3004 /* Otherwise, we have a nontrivial interval. When
3005 we're all done, the pattern will look like:
3006 set_number_at <jump count> <upper bound>
3007 set_number_at <succeed_n count> <lower bound>
3008 succeed_n <after jump addr> <succeed_n count>
3009 <body of loop>
3010 jump_n <succeed_n addr> <jump count>
3011 (The upper bound and `jump_n' are omitted if
3012 `upper_bound' is 1, though.) */
3013 else
3014 { /* If the upper bound is > 1, we need to insert
3015 more at the end of the loop. */
3016 unsigned int nbytes = (upper_bound < 0 ? 3
3017 : upper_bound > 1 ? 5 : 0);
3018 unsigned int startoffset = 0;
3020 GET_BUFFER_SPACE (20); /* We might use less. */
3022 if (lower_bound == 0)
3024 /* A succeed_n that starts with 0 is really a
3025 a simple on_failure_jump_loop. */
3026 INSERT_JUMP (on_failure_jump_loop, laststart,
3027 b + 3 + nbytes);
3028 b += 3;
3030 else
3032 /* Initialize lower bound of the `succeed_n', even
3033 though it will be set during matching by its
3034 attendant `set_number_at' (inserted next),
3035 because `re_compile_fastmap' needs to know.
3036 Jump to the `jump_n' we might insert below. */
3037 INSERT_JUMP2 (succeed_n, laststart,
3038 b + 5 + nbytes,
3039 lower_bound);
3040 b += 5;
3042 /* Code to initialize the lower bound. Insert
3043 before the `succeed_n'. The `5' is the last two
3044 bytes of this `set_number_at', plus 3 bytes of
3045 the following `succeed_n'. */
3046 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3047 b += 5;
3048 startoffset += 5;
3051 if (upper_bound < 0)
3053 /* A negative upper bound stands for infinity,
3054 in which case it degenerates to a plain jump. */
3055 STORE_JUMP (jump, b, laststart + startoffset);
3056 b += 3;
3058 else if (upper_bound > 1)
3059 { /* More than one repetition is allowed, so
3060 append a backward jump to the `succeed_n'
3061 that starts this interval.
3063 When we've reached this during matching,
3064 we'll have matched the interval once, so
3065 jump back only `upper_bound - 1' times. */
3066 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3067 upper_bound - 1);
3068 b += 5;
3070 /* The location we want to set is the second
3071 parameter of the `jump_n'; that is `b-2' as
3072 an absolute address. `laststart' will be
3073 the `set_number_at' we're about to insert;
3074 `laststart+3' the number to set, the source
3075 for the relative address. But we are
3076 inserting into the middle of the pattern --
3077 so everything is getting moved up by 5.
3078 Conclusion: (b - 2) - (laststart + 3) + 5,
3079 i.e., b - laststart.
3081 We insert this at the beginning of the loop
3082 so that if we fail during matching, we'll
3083 reinitialize the bounds. */
3084 insert_op2 (set_number_at, laststart, b - laststart,
3085 upper_bound - 1, b);
3086 b += 5;
3089 pending_exact = 0;
3090 beg_interval = NULL;
3092 break;
3094 unfetch_interval:
3095 /* If an invalid interval, match the characters as literals. */
3096 assert (beg_interval);
3097 p = beg_interval;
3098 beg_interval = NULL;
3100 /* normal_char and normal_backslash need `c'. */
3101 c = '{';
3103 if (!(syntax & RE_NO_BK_BRACES))
3105 assert (p > pattern && p[-1] == '\\');
3106 goto normal_backslash;
3108 else
3109 goto normal_char;
3111 #ifdef emacs
3112 /* There is no way to specify the before_dot and after_dot
3113 operators. rms says this is ok. --karl */
3114 case '=':
3115 BUF_PUSH (at_dot);
3116 break;
3118 case 's':
3119 laststart = b;
3120 PATFETCH (c);
3121 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3122 break;
3124 case 'S':
3125 laststart = b;
3126 PATFETCH (c);
3127 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3128 break;
3130 case 'c':
3131 laststart = b;
3132 PATFETCH_RAW (c);
3133 BUF_PUSH_2 (categoryspec, c);
3134 break;
3136 case 'C':
3137 laststart = b;
3138 PATFETCH_RAW (c);
3139 BUF_PUSH_2 (notcategoryspec, c);
3140 break;
3141 #endif /* emacs */
3144 case 'w':
3145 if (syntax & RE_NO_GNU_OPS)
3146 goto normal_char;
3147 laststart = b;
3148 BUF_PUSH_2 (syntaxspec, Sword);
3149 break;
3152 case 'W':
3153 if (syntax & RE_NO_GNU_OPS)
3154 goto normal_char;
3155 laststart = b;
3156 BUF_PUSH_2 (notsyntaxspec, Sword);
3157 break;
3160 case '<':
3161 if (syntax & RE_NO_GNU_OPS)
3162 goto normal_char;
3163 BUF_PUSH (wordbeg);
3164 break;
3166 case '>':
3167 if (syntax & RE_NO_GNU_OPS)
3168 goto normal_char;
3169 BUF_PUSH (wordend);
3170 break;
3172 case 'b':
3173 if (syntax & RE_NO_GNU_OPS)
3174 goto normal_char;
3175 BUF_PUSH (wordbound);
3176 break;
3178 case 'B':
3179 if (syntax & RE_NO_GNU_OPS)
3180 goto normal_char;
3181 BUF_PUSH (notwordbound);
3182 break;
3184 case '`':
3185 if (syntax & RE_NO_GNU_OPS)
3186 goto normal_char;
3187 BUF_PUSH (begbuf);
3188 break;
3190 case '\'':
3191 if (syntax & RE_NO_GNU_OPS)
3192 goto normal_char;
3193 BUF_PUSH (endbuf);
3194 break;
3196 case '1': case '2': case '3': case '4': case '5':
3197 case '6': case '7': case '8': case '9':
3199 regnum_t reg;
3201 if (syntax & RE_NO_BK_REFS)
3202 goto normal_backslash;
3204 reg = c - '0';
3206 /* Can't back reference to a subexpression before its end. */
3207 if (reg > regnum || group_in_compile_stack (compile_stack, reg))
3208 FREE_STACK_RETURN (REG_ESUBREG);
3210 laststart = b;
3211 BUF_PUSH_2 (duplicate, reg);
3213 break;
3216 case '+':
3217 case '?':
3218 if (syntax & RE_BK_PLUS_QM)
3219 goto handle_plus;
3220 else
3221 goto normal_backslash;
3223 default:
3224 normal_backslash:
3225 /* You might think it would be useful for \ to mean
3226 not to translate; but if we don't translate it
3227 it will never match anything. */
3228 c = TRANSLATE (c);
3229 goto normal_char;
3231 break;
3234 default:
3235 /* Expects the character in `c'. */
3236 normal_char:
3237 /* If no exactn currently being built. */
3238 if (!pending_exact
3240 /* If last exactn not at current position. */
3241 || pending_exact + *pending_exact + 1 != b
3243 /* We have only one byte following the exactn for the count. */
3244 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3246 /* If followed by a repetition operator. */
3247 || (p != pend && (*p == '*' || *p == '^'))
3248 || ((syntax & RE_BK_PLUS_QM)
3249 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3250 : p != pend && (*p == '+' || *p == '?'))
3251 || ((syntax & RE_INTERVALS)
3252 && ((syntax & RE_NO_BK_BRACES)
3253 ? p != pend && *p == '{'
3254 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3256 /* Start building a new exactn. */
3258 laststart = b;
3260 BUF_PUSH_2 (exactn, 0);
3261 pending_exact = b - 1;
3264 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3266 int len;
3268 if (multibyte)
3269 len = CHAR_STRING (c, b);
3270 else
3271 *b = c, len = 1;
3272 b += len;
3273 (*pending_exact) += len;
3276 break;
3277 } /* switch (c) */
3278 } /* while p != pend */
3281 /* Through the pattern now. */
3283 FIXUP_ALT_JUMP ();
3285 if (!COMPILE_STACK_EMPTY)
3286 FREE_STACK_RETURN (REG_EPAREN);
3288 /* If we don't want backtracking, force success
3289 the first time we reach the end of the compiled pattern. */
3290 if (syntax & RE_NO_POSIX_BACKTRACKING)
3291 BUF_PUSH (succeed);
3293 free (compile_stack.stack);
3295 /* We have succeeded; set the length of the buffer. */
3296 bufp->used = b - bufp->buffer;
3298 #ifdef DEBUG
3299 if (debug > 0)
3301 re_compile_fastmap (bufp);
3302 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3303 print_compiled_pattern (bufp);
3305 debug--;
3306 #endif /* DEBUG */
3308 #ifndef MATCH_MAY_ALLOCATE
3309 /* Initialize the failure stack to the largest possible stack. This
3310 isn't necessary unless we're trying to avoid calling alloca in
3311 the search and match routines. */
3313 int num_regs = bufp->re_nsub + 1;
3315 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3317 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3319 if (! fail_stack.stack)
3320 fail_stack.stack
3321 = (fail_stack_elt_t *) malloc (fail_stack.size
3322 * sizeof (fail_stack_elt_t));
3323 else
3324 fail_stack.stack
3325 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3326 (fail_stack.size
3327 * sizeof (fail_stack_elt_t)));
3330 regex_grow_registers (num_regs);
3332 #endif /* not MATCH_MAY_ALLOCATE */
3334 return REG_NOERROR;
3335 } /* regex_compile */
3337 /* Subroutines for `regex_compile'. */
3339 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3341 static void
3342 store_op1 (op, loc, arg)
3343 re_opcode_t op;
3344 unsigned char *loc;
3345 int arg;
3347 *loc = (unsigned char) op;
3348 STORE_NUMBER (loc + 1, arg);
3352 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3354 static void
3355 store_op2 (op, loc, arg1, arg2)
3356 re_opcode_t op;
3357 unsigned char *loc;
3358 int arg1, arg2;
3360 *loc = (unsigned char) op;
3361 STORE_NUMBER (loc + 1, arg1);
3362 STORE_NUMBER (loc + 3, arg2);
3366 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3367 for OP followed by two-byte integer parameter ARG. */
3369 static void
3370 insert_op1 (op, loc, arg, end)
3371 re_opcode_t op;
3372 unsigned char *loc;
3373 int arg;
3374 unsigned char *end;
3376 register unsigned char *pfrom = end;
3377 register unsigned char *pto = end + 3;
3379 while (pfrom != loc)
3380 *--pto = *--pfrom;
3382 store_op1 (op, loc, arg);
3386 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3388 static void
3389 insert_op2 (op, loc, arg1, arg2, end)
3390 re_opcode_t op;
3391 unsigned char *loc;
3392 int arg1, arg2;
3393 unsigned char *end;
3395 register unsigned char *pfrom = end;
3396 register unsigned char *pto = end + 5;
3398 while (pfrom != loc)
3399 *--pto = *--pfrom;
3401 store_op2 (op, loc, arg1, arg2);
3405 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3406 after an alternative or a begin-subexpression. We assume there is at
3407 least one character before the ^. */
3409 static boolean
3410 at_begline_loc_p (pattern, p, syntax)
3411 re_char *pattern, *p;
3412 reg_syntax_t syntax;
3414 re_char *prev = p - 2;
3415 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3417 return
3418 /* After a subexpression? */
3419 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3420 /* After an alternative? */
3421 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash))
3422 /* After a shy subexpression? */
3423 || ((syntax & RE_SHY_GROUPS) && prev - 2 >= pattern
3424 && prev[-1] == '?' && prev[-2] == '('
3425 && (syntax & RE_NO_BK_PARENS
3426 || (prev - 3 >= pattern && prev[-3] == '\\')));
3430 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3431 at least one character after the $, i.e., `P < PEND'. */
3433 static boolean
3434 at_endline_loc_p (p, pend, syntax)
3435 re_char *p, *pend;
3436 reg_syntax_t syntax;
3438 re_char *next = p;
3439 boolean next_backslash = *next == '\\';
3440 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3442 return
3443 /* Before a subexpression? */
3444 (syntax & RE_NO_BK_PARENS ? *next == ')'
3445 : next_backslash && next_next && *next_next == ')')
3446 /* Before an alternative? */
3447 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3448 : next_backslash && next_next && *next_next == '|');
3452 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3453 false if it's not. */
3455 static boolean
3456 group_in_compile_stack (compile_stack, regnum)
3457 compile_stack_type compile_stack;
3458 regnum_t regnum;
3460 int this_element;
3462 for (this_element = compile_stack.avail - 1;
3463 this_element >= 0;
3464 this_element--)
3465 if (compile_stack.stack[this_element].regnum == regnum)
3466 return true;
3468 return false;
3471 /* analyse_first.
3472 If fastmap is non-NULL, go through the pattern and fill fastmap
3473 with all the possible leading chars. If fastmap is NULL, don't
3474 bother filling it up (obviously) and only return whether the
3475 pattern could potentially match the empty string.
3477 Return 1 if p..pend might match the empty string.
3478 Return 0 if p..pend matches at least one char.
3479 Return -1 if fastmap was not updated accurately. */
3481 static int
3482 analyse_first (p, pend, fastmap, multibyte)
3483 re_char *p, *pend;
3484 char *fastmap;
3485 const int multibyte;
3487 int j, k;
3488 boolean not;
3490 /* If all elements for base leading-codes in fastmap is set, this
3491 flag is set true. */
3492 boolean match_any_multibyte_characters = false;
3494 assert (p);
3496 /* The loop below works as follows:
3497 - It has a working-list kept in the PATTERN_STACK and which basically
3498 starts by only containing a pointer to the first operation.
3499 - If the opcode we're looking at is a match against some set of
3500 chars, then we add those chars to the fastmap and go on to the
3501 next work element from the worklist (done via `break').
3502 - If the opcode is a control operator on the other hand, we either
3503 ignore it (if it's meaningless at this point, such as `start_memory')
3504 or execute it (if it's a jump). If the jump has several destinations
3505 (i.e. `on_failure_jump'), then we push the other destination onto the
3506 worklist.
3507 We guarantee termination by ignoring backward jumps (more or less),
3508 so that `p' is monotonically increasing. More to the point, we
3509 never set `p' (or push) anything `<= p1'. */
3511 while (p < pend)
3513 /* `p1' is used as a marker of how far back a `on_failure_jump'
3514 can go without being ignored. It is normally equal to `p'
3515 (which prevents any backward `on_failure_jump') except right
3516 after a plain `jump', to allow patterns such as:
3517 0: jump 10
3518 3..9: <body>
3519 10: on_failure_jump 3
3520 as used for the *? operator. */
3521 re_char *p1 = p;
3523 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3525 case succeed:
3526 return 1;
3527 continue;
3529 case duplicate:
3530 /* If the first character has to match a backreference, that means
3531 that the group was empty (since it already matched). Since this
3532 is the only case that interests us here, we can assume that the
3533 backreference must match the empty string. */
3534 p++;
3535 continue;
3538 /* Following are the cases which match a character. These end
3539 with `break'. */
3541 case exactn:
3542 if (fastmap)
3544 int c = RE_STRING_CHAR (p + 1, pend - p);
3546 if (SINGLE_BYTE_CHAR_P (c))
3547 fastmap[c] = 1;
3548 else
3549 fastmap[p[1]] = 1;
3551 break;
3554 case anychar:
3555 /* We could put all the chars except for \n (and maybe \0)
3556 but we don't bother since it is generally not worth it. */
3557 if (!fastmap) break;
3558 return -1;
3561 case charset_not:
3562 /* Chars beyond end of bitmap are possible matches.
3563 All the single-byte codes can occur in multibyte buffers.
3564 So any that are not listed in the charset
3565 are possible matches, even in multibyte buffers. */
3566 if (!fastmap) break;
3567 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3568 j < (1 << BYTEWIDTH); j++)
3569 fastmap[j] = 1;
3570 /* Fallthrough */
3571 case charset:
3572 if (!fastmap) break;
3573 not = (re_opcode_t) *(p - 1) == charset_not;
3574 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3575 j >= 0; j--)
3576 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3577 fastmap[j] = 1;
3579 if ((not && multibyte)
3580 /* Any character set can possibly contain a character
3581 which doesn't match the specified set of characters. */
3582 || (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3583 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3584 /* If we can match a character class, we can match
3585 any character set. */
3587 set_fastmap_for_multibyte_characters:
3588 if (match_any_multibyte_characters == false)
3590 for (j = 0x80; j < 0xA0; j++) /* XXX */
3591 if (BASE_LEADING_CODE_P (j))
3592 fastmap[j] = 1;
3593 match_any_multibyte_characters = true;
3597 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3598 && match_any_multibyte_characters == false)
3600 /* Set fastmap[I] 1 where I is a base leading code of each
3601 multibyte character in the range table. */
3602 int c, count;
3604 /* Make P points the range table. `+ 2' is to skip flag
3605 bits for a character class. */
3606 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3608 /* Extract the number of ranges in range table into COUNT. */
3609 EXTRACT_NUMBER_AND_INCR (count, p);
3610 for (; count > 0; count--, p += 2 * 3) /* XXX */
3612 /* Extract the start of each range. */
3613 EXTRACT_CHARACTER (c, p);
3614 j = CHAR_CHARSET (c);
3615 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3618 break;
3620 case syntaxspec:
3621 case notsyntaxspec:
3622 if (!fastmap) break;
3623 #ifndef emacs
3624 not = (re_opcode_t)p[-1] == notsyntaxspec;
3625 k = *p++;
3626 for (j = 0; j < (1 << BYTEWIDTH); j++)
3627 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3628 fastmap[j] = 1;
3629 break;
3630 #else /* emacs */
3631 /* This match depends on text properties. These end with
3632 aborting optimizations. */
3633 return -1;
3635 case categoryspec:
3636 case notcategoryspec:
3637 if (!fastmap) break;
3638 not = (re_opcode_t)p[-1] == notcategoryspec;
3639 k = *p++;
3640 for (j = 0; j < (1 << BYTEWIDTH); j++)
3641 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3642 fastmap[j] = 1;
3644 if (multibyte)
3645 /* Any character set can possibly contain a character
3646 whose category is K (or not). */
3647 goto set_fastmap_for_multibyte_characters;
3648 break;
3650 /* All cases after this match the empty string. These end with
3651 `continue'. */
3653 case before_dot:
3654 case at_dot:
3655 case after_dot:
3656 #endif /* !emacs */
3657 case no_op:
3658 case begline:
3659 case endline:
3660 case begbuf:
3661 case endbuf:
3662 case wordbound:
3663 case notwordbound:
3664 case wordbeg:
3665 case wordend:
3666 continue;
3669 case jump:
3670 EXTRACT_NUMBER_AND_INCR (j, p);
3671 if (j < 0)
3672 /* Backward jumps can only go back to code that we've already
3673 visited. `re_compile' should make sure this is true. */
3674 break;
3675 p += j;
3676 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
3678 case on_failure_jump:
3679 case on_failure_keep_string_jump:
3680 case on_failure_jump_loop:
3681 case on_failure_jump_nastyloop:
3682 case on_failure_jump_smart:
3683 p++;
3684 break;
3685 default:
3686 continue;
3688 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3689 to jump back to "just after here". */
3690 /* Fallthrough */
3692 case on_failure_jump:
3693 case on_failure_keep_string_jump:
3694 case on_failure_jump_nastyloop:
3695 case on_failure_jump_loop:
3696 case on_failure_jump_smart:
3697 EXTRACT_NUMBER_AND_INCR (j, p);
3698 if (p + j <= p1)
3699 ; /* Backward jump to be ignored. */
3700 else
3701 { /* We have to look down both arms.
3702 We first go down the "straight" path so as to minimize
3703 stack usage when going through alternatives. */
3704 int r = analyse_first (p, pend, fastmap, multibyte);
3705 if (r) return r;
3706 p += j;
3708 continue;
3711 case jump_n:
3712 /* This code simply does not properly handle forward jump_n. */
3713 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
3714 p += 4;
3715 /* jump_n can either jump or fall through. The (backward) jump
3716 case has already been handled, so we only need to look at the
3717 fallthrough case. */
3718 continue;
3720 case succeed_n:
3721 /* If N == 0, it should be an on_failure_jump_loop instead. */
3722 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
3723 p += 4;
3724 /* We only care about one iteration of the loop, so we don't
3725 need to consider the case where this behaves like an
3726 on_failure_jump. */
3727 continue;
3730 case set_number_at:
3731 p += 4;
3732 continue;
3735 case start_memory:
3736 case stop_memory:
3737 p += 1;
3738 continue;
3741 default:
3742 abort (); /* We have listed all the cases. */
3743 } /* switch *p++ */
3745 /* Getting here means we have found the possible starting
3746 characters for one path of the pattern -- and that the empty
3747 string does not match. We need not follow this path further. */
3748 return 0;
3749 } /* while p */
3751 /* We reached the end without matching anything. */
3752 return 1;
3754 } /* analyse_first */
3756 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3757 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3758 characters can start a string that matches the pattern. This fastmap
3759 is used by re_search to skip quickly over impossible starting points.
3761 Character codes above (1 << BYTEWIDTH) are not represented in the
3762 fastmap, but the leading codes are represented. Thus, the fastmap
3763 indicates which character sets could start a match.
3765 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3766 area as BUFP->fastmap.
3768 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3769 the pattern buffer.
3771 Returns 0 if we succeed, -2 if an internal error. */
3774 re_compile_fastmap (bufp)
3775 struct re_pattern_buffer *bufp;
3777 char *fastmap = bufp->fastmap;
3778 int analysis;
3780 assert (fastmap && bufp->buffer);
3782 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3783 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3785 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
3786 fastmap, RE_MULTIBYTE_P (bufp));
3787 bufp->can_be_null = (analysis != 0);
3788 return 0;
3789 } /* re_compile_fastmap */
3791 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3792 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3793 this memory for recording register information. STARTS and ENDS
3794 must be allocated using the malloc library routine, and must each
3795 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3797 If NUM_REGS == 0, then subsequent matches should allocate their own
3798 register data.
3800 Unless this function is called, the first search or match using
3801 PATTERN_BUFFER will allocate its own register data, without
3802 freeing the old data. */
3804 void
3805 re_set_registers (bufp, regs, num_regs, starts, ends)
3806 struct re_pattern_buffer *bufp;
3807 struct re_registers *regs;
3808 unsigned num_regs;
3809 regoff_t *starts, *ends;
3811 if (num_regs)
3813 bufp->regs_allocated = REGS_REALLOCATE;
3814 regs->num_regs = num_regs;
3815 regs->start = starts;
3816 regs->end = ends;
3818 else
3820 bufp->regs_allocated = REGS_UNALLOCATED;
3821 regs->num_regs = 0;
3822 regs->start = regs->end = (regoff_t *) 0;
3825 WEAK_ALIAS (__re_set_registers, re_set_registers)
3827 /* Searching routines. */
3829 /* Like re_search_2, below, but only one string is specified, and
3830 doesn't let you say where to stop matching. */
3833 re_search (bufp, string, size, startpos, range, regs)
3834 struct re_pattern_buffer *bufp;
3835 const char *string;
3836 int size, startpos, range;
3837 struct re_registers *regs;
3839 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3840 regs, size);
3842 WEAK_ALIAS (__re_search, re_search)
3844 /* End address of virtual concatenation of string. */
3845 #define STOP_ADDR_VSTRING(P) \
3846 (((P) >= size1 ? string2 + size2 : string1 + size1))
3848 /* Address of POS in the concatenation of virtual string. */
3849 #define POS_ADDR_VSTRING(POS) \
3850 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3852 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3853 virtual concatenation of STRING1 and STRING2, starting first at index
3854 STARTPOS, then at STARTPOS + 1, and so on.
3856 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3858 RANGE is how far to scan while trying to match. RANGE = 0 means try
3859 only at STARTPOS; in general, the last start tried is STARTPOS +
3860 RANGE.
3862 In REGS, return the indices of the virtual concatenation of STRING1
3863 and STRING2 that matched the entire BUFP->buffer and its contained
3864 subexpressions.
3866 Do not consider matching one past the index STOP in the virtual
3867 concatenation of STRING1 and STRING2.
3869 We return either the position in the strings at which the match was
3870 found, -1 if no match, or -2 if error (such as failure
3871 stack overflow). */
3874 re_search_2 (bufp, str1, size1, str2, size2, startpos, range, regs, stop)
3875 struct re_pattern_buffer *bufp;
3876 const char *str1, *str2;
3877 int size1, size2;
3878 int startpos;
3879 int range;
3880 struct re_registers *regs;
3881 int stop;
3883 int val;
3884 re_char *string1 = (re_char*) str1;
3885 re_char *string2 = (re_char*) str2;
3886 register char *fastmap = bufp->fastmap;
3887 register RE_TRANSLATE_TYPE translate = bufp->translate;
3888 int total_size = size1 + size2;
3889 int endpos = startpos + range;
3890 boolean anchored_start;
3892 /* Nonzero if we have to concern multibyte character. */
3893 const boolean multibyte = RE_MULTIBYTE_P (bufp);
3895 /* Check for out-of-range STARTPOS. */
3896 if (startpos < 0 || startpos > total_size)
3897 return -1;
3899 /* Fix up RANGE if it might eventually take us outside
3900 the virtual concatenation of STRING1 and STRING2.
3901 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3902 if (endpos < 0)
3903 range = 0 - startpos;
3904 else if (endpos > total_size)
3905 range = total_size - startpos;
3907 /* If the search isn't to be a backwards one, don't waste time in a
3908 search for a pattern anchored at beginning of buffer. */
3909 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3911 if (startpos > 0)
3912 return -1;
3913 else
3914 range = 0;
3917 #ifdef emacs
3918 /* In a forward search for something that starts with \=.
3919 don't keep searching past point. */
3920 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3922 range = PT_BYTE - BEGV_BYTE - startpos;
3923 if (range < 0)
3924 return -1;
3926 #endif /* emacs */
3928 /* Update the fastmap now if not correct already. */
3929 if (fastmap && !bufp->fastmap_accurate)
3930 re_compile_fastmap (bufp);
3932 /* See whether the pattern is anchored. */
3933 anchored_start = (bufp->buffer[0] == begline);
3935 #ifdef emacs
3936 gl_state.object = re_match_object;
3938 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
3940 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
3942 #endif
3944 /* Loop through the string, looking for a place to start matching. */
3945 for (;;)
3947 /* If the pattern is anchored,
3948 skip quickly past places we cannot match.
3949 We don't bother to treat startpos == 0 specially
3950 because that case doesn't repeat. */
3951 if (anchored_start && startpos > 0)
3953 if (! ((startpos <= size1 ? string1[startpos - 1]
3954 : string2[startpos - size1 - 1])
3955 == '\n'))
3956 goto advance;
3959 /* If a fastmap is supplied, skip quickly over characters that
3960 cannot be the start of a match. If the pattern can match the
3961 null string, however, we don't need to skip characters; we want
3962 the first null string. */
3963 if (fastmap && startpos < total_size && !bufp->can_be_null)
3965 register re_char *d;
3966 register re_wchar_t buf_ch;
3968 d = POS_ADDR_VSTRING (startpos);
3970 if (range > 0) /* Searching forwards. */
3972 register int lim = 0;
3973 int irange = range;
3975 if (startpos < size1 && startpos + range >= size1)
3976 lim = range - (size1 - startpos);
3978 /* Written out as an if-else to avoid testing `translate'
3979 inside the loop. */
3980 if (RE_TRANSLATE_P (translate))
3982 if (multibyte)
3983 while (range > lim)
3985 int buf_charlen;
3987 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
3988 buf_charlen);
3990 buf_ch = RE_TRANSLATE (translate, buf_ch);
3991 if (buf_ch >= 0400
3992 || fastmap[buf_ch])
3993 break;
3995 range -= buf_charlen;
3996 d += buf_charlen;
3998 else
3999 while (range > lim
4000 && !fastmap[RE_TRANSLATE (translate, *d)])
4002 d++;
4003 range--;
4006 else
4007 while (range > lim && !fastmap[*d])
4009 d++;
4010 range--;
4013 startpos += irange - range;
4015 else /* Searching backwards. */
4017 int room = (startpos >= size1
4018 ? size2 + size1 - startpos
4019 : size1 - startpos);
4020 buf_ch = RE_STRING_CHAR (d, room);
4021 buf_ch = TRANSLATE (buf_ch);
4023 if (! (buf_ch >= 0400
4024 || fastmap[buf_ch]))
4025 goto advance;
4029 /* If can't match the null string, and that's all we have left, fail. */
4030 if (range >= 0 && startpos == total_size && fastmap
4031 && !bufp->can_be_null)
4032 return -1;
4034 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4035 startpos, regs, stop);
4036 #ifndef REGEX_MALLOC
4037 # ifdef C_ALLOCA
4038 alloca (0);
4039 # endif
4040 #endif
4042 if (val >= 0)
4043 return startpos;
4045 if (val == -2)
4046 return -2;
4048 advance:
4049 if (!range)
4050 break;
4051 else if (range > 0)
4053 /* Update STARTPOS to the next character boundary. */
4054 if (multibyte)
4056 re_char *p = POS_ADDR_VSTRING (startpos);
4057 re_char *pend = STOP_ADDR_VSTRING (startpos);
4058 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
4060 range -= len;
4061 if (range < 0)
4062 break;
4063 startpos += len;
4065 else
4067 range--;
4068 startpos++;
4071 else
4073 range++;
4074 startpos--;
4076 /* Update STARTPOS to the previous character boundary. */
4077 if (multibyte)
4079 re_char *p = POS_ADDR_VSTRING (startpos);
4080 int len = 0;
4082 /* Find the head of multibyte form. */
4083 while (!CHAR_HEAD_P (*p))
4084 p--, len++;
4086 /* Adjust it. */
4087 #if 0 /* XXX */
4088 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
4090 else
4091 #endif
4093 range += len;
4094 if (range > 0)
4095 break;
4097 startpos -= len;
4102 return -1;
4103 } /* re_search_2 */
4104 WEAK_ALIAS (__re_search_2, re_search_2)
4106 /* Declarations and macros for re_match_2. */
4108 static int bcmp_translate _RE_ARGS((re_char *s1, re_char *s2,
4109 register int len,
4110 RE_TRANSLATE_TYPE translate,
4111 const int multibyte));
4113 /* This converts PTR, a pointer into one of the search strings `string1'
4114 and `string2' into an offset from the beginning of that string. */
4115 #define POINTER_TO_OFFSET(ptr) \
4116 (FIRST_STRING_P (ptr) \
4117 ? ((regoff_t) ((ptr) - string1)) \
4118 : ((regoff_t) ((ptr) - string2 + size1)))
4120 /* Call before fetching a character with *d. This switches over to
4121 string2 if necessary.
4122 Check re_match_2_internal for a discussion of why end_match_2 might
4123 not be within string2 (but be equal to end_match_1 instead). */
4124 #define PREFETCH() \
4125 while (d == dend) \
4127 /* End of string2 => fail. */ \
4128 if (dend == end_match_2) \
4129 goto fail; \
4130 /* End of string1 => advance to string2. */ \
4131 d = string2; \
4132 dend = end_match_2; \
4135 /* Call before fetching a char with *d if you already checked other limits.
4136 This is meant for use in lookahead operations like wordend, etc..
4137 where we might need to look at parts of the string that might be
4138 outside of the LIMITs (i.e past `stop'). */
4139 #define PREFETCH_NOLIMIT() \
4140 if (d == end1) \
4142 d = string2; \
4143 dend = end_match_2; \
4146 /* Test if at very beginning or at very end of the virtual concatenation
4147 of `string1' and `string2'. If only one string, it's `string2'. */
4148 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4149 #define AT_STRINGS_END(d) ((d) == end2)
4152 /* Test if D points to a character which is word-constituent. We have
4153 two special cases to check for: if past the end of string1, look at
4154 the first character in string2; and if before the beginning of
4155 string2, look at the last character in string1. */
4156 #define WORDCHAR_P(d) \
4157 (SYNTAX ((d) == end1 ? *string2 \
4158 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4159 == Sword)
4161 /* Disabled due to a compiler bug -- see comment at case wordbound */
4163 /* The comment at case wordbound is following one, but we don't use
4164 AT_WORD_BOUNDARY anymore to support multibyte form.
4166 The DEC Alpha C compiler 3.x generates incorrect code for the
4167 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4168 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4169 macro and introducing temporary variables works around the bug. */
4171 #if 0
4172 /* Test if the character before D and the one at D differ with respect
4173 to being word-constituent. */
4174 #define AT_WORD_BOUNDARY(d) \
4175 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4176 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4177 #endif
4179 /* Free everything we malloc. */
4180 #ifdef MATCH_MAY_ALLOCATE
4181 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4182 # define FREE_VARIABLES() \
4183 do { \
4184 REGEX_FREE_STACK (fail_stack.stack); \
4185 FREE_VAR (regstart); \
4186 FREE_VAR (regend); \
4187 FREE_VAR (best_regstart); \
4188 FREE_VAR (best_regend); \
4189 } while (0)
4190 #else
4191 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4192 #endif /* not MATCH_MAY_ALLOCATE */
4195 /* Optimization routines. */
4197 /* If the operation is a match against one or more chars,
4198 return a pointer to the next operation, else return NULL. */
4199 static re_char *
4200 skip_one_char (p)
4201 re_char *p;
4203 switch (SWITCH_ENUM_CAST (*p++))
4205 case anychar:
4206 break;
4208 case exactn:
4209 p += *p + 1;
4210 break;
4212 case charset_not:
4213 case charset:
4214 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4216 int mcnt;
4217 p = CHARSET_RANGE_TABLE (p - 1);
4218 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4219 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4221 else
4222 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4223 break;
4225 case syntaxspec:
4226 case notsyntaxspec:
4227 #ifdef emacs
4228 case categoryspec:
4229 case notcategoryspec:
4230 #endif /* emacs */
4231 p++;
4232 break;
4234 default:
4235 p = NULL;
4237 return p;
4241 /* Jump over non-matching operations. */
4242 static unsigned char *
4243 skip_noops (p, pend)
4244 unsigned char *p, *pend;
4246 int mcnt;
4247 while (p < pend)
4249 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4251 case start_memory:
4252 case stop_memory:
4253 p += 2; break;
4254 case no_op:
4255 p += 1; break;
4256 case jump:
4257 p += 1;
4258 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4259 p += mcnt;
4260 break;
4261 default:
4262 return p;
4265 assert (p == pend);
4266 return p;
4269 /* Non-zero if "p1 matches something" implies "p2 fails". */
4270 static int
4271 mutually_exclusive_p (bufp, p1, p2)
4272 struct re_pattern_buffer *bufp;
4273 unsigned char *p1, *p2;
4275 re_opcode_t op2;
4276 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4277 unsigned char *pend = bufp->buffer + bufp->used;
4279 assert (p1 >= bufp->buffer && p1 < pend
4280 && p2 >= bufp->buffer && p2 <= pend);
4282 /* Skip over open/close-group commands.
4283 If what follows this loop is a ...+ construct,
4284 look at what begins its body, since we will have to
4285 match at least one of that. */
4286 p2 = skip_noops (p2, pend);
4287 /* The same skip can be done for p1, except that this function
4288 is only used in the case where p1 is a simple match operator. */
4289 /* p1 = skip_noops (p1, pend); */
4291 assert (p1 >= bufp->buffer && p1 < pend
4292 && p2 >= bufp->buffer && p2 <= pend);
4294 op2 = p2 == pend ? succeed : *p2;
4296 switch (SWITCH_ENUM_CAST (op2))
4298 case succeed:
4299 case endbuf:
4300 /* If we're at the end of the pattern, we can change. */
4301 if (skip_one_char (p1))
4303 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4304 return 1;
4306 break;
4308 case endline:
4309 case exactn:
4311 register re_wchar_t c
4312 = (re_opcode_t) *p2 == endline ? '\n'
4313 : RE_STRING_CHAR (p2 + 2, pend - p2 - 2);
4315 if ((re_opcode_t) *p1 == exactn)
4317 if (c != RE_STRING_CHAR (p1 + 2, pend - p1 - 2))
4319 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4320 return 1;
4324 else if ((re_opcode_t) *p1 == charset
4325 || (re_opcode_t) *p1 == charset_not)
4327 int not = (re_opcode_t) *p1 == charset_not;
4329 /* Test if C is listed in charset (or charset_not)
4330 at `p1'. */
4331 if (SINGLE_BYTE_CHAR_P (c))
4333 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4334 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4335 not = !not;
4337 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4338 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4340 /* `not' is equal to 1 if c would match, which means
4341 that we can't change to pop_failure_jump. */
4342 if (!not)
4344 DEBUG_PRINT1 (" No match => fast loop.\n");
4345 return 1;
4348 else if ((re_opcode_t) *p1 == anychar
4349 && c == '\n')
4351 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4352 return 1;
4355 break;
4357 case charset:
4359 if ((re_opcode_t) *p1 == exactn)
4360 /* Reuse the code above. */
4361 return mutually_exclusive_p (bufp, p2, p1);
4363 /* It is hard to list up all the character in charset
4364 P2 if it includes multibyte character. Give up in
4365 such case. */
4366 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4368 /* Now, we are sure that P2 has no range table.
4369 So, for the size of bitmap in P2, `p2[1]' is
4370 enough. But P1 may have range table, so the
4371 size of bitmap table of P1 is extracted by
4372 using macro `CHARSET_BITMAP_SIZE'.
4374 Since we know that all the character listed in
4375 P2 is ASCII, it is enough to test only bitmap
4376 table of P1. */
4378 if ((re_opcode_t) *p1 == charset)
4380 int idx;
4381 /* We win if the charset inside the loop
4382 has no overlap with the one after the loop. */
4383 for (idx = 0;
4384 (idx < (int) p2[1]
4385 && idx < CHARSET_BITMAP_SIZE (p1));
4386 idx++)
4387 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4388 break;
4390 if (idx == p2[1]
4391 || idx == CHARSET_BITMAP_SIZE (p1))
4393 DEBUG_PRINT1 (" No match => fast loop.\n");
4394 return 1;
4397 else if ((re_opcode_t) *p1 == charset_not)
4399 int idx;
4400 /* We win if the charset_not inside the loop lists
4401 every character listed in the charset after. */
4402 for (idx = 0; idx < (int) p2[1]; idx++)
4403 if (! (p2[2 + idx] == 0
4404 || (idx < CHARSET_BITMAP_SIZE (p1)
4405 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4406 break;
4408 if (idx == p2[1])
4410 DEBUG_PRINT1 (" No match => fast loop.\n");
4411 return 1;
4416 break;
4418 case charset_not:
4419 switch (SWITCH_ENUM_CAST (*p1))
4421 case exactn:
4422 case charset:
4423 /* Reuse the code above. */
4424 return mutually_exclusive_p (bufp, p2, p1);
4425 case charset_not:
4426 /* When we have two charset_not, it's very unlikely that
4427 they don't overlap. The union of the two sets of excluded
4428 chars should cover all possible chars, which, as a matter of
4429 fact, is virtually impossible in multibyte buffers. */
4432 break;
4434 case wordend:
4435 case notsyntaxspec:
4436 return ((re_opcode_t) *p1 == syntaxspec
4437 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4439 case wordbeg:
4440 case syntaxspec:
4441 return ((re_opcode_t) *p1 == notsyntaxspec
4442 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4444 case wordbound:
4445 return (((re_opcode_t) *p1 == notsyntaxspec
4446 || (re_opcode_t) *p1 == syntaxspec)
4447 && p1[1] == Sword);
4449 #ifdef emacs
4450 case categoryspec:
4451 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4452 case notcategoryspec:
4453 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4454 #endif /* emacs */
4456 default:
4460 /* Safe default. */
4461 return 0;
4465 /* Matching routines. */
4467 #ifndef emacs /* Emacs never uses this. */
4468 /* re_match is like re_match_2 except it takes only a single string. */
4471 re_match (bufp, string, size, pos, regs)
4472 struct re_pattern_buffer *bufp;
4473 const char *string;
4474 int size, pos;
4475 struct re_registers *regs;
4477 int result = re_match_2_internal (bufp, NULL, 0, (re_char*) string, size,
4478 pos, regs, size);
4479 # if defined C_ALLOCA && !defined REGEX_MALLOC
4480 alloca (0);
4481 # endif
4482 return result;
4484 WEAK_ALIAS (__re_match, re_match)
4485 #endif /* not emacs */
4487 #ifdef emacs
4488 /* In Emacs, this is the string or buffer in which we
4489 are matching. It is used for looking up syntax properties. */
4490 Lisp_Object re_match_object;
4491 #endif
4493 /* re_match_2 matches the compiled pattern in BUFP against the
4494 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4495 and SIZE2, respectively). We start matching at POS, and stop
4496 matching at STOP.
4498 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4499 store offsets for the substring each group matched in REGS. See the
4500 documentation for exactly how many groups we fill.
4502 We return -1 if no match, -2 if an internal error (such as the
4503 failure stack overflowing). Otherwise, we return the length of the
4504 matched substring. */
4507 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4508 struct re_pattern_buffer *bufp;
4509 const char *string1, *string2;
4510 int size1, size2;
4511 int pos;
4512 struct re_registers *regs;
4513 int stop;
4515 int result;
4517 #ifdef emacs
4518 int charpos;
4519 gl_state.object = re_match_object;
4520 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4521 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4522 #endif
4524 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4525 (re_char*) string2, size2,
4526 pos, regs, stop);
4527 #if defined C_ALLOCA && !defined REGEX_MALLOC
4528 alloca (0);
4529 #endif
4530 return result;
4532 WEAK_ALIAS (__re_match_2, re_match_2)
4534 /* This is a separate function so that we can force an alloca cleanup
4535 afterwards. */
4536 static int
4537 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4538 struct re_pattern_buffer *bufp;
4539 re_char *string1, *string2;
4540 int size1, size2;
4541 int pos;
4542 struct re_registers *regs;
4543 int stop;
4545 /* General temporaries. */
4546 int mcnt;
4547 size_t reg;
4548 boolean not;
4550 /* Just past the end of the corresponding string. */
4551 re_char *end1, *end2;
4553 /* Pointers into string1 and string2, just past the last characters in
4554 each to consider matching. */
4555 re_char *end_match_1, *end_match_2;
4557 /* Where we are in the data, and the end of the current string. */
4558 re_char *d, *dend;
4560 /* Used sometimes to remember where we were before starting matching
4561 an operator so that we can go back in case of failure. This "atomic"
4562 behavior of matching opcodes is indispensable to the correctness
4563 of the on_failure_keep_string_jump optimization. */
4564 re_char *dfail;
4566 /* Where we are in the pattern, and the end of the pattern. */
4567 re_char *p = bufp->buffer;
4568 re_char *pend = p + bufp->used;
4570 /* We use this to map every character in the string. */
4571 RE_TRANSLATE_TYPE translate = bufp->translate;
4573 /* Nonzero if we have to concern multibyte character. */
4574 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4576 /* Failure point stack. Each place that can handle a failure further
4577 down the line pushes a failure point on this stack. It consists of
4578 regstart, and regend for all registers corresponding to
4579 the subexpressions we're currently inside, plus the number of such
4580 registers, and, finally, two char *'s. The first char * is where
4581 to resume scanning the pattern; the second one is where to resume
4582 scanning the strings. */
4583 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4584 fail_stack_type fail_stack;
4585 #endif
4586 #ifdef DEBUG
4587 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4588 #endif
4590 #if defined REL_ALLOC && defined REGEX_MALLOC
4591 /* This holds the pointer to the failure stack, when
4592 it is allocated relocatably. */
4593 fail_stack_elt_t *failure_stack_ptr;
4594 #endif
4596 /* We fill all the registers internally, independent of what we
4597 return, for use in backreferences. The number here includes
4598 an element for register zero. */
4599 size_t num_regs = bufp->re_nsub + 1;
4601 /* Information on the contents of registers. These are pointers into
4602 the input strings; they record just what was matched (on this
4603 attempt) by a subexpression part of the pattern, that is, the
4604 regnum-th regstart pointer points to where in the pattern we began
4605 matching and the regnum-th regend points to right after where we
4606 stopped matching the regnum-th subexpression. (The zeroth register
4607 keeps track of what the whole pattern matches.) */
4608 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4609 re_char **regstart, **regend;
4610 #endif
4612 /* The following record the register info as found in the above
4613 variables when we find a match better than any we've seen before.
4614 This happens as we backtrack through the failure points, which in
4615 turn happens only if we have not yet matched the entire string. */
4616 unsigned best_regs_set = false;
4617 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4618 re_char **best_regstart, **best_regend;
4619 #endif
4621 /* Logically, this is `best_regend[0]'. But we don't want to have to
4622 allocate space for that if we're not allocating space for anything
4623 else (see below). Also, we never need info about register 0 for
4624 any of the other register vectors, and it seems rather a kludge to
4625 treat `best_regend' differently than the rest. So we keep track of
4626 the end of the best match so far in a separate variable. We
4627 initialize this to NULL so that when we backtrack the first time
4628 and need to test it, it's not garbage. */
4629 re_char *match_end = NULL;
4631 #ifdef DEBUG
4632 /* Counts the total number of registers pushed. */
4633 unsigned num_regs_pushed = 0;
4634 #endif
4636 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4638 INIT_FAIL_STACK ();
4640 #ifdef MATCH_MAY_ALLOCATE
4641 /* Do not bother to initialize all the register variables if there are
4642 no groups in the pattern, as it takes a fair amount of time. If
4643 there are groups, we include space for register 0 (the whole
4644 pattern), even though we never use it, since it simplifies the
4645 array indexing. We should fix this. */
4646 if (bufp->re_nsub)
4648 regstart = REGEX_TALLOC (num_regs, re_char *);
4649 regend = REGEX_TALLOC (num_regs, re_char *);
4650 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4651 best_regend = REGEX_TALLOC (num_regs, re_char *);
4653 if (!(regstart && regend && best_regstart && best_regend))
4655 FREE_VARIABLES ();
4656 return -2;
4659 else
4661 /* We must initialize all our variables to NULL, so that
4662 `FREE_VARIABLES' doesn't try to free them. */
4663 regstart = regend = best_regstart = best_regend = NULL;
4665 #endif /* MATCH_MAY_ALLOCATE */
4667 /* The starting position is bogus. */
4668 if (pos < 0 || pos > size1 + size2)
4670 FREE_VARIABLES ();
4671 return -1;
4674 /* Initialize subexpression text positions to -1 to mark ones that no
4675 start_memory/stop_memory has been seen for. Also initialize the
4676 register information struct. */
4677 for (reg = 1; reg < num_regs; reg++)
4678 regstart[reg] = regend[reg] = NULL;
4680 /* We move `string1' into `string2' if the latter's empty -- but not if
4681 `string1' is null. */
4682 if (size2 == 0 && string1 != NULL)
4684 string2 = string1;
4685 size2 = size1;
4686 string1 = 0;
4687 size1 = 0;
4689 end1 = string1 + size1;
4690 end2 = string2 + size2;
4692 /* `p' scans through the pattern as `d' scans through the data.
4693 `dend' is the end of the input string that `d' points within. `d'
4694 is advanced into the following input string whenever necessary, but
4695 this happens before fetching; therefore, at the beginning of the
4696 loop, `d' can be pointing at the end of a string, but it cannot
4697 equal `string2'. */
4698 if (pos >= size1)
4700 /* Only match within string2. */
4701 d = string2 + pos - size1;
4702 dend = end_match_2 = string2 + stop - size1;
4703 end_match_1 = end1; /* Just to give it a value. */
4705 else
4707 if (stop < size1)
4709 /* Only match within string1. */
4710 end_match_1 = string1 + stop;
4711 /* BEWARE!
4712 When we reach end_match_1, PREFETCH normally switches to string2.
4713 But in the present case, this means that just doing a PREFETCH
4714 makes us jump from `stop' to `gap' within the string.
4715 What we really want here is for the search to stop as
4716 soon as we hit end_match_1. That's why we set end_match_2
4717 to end_match_1 (since PREFETCH fails as soon as we hit
4718 end_match_2). */
4719 end_match_2 = end_match_1;
4721 else
4722 { /* It's important to use this code when stop == size so that
4723 moving `d' from end1 to string2 will not prevent the d == dend
4724 check from catching the end of string. */
4725 end_match_1 = end1;
4726 end_match_2 = string2 + stop - size1;
4728 d = string1 + pos;
4729 dend = end_match_1;
4732 DEBUG_PRINT1 ("The compiled pattern is: ");
4733 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4734 DEBUG_PRINT1 ("The string to match is: `");
4735 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4736 DEBUG_PRINT1 ("'\n");
4738 /* This loops over pattern commands. It exits by returning from the
4739 function if the match is complete, or it drops through if the match
4740 fails at this starting point in the input data. */
4741 for (;;)
4743 DEBUG_PRINT2 ("\n%p: ", p);
4745 if (p == pend)
4746 { /* End of pattern means we might have succeeded. */
4747 DEBUG_PRINT1 ("end of pattern ... ");
4749 /* If we haven't matched the entire string, and we want the
4750 longest match, try backtracking. */
4751 if (d != end_match_2)
4753 /* 1 if this match ends in the same string (string1 or string2)
4754 as the best previous match. */
4755 boolean same_str_p = (FIRST_STRING_P (match_end)
4756 == FIRST_STRING_P (d));
4757 /* 1 if this match is the best seen so far. */
4758 boolean best_match_p;
4760 /* AIX compiler got confused when this was combined
4761 with the previous declaration. */
4762 if (same_str_p)
4763 best_match_p = d > match_end;
4764 else
4765 best_match_p = !FIRST_STRING_P (d);
4767 DEBUG_PRINT1 ("backtracking.\n");
4769 if (!FAIL_STACK_EMPTY ())
4770 { /* More failure points to try. */
4772 /* If exceeds best match so far, save it. */
4773 if (!best_regs_set || best_match_p)
4775 best_regs_set = true;
4776 match_end = d;
4778 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4780 for (reg = 1; reg < num_regs; reg++)
4782 best_regstart[reg] = regstart[reg];
4783 best_regend[reg] = regend[reg];
4786 goto fail;
4789 /* If no failure points, don't restore garbage. And if
4790 last match is real best match, don't restore second
4791 best one. */
4792 else if (best_regs_set && !best_match_p)
4794 restore_best_regs:
4795 /* Restore best match. It may happen that `dend ==
4796 end_match_1' while the restored d is in string2.
4797 For example, the pattern `x.*y.*z' against the
4798 strings `x-' and `y-z-', if the two strings are
4799 not consecutive in memory. */
4800 DEBUG_PRINT1 ("Restoring best registers.\n");
4802 d = match_end;
4803 dend = ((d >= string1 && d <= end1)
4804 ? end_match_1 : end_match_2);
4806 for (reg = 1; reg < num_regs; reg++)
4808 regstart[reg] = best_regstart[reg];
4809 regend[reg] = best_regend[reg];
4812 } /* d != end_match_2 */
4814 succeed_label:
4815 DEBUG_PRINT1 ("Accepting match.\n");
4817 /* If caller wants register contents data back, do it. */
4818 if (regs && !bufp->no_sub)
4820 /* Have the register data arrays been allocated? */
4821 if (bufp->regs_allocated == REGS_UNALLOCATED)
4822 { /* No. So allocate them with malloc. We need one
4823 extra element beyond `num_regs' for the `-1' marker
4824 GNU code uses. */
4825 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4826 regs->start = TALLOC (regs->num_regs, regoff_t);
4827 regs->end = TALLOC (regs->num_regs, regoff_t);
4828 if (regs->start == NULL || regs->end == NULL)
4830 FREE_VARIABLES ();
4831 return -2;
4833 bufp->regs_allocated = REGS_REALLOCATE;
4835 else if (bufp->regs_allocated == REGS_REALLOCATE)
4836 { /* Yes. If we need more elements than were already
4837 allocated, reallocate them. If we need fewer, just
4838 leave it alone. */
4839 if (regs->num_regs < num_regs + 1)
4841 regs->num_regs = num_regs + 1;
4842 RETALLOC (regs->start, regs->num_regs, regoff_t);
4843 RETALLOC (regs->end, regs->num_regs, regoff_t);
4844 if (regs->start == NULL || regs->end == NULL)
4846 FREE_VARIABLES ();
4847 return -2;
4851 else
4853 /* These braces fend off a "empty body in an else-statement"
4854 warning under GCC when assert expands to nothing. */
4855 assert (bufp->regs_allocated == REGS_FIXED);
4858 /* Convert the pointer data in `regstart' and `regend' to
4859 indices. Register zero has to be set differently,
4860 since we haven't kept track of any info for it. */
4861 if (regs->num_regs > 0)
4863 regs->start[0] = pos;
4864 regs->end[0] = POINTER_TO_OFFSET (d);
4867 /* Go through the first `min (num_regs, regs->num_regs)'
4868 registers, since that is all we initialized. */
4869 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
4871 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
4872 regs->start[reg] = regs->end[reg] = -1;
4873 else
4875 regs->start[reg]
4876 = (regoff_t) POINTER_TO_OFFSET (regstart[reg]);
4877 regs->end[reg]
4878 = (regoff_t) POINTER_TO_OFFSET (regend[reg]);
4882 /* If the regs structure we return has more elements than
4883 were in the pattern, set the extra elements to -1. If
4884 we (re)allocated the registers, this is the case,
4885 because we always allocate enough to have at least one
4886 -1 at the end. */
4887 for (reg = num_regs; reg < regs->num_regs; reg++)
4888 regs->start[reg] = regs->end[reg] = -1;
4889 } /* regs && !bufp->no_sub */
4891 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4892 nfailure_points_pushed, nfailure_points_popped,
4893 nfailure_points_pushed - nfailure_points_popped);
4894 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4896 mcnt = POINTER_TO_OFFSET (d) - pos;
4898 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4900 FREE_VARIABLES ();
4901 return mcnt;
4904 /* Otherwise match next pattern command. */
4905 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4907 /* Ignore these. Used to ignore the n of succeed_n's which
4908 currently have n == 0. */
4909 case no_op:
4910 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4911 break;
4913 case succeed:
4914 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4915 goto succeed_label;
4917 /* Match the next n pattern characters exactly. The following
4918 byte in the pattern defines n, and the n bytes after that
4919 are the characters to match. */
4920 case exactn:
4921 mcnt = *p++;
4922 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4924 /* Remember the start point to rollback upon failure. */
4925 dfail = d;
4927 /* This is written out as an if-else so we don't waste time
4928 testing `translate' inside the loop. */
4929 if (RE_TRANSLATE_P (translate))
4931 if (multibyte)
4934 int pat_charlen, buf_charlen;
4935 unsigned int pat_ch, buf_ch;
4937 PREFETCH ();
4938 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
4939 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4941 if (RE_TRANSLATE (translate, buf_ch)
4942 != pat_ch)
4944 d = dfail;
4945 goto fail;
4948 p += pat_charlen;
4949 d += buf_charlen;
4950 mcnt -= pat_charlen;
4952 while (mcnt > 0);
4953 else
4956 PREFETCH ();
4957 if (RE_TRANSLATE (translate, *d) != *p++)
4959 d = dfail;
4960 goto fail;
4962 d++;
4964 while (--mcnt);
4966 else
4970 PREFETCH ();
4971 if (*d++ != *p++)
4973 d = dfail;
4974 goto fail;
4977 while (--mcnt);
4979 break;
4982 /* Match any character except possibly a newline or a null. */
4983 case anychar:
4985 int buf_charlen;
4986 re_wchar_t buf_ch;
4988 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4990 PREFETCH ();
4991 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4992 buf_ch = TRANSLATE (buf_ch);
4994 if ((!(bufp->syntax & RE_DOT_NEWLINE)
4995 && buf_ch == '\n')
4996 || ((bufp->syntax & RE_DOT_NOT_NULL)
4997 && buf_ch == '\000'))
4998 goto fail;
5000 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
5001 d += buf_charlen;
5003 break;
5006 case charset:
5007 case charset_not:
5009 register unsigned int c;
5010 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5011 int len;
5013 /* Start of actual range_table, or end of bitmap if there is no
5014 range table. */
5015 re_char *range_table;
5017 /* Nonzero if there is a range table. */
5018 int range_table_exists;
5020 /* Number of ranges of range table. This is not included
5021 in the initial byte-length of the command. */
5022 int count = 0;
5024 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5026 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5028 if (range_table_exists)
5030 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5031 EXTRACT_NUMBER_AND_INCR (count, range_table);
5034 PREFETCH ();
5035 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5036 c = TRANSLATE (c); /* The character to match. */
5038 if (SINGLE_BYTE_CHAR_P (c))
5039 { /* Lookup bitmap. */
5040 /* Cast to `unsigned' instead of `unsigned char' in
5041 case the bit list is a full 32 bytes long. */
5042 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5043 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5044 not = !not;
5046 #ifdef emacs
5047 else if (range_table_exists)
5049 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5051 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5052 | (class_bits & BIT_MULTIBYTE)
5053 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5054 | (class_bits & BIT_SPACE && ISSPACE (c))
5055 | (class_bits & BIT_UPPER && ISUPPER (c))
5056 | (class_bits & BIT_WORD && ISWORD (c)))
5057 not = !not;
5058 else
5059 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5061 #endif /* emacs */
5063 if (range_table_exists)
5064 p = CHARSET_RANGE_TABLE_END (range_table, count);
5065 else
5066 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5068 if (!not) goto fail;
5070 d += len;
5071 break;
5075 /* The beginning of a group is represented by start_memory.
5076 The argument is the register number. The text
5077 matched within the group is recorded (in the internal
5078 registers data structure) under the register number. */
5079 case start_memory:
5080 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5082 /* In case we need to undo this operation (via backtracking). */
5083 PUSH_FAILURE_REG ((unsigned int)*p);
5085 regstart[*p] = d;
5086 regend[*p] = NULL; /* probably unnecessary. -sm */
5087 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5089 /* Move past the register number and inner group count. */
5090 p += 1;
5091 break;
5094 /* The stop_memory opcode represents the end of a group. Its
5095 argument is the same as start_memory's: the register number. */
5096 case stop_memory:
5097 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5099 assert (!REG_UNSET (regstart[*p]));
5100 /* Strictly speaking, there should be code such as:
5102 assert (REG_UNSET (regend[*p]));
5103 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5105 But the only info to be pushed is regend[*p] and it is known to
5106 be UNSET, so there really isn't anything to push.
5107 Not pushing anything, on the other hand deprives us from the
5108 guarantee that regend[*p] is UNSET since undoing this operation
5109 will not reset its value properly. This is not important since
5110 the value will only be read on the next start_memory or at
5111 the very end and both events can only happen if this stop_memory
5112 is *not* undone. */
5114 regend[*p] = d;
5115 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5117 /* Move past the register number and the inner group count. */
5118 p += 1;
5119 break;
5122 /* \<digit> has been turned into a `duplicate' command which is
5123 followed by the numeric value of <digit> as the register number. */
5124 case duplicate:
5126 register re_char *d2, *dend2;
5127 int regno = *p++; /* Get which register to match against. */
5128 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5130 /* Can't back reference a group which we've never matched. */
5131 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5132 goto fail;
5134 /* Where in input to try to start matching. */
5135 d2 = regstart[regno];
5137 /* Remember the start point to rollback upon failure. */
5138 dfail = d;
5140 /* Where to stop matching; if both the place to start and
5141 the place to stop matching are in the same string, then
5142 set to the place to stop, otherwise, for now have to use
5143 the end of the first string. */
5145 dend2 = ((FIRST_STRING_P (regstart[regno])
5146 == FIRST_STRING_P (regend[regno]))
5147 ? regend[regno] : end_match_1);
5148 for (;;)
5150 /* If necessary, advance to next segment in register
5151 contents. */
5152 while (d2 == dend2)
5154 if (dend2 == end_match_2) break;
5155 if (dend2 == regend[regno]) break;
5157 /* End of string1 => advance to string2. */
5158 d2 = string2;
5159 dend2 = regend[regno];
5161 /* At end of register contents => success */
5162 if (d2 == dend2) break;
5164 /* If necessary, advance to next segment in data. */
5165 PREFETCH ();
5167 /* How many characters left in this segment to match. */
5168 mcnt = dend - d;
5170 /* Want how many consecutive characters we can match in
5171 one shot, so, if necessary, adjust the count. */
5172 if (mcnt > dend2 - d2)
5173 mcnt = dend2 - d2;
5175 /* Compare that many; failure if mismatch, else move
5176 past them. */
5177 if (RE_TRANSLATE_P (translate)
5178 ? bcmp_translate (d, d2, mcnt, translate, multibyte)
5179 : memcmp (d, d2, mcnt))
5181 d = dfail;
5182 goto fail;
5184 d += mcnt, d2 += mcnt;
5187 break;
5190 /* begline matches the empty string at the beginning of the string
5191 (unless `not_bol' is set in `bufp'), and after newlines. */
5192 case begline:
5193 DEBUG_PRINT1 ("EXECUTING begline.\n");
5195 if (AT_STRINGS_BEG (d))
5197 if (!bufp->not_bol) break;
5199 else
5201 unsigned char c;
5202 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5203 if (c == '\n')
5204 break;
5206 /* In all other cases, we fail. */
5207 goto fail;
5210 /* endline is the dual of begline. */
5211 case endline:
5212 DEBUG_PRINT1 ("EXECUTING endline.\n");
5214 if (AT_STRINGS_END (d))
5216 if (!bufp->not_eol) break;
5218 else
5220 PREFETCH_NOLIMIT ();
5221 if (*d == '\n')
5222 break;
5224 goto fail;
5227 /* Match at the very beginning of the data. */
5228 case begbuf:
5229 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5230 if (AT_STRINGS_BEG (d))
5231 break;
5232 goto fail;
5235 /* Match at the very end of the data. */
5236 case endbuf:
5237 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5238 if (AT_STRINGS_END (d))
5239 break;
5240 goto fail;
5243 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5244 pushes NULL as the value for the string on the stack. Then
5245 `POP_FAILURE_POINT' will keep the current value for the
5246 string, instead of restoring it. To see why, consider
5247 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5248 then the . fails against the \n. But the next thing we want
5249 to do is match the \n against the \n; if we restored the
5250 string value, we would be back at the foo.
5252 Because this is used only in specific cases, we don't need to
5253 check all the things that `on_failure_jump' does, to make
5254 sure the right things get saved on the stack. Hence we don't
5255 share its code. The only reason to push anything on the
5256 stack at all is that otherwise we would have to change
5257 `anychar's code to do something besides goto fail in this
5258 case; that seems worse than this. */
5259 case on_failure_keep_string_jump:
5260 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5261 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5262 mcnt, p + mcnt);
5264 PUSH_FAILURE_POINT (p - 3, NULL);
5265 break;
5267 /* A nasty loop is introduced by the non-greedy *? and +?.
5268 With such loops, the stack only ever contains one failure point
5269 at a time, so that a plain on_failure_jump_loop kind of
5270 cycle detection cannot work. Worse yet, such a detection
5271 can not only fail to detect a cycle, but it can also wrongly
5272 detect a cycle (between different instantiations of the same
5273 loop.
5274 So the method used for those nasty loops is a little different:
5275 We use a special cycle-detection-stack-frame which is pushed
5276 when the on_failure_jump_nastyloop failure-point is *popped*.
5277 This special frame thus marks the beginning of one iteration
5278 through the loop and we can hence easily check right here
5279 whether something matched between the beginning and the end of
5280 the loop. */
5281 case on_failure_jump_nastyloop:
5282 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5283 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5284 mcnt, p + mcnt);
5286 assert ((re_opcode_t)p[-4] == no_op);
5287 CHECK_INFINITE_LOOP (p - 4, d);
5288 PUSH_FAILURE_POINT (p - 3, d);
5289 break;
5292 /* Simple loop detecting on_failure_jump: just check on the
5293 failure stack if the same spot was already hit earlier. */
5294 case on_failure_jump_loop:
5295 on_failure:
5296 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5297 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5298 mcnt, p + mcnt);
5300 CHECK_INFINITE_LOOP (p - 3, d);
5301 PUSH_FAILURE_POINT (p - 3, d);
5302 break;
5305 /* Uses of on_failure_jump:
5307 Each alternative starts with an on_failure_jump that points
5308 to the beginning of the next alternative. Each alternative
5309 except the last ends with a jump that in effect jumps past
5310 the rest of the alternatives. (They really jump to the
5311 ending jump of the following alternative, because tensioning
5312 these jumps is a hassle.)
5314 Repeats start with an on_failure_jump that points past both
5315 the repetition text and either the following jump or
5316 pop_failure_jump back to this on_failure_jump. */
5317 case on_failure_jump:
5318 IMMEDIATE_QUIT_CHECK;
5319 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5320 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5321 mcnt, p + mcnt);
5323 PUSH_FAILURE_POINT (p -3, d);
5324 break;
5326 /* This operation is used for greedy *.
5327 Compare the beginning of the repeat with what in the
5328 pattern follows its end. If we can establish that there
5329 is nothing that they would both match, i.e., that we
5330 would have to backtrack because of (as in, e.g., `a*a')
5331 then we can use a non-backtracking loop based on
5332 on_failure_keep_string_jump instead of on_failure_jump. */
5333 case on_failure_jump_smart:
5334 IMMEDIATE_QUIT_CHECK;
5335 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5336 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5337 mcnt, p + mcnt);
5339 re_char *p1 = p; /* Next operation. */
5340 /* Here, we discard `const', making re_match non-reentrant. */
5341 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5342 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5344 p -= 3; /* Reset so that we will re-execute the
5345 instruction once it's been changed. */
5347 EXTRACT_NUMBER (mcnt, p2 - 2);
5349 /* Ensure this is a indeed the trivial kind of loop
5350 we are expecting. */
5351 assert (skip_one_char (p1) == p2 - 3);
5352 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5353 DEBUG_STATEMENT (debug += 2);
5354 if (mutually_exclusive_p (bufp, p1, p2))
5356 /* Use a fast `on_failure_keep_string_jump' loop. */
5357 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5358 *p3 = (unsigned char) on_failure_keep_string_jump;
5359 STORE_NUMBER (p2 - 2, mcnt + 3);
5361 else
5363 /* Default to a safe `on_failure_jump' loop. */
5364 DEBUG_PRINT1 (" smart default => slow loop.\n");
5365 *p3 = (unsigned char) on_failure_jump;
5367 DEBUG_STATEMENT (debug -= 2);
5369 break;
5371 /* Unconditionally jump (without popping any failure points). */
5372 case jump:
5373 unconditional_jump:
5374 IMMEDIATE_QUIT_CHECK;
5375 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5376 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5377 p += mcnt; /* Do the jump. */
5378 DEBUG_PRINT2 ("(to %p).\n", p);
5379 break;
5382 /* Have to succeed matching what follows at least n times.
5383 After that, handle like `on_failure_jump'. */
5384 case succeed_n:
5385 /* Signedness doesn't matter since we only compare MCNT to 0. */
5386 EXTRACT_NUMBER (mcnt, p + 2);
5387 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5389 /* Originally, mcnt is how many times we HAVE to succeed. */
5390 if (mcnt != 0)
5392 /* Here, we discard `const', making re_match non-reentrant. */
5393 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5394 mcnt--;
5395 p += 4;
5396 PUSH_NUMBER (p2, mcnt);
5398 else
5399 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5400 goto on_failure;
5401 break;
5403 case jump_n:
5404 /* Signedness doesn't matter since we only compare MCNT to 0. */
5405 EXTRACT_NUMBER (mcnt, p + 2);
5406 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5408 /* Originally, this is how many times we CAN jump. */
5409 if (mcnt != 0)
5411 /* Here, we discard `const', making re_match non-reentrant. */
5412 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5413 mcnt--;
5414 PUSH_NUMBER (p2, mcnt);
5415 goto unconditional_jump;
5417 /* If don't have to jump any more, skip over the rest of command. */
5418 else
5419 p += 4;
5420 break;
5422 case set_number_at:
5424 unsigned char *p2; /* Location of the counter. */
5425 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5427 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5428 /* Here, we discard `const', making re_match non-reentrant. */
5429 p2 = (unsigned char*) p + mcnt;
5430 /* Signedness doesn't matter since we only copy MCNT's bits . */
5431 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5432 DEBUG_PRINT3 (" Setting %p to %d.\n", p2, mcnt);
5433 PUSH_NUMBER (p2, mcnt);
5434 break;
5437 case wordbound:
5438 case notwordbound:
5439 not = (re_opcode_t) *(p - 1) == notwordbound;
5440 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5442 /* We SUCCEED (or FAIL) in one of the following cases: */
5444 /* Case 1: D is at the beginning or the end of string. */
5445 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5446 not = !not;
5447 else
5449 /* C1 is the character before D, S1 is the syntax of C1, C2
5450 is the character at D, and S2 is the syntax of C2. */
5451 re_wchar_t c1, c2;
5452 int s1, s2;
5453 #ifdef emacs
5454 int offset = PTR_TO_OFFSET (d - 1);
5455 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5456 UPDATE_SYNTAX_TABLE (charpos);
5457 #endif
5458 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5459 s1 = SYNTAX (c1);
5460 #ifdef emacs
5461 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5462 #endif
5463 PREFETCH_NOLIMIT ();
5464 c2 = RE_STRING_CHAR (d, dend - d);
5465 s2 = SYNTAX (c2);
5467 if (/* Case 2: Only one of S1 and S2 is Sword. */
5468 ((s1 == Sword) != (s2 == Sword))
5469 /* Case 3: Both of S1 and S2 are Sword, and macro
5470 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5471 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5472 not = !not;
5474 if (not)
5475 break;
5476 else
5477 goto fail;
5479 case wordbeg:
5480 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5482 /* We FAIL in one of the following cases: */
5484 /* Case 1: D is at the end of string. */
5485 if (AT_STRINGS_END (d))
5486 goto fail;
5487 else
5489 /* C1 is the character before D, S1 is the syntax of C1, C2
5490 is the character at D, and S2 is the syntax of C2. */
5491 re_wchar_t c1, c2;
5492 int s1, s2;
5493 #ifdef emacs
5494 int offset = PTR_TO_OFFSET (d);
5495 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5496 UPDATE_SYNTAX_TABLE (charpos);
5497 #endif
5498 PREFETCH ();
5499 c2 = RE_STRING_CHAR (d, dend - d);
5500 s2 = SYNTAX (c2);
5502 /* Case 2: S2 is not Sword. */
5503 if (s2 != Sword)
5504 goto fail;
5506 /* Case 3: D is not at the beginning of string ... */
5507 if (!AT_STRINGS_BEG (d))
5509 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5510 #ifdef emacs
5511 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5512 #endif
5513 s1 = SYNTAX (c1);
5515 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5516 returns 0. */
5517 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5518 goto fail;
5521 break;
5523 case wordend:
5524 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5526 /* We FAIL in one of the following cases: */
5528 /* Case 1: D is at the beginning of string. */
5529 if (AT_STRINGS_BEG (d))
5530 goto fail;
5531 else
5533 /* C1 is the character before D, S1 is the syntax of C1, C2
5534 is the character at D, and S2 is the syntax of C2. */
5535 re_wchar_t c1, c2;
5536 int s1, s2;
5537 #ifdef emacs
5538 int offset = PTR_TO_OFFSET (d) - 1;
5539 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5540 UPDATE_SYNTAX_TABLE (charpos);
5541 #endif
5542 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5543 s1 = SYNTAX (c1);
5545 /* Case 2: S1 is not Sword. */
5546 if (s1 != Sword)
5547 goto fail;
5549 /* Case 3: D is not at the end of string ... */
5550 if (!AT_STRINGS_END (d))
5552 PREFETCH_NOLIMIT ();
5553 c2 = RE_STRING_CHAR (d, dend - d);
5554 #ifdef emacs
5555 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5556 #endif
5557 s2 = SYNTAX (c2);
5559 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5560 returns 0. */
5561 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5562 goto fail;
5565 break;
5567 case syntaxspec:
5568 case notsyntaxspec:
5569 not = (re_opcode_t) *(p - 1) == notsyntaxspec;
5570 mcnt = *p++;
5571 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
5572 PREFETCH ();
5573 #ifdef emacs
5575 int offset = PTR_TO_OFFSET (d);
5576 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5577 UPDATE_SYNTAX_TABLE (pos1);
5579 #endif
5581 int len;
5582 re_wchar_t c;
5584 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5586 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
5587 goto fail;
5588 d += len;
5590 break;
5592 #ifdef emacs
5593 case before_dot:
5594 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5595 if (PTR_BYTE_POS (d) >= PT_BYTE)
5596 goto fail;
5597 break;
5599 case at_dot:
5600 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5601 if (PTR_BYTE_POS (d) != PT_BYTE)
5602 goto fail;
5603 break;
5605 case after_dot:
5606 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5607 if (PTR_BYTE_POS (d) <= PT_BYTE)
5608 goto fail;
5609 break;
5611 case categoryspec:
5612 case notcategoryspec:
5613 not = (re_opcode_t) *(p - 1) == notcategoryspec;
5614 mcnt = *p++;
5615 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt);
5616 PREFETCH ();
5618 int len;
5619 re_wchar_t c;
5621 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5623 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
5624 goto fail;
5625 d += len;
5627 break;
5629 #endif /* emacs */
5631 default:
5632 abort ();
5634 continue; /* Successfully executed one pattern command; keep going. */
5637 /* We goto here if a matching operation fails. */
5638 fail:
5639 IMMEDIATE_QUIT_CHECK;
5640 if (!FAIL_STACK_EMPTY ())
5642 re_char *str, *pat;
5643 /* A restart point is known. Restore to that state. */
5644 DEBUG_PRINT1 ("\nFAIL:\n");
5645 POP_FAILURE_POINT (str, pat);
5646 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
5648 case on_failure_keep_string_jump:
5649 assert (str == NULL);
5650 goto continue_failure_jump;
5652 case on_failure_jump_nastyloop:
5653 assert ((re_opcode_t)pat[-2] == no_op);
5654 PUSH_FAILURE_POINT (pat - 2, str);
5655 /* Fallthrough */
5657 case on_failure_jump_loop:
5658 case on_failure_jump:
5659 case succeed_n:
5660 d = str;
5661 continue_failure_jump:
5662 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
5663 p = pat + mcnt;
5664 break;
5666 case no_op:
5667 /* A special frame used for nastyloops. */
5668 goto fail;
5670 default:
5671 abort();
5674 assert (p >= bufp->buffer && p <= pend);
5676 if (d >= string1 && d <= end1)
5677 dend = end_match_1;
5679 else
5680 break; /* Matching at this starting point really fails. */
5681 } /* for (;;) */
5683 if (best_regs_set)
5684 goto restore_best_regs;
5686 FREE_VARIABLES ();
5688 return -1; /* Failure to match. */
5689 } /* re_match_2 */
5691 /* Subroutine definitions for re_match_2. */
5693 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5694 bytes; nonzero otherwise. */
5696 static int
5697 bcmp_translate (s1, s2, len, translate, multibyte)
5698 re_char *s1, *s2;
5699 register int len;
5700 RE_TRANSLATE_TYPE translate;
5701 const int multibyte;
5703 register re_char *p1 = s1, *p2 = s2;
5704 re_char *p1_end = s1 + len;
5705 re_char *p2_end = s2 + len;
5707 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5708 different lengths, but relying on a single `len' would break this. -sm */
5709 while (p1 < p1_end && p2 < p2_end)
5711 int p1_charlen, p2_charlen;
5712 re_wchar_t p1_ch, p2_ch;
5714 p1_ch = RE_STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5715 p2_ch = RE_STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5717 if (RE_TRANSLATE (translate, p1_ch)
5718 != RE_TRANSLATE (translate, p2_ch))
5719 return 1;
5721 p1 += p1_charlen, p2 += p2_charlen;
5724 if (p1 != p1_end || p2 != p2_end)
5725 return 1;
5727 return 0;
5730 /* Entry points for GNU code. */
5732 /* re_compile_pattern is the GNU regular expression compiler: it
5733 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5734 Returns 0 if the pattern was valid, otherwise an error string.
5736 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5737 are set in BUFP on entry.
5739 We call regex_compile to do the actual compilation. */
5741 const char *
5742 re_compile_pattern (pattern, length, bufp)
5743 const char *pattern;
5744 size_t length;
5745 struct re_pattern_buffer *bufp;
5747 reg_errcode_t ret;
5749 /* GNU code is written to assume at least RE_NREGS registers will be set
5750 (and at least one extra will be -1). */
5751 bufp->regs_allocated = REGS_UNALLOCATED;
5753 /* And GNU code determines whether or not to get register information
5754 by passing null for the REGS argument to re_match, etc., not by
5755 setting no_sub. */
5756 bufp->no_sub = 0;
5758 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
5760 if (!ret)
5761 return NULL;
5762 return gettext (re_error_msgid[(int) ret]);
5764 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
5766 /* Entry points compatible with 4.2 BSD regex library. We don't define
5767 them unless specifically requested. */
5769 #if defined _REGEX_RE_COMP || defined _LIBC
5771 /* BSD has one and only one pattern buffer. */
5772 static struct re_pattern_buffer re_comp_buf;
5774 char *
5775 # ifdef _LIBC
5776 /* Make these definitions weak in libc, so POSIX programs can redefine
5777 these names if they don't use our functions, and still use
5778 regcomp/regexec below without link errors. */
5779 weak_function
5780 # endif
5781 re_comp (s)
5782 const char *s;
5784 reg_errcode_t ret;
5786 if (!s)
5788 if (!re_comp_buf.buffer)
5789 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5790 return (char *) gettext ("No previous regular expression");
5791 return 0;
5794 if (!re_comp_buf.buffer)
5796 re_comp_buf.buffer = (unsigned char *) malloc (200);
5797 if (re_comp_buf.buffer == NULL)
5798 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5799 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
5800 re_comp_buf.allocated = 200;
5802 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5803 if (re_comp_buf.fastmap == NULL)
5804 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5805 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
5808 /* Since `re_exec' always passes NULL for the `regs' argument, we
5809 don't need to initialize the pattern buffer fields which affect it. */
5811 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5813 if (!ret)
5814 return NULL;
5816 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5817 return (char *) gettext (re_error_msgid[(int) ret]);
5822 # ifdef _LIBC
5823 weak_function
5824 # endif
5825 re_exec (s)
5826 const char *s;
5828 const int len = strlen (s);
5829 return
5830 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5832 #endif /* _REGEX_RE_COMP */
5834 /* POSIX.2 functions. Don't define these for Emacs. */
5836 #ifndef emacs
5838 /* regcomp takes a regular expression as a string and compiles it.
5840 PREG is a regex_t *. We do not expect any fields to be initialized,
5841 since POSIX says we shouldn't. Thus, we set
5843 `buffer' to the compiled pattern;
5844 `used' to the length of the compiled pattern;
5845 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5846 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5847 RE_SYNTAX_POSIX_BASIC;
5848 `fastmap' to an allocated space for the fastmap;
5849 `fastmap_accurate' to zero;
5850 `re_nsub' to the number of subexpressions in PATTERN.
5852 PATTERN is the address of the pattern string.
5854 CFLAGS is a series of bits which affect compilation.
5856 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5857 use POSIX basic syntax.
5859 If REG_NEWLINE is set, then . and [^...] don't match newline.
5860 Also, regexec will try a match beginning after every newline.
5862 If REG_ICASE is set, then we considers upper- and lowercase
5863 versions of letters to be equivalent when matching.
5865 If REG_NOSUB is set, then when PREG is passed to regexec, that
5866 routine will report only success or failure, and nothing about the
5867 registers.
5869 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5870 the return codes and their meanings.) */
5873 regcomp (preg, pattern, cflags)
5874 regex_t *__restrict preg;
5875 const char *__restrict pattern;
5876 int cflags;
5878 reg_errcode_t ret;
5879 reg_syntax_t syntax
5880 = (cflags & REG_EXTENDED) ?
5881 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5883 /* regex_compile will allocate the space for the compiled pattern. */
5884 preg->buffer = 0;
5885 preg->allocated = 0;
5886 preg->used = 0;
5888 /* Try to allocate space for the fastmap. */
5889 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
5891 if (cflags & REG_ICASE)
5893 unsigned i;
5895 preg->translate
5896 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
5897 * sizeof (*(RE_TRANSLATE_TYPE)0));
5898 if (preg->translate == NULL)
5899 return (int) REG_ESPACE;
5901 /* Map uppercase characters to corresponding lowercase ones. */
5902 for (i = 0; i < CHAR_SET_SIZE; i++)
5903 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
5905 else
5906 preg->translate = NULL;
5908 /* If REG_NEWLINE is set, newlines are treated differently. */
5909 if (cflags & REG_NEWLINE)
5910 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5911 syntax &= ~RE_DOT_NEWLINE;
5912 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5914 else
5915 syntax |= RE_NO_NEWLINE_ANCHOR;
5917 preg->no_sub = !!(cflags & REG_NOSUB);
5919 /* POSIX says a null character in the pattern terminates it, so we
5920 can use strlen here in compiling the pattern. */
5921 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
5923 /* POSIX doesn't distinguish between an unmatched open-group and an
5924 unmatched close-group: both are REG_EPAREN. */
5925 if (ret == REG_ERPAREN)
5926 ret = REG_EPAREN;
5928 if (ret == REG_NOERROR && preg->fastmap)
5929 { /* Compute the fastmap now, since regexec cannot modify the pattern
5930 buffer. */
5931 re_compile_fastmap (preg);
5932 if (preg->can_be_null)
5933 { /* The fastmap can't be used anyway. */
5934 free (preg->fastmap);
5935 preg->fastmap = NULL;
5938 return (int) ret;
5940 WEAK_ALIAS (__regcomp, regcomp)
5943 /* regexec searches for a given pattern, specified by PREG, in the
5944 string STRING.
5946 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5947 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5948 least NMATCH elements, and we set them to the offsets of the
5949 corresponding matched substrings.
5951 EFLAGS specifies `execution flags' which affect matching: if
5952 REG_NOTBOL is set, then ^ does not match at the beginning of the
5953 string; if REG_NOTEOL is set, then $ does not match at the end.
5955 We return 0 if we find a match and REG_NOMATCH if not. */
5958 regexec (preg, string, nmatch, pmatch, eflags)
5959 const regex_t *__restrict preg;
5960 const char *__restrict string;
5961 size_t nmatch;
5962 regmatch_t pmatch[];
5963 int eflags;
5965 int ret;
5966 struct re_registers regs;
5967 regex_t private_preg;
5968 int len = strlen (string);
5969 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
5971 private_preg = *preg;
5973 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5974 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5976 /* The user has told us exactly how many registers to return
5977 information about, via `nmatch'. We have to pass that on to the
5978 matching routines. */
5979 private_preg.regs_allocated = REGS_FIXED;
5981 if (want_reg_info)
5983 regs.num_regs = nmatch;
5984 regs.start = TALLOC (nmatch * 2, regoff_t);
5985 if (regs.start == NULL)
5986 return (int) REG_NOMATCH;
5987 regs.end = regs.start + nmatch;
5990 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
5991 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
5992 was a little bit longer but still only matching the real part.
5993 This works because the `endline' will check for a '\n' and will find a
5994 '\0', correctly deciding that this is not the end of a line.
5995 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
5996 a convenient '\0' there. For all we know, the string could be preceded
5997 by '\n' which would throw things off. */
5999 /* Perform the searching operation. */
6000 ret = re_search (&private_preg, string, len,
6001 /* start: */ 0, /* range: */ len,
6002 want_reg_info ? &regs : (struct re_registers *) 0);
6004 /* Copy the register information to the POSIX structure. */
6005 if (want_reg_info)
6007 if (ret >= 0)
6009 unsigned r;
6011 for (r = 0; r < nmatch; r++)
6013 pmatch[r].rm_so = regs.start[r];
6014 pmatch[r].rm_eo = regs.end[r];
6018 /* If we needed the temporary register info, free the space now. */
6019 free (regs.start);
6022 /* We want zero return to mean success, unlike `re_search'. */
6023 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6025 WEAK_ALIAS (__regexec, regexec)
6028 /* Returns a message corresponding to an error code, ERRCODE, returned
6029 from either regcomp or regexec. We don't use PREG here. */
6031 size_t
6032 regerror (errcode, preg, errbuf, errbuf_size)
6033 int errcode;
6034 const regex_t *preg;
6035 char *errbuf;
6036 size_t errbuf_size;
6038 const char *msg;
6039 size_t msg_size;
6041 if (errcode < 0
6042 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6043 /* Only error codes returned by the rest of the code should be passed
6044 to this routine. If we are given anything else, or if other regex
6045 code generates an invalid error code, then the program has a bug.
6046 Dump core so we can fix it. */
6047 abort ();
6049 msg = gettext (re_error_msgid[errcode]);
6051 msg_size = strlen (msg) + 1; /* Includes the null. */
6053 if (errbuf_size != 0)
6055 if (msg_size > errbuf_size)
6057 strncpy (errbuf, msg, errbuf_size - 1);
6058 errbuf[errbuf_size - 1] = 0;
6060 else
6061 strcpy (errbuf, msg);
6064 return msg_size;
6066 WEAK_ALIAS (__regerror, regerror)
6069 /* Free dynamically allocated space used by PREG. */
6071 void
6072 regfree (preg)
6073 regex_t *preg;
6075 if (preg->buffer != NULL)
6076 free (preg->buffer);
6077 preg->buffer = NULL;
6079 preg->allocated = 0;
6080 preg->used = 0;
6082 if (preg->fastmap != NULL)
6083 free (preg->fastmap);
6084 preg->fastmap = NULL;
6085 preg->fastmap_accurate = 0;
6087 if (preg->translate != NULL)
6088 free (preg->translate);
6089 preg->translate = NULL;
6091 WEAK_ALIAS (__regfree, regfree)
6093 #endif /* not emacs */