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)
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,
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
40 #if defined STDC_HEADERS && !defined emacs
43 /* We need this for `regex.h', and perhaps for the Emacs include files. */
44 # include <sys/types.h>
47 /* Whether to use ISO C Amendment 1 wide char functions.
48 Those should not be used for Emacs since it uses its own. */
50 #define WIDE_CHAR_SUPPORT 1
52 #define WIDE_CHAR_SUPPORT \
53 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
56 /* For platform which support the ISO C amendement 1 functionality we
57 support user defined character classes. */
59 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
65 /* We have to keep the namespace clean. */
66 # define regfree(preg) __regfree (preg)
67 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
68 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
69 # define regerror(errcode, preg, errbuf, errbuf_size) \
70 __regerror(errcode, preg, errbuf, errbuf_size)
71 # define re_set_registers(bu, re, nu, st, en) \
72 __re_set_registers (bu, re, nu, st, en)
73 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
74 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
75 # define re_match(bufp, string, size, pos, regs) \
76 __re_match (bufp, string, size, pos, regs)
77 # define re_search(bufp, string, size, startpos, range, regs) \
78 __re_search (bufp, string, size, startpos, range, regs)
79 # define re_compile_pattern(pattern, length, bufp) \
80 __re_compile_pattern (pattern, length, bufp)
81 # define re_set_syntax(syntax) __re_set_syntax (syntax)
82 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
83 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
84 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
86 /* Make sure we call libc's function even if the user overrides them. */
87 # define btowc __btowc
88 # define iswctype __iswctype
89 # define wctype __wctype
91 # define WEAK_ALIAS(a,b) weak_alias (a, b)
93 /* We are also using some library internals. */
94 # include <locale/localeinfo.h>
95 # include <locale/elem-hash.h>
96 # include <langinfo.h>
98 # define WEAK_ALIAS(a,b)
101 /* This is for other GNU distributions with internationalized messages. */
102 #if HAVE_LIBINTL_H || defined _LIBC
103 # include <libintl.h>
105 # define gettext(msgid) (msgid)
109 /* This define is so xgettext can find the internationalizable
111 # define gettext_noop(String) String
114 /* The `emacs' switch turns on certain matching commands
115 that make sense only in Emacs. */
121 /* Make syntax table lookup grant data in gl_state. */
122 # define SYNTAX_ENTRY_VIA_PROPERTY
125 # include "charset.h"
126 # include "category.h"
131 # define malloc xmalloc
135 # define realloc xrealloc
141 /* Converts the pointer to the char to BEG-based offset from the start. */
142 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
143 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
145 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
146 # define RE_STRING_CHAR(p, s) \
147 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
148 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
149 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
151 /* Set C a (possibly multibyte) character before P. P points into a
152 string which is the virtual concatenation of STR1 (which ends at
153 END1) or STR2 (which ends at END2). */
154 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
158 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
159 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
160 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
161 c = STRING_CHAR (dtemp, (p) - dtemp); \
164 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
168 #else /* not emacs */
170 /* If we are not linking with Emacs proper,
171 we can't use the relocating allocator
172 even if config.h says that we can. */
175 # if defined STDC_HEADERS || defined _LIBC
182 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
183 If nothing else has been done, use the method below. */
184 # ifdef INHIBIT_STRING_HEADER
185 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
186 # if !defined bzero && !defined bcopy
187 # undef INHIBIT_STRING_HEADER
192 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
193 This is used in most programs--a few other programs avoid this
194 by defining INHIBIT_STRING_HEADER. */
195 # ifndef INHIBIT_STRING_HEADER
196 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
200 # define bzero(s, n) (memset (s, '\0', n), (s))
202 # define bzero(s, n) __bzero (s, n)
206 # include <strings.h>
208 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
211 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
216 /* Define the syntax stuff for \<, \>, etc. */
218 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
219 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1 };
221 # ifdef SWITCH_ENUM_BUG
222 # define SWITCH_ENUM_CAST(x) ((int)(x))
224 # define SWITCH_ENUM_CAST(x) (x)
227 /* Dummy macros for non-Emacs environments. */
228 # define BASE_LEADING_CODE_P(c) (0)
229 # define CHAR_CHARSET(c) 0
230 # define CHARSET_LEADING_CODE_BASE(c) 0
231 # define MAX_MULTIBYTE_LENGTH 1
232 # define RE_MULTIBYTE_P(x) 0
233 # define WORD_BOUNDARY_P(c1, c2) (0)
234 # define CHAR_HEAD_P(p) (1)
235 # define SINGLE_BYTE_CHAR_P(c) (1)
236 # define SAME_CHARSET_P(c1, c2) (1)
237 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
238 # define STRING_CHAR(p, s) (*(p))
239 # define RE_STRING_CHAR STRING_CHAR
240 # define CHAR_STRING(c, s) (*(s) = (c), 1)
241 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
242 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
243 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
244 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
245 # define MAKE_CHAR(charset, c1, c2) (c1)
246 #endif /* not emacs */
249 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
250 # define RE_TRANSLATE_P(TBL) (TBL)
253 /* Get the interface, including the syntax bits. */
256 /* isalpha etc. are used for the character classes. */
261 /* 1 if C is an ASCII character. */
262 # define IS_REAL_ASCII(c) ((c) < 0200)
264 /* 1 if C is a unibyte character. */
265 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
267 /* The Emacs definitions should not be directly affected by locales. */
269 /* In Emacs, these are only used for single-byte characters. */
270 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
271 # define ISCNTRL(c) ((c) < ' ')
272 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
273 || ((c) >= 'a' && (c) <= 'f') \
274 || ((c) >= 'A' && (c) <= 'F'))
276 /* This is only used for single-byte characters. */
277 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
279 /* The rest must handle multibyte characters. */
281 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
282 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
285 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
286 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
289 # define ISALNUM(c) (IS_REAL_ASCII (c) \
290 ? (((c) >= 'a' && (c) <= 'z') \
291 || ((c) >= 'A' && (c) <= 'Z') \
292 || ((c) >= '0' && (c) <= '9')) \
293 : SYNTAX (c) == Sword)
295 # define ISALPHA(c) (IS_REAL_ASCII (c) \
296 ? (((c) >= 'a' && (c) <= 'z') \
297 || ((c) >= 'A' && (c) <= 'Z')) \
298 : SYNTAX (c) == Sword)
300 # define ISLOWER(c) (LOWERCASEP (c))
302 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
303 ? ((c) > ' ' && (c) < 0177 \
304 && !(((c) >= 'a' && (c) <= 'z') \
305 || ((c) >= 'A' && (c) <= 'Z') \
306 || ((c) >= '0' && (c) <= '9'))) \
307 : SYNTAX (c) != Sword)
309 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
311 # define ISUPPER(c) (UPPERCASEP (c))
313 # define ISWORD(c) (SYNTAX (c) == Sword)
315 #else /* not emacs */
317 /* Jim Meyering writes:
319 "... Some ctype macros are valid only for character codes that
320 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
321 using /bin/cc or gcc but without giving an ansi option). So, all
322 ctype uses should be through macros like ISPRINT... If
323 STDC_HEADERS is defined, then autoconf has verified that the ctype
324 macros don't need to be guarded with references to isascii. ...
325 Defining isascii to 1 should let any compiler worth its salt
326 eliminate the && through constant folding."
327 Solaris defines some of these symbols so we must undefine them first. */
330 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
331 # define ISASCII(c) 1
333 # define ISASCII(c) isascii(c)
336 /* 1 if C is an ASCII character. */
337 # define IS_REAL_ASCII(c) ((c) < 0200)
339 /* This distinction is not meaningful, except in Emacs. */
340 # define ISUNIBYTE(c) 1
343 # define ISBLANK(c) (ISASCII (c) && isblank (c))
345 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
348 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
350 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
354 # define ISPRINT(c) (ISASCII (c) && isprint (c))
355 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
356 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
357 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
358 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
359 # define ISLOWER(c) (ISASCII (c) && islower (c))
360 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
361 # define ISSPACE(c) (ISASCII (c) && isspace (c))
362 # define ISUPPER(c) (ISASCII (c) && isupper (c))
363 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
365 # define ISWORD(c) ISALPHA(c)
368 # define TOLOWER(c) _tolower(c)
370 # define TOLOWER(c) tolower(c)
373 /* How many characters in the character set. */
374 # define CHAR_SET_SIZE 256
378 extern char *re_syntax_table
;
380 # else /* not SYNTAX_TABLE */
382 static char re_syntax_table
[CHAR_SET_SIZE
];
393 bzero (re_syntax_table
, sizeof re_syntax_table
);
395 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
397 re_syntax_table
[c
] = Sword
;
399 re_syntax_table
['_'] = Sword
;
404 # endif /* not SYNTAX_TABLE */
406 # define SYNTAX(c) re_syntax_table[(c)]
408 #endif /* not emacs */
411 # define NULL (void *)0
414 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
415 since ours (we hope) works properly with all combinations of
416 machines, compilers, `char' and `unsigned char' argument types.
417 (Per Bothner suggested the basic approach.) */
418 #undef SIGN_EXTEND_CHAR
420 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
421 #else /* not __STDC__ */
422 /* As in Harbison and Steele. */
423 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
426 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
427 use `alloca' instead of `malloc'. This is because using malloc in
428 re_search* or re_match* could cause memory leaks when C-g is used in
429 Emacs; also, malloc is slower and causes storage fragmentation. On
430 the other hand, malloc is more portable, and easier to debug.
432 Because we sometimes use alloca, some routines have to be macros,
433 not functions -- `alloca'-allocated space disappears at the end of the
434 function it is called in. */
438 # define REGEX_ALLOCATE malloc
439 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
440 # define REGEX_FREE free
442 #else /* not REGEX_MALLOC */
444 /* Emacs already defines alloca, sometimes. */
447 /* Make alloca work the best possible way. */
449 # define alloca __builtin_alloca
450 # else /* not __GNUC__ */
453 # endif /* HAVE_ALLOCA_H */
454 # endif /* not __GNUC__ */
456 # endif /* not alloca */
458 # define REGEX_ALLOCATE alloca
460 /* Assumes a `char *destination' variable. */
461 # define REGEX_REALLOCATE(source, osize, nsize) \
462 (destination = (char *) alloca (nsize), \
463 memcpy (destination, source, osize))
465 /* No need to do anything to free, after alloca. */
466 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
468 #endif /* not REGEX_MALLOC */
470 /* Define how to allocate the failure stack. */
472 #if defined REL_ALLOC && defined REGEX_MALLOC
474 # define REGEX_ALLOCATE_STACK(size) \
475 r_alloc (&failure_stack_ptr, (size))
476 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
477 r_re_alloc (&failure_stack_ptr, (nsize))
478 # define REGEX_FREE_STACK(ptr) \
479 r_alloc_free (&failure_stack_ptr)
481 #else /* not using relocating allocator */
485 # define REGEX_ALLOCATE_STACK malloc
486 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
487 # define REGEX_FREE_STACK free
489 # else /* not REGEX_MALLOC */
491 # define REGEX_ALLOCATE_STACK alloca
493 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
494 REGEX_REALLOCATE (source, osize, nsize)
495 /* No need to explicitly free anything. */
496 # define REGEX_FREE_STACK(arg) ((void)0)
498 # endif /* not REGEX_MALLOC */
499 #endif /* not using relocating allocator */
502 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
503 `string1' or just past its end. This works if PTR is NULL, which is
505 #define FIRST_STRING_P(ptr) \
506 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
508 /* (Re)Allocate N items of type T using malloc, or fail. */
509 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
510 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
511 #define RETALLOC_IF(addr, n, t) \
512 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
513 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
515 #define BYTEWIDTH 8 /* In bits. */
517 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
521 #define MAX(a, b) ((a) > (b) ? (a) : (b))
522 #define MIN(a, b) ((a) < (b) ? (a) : (b))
524 /* Type of source-pattern and string chars. */
525 typedef const unsigned char re_char
;
527 typedef char boolean
;
531 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
532 re_char
*string1
, int size1
,
533 re_char
*string2
, int size2
,
535 struct re_registers
*regs
,
538 /* These are the command codes that appear in compiled regular
539 expressions. Some opcodes are followed by argument bytes. A
540 command code can specify any interpretation whatsoever for its
541 arguments. Zero bytes may appear in the compiled regular expression. */
547 /* Succeed right away--no more backtracking. */
550 /* Followed by one byte giving n, then by n literal bytes. */
553 /* Matches any (more or less) character. */
556 /* Matches any one char belonging to specified set. First
557 following byte is number of bitmap bytes. Then come bytes
558 for a bitmap saying which chars are in. Bits in each byte
559 are ordered low-bit-first. A character is in the set if its
560 bit is 1. A character too large to have a bit in the map is
561 automatically not in the set.
563 If the length byte has the 0x80 bit set, then that stuff
564 is followed by a range table:
565 2 bytes of flags for character sets (low 8 bits, high 8 bits)
566 See RANGE_TABLE_WORK_BITS below.
567 2 bytes, the number of pairs that follow (upto 32767)
568 pairs, each 2 multibyte characters,
569 each multibyte character represented as 3 bytes. */
572 /* Same parameters as charset, but match any character that is
573 not one of those specified. */
576 /* Start remembering the text that is matched, for storing in a
577 register. Followed by one byte with the register number, in
578 the range 0 to one less than the pattern buffer's re_nsub
582 /* Stop remembering the text that is matched and store it in a
583 memory register. Followed by one byte with the register
584 number, in the range 0 to one less than `re_nsub' in the
588 /* Match a duplicate of something remembered. Followed by one
589 byte containing the register number. */
592 /* Fail unless at beginning of line. */
595 /* Fail unless at end of line. */
598 /* Succeeds if at beginning of buffer (if emacs) or at beginning
599 of string to be matched (if not). */
602 /* Analogously, for end of buffer/string. */
605 /* Followed by two byte relative address to which to jump. */
608 /* Followed by two-byte relative address of place to resume at
609 in case of failure. */
612 /* Like on_failure_jump, but pushes a placeholder instead of the
613 current string position when executed. */
614 on_failure_keep_string_jump
,
616 /* Just like `on_failure_jump', except that it checks that we
617 don't get stuck in an infinite loop (matching an empty string
619 on_failure_jump_loop
,
621 /* Just like `on_failure_jump_loop', except that it checks for
622 a different kind of loop (the kind that shows up with non-greedy
623 operators). This operation has to be immediately preceded
625 on_failure_jump_nastyloop
,
627 /* A smart `on_failure_jump' used for greedy * and + operators.
628 It analyses the loop before which it is put and if the
629 loop does not require backtracking, it changes itself to
630 `on_failure_keep_string_jump' and short-circuits the loop,
631 else it just defaults to changing itself into `on_failure_jump'.
632 It assumes that it is pointing to just past a `jump'. */
633 on_failure_jump_smart
,
635 /* Followed by two-byte relative address and two-byte number n.
636 After matching N times, jump to the address upon failure.
637 Does not work if N starts at 0: use on_failure_jump_loop
641 /* Followed by two-byte relative address, and two-byte number n.
642 Jump to the address N times, then fail. */
645 /* Set the following two-byte relative address to the
646 subsequent two-byte number. The address *includes* the two
650 wordbeg
, /* Succeeds if at word beginning. */
651 wordend
, /* Succeeds if at word end. */
653 wordbound
, /* Succeeds if at a word boundary. */
654 notwordbound
, /* Succeeds if not at a word boundary. */
656 /* Matches any character whose syntax is specified. Followed by
657 a byte which contains a syntax code, e.g., Sword. */
660 /* Matches any character whose syntax is not that specified. */
664 ,before_dot
, /* Succeeds if before point. */
665 at_dot
, /* Succeeds if at point. */
666 after_dot
, /* Succeeds if after point. */
668 /* Matches any character whose category-set contains the specified
669 category. The operator is followed by a byte which contains a
670 category code (mnemonic ASCII character). */
673 /* Matches any character whose category-set does not contain the
674 specified category. The operator is followed by a byte which
675 contains the category code (mnemonic ASCII character). */
680 /* Common operations on the compiled pattern. */
682 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
684 #define STORE_NUMBER(destination, number) \
686 (destination)[0] = (number) & 0377; \
687 (destination)[1] = (number) >> 8; \
690 /* Same as STORE_NUMBER, except increment DESTINATION to
691 the byte after where the number is stored. Therefore, DESTINATION
692 must be an lvalue. */
694 #define STORE_NUMBER_AND_INCR(destination, number) \
696 STORE_NUMBER (destination, number); \
697 (destination) += 2; \
700 /* Put into DESTINATION a number stored in two contiguous bytes starting
703 #define EXTRACT_NUMBER(destination, source) \
705 (destination) = *(source) & 0377; \
706 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
710 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
712 extract_number (dest
, source
)
716 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
717 *dest
= *source
& 0377;
721 # ifndef EXTRACT_MACROS /* To debug the macros. */
722 # undef EXTRACT_NUMBER
723 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
724 # endif /* not EXTRACT_MACROS */
728 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
729 SOURCE must be an lvalue. */
731 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
733 EXTRACT_NUMBER (destination, source); \
738 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
741 extract_number_and_incr (destination
, source
)
745 extract_number (destination
, *source
);
749 # ifndef EXTRACT_MACROS
750 # undef EXTRACT_NUMBER_AND_INCR
751 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
752 extract_number_and_incr (&dest, &src)
753 # endif /* not EXTRACT_MACROS */
757 /* Store a multibyte character in three contiguous bytes starting
758 DESTINATION, and increment DESTINATION to the byte after where the
759 character is stored. Therefore, DESTINATION must be an lvalue. */
761 #define STORE_CHARACTER_AND_INCR(destination, character) \
763 (destination)[0] = (character) & 0377; \
764 (destination)[1] = ((character) >> 8) & 0377; \
765 (destination)[2] = (character) >> 16; \
766 (destination) += 3; \
769 /* Put into DESTINATION a character stored in three contiguous bytes
770 starting at SOURCE. */
772 #define EXTRACT_CHARACTER(destination, source) \
774 (destination) = ((source)[0] \
775 | ((source)[1] << 8) \
776 | ((source)[2] << 16)); \
780 /* Macros for charset. */
782 /* Size of bitmap of charset P in bytes. P is a start of charset,
783 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
784 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
786 /* Nonzero if charset P has range table. */
787 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
789 /* Return the address of range table of charset P. But not the start
790 of table itself, but the before where the number of ranges is
791 stored. `2 +' means to skip re_opcode_t and size of bitmap,
792 and the 2 bytes of flags at the start of the range table. */
793 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
795 /* Extract the bit flags that start a range table. */
796 #define CHARSET_RANGE_TABLE_BITS(p) \
797 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
798 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
800 /* Test if C is listed in the bitmap of charset P. */
801 #define CHARSET_LOOKUP_BITMAP(p, c) \
802 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
803 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
805 /* Return the address of end of RANGE_TABLE. COUNT is number of
806 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
807 is start of range and end of range. `* 3' is size of each start
809 #define CHARSET_RANGE_TABLE_END(range_table, count) \
810 ((range_table) + (count) * 2 * 3)
812 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
813 COUNT is number of ranges in RANGE_TABLE. */
814 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
817 re_wchar_t range_start, range_end; \
819 re_char *range_table_end \
820 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
822 for (p = (range_table); p < range_table_end; p += 2 * 3) \
824 EXTRACT_CHARACTER (range_start, p); \
825 EXTRACT_CHARACTER (range_end, p + 3); \
827 if (range_start <= (c) && (c) <= range_end) \
836 /* Test if C is in range table of CHARSET. The flag NOT is negated if
837 C is listed in it. */
838 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
841 /* Number of ranges in range table. */ \
843 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
845 EXTRACT_NUMBER_AND_INCR (count, range_table); \
846 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
850 /* If DEBUG is defined, Regex prints many voluminous messages about what
851 it is doing (if the variable `debug' is nonzero). If linked with the
852 main program in `iregex.c', you can enter patterns and strings
853 interactively. And if linked with the main program in `main.c' and
854 the other test files, you can run the already-written tests. */
858 /* We use standard I/O for debugging. */
861 /* It is useful to test things that ``must'' be true when debugging. */
864 static int debug
= -100000;
866 # define DEBUG_STATEMENT(e) e
867 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
868 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
869 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
870 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
871 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
872 if (debug > 0) print_partial_compiled_pattern (s, e)
873 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
874 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
877 /* Print the fastmap in human-readable form. */
880 print_fastmap (fastmap
)
883 unsigned was_a_range
= 0;
886 while (i
< (1 << BYTEWIDTH
))
892 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
908 /* Print a compiled pattern string in human-readable form, starting at
909 the START pointer into it and ending just before the pointer END. */
912 print_partial_compiled_pattern (start
, end
)
926 /* Loop over pattern commands. */
929 printf ("%d:\t", p
- start
);
931 switch ((re_opcode_t
) *p
++)
943 printf ("/exactn/%d", mcnt
);
953 printf ("/start_memory/%d", *p
++);
957 printf ("/stop_memory/%d", *p
++);
961 printf ("/duplicate/%d", *p
++);
971 register int c
, last
= -100;
972 register int in_range
= 0;
973 int length
= CHARSET_BITMAP_SIZE (p
- 1);
974 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
976 printf ("/charset [%s",
977 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
979 assert (p
+ *p
< pend
);
981 for (c
= 0; c
< 256; c
++)
983 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
985 /* Are we starting a range? */
986 if (last
+ 1 == c
&& ! in_range
)
991 /* Have we broken a range? */
992 else if (last
+ 1 != c
&& in_range
)
1011 if (has_range_table
)
1014 printf ("has-range-table");
1016 /* ??? Should print the range table; for now, just skip it. */
1017 p
+= 2; /* skip range table bits */
1018 EXTRACT_NUMBER_AND_INCR (count
, p
);
1019 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1025 printf ("/begline");
1029 printf ("/endline");
1032 case on_failure_jump
:
1033 extract_number_and_incr (&mcnt
, &p
);
1034 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
1037 case on_failure_keep_string_jump
:
1038 extract_number_and_incr (&mcnt
, &p
);
1039 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1042 case on_failure_jump_nastyloop
:
1043 extract_number_and_incr (&mcnt
, &p
);
1044 printf ("/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1047 case on_failure_jump_loop
:
1048 extract_number_and_incr (&mcnt
, &p
);
1049 printf ("/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1052 case on_failure_jump_smart
:
1053 extract_number_and_incr (&mcnt
, &p
);
1054 printf ("/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1058 extract_number_and_incr (&mcnt
, &p
);
1059 printf ("/jump to %d", p
+ mcnt
- start
);
1063 extract_number_and_incr (&mcnt
, &p
);
1064 extract_number_and_incr (&mcnt2
, &p
);
1065 printf ("/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1069 extract_number_and_incr (&mcnt
, &p
);
1070 extract_number_and_incr (&mcnt2
, &p
);
1071 printf ("/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1075 extract_number_and_incr (&mcnt
, &p
);
1076 extract_number_and_incr (&mcnt2
, &p
);
1077 printf ("/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1081 printf ("/wordbound");
1085 printf ("/notwordbound");
1089 printf ("/wordbeg");
1093 printf ("/wordend");
1096 printf ("/syntaxspec");
1098 printf ("/%d", mcnt
);
1102 printf ("/notsyntaxspec");
1104 printf ("/%d", mcnt
);
1109 printf ("/before_dot");
1117 printf ("/after_dot");
1121 printf ("/categoryspec");
1123 printf ("/%d", mcnt
);
1126 case notcategoryspec
:
1127 printf ("/notcategoryspec");
1129 printf ("/%d", mcnt
);
1142 printf ("?%d", *(p
-1));
1148 printf ("%d:\tend of pattern.\n", p
- start
);
1153 print_compiled_pattern (bufp
)
1154 struct re_pattern_buffer
*bufp
;
1156 re_char
*buffer
= bufp
->buffer
;
1158 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1159 printf ("%ld bytes used/%ld bytes allocated.\n",
1160 bufp
->used
, bufp
->allocated
);
1162 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1164 printf ("fastmap: ");
1165 print_fastmap (bufp
->fastmap
);
1168 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1169 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1170 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1171 printf ("no_sub: %d\t", bufp
->no_sub
);
1172 printf ("not_bol: %d\t", bufp
->not_bol
);
1173 printf ("not_eol: %d\t", bufp
->not_eol
);
1174 printf ("syntax: %lx\n", bufp
->syntax
);
1176 /* Perhaps we should print the translate table? */
1181 print_double_string (where
, string1
, size1
, string2
, size2
)
1194 if (FIRST_STRING_P (where
))
1196 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1197 putchar (string1
[this_char
]);
1202 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1203 putchar (string2
[this_char
]);
1207 #else /* not DEBUG */
1212 # define DEBUG_STATEMENT(e)
1213 # define DEBUG_PRINT1(x)
1214 # define DEBUG_PRINT2(x1, x2)
1215 # define DEBUG_PRINT3(x1, x2, x3)
1216 # define DEBUG_PRINT4(x1, x2, x3, x4)
1217 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1218 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1220 #endif /* not DEBUG */
1222 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1223 also be assigned to arbitrarily: each pattern buffer stores its own
1224 syntax, so it can be changed between regex compilations. */
1225 /* This has no initializer because initialized variables in Emacs
1226 become read-only after dumping. */
1227 reg_syntax_t re_syntax_options
;
1230 /* Specify the precise syntax of regexps for compilation. This provides
1231 for compatibility for various utilities which historically have
1232 different, incompatible syntaxes.
1234 The argument SYNTAX is a bit mask comprised of the various bits
1235 defined in regex.h. We return the old syntax. */
1238 re_set_syntax (syntax
)
1239 reg_syntax_t syntax
;
1241 reg_syntax_t ret
= re_syntax_options
;
1243 re_syntax_options
= syntax
;
1246 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1248 /* This table gives an error message for each of the error codes listed
1249 in regex.h. Obviously the order here has to be same as there.
1250 POSIX doesn't require that we do anything for REG_NOERROR,
1251 but why not be nice? */
1253 static const char *re_error_msgid
[] =
1255 gettext_noop ("Success"), /* REG_NOERROR */
1256 gettext_noop ("No match"), /* REG_NOMATCH */
1257 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1258 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1259 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1260 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1261 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1262 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1263 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1264 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1265 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1266 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1267 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1268 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1269 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1270 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1271 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1274 /* Avoiding alloca during matching, to placate r_alloc. */
1276 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1277 searching and matching functions should not call alloca. On some
1278 systems, alloca is implemented in terms of malloc, and if we're
1279 using the relocating allocator routines, then malloc could cause a
1280 relocation, which might (if the strings being searched are in the
1281 ralloc heap) shift the data out from underneath the regexp
1284 Here's another reason to avoid allocation: Emacs
1285 processes input from X in a signal handler; processing X input may
1286 call malloc; if input arrives while a matching routine is calling
1287 malloc, then we're scrod. But Emacs can't just block input while
1288 calling matching routines; then we don't notice interrupts when
1289 they come in. So, Emacs blocks input around all regexp calls
1290 except the matching calls, which it leaves unprotected, in the
1291 faith that they will not malloc. */
1293 /* Normally, this is fine. */
1294 #define MATCH_MAY_ALLOCATE
1296 /* When using GNU C, we are not REALLY using the C alloca, no matter
1297 what config.h may say. So don't take precautions for it. */
1302 /* The match routines may not allocate if (1) they would do it with malloc
1303 and (2) it's not safe for them to use malloc.
1304 Note that if REL_ALLOC is defined, matching would not use malloc for the
1305 failure stack, but we would still use it for the register vectors;
1306 so REL_ALLOC should not affect this. */
1307 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1308 # undef MATCH_MAY_ALLOCATE
1312 /* Failure stack declarations and macros; both re_compile_fastmap and
1313 re_match_2 use a failure stack. These have to be macros because of
1314 REGEX_ALLOCATE_STACK. */
1317 /* Approximate number of failure points for which to initially allocate space
1318 when matching. If this number is exceeded, we allocate more
1319 space, so it is not a hard limit. */
1320 #ifndef INIT_FAILURE_ALLOC
1321 # define INIT_FAILURE_ALLOC 20
1324 /* Roughly the maximum number of failure points on the stack. Would be
1325 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1326 This is a variable only so users of regex can assign to it; we never
1327 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1328 before using it, so it should probably be a byte-count instead. */
1329 # if defined MATCH_MAY_ALLOCATE
1330 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1331 whose default stack limit is 2mb. In order for a larger
1332 value to work reliably, you have to try to make it accord
1333 with the process stack limit. */
1334 size_t re_max_failures
= 40000;
1336 size_t re_max_failures
= 4000;
1339 union fail_stack_elt
1342 /* This should be the biggest `int' that's no bigger than a pointer. */
1346 typedef union fail_stack_elt fail_stack_elt_t
;
1350 fail_stack_elt_t
*stack
;
1352 size_t avail
; /* Offset of next open position. */
1353 size_t frame
; /* Offset of the cur constructed frame. */
1356 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1357 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1360 /* Define macros to initialize and free the failure stack.
1361 Do `return -2' if the alloc fails. */
1363 #ifdef MATCH_MAY_ALLOCATE
1364 # define INIT_FAIL_STACK() \
1366 fail_stack.stack = (fail_stack_elt_t *) \
1367 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1368 * sizeof (fail_stack_elt_t)); \
1370 if (fail_stack.stack == NULL) \
1373 fail_stack.size = INIT_FAILURE_ALLOC; \
1374 fail_stack.avail = 0; \
1375 fail_stack.frame = 0; \
1378 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1380 # define INIT_FAIL_STACK() \
1382 fail_stack.avail = 0; \
1383 fail_stack.frame = 0; \
1386 # define RESET_FAIL_STACK() ((void)0)
1390 /* Double the size of FAIL_STACK, up to a limit
1391 which allows approximately `re_max_failures' items.
1393 Return 1 if succeeds, and 0 if either ran out of memory
1394 allocating space for it or it was already too large.
1396 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1398 /* Factor to increase the failure stack size by
1399 when we increase it.
1400 This used to be 2, but 2 was too wasteful
1401 because the old discarded stacks added up to as much space
1402 were as ultimate, maximum-size stack. */
1403 #define FAIL_STACK_GROWTH_FACTOR 4
1405 #define GROW_FAIL_STACK(fail_stack) \
1406 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1407 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1409 : ((fail_stack).stack \
1410 = (fail_stack_elt_t *) \
1411 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1412 (fail_stack).size * sizeof (fail_stack_elt_t), \
1413 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1414 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1415 * FAIL_STACK_GROWTH_FACTOR))), \
1417 (fail_stack).stack == NULL \
1419 : ((fail_stack).size \
1420 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1421 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1422 * FAIL_STACK_GROWTH_FACTOR)) \
1423 / sizeof (fail_stack_elt_t)), \
1427 /* Push a pointer value onto the failure stack.
1428 Assumes the variable `fail_stack'. Probably should only
1429 be called from within `PUSH_FAILURE_POINT'. */
1430 #define PUSH_FAILURE_POINTER(item) \
1431 fail_stack.stack[fail_stack.avail++].pointer = (item)
1433 /* This pushes an integer-valued item onto the failure stack.
1434 Assumes the variable `fail_stack'. Probably should only
1435 be called from within `PUSH_FAILURE_POINT'. */
1436 #define PUSH_FAILURE_INT(item) \
1437 fail_stack.stack[fail_stack.avail++].integer = (item)
1439 /* Push a fail_stack_elt_t value onto the failure stack.
1440 Assumes the variable `fail_stack'. Probably should only
1441 be called from within `PUSH_FAILURE_POINT'. */
1442 #define PUSH_FAILURE_ELT(item) \
1443 fail_stack.stack[fail_stack.avail++] = (item)
1445 /* These three POP... operations complement the three PUSH... operations.
1446 All assume that `fail_stack' is nonempty. */
1447 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1448 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1449 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1451 /* Individual items aside from the registers. */
1452 #define NUM_NONREG_ITEMS 3
1454 /* Used to examine the stack (to detect infinite loops). */
1455 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1456 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1457 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1458 #define TOP_FAILURE_HANDLE() fail_stack.frame
1461 #define ENSURE_FAIL_STACK(space) \
1462 while (REMAINING_AVAIL_SLOTS <= space) { \
1463 if (!GROW_FAIL_STACK (fail_stack)) \
1465 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1466 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1469 /* Push register NUM onto the stack. */
1470 #define PUSH_FAILURE_REG(num) \
1472 char *destination; \
1473 ENSURE_FAIL_STACK(3); \
1474 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1475 num, regstart[num], regend[num]); \
1476 PUSH_FAILURE_POINTER (regstart[num]); \
1477 PUSH_FAILURE_POINTER (regend[num]); \
1478 PUSH_FAILURE_INT (num); \
1481 /* Change the counter's value to VAL, but make sure that it will
1482 be reset when backtracking. */
1483 #define PUSH_NUMBER(ptr,val) \
1485 char *destination; \
1487 ENSURE_FAIL_STACK(3); \
1488 EXTRACT_NUMBER (c, ptr); \
1489 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1490 PUSH_FAILURE_INT (c); \
1491 PUSH_FAILURE_POINTER (ptr); \
1492 PUSH_FAILURE_INT (-1); \
1493 STORE_NUMBER (ptr, val); \
1496 /* Pop a saved register off the stack. */
1497 #define POP_FAILURE_REG_OR_COUNT() \
1499 int reg = POP_FAILURE_INT (); \
1502 /* It's a counter. */ \
1503 /* Here, we discard `const', making re_match non-reentrant. */ \
1504 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1505 reg = POP_FAILURE_INT (); \
1506 STORE_NUMBER (ptr, reg); \
1507 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1511 regend[reg] = POP_FAILURE_POINTER (); \
1512 regstart[reg] = POP_FAILURE_POINTER (); \
1513 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1514 reg, regstart[reg], regend[reg]); \
1518 /* Check that we are not stuck in an infinite loop. */
1519 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1521 int failure = TOP_FAILURE_HANDLE (); \
1522 /* Check for infinite matching loops */ \
1523 while (failure > 0 \
1524 && (FAILURE_STR (failure) == string_place \
1525 || FAILURE_STR (failure) == NULL)) \
1527 assert (FAILURE_PAT (failure) >= bufp->buffer \
1528 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1529 if (FAILURE_PAT (failure) == pat_cur) \
1534 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1535 failure = NEXT_FAILURE_HANDLE(failure); \
1537 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1540 /* Push the information about the state we will need
1541 if we ever fail back to it.
1543 Requires variables fail_stack, regstart, regend and
1544 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1547 Does `return FAILURE_CODE' if runs out of memory. */
1549 #define PUSH_FAILURE_POINT(pattern, string_place) \
1551 char *destination; \
1552 /* Must be int, so when we don't save any registers, the arithmetic \
1553 of 0 + -1 isn't done as unsigned. */ \
1555 DEBUG_STATEMENT (nfailure_points_pushed++); \
1556 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1557 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1558 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1560 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1562 DEBUG_PRINT1 ("\n"); \
1564 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1565 PUSH_FAILURE_INT (fail_stack.frame); \
1567 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1568 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1569 DEBUG_PRINT1 ("'\n"); \
1570 PUSH_FAILURE_POINTER (string_place); \
1572 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1573 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1574 PUSH_FAILURE_POINTER (pattern); \
1576 /* Close the frame by moving the frame pointer past it. */ \
1577 fail_stack.frame = fail_stack.avail; \
1580 /* Estimate the size of data pushed by a typical failure stack entry.
1581 An estimate is all we need, because all we use this for
1582 is to choose a limit for how big to make the failure stack. */
1583 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1584 #define TYPICAL_FAILURE_SIZE 20
1586 /* How many items can still be added to the stack without overflowing it. */
1587 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1590 /* Pops what PUSH_FAIL_STACK pushes.
1592 We restore into the parameters, all of which should be lvalues:
1593 STR -- the saved data position.
1594 PAT -- the saved pattern position.
1595 REGSTART, REGEND -- arrays of string positions.
1597 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1598 `pend', `string1', `size1', `string2', and `size2'. */
1600 #define POP_FAILURE_POINT(str, pat) \
1602 assert (!FAIL_STACK_EMPTY ()); \
1604 /* Remove failure points and point to how many regs pushed. */ \
1605 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1606 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1607 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1609 /* Pop the saved registers. */ \
1610 while (fail_stack.frame < fail_stack.avail) \
1611 POP_FAILURE_REG_OR_COUNT (); \
1613 pat = POP_FAILURE_POINTER (); \
1614 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1615 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1617 /* If the saved string location is NULL, it came from an \
1618 on_failure_keep_string_jump opcode, and we want to throw away the \
1619 saved NULL, thus retaining our current position in the string. */ \
1620 str = POP_FAILURE_POINTER (); \
1621 DEBUG_PRINT2 (" Popping string %p: `", str); \
1622 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1623 DEBUG_PRINT1 ("'\n"); \
1625 fail_stack.frame = POP_FAILURE_INT (); \
1626 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1628 assert (fail_stack.avail >= 0); \
1629 assert (fail_stack.frame <= fail_stack.avail); \
1631 DEBUG_STATEMENT (nfailure_points_popped++); \
1632 } while (0) /* POP_FAILURE_POINT */
1636 /* Registers are set to a sentinel when they haven't yet matched. */
1637 #define REG_UNSET(e) ((e) == NULL)
1639 /* Subroutine declarations and macros for regex_compile. */
1641 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1642 reg_syntax_t syntax
,
1643 struct re_pattern_buffer
*bufp
));
1644 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1645 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1646 int arg1
, int arg2
));
1647 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1648 int arg
, unsigned char *end
));
1649 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1650 int arg1
, int arg2
, unsigned char *end
));
1651 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1653 reg_syntax_t syntax
));
1654 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1656 reg_syntax_t syntax
));
1657 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1658 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1659 char *fastmap
, const int multibyte
));
1661 /* Fetch the next character in the uncompiled pattern, with no
1663 #define PATFETCH(c) \
1666 if (p == pend) return REG_EEND; \
1667 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1672 /* If `translate' is non-null, return translate[D], else just D. We
1673 cast the subscript to translate because some data is declared as
1674 `char *', to avoid warnings when a string constant is passed. But
1675 when we use a character as a subscript we must make it unsigned. */
1677 # define TRANSLATE(d) \
1678 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1682 /* Macros for outputting the compiled pattern into `buffer'. */
1684 /* If the buffer isn't allocated when it comes in, use this. */
1685 #define INIT_BUF_SIZE 32
1687 /* Make sure we have at least N more bytes of space in buffer. */
1688 #define GET_BUFFER_SPACE(n) \
1689 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1692 /* Make sure we have one more byte of buffer space and then add C to it. */
1693 #define BUF_PUSH(c) \
1695 GET_BUFFER_SPACE (1); \
1696 *b++ = (unsigned char) (c); \
1700 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1701 #define BUF_PUSH_2(c1, c2) \
1703 GET_BUFFER_SPACE (2); \
1704 *b++ = (unsigned char) (c1); \
1705 *b++ = (unsigned char) (c2); \
1709 /* As with BUF_PUSH_2, except for three bytes. */
1710 #define BUF_PUSH_3(c1, c2, c3) \
1712 GET_BUFFER_SPACE (3); \
1713 *b++ = (unsigned char) (c1); \
1714 *b++ = (unsigned char) (c2); \
1715 *b++ = (unsigned char) (c3); \
1719 /* Store a jump with opcode OP at LOC to location TO. We store a
1720 relative address offset by the three bytes the jump itself occupies. */
1721 #define STORE_JUMP(op, loc, to) \
1722 store_op1 (op, loc, (to) - (loc) - 3)
1724 /* Likewise, for a two-argument jump. */
1725 #define STORE_JUMP2(op, loc, to, arg) \
1726 store_op2 (op, loc, (to) - (loc) - 3, arg)
1728 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1729 #define INSERT_JUMP(op, loc, to) \
1730 insert_op1 (op, loc, (to) - (loc) - 3, b)
1732 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1733 #define INSERT_JUMP2(op, loc, to, arg) \
1734 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1737 /* This is not an arbitrary limit: the arguments which represent offsets
1738 into the pattern are two bytes long. So if 2^16 bytes turns out to
1739 be too small, many things would have to change. */
1740 /* Any other compiler which, like MSC, has allocation limit below 2^16
1741 bytes will have to use approach similar to what was done below for
1742 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1743 reallocating to 0 bytes. Such thing is not going to work too well.
1744 You have been warned!! */
1745 #if defined _MSC_VER && !defined WIN32
1746 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1747 # define MAX_BUF_SIZE 65500L
1749 # define MAX_BUF_SIZE (1L << 16)
1752 /* Extend the buffer by twice its current size via realloc and
1753 reset the pointers that pointed into the old block to point to the
1754 correct places in the new one. If extending the buffer results in it
1755 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1756 #if __BOUNDED_POINTERS__
1757 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1758 # define MOVE_BUFFER_POINTER(P) \
1759 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1760 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1763 SET_HIGH_BOUND (b); \
1764 SET_HIGH_BOUND (begalt); \
1765 if (fixup_alt_jump) \
1766 SET_HIGH_BOUND (fixup_alt_jump); \
1768 SET_HIGH_BOUND (laststart); \
1769 if (pending_exact) \
1770 SET_HIGH_BOUND (pending_exact); \
1773 # define MOVE_BUFFER_POINTER(P) (P) += incr
1774 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1776 #define EXTEND_BUFFER() \
1778 re_char *old_buffer = bufp->buffer; \
1779 if (bufp->allocated == MAX_BUF_SIZE) \
1781 bufp->allocated <<= 1; \
1782 if (bufp->allocated > MAX_BUF_SIZE) \
1783 bufp->allocated = MAX_BUF_SIZE; \
1784 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1785 if (bufp->buffer == NULL) \
1786 return REG_ESPACE; \
1787 /* If the buffer moved, move all the pointers into it. */ \
1788 if (old_buffer != bufp->buffer) \
1790 int incr = bufp->buffer - old_buffer; \
1791 MOVE_BUFFER_POINTER (b); \
1792 MOVE_BUFFER_POINTER (begalt); \
1793 if (fixup_alt_jump) \
1794 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1796 MOVE_BUFFER_POINTER (laststart); \
1797 if (pending_exact) \
1798 MOVE_BUFFER_POINTER (pending_exact); \
1800 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1804 /* Since we have one byte reserved for the register number argument to
1805 {start,stop}_memory, the maximum number of groups we can report
1806 things about is what fits in that byte. */
1807 #define MAX_REGNUM 255
1809 /* But patterns can have more than `MAX_REGNUM' registers. We just
1810 ignore the excess. */
1811 typedef int regnum_t
;
1814 /* Macros for the compile stack. */
1816 /* Since offsets can go either forwards or backwards, this type needs to
1817 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1818 /* int may be not enough when sizeof(int) == 2. */
1819 typedef long pattern_offset_t
;
1823 pattern_offset_t begalt_offset
;
1824 pattern_offset_t fixup_alt_jump
;
1825 pattern_offset_t laststart_offset
;
1827 } compile_stack_elt_t
;
1832 compile_stack_elt_t
*stack
;
1834 unsigned avail
; /* Offset of next open position. */
1835 } compile_stack_type
;
1838 #define INIT_COMPILE_STACK_SIZE 32
1840 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1841 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1843 /* The next available element. */
1844 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1846 /* Explicit quit checking is only used on NTemacs. */
1847 #if defined WINDOWSNT && defined emacs && defined QUIT
1848 extern int immediate_quit
;
1849 # define IMMEDIATE_QUIT_CHECK \
1851 if (immediate_quit) QUIT; \
1854 # define IMMEDIATE_QUIT_CHECK ((void)0)
1857 /* Structure to manage work area for range table. */
1858 struct range_table_work_area
1860 int *table
; /* actual work area. */
1861 int allocated
; /* allocated size for work area in bytes. */
1862 int used
; /* actually used size in words. */
1863 int bits
; /* flag to record character classes */
1866 /* Make sure that WORK_AREA can hold more N multibyte characters.
1867 This is used only in set_image_of_range and set_image_of_range_1.
1868 It expects WORK_AREA to be a pointer.
1869 If it can't get the space, it returns from the surrounding function. */
1871 #define EXTEND_RANGE_TABLE(work_area, n) \
1873 if (((work_area)->used + (n)) * sizeof (int) > (work_area)->allocated) \
1875 extend_range_table_work_area (work_area); \
1876 if ((work_area)->table == 0) \
1877 return (REG_ESPACE); \
1881 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1882 (work_area).bits |= (bit)
1884 /* Bits used to implement the multibyte-part of the various character classes
1885 such as [:alnum:] in a charset's range table. */
1886 #define BIT_WORD 0x1
1887 #define BIT_LOWER 0x2
1888 #define BIT_PUNCT 0x4
1889 #define BIT_SPACE 0x8
1890 #define BIT_UPPER 0x10
1891 #define BIT_MULTIBYTE 0x20
1893 /* Set a range START..END to WORK_AREA.
1894 The range is passed through TRANSLATE, so START and END
1895 should be untranslated. */
1896 #define SET_RANGE_TABLE_WORK_AREA(work_area, start, end) \
1899 tem = set_image_of_range (&work_area, start, end, translate); \
1901 FREE_STACK_RETURN (tem); \
1904 /* Free allocated memory for WORK_AREA. */
1905 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1907 if ((work_area).table) \
1908 free ((work_area).table); \
1911 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1912 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1913 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1914 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1917 /* Set the bit for character C in a list. */
1918 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1921 /* Get the next unsigned number in the uncompiled pattern. */
1922 #define GET_UNSIGNED_NUMBER(num) \
1923 do { if (p != pend) \
1927 FREE_STACK_RETURN (REG_BADBR); \
1928 while ('0' <= c && c <= '9') \
1934 num = num * 10 + c - '0'; \
1935 if (num / 10 != prev) \
1936 FREE_STACK_RETURN (REG_BADBR); \
1942 FREE_STACK_RETURN (REG_BADBR); \
1946 #if WIDE_CHAR_SUPPORT
1947 /* The GNU C library provides support for user-defined character classes
1948 and the functions from ISO C amendement 1. */
1949 # ifdef CHARCLASS_NAME_MAX
1950 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1952 /* This shouldn't happen but some implementation might still have this
1953 problem. Use a reasonable default value. */
1954 # define CHAR_CLASS_MAX_LENGTH 256
1956 typedef wctype_t re_wctype_t
;
1957 typedef wchar_t re_wchar_t
;
1958 # define re_wctype wctype
1959 # define re_iswctype iswctype
1960 # define re_wctype_to_bit(cc) 0
1962 # define CHAR_CLASS_MAX_LENGTH 9 /* Namely, `multibyte'. */
1965 /* Character classes. */
1966 typedef enum { RECC_ERROR
= 0,
1967 RECC_ALNUM
, RECC_ALPHA
, RECC_WORD
,
1968 RECC_GRAPH
, RECC_PRINT
,
1969 RECC_LOWER
, RECC_UPPER
,
1970 RECC_PUNCT
, RECC_CNTRL
,
1971 RECC_DIGIT
, RECC_XDIGIT
,
1972 RECC_BLANK
, RECC_SPACE
,
1973 RECC_MULTIBYTE
, RECC_NONASCII
,
1974 RECC_ASCII
, RECC_UNIBYTE
1977 typedef int re_wchar_t
;
1979 /* Map a string to the char class it names (if any). */
1984 const char *string
= str
;
1985 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
1986 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
1987 else if (STREQ (string
, "word")) return RECC_WORD
;
1988 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
1989 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
1990 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
1991 else if (STREQ (string
, "lower")) return RECC_LOWER
;
1992 else if (STREQ (string
, "print")) return RECC_PRINT
;
1993 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
1994 else if (STREQ (string
, "space")) return RECC_SPACE
;
1995 else if (STREQ (string
, "upper")) return RECC_UPPER
;
1996 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
1997 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
1998 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
1999 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2000 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2001 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2005 /* True iff CH is in the char class CC. */
2007 re_iswctype (ch
, cc
)
2013 case RECC_ALNUM
: return ISALNUM (ch
);
2014 case RECC_ALPHA
: return ISALPHA (ch
);
2015 case RECC_BLANK
: return ISBLANK (ch
);
2016 case RECC_CNTRL
: return ISCNTRL (ch
);
2017 case RECC_DIGIT
: return ISDIGIT (ch
);
2018 case RECC_GRAPH
: return ISGRAPH (ch
);
2019 case RECC_LOWER
: return ISLOWER (ch
);
2020 case RECC_PRINT
: return ISPRINT (ch
);
2021 case RECC_PUNCT
: return ISPUNCT (ch
);
2022 case RECC_SPACE
: return ISSPACE (ch
);
2023 case RECC_UPPER
: return ISUPPER (ch
);
2024 case RECC_XDIGIT
: return ISXDIGIT (ch
);
2025 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2026 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2027 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2028 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2029 case RECC_WORD
: return ISWORD (ch
);
2030 case RECC_ERROR
: return false;
2036 /* Return a bit-pattern to use in the range-table bits to match multibyte
2037 chars of class CC. */
2039 re_wctype_to_bit (cc
)
2044 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2045 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2046 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2047 case RECC_LOWER
: return BIT_LOWER
;
2048 case RECC_UPPER
: return BIT_UPPER
;
2049 case RECC_PUNCT
: return BIT_PUNCT
;
2050 case RECC_SPACE
: return BIT_SPACE
;
2051 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2052 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2059 /* Filling in the work area of a range. */
2061 /* Actually extend the space in WORK_AREA. */
2064 extend_range_table_work_area (work_area
)
2065 struct range_table_work_area
*work_area
;
2067 work_area
->allocated
+= 16 * sizeof (int);
2068 if (work_area
->table
)
2070 = (int *) realloc (work_area
->table
, work_area
->allocated
);
2073 = (int *) malloc (work_area
->allocated
);
2078 /* Carefully find the ranges of codes that are equivalent
2079 under case conversion to the range start..end when passed through
2080 TRANSLATE. Handle the case where non-letters can come in between
2081 two upper-case letters (which happens in Latin-1).
2082 Also handle the case of groups of more than 2 case-equivalent chars.
2084 The basic method is to look at consecutive characters and see
2085 if they can form a run that can be handled as one.
2087 Returns -1 if successful, REG_ESPACE if ran out of space. */
2090 set_image_of_range_1 (work_area
, start
, end
, translate
)
2091 RE_TRANSLATE_TYPE translate
;
2092 struct range_table_work_area
*work_area
;
2093 re_wchar_t start
, end
;
2095 /* `one_case' indicates a character, or a run of characters,
2096 each of which is an isolate (no case-equivalents).
2097 This includes all ASCII non-letters.
2099 `two_case' indicates a character, or a run of characters,
2100 each of which has two case-equivalent forms.
2101 This includes all ASCII letters.
2103 `strange' indicates a character that has more than one
2106 enum case_type
{one_case
, two_case
, strange
};
2108 /* Describe the run that is in progress,
2109 which the next character can try to extend.
2110 If run_type is strange, that means there really is no run.
2111 If run_type is one_case, then run_start...run_end is the run.
2112 If run_type is two_case, then the run is run_start...run_end,
2113 and the case-equivalents end at run_eqv_end. */
2115 enum case_type run_type
= strange
;
2116 int run_start
, run_end
, run_eqv_end
;
2118 Lisp_Object eqv_table
;
2120 if (!RE_TRANSLATE_P (translate
))
2122 EXTEND_RANGE_TABLE (work_area
, 2);
2123 work_area
->table
[work_area
->used
++] = (start
);
2124 work_area
->table
[work_area
->used
++] = (end
);
2128 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2130 for (; start
<= end
; start
++)
2132 enum case_type this_type
;
2133 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2134 int minchar
, maxchar
;
2136 /* Classify this character */
2138 this_type
= one_case
;
2139 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2140 this_type
= two_case
;
2142 this_type
= strange
;
2145 minchar
= start
, maxchar
= eqv
;
2147 minchar
= eqv
, maxchar
= start
;
2149 /* Can this character extend the run in progress? */
2150 if (this_type
== strange
|| this_type
!= run_type
2151 || !(minchar
== run_end
+ 1
2152 && (run_type
== two_case
2153 ? maxchar
== run_eqv_end
+ 1 : 1)))
2156 Record each of its equivalent ranges. */
2157 if (run_type
== one_case
)
2159 EXTEND_RANGE_TABLE (work_area
, 2);
2160 work_area
->table
[work_area
->used
++] = run_start
;
2161 work_area
->table
[work_area
->used
++] = run_end
;
2163 else if (run_type
== two_case
)
2165 EXTEND_RANGE_TABLE (work_area
, 4);
2166 work_area
->table
[work_area
->used
++] = run_start
;
2167 work_area
->table
[work_area
->used
++] = run_end
;
2168 work_area
->table
[work_area
->used
++]
2169 = RE_TRANSLATE (eqv_table
, run_start
);
2170 work_area
->table
[work_area
->used
++]
2171 = RE_TRANSLATE (eqv_table
, run_end
);
2176 if (this_type
== strange
)
2178 /* For a strange character, add each of its equivalents, one
2179 by one. Don't start a range. */
2182 EXTEND_RANGE_TABLE (work_area
, 2);
2183 work_area
->table
[work_area
->used
++] = eqv
;
2184 work_area
->table
[work_area
->used
++] = eqv
;
2185 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2187 while (eqv
!= start
);
2190 /* Add this char to the run, or start a new run. */
2191 else if (run_type
== strange
)
2193 /* Initialize a new range. */
2194 run_type
= this_type
;
2197 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2201 /* Extend a running range. */
2203 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2207 /* If a run is still in progress at the end, finish it now
2208 by recording its equivalent ranges. */
2209 if (run_type
== one_case
)
2211 EXTEND_RANGE_TABLE (work_area
, 2);
2212 work_area
->table
[work_area
->used
++] = run_start
;
2213 work_area
->table
[work_area
->used
++] = run_end
;
2215 else if (run_type
== two_case
)
2217 EXTEND_RANGE_TABLE (work_area
, 4);
2218 work_area
->table
[work_area
->used
++] = run_start
;
2219 work_area
->table
[work_area
->used
++] = run_end
;
2220 work_area
->table
[work_area
->used
++]
2221 = RE_TRANSLATE (eqv_table
, run_start
);
2222 work_area
->table
[work_area
->used
++]
2223 = RE_TRANSLATE (eqv_table
, run_end
);
2231 /* Record the the image of the range start..end when passed through
2232 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2233 and is not even necessarily contiguous.
2234 Normally we approximate it with the smallest contiguous range that contains
2235 all the chars we need. However, for Latin-1 we go to extra effort
2238 This function is not called for ASCII ranges.
2240 Returns -1 if successful, REG_ESPACE if ran out of space. */
2243 set_image_of_range (work_area
, start
, end
, translate
)
2244 RE_TRANSLATE_TYPE translate
;
2245 struct range_table_work_area
*work_area
;
2246 re_wchar_t start
, end
;
2248 re_wchar_t cmin
, cmax
;
2251 /* For Latin-1 ranges, use set_image_of_range_1
2252 to get proper handling of ranges that include letters and nonletters.
2253 For a range that includes the whole of Latin-1, this is not necessary.
2254 For other character sets, we don't bother to get this right. */
2255 if (RE_TRANSLATE_P (translate
) && start
< 04400
2256 && !(start
< 04200 && end
>= 04377))
2263 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2273 EXTEND_RANGE_TABLE (work_area
, 2);
2274 work_area
->table
[work_area
->used
++] = (start
);
2275 work_area
->table
[work_area
->used
++] = (end
);
2277 cmin
= -1, cmax
= -1;
2279 if (RE_TRANSLATE_P (translate
))
2283 for (ch
= start
; ch
<= end
; ch
++)
2285 re_wchar_t c
= TRANSLATE (ch
);
2286 if (! (start
<= c
&& c
<= end
))
2292 cmin
= MIN (cmin
, c
);
2293 cmax
= MAX (cmax
, c
);
2300 EXTEND_RANGE_TABLE (work_area
, 2);
2301 work_area
->table
[work_area
->used
++] = (cmin
);
2302 work_area
->table
[work_area
->used
++] = (cmax
);
2309 #ifndef MATCH_MAY_ALLOCATE
2311 /* If we cannot allocate large objects within re_match_2_internal,
2312 we make the fail stack and register vectors global.
2313 The fail stack, we grow to the maximum size when a regexp
2315 The register vectors, we adjust in size each time we
2316 compile a regexp, according to the number of registers it needs. */
2318 static fail_stack_type fail_stack
;
2320 /* Size with which the following vectors are currently allocated.
2321 That is so we can make them bigger as needed,
2322 but never make them smaller. */
2323 static int regs_allocated_size
;
2325 static re_char
** regstart
, ** regend
;
2326 static re_char
**best_regstart
, **best_regend
;
2328 /* Make the register vectors big enough for NUM_REGS registers,
2329 but don't make them smaller. */
2332 regex_grow_registers (num_regs
)
2335 if (num_regs
> regs_allocated_size
)
2337 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2338 RETALLOC_IF (regend
, num_regs
, re_char
*);
2339 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2340 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2342 regs_allocated_size
= num_regs
;
2346 #endif /* not MATCH_MAY_ALLOCATE */
2348 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2352 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2353 Returns one of error codes defined in `regex.h', or zero for success.
2355 Assumes the `allocated' (and perhaps `buffer') and `translate'
2356 fields are set in BUFP on entry.
2358 If it succeeds, results are put in BUFP (if it returns an error, the
2359 contents of BUFP are undefined):
2360 `buffer' is the compiled pattern;
2361 `syntax' is set to SYNTAX;
2362 `used' is set to the length of the compiled pattern;
2363 `fastmap_accurate' is zero;
2364 `re_nsub' is the number of subexpressions in PATTERN;
2365 `not_bol' and `not_eol' are zero;
2367 The `fastmap' field is neither examined nor set. */
2369 /* Insert the `jump' from the end of last alternative to "here".
2370 The space for the jump has already been allocated. */
2371 #define FIXUP_ALT_JUMP() \
2373 if (fixup_alt_jump) \
2374 STORE_JUMP (jump, fixup_alt_jump, b); \
2378 /* Return, freeing storage we allocated. */
2379 #define FREE_STACK_RETURN(value) \
2381 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2382 free (compile_stack.stack); \
2386 static reg_errcode_t
2387 regex_compile (pattern
, size
, syntax
, bufp
)
2390 reg_syntax_t syntax
;
2391 struct re_pattern_buffer
*bufp
;
2393 /* We fetch characters from PATTERN here. */
2394 register re_wchar_t c
, c1
;
2396 /* A random temporary spot in PATTERN. */
2399 /* Points to the end of the buffer, where we should append. */
2400 register unsigned char *b
;
2402 /* Keeps track of unclosed groups. */
2403 compile_stack_type compile_stack
;
2405 /* Points to the current (ending) position in the pattern. */
2407 /* `const' makes AIX compiler fail. */
2408 unsigned char *p
= pattern
;
2410 re_char
*p
= pattern
;
2412 re_char
*pend
= pattern
+ size
;
2414 /* How to translate the characters in the pattern. */
2415 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2417 /* Address of the count-byte of the most recently inserted `exactn'
2418 command. This makes it possible to tell if a new exact-match
2419 character can be added to that command or if the character requires
2420 a new `exactn' command. */
2421 unsigned char *pending_exact
= 0;
2423 /* Address of start of the most recently finished expression.
2424 This tells, e.g., postfix * where to find the start of its
2425 operand. Reset at the beginning of groups and alternatives. */
2426 unsigned char *laststart
= 0;
2428 /* Address of beginning of regexp, or inside of last group. */
2429 unsigned char *begalt
;
2431 /* Place in the uncompiled pattern (i.e., the {) to
2432 which to go back if the interval is invalid. */
2433 re_char
*beg_interval
;
2435 /* Address of the place where a forward jump should go to the end of
2436 the containing expression. Each alternative of an `or' -- except the
2437 last -- ends with a forward jump of this sort. */
2438 unsigned char *fixup_alt_jump
= 0;
2440 /* Counts open-groups as they are encountered. Remembered for the
2441 matching close-group on the compile stack, so the same register
2442 number is put in the stop_memory as the start_memory. */
2443 regnum_t regnum
= 0;
2445 /* Work area for range table of charset. */
2446 struct range_table_work_area range_table_work
;
2448 /* If the object matched can contain multibyte characters. */
2449 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2453 DEBUG_PRINT1 ("\nCompiling pattern: ");
2456 unsigned debug_count
;
2458 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2459 putchar (pattern
[debug_count
]);
2464 /* Initialize the compile stack. */
2465 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2466 if (compile_stack
.stack
== NULL
)
2469 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2470 compile_stack
.avail
= 0;
2472 range_table_work
.table
= 0;
2473 range_table_work
.allocated
= 0;
2475 /* Initialize the pattern buffer. */
2476 bufp
->syntax
= syntax
;
2477 bufp
->fastmap_accurate
= 0;
2478 bufp
->not_bol
= bufp
->not_eol
= 0;
2480 /* Set `used' to zero, so that if we return an error, the pattern
2481 printer (for debugging) will think there's no pattern. We reset it
2485 /* Always count groups, whether or not bufp->no_sub is set. */
2488 #if !defined emacs && !defined SYNTAX_TABLE
2489 /* Initialize the syntax table. */
2490 init_syntax_once ();
2493 if (bufp
->allocated
== 0)
2496 { /* If zero allocated, but buffer is non-null, try to realloc
2497 enough space. This loses if buffer's address is bogus, but
2498 that is the user's responsibility. */
2499 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2502 { /* Caller did not allocate a buffer. Do it for them. */
2503 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2505 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2507 bufp
->allocated
= INIT_BUF_SIZE
;
2510 begalt
= b
= bufp
->buffer
;
2512 /* Loop through the uncompiled pattern until we're at the end. */
2521 if ( /* If at start of pattern, it's an operator. */
2523 /* If context independent, it's an operator. */
2524 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2525 /* Otherwise, depends on what's come before. */
2526 || at_begline_loc_p (pattern
, p
, syntax
))
2527 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2536 if ( /* If at end of pattern, it's an operator. */
2538 /* If context independent, it's an operator. */
2539 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2540 /* Otherwise, depends on what's next. */
2541 || at_endline_loc_p (p
, pend
, syntax
))
2542 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2551 if ((syntax
& RE_BK_PLUS_QM
)
2552 || (syntax
& RE_LIMITED_OPS
))
2556 /* If there is no previous pattern... */
2559 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2560 FREE_STACK_RETURN (REG_BADRPT
);
2561 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2566 /* 1 means zero (many) matches is allowed. */
2567 boolean zero_times_ok
= 0, many_times_ok
= 0;
2570 /* If there is a sequence of repetition chars, collapse it
2571 down to just one (the right one). We can't combine
2572 interval operators with these because of, e.g., `a{2}*',
2573 which should only match an even number of `a's. */
2577 if ((syntax
& RE_FRUGAL
)
2578 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2582 zero_times_ok
|= c
!= '+';
2583 many_times_ok
|= c
!= '?';
2589 || (!(syntax
& RE_BK_PLUS_QM
)
2590 && (*p
== '+' || *p
== '?')))
2592 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2595 FREE_STACK_RETURN (REG_EESCAPE
);
2596 if (p
[1] == '+' || p
[1] == '?')
2597 PATFETCH (c
); /* Gobble up the backslash. */
2603 /* If we get here, we found another repeat character. */
2607 /* Star, etc. applied to an empty pattern is equivalent
2608 to an empty pattern. */
2609 if (!laststart
|| laststart
== b
)
2612 /* Now we know whether or not zero matches is allowed
2613 and also whether or not two or more matches is allowed. */
2618 boolean simple
= skip_one_char (laststart
) == b
;
2619 unsigned int startoffset
= 0;
2621 /* Check if the loop can match the empty string. */
2622 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2623 ? on_failure_jump
: on_failure_jump_loop
;
2624 assert (skip_one_char (laststart
) <= b
);
2626 if (!zero_times_ok
&& simple
)
2627 { /* Since simple * loops can be made faster by using
2628 on_failure_keep_string_jump, we turn simple P+
2629 into PP* if P is simple. */
2630 unsigned char *p1
, *p2
;
2631 startoffset
= b
- laststart
;
2632 GET_BUFFER_SPACE (startoffset
);
2633 p1
= b
; p2
= laststart
;
2639 GET_BUFFER_SPACE (6);
2642 STORE_JUMP (ofj
, b
, b
+ 6);
2644 /* Simple * loops can use on_failure_keep_string_jump
2645 depending on what follows. But since we don't know
2646 that yet, we leave the decision up to
2647 on_failure_jump_smart. */
2648 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2649 laststart
+ startoffset
, b
+ 6);
2651 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2656 /* A simple ? pattern. */
2657 assert (zero_times_ok
);
2658 GET_BUFFER_SPACE (3);
2659 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2663 else /* not greedy */
2664 { /* I wish the greedy and non-greedy cases could be merged. */
2666 GET_BUFFER_SPACE (7); /* We might use less. */
2669 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2671 /* The non-greedy multiple match looks like
2672 a repeat..until: we only need a conditional jump
2673 at the end of the loop. */
2674 if (emptyp
) BUF_PUSH (no_op
);
2675 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2676 : on_failure_jump
, b
, laststart
);
2680 /* The repeat...until naturally matches one or more.
2681 To also match zero times, we need to first jump to
2682 the end of the loop (its conditional jump). */
2683 INSERT_JUMP (jump
, laststart
, b
);
2689 /* non-greedy a?? */
2690 INSERT_JUMP (jump
, laststart
, b
+ 3);
2692 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2709 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2711 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2713 /* Ensure that we have enough space to push a charset: the
2714 opcode, the length count, and the bitset; 34 bytes in all. */
2715 GET_BUFFER_SPACE (34);
2719 /* We test `*p == '^' twice, instead of using an if
2720 statement, so we only need one BUF_PUSH. */
2721 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2725 /* Remember the first position in the bracket expression. */
2728 /* Push the number of bytes in the bitmap. */
2729 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2731 /* Clear the whole map. */
2732 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2734 /* charset_not matches newline according to a syntax bit. */
2735 if ((re_opcode_t
) b
[-2] == charset_not
2736 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2737 SET_LIST_BIT ('\n');
2739 /* Read in characters and ranges, setting map bits. */
2742 boolean escaped_char
= false;
2743 const unsigned char *p2
= p
;
2745 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2747 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2748 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2749 So the translation is done later in a loop. Example:
2750 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2753 /* \ might escape characters inside [...] and [^...]. */
2754 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2756 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2759 escaped_char
= true;
2763 /* Could be the end of the bracket expression. If it's
2764 not (i.e., when the bracket expression is `[]' so
2765 far), the ']' character bit gets set way below. */
2766 if (c
== ']' && p2
!= p1
)
2770 /* What should we do for the character which is
2771 greater than 0x7F, but not BASE_LEADING_CODE_P?
2774 /* See if we're at the beginning of a possible character
2777 if (!escaped_char
&&
2778 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2780 /* Leave room for the null. */
2781 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2782 const unsigned char *class_beg
;
2788 /* If pattern is `[[:'. */
2789 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2794 if ((c
== ':' && *p
== ']') || p
== pend
)
2796 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2799 /* This is in any case an invalid class name. */
2804 /* If isn't a word bracketed by `[:' and `:]':
2805 undo the ending character, the letters, and
2806 leave the leading `:' and `[' (but set bits for
2808 if (c
== ':' && *p
== ']')
2813 cc
= re_wctype (str
);
2816 FREE_STACK_RETURN (REG_ECTYPE
);
2818 /* Throw away the ] at the end of the character
2822 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2824 /* Most character classes in a multibyte match
2825 just set a flag. Exceptions are is_blank,
2826 is_digit, is_cntrl, and is_xdigit, since
2827 they can only match ASCII characters. We
2828 don't need to handle them for multibyte.
2829 They are distinguished by a negative wctype. */
2832 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work
,
2833 re_wctype_to_bit (cc
));
2835 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ++ch
)
2837 int translated
= TRANSLATE (ch
);
2838 if (re_iswctype (btowc (ch
), cc
))
2839 SET_LIST_BIT (translated
);
2842 /* Repeat the loop. */
2847 /* Go back to right after the "[:". */
2851 /* Because the `:' may starts the range, we
2852 can't simply set bit and repeat the loop.
2853 Instead, just set it to C and handle below. */
2858 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2861 /* Discard the `-'. */
2864 /* Fetch the character which ends the range. */
2867 if (SINGLE_BYTE_CHAR_P (c
))
2869 if (! SINGLE_BYTE_CHAR_P (c1
))
2871 /* Handle a range starting with a
2872 character of less than 256, and ending
2873 with a character of not less than 256.
2874 Split that into two ranges, the low one
2875 ending at 0377, and the high one
2876 starting at the smallest character in
2877 the charset of C1 and ending at C1. */
2878 int charset
= CHAR_CHARSET (c1
);
2879 re_wchar_t c2
= MAKE_CHAR (charset
, 0, 0);
2881 SET_RANGE_TABLE_WORK_AREA (range_table_work
,
2886 else if (!SAME_CHARSET_P (c
, c1
))
2887 FREE_STACK_RETURN (REG_ERANGE
);
2890 /* Range from C to C. */
2893 /* Set the range ... */
2894 if (SINGLE_BYTE_CHAR_P (c
))
2895 /* ... into bitmap. */
2897 re_wchar_t this_char
;
2898 re_wchar_t range_start
= c
, range_end
= c1
;
2900 /* If the start is after the end, the range is empty. */
2901 if (range_start
> range_end
)
2903 if (syntax
& RE_NO_EMPTY_RANGES
)
2904 FREE_STACK_RETURN (REG_ERANGE
);
2905 /* Else, repeat the loop. */
2909 for (this_char
= range_start
; this_char
<= range_end
;
2911 SET_LIST_BIT (TRANSLATE (this_char
));
2915 /* ... into range table. */
2916 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c1
);
2919 /* Discard any (non)matching list bytes that are all 0 at the
2920 end of the map. Decrease the map-length byte too. */
2921 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2925 /* Build real range table from work area. */
2926 if (RANGE_TABLE_WORK_USED (range_table_work
)
2927 || RANGE_TABLE_WORK_BITS (range_table_work
))
2930 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
2932 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2933 bytes for flags, two for COUNT, and three bytes for
2935 GET_BUFFER_SPACE (4 + used
* 3);
2937 /* Indicate the existence of range table. */
2938 laststart
[1] |= 0x80;
2940 /* Store the character class flag bits into the range table.
2941 If not in emacs, these flag bits are always 0. */
2942 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
2943 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
2945 STORE_NUMBER_AND_INCR (b
, used
/ 2);
2946 for (i
= 0; i
< used
; i
++)
2947 STORE_CHARACTER_AND_INCR
2948 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
2955 if (syntax
& RE_NO_BK_PARENS
)
2962 if (syntax
& RE_NO_BK_PARENS
)
2969 if (syntax
& RE_NEWLINE_ALT
)
2976 if (syntax
& RE_NO_BK_VBAR
)
2983 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2984 goto handle_interval
;
2990 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2992 /* Do not translate the character after the \, so that we can
2993 distinguish, e.g., \B from \b, even if we normally would
2994 translate, e.g., B to b. */
3000 if (syntax
& RE_NO_BK_PARENS
)
3001 goto normal_backslash
;
3008 /* Look for a special (?...) construct */
3009 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3011 PATFETCH (c
); /* Gobble up the '?'. */
3015 case ':': shy
= 1; break;
3017 /* Only (?:...) is supported right now. */
3018 FREE_STACK_RETURN (REG_BADPAT
);
3029 if (COMPILE_STACK_FULL
)
3031 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3032 compile_stack_elt_t
);
3033 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3035 compile_stack
.size
<<= 1;
3038 /* These are the values to restore when we hit end of this
3039 group. They are all relative offsets, so that if the
3040 whole pattern moves because of realloc, they will still
3042 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3043 COMPILE_STACK_TOP
.fixup_alt_jump
3044 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3045 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3046 COMPILE_STACK_TOP
.regnum
= shy
? -regnum
: regnum
;
3049 start_memory for groups beyond the last one we can
3050 represent in the compiled pattern. */
3051 if (regnum
<= MAX_REGNUM
&& !shy
)
3052 BUF_PUSH_2 (start_memory
, regnum
);
3054 compile_stack
.avail
++;
3059 /* If we've reached MAX_REGNUM groups, then this open
3060 won't actually generate any code, so we'll have to
3061 clear pending_exact explicitly. */
3067 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3069 if (COMPILE_STACK_EMPTY
)
3071 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3072 goto normal_backslash
;
3074 FREE_STACK_RETURN (REG_ERPAREN
);
3080 /* See similar code for backslashed left paren above. */
3081 if (COMPILE_STACK_EMPTY
)
3083 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3086 FREE_STACK_RETURN (REG_ERPAREN
);
3089 /* Since we just checked for an empty stack above, this
3090 ``can't happen''. */
3091 assert (compile_stack
.avail
!= 0);
3093 /* We don't just want to restore into `regnum', because
3094 later groups should continue to be numbered higher,
3095 as in `(ab)c(de)' -- the second group is #2. */
3096 regnum_t this_group_regnum
;
3098 compile_stack
.avail
--;
3099 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3101 = COMPILE_STACK_TOP
.fixup_alt_jump
3102 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3104 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3105 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
3106 /* If we've reached MAX_REGNUM groups, then this open
3107 won't actually generate any code, so we'll have to
3108 clear pending_exact explicitly. */
3111 /* We're at the end of the group, so now we know how many
3112 groups were inside this one. */
3113 if (this_group_regnum
<= MAX_REGNUM
&& this_group_regnum
> 0)
3114 BUF_PUSH_2 (stop_memory
, this_group_regnum
);
3119 case '|': /* `\|'. */
3120 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3121 goto normal_backslash
;
3123 if (syntax
& RE_LIMITED_OPS
)
3126 /* Insert before the previous alternative a jump which
3127 jumps to this alternative if the former fails. */
3128 GET_BUFFER_SPACE (3);
3129 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3133 /* The alternative before this one has a jump after it
3134 which gets executed if it gets matched. Adjust that
3135 jump so it will jump to this alternative's analogous
3136 jump (put in below, which in turn will jump to the next
3137 (if any) alternative's such jump, etc.). The last such
3138 jump jumps to the correct final destination. A picture:
3144 If we are at `b', then fixup_alt_jump right now points to a
3145 three-byte space after `a'. We'll put in the jump, set
3146 fixup_alt_jump to right after `b', and leave behind three
3147 bytes which we'll fill in when we get to after `c'. */
3151 /* Mark and leave space for a jump after this alternative,
3152 to be filled in later either by next alternative or
3153 when know we're at the end of a series of alternatives. */
3155 GET_BUFFER_SPACE (3);
3164 /* If \{ is a literal. */
3165 if (!(syntax
& RE_INTERVALS
)
3166 /* If we're at `\{' and it's not the open-interval
3168 || (syntax
& RE_NO_BK_BRACES
))
3169 goto normal_backslash
;
3173 /* If got here, then the syntax allows intervals. */
3175 /* At least (most) this many matches must be made. */
3176 int lower_bound
= 0, upper_bound
= -1;
3181 FREE_STACK_RETURN (REG_EBRACE
);
3183 GET_UNSIGNED_NUMBER (lower_bound
);
3186 GET_UNSIGNED_NUMBER (upper_bound
);
3188 /* Interval such as `{1}' => match exactly once. */
3189 upper_bound
= lower_bound
;
3191 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3192 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3193 FREE_STACK_RETURN (REG_BADBR
);
3195 if (!(syntax
& RE_NO_BK_BRACES
))
3198 FREE_STACK_RETURN (REG_BADBR
);
3204 FREE_STACK_RETURN (REG_BADBR
);
3206 /* We just parsed a valid interval. */
3208 /* If it's invalid to have no preceding re. */
3211 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3212 FREE_STACK_RETURN (REG_BADRPT
);
3213 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3216 goto unfetch_interval
;
3219 if (upper_bound
== 0)
3220 /* If the upper bound is zero, just drop the sub pattern
3223 else if (lower_bound
== 1 && upper_bound
== 1)
3224 /* Just match it once: nothing to do here. */
3227 /* Otherwise, we have a nontrivial interval. When
3228 we're all done, the pattern will look like:
3229 set_number_at <jump count> <upper bound>
3230 set_number_at <succeed_n count> <lower bound>
3231 succeed_n <after jump addr> <succeed_n count>
3233 jump_n <succeed_n addr> <jump count>
3234 (The upper bound and `jump_n' are omitted if
3235 `upper_bound' is 1, though.) */
3237 { /* If the upper bound is > 1, we need to insert
3238 more at the end of the loop. */
3239 unsigned int nbytes
= (upper_bound
< 0 ? 3
3240 : upper_bound
> 1 ? 5 : 0);
3241 unsigned int startoffset
= 0;
3243 GET_BUFFER_SPACE (20); /* We might use less. */
3245 if (lower_bound
== 0)
3247 /* A succeed_n that starts with 0 is really a
3248 a simple on_failure_jump_loop. */
3249 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3255 /* Initialize lower bound of the `succeed_n', even
3256 though it will be set during matching by its
3257 attendant `set_number_at' (inserted next),
3258 because `re_compile_fastmap' needs to know.
3259 Jump to the `jump_n' we might insert below. */
3260 INSERT_JUMP2 (succeed_n
, laststart
,
3265 /* Code to initialize the lower bound. Insert
3266 before the `succeed_n'. The `5' is the last two
3267 bytes of this `set_number_at', plus 3 bytes of
3268 the following `succeed_n'. */
3269 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3274 if (upper_bound
< 0)
3276 /* A negative upper bound stands for infinity,
3277 in which case it degenerates to a plain jump. */
3278 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3281 else if (upper_bound
> 1)
3282 { /* More than one repetition is allowed, so
3283 append a backward jump to the `succeed_n'
3284 that starts this interval.
3286 When we've reached this during matching,
3287 we'll have matched the interval once, so
3288 jump back only `upper_bound - 1' times. */
3289 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3293 /* The location we want to set is the second
3294 parameter of the `jump_n'; that is `b-2' as
3295 an absolute address. `laststart' will be
3296 the `set_number_at' we're about to insert;
3297 `laststart+3' the number to set, the source
3298 for the relative address. But we are
3299 inserting into the middle of the pattern --
3300 so everything is getting moved up by 5.
3301 Conclusion: (b - 2) - (laststart + 3) + 5,
3302 i.e., b - laststart.
3304 We insert this at the beginning of the loop
3305 so that if we fail during matching, we'll
3306 reinitialize the bounds. */
3307 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3308 upper_bound
- 1, b
);
3313 beg_interval
= NULL
;
3318 /* If an invalid interval, match the characters as literals. */
3319 assert (beg_interval
);
3321 beg_interval
= NULL
;
3323 /* normal_char and normal_backslash need `c'. */
3326 if (!(syntax
& RE_NO_BK_BRACES
))
3328 assert (p
> pattern
&& p
[-1] == '\\');
3329 goto normal_backslash
;
3335 /* There is no way to specify the before_dot and after_dot
3336 operators. rms says this is ok. --karl */
3344 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3350 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3356 BUF_PUSH_2 (categoryspec
, c
);
3362 BUF_PUSH_2 (notcategoryspec
, c
);
3368 if (syntax
& RE_NO_GNU_OPS
)
3371 BUF_PUSH_2 (syntaxspec
, Sword
);
3376 if (syntax
& RE_NO_GNU_OPS
)
3379 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3384 if (syntax
& RE_NO_GNU_OPS
)
3390 if (syntax
& RE_NO_GNU_OPS
)
3396 if (syntax
& RE_NO_GNU_OPS
)
3398 BUF_PUSH (wordbound
);
3402 if (syntax
& RE_NO_GNU_OPS
)
3404 BUF_PUSH (notwordbound
);
3408 if (syntax
& RE_NO_GNU_OPS
)
3414 if (syntax
& RE_NO_GNU_OPS
)
3419 case '1': case '2': case '3': case '4': case '5':
3420 case '6': case '7': case '8': case '9':
3424 if (syntax
& RE_NO_BK_REFS
)
3425 goto normal_backslash
;
3429 /* Can't back reference to a subexpression before its end. */
3430 if (reg
> regnum
|| group_in_compile_stack (compile_stack
, reg
))
3431 FREE_STACK_RETURN (REG_ESUBREG
);
3434 BUF_PUSH_2 (duplicate
, reg
);
3441 if (syntax
& RE_BK_PLUS_QM
)
3444 goto normal_backslash
;
3448 /* You might think it would be useful for \ to mean
3449 not to translate; but if we don't translate it
3450 it will never match anything. */
3457 /* Expects the character in `c'. */
3459 /* If no exactn currently being built. */
3462 /* If last exactn not at current position. */
3463 || pending_exact
+ *pending_exact
+ 1 != b
3465 /* We have only one byte following the exactn for the count. */
3466 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3468 /* If followed by a repetition operator. */
3469 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3470 || ((syntax
& RE_BK_PLUS_QM
)
3471 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3472 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3473 || ((syntax
& RE_INTERVALS
)
3474 && ((syntax
& RE_NO_BK_BRACES
)
3475 ? p
!= pend
&& *p
== '{'
3476 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3478 /* Start building a new exactn. */
3482 BUF_PUSH_2 (exactn
, 0);
3483 pending_exact
= b
- 1;
3486 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3492 len
= CHAR_STRING (c
, b
);
3496 (*pending_exact
) += len
;
3501 } /* while p != pend */
3504 /* Through the pattern now. */
3508 if (!COMPILE_STACK_EMPTY
)
3509 FREE_STACK_RETURN (REG_EPAREN
);
3511 /* If we don't want backtracking, force success
3512 the first time we reach the end of the compiled pattern. */
3513 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3516 free (compile_stack
.stack
);
3518 /* We have succeeded; set the length of the buffer. */
3519 bufp
->used
= b
- bufp
->buffer
;
3524 re_compile_fastmap (bufp
);
3525 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3526 print_compiled_pattern (bufp
);
3531 #ifndef MATCH_MAY_ALLOCATE
3532 /* Initialize the failure stack to the largest possible stack. This
3533 isn't necessary unless we're trying to avoid calling alloca in
3534 the search and match routines. */
3536 int num_regs
= bufp
->re_nsub
+ 1;
3538 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3540 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3542 if (! fail_stack
.stack
)
3544 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3545 * sizeof (fail_stack_elt_t
));
3548 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3550 * sizeof (fail_stack_elt_t
)));
3553 regex_grow_registers (num_regs
);
3555 #endif /* not MATCH_MAY_ALLOCATE */
3558 } /* regex_compile */
3560 /* Subroutines for `regex_compile'. */
3562 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3565 store_op1 (op
, loc
, arg
)
3570 *loc
= (unsigned char) op
;
3571 STORE_NUMBER (loc
+ 1, arg
);
3575 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3578 store_op2 (op
, loc
, arg1
, arg2
)
3583 *loc
= (unsigned char) op
;
3584 STORE_NUMBER (loc
+ 1, arg1
);
3585 STORE_NUMBER (loc
+ 3, arg2
);
3589 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3590 for OP followed by two-byte integer parameter ARG. */
3593 insert_op1 (op
, loc
, arg
, end
)
3599 register unsigned char *pfrom
= end
;
3600 register unsigned char *pto
= end
+ 3;
3602 while (pfrom
!= loc
)
3605 store_op1 (op
, loc
, arg
);
3609 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3612 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3618 register unsigned char *pfrom
= end
;
3619 register unsigned char *pto
= end
+ 5;
3621 while (pfrom
!= loc
)
3624 store_op2 (op
, loc
, arg1
, arg2
);
3628 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3629 after an alternative or a begin-subexpression. We assume there is at
3630 least one character before the ^. */
3633 at_begline_loc_p (pattern
, p
, syntax
)
3634 re_char
*pattern
, *p
;
3635 reg_syntax_t syntax
;
3637 re_char
*prev
= p
- 2;
3638 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3641 /* After a subexpression? */
3642 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3643 /* After an alternative? */
3644 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3645 /* After a shy subexpression? */
3646 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3647 && prev
[-1] == '?' && prev
[-2] == '('
3648 && (syntax
& RE_NO_BK_PARENS
3649 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3653 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3654 at least one character after the $, i.e., `P < PEND'. */
3657 at_endline_loc_p (p
, pend
, syntax
)
3659 reg_syntax_t syntax
;
3662 boolean next_backslash
= *next
== '\\';
3663 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3666 /* Before a subexpression? */
3667 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3668 : next_backslash
&& next_next
&& *next_next
== ')')
3669 /* Before an alternative? */
3670 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3671 : next_backslash
&& next_next
&& *next_next
== '|');
3675 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3676 false if it's not. */
3679 group_in_compile_stack (compile_stack
, regnum
)
3680 compile_stack_type compile_stack
;
3685 for (this_element
= compile_stack
.avail
- 1;
3688 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3695 If fastmap is non-NULL, go through the pattern and fill fastmap
3696 with all the possible leading chars. If fastmap is NULL, don't
3697 bother filling it up (obviously) and only return whether the
3698 pattern could potentially match the empty string.
3700 Return 1 if p..pend might match the empty string.
3701 Return 0 if p..pend matches at least one char.
3702 Return -1 if fastmap was not updated accurately. */
3705 analyse_first (p
, pend
, fastmap
, multibyte
)
3708 const int multibyte
;
3713 /* If all elements for base leading-codes in fastmap is set, this
3714 flag is set true. */
3715 boolean match_any_multibyte_characters
= false;
3719 /* The loop below works as follows:
3720 - It has a working-list kept in the PATTERN_STACK and which basically
3721 starts by only containing a pointer to the first operation.
3722 - If the opcode we're looking at is a match against some set of
3723 chars, then we add those chars to the fastmap and go on to the
3724 next work element from the worklist (done via `break').
3725 - If the opcode is a control operator on the other hand, we either
3726 ignore it (if it's meaningless at this point, such as `start_memory')
3727 or execute it (if it's a jump). If the jump has several destinations
3728 (i.e. `on_failure_jump'), then we push the other destination onto the
3730 We guarantee termination by ignoring backward jumps (more or less),
3731 so that `p' is monotonically increasing. More to the point, we
3732 never set `p' (or push) anything `<= p1'. */
3736 /* `p1' is used as a marker of how far back a `on_failure_jump'
3737 can go without being ignored. It is normally equal to `p'
3738 (which prevents any backward `on_failure_jump') except right
3739 after a plain `jump', to allow patterns such as:
3742 10: on_failure_jump 3
3743 as used for the *? operator. */
3746 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3753 /* If the first character has to match a backreference, that means
3754 that the group was empty (since it already matched). Since this
3755 is the only case that interests us here, we can assume that the
3756 backreference must match the empty string. */
3761 /* Following are the cases which match a character. These end
3767 int c
= RE_STRING_CHAR (p
+ 1, pend
- p
);
3769 if (SINGLE_BYTE_CHAR_P (c
))
3778 /* We could put all the chars except for \n (and maybe \0)
3779 but we don't bother since it is generally not worth it. */
3780 if (!fastmap
) break;
3785 /* Chars beyond end of bitmap are possible matches.
3786 All the single-byte codes can occur in multibyte buffers.
3787 So any that are not listed in the charset
3788 are possible matches, even in multibyte buffers. */
3789 if (!fastmap
) break;
3790 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3791 j
< (1 << BYTEWIDTH
); j
++)
3795 if (!fastmap
) break;
3796 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3797 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3799 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3802 if ((not && multibyte
)
3803 /* Any character set can possibly contain a character
3804 which doesn't match the specified set of characters. */
3805 || (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3806 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3807 /* If we can match a character class, we can match
3808 any character set. */
3810 set_fastmap_for_multibyte_characters
:
3811 if (match_any_multibyte_characters
== false)
3813 for (j
= 0x80; j
< 0xA0; j
++) /* XXX */
3814 if (BASE_LEADING_CODE_P (j
))
3816 match_any_multibyte_characters
= true;
3820 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3821 && match_any_multibyte_characters
== false)
3823 /* Set fastmap[I] 1 where I is a base leading code of each
3824 multibyte character in the range table. */
3827 /* Make P points the range table. `+ 2' is to skip flag
3828 bits for a character class. */
3829 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3831 /* Extract the number of ranges in range table into COUNT. */
3832 EXTRACT_NUMBER_AND_INCR (count
, p
);
3833 for (; count
> 0; count
--, p
+= 2 * 3) /* XXX */
3835 /* Extract the start of each range. */
3836 EXTRACT_CHARACTER (c
, p
);
3837 j
= CHAR_CHARSET (c
);
3838 fastmap
[CHARSET_LEADING_CODE_BASE (j
)] = 1;
3845 if (!fastmap
) break;
3847 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3849 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3850 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
3854 /* This match depends on text properties. These end with
3855 aborting optimizations. */
3859 case notcategoryspec
:
3860 if (!fastmap
) break;
3861 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
3863 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3864 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
3868 /* Any character set can possibly contain a character
3869 whose category is K (or not). */
3870 goto set_fastmap_for_multibyte_characters
;
3873 /* All cases after this match the empty string. These end with
3893 EXTRACT_NUMBER_AND_INCR (j
, p
);
3895 /* Backward jumps can only go back to code that we've already
3896 visited. `re_compile' should make sure this is true. */
3899 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
3901 case on_failure_jump
:
3902 case on_failure_keep_string_jump
:
3903 case on_failure_jump_loop
:
3904 case on_failure_jump_nastyloop
:
3905 case on_failure_jump_smart
:
3911 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3912 to jump back to "just after here". */
3915 case on_failure_jump
:
3916 case on_failure_keep_string_jump
:
3917 case on_failure_jump_nastyloop
:
3918 case on_failure_jump_loop
:
3919 case on_failure_jump_smart
:
3920 EXTRACT_NUMBER_AND_INCR (j
, p
);
3922 ; /* Backward jump to be ignored. */
3924 { /* We have to look down both arms.
3925 We first go down the "straight" path so as to minimize
3926 stack usage when going through alternatives. */
3927 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
3935 /* This code simply does not properly handle forward jump_n. */
3936 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
3938 /* jump_n can either jump or fall through. The (backward) jump
3939 case has already been handled, so we only need to look at the
3940 fallthrough case. */
3944 /* If N == 0, it should be an on_failure_jump_loop instead. */
3945 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
3947 /* We only care about one iteration of the loop, so we don't
3948 need to consider the case where this behaves like an
3965 abort (); /* We have listed all the cases. */
3968 /* Getting here means we have found the possible starting
3969 characters for one path of the pattern -- and that the empty
3970 string does not match. We need not follow this path further. */
3974 /* We reached the end without matching anything. */
3977 } /* analyse_first */
3979 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3980 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3981 characters can start a string that matches the pattern. This fastmap
3982 is used by re_search to skip quickly over impossible starting points.
3984 Character codes above (1 << BYTEWIDTH) are not represented in the
3985 fastmap, but the leading codes are represented. Thus, the fastmap
3986 indicates which character sets could start a match.
3988 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3989 area as BUFP->fastmap.
3991 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3994 Returns 0 if we succeed, -2 if an internal error. */
3997 re_compile_fastmap (bufp
)
3998 struct re_pattern_buffer
*bufp
;
4000 char *fastmap
= bufp
->fastmap
;
4003 assert (fastmap
&& bufp
->buffer
);
4005 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4006 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4008 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4009 fastmap
, RE_MULTIBYTE_P (bufp
));
4010 bufp
->can_be_null
= (analysis
!= 0);
4012 } /* re_compile_fastmap */
4014 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4015 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4016 this memory for recording register information. STARTS and ENDS
4017 must be allocated using the malloc library routine, and must each
4018 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4020 If NUM_REGS == 0, then subsequent matches should allocate their own
4023 Unless this function is called, the first search or match using
4024 PATTERN_BUFFER will allocate its own register data, without
4025 freeing the old data. */
4028 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
4029 struct re_pattern_buffer
*bufp
;
4030 struct re_registers
*regs
;
4032 regoff_t
*starts
, *ends
;
4036 bufp
->regs_allocated
= REGS_REALLOCATE
;
4037 regs
->num_regs
= num_regs
;
4038 regs
->start
= starts
;
4043 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4045 regs
->start
= regs
->end
= (regoff_t
*) 0;
4048 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4050 /* Searching routines. */
4052 /* Like re_search_2, below, but only one string is specified, and
4053 doesn't let you say where to stop matching. */
4056 re_search (bufp
, string
, size
, startpos
, range
, regs
)
4057 struct re_pattern_buffer
*bufp
;
4059 int size
, startpos
, range
;
4060 struct re_registers
*regs
;
4062 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4065 WEAK_ALIAS (__re_search
, re_search
)
4067 /* End address of virtual concatenation of string. */
4068 #define STOP_ADDR_VSTRING(P) \
4069 (((P) >= size1 ? string2 + size2 : string1 + size1))
4071 /* Address of POS in the concatenation of virtual string. */
4072 #define POS_ADDR_VSTRING(POS) \
4073 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4075 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4076 virtual concatenation of STRING1 and STRING2, starting first at index
4077 STARTPOS, then at STARTPOS + 1, and so on.
4079 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4081 RANGE is how far to scan while trying to match. RANGE = 0 means try
4082 only at STARTPOS; in general, the last start tried is STARTPOS +
4085 In REGS, return the indices of the virtual concatenation of STRING1
4086 and STRING2 that matched the entire BUFP->buffer and its contained
4089 Do not consider matching one past the index STOP in the virtual
4090 concatenation of STRING1 and STRING2.
4092 We return either the position in the strings at which the match was
4093 found, -1 if no match, or -2 if error (such as failure
4097 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
4098 struct re_pattern_buffer
*bufp
;
4099 const char *str1
, *str2
;
4103 struct re_registers
*regs
;
4107 re_char
*string1
= (re_char
*) str1
;
4108 re_char
*string2
= (re_char
*) str2
;
4109 register char *fastmap
= bufp
->fastmap
;
4110 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4111 int total_size
= size1
+ size2
;
4112 int endpos
= startpos
+ range
;
4113 boolean anchored_start
;
4115 /* Nonzero if we have to concern multibyte character. */
4116 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4118 /* Check for out-of-range STARTPOS. */
4119 if (startpos
< 0 || startpos
> total_size
)
4122 /* Fix up RANGE if it might eventually take us outside
4123 the virtual concatenation of STRING1 and STRING2.
4124 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4126 range
= 0 - startpos
;
4127 else if (endpos
> total_size
)
4128 range
= total_size
- startpos
;
4130 /* If the search isn't to be a backwards one, don't waste time in a
4131 search for a pattern anchored at beginning of buffer. */
4132 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4141 /* In a forward search for something that starts with \=.
4142 don't keep searching past point. */
4143 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4145 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4151 /* Update the fastmap now if not correct already. */
4152 if (fastmap
&& !bufp
->fastmap_accurate
)
4153 re_compile_fastmap (bufp
);
4155 /* See whether the pattern is anchored. */
4156 anchored_start
= (bufp
->buffer
[0] == begline
);
4159 gl_state
.object
= re_match_object
;
4161 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4163 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4167 /* Loop through the string, looking for a place to start matching. */
4170 /* If the pattern is anchored,
4171 skip quickly past places we cannot match.
4172 We don't bother to treat startpos == 0 specially
4173 because that case doesn't repeat. */
4174 if (anchored_start
&& startpos
> 0)
4176 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4177 : string2
[startpos
- size1
- 1])
4182 /* If a fastmap is supplied, skip quickly over characters that
4183 cannot be the start of a match. If the pattern can match the
4184 null string, however, we don't need to skip characters; we want
4185 the first null string. */
4186 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4188 register re_char
*d
;
4189 register re_wchar_t buf_ch
;
4191 d
= POS_ADDR_VSTRING (startpos
);
4193 if (range
> 0) /* Searching forwards. */
4195 register int lim
= 0;
4198 if (startpos
< size1
&& startpos
+ range
>= size1
)
4199 lim
= range
- (size1
- startpos
);
4201 /* Written out as an if-else to avoid testing `translate'
4203 if (RE_TRANSLATE_P (translate
))
4210 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
4213 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4218 range
-= buf_charlen
;
4223 && !fastmap
[RE_TRANSLATE (translate
, *d
)])
4230 while (range
> lim
&& !fastmap
[*d
])
4236 startpos
+= irange
- range
;
4238 else /* Searching backwards. */
4240 int room
= (startpos
>= size1
4241 ? size2
+ size1
- startpos
4242 : size1
- startpos
);
4243 buf_ch
= RE_STRING_CHAR (d
, room
);
4244 buf_ch
= TRANSLATE (buf_ch
);
4246 if (! (buf_ch
>= 0400
4247 || fastmap
[buf_ch
]))
4252 /* If can't match the null string, and that's all we have left, fail. */
4253 if (range
>= 0 && startpos
== total_size
&& fastmap
4254 && !bufp
->can_be_null
)
4257 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4258 startpos
, regs
, stop
);
4259 #ifndef REGEX_MALLOC
4276 /* Update STARTPOS to the next character boundary. */
4279 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4280 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
4281 int len
= MULTIBYTE_FORM_LENGTH (p
, pend
- p
);
4299 /* Update STARTPOS to the previous character boundary. */
4302 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4305 /* Find the head of multibyte form. */
4306 while (!CHAR_HEAD_P (*p
))
4311 if (MULTIBYTE_FORM_LENGTH (p
, len
+ 1) != (len
+ 1))
4327 WEAK_ALIAS (__re_search_2
, re_search_2
)
4329 /* Declarations and macros for re_match_2. */
4331 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4333 RE_TRANSLATE_TYPE translate
,
4334 const int multibyte
));
4336 /* This converts PTR, a pointer into one of the search strings `string1'
4337 and `string2' into an offset from the beginning of that string. */
4338 #define POINTER_TO_OFFSET(ptr) \
4339 (FIRST_STRING_P (ptr) \
4340 ? ((regoff_t) ((ptr) - string1)) \
4341 : ((regoff_t) ((ptr) - string2 + size1)))
4343 /* Call before fetching a character with *d. This switches over to
4344 string2 if necessary.
4345 Check re_match_2_internal for a discussion of why end_match_2 might
4346 not be within string2 (but be equal to end_match_1 instead). */
4347 #define PREFETCH() \
4350 /* End of string2 => fail. */ \
4351 if (dend == end_match_2) \
4353 /* End of string1 => advance to string2. */ \
4355 dend = end_match_2; \
4358 /* Call before fetching a char with *d if you already checked other limits.
4359 This is meant for use in lookahead operations like wordend, etc..
4360 where we might need to look at parts of the string that might be
4361 outside of the LIMITs (i.e past `stop'). */
4362 #define PREFETCH_NOLIMIT() \
4366 dend = end_match_2; \
4369 /* Test if at very beginning or at very end of the virtual concatenation
4370 of `string1' and `string2'. If only one string, it's `string2'. */
4371 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4372 #define AT_STRINGS_END(d) ((d) == end2)
4375 /* Test if D points to a character which is word-constituent. We have
4376 two special cases to check for: if past the end of string1, look at
4377 the first character in string2; and if before the beginning of
4378 string2, look at the last character in string1. */
4379 #define WORDCHAR_P(d) \
4380 (SYNTAX ((d) == end1 ? *string2 \
4381 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4384 /* Disabled due to a compiler bug -- see comment at case wordbound */
4386 /* The comment at case wordbound is following one, but we don't use
4387 AT_WORD_BOUNDARY anymore to support multibyte form.
4389 The DEC Alpha C compiler 3.x generates incorrect code for the
4390 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4391 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4392 macro and introducing temporary variables works around the bug. */
4395 /* Test if the character before D and the one at D differ with respect
4396 to being word-constituent. */
4397 #define AT_WORD_BOUNDARY(d) \
4398 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4399 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4402 /* Free everything we malloc. */
4403 #ifdef MATCH_MAY_ALLOCATE
4404 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4405 # define FREE_VARIABLES() \
4407 REGEX_FREE_STACK (fail_stack.stack); \
4408 FREE_VAR (regstart); \
4409 FREE_VAR (regend); \
4410 FREE_VAR (best_regstart); \
4411 FREE_VAR (best_regend); \
4414 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4415 #endif /* not MATCH_MAY_ALLOCATE */
4418 /* Optimization routines. */
4420 /* If the operation is a match against one or more chars,
4421 return a pointer to the next operation, else return NULL. */
4426 switch (SWITCH_ENUM_CAST (*p
++))
4437 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4440 p
= CHARSET_RANGE_TABLE (p
- 1);
4441 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4442 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4445 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4452 case notcategoryspec
:
4464 /* Jump over non-matching operations. */
4465 static unsigned char *
4466 skip_noops (p
, pend
)
4467 unsigned char *p
, *pend
;
4472 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4481 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4492 /* Non-zero if "p1 matches something" implies "p2 fails". */
4494 mutually_exclusive_p (bufp
, p1
, p2
)
4495 struct re_pattern_buffer
*bufp
;
4496 unsigned char *p1
, *p2
;
4499 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4500 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4502 assert (p1
>= bufp
->buffer
&& p1
< pend
4503 && p2
>= bufp
->buffer
&& p2
<= pend
);
4505 /* Skip over open/close-group commands.
4506 If what follows this loop is a ...+ construct,
4507 look at what begins its body, since we will have to
4508 match at least one of that. */
4509 p2
= skip_noops (p2
, pend
);
4510 /* The same skip can be done for p1, except that this function
4511 is only used in the case where p1 is a simple match operator. */
4512 /* p1 = skip_noops (p1, pend); */
4514 assert (p1
>= bufp
->buffer
&& p1
< pend
4515 && p2
>= bufp
->buffer
&& p2
<= pend
);
4517 op2
= p2
== pend
? succeed
: *p2
;
4519 switch (SWITCH_ENUM_CAST (op2
))
4523 /* If we're at the end of the pattern, we can change. */
4524 if (skip_one_char (p1
))
4526 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4534 register re_wchar_t c
4535 = (re_opcode_t
) *p2
== endline
? '\n'
4536 : RE_STRING_CHAR (p2
+ 2, pend
- p2
- 2);
4538 if ((re_opcode_t
) *p1
== exactn
)
4540 if (c
!= RE_STRING_CHAR (p1
+ 2, pend
- p1
- 2))
4542 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4547 else if ((re_opcode_t
) *p1
== charset
4548 || (re_opcode_t
) *p1
== charset_not
)
4550 int not = (re_opcode_t
) *p1
== charset_not
;
4552 /* Test if C is listed in charset (or charset_not)
4554 if (SINGLE_BYTE_CHAR_P (c
))
4556 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4557 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4560 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4561 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4563 /* `not' is equal to 1 if c would match, which means
4564 that we can't change to pop_failure_jump. */
4567 DEBUG_PRINT1 (" No match => fast loop.\n");
4571 else if ((re_opcode_t
) *p1
== anychar
4574 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4582 if ((re_opcode_t
) *p1
== exactn
)
4583 /* Reuse the code above. */
4584 return mutually_exclusive_p (bufp
, p2
, p1
);
4586 /* It is hard to list up all the character in charset
4587 P2 if it includes multibyte character. Give up in
4589 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4591 /* Now, we are sure that P2 has no range table.
4592 So, for the size of bitmap in P2, `p2[1]' is
4593 enough. But P1 may have range table, so the
4594 size of bitmap table of P1 is extracted by
4595 using macro `CHARSET_BITMAP_SIZE'.
4597 Since we know that all the character listed in
4598 P2 is ASCII, it is enough to test only bitmap
4601 if ((re_opcode_t
) *p1
== charset
)
4604 /* We win if the charset inside the loop
4605 has no overlap with the one after the loop. */
4608 && idx
< CHARSET_BITMAP_SIZE (p1
));
4610 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4614 || idx
== CHARSET_BITMAP_SIZE (p1
))
4616 DEBUG_PRINT1 (" No match => fast loop.\n");
4620 else if ((re_opcode_t
) *p1
== charset_not
)
4623 /* We win if the charset_not inside the loop lists
4624 every character listed in the charset after. */
4625 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4626 if (! (p2
[2 + idx
] == 0
4627 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4628 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4633 DEBUG_PRINT1 (" No match => fast loop.\n");
4642 switch (SWITCH_ENUM_CAST (*p1
))
4646 /* Reuse the code above. */
4647 return mutually_exclusive_p (bufp
, p2
, p1
);
4649 /* When we have two charset_not, it's very unlikely that
4650 they don't overlap. The union of the two sets of excluded
4651 chars should cover all possible chars, which, as a matter of
4652 fact, is virtually impossible in multibyte buffers. */
4659 return ((re_opcode_t
) *p1
== syntaxspec
4660 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4664 return ((re_opcode_t
) *p1
== notsyntaxspec
4665 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4668 return (((re_opcode_t
) *p1
== notsyntaxspec
4669 || (re_opcode_t
) *p1
== syntaxspec
)
4674 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4675 case notcategoryspec
:
4676 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4688 /* Matching routines. */
4690 #ifndef emacs /* Emacs never uses this. */
4691 /* re_match is like re_match_2 except it takes only a single string. */
4694 re_match (bufp
, string
, size
, pos
, regs
)
4695 struct re_pattern_buffer
*bufp
;
4698 struct re_registers
*regs
;
4700 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
4702 # if defined C_ALLOCA && !defined REGEX_MALLOC
4707 WEAK_ALIAS (__re_match
, re_match
)
4708 #endif /* not emacs */
4711 /* In Emacs, this is the string or buffer in which we
4712 are matching. It is used for looking up syntax properties. */
4713 Lisp_Object re_match_object
;
4716 /* re_match_2 matches the compiled pattern in BUFP against the
4717 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4718 and SIZE2, respectively). We start matching at POS, and stop
4721 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4722 store offsets for the substring each group matched in REGS. See the
4723 documentation for exactly how many groups we fill.
4725 We return -1 if no match, -2 if an internal error (such as the
4726 failure stack overflowing). Otherwise, we return the length of the
4727 matched substring. */
4730 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4731 struct re_pattern_buffer
*bufp
;
4732 const char *string1
, *string2
;
4735 struct re_registers
*regs
;
4742 gl_state
.object
= re_match_object
;
4743 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4744 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4747 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4748 (re_char
*) string2
, size2
,
4750 #if defined C_ALLOCA && !defined REGEX_MALLOC
4755 WEAK_ALIAS (__re_match_2
, re_match_2
)
4757 /* This is a separate function so that we can force an alloca cleanup
4760 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4761 struct re_pattern_buffer
*bufp
;
4762 re_char
*string1
, *string2
;
4765 struct re_registers
*regs
;
4768 /* General temporaries. */
4773 /* Just past the end of the corresponding string. */
4774 re_char
*end1
, *end2
;
4776 /* Pointers into string1 and string2, just past the last characters in
4777 each to consider matching. */
4778 re_char
*end_match_1
, *end_match_2
;
4780 /* Where we are in the data, and the end of the current string. */
4783 /* Used sometimes to remember where we were before starting matching
4784 an operator so that we can go back in case of failure. This "atomic"
4785 behavior of matching opcodes is indispensable to the correctness
4786 of the on_failure_keep_string_jump optimization. */
4789 /* Where we are in the pattern, and the end of the pattern. */
4790 re_char
*p
= bufp
->buffer
;
4791 re_char
*pend
= p
+ bufp
->used
;
4793 /* We use this to map every character in the string. */
4794 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4796 /* Nonzero if we have to concern multibyte character. */
4797 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4799 /* Failure point stack. Each place that can handle a failure further
4800 down the line pushes a failure point on this stack. It consists of
4801 regstart, and regend for all registers corresponding to
4802 the subexpressions we're currently inside, plus the number of such
4803 registers, and, finally, two char *'s. The first char * is where
4804 to resume scanning the pattern; the second one is where to resume
4805 scanning the strings. */
4806 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4807 fail_stack_type fail_stack
;
4810 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4813 #if defined REL_ALLOC && defined REGEX_MALLOC
4814 /* This holds the pointer to the failure stack, when
4815 it is allocated relocatably. */
4816 fail_stack_elt_t
*failure_stack_ptr
;
4819 /* We fill all the registers internally, independent of what we
4820 return, for use in backreferences. The number here includes
4821 an element for register zero. */
4822 size_t num_regs
= bufp
->re_nsub
+ 1;
4824 /* Information on the contents of registers. These are pointers into
4825 the input strings; they record just what was matched (on this
4826 attempt) by a subexpression part of the pattern, that is, the
4827 regnum-th regstart pointer points to where in the pattern we began
4828 matching and the regnum-th regend points to right after where we
4829 stopped matching the regnum-th subexpression. (The zeroth register
4830 keeps track of what the whole pattern matches.) */
4831 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4832 re_char
**regstart
, **regend
;
4835 /* The following record the register info as found in the above
4836 variables when we find a match better than any we've seen before.
4837 This happens as we backtrack through the failure points, which in
4838 turn happens only if we have not yet matched the entire string. */
4839 unsigned best_regs_set
= false;
4840 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4841 re_char
**best_regstart
, **best_regend
;
4844 /* Logically, this is `best_regend[0]'. But we don't want to have to
4845 allocate space for that if we're not allocating space for anything
4846 else (see below). Also, we never need info about register 0 for
4847 any of the other register vectors, and it seems rather a kludge to
4848 treat `best_regend' differently than the rest. So we keep track of
4849 the end of the best match so far in a separate variable. We
4850 initialize this to NULL so that when we backtrack the first time
4851 and need to test it, it's not garbage. */
4852 re_char
*match_end
= NULL
;
4855 /* Counts the total number of registers pushed. */
4856 unsigned num_regs_pushed
= 0;
4859 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4863 #ifdef MATCH_MAY_ALLOCATE
4864 /* Do not bother to initialize all the register variables if there are
4865 no groups in the pattern, as it takes a fair amount of time. If
4866 there are groups, we include space for register 0 (the whole
4867 pattern), even though we never use it, since it simplifies the
4868 array indexing. We should fix this. */
4871 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4872 regend
= REGEX_TALLOC (num_regs
, re_char
*);
4873 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4874 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
4876 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
4884 /* We must initialize all our variables to NULL, so that
4885 `FREE_VARIABLES' doesn't try to free them. */
4886 regstart
= regend
= best_regstart
= best_regend
= NULL
;
4888 #endif /* MATCH_MAY_ALLOCATE */
4890 /* The starting position is bogus. */
4891 if (pos
< 0 || pos
> size1
+ size2
)
4897 /* Initialize subexpression text positions to -1 to mark ones that no
4898 start_memory/stop_memory has been seen for. Also initialize the
4899 register information struct. */
4900 for (reg
= 1; reg
< num_regs
; reg
++)
4901 regstart
[reg
] = regend
[reg
] = NULL
;
4903 /* We move `string1' into `string2' if the latter's empty -- but not if
4904 `string1' is null. */
4905 if (size2
== 0 && string1
!= NULL
)
4912 end1
= string1
+ size1
;
4913 end2
= string2
+ size2
;
4915 /* `p' scans through the pattern as `d' scans through the data.
4916 `dend' is the end of the input string that `d' points within. `d'
4917 is advanced into the following input string whenever necessary, but
4918 this happens before fetching; therefore, at the beginning of the
4919 loop, `d' can be pointing at the end of a string, but it cannot
4923 /* Only match within string2. */
4924 d
= string2
+ pos
- size1
;
4925 dend
= end_match_2
= string2
+ stop
- size1
;
4926 end_match_1
= end1
; /* Just to give it a value. */
4932 /* Only match within string1. */
4933 end_match_1
= string1
+ stop
;
4935 When we reach end_match_1, PREFETCH normally switches to string2.
4936 But in the present case, this means that just doing a PREFETCH
4937 makes us jump from `stop' to `gap' within the string.
4938 What we really want here is for the search to stop as
4939 soon as we hit end_match_1. That's why we set end_match_2
4940 to end_match_1 (since PREFETCH fails as soon as we hit
4942 end_match_2
= end_match_1
;
4945 { /* It's important to use this code when stop == size so that
4946 moving `d' from end1 to string2 will not prevent the d == dend
4947 check from catching the end of string. */
4949 end_match_2
= string2
+ stop
- size1
;
4955 DEBUG_PRINT1 ("The compiled pattern is: ");
4956 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
4957 DEBUG_PRINT1 ("The string to match is: `");
4958 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
4959 DEBUG_PRINT1 ("'\n");
4961 /* This loops over pattern commands. It exits by returning from the
4962 function if the match is complete, or it drops through if the match
4963 fails at this starting point in the input data. */
4966 DEBUG_PRINT2 ("\n%p: ", p
);
4969 { /* End of pattern means we might have succeeded. */
4970 DEBUG_PRINT1 ("end of pattern ... ");
4972 /* If we haven't matched the entire string, and we want the
4973 longest match, try backtracking. */
4974 if (d
!= end_match_2
)
4976 /* 1 if this match ends in the same string (string1 or string2)
4977 as the best previous match. */
4978 boolean same_str_p
= (FIRST_STRING_P (match_end
)
4979 == FIRST_STRING_P (d
));
4980 /* 1 if this match is the best seen so far. */
4981 boolean best_match_p
;
4983 /* AIX compiler got confused when this was combined
4984 with the previous declaration. */
4986 best_match_p
= d
> match_end
;
4988 best_match_p
= !FIRST_STRING_P (d
);
4990 DEBUG_PRINT1 ("backtracking.\n");
4992 if (!FAIL_STACK_EMPTY ())
4993 { /* More failure points to try. */
4995 /* If exceeds best match so far, save it. */
4996 if (!best_regs_set
|| best_match_p
)
4998 best_regs_set
= true;
5001 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5003 for (reg
= 1; reg
< num_regs
; reg
++)
5005 best_regstart
[reg
] = regstart
[reg
];
5006 best_regend
[reg
] = regend
[reg
];
5012 /* If no failure points, don't restore garbage. And if
5013 last match is real best match, don't restore second
5015 else if (best_regs_set
&& !best_match_p
)
5018 /* Restore best match. It may happen that `dend ==
5019 end_match_1' while the restored d is in string2.
5020 For example, the pattern `x.*y.*z' against the
5021 strings `x-' and `y-z-', if the two strings are
5022 not consecutive in memory. */
5023 DEBUG_PRINT1 ("Restoring best registers.\n");
5026 dend
= ((d
>= string1
&& d
<= end1
)
5027 ? end_match_1
: end_match_2
);
5029 for (reg
= 1; reg
< num_regs
; reg
++)
5031 regstart
[reg
] = best_regstart
[reg
];
5032 regend
[reg
] = best_regend
[reg
];
5035 } /* d != end_match_2 */
5038 DEBUG_PRINT1 ("Accepting match.\n");
5040 /* If caller wants register contents data back, do it. */
5041 if (regs
&& !bufp
->no_sub
)
5043 /* Have the register data arrays been allocated? */
5044 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5045 { /* No. So allocate them with malloc. We need one
5046 extra element beyond `num_regs' for the `-1' marker
5048 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5049 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5050 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5051 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5056 bufp
->regs_allocated
= REGS_REALLOCATE
;
5058 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5059 { /* Yes. If we need more elements than were already
5060 allocated, reallocate them. If we need fewer, just
5062 if (regs
->num_regs
< num_regs
+ 1)
5064 regs
->num_regs
= num_regs
+ 1;
5065 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5066 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5067 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5076 /* These braces fend off a "empty body in an else-statement"
5077 warning under GCC when assert expands to nothing. */
5078 assert (bufp
->regs_allocated
== REGS_FIXED
);
5081 /* Convert the pointer data in `regstart' and `regend' to
5082 indices. Register zero has to be set differently,
5083 since we haven't kept track of any info for it. */
5084 if (regs
->num_regs
> 0)
5086 regs
->start
[0] = pos
;
5087 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5090 /* Go through the first `min (num_regs, regs->num_regs)'
5091 registers, since that is all we initialized. */
5092 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5094 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5095 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5099 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
5101 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
5105 /* If the regs structure we return has more elements than
5106 were in the pattern, set the extra elements to -1. If
5107 we (re)allocated the registers, this is the case,
5108 because we always allocate enough to have at least one
5110 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5111 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5112 } /* regs && !bufp->no_sub */
5114 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5115 nfailure_points_pushed
, nfailure_points_popped
,
5116 nfailure_points_pushed
- nfailure_points_popped
);
5117 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
5119 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
5121 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5127 /* Otherwise match next pattern command. */
5128 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5130 /* Ignore these. Used to ignore the n of succeed_n's which
5131 currently have n == 0. */
5133 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5137 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5140 /* Match the next n pattern characters exactly. The following
5141 byte in the pattern defines n, and the n bytes after that
5142 are the characters to match. */
5145 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5147 /* Remember the start point to rollback upon failure. */
5150 /* This is written out as an if-else so we don't waste time
5151 testing `translate' inside the loop. */
5152 if (RE_TRANSLATE_P (translate
))
5157 int pat_charlen
, buf_charlen
;
5158 unsigned int pat_ch
, buf_ch
;
5161 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
5162 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
5164 if (RE_TRANSLATE (translate
, buf_ch
)
5173 mcnt
-= pat_charlen
;
5180 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5205 /* Match any character except possibly a newline or a null. */
5211 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5214 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
5215 buf_ch
= TRANSLATE (buf_ch
);
5217 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5219 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5220 && buf_ch
== '\000'))
5223 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5232 register unsigned int c
;
5233 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5236 /* Start of actual range_table, or end of bitmap if there is no
5238 re_char
*range_table
;
5240 /* Nonzero if there is a range table. */
5241 int range_table_exists
;
5243 /* Number of ranges of range table. This is not included
5244 in the initial byte-length of the command. */
5247 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5249 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5251 if (range_table_exists
)
5253 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5254 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5258 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5259 c
= TRANSLATE (c
); /* The character to match. */
5261 if (SINGLE_BYTE_CHAR_P (c
))
5262 { /* Lookup bitmap. */
5263 /* Cast to `unsigned' instead of `unsigned char' in
5264 case the bit list is a full 32 bytes long. */
5265 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5266 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5270 else if (range_table_exists
)
5272 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5274 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5275 | (class_bits
& BIT_MULTIBYTE
)
5276 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5277 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5278 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5279 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5282 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5286 if (range_table_exists
)
5287 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5289 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5291 if (!not) goto fail
;
5298 /* The beginning of a group is represented by start_memory.
5299 The argument is the register number. The text
5300 matched within the group is recorded (in the internal
5301 registers data structure) under the register number. */
5303 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5305 /* In case we need to undo this operation (via backtracking). */
5306 PUSH_FAILURE_REG ((unsigned int)*p
);
5309 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5310 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5312 /* Move past the register number and inner group count. */
5317 /* The stop_memory opcode represents the end of a group. Its
5318 argument is the same as start_memory's: the register number. */
5320 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5322 assert (!REG_UNSET (regstart
[*p
]));
5323 /* Strictly speaking, there should be code such as:
5325 assert (REG_UNSET (regend[*p]));
5326 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5328 But the only info to be pushed is regend[*p] and it is known to
5329 be UNSET, so there really isn't anything to push.
5330 Not pushing anything, on the other hand deprives us from the
5331 guarantee that regend[*p] is UNSET since undoing this operation
5332 will not reset its value properly. This is not important since
5333 the value will only be read on the next start_memory or at
5334 the very end and both events can only happen if this stop_memory
5338 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5340 /* Move past the register number and the inner group count. */
5345 /* \<digit> has been turned into a `duplicate' command which is
5346 followed by the numeric value of <digit> as the register number. */
5349 register re_char
*d2
, *dend2
;
5350 int regno
= *p
++; /* Get which register to match against. */
5351 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5353 /* Can't back reference a group which we've never matched. */
5354 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5357 /* Where in input to try to start matching. */
5358 d2
= regstart
[regno
];
5360 /* Remember the start point to rollback upon failure. */
5363 /* Where to stop matching; if both the place to start and
5364 the place to stop matching are in the same string, then
5365 set to the place to stop, otherwise, for now have to use
5366 the end of the first string. */
5368 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5369 == FIRST_STRING_P (regend
[regno
]))
5370 ? regend
[regno
] : end_match_1
);
5373 /* If necessary, advance to next segment in register
5377 if (dend2
== end_match_2
) break;
5378 if (dend2
== regend
[regno
]) break;
5380 /* End of string1 => advance to string2. */
5382 dend2
= regend
[regno
];
5384 /* At end of register contents => success */
5385 if (d2
== dend2
) break;
5387 /* If necessary, advance to next segment in data. */
5390 /* How many characters left in this segment to match. */
5393 /* Want how many consecutive characters we can match in
5394 one shot, so, if necessary, adjust the count. */
5395 if (mcnt
> dend2
- d2
)
5398 /* Compare that many; failure if mismatch, else move
5400 if (RE_TRANSLATE_P (translate
)
5401 ? bcmp_translate (d
, d2
, mcnt
, translate
, multibyte
)
5402 : memcmp (d
, d2
, mcnt
))
5407 d
+= mcnt
, d2
+= mcnt
;
5413 /* begline matches the empty string at the beginning of the string
5414 (unless `not_bol' is set in `bufp'), and after newlines. */
5416 DEBUG_PRINT1 ("EXECUTING begline.\n");
5418 if (AT_STRINGS_BEG (d
))
5420 if (!bufp
->not_bol
) break;
5425 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5429 /* In all other cases, we fail. */
5433 /* endline is the dual of begline. */
5435 DEBUG_PRINT1 ("EXECUTING endline.\n");
5437 if (AT_STRINGS_END (d
))
5439 if (!bufp
->not_eol
) break;
5443 PREFETCH_NOLIMIT ();
5450 /* Match at the very beginning of the data. */
5452 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5453 if (AT_STRINGS_BEG (d
))
5458 /* Match at the very end of the data. */
5460 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5461 if (AT_STRINGS_END (d
))
5466 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5467 pushes NULL as the value for the string on the stack. Then
5468 `POP_FAILURE_POINT' will keep the current value for the
5469 string, instead of restoring it. To see why, consider
5470 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5471 then the . fails against the \n. But the next thing we want
5472 to do is match the \n against the \n; if we restored the
5473 string value, we would be back at the foo.
5475 Because this is used only in specific cases, we don't need to
5476 check all the things that `on_failure_jump' does, to make
5477 sure the right things get saved on the stack. Hence we don't
5478 share its code. The only reason to push anything on the
5479 stack at all is that otherwise we would have to change
5480 `anychar's code to do something besides goto fail in this
5481 case; that seems worse than this. */
5482 case on_failure_keep_string_jump
:
5483 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5484 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5487 PUSH_FAILURE_POINT (p
- 3, NULL
);
5490 /* A nasty loop is introduced by the non-greedy *? and +?.
5491 With such loops, the stack only ever contains one failure point
5492 at a time, so that a plain on_failure_jump_loop kind of
5493 cycle detection cannot work. Worse yet, such a detection
5494 can not only fail to detect a cycle, but it can also wrongly
5495 detect a cycle (between different instantiations of the same
5497 So the method used for those nasty loops is a little different:
5498 We use a special cycle-detection-stack-frame which is pushed
5499 when the on_failure_jump_nastyloop failure-point is *popped*.
5500 This special frame thus marks the beginning of one iteration
5501 through the loop and we can hence easily check right here
5502 whether something matched between the beginning and the end of
5504 case on_failure_jump_nastyloop
:
5505 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5506 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5509 assert ((re_opcode_t
)p
[-4] == no_op
);
5512 CHECK_INFINITE_LOOP (p
- 4, d
);
5514 /* If there's a cycle, just continue without pushing
5515 this failure point. The failure point is the "try again"
5516 option, which shouldn't be tried.
5517 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5518 PUSH_FAILURE_POINT (p
- 3, d
);
5522 /* Simple loop detecting on_failure_jump: just check on the
5523 failure stack if the same spot was already hit earlier. */
5524 case on_failure_jump_loop
:
5526 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5527 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5531 CHECK_INFINITE_LOOP (p
- 3, d
);
5533 /* If there's a cycle, get out of the loop, as if the matching
5534 had failed. We used to just `goto fail' here, but that was
5535 aborting the search a bit too early: we want to keep the
5536 empty-loop-match and keep matching after the loop.
5537 We want (x?)*y\1z to match both xxyz and xxyxz. */
5540 PUSH_FAILURE_POINT (p
- 3, d
);
5545 /* Uses of on_failure_jump:
5547 Each alternative starts with an on_failure_jump that points
5548 to the beginning of the next alternative. Each alternative
5549 except the last ends with a jump that in effect jumps past
5550 the rest of the alternatives. (They really jump to the
5551 ending jump of the following alternative, because tensioning
5552 these jumps is a hassle.)
5554 Repeats start with an on_failure_jump that points past both
5555 the repetition text and either the following jump or
5556 pop_failure_jump back to this on_failure_jump. */
5557 case on_failure_jump
:
5558 IMMEDIATE_QUIT_CHECK
;
5559 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5560 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5563 PUSH_FAILURE_POINT (p
-3, d
);
5566 /* This operation is used for greedy *.
5567 Compare the beginning of the repeat with what in the
5568 pattern follows its end. If we can establish that there
5569 is nothing that they would both match, i.e., that we
5570 would have to backtrack because of (as in, e.g., `a*a')
5571 then we can use a non-backtracking loop based on
5572 on_failure_keep_string_jump instead of on_failure_jump. */
5573 case on_failure_jump_smart
:
5574 IMMEDIATE_QUIT_CHECK
;
5575 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5576 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5579 re_char
*p1
= p
; /* Next operation. */
5580 /* Here, we discard `const', making re_match non-reentrant. */
5581 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5582 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5584 p
-= 3; /* Reset so that we will re-execute the
5585 instruction once it's been changed. */
5587 EXTRACT_NUMBER (mcnt
, p2
- 2);
5589 /* Ensure this is a indeed the trivial kind of loop
5590 we are expecting. */
5591 assert (skip_one_char (p1
) == p2
- 3);
5592 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5593 DEBUG_STATEMENT (debug
+= 2);
5594 if (mutually_exclusive_p (bufp
, p1
, p2
))
5596 /* Use a fast `on_failure_keep_string_jump' loop. */
5597 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5598 *p3
= (unsigned char) on_failure_keep_string_jump
;
5599 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5603 /* Default to a safe `on_failure_jump' loop. */
5604 DEBUG_PRINT1 (" smart default => slow loop.\n");
5605 *p3
= (unsigned char) on_failure_jump
;
5607 DEBUG_STATEMENT (debug
-= 2);
5611 /* Unconditionally jump (without popping any failure points). */
5614 IMMEDIATE_QUIT_CHECK
;
5615 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5616 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5617 p
+= mcnt
; /* Do the jump. */
5618 DEBUG_PRINT2 ("(to %p).\n", p
);
5622 /* Have to succeed matching what follows at least n times.
5623 After that, handle like `on_failure_jump'. */
5625 /* Signedness doesn't matter since we only compare MCNT to 0. */
5626 EXTRACT_NUMBER (mcnt
, p
+ 2);
5627 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5629 /* Originally, mcnt is how many times we HAVE to succeed. */
5632 /* Here, we discard `const', making re_match non-reentrant. */
5633 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5636 PUSH_NUMBER (p2
, mcnt
);
5639 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5644 /* Signedness doesn't matter since we only compare MCNT to 0. */
5645 EXTRACT_NUMBER (mcnt
, p
+ 2);
5646 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5648 /* Originally, this is how many times we CAN jump. */
5651 /* Here, we discard `const', making re_match non-reentrant. */
5652 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5654 PUSH_NUMBER (p2
, mcnt
);
5655 goto unconditional_jump
;
5657 /* If don't have to jump any more, skip over the rest of command. */
5664 unsigned char *p2
; /* Location of the counter. */
5665 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5667 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5668 /* Here, we discard `const', making re_match non-reentrant. */
5669 p2
= (unsigned char*) p
+ mcnt
;
5670 /* Signedness doesn't matter since we only copy MCNT's bits . */
5671 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5672 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5673 PUSH_NUMBER (p2
, mcnt
);
5679 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5680 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5682 /* We SUCCEED (or FAIL) in one of the following cases: */
5684 /* Case 1: D is at the beginning or the end of string. */
5685 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5689 /* C1 is the character before D, S1 is the syntax of C1, C2
5690 is the character at D, and S2 is the syntax of C2. */
5694 int offset
= PTR_TO_OFFSET (d
- 1);
5695 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5696 UPDATE_SYNTAX_TABLE (charpos
);
5698 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5701 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5703 PREFETCH_NOLIMIT ();
5704 c2
= RE_STRING_CHAR (d
, dend
- d
);
5707 if (/* Case 2: Only one of S1 and S2 is Sword. */
5708 ((s1
== Sword
) != (s2
== Sword
))
5709 /* Case 3: Both of S1 and S2 are Sword, and macro
5710 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5711 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5720 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5722 /* We FAIL in one of the following cases: */
5724 /* Case 1: D is at the end of string. */
5725 if (AT_STRINGS_END (d
))
5729 /* C1 is the character before D, S1 is the syntax of C1, C2
5730 is the character at D, and S2 is the syntax of C2. */
5734 int offset
= PTR_TO_OFFSET (d
);
5735 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5736 UPDATE_SYNTAX_TABLE (charpos
);
5739 c2
= RE_STRING_CHAR (d
, dend
- d
);
5742 /* Case 2: S2 is not Sword. */
5746 /* Case 3: D is not at the beginning of string ... */
5747 if (!AT_STRINGS_BEG (d
))
5749 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5751 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5755 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5757 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5764 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5766 /* We FAIL in one of the following cases: */
5768 /* Case 1: D is at the beginning of string. */
5769 if (AT_STRINGS_BEG (d
))
5773 /* C1 is the character before D, S1 is the syntax of C1, C2
5774 is the character at D, and S2 is the syntax of C2. */
5778 int offset
= PTR_TO_OFFSET (d
) - 1;
5779 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5780 UPDATE_SYNTAX_TABLE (charpos
);
5782 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5785 /* Case 2: S1 is not Sword. */
5789 /* Case 3: D is not at the end of string ... */
5790 if (!AT_STRINGS_END (d
))
5792 PREFETCH_NOLIMIT ();
5793 c2
= RE_STRING_CHAR (d
, dend
- d
);
5795 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
5799 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5801 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5809 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
5811 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
5815 int offset
= PTR_TO_OFFSET (d
);
5816 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5817 UPDATE_SYNTAX_TABLE (pos1
);
5824 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5826 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
5834 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5835 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
5840 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5841 if (PTR_BYTE_POS (d
) != PT_BYTE
)
5846 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5847 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
5852 case notcategoryspec
:
5853 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
5855 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
5861 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5863 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
5874 continue; /* Successfully executed one pattern command; keep going. */
5877 /* We goto here if a matching operation fails. */
5879 IMMEDIATE_QUIT_CHECK
;
5880 if (!FAIL_STACK_EMPTY ())
5883 /* A restart point is known. Restore to that state. */
5884 DEBUG_PRINT1 ("\nFAIL:\n");
5885 POP_FAILURE_POINT (str
, pat
);
5886 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
5888 case on_failure_keep_string_jump
:
5889 assert (str
== NULL
);
5890 goto continue_failure_jump
;
5892 case on_failure_jump_nastyloop
:
5893 assert ((re_opcode_t
)pat
[-2] == no_op
);
5894 PUSH_FAILURE_POINT (pat
- 2, str
);
5897 case on_failure_jump_loop
:
5898 case on_failure_jump
:
5901 continue_failure_jump
:
5902 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
5907 /* A special frame used for nastyloops. */
5914 assert (p
>= bufp
->buffer
&& p
<= pend
);
5916 if (d
>= string1
&& d
<= end1
)
5920 break; /* Matching at this starting point really fails. */
5924 goto restore_best_regs
;
5928 return -1; /* Failure to match. */
5931 /* Subroutine definitions for re_match_2. */
5933 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5934 bytes; nonzero otherwise. */
5937 bcmp_translate (s1
, s2
, len
, translate
, multibyte
)
5940 RE_TRANSLATE_TYPE translate
;
5941 const int multibyte
;
5943 register re_char
*p1
= s1
, *p2
= s2
;
5944 re_char
*p1_end
= s1
+ len
;
5945 re_char
*p2_end
= s2
+ len
;
5947 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5948 different lengths, but relying on a single `len' would break this. -sm */
5949 while (p1
< p1_end
&& p2
< p2_end
)
5951 int p1_charlen
, p2_charlen
;
5952 re_wchar_t p1_ch
, p2_ch
;
5954 p1_ch
= RE_STRING_CHAR_AND_LENGTH (p1
, p1_end
- p1
, p1_charlen
);
5955 p2_ch
= RE_STRING_CHAR_AND_LENGTH (p2
, p2_end
- p2
, p2_charlen
);
5957 if (RE_TRANSLATE (translate
, p1_ch
)
5958 != RE_TRANSLATE (translate
, p2_ch
))
5961 p1
+= p1_charlen
, p2
+= p2_charlen
;
5964 if (p1
!= p1_end
|| p2
!= p2_end
)
5970 /* Entry points for GNU code. */
5972 /* re_compile_pattern is the GNU regular expression compiler: it
5973 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5974 Returns 0 if the pattern was valid, otherwise an error string.
5976 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5977 are set in BUFP on entry.
5979 We call regex_compile to do the actual compilation. */
5982 re_compile_pattern (pattern
, length
, bufp
)
5983 const char *pattern
;
5985 struct re_pattern_buffer
*bufp
;
5989 /* GNU code is written to assume at least RE_NREGS registers will be set
5990 (and at least one extra will be -1). */
5991 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5993 /* And GNU code determines whether or not to get register information
5994 by passing null for the REGS argument to re_match, etc., not by
5998 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6002 return gettext (re_error_msgid
[(int) ret
]);
6004 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6006 /* Entry points compatible with 4.2 BSD regex library. We don't define
6007 them unless specifically requested. */
6009 #if defined _REGEX_RE_COMP || defined _LIBC
6011 /* BSD has one and only one pattern buffer. */
6012 static struct re_pattern_buffer re_comp_buf
;
6016 /* Make these definitions weak in libc, so POSIX programs can redefine
6017 these names if they don't use our functions, and still use
6018 regcomp/regexec below without link errors. */
6028 if (!re_comp_buf
.buffer
)
6029 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6030 return (char *) gettext ("No previous regular expression");
6034 if (!re_comp_buf
.buffer
)
6036 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
6037 if (re_comp_buf
.buffer
== NULL
)
6038 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6039 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6040 re_comp_buf
.allocated
= 200;
6042 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6043 if (re_comp_buf
.fastmap
== NULL
)
6044 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6045 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6048 /* Since `re_exec' always passes NULL for the `regs' argument, we
6049 don't need to initialize the pattern buffer fields which affect it. */
6051 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6056 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6057 return (char *) gettext (re_error_msgid
[(int) ret
]);
6068 const int len
= strlen (s
);
6070 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
6072 #endif /* _REGEX_RE_COMP */
6074 /* POSIX.2 functions. Don't define these for Emacs. */
6078 /* regcomp takes a regular expression as a string and compiles it.
6080 PREG is a regex_t *. We do not expect any fields to be initialized,
6081 since POSIX says we shouldn't. Thus, we set
6083 `buffer' to the compiled pattern;
6084 `used' to the length of the compiled pattern;
6085 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6086 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6087 RE_SYNTAX_POSIX_BASIC;
6088 `fastmap' to an allocated space for the fastmap;
6089 `fastmap_accurate' to zero;
6090 `re_nsub' to the number of subexpressions in PATTERN.
6092 PATTERN is the address of the pattern string.
6094 CFLAGS is a series of bits which affect compilation.
6096 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6097 use POSIX basic syntax.
6099 If REG_NEWLINE is set, then . and [^...] don't match newline.
6100 Also, regexec will try a match beginning after every newline.
6102 If REG_ICASE is set, then we considers upper- and lowercase
6103 versions of letters to be equivalent when matching.
6105 If REG_NOSUB is set, then when PREG is passed to regexec, that
6106 routine will report only success or failure, and nothing about the
6109 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6110 the return codes and their meanings.) */
6113 regcomp (preg
, pattern
, cflags
)
6114 regex_t
*__restrict preg
;
6115 const char *__restrict pattern
;
6120 = (cflags
& REG_EXTENDED
) ?
6121 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6123 /* regex_compile will allocate the space for the compiled pattern. */
6125 preg
->allocated
= 0;
6128 /* Try to allocate space for the fastmap. */
6129 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6131 if (cflags
& REG_ICASE
)
6136 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6137 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6138 if (preg
->translate
== NULL
)
6139 return (int) REG_ESPACE
;
6141 /* Map uppercase characters to corresponding lowercase ones. */
6142 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6143 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6146 preg
->translate
= NULL
;
6148 /* If REG_NEWLINE is set, newlines are treated differently. */
6149 if (cflags
& REG_NEWLINE
)
6150 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6151 syntax
&= ~RE_DOT_NEWLINE
;
6152 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6155 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6157 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6159 /* POSIX says a null character in the pattern terminates it, so we
6160 can use strlen here in compiling the pattern. */
6161 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6163 /* POSIX doesn't distinguish between an unmatched open-group and an
6164 unmatched close-group: both are REG_EPAREN. */
6165 if (ret
== REG_ERPAREN
)
6168 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6169 { /* Compute the fastmap now, since regexec cannot modify the pattern
6171 re_compile_fastmap (preg
);
6172 if (preg
->can_be_null
)
6173 { /* The fastmap can't be used anyway. */
6174 free (preg
->fastmap
);
6175 preg
->fastmap
= NULL
;
6180 WEAK_ALIAS (__regcomp
, regcomp
)
6183 /* regexec searches for a given pattern, specified by PREG, in the
6186 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6187 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6188 least NMATCH elements, and we set them to the offsets of the
6189 corresponding matched substrings.
6191 EFLAGS specifies `execution flags' which affect matching: if
6192 REG_NOTBOL is set, then ^ does not match at the beginning of the
6193 string; if REG_NOTEOL is set, then $ does not match at the end.
6195 We return 0 if we find a match and REG_NOMATCH if not. */
6198 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
6199 const regex_t
*__restrict preg
;
6200 const char *__restrict string
;
6202 regmatch_t pmatch
[__restrict_arr
];
6206 struct re_registers regs
;
6207 regex_t private_preg
;
6208 int len
= strlen (string
);
6209 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6211 private_preg
= *preg
;
6213 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6214 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6216 /* The user has told us exactly how many registers to return
6217 information about, via `nmatch'. We have to pass that on to the
6218 matching routines. */
6219 private_preg
.regs_allocated
= REGS_FIXED
;
6223 regs
.num_regs
= nmatch
;
6224 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6225 if (regs
.start
== NULL
)
6226 return (int) REG_NOMATCH
;
6227 regs
.end
= regs
.start
+ nmatch
;
6230 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6231 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6232 was a little bit longer but still only matching the real part.
6233 This works because the `endline' will check for a '\n' and will find a
6234 '\0', correctly deciding that this is not the end of a line.
6235 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6236 a convenient '\0' there. For all we know, the string could be preceded
6237 by '\n' which would throw things off. */
6239 /* Perform the searching operation. */
6240 ret
= re_search (&private_preg
, string
, len
,
6241 /* start: */ 0, /* range: */ len
,
6242 want_reg_info
? ®s
: (struct re_registers
*) 0);
6244 /* Copy the register information to the POSIX structure. */
6251 for (r
= 0; r
< nmatch
; r
++)
6253 pmatch
[r
].rm_so
= regs
.start
[r
];
6254 pmatch
[r
].rm_eo
= regs
.end
[r
];
6258 /* If we needed the temporary register info, free the space now. */
6262 /* We want zero return to mean success, unlike `re_search'. */
6263 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
6265 WEAK_ALIAS (__regexec
, regexec
)
6268 /* Returns a message corresponding to an error code, ERRCODE, returned
6269 from either regcomp or regexec. We don't use PREG here. */
6272 regerror (errcode
, preg
, errbuf
, errbuf_size
)
6274 const regex_t
*preg
;
6282 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6283 /* Only error codes returned by the rest of the code should be passed
6284 to this routine. If we are given anything else, or if other regex
6285 code generates an invalid error code, then the program has a bug.
6286 Dump core so we can fix it. */
6289 msg
= gettext (re_error_msgid
[errcode
]);
6291 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6293 if (errbuf_size
!= 0)
6295 if (msg_size
> errbuf_size
)
6297 strncpy (errbuf
, msg
, errbuf_size
- 1);
6298 errbuf
[errbuf_size
- 1] = 0;
6301 strcpy (errbuf
, msg
);
6306 WEAK_ALIAS (__regerror
, regerror
)
6309 /* Free dynamically allocated space used by PREG. */
6315 if (preg
->buffer
!= NULL
)
6316 free (preg
->buffer
);
6317 preg
->buffer
= NULL
;
6319 preg
->allocated
= 0;
6322 if (preg
->fastmap
!= NULL
)
6323 free (preg
->fastmap
);
6324 preg
->fastmap
= NULL
;
6325 preg
->fastmap_accurate
= 0;
6327 if (preg
->translate
!= NULL
)
6328 free (preg
->translate
);
6329 preg
->translate
= NULL
;
6331 WEAK_ALIAS (__regfree
, regfree
)
6333 #endif /* not emacs */