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-2013 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, see <http://www.gnu.org/licenses/>. */
21 - structure the opcode space into opcode+flag.
22 - merge with glibc's regex.[ch].
23 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
24 need to modify the compiled regexp so that re_match can be reentrant.
25 - get rid of on_failure_jump_smart by doing the optimization in re_comp
26 rather than at run-time, so that re_match can be reentrant.
29 /* AIX requires this to be the first thing in the file. */
30 #if defined _AIX && !defined REGEX_MALLOC
34 /* Ignore some GCC warnings for now. This section should go away
35 once the Emacs and Gnulib regex code is merged. */
36 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__) || defined __clang__
37 # pragma GCC diagnostic ignored "-Wstrict-overflow"
39 # pragma GCC diagnostic ignored "-Wunused-function"
40 # pragma GCC diagnostic ignored "-Wunused-macros"
41 # pragma GCC diagnostic ignored "-Wunused-result"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
46 #if 4 < __GNUC__ + (6 <= __GNUC_MINOR__) && ! defined __clang__
47 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
55 /* We need this for `regex.h', and perhaps for the Emacs include files. */
56 # include <sys/types.h>
59 /* Whether to use ISO C Amendment 1 wide char functions.
60 Those should not be used for Emacs since it uses its own. */
62 #define WIDE_CHAR_SUPPORT 1
64 #define WIDE_CHAR_SUPPORT \
65 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
68 /* For platform which support the ISO C amendment 1 functionality we
69 support user defined character classes. */
71 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
77 /* We have to keep the namespace clean. */
78 # define regfree(preg) __regfree (preg)
79 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
80 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
81 # define regerror(err_code, preg, errbuf, errbuf_size) \
82 __regerror (err_code, preg, errbuf, errbuf_size)
83 # define re_set_registers(bu, re, nu, st, en) \
84 __re_set_registers (bu, re, nu, st, en)
85 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
86 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
87 # define re_match(bufp, string, size, pos, regs) \
88 __re_match (bufp, string, size, pos, regs)
89 # define re_search(bufp, string, size, startpos, range, regs) \
90 __re_search (bufp, string, size, startpos, range, regs)
91 # define re_compile_pattern(pattern, length, bufp) \
92 __re_compile_pattern (pattern, length, bufp)
93 # define re_set_syntax(syntax) __re_set_syntax (syntax)
94 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
95 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
96 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
98 /* Make sure we call libc's function even if the user overrides them. */
99 # define btowc __btowc
100 # define iswctype __iswctype
101 # define wctype __wctype
103 # define WEAK_ALIAS(a,b) weak_alias (a, b)
105 /* We are also using some library internals. */
106 # include <locale/localeinfo.h>
107 # include <locale/elem-hash.h>
108 # include <langinfo.h>
110 # define WEAK_ALIAS(a,b)
113 /* This is for other GNU distributions with internationalized messages. */
114 #if HAVE_LIBINTL_H || defined _LIBC
115 # include <libintl.h>
117 # define gettext(msgid) (msgid)
121 /* This define is so xgettext can find the internationalizable
123 # define gettext_noop(String) String
126 /* The `emacs' switch turns on certain matching commands
127 that make sense only in Emacs. */
131 # include "character.h"
135 # include "category.h"
137 /* Make syntax table lookup grant data in gl_state. */
138 # define SYNTAX(c) syntax_property (c, 1)
143 # define malloc xmalloc
147 # define realloc xrealloc
153 /* Converts the pointer to the char to BEG-based offset from the start. */
154 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
155 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
157 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
158 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
159 # define RE_STRING_CHAR(p, multibyte) \
160 (multibyte ? (STRING_CHAR (p)) : (*(p)))
161 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
162 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
164 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
166 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
168 /* Set C a (possibly converted to multibyte) character before P. P
169 points into a string which is the virtual concatenation of STR1
170 (which ends at END1) or STR2 (which ends at END2). */
171 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
173 if (target_multibyte) \
175 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
176 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
177 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
178 c = STRING_CHAR (dtemp); \
182 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
183 (c) = RE_CHAR_TO_MULTIBYTE (c); \
187 /* Set C a (possibly converted to multibyte) character at P, and set
188 LEN to the byte length of that character. */
189 # define GET_CHAR_AFTER(c, p, len) \
191 if (target_multibyte) \
192 (c) = STRING_CHAR_AND_LENGTH (p, len); \
197 (c) = RE_CHAR_TO_MULTIBYTE (c); \
201 #else /* not emacs */
203 /* If we are not linking with Emacs proper,
204 we can't use the relocating allocator
205 even if config.h says that we can. */
210 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
213 xmalloc (size_t size
)
215 void *val
= malloc (size
);
218 write (2, "virtual memory exhausted\n", 25);
225 xrealloc (void *block
, size_t size
)
228 /* We must call malloc explicitly when BLOCK is 0, since some
229 reallocs don't do this. */
233 val
= realloc (block
, size
);
236 write (2, "virtual memory exhausted\n", 25);
245 # define malloc xmalloc
249 # define realloc xrealloc
251 # include <stdbool.h>
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 /* Dummy macros for non-Emacs environments. */
260 # define MAX_MULTIBYTE_LENGTH 1
261 # define RE_MULTIBYTE_P(x) 0
262 # define RE_TARGET_MULTIBYTE_P(x) 0
263 # define WORD_BOUNDARY_P(c1, c2) (0)
264 # define BYTES_BY_CHAR_HEAD(p) (1)
265 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
266 # define STRING_CHAR(p) (*(p))
267 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
268 # define CHAR_STRING(c, s) (*(s) = (c), 1)
269 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
270 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
271 # define RE_CHAR_TO_MULTIBYTE(c) (c)
272 # define RE_CHAR_TO_UNIBYTE(c) (c)
273 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
274 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
275 # define GET_CHAR_AFTER(c, p, len) \
277 # define CHAR_BYTE8_P(c) (0)
278 # define CHAR_LEADING_CODE(c) (c)
280 #endif /* not emacs */
283 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
284 # define RE_TRANSLATE_P(TBL) (TBL)
287 /* Get the interface, including the syntax bits. */
290 /* isalpha etc. are used for the character classes. */
295 /* 1 if C is an ASCII character. */
296 # define IS_REAL_ASCII(c) ((c) < 0200)
298 /* 1 if C is a unibyte character. */
299 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
301 /* The Emacs definitions should not be directly affected by locales. */
303 /* In Emacs, these are only used for single-byte characters. */
304 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
305 # define ISCNTRL(c) ((c) < ' ')
306 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
307 || ((c) >= 'a' && (c) <= 'f') \
308 || ((c) >= 'A' && (c) <= 'F'))
310 /* This is only used for single-byte characters. */
311 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
313 /* The rest must handle multibyte characters. */
315 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
316 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
319 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
320 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
323 # define ISALNUM(c) (IS_REAL_ASCII (c) \
324 ? (((c) >= 'a' && (c) <= 'z') \
325 || ((c) >= 'A' && (c) <= 'Z') \
326 || ((c) >= '0' && (c) <= '9')) \
327 : SYNTAX (c) == Sword)
329 # define ISALPHA(c) (IS_REAL_ASCII (c) \
330 ? (((c) >= 'a' && (c) <= 'z') \
331 || ((c) >= 'A' && (c) <= 'Z')) \
332 : SYNTAX (c) == Sword)
334 # define ISLOWER(c) lowercasep (c)
336 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
337 ? ((c) > ' ' && (c) < 0177 \
338 && !(((c) >= 'a' && (c) <= 'z') \
339 || ((c) >= 'A' && (c) <= 'Z') \
340 || ((c) >= '0' && (c) <= '9'))) \
341 : SYNTAX (c) != Sword)
343 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
345 # define ISUPPER(c) uppercasep (c)
347 # define ISWORD(c) (SYNTAX (c) == Sword)
349 #else /* not emacs */
351 /* 1 if C is an ASCII character. */
352 # define IS_REAL_ASCII(c) ((c) < 0200)
354 /* This distinction is not meaningful, except in Emacs. */
355 # define ISUNIBYTE(c) 1
358 # define ISBLANK(c) isblank (c)
360 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
363 # define ISGRAPH(c) isgraph (c)
365 # define ISGRAPH(c) (isprint (c) && !isspace (c))
368 /* Solaris defines ISPRINT so we must undefine it first. */
370 # define ISPRINT(c) isprint (c)
371 # define ISDIGIT(c) isdigit (c)
372 # define ISALNUM(c) isalnum (c)
373 # define ISALPHA(c) isalpha (c)
374 # define ISCNTRL(c) iscntrl (c)
375 # define ISLOWER(c) islower (c)
376 # define ISPUNCT(c) ispunct (c)
377 # define ISSPACE(c) isspace (c)
378 # define ISUPPER(c) isupper (c)
379 # define ISXDIGIT(c) isxdigit (c)
381 # define ISWORD(c) ISALPHA (c)
384 # define TOLOWER(c) _tolower (c)
386 # define TOLOWER(c) tolower (c)
389 /* How many characters in the character set. */
390 # define CHAR_SET_SIZE 256
394 extern char *re_syntax_table
;
396 # else /* not SYNTAX_TABLE */
398 static char re_syntax_table
[CHAR_SET_SIZE
];
401 init_syntax_once (void)
409 memset (re_syntax_table
, 0, sizeof re_syntax_table
);
411 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
413 re_syntax_table
[c
] = Sword
;
415 re_syntax_table
['_'] = Ssymbol
;
420 # endif /* not SYNTAX_TABLE */
422 # define SYNTAX(c) re_syntax_table[(c)]
424 #endif /* not emacs */
426 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
428 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
429 use `alloca' instead of `malloc'. This is because using malloc in
430 re_search* or re_match* could cause memory leaks when C-g is used in
431 Emacs; also, malloc is slower and causes storage fragmentation. On
432 the other hand, malloc is more portable, and easier to debug.
434 Because we sometimes use alloca, some routines have to be macros,
435 not functions -- `alloca'-allocated space disappears at the end of the
436 function it is called in. */
440 # define REGEX_ALLOCATE malloc
441 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
442 # define REGEX_FREE free
444 #else /* not REGEX_MALLOC */
446 /* Emacs already defines alloca, sometimes. */
449 /* Make alloca work the best possible way. */
451 # define alloca __builtin_alloca
452 # else /* not __GNUC__ */
453 # ifdef HAVE_ALLOCA_H
455 # endif /* HAVE_ALLOCA_H */
456 # endif /* not __GNUC__ */
458 # endif /* not alloca */
460 # define REGEX_ALLOCATE alloca
462 /* Assumes a `char *destination' variable. */
463 # define REGEX_REALLOCATE(source, osize, nsize) \
464 (destination = alloca (nsize), \
465 memcpy (destination, source, osize))
467 /* No need to do anything to free, after alloca. */
468 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
470 #endif /* not REGEX_MALLOC */
472 /* Define how to allocate the failure stack. */
474 #if defined REL_ALLOC && defined REGEX_MALLOC
476 # define REGEX_ALLOCATE_STACK(size) \
477 r_alloc (&failure_stack_ptr, (size))
478 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
479 r_re_alloc (&failure_stack_ptr, (nsize))
480 # define REGEX_FREE_STACK(ptr) \
481 r_alloc_free (&failure_stack_ptr)
483 #else /* not using relocating allocator */
487 # define REGEX_ALLOCATE_STACK malloc
488 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
489 # define REGEX_FREE_STACK free
491 # else /* not REGEX_MALLOC */
493 # define REGEX_ALLOCATE_STACK alloca
495 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
496 REGEX_REALLOCATE (source, osize, nsize)
497 /* No need to explicitly free anything. */
498 # define REGEX_FREE_STACK(arg) ((void)0)
500 # endif /* not REGEX_MALLOC */
501 #endif /* not using relocating allocator */
504 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
505 `string1' or just past its end. This works if PTR is NULL, which is
507 #define FIRST_STRING_P(ptr) \
508 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
510 /* (Re)Allocate N items of type T using malloc, or fail. */
511 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
512 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
513 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
515 #define BYTEWIDTH 8 /* In bits. */
517 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
521 #define MAX(a, b) ((a) > (b) ? (a) : (b))
522 #define MIN(a, b) ((a) < (b) ? (a) : (b))
524 /* Type of source-pattern and string chars. */
526 typedef unsigned char re_char
;
527 typedef const re_char const_re_char
;
529 typedef const unsigned char re_char
;
530 typedef re_char const_re_char
;
533 typedef char boolean
;
535 static regoff_t
re_match_2_internal (struct re_pattern_buffer
*bufp
,
536 re_char
*string1
, size_t size1
,
537 re_char
*string2
, size_t size2
,
539 struct re_registers
*regs
,
542 /* These are the command codes that appear in compiled regular
543 expressions. Some opcodes are followed by argument bytes. A
544 command code can specify any interpretation whatsoever for its
545 arguments. Zero bytes may appear in the compiled regular expression. */
551 /* Succeed right away--no more backtracking. */
554 /* Followed by one byte giving n, then by n literal bytes. */
557 /* Matches any (more or less) character. */
560 /* Matches any one char belonging to specified set. First
561 following byte is number of bitmap bytes. Then come bytes
562 for a bitmap saying which chars are in. Bits in each byte
563 are ordered low-bit-first. A character is in the set if its
564 bit is 1. A character too large to have a bit in the map is
565 automatically not in the set.
567 If the length byte has the 0x80 bit set, then that stuff
568 is followed by a range table:
569 2 bytes of flags for character sets (low 8 bits, high 8 bits)
570 See RANGE_TABLE_WORK_BITS below.
571 2 bytes, the number of pairs that follow (upto 32767)
572 pairs, each 2 multibyte characters,
573 each multibyte character represented as 3 bytes. */
576 /* Same parameters as charset, but match any character that is
577 not one of those specified. */
580 /* Start remembering the text that is matched, for storing in a
581 register. Followed by one byte with the register number, in
582 the range 0 to one less than the pattern buffer's re_nsub
586 /* Stop remembering the text that is matched and store it in a
587 memory register. Followed by one byte with the register
588 number, in the range 0 to one less than `re_nsub' in the
592 /* Match a duplicate of something remembered. Followed by one
593 byte containing the register number. */
596 /* Fail unless at beginning of line. */
599 /* Fail unless at end of line. */
602 /* Succeeds if at beginning of buffer (if emacs) or at beginning
603 of string to be matched (if not). */
606 /* Analogously, for end of buffer/string. */
609 /* Followed by two byte relative address to which to jump. */
612 /* Followed by two-byte relative address of place to resume at
613 in case of failure. */
616 /* Like on_failure_jump, but pushes a placeholder instead of the
617 current string position when executed. */
618 on_failure_keep_string_jump
,
620 /* Just like `on_failure_jump', except that it checks that we
621 don't get stuck in an infinite loop (matching an empty string
623 on_failure_jump_loop
,
625 /* Just like `on_failure_jump_loop', except that it checks for
626 a different kind of loop (the kind that shows up with non-greedy
627 operators). This operation has to be immediately preceded
629 on_failure_jump_nastyloop
,
631 /* A smart `on_failure_jump' used for greedy * and + operators.
632 It analyzes the loop before which it is put and if the
633 loop does not require backtracking, it changes itself to
634 `on_failure_keep_string_jump' and short-circuits the loop,
635 else it just defaults to changing itself into `on_failure_jump'.
636 It assumes that it is pointing to just past a `jump'. */
637 on_failure_jump_smart
,
639 /* Followed by two-byte relative address and two-byte number n.
640 After matching N times, jump to the address upon failure.
641 Does not work if N starts at 0: use on_failure_jump_loop
645 /* Followed by two-byte relative address, and two-byte number n.
646 Jump to the address N times, then fail. */
649 /* Set the following two-byte relative address to the
650 subsequent two-byte number. The address *includes* the two
654 wordbeg
, /* Succeeds if at word beginning. */
655 wordend
, /* Succeeds if at word end. */
657 wordbound
, /* Succeeds if at a word boundary. */
658 notwordbound
, /* Succeeds if not at a word boundary. */
660 symbeg
, /* Succeeds if at symbol beginning. */
661 symend
, /* Succeeds if at symbol end. */
663 /* Matches any character whose syntax is specified. Followed by
664 a byte which contains a syntax code, e.g., Sword. */
667 /* Matches any character whose syntax is not that specified. */
671 ,before_dot
, /* Succeeds if before point. */
672 at_dot
, /* Succeeds if at point. */
673 after_dot
, /* Succeeds if after point. */
675 /* Matches any character whose category-set contains the specified
676 category. The operator is followed by a byte which contains a
677 category code (mnemonic ASCII character). */
680 /* Matches any character whose category-set does not contain the
681 specified category. The operator is followed by a byte which
682 contains the category code (mnemonic ASCII character). */
687 /* Common operations on the compiled pattern. */
689 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
691 #define STORE_NUMBER(destination, number) \
693 (destination)[0] = (number) & 0377; \
694 (destination)[1] = (number) >> 8; \
697 /* Same as STORE_NUMBER, except increment DESTINATION to
698 the byte after where the number is stored. Therefore, DESTINATION
699 must be an lvalue. */
701 #define STORE_NUMBER_AND_INCR(destination, number) \
703 STORE_NUMBER (destination, number); \
704 (destination) += 2; \
707 /* Put into DESTINATION a number stored in two contiguous bytes starting
710 #define EXTRACT_NUMBER(destination, source) \
711 ((destination) = extract_number (source))
714 extract_number (re_char
*source
)
716 return (SIGN_EXTEND_CHAR (source
[1]) << 8) + source
[0];
719 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
720 SOURCE must be an lvalue. */
722 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
723 ((destination) = extract_number_and_incr (&source))
726 extract_number_and_incr (re_char
**source
)
728 int num
= extract_number (*source
);
733 /* Store a multibyte character in three contiguous bytes starting
734 DESTINATION, and increment DESTINATION to the byte after where the
735 character is stored. Therefore, DESTINATION must be an lvalue. */
737 #define STORE_CHARACTER_AND_INCR(destination, character) \
739 (destination)[0] = (character) & 0377; \
740 (destination)[1] = ((character) >> 8) & 0377; \
741 (destination)[2] = (character) >> 16; \
742 (destination) += 3; \
745 /* Put into DESTINATION a character stored in three contiguous bytes
746 starting at SOURCE. */
748 #define EXTRACT_CHARACTER(destination, source) \
750 (destination) = ((source)[0] \
751 | ((source)[1] << 8) \
752 | ((source)[2] << 16)); \
756 /* Macros for charset. */
758 /* Size of bitmap of charset P in bytes. P is a start of charset,
759 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
760 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
762 /* Nonzero if charset P has range table. */
763 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
765 /* Return the address of range table of charset P. But not the start
766 of table itself, but the before where the number of ranges is
767 stored. `2 +' means to skip re_opcode_t and size of bitmap,
768 and the 2 bytes of flags at the start of the range table. */
769 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
772 /* Extract the bit flags that start a range table. */
773 #define CHARSET_RANGE_TABLE_BITS(p) \
774 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
775 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
778 /* Return the address of end of RANGE_TABLE. COUNT is number of
779 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
780 is start of range and end of range. `* 3' is size of each start
782 #define CHARSET_RANGE_TABLE_END(range_table, count) \
783 ((range_table) + (count) * 2 * 3)
785 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
786 COUNT is number of ranges in RANGE_TABLE. */
787 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
790 re_wchar_t range_start, range_end; \
792 re_char *range_table_end \
793 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
795 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
797 EXTRACT_CHARACTER (range_start, rtp); \
798 EXTRACT_CHARACTER (range_end, rtp + 3); \
800 if (range_start <= (c) && (c) <= range_end) \
809 /* Test if C is in range table of CHARSET. The flag NOT is negated if
810 C is listed in it. */
811 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
814 /* Number of ranges in range table. */ \
816 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
818 EXTRACT_NUMBER_AND_INCR (count, range_table); \
819 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
823 /* If DEBUG is defined, Regex prints many voluminous messages about what
824 it is doing (if the variable `debug' is nonzero). If linked with the
825 main program in `iregex.c', you can enter patterns and strings
826 interactively. And if linked with the main program in `main.c' and
827 the other test files, you can run the already-written tests. */
831 /* We use standard I/O for debugging. */
834 /* It is useful to test things that ``must'' be true when debugging. */
837 static int debug
= -100000;
839 # define DEBUG_STATEMENT(e) e
840 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
841 # define DEBUG_COMPILES_ARGUMENTS
842 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
843 if (debug > 0) print_partial_compiled_pattern (s, e)
844 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
845 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
848 /* Print the fastmap in human-readable form. */
851 print_fastmap (char *fastmap
)
853 unsigned was_a_range
= 0;
856 while (i
< (1 << BYTEWIDTH
))
862 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
878 /* Print a compiled pattern string in human-readable form, starting at
879 the START pointer into it and ending just before the pointer END. */
882 print_partial_compiled_pattern (re_char
*start
, re_char
*end
)
890 fprintf (stderr
, "(null)\n");
894 /* Loop over pattern commands. */
897 fprintf (stderr
, "%td:\t", p
- start
);
899 switch ((re_opcode_t
) *p
++)
902 fprintf (stderr
, "/no_op");
906 fprintf (stderr
, "/succeed");
911 fprintf (stderr
, "/exactn/%d", mcnt
);
914 fprintf (stderr
, "/%c", *p
++);
920 fprintf (stderr
, "/start_memory/%d", *p
++);
924 fprintf (stderr
, "/stop_memory/%d", *p
++);
928 fprintf (stderr
, "/duplicate/%d", *p
++);
932 fprintf (stderr
, "/anychar");
938 register int c
, last
= -100;
939 register int in_range
= 0;
940 int length
= CHARSET_BITMAP_SIZE (p
- 1);
941 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
943 fprintf (stderr
, "/charset [%s",
944 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
947 fprintf (stderr
, " !extends past end of pattern! ");
949 for (c
= 0; c
< 256; c
++)
951 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
953 /* Are we starting a range? */
954 if (last
+ 1 == c
&& ! in_range
)
956 fprintf (stderr
, "-");
959 /* Have we broken a range? */
960 else if (last
+ 1 != c
&& in_range
)
962 fprintf (stderr
, "%c", last
);
967 fprintf (stderr
, "%c", c
);
973 fprintf (stderr
, "%c", last
);
975 fprintf (stderr
, "]");
982 fprintf (stderr
, "has-range-table");
984 /* ??? Should print the range table; for now, just skip it. */
985 p
+= 2; /* skip range table bits */
986 EXTRACT_NUMBER_AND_INCR (count
, p
);
987 p
= CHARSET_RANGE_TABLE_END (p
, count
);
993 fprintf (stderr
, "/begline");
997 fprintf (stderr
, "/endline");
1000 case on_failure_jump
:
1001 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1002 fprintf (stderr
, "/on_failure_jump to %td", p
+ mcnt
- start
);
1005 case on_failure_keep_string_jump
:
1006 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1007 fprintf (stderr
, "/on_failure_keep_string_jump to %td",
1011 case on_failure_jump_nastyloop
:
1012 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1013 fprintf (stderr
, "/on_failure_jump_nastyloop to %td",
1017 case on_failure_jump_loop
:
1018 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1019 fprintf (stderr
, "/on_failure_jump_loop to %td",
1023 case on_failure_jump_smart
:
1024 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1025 fprintf (stderr
, "/on_failure_jump_smart to %td",
1030 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1031 fprintf (stderr
, "/jump to %td", p
+ mcnt
- start
);
1035 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1036 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
1037 fprintf (stderr
, "/succeed_n to %td, %d times",
1038 p
- 2 + mcnt
- start
, mcnt2
);
1042 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1043 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
1044 fprintf (stderr
, "/jump_n to %td, %d times",
1045 p
- 2 + mcnt
- start
, mcnt2
);
1049 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1050 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
1051 fprintf (stderr
, "/set_number_at location %td to %d",
1052 p
- 2 + mcnt
- start
, mcnt2
);
1056 fprintf (stderr
, "/wordbound");
1060 fprintf (stderr
, "/notwordbound");
1064 fprintf (stderr
, "/wordbeg");
1068 fprintf (stderr
, "/wordend");
1072 fprintf (stderr
, "/symbeg");
1076 fprintf (stderr
, "/symend");
1080 fprintf (stderr
, "/syntaxspec");
1082 fprintf (stderr
, "/%d", mcnt
);
1086 fprintf (stderr
, "/notsyntaxspec");
1088 fprintf (stderr
, "/%d", mcnt
);
1093 fprintf (stderr
, "/before_dot");
1097 fprintf (stderr
, "/at_dot");
1101 fprintf (stderr
, "/after_dot");
1105 fprintf (stderr
, "/categoryspec");
1107 fprintf (stderr
, "/%d", mcnt
);
1110 case notcategoryspec
:
1111 fprintf (stderr
, "/notcategoryspec");
1113 fprintf (stderr
, "/%d", mcnt
);
1118 fprintf (stderr
, "/begbuf");
1122 fprintf (stderr
, "/endbuf");
1126 fprintf (stderr
, "?%d", *(p
-1));
1129 fprintf (stderr
, "\n");
1132 fprintf (stderr
, "%td:\tend of pattern.\n", p
- start
);
1137 print_compiled_pattern (struct re_pattern_buffer
*bufp
)
1139 re_char
*buffer
= bufp
->buffer
;
1141 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1142 printf ("%ld bytes used/%ld bytes allocated.\n",
1143 bufp
->used
, bufp
->allocated
);
1145 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1147 printf ("fastmap: ");
1148 print_fastmap (bufp
->fastmap
);
1151 printf ("re_nsub: %zu\t", bufp
->re_nsub
);
1152 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1153 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1154 printf ("no_sub: %d\t", bufp
->no_sub
);
1155 printf ("not_bol: %d\t", bufp
->not_bol
);
1156 printf ("not_eol: %d\t", bufp
->not_eol
);
1157 printf ("syntax: %lx\n", bufp
->syntax
);
1159 /* Perhaps we should print the translate table? */
1164 print_double_string (re_char
*where
, re_char
*string1
, ssize_t size1
,
1165 re_char
*string2
, ssize_t size2
)
1173 if (FIRST_STRING_P (where
))
1175 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1176 putchar (string1
[this_char
]);
1181 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1182 putchar (string2
[this_char
]);
1186 #else /* not DEBUG */
1191 # define DEBUG_STATEMENT(e)
1192 # if __STDC_VERSION__ < 199901L
1193 # define DEBUG_COMPILES_ARGUMENTS
1194 # define DEBUG_PRINT /* 'DEBUG_PRINT (x, y)' discards X and Y. */ (void)
1196 # define DEBUG_PRINT(...)
1198 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1199 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1201 #endif /* not DEBUG */
1203 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1205 # define IF_LINT(Code) Code
1207 # define IF_LINT(Code) /* empty */
1210 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1211 also be assigned to arbitrarily: each pattern buffer stores its own
1212 syntax, so it can be changed between regex compilations. */
1213 /* This has no initializer because initialized variables in Emacs
1214 become read-only after dumping. */
1215 reg_syntax_t re_syntax_options
;
1218 /* Specify the precise syntax of regexps for compilation. This provides
1219 for compatibility for various utilities which historically have
1220 different, incompatible syntaxes.
1222 The argument SYNTAX is a bit mask comprised of the various bits
1223 defined in regex.h. We return the old syntax. */
1226 re_set_syntax (reg_syntax_t syntax
)
1228 reg_syntax_t ret
= re_syntax_options
;
1230 re_syntax_options
= syntax
;
1233 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1235 /* Regexp to use to replace spaces, or NULL meaning don't. */
1236 static const_re_char
*whitespace_regexp
;
1239 re_set_whitespace_regexp (const char *regexp
)
1241 whitespace_regexp
= (const_re_char
*) regexp
;
1243 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1245 /* This table gives an error message for each of the error codes listed
1246 in regex.h. Obviously the order here has to be same as there.
1247 POSIX doesn't require that we do anything for REG_NOERROR,
1248 but why not be nice? */
1250 static const char *re_error_msgid
[] =
1252 gettext_noop ("Success"), /* REG_NOERROR */
1253 gettext_noop ("No match"), /* REG_NOMATCH */
1254 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1255 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1256 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1257 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1258 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1259 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1260 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1261 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1262 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1263 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1264 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1265 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1266 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1267 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1268 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1269 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1272 /* Avoiding alloca during matching, to placate r_alloc. */
1274 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1275 searching and matching functions should not call alloca. On some
1276 systems, alloca is implemented in terms of malloc, and if we're
1277 using the relocating allocator routines, then malloc could cause a
1278 relocation, which might (if the strings being searched are in the
1279 ralloc heap) shift the data out from underneath the regexp
1282 Here's another reason to avoid allocation: Emacs
1283 processes input from X in a signal handler; processing X input may
1284 call malloc; if input arrives while a matching routine is calling
1285 malloc, then we're scrod. But Emacs can't just block input while
1286 calling matching routines; then we don't notice interrupts when
1287 they come in. So, Emacs blocks input around all regexp calls
1288 except the matching calls, which it leaves unprotected, in the
1289 faith that they will not malloc. */
1291 /* Normally, this is fine. */
1292 #define MATCH_MAY_ALLOCATE
1294 /* The match routines may not allocate if (1) they would do it with malloc
1295 and (2) it's not safe for them to use malloc.
1296 Note that if REL_ALLOC is defined, matching would not use malloc for the
1297 failure stack, but we would still use it for the register vectors;
1298 so REL_ALLOC should not affect this. */
1299 #if defined REGEX_MALLOC && defined emacs
1300 # undef MATCH_MAY_ALLOCATE
1304 /* Failure stack declarations and macros; both re_compile_fastmap and
1305 re_match_2 use a failure stack. These have to be macros because of
1306 REGEX_ALLOCATE_STACK. */
1309 /* Approximate number of failure points for which to initially allocate space
1310 when matching. If this number is exceeded, we allocate more
1311 space, so it is not a hard limit. */
1312 #ifndef INIT_FAILURE_ALLOC
1313 # define INIT_FAILURE_ALLOC 20
1316 /* Roughly the maximum number of failure points on the stack. Would be
1317 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1318 This is a variable only so users of regex can assign to it; we never
1319 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1320 before using it, so it should probably be a byte-count instead. */
1321 # if defined MATCH_MAY_ALLOCATE
1322 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1323 whose default stack limit is 2mb. In order for a larger
1324 value to work reliably, you have to try to make it accord
1325 with the process stack limit. */
1326 size_t re_max_failures
= 40000;
1328 size_t re_max_failures
= 4000;
1331 union fail_stack_elt
1334 /* This should be the biggest `int' that's no bigger than a pointer. */
1338 typedef union fail_stack_elt fail_stack_elt_t
;
1342 fail_stack_elt_t
*stack
;
1344 size_t avail
; /* Offset of next open position. */
1345 size_t frame
; /* Offset of the cur constructed frame. */
1348 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1351 /* Define macros to initialize and free the failure stack.
1352 Do `return -2' if the alloc fails. */
1354 #ifdef MATCH_MAY_ALLOCATE
1355 # define INIT_FAIL_STACK() \
1357 fail_stack.stack = \
1358 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1359 * sizeof (fail_stack_elt_t)); \
1361 if (fail_stack.stack == NULL) \
1364 fail_stack.size = INIT_FAILURE_ALLOC; \
1365 fail_stack.avail = 0; \
1366 fail_stack.frame = 0; \
1369 # define INIT_FAIL_STACK() \
1371 fail_stack.avail = 0; \
1372 fail_stack.frame = 0; \
1375 # define RETALLOC_IF(addr, n, t) \
1376 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1380 /* Double the size of FAIL_STACK, up to a limit
1381 which allows approximately `re_max_failures' items.
1383 Return 1 if succeeds, and 0 if either ran out of memory
1384 allocating space for it or it was already too large.
1386 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1388 /* Factor to increase the failure stack size by
1389 when we increase it.
1390 This used to be 2, but 2 was too wasteful
1391 because the old discarded stacks added up to as much space
1392 were as ultimate, maximum-size stack. */
1393 #define FAIL_STACK_GROWTH_FACTOR 4
1395 #define GROW_FAIL_STACK(fail_stack) \
1396 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1397 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1399 : ((fail_stack).stack \
1400 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1401 (fail_stack).size * sizeof (fail_stack_elt_t), \
1402 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1403 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1404 * FAIL_STACK_GROWTH_FACTOR))), \
1406 (fail_stack).stack == NULL \
1408 : ((fail_stack).size \
1409 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1410 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1411 * FAIL_STACK_GROWTH_FACTOR)) \
1412 / sizeof (fail_stack_elt_t)), \
1416 /* Push a pointer value onto the failure stack.
1417 Assumes the variable `fail_stack'. Probably should only
1418 be called from within `PUSH_FAILURE_POINT'. */
1419 #define PUSH_FAILURE_POINTER(item) \
1420 fail_stack.stack[fail_stack.avail++].pointer = (item)
1422 /* This pushes an integer-valued item onto the failure stack.
1423 Assumes the variable `fail_stack'. Probably should only
1424 be called from within `PUSH_FAILURE_POINT'. */
1425 #define PUSH_FAILURE_INT(item) \
1426 fail_stack.stack[fail_stack.avail++].integer = (item)
1428 /* These POP... operations complement the PUSH... operations.
1429 All assume that `fail_stack' is nonempty. */
1430 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1431 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1433 /* Individual items aside from the registers. */
1434 #define NUM_NONREG_ITEMS 3
1436 /* Used to examine the stack (to detect infinite loops). */
1437 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1438 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1439 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1440 #define TOP_FAILURE_HANDLE() fail_stack.frame
1443 #define ENSURE_FAIL_STACK(space) \
1444 while (REMAINING_AVAIL_SLOTS <= space) { \
1445 if (!GROW_FAIL_STACK (fail_stack)) \
1447 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1448 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1451 /* Push register NUM onto the stack. */
1452 #define PUSH_FAILURE_REG(num) \
1454 char *destination; \
1456 ENSURE_FAIL_STACK(3); \
1457 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1458 n, regstart[n], regend[n]); \
1459 PUSH_FAILURE_POINTER (regstart[n]); \
1460 PUSH_FAILURE_POINTER (regend[n]); \
1461 PUSH_FAILURE_INT (n); \
1464 /* Change the counter's value to VAL, but make sure that it will
1465 be reset when backtracking. */
1466 #define PUSH_NUMBER(ptr,val) \
1468 char *destination; \
1470 ENSURE_FAIL_STACK(3); \
1471 EXTRACT_NUMBER (c, ptr); \
1472 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1473 PUSH_FAILURE_INT (c); \
1474 PUSH_FAILURE_POINTER (ptr); \
1475 PUSH_FAILURE_INT (-1); \
1476 STORE_NUMBER (ptr, val); \
1479 /* Pop a saved register off the stack. */
1480 #define POP_FAILURE_REG_OR_COUNT() \
1482 long pfreg = POP_FAILURE_INT (); \
1485 /* It's a counter. */ \
1486 /* Here, we discard `const', making re_match non-reentrant. */ \
1487 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1488 pfreg = POP_FAILURE_INT (); \
1489 STORE_NUMBER (ptr, pfreg); \
1490 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1494 regend[pfreg] = POP_FAILURE_POINTER (); \
1495 regstart[pfreg] = POP_FAILURE_POINTER (); \
1496 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1497 pfreg, regstart[pfreg], regend[pfreg]); \
1501 /* Check that we are not stuck in an infinite loop. */
1502 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1504 ssize_t failure = TOP_FAILURE_HANDLE (); \
1505 /* Check for infinite matching loops */ \
1506 while (failure > 0 \
1507 && (FAILURE_STR (failure) == string_place \
1508 || FAILURE_STR (failure) == NULL)) \
1510 assert (FAILURE_PAT (failure) >= bufp->buffer \
1511 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1512 if (FAILURE_PAT (failure) == pat_cur) \
1517 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1518 failure = NEXT_FAILURE_HANDLE(failure); \
1520 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1523 /* Push the information about the state we will need
1524 if we ever fail back to it.
1526 Requires variables fail_stack, regstart, regend and
1527 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1530 Does `return FAILURE_CODE' if runs out of memory. */
1532 #define PUSH_FAILURE_POINT(pattern, string_place) \
1534 char *destination; \
1535 /* Must be int, so when we don't save any registers, the arithmetic \
1536 of 0 + -1 isn't done as unsigned. */ \
1538 DEBUG_STATEMENT (nfailure_points_pushed++); \
1539 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1540 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1541 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1543 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1545 DEBUG_PRINT ("\n"); \
1547 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1548 PUSH_FAILURE_INT (fail_stack.frame); \
1550 DEBUG_PRINT (" Push string %p: `", string_place); \
1551 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1552 DEBUG_PRINT ("'\n"); \
1553 PUSH_FAILURE_POINTER (string_place); \
1555 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1556 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1557 PUSH_FAILURE_POINTER (pattern); \
1559 /* Close the frame by moving the frame pointer past it. */ \
1560 fail_stack.frame = fail_stack.avail; \
1563 /* Estimate the size of data pushed by a typical failure stack entry.
1564 An estimate is all we need, because all we use this for
1565 is to choose a limit for how big to make the failure stack. */
1566 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1567 #define TYPICAL_FAILURE_SIZE 20
1569 /* How many items can still be added to the stack without overflowing it. */
1570 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1573 /* Pops what PUSH_FAIL_STACK pushes.
1575 We restore into the parameters, all of which should be lvalues:
1576 STR -- the saved data position.
1577 PAT -- the saved pattern position.
1578 REGSTART, REGEND -- arrays of string positions.
1580 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1581 `pend', `string1', `size1', `string2', and `size2'. */
1583 #define POP_FAILURE_POINT(str, pat) \
1585 assert (!FAIL_STACK_EMPTY ()); \
1587 /* Remove failure points and point to how many regs pushed. */ \
1588 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1589 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1590 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1592 /* Pop the saved registers. */ \
1593 while (fail_stack.frame < fail_stack.avail) \
1594 POP_FAILURE_REG_OR_COUNT (); \
1596 pat = POP_FAILURE_POINTER (); \
1597 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1598 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1600 /* If the saved string location is NULL, it came from an \
1601 on_failure_keep_string_jump opcode, and we want to throw away the \
1602 saved NULL, thus retaining our current position in the string. */ \
1603 str = POP_FAILURE_POINTER (); \
1604 DEBUG_PRINT (" Popping string %p: `", str); \
1605 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1606 DEBUG_PRINT ("'\n"); \
1608 fail_stack.frame = POP_FAILURE_INT (); \
1609 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1611 assert (fail_stack.avail >= 0); \
1612 assert (fail_stack.frame <= fail_stack.avail); \
1614 DEBUG_STATEMENT (nfailure_points_popped++); \
1615 } while (0) /* POP_FAILURE_POINT */
1619 /* Registers are set to a sentinel when they haven't yet matched. */
1620 #define REG_UNSET(e) ((e) == NULL)
1622 /* Subroutine declarations and macros for regex_compile. */
1624 static reg_errcode_t
regex_compile (re_char
*pattern
, size_t size
,
1625 reg_syntax_t syntax
,
1626 struct re_pattern_buffer
*bufp
);
1627 static void store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
);
1628 static void store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
);
1629 static void insert_op1 (re_opcode_t op
, unsigned char *loc
,
1630 int arg
, unsigned char *end
);
1631 static void insert_op2 (re_opcode_t op
, unsigned char *loc
,
1632 int arg1
, int arg2
, unsigned char *end
);
1633 static boolean
at_begline_loc_p (re_char
*pattern
, re_char
*p
,
1634 reg_syntax_t syntax
);
1635 static boolean
at_endline_loc_p (re_char
*p
, re_char
*pend
,
1636 reg_syntax_t syntax
);
1637 static re_char
*skip_one_char (re_char
*p
);
1638 static int analyse_first (re_char
*p
, re_char
*pend
,
1639 char *fastmap
, const int multibyte
);
1641 /* Fetch the next character in the uncompiled pattern, with no
1643 #define PATFETCH(c) \
1646 if (p == pend) return REG_EEND; \
1647 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1652 /* If `translate' is non-null, return translate[D], else just D. We
1653 cast the subscript to translate because some data is declared as
1654 `char *', to avoid warnings when a string constant is passed. But
1655 when we use a character as a subscript we must make it unsigned. */
1657 # define TRANSLATE(d) \
1658 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1662 /* Macros for outputting the compiled pattern into `buffer'. */
1664 /* If the buffer isn't allocated when it comes in, use this. */
1665 #define INIT_BUF_SIZE 32
1667 /* Make sure we have at least N more bytes of space in buffer. */
1668 #define GET_BUFFER_SPACE(n) \
1669 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1672 /* Make sure we have one more byte of buffer space and then add C to it. */
1673 #define BUF_PUSH(c) \
1675 GET_BUFFER_SPACE (1); \
1676 *b++ = (unsigned char) (c); \
1680 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1681 #define BUF_PUSH_2(c1, c2) \
1683 GET_BUFFER_SPACE (2); \
1684 *b++ = (unsigned char) (c1); \
1685 *b++ = (unsigned char) (c2); \
1689 /* Store a jump with opcode OP at LOC to location TO. We store a
1690 relative address offset by the three bytes the jump itself occupies. */
1691 #define STORE_JUMP(op, loc, to) \
1692 store_op1 (op, loc, (to) - (loc) - 3)
1694 /* Likewise, for a two-argument jump. */
1695 #define STORE_JUMP2(op, loc, to, arg) \
1696 store_op2 (op, loc, (to) - (loc) - 3, arg)
1698 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1699 #define INSERT_JUMP(op, loc, to) \
1700 insert_op1 (op, loc, (to) - (loc) - 3, b)
1702 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1703 #define INSERT_JUMP2(op, loc, to, arg) \
1704 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1707 /* This is not an arbitrary limit: the arguments which represent offsets
1708 into the pattern are two bytes long. So if 2^15 bytes turns out to
1709 be too small, many things would have to change. */
1710 # define MAX_BUF_SIZE (1L << 15)
1712 /* Extend the buffer by twice its current size via realloc and
1713 reset the pointers that pointed into the old block to point to the
1714 correct places in the new one. If extending the buffer results in it
1715 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1716 #if __BOUNDED_POINTERS__
1717 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1718 # define MOVE_BUFFER_POINTER(P) \
1719 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1720 SET_HIGH_BOUND (P), \
1721 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1722 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1725 SET_HIGH_BOUND (b); \
1726 SET_HIGH_BOUND (begalt); \
1727 if (fixup_alt_jump) \
1728 SET_HIGH_BOUND (fixup_alt_jump); \
1730 SET_HIGH_BOUND (laststart); \
1731 if (pending_exact) \
1732 SET_HIGH_BOUND (pending_exact); \
1735 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1736 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1738 #define EXTEND_BUFFER() \
1740 unsigned char *old_buffer = bufp->buffer; \
1741 if (bufp->allocated == MAX_BUF_SIZE) \
1743 bufp->allocated <<= 1; \
1744 if (bufp->allocated > MAX_BUF_SIZE) \
1745 bufp->allocated = MAX_BUF_SIZE; \
1746 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1747 if (bufp->buffer == NULL) \
1748 return REG_ESPACE; \
1749 /* If the buffer moved, move all the pointers into it. */ \
1750 if (old_buffer != bufp->buffer) \
1752 unsigned char *new_buffer = bufp->buffer; \
1753 MOVE_BUFFER_POINTER (b); \
1754 MOVE_BUFFER_POINTER (begalt); \
1755 if (fixup_alt_jump) \
1756 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1758 MOVE_BUFFER_POINTER (laststart); \
1759 if (pending_exact) \
1760 MOVE_BUFFER_POINTER (pending_exact); \
1762 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1766 /* Since we have one byte reserved for the register number argument to
1767 {start,stop}_memory, the maximum number of groups we can report
1768 things about is what fits in that byte. */
1769 #define MAX_REGNUM 255
1771 /* But patterns can have more than `MAX_REGNUM' registers. We just
1772 ignore the excess. */
1773 typedef int regnum_t
;
1776 /* Macros for the compile stack. */
1778 /* Since offsets can go either forwards or backwards, this type needs to
1779 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1780 /* int may be not enough when sizeof(int) == 2. */
1781 typedef long pattern_offset_t
;
1785 pattern_offset_t begalt_offset
;
1786 pattern_offset_t fixup_alt_jump
;
1787 pattern_offset_t laststart_offset
;
1789 } compile_stack_elt_t
;
1794 compile_stack_elt_t
*stack
;
1796 size_t avail
; /* Offset of next open position. */
1797 } compile_stack_type
;
1800 #define INIT_COMPILE_STACK_SIZE 32
1802 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1803 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1805 /* The next available element. */
1806 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1808 /* Explicit quit checking is needed for Emacs, which uses polling to
1809 process input events. */
1811 # define IMMEDIATE_QUIT_CHECK \
1813 if (immediate_quit) QUIT; \
1816 # define IMMEDIATE_QUIT_CHECK ((void)0)
1819 /* Structure to manage work area for range table. */
1820 struct range_table_work_area
1822 int *table
; /* actual work area. */
1823 int allocated
; /* allocated size for work area in bytes. */
1824 int used
; /* actually used size in words. */
1825 int bits
; /* flag to record character classes */
1830 /* Make sure that WORK_AREA can hold more N multibyte characters.
1831 This is used only in set_image_of_range and set_image_of_range_1.
1832 It expects WORK_AREA to be a pointer.
1833 If it can't get the space, it returns from the surrounding function. */
1835 #define EXTEND_RANGE_TABLE(work_area, n) \
1837 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1839 extend_range_table_work_area (&work_area); \
1840 if ((work_area).table == 0) \
1841 return (REG_ESPACE); \
1845 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1846 (work_area).bits |= (bit)
1848 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1849 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1851 EXTEND_RANGE_TABLE ((work_area), 2); \
1852 (work_area).table[(work_area).used++] = (range_start); \
1853 (work_area).table[(work_area).used++] = (range_end); \
1858 /* Free allocated memory for WORK_AREA. */
1859 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1861 if ((work_area).table) \
1862 free ((work_area).table); \
1865 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1866 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1867 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1868 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1870 /* Bits used to implement the multibyte-part of the various character classes
1871 such as [:alnum:] in a charset's range table. */
1872 #define BIT_WORD 0x1
1873 #define BIT_LOWER 0x2
1874 #define BIT_PUNCT 0x4
1875 #define BIT_SPACE 0x8
1876 #define BIT_UPPER 0x10
1877 #define BIT_MULTIBYTE 0x20
1880 /* Set the bit for character C in a list. */
1881 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1886 /* Store characters in the range FROM to TO in the bitmap at B (for
1887 ASCII and unibyte characters) and WORK_AREA (for multibyte
1888 characters) while translating them and paying attention to the
1889 continuity of translated characters.
1891 Implementation note: It is better to implement these fairly big
1892 macros by a function, but it's not that easy because macros called
1893 in this macro assume various local variables already declared. */
1895 /* Both FROM and TO are ASCII characters. */
1897 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1901 for (C0 = (FROM); C0 <= (TO); C0++) \
1903 C1 = TRANSLATE (C0); \
1904 if (! ASCII_CHAR_P (C1)) \
1906 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1907 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1910 SET_LIST_BIT (C1); \
1915 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1917 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1919 int C0, C1, C2, I; \
1920 int USED = RANGE_TABLE_WORK_USED (work_area); \
1922 for (C0 = (FROM); C0 <= (TO); C0++) \
1924 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1925 if (CHAR_BYTE8_P (C1)) \
1926 SET_LIST_BIT (C0); \
1929 C2 = TRANSLATE (C1); \
1931 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1933 SET_LIST_BIT (C1); \
1934 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1936 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1937 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1939 if (C2 >= from - 1 && C2 <= to + 1) \
1941 if (C2 == from - 1) \
1942 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1943 else if (C2 == to + 1) \
1944 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1949 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1955 /* Both FROM and TO are multibyte characters. */
1957 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1959 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1961 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1962 for (C0 = (FROM); C0 <= (TO); C0++) \
1964 C1 = TRANSLATE (C0); \
1965 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1966 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1967 SET_LIST_BIT (C2); \
1968 if (C1 >= (FROM) && C1 <= (TO)) \
1970 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1972 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1973 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1975 if (C1 >= from - 1 && C1 <= to + 1) \
1977 if (C1 == from - 1) \
1978 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1979 else if (C1 == to + 1) \
1980 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1985 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1991 /* Get the next unsigned number in the uncompiled pattern. */
1992 #define GET_INTERVAL_COUNT(num) \
1995 FREE_STACK_RETURN (REG_EBRACE); \
1999 while ('0' <= c && c <= '9') \
2003 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
2004 FREE_STACK_RETURN (REG_BADBR); \
2005 num = num * 10 + c - '0'; \
2007 FREE_STACK_RETURN (REG_EBRACE); \
2013 #if ! WIDE_CHAR_SUPPORT
2015 /* Map a string to the char class it names (if any). */
2017 re_wctype (const_re_char
*str
)
2019 const char *string
= (const char *) str
;
2020 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2021 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2022 else if (STREQ (string
, "word")) return RECC_WORD
;
2023 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2024 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2025 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2026 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2027 else if (STREQ (string
, "print")) return RECC_PRINT
;
2028 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2029 else if (STREQ (string
, "space")) return RECC_SPACE
;
2030 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2031 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2032 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2033 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2034 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2035 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2036 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2040 /* True if CH is in the char class CC. */
2042 re_iswctype (int ch
, re_wctype_t cc
)
2046 case RECC_ALNUM
: return ISALNUM (ch
) != 0;
2047 case RECC_ALPHA
: return ISALPHA (ch
) != 0;
2048 case RECC_BLANK
: return ISBLANK (ch
) != 0;
2049 case RECC_CNTRL
: return ISCNTRL (ch
) != 0;
2050 case RECC_DIGIT
: return ISDIGIT (ch
) != 0;
2051 case RECC_GRAPH
: return ISGRAPH (ch
) != 0;
2052 case RECC_LOWER
: return ISLOWER (ch
) != 0;
2053 case RECC_PRINT
: return ISPRINT (ch
) != 0;
2054 case RECC_PUNCT
: return ISPUNCT (ch
) != 0;
2055 case RECC_SPACE
: return ISSPACE (ch
) != 0;
2056 case RECC_UPPER
: return ISUPPER (ch
) != 0;
2057 case RECC_XDIGIT
: return ISXDIGIT (ch
) != 0;
2058 case RECC_ASCII
: return IS_REAL_ASCII (ch
) != 0;
2059 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2060 case RECC_UNIBYTE
: return ISUNIBYTE (ch
) != 0;
2061 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2062 case RECC_WORD
: return ISWORD (ch
) != 0;
2063 case RECC_ERROR
: return false;
2069 /* Return a bit-pattern to use in the range-table bits to match multibyte
2070 chars of class CC. */
2072 re_wctype_to_bit (re_wctype_t cc
)
2076 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2077 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2078 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2079 case RECC_LOWER
: return BIT_LOWER
;
2080 case RECC_UPPER
: return BIT_UPPER
;
2081 case RECC_PUNCT
: return BIT_PUNCT
;
2082 case RECC_SPACE
: return BIT_SPACE
;
2083 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2084 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2091 /* Filling in the work area of a range. */
2093 /* Actually extend the space in WORK_AREA. */
2096 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2098 work_area
->allocated
+= 16 * sizeof (int);
2099 work_area
->table
= realloc (work_area
->table
, work_area
->allocated
);
2105 /* Carefully find the ranges of codes that are equivalent
2106 under case conversion to the range start..end when passed through
2107 TRANSLATE. Handle the case where non-letters can come in between
2108 two upper-case letters (which happens in Latin-1).
2109 Also handle the case of groups of more than 2 case-equivalent chars.
2111 The basic method is to look at consecutive characters and see
2112 if they can form a run that can be handled as one.
2114 Returns -1 if successful, REG_ESPACE if ran out of space. */
2117 set_image_of_range_1 (struct range_table_work_area
*work_area
,
2118 re_wchar_t start
, re_wchar_t end
,
2119 RE_TRANSLATE_TYPE translate
)
2121 /* `one_case' indicates a character, or a run of characters,
2122 each of which is an isolate (no case-equivalents).
2123 This includes all ASCII non-letters.
2125 `two_case' indicates a character, or a run of characters,
2126 each of which has two case-equivalent forms.
2127 This includes all ASCII letters.
2129 `strange' indicates a character that has more than one
2132 enum case_type
{one_case
, two_case
, strange
};
2134 /* Describe the run that is in progress,
2135 which the next character can try to extend.
2136 If run_type is strange, that means there really is no run.
2137 If run_type is one_case, then run_start...run_end is the run.
2138 If run_type is two_case, then the run is run_start...run_end,
2139 and the case-equivalents end at run_eqv_end. */
2141 enum case_type run_type
= strange
;
2142 int run_start
, run_end
, run_eqv_end
;
2144 Lisp_Object eqv_table
;
2146 if (!RE_TRANSLATE_P (translate
))
2148 EXTEND_RANGE_TABLE (work_area
, 2);
2149 work_area
->table
[work_area
->used
++] = (start
);
2150 work_area
->table
[work_area
->used
++] = (end
);
2154 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2156 for (; start
<= end
; start
++)
2158 enum case_type this_type
;
2159 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2160 int minchar
, maxchar
;
2162 /* Classify this character */
2164 this_type
= one_case
;
2165 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2166 this_type
= two_case
;
2168 this_type
= strange
;
2171 minchar
= start
, maxchar
= eqv
;
2173 minchar
= eqv
, maxchar
= start
;
2175 /* Can this character extend the run in progress? */
2176 if (this_type
== strange
|| this_type
!= run_type
2177 || !(minchar
== run_end
+ 1
2178 && (run_type
== two_case
2179 ? maxchar
== run_eqv_end
+ 1 : 1)))
2182 Record each of its equivalent ranges. */
2183 if (run_type
== one_case
)
2185 EXTEND_RANGE_TABLE (work_area
, 2);
2186 work_area
->table
[work_area
->used
++] = run_start
;
2187 work_area
->table
[work_area
->used
++] = run_end
;
2189 else if (run_type
== two_case
)
2191 EXTEND_RANGE_TABLE (work_area
, 4);
2192 work_area
->table
[work_area
->used
++] = run_start
;
2193 work_area
->table
[work_area
->used
++] = run_end
;
2194 work_area
->table
[work_area
->used
++]
2195 = RE_TRANSLATE (eqv_table
, run_start
);
2196 work_area
->table
[work_area
->used
++]
2197 = RE_TRANSLATE (eqv_table
, run_end
);
2202 if (this_type
== strange
)
2204 /* For a strange character, add each of its equivalents, one
2205 by one. Don't start a range. */
2208 EXTEND_RANGE_TABLE (work_area
, 2);
2209 work_area
->table
[work_area
->used
++] = eqv
;
2210 work_area
->table
[work_area
->used
++] = eqv
;
2211 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2213 while (eqv
!= start
);
2216 /* Add this char to the run, or start a new run. */
2217 else if (run_type
== strange
)
2219 /* Initialize a new range. */
2220 run_type
= this_type
;
2223 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2227 /* Extend a running range. */
2229 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2233 /* If a run is still in progress at the end, finish it now
2234 by recording its equivalent ranges. */
2235 if (run_type
== one_case
)
2237 EXTEND_RANGE_TABLE (work_area
, 2);
2238 work_area
->table
[work_area
->used
++] = run_start
;
2239 work_area
->table
[work_area
->used
++] = run_end
;
2241 else if (run_type
== two_case
)
2243 EXTEND_RANGE_TABLE (work_area
, 4);
2244 work_area
->table
[work_area
->used
++] = run_start
;
2245 work_area
->table
[work_area
->used
++] = run_end
;
2246 work_area
->table
[work_area
->used
++]
2247 = RE_TRANSLATE (eqv_table
, run_start
);
2248 work_area
->table
[work_area
->used
++]
2249 = RE_TRANSLATE (eqv_table
, run_end
);
2257 /* Record the image of the range start..end when passed through
2258 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2259 and is not even necessarily contiguous.
2260 Normally we approximate it with the smallest contiguous range that contains
2261 all the chars we need. However, for Latin-1 we go to extra effort
2264 This function is not called for ASCII ranges.
2266 Returns -1 if successful, REG_ESPACE if ran out of space. */
2269 set_image_of_range (struct range_table_work_area
*work_area
,
2270 re_wchar_t start
, re_wchar_t end
,
2271 RE_TRANSLATE_TYPE translate
)
2273 re_wchar_t cmin
, cmax
;
2276 /* For Latin-1 ranges, use set_image_of_range_1
2277 to get proper handling of ranges that include letters and nonletters.
2278 For a range that includes the whole of Latin-1, this is not necessary.
2279 For other character sets, we don't bother to get this right. */
2280 if (RE_TRANSLATE_P (translate
) && start
< 04400
2281 && !(start
< 04200 && end
>= 04377))
2288 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2298 EXTEND_RANGE_TABLE (work_area
, 2);
2299 work_area
->table
[work_area
->used
++] = (start
);
2300 work_area
->table
[work_area
->used
++] = (end
);
2302 cmin
= -1, cmax
= -1;
2304 if (RE_TRANSLATE_P (translate
))
2308 for (ch
= start
; ch
<= end
; ch
++)
2310 re_wchar_t c
= TRANSLATE (ch
);
2311 if (! (start
<= c
&& c
<= end
))
2317 cmin
= MIN (cmin
, c
);
2318 cmax
= MAX (cmax
, c
);
2325 EXTEND_RANGE_TABLE (work_area
, 2);
2326 work_area
->table
[work_area
->used
++] = (cmin
);
2327 work_area
->table
[work_area
->used
++] = (cmax
);
2335 #ifndef MATCH_MAY_ALLOCATE
2337 /* If we cannot allocate large objects within re_match_2_internal,
2338 we make the fail stack and register vectors global.
2339 The fail stack, we grow to the maximum size when a regexp
2341 The register vectors, we adjust in size each time we
2342 compile a regexp, according to the number of registers it needs. */
2344 static fail_stack_type fail_stack
;
2346 /* Size with which the following vectors are currently allocated.
2347 That is so we can make them bigger as needed,
2348 but never make them smaller. */
2349 static int regs_allocated_size
;
2351 static re_char
** regstart
, ** regend
;
2352 static re_char
**best_regstart
, **best_regend
;
2354 /* Make the register vectors big enough for NUM_REGS registers,
2355 but don't make them smaller. */
2358 regex_grow_registers (int num_regs
)
2360 if (num_regs
> regs_allocated_size
)
2362 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2363 RETALLOC_IF (regend
, num_regs
, re_char
*);
2364 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2365 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2367 regs_allocated_size
= num_regs
;
2371 #endif /* not MATCH_MAY_ALLOCATE */
2373 static boolean
group_in_compile_stack (compile_stack_type compile_stack
,
2376 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2377 Returns one of error codes defined in `regex.h', or zero for success.
2379 Assumes the `allocated' (and perhaps `buffer') and `translate'
2380 fields are set in BUFP on entry.
2382 If it succeeds, results are put in BUFP (if it returns an error, the
2383 contents of BUFP are undefined):
2384 `buffer' is the compiled pattern;
2385 `syntax' is set to SYNTAX;
2386 `used' is set to the length of the compiled pattern;
2387 `fastmap_accurate' is zero;
2388 `re_nsub' is the number of subexpressions in PATTERN;
2389 `not_bol' and `not_eol' are zero;
2391 The `fastmap' field is neither examined nor set. */
2393 /* Insert the `jump' from the end of last alternative to "here".
2394 The space for the jump has already been allocated. */
2395 #define FIXUP_ALT_JUMP() \
2397 if (fixup_alt_jump) \
2398 STORE_JUMP (jump, fixup_alt_jump, b); \
2402 /* Return, freeing storage we allocated. */
2403 #define FREE_STACK_RETURN(value) \
2405 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2406 free (compile_stack.stack); \
2410 static reg_errcode_t
2411 regex_compile (const_re_char
*pattern
, size_t size
, reg_syntax_t syntax
,
2412 struct re_pattern_buffer
*bufp
)
2414 /* We fetch characters from PATTERN here. */
2415 register re_wchar_t c
, c1
;
2417 /* Points to the end of the buffer, where we should append. */
2418 register unsigned char *b
;
2420 /* Keeps track of unclosed groups. */
2421 compile_stack_type compile_stack
;
2423 /* Points to the current (ending) position in the pattern. */
2425 /* `const' makes AIX compiler fail. */
2426 unsigned char *p
= pattern
;
2428 re_char
*p
= pattern
;
2430 re_char
*pend
= pattern
+ size
;
2432 /* How to translate the characters in the pattern. */
2433 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2435 /* Address of the count-byte of the most recently inserted `exactn'
2436 command. This makes it possible to tell if a new exact-match
2437 character can be added to that command or if the character requires
2438 a new `exactn' command. */
2439 unsigned char *pending_exact
= 0;
2441 /* Address of start of the most recently finished expression.
2442 This tells, e.g., postfix * where to find the start of its
2443 operand. Reset at the beginning of groups and alternatives. */
2444 unsigned char *laststart
= 0;
2446 /* Address of beginning of regexp, or inside of last group. */
2447 unsigned char *begalt
;
2449 /* Place in the uncompiled pattern (i.e., the {) to
2450 which to go back if the interval is invalid. */
2451 re_char
*beg_interval
;
2453 /* Address of the place where a forward jump should go to the end of
2454 the containing expression. Each alternative of an `or' -- except the
2455 last -- ends with a forward jump of this sort. */
2456 unsigned char *fixup_alt_jump
= 0;
2458 /* Work area for range table of charset. */
2459 struct range_table_work_area range_table_work
;
2461 /* If the object matched can contain multibyte characters. */
2462 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2464 /* Nonzero if we have pushed down into a subpattern. */
2465 int in_subpattern
= 0;
2467 /* These hold the values of p, pattern, and pend from the main
2468 pattern when we have pushed into a subpattern. */
2469 re_char
*main_p
IF_LINT (= NULL
);
2470 re_char
*main_pattern
IF_LINT (= NULL
);
2471 re_char
*main_pend
IF_LINT (= NULL
);
2475 DEBUG_PRINT ("\nCompiling pattern: ");
2478 unsigned debug_count
;
2480 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2481 putchar (pattern
[debug_count
]);
2486 /* Initialize the compile stack. */
2487 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2488 if (compile_stack
.stack
== NULL
)
2491 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2492 compile_stack
.avail
= 0;
2494 range_table_work
.table
= 0;
2495 range_table_work
.allocated
= 0;
2497 /* Initialize the pattern buffer. */
2498 bufp
->syntax
= syntax
;
2499 bufp
->fastmap_accurate
= 0;
2500 bufp
->not_bol
= bufp
->not_eol
= 0;
2501 bufp
->used_syntax
= 0;
2503 /* Set `used' to zero, so that if we return an error, the pattern
2504 printer (for debugging) will think there's no pattern. We reset it
2508 /* Always count groups, whether or not bufp->no_sub is set. */
2511 #if !defined emacs && !defined SYNTAX_TABLE
2512 /* Initialize the syntax table. */
2513 init_syntax_once ();
2516 if (bufp
->allocated
== 0)
2519 { /* If zero allocated, but buffer is non-null, try to realloc
2520 enough space. This loses if buffer's address is bogus, but
2521 that is the user's responsibility. */
2522 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2525 { /* Caller did not allocate a buffer. Do it for them. */
2526 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2528 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2530 bufp
->allocated
= INIT_BUF_SIZE
;
2533 begalt
= b
= bufp
->buffer
;
2535 /* Loop through the uncompiled pattern until we're at the end. */
2540 /* If this is the end of an included regexp,
2541 pop back to the main regexp and try again. */
2545 pattern
= main_pattern
;
2550 /* If this is the end of the main regexp, we are done. */
2562 /* If there's no special whitespace regexp, treat
2563 spaces normally. And don't try to do this recursively. */
2564 if (!whitespace_regexp
|| in_subpattern
)
2567 /* Peek past following spaces. */
2574 /* If the spaces are followed by a repetition op,
2575 treat them normally. */
2577 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2578 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2581 /* Replace the spaces with the whitespace regexp. */
2585 main_pattern
= pattern
;
2586 p
= pattern
= whitespace_regexp
;
2587 pend
= p
+ strlen ((const char *) p
);
2593 if ( /* If at start of pattern, it's an operator. */
2595 /* If context independent, it's an operator. */
2596 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2597 /* Otherwise, depends on what's come before. */
2598 || at_begline_loc_p (pattern
, p
, syntax
))
2599 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2608 if ( /* If at end of pattern, it's an operator. */
2610 /* If context independent, it's an operator. */
2611 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2612 /* Otherwise, depends on what's next. */
2613 || at_endline_loc_p (p
, pend
, syntax
))
2614 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2623 if ((syntax
& RE_BK_PLUS_QM
)
2624 || (syntax
& RE_LIMITED_OPS
))
2628 /* If there is no previous pattern... */
2631 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2632 FREE_STACK_RETURN (REG_BADRPT
);
2633 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2638 /* 1 means zero (many) matches is allowed. */
2639 boolean zero_times_ok
= 0, many_times_ok
= 0;
2642 /* If there is a sequence of repetition chars, collapse it
2643 down to just one (the right one). We can't combine
2644 interval operators with these because of, e.g., `a{2}*',
2645 which should only match an even number of `a's. */
2649 if ((syntax
& RE_FRUGAL
)
2650 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2654 zero_times_ok
|= c
!= '+';
2655 many_times_ok
|= c
!= '?';
2661 || (!(syntax
& RE_BK_PLUS_QM
)
2662 && (*p
== '+' || *p
== '?')))
2664 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2667 FREE_STACK_RETURN (REG_EESCAPE
);
2668 if (p
[1] == '+' || p
[1] == '?')
2669 PATFETCH (c
); /* Gobble up the backslash. */
2675 /* If we get here, we found another repeat character. */
2679 /* Star, etc. applied to an empty pattern is equivalent
2680 to an empty pattern. */
2681 if (!laststart
|| laststart
== b
)
2684 /* Now we know whether or not zero matches is allowed
2685 and also whether or not two or more matches is allowed. */
2690 boolean simple
= skip_one_char (laststart
) == b
;
2691 size_t startoffset
= 0;
2693 /* Check if the loop can match the empty string. */
2694 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2695 ? on_failure_jump
: on_failure_jump_loop
;
2696 assert (skip_one_char (laststart
) <= b
);
2698 if (!zero_times_ok
&& simple
)
2699 { /* Since simple * loops can be made faster by using
2700 on_failure_keep_string_jump, we turn simple P+
2701 into PP* if P is simple. */
2702 unsigned char *p1
, *p2
;
2703 startoffset
= b
- laststart
;
2704 GET_BUFFER_SPACE (startoffset
);
2705 p1
= b
; p2
= laststart
;
2711 GET_BUFFER_SPACE (6);
2714 STORE_JUMP (ofj
, b
, b
+ 6);
2716 /* Simple * loops can use on_failure_keep_string_jump
2717 depending on what follows. But since we don't know
2718 that yet, we leave the decision up to
2719 on_failure_jump_smart. */
2720 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2721 laststart
+ startoffset
, b
+ 6);
2723 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2728 /* A simple ? pattern. */
2729 assert (zero_times_ok
);
2730 GET_BUFFER_SPACE (3);
2731 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2735 else /* not greedy */
2736 { /* I wish the greedy and non-greedy cases could be merged. */
2738 GET_BUFFER_SPACE (7); /* We might use less. */
2741 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2743 /* The non-greedy multiple match looks like
2744 a repeat..until: we only need a conditional jump
2745 at the end of the loop. */
2746 if (emptyp
) BUF_PUSH (no_op
);
2747 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2748 : on_failure_jump
, b
, laststart
);
2752 /* The repeat...until naturally matches one or more.
2753 To also match zero times, we need to first jump to
2754 the end of the loop (its conditional jump). */
2755 INSERT_JUMP (jump
, laststart
, b
);
2761 /* non-greedy a?? */
2762 INSERT_JUMP (jump
, laststart
, b
+ 3);
2764 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2783 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2785 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2787 /* Ensure that we have enough space to push a charset: the
2788 opcode, the length count, and the bitset; 34 bytes in all. */
2789 GET_BUFFER_SPACE (34);
2793 /* We test `*p == '^' twice, instead of using an if
2794 statement, so we only need one BUF_PUSH. */
2795 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2799 /* Remember the first position in the bracket expression. */
2802 /* Push the number of bytes in the bitmap. */
2803 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2805 /* Clear the whole map. */
2806 memset (b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2808 /* charset_not matches newline according to a syntax bit. */
2809 if ((re_opcode_t
) b
[-2] == charset_not
2810 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2811 SET_LIST_BIT ('\n');
2813 /* Read in characters and ranges, setting map bits. */
2816 boolean escaped_char
= false;
2817 const unsigned char *p2
= p
;
2820 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2822 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2823 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2824 So the translation is done later in a loop. Example:
2825 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2828 /* \ might escape characters inside [...] and [^...]. */
2829 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2831 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2834 escaped_char
= true;
2838 /* Could be the end of the bracket expression. If it's
2839 not (i.e., when the bracket expression is `[]' so
2840 far), the ']' character bit gets set way below. */
2841 if (c
== ']' && p2
!= p1
)
2845 /* See if we're at the beginning of a possible character
2848 if (!escaped_char
&&
2849 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2851 /* Leave room for the null. */
2852 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2853 const unsigned char *class_beg
;
2859 /* If pattern is `[[:'. */
2860 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2865 if ((c
== ':' && *p
== ']') || p
== pend
)
2867 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2870 /* This is in any case an invalid class name. */
2875 /* If isn't a word bracketed by `[:' and `:]':
2876 undo the ending character, the letters, and
2877 leave the leading `:' and `[' (but set bits for
2879 if (c
== ':' && *p
== ']')
2881 re_wctype_t cc
= re_wctype (str
);
2884 FREE_STACK_RETURN (REG_ECTYPE
);
2886 /* Throw away the ] at the end of the character
2890 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2893 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
2894 if (re_iswctype (btowc (ch
), cc
))
2897 if (c
< (1 << BYTEWIDTH
))
2901 /* Most character classes in a multibyte match
2902 just set a flag. Exceptions are is_blank,
2903 is_digit, is_cntrl, and is_xdigit, since
2904 they can only match ASCII characters. We
2905 don't need to handle them for multibyte.
2906 They are distinguished by a negative wctype. */
2908 /* Setup the gl_state object to its buffer-defined
2909 value. This hardcodes the buffer-global
2910 syntax-table for ASCII chars, while the other chars
2911 will obey syntax-table properties. It's not ideal,
2912 but it's the way it's been done until now. */
2913 SETUP_BUFFER_SYNTAX_TABLE ();
2915 for (ch
= 0; ch
< 256; ++ch
)
2917 c
= RE_CHAR_TO_MULTIBYTE (ch
);
2918 if (! CHAR_BYTE8_P (c
)
2919 && re_iswctype (c
, cc
))
2925 if (ASCII_CHAR_P (c1
))
2927 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
2931 SET_RANGE_TABLE_WORK_AREA_BIT
2932 (range_table_work
, re_wctype_to_bit (cc
));
2934 /* In most cases the matching rule for char classes
2935 only uses the syntax table for multibyte chars,
2936 so that the content of the syntax-table it is not
2937 hardcoded in the range_table. SPACE and WORD are
2938 the two exceptions. */
2939 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
2940 bufp
->used_syntax
= 1;
2942 /* Repeat the loop. */
2947 /* Go back to right after the "[:". */
2951 /* Because the `:' may starts the range, we
2952 can't simply set bit and repeat the loop.
2953 Instead, just set it to C and handle below. */
2958 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2961 /* Discard the `-'. */
2964 /* Fetch the character which ends the range. */
2967 if (CHAR_BYTE8_P (c1
)
2968 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
2969 /* Treat the range from a multibyte character to
2970 raw-byte character as empty. */
2975 /* Range from C to C. */
2980 if (syntax
& RE_NO_EMPTY_RANGES
)
2981 FREE_STACK_RETURN (REG_ERANGEX
);
2982 /* Else, repeat the loop. */
2987 /* Set the range into bitmap */
2988 for (; c
<= c1
; c
++)
2991 if (ch
< (1 << BYTEWIDTH
))
2998 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
3000 if (CHAR_BYTE8_P (c1
))
3001 c
= BYTE8_TO_CHAR (128);
3005 if (CHAR_BYTE8_P (c
))
3007 c
= CHAR_TO_BYTE8 (c
);
3008 c1
= CHAR_TO_BYTE8 (c1
);
3009 for (; c
<= c1
; c
++)
3014 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
3018 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
3025 /* Discard any (non)matching list bytes that are all 0 at the
3026 end of the map. Decrease the map-length byte too. */
3027 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3031 /* Build real range table from work area. */
3032 if (RANGE_TABLE_WORK_USED (range_table_work
)
3033 || RANGE_TABLE_WORK_BITS (range_table_work
))
3036 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3038 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3039 bytes for flags, two for COUNT, and three bytes for
3041 GET_BUFFER_SPACE (4 + used
* 3);
3043 /* Indicate the existence of range table. */
3044 laststart
[1] |= 0x80;
3046 /* Store the character class flag bits into the range table.
3047 If not in emacs, these flag bits are always 0. */
3048 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3049 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3051 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3052 for (i
= 0; i
< used
; i
++)
3053 STORE_CHARACTER_AND_INCR
3054 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3061 if (syntax
& RE_NO_BK_PARENS
)
3068 if (syntax
& RE_NO_BK_PARENS
)
3075 if (syntax
& RE_NEWLINE_ALT
)
3082 if (syntax
& RE_NO_BK_VBAR
)
3089 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3090 goto handle_interval
;
3096 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3098 /* Do not translate the character after the \, so that we can
3099 distinguish, e.g., \B from \b, even if we normally would
3100 translate, e.g., B to b. */
3106 if (syntax
& RE_NO_BK_PARENS
)
3107 goto normal_backslash
;
3112 regnum_t regnum
= 0;
3115 /* Look for a special (?...) construct */
3116 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3118 PATFETCH (c
); /* Gobble up the '?'. */
3124 case ':': shy
= 1; break;
3126 /* An explicitly specified regnum must start
3129 FREE_STACK_RETURN (REG_BADPAT
);
3130 case '1': case '2': case '3': case '4':
3131 case '5': case '6': case '7': case '8': case '9':
3132 regnum
= 10*regnum
+ (c
- '0'); break;
3134 /* Only (?:...) is supported right now. */
3135 FREE_STACK_RETURN (REG_BADPAT
);
3142 regnum
= ++bufp
->re_nsub
;
3144 { /* It's actually not shy, but explicitly numbered. */
3146 if (regnum
> bufp
->re_nsub
)
3147 bufp
->re_nsub
= regnum
;
3148 else if (regnum
> bufp
->re_nsub
3149 /* Ideally, we'd want to check that the specified
3150 group can't have matched (i.e. all subgroups
3151 using the same regnum are in other branches of
3152 OR patterns), but we don't currently keep track
3153 of enough info to do that easily. */
3154 || group_in_compile_stack (compile_stack
, regnum
))
3155 FREE_STACK_RETURN (REG_BADPAT
);
3158 /* It's really shy. */
3159 regnum
= - bufp
->re_nsub
;
3161 if (COMPILE_STACK_FULL
)
3163 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3164 compile_stack_elt_t
);
3165 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3167 compile_stack
.size
<<= 1;
3170 /* These are the values to restore when we hit end of this
3171 group. They are all relative offsets, so that if the
3172 whole pattern moves because of realloc, they will still
3174 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3175 COMPILE_STACK_TOP
.fixup_alt_jump
3176 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3177 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3178 COMPILE_STACK_TOP
.regnum
= regnum
;
3180 /* Do not push a start_memory for groups beyond the last one
3181 we can represent in the compiled pattern. */
3182 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3183 BUF_PUSH_2 (start_memory
, regnum
);
3185 compile_stack
.avail
++;
3190 /* If we've reached MAX_REGNUM groups, then this open
3191 won't actually generate any code, so we'll have to
3192 clear pending_exact explicitly. */
3198 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3200 if (COMPILE_STACK_EMPTY
)
3202 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3203 goto normal_backslash
;
3205 FREE_STACK_RETURN (REG_ERPAREN
);
3211 /* See similar code for backslashed left paren above. */
3212 if (COMPILE_STACK_EMPTY
)
3214 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3217 FREE_STACK_RETURN (REG_ERPAREN
);
3220 /* Since we just checked for an empty stack above, this
3221 ``can't happen''. */
3222 assert (compile_stack
.avail
!= 0);
3224 /* We don't just want to restore into `regnum', because
3225 later groups should continue to be numbered higher,
3226 as in `(ab)c(de)' -- the second group is #2. */
3229 compile_stack
.avail
--;
3230 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3232 = COMPILE_STACK_TOP
.fixup_alt_jump
3233 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3235 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3236 regnum
= COMPILE_STACK_TOP
.regnum
;
3237 /* If we've reached MAX_REGNUM groups, then this open
3238 won't actually generate any code, so we'll have to
3239 clear pending_exact explicitly. */
3242 /* We're at the end of the group, so now we know how many
3243 groups were inside this one. */
3244 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3245 BUF_PUSH_2 (stop_memory
, regnum
);
3250 case '|': /* `\|'. */
3251 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3252 goto normal_backslash
;
3254 if (syntax
& RE_LIMITED_OPS
)
3257 /* Insert before the previous alternative a jump which
3258 jumps to this alternative if the former fails. */
3259 GET_BUFFER_SPACE (3);
3260 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3264 /* The alternative before this one has a jump after it
3265 which gets executed if it gets matched. Adjust that
3266 jump so it will jump to this alternative's analogous
3267 jump (put in below, which in turn will jump to the next
3268 (if any) alternative's such jump, etc.). The last such
3269 jump jumps to the correct final destination. A picture:
3275 If we are at `b', then fixup_alt_jump right now points to a
3276 three-byte space after `a'. We'll put in the jump, set
3277 fixup_alt_jump to right after `b', and leave behind three
3278 bytes which we'll fill in when we get to after `c'. */
3282 /* Mark and leave space for a jump after this alternative,
3283 to be filled in later either by next alternative or
3284 when know we're at the end of a series of alternatives. */
3286 GET_BUFFER_SPACE (3);
3295 /* If \{ is a literal. */
3296 if (!(syntax
& RE_INTERVALS
)
3297 /* If we're at `\{' and it's not the open-interval
3299 || (syntax
& RE_NO_BK_BRACES
))
3300 goto normal_backslash
;
3304 /* If got here, then the syntax allows intervals. */
3306 /* At least (most) this many matches must be made. */
3307 int lower_bound
= 0, upper_bound
= -1;
3311 GET_INTERVAL_COUNT (lower_bound
);
3314 GET_INTERVAL_COUNT (upper_bound
);
3316 /* Interval such as `{1}' => match exactly once. */
3317 upper_bound
= lower_bound
;
3320 || (0 <= upper_bound
&& upper_bound
< lower_bound
))
3321 FREE_STACK_RETURN (REG_BADBR
);
3323 if (!(syntax
& RE_NO_BK_BRACES
))
3326 FREE_STACK_RETURN (REG_BADBR
);
3328 FREE_STACK_RETURN (REG_EESCAPE
);
3333 FREE_STACK_RETURN (REG_BADBR
);
3335 /* We just parsed a valid interval. */
3337 /* If it's invalid to have no preceding re. */
3340 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3341 FREE_STACK_RETURN (REG_BADRPT
);
3342 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3345 goto unfetch_interval
;
3348 if (upper_bound
== 0)
3349 /* If the upper bound is zero, just drop the sub pattern
3352 else if (lower_bound
== 1 && upper_bound
== 1)
3353 /* Just match it once: nothing to do here. */
3356 /* Otherwise, we have a nontrivial interval. When
3357 we're all done, the pattern will look like:
3358 set_number_at <jump count> <upper bound>
3359 set_number_at <succeed_n count> <lower bound>
3360 succeed_n <after jump addr> <succeed_n count>
3362 jump_n <succeed_n addr> <jump count>
3363 (The upper bound and `jump_n' are omitted if
3364 `upper_bound' is 1, though.) */
3366 { /* If the upper bound is > 1, we need to insert
3367 more at the end of the loop. */
3368 unsigned int nbytes
= (upper_bound
< 0 ? 3
3369 : upper_bound
> 1 ? 5 : 0);
3370 unsigned int startoffset
= 0;
3372 GET_BUFFER_SPACE (20); /* We might use less. */
3374 if (lower_bound
== 0)
3376 /* A succeed_n that starts with 0 is really a
3377 a simple on_failure_jump_loop. */
3378 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3384 /* Initialize lower bound of the `succeed_n', even
3385 though it will be set during matching by its
3386 attendant `set_number_at' (inserted next),
3387 because `re_compile_fastmap' needs to know.
3388 Jump to the `jump_n' we might insert below. */
3389 INSERT_JUMP2 (succeed_n
, laststart
,
3394 /* Code to initialize the lower bound. Insert
3395 before the `succeed_n'. The `5' is the last two
3396 bytes of this `set_number_at', plus 3 bytes of
3397 the following `succeed_n'. */
3398 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3403 if (upper_bound
< 0)
3405 /* A negative upper bound stands for infinity,
3406 in which case it degenerates to a plain jump. */
3407 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3410 else if (upper_bound
> 1)
3411 { /* More than one repetition is allowed, so
3412 append a backward jump to the `succeed_n'
3413 that starts this interval.
3415 When we've reached this during matching,
3416 we'll have matched the interval once, so
3417 jump back only `upper_bound - 1' times. */
3418 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3422 /* The location we want to set is the second
3423 parameter of the `jump_n'; that is `b-2' as
3424 an absolute address. `laststart' will be
3425 the `set_number_at' we're about to insert;
3426 `laststart+3' the number to set, the source
3427 for the relative address. But we are
3428 inserting into the middle of the pattern --
3429 so everything is getting moved up by 5.
3430 Conclusion: (b - 2) - (laststart + 3) + 5,
3431 i.e., b - laststart.
3433 We insert this at the beginning of the loop
3434 so that if we fail during matching, we'll
3435 reinitialize the bounds. */
3436 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3437 upper_bound
- 1, b
);
3442 beg_interval
= NULL
;
3447 /* If an invalid interval, match the characters as literals. */
3448 assert (beg_interval
);
3450 beg_interval
= NULL
;
3452 /* normal_char and normal_backslash need `c'. */
3455 if (!(syntax
& RE_NO_BK_BRACES
))
3457 assert (p
> pattern
&& p
[-1] == '\\');
3458 goto normal_backslash
;
3464 /* There is no way to specify the before_dot and after_dot
3465 operators. rms says this is ok. --karl */
3474 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3480 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3486 BUF_PUSH_2 (categoryspec
, c
);
3492 BUF_PUSH_2 (notcategoryspec
, c
);
3498 if (syntax
& RE_NO_GNU_OPS
)
3501 BUF_PUSH_2 (syntaxspec
, Sword
);
3506 if (syntax
& RE_NO_GNU_OPS
)
3509 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3514 if (syntax
& RE_NO_GNU_OPS
)
3521 if (syntax
& RE_NO_GNU_OPS
)
3528 if (syntax
& RE_NO_GNU_OPS
)
3537 FREE_STACK_RETURN (REG_BADPAT
);
3541 if (syntax
& RE_NO_GNU_OPS
)
3543 BUF_PUSH (wordbound
);
3547 if (syntax
& RE_NO_GNU_OPS
)
3549 BUF_PUSH (notwordbound
);
3553 if (syntax
& RE_NO_GNU_OPS
)
3559 if (syntax
& RE_NO_GNU_OPS
)
3564 case '1': case '2': case '3': case '4': case '5':
3565 case '6': case '7': case '8': case '9':
3569 if (syntax
& RE_NO_BK_REFS
)
3570 goto normal_backslash
;
3574 if (reg
> bufp
->re_nsub
|| reg
< 1
3575 /* Can't back reference to a subexp before its end. */
3576 || group_in_compile_stack (compile_stack
, reg
))
3577 FREE_STACK_RETURN (REG_ESUBREG
);
3580 BUF_PUSH_2 (duplicate
, reg
);
3587 if (syntax
& RE_BK_PLUS_QM
)
3590 goto normal_backslash
;
3594 /* You might think it would be useful for \ to mean
3595 not to translate; but if we don't translate it
3596 it will never match anything. */
3603 /* Expects the character in `c'. */
3605 /* If no exactn currently being built. */
3608 /* If last exactn not at current position. */
3609 || pending_exact
+ *pending_exact
+ 1 != b
3611 /* We have only one byte following the exactn for the count. */
3612 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3614 /* If followed by a repetition operator. */
3615 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3616 || ((syntax
& RE_BK_PLUS_QM
)
3617 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3618 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3619 || ((syntax
& RE_INTERVALS
)
3620 && ((syntax
& RE_NO_BK_BRACES
)
3621 ? p
!= pend
&& *p
== '{'
3622 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3624 /* Start building a new exactn. */
3628 BUF_PUSH_2 (exactn
, 0);
3629 pending_exact
= b
- 1;
3632 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3639 len
= CHAR_STRING (c
, b
);
3644 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3645 if (! CHAR_BYTE8_P (c1
))
3647 re_wchar_t c2
= TRANSLATE (c1
);
3649 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3655 (*pending_exact
) += len
;
3660 } /* while p != pend */
3663 /* Through the pattern now. */
3667 if (!COMPILE_STACK_EMPTY
)
3668 FREE_STACK_RETURN (REG_EPAREN
);
3670 /* If we don't want backtracking, force success
3671 the first time we reach the end of the compiled pattern. */
3672 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3675 /* We have succeeded; set the length of the buffer. */
3676 bufp
->used
= b
- bufp
->buffer
;
3681 re_compile_fastmap (bufp
);
3682 DEBUG_PRINT ("\nCompiled pattern: \n");
3683 print_compiled_pattern (bufp
);
3688 #ifndef MATCH_MAY_ALLOCATE
3689 /* Initialize the failure stack to the largest possible stack. This
3690 isn't necessary unless we're trying to avoid calling alloca in
3691 the search and match routines. */
3693 int num_regs
= bufp
->re_nsub
+ 1;
3695 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3697 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3698 falk_stack
.stack
= realloc (fail_stack
.stack
,
3699 fail_stack
.size
* sizeof *falk_stack
.stack
);
3702 regex_grow_registers (num_regs
);
3704 #endif /* not MATCH_MAY_ALLOCATE */
3706 FREE_STACK_RETURN (REG_NOERROR
);
3707 } /* regex_compile */
3709 /* Subroutines for `regex_compile'. */
3711 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3714 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3716 *loc
= (unsigned char) op
;
3717 STORE_NUMBER (loc
+ 1, arg
);
3721 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3724 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3726 *loc
= (unsigned char) op
;
3727 STORE_NUMBER (loc
+ 1, arg1
);
3728 STORE_NUMBER (loc
+ 3, arg2
);
3732 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3733 for OP followed by two-byte integer parameter ARG. */
3736 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3738 register unsigned char *pfrom
= end
;
3739 register unsigned char *pto
= end
+ 3;
3741 while (pfrom
!= loc
)
3744 store_op1 (op
, loc
, arg
);
3748 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3751 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3753 register unsigned char *pfrom
= end
;
3754 register unsigned char *pto
= end
+ 5;
3756 while (pfrom
!= loc
)
3759 store_op2 (op
, loc
, arg1
, arg2
);
3763 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3764 after an alternative or a begin-subexpression. We assume there is at
3765 least one character before the ^. */
3768 at_begline_loc_p (const_re_char
*pattern
, const_re_char
*p
, reg_syntax_t syntax
)
3770 re_char
*prev
= p
- 2;
3771 boolean odd_backslashes
;
3773 /* After a subexpression? */
3775 odd_backslashes
= (syntax
& RE_NO_BK_PARENS
) == 0;
3777 /* After an alternative? */
3778 else if (*prev
== '|')
3779 odd_backslashes
= (syntax
& RE_NO_BK_VBAR
) == 0;
3781 /* After a shy subexpression? */
3782 else if (*prev
== ':' && (syntax
& RE_SHY_GROUPS
))
3784 /* Skip over optional regnum. */
3785 while (prev
- 1 >= pattern
&& prev
[-1] >= '0' && prev
[-1] <= '9')
3788 if (!(prev
- 2 >= pattern
3789 && prev
[-1] == '?' && prev
[-2] == '('))
3792 odd_backslashes
= (syntax
& RE_NO_BK_PARENS
) == 0;
3797 /* Count the number of preceding backslashes. */
3799 while (prev
- 1 >= pattern
&& prev
[-1] == '\\')
3801 return (p
- prev
) & odd_backslashes
;
3805 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3806 at least one character after the $, i.e., `P < PEND'. */
3809 at_endline_loc_p (const_re_char
*p
, const_re_char
*pend
, reg_syntax_t syntax
)
3812 boolean next_backslash
= *next
== '\\';
3813 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3816 /* Before a subexpression? */
3817 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3818 : next_backslash
&& next_next
&& *next_next
== ')')
3819 /* Before an alternative? */
3820 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3821 : next_backslash
&& next_next
&& *next_next
== '|');
3825 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3826 false if it's not. */
3829 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3831 ssize_t this_element
;
3833 for (this_element
= compile_stack
.avail
- 1;
3836 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3843 If fastmap is non-NULL, go through the pattern and fill fastmap
3844 with all the possible leading chars. If fastmap is NULL, don't
3845 bother filling it up (obviously) and only return whether the
3846 pattern could potentially match the empty string.
3848 Return 1 if p..pend might match the empty string.
3849 Return 0 if p..pend matches at least one char.
3850 Return -1 if fastmap was not updated accurately. */
3853 analyse_first (const_re_char
*p
, const_re_char
*pend
, char *fastmap
,
3854 const int multibyte
)
3859 /* If all elements for base leading-codes in fastmap is set, this
3860 flag is set true. */
3861 boolean match_any_multibyte_characters
= false;
3865 /* The loop below works as follows:
3866 - It has a working-list kept in the PATTERN_STACK and which basically
3867 starts by only containing a pointer to the first operation.
3868 - If the opcode we're looking at is a match against some set of
3869 chars, then we add those chars to the fastmap and go on to the
3870 next work element from the worklist (done via `break').
3871 - If the opcode is a control operator on the other hand, we either
3872 ignore it (if it's meaningless at this point, such as `start_memory')
3873 or execute it (if it's a jump). If the jump has several destinations
3874 (i.e. `on_failure_jump'), then we push the other destination onto the
3876 We guarantee termination by ignoring backward jumps (more or less),
3877 so that `p' is monotonically increasing. More to the point, we
3878 never set `p' (or push) anything `<= p1'. */
3882 /* `p1' is used as a marker of how far back a `on_failure_jump'
3883 can go without being ignored. It is normally equal to `p'
3884 (which prevents any backward `on_failure_jump') except right
3885 after a plain `jump', to allow patterns such as:
3888 10: on_failure_jump 3
3889 as used for the *? operator. */
3898 /* If the first character has to match a backreference, that means
3899 that the group was empty (since it already matched). Since this
3900 is the only case that interests us here, we can assume that the
3901 backreference must match the empty string. */
3906 /* Following are the cases which match a character. These end
3912 /* If multibyte is nonzero, the first byte of each
3913 character is an ASCII or a leading code. Otherwise,
3914 each byte is a character. Thus, this works in both
3919 /* For the case of matching this unibyte regex
3920 against multibyte, we must set a leading code of
3921 the corresponding multibyte character. */
3922 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
3924 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
3931 /* We could put all the chars except for \n (and maybe \0)
3932 but we don't bother since it is generally not worth it. */
3933 if (!fastmap
) break;
3938 if (!fastmap
) break;
3940 /* Chars beyond end of bitmap are possible matches. */
3941 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3942 j
< (1 << BYTEWIDTH
); j
++)
3948 if (!fastmap
) break;
3949 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3950 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3952 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3956 if (/* Any leading code can possibly start a character
3957 which doesn't match the specified set of characters. */
3960 /* If we can match a character class, we can match any
3961 multibyte characters. */
3962 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3963 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3966 if (match_any_multibyte_characters
== false)
3968 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
3969 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
3971 match_any_multibyte_characters
= true;
3975 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3976 && match_any_multibyte_characters
== false)
3978 /* Set fastmap[I] to 1 where I is a leading code of each
3979 multibyte character in the range table. */
3981 unsigned char lc1
, lc2
;
3983 /* Make P points the range table. `+ 2' is to skip flag
3984 bits for a character class. */
3985 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3987 /* Extract the number of ranges in range table into COUNT. */
3988 EXTRACT_NUMBER_AND_INCR (count
, p
);
3989 for (; count
> 0; count
--, p
+= 3)
3991 /* Extract the start and end of each range. */
3992 EXTRACT_CHARACTER (c
, p
);
3993 lc1
= CHAR_LEADING_CODE (c
);
3995 EXTRACT_CHARACTER (c
, p
);
3996 lc2
= CHAR_LEADING_CODE (c
);
3997 for (j
= lc1
; j
<= lc2
; j
++)
4006 if (!fastmap
) break;
4008 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
4010 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4011 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4015 /* This match depends on text properties. These end with
4016 aborting optimizations. */
4020 case notcategoryspec
:
4021 if (!fastmap
) break;
4022 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4024 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
4025 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4028 /* Any leading code can possibly start a character which
4029 has or doesn't has the specified category. */
4030 if (match_any_multibyte_characters
== false)
4032 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4033 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4035 match_any_multibyte_characters
= true;
4039 /* All cases after this match the empty string. These end with
4061 EXTRACT_NUMBER_AND_INCR (j
, p
);
4063 /* Backward jumps can only go back to code that we've already
4064 visited. `re_compile' should make sure this is true. */
4069 case on_failure_jump
:
4070 case on_failure_keep_string_jump
:
4071 case on_failure_jump_loop
:
4072 case on_failure_jump_nastyloop
:
4073 case on_failure_jump_smart
:
4079 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4080 to jump back to "just after here". */
4083 case on_failure_jump
:
4084 case on_failure_keep_string_jump
:
4085 case on_failure_jump_nastyloop
:
4086 case on_failure_jump_loop
:
4087 case on_failure_jump_smart
:
4088 EXTRACT_NUMBER_AND_INCR (j
, p
);
4090 ; /* Backward jump to be ignored. */
4092 { /* We have to look down both arms.
4093 We first go down the "straight" path so as to minimize
4094 stack usage when going through alternatives. */
4095 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4103 /* This code simply does not properly handle forward jump_n. */
4104 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4106 /* jump_n can either jump or fall through. The (backward) jump
4107 case has already been handled, so we only need to look at the
4108 fallthrough case. */
4112 /* If N == 0, it should be an on_failure_jump_loop instead. */
4113 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4115 /* We only care about one iteration of the loop, so we don't
4116 need to consider the case where this behaves like an
4133 abort (); /* We have listed all the cases. */
4136 /* Getting here means we have found the possible starting
4137 characters for one path of the pattern -- and that the empty
4138 string does not match. We need not follow this path further. */
4142 /* We reached the end without matching anything. */
4145 } /* analyse_first */
4147 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4148 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4149 characters can start a string that matches the pattern. This fastmap
4150 is used by re_search to skip quickly over impossible starting points.
4152 Character codes above (1 << BYTEWIDTH) are not represented in the
4153 fastmap, but the leading codes are represented. Thus, the fastmap
4154 indicates which character sets could start a match.
4156 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4157 area as BUFP->fastmap.
4159 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4162 Returns 0 if we succeed, -2 if an internal error. */
4165 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4167 char *fastmap
= bufp
->fastmap
;
4170 assert (fastmap
&& bufp
->buffer
);
4172 memset (fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4173 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4175 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4176 fastmap
, RE_MULTIBYTE_P (bufp
));
4177 bufp
->can_be_null
= (analysis
!= 0);
4179 } /* re_compile_fastmap */
4181 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4182 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4183 this memory for recording register information. STARTS and ENDS
4184 must be allocated using the malloc library routine, and must each
4185 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4187 If NUM_REGS == 0, then subsequent matches should allocate their own
4190 Unless this function is called, the first search or match using
4191 PATTERN_BUFFER will allocate its own register data, without
4192 freeing the old data. */
4195 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4199 bufp
->regs_allocated
= REGS_REALLOCATE
;
4200 regs
->num_regs
= num_regs
;
4201 regs
->start
= starts
;
4206 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4208 regs
->start
= regs
->end
= 0;
4211 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4213 /* Searching routines. */
4215 /* Like re_search_2, below, but only one string is specified, and
4216 doesn't let you say where to stop matching. */
4219 re_search (struct re_pattern_buffer
*bufp
, const char *string
, size_t size
,
4220 ssize_t startpos
, ssize_t range
, struct re_registers
*regs
)
4222 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4225 WEAK_ALIAS (__re_search
, re_search
)
4227 /* Head address of virtual concatenation of string. */
4228 #define HEAD_ADDR_VSTRING(P) \
4229 (((P) >= size1 ? string2 : string1))
4231 /* Address of POS in the concatenation of virtual string. */
4232 #define POS_ADDR_VSTRING(POS) \
4233 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4235 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4236 virtual concatenation of STRING1 and STRING2, starting first at index
4237 STARTPOS, then at STARTPOS + 1, and so on.
4239 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4241 RANGE is how far to scan while trying to match. RANGE = 0 means try
4242 only at STARTPOS; in general, the last start tried is STARTPOS +
4245 In REGS, return the indices of the virtual concatenation of STRING1
4246 and STRING2 that matched the entire BUFP->buffer and its contained
4249 Do not consider matching one past the index STOP in the virtual
4250 concatenation of STRING1 and STRING2.
4252 We return either the position in the strings at which the match was
4253 found, -1 if no match, or -2 if error (such as failure
4257 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, size_t size1
,
4258 const char *str2
, size_t size2
, ssize_t startpos
, ssize_t range
,
4259 struct re_registers
*regs
, ssize_t stop
)
4262 re_char
*string1
= (re_char
*) str1
;
4263 re_char
*string2
= (re_char
*) str2
;
4264 register char *fastmap
= bufp
->fastmap
;
4265 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4266 size_t total_size
= size1
+ size2
;
4267 ssize_t endpos
= startpos
+ range
;
4268 boolean anchored_start
;
4269 /* Nonzero if we are searching multibyte string. */
4270 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4272 /* Check for out-of-range STARTPOS. */
4273 if (startpos
< 0 || startpos
> total_size
)
4276 /* Fix up RANGE if it might eventually take us outside
4277 the virtual concatenation of STRING1 and STRING2.
4278 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4280 range
= 0 - startpos
;
4281 else if (endpos
> total_size
)
4282 range
= total_size
- startpos
;
4284 /* If the search isn't to be a backwards one, don't waste time in a
4285 search for a pattern anchored at beginning of buffer. */
4286 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4295 /* In a forward search for something that starts with \=.
4296 don't keep searching past point. */
4297 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4299 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4305 /* Update the fastmap now if not correct already. */
4306 if (fastmap
&& !bufp
->fastmap_accurate
)
4307 re_compile_fastmap (bufp
);
4309 /* See whether the pattern is anchored. */
4310 anchored_start
= (bufp
->buffer
[0] == begline
);
4313 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4315 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4317 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4321 /* Loop through the string, looking for a place to start matching. */
4324 /* If the pattern is anchored,
4325 skip quickly past places we cannot match.
4326 We don't bother to treat startpos == 0 specially
4327 because that case doesn't repeat. */
4328 if (anchored_start
&& startpos
> 0)
4330 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4331 : string2
[startpos
- size1
- 1])
4336 /* If a fastmap is supplied, skip quickly over characters that
4337 cannot be the start of a match. If the pattern can match the
4338 null string, however, we don't need to skip characters; we want
4339 the first null string. */
4340 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4342 register re_char
*d
;
4343 register re_wchar_t buf_ch
;
4345 d
= POS_ADDR_VSTRING (startpos
);
4347 if (range
> 0) /* Searching forwards. */
4349 register int lim
= 0;
4350 ssize_t irange
= range
;
4352 if (startpos
< size1
&& startpos
+ range
>= size1
)
4353 lim
= range
- (size1
- startpos
);
4355 /* Written out as an if-else to avoid testing `translate'
4357 if (RE_TRANSLATE_P (translate
))
4364 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4365 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4366 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4369 range
-= buf_charlen
;
4375 register re_wchar_t ch
, translated
;
4378 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4379 translated
= RE_TRANSLATE (translate
, ch
);
4380 if (translated
!= ch
4381 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4383 if (fastmap
[buf_ch
])
4396 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4397 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4399 range
-= buf_charlen
;
4403 while (range
> lim
&& !fastmap
[*d
])
4409 startpos
+= irange
- range
;
4411 else /* Searching backwards. */
4415 buf_ch
= STRING_CHAR (d
);
4416 buf_ch
= TRANSLATE (buf_ch
);
4417 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4422 register re_wchar_t ch
, translated
;
4425 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4426 translated
= TRANSLATE (ch
);
4427 if (translated
!= ch
4428 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4430 if (! fastmap
[TRANSLATE (buf_ch
)])
4436 /* If can't match the null string, and that's all we have left, fail. */
4437 if (range
>= 0 && startpos
== total_size
&& fastmap
4438 && !bufp
->can_be_null
)
4441 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4442 startpos
, regs
, stop
);
4455 /* Update STARTPOS to the next character boundary. */
4458 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4459 int len
= BYTES_BY_CHAR_HEAD (*p
);
4477 /* Update STARTPOS to the previous character boundary. */
4480 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4482 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4484 /* Find the head of multibyte form. */
4485 PREV_CHAR_BOUNDARY (p
, phead
);
4486 range
+= p0
- 1 - p
;
4490 startpos
-= p0
- 1 - p
;
4496 WEAK_ALIAS (__re_search_2
, re_search_2
)
4498 /* Declarations and macros for re_match_2. */
4500 static int bcmp_translate (re_char
*s1
, re_char
*s2
,
4501 register ssize_t len
,
4502 RE_TRANSLATE_TYPE translate
,
4503 const int multibyte
);
4505 /* This converts PTR, a pointer into one of the search strings `string1'
4506 and `string2' into an offset from the beginning of that string. */
4507 #define POINTER_TO_OFFSET(ptr) \
4508 (FIRST_STRING_P (ptr) \
4510 : (ptr) - string2 + (ptrdiff_t) size1)
4512 /* Call before fetching a character with *d. This switches over to
4513 string2 if necessary.
4514 Check re_match_2_internal for a discussion of why end_match_2 might
4515 not be within string2 (but be equal to end_match_1 instead). */
4516 #define PREFETCH() \
4519 /* End of string2 => fail. */ \
4520 if (dend == end_match_2) \
4522 /* End of string1 => advance to string2. */ \
4524 dend = end_match_2; \
4527 /* Call before fetching a char with *d if you already checked other limits.
4528 This is meant for use in lookahead operations like wordend, etc..
4529 where we might need to look at parts of the string that might be
4530 outside of the LIMITs (i.e past `stop'). */
4531 #define PREFETCH_NOLIMIT() \
4535 dend = end_match_2; \
4538 /* Test if at very beginning or at very end of the virtual concatenation
4539 of `string1' and `string2'. If only one string, it's `string2'. */
4540 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4541 #define AT_STRINGS_END(d) ((d) == end2)
4543 /* Disabled due to a compiler bug -- see comment at case wordbound */
4545 /* The comment at case wordbound is following one, but we don't use
4546 AT_WORD_BOUNDARY anymore to support multibyte form.
4548 The DEC Alpha C compiler 3.x generates incorrect code for the
4549 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4550 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4551 macro and introducing temporary variables works around the bug. */
4554 /* Test if D points to a character which is word-constituent. We have
4555 two special cases to check for: if past the end of string1, look at
4556 the first character in string2; and if before the beginning of
4557 string2, look at the last character in string1. */
4558 #define WORDCHAR_P(d) \
4559 (SYNTAX ((d) == end1 ? *string2 \
4560 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4563 /* Test if the character before D and the one at D differ with respect
4564 to being word-constituent. */
4565 #define AT_WORD_BOUNDARY(d) \
4566 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4567 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4570 /* Free everything we malloc. */
4571 #ifdef MATCH_MAY_ALLOCATE
4572 # define FREE_VAR(var) \
4580 # define FREE_VARIABLES() \
4582 REGEX_FREE_STACK (fail_stack.stack); \
4583 FREE_VAR (regstart); \
4584 FREE_VAR (regend); \
4585 FREE_VAR (best_regstart); \
4586 FREE_VAR (best_regend); \
4589 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4590 #endif /* not MATCH_MAY_ALLOCATE */
4593 /* Optimization routines. */
4595 /* If the operation is a match against one or more chars,
4596 return a pointer to the next operation, else return NULL. */
4598 skip_one_char (const_re_char
*p
)
4611 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4614 p
= CHARSET_RANGE_TABLE (p
- 1);
4615 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4616 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4619 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4626 case notcategoryspec
:
4638 /* Jump over non-matching operations. */
4640 skip_noops (const_re_char
*p
, const_re_char
*pend
)
4654 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4665 /* Non-zero if "p1 matches something" implies "p2 fails". */
4667 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const_re_char
*p1
,
4671 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4672 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4674 assert (p1
>= bufp
->buffer
&& p1
< pend
4675 && p2
>= bufp
->buffer
&& p2
<= pend
);
4677 /* Skip over open/close-group commands.
4678 If what follows this loop is a ...+ construct,
4679 look at what begins its body, since we will have to
4680 match at least one of that. */
4681 p2
= skip_noops (p2
, pend
);
4682 /* The same skip can be done for p1, except that this function
4683 is only used in the case where p1 is a simple match operator. */
4684 /* p1 = skip_noops (p1, pend); */
4686 assert (p1
>= bufp
->buffer
&& p1
< pend
4687 && p2
>= bufp
->buffer
&& p2
<= pend
);
4689 op2
= p2
== pend
? succeed
: *p2
;
4695 /* If we're at the end of the pattern, we can change. */
4696 if (skip_one_char (p1
))
4698 DEBUG_PRINT (" End of pattern: fast loop.\n");
4706 register re_wchar_t c
4707 = (re_opcode_t
) *p2
== endline
? '\n'
4708 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4710 if ((re_opcode_t
) *p1
== exactn
)
4712 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4714 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4719 else if ((re_opcode_t
) *p1
== charset
4720 || (re_opcode_t
) *p1
== charset_not
)
4722 int not = (re_opcode_t
) *p1
== charset_not
;
4724 /* Test if C is listed in charset (or charset_not)
4726 if (! multibyte
|| IS_REAL_ASCII (c
))
4728 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4729 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4732 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4733 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4735 /* `not' is equal to 1 if c would match, which means
4736 that we can't change to pop_failure_jump. */
4739 DEBUG_PRINT (" No match => fast loop.\n");
4743 else if ((re_opcode_t
) *p1
== anychar
4746 DEBUG_PRINT (" . != \\n => fast loop.\n");
4754 if ((re_opcode_t
) *p1
== exactn
)
4755 /* Reuse the code above. */
4756 return mutually_exclusive_p (bufp
, p2
, p1
);
4758 /* It is hard to list up all the character in charset
4759 P2 if it includes multibyte character. Give up in
4761 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4763 /* Now, we are sure that P2 has no range table.
4764 So, for the size of bitmap in P2, `p2[1]' is
4765 enough. But P1 may have range table, so the
4766 size of bitmap table of P1 is extracted by
4767 using macro `CHARSET_BITMAP_SIZE'.
4769 In a multibyte case, we know that all the character
4770 listed in P2 is ASCII. In a unibyte case, P1 has only a
4771 bitmap table. So, in both cases, it is enough to test
4772 only the bitmap table of P1. */
4774 if ((re_opcode_t
) *p1
== charset
)
4777 /* We win if the charset inside the loop
4778 has no overlap with the one after the loop. */
4781 && idx
< CHARSET_BITMAP_SIZE (p1
));
4783 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4787 || idx
== CHARSET_BITMAP_SIZE (p1
))
4789 DEBUG_PRINT (" No match => fast loop.\n");
4793 else if ((re_opcode_t
) *p1
== charset_not
)
4796 /* We win if the charset_not inside the loop lists
4797 every character listed in the charset after. */
4798 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4799 if (! (p2
[2 + idx
] == 0
4800 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4801 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4806 DEBUG_PRINT (" No match => fast loop.\n");
4819 /* Reuse the code above. */
4820 return mutually_exclusive_p (bufp
, p2
, p1
);
4822 /* When we have two charset_not, it's very unlikely that
4823 they don't overlap. The union of the two sets of excluded
4824 chars should cover all possible chars, which, as a matter of
4825 fact, is virtually impossible in multibyte buffers. */
4831 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4833 return ((re_opcode_t
) *p1
== syntaxspec
4834 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4836 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4839 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4841 return ((re_opcode_t
) *p1
== notsyntaxspec
4842 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4844 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4847 return (((re_opcode_t
) *p1
== notsyntaxspec
4848 || (re_opcode_t
) *p1
== syntaxspec
)
4853 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4854 case notcategoryspec
:
4855 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4867 /* Matching routines. */
4869 #ifndef emacs /* Emacs never uses this. */
4870 /* re_match is like re_match_2 except it takes only a single string. */
4873 re_match (struct re_pattern_buffer
*bufp
, const char *string
,
4874 size_t size
, ssize_t pos
, struct re_registers
*regs
)
4876 regoff_t result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
,
4877 size
, pos
, regs
, size
);
4880 WEAK_ALIAS (__re_match
, re_match
)
4881 #endif /* not emacs */
4884 /* In Emacs, this is the string or buffer in which we
4885 are matching. It is used for looking up syntax properties. */
4886 Lisp_Object re_match_object
;
4889 /* re_match_2 matches the compiled pattern in BUFP against the
4890 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4891 and SIZE2, respectively). We start matching at POS, and stop
4894 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4895 store offsets for the substring each group matched in REGS. See the
4896 documentation for exactly how many groups we fill.
4898 We return -1 if no match, -2 if an internal error (such as the
4899 failure stack overflowing). Otherwise, we return the length of the
4900 matched substring. */
4903 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
,
4904 size_t size1
, const char *string2
, size_t size2
, ssize_t pos
,
4905 struct re_registers
*regs
, ssize_t stop
)
4911 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4912 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4913 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4916 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4917 (re_char
*) string2
, size2
,
4921 WEAK_ALIAS (__re_match_2
, re_match_2
)
4924 /* This is a separate function so that we can force an alloca cleanup
4927 re_match_2_internal (struct re_pattern_buffer
*bufp
, const_re_char
*string1
,
4928 size_t size1
, const_re_char
*string2
, size_t size2
,
4929 ssize_t pos
, struct re_registers
*regs
, ssize_t stop
)
4931 /* General temporaries. */
4935 /* Just past the end of the corresponding string. */
4936 re_char
*end1
, *end2
;
4938 /* Pointers into string1 and string2, just past the last characters in
4939 each to consider matching. */
4940 re_char
*end_match_1
, *end_match_2
;
4942 /* Where we are in the data, and the end of the current string. */
4945 /* Used sometimes to remember where we were before starting matching
4946 an operator so that we can go back in case of failure. This "atomic"
4947 behavior of matching opcodes is indispensable to the correctness
4948 of the on_failure_keep_string_jump optimization. */
4951 /* Where we are in the pattern, and the end of the pattern. */
4952 re_char
*p
= bufp
->buffer
;
4953 re_char
*pend
= p
+ bufp
->used
;
4955 /* We use this to map every character in the string. */
4956 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4958 /* Nonzero if BUFP is setup from a multibyte regex. */
4959 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4961 /* Nonzero if STRING1/STRING2 are multibyte. */
4962 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4964 /* Failure point stack. Each place that can handle a failure further
4965 down the line pushes a failure point on this stack. It consists of
4966 regstart, and regend for all registers corresponding to
4967 the subexpressions we're currently inside, plus the number of such
4968 registers, and, finally, two char *'s. The first char * is where
4969 to resume scanning the pattern; the second one is where to resume
4970 scanning the strings. */
4971 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4972 fail_stack_type fail_stack
;
4974 #ifdef DEBUG_COMPILES_ARGUMENTS
4975 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4978 #if defined REL_ALLOC && defined REGEX_MALLOC
4979 /* This holds the pointer to the failure stack, when
4980 it is allocated relocatably. */
4981 fail_stack_elt_t
*failure_stack_ptr
;
4984 /* We fill all the registers internally, independent of what we
4985 return, for use in backreferences. The number here includes
4986 an element for register zero. */
4987 size_t num_regs
= bufp
->re_nsub
+ 1;
4989 /* Information on the contents of registers. These are pointers into
4990 the input strings; they record just what was matched (on this
4991 attempt) by a subexpression part of the pattern, that is, the
4992 regnum-th regstart pointer points to where in the pattern we began
4993 matching and the regnum-th regend points to right after where we
4994 stopped matching the regnum-th subexpression. (The zeroth register
4995 keeps track of what the whole pattern matches.) */
4996 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4997 re_char
**regstart
, **regend
;
5000 /* The following record the register info as found in the above
5001 variables when we find a match better than any we've seen before.
5002 This happens as we backtrack through the failure points, which in
5003 turn happens only if we have not yet matched the entire string. */
5004 unsigned best_regs_set
= false;
5005 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5006 re_char
**best_regstart
, **best_regend
;
5009 /* Logically, this is `best_regend[0]'. But we don't want to have to
5010 allocate space for that if we're not allocating space for anything
5011 else (see below). Also, we never need info about register 0 for
5012 any of the other register vectors, and it seems rather a kludge to
5013 treat `best_regend' differently than the rest. So we keep track of
5014 the end of the best match so far in a separate variable. We
5015 initialize this to NULL so that when we backtrack the first time
5016 and need to test it, it's not garbage. */
5017 re_char
*match_end
= NULL
;
5019 #ifdef DEBUG_COMPILES_ARGUMENTS
5020 /* Counts the total number of registers pushed. */
5021 unsigned num_regs_pushed
= 0;
5024 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5028 #ifdef MATCH_MAY_ALLOCATE
5029 /* Do not bother to initialize all the register variables if there are
5030 no groups in the pattern, as it takes a fair amount of time. If
5031 there are groups, we include space for register 0 (the whole
5032 pattern), even though we never use it, since it simplifies the
5033 array indexing. We should fix this. */
5036 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5037 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5038 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5039 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5041 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5049 /* We must initialize all our variables to NULL, so that
5050 `FREE_VARIABLES' doesn't try to free them. */
5051 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5053 #endif /* MATCH_MAY_ALLOCATE */
5055 /* The starting position is bogus. */
5056 if (pos
< 0 || pos
> size1
+ size2
)
5062 /* Initialize subexpression text positions to -1 to mark ones that no
5063 start_memory/stop_memory has been seen for. Also initialize the
5064 register information struct. */
5065 for (reg
= 1; reg
< num_regs
; reg
++)
5066 regstart
[reg
] = regend
[reg
] = NULL
;
5068 /* We move `string1' into `string2' if the latter's empty -- but not if
5069 `string1' is null. */
5070 if (size2
== 0 && string1
!= NULL
)
5077 end1
= string1
+ size1
;
5078 end2
= string2
+ size2
;
5080 /* `p' scans through the pattern as `d' scans through the data.
5081 `dend' is the end of the input string that `d' points within. `d'
5082 is advanced into the following input string whenever necessary, but
5083 this happens before fetching; therefore, at the beginning of the
5084 loop, `d' can be pointing at the end of a string, but it cannot
5088 /* Only match within string2. */
5089 d
= string2
+ pos
- size1
;
5090 dend
= end_match_2
= string2
+ stop
- size1
;
5091 end_match_1
= end1
; /* Just to give it a value. */
5097 /* Only match within string1. */
5098 end_match_1
= string1
+ stop
;
5100 When we reach end_match_1, PREFETCH normally switches to string2.
5101 But in the present case, this means that just doing a PREFETCH
5102 makes us jump from `stop' to `gap' within the string.
5103 What we really want here is for the search to stop as
5104 soon as we hit end_match_1. That's why we set end_match_2
5105 to end_match_1 (since PREFETCH fails as soon as we hit
5107 end_match_2
= end_match_1
;
5110 { /* It's important to use this code when stop == size so that
5111 moving `d' from end1 to string2 will not prevent the d == dend
5112 check from catching the end of string. */
5114 end_match_2
= string2
+ stop
- size1
;
5120 DEBUG_PRINT ("The compiled pattern is: ");
5121 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5122 DEBUG_PRINT ("The string to match is: `");
5123 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5124 DEBUG_PRINT ("'\n");
5126 /* This loops over pattern commands. It exits by returning from the
5127 function if the match is complete, or it drops through if the match
5128 fails at this starting point in the input data. */
5131 DEBUG_PRINT ("\n%p: ", p
);
5137 /* End of pattern means we might have succeeded. */
5138 DEBUG_PRINT ("end of pattern ... ");
5140 /* If we haven't matched the entire string, and we want the
5141 longest match, try backtracking. */
5142 if (d
!= end_match_2
)
5144 /* 1 if this match ends in the same string (string1 or string2)
5145 as the best previous match. */
5146 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5147 == FIRST_STRING_P (d
));
5148 /* 1 if this match is the best seen so far. */
5149 boolean best_match_p
;
5151 /* AIX compiler got confused when this was combined
5152 with the previous declaration. */
5154 best_match_p
= d
> match_end
;
5156 best_match_p
= !FIRST_STRING_P (d
);
5158 DEBUG_PRINT ("backtracking.\n");
5160 if (!FAIL_STACK_EMPTY ())
5161 { /* More failure points to try. */
5163 /* If exceeds best match so far, save it. */
5164 if (!best_regs_set
|| best_match_p
)
5166 best_regs_set
= true;
5169 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5171 for (reg
= 1; reg
< num_regs
; reg
++)
5173 best_regstart
[reg
] = regstart
[reg
];
5174 best_regend
[reg
] = regend
[reg
];
5180 /* If no failure points, don't restore garbage. And if
5181 last match is real best match, don't restore second
5183 else if (best_regs_set
&& !best_match_p
)
5186 /* Restore best match. It may happen that `dend ==
5187 end_match_1' while the restored d is in string2.
5188 For example, the pattern `x.*y.*z' against the
5189 strings `x-' and `y-z-', if the two strings are
5190 not consecutive in memory. */
5191 DEBUG_PRINT ("Restoring best registers.\n");
5194 dend
= ((d
>= string1
&& d
<= end1
)
5195 ? end_match_1
: end_match_2
);
5197 for (reg
= 1; reg
< num_regs
; reg
++)
5199 regstart
[reg
] = best_regstart
[reg
];
5200 regend
[reg
] = best_regend
[reg
];
5203 } /* d != end_match_2 */
5206 DEBUG_PRINT ("Accepting match.\n");
5208 /* If caller wants register contents data back, do it. */
5209 if (regs
&& !bufp
->no_sub
)
5211 /* Have the register data arrays been allocated? */
5212 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5213 { /* No. So allocate them with malloc. We need one
5214 extra element beyond `num_regs' for the `-1' marker
5216 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5217 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5218 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5219 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5224 bufp
->regs_allocated
= REGS_REALLOCATE
;
5226 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5227 { /* Yes. If we need more elements than were already
5228 allocated, reallocate them. If we need fewer, just
5230 if (regs
->num_regs
< num_regs
+ 1)
5232 regs
->num_regs
= num_regs
+ 1;
5233 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5234 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5235 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5244 /* These braces fend off a "empty body in an else-statement"
5245 warning under GCC when assert expands to nothing. */
5246 assert (bufp
->regs_allocated
== REGS_FIXED
);
5249 /* Convert the pointer data in `regstart' and `regend' to
5250 indices. Register zero has to be set differently,
5251 since we haven't kept track of any info for it. */
5252 if (regs
->num_regs
> 0)
5254 regs
->start
[0] = pos
;
5255 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5258 /* Go through the first `min (num_regs, regs->num_regs)'
5259 registers, since that is all we initialized. */
5260 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5262 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5263 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5266 regs
->start
[reg
] = POINTER_TO_OFFSET (regstart
[reg
]);
5267 regs
->end
[reg
] = POINTER_TO_OFFSET (regend
[reg
]);
5271 /* If the regs structure we return has more elements than
5272 were in the pattern, set the extra elements to -1. If
5273 we (re)allocated the registers, this is the case,
5274 because we always allocate enough to have at least one
5276 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5277 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5278 } /* regs && !bufp->no_sub */
5280 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5281 nfailure_points_pushed
, nfailure_points_popped
,
5282 nfailure_points_pushed
- nfailure_points_popped
);
5283 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed
);
5285 dcnt
= POINTER_TO_OFFSET (d
) - pos
;
5287 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt
);
5293 /* Otherwise match next pattern command. */
5296 /* Ignore these. Used to ignore the n of succeed_n's which
5297 currently have n == 0. */
5299 DEBUG_PRINT ("EXECUTING no_op.\n");
5303 DEBUG_PRINT ("EXECUTING succeed.\n");
5306 /* Match the next n pattern characters exactly. The following
5307 byte in the pattern defines n, and the n bytes after that
5308 are the characters to match. */
5311 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt
);
5313 /* Remember the start point to rollback upon failure. */
5317 /* This is written out as an if-else so we don't waste time
5318 testing `translate' inside the loop. */
5319 if (RE_TRANSLATE_P (translate
))
5323 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5343 /* The cost of testing `translate' is comparatively small. */
5344 if (target_multibyte
)
5347 int pat_charlen
, buf_charlen
;
5352 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5355 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5358 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5360 if (TRANSLATE (buf_ch
) != pat_ch
)
5368 mcnt
-= pat_charlen
;
5380 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5381 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5388 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5389 if (! CHAR_BYTE8_P (buf_ch
))
5391 buf_ch
= TRANSLATE (buf_ch
);
5392 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5398 if (buf_ch
!= pat_ch
)
5411 /* Match any character except possibly a newline or a null. */
5417 DEBUG_PRINT ("EXECUTING anychar.\n");
5420 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5422 buf_ch
= TRANSLATE (buf_ch
);
5424 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5426 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5427 && buf_ch
== '\000'))
5430 DEBUG_PRINT (" Matched `%d'.\n", *d
);
5439 register unsigned int c
;
5440 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5443 /* Start of actual range_table, or end of bitmap if there is no
5445 re_char
*range_table
IF_LINT (= NULL
);
5447 /* Nonzero if there is a range table. */
5448 int range_table_exists
;
5450 /* Number of ranges of range table. This is not included
5451 in the initial byte-length of the command. */
5454 /* Whether matching against a unibyte character. */
5455 boolean unibyte_char
= false;
5457 DEBUG_PRINT ("EXECUTING charset%s.\n", not ? "_not" : "");
5459 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5461 if (range_table_exists
)
5463 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5464 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5468 c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5469 if (target_multibyte
)
5474 c1
= RE_CHAR_TO_UNIBYTE (c
);
5477 unibyte_char
= true;
5483 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5485 if (! CHAR_BYTE8_P (c1
))
5487 c1
= TRANSLATE (c1
);
5488 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5491 unibyte_char
= true;
5496 unibyte_char
= true;
5499 if (unibyte_char
&& c
< (1 << BYTEWIDTH
))
5500 { /* Lookup bitmap. */
5501 /* Cast to `unsigned' instead of `unsigned char' in
5502 case the bit list is a full 32 bytes long. */
5503 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5504 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5508 else if (range_table_exists
)
5510 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5512 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5513 | (class_bits
& BIT_MULTIBYTE
)
5514 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5515 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5516 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5517 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5520 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5524 if (range_table_exists
)
5525 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5527 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5529 if (!not) goto fail
;
5536 /* The beginning of a group is represented by start_memory.
5537 The argument is the register number. The text
5538 matched within the group is recorded (in the internal
5539 registers data structure) under the register number. */
5541 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p
);
5543 /* In case we need to undo this operation (via backtracking). */
5544 PUSH_FAILURE_REG (*p
);
5547 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5548 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart
[*p
]));
5550 /* Move past the register number and inner group count. */
5555 /* The stop_memory opcode represents the end of a group. Its
5556 argument is the same as start_memory's: the register number. */
5558 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p
);
5560 assert (!REG_UNSET (regstart
[*p
]));
5561 /* Strictly speaking, there should be code such as:
5563 assert (REG_UNSET (regend[*p]));
5564 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5566 But the only info to be pushed is regend[*p] and it is known to
5567 be UNSET, so there really isn't anything to push.
5568 Not pushing anything, on the other hand deprives us from the
5569 guarantee that regend[*p] is UNSET since undoing this operation
5570 will not reset its value properly. This is not important since
5571 the value will only be read on the next start_memory or at
5572 the very end and both events can only happen if this stop_memory
5576 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend
[*p
]));
5578 /* Move past the register number and the inner group count. */
5583 /* \<digit> has been turned into a `duplicate' command which is
5584 followed by the numeric value of <digit> as the register number. */
5587 register re_char
*d2
, *dend2
;
5588 int regno
= *p
++; /* Get which register to match against. */
5589 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno
);
5591 /* Can't back reference a group which we've never matched. */
5592 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5595 /* Where in input to try to start matching. */
5596 d2
= regstart
[regno
];
5598 /* Remember the start point to rollback upon failure. */
5601 /* Where to stop matching; if both the place to start and
5602 the place to stop matching are in the same string, then
5603 set to the place to stop, otherwise, for now have to use
5604 the end of the first string. */
5606 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5607 == FIRST_STRING_P (regend
[regno
]))
5608 ? regend
[regno
] : end_match_1
);
5613 /* If necessary, advance to next segment in register
5617 if (dend2
== end_match_2
) break;
5618 if (dend2
== regend
[regno
]) break;
5620 /* End of string1 => advance to string2. */
5622 dend2
= regend
[regno
];
5624 /* At end of register contents => success */
5625 if (d2
== dend2
) break;
5627 /* If necessary, advance to next segment in data. */
5630 /* How many characters left in this segment to match. */
5633 /* Want how many consecutive characters we can match in
5634 one shot, so, if necessary, adjust the count. */
5635 if (dcnt
> dend2
- d2
)
5638 /* Compare that many; failure if mismatch, else move
5640 if (RE_TRANSLATE_P (translate
)
5641 ? bcmp_translate (d
, d2
, dcnt
, translate
, target_multibyte
)
5642 : memcmp (d
, d2
, dcnt
))
5647 d
+= dcnt
, d2
+= dcnt
;
5653 /* begline matches the empty string at the beginning of the string
5654 (unless `not_bol' is set in `bufp'), and after newlines. */
5656 DEBUG_PRINT ("EXECUTING begline.\n");
5658 if (AT_STRINGS_BEG (d
))
5660 if (!bufp
->not_bol
) break;
5665 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5669 /* In all other cases, we fail. */
5673 /* endline is the dual of begline. */
5675 DEBUG_PRINT ("EXECUTING endline.\n");
5677 if (AT_STRINGS_END (d
))
5679 if (!bufp
->not_eol
) break;
5683 PREFETCH_NOLIMIT ();
5690 /* Match at the very beginning of the data. */
5692 DEBUG_PRINT ("EXECUTING begbuf.\n");
5693 if (AT_STRINGS_BEG (d
))
5698 /* Match at the very end of the data. */
5700 DEBUG_PRINT ("EXECUTING endbuf.\n");
5701 if (AT_STRINGS_END (d
))
5706 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5707 pushes NULL as the value for the string on the stack. Then
5708 `POP_FAILURE_POINT' will keep the current value for the
5709 string, instead of restoring it. To see why, consider
5710 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5711 then the . fails against the \n. But the next thing we want
5712 to do is match the \n against the \n; if we restored the
5713 string value, we would be back at the foo.
5715 Because this is used only in specific cases, we don't need to
5716 check all the things that `on_failure_jump' does, to make
5717 sure the right things get saved on the stack. Hence we don't
5718 share its code. The only reason to push anything on the
5719 stack at all is that otherwise we would have to change
5720 `anychar's code to do something besides goto fail in this
5721 case; that seems worse than this. */
5722 case on_failure_keep_string_jump
:
5723 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5724 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5727 PUSH_FAILURE_POINT (p
- 3, NULL
);
5730 /* A nasty loop is introduced by the non-greedy *? and +?.
5731 With such loops, the stack only ever contains one failure point
5732 at a time, so that a plain on_failure_jump_loop kind of
5733 cycle detection cannot work. Worse yet, such a detection
5734 can not only fail to detect a cycle, but it can also wrongly
5735 detect a cycle (between different instantiations of the same
5737 So the method used for those nasty loops is a little different:
5738 We use a special cycle-detection-stack-frame which is pushed
5739 when the on_failure_jump_nastyloop failure-point is *popped*.
5740 This special frame thus marks the beginning of one iteration
5741 through the loop and we can hence easily check right here
5742 whether something matched between the beginning and the end of
5744 case on_failure_jump_nastyloop
:
5745 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5746 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5749 assert ((re_opcode_t
)p
[-4] == no_op
);
5752 CHECK_INFINITE_LOOP (p
- 4, d
);
5754 /* If there's a cycle, just continue without pushing
5755 this failure point. The failure point is the "try again"
5756 option, which shouldn't be tried.
5757 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5758 PUSH_FAILURE_POINT (p
- 3, d
);
5762 /* Simple loop detecting on_failure_jump: just check on the
5763 failure stack if the same spot was already hit earlier. */
5764 case on_failure_jump_loop
:
5766 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5767 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5771 CHECK_INFINITE_LOOP (p
- 3, d
);
5773 /* If there's a cycle, get out of the loop, as if the matching
5774 had failed. We used to just `goto fail' here, but that was
5775 aborting the search a bit too early: we want to keep the
5776 empty-loop-match and keep matching after the loop.
5777 We want (x?)*y\1z to match both xxyz and xxyxz. */
5780 PUSH_FAILURE_POINT (p
- 3, d
);
5785 /* Uses of on_failure_jump:
5787 Each alternative starts with an on_failure_jump that points
5788 to the beginning of the next alternative. Each alternative
5789 except the last ends with a jump that in effect jumps past
5790 the rest of the alternatives. (They really jump to the
5791 ending jump of the following alternative, because tensioning
5792 these jumps is a hassle.)
5794 Repeats start with an on_failure_jump that points past both
5795 the repetition text and either the following jump or
5796 pop_failure_jump back to this on_failure_jump. */
5797 case on_failure_jump
:
5798 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5799 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5802 PUSH_FAILURE_POINT (p
-3, d
);
5805 /* This operation is used for greedy *.
5806 Compare the beginning of the repeat with what in the
5807 pattern follows its end. If we can establish that there
5808 is nothing that they would both match, i.e., that we
5809 would have to backtrack because of (as in, e.g., `a*a')
5810 then we can use a non-backtracking loop based on
5811 on_failure_keep_string_jump instead of on_failure_jump. */
5812 case on_failure_jump_smart
:
5813 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5814 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5817 re_char
*p1
= p
; /* Next operation. */
5818 /* Here, we discard `const', making re_match non-reentrant. */
5819 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5820 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5822 p
-= 3; /* Reset so that we will re-execute the
5823 instruction once it's been changed. */
5825 EXTRACT_NUMBER (mcnt
, p2
- 2);
5827 /* Ensure this is a indeed the trivial kind of loop
5828 we are expecting. */
5829 assert (skip_one_char (p1
) == p2
- 3);
5830 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5831 DEBUG_STATEMENT (debug
+= 2);
5832 if (mutually_exclusive_p (bufp
, p1
, p2
))
5834 /* Use a fast `on_failure_keep_string_jump' loop. */
5835 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5836 *p3
= (unsigned char) on_failure_keep_string_jump
;
5837 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5841 /* Default to a safe `on_failure_jump' loop. */
5842 DEBUG_PRINT (" smart default => slow loop.\n");
5843 *p3
= (unsigned char) on_failure_jump
;
5845 DEBUG_STATEMENT (debug
-= 2);
5849 /* Unconditionally jump (without popping any failure points). */
5852 IMMEDIATE_QUIT_CHECK
;
5853 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5854 DEBUG_PRINT ("EXECUTING jump %d ", mcnt
);
5855 p
+= mcnt
; /* Do the jump. */
5856 DEBUG_PRINT ("(to %p).\n", p
);
5860 /* Have to succeed matching what follows at least n times.
5861 After that, handle like `on_failure_jump'. */
5863 /* Signedness doesn't matter since we only compare MCNT to 0. */
5864 EXTRACT_NUMBER (mcnt
, p
+ 2);
5865 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt
);
5867 /* Originally, mcnt is how many times we HAVE to succeed. */
5870 /* Here, we discard `const', making re_match non-reentrant. */
5871 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5874 PUSH_NUMBER (p2
, mcnt
);
5877 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5882 /* Signedness doesn't matter since we only compare MCNT to 0. */
5883 EXTRACT_NUMBER (mcnt
, p
+ 2);
5884 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt
);
5886 /* Originally, this is how many times we CAN jump. */
5889 /* Here, we discard `const', making re_match non-reentrant. */
5890 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5892 PUSH_NUMBER (p2
, mcnt
);
5893 goto unconditional_jump
;
5895 /* If don't have to jump any more, skip over the rest of command. */
5902 unsigned char *p2
; /* Location of the counter. */
5903 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5905 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5906 /* Here, we discard `const', making re_match non-reentrant. */
5907 p2
= (unsigned char*) p
+ mcnt
;
5908 /* Signedness doesn't matter since we only copy MCNT's bits. */
5909 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5910 DEBUG_PRINT (" Setting %p to %d.\n", p2
, mcnt
);
5911 PUSH_NUMBER (p2
, mcnt
);
5918 boolean
not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5919 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5921 /* We SUCCEED (or FAIL) in one of the following cases: */
5923 /* Case 1: D is at the beginning or the end of string. */
5924 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5928 /* C1 is the character before D, S1 is the syntax of C1, C2
5929 is the character at D, and S2 is the syntax of C2. */
5934 ssize_t offset
= PTR_TO_OFFSET (d
- 1);
5935 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5936 UPDATE_SYNTAX_TABLE (charpos
);
5938 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5941 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5943 PREFETCH_NOLIMIT ();
5944 GET_CHAR_AFTER (c2
, d
, dummy
);
5947 if (/* Case 2: Only one of S1 and S2 is Sword. */
5948 ((s1
== Sword
) != (s2
== Sword
))
5949 /* Case 3: Both of S1 and S2 are Sword, and macro
5950 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5951 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5961 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5963 /* We FAIL in one of the following cases: */
5965 /* Case 1: D is at the end of string. */
5966 if (AT_STRINGS_END (d
))
5970 /* C1 is the character before D, S1 is the syntax of C1, C2
5971 is the character at D, and S2 is the syntax of C2. */
5976 ssize_t offset
= PTR_TO_OFFSET (d
);
5977 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5978 UPDATE_SYNTAX_TABLE (charpos
);
5981 GET_CHAR_AFTER (c2
, d
, dummy
);
5984 /* Case 2: S2 is not Sword. */
5988 /* Case 3: D is not at the beginning of string ... */
5989 if (!AT_STRINGS_BEG (d
))
5991 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5993 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5997 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5999 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6006 DEBUG_PRINT ("EXECUTING wordend.\n");
6008 /* We FAIL in one of the following cases: */
6010 /* Case 1: D is at the beginning of string. */
6011 if (AT_STRINGS_BEG (d
))
6015 /* C1 is the character before D, S1 is the syntax of C1, C2
6016 is the character at D, and S2 is the syntax of C2. */
6021 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6022 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6023 UPDATE_SYNTAX_TABLE (charpos
);
6025 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6028 /* Case 2: S1 is not Sword. */
6032 /* Case 3: D is not at the end of string ... */
6033 if (!AT_STRINGS_END (d
))
6035 PREFETCH_NOLIMIT ();
6036 GET_CHAR_AFTER (c2
, d
, dummy
);
6038 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6042 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6044 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6051 DEBUG_PRINT ("EXECUTING symbeg.\n");
6053 /* We FAIL in one of the following cases: */
6055 /* Case 1: D is at the end of string. */
6056 if (AT_STRINGS_END (d
))
6060 /* C1 is the character before D, S1 is the syntax of C1, C2
6061 is the character at D, and S2 is the syntax of C2. */
6065 ssize_t offset
= PTR_TO_OFFSET (d
);
6066 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6067 UPDATE_SYNTAX_TABLE (charpos
);
6070 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6073 /* Case 2: S2 is neither Sword nor Ssymbol. */
6074 if (s2
!= Sword
&& s2
!= Ssymbol
)
6077 /* Case 3: D is not at the beginning of string ... */
6078 if (!AT_STRINGS_BEG (d
))
6080 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6082 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6086 /* ... and S1 is Sword or Ssymbol. */
6087 if (s1
== Sword
|| s1
== Ssymbol
)
6094 DEBUG_PRINT ("EXECUTING symend.\n");
6096 /* We FAIL in one of the following cases: */
6098 /* Case 1: D is at the beginning of string. */
6099 if (AT_STRINGS_BEG (d
))
6103 /* C1 is the character before D, S1 is the syntax of C1, C2
6104 is the character at D, and S2 is the syntax of C2. */
6108 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6109 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6110 UPDATE_SYNTAX_TABLE (charpos
);
6112 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6115 /* Case 2: S1 is neither Ssymbol nor Sword. */
6116 if (s1
!= Sword
&& s1
!= Ssymbol
)
6119 /* Case 3: D is not at the end of string ... */
6120 if (!AT_STRINGS_END (d
))
6122 PREFETCH_NOLIMIT ();
6123 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6125 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6129 /* ... and S2 is Sword or Ssymbol. */
6130 if (s2
== Sword
|| s2
== Ssymbol
)
6139 boolean
not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6141 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6146 ssize_t offset
= PTR_TO_OFFSET (d
);
6147 ssize_t pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6148 UPDATE_SYNTAX_TABLE (pos1
);
6155 GET_CHAR_AFTER (c
, d
, len
);
6156 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6165 DEBUG_PRINT ("EXECUTING before_dot.\n");
6166 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6171 DEBUG_PRINT ("EXECUTING at_dot.\n");
6172 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6177 DEBUG_PRINT ("EXECUTING after_dot.\n");
6178 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6183 case notcategoryspec
:
6185 boolean
not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6187 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6188 not ? "not" : "", mcnt
);
6194 GET_CHAR_AFTER (c
, d
, len
);
6195 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6207 continue; /* Successfully executed one pattern command; keep going. */
6210 /* We goto here if a matching operation fails. */
6212 IMMEDIATE_QUIT_CHECK
;
6213 if (!FAIL_STACK_EMPTY ())
6216 /* A restart point is known. Restore to that state. */
6217 DEBUG_PRINT ("\nFAIL:\n");
6218 POP_FAILURE_POINT (str
, pat
);
6221 case on_failure_keep_string_jump
:
6222 assert (str
== NULL
);
6223 goto continue_failure_jump
;
6225 case on_failure_jump_nastyloop
:
6226 assert ((re_opcode_t
)pat
[-2] == no_op
);
6227 PUSH_FAILURE_POINT (pat
- 2, str
);
6230 case on_failure_jump_loop
:
6231 case on_failure_jump
:
6234 continue_failure_jump
:
6235 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6240 /* A special frame used for nastyloops. */
6247 assert (p
>= bufp
->buffer
&& p
<= pend
);
6249 if (d
>= string1
&& d
<= end1
)
6253 break; /* Matching at this starting point really fails. */
6257 goto restore_best_regs
;
6261 return -1; /* Failure to match. */
6264 /* Subroutine definitions for re_match_2. */
6266 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6267 bytes; nonzero otherwise. */
6270 bcmp_translate (const_re_char
*s1
, const_re_char
*s2
, register ssize_t len
,
6271 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6273 register re_char
*p1
= s1
, *p2
= s2
;
6274 re_char
*p1_end
= s1
+ len
;
6275 re_char
*p2_end
= s2
+ len
;
6277 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6278 different lengths, but relying on a single `len' would break this. -sm */
6279 while (p1
< p1_end
&& p2
< p2_end
)
6281 int p1_charlen
, p2_charlen
;
6282 re_wchar_t p1_ch
, p2_ch
;
6284 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6285 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6287 if (RE_TRANSLATE (translate
, p1_ch
)
6288 != RE_TRANSLATE (translate
, p2_ch
))
6291 p1
+= p1_charlen
, p2
+= p2_charlen
;
6294 if (p1
!= p1_end
|| p2
!= p2_end
)
6300 /* Entry points for GNU code. */
6302 /* re_compile_pattern is the GNU regular expression compiler: it
6303 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6304 Returns 0 if the pattern was valid, otherwise an error string.
6306 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6307 are set in BUFP on entry.
6309 We call regex_compile to do the actual compilation. */
6312 re_compile_pattern (const char *pattern
, size_t length
,
6313 struct re_pattern_buffer
*bufp
)
6317 /* GNU code is written to assume at least RE_NREGS registers will be set
6318 (and at least one extra will be -1). */
6319 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6321 /* And GNU code determines whether or not to get register information
6322 by passing null for the REGS argument to re_match, etc., not by
6326 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6330 return gettext (re_error_msgid
[(int) ret
]);
6332 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6334 /* Entry points compatible with 4.2 BSD regex library. We don't define
6335 them unless specifically requested. */
6337 #if defined _REGEX_RE_COMP || defined _LIBC
6339 /* BSD has one and only one pattern buffer. */
6340 static struct re_pattern_buffer re_comp_buf
;
6344 /* Make these definitions weak in libc, so POSIX programs can redefine
6345 these names if they don't use our functions, and still use
6346 regcomp/regexec below without link errors. */
6349 re_comp (const char *s
)
6355 if (!re_comp_buf
.buffer
)
6356 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6357 return (char *) gettext ("No previous regular expression");
6361 if (!re_comp_buf
.buffer
)
6363 re_comp_buf
.buffer
= malloc (200);
6364 if (re_comp_buf
.buffer
== NULL
)
6365 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6366 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6367 re_comp_buf
.allocated
= 200;
6369 re_comp_buf
.fastmap
= malloc (1 << BYTEWIDTH
);
6370 if (re_comp_buf
.fastmap
== NULL
)
6371 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6372 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6375 /* Since `re_exec' always passes NULL for the `regs' argument, we
6376 don't need to initialize the pattern buffer fields which affect it. */
6378 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6383 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6384 return (char *) gettext (re_error_msgid
[(int) ret
]);
6392 re_exec (const char *s
)
6394 const size_t len
= strlen (s
);
6395 return re_search (&re_comp_buf
, s
, len
, 0, len
, 0) >= 0;
6397 #endif /* _REGEX_RE_COMP */
6399 /* POSIX.2 functions. Don't define these for Emacs. */
6403 /* regcomp takes a regular expression as a string and compiles it.
6405 PREG is a regex_t *. We do not expect any fields to be initialized,
6406 since POSIX says we shouldn't. Thus, we set
6408 `buffer' to the compiled pattern;
6409 `used' to the length of the compiled pattern;
6410 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6411 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6412 RE_SYNTAX_POSIX_BASIC;
6413 `fastmap' to an allocated space for the fastmap;
6414 `fastmap_accurate' to zero;
6415 `re_nsub' to the number of subexpressions in PATTERN.
6417 PATTERN is the address of the pattern string.
6419 CFLAGS is a series of bits which affect compilation.
6421 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6422 use POSIX basic syntax.
6424 If REG_NEWLINE is set, then . and [^...] don't match newline.
6425 Also, regexec will try a match beginning after every newline.
6427 If REG_ICASE is set, then we considers upper- and lowercase
6428 versions of letters to be equivalent when matching.
6430 If REG_NOSUB is set, then when PREG is passed to regexec, that
6431 routine will report only success or failure, and nothing about the
6434 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6435 the return codes and their meanings.) */
6438 regcomp (regex_t
*_Restrict_ preg
, const char *_Restrict_ pattern
,
6443 = (cflags
& REG_EXTENDED
) ?
6444 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6446 /* regex_compile will allocate the space for the compiled pattern. */
6448 preg
->allocated
= 0;
6451 /* Try to allocate space for the fastmap. */
6452 preg
->fastmap
= malloc (1 << BYTEWIDTH
);
6454 if (cflags
& REG_ICASE
)
6458 preg
->translate
= malloc (CHAR_SET_SIZE
* sizeof *preg
->translate
);
6459 if (preg
->translate
== NULL
)
6460 return (int) REG_ESPACE
;
6462 /* Map uppercase characters to corresponding lowercase ones. */
6463 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6464 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6467 preg
->translate
= NULL
;
6469 /* If REG_NEWLINE is set, newlines are treated differently. */
6470 if (cflags
& REG_NEWLINE
)
6471 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6472 syntax
&= ~RE_DOT_NEWLINE
;
6473 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6476 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6478 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6480 /* POSIX says a null character in the pattern terminates it, so we
6481 can use strlen here in compiling the pattern. */
6482 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6484 /* POSIX doesn't distinguish between an unmatched open-group and an
6485 unmatched close-group: both are REG_EPAREN. */
6486 if (ret
== REG_ERPAREN
)
6489 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6490 { /* Compute the fastmap now, since regexec cannot modify the pattern
6492 re_compile_fastmap (preg
);
6493 if (preg
->can_be_null
)
6494 { /* The fastmap can't be used anyway. */
6495 free (preg
->fastmap
);
6496 preg
->fastmap
= NULL
;
6501 WEAK_ALIAS (__regcomp
, regcomp
)
6504 /* regexec searches for a given pattern, specified by PREG, in the
6507 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6508 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6509 least NMATCH elements, and we set them to the offsets of the
6510 corresponding matched substrings.
6512 EFLAGS specifies `execution flags' which affect matching: if
6513 REG_NOTBOL is set, then ^ does not match at the beginning of the
6514 string; if REG_NOTEOL is set, then $ does not match at the end.
6516 We return 0 if we find a match and REG_NOMATCH if not. */
6519 regexec (const regex_t
*_Restrict_ preg
, const char *_Restrict_ string
,
6520 size_t nmatch
, regmatch_t pmatch
[_Restrict_arr_
], int eflags
)
6523 struct re_registers regs
;
6524 regex_t private_preg
;
6525 size_t len
= strlen (string
);
6526 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6528 private_preg
= *preg
;
6530 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6531 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6533 /* The user has told us exactly how many registers to return
6534 information about, via `nmatch'. We have to pass that on to the
6535 matching routines. */
6536 private_preg
.regs_allocated
= REGS_FIXED
;
6540 regs
.num_regs
= nmatch
;
6541 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6542 if (regs
.start
== NULL
)
6544 regs
.end
= regs
.start
+ nmatch
;
6547 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6548 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6549 was a little bit longer but still only matching the real part.
6550 This works because the `endline' will check for a '\n' and will find a
6551 '\0', correctly deciding that this is not the end of a line.
6552 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6553 a convenient '\0' there. For all we know, the string could be preceded
6554 by '\n' which would throw things off. */
6556 /* Perform the searching operation. */
6557 ret
= re_search (&private_preg
, string
, len
,
6558 /* start: */ 0, /* range: */ len
,
6559 want_reg_info
? ®s
: 0);
6561 /* Copy the register information to the POSIX structure. */
6568 for (r
= 0; r
< nmatch
; r
++)
6570 pmatch
[r
].rm_so
= regs
.start
[r
];
6571 pmatch
[r
].rm_eo
= regs
.end
[r
];
6575 /* If we needed the temporary register info, free the space now. */
6579 /* We want zero return to mean success, unlike `re_search'. */
6580 return ret
>= 0 ? REG_NOERROR
: REG_NOMATCH
;
6582 WEAK_ALIAS (__regexec
, regexec
)
6585 /* Returns a message corresponding to an error code, ERR_CODE, returned
6586 from either regcomp or regexec. We don't use PREG here.
6588 ERR_CODE was previously called ERRCODE, but that name causes an
6589 error with msvc8 compiler. */
6592 regerror (int err_code
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
6598 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6599 /* Only error codes returned by the rest of the code should be passed
6600 to this routine. If we are given anything else, or if other regex
6601 code generates an invalid error code, then the program has a bug.
6602 Dump core so we can fix it. */
6605 msg
= gettext (re_error_msgid
[err_code
]);
6607 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6609 if (errbuf_size
!= 0)
6611 if (msg_size
> errbuf_size
)
6613 memcpy (errbuf
, msg
, errbuf_size
- 1);
6614 errbuf
[errbuf_size
- 1] = 0;
6617 strcpy (errbuf
, msg
);
6622 WEAK_ALIAS (__regerror
, regerror
)
6625 /* Free dynamically allocated space used by PREG. */
6628 regfree (regex_t
*preg
)
6630 free (preg
->buffer
);
6631 preg
->buffer
= NULL
;
6633 preg
->allocated
= 0;
6636 free (preg
->fastmap
);
6637 preg
->fastmap
= NULL
;
6638 preg
->fastmap_accurate
= 0;
6640 free (preg
->translate
);
6641 preg
->translate
= NULL
;
6643 WEAK_ALIAS (__regfree
, regfree
)
6645 #endif /* not emacs */