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-2011 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 3, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
26 need to modify the compiled regexp so that re_match can be reentrant.
27 - get rid of on_failure_jump_smart by doing the optimization in re_comp
28 rather than at run-time, so that re_match can be reentrant.
31 /* AIX requires this to be the first thing in the file. */
32 #if defined _AIX && !defined REGEX_MALLOC
40 #if defined STDC_HEADERS && !defined emacs
43 /* We need this for `regex.h', and perhaps for the Emacs include files. */
44 # include <sys/types.h>
47 /* Whether to use ISO C Amendment 1 wide char functions.
48 Those should not be used for Emacs since it uses its own. */
50 #define WIDE_CHAR_SUPPORT 1
52 #define WIDE_CHAR_SUPPORT \
53 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
56 /* For platform which support the ISO C amendement 1 functionality we
57 support user defined character classes. */
59 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
65 /* We have to keep the namespace clean. */
66 # define regfree(preg) __regfree (preg)
67 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
68 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
69 # define regerror(err_code, preg, errbuf, errbuf_size) \
70 __regerror(err_code, preg, errbuf, errbuf_size)
71 # define re_set_registers(bu, re, nu, st, en) \
72 __re_set_registers (bu, re, nu, st, en)
73 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
74 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
75 # define re_match(bufp, string, size, pos, regs) \
76 __re_match (bufp, string, size, pos, regs)
77 # define re_search(bufp, string, size, startpos, range, regs) \
78 __re_search (bufp, string, size, startpos, range, regs)
79 # define re_compile_pattern(pattern, length, bufp) \
80 __re_compile_pattern (pattern, length, bufp)
81 # define re_set_syntax(syntax) __re_set_syntax (syntax)
82 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
83 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
84 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
86 /* Make sure we call libc's function even if the user overrides them. */
87 # define btowc __btowc
88 # define iswctype __iswctype
89 # define wctype __wctype
91 # define WEAK_ALIAS(a,b) weak_alias (a, b)
93 /* We are also using some library internals. */
94 # include <locale/localeinfo.h>
95 # include <locale/elem-hash.h>
96 # include <langinfo.h>
98 # define WEAK_ALIAS(a,b)
101 /* This is for other GNU distributions with internationalized messages. */
102 #if HAVE_LIBINTL_H || defined _LIBC
103 # include <libintl.h>
105 # define gettext(msgid) (msgid)
109 /* This define is so xgettext can find the internationalizable
111 # define gettext_noop(String) String
114 /* The `emacs' switch turns on certain matching commands
115 that make sense only in Emacs. */
122 /* Make syntax table lookup grant data in gl_state. */
123 # define SYNTAX_ENTRY_VIA_PROPERTY
126 # include "character.h"
127 # include "category.h"
132 # define malloc xmalloc
136 # define realloc xrealloc
142 /* Converts the pointer to the char to BEG-based offset from the start. */
143 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
144 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
146 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
147 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
148 # define RE_STRING_CHAR(p, multibyte) \
149 (multibyte ? (STRING_CHAR (p)) : (*(p)))
150 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
151 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
153 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
155 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
157 /* Set C a (possibly converted to multibyte) character before P. P
158 points into a string which is the virtual concatenation of STR1
159 (which ends at END1) or STR2 (which ends at END2). */
160 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
162 if (target_multibyte) \
164 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
165 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
166 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
167 c = STRING_CHAR (dtemp); \
171 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
172 (c) = RE_CHAR_TO_MULTIBYTE (c); \
176 /* Set C a (possibly converted to multibyte) character at P, and set
177 LEN to the byte length of that character. */
178 # define GET_CHAR_AFTER(c, p, len) \
180 if (target_multibyte) \
181 (c) = STRING_CHAR_AND_LENGTH (p, len); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
190 #else /* not emacs */
192 /* If we are not linking with Emacs proper,
193 we can't use the relocating allocator
194 even if config.h says that we can. */
199 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
202 xmalloc (size_t size
)
205 val
= (void *) malloc (size
);
208 write (2, "virtual memory exhausted\n", 25);
215 xrealloc (void *block
, size_t size
)
218 /* We must call malloc explicitly when BLOCK is 0, since some
219 reallocs don't do this. */
221 val
= (void *) malloc (size
);
223 val
= (void *) realloc (block
, size
);
226 write (2, "virtual memory exhausted\n", 25);
235 # define malloc xmalloc
239 # define realloc xrealloc
241 /* This is the normal way of making sure we have memcpy, memcmp and memset. */
242 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
245 # include <strings.h>
247 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
250 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
254 /* Define the syntax stuff for \<, \>, etc. */
256 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
257 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1, Ssymbol
= 2 };
259 # define SWITCH_ENUM_CAST(x) (x)
261 /* Dummy macros for non-Emacs environments. */
262 # define CHAR_CHARSET(c) 0
263 # define CHARSET_LEADING_CODE_BASE(c) 0
264 # define MAX_MULTIBYTE_LENGTH 1
265 # define RE_MULTIBYTE_P(x) 0
266 # define RE_TARGET_MULTIBYTE_P(x) 0
267 # define WORD_BOUNDARY_P(c1, c2) (0)
268 # define CHAR_HEAD_P(p) (1)
269 # define SINGLE_BYTE_CHAR_P(c) (1)
270 # define SAME_CHARSET_P(c1, c2) (1)
271 # define BYTES_BY_CHAR_HEAD(p) (1)
272 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
273 # define STRING_CHAR(p) (*(p))
274 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
275 # define CHAR_STRING(c, s) (*(s) = (c), 1)
276 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
277 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
278 # define RE_CHAR_TO_MULTIBYTE(c) (c)
279 # define RE_CHAR_TO_UNIBYTE(c) (c)
280 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
281 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
282 # define GET_CHAR_AFTER(c, p, len) \
284 # define MAKE_CHAR(charset, c1, c2) (c1)
285 # define BYTE8_TO_CHAR(c) (c)
286 # define CHAR_BYTE8_P(c) (0)
287 # define CHAR_LEADING_CODE(c) (c)
289 #endif /* not emacs */
292 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
293 # define RE_TRANSLATE_P(TBL) (TBL)
296 /* Get the interface, including the syntax bits. */
299 /* isalpha etc. are used for the character classes. */
304 /* 1 if C is an ASCII character. */
305 # define IS_REAL_ASCII(c) ((c) < 0200)
307 /* 1 if C is a unibyte character. */
308 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
310 /* The Emacs definitions should not be directly affected by locales. */
312 /* In Emacs, these are only used for single-byte characters. */
313 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
314 # define ISCNTRL(c) ((c) < ' ')
315 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
316 || ((c) >= 'a' && (c) <= 'f') \
317 || ((c) >= 'A' && (c) <= 'F'))
319 /* This is only used for single-byte characters. */
320 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
322 /* The rest must handle multibyte characters. */
324 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
325 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
328 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
329 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
332 # define ISALNUM(c) (IS_REAL_ASCII (c) \
333 ? (((c) >= 'a' && (c) <= 'z') \
334 || ((c) >= 'A' && (c) <= 'Z') \
335 || ((c) >= '0' && (c) <= '9')) \
336 : SYNTAX (c) == Sword)
338 # define ISALPHA(c) (IS_REAL_ASCII (c) \
339 ? (((c) >= 'a' && (c) <= 'z') \
340 || ((c) >= 'A' && (c) <= 'Z')) \
341 : SYNTAX (c) == Sword)
343 # define ISLOWER(c) (LOWERCASEP (c))
345 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
346 ? ((c) > ' ' && (c) < 0177 \
347 && !(((c) >= 'a' && (c) <= 'z') \
348 || ((c) >= 'A' && (c) <= 'Z') \
349 || ((c) >= '0' && (c) <= '9'))) \
350 : SYNTAX (c) != Sword)
352 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
354 # define ISUPPER(c) (UPPERCASEP (c))
356 # define ISWORD(c) (SYNTAX (c) == Sword)
358 #else /* not emacs */
360 /* Jim Meyering writes:
362 "... Some ctype macros are valid only for character codes that
363 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
364 using /bin/cc or gcc but without giving an ansi option). So, all
365 ctype uses should be through macros like ISPRINT... If
366 STDC_HEADERS is defined, then autoconf has verified that the ctype
367 macros don't need to be guarded with references to isascii. ...
368 Defining isascii to 1 should let any compiler worth its salt
369 eliminate the && through constant folding."
370 Solaris defines some of these symbols so we must undefine them first. */
373 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
374 # define ISASCII(c) 1
376 # define ISASCII(c) isascii(c)
379 /* 1 if C is an ASCII character. */
380 # define IS_REAL_ASCII(c) ((c) < 0200)
382 /* This distinction is not meaningful, except in Emacs. */
383 # define ISUNIBYTE(c) 1
386 # define ISBLANK(c) (ISASCII (c) && isblank (c))
388 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
391 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
393 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
397 # define ISPRINT(c) (ISASCII (c) && isprint (c))
398 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
399 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
400 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
401 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
402 # define ISLOWER(c) (ISASCII (c) && islower (c))
403 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
404 # define ISSPACE(c) (ISASCII (c) && isspace (c))
405 # define ISUPPER(c) (ISASCII (c) && isupper (c))
406 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
408 # define ISWORD(c) ISALPHA(c)
411 # define TOLOWER(c) _tolower(c)
413 # define TOLOWER(c) tolower(c)
416 /* How many characters in the character set. */
417 # define CHAR_SET_SIZE 256
421 extern char *re_syntax_table
;
423 # else /* not SYNTAX_TABLE */
425 static char re_syntax_table
[CHAR_SET_SIZE
];
428 init_syntax_once (void)
436 memset (re_syntax_table
, 0, sizeof re_syntax_table
);
438 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
440 re_syntax_table
[c
] = Sword
;
442 re_syntax_table
['_'] = Ssymbol
;
447 # endif /* not SYNTAX_TABLE */
449 # define SYNTAX(c) re_syntax_table[(c)]
451 #endif /* not emacs */
454 # define NULL (void *)0
457 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
458 since ours (we hope) works properly with all combinations of
459 machines, compilers, `char' and `unsigned char' argument types.
460 (Per Bothner suggested the basic approach.) */
461 #undef SIGN_EXTEND_CHAR
463 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
464 #else /* not __STDC__ */
465 /* As in Harbison and Steele. */
466 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
469 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
470 use `alloca' instead of `malloc'. This is because using malloc in
471 re_search* or re_match* could cause memory leaks when C-g is used in
472 Emacs; also, malloc is slower and causes storage fragmentation. On
473 the other hand, malloc is more portable, and easier to debug.
475 Because we sometimes use alloca, some routines have to be macros,
476 not functions -- `alloca'-allocated space disappears at the end of the
477 function it is called in. */
481 # define REGEX_ALLOCATE malloc
482 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
483 # define REGEX_FREE free
485 #else /* not REGEX_MALLOC */
487 /* Emacs already defines alloca, sometimes. */
490 /* Make alloca work the best possible way. */
492 # define alloca __builtin_alloca
493 # else /* not __GNUC__ */
494 # ifdef HAVE_ALLOCA_H
496 # endif /* HAVE_ALLOCA_H */
497 # endif /* not __GNUC__ */
499 # endif /* not alloca */
501 # define REGEX_ALLOCATE alloca
503 /* Assumes a `char *destination' variable. */
504 # define REGEX_REALLOCATE(source, osize, nsize) \
505 (destination = (char *) alloca (nsize), \
506 memcpy (destination, source, osize))
508 /* No need to do anything to free, after alloca. */
509 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
511 #endif /* not REGEX_MALLOC */
513 /* Define how to allocate the failure stack. */
515 #if defined REL_ALLOC && defined REGEX_MALLOC
517 # define REGEX_ALLOCATE_STACK(size) \
518 r_alloc (&failure_stack_ptr, (size))
519 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
520 r_re_alloc (&failure_stack_ptr, (nsize))
521 # define REGEX_FREE_STACK(ptr) \
522 r_alloc_free (&failure_stack_ptr)
524 #else /* not using relocating allocator */
528 # define REGEX_ALLOCATE_STACK malloc
529 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
530 # define REGEX_FREE_STACK free
532 # else /* not REGEX_MALLOC */
534 # define REGEX_ALLOCATE_STACK alloca
536 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
537 REGEX_REALLOCATE (source, osize, nsize)
538 /* No need to explicitly free anything. */
539 # define REGEX_FREE_STACK(arg) ((void)0)
541 # endif /* not REGEX_MALLOC */
542 #endif /* not using relocating allocator */
545 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
546 `string1' or just past its end. This works if PTR is NULL, which is
548 #define FIRST_STRING_P(ptr) \
549 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
551 /* (Re)Allocate N items of type T using malloc, or fail. */
552 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
553 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
554 #define RETALLOC_IF(addr, n, t) \
555 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
556 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
558 #define BYTEWIDTH 8 /* In bits. */
560 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
564 #define MAX(a, b) ((a) > (b) ? (a) : (b))
565 #define MIN(a, b) ((a) < (b) ? (a) : (b))
567 /* Type of source-pattern and string chars. */
568 typedef const unsigned char re_char
;
570 typedef char boolean
;
574 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
575 re_char
*string1
, int size1
,
576 re_char
*string2
, int size2
,
578 struct re_registers
*regs
,
581 /* These are the command codes that appear in compiled regular
582 expressions. Some opcodes are followed by argument bytes. A
583 command code can specify any interpretation whatsoever for its
584 arguments. Zero bytes may appear in the compiled regular expression. */
590 /* Succeed right away--no more backtracking. */
593 /* Followed by one byte giving n, then by n literal bytes. */
596 /* Matches any (more or less) character. */
599 /* Matches any one char belonging to specified set. First
600 following byte is number of bitmap bytes. Then come bytes
601 for a bitmap saying which chars are in. Bits in each byte
602 are ordered low-bit-first. A character is in the set if its
603 bit is 1. A character too large to have a bit in the map is
604 automatically not in the set.
606 If the length byte has the 0x80 bit set, then that stuff
607 is followed by a range table:
608 2 bytes of flags for character sets (low 8 bits, high 8 bits)
609 See RANGE_TABLE_WORK_BITS below.
610 2 bytes, the number of pairs that follow (upto 32767)
611 pairs, each 2 multibyte characters,
612 each multibyte character represented as 3 bytes. */
615 /* Same parameters as charset, but match any character that is
616 not one of those specified. */
619 /* Start remembering the text that is matched, for storing in a
620 register. Followed by one byte with the register number, in
621 the range 0 to one less than the pattern buffer's re_nsub
625 /* Stop remembering the text that is matched and store it in a
626 memory register. Followed by one byte with the register
627 number, in the range 0 to one less than `re_nsub' in the
631 /* Match a duplicate of something remembered. Followed by one
632 byte containing the register number. */
635 /* Fail unless at beginning of line. */
638 /* Fail unless at end of line. */
641 /* Succeeds if at beginning of buffer (if emacs) or at beginning
642 of string to be matched (if not). */
645 /* Analogously, for end of buffer/string. */
648 /* Followed by two byte relative address to which to jump. */
651 /* Followed by two-byte relative address of place to resume at
652 in case of failure. */
655 /* Like on_failure_jump, but pushes a placeholder instead of the
656 current string position when executed. */
657 on_failure_keep_string_jump
,
659 /* Just like `on_failure_jump', except that it checks that we
660 don't get stuck in an infinite loop (matching an empty string
662 on_failure_jump_loop
,
664 /* Just like `on_failure_jump_loop', except that it checks for
665 a different kind of loop (the kind that shows up with non-greedy
666 operators). This operation has to be immediately preceded
668 on_failure_jump_nastyloop
,
670 /* A smart `on_failure_jump' used for greedy * and + operators.
671 It analyses the loop before which it is put and if the
672 loop does not require backtracking, it changes itself to
673 `on_failure_keep_string_jump' and short-circuits the loop,
674 else it just defaults to changing itself into `on_failure_jump'.
675 It assumes that it is pointing to just past a `jump'. */
676 on_failure_jump_smart
,
678 /* Followed by two-byte relative address and two-byte number n.
679 After matching N times, jump to the address upon failure.
680 Does not work if N starts at 0: use on_failure_jump_loop
684 /* Followed by two-byte relative address, and two-byte number n.
685 Jump to the address N times, then fail. */
688 /* Set the following two-byte relative address to the
689 subsequent two-byte number. The address *includes* the two
693 wordbeg
, /* Succeeds if at word beginning. */
694 wordend
, /* Succeeds if at word end. */
696 wordbound
, /* Succeeds if at a word boundary. */
697 notwordbound
, /* Succeeds if not at a word boundary. */
699 symbeg
, /* Succeeds if at symbol beginning. */
700 symend
, /* Succeeds if at symbol end. */
702 /* Matches any character whose syntax is specified. Followed by
703 a byte which contains a syntax code, e.g., Sword. */
706 /* Matches any character whose syntax is not that specified. */
710 ,before_dot
, /* Succeeds if before point. */
711 at_dot
, /* Succeeds if at point. */
712 after_dot
, /* Succeeds if after point. */
714 /* Matches any character whose category-set contains the specified
715 category. The operator is followed by a byte which contains a
716 category code (mnemonic ASCII character). */
719 /* Matches any character whose category-set does not contain the
720 specified category. The operator is followed by a byte which
721 contains the category code (mnemonic ASCII character). */
726 /* Common operations on the compiled pattern. */
728 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
730 #define STORE_NUMBER(destination, number) \
732 (destination)[0] = (number) & 0377; \
733 (destination)[1] = (number) >> 8; \
736 /* Same as STORE_NUMBER, except increment DESTINATION to
737 the byte after where the number is stored. Therefore, DESTINATION
738 must be an lvalue. */
740 #define STORE_NUMBER_AND_INCR(destination, number) \
742 STORE_NUMBER (destination, number); \
743 (destination) += 2; \
746 /* Put into DESTINATION a number stored in two contiguous bytes starting
749 #define EXTRACT_NUMBER(destination, source) \
751 (destination) = *(source) & 0377; \
752 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
756 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
758 extract_number (dest
, source
)
762 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
763 *dest
= *source
& 0377;
767 # ifndef EXTRACT_MACROS /* To debug the macros. */
768 # undef EXTRACT_NUMBER
769 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
770 # endif /* not EXTRACT_MACROS */
774 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
775 SOURCE must be an lvalue. */
777 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
779 EXTRACT_NUMBER (destination, source); \
784 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
787 extract_number_and_incr (destination
, source
)
791 extract_number (destination
, *source
);
795 # ifndef EXTRACT_MACROS
796 # undef EXTRACT_NUMBER_AND_INCR
797 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
798 extract_number_and_incr (&dest, &src)
799 # endif /* not EXTRACT_MACROS */
803 /* Store a multibyte character in three contiguous bytes starting
804 DESTINATION, and increment DESTINATION to the byte after where the
805 character is stored. Therefore, DESTINATION must be an lvalue. */
807 #define STORE_CHARACTER_AND_INCR(destination, character) \
809 (destination)[0] = (character) & 0377; \
810 (destination)[1] = ((character) >> 8) & 0377; \
811 (destination)[2] = (character) >> 16; \
812 (destination) += 3; \
815 /* Put into DESTINATION a character stored in three contiguous bytes
816 starting at SOURCE. */
818 #define EXTRACT_CHARACTER(destination, source) \
820 (destination) = ((source)[0] \
821 | ((source)[1] << 8) \
822 | ((source)[2] << 16)); \
826 /* Macros for charset. */
828 /* Size of bitmap of charset P in bytes. P is a start of charset,
829 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
830 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
832 /* Nonzero if charset P has range table. */
833 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
835 /* Return the address of range table of charset P. But not the start
836 of table itself, but the before where the number of ranges is
837 stored. `2 +' means to skip re_opcode_t and size of bitmap,
838 and the 2 bytes of flags at the start of the range table. */
839 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
841 /* Extract the bit flags that start a range table. */
842 #define CHARSET_RANGE_TABLE_BITS(p) \
843 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
844 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
846 /* Test if C is listed in the bitmap of charset P. */
847 #define CHARSET_LOOKUP_BITMAP(p, c) \
848 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
849 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
851 /* Return the address of end of RANGE_TABLE. COUNT is number of
852 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
853 is start of range and end of range. `* 3' is size of each start
855 #define CHARSET_RANGE_TABLE_END(range_table, count) \
856 ((range_table) + (count) * 2 * 3)
858 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
859 COUNT is number of ranges in RANGE_TABLE. */
860 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
863 re_wchar_t range_start, range_end; \
865 re_char *range_table_end \
866 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
868 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
870 EXTRACT_CHARACTER (range_start, rtp); \
871 EXTRACT_CHARACTER (range_end, rtp + 3); \
873 if (range_start <= (c) && (c) <= range_end) \
882 /* Test if C is in range table of CHARSET. The flag NOT is negated if
883 C is listed in it. */
884 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
887 /* Number of ranges in range table. */ \
889 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
891 EXTRACT_NUMBER_AND_INCR (count, range_table); \
892 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
896 /* If DEBUG is defined, Regex prints many voluminous messages about what
897 it is doing (if the variable `debug' is nonzero). If linked with the
898 main program in `iregex.c', you can enter patterns and strings
899 interactively. And if linked with the main program in `main.c' and
900 the other test files, you can run the already-written tests. */
904 /* We use standard I/O for debugging. */
907 /* It is useful to test things that ``must'' be true when debugging. */
910 static int debug
= -100000;
912 # define DEBUG_STATEMENT(e) e
913 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
914 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
915 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
916 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
917 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
918 if (debug > 0) print_partial_compiled_pattern (s, e)
919 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
920 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
923 /* Print the fastmap in human-readable form. */
926 print_fastmap (fastmap
)
929 unsigned was_a_range
= 0;
932 while (i
< (1 << BYTEWIDTH
))
938 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
954 /* Print a compiled pattern string in human-readable form, starting at
955 the START pointer into it and ending just before the pointer END. */
958 print_partial_compiled_pattern (start
, end
)
968 fprintf (stderr
, "(null)\n");
972 /* Loop over pattern commands. */
975 fprintf (stderr
, "%d:\t", p
- start
);
977 switch ((re_opcode_t
) *p
++)
980 fprintf (stderr
, "/no_op");
984 fprintf (stderr
, "/succeed");
989 fprintf (stderr
, "/exactn/%d", mcnt
);
992 fprintf (stderr
, "/%c", *p
++);
998 fprintf (stderr
, "/start_memory/%d", *p
++);
1002 fprintf (stderr
, "/stop_memory/%d", *p
++);
1006 fprintf (stderr
, "/duplicate/%d", *p
++);
1010 fprintf (stderr
, "/anychar");
1016 register int c
, last
= -100;
1017 register int in_range
= 0;
1018 int length
= CHARSET_BITMAP_SIZE (p
- 1);
1019 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
1021 fprintf (stderr
, "/charset [%s",
1022 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
1025 fprintf (stderr
, " !extends past end of pattern! ");
1027 for (c
= 0; c
< 256; c
++)
1029 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
1031 /* Are we starting a range? */
1032 if (last
+ 1 == c
&& ! in_range
)
1034 fprintf (stderr
, "-");
1037 /* Have we broken a range? */
1038 else if (last
+ 1 != c
&& in_range
)
1040 fprintf (stderr
, "%c", last
);
1045 fprintf (stderr
, "%c", c
);
1051 fprintf (stderr
, "%c", last
);
1053 fprintf (stderr
, "]");
1057 if (has_range_table
)
1060 fprintf (stderr
, "has-range-table");
1062 /* ??? Should print the range table; for now, just skip it. */
1063 p
+= 2; /* skip range table bits */
1064 EXTRACT_NUMBER_AND_INCR (count
, p
);
1065 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1071 fprintf (stderr
, "/begline");
1075 fprintf (stderr
, "/endline");
1078 case on_failure_jump
:
1079 extract_number_and_incr (&mcnt
, &p
);
1080 fprintf (stderr
, "/on_failure_jump to %d", p
+ mcnt
- start
);
1083 case on_failure_keep_string_jump
:
1084 extract_number_and_incr (&mcnt
, &p
);
1085 fprintf (stderr
, "/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1088 case on_failure_jump_nastyloop
:
1089 extract_number_and_incr (&mcnt
, &p
);
1090 fprintf (stderr
, "/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1093 case on_failure_jump_loop
:
1094 extract_number_and_incr (&mcnt
, &p
);
1095 fprintf (stderr
, "/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1098 case on_failure_jump_smart
:
1099 extract_number_and_incr (&mcnt
, &p
);
1100 fprintf (stderr
, "/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1104 extract_number_and_incr (&mcnt
, &p
);
1105 fprintf (stderr
, "/jump to %d", p
+ mcnt
- start
);
1109 extract_number_and_incr (&mcnt
, &p
);
1110 extract_number_and_incr (&mcnt2
, &p
);
1111 fprintf (stderr
, "/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1115 extract_number_and_incr (&mcnt
, &p
);
1116 extract_number_and_incr (&mcnt2
, &p
);
1117 fprintf (stderr
, "/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1121 extract_number_and_incr (&mcnt
, &p
);
1122 extract_number_and_incr (&mcnt2
, &p
);
1123 fprintf (stderr
, "/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1127 fprintf (stderr
, "/wordbound");
1131 fprintf (stderr
, "/notwordbound");
1135 fprintf (stderr
, "/wordbeg");
1139 fprintf (stderr
, "/wordend");
1143 fprintf (stderr
, "/symbeg");
1147 fprintf (stderr
, "/symend");
1151 fprintf (stderr
, "/syntaxspec");
1153 fprintf (stderr
, "/%d", mcnt
);
1157 fprintf (stderr
, "/notsyntaxspec");
1159 fprintf (stderr
, "/%d", mcnt
);
1164 fprintf (stderr
, "/before_dot");
1168 fprintf (stderr
, "/at_dot");
1172 fprintf (stderr
, "/after_dot");
1176 fprintf (stderr
, "/categoryspec");
1178 fprintf (stderr
, "/%d", mcnt
);
1181 case notcategoryspec
:
1182 fprintf (stderr
, "/notcategoryspec");
1184 fprintf (stderr
, "/%d", mcnt
);
1189 fprintf (stderr
, "/begbuf");
1193 fprintf (stderr
, "/endbuf");
1197 fprintf (stderr
, "?%d", *(p
-1));
1200 fprintf (stderr
, "\n");
1203 fprintf (stderr
, "%d:\tend of pattern.\n", p
- start
);
1208 print_compiled_pattern (bufp
)
1209 struct re_pattern_buffer
*bufp
;
1211 re_char
*buffer
= bufp
->buffer
;
1213 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1214 printf ("%ld bytes used/%ld bytes allocated.\n",
1215 bufp
->used
, bufp
->allocated
);
1217 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1219 printf ("fastmap: ");
1220 print_fastmap (bufp
->fastmap
);
1223 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1224 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1225 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1226 printf ("no_sub: %d\t", bufp
->no_sub
);
1227 printf ("not_bol: %d\t", bufp
->not_bol
);
1228 printf ("not_eol: %d\t", bufp
->not_eol
);
1229 printf ("syntax: %lx\n", bufp
->syntax
);
1231 /* Perhaps we should print the translate table? */
1236 print_double_string (where
, string1
, size1
, string2
, size2
)
1249 if (FIRST_STRING_P (where
))
1251 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1252 putchar (string1
[this_char
]);
1257 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1258 putchar (string2
[this_char
]);
1262 #else /* not DEBUG */
1267 # define DEBUG_STATEMENT(e)
1268 # define DEBUG_PRINT1(x)
1269 # define DEBUG_PRINT2(x1, x2)
1270 # define DEBUG_PRINT3(x1, x2, x3)
1271 # define DEBUG_PRINT4(x1, x2, x3, x4)
1272 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1273 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1275 #endif /* not DEBUG */
1277 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1278 also be assigned to arbitrarily: each pattern buffer stores its own
1279 syntax, so it can be changed between regex compilations. */
1280 /* This has no initializer because initialized variables in Emacs
1281 become read-only after dumping. */
1282 reg_syntax_t re_syntax_options
;
1285 /* Specify the precise syntax of regexps for compilation. This provides
1286 for compatibility for various utilities which historically have
1287 different, incompatible syntaxes.
1289 The argument SYNTAX is a bit mask comprised of the various bits
1290 defined in regex.h. We return the old syntax. */
1293 re_set_syntax (reg_syntax_t syntax
)
1295 reg_syntax_t ret
= re_syntax_options
;
1297 re_syntax_options
= syntax
;
1300 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1302 /* Regexp to use to replace spaces, or NULL meaning don't. */
1303 static re_char
*whitespace_regexp
;
1306 re_set_whitespace_regexp (const char *regexp
)
1308 whitespace_regexp
= (re_char
*) regexp
;
1310 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1312 /* This table gives an error message for each of the error codes listed
1313 in regex.h. Obviously the order here has to be same as there.
1314 POSIX doesn't require that we do anything for REG_NOERROR,
1315 but why not be nice? */
1317 static const char *re_error_msgid
[] =
1319 gettext_noop ("Success"), /* REG_NOERROR */
1320 gettext_noop ("No match"), /* REG_NOMATCH */
1321 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1322 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1323 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1324 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1325 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1326 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1327 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1328 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1329 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1330 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1331 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1332 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1333 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1334 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1335 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1336 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1339 /* Avoiding alloca during matching, to placate r_alloc. */
1341 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1342 searching and matching functions should not call alloca. On some
1343 systems, alloca is implemented in terms of malloc, and if we're
1344 using the relocating allocator routines, then malloc could cause a
1345 relocation, which might (if the strings being searched are in the
1346 ralloc heap) shift the data out from underneath the regexp
1349 Here's another reason to avoid allocation: Emacs
1350 processes input from X in a signal handler; processing X input may
1351 call malloc; if input arrives while a matching routine is calling
1352 malloc, then we're scrod. But Emacs can't just block input while
1353 calling matching routines; then we don't notice interrupts when
1354 they come in. So, Emacs blocks input around all regexp calls
1355 except the matching calls, which it leaves unprotected, in the
1356 faith that they will not malloc. */
1358 /* Normally, this is fine. */
1359 #define MATCH_MAY_ALLOCATE
1361 /* The match routines may not allocate if (1) they would do it with malloc
1362 and (2) it's not safe for them to use malloc.
1363 Note that if REL_ALLOC is defined, matching would not use malloc for the
1364 failure stack, but we would still use it for the register vectors;
1365 so REL_ALLOC should not affect this. */
1366 #if defined REGEX_MALLOC && defined emacs
1367 # undef MATCH_MAY_ALLOCATE
1371 /* Failure stack declarations and macros; both re_compile_fastmap and
1372 re_match_2 use a failure stack. These have to be macros because of
1373 REGEX_ALLOCATE_STACK. */
1376 /* Approximate number of failure points for which to initially allocate space
1377 when matching. If this number is exceeded, we allocate more
1378 space, so it is not a hard limit. */
1379 #ifndef INIT_FAILURE_ALLOC
1380 # define INIT_FAILURE_ALLOC 20
1383 /* Roughly the maximum number of failure points on the stack. Would be
1384 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1385 This is a variable only so users of regex can assign to it; we never
1386 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1387 before using it, so it should probably be a byte-count instead. */
1388 # if defined MATCH_MAY_ALLOCATE
1389 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1390 whose default stack limit is 2mb. In order for a larger
1391 value to work reliably, you have to try to make it accord
1392 with the process stack limit. */
1393 size_t re_max_failures
= 40000;
1395 size_t re_max_failures
= 4000;
1398 union fail_stack_elt
1401 /* This should be the biggest `int' that's no bigger than a pointer. */
1405 typedef union fail_stack_elt fail_stack_elt_t
;
1409 fail_stack_elt_t
*stack
;
1411 size_t avail
; /* Offset of next open position. */
1412 size_t frame
; /* Offset of the cur constructed frame. */
1415 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1416 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1419 /* Define macros to initialize and free the failure stack.
1420 Do `return -2' if the alloc fails. */
1422 #ifdef MATCH_MAY_ALLOCATE
1423 # define INIT_FAIL_STACK() \
1425 fail_stack.stack = (fail_stack_elt_t *) \
1426 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1427 * sizeof (fail_stack_elt_t)); \
1429 if (fail_stack.stack == NULL) \
1432 fail_stack.size = INIT_FAILURE_ALLOC; \
1433 fail_stack.avail = 0; \
1434 fail_stack.frame = 0; \
1437 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1439 # define INIT_FAIL_STACK() \
1441 fail_stack.avail = 0; \
1442 fail_stack.frame = 0; \
1445 # define RESET_FAIL_STACK() ((void)0)
1449 /* Double the size of FAIL_STACK, up to a limit
1450 which allows approximately `re_max_failures' items.
1452 Return 1 if succeeds, and 0 if either ran out of memory
1453 allocating space for it or it was already too large.
1455 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1457 /* Factor to increase the failure stack size by
1458 when we increase it.
1459 This used to be 2, but 2 was too wasteful
1460 because the old discarded stacks added up to as much space
1461 were as ultimate, maximum-size stack. */
1462 #define FAIL_STACK_GROWTH_FACTOR 4
1464 #define GROW_FAIL_STACK(fail_stack) \
1465 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1466 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1468 : ((fail_stack).stack \
1469 = (fail_stack_elt_t *) \
1470 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1471 (fail_stack).size * sizeof (fail_stack_elt_t), \
1472 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1473 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1474 * FAIL_STACK_GROWTH_FACTOR))), \
1476 (fail_stack).stack == NULL \
1478 : ((fail_stack).size \
1479 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1480 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1481 * FAIL_STACK_GROWTH_FACTOR)) \
1482 / sizeof (fail_stack_elt_t)), \
1486 /* Push a pointer value onto the failure stack.
1487 Assumes the variable `fail_stack'. Probably should only
1488 be called from within `PUSH_FAILURE_POINT'. */
1489 #define PUSH_FAILURE_POINTER(item) \
1490 fail_stack.stack[fail_stack.avail++].pointer = (item)
1492 /* This pushes an integer-valued item onto the failure stack.
1493 Assumes the variable `fail_stack'. Probably should only
1494 be called from within `PUSH_FAILURE_POINT'. */
1495 #define PUSH_FAILURE_INT(item) \
1496 fail_stack.stack[fail_stack.avail++].integer = (item)
1498 /* Push a fail_stack_elt_t value onto the failure stack.
1499 Assumes the variable `fail_stack'. Probably should only
1500 be called from within `PUSH_FAILURE_POINT'. */
1501 #define PUSH_FAILURE_ELT(item) \
1502 fail_stack.stack[fail_stack.avail++] = (item)
1504 /* These three POP... operations complement the three PUSH... operations.
1505 All assume that `fail_stack' is nonempty. */
1506 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1507 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1508 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1510 /* Individual items aside from the registers. */
1511 #define NUM_NONREG_ITEMS 3
1513 /* Used to examine the stack (to detect infinite loops). */
1514 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1515 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1516 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1517 #define TOP_FAILURE_HANDLE() fail_stack.frame
1520 #define ENSURE_FAIL_STACK(space) \
1521 while (REMAINING_AVAIL_SLOTS <= space) { \
1522 if (!GROW_FAIL_STACK (fail_stack)) \
1524 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1525 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1528 /* Push register NUM onto the stack. */
1529 #define PUSH_FAILURE_REG(num) \
1531 char *destination; \
1532 ENSURE_FAIL_STACK(3); \
1533 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1534 num, regstart[num], regend[num]); \
1535 PUSH_FAILURE_POINTER (regstart[num]); \
1536 PUSH_FAILURE_POINTER (regend[num]); \
1537 PUSH_FAILURE_INT (num); \
1540 /* Change the counter's value to VAL, but make sure that it will
1541 be reset when backtracking. */
1542 #define PUSH_NUMBER(ptr,val) \
1544 char *destination; \
1546 ENSURE_FAIL_STACK(3); \
1547 EXTRACT_NUMBER (c, ptr); \
1548 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1549 PUSH_FAILURE_INT (c); \
1550 PUSH_FAILURE_POINTER (ptr); \
1551 PUSH_FAILURE_INT (-1); \
1552 STORE_NUMBER (ptr, val); \
1555 /* Pop a saved register off the stack. */
1556 #define POP_FAILURE_REG_OR_COUNT() \
1558 int pfreg = POP_FAILURE_INT (); \
1561 /* It's a counter. */ \
1562 /* Here, we discard `const', making re_match non-reentrant. */ \
1563 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1564 pfreg = POP_FAILURE_INT (); \
1565 STORE_NUMBER (ptr, pfreg); \
1566 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, pfreg); \
1570 regend[pfreg] = POP_FAILURE_POINTER (); \
1571 regstart[pfreg] = POP_FAILURE_POINTER (); \
1572 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1573 pfreg, regstart[pfreg], regend[pfreg]); \
1577 /* Check that we are not stuck in an infinite loop. */
1578 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1580 int failure = TOP_FAILURE_HANDLE (); \
1581 /* Check for infinite matching loops */ \
1582 while (failure > 0 \
1583 && (FAILURE_STR (failure) == string_place \
1584 || FAILURE_STR (failure) == NULL)) \
1586 assert (FAILURE_PAT (failure) >= bufp->buffer \
1587 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1588 if (FAILURE_PAT (failure) == pat_cur) \
1593 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1594 failure = NEXT_FAILURE_HANDLE(failure); \
1596 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1599 /* Push the information about the state we will need
1600 if we ever fail back to it.
1602 Requires variables fail_stack, regstart, regend and
1603 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1606 Does `return FAILURE_CODE' if runs out of memory. */
1608 #define PUSH_FAILURE_POINT(pattern, string_place) \
1610 char *destination; \
1611 /* Must be int, so when we don't save any registers, the arithmetic \
1612 of 0 + -1 isn't done as unsigned. */ \
1614 DEBUG_STATEMENT (nfailure_points_pushed++); \
1615 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1616 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1617 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1619 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1621 DEBUG_PRINT1 ("\n"); \
1623 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1624 PUSH_FAILURE_INT (fail_stack.frame); \
1626 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1627 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1628 DEBUG_PRINT1 ("'\n"); \
1629 PUSH_FAILURE_POINTER (string_place); \
1631 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1632 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1633 PUSH_FAILURE_POINTER (pattern); \
1635 /* Close the frame by moving the frame pointer past it. */ \
1636 fail_stack.frame = fail_stack.avail; \
1639 /* Estimate the size of data pushed by a typical failure stack entry.
1640 An estimate is all we need, because all we use this for
1641 is to choose a limit for how big to make the failure stack. */
1642 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1643 #define TYPICAL_FAILURE_SIZE 20
1645 /* How many items can still be added to the stack without overflowing it. */
1646 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1649 /* Pops what PUSH_FAIL_STACK pushes.
1651 We restore into the parameters, all of which should be lvalues:
1652 STR -- the saved data position.
1653 PAT -- the saved pattern position.
1654 REGSTART, REGEND -- arrays of string positions.
1656 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1657 `pend', `string1', `size1', `string2', and `size2'. */
1659 #define POP_FAILURE_POINT(str, pat) \
1661 assert (!FAIL_STACK_EMPTY ()); \
1663 /* Remove failure points and point to how many regs pushed. */ \
1664 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1665 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1666 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1668 /* Pop the saved registers. */ \
1669 while (fail_stack.frame < fail_stack.avail) \
1670 POP_FAILURE_REG_OR_COUNT (); \
1672 pat = POP_FAILURE_POINTER (); \
1673 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1674 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1676 /* If the saved string location is NULL, it came from an \
1677 on_failure_keep_string_jump opcode, and we want to throw away the \
1678 saved NULL, thus retaining our current position in the string. */ \
1679 str = POP_FAILURE_POINTER (); \
1680 DEBUG_PRINT2 (" Popping string %p: `", str); \
1681 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1682 DEBUG_PRINT1 ("'\n"); \
1684 fail_stack.frame = POP_FAILURE_INT (); \
1685 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1687 assert (fail_stack.avail >= 0); \
1688 assert (fail_stack.frame <= fail_stack.avail); \
1690 DEBUG_STATEMENT (nfailure_points_popped++); \
1691 } while (0) /* POP_FAILURE_POINT */
1695 /* Registers are set to a sentinel when they haven't yet matched. */
1696 #define REG_UNSET(e) ((e) == NULL)
1698 /* Subroutine declarations and macros for regex_compile. */
1700 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1701 reg_syntax_t syntax
,
1702 struct re_pattern_buffer
*bufp
));
1703 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1704 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1705 int arg1
, int arg2
));
1706 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1707 int arg
, unsigned char *end
));
1708 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1709 int arg1
, int arg2
, unsigned char *end
));
1710 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1712 reg_syntax_t syntax
));
1713 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1715 reg_syntax_t syntax
));
1716 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1717 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1718 char *fastmap
, const int multibyte
));
1720 /* Fetch the next character in the uncompiled pattern, with no
1722 #define PATFETCH(c) \
1725 if (p == pend) return REG_EEND; \
1726 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1731 /* If `translate' is non-null, return translate[D], else just D. We
1732 cast the subscript to translate because some data is declared as
1733 `char *', to avoid warnings when a string constant is passed. But
1734 when we use a character as a subscript we must make it unsigned. */
1736 # define TRANSLATE(d) \
1737 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1741 /* Macros for outputting the compiled pattern into `buffer'. */
1743 /* If the buffer isn't allocated when it comes in, use this. */
1744 #define INIT_BUF_SIZE 32
1746 /* Make sure we have at least N more bytes of space in buffer. */
1747 #define GET_BUFFER_SPACE(n) \
1748 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1751 /* Make sure we have one more byte of buffer space and then add C to it. */
1752 #define BUF_PUSH(c) \
1754 GET_BUFFER_SPACE (1); \
1755 *b++ = (unsigned char) (c); \
1759 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1760 #define BUF_PUSH_2(c1, c2) \
1762 GET_BUFFER_SPACE (2); \
1763 *b++ = (unsigned char) (c1); \
1764 *b++ = (unsigned char) (c2); \
1768 /* As with BUF_PUSH_2, except for three bytes. */
1769 #define BUF_PUSH_3(c1, c2, c3) \
1771 GET_BUFFER_SPACE (3); \
1772 *b++ = (unsigned char) (c1); \
1773 *b++ = (unsigned char) (c2); \
1774 *b++ = (unsigned char) (c3); \
1778 /* Store a jump with opcode OP at LOC to location TO. We store a
1779 relative address offset by the three bytes the jump itself occupies. */
1780 #define STORE_JUMP(op, loc, to) \
1781 store_op1 (op, loc, (to) - (loc) - 3)
1783 /* Likewise, for a two-argument jump. */
1784 #define STORE_JUMP2(op, loc, to, arg) \
1785 store_op2 (op, loc, (to) - (loc) - 3, arg)
1787 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1788 #define INSERT_JUMP(op, loc, to) \
1789 insert_op1 (op, loc, (to) - (loc) - 3, b)
1791 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1792 #define INSERT_JUMP2(op, loc, to, arg) \
1793 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1796 /* This is not an arbitrary limit: the arguments which represent offsets
1797 into the pattern are two bytes long. So if 2^15 bytes turns out to
1798 be too small, many things would have to change. */
1799 # define MAX_BUF_SIZE (1L << 15)
1801 #if 0 /* This is when we thought it could be 2^16 bytes. */
1802 /* Any other compiler which, like MSC, has allocation limit below 2^16
1803 bytes will have to use approach similar to what was done below for
1804 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1805 reallocating to 0 bytes. Such thing is not going to work too well.
1806 You have been warned!! */
1807 #if defined _MSC_VER && !defined WIN32
1808 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1809 # define MAX_BUF_SIZE 65500L
1811 # define MAX_BUF_SIZE (1L << 16)
1815 /* Extend the buffer by twice its current size via realloc and
1816 reset the pointers that pointed into the old block to point to the
1817 correct places in the new one. If extending the buffer results in it
1818 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1819 #if __BOUNDED_POINTERS__
1820 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1821 # define MOVE_BUFFER_POINTER(P) \
1822 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1823 SET_HIGH_BOUND (P), \
1824 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1825 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1828 SET_HIGH_BOUND (b); \
1829 SET_HIGH_BOUND (begalt); \
1830 if (fixup_alt_jump) \
1831 SET_HIGH_BOUND (fixup_alt_jump); \
1833 SET_HIGH_BOUND (laststart); \
1834 if (pending_exact) \
1835 SET_HIGH_BOUND (pending_exact); \
1838 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1839 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1841 #define EXTEND_BUFFER() \
1843 unsigned char *old_buffer = bufp->buffer; \
1844 if (bufp->allocated == MAX_BUF_SIZE) \
1846 bufp->allocated <<= 1; \
1847 if (bufp->allocated > MAX_BUF_SIZE) \
1848 bufp->allocated = MAX_BUF_SIZE; \
1849 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1850 if (bufp->buffer == NULL) \
1851 return REG_ESPACE; \
1852 /* If the buffer moved, move all the pointers into it. */ \
1853 if (old_buffer != bufp->buffer) \
1855 unsigned char *new_buffer = bufp->buffer; \
1856 MOVE_BUFFER_POINTER (b); \
1857 MOVE_BUFFER_POINTER (begalt); \
1858 if (fixup_alt_jump) \
1859 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1861 MOVE_BUFFER_POINTER (laststart); \
1862 if (pending_exact) \
1863 MOVE_BUFFER_POINTER (pending_exact); \
1865 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1869 /* Since we have one byte reserved for the register number argument to
1870 {start,stop}_memory, the maximum number of groups we can report
1871 things about is what fits in that byte. */
1872 #define MAX_REGNUM 255
1874 /* But patterns can have more than `MAX_REGNUM' registers. We just
1875 ignore the excess. */
1876 typedef int regnum_t
;
1879 /* Macros for the compile stack. */
1881 /* Since offsets can go either forwards or backwards, this type needs to
1882 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1883 /* int may be not enough when sizeof(int) == 2. */
1884 typedef long pattern_offset_t
;
1888 pattern_offset_t begalt_offset
;
1889 pattern_offset_t fixup_alt_jump
;
1890 pattern_offset_t laststart_offset
;
1892 } compile_stack_elt_t
;
1897 compile_stack_elt_t
*stack
;
1899 unsigned avail
; /* Offset of next open position. */
1900 } compile_stack_type
;
1903 #define INIT_COMPILE_STACK_SIZE 32
1905 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1906 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1908 /* The next available element. */
1909 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1911 /* Explicit quit checking is only used on NTemacs and whenever we
1912 use polling to process input events. */
1913 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1914 extern int immediate_quit
;
1915 # define IMMEDIATE_QUIT_CHECK \
1917 if (immediate_quit) QUIT; \
1920 # define IMMEDIATE_QUIT_CHECK ((void)0)
1923 /* Structure to manage work area for range table. */
1924 struct range_table_work_area
1926 int *table
; /* actual work area. */
1927 int allocated
; /* allocated size for work area in bytes. */
1928 int used
; /* actually used size in words. */
1929 int bits
; /* flag to record character classes */
1932 /* Make sure that WORK_AREA can hold more N multibyte characters.
1933 This is used only in set_image_of_range and set_image_of_range_1.
1934 It expects WORK_AREA to be a pointer.
1935 If it can't get the space, it returns from the surrounding function. */
1937 #define EXTEND_RANGE_TABLE(work_area, n) \
1939 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1941 extend_range_table_work_area (&work_area); \
1942 if ((work_area).table == 0) \
1943 return (REG_ESPACE); \
1947 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1948 (work_area).bits |= (bit)
1950 /* Bits used to implement the multibyte-part of the various character classes
1951 such as [:alnum:] in a charset's range table. */
1952 #define BIT_WORD 0x1
1953 #define BIT_LOWER 0x2
1954 #define BIT_PUNCT 0x4
1955 #define BIT_SPACE 0x8
1956 #define BIT_UPPER 0x10
1957 #define BIT_MULTIBYTE 0x20
1959 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1960 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1962 EXTEND_RANGE_TABLE ((work_area), 2); \
1963 (work_area).table[(work_area).used++] = (range_start); \
1964 (work_area).table[(work_area).used++] = (range_end); \
1967 /* Free allocated memory for WORK_AREA. */
1968 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1970 if ((work_area).table) \
1971 free ((work_area).table); \
1974 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1975 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1976 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1977 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1980 /* Set the bit for character C in a list. */
1981 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1986 /* Store characters in the range FROM to TO in the bitmap at B (for
1987 ASCII and unibyte characters) and WORK_AREA (for multibyte
1988 characters) while translating them and paying attention to the
1989 continuity of translated characters.
1991 Implementation note: It is better to implement these fairly big
1992 macros by a function, but it's not that easy because macros called
1993 in this macro assume various local variables already declared. */
1995 /* Both FROM and TO are ASCII characters. */
1997 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
2001 for (C0 = (FROM); C0 <= (TO); C0++) \
2003 C1 = TRANSLATE (C0); \
2004 if (! ASCII_CHAR_P (C1)) \
2006 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2007 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
2010 SET_LIST_BIT (C1); \
2015 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
2017 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
2019 int C0, C1, C2, I; \
2020 int USED = RANGE_TABLE_WORK_USED (work_area); \
2022 for (C0 = (FROM); C0 <= (TO); C0++) \
2024 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
2025 if (CHAR_BYTE8_P (C1)) \
2026 SET_LIST_BIT (C0); \
2029 C2 = TRANSLATE (C1); \
2031 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
2033 SET_LIST_BIT (C1); \
2034 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2036 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2037 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2039 if (C2 >= from - 1 && C2 <= to + 1) \
2041 if (C2 == from - 1) \
2042 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2043 else if (C2 == to + 1) \
2044 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2049 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
2055 /* Both FROM and TO are multibyte characters. */
2057 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2059 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2061 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2062 for (C0 = (FROM); C0 <= (TO); C0++) \
2064 C1 = TRANSLATE (C0); \
2065 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2066 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2067 SET_LIST_BIT (C2); \
2068 if (C1 >= (FROM) && C1 <= (TO)) \
2070 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2072 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2073 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2075 if (C1 >= from - 1 && C1 <= to + 1) \
2077 if (C1 == from - 1) \
2078 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2079 else if (C1 == to + 1) \
2080 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2085 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2091 /* Get the next unsigned number in the uncompiled pattern. */
2092 #define GET_UNSIGNED_NUMBER(num) \
2095 FREE_STACK_RETURN (REG_EBRACE); \
2099 while ('0' <= c && c <= '9') \
2105 num = num * 10 + c - '0'; \
2106 if (num / 10 != prev) \
2107 FREE_STACK_RETURN (REG_BADBR); \
2109 FREE_STACK_RETURN (REG_EBRACE); \
2115 #if ! WIDE_CHAR_SUPPORT
2117 /* Map a string to the char class it names (if any). */
2119 re_wctype (const re_char
*str
)
2121 const char *string
= (const char *) str
;
2122 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2123 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2124 else if (STREQ (string
, "word")) return RECC_WORD
;
2125 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2126 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2127 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2128 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2129 else if (STREQ (string
, "print")) return RECC_PRINT
;
2130 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2131 else if (STREQ (string
, "space")) return RECC_SPACE
;
2132 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2133 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2134 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2135 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2136 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2137 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2138 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2142 /* True if CH is in the char class CC. */
2144 re_iswctype (int ch
, re_wctype_t cc
)
2148 case RECC_ALNUM
: return ISALNUM (ch
);
2149 case RECC_ALPHA
: return ISALPHA (ch
);
2150 case RECC_BLANK
: return ISBLANK (ch
);
2151 case RECC_CNTRL
: return ISCNTRL (ch
);
2152 case RECC_DIGIT
: return ISDIGIT (ch
);
2153 case RECC_GRAPH
: return ISGRAPH (ch
);
2154 case RECC_LOWER
: return ISLOWER (ch
);
2155 case RECC_PRINT
: return ISPRINT (ch
);
2156 case RECC_PUNCT
: return ISPUNCT (ch
);
2157 case RECC_SPACE
: return ISSPACE (ch
);
2158 case RECC_UPPER
: return ISUPPER (ch
);
2159 case RECC_XDIGIT
: return ISXDIGIT (ch
);
2160 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2161 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2162 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2163 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2164 case RECC_WORD
: return ISWORD (ch
);
2165 case RECC_ERROR
: return false;
2171 /* Return a bit-pattern to use in the range-table bits to match multibyte
2172 chars of class CC. */
2174 re_wctype_to_bit (re_wctype_t cc
)
2178 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2179 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2180 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2181 case RECC_LOWER
: return BIT_LOWER
;
2182 case RECC_UPPER
: return BIT_UPPER
;
2183 case RECC_PUNCT
: return BIT_PUNCT
;
2184 case RECC_SPACE
: return BIT_SPACE
;
2185 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2186 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2193 /* Filling in the work area of a range. */
2195 /* Actually extend the space in WORK_AREA. */
2198 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2200 work_area
->allocated
+= 16 * sizeof (int);
2201 if (work_area
->table
)
2203 = (int *) realloc (work_area
->table
, work_area
->allocated
);
2206 = (int *) malloc (work_area
->allocated
);
2212 /* Carefully find the ranges of codes that are equivalent
2213 under case conversion to the range start..end when passed through
2214 TRANSLATE. Handle the case where non-letters can come in between
2215 two upper-case letters (which happens in Latin-1).
2216 Also handle the case of groups of more than 2 case-equivalent chars.
2218 The basic method is to look at consecutive characters and see
2219 if they can form a run that can be handled as one.
2221 Returns -1 if successful, REG_ESPACE if ran out of space. */
2224 set_image_of_range_1 (work_area
, start
, end
, translate
)
2225 RE_TRANSLATE_TYPE translate
;
2226 struct range_table_work_area
*work_area
;
2227 re_wchar_t start
, end
;
2229 /* `one_case' indicates a character, or a run of characters,
2230 each of which is an isolate (no case-equivalents).
2231 This includes all ASCII non-letters.
2233 `two_case' indicates a character, or a run of characters,
2234 each of which has two case-equivalent forms.
2235 This includes all ASCII letters.
2237 `strange' indicates a character that has more than one
2240 enum case_type
{one_case
, two_case
, strange
};
2242 /* Describe the run that is in progress,
2243 which the next character can try to extend.
2244 If run_type is strange, that means there really is no run.
2245 If run_type is one_case, then run_start...run_end is the run.
2246 If run_type is two_case, then the run is run_start...run_end,
2247 and the case-equivalents end at run_eqv_end. */
2249 enum case_type run_type
= strange
;
2250 int run_start
, run_end
, run_eqv_end
;
2252 Lisp_Object eqv_table
;
2254 if (!RE_TRANSLATE_P (translate
))
2256 EXTEND_RANGE_TABLE (work_area
, 2);
2257 work_area
->table
[work_area
->used
++] = (start
);
2258 work_area
->table
[work_area
->used
++] = (end
);
2262 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2264 for (; start
<= end
; start
++)
2266 enum case_type this_type
;
2267 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2268 int minchar
, maxchar
;
2270 /* Classify this character */
2272 this_type
= one_case
;
2273 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2274 this_type
= two_case
;
2276 this_type
= strange
;
2279 minchar
= start
, maxchar
= eqv
;
2281 minchar
= eqv
, maxchar
= start
;
2283 /* Can this character extend the run in progress? */
2284 if (this_type
== strange
|| this_type
!= run_type
2285 || !(minchar
== run_end
+ 1
2286 && (run_type
== two_case
2287 ? maxchar
== run_eqv_end
+ 1 : 1)))
2290 Record each of its equivalent ranges. */
2291 if (run_type
== one_case
)
2293 EXTEND_RANGE_TABLE (work_area
, 2);
2294 work_area
->table
[work_area
->used
++] = run_start
;
2295 work_area
->table
[work_area
->used
++] = run_end
;
2297 else if (run_type
== two_case
)
2299 EXTEND_RANGE_TABLE (work_area
, 4);
2300 work_area
->table
[work_area
->used
++] = run_start
;
2301 work_area
->table
[work_area
->used
++] = run_end
;
2302 work_area
->table
[work_area
->used
++]
2303 = RE_TRANSLATE (eqv_table
, run_start
);
2304 work_area
->table
[work_area
->used
++]
2305 = RE_TRANSLATE (eqv_table
, run_end
);
2310 if (this_type
== strange
)
2312 /* For a strange character, add each of its equivalents, one
2313 by one. Don't start a range. */
2316 EXTEND_RANGE_TABLE (work_area
, 2);
2317 work_area
->table
[work_area
->used
++] = eqv
;
2318 work_area
->table
[work_area
->used
++] = eqv
;
2319 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2321 while (eqv
!= start
);
2324 /* Add this char to the run, or start a new run. */
2325 else if (run_type
== strange
)
2327 /* Initialize a new range. */
2328 run_type
= this_type
;
2331 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2335 /* Extend a running range. */
2337 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2341 /* If a run is still in progress at the end, finish it now
2342 by recording its equivalent ranges. */
2343 if (run_type
== one_case
)
2345 EXTEND_RANGE_TABLE (work_area
, 2);
2346 work_area
->table
[work_area
->used
++] = run_start
;
2347 work_area
->table
[work_area
->used
++] = run_end
;
2349 else if (run_type
== two_case
)
2351 EXTEND_RANGE_TABLE (work_area
, 4);
2352 work_area
->table
[work_area
->used
++] = run_start
;
2353 work_area
->table
[work_area
->used
++] = run_end
;
2354 work_area
->table
[work_area
->used
++]
2355 = RE_TRANSLATE (eqv_table
, run_start
);
2356 work_area
->table
[work_area
->used
++]
2357 = RE_TRANSLATE (eqv_table
, run_end
);
2365 /* Record the image of the range start..end when passed through
2366 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2367 and is not even necessarily contiguous.
2368 Normally we approximate it with the smallest contiguous range that contains
2369 all the chars we need. However, for Latin-1 we go to extra effort
2372 This function is not called for ASCII ranges.
2374 Returns -1 if successful, REG_ESPACE if ran out of space. */
2377 set_image_of_range (work_area
, start
, end
, translate
)
2378 RE_TRANSLATE_TYPE translate
;
2379 struct range_table_work_area
*work_area
;
2380 re_wchar_t start
, end
;
2382 re_wchar_t cmin
, cmax
;
2385 /* For Latin-1 ranges, use set_image_of_range_1
2386 to get proper handling of ranges that include letters and nonletters.
2387 For a range that includes the whole of Latin-1, this is not necessary.
2388 For other character sets, we don't bother to get this right. */
2389 if (RE_TRANSLATE_P (translate
) && start
< 04400
2390 && !(start
< 04200 && end
>= 04377))
2397 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2407 EXTEND_RANGE_TABLE (work_area
, 2);
2408 work_area
->table
[work_area
->used
++] = (start
);
2409 work_area
->table
[work_area
->used
++] = (end
);
2411 cmin
= -1, cmax
= -1;
2413 if (RE_TRANSLATE_P (translate
))
2417 for (ch
= start
; ch
<= end
; ch
++)
2419 re_wchar_t c
= TRANSLATE (ch
);
2420 if (! (start
<= c
&& c
<= end
))
2426 cmin
= MIN (cmin
, c
);
2427 cmax
= MAX (cmax
, c
);
2434 EXTEND_RANGE_TABLE (work_area
, 2);
2435 work_area
->table
[work_area
->used
++] = (cmin
);
2436 work_area
->table
[work_area
->used
++] = (cmax
);
2444 #ifndef MATCH_MAY_ALLOCATE
2446 /* If we cannot allocate large objects within re_match_2_internal,
2447 we make the fail stack and register vectors global.
2448 The fail stack, we grow to the maximum size when a regexp
2450 The register vectors, we adjust in size each time we
2451 compile a regexp, according to the number of registers it needs. */
2453 static fail_stack_type fail_stack
;
2455 /* Size with which the following vectors are currently allocated.
2456 That is so we can make them bigger as needed,
2457 but never make them smaller. */
2458 static int regs_allocated_size
;
2460 static re_char
** regstart
, ** regend
;
2461 static re_char
**best_regstart
, **best_regend
;
2463 /* Make the register vectors big enough for NUM_REGS registers,
2464 but don't make them smaller. */
2467 regex_grow_registers (num_regs
)
2470 if (num_regs
> regs_allocated_size
)
2472 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2473 RETALLOC_IF (regend
, num_regs
, re_char
*);
2474 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2475 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2477 regs_allocated_size
= num_regs
;
2481 #endif /* not MATCH_MAY_ALLOCATE */
2483 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2487 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2488 Returns one of error codes defined in `regex.h', or zero for success.
2490 Assumes the `allocated' (and perhaps `buffer') and `translate'
2491 fields are set in BUFP on entry.
2493 If it succeeds, results are put in BUFP (if it returns an error, the
2494 contents of BUFP are undefined):
2495 `buffer' is the compiled pattern;
2496 `syntax' is set to SYNTAX;
2497 `used' is set to the length of the compiled pattern;
2498 `fastmap_accurate' is zero;
2499 `re_nsub' is the number of subexpressions in PATTERN;
2500 `not_bol' and `not_eol' are zero;
2502 The `fastmap' field is neither examined nor set. */
2504 /* Insert the `jump' from the end of last alternative to "here".
2505 The space for the jump has already been allocated. */
2506 #define FIXUP_ALT_JUMP() \
2508 if (fixup_alt_jump) \
2509 STORE_JUMP (jump, fixup_alt_jump, b); \
2513 /* Return, freeing storage we allocated. */
2514 #define FREE_STACK_RETURN(value) \
2516 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2517 free (compile_stack.stack); \
2521 static reg_errcode_t
2522 regex_compile (const re_char
*pattern
, size_t size
, reg_syntax_t syntax
, struct re_pattern_buffer
*bufp
)
2524 /* We fetch characters from PATTERN here. */
2525 register re_wchar_t c
, c1
;
2527 /* Points to the end of the buffer, where we should append. */
2528 register unsigned char *b
;
2530 /* Keeps track of unclosed groups. */
2531 compile_stack_type compile_stack
;
2533 /* Points to the current (ending) position in the pattern. */
2535 /* `const' makes AIX compiler fail. */
2536 unsigned char *p
= pattern
;
2538 re_char
*p
= pattern
;
2540 re_char
*pend
= pattern
+ size
;
2542 /* How to translate the characters in the pattern. */
2543 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2545 /* Address of the count-byte of the most recently inserted `exactn'
2546 command. This makes it possible to tell if a new exact-match
2547 character can be added to that command or if the character requires
2548 a new `exactn' command. */
2549 unsigned char *pending_exact
= 0;
2551 /* Address of start of the most recently finished expression.
2552 This tells, e.g., postfix * where to find the start of its
2553 operand. Reset at the beginning of groups and alternatives. */
2554 unsigned char *laststart
= 0;
2556 /* Address of beginning of regexp, or inside of last group. */
2557 unsigned char *begalt
;
2559 /* Place in the uncompiled pattern (i.e., the {) to
2560 which to go back if the interval is invalid. */
2561 re_char
*beg_interval
;
2563 /* Address of the place where a forward jump should go to the end of
2564 the containing expression. Each alternative of an `or' -- except the
2565 last -- ends with a forward jump of this sort. */
2566 unsigned char *fixup_alt_jump
= 0;
2568 /* Work area for range table of charset. */
2569 struct range_table_work_area range_table_work
;
2571 /* If the object matched can contain multibyte characters. */
2572 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2574 /* Nonzero if we have pushed down into a subpattern. */
2575 int in_subpattern
= 0;
2577 /* These hold the values of p, pattern, and pend from the main
2578 pattern when we have pushed into a subpattern. */
2580 re_char
*main_pattern
;
2585 DEBUG_PRINT1 ("\nCompiling pattern: ");
2588 unsigned debug_count
;
2590 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2591 putchar (pattern
[debug_count
]);
2596 /* Initialize the compile stack. */
2597 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2598 if (compile_stack
.stack
== NULL
)
2601 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2602 compile_stack
.avail
= 0;
2604 range_table_work
.table
= 0;
2605 range_table_work
.allocated
= 0;
2607 /* Initialize the pattern buffer. */
2608 bufp
->syntax
= syntax
;
2609 bufp
->fastmap_accurate
= 0;
2610 bufp
->not_bol
= bufp
->not_eol
= 0;
2611 bufp
->used_syntax
= 0;
2613 /* Set `used' to zero, so that if we return an error, the pattern
2614 printer (for debugging) will think there's no pattern. We reset it
2618 /* Always count groups, whether or not bufp->no_sub is set. */
2621 #if !defined emacs && !defined SYNTAX_TABLE
2622 /* Initialize the syntax table. */
2623 init_syntax_once ();
2626 if (bufp
->allocated
== 0)
2629 { /* If zero allocated, but buffer is non-null, try to realloc
2630 enough space. This loses if buffer's address is bogus, but
2631 that is the user's responsibility. */
2632 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2635 { /* Caller did not allocate a buffer. Do it for them. */
2636 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2638 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2640 bufp
->allocated
= INIT_BUF_SIZE
;
2643 begalt
= b
= bufp
->buffer
;
2645 /* Loop through the uncompiled pattern until we're at the end. */
2650 /* If this is the end of an included regexp,
2651 pop back to the main regexp and try again. */
2655 pattern
= main_pattern
;
2660 /* If this is the end of the main regexp, we are done. */
2672 /* If there's no special whitespace regexp, treat
2673 spaces normally. And don't try to do this recursively. */
2674 if (!whitespace_regexp
|| in_subpattern
)
2677 /* Peek past following spaces. */
2684 /* If the spaces are followed by a repetition op,
2685 treat them normally. */
2687 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2688 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2691 /* Replace the spaces with the whitespace regexp. */
2695 main_pattern
= pattern
;
2696 p
= pattern
= whitespace_regexp
;
2697 pend
= p
+ strlen ((const char *) p
);
2703 if ( /* If at start of pattern, it's an operator. */
2705 /* If context independent, it's an operator. */
2706 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2707 /* Otherwise, depends on what's come before. */
2708 || at_begline_loc_p (pattern
, p
, syntax
))
2709 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2718 if ( /* If at end of pattern, it's an operator. */
2720 /* If context independent, it's an operator. */
2721 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2722 /* Otherwise, depends on what's next. */
2723 || at_endline_loc_p (p
, pend
, syntax
))
2724 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2733 if ((syntax
& RE_BK_PLUS_QM
)
2734 || (syntax
& RE_LIMITED_OPS
))
2738 /* If there is no previous pattern... */
2741 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2742 FREE_STACK_RETURN (REG_BADRPT
);
2743 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2748 /* 1 means zero (many) matches is allowed. */
2749 boolean zero_times_ok
= 0, many_times_ok
= 0;
2752 /* If there is a sequence of repetition chars, collapse it
2753 down to just one (the right one). We can't combine
2754 interval operators with these because of, e.g., `a{2}*',
2755 which should only match an even number of `a's. */
2759 if ((syntax
& RE_FRUGAL
)
2760 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2764 zero_times_ok
|= c
!= '+';
2765 many_times_ok
|= c
!= '?';
2771 || (!(syntax
& RE_BK_PLUS_QM
)
2772 && (*p
== '+' || *p
== '?')))
2774 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2777 FREE_STACK_RETURN (REG_EESCAPE
);
2778 if (p
[1] == '+' || p
[1] == '?')
2779 PATFETCH (c
); /* Gobble up the backslash. */
2785 /* If we get here, we found another repeat character. */
2789 /* Star, etc. applied to an empty pattern is equivalent
2790 to an empty pattern. */
2791 if (!laststart
|| laststart
== b
)
2794 /* Now we know whether or not zero matches is allowed
2795 and also whether or not two or more matches is allowed. */
2800 boolean simple
= skip_one_char (laststart
) == b
;
2801 unsigned int startoffset
= 0;
2803 /* Check if the loop can match the empty string. */
2804 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2805 ? on_failure_jump
: on_failure_jump_loop
;
2806 assert (skip_one_char (laststart
) <= b
);
2808 if (!zero_times_ok
&& simple
)
2809 { /* Since simple * loops can be made faster by using
2810 on_failure_keep_string_jump, we turn simple P+
2811 into PP* if P is simple. */
2812 unsigned char *p1
, *p2
;
2813 startoffset
= b
- laststart
;
2814 GET_BUFFER_SPACE (startoffset
);
2815 p1
= b
; p2
= laststart
;
2821 GET_BUFFER_SPACE (6);
2824 STORE_JUMP (ofj
, b
, b
+ 6);
2826 /* Simple * loops can use on_failure_keep_string_jump
2827 depending on what follows. But since we don't know
2828 that yet, we leave the decision up to
2829 on_failure_jump_smart. */
2830 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2831 laststart
+ startoffset
, b
+ 6);
2833 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2838 /* A simple ? pattern. */
2839 assert (zero_times_ok
);
2840 GET_BUFFER_SPACE (3);
2841 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2845 else /* not greedy */
2846 { /* I wish the greedy and non-greedy cases could be merged. */
2848 GET_BUFFER_SPACE (7); /* We might use less. */
2851 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2853 /* The non-greedy multiple match looks like
2854 a repeat..until: we only need a conditional jump
2855 at the end of the loop. */
2856 if (emptyp
) BUF_PUSH (no_op
);
2857 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2858 : on_failure_jump
, b
, laststart
);
2862 /* The repeat...until naturally matches one or more.
2863 To also match zero times, we need to first jump to
2864 the end of the loop (its conditional jump). */
2865 INSERT_JUMP (jump
, laststart
, b
);
2871 /* non-greedy a?? */
2872 INSERT_JUMP (jump
, laststart
, b
+ 3);
2874 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2893 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2895 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2897 /* Ensure that we have enough space to push a charset: the
2898 opcode, the length count, and the bitset; 34 bytes in all. */
2899 GET_BUFFER_SPACE (34);
2903 /* We test `*p == '^' twice, instead of using an if
2904 statement, so we only need one BUF_PUSH. */
2905 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2909 /* Remember the first position in the bracket expression. */
2912 /* Push the number of bytes in the bitmap. */
2913 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2915 /* Clear the whole map. */
2916 memset (b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2918 /* charset_not matches newline according to a syntax bit. */
2919 if ((re_opcode_t
) b
[-2] == charset_not
2920 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2921 SET_LIST_BIT ('\n');
2923 /* Read in characters and ranges, setting map bits. */
2926 boolean escaped_char
= false;
2927 const unsigned char *p2
= p
;
2930 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2932 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2933 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2934 So the translation is done later in a loop. Example:
2935 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2938 /* \ might escape characters inside [...] and [^...]. */
2939 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2941 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2944 escaped_char
= true;
2948 /* Could be the end of the bracket expression. If it's
2949 not (i.e., when the bracket expression is `[]' so
2950 far), the ']' character bit gets set way below. */
2951 if (c
== ']' && p2
!= p1
)
2955 /* See if we're at the beginning of a possible character
2958 if (!escaped_char
&&
2959 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2961 /* Leave room for the null. */
2962 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2963 const unsigned char *class_beg
;
2969 /* If pattern is `[[:'. */
2970 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2975 if ((c
== ':' && *p
== ']') || p
== pend
)
2977 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2980 /* This is in any case an invalid class name. */
2985 /* If isn't a word bracketed by `[:' and `:]':
2986 undo the ending character, the letters, and
2987 leave the leading `:' and `[' (but set bits for
2989 if (c
== ':' && *p
== ']')
2991 re_wctype_t cc
= re_wctype (str
);
2994 FREE_STACK_RETURN (REG_ECTYPE
);
2996 /* Throw away the ] at the end of the character
3000 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
3003 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
3004 if (re_iswctype (btowc (ch
), cc
))
3007 if (c
< (1 << BYTEWIDTH
))
3011 /* Most character classes in a multibyte match
3012 just set a flag. Exceptions are is_blank,
3013 is_digit, is_cntrl, and is_xdigit, since
3014 they can only match ASCII characters. We
3015 don't need to handle them for multibyte.
3016 They are distinguished by a negative wctype. */
3018 /* Setup the gl_state object to its buffer-defined
3019 value. This hardcodes the buffer-global
3020 syntax-table for ASCII chars, while the other chars
3021 will obey syntax-table properties. It's not ideal,
3022 but it's the way it's been done until now. */
3023 SETUP_BUFFER_SYNTAX_TABLE ();
3025 for (ch
= 0; ch
< 256; ++ch
)
3027 c
= RE_CHAR_TO_MULTIBYTE (ch
);
3028 if (! CHAR_BYTE8_P (c
)
3029 && re_iswctype (c
, cc
))
3035 if (ASCII_CHAR_P (c1
))
3037 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
3041 SET_RANGE_TABLE_WORK_AREA_BIT
3042 (range_table_work
, re_wctype_to_bit (cc
));
3044 /* In most cases the matching rule for char classes
3045 only uses the syntax table for multibyte chars,
3046 so that the content of the syntax-table it is not
3047 hardcoded in the range_table. SPACE and WORD are
3048 the two exceptions. */
3049 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
3050 bufp
->used_syntax
= 1;
3052 /* Repeat the loop. */
3057 /* Go back to right after the "[:". */
3061 /* Because the `:' may starts the range, we
3062 can't simply set bit and repeat the loop.
3063 Instead, just set it to C and handle below. */
3068 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
3071 /* Discard the `-'. */
3074 /* Fetch the character which ends the range. */
3077 if (CHAR_BYTE8_P (c1
)
3078 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
3079 /* Treat the range from a multibyte character to
3080 raw-byte character as empty. */
3085 /* Range from C to C. */
3090 if (syntax
& RE_NO_EMPTY_RANGES
)
3091 FREE_STACK_RETURN (REG_ERANGEX
);
3092 /* Else, repeat the loop. */
3097 /* Set the range into bitmap */
3098 for (; c
<= c1
; c
++)
3101 if (ch
< (1 << BYTEWIDTH
))
3108 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
3110 if (CHAR_BYTE8_P (c1
))
3111 c
= BYTE8_TO_CHAR (128);
3115 if (CHAR_BYTE8_P (c
))
3117 c
= CHAR_TO_BYTE8 (c
);
3118 c1
= CHAR_TO_BYTE8 (c1
);
3119 for (; c
<= c1
; c
++)
3124 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
3128 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
3135 /* Discard any (non)matching list bytes that are all 0 at the
3136 end of the map. Decrease the map-length byte too. */
3137 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3141 /* Build real range table from work area. */
3142 if (RANGE_TABLE_WORK_USED (range_table_work
)
3143 || RANGE_TABLE_WORK_BITS (range_table_work
))
3146 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3148 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3149 bytes for flags, two for COUNT, and three bytes for
3151 GET_BUFFER_SPACE (4 + used
* 3);
3153 /* Indicate the existence of range table. */
3154 laststart
[1] |= 0x80;
3156 /* Store the character class flag bits into the range table.
3157 If not in emacs, these flag bits are always 0. */
3158 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3159 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3161 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3162 for (i
= 0; i
< used
; i
++)
3163 STORE_CHARACTER_AND_INCR
3164 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3171 if (syntax
& RE_NO_BK_PARENS
)
3178 if (syntax
& RE_NO_BK_PARENS
)
3185 if (syntax
& RE_NEWLINE_ALT
)
3192 if (syntax
& RE_NO_BK_VBAR
)
3199 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3200 goto handle_interval
;
3206 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3208 /* Do not translate the character after the \, so that we can
3209 distinguish, e.g., \B from \b, even if we normally would
3210 translate, e.g., B to b. */
3216 if (syntax
& RE_NO_BK_PARENS
)
3217 goto normal_backslash
;
3222 regnum_t regnum
= 0;
3225 /* Look for a special (?...) construct */
3226 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3228 PATFETCH (c
); /* Gobble up the '?'. */
3234 case ':': shy
= 1; break;
3236 /* An explicitly specified regnum must start
3239 FREE_STACK_RETURN (REG_BADPAT
);
3240 case '1': case '2': case '3': case '4':
3241 case '5': case '6': case '7': case '8': case '9':
3242 regnum
= 10*regnum
+ (c
- '0'); break;
3244 /* Only (?:...) is supported right now. */
3245 FREE_STACK_RETURN (REG_BADPAT
);
3252 regnum
= ++bufp
->re_nsub
;
3254 { /* It's actually not shy, but explicitly numbered. */
3256 if (regnum
> bufp
->re_nsub
)
3257 bufp
->re_nsub
= regnum
;
3258 else if (regnum
> bufp
->re_nsub
3259 /* Ideally, we'd want to check that the specified
3260 group can't have matched (i.e. all subgroups
3261 using the same regnum are in other branches of
3262 OR patterns), but we don't currently keep track
3263 of enough info to do that easily. */
3264 || group_in_compile_stack (compile_stack
, regnum
))
3265 FREE_STACK_RETURN (REG_BADPAT
);
3268 /* It's really shy. */
3269 regnum
= - bufp
->re_nsub
;
3271 if (COMPILE_STACK_FULL
)
3273 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3274 compile_stack_elt_t
);
3275 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3277 compile_stack
.size
<<= 1;
3280 /* These are the values to restore when we hit end of this
3281 group. They are all relative offsets, so that if the
3282 whole pattern moves because of realloc, they will still
3284 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3285 COMPILE_STACK_TOP
.fixup_alt_jump
3286 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3287 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3288 COMPILE_STACK_TOP
.regnum
= regnum
;
3290 /* Do not push a start_memory for groups beyond the last one
3291 we can represent in the compiled pattern. */
3292 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3293 BUF_PUSH_2 (start_memory
, regnum
);
3295 compile_stack
.avail
++;
3300 /* If we've reached MAX_REGNUM groups, then this open
3301 won't actually generate any code, so we'll have to
3302 clear pending_exact explicitly. */
3308 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3310 if (COMPILE_STACK_EMPTY
)
3312 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3313 goto normal_backslash
;
3315 FREE_STACK_RETURN (REG_ERPAREN
);
3321 /* See similar code for backslashed left paren above. */
3322 if (COMPILE_STACK_EMPTY
)
3324 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3327 FREE_STACK_RETURN (REG_ERPAREN
);
3330 /* Since we just checked for an empty stack above, this
3331 ``can't happen''. */
3332 assert (compile_stack
.avail
!= 0);
3334 /* We don't just want to restore into `regnum', because
3335 later groups should continue to be numbered higher,
3336 as in `(ab)c(de)' -- the second group is #2. */
3339 compile_stack
.avail
--;
3340 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3342 = COMPILE_STACK_TOP
.fixup_alt_jump
3343 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3345 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3346 regnum
= COMPILE_STACK_TOP
.regnum
;
3347 /* If we've reached MAX_REGNUM groups, then this open
3348 won't actually generate any code, so we'll have to
3349 clear pending_exact explicitly. */
3352 /* We're at the end of the group, so now we know how many
3353 groups were inside this one. */
3354 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3355 BUF_PUSH_2 (stop_memory
, regnum
);
3360 case '|': /* `\|'. */
3361 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3362 goto normal_backslash
;
3364 if (syntax
& RE_LIMITED_OPS
)
3367 /* Insert before the previous alternative a jump which
3368 jumps to this alternative if the former fails. */
3369 GET_BUFFER_SPACE (3);
3370 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3374 /* The alternative before this one has a jump after it
3375 which gets executed if it gets matched. Adjust that
3376 jump so it will jump to this alternative's analogous
3377 jump (put in below, which in turn will jump to the next
3378 (if any) alternative's such jump, etc.). The last such
3379 jump jumps to the correct final destination. A picture:
3385 If we are at `b', then fixup_alt_jump right now points to a
3386 three-byte space after `a'. We'll put in the jump, set
3387 fixup_alt_jump to right after `b', and leave behind three
3388 bytes which we'll fill in when we get to after `c'. */
3392 /* Mark and leave space for a jump after this alternative,
3393 to be filled in later either by next alternative or
3394 when know we're at the end of a series of alternatives. */
3396 GET_BUFFER_SPACE (3);
3405 /* If \{ is a literal. */
3406 if (!(syntax
& RE_INTERVALS
)
3407 /* If we're at `\{' and it's not the open-interval
3409 || (syntax
& RE_NO_BK_BRACES
))
3410 goto normal_backslash
;
3414 /* If got here, then the syntax allows intervals. */
3416 /* At least (most) this many matches must be made. */
3417 int lower_bound
= 0, upper_bound
= -1;
3421 GET_UNSIGNED_NUMBER (lower_bound
);
3424 GET_UNSIGNED_NUMBER (upper_bound
);
3426 /* Interval such as `{1}' => match exactly once. */
3427 upper_bound
= lower_bound
;
3429 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3430 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3431 FREE_STACK_RETURN (REG_BADBR
);
3433 if (!(syntax
& RE_NO_BK_BRACES
))
3436 FREE_STACK_RETURN (REG_BADBR
);
3438 FREE_STACK_RETURN (REG_EESCAPE
);
3443 FREE_STACK_RETURN (REG_BADBR
);
3445 /* We just parsed a valid interval. */
3447 /* If it's invalid to have no preceding re. */
3450 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3451 FREE_STACK_RETURN (REG_BADRPT
);
3452 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3455 goto unfetch_interval
;
3458 if (upper_bound
== 0)
3459 /* If the upper bound is zero, just drop the sub pattern
3462 else if (lower_bound
== 1 && upper_bound
== 1)
3463 /* Just match it once: nothing to do here. */
3466 /* Otherwise, we have a nontrivial interval. When
3467 we're all done, the pattern will look like:
3468 set_number_at <jump count> <upper bound>
3469 set_number_at <succeed_n count> <lower bound>
3470 succeed_n <after jump addr> <succeed_n count>
3472 jump_n <succeed_n addr> <jump count>
3473 (The upper bound and `jump_n' are omitted if
3474 `upper_bound' is 1, though.) */
3476 { /* If the upper bound is > 1, we need to insert
3477 more at the end of the loop. */
3478 unsigned int nbytes
= (upper_bound
< 0 ? 3
3479 : upper_bound
> 1 ? 5 : 0);
3480 unsigned int startoffset
= 0;
3482 GET_BUFFER_SPACE (20); /* We might use less. */
3484 if (lower_bound
== 0)
3486 /* A succeed_n that starts with 0 is really a
3487 a simple on_failure_jump_loop. */
3488 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3494 /* Initialize lower bound of the `succeed_n', even
3495 though it will be set during matching by its
3496 attendant `set_number_at' (inserted next),
3497 because `re_compile_fastmap' needs to know.
3498 Jump to the `jump_n' we might insert below. */
3499 INSERT_JUMP2 (succeed_n
, laststart
,
3504 /* Code to initialize the lower bound. Insert
3505 before the `succeed_n'. The `5' is the last two
3506 bytes of this `set_number_at', plus 3 bytes of
3507 the following `succeed_n'. */
3508 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3513 if (upper_bound
< 0)
3515 /* A negative upper bound stands for infinity,
3516 in which case it degenerates to a plain jump. */
3517 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3520 else if (upper_bound
> 1)
3521 { /* More than one repetition is allowed, so
3522 append a backward jump to the `succeed_n'
3523 that starts this interval.
3525 When we've reached this during matching,
3526 we'll have matched the interval once, so
3527 jump back only `upper_bound - 1' times. */
3528 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3532 /* The location we want to set is the second
3533 parameter of the `jump_n'; that is `b-2' as
3534 an absolute address. `laststart' will be
3535 the `set_number_at' we're about to insert;
3536 `laststart+3' the number to set, the source
3537 for the relative address. But we are
3538 inserting into the middle of the pattern --
3539 so everything is getting moved up by 5.
3540 Conclusion: (b - 2) - (laststart + 3) + 5,
3541 i.e., b - laststart.
3543 We insert this at the beginning of the loop
3544 so that if we fail during matching, we'll
3545 reinitialize the bounds. */
3546 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3547 upper_bound
- 1, b
);
3552 beg_interval
= NULL
;
3557 /* If an invalid interval, match the characters as literals. */
3558 assert (beg_interval
);
3560 beg_interval
= NULL
;
3562 /* normal_char and normal_backslash need `c'. */
3565 if (!(syntax
& RE_NO_BK_BRACES
))
3567 assert (p
> pattern
&& p
[-1] == '\\');
3568 goto normal_backslash
;
3574 /* There is no way to specify the before_dot and after_dot
3575 operators. rms says this is ok. --karl */
3583 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3589 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3595 BUF_PUSH_2 (categoryspec
, c
);
3601 BUF_PUSH_2 (notcategoryspec
, c
);
3607 if (syntax
& RE_NO_GNU_OPS
)
3610 BUF_PUSH_2 (syntaxspec
, Sword
);
3615 if (syntax
& RE_NO_GNU_OPS
)
3618 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3623 if (syntax
& RE_NO_GNU_OPS
)
3629 if (syntax
& RE_NO_GNU_OPS
)
3635 if (syntax
& RE_NO_GNU_OPS
)
3644 FREE_STACK_RETURN (REG_BADPAT
);
3648 if (syntax
& RE_NO_GNU_OPS
)
3650 BUF_PUSH (wordbound
);
3654 if (syntax
& RE_NO_GNU_OPS
)
3656 BUF_PUSH (notwordbound
);
3660 if (syntax
& RE_NO_GNU_OPS
)
3666 if (syntax
& RE_NO_GNU_OPS
)
3671 case '1': case '2': case '3': case '4': case '5':
3672 case '6': case '7': case '8': case '9':
3676 if (syntax
& RE_NO_BK_REFS
)
3677 goto normal_backslash
;
3681 if (reg
> bufp
->re_nsub
|| reg
< 1
3682 /* Can't back reference to a subexp before its end. */
3683 || group_in_compile_stack (compile_stack
, reg
))
3684 FREE_STACK_RETURN (REG_ESUBREG
);
3687 BUF_PUSH_2 (duplicate
, reg
);
3694 if (syntax
& RE_BK_PLUS_QM
)
3697 goto normal_backslash
;
3701 /* You might think it would be useful for \ to mean
3702 not to translate; but if we don't translate it
3703 it will never match anything. */
3710 /* Expects the character in `c'. */
3712 /* If no exactn currently being built. */
3715 /* If last exactn not at current position. */
3716 || pending_exact
+ *pending_exact
+ 1 != b
3718 /* We have only one byte following the exactn for the count. */
3719 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3721 /* If followed by a repetition operator. */
3722 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3723 || ((syntax
& RE_BK_PLUS_QM
)
3724 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3725 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3726 || ((syntax
& RE_INTERVALS
)
3727 && ((syntax
& RE_NO_BK_BRACES
)
3728 ? p
!= pend
&& *p
== '{'
3729 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3731 /* Start building a new exactn. */
3735 BUF_PUSH_2 (exactn
, 0);
3736 pending_exact
= b
- 1;
3739 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3746 len
= CHAR_STRING (c
, b
);
3751 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3752 if (! CHAR_BYTE8_P (c1
))
3754 re_wchar_t c2
= TRANSLATE (c1
);
3756 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3762 (*pending_exact
) += len
;
3767 } /* while p != pend */
3770 /* Through the pattern now. */
3774 if (!COMPILE_STACK_EMPTY
)
3775 FREE_STACK_RETURN (REG_EPAREN
);
3777 /* If we don't want backtracking, force success
3778 the first time we reach the end of the compiled pattern. */
3779 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3782 /* We have succeeded; set the length of the buffer. */
3783 bufp
->used
= b
- bufp
->buffer
;
3788 re_compile_fastmap (bufp
);
3789 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3790 print_compiled_pattern (bufp
);
3795 #ifndef MATCH_MAY_ALLOCATE
3796 /* Initialize the failure stack to the largest possible stack. This
3797 isn't necessary unless we're trying to avoid calling alloca in
3798 the search and match routines. */
3800 int num_regs
= bufp
->re_nsub
+ 1;
3802 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3804 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3806 if (! fail_stack
.stack
)
3808 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3809 * sizeof (fail_stack_elt_t
));
3812 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3814 * sizeof (fail_stack_elt_t
)));
3817 regex_grow_registers (num_regs
);
3819 #endif /* not MATCH_MAY_ALLOCATE */
3821 FREE_STACK_RETURN (REG_NOERROR
);
3822 } /* regex_compile */
3824 /* Subroutines for `regex_compile'. */
3826 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3829 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3831 *loc
= (unsigned char) op
;
3832 STORE_NUMBER (loc
+ 1, arg
);
3836 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3839 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3841 *loc
= (unsigned char) op
;
3842 STORE_NUMBER (loc
+ 1, arg1
);
3843 STORE_NUMBER (loc
+ 3, arg2
);
3847 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3848 for OP followed by two-byte integer parameter ARG. */
3851 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3853 register unsigned char *pfrom
= end
;
3854 register unsigned char *pto
= end
+ 3;
3856 while (pfrom
!= loc
)
3859 store_op1 (op
, loc
, arg
);
3863 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3866 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3868 register unsigned char *pfrom
= end
;
3869 register unsigned char *pto
= end
+ 5;
3871 while (pfrom
!= loc
)
3874 store_op2 (op
, loc
, arg1
, arg2
);
3878 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3879 after an alternative or a begin-subexpression. We assume there is at
3880 least one character before the ^. */
3883 at_begline_loc_p (const re_char
*pattern
, const re_char
*p
, reg_syntax_t syntax
)
3885 re_char
*prev
= p
- 2;
3886 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3889 /* After a subexpression? */
3890 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3891 /* After an alternative? */
3892 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3893 /* After a shy subexpression? */
3894 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3895 && prev
[-1] == '?' && prev
[-2] == '('
3896 && (syntax
& RE_NO_BK_PARENS
3897 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3901 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3902 at least one character after the $, i.e., `P < PEND'. */
3905 at_endline_loc_p (const re_char
*p
, const re_char
*pend
, reg_syntax_t syntax
)
3908 boolean next_backslash
= *next
== '\\';
3909 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3912 /* Before a subexpression? */
3913 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3914 : next_backslash
&& next_next
&& *next_next
== ')')
3915 /* Before an alternative? */
3916 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3917 : next_backslash
&& next_next
&& *next_next
== '|');
3921 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3922 false if it's not. */
3925 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3929 for (this_element
= compile_stack
.avail
- 1;
3932 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3939 If fastmap is non-NULL, go through the pattern and fill fastmap
3940 with all the possible leading chars. If fastmap is NULL, don't
3941 bother filling it up (obviously) and only return whether the
3942 pattern could potentially match the empty string.
3944 Return 1 if p..pend might match the empty string.
3945 Return 0 if p..pend matches at least one char.
3946 Return -1 if fastmap was not updated accurately. */
3949 analyse_first (const re_char
*p
, const re_char
*pend
, char *fastmap
, const int multibyte
)
3954 /* If all elements for base leading-codes in fastmap is set, this
3955 flag is set true. */
3956 boolean match_any_multibyte_characters
= false;
3960 /* The loop below works as follows:
3961 - It has a working-list kept in the PATTERN_STACK and which basically
3962 starts by only containing a pointer to the first operation.
3963 - If the opcode we're looking at is a match against some set of
3964 chars, then we add those chars to the fastmap and go on to the
3965 next work element from the worklist (done via `break').
3966 - If the opcode is a control operator on the other hand, we either
3967 ignore it (if it's meaningless at this point, such as `start_memory')
3968 or execute it (if it's a jump). If the jump has several destinations
3969 (i.e. `on_failure_jump'), then we push the other destination onto the
3971 We guarantee termination by ignoring backward jumps (more or less),
3972 so that `p' is monotonically increasing. More to the point, we
3973 never set `p' (or push) anything `<= p1'. */
3977 /* `p1' is used as a marker of how far back a `on_failure_jump'
3978 can go without being ignored. It is normally equal to `p'
3979 (which prevents any backward `on_failure_jump') except right
3980 after a plain `jump', to allow patterns such as:
3983 10: on_failure_jump 3
3984 as used for the *? operator. */
3987 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3993 /* If the first character has to match a backreference, that means
3994 that the group was empty (since it already matched). Since this
3995 is the only case that interests us here, we can assume that the
3996 backreference must match the empty string. */
4001 /* Following are the cases which match a character. These end
4007 /* If multibyte is nonzero, the first byte of each
4008 character is an ASCII or a leading code. Otherwise,
4009 each byte is a character. Thus, this works in both
4014 /* For the case of matching this unibyte regex
4015 against multibyte, we must set a leading code of
4016 the corresponding multibyte character. */
4017 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
4019 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
4026 /* We could put all the chars except for \n (and maybe \0)
4027 but we don't bother since it is generally not worth it. */
4028 if (!fastmap
) break;
4033 if (!fastmap
) break;
4035 /* Chars beyond end of bitmap are possible matches. */
4036 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
4037 j
< (1 << BYTEWIDTH
); j
++)
4043 if (!fastmap
) break;
4044 not = (re_opcode_t
) *(p
- 1) == charset_not
;
4045 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
4047 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
4051 if (/* Any leading code can possibly start a character
4052 which doesn't match the specified set of characters. */
4055 /* If we can match a character class, we can match any
4056 multibyte characters. */
4057 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4058 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
4061 if (match_any_multibyte_characters
== false)
4063 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4064 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4066 match_any_multibyte_characters
= true;
4070 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4071 && match_any_multibyte_characters
== false)
4073 /* Set fastmap[I] to 1 where I is a leading code of each
4074 multibyte character in the range table. */
4076 unsigned char lc1
, lc2
;
4078 /* Make P points the range table. `+ 2' is to skip flag
4079 bits for a character class. */
4080 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
4082 /* Extract the number of ranges in range table into COUNT. */
4083 EXTRACT_NUMBER_AND_INCR (count
, p
);
4084 for (; count
> 0; count
--, p
+= 3)
4086 /* Extract the start and end of each range. */
4087 EXTRACT_CHARACTER (c
, p
);
4088 lc1
= CHAR_LEADING_CODE (c
);
4090 EXTRACT_CHARACTER (c
, p
);
4091 lc2
= CHAR_LEADING_CODE (c
);
4092 for (j
= lc1
; j
<= lc2
; j
++)
4101 if (!fastmap
) break;
4103 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
4105 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4106 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4110 /* This match depends on text properties. These end with
4111 aborting optimizations. */
4115 case notcategoryspec
:
4116 if (!fastmap
) break;
4117 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4119 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
4120 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4123 /* Any leading code can possibly start a character which
4124 has or doesn't has the specified category. */
4125 if (match_any_multibyte_characters
== false)
4127 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4128 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4130 match_any_multibyte_characters
= true;
4134 /* All cases after this match the empty string. These end with
4156 EXTRACT_NUMBER_AND_INCR (j
, p
);
4158 /* Backward jumps can only go back to code that we've already
4159 visited. `re_compile' should make sure this is true. */
4162 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4164 case on_failure_jump
:
4165 case on_failure_keep_string_jump
:
4166 case on_failure_jump_loop
:
4167 case on_failure_jump_nastyloop
:
4168 case on_failure_jump_smart
:
4174 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4175 to jump back to "just after here". */
4178 case on_failure_jump
:
4179 case on_failure_keep_string_jump
:
4180 case on_failure_jump_nastyloop
:
4181 case on_failure_jump_loop
:
4182 case on_failure_jump_smart
:
4183 EXTRACT_NUMBER_AND_INCR (j
, p
);
4185 ; /* Backward jump to be ignored. */
4187 { /* We have to look down both arms.
4188 We first go down the "straight" path so as to minimize
4189 stack usage when going through alternatives. */
4190 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4198 /* This code simply does not properly handle forward jump_n. */
4199 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4201 /* jump_n can either jump or fall through. The (backward) jump
4202 case has already been handled, so we only need to look at the
4203 fallthrough case. */
4207 /* If N == 0, it should be an on_failure_jump_loop instead. */
4208 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4210 /* We only care about one iteration of the loop, so we don't
4211 need to consider the case where this behaves like an
4228 abort (); /* We have listed all the cases. */
4231 /* Getting here means we have found the possible starting
4232 characters for one path of the pattern -- and that the empty
4233 string does not match. We need not follow this path further. */
4237 /* We reached the end without matching anything. */
4240 } /* analyse_first */
4242 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4243 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4244 characters can start a string that matches the pattern. This fastmap
4245 is used by re_search to skip quickly over impossible starting points.
4247 Character codes above (1 << BYTEWIDTH) are not represented in the
4248 fastmap, but the leading codes are represented. Thus, the fastmap
4249 indicates which character sets could start a match.
4251 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4252 area as BUFP->fastmap.
4254 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4257 Returns 0 if we succeed, -2 if an internal error. */
4260 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4262 char *fastmap
= bufp
->fastmap
;
4265 assert (fastmap
&& bufp
->buffer
);
4267 memset (fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4268 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4270 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4271 fastmap
, RE_MULTIBYTE_P (bufp
));
4272 bufp
->can_be_null
= (analysis
!= 0);
4274 } /* re_compile_fastmap */
4276 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4277 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4278 this memory for recording register information. STARTS and ENDS
4279 must be allocated using the malloc library routine, and must each
4280 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4282 If NUM_REGS == 0, then subsequent matches should allocate their own
4285 Unless this function is called, the first search or match using
4286 PATTERN_BUFFER will allocate its own register data, without
4287 freeing the old data. */
4290 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4294 bufp
->regs_allocated
= REGS_REALLOCATE
;
4295 regs
->num_regs
= num_regs
;
4296 regs
->start
= starts
;
4301 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4303 regs
->start
= regs
->end
= (regoff_t
*) 0;
4306 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4308 /* Searching routines. */
4310 /* Like re_search_2, below, but only one string is specified, and
4311 doesn't let you say where to stop matching. */
4314 re_search (struct re_pattern_buffer
*bufp
, const char *string
, int size
, int startpos
, int range
, struct re_registers
*regs
)
4316 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4319 WEAK_ALIAS (__re_search
, re_search
)
4321 /* Head address of virtual concatenation of string. */
4322 #define HEAD_ADDR_VSTRING(P) \
4323 (((P) >= size1 ? string2 : string1))
4325 /* End address of virtual concatenation of string. */
4326 #define STOP_ADDR_VSTRING(P) \
4327 (((P) >= size1 ? string2 + size2 : string1 + size1))
4329 /* Address of POS in the concatenation of virtual string. */
4330 #define POS_ADDR_VSTRING(POS) \
4331 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4333 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4334 virtual concatenation of STRING1 and STRING2, starting first at index
4335 STARTPOS, then at STARTPOS + 1, and so on.
4337 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4339 RANGE is how far to scan while trying to match. RANGE = 0 means try
4340 only at STARTPOS; in general, the last start tried is STARTPOS +
4343 In REGS, return the indices of the virtual concatenation of STRING1
4344 and STRING2 that matched the entire BUFP->buffer and its contained
4347 Do not consider matching one past the index STOP in the virtual
4348 concatenation of STRING1 and STRING2.
4350 We return either the position in the strings at which the match was
4351 found, -1 if no match, or -2 if error (such as failure
4355 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, int size1
, const char *str2
, int size2
, int startpos
, int range
, struct re_registers
*regs
, int stop
)
4358 re_char
*string1
= (re_char
*) str1
;
4359 re_char
*string2
= (re_char
*) str2
;
4360 register char *fastmap
= bufp
->fastmap
;
4361 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4362 int total_size
= size1
+ size2
;
4363 int endpos
= startpos
+ range
;
4364 boolean anchored_start
;
4365 /* Nonzero if we are searching multibyte string. */
4366 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4368 /* Check for out-of-range STARTPOS. */
4369 if (startpos
< 0 || startpos
> total_size
)
4372 /* Fix up RANGE if it might eventually take us outside
4373 the virtual concatenation of STRING1 and STRING2.
4374 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4376 range
= 0 - startpos
;
4377 else if (endpos
> total_size
)
4378 range
= total_size
- startpos
;
4380 /* If the search isn't to be a backwards one, don't waste time in a
4381 search for a pattern anchored at beginning of buffer. */
4382 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4391 /* In a forward search for something that starts with \=.
4392 don't keep searching past point. */
4393 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4395 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4401 /* Update the fastmap now if not correct already. */
4402 if (fastmap
&& !bufp
->fastmap_accurate
)
4403 re_compile_fastmap (bufp
);
4405 /* See whether the pattern is anchored. */
4406 anchored_start
= (bufp
->buffer
[0] == begline
);
4409 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4411 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4413 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4417 /* Loop through the string, looking for a place to start matching. */
4420 /* If the pattern is anchored,
4421 skip quickly past places we cannot match.
4422 We don't bother to treat startpos == 0 specially
4423 because that case doesn't repeat. */
4424 if (anchored_start
&& startpos
> 0)
4426 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4427 : string2
[startpos
- size1
- 1])
4432 /* If a fastmap is supplied, skip quickly over characters that
4433 cannot be the start of a match. If the pattern can match the
4434 null string, however, we don't need to skip characters; we want
4435 the first null string. */
4436 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4438 register re_char
*d
;
4439 register re_wchar_t buf_ch
;
4441 d
= POS_ADDR_VSTRING (startpos
);
4443 if (range
> 0) /* Searching forwards. */
4445 register int lim
= 0;
4448 if (startpos
< size1
&& startpos
+ range
>= size1
)
4449 lim
= range
- (size1
- startpos
);
4451 /* Written out as an if-else to avoid testing `translate'
4453 if (RE_TRANSLATE_P (translate
))
4460 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4461 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4462 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4465 range
-= buf_charlen
;
4471 register re_wchar_t ch
, translated
;
4474 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4475 translated
= RE_TRANSLATE (translate
, ch
);
4476 if (translated
!= ch
4477 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4479 if (fastmap
[buf_ch
])
4492 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4493 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4495 range
-= buf_charlen
;
4499 while (range
> lim
&& !fastmap
[*d
])
4505 startpos
+= irange
- range
;
4507 else /* Searching backwards. */
4511 buf_ch
= STRING_CHAR (d
);
4512 buf_ch
= TRANSLATE (buf_ch
);
4513 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4518 register re_wchar_t ch
, translated
;
4521 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4522 translated
= TRANSLATE (ch
);
4523 if (translated
!= ch
4524 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4526 if (! fastmap
[TRANSLATE (buf_ch
)])
4532 /* If can't match the null string, and that's all we have left, fail. */
4533 if (range
>= 0 && startpos
== total_size
&& fastmap
4534 && !bufp
->can_be_null
)
4537 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4538 startpos
, regs
, stop
);
4551 /* Update STARTPOS to the next character boundary. */
4554 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4555 int len
= BYTES_BY_CHAR_HEAD (*p
);
4573 /* Update STARTPOS to the previous character boundary. */
4576 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4578 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4580 /* Find the head of multibyte form. */
4581 PREV_CHAR_BOUNDARY (p
, phead
);
4582 range
+= p0
- 1 - p
;
4586 startpos
-= p0
- 1 - p
;
4592 WEAK_ALIAS (__re_search_2
, re_search_2
)
4594 /* Declarations and macros for re_match_2. */
4596 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4598 RE_TRANSLATE_TYPE translate
,
4599 const int multibyte
));
4601 /* This converts PTR, a pointer into one of the search strings `string1'
4602 and `string2' into an offset from the beginning of that string. */
4603 #define POINTER_TO_OFFSET(ptr) \
4604 (FIRST_STRING_P (ptr) \
4605 ? ((regoff_t) ((ptr) - string1)) \
4606 : ((regoff_t) ((ptr) - string2 + size1)))
4608 /* Call before fetching a character with *d. This switches over to
4609 string2 if necessary.
4610 Check re_match_2_internal for a discussion of why end_match_2 might
4611 not be within string2 (but be equal to end_match_1 instead). */
4612 #define PREFETCH() \
4615 /* End of string2 => fail. */ \
4616 if (dend == end_match_2) \
4618 /* End of string1 => advance to string2. */ \
4620 dend = end_match_2; \
4623 /* Call before fetching a char with *d if you already checked other limits.
4624 This is meant for use in lookahead operations like wordend, etc..
4625 where we might need to look at parts of the string that might be
4626 outside of the LIMITs (i.e past `stop'). */
4627 #define PREFETCH_NOLIMIT() \
4631 dend = end_match_2; \
4634 /* Test if at very beginning or at very end of the virtual concatenation
4635 of `string1' and `string2'. If only one string, it's `string2'. */
4636 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4637 #define AT_STRINGS_END(d) ((d) == end2)
4640 /* Test if D points to a character which is word-constituent. We have
4641 two special cases to check for: if past the end of string1, look at
4642 the first character in string2; and if before the beginning of
4643 string2, look at the last character in string1. */
4644 #define WORDCHAR_P(d) \
4645 (SYNTAX ((d) == end1 ? *string2 \
4646 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4649 /* Disabled due to a compiler bug -- see comment at case wordbound */
4651 /* The comment at case wordbound is following one, but we don't use
4652 AT_WORD_BOUNDARY anymore to support multibyte form.
4654 The DEC Alpha C compiler 3.x generates incorrect code for the
4655 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4656 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4657 macro and introducing temporary variables works around the bug. */
4660 /* Test if the character before D and the one at D differ with respect
4661 to being word-constituent. */
4662 #define AT_WORD_BOUNDARY(d) \
4663 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4664 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4667 /* Free everything we malloc. */
4668 #ifdef MATCH_MAY_ALLOCATE
4669 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4670 # define FREE_VARIABLES() \
4672 REGEX_FREE_STACK (fail_stack.stack); \
4673 FREE_VAR (regstart); \
4674 FREE_VAR (regend); \
4675 FREE_VAR (best_regstart); \
4676 FREE_VAR (best_regend); \
4679 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4680 #endif /* not MATCH_MAY_ALLOCATE */
4683 /* Optimization routines. */
4685 /* If the operation is a match against one or more chars,
4686 return a pointer to the next operation, else return NULL. */
4688 skip_one_char (const re_char
*p
)
4690 switch (SWITCH_ENUM_CAST (*p
++))
4701 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4704 p
= CHARSET_RANGE_TABLE (p
- 1);
4705 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4706 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4709 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4716 case notcategoryspec
:
4728 /* Jump over non-matching operations. */
4730 skip_noops (const re_char
*p
, const re_char
*pend
)
4735 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4744 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4755 /* Non-zero if "p1 matches something" implies "p2 fails". */
4757 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const re_char
*p1
, const re_char
*p2
)
4760 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4761 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4763 assert (p1
>= bufp
->buffer
&& p1
< pend
4764 && p2
>= bufp
->buffer
&& p2
<= pend
);
4766 /* Skip over open/close-group commands.
4767 If what follows this loop is a ...+ construct,
4768 look at what begins its body, since we will have to
4769 match at least one of that. */
4770 p2
= skip_noops (p2
, pend
);
4771 /* The same skip can be done for p1, except that this function
4772 is only used in the case where p1 is a simple match operator. */
4773 /* p1 = skip_noops (p1, pend); */
4775 assert (p1
>= bufp
->buffer
&& p1
< pend
4776 && p2
>= bufp
->buffer
&& p2
<= pend
);
4778 op2
= p2
== pend
? succeed
: *p2
;
4780 switch (SWITCH_ENUM_CAST (op2
))
4784 /* If we're at the end of the pattern, we can change. */
4785 if (skip_one_char (p1
))
4787 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4795 register re_wchar_t c
4796 = (re_opcode_t
) *p2
== endline
? '\n'
4797 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4799 if ((re_opcode_t
) *p1
== exactn
)
4801 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4803 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4808 else if ((re_opcode_t
) *p1
== charset
4809 || (re_opcode_t
) *p1
== charset_not
)
4811 int not = (re_opcode_t
) *p1
== charset_not
;
4813 /* Test if C is listed in charset (or charset_not)
4815 if (! multibyte
|| IS_REAL_ASCII (c
))
4817 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4818 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4821 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4822 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4824 /* `not' is equal to 1 if c would match, which means
4825 that we can't change to pop_failure_jump. */
4828 DEBUG_PRINT1 (" No match => fast loop.\n");
4832 else if ((re_opcode_t
) *p1
== anychar
4835 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4843 if ((re_opcode_t
) *p1
== exactn
)
4844 /* Reuse the code above. */
4845 return mutually_exclusive_p (bufp
, p2
, p1
);
4847 /* It is hard to list up all the character in charset
4848 P2 if it includes multibyte character. Give up in
4850 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4852 /* Now, we are sure that P2 has no range table.
4853 So, for the size of bitmap in P2, `p2[1]' is
4854 enough. But P1 may have range table, so the
4855 size of bitmap table of P1 is extracted by
4856 using macro `CHARSET_BITMAP_SIZE'.
4858 In a multibyte case, we know that all the character
4859 listed in P2 is ASCII. In a unibyte case, P1 has only a
4860 bitmap table. So, in both cases, it is enough to test
4861 only the bitmap table of P1. */
4863 if ((re_opcode_t
) *p1
== charset
)
4866 /* We win if the charset inside the loop
4867 has no overlap with the one after the loop. */
4870 && idx
< CHARSET_BITMAP_SIZE (p1
));
4872 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4876 || idx
== CHARSET_BITMAP_SIZE (p1
))
4878 DEBUG_PRINT1 (" No match => fast loop.\n");
4882 else if ((re_opcode_t
) *p1
== charset_not
)
4885 /* We win if the charset_not inside the loop lists
4886 every character listed in the charset after. */
4887 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4888 if (! (p2
[2 + idx
] == 0
4889 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4890 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4895 DEBUG_PRINT1 (" No match => fast loop.\n");
4904 switch (SWITCH_ENUM_CAST (*p1
))
4908 /* Reuse the code above. */
4909 return mutually_exclusive_p (bufp
, p2
, p1
);
4911 /* When we have two charset_not, it's very unlikely that
4912 they don't overlap. The union of the two sets of excluded
4913 chars should cover all possible chars, which, as a matter of
4914 fact, is virtually impossible in multibyte buffers. */
4920 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4922 return ((re_opcode_t
) *p1
== syntaxspec
4923 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4925 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4928 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4930 return ((re_opcode_t
) *p1
== notsyntaxspec
4931 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4933 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4936 return (((re_opcode_t
) *p1
== notsyntaxspec
4937 || (re_opcode_t
) *p1
== syntaxspec
)
4942 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4943 case notcategoryspec
:
4944 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4956 /* Matching routines. */
4958 #ifndef emacs /* Emacs never uses this. */
4959 /* re_match is like re_match_2 except it takes only a single string. */
4962 re_match (struct re_pattern_buffer
*bufp
, const char *string
,
4963 int size
, int pos
, struct re_registers
*regs
)
4965 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
4969 WEAK_ALIAS (__re_match
, re_match
)
4970 #endif /* not emacs */
4973 /* In Emacs, this is the string or buffer in which we
4974 are matching. It is used for looking up syntax properties. */
4975 Lisp_Object re_match_object
;
4978 /* re_match_2 matches the compiled pattern in BUFP against the
4979 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4980 and SIZE2, respectively). We start matching at POS, and stop
4983 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4984 store offsets for the substring each group matched in REGS. See the
4985 documentation for exactly how many groups we fill.
4987 We return -1 if no match, -2 if an internal error (such as the
4988 failure stack overflowing). Otherwise, we return the length of the
4989 matched substring. */
4992 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
, int size1
, const char *string2
, int size2
, int pos
, struct re_registers
*regs
, int stop
)
4998 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4999 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
5000 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
5003 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
5004 (re_char
*) string2
, size2
,
5008 WEAK_ALIAS (__re_match_2
, re_match_2
)
5011 /* This is a separate function so that we can force an alloca cleanup
5014 re_match_2_internal (struct re_pattern_buffer
*bufp
, const re_char
*string1
, int size1
, const re_char
*string2
, int size2
, int pos
, struct re_registers
*regs
, int stop
)
5016 /* General temporaries. */
5020 /* Just past the end of the corresponding string. */
5021 re_char
*end1
, *end2
;
5023 /* Pointers into string1 and string2, just past the last characters in
5024 each to consider matching. */
5025 re_char
*end_match_1
, *end_match_2
;
5027 /* Where we are in the data, and the end of the current string. */
5030 /* Used sometimes to remember where we were before starting matching
5031 an operator so that we can go back in case of failure. This "atomic"
5032 behavior of matching opcodes is indispensable to the correctness
5033 of the on_failure_keep_string_jump optimization. */
5036 /* Where we are in the pattern, and the end of the pattern. */
5037 re_char
*p
= bufp
->buffer
;
5038 re_char
*pend
= p
+ bufp
->used
;
5040 /* We use this to map every character in the string. */
5041 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
5043 /* Nonzero if BUFP is setup from a multibyte regex. */
5044 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
5046 /* Nonzero if STRING1/STRING2 are multibyte. */
5047 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
5049 /* Failure point stack. Each place that can handle a failure further
5050 down the line pushes a failure point on this stack. It consists of
5051 regstart, and regend for all registers corresponding to
5052 the subexpressions we're currently inside, plus the number of such
5053 registers, and, finally, two char *'s. The first char * is where
5054 to resume scanning the pattern; the second one is where to resume
5055 scanning the strings. */
5056 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5057 fail_stack_type fail_stack
;
5060 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
5063 #if defined REL_ALLOC && defined REGEX_MALLOC
5064 /* This holds the pointer to the failure stack, when
5065 it is allocated relocatably. */
5066 fail_stack_elt_t
*failure_stack_ptr
;
5069 /* We fill all the registers internally, independent of what we
5070 return, for use in backreferences. The number here includes
5071 an element for register zero. */
5072 size_t num_regs
= bufp
->re_nsub
+ 1;
5074 /* Information on the contents of registers. These are pointers into
5075 the input strings; they record just what was matched (on this
5076 attempt) by a subexpression part of the pattern, that is, the
5077 regnum-th regstart pointer points to where in the pattern we began
5078 matching and the regnum-th regend points to right after where we
5079 stopped matching the regnum-th subexpression. (The zeroth register
5080 keeps track of what the whole pattern matches.) */
5081 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5082 re_char
**regstart
, **regend
;
5085 /* The following record the register info as found in the above
5086 variables when we find a match better than any we've seen before.
5087 This happens as we backtrack through the failure points, which in
5088 turn happens only if we have not yet matched the entire string. */
5089 unsigned best_regs_set
= false;
5090 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5091 re_char
**best_regstart
, **best_regend
;
5094 /* Logically, this is `best_regend[0]'. But we don't want to have to
5095 allocate space for that if we're not allocating space for anything
5096 else (see below). Also, we never need info about register 0 for
5097 any of the other register vectors, and it seems rather a kludge to
5098 treat `best_regend' differently than the rest. So we keep track of
5099 the end of the best match so far in a separate variable. We
5100 initialize this to NULL so that when we backtrack the first time
5101 and need to test it, it's not garbage. */
5102 re_char
*match_end
= NULL
;
5105 /* Counts the total number of registers pushed. */
5106 unsigned num_regs_pushed
= 0;
5109 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5113 #ifdef MATCH_MAY_ALLOCATE
5114 /* Do not bother to initialize all the register variables if there are
5115 no groups in the pattern, as it takes a fair amount of time. If
5116 there are groups, we include space for register 0 (the whole
5117 pattern), even though we never use it, since it simplifies the
5118 array indexing. We should fix this. */
5121 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5122 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5123 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5124 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5126 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5134 /* We must initialize all our variables to NULL, so that
5135 `FREE_VARIABLES' doesn't try to free them. */
5136 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5138 #endif /* MATCH_MAY_ALLOCATE */
5140 /* The starting position is bogus. */
5141 if (pos
< 0 || pos
> size1
+ size2
)
5147 /* Initialize subexpression text positions to -1 to mark ones that no
5148 start_memory/stop_memory has been seen for. Also initialize the
5149 register information struct. */
5150 for (reg
= 1; reg
< num_regs
; reg
++)
5151 regstart
[reg
] = regend
[reg
] = NULL
;
5153 /* We move `string1' into `string2' if the latter's empty -- but not if
5154 `string1' is null. */
5155 if (size2
== 0 && string1
!= NULL
)
5162 end1
= string1
+ size1
;
5163 end2
= string2
+ size2
;
5165 /* `p' scans through the pattern as `d' scans through the data.
5166 `dend' is the end of the input string that `d' points within. `d'
5167 is advanced into the following input string whenever necessary, but
5168 this happens before fetching; therefore, at the beginning of the
5169 loop, `d' can be pointing at the end of a string, but it cannot
5173 /* Only match within string2. */
5174 d
= string2
+ pos
- size1
;
5175 dend
= end_match_2
= string2
+ stop
- size1
;
5176 end_match_1
= end1
; /* Just to give it a value. */
5182 /* Only match within string1. */
5183 end_match_1
= string1
+ stop
;
5185 When we reach end_match_1, PREFETCH normally switches to string2.
5186 But in the present case, this means that just doing a PREFETCH
5187 makes us jump from `stop' to `gap' within the string.
5188 What we really want here is for the search to stop as
5189 soon as we hit end_match_1. That's why we set end_match_2
5190 to end_match_1 (since PREFETCH fails as soon as we hit
5192 end_match_2
= end_match_1
;
5195 { /* It's important to use this code when stop == size so that
5196 moving `d' from end1 to string2 will not prevent the d == dend
5197 check from catching the end of string. */
5199 end_match_2
= string2
+ stop
- size1
;
5205 DEBUG_PRINT1 ("The compiled pattern is: ");
5206 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5207 DEBUG_PRINT1 ("The string to match is: `");
5208 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5209 DEBUG_PRINT1 ("'\n");
5211 /* This loops over pattern commands. It exits by returning from the
5212 function if the match is complete, or it drops through if the match
5213 fails at this starting point in the input data. */
5216 DEBUG_PRINT2 ("\n%p: ", p
);
5219 { /* End of pattern means we might have succeeded. */
5220 DEBUG_PRINT1 ("end of pattern ... ");
5222 /* If we haven't matched the entire string, and we want the
5223 longest match, try backtracking. */
5224 if (d
!= end_match_2
)
5226 /* 1 if this match ends in the same string (string1 or string2)
5227 as the best previous match. */
5228 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5229 == FIRST_STRING_P (d
));
5230 /* 1 if this match is the best seen so far. */
5231 boolean best_match_p
;
5233 /* AIX compiler got confused when this was combined
5234 with the previous declaration. */
5236 best_match_p
= d
> match_end
;
5238 best_match_p
= !FIRST_STRING_P (d
);
5240 DEBUG_PRINT1 ("backtracking.\n");
5242 if (!FAIL_STACK_EMPTY ())
5243 { /* More failure points to try. */
5245 /* If exceeds best match so far, save it. */
5246 if (!best_regs_set
|| best_match_p
)
5248 best_regs_set
= true;
5251 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5253 for (reg
= 1; reg
< num_regs
; reg
++)
5255 best_regstart
[reg
] = regstart
[reg
];
5256 best_regend
[reg
] = regend
[reg
];
5262 /* If no failure points, don't restore garbage. And if
5263 last match is real best match, don't restore second
5265 else if (best_regs_set
&& !best_match_p
)
5268 /* Restore best match. It may happen that `dend ==
5269 end_match_1' while the restored d is in string2.
5270 For example, the pattern `x.*y.*z' against the
5271 strings `x-' and `y-z-', if the two strings are
5272 not consecutive in memory. */
5273 DEBUG_PRINT1 ("Restoring best registers.\n");
5276 dend
= ((d
>= string1
&& d
<= end1
)
5277 ? end_match_1
: end_match_2
);
5279 for (reg
= 1; reg
< num_regs
; reg
++)
5281 regstart
[reg
] = best_regstart
[reg
];
5282 regend
[reg
] = best_regend
[reg
];
5285 } /* d != end_match_2 */
5288 DEBUG_PRINT1 ("Accepting match.\n");
5290 /* If caller wants register contents data back, do it. */
5291 if (regs
&& !bufp
->no_sub
)
5293 /* Have the register data arrays been allocated? */
5294 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5295 { /* No. So allocate them with malloc. We need one
5296 extra element beyond `num_regs' for the `-1' marker
5298 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5299 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5300 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5301 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5306 bufp
->regs_allocated
= REGS_REALLOCATE
;
5308 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5309 { /* Yes. If we need more elements than were already
5310 allocated, reallocate them. If we need fewer, just
5312 if (regs
->num_regs
< num_regs
+ 1)
5314 regs
->num_regs
= num_regs
+ 1;
5315 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5316 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5317 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5326 /* These braces fend off a "empty body in an else-statement"
5327 warning under GCC when assert expands to nothing. */
5328 assert (bufp
->regs_allocated
== REGS_FIXED
);
5331 /* Convert the pointer data in `regstart' and `regend' to
5332 indices. Register zero has to be set differently,
5333 since we haven't kept track of any info for it. */
5334 if (regs
->num_regs
> 0)
5336 regs
->start
[0] = pos
;
5337 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5340 /* Go through the first `min (num_regs, regs->num_regs)'
5341 registers, since that is all we initialized. */
5342 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5344 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5345 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5349 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
5351 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
5355 /* If the regs structure we return has more elements than
5356 were in the pattern, set the extra elements to -1. If
5357 we (re)allocated the registers, this is the case,
5358 because we always allocate enough to have at least one
5360 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5361 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5362 } /* regs && !bufp->no_sub */
5364 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5365 nfailure_points_pushed
, nfailure_points_popped
,
5366 nfailure_points_pushed
- nfailure_points_popped
);
5367 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
5369 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
5371 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5377 /* Otherwise match next pattern command. */
5378 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5380 /* Ignore these. Used to ignore the n of succeed_n's which
5381 currently have n == 0. */
5383 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5387 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5390 /* Match the next n pattern characters exactly. The following
5391 byte in the pattern defines n, and the n bytes after that
5392 are the characters to match. */
5395 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5397 /* Remember the start point to rollback upon failure. */
5401 /* This is written out as an if-else so we don't waste time
5402 testing `translate' inside the loop. */
5403 if (RE_TRANSLATE_P (translate
))
5407 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5427 /* The cost of testing `translate' is comparatively small. */
5428 if (target_multibyte
)
5431 int pat_charlen
, buf_charlen
;
5436 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5439 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5442 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5444 if (TRANSLATE (buf_ch
) != pat_ch
)
5452 mcnt
-= pat_charlen
;
5464 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5465 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5472 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5473 if (! CHAR_BYTE8_P (buf_ch
))
5475 buf_ch
= TRANSLATE (buf_ch
);
5476 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5482 if (buf_ch
!= pat_ch
)
5495 /* Match any character except possibly a newline or a null. */
5501 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5504 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5506 buf_ch
= TRANSLATE (buf_ch
);
5508 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5510 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5511 && buf_ch
== '\000'))
5514 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5523 register unsigned int c
;
5524 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5527 /* Start of actual range_table, or end of bitmap if there is no
5529 re_char
*range_table
;
5531 /* Nonzero if there is a range table. */
5532 int range_table_exists
;
5534 /* Number of ranges of range table. This is not included
5535 in the initial byte-length of the command. */
5538 /* Whether matching against a unibyte character. */
5539 boolean unibyte_char
= false;
5541 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5543 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5545 if (range_table_exists
)
5547 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5548 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5552 c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5553 if (target_multibyte
)
5558 c1
= RE_CHAR_TO_UNIBYTE (c
);
5561 unibyte_char
= true;
5567 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5569 if (! CHAR_BYTE8_P (c1
))
5571 c1
= TRANSLATE (c1
);
5572 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5575 unibyte_char
= true;
5580 unibyte_char
= true;
5583 if (unibyte_char
&& c
< (1 << BYTEWIDTH
))
5584 { /* Lookup bitmap. */
5585 /* Cast to `unsigned' instead of `unsigned char' in
5586 case the bit list is a full 32 bytes long. */
5587 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5588 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5592 else if (range_table_exists
)
5594 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5596 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5597 | (class_bits
& BIT_MULTIBYTE
)
5598 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5599 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5600 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5601 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5604 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5608 if (range_table_exists
)
5609 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5611 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5613 if (!not) goto fail
;
5620 /* The beginning of a group is represented by start_memory.
5621 The argument is the register number. The text
5622 matched within the group is recorded (in the internal
5623 registers data structure) under the register number. */
5625 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5627 /* In case we need to undo this operation (via backtracking). */
5628 PUSH_FAILURE_REG ((unsigned int)*p
);
5631 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5632 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5634 /* Move past the register number and inner group count. */
5639 /* The stop_memory opcode represents the end of a group. Its
5640 argument is the same as start_memory's: the register number. */
5642 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5644 assert (!REG_UNSET (regstart
[*p
]));
5645 /* Strictly speaking, there should be code such as:
5647 assert (REG_UNSET (regend[*p]));
5648 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5650 But the only info to be pushed is regend[*p] and it is known to
5651 be UNSET, so there really isn't anything to push.
5652 Not pushing anything, on the other hand deprives us from the
5653 guarantee that regend[*p] is UNSET since undoing this operation
5654 will not reset its value properly. This is not important since
5655 the value will only be read on the next start_memory or at
5656 the very end and both events can only happen if this stop_memory
5660 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5662 /* Move past the register number and the inner group count. */
5667 /* \<digit> has been turned into a `duplicate' command which is
5668 followed by the numeric value of <digit> as the register number. */
5671 register re_char
*d2
, *dend2
;
5672 int regno
= *p
++; /* Get which register to match against. */
5673 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5675 /* Can't back reference a group which we've never matched. */
5676 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5679 /* Where in input to try to start matching. */
5680 d2
= regstart
[regno
];
5682 /* Remember the start point to rollback upon failure. */
5685 /* Where to stop matching; if both the place to start and
5686 the place to stop matching are in the same string, then
5687 set to the place to stop, otherwise, for now have to use
5688 the end of the first string. */
5690 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5691 == FIRST_STRING_P (regend
[regno
]))
5692 ? regend
[regno
] : end_match_1
);
5695 /* If necessary, advance to next segment in register
5699 if (dend2
== end_match_2
) break;
5700 if (dend2
== regend
[regno
]) break;
5702 /* End of string1 => advance to string2. */
5704 dend2
= regend
[regno
];
5706 /* At end of register contents => success */
5707 if (d2
== dend2
) break;
5709 /* If necessary, advance to next segment in data. */
5712 /* How many characters left in this segment to match. */
5715 /* Want how many consecutive characters we can match in
5716 one shot, so, if necessary, adjust the count. */
5717 if (mcnt
> dend2
- d2
)
5720 /* Compare that many; failure if mismatch, else move
5722 if (RE_TRANSLATE_P (translate
)
5723 ? bcmp_translate (d
, d2
, mcnt
, translate
, target_multibyte
)
5724 : memcmp (d
, d2
, mcnt
))
5729 d
+= mcnt
, d2
+= mcnt
;
5735 /* begline matches the empty string at the beginning of the string
5736 (unless `not_bol' is set in `bufp'), and after newlines. */
5738 DEBUG_PRINT1 ("EXECUTING begline.\n");
5740 if (AT_STRINGS_BEG (d
))
5742 if (!bufp
->not_bol
) break;
5747 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5751 /* In all other cases, we fail. */
5755 /* endline is the dual of begline. */
5757 DEBUG_PRINT1 ("EXECUTING endline.\n");
5759 if (AT_STRINGS_END (d
))
5761 if (!bufp
->not_eol
) break;
5765 PREFETCH_NOLIMIT ();
5772 /* Match at the very beginning of the data. */
5774 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5775 if (AT_STRINGS_BEG (d
))
5780 /* Match at the very end of the data. */
5782 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5783 if (AT_STRINGS_END (d
))
5788 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5789 pushes NULL as the value for the string on the stack. Then
5790 `POP_FAILURE_POINT' will keep the current value for the
5791 string, instead of restoring it. To see why, consider
5792 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5793 then the . fails against the \n. But the next thing we want
5794 to do is match the \n against the \n; if we restored the
5795 string value, we would be back at the foo.
5797 Because this is used only in specific cases, we don't need to
5798 check all the things that `on_failure_jump' does, to make
5799 sure the right things get saved on the stack. Hence we don't
5800 share its code. The only reason to push anything on the
5801 stack at all is that otherwise we would have to change
5802 `anychar's code to do something besides goto fail in this
5803 case; that seems worse than this. */
5804 case on_failure_keep_string_jump
:
5805 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5806 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5809 PUSH_FAILURE_POINT (p
- 3, NULL
);
5812 /* A nasty loop is introduced by the non-greedy *? and +?.
5813 With such loops, the stack only ever contains one failure point
5814 at a time, so that a plain on_failure_jump_loop kind of
5815 cycle detection cannot work. Worse yet, such a detection
5816 can not only fail to detect a cycle, but it can also wrongly
5817 detect a cycle (between different instantiations of the same
5819 So the method used for those nasty loops is a little different:
5820 We use a special cycle-detection-stack-frame which is pushed
5821 when the on_failure_jump_nastyloop failure-point is *popped*.
5822 This special frame thus marks the beginning of one iteration
5823 through the loop and we can hence easily check right here
5824 whether something matched between the beginning and the end of
5826 case on_failure_jump_nastyloop
:
5827 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5828 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5831 assert ((re_opcode_t
)p
[-4] == no_op
);
5834 CHECK_INFINITE_LOOP (p
- 4, d
);
5836 /* If there's a cycle, just continue without pushing
5837 this failure point. The failure point is the "try again"
5838 option, which shouldn't be tried.
5839 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5840 PUSH_FAILURE_POINT (p
- 3, d
);
5844 /* Simple loop detecting on_failure_jump: just check on the
5845 failure stack if the same spot was already hit earlier. */
5846 case on_failure_jump_loop
:
5848 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5849 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5853 CHECK_INFINITE_LOOP (p
- 3, d
);
5855 /* If there's a cycle, get out of the loop, as if the matching
5856 had failed. We used to just `goto fail' here, but that was
5857 aborting the search a bit too early: we want to keep the
5858 empty-loop-match and keep matching after the loop.
5859 We want (x?)*y\1z to match both xxyz and xxyxz. */
5862 PUSH_FAILURE_POINT (p
- 3, d
);
5867 /* Uses of on_failure_jump:
5869 Each alternative starts with an on_failure_jump that points
5870 to the beginning of the next alternative. Each alternative
5871 except the last ends with a jump that in effect jumps past
5872 the rest of the alternatives. (They really jump to the
5873 ending jump of the following alternative, because tensioning
5874 these jumps is a hassle.)
5876 Repeats start with an on_failure_jump that points past both
5877 the repetition text and either the following jump or
5878 pop_failure_jump back to this on_failure_jump. */
5879 case on_failure_jump
:
5880 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5881 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5884 PUSH_FAILURE_POINT (p
-3, d
);
5887 /* This operation is used for greedy *.
5888 Compare the beginning of the repeat with what in the
5889 pattern follows its end. If we can establish that there
5890 is nothing that they would both match, i.e., that we
5891 would have to backtrack because of (as in, e.g., `a*a')
5892 then we can use a non-backtracking loop based on
5893 on_failure_keep_string_jump instead of on_failure_jump. */
5894 case on_failure_jump_smart
:
5895 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5896 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5899 re_char
*p1
= p
; /* Next operation. */
5900 /* Here, we discard `const', making re_match non-reentrant. */
5901 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5902 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5904 p
-= 3; /* Reset so that we will re-execute the
5905 instruction once it's been changed. */
5907 EXTRACT_NUMBER (mcnt
, p2
- 2);
5909 /* Ensure this is a indeed the trivial kind of loop
5910 we are expecting. */
5911 assert (skip_one_char (p1
) == p2
- 3);
5912 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5913 DEBUG_STATEMENT (debug
+= 2);
5914 if (mutually_exclusive_p (bufp
, p1
, p2
))
5916 /* Use a fast `on_failure_keep_string_jump' loop. */
5917 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5918 *p3
= (unsigned char) on_failure_keep_string_jump
;
5919 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5923 /* Default to a safe `on_failure_jump' loop. */
5924 DEBUG_PRINT1 (" smart default => slow loop.\n");
5925 *p3
= (unsigned char) on_failure_jump
;
5927 DEBUG_STATEMENT (debug
-= 2);
5931 /* Unconditionally jump (without popping any failure points). */
5934 IMMEDIATE_QUIT_CHECK
;
5935 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5936 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5937 p
+= mcnt
; /* Do the jump. */
5938 DEBUG_PRINT2 ("(to %p).\n", p
);
5942 /* Have to succeed matching what follows at least n times.
5943 After that, handle like `on_failure_jump'. */
5945 /* Signedness doesn't matter since we only compare MCNT to 0. */
5946 EXTRACT_NUMBER (mcnt
, p
+ 2);
5947 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5949 /* Originally, mcnt is how many times we HAVE to succeed. */
5952 /* Here, we discard `const', making re_match non-reentrant. */
5953 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5956 PUSH_NUMBER (p2
, mcnt
);
5959 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5964 /* Signedness doesn't matter since we only compare MCNT to 0. */
5965 EXTRACT_NUMBER (mcnt
, p
+ 2);
5966 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5968 /* Originally, this is how many times we CAN jump. */
5971 /* Here, we discard `const', making re_match non-reentrant. */
5972 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5974 PUSH_NUMBER (p2
, mcnt
);
5975 goto unconditional_jump
;
5977 /* If don't have to jump any more, skip over the rest of command. */
5984 unsigned char *p2
; /* Location of the counter. */
5985 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5987 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5988 /* Here, we discard `const', making re_match non-reentrant. */
5989 p2
= (unsigned char*) p
+ mcnt
;
5990 /* Signedness doesn't matter since we only copy MCNT's bits . */
5991 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5992 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5993 PUSH_NUMBER (p2
, mcnt
);
6000 boolean
not = (re_opcode_t
) *(p
- 1) == notwordbound
;
6001 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
6003 /* We SUCCEED (or FAIL) in one of the following cases: */
6005 /* Case 1: D is at the beginning or the end of string. */
6006 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
6010 /* C1 is the character before D, S1 is the syntax of C1, C2
6011 is the character at D, and S2 is the syntax of C2. */
6016 int offset
= PTR_TO_OFFSET (d
- 1);
6017 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6018 UPDATE_SYNTAX_TABLE (charpos
);
6020 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6023 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6025 PREFETCH_NOLIMIT ();
6026 GET_CHAR_AFTER (c2
, d
, dummy
);
6029 if (/* Case 2: Only one of S1 and S2 is Sword. */
6030 ((s1
== Sword
) != (s2
== Sword
))
6031 /* Case 3: Both of S1 and S2 are Sword, and macro
6032 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
6033 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
6043 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
6045 /* We FAIL in one of the following cases: */
6047 /* Case 1: D is at the end of string. */
6048 if (AT_STRINGS_END (d
))
6052 /* C1 is the character before D, S1 is the syntax of C1, C2
6053 is the character at D, and S2 is the syntax of C2. */
6058 int offset
= PTR_TO_OFFSET (d
);
6059 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6060 UPDATE_SYNTAX_TABLE (charpos
);
6063 GET_CHAR_AFTER (c2
, d
, dummy
);
6066 /* Case 2: S2 is not Sword. */
6070 /* Case 3: D is not at the beginning of string ... */
6071 if (!AT_STRINGS_BEG (d
))
6073 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6075 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6079 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6081 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6088 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6090 /* We FAIL in one of the following cases: */
6092 /* Case 1: D is at the beginning of string. */
6093 if (AT_STRINGS_BEG (d
))
6097 /* C1 is the character before D, S1 is the syntax of C1, C2
6098 is the character at D, and S2 is the syntax of C2. */
6103 int offset
= PTR_TO_OFFSET (d
) - 1;
6104 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6105 UPDATE_SYNTAX_TABLE (charpos
);
6107 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6110 /* Case 2: S1 is not Sword. */
6114 /* Case 3: D is not at the end of string ... */
6115 if (!AT_STRINGS_END (d
))
6117 PREFETCH_NOLIMIT ();
6118 GET_CHAR_AFTER (c2
, d
, dummy
);
6120 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6124 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6126 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6133 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6135 /* We FAIL in one of the following cases: */
6137 /* Case 1: D is at the end of string. */
6138 if (AT_STRINGS_END (d
))
6142 /* C1 is the character before D, S1 is the syntax of C1, C2
6143 is the character at D, and S2 is the syntax of C2. */
6147 int offset
= PTR_TO_OFFSET (d
);
6148 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6149 UPDATE_SYNTAX_TABLE (charpos
);
6152 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6155 /* Case 2: S2 is neither Sword nor Ssymbol. */
6156 if (s2
!= Sword
&& s2
!= Ssymbol
)
6159 /* Case 3: D is not at the beginning of string ... */
6160 if (!AT_STRINGS_BEG (d
))
6162 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6164 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6168 /* ... and S1 is Sword or Ssymbol. */
6169 if (s1
== Sword
|| s1
== Ssymbol
)
6176 DEBUG_PRINT1 ("EXECUTING symend.\n");
6178 /* We FAIL in one of the following cases: */
6180 /* Case 1: D is at the beginning of string. */
6181 if (AT_STRINGS_BEG (d
))
6185 /* C1 is the character before D, S1 is the syntax of C1, C2
6186 is the character at D, and S2 is the syntax of C2. */
6190 int offset
= PTR_TO_OFFSET (d
) - 1;
6191 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6192 UPDATE_SYNTAX_TABLE (charpos
);
6194 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6197 /* Case 2: S1 is neither Ssymbol nor Sword. */
6198 if (s1
!= Sword
&& s1
!= Ssymbol
)
6201 /* Case 3: D is not at the end of string ... */
6202 if (!AT_STRINGS_END (d
))
6204 PREFETCH_NOLIMIT ();
6205 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6207 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6211 /* ... and S2 is Sword or Ssymbol. */
6212 if (s2
== Sword
|| s2
== Ssymbol
)
6221 boolean
not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6223 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
6227 int offset
= PTR_TO_OFFSET (d
);
6228 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6229 UPDATE_SYNTAX_TABLE (pos1
);
6236 GET_CHAR_AFTER (c
, d
, len
);
6237 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6246 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6247 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6252 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6253 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6258 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6259 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6264 case notcategoryspec
:
6265 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6267 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
6273 GET_CHAR_AFTER (c
, d
, len
);
6274 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6285 continue; /* Successfully executed one pattern command; keep going. */
6288 /* We goto here if a matching operation fails. */
6290 IMMEDIATE_QUIT_CHECK
;
6291 if (!FAIL_STACK_EMPTY ())
6294 /* A restart point is known. Restore to that state. */
6295 DEBUG_PRINT1 ("\nFAIL:\n");
6296 POP_FAILURE_POINT (str
, pat
);
6297 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
6299 case on_failure_keep_string_jump
:
6300 assert (str
== NULL
);
6301 goto continue_failure_jump
;
6303 case on_failure_jump_nastyloop
:
6304 assert ((re_opcode_t
)pat
[-2] == no_op
);
6305 PUSH_FAILURE_POINT (pat
- 2, str
);
6308 case on_failure_jump_loop
:
6309 case on_failure_jump
:
6312 continue_failure_jump
:
6313 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6318 /* A special frame used for nastyloops. */
6325 assert (p
>= bufp
->buffer
&& p
<= pend
);
6327 if (d
>= string1
&& d
<= end1
)
6331 break; /* Matching at this starting point really fails. */
6335 goto restore_best_regs
;
6339 return -1; /* Failure to match. */
6342 /* Subroutine definitions for re_match_2. */
6344 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6345 bytes; nonzero otherwise. */
6348 bcmp_translate (const re_char
*s1
, const re_char
*s2
, register int len
,
6349 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6351 register re_char
*p1
= s1
, *p2
= s2
;
6352 re_char
*p1_end
= s1
+ len
;
6353 re_char
*p2_end
= s2
+ len
;
6355 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6356 different lengths, but relying on a single `len' would break this. -sm */
6357 while (p1
< p1_end
&& p2
< p2_end
)
6359 int p1_charlen
, p2_charlen
;
6360 re_wchar_t p1_ch
, p2_ch
;
6362 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6363 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6365 if (RE_TRANSLATE (translate
, p1_ch
)
6366 != RE_TRANSLATE (translate
, p2_ch
))
6369 p1
+= p1_charlen
, p2
+= p2_charlen
;
6372 if (p1
!= p1_end
|| p2
!= p2_end
)
6378 /* Entry points for GNU code. */
6380 /* re_compile_pattern is the GNU regular expression compiler: it
6381 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6382 Returns 0 if the pattern was valid, otherwise an error string.
6384 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6385 are set in BUFP on entry.
6387 We call regex_compile to do the actual compilation. */
6390 re_compile_pattern (const char *pattern
, size_t length
, struct re_pattern_buffer
*bufp
)
6394 /* GNU code is written to assume at least RE_NREGS registers will be set
6395 (and at least one extra will be -1). */
6396 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6398 /* And GNU code determines whether or not to get register information
6399 by passing null for the REGS argument to re_match, etc., not by
6403 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6407 return gettext (re_error_msgid
[(int) ret
]);
6409 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6411 /* Entry points compatible with 4.2 BSD regex library. We don't define
6412 them unless specifically requested. */
6414 #if defined _REGEX_RE_COMP || defined _LIBC
6416 /* BSD has one and only one pattern buffer. */
6417 static struct re_pattern_buffer re_comp_buf
;
6421 /* Make these definitions weak in libc, so POSIX programs can redefine
6422 these names if they don't use our functions, and still use
6423 regcomp/regexec below without link errors. */
6433 if (!re_comp_buf
.buffer
)
6434 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6435 return (char *) gettext ("No previous regular expression");
6439 if (!re_comp_buf
.buffer
)
6441 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
6442 if (re_comp_buf
.buffer
== NULL
)
6443 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6444 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6445 re_comp_buf
.allocated
= 200;
6447 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6448 if (re_comp_buf
.fastmap
== NULL
)
6449 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6450 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6453 /* Since `re_exec' always passes NULL for the `regs' argument, we
6454 don't need to initialize the pattern buffer fields which affect it. */
6456 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6461 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6462 return (char *) gettext (re_error_msgid
[(int) ret
]);
6473 const int len
= strlen (s
);
6475 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
6477 #endif /* _REGEX_RE_COMP */
6479 /* POSIX.2 functions. Don't define these for Emacs. */
6483 /* regcomp takes a regular expression as a string and compiles it.
6485 PREG is a regex_t *. We do not expect any fields to be initialized,
6486 since POSIX says we shouldn't. Thus, we set
6488 `buffer' to the compiled pattern;
6489 `used' to the length of the compiled pattern;
6490 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6491 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6492 RE_SYNTAX_POSIX_BASIC;
6493 `fastmap' to an allocated space for the fastmap;
6494 `fastmap_accurate' to zero;
6495 `re_nsub' to the number of subexpressions in PATTERN.
6497 PATTERN is the address of the pattern string.
6499 CFLAGS is a series of bits which affect compilation.
6501 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6502 use POSIX basic syntax.
6504 If REG_NEWLINE is set, then . and [^...] don't match newline.
6505 Also, regexec will try a match beginning after every newline.
6507 If REG_ICASE is set, then we considers upper- and lowercase
6508 versions of letters to be equivalent when matching.
6510 If REG_NOSUB is set, then when PREG is passed to regexec, that
6511 routine will report only success or failure, and nothing about the
6514 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6515 the return codes and their meanings.) */
6518 regcomp (regex_t
*__restrict preg
, const char *__restrict pattern
,
6523 = (cflags
& REG_EXTENDED
) ?
6524 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6526 /* regex_compile will allocate the space for the compiled pattern. */
6528 preg
->allocated
= 0;
6531 /* Try to allocate space for the fastmap. */
6532 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6534 if (cflags
& REG_ICASE
)
6539 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6540 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6541 if (preg
->translate
== NULL
)
6542 return (int) REG_ESPACE
;
6544 /* Map uppercase characters to corresponding lowercase ones. */
6545 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6546 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6549 preg
->translate
= NULL
;
6551 /* If REG_NEWLINE is set, newlines are treated differently. */
6552 if (cflags
& REG_NEWLINE
)
6553 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6554 syntax
&= ~RE_DOT_NEWLINE
;
6555 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6558 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6560 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6562 /* POSIX says a null character in the pattern terminates it, so we
6563 can use strlen here in compiling the pattern. */
6564 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6566 /* POSIX doesn't distinguish between an unmatched open-group and an
6567 unmatched close-group: both are REG_EPAREN. */
6568 if (ret
== REG_ERPAREN
)
6571 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6572 { /* Compute the fastmap now, since regexec cannot modify the pattern
6574 re_compile_fastmap (preg
);
6575 if (preg
->can_be_null
)
6576 { /* The fastmap can't be used anyway. */
6577 free (preg
->fastmap
);
6578 preg
->fastmap
= NULL
;
6583 WEAK_ALIAS (__regcomp
, regcomp
)
6586 /* regexec searches for a given pattern, specified by PREG, in the
6589 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6590 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6591 least NMATCH elements, and we set them to the offsets of the
6592 corresponding matched substrings.
6594 EFLAGS specifies `execution flags' which affect matching: if
6595 REG_NOTBOL is set, then ^ does not match at the beginning of the
6596 string; if REG_NOTEOL is set, then $ does not match at the end.
6598 We return 0 if we find a match and REG_NOMATCH if not. */
6601 regexec (const regex_t
*__restrict preg
, const char *__restrict string
,
6602 size_t nmatch
, regmatch_t pmatch
[__restrict_arr
], int eflags
)
6605 struct re_registers regs
;
6606 regex_t private_preg
;
6607 int len
= strlen (string
);
6608 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6610 private_preg
= *preg
;
6612 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6613 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6615 /* The user has told us exactly how many registers to return
6616 information about, via `nmatch'. We have to pass that on to the
6617 matching routines. */
6618 private_preg
.regs_allocated
= REGS_FIXED
;
6622 regs
.num_regs
= nmatch
;
6623 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6624 if (regs
.start
== NULL
)
6625 return (int) REG_NOMATCH
;
6626 regs
.end
= regs
.start
+ nmatch
;
6629 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6630 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6631 was a little bit longer but still only matching the real part.
6632 This works because the `endline' will check for a '\n' and will find a
6633 '\0', correctly deciding that this is not the end of a line.
6634 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6635 a convenient '\0' there. For all we know, the string could be preceded
6636 by '\n' which would throw things off. */
6638 /* Perform the searching operation. */
6639 ret
= re_search (&private_preg
, string
, len
,
6640 /* start: */ 0, /* range: */ len
,
6641 want_reg_info
? ®s
: (struct re_registers
*) 0);
6643 /* Copy the register information to the POSIX structure. */
6650 for (r
= 0; r
< nmatch
; r
++)
6652 pmatch
[r
].rm_so
= regs
.start
[r
];
6653 pmatch
[r
].rm_eo
= regs
.end
[r
];
6657 /* If we needed the temporary register info, free the space now. */
6661 /* We want zero return to mean success, unlike `re_search'. */
6662 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
6664 WEAK_ALIAS (__regexec
, regexec
)
6667 /* Returns a message corresponding to an error code, ERR_CODE, returned
6668 from either regcomp or regexec. We don't use PREG here.
6670 ERR_CODE was previously called ERRCODE, but that name causes an
6671 error with msvc8 compiler. */
6674 regerror (int err_code
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
6680 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6681 /* Only error codes returned by the rest of the code should be passed
6682 to this routine. If we are given anything else, or if other regex
6683 code generates an invalid error code, then the program has a bug.
6684 Dump core so we can fix it. */
6687 msg
= gettext (re_error_msgid
[err_code
]);
6689 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6691 if (errbuf_size
!= 0)
6693 if (msg_size
> errbuf_size
)
6695 strncpy (errbuf
, msg
, errbuf_size
- 1);
6696 errbuf
[errbuf_size
- 1] = 0;
6699 strcpy (errbuf
, msg
);
6704 WEAK_ALIAS (__regerror
, regerror
)
6707 /* Free dynamically allocated space used by PREG. */
6710 regfree (regex_t
*preg
)
6712 free (preg
->buffer
);
6713 preg
->buffer
= NULL
;
6715 preg
->allocated
= 0;
6718 free (preg
->fastmap
);
6719 preg
->fastmap
= NULL
;
6720 preg
->fastmap_accurate
= 0;
6722 free (preg
->translate
);
6723 preg
->translate
= NULL
;
6725 WEAK_ALIAS (__regfree
, regfree
)
6727 #endif /* not emacs */