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
43 #if defined STDC_HEADERS && !defined emacs
46 /* We need this for `regex.h', and perhaps for the Emacs include files. */
47 # include <sys/types.h>
50 /* Whether to use ISO C Amendment 1 wide char functions.
51 Those should not be used for Emacs since it uses its own. */
53 #define WIDE_CHAR_SUPPORT 1
55 #define WIDE_CHAR_SUPPORT \
56 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
59 /* For platform which support the ISO C amendement 1 functionality we
60 support user defined character classes. */
62 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
68 /* We have to keep the namespace clean. */
69 # define regfree(preg) __regfree (preg)
70 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
71 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
72 # define regerror(errcode, preg, errbuf, errbuf_size) \
73 __regerror(errcode, preg, errbuf, errbuf_size)
74 # define re_set_registers(bu, re, nu, st, en) \
75 __re_set_registers (bu, re, nu, st, en)
76 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
77 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
78 # define re_match(bufp, string, size, pos, regs) \
79 __re_match (bufp, string, size, pos, regs)
80 # define re_search(bufp, string, size, startpos, range, regs) \
81 __re_search (bufp, string, size, startpos, range, regs)
82 # define re_compile_pattern(pattern, length, bufp) \
83 __re_compile_pattern (pattern, length, bufp)
84 # define re_set_syntax(syntax) __re_set_syntax (syntax)
85 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
86 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
87 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
89 /* Make sure we call libc's function even if the user overrides them. */
90 # define btowc __btowc
91 # define iswctype __iswctype
92 # define wctype __wctype
94 # define WEAK_ALIAS(a,b) weak_alias (a, b)
96 /* We are also using some library internals. */
97 # include <locale/localeinfo.h>
98 # include <locale/elem-hash.h>
99 # include <langinfo.h>
101 # define WEAK_ALIAS(a,b)
104 /* This is for other GNU distributions with internationalized messages. */
105 #if HAVE_LIBINTL_H || defined _LIBC
106 # include <libintl.h>
108 # define gettext(msgid) (msgid)
112 /* This define is so xgettext can find the internationalizable
114 # define gettext_noop(String) String
117 /* The `emacs' switch turns on certain matching commands
118 that make sense only in Emacs. */
124 /* Make syntax table lookup grant data in gl_state. */
125 # define SYNTAX_ENTRY_VIA_PROPERTY
128 # include "character.h"
129 # include "category.h"
134 # define malloc xmalloc
138 # define realloc xrealloc
144 /* Converts the pointer to the char to BEG-based offset from the start. */
145 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
146 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
148 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
149 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
150 # define RE_STRING_CHAR(p, s) \
151 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
152 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
153 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
155 /* Set C a (possibly multibyte) character before P. P points into a
156 string which is the virtual concatenation of STR1 (which ends at
157 END1) or STR2 (which ends at END2). */
158 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
160 if (target_multibyte) \
162 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
163 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
164 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
165 c = STRING_CHAR (dtemp, (p) - dtemp); \
169 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
171 MAKE_CHAR_MULTIBYTE (c); \
176 #else /* not emacs */
178 /* If we are not linking with Emacs proper,
179 we can't use the relocating allocator
180 even if config.h says that we can. */
183 # if defined STDC_HEADERS || defined _LIBC
190 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
191 If nothing else has been done, use the method below. */
192 # ifdef INHIBIT_STRING_HEADER
193 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
194 # if !defined bzero && !defined bcopy
195 # undef INHIBIT_STRING_HEADER
200 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
201 This is used in most programs--a few other programs avoid this
202 by defining INHIBIT_STRING_HEADER. */
203 # ifndef INHIBIT_STRING_HEADER
204 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
208 # define bzero(s, n) (memset (s, '\0', n), (s))
210 # define bzero(s, n) __bzero (s, n)
214 # include <strings.h>
216 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
219 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
224 /* Define the syntax stuff for \<, \>, etc. */
226 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
227 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1 };
229 # ifdef SWITCH_ENUM_BUG
230 # define SWITCH_ENUM_CAST(x) ((int)(x))
232 # define SWITCH_ENUM_CAST(x) (x)
235 /* Dummy macros for non-Emacs environments. */
236 # define BASE_LEADING_CODE_P(c) (0)
237 # define CHAR_CHARSET(c) 0
238 # define CHARSET_LEADING_CODE_BASE(c) 0
239 # define MAX_MULTIBYTE_LENGTH 1
240 # define RE_MULTIBYTE_P(x) 0
241 # define RE_TARGET_MULTIBYTE_P(x) 0
242 # define WORD_BOUNDARY_P(c1, c2) (0)
243 # define CHAR_HEAD_P(p) (1)
244 # define SINGLE_BYTE_CHAR_P(c) (1)
245 # define SAME_CHARSET_P(c1, c2) (1)
246 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
247 # define STRING_CHAR(p, s) (*(p))
248 # define RE_STRING_CHAR STRING_CHAR
249 # define CHAR_STRING(c, s) (*(s) = (c), 1)
250 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
251 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
252 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
253 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
254 # define MAKE_CHAR(charset, c1, c2) (c1)
255 # define BYTE8_TO_CHAR(c) (c)
256 # define CHAR_BYTE8_P(c) (0)
257 # define MAKE_CHAR_MULTIBYTE(c) 0
258 # define CHAR_LEADING_CODE(c) (c)
259 #endif /* not emacs */
262 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
263 # define RE_TRANSLATE_P(TBL) (TBL)
266 /* Get the interface, including the syntax bits. */
269 /* isalpha etc. are used for the character classes. */
274 /* 1 if C is an ASCII character. */
275 # define IS_REAL_ASCII(c) ((c) < 0200)
277 /* 1 if C is a unibyte character. */
278 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
280 /* The Emacs definitions should not be directly affected by locales. */
282 /* In Emacs, these are only used for single-byte characters. */
283 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
284 # define ISCNTRL(c) ((c) < ' ')
285 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
286 || ((c) >= 'a' && (c) <= 'f') \
287 || ((c) >= 'A' && (c) <= 'F'))
289 /* This is only used for single-byte characters. */
290 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
292 /* The rest must handle multibyte characters. */
294 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
295 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
298 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
299 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
302 # define ISALNUM(c) (IS_REAL_ASCII (c) \
303 ? (((c) >= 'a' && (c) <= 'z') \
304 || ((c) >= 'A' && (c) <= 'Z') \
305 || ((c) >= '0' && (c) <= '9')) \
306 : SYNTAX (c) == Sword)
308 # define ISALPHA(c) (IS_REAL_ASCII (c) \
309 ? (((c) >= 'a' && (c) <= 'z') \
310 || ((c) >= 'A' && (c) <= 'Z')) \
311 : SYNTAX (c) == Sword)
313 # define ISLOWER(c) (LOWERCASEP (c))
315 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
316 ? ((c) > ' ' && (c) < 0177 \
317 && !(((c) >= 'a' && (c) <= 'z') \
318 || ((c) >= 'A' && (c) <= 'Z') \
319 || ((c) >= '0' && (c) <= '9'))) \
320 : SYNTAX (c) != Sword)
322 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
324 # define ISUPPER(c) (UPPERCASEP (c))
326 # define ISWORD(c) (SYNTAX (c) == Sword)
328 #else /* not emacs */
330 /* Jim Meyering writes:
332 "... Some ctype macros are valid only for character codes that
333 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
334 using /bin/cc or gcc but without giving an ansi option). So, all
335 ctype uses should be through macros like ISPRINT... If
336 STDC_HEADERS is defined, then autoconf has verified that the ctype
337 macros don't need to be guarded with references to isascii. ...
338 Defining isascii to 1 should let any compiler worth its salt
339 eliminate the && through constant folding."
340 Solaris defines some of these symbols so we must undefine them first. */
343 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
344 # define ISASCII(c) 1
346 # define ISASCII(c) isascii(c)
349 /* 1 if C is an ASCII character. */
350 # define IS_REAL_ASCII(c) ((c) < 0200)
352 /* This distinction is not meaningful, except in Emacs. */
353 # define ISUNIBYTE(c) 1
356 # define ISBLANK(c) (ISASCII (c) && isblank (c))
358 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
361 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
363 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
367 # define ISPRINT(c) (ISASCII (c) && isprint (c))
368 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
369 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
370 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
371 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
372 # define ISLOWER(c) (ISASCII (c) && islower (c))
373 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
374 # define ISSPACE(c) (ISASCII (c) && isspace (c))
375 # define ISUPPER(c) (ISASCII (c) && isupper (c))
376 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
378 # define ISWORD(c) ISALPHA(c)
381 # define TOLOWER(c) _tolower(c)
383 # define TOLOWER(c) tolower(c)
386 /* How many characters in the character set. */
387 # define CHAR_SET_SIZE 256
391 extern char *re_syntax_table
;
393 # else /* not SYNTAX_TABLE */
395 static char re_syntax_table
[CHAR_SET_SIZE
];
406 bzero (re_syntax_table
, sizeof re_syntax_table
);
408 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
410 re_syntax_table
[c
] = Sword
;
412 re_syntax_table
['_'] = Sword
;
417 # endif /* not SYNTAX_TABLE */
419 # define SYNTAX(c) re_syntax_table[(c)]
421 #endif /* not emacs */
424 # define NULL (void *)0
427 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
428 since ours (we hope) works properly with all combinations of
429 machines, compilers, `char' and `unsigned char' argument types.
430 (Per Bothner suggested the basic approach.) */
431 #undef SIGN_EXTEND_CHAR
433 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
434 #else /* not __STDC__ */
435 /* As in Harbison and Steele. */
436 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
439 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
440 use `alloca' instead of `malloc'. This is because using malloc in
441 re_search* or re_match* could cause memory leaks when C-g is used in
442 Emacs; also, malloc is slower and causes storage fragmentation. On
443 the other hand, malloc is more portable, and easier to debug.
445 Because we sometimes use alloca, some routines have to be macros,
446 not functions -- `alloca'-allocated space disappears at the end of the
447 function it is called in. */
451 # define REGEX_ALLOCATE malloc
452 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
453 # define REGEX_FREE free
455 #else /* not REGEX_MALLOC */
457 /* Emacs already defines alloca, sometimes. */
460 /* Make alloca work the best possible way. */
462 # define alloca __builtin_alloca
463 # else /* not __GNUC__ */
464 # ifdef HAVE_ALLOCA_H
466 # endif /* HAVE_ALLOCA_H */
467 # endif /* not __GNUC__ */
469 # endif /* not alloca */
471 # define REGEX_ALLOCATE alloca
473 /* Assumes a `char *destination' variable. */
474 # define REGEX_REALLOCATE(source, osize, nsize) \
475 (destination = (char *) alloca (nsize), \
476 memcpy (destination, source, osize))
478 /* No need to do anything to free, after alloca. */
479 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
481 #endif /* not REGEX_MALLOC */
483 /* Define how to allocate the failure stack. */
485 #if defined REL_ALLOC && defined REGEX_MALLOC
487 # define REGEX_ALLOCATE_STACK(size) \
488 r_alloc (&failure_stack_ptr, (size))
489 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
490 r_re_alloc (&failure_stack_ptr, (nsize))
491 # define REGEX_FREE_STACK(ptr) \
492 r_alloc_free (&failure_stack_ptr)
494 #else /* not using relocating allocator */
498 # define REGEX_ALLOCATE_STACK malloc
499 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
500 # define REGEX_FREE_STACK free
502 # else /* not REGEX_MALLOC */
504 # define REGEX_ALLOCATE_STACK alloca
506 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
507 REGEX_REALLOCATE (source, osize, nsize)
508 /* No need to explicitly free anything. */
509 # define REGEX_FREE_STACK(arg) ((void)0)
511 # endif /* not REGEX_MALLOC */
512 #endif /* not using relocating allocator */
515 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
516 `string1' or just past its end. This works if PTR is NULL, which is
518 #define FIRST_STRING_P(ptr) \
519 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
521 /* (Re)Allocate N items of type T using malloc, or fail. */
522 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
523 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
524 #define RETALLOC_IF(addr, n, t) \
525 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
526 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
528 #define BYTEWIDTH 8 /* In bits. */
530 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
534 #define MAX(a, b) ((a) > (b) ? (a) : (b))
535 #define MIN(a, b) ((a) < (b) ? (a) : (b))
537 /* Type of source-pattern and string chars. */
538 typedef const unsigned char re_char
;
540 typedef char boolean
;
544 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
545 re_char
*string1
, int size1
,
546 re_char
*string2
, int size2
,
548 struct re_registers
*regs
,
551 /* These are the command codes that appear in compiled regular
552 expressions. Some opcodes are followed by argument bytes. A
553 command code can specify any interpretation whatsoever for its
554 arguments. Zero bytes may appear in the compiled regular expression. */
560 /* Succeed right away--no more backtracking. */
563 /* Followed by one byte giving n, then by n literal bytes. */
566 /* Matches any (more or less) character. */
569 /* Matches any one char belonging to specified set. First
570 following byte is number of bitmap bytes. Then come bytes
571 for a bitmap saying which chars are in. Bits in each byte
572 are ordered low-bit-first. A character is in the set if its
573 bit is 1. A character too large to have a bit in the map is
574 automatically not in the set.
576 If the length byte has the 0x80 bit set, then that stuff
577 is followed by a range table:
578 2 bytes of flags for character sets (low 8 bits, high 8 bits)
579 See RANGE_TABLE_WORK_BITS below.
580 2 bytes, the number of pairs that follow (upto 32767)
581 pairs, each 2 multibyte characters,
582 each multibyte character represented as 3 bytes. */
585 /* Same parameters as charset, but match any character that is
586 not one of those specified. */
589 /* Start remembering the text that is matched, for storing in a
590 register. Followed by one byte with the register number, in
591 the range 0 to one less than the pattern buffer's re_nsub
595 /* Stop remembering the text that is matched and store it in a
596 memory register. Followed by one byte with the register
597 number, in the range 0 to one less than `re_nsub' in the
601 /* Match a duplicate of something remembered. Followed by one
602 byte containing the register number. */
605 /* Fail unless at beginning of line. */
608 /* Fail unless at end of line. */
611 /* Succeeds if at beginning of buffer (if emacs) or at beginning
612 of string to be matched (if not). */
615 /* Analogously, for end of buffer/string. */
618 /* Followed by two byte relative address to which to jump. */
621 /* Followed by two-byte relative address of place to resume at
622 in case of failure. */
625 /* Like on_failure_jump, but pushes a placeholder instead of the
626 current string position when executed. */
627 on_failure_keep_string_jump
,
629 /* Just like `on_failure_jump', except that it checks that we
630 don't get stuck in an infinite loop (matching an empty string
632 on_failure_jump_loop
,
634 /* Just like `on_failure_jump_loop', except that it checks for
635 a different kind of loop (the kind that shows up with non-greedy
636 operators). This operation has to be immediately preceded
638 on_failure_jump_nastyloop
,
640 /* A smart `on_failure_jump' used for greedy * and + operators.
641 It analyses the loop before which it is put and if the
642 loop does not require backtracking, it changes itself to
643 `on_failure_keep_string_jump' and short-circuits the loop,
644 else it just defaults to changing itself into `on_failure_jump'.
645 It assumes that it is pointing to just past a `jump'. */
646 on_failure_jump_smart
,
648 /* Followed by two-byte relative address and two-byte number n.
649 After matching N times, jump to the address upon failure.
650 Does not work if N starts at 0: use on_failure_jump_loop
654 /* Followed by two-byte relative address, and two-byte number n.
655 Jump to the address N times, then fail. */
658 /* Set the following two-byte relative address to the
659 subsequent two-byte number. The address *includes* the two
663 wordbeg
, /* Succeeds if at word beginning. */
664 wordend
, /* Succeeds if at word end. */
666 wordbound
, /* Succeeds if at a word boundary. */
667 notwordbound
, /* Succeeds if not at a word boundary. */
669 /* Matches any character whose syntax is specified. Followed by
670 a byte which contains a syntax code, e.g., Sword. */
673 /* Matches any character whose syntax is not that specified. */
677 ,before_dot
, /* Succeeds if before point. */
678 at_dot
, /* Succeeds if at point. */
679 after_dot
, /* Succeeds if after point. */
681 /* Matches any character whose category-set contains the specified
682 category. The operator is followed by a byte which contains a
683 category code (mnemonic ASCII character). */
686 /* Matches any character whose category-set does not contain the
687 specified category. The operator is followed by a byte which
688 contains the category code (mnemonic ASCII character). */
693 /* Common operations on the compiled pattern. */
695 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
697 #define STORE_NUMBER(destination, number) \
699 (destination)[0] = (number) & 0377; \
700 (destination)[1] = (number) >> 8; \
703 /* Same as STORE_NUMBER, except increment DESTINATION to
704 the byte after where the number is stored. Therefore, DESTINATION
705 must be an lvalue. */
707 #define STORE_NUMBER_AND_INCR(destination, number) \
709 STORE_NUMBER (destination, number); \
710 (destination) += 2; \
713 /* Put into DESTINATION a number stored in two contiguous bytes starting
716 #define EXTRACT_NUMBER(destination, source) \
718 (destination) = *(source) & 0377; \
719 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
723 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
725 extract_number (dest
, source
)
729 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
730 *dest
= *source
& 0377;
734 # ifndef EXTRACT_MACROS /* To debug the macros. */
735 # undef EXTRACT_NUMBER
736 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
737 # endif /* not EXTRACT_MACROS */
741 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
742 SOURCE must be an lvalue. */
744 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
746 EXTRACT_NUMBER (destination, source); \
751 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
754 extract_number_and_incr (destination
, source
)
758 extract_number (destination
, *source
);
762 # ifndef EXTRACT_MACROS
763 # undef EXTRACT_NUMBER_AND_INCR
764 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
765 extract_number_and_incr (&dest, &src)
766 # endif /* not EXTRACT_MACROS */
770 /* Store a multibyte character in three contiguous bytes starting
771 DESTINATION, and increment DESTINATION to the byte after where the
772 character is stored. Therefore, DESTINATION must be an lvalue. */
774 #define STORE_CHARACTER_AND_INCR(destination, character) \
776 (destination)[0] = (character) & 0377; \
777 (destination)[1] = ((character) >> 8) & 0377; \
778 (destination)[2] = (character) >> 16; \
779 (destination) += 3; \
782 /* Put into DESTINATION a character stored in three contiguous bytes
783 starting at SOURCE. */
785 #define EXTRACT_CHARACTER(destination, source) \
787 (destination) = ((source)[0] \
788 | ((source)[1] << 8) \
789 | ((source)[2] << 16)); \
793 /* Macros for charset. */
795 /* Size of bitmap of charset P in bytes. P is a start of charset,
796 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
797 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
799 /* Nonzero if charset P has range table. */
800 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
802 /* Return the address of range table of charset P. But not the start
803 of table itself, but the before where the number of ranges is
804 stored. `2 +' means to skip re_opcode_t and size of bitmap,
805 and the 2 bytes of flags at the start of the range table. */
806 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
808 /* Extract the bit flags that start a range table. */
809 #define CHARSET_RANGE_TABLE_BITS(p) \
810 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
811 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
813 /* Test if C is listed in the bitmap of charset P. */
814 #define CHARSET_LOOKUP_BITMAP(p, c) \
815 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
816 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
818 /* Return the address of end of RANGE_TABLE. COUNT is number of
819 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
820 is start of range and end of range. `* 3' is size of each start
822 #define CHARSET_RANGE_TABLE_END(range_table, count) \
823 ((range_table) + (count) * 2 * 3)
825 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
826 COUNT is number of ranges in RANGE_TABLE. */
827 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
830 re_wchar_t range_start, range_end; \
832 re_char *range_table_end \
833 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
835 for (p = (range_table); p < range_table_end; p += 2 * 3) \
837 EXTRACT_CHARACTER (range_start, p); \
838 EXTRACT_CHARACTER (range_end, p + 3); \
840 if (range_start <= (c) && (c) <= range_end) \
849 /* Test if C is in range table of CHARSET. The flag NOT is negated if
850 C is listed in it. */
851 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
854 /* Number of ranges in range table. */ \
856 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
858 EXTRACT_NUMBER_AND_INCR (count, range_table); \
859 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
863 /* If DEBUG is defined, Regex prints many voluminous messages about what
864 it is doing (if the variable `debug' is nonzero). If linked with the
865 main program in `iregex.c', you can enter patterns and strings
866 interactively. And if linked with the main program in `main.c' and
867 the other test files, you can run the already-written tests. */
871 /* We use standard I/O for debugging. */
874 /* It is useful to test things that ``must'' be true when debugging. */
877 static int debug
= -100000;
879 # define DEBUG_STATEMENT(e) e
880 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
881 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
882 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
883 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
884 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
885 if (debug > 0) print_partial_compiled_pattern (s, e)
886 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
887 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
890 /* Print the fastmap in human-readable form. */
893 print_fastmap (fastmap
)
896 unsigned was_a_range
= 0;
899 while (i
< (1 << BYTEWIDTH
))
905 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
921 /* Print a compiled pattern string in human-readable form, starting at
922 the START pointer into it and ending just before the pointer END. */
925 print_partial_compiled_pattern (start
, end
)
939 /* Loop over pattern commands. */
942 printf ("%d:\t", p
- start
);
944 switch ((re_opcode_t
) *p
++)
956 printf ("/exactn/%d", mcnt
);
966 printf ("/start_memory/%d", *p
++);
970 printf ("/stop_memory/%d", *p
++);
974 printf ("/duplicate/%d", *p
++);
984 register int c
, last
= -100;
985 register int in_range
= 0;
986 int length
= CHARSET_BITMAP_SIZE (p
- 1);
987 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
989 printf ("/charset [%s",
990 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
992 assert (p
+ *p
< pend
);
994 for (c
= 0; c
< 256; c
++)
996 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
998 /* Are we starting a range? */
999 if (last
+ 1 == c
&& ! in_range
)
1004 /* Have we broken a range? */
1005 else if (last
+ 1 != c
&& in_range
)
1024 if (has_range_table
)
1027 printf ("has-range-table");
1029 /* ??? Should print the range table; for now, just skip it. */
1030 p
+= 2; /* skip range table bits */
1031 EXTRACT_NUMBER_AND_INCR (count
, p
);
1032 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1038 printf ("/begline");
1042 printf ("/endline");
1045 case on_failure_jump
:
1046 extract_number_and_incr (&mcnt
, &p
);
1047 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
1050 case on_failure_keep_string_jump
:
1051 extract_number_and_incr (&mcnt
, &p
);
1052 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1055 case on_failure_jump_nastyloop
:
1056 extract_number_and_incr (&mcnt
, &p
);
1057 printf ("/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1060 case on_failure_jump_loop
:
1061 extract_number_and_incr (&mcnt
, &p
);
1062 printf ("/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1065 case on_failure_jump_smart
:
1066 extract_number_and_incr (&mcnt
, &p
);
1067 printf ("/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1071 extract_number_and_incr (&mcnt
, &p
);
1072 printf ("/jump to %d", p
+ mcnt
- start
);
1076 extract_number_and_incr (&mcnt
, &p
);
1077 extract_number_and_incr (&mcnt2
, &p
);
1078 printf ("/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1082 extract_number_and_incr (&mcnt
, &p
);
1083 extract_number_and_incr (&mcnt2
, &p
);
1084 printf ("/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1088 extract_number_and_incr (&mcnt
, &p
);
1089 extract_number_and_incr (&mcnt2
, &p
);
1090 printf ("/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1094 printf ("/wordbound");
1098 printf ("/notwordbound");
1102 printf ("/wordbeg");
1106 printf ("/wordend");
1109 printf ("/syntaxspec");
1111 printf ("/%d", mcnt
);
1115 printf ("/notsyntaxspec");
1117 printf ("/%d", mcnt
);
1122 printf ("/before_dot");
1130 printf ("/after_dot");
1134 printf ("/categoryspec");
1136 printf ("/%d", mcnt
);
1139 case notcategoryspec
:
1140 printf ("/notcategoryspec");
1142 printf ("/%d", mcnt
);
1155 printf ("?%d", *(p
-1));
1161 printf ("%d:\tend of pattern.\n", p
- start
);
1166 print_compiled_pattern (bufp
)
1167 struct re_pattern_buffer
*bufp
;
1169 re_char
*buffer
= bufp
->buffer
;
1171 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1172 printf ("%ld bytes used/%ld bytes allocated.\n",
1173 bufp
->used
, bufp
->allocated
);
1175 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1177 printf ("fastmap: ");
1178 print_fastmap (bufp
->fastmap
);
1181 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1182 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1183 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1184 printf ("no_sub: %d\t", bufp
->no_sub
);
1185 printf ("not_bol: %d\t", bufp
->not_bol
);
1186 printf ("not_eol: %d\t", bufp
->not_eol
);
1187 printf ("syntax: %lx\n", bufp
->syntax
);
1189 /* Perhaps we should print the translate table? */
1194 print_double_string (where
, string1
, size1
, string2
, size2
)
1207 if (FIRST_STRING_P (where
))
1209 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1210 putchar (string1
[this_char
]);
1215 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1216 putchar (string2
[this_char
]);
1220 #else /* not DEBUG */
1225 # define DEBUG_STATEMENT(e)
1226 # define DEBUG_PRINT1(x)
1227 # define DEBUG_PRINT2(x1, x2)
1228 # define DEBUG_PRINT3(x1, x2, x3)
1229 # define DEBUG_PRINT4(x1, x2, x3, x4)
1230 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1231 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1233 #endif /* not DEBUG */
1235 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1236 also be assigned to arbitrarily: each pattern buffer stores its own
1237 syntax, so it can be changed between regex compilations. */
1238 /* This has no initializer because initialized variables in Emacs
1239 become read-only after dumping. */
1240 reg_syntax_t re_syntax_options
;
1243 /* Specify the precise syntax of regexps for compilation. This provides
1244 for compatibility for various utilities which historically have
1245 different, incompatible syntaxes.
1247 The argument SYNTAX is a bit mask comprised of the various bits
1248 defined in regex.h. We return the old syntax. */
1251 re_set_syntax (syntax
)
1252 reg_syntax_t syntax
;
1254 reg_syntax_t ret
= re_syntax_options
;
1256 re_syntax_options
= syntax
;
1259 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1261 /* This table gives an error message for each of the error codes listed
1262 in regex.h. Obviously the order here has to be same as there.
1263 POSIX doesn't require that we do anything for REG_NOERROR,
1264 but why not be nice? */
1266 static const char *re_error_msgid
[] =
1268 gettext_noop ("Success"), /* REG_NOERROR */
1269 gettext_noop ("No match"), /* REG_NOMATCH */
1270 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1271 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1272 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1273 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1274 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1275 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1276 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1277 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1278 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1279 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1280 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1281 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1282 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1283 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1284 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1287 /* Avoiding alloca during matching, to placate r_alloc. */
1289 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1290 searching and matching functions should not call alloca. On some
1291 systems, alloca is implemented in terms of malloc, and if we're
1292 using the relocating allocator routines, then malloc could cause a
1293 relocation, which might (if the strings being searched are in the
1294 ralloc heap) shift the data out from underneath the regexp
1297 Here's another reason to avoid allocation: Emacs
1298 processes input from X in a signal handler; processing X input may
1299 call malloc; if input arrives while a matching routine is calling
1300 malloc, then we're scrod. But Emacs can't just block input while
1301 calling matching routines; then we don't notice interrupts when
1302 they come in. So, Emacs blocks input around all regexp calls
1303 except the matching calls, which it leaves unprotected, in the
1304 faith that they will not malloc. */
1306 /* Normally, this is fine. */
1307 #define MATCH_MAY_ALLOCATE
1309 /* When using GNU C, we are not REALLY using the C alloca, no matter
1310 what config.h may say. So don't take precautions for it. */
1315 /* The match routines may not allocate if (1) they would do it with malloc
1316 and (2) it's not safe for them to use malloc.
1317 Note that if REL_ALLOC is defined, matching would not use malloc for the
1318 failure stack, but we would still use it for the register vectors;
1319 so REL_ALLOC should not affect this. */
1320 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1321 # undef MATCH_MAY_ALLOCATE
1325 /* Failure stack declarations and macros; both re_compile_fastmap and
1326 re_match_2 use a failure stack. These have to be macros because of
1327 REGEX_ALLOCATE_STACK. */
1330 /* Approximate number of failure points for which to initially allocate space
1331 when matching. If this number is exceeded, we allocate more
1332 space, so it is not a hard limit. */
1333 #ifndef INIT_FAILURE_ALLOC
1334 # define INIT_FAILURE_ALLOC 20
1337 /* Roughly the maximum number of failure points on the stack. Would be
1338 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1339 This is a variable only so users of regex can assign to it; we never
1340 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1341 before using it, so it should probably be a byte-count instead. */
1342 # if defined MATCH_MAY_ALLOCATE
1343 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1344 whose default stack limit is 2mb. In order for a larger
1345 value to work reliably, you have to try to make it accord
1346 with the process stack limit. */
1347 size_t re_max_failures
= 40000;
1349 size_t re_max_failures
= 4000;
1352 union fail_stack_elt
1355 /* This should be the biggest `int' that's no bigger than a pointer. */
1359 typedef union fail_stack_elt fail_stack_elt_t
;
1363 fail_stack_elt_t
*stack
;
1365 size_t avail
; /* Offset of next open position. */
1366 size_t frame
; /* Offset of the cur constructed frame. */
1369 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1370 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1373 /* Define macros to initialize and free the failure stack.
1374 Do `return -2' if the alloc fails. */
1376 #ifdef MATCH_MAY_ALLOCATE
1377 # define INIT_FAIL_STACK() \
1379 fail_stack.stack = (fail_stack_elt_t *) \
1380 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1381 * sizeof (fail_stack_elt_t)); \
1383 if (fail_stack.stack == NULL) \
1386 fail_stack.size = INIT_FAILURE_ALLOC; \
1387 fail_stack.avail = 0; \
1388 fail_stack.frame = 0; \
1391 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1393 # define INIT_FAIL_STACK() \
1395 fail_stack.avail = 0; \
1396 fail_stack.frame = 0; \
1399 # define RESET_FAIL_STACK() ((void)0)
1403 /* Double the size of FAIL_STACK, up to a limit
1404 which allows approximately `re_max_failures' items.
1406 Return 1 if succeeds, and 0 if either ran out of memory
1407 allocating space for it or it was already too large.
1409 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1411 /* Factor to increase the failure stack size by
1412 when we increase it.
1413 This used to be 2, but 2 was too wasteful
1414 because the old discarded stacks added up to as much space
1415 were as ultimate, maximum-size stack. */
1416 #define FAIL_STACK_GROWTH_FACTOR 4
1418 #define GROW_FAIL_STACK(fail_stack) \
1419 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1420 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1422 : ((fail_stack).stack \
1423 = (fail_stack_elt_t *) \
1424 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1425 (fail_stack).size * sizeof (fail_stack_elt_t), \
1426 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1427 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1428 * FAIL_STACK_GROWTH_FACTOR))), \
1430 (fail_stack).stack == NULL \
1432 : ((fail_stack).size \
1433 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1434 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1435 * FAIL_STACK_GROWTH_FACTOR)) \
1436 / sizeof (fail_stack_elt_t)), \
1440 /* Push a pointer value onto the failure stack.
1441 Assumes the variable `fail_stack'. Probably should only
1442 be called from within `PUSH_FAILURE_POINT'. */
1443 #define PUSH_FAILURE_POINTER(item) \
1444 fail_stack.stack[fail_stack.avail++].pointer = (item)
1446 /* This pushes an integer-valued item onto the failure stack.
1447 Assumes the variable `fail_stack'. Probably should only
1448 be called from within `PUSH_FAILURE_POINT'. */
1449 #define PUSH_FAILURE_INT(item) \
1450 fail_stack.stack[fail_stack.avail++].integer = (item)
1452 /* Push a fail_stack_elt_t value onto the failure stack.
1453 Assumes the variable `fail_stack'. Probably should only
1454 be called from within `PUSH_FAILURE_POINT'. */
1455 #define PUSH_FAILURE_ELT(item) \
1456 fail_stack.stack[fail_stack.avail++] = (item)
1458 /* These three POP... operations complement the three PUSH... operations.
1459 All assume that `fail_stack' is nonempty. */
1460 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1461 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1462 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1464 /* Individual items aside from the registers. */
1465 #define NUM_NONREG_ITEMS 3
1467 /* Used to examine the stack (to detect infinite loops). */
1468 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1469 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1470 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1471 #define TOP_FAILURE_HANDLE() fail_stack.frame
1474 #define ENSURE_FAIL_STACK(space) \
1475 while (REMAINING_AVAIL_SLOTS <= space) { \
1476 if (!GROW_FAIL_STACK (fail_stack)) \
1478 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1479 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1482 /* Push register NUM onto the stack. */
1483 #define PUSH_FAILURE_REG(num) \
1485 char *destination; \
1486 ENSURE_FAIL_STACK(3); \
1487 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1488 num, regstart[num], regend[num]); \
1489 PUSH_FAILURE_POINTER (regstart[num]); \
1490 PUSH_FAILURE_POINTER (regend[num]); \
1491 PUSH_FAILURE_INT (num); \
1494 /* Change the counter's value to VAL, but make sure that it will
1495 be reset when backtracking. */
1496 #define PUSH_NUMBER(ptr,val) \
1498 char *destination; \
1500 ENSURE_FAIL_STACK(3); \
1501 EXTRACT_NUMBER (c, ptr); \
1502 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1503 PUSH_FAILURE_INT (c); \
1504 PUSH_FAILURE_POINTER (ptr); \
1505 PUSH_FAILURE_INT (-1); \
1506 STORE_NUMBER (ptr, val); \
1509 /* Pop a saved register off the stack. */
1510 #define POP_FAILURE_REG_OR_COUNT() \
1512 int reg = POP_FAILURE_INT (); \
1515 /* It's a counter. */ \
1516 /* Here, we discard `const', making re_match non-reentrant. */ \
1517 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1518 reg = POP_FAILURE_INT (); \
1519 STORE_NUMBER (ptr, reg); \
1520 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1524 regend[reg] = POP_FAILURE_POINTER (); \
1525 regstart[reg] = POP_FAILURE_POINTER (); \
1526 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1527 reg, regstart[reg], regend[reg]); \
1531 /* Check that we are not stuck in an infinite loop. */
1532 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1534 int failure = TOP_FAILURE_HANDLE(); \
1535 /* Check for infinite matching loops */ \
1536 while (failure > 0 && \
1537 (FAILURE_STR (failure) == string_place \
1538 || FAILURE_STR (failure) == NULL)) \
1540 assert (FAILURE_PAT (failure) >= bufp->buffer \
1541 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1542 if (FAILURE_PAT (failure) == pat_cur) \
1544 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1545 failure = NEXT_FAILURE_HANDLE(failure); \
1547 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1550 /* Push the information about the state we will need
1551 if we ever fail back to it.
1553 Requires variables fail_stack, regstart, regend and
1554 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1557 Does `return FAILURE_CODE' if runs out of memory. */
1559 #define PUSH_FAILURE_POINT(pattern, string_place) \
1561 char *destination; \
1562 /* Must be int, so when we don't save any registers, the arithmetic \
1563 of 0 + -1 isn't done as unsigned. */ \
1565 DEBUG_STATEMENT (nfailure_points_pushed++); \
1566 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1567 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1568 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1570 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1572 DEBUG_PRINT1 ("\n"); \
1574 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1575 PUSH_FAILURE_INT (fail_stack.frame); \
1577 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1578 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1579 DEBUG_PRINT1 ("'\n"); \
1580 PUSH_FAILURE_POINTER (string_place); \
1582 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1583 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1584 PUSH_FAILURE_POINTER (pattern); \
1586 /* Close the frame by moving the frame pointer past it. */ \
1587 fail_stack.frame = fail_stack.avail; \
1590 /* Estimate the size of data pushed by a typical failure stack entry.
1591 An estimate is all we need, because all we use this for
1592 is to choose a limit for how big to make the failure stack. */
1593 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1594 #define TYPICAL_FAILURE_SIZE 20
1596 /* How many items can still be added to the stack without overflowing it. */
1597 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1600 /* Pops what PUSH_FAIL_STACK pushes.
1602 We restore into the parameters, all of which should be lvalues:
1603 STR -- the saved data position.
1604 PAT -- the saved pattern position.
1605 REGSTART, REGEND -- arrays of string positions.
1607 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1608 `pend', `string1', `size1', `string2', and `size2'. */
1610 #define POP_FAILURE_POINT(str, pat) \
1612 assert (!FAIL_STACK_EMPTY ()); \
1614 /* Remove failure points and point to how many regs pushed. */ \
1615 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1616 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1617 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1619 /* Pop the saved registers. */ \
1620 while (fail_stack.frame < fail_stack.avail) \
1621 POP_FAILURE_REG_OR_COUNT (); \
1623 pat = POP_FAILURE_POINTER (); \
1624 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1625 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1627 /* If the saved string location is NULL, it came from an \
1628 on_failure_keep_string_jump opcode, and we want to throw away the \
1629 saved NULL, thus retaining our current position in the string. */ \
1630 str = POP_FAILURE_POINTER (); \
1631 DEBUG_PRINT2 (" Popping string %p: `", str); \
1632 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1633 DEBUG_PRINT1 ("'\n"); \
1635 fail_stack.frame = POP_FAILURE_INT (); \
1636 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1638 assert (fail_stack.avail >= 0); \
1639 assert (fail_stack.frame <= fail_stack.avail); \
1641 DEBUG_STATEMENT (nfailure_points_popped++); \
1642 } while (0) /* POP_FAILURE_POINT */
1646 /* Registers are set to a sentinel when they haven't yet matched. */
1647 #define REG_UNSET(e) ((e) == NULL)
1649 /* Subroutine declarations and macros for regex_compile. */
1651 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1652 reg_syntax_t syntax
,
1653 struct re_pattern_buffer
*bufp
));
1654 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1655 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1656 int arg1
, int arg2
));
1657 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1658 int arg
, unsigned char *end
));
1659 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1660 int arg1
, int arg2
, unsigned char *end
));
1661 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1663 reg_syntax_t syntax
));
1664 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1666 reg_syntax_t syntax
));
1667 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1668 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1669 char *fastmap
, const int multibyte
));
1671 /* Fetch the next character in the uncompiled pattern---translating it
1673 #define PATFETCH(c) \
1677 MAKE_CHAR_MULTIBYTE (c); \
1678 c = TRANSLATE (c); \
1681 /* Fetch the next character in the uncompiled pattern, with no
1683 #define PATFETCH_RAW(c) \
1686 if (p == pend) return REG_EEND; \
1687 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1692 /* If `translate' is non-null, return translate[D], else just D. We
1693 cast the subscript to translate because some data is declared as
1694 `char *', to avoid warnings when a string constant is passed. But
1695 when we use a character as a subscript we must make it unsigned. */
1697 # define TRANSLATE(d) \
1698 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1702 /* Macros for outputting the compiled pattern into `buffer'. */
1704 /* If the buffer isn't allocated when it comes in, use this. */
1705 #define INIT_BUF_SIZE 32
1707 /* Make sure we have at least N more bytes of space in buffer. */
1708 #define GET_BUFFER_SPACE(n) \
1709 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1712 /* Make sure we have one more byte of buffer space and then add C to it. */
1713 #define BUF_PUSH(c) \
1715 GET_BUFFER_SPACE (1); \
1716 *b++ = (unsigned char) (c); \
1720 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1721 #define BUF_PUSH_2(c1, c2) \
1723 GET_BUFFER_SPACE (2); \
1724 *b++ = (unsigned char) (c1); \
1725 *b++ = (unsigned char) (c2); \
1729 /* As with BUF_PUSH_2, except for three bytes. */
1730 #define BUF_PUSH_3(c1, c2, c3) \
1732 GET_BUFFER_SPACE (3); \
1733 *b++ = (unsigned char) (c1); \
1734 *b++ = (unsigned char) (c2); \
1735 *b++ = (unsigned char) (c3); \
1739 /* Store a jump with opcode OP at LOC to location TO. We store a
1740 relative address offset by the three bytes the jump itself occupies. */
1741 #define STORE_JUMP(op, loc, to) \
1742 store_op1 (op, loc, (to) - (loc) - 3)
1744 /* Likewise, for a two-argument jump. */
1745 #define STORE_JUMP2(op, loc, to, arg) \
1746 store_op2 (op, loc, (to) - (loc) - 3, arg)
1748 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1749 #define INSERT_JUMP(op, loc, to) \
1750 insert_op1 (op, loc, (to) - (loc) - 3, b)
1752 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1753 #define INSERT_JUMP2(op, loc, to, arg) \
1754 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1757 /* This is not an arbitrary limit: the arguments which represent offsets
1758 into the pattern are two bytes long. So if 2^16 bytes turns out to
1759 be too small, many things would have to change. */
1760 /* Any other compiler which, like MSC, has allocation limit below 2^16
1761 bytes will have to use approach similar to what was done below for
1762 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1763 reallocating to 0 bytes. Such thing is not going to work too well.
1764 You have been warned!! */
1765 #if defined _MSC_VER && !defined WIN32
1766 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1767 # define MAX_BUF_SIZE 65500L
1769 # define MAX_BUF_SIZE (1L << 16)
1772 /* Extend the buffer by twice its current size via realloc and
1773 reset the pointers that pointed into the old block to point to the
1774 correct places in the new one. If extending the buffer results in it
1775 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1776 #if __BOUNDED_POINTERS__
1777 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1778 # define MOVE_BUFFER_POINTER(P) \
1779 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1780 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1783 SET_HIGH_BOUND (b); \
1784 SET_HIGH_BOUND (begalt); \
1785 if (fixup_alt_jump) \
1786 SET_HIGH_BOUND (fixup_alt_jump); \
1788 SET_HIGH_BOUND (laststart); \
1789 if (pending_exact) \
1790 SET_HIGH_BOUND (pending_exact); \
1793 # define MOVE_BUFFER_POINTER(P) (P) += incr
1794 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1796 #define EXTEND_BUFFER() \
1798 re_char *old_buffer = bufp->buffer; \
1799 if (bufp->allocated == MAX_BUF_SIZE) \
1801 bufp->allocated <<= 1; \
1802 if (bufp->allocated > MAX_BUF_SIZE) \
1803 bufp->allocated = MAX_BUF_SIZE; \
1804 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1805 if (bufp->buffer == NULL) \
1806 return REG_ESPACE; \
1807 /* If the buffer moved, move all the pointers into it. */ \
1808 if (old_buffer != bufp->buffer) \
1810 int incr = bufp->buffer - old_buffer; \
1811 MOVE_BUFFER_POINTER (b); \
1812 MOVE_BUFFER_POINTER (begalt); \
1813 if (fixup_alt_jump) \
1814 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1816 MOVE_BUFFER_POINTER (laststart); \
1817 if (pending_exact) \
1818 MOVE_BUFFER_POINTER (pending_exact); \
1820 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1824 /* Since we have one byte reserved for the register number argument to
1825 {start,stop}_memory, the maximum number of groups we can report
1826 things about is what fits in that byte. */
1827 #define MAX_REGNUM 255
1829 /* But patterns can have more than `MAX_REGNUM' registers. We just
1830 ignore the excess. */
1831 typedef unsigned regnum_t
;
1834 /* Macros for the compile stack. */
1836 /* Since offsets can go either forwards or backwards, this type needs to
1837 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1838 /* int may be not enough when sizeof(int) == 2. */
1839 typedef long pattern_offset_t
;
1843 pattern_offset_t begalt_offset
;
1844 pattern_offset_t fixup_alt_jump
;
1845 pattern_offset_t laststart_offset
;
1847 } compile_stack_elt_t
;
1852 compile_stack_elt_t
*stack
;
1854 unsigned avail
; /* Offset of next open position. */
1855 } compile_stack_type
;
1858 #define INIT_COMPILE_STACK_SIZE 32
1860 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1861 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1863 /* The next available element. */
1864 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1867 /* Structure to manage work area for range table. */
1868 struct range_table_work_area
1870 int *table
; /* actual work area. */
1871 int allocated
; /* allocated size for work area in bytes. */
1872 int used
; /* actually used size in words. */
1873 int bits
; /* flag to record character classes */
1876 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1877 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1879 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1881 (work_area).allocated += 16 * sizeof (int); \
1882 if ((work_area).table) \
1884 = (int *) realloc ((work_area).table, (work_area).allocated); \
1887 = (int *) malloc ((work_area).allocated); \
1888 if ((work_area).table == 0) \
1889 FREE_STACK_RETURN (REG_ESPACE); \
1893 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1894 (work_area).bits |= (bit)
1896 /* Bits used to implement the multibyte-part of the various character classes
1897 such as [:alnum:] in a charset's range table. */
1898 #define BIT_WORD 0x1
1899 #define BIT_LOWER 0x2
1900 #define BIT_PUNCT 0x4
1901 #define BIT_SPACE 0x8
1902 #define BIT_UPPER 0x10
1903 #define BIT_MULTIBYTE 0x20
1905 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1906 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1908 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1909 (work_area).table[(work_area).used++] = (range_start); \
1910 (work_area).table[(work_area).used++] = (range_end); \
1913 /* Free allocated memory for WORK_AREA. */
1914 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1916 if ((work_area).table) \
1917 free ((work_area).table); \
1920 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1921 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1922 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1923 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1926 /* Set the bit for character C in a list. */
1927 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1932 /* It is better to implement this jumbo macro by a function, but it's
1933 not that easy because macros called within it assumes various
1934 variables being defined. */
1936 #define HANDLE_UNIBYTE_RANGE(work_area, c1, c2) \
1938 int char_table[257]; \
1941 char_table[(c1) - 1] = -2; /* head sentinel */ \
1942 for (i = (c1); i <= (c2); i++) \
1943 char_table[i] = TRANSLATE (unibyte_char_to_multibyte (i)); \
1944 char_table[i] = MAX_CHAR + 2; /* tail sentinel */ \
1946 /* As the number of data is small (at most 128) and we can expect \
1947 that data in char_table are mostly sorted, we use fairly simple \
1948 `insertion sort'. */ \
1949 for (i = (c1) + 1; i <= (c2); i++) \
1951 c = char_table[i]; \
1953 while (char_table[j - 1] > c) \
1954 char_table[j] = char_table[j - 1], j--; \
1955 char_table[j] = c; \
1958 for (i = (c1); i <= (c2); i++) \
1960 c = char_table[i]; \
1961 if (! IS_REAL_ASCII (c)) \
1967 c = char_table[i]; \
1968 for (j = i + 1; j <= (c2); j++) \
1969 if (char_table[j] - c != j - i) \
1971 SET_RANGE_TABLE_WORK_AREA ((work_area), c, char_table[j - 1]); \
1978 /* Get the next unsigned number in the uncompiled pattern. */
1979 #define GET_UNSIGNED_NUMBER(num) \
1980 do { if (p != pend) \
1983 while ('0' <= c && c <= '9') \
1987 num = num * 10 + c - '0'; \
1995 #if WIDE_CHAR_SUPPORT
1996 /* The GNU C library provides support for user-defined character classes
1997 and the functions from ISO C amendement 1. */
1998 # ifdef CHARCLASS_NAME_MAX
1999 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2001 /* This shouldn't happen but some implementation might still have this
2002 problem. Use a reasonable default value. */
2003 # define CHAR_CLASS_MAX_LENGTH 256
2005 typedef wctype_t re_wctype_t
;
2006 typedef wchar_t re_wchar_t
;
2007 # define re_wctype wctype
2008 # define re_iswctype iswctype
2009 # define re_wctype_to_bit(cc) 0
2011 # define CHAR_CLASS_MAX_LENGTH 9 /* Namely, `multibyte'. */
2014 /* Character classes. */
2015 typedef enum { RECC_ERROR
= 0,
2016 RECC_ALNUM
, RECC_ALPHA
, RECC_WORD
,
2017 RECC_GRAPH
, RECC_PRINT
,
2018 RECC_LOWER
, RECC_UPPER
,
2019 RECC_PUNCT
, RECC_CNTRL
,
2020 RECC_DIGIT
, RECC_XDIGIT
,
2021 RECC_BLANK
, RECC_SPACE
,
2022 RECC_MULTIBYTE
, RECC_NONASCII
,
2023 RECC_ASCII
, RECC_UNIBYTE
2026 typedef int re_wchar_t
;
2028 /* Map a string to the char class it names (if any). */
2033 const char *string
= str
;
2034 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2035 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2036 else if (STREQ (string
, "word")) return RECC_WORD
;
2037 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2038 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2039 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2040 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2041 else if (STREQ (string
, "print")) return RECC_PRINT
;
2042 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2043 else if (STREQ (string
, "space")) return RECC_SPACE
;
2044 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2045 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2046 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2047 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2048 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2049 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2050 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2054 /* True iff CH is in the char class CC. */
2056 re_iswctype (ch
, cc
)
2062 case RECC_ALNUM
: return ISALNUM (ch
);
2063 case RECC_ALPHA
: return ISALPHA (ch
);
2064 case RECC_BLANK
: return ISBLANK (ch
);
2065 case RECC_CNTRL
: return ISCNTRL (ch
);
2066 case RECC_DIGIT
: return ISDIGIT (ch
);
2067 case RECC_GRAPH
: return ISGRAPH (ch
);
2068 case RECC_LOWER
: return ISLOWER (ch
);
2069 case RECC_PRINT
: return ISPRINT (ch
);
2070 case RECC_PUNCT
: return ISPUNCT (ch
);
2071 case RECC_SPACE
: return ISSPACE (ch
);
2072 case RECC_UPPER
: return ISUPPER (ch
);
2073 case RECC_XDIGIT
: return ISXDIGIT (ch
);
2074 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2075 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2076 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2077 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2078 case RECC_WORD
: return ISWORD (ch
);
2079 case RECC_ERROR
: return false;
2085 /* Return a bit-pattern to use in the range-table bits to match multibyte
2086 chars of class CC. */
2088 re_wctype_to_bit (cc
)
2093 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2094 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2095 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2096 case RECC_LOWER
: return BIT_LOWER
;
2097 case RECC_UPPER
: return BIT_UPPER
;
2098 case RECC_PUNCT
: return BIT_PUNCT
;
2099 case RECC_SPACE
: return BIT_SPACE
;
2100 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2101 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2108 /* Explicit quit checking is only used on NTemacs. */
2109 #if defined WINDOWSNT && defined emacs && defined QUIT
2110 extern int immediate_quit
;
2111 # define IMMEDIATE_QUIT_CHECK \
2113 if (immediate_quit) QUIT; \
2116 # define IMMEDIATE_QUIT_CHECK ((void)0)
2119 #ifndef MATCH_MAY_ALLOCATE
2121 /* If we cannot allocate large objects within re_match_2_internal,
2122 we make the fail stack and register vectors global.
2123 The fail stack, we grow to the maximum size when a regexp
2125 The register vectors, we adjust in size each time we
2126 compile a regexp, according to the number of registers it needs. */
2128 static fail_stack_type fail_stack
;
2130 /* Size with which the following vectors are currently allocated.
2131 That is so we can make them bigger as needed,
2132 but never make them smaller. */
2133 static int regs_allocated_size
;
2135 static re_char
** regstart
, ** regend
;
2136 static re_char
**best_regstart
, **best_regend
;
2138 /* Make the register vectors big enough for NUM_REGS registers,
2139 but don't make them smaller. */
2142 regex_grow_registers (num_regs
)
2145 if (num_regs
> regs_allocated_size
)
2147 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2148 RETALLOC_IF (regend
, num_regs
, re_char
*);
2149 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2150 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2152 regs_allocated_size
= num_regs
;
2156 #endif /* not MATCH_MAY_ALLOCATE */
2158 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2162 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2163 Returns one of error codes defined in `regex.h', or zero for success.
2165 Assumes the `allocated' (and perhaps `buffer') and `translate'
2166 fields are set in BUFP on entry.
2168 If it succeeds, results are put in BUFP (if it returns an error, the
2169 contents of BUFP are undefined):
2170 `buffer' is the compiled pattern;
2171 `syntax' is set to SYNTAX;
2172 `used' is set to the length of the compiled pattern;
2173 `fastmap_accurate' is zero;
2174 `re_nsub' is the number of subexpressions in PATTERN;
2175 `not_bol' and `not_eol' are zero;
2177 The `fastmap' field is neither examined nor set. */
2179 /* Insert the `jump' from the end of last alternative to "here".
2180 The space for the jump has already been allocated. */
2181 #define FIXUP_ALT_JUMP() \
2183 if (fixup_alt_jump) \
2184 STORE_JUMP (jump, fixup_alt_jump, b); \
2188 /* Return, freeing storage we allocated. */
2189 #define FREE_STACK_RETURN(value) \
2191 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2192 free (compile_stack.stack); \
2196 static reg_errcode_t
2197 regex_compile (pattern
, size
, syntax
, bufp
)
2200 reg_syntax_t syntax
;
2201 struct re_pattern_buffer
*bufp
;
2203 /* We fetch characters from PATTERN here. */
2204 register re_wchar_t c
, c1
;
2206 /* A random temporary spot in PATTERN. */
2209 /* Points to the end of the buffer, where we should append. */
2210 register unsigned char *b
;
2212 /* Keeps track of unclosed groups. */
2213 compile_stack_type compile_stack
;
2215 /* Points to the current (ending) position in the pattern. */
2217 /* `const' makes AIX compiler fail. */
2218 unsigned char *p
= pattern
;
2220 re_char
*p
= pattern
;
2222 re_char
*pend
= pattern
+ size
;
2224 /* How to translate the characters in the pattern. */
2225 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2227 /* Address of the count-byte of the most recently inserted `exactn'
2228 command. This makes it possible to tell if a new exact-match
2229 character can be added to that command or if the character requires
2230 a new `exactn' command. */
2231 unsigned char *pending_exact
= 0;
2233 /* Address of start of the most recently finished expression.
2234 This tells, e.g., postfix * where to find the start of its
2235 operand. Reset at the beginning of groups and alternatives. */
2236 unsigned char *laststart
= 0;
2238 /* Address of beginning of regexp, or inside of last group. */
2239 unsigned char *begalt
;
2241 /* Place in the uncompiled pattern (i.e., the {) to
2242 which to go back if the interval is invalid. */
2243 re_char
*beg_interval
;
2245 /* Address of the place where a forward jump should go to the end of
2246 the containing expression. Each alternative of an `or' -- except the
2247 last -- ends with a forward jump of this sort. */
2248 unsigned char *fixup_alt_jump
= 0;
2250 /* Counts open-groups as they are encountered. Remembered for the
2251 matching close-group on the compile stack, so the same register
2252 number is put in the stop_memory as the start_memory. */
2253 regnum_t regnum
= 0;
2255 /* Work area for range table of charset. */
2256 struct range_table_work_area range_table_work
;
2258 /* If the object matched can contain multibyte characters. */
2259 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2263 DEBUG_PRINT1 ("\nCompiling pattern: ");
2266 unsigned debug_count
;
2268 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2269 putchar (pattern
[debug_count
]);
2274 /* Initialize the compile stack. */
2275 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2276 if (compile_stack
.stack
== NULL
)
2279 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2280 compile_stack
.avail
= 0;
2282 range_table_work
.table
= 0;
2283 range_table_work
.allocated
= 0;
2285 /* Initialize the pattern buffer. */
2286 bufp
->syntax
= syntax
;
2287 bufp
->fastmap_accurate
= 0;
2288 bufp
->not_bol
= bufp
->not_eol
= 0;
2290 /* Set `used' to zero, so that if we return an error, the pattern
2291 printer (for debugging) will think there's no pattern. We reset it
2295 /* Always count groups, whether or not bufp->no_sub is set. */
2298 #if !defined emacs && !defined SYNTAX_TABLE
2299 /* Initialize the syntax table. */
2300 init_syntax_once ();
2303 if (bufp
->allocated
== 0)
2306 { /* If zero allocated, but buffer is non-null, try to realloc
2307 enough space. This loses if buffer's address is bogus, but
2308 that is the user's responsibility. */
2309 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2312 { /* Caller did not allocate a buffer. Do it for them. */
2313 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2315 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2317 bufp
->allocated
= INIT_BUF_SIZE
;
2320 begalt
= b
= bufp
->buffer
;
2322 /* Loop through the uncompiled pattern until we're at the end. */
2331 if ( /* If at start of pattern, it's an operator. */
2333 /* If context independent, it's an operator. */
2334 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2335 /* Otherwise, depends on what's come before. */
2336 || at_begline_loc_p (pattern
, p
, syntax
))
2337 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2346 if ( /* If at end of pattern, it's an operator. */
2348 /* If context independent, it's an operator. */
2349 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2350 /* Otherwise, depends on what's next. */
2351 || at_endline_loc_p (p
, pend
, syntax
))
2352 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2361 if ((syntax
& RE_BK_PLUS_QM
)
2362 || (syntax
& RE_LIMITED_OPS
))
2366 /* If there is no previous pattern... */
2369 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2370 FREE_STACK_RETURN (REG_BADRPT
);
2371 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2376 /* 1 means zero (many) matches is allowed. */
2377 boolean zero_times_ok
= 0, many_times_ok
= 0;
2380 /* If there is a sequence of repetition chars, collapse it
2381 down to just one (the right one). We can't combine
2382 interval operators with these because of, e.g., `a{2}*',
2383 which should only match an even number of `a's. */
2387 if ((syntax
& RE_FRUGAL
)
2388 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2392 zero_times_ok
|= c
!= '+';
2393 many_times_ok
|= c
!= '?';
2399 || (!(syntax
& RE_BK_PLUS_QM
)
2400 && (*p
== '+' || *p
== '?')))
2402 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2405 FREE_STACK_RETURN (REG_EESCAPE
);
2406 if (p
[1] == '+' || p
[1] == '?')
2407 PATFETCH_RAW (c
); /* Gobble up the backslash. */
2413 /* If we get here, we found another repeat character. */
2417 /* Star, etc. applied to an empty pattern is equivalent
2418 to an empty pattern. */
2419 if (!laststart
|| laststart
== b
)
2422 /* Now we know whether or not zero matches is allowed
2423 and also whether or not two or more matches is allowed. */
2428 boolean simple
= skip_one_char (laststart
) == b
;
2429 unsigned int startoffset
= 0;
2431 /* Check if the loop can match the empty string. */
2432 (simple
|| !analyse_first (laststart
, b
, NULL
, 0)) ?
2433 on_failure_jump
: on_failure_jump_loop
;
2434 assert (skip_one_char (laststart
) <= b
);
2436 if (!zero_times_ok
&& simple
)
2437 { /* Since simple * loops can be made faster by using
2438 on_failure_keep_string_jump, we turn simple P+
2439 into PP* if P is simple. */
2440 unsigned char *p1
, *p2
;
2441 startoffset
= b
- laststart
;
2442 GET_BUFFER_SPACE (startoffset
);
2443 p1
= b
; p2
= laststart
;
2449 GET_BUFFER_SPACE (6);
2452 STORE_JUMP (ofj
, b
, b
+ 6);
2454 /* Simple * loops can use on_failure_keep_string_jump
2455 depending on what follows. But since we don't know
2456 that yet, we leave the decision up to
2457 on_failure_jump_smart. */
2458 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2459 laststart
+ startoffset
, b
+ 6);
2461 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2466 /* A simple ? pattern. */
2467 assert (zero_times_ok
);
2468 GET_BUFFER_SPACE (3);
2469 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2473 else /* not greedy */
2474 { /* I wish the greedy and non-greedy cases could be merged. */
2476 GET_BUFFER_SPACE (7); /* We might use less. */
2479 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2481 /* The non-greedy multiple match looks like a repeat..until:
2482 we only need a conditional jump at the end of the loop */
2483 if (emptyp
) BUF_PUSH (no_op
);
2484 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2485 : on_failure_jump
, b
, laststart
);
2489 /* The repeat...until naturally matches one or more.
2490 To also match zero times, we need to first jump to
2491 the end of the loop (its conditional jump). */
2492 INSERT_JUMP (jump
, laststart
, b
);
2498 /* non-greedy a?? */
2499 INSERT_JUMP (jump
, laststart
, b
+ 3);
2501 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2518 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2520 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2522 /* Ensure that we have enough space to push a charset: the
2523 opcode, the length count, and the bitset; 34 bytes in all. */
2524 GET_BUFFER_SPACE (34);
2528 /* We test `*p == '^' twice, instead of using an if
2529 statement, so we only need one BUF_PUSH. */
2530 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2534 /* Remember the first position in the bracket expression. */
2537 /* Push the number of bytes in the bitmap. */
2538 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2540 /* Clear the whole map. */
2541 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2543 /* charset_not matches newline according to a syntax bit. */
2544 if ((re_opcode_t
) b
[-2] == charset_not
2545 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2546 SET_LIST_BIT ('\n');
2548 /* Read in characters and ranges, setting map bits. */
2551 boolean escaped_char
= false;
2552 const unsigned char *p2
= p
;
2554 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2558 /* \ might escape characters inside [...] and [^...]. */
2559 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2561 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2564 escaped_char
= true;
2568 /* Could be the end of the bracket expression. If it's
2569 not (i.e., when the bracket expression is `[]' so
2570 far), the ']' character bit gets set way below. */
2571 if (c
== ']' && p2
!= p1
)
2575 /* What should we do for the character which is
2576 greater than 0x7F, but not BASE_LEADING_CODE_P?
2579 /* See if we're at the beginning of a possible character
2582 if (!escaped_char
&&
2583 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2585 /* Leave room for the null. */
2586 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2587 const unsigned char *class_beg
;
2593 /* If pattern is `[[:'. */
2594 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2599 if ((c
== ':' && *p
== ']') || p
== pend
)
2601 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2604 /* This is in any case an invalid class name. */
2609 /* If isn't a word bracketed by `[:' and `:]':
2610 undo the ending character, the letters, and
2611 leave the leading `:' and `[' (but set bits for
2613 if (c
== ':' && *p
== ']')
2618 cc
= re_wctype (str
);
2621 FREE_STACK_RETURN (REG_ECTYPE
);
2623 /* Throw away the ] at the end of the character
2627 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2629 /* Most character classes in a multibyte match
2630 just set a flag. Exceptions are is_blank,
2631 is_digit, is_cntrl, and is_xdigit, since
2632 they can only match ASCII characters. We
2633 don't need to handle them for multibyte.
2634 They are distinguished by a negative wctype.
2635 We need this only for Emacs. */
2637 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work
,
2638 re_wctype_to_bit (cc
));
2641 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ++ch
)
2643 MAKE_CHAR_MULTIBYTE (ch
);
2644 ch
= TRANSLATE (ch
);
2645 if (IS_REAL_ASCII (ch
)
2646 & re_iswctype (btowc (ch
), cc
))
2650 /* Repeat the loop. */
2655 /* Go back to right after the "[:". */
2659 /* Because the `:' may starts the range, we
2660 can't simply set bit and repeat the loop.
2661 Instead, just set it to C and handle below. */
2666 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2669 /* Discard the `-'. */
2672 /* Fetch the character which ends the range. */
2678 c1
= TRANSLATE (c1
);
2679 if (! IS_REAL_ASCII (c1
))
2681 SET_RANGE_TABLE_WORK_AREA (range_table_work
,
2688 if (! IS_REAL_ASCII (c1
))
2690 int c2
= MAX (c
, 128);
2692 HANDLE_UNIBYTE_RANGE (range_table_work
, c2
, c1
);
2700 /* Range from C to C. */
2702 MAKE_CHAR_MULTIBYTE (c
);
2704 if (IS_REAL_ASCII (c
))
2708 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c
);
2709 c
= -1; /* Suppress setting bitmap. */
2713 /* Set the range into bitmap */
2716 re_wchar_t this_char
;
2717 int range_start
= c
, range_end
= c1
;
2719 /* If the start is after the end, the range is empty. */
2720 if (range_start
> range_end
)
2722 if (syntax
& RE_NO_EMPTY_RANGES
)
2723 FREE_STACK_RETURN (REG_ERANGE
);
2724 /* Else, repeat the loop. */
2728 for (this_char
= range_start
; this_char
<= range_end
;
2730 SET_LIST_BIT (TRANSLATE (this_char
));
2735 /* Discard any (non)matching list bytes that are all 0 at the
2736 end of the map. Decrease the map-length byte too. */
2737 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2741 /* Build real range table from work area. */
2742 if (RANGE_TABLE_WORK_USED (range_table_work
)
2743 || RANGE_TABLE_WORK_BITS (range_table_work
))
2746 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
2748 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2749 bytes for flags, two for COUNT, and three bytes for
2751 GET_BUFFER_SPACE (4 + used
* 3);
2753 /* Indicate the existence of range table. */
2754 laststart
[1] |= 0x80;
2756 /* Store the character class flag bits into the range table.
2757 If not in emacs, these flag bits are always 0. */
2758 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
2759 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
2761 STORE_NUMBER_AND_INCR (b
, used
/ 2);
2762 for (i
= 0; i
< used
; i
++)
2763 STORE_CHARACTER_AND_INCR
2764 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
2771 if (syntax
& RE_NO_BK_PARENS
)
2778 if (syntax
& RE_NO_BK_PARENS
)
2785 if (syntax
& RE_NEWLINE_ALT
)
2792 if (syntax
& RE_NO_BK_VBAR
)
2799 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2800 goto handle_interval
;
2806 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2808 /* Do not translate the character after the \, so that we can
2809 distinguish, e.g., \B from \b, even if we normally would
2810 translate, e.g., B to b. */
2816 if (syntax
& RE_NO_BK_PARENS
)
2817 goto normal_backslash
;
2824 /* Look for a special (?...) construct */
2825 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
2827 PATFETCH_RAW (c
); /* Gobble up the '?'. */
2831 case ':': shy
= 1; break;
2833 /* Only (?:...) is supported right now. */
2834 FREE_STACK_RETURN (REG_BADPAT
);
2845 if (COMPILE_STACK_FULL
)
2847 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
2848 compile_stack_elt_t
);
2849 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
2851 compile_stack
.size
<<= 1;
2854 /* These are the values to restore when we hit end of this
2855 group. They are all relative offsets, so that if the
2856 whole pattern moves because of realloc, they will still
2858 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
2859 COMPILE_STACK_TOP
.fixup_alt_jump
2860 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
2861 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
2862 COMPILE_STACK_TOP
.regnum
= shy
? -regnum
: regnum
;
2865 start_memory for groups beyond the last one we can
2866 represent in the compiled pattern. */
2867 if (regnum
<= MAX_REGNUM
&& !shy
)
2868 BUF_PUSH_2 (start_memory
, regnum
);
2870 compile_stack
.avail
++;
2875 /* If we've reached MAX_REGNUM groups, then this open
2876 won't actually generate any code, so we'll have to
2877 clear pending_exact explicitly. */
2883 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
2885 if (COMPILE_STACK_EMPTY
)
2887 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2888 goto normal_backslash
;
2890 FREE_STACK_RETURN (REG_ERPAREN
);
2896 /* See similar code for backslashed left paren above. */
2897 if (COMPILE_STACK_EMPTY
)
2899 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2902 FREE_STACK_RETURN (REG_ERPAREN
);
2905 /* Since we just checked for an empty stack above, this
2906 ``can't happen''. */
2907 assert (compile_stack
.avail
!= 0);
2909 /* We don't just want to restore into `regnum', because
2910 later groups should continue to be numbered higher,
2911 as in `(ab)c(de)' -- the second group is #2. */
2912 regnum_t this_group_regnum
;
2914 compile_stack
.avail
--;
2915 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
2917 = COMPILE_STACK_TOP
.fixup_alt_jump
2918 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
2920 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
2921 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
2922 /* If we've reached MAX_REGNUM groups, then this open
2923 won't actually generate any code, so we'll have to
2924 clear pending_exact explicitly. */
2927 /* We're at the end of the group, so now we know how many
2928 groups were inside this one. */
2929 if (this_group_regnum
<= MAX_REGNUM
&& this_group_regnum
> 0)
2930 BUF_PUSH_2 (stop_memory
, this_group_regnum
);
2935 case '|': /* `\|'. */
2936 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2937 goto normal_backslash
;
2939 if (syntax
& RE_LIMITED_OPS
)
2942 /* Insert before the previous alternative a jump which
2943 jumps to this alternative if the former fails. */
2944 GET_BUFFER_SPACE (3);
2945 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
2949 /* The alternative before this one has a jump after it
2950 which gets executed if it gets matched. Adjust that
2951 jump so it will jump to this alternative's analogous
2952 jump (put in below, which in turn will jump to the next
2953 (if any) alternative's such jump, etc.). The last such
2954 jump jumps to the correct final destination. A picture:
2960 If we are at `b', then fixup_alt_jump right now points to a
2961 three-byte space after `a'. We'll put in the jump, set
2962 fixup_alt_jump to right after `b', and leave behind three
2963 bytes which we'll fill in when we get to after `c'. */
2967 /* Mark and leave space for a jump after this alternative,
2968 to be filled in later either by next alternative or
2969 when know we're at the end of a series of alternatives. */
2971 GET_BUFFER_SPACE (3);
2980 /* If \{ is a literal. */
2981 if (!(syntax
& RE_INTERVALS
)
2982 /* If we're at `\{' and it's not the open-interval
2984 || (syntax
& RE_NO_BK_BRACES
))
2985 goto normal_backslash
;
2989 /* If got here, then the syntax allows intervals. */
2991 /* At least (most) this many matches must be made. */
2992 int lower_bound
= 0, upper_bound
= -1;
2997 FREE_STACK_RETURN (REG_EBRACE
);
2999 GET_UNSIGNED_NUMBER (lower_bound
);
3002 GET_UNSIGNED_NUMBER (upper_bound
);
3004 /* Interval such as `{1}' => match exactly once. */
3005 upper_bound
= lower_bound
;
3007 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3008 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3009 FREE_STACK_RETURN (REG_BADBR
);
3011 if (!(syntax
& RE_NO_BK_BRACES
))
3014 FREE_STACK_RETURN (REG_BADBR
);
3020 FREE_STACK_RETURN (REG_BADBR
);
3022 /* We just parsed a valid interval. */
3024 /* If it's invalid to have no preceding re. */
3027 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3028 FREE_STACK_RETURN (REG_BADRPT
);
3029 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3032 goto unfetch_interval
;
3035 if (upper_bound
== 0)
3036 /* If the upper bound is zero, just drop the sub pattern
3039 else if (lower_bound
== 1 && upper_bound
== 1)
3040 /* Just match it once: nothing to do here. */
3043 /* Otherwise, we have a nontrivial interval. When
3044 we're all done, the pattern will look like:
3045 set_number_at <jump count> <upper bound>
3046 set_number_at <succeed_n count> <lower bound>
3047 succeed_n <after jump addr> <succeed_n count>
3049 jump_n <succeed_n addr> <jump count>
3050 (The upper bound and `jump_n' are omitted if
3051 `upper_bound' is 1, though.) */
3053 { /* If the upper bound is > 1, we need to insert
3054 more at the end of the loop. */
3055 unsigned int nbytes
= (upper_bound
< 0 ? 3
3056 : upper_bound
> 1 ? 5 : 0);
3057 unsigned int startoffset
= 0;
3059 GET_BUFFER_SPACE (20); /* We might use less. */
3061 if (lower_bound
== 0)
3063 /* A succeed_n that starts with 0 is really a
3064 a simple on_failure_jump_loop. */
3065 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3071 /* Initialize lower bound of the `succeed_n', even
3072 though it will be set during matching by its
3073 attendant `set_number_at' (inserted next),
3074 because `re_compile_fastmap' needs to know.
3075 Jump to the `jump_n' we might insert below. */
3076 INSERT_JUMP2 (succeed_n
, laststart
,
3081 /* Code to initialize the lower bound. Insert
3082 before the `succeed_n'. The `5' is the last two
3083 bytes of this `set_number_at', plus 3 bytes of
3084 the following `succeed_n'. */
3085 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3090 if (upper_bound
< 0)
3092 /* A negative upper bound stands for infinity,
3093 in which case it degenerates to a plain jump. */
3094 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3097 else if (upper_bound
> 1)
3098 { /* More than one repetition is allowed, so
3099 append a backward jump to the `succeed_n'
3100 that starts this interval.
3102 When we've reached this during matching,
3103 we'll have matched the interval once, so
3104 jump back only `upper_bound - 1' times. */
3105 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3109 /* The location we want to set is the second
3110 parameter of the `jump_n'; that is `b-2' as
3111 an absolute address. `laststart' will be
3112 the `set_number_at' we're about to insert;
3113 `laststart+3' the number to set, the source
3114 for the relative address. But we are
3115 inserting into the middle of the pattern --
3116 so everything is getting moved up by 5.
3117 Conclusion: (b - 2) - (laststart + 3) + 5,
3118 i.e., b - laststart.
3120 We insert this at the beginning of the loop
3121 so that if we fail during matching, we'll
3122 reinitialize the bounds. */
3123 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3124 upper_bound
- 1, b
);
3129 beg_interval
= NULL
;
3134 /* If an invalid interval, match the characters as literals. */
3135 assert (beg_interval
);
3137 beg_interval
= NULL
;
3139 /* normal_char and normal_backslash need `c'. */
3142 if (!(syntax
& RE_NO_BK_BRACES
))
3144 assert (p
> pattern
&& p
[-1] == '\\');
3145 goto normal_backslash
;
3151 /* There is no way to specify the before_dot and after_dot
3152 operators. rms says this is ok. --karl */
3160 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3166 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3172 BUF_PUSH_2 (categoryspec
, c
);
3178 BUF_PUSH_2 (notcategoryspec
, c
);
3184 if (syntax
& RE_NO_GNU_OPS
)
3187 BUF_PUSH_2 (syntaxspec
, Sword
);
3192 if (syntax
& RE_NO_GNU_OPS
)
3195 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3200 if (syntax
& RE_NO_GNU_OPS
)
3206 if (syntax
& RE_NO_GNU_OPS
)
3212 if (syntax
& RE_NO_GNU_OPS
)
3214 BUF_PUSH (wordbound
);
3218 if (syntax
& RE_NO_GNU_OPS
)
3220 BUF_PUSH (notwordbound
);
3224 if (syntax
& RE_NO_GNU_OPS
)
3230 if (syntax
& RE_NO_GNU_OPS
)
3235 case '1': case '2': case '3': case '4': case '5':
3236 case '6': case '7': case '8': case '9':
3240 if (syntax
& RE_NO_BK_REFS
)
3241 goto normal_backslash
;
3245 /* Can't back reference to a subexpression before its end. */
3246 if (reg
> regnum
|| group_in_compile_stack (compile_stack
, reg
))
3247 FREE_STACK_RETURN (REG_ESUBREG
);
3250 BUF_PUSH_2 (duplicate
, reg
);
3257 if (syntax
& RE_BK_PLUS_QM
)
3260 goto normal_backslash
;
3264 /* You might think it would be useful for \ to mean
3265 not to translate; but if we don't translate it
3266 it will never match anything. */
3274 /* Expects the character in `c'. */
3276 /* If no exactn currently being built. */
3279 /* If last exactn not at current position. */
3280 || pending_exact
+ *pending_exact
+ 1 != b
3282 /* We have only one byte following the exactn for the count. */
3283 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3285 /* If followed by a repetition operator. */
3286 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3287 || ((syntax
& RE_BK_PLUS_QM
)
3288 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3289 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3290 || ((syntax
& RE_INTERVALS
)
3291 && ((syntax
& RE_NO_BK_BRACES
)
3292 ? p
!= pend
&& *p
== '{'
3293 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3295 /* Start building a new exactn. */
3299 BUF_PUSH_2 (exactn
, 0);
3300 pending_exact
= b
- 1;
3303 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3308 MAKE_CHAR_MULTIBYTE (c
);
3310 len
= CHAR_STRING (c
, b
);
3312 (*pending_exact
) += len
;
3317 } /* while p != pend */
3320 /* Through the pattern now. */
3324 if (!COMPILE_STACK_EMPTY
)
3325 FREE_STACK_RETURN (REG_EPAREN
);
3327 /* If we don't want backtracking, force success
3328 the first time we reach the end of the compiled pattern. */
3329 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3332 free (compile_stack
.stack
);
3334 /* We have succeeded; set the length of the buffer. */
3335 bufp
->used
= b
- bufp
->buffer
;
3340 re_compile_fastmap (bufp
);
3341 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3342 print_compiled_pattern (bufp
);
3347 #ifndef MATCH_MAY_ALLOCATE
3348 /* Initialize the failure stack to the largest possible stack. This
3349 isn't necessary unless we're trying to avoid calling alloca in
3350 the search and match routines. */
3352 int num_regs
= bufp
->re_nsub
+ 1;
3354 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3356 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3358 if (! fail_stack
.stack
)
3360 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3361 * sizeof (fail_stack_elt_t
));
3364 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3366 * sizeof (fail_stack_elt_t
)));
3369 regex_grow_registers (num_regs
);
3371 #endif /* not MATCH_MAY_ALLOCATE */
3374 } /* regex_compile */
3376 /* Subroutines for `regex_compile'. */
3378 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3381 store_op1 (op
, loc
, arg
)
3386 *loc
= (unsigned char) op
;
3387 STORE_NUMBER (loc
+ 1, arg
);
3391 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3394 store_op2 (op
, loc
, arg1
, arg2
)
3399 *loc
= (unsigned char) op
;
3400 STORE_NUMBER (loc
+ 1, arg1
);
3401 STORE_NUMBER (loc
+ 3, arg2
);
3405 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3406 for OP followed by two-byte integer parameter ARG. */
3409 insert_op1 (op
, loc
, arg
, end
)
3415 register unsigned char *pfrom
= end
;
3416 register unsigned char *pto
= end
+ 3;
3418 while (pfrom
!= loc
)
3421 store_op1 (op
, loc
, arg
);
3425 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3428 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3434 register unsigned char *pfrom
= end
;
3435 register unsigned char *pto
= end
+ 5;
3437 while (pfrom
!= loc
)
3440 store_op2 (op
, loc
, arg1
, arg2
);
3444 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3445 after an alternative or a begin-subexpression. We assume there is at
3446 least one character before the ^. */
3449 at_begline_loc_p (pattern
, p
, syntax
)
3450 re_char
*pattern
, *p
;
3451 reg_syntax_t syntax
;
3453 re_char
*prev
= p
- 2;
3454 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3457 /* After a subexpression? */
3458 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3459 /* After an alternative? */
3460 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3461 /* After a shy subexpression? */
3462 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3463 && prev
[-1] == '?' && prev
[-2] == '('
3464 && (syntax
& RE_NO_BK_PARENS
3465 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3469 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3470 at least one character after the $, i.e., `P < PEND'. */
3473 at_endline_loc_p (p
, pend
, syntax
)
3475 reg_syntax_t syntax
;
3478 boolean next_backslash
= *next
== '\\';
3479 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3482 /* Before a subexpression? */
3483 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3484 : next_backslash
&& next_next
&& *next_next
== ')')
3485 /* Before an alternative? */
3486 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3487 : next_backslash
&& next_next
&& *next_next
== '|');
3491 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3492 false if it's not. */
3495 group_in_compile_stack (compile_stack
, regnum
)
3496 compile_stack_type compile_stack
;
3501 for (this_element
= compile_stack
.avail
- 1;
3504 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3511 If fastmap is non-NULL, go through the pattern and fill fastmap
3512 with all the possible leading chars. If fastmap is NULL, don't
3513 bother filling it up (obviously) and only return whether the
3514 pattern could potentially match the empty string.
3516 MULTIBYTE is always 1 for Emacs, and 0 otherwise.
3518 Return 1 if p..pend might match the empty string.
3519 Return 0 if p..pend matches at least one char.
3520 Return -1 if fastmap was not updated accurately. */
3523 analyse_first (p
, pend
, fastmap
, multibyte
)
3526 const int multibyte
;
3531 /* If all elements for base leading-codes in fastmap is set, this
3532 flag is set true. */
3533 boolean match_any_multibyte_characters
= false;
3537 /* The loop below works as follows:
3538 - It has a working-list kept in the PATTERN_STACK and which basically
3539 starts by only containing a pointer to the first operation.
3540 - If the opcode we're looking at is a match against some set of
3541 chars, then we add those chars to the fastmap and go on to the
3542 next work element from the worklist (done via `break').
3543 - If the opcode is a control operator on the other hand, we either
3544 ignore it (if it's meaningless at this point, such as `start_memory')
3545 or execute it (if it's a jump). If the jump has several destinations
3546 (i.e. `on_failure_jump'), then we push the other destination onto the
3548 We guarantee termination by ignoring backward jumps (more or less),
3549 so that `p' is monotonically increasing. More to the point, we
3550 never set `p' (or push) anything `<= p1'. */
3554 /* `p1' is used as a marker of how far back a `on_failure_jump'
3555 can go without being ignored. It is normally equal to `p'
3556 (which prevents any backward `on_failure_jump') except right
3557 after a plain `jump', to allow patterns such as:
3560 10: on_failure_jump 3
3561 as used for the *? operator. */
3564 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3571 /* If the first character has to match a backreference, that means
3572 that the group was empty (since it already matched). Since this
3573 is the only case that interests us here, we can assume that the
3574 backreference must match the empty string. */
3579 /* Following are the cases which match a character. These end
3584 /* If multibyte is nonzero, the first byte of each
3585 character is an ASCII or a leading code. Otherwise,
3586 each byte is a character. Thus, this works in both
3593 /* We could put all the chars except for \n (and maybe \0)
3594 but we don't bother since it is generally not worth it. */
3595 if (!fastmap
) break;
3600 if (!fastmap
) break;
3602 /* Chars beyond end of bitmap are possible matches. */
3603 /* Emacs uses the bitmap only for ASCII characters. */
3604 int limit
= multibyte
? 128 : (1 << BYTEWIDTH
);
3606 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3613 if (!fastmap
) break;
3614 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3615 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3617 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3620 if ((not && multibyte
)
3621 /* Any leading code can possibly start a character
3622 which doesn't match the specified set of characters. */
3623 || (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3624 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3625 /* If we can match a character class, we can match
3626 any character set. */
3628 set_fastmap_for_multibyte_characters
:
3629 if (match_any_multibyte_characters
== false)
3631 for (j
= 0x80; j
< 0x100; j
++) /* XXX */
3632 if (BASE_LEADING_CODE_P (j
))
3634 match_any_multibyte_characters
= true;
3638 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3639 && match_any_multibyte_characters
== false)
3641 /* Set fastmap[I] to 1 where I is a leading code of each
3642 multibyte characer in the range table. */
3644 unsigned char lc1
, lc2
;
3646 /* Make P points the range table. `+ 2' is to skip flag
3647 bits for a character class. */
3648 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3650 /* Extract the number of ranges in range table into COUNT. */
3651 EXTRACT_NUMBER_AND_INCR (count
, p
);
3652 for (; count
> 0; count
--, p
+= 2 * 3) /* XXX */
3654 /* Extract the start and end of each range. */
3655 EXTRACT_CHARACTER (c
, p
);
3656 lc1
= CHAR_LEADING_CODE (c
);
3658 EXTRACT_CHARACTER (c
, p
);
3659 lc2
= CHAR_LEADING_CODE (c
);
3660 for (j
= lc1
; j
<= lc2
; j
++)
3668 if (!fastmap
) break;
3670 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3672 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3673 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
3677 /* This match depends on text properties. These end with
3678 aborting optimizations. */
3682 case notcategoryspec
:
3683 if (!fastmap
) break;
3684 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
3686 for (j
= (multibyte
? 127 : (1 << BYTEWIDTH
)); j
>= 0; j
--)
3687 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
3691 /* Any character set can possibly contain a character
3692 whose category is K (or not). */
3693 goto set_fastmap_for_multibyte_characters
;
3696 /* All cases after this match the empty string. These end with
3716 EXTRACT_NUMBER_AND_INCR (j
, p
);
3718 /* Backward jumps can only go back to code that we've already
3719 visited. `re_compile' should make sure this is true. */
3722 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
3724 case on_failure_jump
:
3725 case on_failure_keep_string_jump
:
3726 case on_failure_jump_loop
:
3727 case on_failure_jump_nastyloop
:
3728 case on_failure_jump_smart
:
3734 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3735 to jump back to "just after here". */
3738 case on_failure_jump
:
3739 case on_failure_keep_string_jump
:
3740 case on_failure_jump_nastyloop
:
3741 case on_failure_jump_loop
:
3742 case on_failure_jump_smart
:
3743 EXTRACT_NUMBER_AND_INCR (j
, p
);
3745 ; /* Backward jump to be ignored. */
3747 { /* We have to look down both arms.
3748 We first go down the "straight" path so as to minimize
3749 stack usage when going through alternatives. */
3750 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
3758 /* This code simply does not properly handle forward jump_n. */
3759 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
3761 /* jump_n can either jump or fall through. The (backward) jump
3762 case has already been handled, so we only need to look at the
3763 fallthrough case. */
3767 /* If N == 0, it should be an on_failure_jump_loop instead. */
3768 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
3770 /* We only care about one iteration of the loop, so we don't
3771 need to consider the case where this behaves like an
3788 abort (); /* We have listed all the cases. */
3791 /* Getting here means we have found the possible starting
3792 characters for one path of the pattern -- and that the empty
3793 string does not match. We need not follow this path further. */
3797 /* We reached the end without matching anything. */
3800 } /* analyse_first */
3802 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3803 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3804 characters can start a string that matches the pattern. This fastmap
3805 is used by re_search to skip quickly over impossible starting points.
3807 Character codes above (1 << BYTEWIDTH) are not represented in the
3808 fastmap, but the leading codes are represented. Thus, the fastmap
3809 indicates which character sets could start a match.
3811 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3812 area as BUFP->fastmap.
3814 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3817 Returns 0 if we succeed, -2 if an internal error. */
3820 re_compile_fastmap (bufp
)
3821 struct re_pattern_buffer
*bufp
;
3823 char *fastmap
= bufp
->fastmap
;
3826 assert (fastmap
&& bufp
->buffer
);
3828 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
3829 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
3831 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
3834 /* The compiled pattern buffer is always
3835 setup for multibyte characters. */
3841 bufp
->can_be_null
= (analysis
!= 0);
3843 } /* re_compile_fastmap */
3845 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3846 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3847 this memory for recording register information. STARTS and ENDS
3848 must be allocated using the malloc library routine, and must each
3849 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3851 If NUM_REGS == 0, then subsequent matches should allocate their own
3854 Unless this function is called, the first search or match using
3855 PATTERN_BUFFER will allocate its own register data, without
3856 freeing the old data. */
3859 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3860 struct re_pattern_buffer
*bufp
;
3861 struct re_registers
*regs
;
3863 regoff_t
*starts
, *ends
;
3867 bufp
->regs_allocated
= REGS_REALLOCATE
;
3868 regs
->num_regs
= num_regs
;
3869 regs
->start
= starts
;
3874 bufp
->regs_allocated
= REGS_UNALLOCATED
;
3876 regs
->start
= regs
->end
= (regoff_t
*) 0;
3879 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
3881 /* Searching routines. */
3883 /* Like re_search_2, below, but only one string is specified, and
3884 doesn't let you say where to stop matching. */
3887 re_search (bufp
, string
, size
, startpos
, range
, regs
)
3888 struct re_pattern_buffer
*bufp
;
3890 int size
, startpos
, range
;
3891 struct re_registers
*regs
;
3893 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
3896 WEAK_ALIAS (__re_search
, re_search
)
3898 /* End address of virtual concatenation of string. */
3899 #define STOP_ADDR_VSTRING(P) \
3900 (((P) >= size1 ? string2 + size2 : string1 + size1))
3902 /* Address of POS in the concatenation of virtual string. */
3903 #define POS_ADDR_VSTRING(POS) \
3904 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3906 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3907 virtual concatenation of STRING1 and STRING2, starting first at index
3908 STARTPOS, then at STARTPOS + 1, and so on.
3910 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3912 RANGE is how far to scan while trying to match. RANGE = 0 means try
3913 only at STARTPOS; in general, the last start tried is STARTPOS +
3916 In REGS, return the indices of the virtual concatenation of STRING1
3917 and STRING2 that matched the entire BUFP->buffer and its contained
3920 Do not consider matching one past the index STOP in the virtual
3921 concatenation of STRING1 and STRING2.
3923 We return either the position in the strings at which the match was
3924 found, -1 if no match, or -2 if error (such as failure
3928 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
3929 struct re_pattern_buffer
*bufp
;
3930 const char *str1
, *str2
;
3934 struct re_registers
*regs
;
3938 re_char
*string1
= (re_char
*) str1
;
3939 re_char
*string2
= (re_char
*) str2
;
3940 register char *fastmap
= bufp
->fastmap
;
3941 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3942 int total_size
= size1
+ size2
;
3943 int endpos
= startpos
+ range
;
3944 boolean anchored_start
;
3946 /* Nonzero if BUFP is setup for multibyte characters. */
3948 const boolean multibyte
= 1;
3950 const boolean multibyte
= 0;
3952 /* Nonzero if STR1 and STR2 contains multibyte characters. */
3953 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
3955 /* Check for out-of-range STARTPOS. */
3956 if (startpos
< 0 || startpos
> total_size
)
3959 /* Fix up RANGE if it might eventually take us outside
3960 the virtual concatenation of STRING1 and STRING2.
3961 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3963 range
= 0 - startpos
;
3964 else if (endpos
> total_size
)
3965 range
= total_size
- startpos
;
3967 /* If the search isn't to be a backwards one, don't waste time in a
3968 search for a pattern anchored at beginning of buffer. */
3969 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
3978 /* In a forward search for something that starts with \=.
3979 don't keep searching past point. */
3980 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
3982 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
3988 /* Update the fastmap now if not correct already. */
3989 if (fastmap
&& !bufp
->fastmap_accurate
)
3990 re_compile_fastmap (bufp
);
3992 /* See whether the pattern is anchored. */
3993 anchored_start
= (bufp
->buffer
[0] == begline
);
3996 gl_state
.object
= re_match_object
;
3998 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4000 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4004 /* Loop through the string, looking for a place to start matching. */
4007 /* If the pattern is anchored,
4008 skip quickly past places we cannot match.
4009 We don't bother to treat startpos == 0 specially
4010 because that case doesn't repeat. */
4011 if (anchored_start
&& startpos
> 0)
4013 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4014 : string2
[startpos
- size1
- 1])
4019 /* If a fastmap is supplied, skip quickly over characters that
4020 cannot be the start of a match. If the pattern can match the
4021 null string, however, we don't need to skip characters; we want
4022 the first null string. */
4023 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4025 register re_char
*d
;
4026 register re_wchar_t buf_ch
;
4028 d
= POS_ADDR_VSTRING (startpos
);
4030 if (range
> 0) /* Searching forwards. */
4032 register int lim
= 0;
4035 if (startpos
< size1
&& startpos
+ range
>= size1
)
4036 lim
= range
- (size1
- startpos
);
4038 /* Written out as an if-else to avoid testing `translate'
4040 if (RE_TRANSLATE_P (translate
))
4042 if (target_multibyte
)
4047 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
4050 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4051 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4054 range
-= buf_charlen
;
4061 MAKE_CHAR_MULTIBYTE (buf_ch
);
4062 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4063 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4071 && !fastmap
[RE_TRANSLATE (translate
, *d
)])
4077 else if (multibyte
&& ! target_multibyte
)
4080 MAKE_CHAR_MULTIBYTE (buf_ch
);
4081 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4088 while (range
> lim
&& !fastmap
[*d
])
4094 startpos
+= irange
- range
;
4096 else /* Searching backwards. */
4098 int room
= (startpos
>= size1
4099 ? size2
+ size1
- startpos
4100 : size1
- startpos
);
4101 buf_ch
= RE_STRING_CHAR (d
, room
);
4102 if (! target_multibyte
)
4103 MAKE_CHAR_MULTIBYTE (buf_ch
);
4104 buf_ch
= TRANSLATE (buf_ch
);
4106 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4111 /* If can't match the null string, and that's all we have left, fail. */
4112 if (range
>= 0 && startpos
== total_size
&& fastmap
4113 && !bufp
->can_be_null
)
4116 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4117 startpos
, regs
, stop
);
4118 #ifndef REGEX_MALLOC
4135 /* Update STARTPOS to the next character boundary. */
4136 if (target_multibyte
)
4138 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4139 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
4140 int len
= MULTIBYTE_FORM_LENGTH (p
, pend
- p
);
4158 /* Update STARTPOS to the previous character boundary. */
4159 if (target_multibyte
)
4161 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4164 /* Find the head of multibyte form. */
4165 while (!CHAR_HEAD_P (*p
))
4170 if (MULTIBYTE_FORM_LENGTH (p
, len
+ 1) != (len
+ 1))
4186 WEAK_ALIAS (__re_search_2
, re_search_2
)
4188 /* Declarations and macros for re_match_2. */
4190 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4192 RE_TRANSLATE_TYPE translate
,
4193 const int multibyte
));
4195 /* This converts PTR, a pointer into one of the search strings `string1'
4196 and `string2' into an offset from the beginning of that string. */
4197 #define POINTER_TO_OFFSET(ptr) \
4198 (FIRST_STRING_P (ptr) \
4199 ? ((regoff_t) ((ptr) - string1)) \
4200 : ((regoff_t) ((ptr) - string2 + size1)))
4202 /* Call before fetching a character with *d. This switches over to
4203 string2 if necessary.
4204 Check re_match_2_internal for a discussion of why end_match_2 might
4205 not be within string2 (but be equal to end_match_1 instead). */
4206 #define PREFETCH() \
4209 /* End of string2 => fail. */ \
4210 if (dend == end_match_2) \
4212 /* End of string1 => advance to string2. */ \
4214 dend = end_match_2; \
4217 /* Call before fetching a char with *d if you already checked other limits.
4218 This is meant for use in lookahead operations like wordend, etc..
4219 where we might need to look at parts of the string that might be
4220 outside of the LIMITs (i.e past `stop'). */
4221 #define PREFETCH_NOLIMIT() \
4225 dend = end_match_2; \
4228 /* Test if at very beginning or at very end of the virtual concatenation
4229 of `string1' and `string2'. If only one string, it's `string2'. */
4230 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4231 #define AT_STRINGS_END(d) ((d) == end2)
4234 /* Test if D points to a character which is word-constituent. We have
4235 two special cases to check for: if past the end of string1, look at
4236 the first character in string2; and if before the beginning of
4237 string2, look at the last character in string1. */
4238 #define WORDCHAR_P(d) \
4239 (SYNTAX ((d) == end1 ? *string2 \
4240 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4243 /* Disabled due to a compiler bug -- see comment at case wordbound */
4245 /* The comment at case wordbound is following one, but we don't use
4246 AT_WORD_BOUNDARY anymore to support multibyte form.
4248 The DEC Alpha C compiler 3.x generates incorrect code for the
4249 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4250 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4251 macro and introducing temporary variables works around the bug. */
4254 /* Test if the character before D and the one at D differ with respect
4255 to being word-constituent. */
4256 #define AT_WORD_BOUNDARY(d) \
4257 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4258 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4261 /* Free everything we malloc. */
4262 #ifdef MATCH_MAY_ALLOCATE
4263 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4264 # define FREE_VARIABLES() \
4266 REGEX_FREE_STACK (fail_stack.stack); \
4267 FREE_VAR (regstart); \
4268 FREE_VAR (regend); \
4269 FREE_VAR (best_regstart); \
4270 FREE_VAR (best_regend); \
4273 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4274 #endif /* not MATCH_MAY_ALLOCATE */
4277 /* Optimization routines. */
4279 /* If the operation is a match against one or more chars,
4280 return a pointer to the next operation, else return NULL. */
4285 switch (SWITCH_ENUM_CAST (*p
++))
4296 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4299 p
= CHARSET_RANGE_TABLE (p
- 1);
4300 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4301 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4304 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4311 case notcategoryspec
:
4323 /* Jump over non-matching operations. */
4324 static unsigned char *
4325 skip_noops (p
, pend
)
4326 unsigned char *p
, *pend
;
4331 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4340 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4351 /* Non-zero if "p1 matches something" implies "p2 fails". */
4353 mutually_exclusive_p (bufp
, p1
, p2
)
4354 struct re_pattern_buffer
*bufp
;
4355 unsigned char *p1
, *p2
;
4358 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4359 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4361 assert (p1
>= bufp
->buffer
&& p1
< pend
4362 && p2
>= bufp
->buffer
&& p2
<= pend
);
4364 /* Skip over open/close-group commands.
4365 If what follows this loop is a ...+ construct,
4366 look at what begins its body, since we will have to
4367 match at least one of that. */
4368 p2
= skip_noops (p2
, pend
);
4369 /* The same skip can be done for p1, except that this function
4370 is only used in the case where p1 is a simple match operator. */
4371 /* p1 = skip_noops (p1, pend); */
4373 assert (p1
>= bufp
->buffer
&& p1
< pend
4374 && p2
>= bufp
->buffer
&& p2
<= pend
);
4376 op2
= p2
== pend
? succeed
: *p2
;
4378 switch (SWITCH_ENUM_CAST (op2
))
4382 /* If we're at the end of the pattern, we can change. */
4383 if (skip_one_char (p1
))
4385 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4393 register re_wchar_t c
4394 = (re_opcode_t
) *p2
== endline
? '\n'
4395 : RE_STRING_CHAR (p2
+ 2, pend
- p2
- 2);
4397 if ((re_opcode_t
) *p1
== exactn
)
4399 if (c
!= RE_STRING_CHAR (p1
+ 2, pend
- p1
- 2))
4401 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4406 else if ((re_opcode_t
) *p1
== charset
4407 || (re_opcode_t
) *p1
== charset_not
)
4409 int not = (re_opcode_t
) *p1
== charset_not
;
4411 /* Test if C is listed in charset (or charset_not)
4413 if (SINGLE_BYTE_CHAR_P (c
))
4415 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4416 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4419 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4420 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4422 /* `not' is equal to 1 if c would match, which means
4423 that we can't change to pop_failure_jump. */
4426 DEBUG_PRINT1 (" No match => fast loop.\n");
4430 else if ((re_opcode_t
) *p1
== anychar
4433 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4441 if ((re_opcode_t
) *p1
== exactn
)
4442 /* Reuse the code above. */
4443 return mutually_exclusive_p (bufp
, p2
, p1
);
4445 /* It is hard to list up all the character in charset
4446 P2 if it includes multibyte character. Give up in
4448 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4450 /* Now, we are sure that P2 has no range table.
4451 So, for the size of bitmap in P2, `p2[1]' is
4452 enough. But P1 may have range table, so the
4453 size of bitmap table of P1 is extracted by
4454 using macro `CHARSET_BITMAP_SIZE'.
4456 Since we know that all the character listed in
4457 P2 is ASCII, it is enough to test only bitmap
4460 if ((re_opcode_t
) *p1
== charset
)
4463 /* We win if the charset inside the loop
4464 has no overlap with the one after the loop. */
4467 && idx
< CHARSET_BITMAP_SIZE (p1
));
4469 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4473 || idx
== CHARSET_BITMAP_SIZE (p1
))
4475 DEBUG_PRINT1 (" No match => fast loop.\n");
4479 else if ((re_opcode_t
) *p1
== charset_not
)
4482 /* We win if the charset_not inside the loop lists
4483 every character listed in the charset after. */
4484 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4485 if (! (p2
[2 + idx
] == 0
4486 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4487 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4492 DEBUG_PRINT1 (" No match => fast loop.\n");
4501 switch (SWITCH_ENUM_CAST (*p1
))
4505 /* Reuse the code above. */
4506 return mutually_exclusive_p (bufp
, p2
, p1
);
4508 /* When we have two charset_not, it's very unlikely that
4509 they don't overlap. The union of the two sets of excluded
4510 chars should cover all possible chars, which, as a matter of
4511 fact, is virtually impossible in multibyte buffers. */
4518 return ((re_opcode_t
) *p1
== syntaxspec
4519 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4523 return ((re_opcode_t
) *p1
== notsyntaxspec
4524 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4527 return (((re_opcode_t
) *p1
== notsyntaxspec
4528 || (re_opcode_t
) *p1
== syntaxspec
)
4533 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4534 case notcategoryspec
:
4535 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4547 /* Matching routines. */
4549 #ifndef emacs /* Emacs never uses this. */
4550 /* re_match is like re_match_2 except it takes only a single string. */
4553 re_match (bufp
, string
, size
, pos
, regs
)
4554 struct re_pattern_buffer
*bufp
;
4557 struct re_registers
*regs
;
4559 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
4561 # if defined C_ALLOCA && !defined REGEX_MALLOC
4566 WEAK_ALIAS (__re_match
, re_match
)
4567 #endif /* not emacs */
4570 /* In Emacs, this is the string or buffer in which we
4571 are matching. It is used for looking up syntax properties. */
4572 Lisp_Object re_match_object
;
4575 /* re_match_2 matches the compiled pattern in BUFP against the
4576 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4577 and SIZE2, respectively). We start matching at POS, and stop
4580 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4581 store offsets for the substring each group matched in REGS. See the
4582 documentation for exactly how many groups we fill.
4584 We return -1 if no match, -2 if an internal error (such as the
4585 failure stack overflowing). Otherwise, we return the length of the
4586 matched substring. */
4589 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4590 struct re_pattern_buffer
*bufp
;
4591 const char *string1
, *string2
;
4594 struct re_registers
*regs
;
4601 gl_state
.object
= re_match_object
;
4602 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4603 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4606 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4607 (re_char
*) string2
, size2
,
4609 #if defined C_ALLOCA && !defined REGEX_MALLOC
4614 WEAK_ALIAS (__re_match_2
, re_match_2
)
4617 #define TARGET_CHAR_AND_LENGTH(d, len, actual_len) \
4619 ? STRING_CHAR_AND_LENGTH (d, len, actual_len) \
4620 : (actual_len = 1, unibyte_char_to_multibyte (*d)))
4622 #define TARGET_CHAR_AND_LENGTH(d, len, actual_len) \
4623 (actual_len = 1, *d)
4627 /* This is a separate function so that we can force an alloca cleanup
4630 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4631 struct re_pattern_buffer
*bufp
;
4632 re_char
*string1
, *string2
;
4635 struct re_registers
*regs
;
4638 /* General temporaries. */
4643 /* Just past the end of the corresponding string. */
4644 re_char
*end1
, *end2
;
4646 /* Pointers into string1 and string2, just past the last characters in
4647 each to consider matching. */
4648 re_char
*end_match_1
, *end_match_2
;
4650 /* Where we are in the data, and the end of the current string. */
4653 /* Used sometimes to remember where we were before starting matching
4654 an operator so that we can go back in case of failure. This "atomic"
4655 behavior of matching opcodes is indispensable to the correctness
4656 of the on_failure_keep_string_jump optimization. */
4659 /* Where we are in the pattern, and the end of the pattern. */
4660 re_char
*p
= bufp
->buffer
;
4661 re_char
*pend
= p
+ bufp
->used
;
4663 /* We use this to map every character in the string. */
4664 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4666 /* Nonzero if BUFP is setup for multibyte characters. */
4668 const boolean multibyte
= 1;
4670 const boolean multibyte
= 0;
4672 /* Nonzero if STR1 and STR2 contains multibyte characters. */
4673 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4675 /* Failure point stack. Each place that can handle a failure further
4676 down the line pushes a failure point on this stack. It consists of
4677 regstart, and regend for all registers corresponding to
4678 the subexpressions we're currently inside, plus the number of such
4679 registers, and, finally, two char *'s. The first char * is where
4680 to resume scanning the pattern; the second one is where to resume
4681 scanning the strings. */
4682 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4683 fail_stack_type fail_stack
;
4686 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4689 #if defined REL_ALLOC && defined REGEX_MALLOC
4690 /* This holds the pointer to the failure stack, when
4691 it is allocated relocatably. */
4692 fail_stack_elt_t
*failure_stack_ptr
;
4695 /* We fill all the registers internally, independent of what we
4696 return, for use in backreferences. The number here includes
4697 an element for register zero. */
4698 size_t num_regs
= bufp
->re_nsub
+ 1;
4700 /* Information on the contents of registers. These are pointers into
4701 the input strings; they record just what was matched (on this
4702 attempt) by a subexpression part of the pattern, that is, the
4703 regnum-th regstart pointer points to where in the pattern we began
4704 matching and the regnum-th regend points to right after where we
4705 stopped matching the regnum-th subexpression. (The zeroth register
4706 keeps track of what the whole pattern matches.) */
4707 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4708 re_char
**regstart
, **regend
;
4711 /* The following record the register info as found in the above
4712 variables when we find a match better than any we've seen before.
4713 This happens as we backtrack through the failure points, which in
4714 turn happens only if we have not yet matched the entire string. */
4715 unsigned best_regs_set
= false;
4716 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4717 re_char
**best_regstart
, **best_regend
;
4720 /* Logically, this is `best_regend[0]'. But we don't want to have to
4721 allocate space for that if we're not allocating space for anything
4722 else (see below). Also, we never need info about register 0 for
4723 any of the other register vectors, and it seems rather a kludge to
4724 treat `best_regend' differently than the rest. So we keep track of
4725 the end of the best match so far in a separate variable. We
4726 initialize this to NULL so that when we backtrack the first time
4727 and need to test it, it's not garbage. */
4728 re_char
*match_end
= NULL
;
4731 /* Counts the total number of registers pushed. */
4732 unsigned num_regs_pushed
= 0;
4735 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4739 #ifdef MATCH_MAY_ALLOCATE
4740 /* Do not bother to initialize all the register variables if there are
4741 no groups in the pattern, as it takes a fair amount of time. If
4742 there are groups, we include space for register 0 (the whole
4743 pattern), even though we never use it, since it simplifies the
4744 array indexing. We should fix this. */
4747 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4748 regend
= REGEX_TALLOC (num_regs
, re_char
*);
4749 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4750 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
4752 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
4760 /* We must initialize all our variables to NULL, so that
4761 `FREE_VARIABLES' doesn't try to free them. */
4762 regstart
= regend
= best_regstart
= best_regend
= NULL
;
4764 #endif /* MATCH_MAY_ALLOCATE */
4766 /* The starting position is bogus. */
4767 if (pos
< 0 || pos
> size1
+ size2
)
4773 /* Initialize subexpression text positions to -1 to mark ones that no
4774 start_memory/stop_memory has been seen for. Also initialize the
4775 register information struct. */
4776 for (reg
= 1; reg
< num_regs
; reg
++)
4777 regstart
[reg
] = regend
[reg
] = NULL
;
4779 /* We move `string1' into `string2' if the latter's empty -- but not if
4780 `string1' is null. */
4781 if (size2
== 0 && string1
!= NULL
)
4788 end1
= string1
+ size1
;
4789 end2
= string2
+ size2
;
4791 /* `p' scans through the pattern as `d' scans through the data.
4792 `dend' is the end of the input string that `d' points within. `d'
4793 is advanced into the following input string whenever necessary, but
4794 this happens before fetching; therefore, at the beginning of the
4795 loop, `d' can be pointing at the end of a string, but it cannot
4799 /* Only match within string2. */
4800 d
= string2
+ pos
- size1
;
4801 dend
= end_match_2
= string2
+ stop
- size1
;
4802 end_match_1
= end1
; /* Just to give it a value. */
4808 /* Only match within string1. */
4809 end_match_1
= string1
+ stop
;
4811 When we reach end_match_1, PREFETCH normally switches to string2.
4812 But in the present case, this means that just doing a PREFETCH
4813 makes us jump from `stop' to `gap' within the string.
4814 What we really want here is for the search to stop as
4815 soon as we hit end_match_1. That's why we set end_match_2
4816 to end_match_1 (since PREFETCH fails as soon as we hit
4818 end_match_2
= end_match_1
;
4821 { /* It's important to use this code when stop == size so that
4822 moving `d' from end1 to string2 will not prevent the d == dend
4823 check from catching the end of string. */
4825 end_match_2
= string2
+ stop
- size1
;
4831 DEBUG_PRINT1 ("The compiled pattern is: ");
4832 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
4833 DEBUG_PRINT1 ("The string to match is: `");
4834 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
4835 DEBUG_PRINT1 ("'\n");
4837 /* This loops over pattern commands. It exits by returning from the
4838 function if the match is complete, or it drops through if the match
4839 fails at this starting point in the input data. */
4842 DEBUG_PRINT2 ("\n%p: ", p
);
4845 { /* End of pattern means we might have succeeded. */
4846 DEBUG_PRINT1 ("end of pattern ... ");
4848 /* If we haven't matched the entire string, and we want the
4849 longest match, try backtracking. */
4850 if (d
!= end_match_2
)
4852 /* 1 if this match ends in the same string (string1 or string2)
4853 as the best previous match. */
4854 boolean same_str_p
= (FIRST_STRING_P (match_end
)
4855 == FIRST_STRING_P (d
));
4856 /* 1 if this match is the best seen so far. */
4857 boolean best_match_p
;
4859 /* AIX compiler got confused when this was combined
4860 with the previous declaration. */
4862 best_match_p
= d
> match_end
;
4864 best_match_p
= !FIRST_STRING_P (d
);
4866 DEBUG_PRINT1 ("backtracking.\n");
4868 if (!FAIL_STACK_EMPTY ())
4869 { /* More failure points to try. */
4871 /* If exceeds best match so far, save it. */
4872 if (!best_regs_set
|| best_match_p
)
4874 best_regs_set
= true;
4877 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4879 for (reg
= 1; reg
< num_regs
; reg
++)
4881 best_regstart
[reg
] = regstart
[reg
];
4882 best_regend
[reg
] = regend
[reg
];
4888 /* If no failure points, don't restore garbage. And if
4889 last match is real best match, don't restore second
4891 else if (best_regs_set
&& !best_match_p
)
4894 /* Restore best match. It may happen that `dend ==
4895 end_match_1' while the restored d is in string2.
4896 For example, the pattern `x.*y.*z' against the
4897 strings `x-' and `y-z-', if the two strings are
4898 not consecutive in memory. */
4899 DEBUG_PRINT1 ("Restoring best registers.\n");
4902 dend
= ((d
>= string1
&& d
<= end1
)
4903 ? end_match_1
: end_match_2
);
4905 for (reg
= 1; reg
< num_regs
; reg
++)
4907 regstart
[reg
] = best_regstart
[reg
];
4908 regend
[reg
] = best_regend
[reg
];
4911 } /* d != end_match_2 */
4914 DEBUG_PRINT1 ("Accepting match.\n");
4916 /* If caller wants register contents data back, do it. */
4917 if (regs
&& !bufp
->no_sub
)
4919 /* Have the register data arrays been allocated? */
4920 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
4921 { /* No. So allocate them with malloc. We need one
4922 extra element beyond `num_regs' for the `-1' marker
4924 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
4925 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
4926 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
4927 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4932 bufp
->regs_allocated
= REGS_REALLOCATE
;
4934 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
4935 { /* Yes. If we need more elements than were already
4936 allocated, reallocate them. If we need fewer, just
4938 if (regs
->num_regs
< num_regs
+ 1)
4940 regs
->num_regs
= num_regs
+ 1;
4941 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
4942 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
4943 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4952 /* These braces fend off a "empty body in an else-statement"
4953 warning under GCC when assert expands to nothing. */
4954 assert (bufp
->regs_allocated
== REGS_FIXED
);
4957 /* Convert the pointer data in `regstart' and `regend' to
4958 indices. Register zero has to be set differently,
4959 since we haven't kept track of any info for it. */
4960 if (regs
->num_regs
> 0)
4962 regs
->start
[0] = pos
;
4963 regs
->end
[0] = POINTER_TO_OFFSET (d
);
4966 /* Go through the first `min (num_regs, regs->num_regs)'
4967 registers, since that is all we initialized. */
4968 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
4970 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
4971 regs
->start
[reg
] = regs
->end
[reg
] = -1;
4975 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
4977 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
4981 /* If the regs structure we return has more elements than
4982 were in the pattern, set the extra elements to -1. If
4983 we (re)allocated the registers, this is the case,
4984 because we always allocate enough to have at least one
4986 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
4987 regs
->start
[reg
] = regs
->end
[reg
] = -1;
4988 } /* regs && !bufp->no_sub */
4990 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4991 nfailure_points_pushed
, nfailure_points_popped
,
4992 nfailure_points_pushed
- nfailure_points_popped
);
4993 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
4995 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
4997 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5003 /* Otherwise match next pattern command. */
5004 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5006 /* Ignore these. Used to ignore the n of succeed_n's which
5007 currently have n == 0. */
5009 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5013 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5016 /* Match the next n pattern characters exactly. The following
5017 byte in the pattern defines n, and the n bytes after that
5018 are the characters to match. */
5021 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5023 /* Remember the start point to rollback upon failure. */
5026 /* This is written out as an if-else so we don't waste time
5027 testing `translate' inside the loop. */
5028 if (RE_TRANSLATE_P (translate
))
5033 int pat_charlen
, buf_charlen
;
5034 unsigned int pat_ch
, buf_ch
;
5037 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
5038 buf_ch
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
5040 if (RE_TRANSLATE (translate
, buf_ch
)
5049 mcnt
-= pat_charlen
;
5056 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5067 if (multibyte
== target_multibyte
)
5078 else /* i.e. multibyte && ! target_multibyte */
5081 int pat_charlen
, buf_charlen
;
5082 unsigned int pat_ch
, buf_ch
;
5085 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
5086 buf_ch
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
5088 if (pat_ch
!= buf_ch
)
5095 mcnt
-= pat_charlen
;
5102 /* Match any character except possibly a newline or a null. */
5108 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5111 buf_ch
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
5112 buf_ch
= TRANSLATE (buf_ch
);
5114 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5116 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5117 && buf_ch
== '\000'))
5120 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5129 register unsigned int c
;
5130 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5133 /* Start of actual range_table, or end of bitmap if there is no
5135 re_char
*range_table
;
5137 /* Nonzero if there is a range table. */
5138 int range_table_exists
;
5140 /* Number of ranges of range table. This is not included
5141 in the initial byte-length of the command. */
5144 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5146 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5148 if (range_table_exists
)
5150 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5151 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5155 c
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5156 c
= TRANSLATE (c
); /* The character to match. */
5158 if (! multibyte
|| IS_REAL_ASCII (c
))
5159 { /* Lookup bitmap. */
5160 /* Cast to `unsigned' instead of `unsigned char' in
5161 case the bit list is a full 32 bytes long. */
5162 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5163 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5167 else if (range_table_exists
)
5169 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5171 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5172 | (class_bits
& BIT_MULTIBYTE
)
5173 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5174 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5175 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5176 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5179 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5183 if (range_table_exists
)
5184 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5186 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5188 if (!not) goto fail
;
5195 /* The beginning of a group is represented by start_memory.
5196 The argument is the register number. The text
5197 matched within the group is recorded (in the internal
5198 registers data structure) under the register number. */
5200 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5202 /* In case we need to undo this operation (via backtracking). */
5203 PUSH_FAILURE_REG ((unsigned int)*p
);
5206 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5207 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5209 /* Move past the register number and inner group count. */
5214 /* The stop_memory opcode represents the end of a group. Its
5215 argument is the same as start_memory's: the register number. */
5217 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5219 assert (!REG_UNSET (regstart
[*p
]));
5220 /* Strictly speaking, there should be code such as:
5222 assert (REG_UNSET (regend[*p]));
5223 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5225 But the only info to be pushed is regend[*p] and it is known to
5226 be UNSET, so there really isn't anything to push.
5227 Not pushing anything, on the other hand deprives us from the
5228 guarantee that regend[*p] is UNSET since undoing this operation
5229 will not reset its value properly. This is not important since
5230 the value will only be read on the next start_memory or at
5231 the very end and both events can only happen if this stop_memory
5235 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5237 /* Move past the register number and the inner group count. */
5242 /* \<digit> has been turned into a `duplicate' command which is
5243 followed by the numeric value of <digit> as the register number. */
5246 register re_char
*d2
, *dend2
;
5247 int regno
= *p
++; /* Get which register to match against. */
5248 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5250 /* Can't back reference a group which we've never matched. */
5251 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5254 /* Where in input to try to start matching. */
5255 d2
= regstart
[regno
];
5257 /* Remember the start point to rollback upon failure. */
5260 /* Where to stop matching; if both the place to start and
5261 the place to stop matching are in the same string, then
5262 set to the place to stop, otherwise, for now have to use
5263 the end of the first string. */
5265 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5266 == FIRST_STRING_P (regend
[regno
]))
5267 ? regend
[regno
] : end_match_1
);
5270 /* If necessary, advance to next segment in register
5274 if (dend2
== end_match_2
) break;
5275 if (dend2
== regend
[regno
]) break;
5277 /* End of string1 => advance to string2. */
5279 dend2
= regend
[regno
];
5281 /* At end of register contents => success */
5282 if (d2
== dend2
) break;
5284 /* If necessary, advance to next segment in data. */
5287 /* How many characters left in this segment to match. */
5290 /* Want how many consecutive characters we can match in
5291 one shot, so, if necessary, adjust the count. */
5292 if (mcnt
> dend2
- d2
)
5295 /* Compare that many; failure if mismatch, else move
5297 if (RE_TRANSLATE_P (translate
)
5298 ? bcmp_translate (d
, d2
, mcnt
, translate
, target_multibyte
)
5299 : memcmp (d
, d2
, mcnt
))
5304 d
+= mcnt
, d2
+= mcnt
;
5310 /* begline matches the empty string at the beginning of the string
5311 (unless `not_bol' is set in `bufp'), and after newlines. */
5313 DEBUG_PRINT1 ("EXECUTING begline.\n");
5315 if (AT_STRINGS_BEG (d
))
5317 if (!bufp
->not_bol
) break;
5322 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5326 /* In all other cases, we fail. */
5330 /* endline is the dual of begline. */
5332 DEBUG_PRINT1 ("EXECUTING endline.\n");
5334 if (AT_STRINGS_END (d
))
5336 if (!bufp
->not_eol
) break;
5340 PREFETCH_NOLIMIT ();
5347 /* Match at the very beginning of the data. */
5349 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5350 if (AT_STRINGS_BEG (d
))
5355 /* Match at the very end of the data. */
5357 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5358 if (AT_STRINGS_END (d
))
5363 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5364 pushes NULL as the value for the string on the stack. Then
5365 `POP_FAILURE_POINT' will keep the current value for the
5366 string, instead of restoring it. To see why, consider
5367 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5368 then the . fails against the \n. But the next thing we want
5369 to do is match the \n against the \n; if we restored the
5370 string value, we would be back at the foo.
5372 Because this is used only in specific cases, we don't need to
5373 check all the things that `on_failure_jump' does, to make
5374 sure the right things get saved on the stack. Hence we don't
5375 share its code. The only reason to push anything on the
5376 stack at all is that otherwise we would have to change
5377 `anychar's code to do something besides goto fail in this
5378 case; that seems worse than this. */
5379 case on_failure_keep_string_jump
:
5380 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5381 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5384 PUSH_FAILURE_POINT (p
- 3, NULL
);
5387 /* A nasty loop is introduced by the non-greedy *? and +?.
5388 With such loops, the stack only ever contains one failure point
5389 at a time, so that a plain on_failure_jump_loop kind of
5390 cycle detection cannot work. Worse yet, such a detection
5391 can not only fail to detect a cycle, but it can also wrongly
5392 detect a cycle (between different instantiations of the same
5394 So the method used for those nasty loops is a little different:
5395 We use a special cycle-detection-stack-frame which is pushed
5396 when the on_failure_jump_nastyloop failure-point is *popped*.
5397 This special frame thus marks the beginning of one iteration
5398 through the loop and we can hence easily check right here
5399 whether something matched between the beginning and the end of
5401 case on_failure_jump_nastyloop
:
5402 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5403 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5406 assert ((re_opcode_t
)p
[-4] == no_op
);
5407 CHECK_INFINITE_LOOP (p
- 4, d
);
5408 PUSH_FAILURE_POINT (p
- 3, d
);
5412 /* Simple loop detecting on_failure_jump: just check on the
5413 failure stack if the same spot was already hit earlier. */
5414 case on_failure_jump_loop
:
5416 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5417 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5420 CHECK_INFINITE_LOOP (p
- 3, d
);
5421 PUSH_FAILURE_POINT (p
- 3, d
);
5425 /* Uses of on_failure_jump:
5427 Each alternative starts with an on_failure_jump that points
5428 to the beginning of the next alternative. Each alternative
5429 except the last ends with a jump that in effect jumps past
5430 the rest of the alternatives. (They really jump to the
5431 ending jump of the following alternative, because tensioning
5432 these jumps is a hassle.)
5434 Repeats start with an on_failure_jump that points past both
5435 the repetition text and either the following jump or
5436 pop_failure_jump back to this on_failure_jump. */
5437 case on_failure_jump
:
5438 IMMEDIATE_QUIT_CHECK
;
5439 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5440 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5443 PUSH_FAILURE_POINT (p
-3, d
);
5446 /* This operation is used for greedy *.
5447 Compare the beginning of the repeat with what in the
5448 pattern follows its end. If we can establish that there
5449 is nothing that they would both match, i.e., that we
5450 would have to backtrack because of (as in, e.g., `a*a')
5451 then we can use a non-backtracking loop based on
5452 on_failure_keep_string_jump instead of on_failure_jump. */
5453 case on_failure_jump_smart
:
5454 IMMEDIATE_QUIT_CHECK
;
5455 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5456 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5459 re_char
*p1
= p
; /* Next operation. */
5460 /* Here, we discard `const', making re_match non-reentrant. */
5461 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5462 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5464 p
-= 3; /* Reset so that we will re-execute the
5465 instruction once it's been changed. */
5467 EXTRACT_NUMBER (mcnt
, p2
- 2);
5469 /* Ensure this is a indeed the trivial kind of loop
5470 we are expecting. */
5471 assert (skip_one_char (p1
) == p2
- 3);
5472 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5473 DEBUG_STATEMENT (debug
+= 2);
5474 if (mutually_exclusive_p (bufp
, p1
, p2
))
5476 /* Use a fast `on_failure_keep_string_jump' loop. */
5477 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5478 *p3
= (unsigned char) on_failure_keep_string_jump
;
5479 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5483 /* Default to a safe `on_failure_jump' loop. */
5484 DEBUG_PRINT1 (" smart default => slow loop.\n");
5485 *p3
= (unsigned char) on_failure_jump
;
5487 DEBUG_STATEMENT (debug
-= 2);
5491 /* Unconditionally jump (without popping any failure points). */
5494 IMMEDIATE_QUIT_CHECK
;
5495 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5496 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5497 p
+= mcnt
; /* Do the jump. */
5498 DEBUG_PRINT2 ("(to %p).\n", p
);
5502 /* Have to succeed matching what follows at least n times.
5503 After that, handle like `on_failure_jump'. */
5505 /* Signedness doesn't matter since we only compare MCNT to 0. */
5506 EXTRACT_NUMBER (mcnt
, p
+ 2);
5507 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5509 /* Originally, mcnt is how many times we HAVE to succeed. */
5512 /* Here, we discard `const', making re_match non-reentrant. */
5513 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5516 PUSH_NUMBER (p2
, mcnt
);
5519 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5524 /* Signedness doesn't matter since we only compare MCNT to 0. */
5525 EXTRACT_NUMBER (mcnt
, p
+ 2);
5526 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5528 /* Originally, this is how many times we CAN jump. */
5531 /* Here, we discard `const', making re_match non-reentrant. */
5532 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5534 PUSH_NUMBER (p2
, mcnt
);
5535 goto unconditional_jump
;
5537 /* If don't have to jump any more, skip over the rest of command. */
5544 unsigned char *p2
; /* Location of the counter. */
5545 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5547 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5548 /* Here, we discard `const', making re_match non-reentrant. */
5549 p2
= (unsigned char*) p
+ mcnt
;
5550 /* Signedness doesn't matter since we only copy MCNT's bits . */
5551 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5552 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5553 PUSH_NUMBER (p2
, mcnt
);
5559 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5560 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5562 /* We SUCCEED (or FAIL) in one of the following cases: */
5564 /* Case 1: D is at the beginning or the end of string. */
5565 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5569 /* C1 is the character before D, S1 is the syntax of C1, C2
5570 is the character at D, and S2 is the syntax of C2. */
5575 int offset
= PTR_TO_OFFSET (d
- 1);
5576 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5577 UPDATE_SYNTAX_TABLE (charpos
);
5579 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5582 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5584 PREFETCH_NOLIMIT ();
5585 c2
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, dummy
);
5588 if (/* Case 2: Only one of S1 and S2 is Sword. */
5589 ((s1
== Sword
) != (s2
== Sword
))
5590 /* Case 3: Both of S1 and S2 are Sword, and macro
5591 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5592 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5601 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5603 /* We FAIL in one of the following cases: */
5605 /* Case 1: D is at the end of string. */
5606 if (AT_STRINGS_END (d
))
5610 /* C1 is the character before D, S1 is the syntax of C1, C2
5611 is the character at D, and S2 is the syntax of C2. */
5616 int offset
= PTR_TO_OFFSET (d
);
5617 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5618 UPDATE_SYNTAX_TABLE (charpos
);
5621 c2
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, dummy
);
5624 /* Case 2: S2 is not Sword. */
5628 /* Case 3: D is not at the beginning of string ... */
5629 if (!AT_STRINGS_BEG (d
))
5631 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5633 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5637 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5639 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5646 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5648 /* We FAIL in one of the following cases: */
5650 /* Case 1: D is at the beginning of string. */
5651 if (AT_STRINGS_BEG (d
))
5655 /* C1 is the character before D, S1 is the syntax of C1, C2
5656 is the character at D, and S2 is the syntax of C2. */
5661 int offset
= PTR_TO_OFFSET (d
) - 1;
5662 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5663 UPDATE_SYNTAX_TABLE (charpos
);
5665 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5668 /* Case 2: S1 is not Sword. */
5672 /* Case 3: D is not at the end of string ... */
5673 if (!AT_STRINGS_END (d
))
5675 PREFETCH_NOLIMIT ();
5676 c2
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, dummy
);
5678 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
5682 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5684 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5692 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
5694 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
5698 int offset
= PTR_TO_OFFSET (d
);
5699 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5700 UPDATE_SYNTAX_TABLE (pos1
);
5707 c
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5708 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
5716 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5717 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
5722 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5723 if (PTR_BYTE_POS (d
) != PT_BYTE
)
5728 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5729 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
5734 case notcategoryspec
:
5735 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
5737 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
5743 c
= TARGET_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5745 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
5756 continue; /* Successfully executed one pattern command; keep going. */
5759 /* We goto here if a matching operation fails. */
5761 IMMEDIATE_QUIT_CHECK
;
5762 if (!FAIL_STACK_EMPTY ())
5765 /* A restart point is known. Restore to that state. */
5766 DEBUG_PRINT1 ("\nFAIL:\n");
5767 POP_FAILURE_POINT (str
, pat
);
5768 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
5770 case on_failure_keep_string_jump
:
5771 assert (str
== NULL
);
5772 goto continue_failure_jump
;
5774 case on_failure_jump_nastyloop
:
5775 assert ((re_opcode_t
)pat
[-2] == no_op
);
5776 PUSH_FAILURE_POINT (pat
- 2, str
);
5779 case on_failure_jump_loop
:
5780 case on_failure_jump
:
5783 continue_failure_jump
:
5784 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
5789 /* A special frame used for nastyloops. */
5796 assert (p
>= bufp
->buffer
&& p
<= pend
);
5798 if (d
>= string1
&& d
<= end1
)
5802 break; /* Matching at this starting point really fails. */
5806 goto restore_best_regs
;
5810 return -1; /* Failure to match. */
5813 /* Subroutine definitions for re_match_2. */
5815 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5816 bytes; nonzero otherwise. */
5819 bcmp_translate (s1
, s2
, len
, translate
, target_multibyte
)
5822 RE_TRANSLATE_TYPE translate
;
5823 const int target_multibyte
;
5825 register re_char
*p1
= s1
, *p2
= s2
;
5826 re_char
*p1_end
= s1
+ len
;
5827 re_char
*p2_end
= s2
+ len
;
5829 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5830 different lengths, but relying on a single `len' would break this. -sm */
5831 while (p1
< p1_end
&& p2
< p2_end
)
5833 int p1_charlen
, p2_charlen
;
5834 re_wchar_t p1_ch
, p2_ch
;
5836 p1_ch
= TARGET_CHAR_AND_LENGTH (p1
, p1_end
- p1
, p1_charlen
);
5837 p2_ch
= TARGET_CHAR_AND_LENGTH (p2
, p2_end
- p2
, p2_charlen
);
5839 if (RE_TRANSLATE (translate
, p1_ch
)
5840 != RE_TRANSLATE (translate
, p2_ch
))
5843 p1
+= p1_charlen
, p2
+= p2_charlen
;
5846 if (p1
!= p1_end
|| p2
!= p2_end
)
5852 /* Entry points for GNU code. */
5854 /* re_compile_pattern is the GNU regular expression compiler: it
5855 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5856 Returns 0 if the pattern was valid, otherwise an error string.
5858 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5859 are set in BUFP on entry.
5861 We call regex_compile to do the actual compilation. */
5864 re_compile_pattern (pattern
, length
, bufp
)
5865 const char *pattern
;
5867 struct re_pattern_buffer
*bufp
;
5871 /* GNU code is written to assume at least RE_NREGS registers will be set
5872 (and at least one extra will be -1). */
5873 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5875 /* And GNU code determines whether or not to get register information
5876 by passing null for the REGS argument to re_match, etc., not by
5880 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
5884 return gettext (re_error_msgid
[(int) ret
]);
5886 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
5888 /* Entry points compatible with 4.2 BSD regex library. We don't define
5889 them unless specifically requested. */
5891 #if defined _REGEX_RE_COMP || defined _LIBC
5893 /* BSD has one and only one pattern buffer. */
5894 static struct re_pattern_buffer re_comp_buf
;
5898 /* Make these definitions weak in libc, so POSIX programs can redefine
5899 these names if they don't use our functions, and still use
5900 regcomp/regexec below without link errors. */
5910 if (!re_comp_buf
.buffer
)
5911 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5912 return (char *) gettext ("No previous regular expression");
5916 if (!re_comp_buf
.buffer
)
5918 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
5919 if (re_comp_buf
.buffer
== NULL
)
5920 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5921 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
5922 re_comp_buf
.allocated
= 200;
5924 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5925 if (re_comp_buf
.fastmap
== NULL
)
5926 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5927 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
5930 /* Since `re_exec' always passes NULL for the `regs' argument, we
5931 don't need to initialize the pattern buffer fields which affect it. */
5933 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
5938 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5939 return (char *) gettext (re_error_msgid
[(int) ret
]);
5950 const int len
= strlen (s
);
5952 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
5954 #endif /* _REGEX_RE_COMP */
5956 /* POSIX.2 functions. Don't define these for Emacs. */
5960 /* regcomp takes a regular expression as a string and compiles it.
5962 PREG is a regex_t *. We do not expect any fields to be initialized,
5963 since POSIX says we shouldn't. Thus, we set
5965 `buffer' to the compiled pattern;
5966 `used' to the length of the compiled pattern;
5967 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5968 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5969 RE_SYNTAX_POSIX_BASIC;
5970 `fastmap' to an allocated space for the fastmap;
5971 `fastmap_accurate' to zero;
5972 `re_nsub' to the number of subexpressions in PATTERN.
5974 PATTERN is the address of the pattern string.
5976 CFLAGS is a series of bits which affect compilation.
5978 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5979 use POSIX basic syntax.
5981 If REG_NEWLINE is set, then . and [^...] don't match newline.
5982 Also, regexec will try a match beginning after every newline.
5984 If REG_ICASE is set, then we considers upper- and lowercase
5985 versions of letters to be equivalent when matching.
5987 If REG_NOSUB is set, then when PREG is passed to regexec, that
5988 routine will report only success or failure, and nothing about the
5991 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5992 the return codes and their meanings.) */
5995 regcomp (preg
, pattern
, cflags
)
5996 regex_t
*__restrict preg
;
5997 const char *__restrict pattern
;
6002 = (cflags
& REG_EXTENDED
) ?
6003 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6005 /* regex_compile will allocate the space for the compiled pattern. */
6007 preg
->allocated
= 0;
6010 /* Try to allocate space for the fastmap. */
6011 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6013 if (cflags
& REG_ICASE
)
6018 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6019 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6020 if (preg
->translate
== NULL
)
6021 return (int) REG_ESPACE
;
6023 /* Map uppercase characters to corresponding lowercase ones. */
6024 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6025 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6028 preg
->translate
= NULL
;
6030 /* If REG_NEWLINE is set, newlines are treated differently. */
6031 if (cflags
& REG_NEWLINE
)
6032 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6033 syntax
&= ~RE_DOT_NEWLINE
;
6034 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6037 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6039 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6041 /* POSIX says a null character in the pattern terminates it, so we
6042 can use strlen here in compiling the pattern. */
6043 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6045 /* POSIX doesn't distinguish between an unmatched open-group and an
6046 unmatched close-group: both are REG_EPAREN. */
6047 if (ret
== REG_ERPAREN
)
6050 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6051 { /* Compute the fastmap now, since regexec cannot modify the pattern
6053 re_compile_fastmap (preg
);
6054 if (preg
->can_be_null
)
6055 { /* The fastmap can't be used anyway. */
6056 free (preg
->fastmap
);
6057 preg
->fastmap
= NULL
;
6062 WEAK_ALIAS (__regcomp
, regcomp
)
6065 /* regexec searches for a given pattern, specified by PREG, in the
6068 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6069 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6070 least NMATCH elements, and we set them to the offsets of the
6071 corresponding matched substrings.
6073 EFLAGS specifies `execution flags' which affect matching: if
6074 REG_NOTBOL is set, then ^ does not match at the beginning of the
6075 string; if REG_NOTEOL is set, then $ does not match at the end.
6077 We return 0 if we find a match and REG_NOMATCH if not. */
6080 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
6081 const regex_t
*__restrict preg
;
6082 const char *__restrict string
;
6084 regmatch_t pmatch
[];
6088 struct re_registers regs
;
6089 regex_t private_preg
;
6090 int len
= strlen (string
);
6091 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6093 private_preg
= *preg
;
6095 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6096 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6098 /* The user has told us exactly how many registers to return
6099 information about, via `nmatch'. We have to pass that on to the
6100 matching routines. */
6101 private_preg
.regs_allocated
= REGS_FIXED
;
6105 regs
.num_regs
= nmatch
;
6106 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6107 if (regs
.start
== NULL
)
6108 return (int) REG_NOMATCH
;
6109 regs
.end
= regs
.start
+ nmatch
;
6112 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6113 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6114 was a little bit longer but still only matching the real part.
6115 This works because the `endline' will check for a '\n' and will find a
6116 '\0', correctly deciding that this is not the end of a line.
6117 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6118 a convenient '\0' there. For all we know, the string could be preceded
6119 by '\n' which would throw things off. */
6121 /* Perform the searching operation. */
6122 ret
= re_search (&private_preg
, string
, len
,
6123 /* start: */ 0, /* range: */ len
,
6124 want_reg_info
? ®s
: (struct re_registers
*) 0);
6126 /* Copy the register information to the POSIX structure. */
6133 for (r
= 0; r
< nmatch
; r
++)
6135 pmatch
[r
].rm_so
= regs
.start
[r
];
6136 pmatch
[r
].rm_eo
= regs
.end
[r
];
6140 /* If we needed the temporary register info, free the space now. */
6144 /* We want zero return to mean success, unlike `re_search'. */
6145 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
6147 WEAK_ALIAS (__regexec
, regexec
)
6150 /* Returns a message corresponding to an error code, ERRCODE, returned
6151 from either regcomp or regexec. We don't use PREG here. */
6154 regerror (errcode
, preg
, errbuf
, errbuf_size
)
6156 const regex_t
*preg
;
6164 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6165 /* Only error codes returned by the rest of the code should be passed
6166 to this routine. If we are given anything else, or if other regex
6167 code generates an invalid error code, then the program has a bug.
6168 Dump core so we can fix it. */
6171 msg
= gettext (re_error_msgid
[errcode
]);
6173 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6175 if (errbuf_size
!= 0)
6177 if (msg_size
> errbuf_size
)
6179 strncpy (errbuf
, msg
, errbuf_size
- 1);
6180 errbuf
[errbuf_size
- 1] = 0;
6183 strcpy (errbuf
, msg
);
6188 WEAK_ALIAS (__regerror
, regerror
)
6191 /* Free dynamically allocated space used by PREG. */
6197 if (preg
->buffer
!= NULL
)
6198 free (preg
->buffer
);
6199 preg
->buffer
= NULL
;
6201 preg
->allocated
= 0;
6204 if (preg
->fastmap
!= NULL
)
6205 free (preg
->fastmap
);
6206 preg
->fastmap
= NULL
;
6207 preg
->fastmap_accurate
= 0;
6209 if (preg
->translate
!= NULL
)
6210 free (preg
->translate
);
6211 preg
->translate
= NULL
;
6213 WEAK_ALIAS (__regfree
, regfree
)
6215 #endif /* not emacs */