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__ + (5 <= __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"
134 /* Make syntax table lookup grant data in gl_state. */
135 # define SYNTAX_ENTRY_VIA_PROPERTY
138 # include "category.h"
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 CHAR_CHARSET(c) 0
261 # define CHARSET_LEADING_CODE_BASE(c) 0
262 # define MAX_MULTIBYTE_LENGTH 1
263 # define RE_MULTIBYTE_P(x) 0
264 # define RE_TARGET_MULTIBYTE_P(x) 0
265 # define WORD_BOUNDARY_P(c1, c2) (0)
266 # define CHAR_HEAD_P(p) (1)
267 # define SINGLE_BYTE_CHAR_P(c) (1)
268 # define SAME_CHARSET_P(c1, c2) (1)
269 # define BYTES_BY_CHAR_HEAD(p) (1)
270 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
271 # define STRING_CHAR(p) (*(p))
272 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
273 # define CHAR_STRING(c, s) (*(s) = (c), 1)
274 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
275 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
276 # define RE_CHAR_TO_MULTIBYTE(c) (c)
277 # define RE_CHAR_TO_UNIBYTE(c) (c)
278 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
279 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
280 # define GET_CHAR_AFTER(c, p, len) \
282 # define MAKE_CHAR(charset, c1, c2) (c1)
283 # define BYTE8_TO_CHAR(c) (c)
284 # define CHAR_BYTE8_P(c) (0)
285 # define CHAR_LEADING_CODE(c) (c)
287 #endif /* not emacs */
290 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
291 # define RE_TRANSLATE_P(TBL) (TBL)
294 /* Get the interface, including the syntax bits. */
297 /* isalpha etc. are used for the character classes. */
302 /* 1 if C is an ASCII character. */
303 # define IS_REAL_ASCII(c) ((c) < 0200)
305 /* 1 if C is a unibyte character. */
306 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
308 /* The Emacs definitions should not be directly affected by locales. */
310 /* In Emacs, these are only used for single-byte characters. */
311 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
312 # define ISCNTRL(c) ((c) < ' ')
313 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
314 || ((c) >= 'a' && (c) <= 'f') \
315 || ((c) >= 'A' && (c) <= 'F'))
317 /* This is only used for single-byte characters. */
318 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
320 /* The rest must handle multibyte characters. */
322 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
323 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
326 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
327 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
330 # define ISALNUM(c) (IS_REAL_ASCII (c) \
331 ? (((c) >= 'a' && (c) <= 'z') \
332 || ((c) >= 'A' && (c) <= 'Z') \
333 || ((c) >= '0' && (c) <= '9')) \
334 : SYNTAX (c) == Sword)
336 # define ISALPHA(c) (IS_REAL_ASCII (c) \
337 ? (((c) >= 'a' && (c) <= 'z') \
338 || ((c) >= 'A' && (c) <= 'Z')) \
339 : SYNTAX (c) == Sword)
341 # define ISLOWER(c) lowercasep (c)
343 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
344 ? ((c) > ' ' && (c) < 0177 \
345 && !(((c) >= 'a' && (c) <= 'z') \
346 || ((c) >= 'A' && (c) <= 'Z') \
347 || ((c) >= '0' && (c) <= '9'))) \
348 : SYNTAX (c) != Sword)
350 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
352 # define ISUPPER(c) uppercasep (c)
354 # define ISWORD(c) (SYNTAX (c) == Sword)
356 #else /* not emacs */
358 /* 1 if C is an ASCII character. */
359 # define IS_REAL_ASCII(c) ((c) < 0200)
361 /* This distinction is not meaningful, except in Emacs. */
362 # define ISUNIBYTE(c) 1
365 # define ISBLANK(c) isblank (c)
367 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
370 # define ISGRAPH(c) isgraph (c)
372 # define ISGRAPH(c) (isprint (c) && !isspace (c))
375 /* Solaris defines ISPRINT so we must undefine it first. */
377 # define ISPRINT(c) isprint (c)
378 # define ISDIGIT(c) isdigit (c)
379 # define ISALNUM(c) isalnum (c)
380 # define ISALPHA(c) isalpha (c)
381 # define ISCNTRL(c) iscntrl (c)
382 # define ISLOWER(c) islower (c)
383 # define ISPUNCT(c) ispunct (c)
384 # define ISSPACE(c) isspace (c)
385 # define ISUPPER(c) isupper (c)
386 # define ISXDIGIT(c) isxdigit (c)
388 # define ISWORD(c) ISALPHA (c)
391 # define TOLOWER(c) _tolower (c)
393 # define TOLOWER(c) tolower (c)
396 /* How many characters in the character set. */
397 # define CHAR_SET_SIZE 256
401 extern char *re_syntax_table
;
403 # else /* not SYNTAX_TABLE */
405 static char re_syntax_table
[CHAR_SET_SIZE
];
408 init_syntax_once (void)
416 memset (re_syntax_table
, 0, sizeof re_syntax_table
);
418 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
420 re_syntax_table
[c
] = Sword
;
422 re_syntax_table
['_'] = Ssymbol
;
427 # endif /* not SYNTAX_TABLE */
429 # define SYNTAX(c) re_syntax_table[(c)]
431 #endif /* not emacs */
433 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
435 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
436 use `alloca' instead of `malloc'. This is because using malloc in
437 re_search* or re_match* could cause memory leaks when C-g is used in
438 Emacs; also, malloc is slower and causes storage fragmentation. On
439 the other hand, malloc is more portable, and easier to debug.
441 Because we sometimes use alloca, some routines have to be macros,
442 not functions -- `alloca'-allocated space disappears at the end of the
443 function it is called in. */
447 # define REGEX_ALLOCATE malloc
448 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
449 # define REGEX_FREE free
451 #else /* not REGEX_MALLOC */
453 /* Emacs already defines alloca, sometimes. */
456 /* Make alloca work the best possible way. */
458 # define alloca __builtin_alloca
459 # else /* not __GNUC__ */
460 # ifdef HAVE_ALLOCA_H
462 # endif /* HAVE_ALLOCA_H */
463 # endif /* not __GNUC__ */
465 # endif /* not alloca */
467 # define REGEX_ALLOCATE alloca
469 /* Assumes a `char *destination' variable. */
470 # define REGEX_REALLOCATE(source, osize, nsize) \
471 (destination = (char *) alloca (nsize), \
472 memcpy (destination, source, osize))
474 /* No need to do anything to free, after alloca. */
475 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
477 #endif /* not REGEX_MALLOC */
479 /* Define how to allocate the failure stack. */
481 #if defined REL_ALLOC && defined REGEX_MALLOC
483 # define REGEX_ALLOCATE_STACK(size) \
484 r_alloc (&failure_stack_ptr, (size))
485 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
486 r_re_alloc (&failure_stack_ptr, (nsize))
487 # define REGEX_FREE_STACK(ptr) \
488 r_alloc_free (&failure_stack_ptr)
490 #else /* not using relocating allocator */
494 # define REGEX_ALLOCATE_STACK malloc
495 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
496 # define REGEX_FREE_STACK free
498 # else /* not REGEX_MALLOC */
500 # define REGEX_ALLOCATE_STACK alloca
502 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
503 REGEX_REALLOCATE (source, osize, nsize)
504 /* No need to explicitly free anything. */
505 # define REGEX_FREE_STACK(arg) ((void)0)
507 # endif /* not REGEX_MALLOC */
508 #endif /* not using relocating allocator */
511 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
512 `string1' or just past its end. This works if PTR is NULL, which is
514 #define FIRST_STRING_P(ptr) \
515 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
517 /* (Re)Allocate N items of type T using malloc, or fail. */
518 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
519 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
520 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
522 #define BYTEWIDTH 8 /* In bits. */
524 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
528 #define MAX(a, b) ((a) > (b) ? (a) : (b))
529 #define MIN(a, b) ((a) < (b) ? (a) : (b))
531 /* Type of source-pattern and string chars. */
533 typedef unsigned char re_char
;
535 typedef const unsigned char re_char
;
538 typedef char boolean
;
540 static regoff_t
re_match_2_internal (struct re_pattern_buffer
*bufp
,
541 re_char
*string1
, size_t size1
,
542 re_char
*string2
, size_t size2
,
544 struct re_registers
*regs
,
547 /* These are the command codes that appear in compiled regular
548 expressions. Some opcodes are followed by argument bytes. A
549 command code can specify any interpretation whatsoever for its
550 arguments. Zero bytes may appear in the compiled regular expression. */
556 /* Succeed right away--no more backtracking. */
559 /* Followed by one byte giving n, then by n literal bytes. */
562 /* Matches any (more or less) character. */
565 /* Matches any one char belonging to specified set. First
566 following byte is number of bitmap bytes. Then come bytes
567 for a bitmap saying which chars are in. Bits in each byte
568 are ordered low-bit-first. A character is in the set if its
569 bit is 1. A character too large to have a bit in the map is
570 automatically not in the set.
572 If the length byte has the 0x80 bit set, then that stuff
573 is followed by a range table:
574 2 bytes of flags for character sets (low 8 bits, high 8 bits)
575 See RANGE_TABLE_WORK_BITS below.
576 2 bytes, the number of pairs that follow (upto 32767)
577 pairs, each 2 multibyte characters,
578 each multibyte character represented as 3 bytes. */
581 /* Same parameters as charset, but match any character that is
582 not one of those specified. */
585 /* Start remembering the text that is matched, for storing in a
586 register. Followed by one byte with the register number, in
587 the range 0 to one less than the pattern buffer's re_nsub
591 /* Stop remembering the text that is matched and store it in a
592 memory register. Followed by one byte with the register
593 number, in the range 0 to one less than `re_nsub' in the
597 /* Match a duplicate of something remembered. Followed by one
598 byte containing the register number. */
601 /* Fail unless at beginning of line. */
604 /* Fail unless at end of line. */
607 /* Succeeds if at beginning of buffer (if emacs) or at beginning
608 of string to be matched (if not). */
611 /* Analogously, for end of buffer/string. */
614 /* Followed by two byte relative address to which to jump. */
617 /* Followed by two-byte relative address of place to resume at
618 in case of failure. */
621 /* Like on_failure_jump, but pushes a placeholder instead of the
622 current string position when executed. */
623 on_failure_keep_string_jump
,
625 /* Just like `on_failure_jump', except that it checks that we
626 don't get stuck in an infinite loop (matching an empty string
628 on_failure_jump_loop
,
630 /* Just like `on_failure_jump_loop', except that it checks for
631 a different kind of loop (the kind that shows up with non-greedy
632 operators). This operation has to be immediately preceded
634 on_failure_jump_nastyloop
,
636 /* A smart `on_failure_jump' used for greedy * and + operators.
637 It analyzes the loop before which it is put and if the
638 loop does not require backtracking, it changes itself to
639 `on_failure_keep_string_jump' and short-circuits the loop,
640 else it just defaults to changing itself into `on_failure_jump'.
641 It assumes that it is pointing to just past a `jump'. */
642 on_failure_jump_smart
,
644 /* Followed by two-byte relative address and two-byte number n.
645 After matching N times, jump to the address upon failure.
646 Does not work if N starts at 0: use on_failure_jump_loop
650 /* Followed by two-byte relative address, and two-byte number n.
651 Jump to the address N times, then fail. */
654 /* Set the following two-byte relative address to the
655 subsequent two-byte number. The address *includes* the two
659 wordbeg
, /* Succeeds if at word beginning. */
660 wordend
, /* Succeeds if at word end. */
662 wordbound
, /* Succeeds if at a word boundary. */
663 notwordbound
, /* Succeeds if not at a word boundary. */
665 symbeg
, /* Succeeds if at symbol beginning. */
666 symend
, /* Succeeds if at symbol end. */
668 /* Matches any character whose syntax is specified. Followed by
669 a byte which contains a syntax code, e.g., Sword. */
672 /* Matches any character whose syntax is not that specified. */
676 ,before_dot
, /* Succeeds if before point. */
677 at_dot
, /* Succeeds if at point. */
678 after_dot
, /* Succeeds if after point. */
680 /* Matches any character whose category-set contains the specified
681 category. The operator is followed by a byte which contains a
682 category code (mnemonic ASCII character). */
685 /* Matches any character whose category-set does not contain the
686 specified category. The operator is followed by a byte which
687 contains the category code (mnemonic ASCII character). */
692 /* Common operations on the compiled pattern. */
694 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
696 #define STORE_NUMBER(destination, number) \
698 (destination)[0] = (number) & 0377; \
699 (destination)[1] = (number) >> 8; \
702 /* Same as STORE_NUMBER, except increment DESTINATION to
703 the byte after where the number is stored. Therefore, DESTINATION
704 must be an lvalue. */
706 #define STORE_NUMBER_AND_INCR(destination, number) \
708 STORE_NUMBER (destination, number); \
709 (destination) += 2; \
712 /* Put into DESTINATION a number stored in two contiguous bytes starting
715 #define EXTRACT_NUMBER(destination, source) \
716 ((destination) = extract_number (source))
719 extract_number (re_char
*source
)
721 return (SIGN_EXTEND_CHAR (source
[1]) << 8) + source
[0];
724 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
725 SOURCE must be an lvalue. */
727 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
728 ((destination) = extract_number_and_incr (&source))
731 extract_number_and_incr (re_char
**source
)
733 int num
= extract_number (*source
);
738 /* Store a multibyte character in three contiguous bytes starting
739 DESTINATION, and increment DESTINATION to the byte after where the
740 character is stored. Therefore, DESTINATION must be an lvalue. */
742 #define STORE_CHARACTER_AND_INCR(destination, character) \
744 (destination)[0] = (character) & 0377; \
745 (destination)[1] = ((character) >> 8) & 0377; \
746 (destination)[2] = (character) >> 16; \
747 (destination) += 3; \
750 /* Put into DESTINATION a character stored in three contiguous bytes
751 starting at SOURCE. */
753 #define EXTRACT_CHARACTER(destination, source) \
755 (destination) = ((source)[0] \
756 | ((source)[1] << 8) \
757 | ((source)[2] << 16)); \
761 /* Macros for charset. */
763 /* Size of bitmap of charset P in bytes. P is a start of charset,
764 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
765 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
767 /* Nonzero if charset P has range table. */
768 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
770 /* Return the address of range table of charset P. But not the start
771 of table itself, but the before where the number of ranges is
772 stored. `2 +' means to skip re_opcode_t and size of bitmap,
773 and the 2 bytes of flags at the start of the range table. */
774 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
776 /* Extract the bit flags that start a range table. */
777 #define CHARSET_RANGE_TABLE_BITS(p) \
778 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
779 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
781 /* Return the address of end of RANGE_TABLE. COUNT is number of
782 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
783 is start of range and end of range. `* 3' is size of each start
785 #define CHARSET_RANGE_TABLE_END(range_table, count) \
786 ((range_table) + (count) * 2 * 3)
788 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
789 COUNT is number of ranges in RANGE_TABLE. */
790 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
793 re_wchar_t range_start, range_end; \
795 re_char *range_table_end \
796 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
798 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
800 EXTRACT_CHARACTER (range_start, rtp); \
801 EXTRACT_CHARACTER (range_end, rtp + 3); \
803 if (range_start <= (c) && (c) <= range_end) \
812 /* Test if C is in range table of CHARSET. The flag NOT is negated if
813 C is listed in it. */
814 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
817 /* Number of ranges in range table. */ \
819 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
821 EXTRACT_NUMBER_AND_INCR (count, range_table); \
822 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
826 /* If DEBUG is defined, Regex prints many voluminous messages about what
827 it is doing (if the variable `debug' is nonzero). If linked with the
828 main program in `iregex.c', you can enter patterns and strings
829 interactively. And if linked with the main program in `main.c' and
830 the other test files, you can run the already-written tests. */
834 /* We use standard I/O for debugging. */
837 /* It is useful to test things that ``must'' be true when debugging. */
840 static int debug
= -100000;
842 # define DEBUG_STATEMENT(e) e
843 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
844 # define DEBUG_COMPILES_ARGUMENTS
845 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
846 if (debug > 0) print_partial_compiled_pattern (s, e)
847 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
848 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
851 /* Print the fastmap in human-readable form. */
854 print_fastmap (char *fastmap
)
856 unsigned was_a_range
= 0;
859 while (i
< (1 << BYTEWIDTH
))
865 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
881 /* Print a compiled pattern string in human-readable form, starting at
882 the START pointer into it and ending just before the pointer END. */
885 print_partial_compiled_pattern (re_char
*start
, re_char
*end
)
893 fprintf (stderr
, "(null)\n");
897 /* Loop over pattern commands. */
900 fprintf (stderr
, "%td:\t", p
- start
);
902 switch ((re_opcode_t
) *p
++)
905 fprintf (stderr
, "/no_op");
909 fprintf (stderr
, "/succeed");
914 fprintf (stderr
, "/exactn/%d", mcnt
);
917 fprintf (stderr
, "/%c", *p
++);
923 fprintf (stderr
, "/start_memory/%d", *p
++);
927 fprintf (stderr
, "/stop_memory/%d", *p
++);
931 fprintf (stderr
, "/duplicate/%d", *p
++);
935 fprintf (stderr
, "/anychar");
941 register int c
, last
= -100;
942 register int in_range
= 0;
943 int length
= CHARSET_BITMAP_SIZE (p
- 1);
944 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
946 fprintf (stderr
, "/charset [%s",
947 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
950 fprintf (stderr
, " !extends past end of pattern! ");
952 for (c
= 0; c
< 256; c
++)
954 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
956 /* Are we starting a range? */
957 if (last
+ 1 == c
&& ! in_range
)
959 fprintf (stderr
, "-");
962 /* Have we broken a range? */
963 else if (last
+ 1 != c
&& in_range
)
965 fprintf (stderr
, "%c", last
);
970 fprintf (stderr
, "%c", c
);
976 fprintf (stderr
, "%c", last
);
978 fprintf (stderr
, "]");
985 fprintf (stderr
, "has-range-table");
987 /* ??? Should print the range table; for now, just skip it. */
988 p
+= 2; /* skip range table bits */
989 EXTRACT_NUMBER_AND_INCR (count
, p
);
990 p
= CHARSET_RANGE_TABLE_END (p
, count
);
996 fprintf (stderr
, "/begline");
1000 fprintf (stderr
, "/endline");
1003 case on_failure_jump
:
1004 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1005 fprintf (stderr
, "/on_failure_jump to %td", p
+ mcnt
- start
);
1008 case on_failure_keep_string_jump
:
1009 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1010 fprintf (stderr
, "/on_failure_keep_string_jump to %td",
1014 case on_failure_jump_nastyloop
:
1015 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1016 fprintf (stderr
, "/on_failure_jump_nastyloop to %td",
1020 case on_failure_jump_loop
:
1021 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1022 fprintf (stderr
, "/on_failure_jump_loop to %td",
1026 case on_failure_jump_smart
:
1027 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1028 fprintf (stderr
, "/on_failure_jump_smart to %td",
1033 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1034 fprintf (stderr
, "/jump to %td", p
+ mcnt
- start
);
1038 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1039 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
1040 fprintf (stderr
, "/succeed_n to %td, %d times",
1041 p
- 2 + mcnt
- start
, mcnt2
);
1045 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1046 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
1047 fprintf (stderr
, "/jump_n to %td, %d times",
1048 p
- 2 + mcnt
- start
, mcnt2
);
1052 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1053 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
1054 fprintf (stderr
, "/set_number_at location %td to %d",
1055 p
- 2 + mcnt
- start
, mcnt2
);
1059 fprintf (stderr
, "/wordbound");
1063 fprintf (stderr
, "/notwordbound");
1067 fprintf (stderr
, "/wordbeg");
1071 fprintf (stderr
, "/wordend");
1075 fprintf (stderr
, "/symbeg");
1079 fprintf (stderr
, "/symend");
1083 fprintf (stderr
, "/syntaxspec");
1085 fprintf (stderr
, "/%d", mcnt
);
1089 fprintf (stderr
, "/notsyntaxspec");
1091 fprintf (stderr
, "/%d", mcnt
);
1096 fprintf (stderr
, "/before_dot");
1100 fprintf (stderr
, "/at_dot");
1104 fprintf (stderr
, "/after_dot");
1108 fprintf (stderr
, "/categoryspec");
1110 fprintf (stderr
, "/%d", mcnt
);
1113 case notcategoryspec
:
1114 fprintf (stderr
, "/notcategoryspec");
1116 fprintf (stderr
, "/%d", mcnt
);
1121 fprintf (stderr
, "/begbuf");
1125 fprintf (stderr
, "/endbuf");
1129 fprintf (stderr
, "?%d", *(p
-1));
1132 fprintf (stderr
, "\n");
1135 fprintf (stderr
, "%td:\tend of pattern.\n", p
- start
);
1140 print_compiled_pattern (struct re_pattern_buffer
*bufp
)
1142 re_char
*buffer
= bufp
->buffer
;
1144 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1145 printf ("%ld bytes used/%ld bytes allocated.\n",
1146 bufp
->used
, bufp
->allocated
);
1148 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1150 printf ("fastmap: ");
1151 print_fastmap (bufp
->fastmap
);
1154 printf ("re_nsub: %zu\t", bufp
->re_nsub
);
1155 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1156 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1157 printf ("no_sub: %d\t", bufp
->no_sub
);
1158 printf ("not_bol: %d\t", bufp
->not_bol
);
1159 printf ("not_eol: %d\t", bufp
->not_eol
);
1160 printf ("syntax: %lx\n", bufp
->syntax
);
1162 /* Perhaps we should print the translate table? */
1167 print_double_string (re_char
*where
, re_char
*string1
, ssize_t size1
,
1168 re_char
*string2
, ssize_t size2
)
1176 if (FIRST_STRING_P (where
))
1178 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1179 putchar (string1
[this_char
]);
1184 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1185 putchar (string2
[this_char
]);
1189 #else /* not DEBUG */
1194 # define DEBUG_STATEMENT(e)
1195 # if __STDC_VERSION__ < 199901L
1196 # define DEBUG_COMPILES_ARGUMENTS
1197 # define DEBUG_PRINT /* 'DEBUG_PRINT (x, y)' discards X and Y. */ (void)
1199 # define DEBUG_PRINT(...)
1201 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1202 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1204 #endif /* not DEBUG */
1206 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1208 # define IF_LINT(Code) Code
1210 # define IF_LINT(Code) /* empty */
1214 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1215 also be assigned to arbitrarily: each pattern buffer stores its own
1216 syntax, so it can be changed between regex compilations. */
1217 /* This has no initializer because initialized variables in Emacs
1218 become read-only after dumping. */
1219 reg_syntax_t re_syntax_options
;
1223 /* Specify the precise syntax of regexps for compilation. This provides
1224 for compatibility for various utilities which historically have
1225 different, incompatible syntaxes.
1227 The argument SYNTAX is a bit mask comprised of the various bits
1228 defined in regex.h. We return the old syntax. */
1231 re_set_syntax (reg_syntax_t syntax
)
1233 reg_syntax_t ret
= re_syntax_options
;
1235 re_syntax_options
= syntax
;
1238 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1241 /* Regexp to use to replace spaces, or NULL meaning don't. */
1242 static re_char
*whitespace_regexp
;
1246 re_set_whitespace_regexp (const char *regexp
)
1248 whitespace_regexp
= (re_char
*) regexp
;
1250 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1252 /* This table gives an error message for each of the error codes listed
1253 in regex.h. Obviously the order here has to be same as there.
1254 POSIX doesn't require that we do anything for REG_NOERROR,
1255 but why not be nice? */
1257 static const char *re_error_msgid
[] =
1259 gettext_noop ("Success"), /* REG_NOERROR */
1260 gettext_noop ("No match"), /* REG_NOMATCH */
1261 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1262 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1263 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1264 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1265 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1266 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1267 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1268 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1269 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1270 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1271 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1272 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1273 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1274 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1275 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1276 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1279 /* Avoiding alloca during matching, to placate r_alloc. */
1281 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1282 searching and matching functions should not call alloca. On some
1283 systems, alloca is implemented in terms of malloc, and if we're
1284 using the relocating allocator routines, then malloc could cause a
1285 relocation, which might (if the strings being searched are in the
1286 ralloc heap) shift the data out from underneath the regexp
1289 Here's another reason to avoid allocation: Emacs
1290 processes input from X in a signal handler; processing X input may
1291 call malloc; if input arrives while a matching routine is calling
1292 malloc, then we're scrod. But Emacs can't just block input while
1293 calling matching routines; then we don't notice interrupts when
1294 they come in. So, Emacs blocks input around all regexp calls
1295 except the matching calls, which it leaves unprotected, in the
1296 faith that they will not malloc. */
1298 /* Normally, this is fine. */
1299 #define MATCH_MAY_ALLOCATE
1301 /* The match routines may not allocate if (1) they would do it with malloc
1302 and (2) it's not safe for them to use malloc.
1303 Note that if REL_ALLOC is defined, matching would not use malloc for the
1304 failure stack, but we would still use it for the register vectors;
1305 so REL_ALLOC should not affect this. */
1306 #if defined REGEX_MALLOC && defined emacs
1307 # undef MATCH_MAY_ALLOCATE
1311 /* Failure stack declarations and macros; both re_compile_fastmap and
1312 re_match_2 use a failure stack. These have to be macros because of
1313 REGEX_ALLOCATE_STACK. */
1316 /* Approximate number of failure points for which to initially allocate space
1317 when matching. If this number is exceeded, we allocate more
1318 space, so it is not a hard limit. */
1319 #ifndef INIT_FAILURE_ALLOC
1320 # define INIT_FAILURE_ALLOC 20
1323 /* Roughly the maximum number of failure points on the stack. Would be
1324 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1325 This is a variable only so users of regex can assign to it; we never
1326 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1327 before using it, so it should probably be a byte-count instead. */
1328 # if defined MATCH_MAY_ALLOCATE
1329 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1330 whose default stack limit is 2mb. In order for a larger
1331 value to work reliably, you have to try to make it accord
1332 with the process stack limit. */
1333 size_t re_max_failures
= 40000;
1335 size_t re_max_failures
= 4000;
1338 union fail_stack_elt
1341 /* This should be the biggest `int' that's no bigger than a pointer. */
1345 typedef union fail_stack_elt fail_stack_elt_t
;
1349 fail_stack_elt_t
*stack
;
1351 size_t avail
; /* Offset of next open position. */
1352 size_t frame
; /* Offset of the cur constructed frame. */
1355 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1358 /* Define macros to initialize and free the failure stack.
1359 Do `return -2' if the alloc fails. */
1361 #ifdef MATCH_MAY_ALLOCATE
1362 # define INIT_FAIL_STACK() \
1364 fail_stack.stack = \
1365 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1366 * sizeof (fail_stack_elt_t)); \
1368 if (fail_stack.stack == NULL) \
1371 fail_stack.size = INIT_FAILURE_ALLOC; \
1372 fail_stack.avail = 0; \
1373 fail_stack.frame = 0; \
1376 # define INIT_FAIL_STACK() \
1378 fail_stack.avail = 0; \
1379 fail_stack.frame = 0; \
1382 # define RETALLOC_IF(addr, n, t) \
1383 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1387 /* Double the size of FAIL_STACK, up to a limit
1388 which allows approximately `re_max_failures' items.
1390 Return 1 if succeeds, and 0 if either ran out of memory
1391 allocating space for it or it was already too large.
1393 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1395 /* Factor to increase the failure stack size by
1396 when we increase it.
1397 This used to be 2, but 2 was too wasteful
1398 because the old discarded stacks added up to as much space
1399 were as ultimate, maximum-size stack. */
1400 #define FAIL_STACK_GROWTH_FACTOR 4
1402 #define GROW_FAIL_STACK(fail_stack) \
1403 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1404 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1406 : ((fail_stack).stack \
1407 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1408 (fail_stack).size * sizeof (fail_stack_elt_t), \
1409 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1410 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1411 * FAIL_STACK_GROWTH_FACTOR))), \
1413 (fail_stack).stack == NULL \
1415 : ((fail_stack).size \
1416 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1417 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1418 * FAIL_STACK_GROWTH_FACTOR)) \
1419 / sizeof (fail_stack_elt_t)), \
1423 /* Push a pointer value onto the failure stack.
1424 Assumes the variable `fail_stack'. Probably should only
1425 be called from within `PUSH_FAILURE_POINT'. */
1426 #define PUSH_FAILURE_POINTER(item) \
1427 fail_stack.stack[fail_stack.avail++].pointer = (item)
1429 /* This pushes an integer-valued item onto the failure stack.
1430 Assumes the variable `fail_stack'. Probably should only
1431 be called from within `PUSH_FAILURE_POINT'. */
1432 #define PUSH_FAILURE_INT(item) \
1433 fail_stack.stack[fail_stack.avail++].integer = (item)
1435 /* These POP... operations complement the PUSH... operations.
1436 All assume that `fail_stack' is nonempty. */
1437 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1438 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1440 /* Individual items aside from the registers. */
1441 #define NUM_NONREG_ITEMS 3
1443 /* Used to examine the stack (to detect infinite loops). */
1444 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1445 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1446 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1447 #define TOP_FAILURE_HANDLE() fail_stack.frame
1450 #define ENSURE_FAIL_STACK(space) \
1451 while (REMAINING_AVAIL_SLOTS <= space) { \
1452 if (!GROW_FAIL_STACK (fail_stack)) \
1454 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1455 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1458 /* Push register NUM onto the stack. */
1459 #define PUSH_FAILURE_REG(num) \
1461 char *destination; \
1463 ENSURE_FAIL_STACK(3); \
1464 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1465 n, regstart[n], regend[n]); \
1466 PUSH_FAILURE_POINTER (regstart[n]); \
1467 PUSH_FAILURE_POINTER (regend[n]); \
1468 PUSH_FAILURE_INT (n); \
1471 /* Change the counter's value to VAL, but make sure that it will
1472 be reset when backtracking. */
1473 #define PUSH_NUMBER(ptr,val) \
1475 char *destination; \
1477 ENSURE_FAIL_STACK(3); \
1478 EXTRACT_NUMBER (c, ptr); \
1479 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1480 PUSH_FAILURE_INT (c); \
1481 PUSH_FAILURE_POINTER (ptr); \
1482 PUSH_FAILURE_INT (-1); \
1483 STORE_NUMBER (ptr, val); \
1486 /* Pop a saved register off the stack. */
1487 #define POP_FAILURE_REG_OR_COUNT() \
1489 long pfreg = POP_FAILURE_INT (); \
1492 /* It's a counter. */ \
1493 /* Here, we discard `const', making re_match non-reentrant. */ \
1494 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1495 pfreg = POP_FAILURE_INT (); \
1496 STORE_NUMBER (ptr, pfreg); \
1497 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1501 regend[pfreg] = POP_FAILURE_POINTER (); \
1502 regstart[pfreg] = POP_FAILURE_POINTER (); \
1503 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1504 pfreg, regstart[pfreg], regend[pfreg]); \
1508 /* Check that we are not stuck in an infinite loop. */
1509 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1511 ssize_t failure = TOP_FAILURE_HANDLE (); \
1512 /* Check for infinite matching loops */ \
1513 while (failure > 0 \
1514 && (FAILURE_STR (failure) == string_place \
1515 || FAILURE_STR (failure) == NULL)) \
1517 assert (FAILURE_PAT (failure) >= bufp->buffer \
1518 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1519 if (FAILURE_PAT (failure) == pat_cur) \
1524 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1525 failure = NEXT_FAILURE_HANDLE(failure); \
1527 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1530 /* Push the information about the state we will need
1531 if we ever fail back to it.
1533 Requires variables fail_stack, regstart, regend and
1534 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1537 Does `return FAILURE_CODE' if runs out of memory. */
1539 #define PUSH_FAILURE_POINT(pattern, string_place) \
1541 char *destination; \
1542 /* Must be int, so when we don't save any registers, the arithmetic \
1543 of 0 + -1 isn't done as unsigned. */ \
1545 DEBUG_STATEMENT (nfailure_points_pushed++); \
1546 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1547 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1548 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1550 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1552 DEBUG_PRINT ("\n"); \
1554 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1555 PUSH_FAILURE_INT (fail_stack.frame); \
1557 DEBUG_PRINT (" Push string %p: `", string_place); \
1558 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1559 DEBUG_PRINT ("'\n"); \
1560 PUSH_FAILURE_POINTER (string_place); \
1562 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1563 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1564 PUSH_FAILURE_POINTER (pattern); \
1566 /* Close the frame by moving the frame pointer past it. */ \
1567 fail_stack.frame = fail_stack.avail; \
1570 /* Estimate the size of data pushed by a typical failure stack entry.
1571 An estimate is all we need, because all we use this for
1572 is to choose a limit for how big to make the failure stack. */
1573 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1574 #define TYPICAL_FAILURE_SIZE 20
1576 /* How many items can still be added to the stack without overflowing it. */
1577 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1580 /* Pops what PUSH_FAIL_STACK pushes.
1582 We restore into the parameters, all of which should be lvalues:
1583 STR -- the saved data position.
1584 PAT -- the saved pattern position.
1585 REGSTART, REGEND -- arrays of string positions.
1587 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1588 `pend', `string1', `size1', `string2', and `size2'. */
1590 #define POP_FAILURE_POINT(str, pat) \
1592 assert (!FAIL_STACK_EMPTY ()); \
1594 /* Remove failure points and point to how many regs pushed. */ \
1595 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1596 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1597 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1599 /* Pop the saved registers. */ \
1600 while (fail_stack.frame < fail_stack.avail) \
1601 POP_FAILURE_REG_OR_COUNT (); \
1603 pat = POP_FAILURE_POINTER (); \
1604 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1605 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1607 /* If the saved string location is NULL, it came from an \
1608 on_failure_keep_string_jump opcode, and we want to throw away the \
1609 saved NULL, thus retaining our current position in the string. */ \
1610 str = POP_FAILURE_POINTER (); \
1611 DEBUG_PRINT (" Popping string %p: `", str); \
1612 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1613 DEBUG_PRINT ("'\n"); \
1615 fail_stack.frame = POP_FAILURE_INT (); \
1616 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1618 assert (fail_stack.avail >= 0); \
1619 assert (fail_stack.frame <= fail_stack.avail); \
1621 DEBUG_STATEMENT (nfailure_points_popped++); \
1622 } while (0) /* POP_FAILURE_POINT */
1626 /* Registers are set to a sentinel when they haven't yet matched. */
1627 #define REG_UNSET(e) ((e) == NULL)
1629 /* Subroutine declarations and macros for regex_compile. */
1631 static reg_errcode_t
regex_compile (re_char
*pattern
, size_t size
,
1632 reg_syntax_t syntax
,
1633 struct re_pattern_buffer
*bufp
);
1634 static void store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
);
1635 static void store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
);
1636 static void insert_op1 (re_opcode_t op
, unsigned char *loc
,
1637 int arg
, unsigned char *end
);
1638 static void insert_op2 (re_opcode_t op
, unsigned char *loc
,
1639 int arg1
, int arg2
, unsigned char *end
);
1640 static boolean
at_begline_loc_p (re_char
*pattern
, re_char
*p
,
1641 reg_syntax_t syntax
);
1642 static boolean
at_endline_loc_p (re_char
*p
, re_char
*pend
,
1643 reg_syntax_t syntax
);
1644 static re_char
*skip_one_char (re_char
*p
);
1645 static int analyse_first (re_char
*p
, re_char
*pend
,
1646 char *fastmap
, const int multibyte
);
1648 /* Fetch the next character in the uncompiled pattern, with no
1650 #define PATFETCH(c) \
1653 if (p == pend) return REG_EEND; \
1654 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1659 /* If `translate' is non-null, return translate[D], else just D. We
1660 cast the subscript to translate because some data is declared as
1661 `char *', to avoid warnings when a string constant is passed. But
1662 when we use a character as a subscript we must make it unsigned. */
1664 # define TRANSLATE(d) \
1665 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1669 /* Macros for outputting the compiled pattern into `buffer'. */
1671 /* If the buffer isn't allocated when it comes in, use this. */
1672 #define INIT_BUF_SIZE 32
1674 /* Make sure we have at least N more bytes of space in buffer. */
1675 #define GET_BUFFER_SPACE(n) \
1676 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1679 /* Make sure we have one more byte of buffer space and then add C to it. */
1680 #define BUF_PUSH(c) \
1682 GET_BUFFER_SPACE (1); \
1683 *b++ = (unsigned char) (c); \
1687 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1688 #define BUF_PUSH_2(c1, c2) \
1690 GET_BUFFER_SPACE (2); \
1691 *b++ = (unsigned char) (c1); \
1692 *b++ = (unsigned char) (c2); \
1696 /* Store a jump with opcode OP at LOC to location TO. We store a
1697 relative address offset by the three bytes the jump itself occupies. */
1698 #define STORE_JUMP(op, loc, to) \
1699 store_op1 (op, loc, (to) - (loc) - 3)
1701 /* Likewise, for a two-argument jump. */
1702 #define STORE_JUMP2(op, loc, to, arg) \
1703 store_op2 (op, loc, (to) - (loc) - 3, arg)
1705 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1706 #define INSERT_JUMP(op, loc, to) \
1707 insert_op1 (op, loc, (to) - (loc) - 3, b)
1709 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1710 #define INSERT_JUMP2(op, loc, to, arg) \
1711 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1714 /* This is not an arbitrary limit: the arguments which represent offsets
1715 into the pattern are two bytes long. So if 2^15 bytes turns out to
1716 be too small, many things would have to change. */
1717 # define MAX_BUF_SIZE (1L << 15)
1719 /* Extend the buffer by twice its current size via realloc and
1720 reset the pointers that pointed into the old block to point to the
1721 correct places in the new one. If extending the buffer results in it
1722 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1723 #if __BOUNDED_POINTERS__
1724 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1725 # define MOVE_BUFFER_POINTER(P) \
1726 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1727 SET_HIGH_BOUND (P), \
1728 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1729 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1732 SET_HIGH_BOUND (b); \
1733 SET_HIGH_BOUND (begalt); \
1734 if (fixup_alt_jump) \
1735 SET_HIGH_BOUND (fixup_alt_jump); \
1737 SET_HIGH_BOUND (laststart); \
1738 if (pending_exact) \
1739 SET_HIGH_BOUND (pending_exact); \
1742 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1743 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1745 #define EXTEND_BUFFER() \
1747 unsigned char *old_buffer = bufp->buffer; \
1748 if (bufp->allocated == MAX_BUF_SIZE) \
1750 bufp->allocated <<= 1; \
1751 if (bufp->allocated > MAX_BUF_SIZE) \
1752 bufp->allocated = MAX_BUF_SIZE; \
1753 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1754 if (bufp->buffer == NULL) \
1755 return REG_ESPACE; \
1756 /* If the buffer moved, move all the pointers into it. */ \
1757 if (old_buffer != bufp->buffer) \
1759 unsigned char *new_buffer = bufp->buffer; \
1760 MOVE_BUFFER_POINTER (b); \
1761 MOVE_BUFFER_POINTER (begalt); \
1762 if (fixup_alt_jump) \
1763 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1765 MOVE_BUFFER_POINTER (laststart); \
1766 if (pending_exact) \
1767 MOVE_BUFFER_POINTER (pending_exact); \
1769 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1773 /* Since we have one byte reserved for the register number argument to
1774 {start,stop}_memory, the maximum number of groups we can report
1775 things about is what fits in that byte. */
1776 #define MAX_REGNUM 255
1778 /* But patterns can have more than `MAX_REGNUM' registers. We just
1779 ignore the excess. */
1780 typedef int regnum_t
;
1783 /* Macros for the compile stack. */
1785 /* Since offsets can go either forwards or backwards, this type needs to
1786 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1787 /* int may be not enough when sizeof(int) == 2. */
1788 typedef long pattern_offset_t
;
1792 pattern_offset_t begalt_offset
;
1793 pattern_offset_t fixup_alt_jump
;
1794 pattern_offset_t laststart_offset
;
1796 } compile_stack_elt_t
;
1801 compile_stack_elt_t
*stack
;
1803 size_t avail
; /* Offset of next open position. */
1804 } compile_stack_type
;
1807 #define INIT_COMPILE_STACK_SIZE 32
1809 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1810 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1812 /* The next available element. */
1813 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1815 /* Explicit quit checking is needed for Emacs, which uses polling to
1816 process input events. */
1818 # define IMMEDIATE_QUIT_CHECK \
1820 if (immediate_quit) QUIT; \
1823 # define IMMEDIATE_QUIT_CHECK ((void)0)
1826 /* Structure to manage work area for range table. */
1827 struct range_table_work_area
1829 int *table
; /* actual work area. */
1830 int allocated
; /* allocated size for work area in bytes. */
1831 int used
; /* actually used size in words. */
1832 int bits
; /* flag to record character classes */
1835 /* Make sure that WORK_AREA can hold more N multibyte characters.
1836 This is used only in set_image_of_range and set_image_of_range_1.
1837 It expects WORK_AREA to be a pointer.
1838 If it can't get the space, it returns from the surrounding function. */
1840 #define EXTEND_RANGE_TABLE(work_area, n) \
1842 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1844 extend_range_table_work_area (&work_area); \
1845 if ((work_area).table == 0) \
1846 return (REG_ESPACE); \
1850 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1851 (work_area).bits |= (bit)
1853 /* Bits used to implement the multibyte-part of the various character classes
1854 such as [:alnum:] in a charset's range table. */
1855 #define BIT_WORD 0x1
1856 #define BIT_LOWER 0x2
1857 #define BIT_PUNCT 0x4
1858 #define BIT_SPACE 0x8
1859 #define BIT_UPPER 0x10
1860 #define BIT_MULTIBYTE 0x20
1862 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1863 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1865 EXTEND_RANGE_TABLE ((work_area), 2); \
1866 (work_area).table[(work_area).used++] = (range_start); \
1867 (work_area).table[(work_area).used++] = (range_end); \
1870 /* Free allocated memory for WORK_AREA. */
1871 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1873 if ((work_area).table) \
1874 free ((work_area).table); \
1877 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1878 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1879 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1880 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1883 /* Set the bit for character C in a list. */
1884 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1889 /* Store characters in the range FROM to TO in the bitmap at B (for
1890 ASCII and unibyte characters) and WORK_AREA (for multibyte
1891 characters) while translating them and paying attention to the
1892 continuity of translated characters.
1894 Implementation note: It is better to implement these fairly big
1895 macros by a function, but it's not that easy because macros called
1896 in this macro assume various local variables already declared. */
1898 /* Both FROM and TO are ASCII characters. */
1900 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1904 for (C0 = (FROM); C0 <= (TO); C0++) \
1906 C1 = TRANSLATE (C0); \
1907 if (! ASCII_CHAR_P (C1)) \
1909 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1910 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1913 SET_LIST_BIT (C1); \
1918 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1920 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1922 int C0, C1, C2, I; \
1923 int USED = RANGE_TABLE_WORK_USED (work_area); \
1925 for (C0 = (FROM); C0 <= (TO); C0++) \
1927 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1928 if (CHAR_BYTE8_P (C1)) \
1929 SET_LIST_BIT (C0); \
1932 C2 = TRANSLATE (C1); \
1934 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1936 SET_LIST_BIT (C1); \
1937 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1939 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1940 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1942 if (C2 >= from - 1 && C2 <= to + 1) \
1944 if (C2 == from - 1) \
1945 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1946 else if (C2 == to + 1) \
1947 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1952 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1958 /* Both FROM and TO are multibyte characters. */
1960 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1962 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1964 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1965 for (C0 = (FROM); C0 <= (TO); C0++) \
1967 C1 = TRANSLATE (C0); \
1968 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1969 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1970 SET_LIST_BIT (C2); \
1971 if (C1 >= (FROM) && C1 <= (TO)) \
1973 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1975 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1976 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1978 if (C1 >= from - 1 && C1 <= to + 1) \
1980 if (C1 == from - 1) \
1981 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1982 else if (C1 == to + 1) \
1983 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1988 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1994 /* Get the next unsigned number in the uncompiled pattern. */
1995 #define GET_UNSIGNED_NUMBER(num) \
1998 FREE_STACK_RETURN (REG_EBRACE); \
2002 while ('0' <= c && c <= '9') \
2008 num = num * 10 + c - '0'; \
2009 if (num / 10 != prev) \
2010 FREE_STACK_RETURN (REG_BADBR); \
2012 FREE_STACK_RETURN (REG_EBRACE); \
2018 #if ! WIDE_CHAR_SUPPORT
2020 /* Map a string to the char class it names (if any). */
2022 re_wctype (const re_char
*str
)
2024 const char *string
= (const char *) str
;
2025 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2026 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2027 else if (STREQ (string
, "word")) return RECC_WORD
;
2028 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2029 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2030 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2031 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2032 else if (STREQ (string
, "print")) return RECC_PRINT
;
2033 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2034 else if (STREQ (string
, "space")) return RECC_SPACE
;
2035 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2036 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2037 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2038 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2039 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2040 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2041 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2045 /* True if CH is in the char class CC. */
2047 re_iswctype (int ch
, re_wctype_t cc
)
2051 case RECC_ALNUM
: return ISALNUM (ch
) != 0;
2052 case RECC_ALPHA
: return ISALPHA (ch
) != 0;
2053 case RECC_BLANK
: return ISBLANK (ch
) != 0;
2054 case RECC_CNTRL
: return ISCNTRL (ch
) != 0;
2055 case RECC_DIGIT
: return ISDIGIT (ch
) != 0;
2056 case RECC_GRAPH
: return ISGRAPH (ch
) != 0;
2057 case RECC_LOWER
: return ISLOWER (ch
) != 0;
2058 case RECC_PRINT
: return ISPRINT (ch
) != 0;
2059 case RECC_PUNCT
: return ISPUNCT (ch
) != 0;
2060 case RECC_SPACE
: return ISSPACE (ch
) != 0;
2061 case RECC_UPPER
: return ISUPPER (ch
) != 0;
2062 case RECC_XDIGIT
: return ISXDIGIT (ch
) != 0;
2063 case RECC_ASCII
: return IS_REAL_ASCII (ch
) != 0;
2064 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2065 case RECC_UNIBYTE
: return ISUNIBYTE (ch
) != 0;
2066 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2067 case RECC_WORD
: return ISWORD (ch
) != 0;
2068 case RECC_ERROR
: return false;
2074 /* Return a bit-pattern to use in the range-table bits to match multibyte
2075 chars of class CC. */
2077 re_wctype_to_bit (re_wctype_t cc
)
2081 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2082 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2083 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2084 case RECC_LOWER
: return BIT_LOWER
;
2085 case RECC_UPPER
: return BIT_UPPER
;
2086 case RECC_PUNCT
: return BIT_PUNCT
;
2087 case RECC_SPACE
: return BIT_SPACE
;
2088 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2089 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2096 /* Filling in the work area of a range. */
2098 /* Actually extend the space in WORK_AREA. */
2101 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2103 work_area
->allocated
+= 16 * sizeof (int);
2104 work_area
->table
= realloc (work_area
->table
, work_area
->allocated
);
2110 /* Carefully find the ranges of codes that are equivalent
2111 under case conversion to the range start..end when passed through
2112 TRANSLATE. Handle the case where non-letters can come in between
2113 two upper-case letters (which happens in Latin-1).
2114 Also handle the case of groups of more than 2 case-equivalent chars.
2116 The basic method is to look at consecutive characters and see
2117 if they can form a run that can be handled as one.
2119 Returns -1 if successful, REG_ESPACE if ran out of space. */
2122 set_image_of_range_1 (struct range_table_work_area
*work_area
,
2123 re_wchar_t start
, re_wchar_t end
,
2124 RE_TRANSLATE_TYPE translate
)
2126 /* `one_case' indicates a character, or a run of characters,
2127 each of which is an isolate (no case-equivalents).
2128 This includes all ASCII non-letters.
2130 `two_case' indicates a character, or a run of characters,
2131 each of which has two case-equivalent forms.
2132 This includes all ASCII letters.
2134 `strange' indicates a character that has more than one
2137 enum case_type
{one_case
, two_case
, strange
};
2139 /* Describe the run that is in progress,
2140 which the next character can try to extend.
2141 If run_type is strange, that means there really is no run.
2142 If run_type is one_case, then run_start...run_end is the run.
2143 If run_type is two_case, then the run is run_start...run_end,
2144 and the case-equivalents end at run_eqv_end. */
2146 enum case_type run_type
= strange
;
2147 int run_start
, run_end
, run_eqv_end
;
2149 Lisp_Object eqv_table
;
2151 if (!RE_TRANSLATE_P (translate
))
2153 EXTEND_RANGE_TABLE (work_area
, 2);
2154 work_area
->table
[work_area
->used
++] = (start
);
2155 work_area
->table
[work_area
->used
++] = (end
);
2159 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2161 for (; start
<= end
; start
++)
2163 enum case_type this_type
;
2164 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2165 int minchar
, maxchar
;
2167 /* Classify this character */
2169 this_type
= one_case
;
2170 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2171 this_type
= two_case
;
2173 this_type
= strange
;
2176 minchar
= start
, maxchar
= eqv
;
2178 minchar
= eqv
, maxchar
= start
;
2180 /* Can this character extend the run in progress? */
2181 if (this_type
== strange
|| this_type
!= run_type
2182 || !(minchar
== run_end
+ 1
2183 && (run_type
== two_case
2184 ? maxchar
== run_eqv_end
+ 1 : 1)))
2187 Record each of its equivalent ranges. */
2188 if (run_type
== one_case
)
2190 EXTEND_RANGE_TABLE (work_area
, 2);
2191 work_area
->table
[work_area
->used
++] = run_start
;
2192 work_area
->table
[work_area
->used
++] = run_end
;
2194 else if (run_type
== two_case
)
2196 EXTEND_RANGE_TABLE (work_area
, 4);
2197 work_area
->table
[work_area
->used
++] = run_start
;
2198 work_area
->table
[work_area
->used
++] = run_end
;
2199 work_area
->table
[work_area
->used
++]
2200 = RE_TRANSLATE (eqv_table
, run_start
);
2201 work_area
->table
[work_area
->used
++]
2202 = RE_TRANSLATE (eqv_table
, run_end
);
2207 if (this_type
== strange
)
2209 /* For a strange character, add each of its equivalents, one
2210 by one. Don't start a range. */
2213 EXTEND_RANGE_TABLE (work_area
, 2);
2214 work_area
->table
[work_area
->used
++] = eqv
;
2215 work_area
->table
[work_area
->used
++] = eqv
;
2216 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2218 while (eqv
!= start
);
2221 /* Add this char to the run, or start a new run. */
2222 else if (run_type
== strange
)
2224 /* Initialize a new range. */
2225 run_type
= this_type
;
2228 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2232 /* Extend a running range. */
2234 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2238 /* If a run is still in progress at the end, finish it now
2239 by recording its equivalent ranges. */
2240 if (run_type
== one_case
)
2242 EXTEND_RANGE_TABLE (work_area
, 2);
2243 work_area
->table
[work_area
->used
++] = run_start
;
2244 work_area
->table
[work_area
->used
++] = run_end
;
2246 else if (run_type
== two_case
)
2248 EXTEND_RANGE_TABLE (work_area
, 4);
2249 work_area
->table
[work_area
->used
++] = run_start
;
2250 work_area
->table
[work_area
->used
++] = run_end
;
2251 work_area
->table
[work_area
->used
++]
2252 = RE_TRANSLATE (eqv_table
, run_start
);
2253 work_area
->table
[work_area
->used
++]
2254 = RE_TRANSLATE (eqv_table
, run_end
);
2262 /* Record the image of the range start..end when passed through
2263 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2264 and is not even necessarily contiguous.
2265 Normally we approximate it with the smallest contiguous range that contains
2266 all the chars we need. However, for Latin-1 we go to extra effort
2269 This function is not called for ASCII ranges.
2271 Returns -1 if successful, REG_ESPACE if ran out of space. */
2274 set_image_of_range (struct range_table_work_area
*work_area
,
2275 re_wchar_t start
, re_wchar_t end
,
2276 RE_TRANSLATE_TYPE translate
)
2278 re_wchar_t cmin
, cmax
;
2281 /* For Latin-1 ranges, use set_image_of_range_1
2282 to get proper handling of ranges that include letters and nonletters.
2283 For a range that includes the whole of Latin-1, this is not necessary.
2284 For other character sets, we don't bother to get this right. */
2285 if (RE_TRANSLATE_P (translate
) && start
< 04400
2286 && !(start
< 04200 && end
>= 04377))
2293 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2303 EXTEND_RANGE_TABLE (work_area
, 2);
2304 work_area
->table
[work_area
->used
++] = (start
);
2305 work_area
->table
[work_area
->used
++] = (end
);
2307 cmin
= -1, cmax
= -1;
2309 if (RE_TRANSLATE_P (translate
))
2313 for (ch
= start
; ch
<= end
; ch
++)
2315 re_wchar_t c
= TRANSLATE (ch
);
2316 if (! (start
<= c
&& c
<= end
))
2322 cmin
= MIN (cmin
, c
);
2323 cmax
= MAX (cmax
, c
);
2330 EXTEND_RANGE_TABLE (work_area
, 2);
2331 work_area
->table
[work_area
->used
++] = (cmin
);
2332 work_area
->table
[work_area
->used
++] = (cmax
);
2340 #ifndef MATCH_MAY_ALLOCATE
2342 /* If we cannot allocate large objects within re_match_2_internal,
2343 we make the fail stack and register vectors global.
2344 The fail stack, we grow to the maximum size when a regexp
2346 The register vectors, we adjust in size each time we
2347 compile a regexp, according to the number of registers it needs. */
2349 static fail_stack_type fail_stack
;
2351 /* Size with which the following vectors are currently allocated.
2352 That is so we can make them bigger as needed,
2353 but never make them smaller. */
2354 static int regs_allocated_size
;
2356 static re_char
** regstart
, ** regend
;
2357 static re_char
**best_regstart
, **best_regend
;
2359 /* Make the register vectors big enough for NUM_REGS registers,
2360 but don't make them smaller. */
2363 regex_grow_registers (int num_regs
)
2365 if (num_regs
> regs_allocated_size
)
2367 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2368 RETALLOC_IF (regend
, num_regs
, re_char
*);
2369 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2370 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2372 regs_allocated_size
= num_regs
;
2376 #endif /* not MATCH_MAY_ALLOCATE */
2378 static boolean
group_in_compile_stack (compile_stack_type compile_stack
,
2381 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2382 Returns one of error codes defined in `regex.h', or zero for success.
2384 Assumes the `allocated' (and perhaps `buffer') and `translate'
2385 fields are set in BUFP on entry.
2387 If it succeeds, results are put in BUFP (if it returns an error, the
2388 contents of BUFP are undefined):
2389 `buffer' is the compiled pattern;
2390 `syntax' is set to SYNTAX;
2391 `used' is set to the length of the compiled pattern;
2392 `fastmap_accurate' is zero;
2393 `re_nsub' is the number of subexpressions in PATTERN;
2394 `not_bol' and `not_eol' are zero;
2396 The `fastmap' field is neither examined nor set. */
2398 /* Insert the `jump' from the end of last alternative to "here".
2399 The space for the jump has already been allocated. */
2400 #define FIXUP_ALT_JUMP() \
2402 if (fixup_alt_jump) \
2403 STORE_JUMP (jump, fixup_alt_jump, b); \
2407 /* Return, freeing storage we allocated. */
2408 #define FREE_STACK_RETURN(value) \
2410 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2411 free (compile_stack.stack); \
2415 static reg_errcode_t
2416 regex_compile (const re_char
*pattern
, size_t size
, reg_syntax_t syntax
, struct re_pattern_buffer
*bufp
)
2418 /* We fetch characters from PATTERN here. */
2419 register re_wchar_t c
, c1
;
2421 /* Points to the end of the buffer, where we should append. */
2422 register unsigned char *b
;
2424 /* Keeps track of unclosed groups. */
2425 compile_stack_type compile_stack
;
2427 /* Points to the current (ending) position in the pattern. */
2429 /* `const' makes AIX compiler fail. */
2430 unsigned char *p
= pattern
;
2432 re_char
*p
= pattern
;
2434 re_char
*pend
= pattern
+ size
;
2436 /* How to translate the characters in the pattern. */
2437 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2439 /* Address of the count-byte of the most recently inserted `exactn'
2440 command. This makes it possible to tell if a new exact-match
2441 character can be added to that command or if the character requires
2442 a new `exactn' command. */
2443 unsigned char *pending_exact
= 0;
2445 /* Address of start of the most recently finished expression.
2446 This tells, e.g., postfix * where to find the start of its
2447 operand. Reset at the beginning of groups and alternatives. */
2448 unsigned char *laststart
= 0;
2450 /* Address of beginning of regexp, or inside of last group. */
2451 unsigned char *begalt
;
2453 /* Place in the uncompiled pattern (i.e., the {) to
2454 which to go back if the interval is invalid. */
2455 re_char
*beg_interval
;
2457 /* Address of the place where a forward jump should go to the end of
2458 the containing expression. Each alternative of an `or' -- except the
2459 last -- ends with a forward jump of this sort. */
2460 unsigned char *fixup_alt_jump
= 0;
2462 /* Work area for range table of charset. */
2463 struct range_table_work_area range_table_work
;
2465 /* If the object matched can contain multibyte characters. */
2466 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2468 /* Nonzero if we have pushed down into a subpattern. */
2469 int in_subpattern
= 0;
2471 /* These hold the values of p, pattern, and pend from the main
2472 pattern when we have pushed into a subpattern. */
2473 re_char
*main_p
IF_LINT (= NULL
);
2474 re_char
*main_pattern
IF_LINT (= NULL
);
2475 re_char
*main_pend
IF_LINT (= NULL
);
2479 DEBUG_PRINT ("\nCompiling pattern: ");
2482 unsigned debug_count
;
2484 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2485 putchar (pattern
[debug_count
]);
2490 /* Initialize the compile stack. */
2491 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2492 if (compile_stack
.stack
== NULL
)
2495 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2496 compile_stack
.avail
= 0;
2498 range_table_work
.table
= 0;
2499 range_table_work
.allocated
= 0;
2501 /* Initialize the pattern buffer. */
2502 bufp
->syntax
= syntax
;
2503 bufp
->fastmap_accurate
= 0;
2504 bufp
->not_bol
= bufp
->not_eol
= 0;
2505 bufp
->used_syntax
= 0;
2507 /* Set `used' to zero, so that if we return an error, the pattern
2508 printer (for debugging) will think there's no pattern. We reset it
2512 /* Always count groups, whether or not bufp->no_sub is set. */
2515 #if !defined emacs && !defined SYNTAX_TABLE
2516 /* Initialize the syntax table. */
2517 init_syntax_once ();
2520 if (bufp
->allocated
== 0)
2523 { /* If zero allocated, but buffer is non-null, try to realloc
2524 enough space. This loses if buffer's address is bogus, but
2525 that is the user's responsibility. */
2526 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2529 { /* Caller did not allocate a buffer. Do it for them. */
2530 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2532 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2534 bufp
->allocated
= INIT_BUF_SIZE
;
2537 begalt
= b
= bufp
->buffer
;
2539 /* Loop through the uncompiled pattern until we're at the end. */
2544 /* If this is the end of an included regexp,
2545 pop back to the main regexp and try again. */
2549 pattern
= main_pattern
;
2554 /* If this is the end of the main regexp, we are done. */
2566 /* If there's no special whitespace regexp, treat
2567 spaces normally. And don't try to do this recursively. */
2568 if (!whitespace_regexp
|| in_subpattern
)
2571 /* Peek past following spaces. */
2578 /* If the spaces are followed by a repetition op,
2579 treat them normally. */
2581 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2582 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2585 /* Replace the spaces with the whitespace regexp. */
2589 main_pattern
= pattern
;
2590 p
= pattern
= whitespace_regexp
;
2591 pend
= p
+ strlen ((const char *) p
);
2597 if ( /* If at start of pattern, it's an operator. */
2599 /* If context independent, it's an operator. */
2600 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2601 /* Otherwise, depends on what's come before. */
2602 || at_begline_loc_p (pattern
, p
, syntax
))
2603 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2612 if ( /* If at end of pattern, it's an operator. */
2614 /* If context independent, it's an operator. */
2615 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2616 /* Otherwise, depends on what's next. */
2617 || at_endline_loc_p (p
, pend
, syntax
))
2618 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2627 if ((syntax
& RE_BK_PLUS_QM
)
2628 || (syntax
& RE_LIMITED_OPS
))
2632 /* If there is no previous pattern... */
2635 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2636 FREE_STACK_RETURN (REG_BADRPT
);
2637 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2642 /* 1 means zero (many) matches is allowed. */
2643 boolean zero_times_ok
= 0, many_times_ok
= 0;
2646 /* If there is a sequence of repetition chars, collapse it
2647 down to just one (the right one). We can't combine
2648 interval operators with these because of, e.g., `a{2}*',
2649 which should only match an even number of `a's. */
2653 if ((syntax
& RE_FRUGAL
)
2654 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2658 zero_times_ok
|= c
!= '+';
2659 many_times_ok
|= c
!= '?';
2665 || (!(syntax
& RE_BK_PLUS_QM
)
2666 && (*p
== '+' || *p
== '?')))
2668 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2671 FREE_STACK_RETURN (REG_EESCAPE
);
2672 if (p
[1] == '+' || p
[1] == '?')
2673 PATFETCH (c
); /* Gobble up the backslash. */
2679 /* If we get here, we found another repeat character. */
2683 /* Star, etc. applied to an empty pattern is equivalent
2684 to an empty pattern. */
2685 if (!laststart
|| laststart
== b
)
2688 /* Now we know whether or not zero matches is allowed
2689 and also whether or not two or more matches is allowed. */
2694 boolean simple
= skip_one_char (laststart
) == b
;
2695 size_t startoffset
= 0;
2697 /* Check if the loop can match the empty string. */
2698 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2699 ? on_failure_jump
: on_failure_jump_loop
;
2700 assert (skip_one_char (laststart
) <= b
);
2702 if (!zero_times_ok
&& simple
)
2703 { /* Since simple * loops can be made faster by using
2704 on_failure_keep_string_jump, we turn simple P+
2705 into PP* if P is simple. */
2706 unsigned char *p1
, *p2
;
2707 startoffset
= b
- laststart
;
2708 GET_BUFFER_SPACE (startoffset
);
2709 p1
= b
; p2
= laststart
;
2715 GET_BUFFER_SPACE (6);
2718 STORE_JUMP (ofj
, b
, b
+ 6);
2720 /* Simple * loops can use on_failure_keep_string_jump
2721 depending on what follows. But since we don't know
2722 that yet, we leave the decision up to
2723 on_failure_jump_smart. */
2724 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2725 laststart
+ startoffset
, b
+ 6);
2727 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2732 /* A simple ? pattern. */
2733 assert (zero_times_ok
);
2734 GET_BUFFER_SPACE (3);
2735 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2739 else /* not greedy */
2740 { /* I wish the greedy and non-greedy cases could be merged. */
2742 GET_BUFFER_SPACE (7); /* We might use less. */
2745 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2747 /* The non-greedy multiple match looks like
2748 a repeat..until: we only need a conditional jump
2749 at the end of the loop. */
2750 if (emptyp
) BUF_PUSH (no_op
);
2751 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2752 : on_failure_jump
, b
, laststart
);
2756 /* The repeat...until naturally matches one or more.
2757 To also match zero times, we need to first jump to
2758 the end of the loop (its conditional jump). */
2759 INSERT_JUMP (jump
, laststart
, b
);
2765 /* non-greedy a?? */
2766 INSERT_JUMP (jump
, laststart
, b
+ 3);
2768 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2787 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2789 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2791 /* Ensure that we have enough space to push a charset: the
2792 opcode, the length count, and the bitset; 34 bytes in all. */
2793 GET_BUFFER_SPACE (34);
2797 /* We test `*p == '^' twice, instead of using an if
2798 statement, so we only need one BUF_PUSH. */
2799 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2803 /* Remember the first position in the bracket expression. */
2806 /* Push the number of bytes in the bitmap. */
2807 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2809 /* Clear the whole map. */
2810 memset (b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2812 /* charset_not matches newline according to a syntax bit. */
2813 if ((re_opcode_t
) b
[-2] == charset_not
2814 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2815 SET_LIST_BIT ('\n');
2817 /* Read in characters and ranges, setting map bits. */
2820 boolean escaped_char
= false;
2821 const unsigned char *p2
= p
;
2824 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2826 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2827 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2828 So the translation is done later in a loop. Example:
2829 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2832 /* \ might escape characters inside [...] and [^...]. */
2833 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2835 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2838 escaped_char
= true;
2842 /* Could be the end of the bracket expression. If it's
2843 not (i.e., when the bracket expression is `[]' so
2844 far), the ']' character bit gets set way below. */
2845 if (c
== ']' && p2
!= p1
)
2849 /* See if we're at the beginning of a possible character
2852 if (!escaped_char
&&
2853 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2855 /* Leave room for the null. */
2856 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2857 const unsigned char *class_beg
;
2863 /* If pattern is `[[:'. */
2864 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2869 if ((c
== ':' && *p
== ']') || p
== pend
)
2871 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2874 /* This is in any case an invalid class name. */
2879 /* If isn't a word bracketed by `[:' and `:]':
2880 undo the ending character, the letters, and
2881 leave the leading `:' and `[' (but set bits for
2883 if (c
== ':' && *p
== ']')
2885 re_wctype_t cc
= re_wctype (str
);
2888 FREE_STACK_RETURN (REG_ECTYPE
);
2890 /* Throw away the ] at the end of the character
2894 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2897 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
2898 if (re_iswctype (btowc (ch
), cc
))
2901 if (c
< (1 << BYTEWIDTH
))
2905 /* Most character classes in a multibyte match
2906 just set a flag. Exceptions are is_blank,
2907 is_digit, is_cntrl, and is_xdigit, since
2908 they can only match ASCII characters. We
2909 don't need to handle them for multibyte.
2910 They are distinguished by a negative wctype. */
2912 /* Setup the gl_state object to its buffer-defined
2913 value. This hardcodes the buffer-global
2914 syntax-table for ASCII chars, while the other chars
2915 will obey syntax-table properties. It's not ideal,
2916 but it's the way it's been done until now. */
2917 SETUP_BUFFER_SYNTAX_TABLE ();
2919 for (ch
= 0; ch
< 256; ++ch
)
2921 c
= RE_CHAR_TO_MULTIBYTE (ch
);
2922 if (! CHAR_BYTE8_P (c
)
2923 && re_iswctype (c
, cc
))
2929 if (ASCII_CHAR_P (c1
))
2931 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
2935 SET_RANGE_TABLE_WORK_AREA_BIT
2936 (range_table_work
, re_wctype_to_bit (cc
));
2938 /* In most cases the matching rule for char classes
2939 only uses the syntax table for multibyte chars,
2940 so that the content of the syntax-table it is not
2941 hardcoded in the range_table. SPACE and WORD are
2942 the two exceptions. */
2943 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
2944 bufp
->used_syntax
= 1;
2946 /* Repeat the loop. */
2951 /* Go back to right after the "[:". */
2955 /* Because the `:' may starts the range, we
2956 can't simply set bit and repeat the loop.
2957 Instead, just set it to C and handle below. */
2962 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2965 /* Discard the `-'. */
2968 /* Fetch the character which ends the range. */
2971 if (CHAR_BYTE8_P (c1
)
2972 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
2973 /* Treat the range from a multibyte character to
2974 raw-byte character as empty. */
2979 /* Range from C to C. */
2984 if (syntax
& RE_NO_EMPTY_RANGES
)
2985 FREE_STACK_RETURN (REG_ERANGEX
);
2986 /* Else, repeat the loop. */
2991 /* Set the range into bitmap */
2992 for (; c
<= c1
; c
++)
2995 if (ch
< (1 << BYTEWIDTH
))
3002 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
3004 if (CHAR_BYTE8_P (c1
))
3005 c
= BYTE8_TO_CHAR (128);
3009 if (CHAR_BYTE8_P (c
))
3011 c
= CHAR_TO_BYTE8 (c
);
3012 c1
= CHAR_TO_BYTE8 (c1
);
3013 for (; c
<= c1
; c
++)
3018 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
3022 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
3029 /* Discard any (non)matching list bytes that are all 0 at the
3030 end of the map. Decrease the map-length byte too. */
3031 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3035 /* Build real range table from work area. */
3036 if (RANGE_TABLE_WORK_USED (range_table_work
)
3037 || RANGE_TABLE_WORK_BITS (range_table_work
))
3040 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3042 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3043 bytes for flags, two for COUNT, and three bytes for
3045 GET_BUFFER_SPACE (4 + used
* 3);
3047 /* Indicate the existence of range table. */
3048 laststart
[1] |= 0x80;
3050 /* Store the character class flag bits into the range table.
3051 If not in emacs, these flag bits are always 0. */
3052 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3053 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3055 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3056 for (i
= 0; i
< used
; i
++)
3057 STORE_CHARACTER_AND_INCR
3058 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3065 if (syntax
& RE_NO_BK_PARENS
)
3072 if (syntax
& RE_NO_BK_PARENS
)
3079 if (syntax
& RE_NEWLINE_ALT
)
3086 if (syntax
& RE_NO_BK_VBAR
)
3093 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3094 goto handle_interval
;
3100 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3102 /* Do not translate the character after the \, so that we can
3103 distinguish, e.g., \B from \b, even if we normally would
3104 translate, e.g., B to b. */
3110 if (syntax
& RE_NO_BK_PARENS
)
3111 goto normal_backslash
;
3116 regnum_t regnum
= 0;
3119 /* Look for a special (?...) construct */
3120 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3122 PATFETCH (c
); /* Gobble up the '?'. */
3128 case ':': shy
= 1; break;
3130 /* An explicitly specified regnum must start
3133 FREE_STACK_RETURN (REG_BADPAT
);
3134 case '1': case '2': case '3': case '4':
3135 case '5': case '6': case '7': case '8': case '9':
3136 regnum
= 10*regnum
+ (c
- '0'); break;
3138 /* Only (?:...) is supported right now. */
3139 FREE_STACK_RETURN (REG_BADPAT
);
3146 regnum
= ++bufp
->re_nsub
;
3148 { /* It's actually not shy, but explicitly numbered. */
3150 if (regnum
> bufp
->re_nsub
)
3151 bufp
->re_nsub
= regnum
;
3152 else if (regnum
> bufp
->re_nsub
3153 /* Ideally, we'd want to check that the specified
3154 group can't have matched (i.e. all subgroups
3155 using the same regnum are in other branches of
3156 OR patterns), but we don't currently keep track
3157 of enough info to do that easily. */
3158 || group_in_compile_stack (compile_stack
, regnum
))
3159 FREE_STACK_RETURN (REG_BADPAT
);
3162 /* It's really shy. */
3163 regnum
= - bufp
->re_nsub
;
3165 if (COMPILE_STACK_FULL
)
3167 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3168 compile_stack_elt_t
);
3169 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3171 compile_stack
.size
<<= 1;
3174 /* These are the values to restore when we hit end of this
3175 group. They are all relative offsets, so that if the
3176 whole pattern moves because of realloc, they will still
3178 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3179 COMPILE_STACK_TOP
.fixup_alt_jump
3180 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3181 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3182 COMPILE_STACK_TOP
.regnum
= regnum
;
3184 /* Do not push a start_memory for groups beyond the last one
3185 we can represent in the compiled pattern. */
3186 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3187 BUF_PUSH_2 (start_memory
, regnum
);
3189 compile_stack
.avail
++;
3194 /* If we've reached MAX_REGNUM groups, then this open
3195 won't actually generate any code, so we'll have to
3196 clear pending_exact explicitly. */
3202 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3204 if (COMPILE_STACK_EMPTY
)
3206 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3207 goto normal_backslash
;
3209 FREE_STACK_RETURN (REG_ERPAREN
);
3215 /* See similar code for backslashed left paren above. */
3216 if (COMPILE_STACK_EMPTY
)
3218 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3221 FREE_STACK_RETURN (REG_ERPAREN
);
3224 /* Since we just checked for an empty stack above, this
3225 ``can't happen''. */
3226 assert (compile_stack
.avail
!= 0);
3228 /* We don't just want to restore into `regnum', because
3229 later groups should continue to be numbered higher,
3230 as in `(ab)c(de)' -- the second group is #2. */
3233 compile_stack
.avail
--;
3234 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3236 = COMPILE_STACK_TOP
.fixup_alt_jump
3237 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3239 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3240 regnum
= COMPILE_STACK_TOP
.regnum
;
3241 /* If we've reached MAX_REGNUM groups, then this open
3242 won't actually generate any code, so we'll have to
3243 clear pending_exact explicitly. */
3246 /* We're at the end of the group, so now we know how many
3247 groups were inside this one. */
3248 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3249 BUF_PUSH_2 (stop_memory
, regnum
);
3254 case '|': /* `\|'. */
3255 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3256 goto normal_backslash
;
3258 if (syntax
& RE_LIMITED_OPS
)
3261 /* Insert before the previous alternative a jump which
3262 jumps to this alternative if the former fails. */
3263 GET_BUFFER_SPACE (3);
3264 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3268 /* The alternative before this one has a jump after it
3269 which gets executed if it gets matched. Adjust that
3270 jump so it will jump to this alternative's analogous
3271 jump (put in below, which in turn will jump to the next
3272 (if any) alternative's such jump, etc.). The last such
3273 jump jumps to the correct final destination. A picture:
3279 If we are at `b', then fixup_alt_jump right now points to a
3280 three-byte space after `a'. We'll put in the jump, set
3281 fixup_alt_jump to right after `b', and leave behind three
3282 bytes which we'll fill in when we get to after `c'. */
3286 /* Mark and leave space for a jump after this alternative,
3287 to be filled in later either by next alternative or
3288 when know we're at the end of a series of alternatives. */
3290 GET_BUFFER_SPACE (3);
3299 /* If \{ is a literal. */
3300 if (!(syntax
& RE_INTERVALS
)
3301 /* If we're at `\{' and it's not the open-interval
3303 || (syntax
& RE_NO_BK_BRACES
))
3304 goto normal_backslash
;
3308 /* If got here, then the syntax allows intervals. */
3310 /* At least (most) this many matches must be made. */
3311 int lower_bound
= 0, upper_bound
= -1;
3315 GET_UNSIGNED_NUMBER (lower_bound
);
3318 GET_UNSIGNED_NUMBER (upper_bound
);
3320 /* Interval such as `{1}' => match exactly once. */
3321 upper_bound
= lower_bound
;
3323 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3324 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3325 FREE_STACK_RETURN (REG_BADBR
);
3327 if (!(syntax
& RE_NO_BK_BRACES
))
3330 FREE_STACK_RETURN (REG_BADBR
);
3332 FREE_STACK_RETURN (REG_EESCAPE
);
3337 FREE_STACK_RETURN (REG_BADBR
);
3339 /* We just parsed a valid interval. */
3341 /* If it's invalid to have no preceding re. */
3344 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3345 FREE_STACK_RETURN (REG_BADRPT
);
3346 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3349 goto unfetch_interval
;
3352 if (upper_bound
== 0)
3353 /* If the upper bound is zero, just drop the sub pattern
3356 else if (lower_bound
== 1 && upper_bound
== 1)
3357 /* Just match it once: nothing to do here. */
3360 /* Otherwise, we have a nontrivial interval. When
3361 we're all done, the pattern will look like:
3362 set_number_at <jump count> <upper bound>
3363 set_number_at <succeed_n count> <lower bound>
3364 succeed_n <after jump addr> <succeed_n count>
3366 jump_n <succeed_n addr> <jump count>
3367 (The upper bound and `jump_n' are omitted if
3368 `upper_bound' is 1, though.) */
3370 { /* If the upper bound is > 1, we need to insert
3371 more at the end of the loop. */
3372 unsigned int nbytes
= (upper_bound
< 0 ? 3
3373 : upper_bound
> 1 ? 5 : 0);
3374 unsigned int startoffset
= 0;
3376 GET_BUFFER_SPACE (20); /* We might use less. */
3378 if (lower_bound
== 0)
3380 /* A succeed_n that starts with 0 is really a
3381 a simple on_failure_jump_loop. */
3382 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3388 /* Initialize lower bound of the `succeed_n', even
3389 though it will be set during matching by its
3390 attendant `set_number_at' (inserted next),
3391 because `re_compile_fastmap' needs to know.
3392 Jump to the `jump_n' we might insert below. */
3393 INSERT_JUMP2 (succeed_n
, laststart
,
3398 /* Code to initialize the lower bound. Insert
3399 before the `succeed_n'. The `5' is the last two
3400 bytes of this `set_number_at', plus 3 bytes of
3401 the following `succeed_n'. */
3402 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3407 if (upper_bound
< 0)
3409 /* A negative upper bound stands for infinity,
3410 in which case it degenerates to a plain jump. */
3411 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3414 else if (upper_bound
> 1)
3415 { /* More than one repetition is allowed, so
3416 append a backward jump to the `succeed_n'
3417 that starts this interval.
3419 When we've reached this during matching,
3420 we'll have matched the interval once, so
3421 jump back only `upper_bound - 1' times. */
3422 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3426 /* The location we want to set is the second
3427 parameter of the `jump_n'; that is `b-2' as
3428 an absolute address. `laststart' will be
3429 the `set_number_at' we're about to insert;
3430 `laststart+3' the number to set, the source
3431 for the relative address. But we are
3432 inserting into the middle of the pattern --
3433 so everything is getting moved up by 5.
3434 Conclusion: (b - 2) - (laststart + 3) + 5,
3435 i.e., b - laststart.
3437 We insert this at the beginning of the loop
3438 so that if we fail during matching, we'll
3439 reinitialize the bounds. */
3440 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3441 upper_bound
- 1, b
);
3446 beg_interval
= NULL
;
3451 /* If an invalid interval, match the characters as literals. */
3452 assert (beg_interval
);
3454 beg_interval
= NULL
;
3456 /* normal_char and normal_backslash need `c'. */
3459 if (!(syntax
& RE_NO_BK_BRACES
))
3461 assert (p
> pattern
&& p
[-1] == '\\');
3462 goto normal_backslash
;
3468 /* There is no way to specify the before_dot and after_dot
3469 operators. rms says this is ok. --karl */
3478 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3484 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3490 BUF_PUSH_2 (categoryspec
, c
);
3496 BUF_PUSH_2 (notcategoryspec
, c
);
3502 if (syntax
& RE_NO_GNU_OPS
)
3505 BUF_PUSH_2 (syntaxspec
, Sword
);
3510 if (syntax
& RE_NO_GNU_OPS
)
3513 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3518 if (syntax
& RE_NO_GNU_OPS
)
3525 if (syntax
& RE_NO_GNU_OPS
)
3532 if (syntax
& RE_NO_GNU_OPS
)
3541 FREE_STACK_RETURN (REG_BADPAT
);
3545 if (syntax
& RE_NO_GNU_OPS
)
3547 BUF_PUSH (wordbound
);
3551 if (syntax
& RE_NO_GNU_OPS
)
3553 BUF_PUSH (notwordbound
);
3557 if (syntax
& RE_NO_GNU_OPS
)
3563 if (syntax
& RE_NO_GNU_OPS
)
3568 case '1': case '2': case '3': case '4': case '5':
3569 case '6': case '7': case '8': case '9':
3573 if (syntax
& RE_NO_BK_REFS
)
3574 goto normal_backslash
;
3578 if (reg
> bufp
->re_nsub
|| reg
< 1
3579 /* Can't back reference to a subexp before its end. */
3580 || group_in_compile_stack (compile_stack
, reg
))
3581 FREE_STACK_RETURN (REG_ESUBREG
);
3584 BUF_PUSH_2 (duplicate
, reg
);
3591 if (syntax
& RE_BK_PLUS_QM
)
3594 goto normal_backslash
;
3598 /* You might think it would be useful for \ to mean
3599 not to translate; but if we don't translate it
3600 it will never match anything. */
3607 /* Expects the character in `c'. */
3609 /* If no exactn currently being built. */
3612 /* If last exactn not at current position. */
3613 || pending_exact
+ *pending_exact
+ 1 != b
3615 /* We have only one byte following the exactn for the count. */
3616 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3618 /* If followed by a repetition operator. */
3619 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3620 || ((syntax
& RE_BK_PLUS_QM
)
3621 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3622 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3623 || ((syntax
& RE_INTERVALS
)
3624 && ((syntax
& RE_NO_BK_BRACES
)
3625 ? p
!= pend
&& *p
== '{'
3626 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3628 /* Start building a new exactn. */
3632 BUF_PUSH_2 (exactn
, 0);
3633 pending_exact
= b
- 1;
3636 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3643 len
= CHAR_STRING (c
, b
);
3648 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3649 if (! CHAR_BYTE8_P (c1
))
3651 re_wchar_t c2
= TRANSLATE (c1
);
3653 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3659 (*pending_exact
) += len
;
3664 } /* while p != pend */
3667 /* Through the pattern now. */
3671 if (!COMPILE_STACK_EMPTY
)
3672 FREE_STACK_RETURN (REG_EPAREN
);
3674 /* If we don't want backtracking, force success
3675 the first time we reach the end of the compiled pattern. */
3676 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3679 /* We have succeeded; set the length of the buffer. */
3680 bufp
->used
= b
- bufp
->buffer
;
3685 re_compile_fastmap (bufp
);
3686 DEBUG_PRINT ("\nCompiled pattern: \n");
3687 print_compiled_pattern (bufp
);
3692 #ifndef MATCH_MAY_ALLOCATE
3693 /* Initialize the failure stack to the largest possible stack. This
3694 isn't necessary unless we're trying to avoid calling alloca in
3695 the search and match routines. */
3697 int num_regs
= bufp
->re_nsub
+ 1;
3699 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3701 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3702 falk_stack
.stack
= realloc (fail_stack
.stack
,
3703 fail_stack
.size
* sizeof *falk_stack
.stack
);
3706 regex_grow_registers (num_regs
);
3708 #endif /* not MATCH_MAY_ALLOCATE */
3710 FREE_STACK_RETURN (REG_NOERROR
);
3711 } /* regex_compile */
3713 /* Subroutines for `regex_compile'. */
3715 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3718 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3720 *loc
= (unsigned char) op
;
3721 STORE_NUMBER (loc
+ 1, arg
);
3725 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3728 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3730 *loc
= (unsigned char) op
;
3731 STORE_NUMBER (loc
+ 1, arg1
);
3732 STORE_NUMBER (loc
+ 3, arg2
);
3736 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3737 for OP followed by two-byte integer parameter ARG. */
3740 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3742 register unsigned char *pfrom
= end
;
3743 register unsigned char *pto
= end
+ 3;
3745 while (pfrom
!= loc
)
3748 store_op1 (op
, loc
, arg
);
3752 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3755 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3757 register unsigned char *pfrom
= end
;
3758 register unsigned char *pto
= end
+ 5;
3760 while (pfrom
!= loc
)
3763 store_op2 (op
, loc
, arg1
, arg2
);
3767 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3768 after an alternative or a begin-subexpression. We assume there is at
3769 least one character before the ^. */
3772 at_begline_loc_p (const re_char
*pattern
, const re_char
*p
, reg_syntax_t syntax
)
3774 re_char
*prev
= p
- 2;
3775 boolean odd_backslashes
;
3777 /* After a subexpression? */
3779 odd_backslashes
= (syntax
& RE_NO_BK_PARENS
) == 0;
3781 /* After an alternative? */
3782 else if (*prev
== '|')
3783 odd_backslashes
= (syntax
& RE_NO_BK_VBAR
) == 0;
3785 /* After a shy subexpression? */
3786 else if (*prev
== ':' && (syntax
& RE_SHY_GROUPS
))
3788 /* Skip over optional regnum. */
3789 while (prev
- 1 >= pattern
&& prev
[-1] >= '0' && prev
[-1] <= '9')
3792 if (!(prev
- 2 >= pattern
3793 && prev
[-1] == '?' && prev
[-2] == '('))
3796 odd_backslashes
= (syntax
& RE_NO_BK_PARENS
) == 0;
3801 /* Count the number of preceding backslashes. */
3803 while (prev
- 1 >= pattern
&& prev
[-1] == '\\')
3805 return (p
- prev
) & odd_backslashes
;
3809 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3810 at least one character after the $, i.e., `P < PEND'. */
3813 at_endline_loc_p (const re_char
*p
, const re_char
*pend
, reg_syntax_t syntax
)
3816 boolean next_backslash
= *next
== '\\';
3817 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3820 /* Before a subexpression? */
3821 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3822 : next_backslash
&& next_next
&& *next_next
== ')')
3823 /* Before an alternative? */
3824 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3825 : next_backslash
&& next_next
&& *next_next
== '|');
3829 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3830 false if it's not. */
3833 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3835 ssize_t this_element
;
3837 for (this_element
= compile_stack
.avail
- 1;
3840 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3847 If fastmap is non-NULL, go through the pattern and fill fastmap
3848 with all the possible leading chars. If fastmap is NULL, don't
3849 bother filling it up (obviously) and only return whether the
3850 pattern could potentially match the empty string.
3852 Return 1 if p..pend might match the empty string.
3853 Return 0 if p..pend matches at least one char.
3854 Return -1 if fastmap was not updated accurately. */
3857 analyse_first (const re_char
*p
, const re_char
*pend
, char *fastmap
, const int multibyte
)
3862 /* If all elements for base leading-codes in fastmap is set, this
3863 flag is set true. */
3864 boolean match_any_multibyte_characters
= false;
3868 /* The loop below works as follows:
3869 - It has a working-list kept in the PATTERN_STACK and which basically
3870 starts by only containing a pointer to the first operation.
3871 - If the opcode we're looking at is a match against some set of
3872 chars, then we add those chars to the fastmap and go on to the
3873 next work element from the worklist (done via `break').
3874 - If the opcode is a control operator on the other hand, we either
3875 ignore it (if it's meaningless at this point, such as `start_memory')
3876 or execute it (if it's a jump). If the jump has several destinations
3877 (i.e. `on_failure_jump'), then we push the other destination onto the
3879 We guarantee termination by ignoring backward jumps (more or less),
3880 so that `p' is monotonically increasing. More to the point, we
3881 never set `p' (or push) anything `<= p1'. */
3885 /* `p1' is used as a marker of how far back a `on_failure_jump'
3886 can go without being ignored. It is normally equal to `p'
3887 (which prevents any backward `on_failure_jump') except right
3888 after a plain `jump', to allow patterns such as:
3891 10: on_failure_jump 3
3892 as used for the *? operator. */
3901 /* If the first character has to match a backreference, that means
3902 that the group was empty (since it already matched). Since this
3903 is the only case that interests us here, we can assume that the
3904 backreference must match the empty string. */
3909 /* Following are the cases which match a character. These end
3915 /* If multibyte is nonzero, the first byte of each
3916 character is an ASCII or a leading code. Otherwise,
3917 each byte is a character. Thus, this works in both
3922 /* For the case of matching this unibyte regex
3923 against multibyte, we must set a leading code of
3924 the corresponding multibyte character. */
3925 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
3927 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
3934 /* We could put all the chars except for \n (and maybe \0)
3935 but we don't bother since it is generally not worth it. */
3936 if (!fastmap
) break;
3941 if (!fastmap
) break;
3943 /* Chars beyond end of bitmap are possible matches. */
3944 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3945 j
< (1 << BYTEWIDTH
); j
++)
3951 if (!fastmap
) break;
3952 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3953 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3955 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3959 if (/* Any leading code can possibly start a character
3960 which doesn't match the specified set of characters. */
3963 /* If we can match a character class, we can match any
3964 multibyte characters. */
3965 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3966 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3969 if (match_any_multibyte_characters
== false)
3971 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
3972 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
3974 match_any_multibyte_characters
= true;
3978 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3979 && match_any_multibyte_characters
== false)
3981 /* Set fastmap[I] to 1 where I is a leading code of each
3982 multibyte character in the range table. */
3984 unsigned char lc1
, lc2
;
3986 /* Make P points the range table. `+ 2' is to skip flag
3987 bits for a character class. */
3988 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3990 /* Extract the number of ranges in range table into COUNT. */
3991 EXTRACT_NUMBER_AND_INCR (count
, p
);
3992 for (; count
> 0; count
--, p
+= 3)
3994 /* Extract the start and end of each range. */
3995 EXTRACT_CHARACTER (c
, p
);
3996 lc1
= CHAR_LEADING_CODE (c
);
3998 EXTRACT_CHARACTER (c
, p
);
3999 lc2
= CHAR_LEADING_CODE (c
);
4000 for (j
= lc1
; j
<= lc2
; j
++)
4009 if (!fastmap
) break;
4011 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
4013 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4014 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4018 /* This match depends on text properties. These end with
4019 aborting optimizations. */
4023 case notcategoryspec
:
4024 if (!fastmap
) break;
4025 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4027 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
4028 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4031 /* Any leading code can possibly start a character which
4032 has or doesn't has the specified category. */
4033 if (match_any_multibyte_characters
== false)
4035 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4036 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4038 match_any_multibyte_characters
= true;
4042 /* All cases after this match the empty string. These end with
4064 EXTRACT_NUMBER_AND_INCR (j
, p
);
4066 /* Backward jumps can only go back to code that we've already
4067 visited. `re_compile' should make sure this is true. */
4072 case on_failure_jump
:
4073 case on_failure_keep_string_jump
:
4074 case on_failure_jump_loop
:
4075 case on_failure_jump_nastyloop
:
4076 case on_failure_jump_smart
:
4082 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4083 to jump back to "just after here". */
4086 case on_failure_jump
:
4087 case on_failure_keep_string_jump
:
4088 case on_failure_jump_nastyloop
:
4089 case on_failure_jump_loop
:
4090 case on_failure_jump_smart
:
4091 EXTRACT_NUMBER_AND_INCR (j
, p
);
4093 ; /* Backward jump to be ignored. */
4095 { /* We have to look down both arms.
4096 We first go down the "straight" path so as to minimize
4097 stack usage when going through alternatives. */
4098 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4106 /* This code simply does not properly handle forward jump_n. */
4107 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4109 /* jump_n can either jump or fall through. The (backward) jump
4110 case has already been handled, so we only need to look at the
4111 fallthrough case. */
4115 /* If N == 0, it should be an on_failure_jump_loop instead. */
4116 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4118 /* We only care about one iteration of the loop, so we don't
4119 need to consider the case where this behaves like an
4136 abort (); /* We have listed all the cases. */
4139 /* Getting here means we have found the possible starting
4140 characters for one path of the pattern -- and that the empty
4141 string does not match. We need not follow this path further. */
4145 /* We reached the end without matching anything. */
4148 } /* analyse_first */
4150 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4151 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4152 characters can start a string that matches the pattern. This fastmap
4153 is used by re_search to skip quickly over impossible starting points.
4155 Character codes above (1 << BYTEWIDTH) are not represented in the
4156 fastmap, but the leading codes are represented. Thus, the fastmap
4157 indicates which character sets could start a match.
4159 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4160 area as BUFP->fastmap.
4162 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4165 Returns 0 if we succeed, -2 if an internal error. */
4168 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4170 char *fastmap
= bufp
->fastmap
;
4173 assert (fastmap
&& bufp
->buffer
);
4175 memset (fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4176 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4178 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4179 fastmap
, RE_MULTIBYTE_P (bufp
));
4180 bufp
->can_be_null
= (analysis
!= 0);
4182 } /* re_compile_fastmap */
4184 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4185 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4186 this memory for recording register information. STARTS and ENDS
4187 must be allocated using the malloc library routine, and must each
4188 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4190 If NUM_REGS == 0, then subsequent matches should allocate their own
4193 Unless this function is called, the first search or match using
4194 PATTERN_BUFFER will allocate its own register data, without
4195 freeing the old data. */
4198 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4202 bufp
->regs_allocated
= REGS_REALLOCATE
;
4203 regs
->num_regs
= num_regs
;
4204 regs
->start
= starts
;
4209 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4211 regs
->start
= regs
->end
= (regoff_t
*) 0;
4214 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4216 /* Searching routines. */
4218 /* Like re_search_2, below, but only one string is specified, and
4219 doesn't let you say where to stop matching. */
4222 re_search (struct re_pattern_buffer
*bufp
, const char *string
, size_t size
,
4223 ssize_t startpos
, ssize_t range
, struct re_registers
*regs
)
4225 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4228 WEAK_ALIAS (__re_search
, re_search
)
4230 /* Head address of virtual concatenation of string. */
4231 #define HEAD_ADDR_VSTRING(P) \
4232 (((P) >= size1 ? string2 : string1))
4234 /* Address of POS in the concatenation of virtual string. */
4235 #define POS_ADDR_VSTRING(POS) \
4236 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4238 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4239 virtual concatenation of STRING1 and STRING2, starting first at index
4240 STARTPOS, then at STARTPOS + 1, and so on.
4242 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4244 RANGE is how far to scan while trying to match. RANGE = 0 means try
4245 only at STARTPOS; in general, the last start tried is STARTPOS +
4248 In REGS, return the indices of the virtual concatenation of STRING1
4249 and STRING2 that matched the entire BUFP->buffer and its contained
4252 Do not consider matching one past the index STOP in the virtual
4253 concatenation of STRING1 and STRING2.
4255 We return either the position in the strings at which the match was
4256 found, -1 if no match, or -2 if error (such as failure
4260 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, size_t size1
,
4261 const char *str2
, size_t size2
, ssize_t startpos
, ssize_t range
,
4262 struct re_registers
*regs
, ssize_t stop
)
4265 re_char
*string1
= (re_char
*) str1
;
4266 re_char
*string2
= (re_char
*) str2
;
4267 register char *fastmap
= bufp
->fastmap
;
4268 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4269 size_t total_size
= size1
+ size2
;
4270 ssize_t endpos
= startpos
+ range
;
4271 boolean anchored_start
;
4272 /* Nonzero if we are searching multibyte string. */
4273 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4275 /* Check for out-of-range STARTPOS. */
4276 if (startpos
< 0 || startpos
> total_size
)
4279 /* Fix up RANGE if it might eventually take us outside
4280 the virtual concatenation of STRING1 and STRING2.
4281 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4283 range
= 0 - startpos
;
4284 else if (endpos
> total_size
)
4285 range
= total_size
- startpos
;
4287 /* If the search isn't to be a backwards one, don't waste time in a
4288 search for a pattern anchored at beginning of buffer. */
4289 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4298 /* In a forward search for something that starts with \=.
4299 don't keep searching past point. */
4300 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4302 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4308 /* Update the fastmap now if not correct already. */
4309 if (fastmap
&& !bufp
->fastmap_accurate
)
4310 re_compile_fastmap (bufp
);
4312 /* See whether the pattern is anchored. */
4313 anchored_start
= (bufp
->buffer
[0] == begline
);
4316 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4318 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4320 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4324 /* Loop through the string, looking for a place to start matching. */
4327 /* If the pattern is anchored,
4328 skip quickly past places we cannot match.
4329 We don't bother to treat startpos == 0 specially
4330 because that case doesn't repeat. */
4331 if (anchored_start
&& startpos
> 0)
4333 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4334 : string2
[startpos
- size1
- 1])
4339 /* If a fastmap is supplied, skip quickly over characters that
4340 cannot be the start of a match. If the pattern can match the
4341 null string, however, we don't need to skip characters; we want
4342 the first null string. */
4343 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4345 register re_char
*d
;
4346 register re_wchar_t buf_ch
;
4348 d
= POS_ADDR_VSTRING (startpos
);
4350 if (range
> 0) /* Searching forwards. */
4352 register int lim
= 0;
4353 ssize_t irange
= range
;
4355 if (startpos
< size1
&& startpos
+ range
>= size1
)
4356 lim
= range
- (size1
- startpos
);
4358 /* Written out as an if-else to avoid testing `translate'
4360 if (RE_TRANSLATE_P (translate
))
4367 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4368 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4369 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4372 range
-= buf_charlen
;
4378 register re_wchar_t ch
, translated
;
4381 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4382 translated
= RE_TRANSLATE (translate
, ch
);
4383 if (translated
!= ch
4384 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4386 if (fastmap
[buf_ch
])
4399 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4400 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4402 range
-= buf_charlen
;
4406 while (range
> lim
&& !fastmap
[*d
])
4412 startpos
+= irange
- range
;
4414 else /* Searching backwards. */
4418 buf_ch
= STRING_CHAR (d
);
4419 buf_ch
= TRANSLATE (buf_ch
);
4420 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4425 register re_wchar_t ch
, translated
;
4428 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4429 translated
= TRANSLATE (ch
);
4430 if (translated
!= ch
4431 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4433 if (! fastmap
[TRANSLATE (buf_ch
)])
4439 /* If can't match the null string, and that's all we have left, fail. */
4440 if (range
>= 0 && startpos
== total_size
&& fastmap
4441 && !bufp
->can_be_null
)
4444 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4445 startpos
, regs
, stop
);
4458 /* Update STARTPOS to the next character boundary. */
4461 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4462 int len
= BYTES_BY_CHAR_HEAD (*p
);
4480 /* Update STARTPOS to the previous character boundary. */
4483 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4485 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4487 /* Find the head of multibyte form. */
4488 PREV_CHAR_BOUNDARY (p
, phead
);
4489 range
+= p0
- 1 - p
;
4493 startpos
-= p0
- 1 - p
;
4499 WEAK_ALIAS (__re_search_2
, re_search_2
)
4501 /* Declarations and macros for re_match_2. */
4503 static int bcmp_translate (re_char
*s1
, re_char
*s2
,
4504 register ssize_t len
,
4505 RE_TRANSLATE_TYPE translate
,
4506 const int multibyte
);
4508 /* This converts PTR, a pointer into one of the search strings `string1'
4509 and `string2' into an offset from the beginning of that string. */
4510 #define POINTER_TO_OFFSET(ptr) \
4511 (FIRST_STRING_P (ptr) \
4513 : (ptr) - string2 + (ptrdiff_t) size1)
4515 /* Call before fetching a character with *d. This switches over to
4516 string2 if necessary.
4517 Check re_match_2_internal for a discussion of why end_match_2 might
4518 not be within string2 (but be equal to end_match_1 instead). */
4519 #define PREFETCH() \
4522 /* End of string2 => fail. */ \
4523 if (dend == end_match_2) \
4525 /* End of string1 => advance to string2. */ \
4527 dend = end_match_2; \
4530 /* Call before fetching a char with *d if you already checked other limits.
4531 This is meant for use in lookahead operations like wordend, etc..
4532 where we might need to look at parts of the string that might be
4533 outside of the LIMITs (i.e past `stop'). */
4534 #define PREFETCH_NOLIMIT() \
4538 dend = end_match_2; \
4541 /* Test if at very beginning or at very end of the virtual concatenation
4542 of `string1' and `string2'. If only one string, it's `string2'. */
4543 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4544 #define AT_STRINGS_END(d) ((d) == end2)
4546 /* Disabled due to a compiler bug -- see comment at case wordbound */
4548 /* The comment at case wordbound is following one, but we don't use
4549 AT_WORD_BOUNDARY anymore to support multibyte form.
4551 The DEC Alpha C compiler 3.x generates incorrect code for the
4552 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4553 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4554 macro and introducing temporary variables works around the bug. */
4557 /* Test if D points to a character which is word-constituent. We have
4558 two special cases to check for: if past the end of string1, look at
4559 the first character in string2; and if before the beginning of
4560 string2, look at the last character in string1. */
4561 #define WORDCHAR_P(d) \
4562 (SYNTAX ((d) == end1 ? *string2 \
4563 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4566 /* Test if the character before D and the one at D differ with respect
4567 to being word-constituent. */
4568 #define AT_WORD_BOUNDARY(d) \
4569 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4570 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4573 /* Free everything we malloc. */
4574 #ifdef MATCH_MAY_ALLOCATE
4575 # define FREE_VAR(var) \
4583 # define FREE_VARIABLES() \
4585 REGEX_FREE_STACK (fail_stack.stack); \
4586 FREE_VAR (regstart); \
4587 FREE_VAR (regend); \
4588 FREE_VAR (best_regstart); \
4589 FREE_VAR (best_regend); \
4592 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4593 #endif /* not MATCH_MAY_ALLOCATE */
4596 /* Optimization routines. */
4598 /* If the operation is a match against one or more chars,
4599 return a pointer to the next operation, else return NULL. */
4601 skip_one_char (const re_char
*p
)
4614 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4617 p
= CHARSET_RANGE_TABLE (p
- 1);
4618 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4619 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4622 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4629 case notcategoryspec
:
4641 /* Jump over non-matching operations. */
4643 skip_noops (const re_char
*p
, const re_char
*pend
)
4657 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4668 /* Non-zero if "p1 matches something" implies "p2 fails". */
4670 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const re_char
*p1
, const re_char
*p2
)
4673 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4674 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4676 assert (p1
>= bufp
->buffer
&& p1
< pend
4677 && p2
>= bufp
->buffer
&& p2
<= pend
);
4679 /* Skip over open/close-group commands.
4680 If what follows this loop is a ...+ construct,
4681 look at what begins its body, since we will have to
4682 match at least one of that. */
4683 p2
= skip_noops (p2
, pend
);
4684 /* The same skip can be done for p1, except that this function
4685 is only used in the case where p1 is a simple match operator. */
4686 /* p1 = skip_noops (p1, pend); */
4688 assert (p1
>= bufp
->buffer
&& p1
< pend
4689 && p2
>= bufp
->buffer
&& p2
<= pend
);
4691 op2
= p2
== pend
? succeed
: *p2
;
4697 /* If we're at the end of the pattern, we can change. */
4698 if (skip_one_char (p1
))
4700 DEBUG_PRINT (" End of pattern: fast loop.\n");
4708 register re_wchar_t c
4709 = (re_opcode_t
) *p2
== endline
? '\n'
4710 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4712 if ((re_opcode_t
) *p1
== exactn
)
4714 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4716 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4721 else if ((re_opcode_t
) *p1
== charset
4722 || (re_opcode_t
) *p1
== charset_not
)
4724 int not = (re_opcode_t
) *p1
== charset_not
;
4726 /* Test if C is listed in charset (or charset_not)
4728 if (! multibyte
|| IS_REAL_ASCII (c
))
4730 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4731 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4734 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4735 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4737 /* `not' is equal to 1 if c would match, which means
4738 that we can't change to pop_failure_jump. */
4741 DEBUG_PRINT (" No match => fast loop.\n");
4745 else if ((re_opcode_t
) *p1
== anychar
4748 DEBUG_PRINT (" . != \\n => fast loop.\n");
4756 if ((re_opcode_t
) *p1
== exactn
)
4757 /* Reuse the code above. */
4758 return mutually_exclusive_p (bufp
, p2
, p1
);
4760 /* It is hard to list up all the character in charset
4761 P2 if it includes multibyte character. Give up in
4763 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4765 /* Now, we are sure that P2 has no range table.
4766 So, for the size of bitmap in P2, `p2[1]' is
4767 enough. But P1 may have range table, so the
4768 size of bitmap table of P1 is extracted by
4769 using macro `CHARSET_BITMAP_SIZE'.
4771 In a multibyte case, we know that all the character
4772 listed in P2 is ASCII. In a unibyte case, P1 has only a
4773 bitmap table. So, in both cases, it is enough to test
4774 only the bitmap table of P1. */
4776 if ((re_opcode_t
) *p1
== charset
)
4779 /* We win if the charset inside the loop
4780 has no overlap with the one after the loop. */
4783 && idx
< CHARSET_BITMAP_SIZE (p1
));
4785 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4789 || idx
== CHARSET_BITMAP_SIZE (p1
))
4791 DEBUG_PRINT (" No match => fast loop.\n");
4795 else if ((re_opcode_t
) *p1
== charset_not
)
4798 /* We win if the charset_not inside the loop lists
4799 every character listed in the charset after. */
4800 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4801 if (! (p2
[2 + idx
] == 0
4802 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4803 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4808 DEBUG_PRINT (" No match => fast loop.\n");
4821 /* Reuse the code above. */
4822 return mutually_exclusive_p (bufp
, p2
, p1
);
4824 /* When we have two charset_not, it's very unlikely that
4825 they don't overlap. The union of the two sets of excluded
4826 chars should cover all possible chars, which, as a matter of
4827 fact, is virtually impossible in multibyte buffers. */
4833 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4835 return ((re_opcode_t
) *p1
== syntaxspec
4836 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4838 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4841 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4843 return ((re_opcode_t
) *p1
== notsyntaxspec
4844 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4846 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4849 return (((re_opcode_t
) *p1
== notsyntaxspec
4850 || (re_opcode_t
) *p1
== syntaxspec
)
4855 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4856 case notcategoryspec
:
4857 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4869 /* Matching routines. */
4871 #ifndef emacs /* Emacs never uses this. */
4872 /* re_match is like re_match_2 except it takes only a single string. */
4875 re_match (struct re_pattern_buffer
*bufp
, const char *string
,
4876 size_t size
, ssize_t pos
, struct re_registers
*regs
)
4878 regoff_t result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
,
4879 size
, pos
, regs
, size
);
4882 WEAK_ALIAS (__re_match
, re_match
)
4883 #endif /* not emacs */
4885 /* re_match_2 matches the compiled pattern in BUFP against the
4886 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4887 and SIZE2, respectively). We start matching at POS, and stop
4890 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4891 store offsets for the substring each group matched in REGS. See the
4892 documentation for exactly how many groups we fill.
4894 We return -1 if no match, -2 if an internal error (such as the
4895 failure stack overflowing). Otherwise, we return the length of the
4896 matched substring. */
4899 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
,
4900 size_t size1
, const char *string2
, size_t size2
, ssize_t pos
,
4901 struct re_registers
*regs
, ssize_t stop
)
4907 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4908 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4909 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4912 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4913 (re_char
*) string2
, size2
,
4917 WEAK_ALIAS (__re_match_2
, re_match_2
)
4920 /* This is a separate function so that we can force an alloca cleanup
4923 re_match_2_internal (struct re_pattern_buffer
*bufp
, const re_char
*string1
,
4924 size_t size1
, const re_char
*string2
, size_t size2
,
4925 ssize_t pos
, struct re_registers
*regs
, ssize_t stop
)
4927 /* General temporaries. */
4931 /* Just past the end of the corresponding string. */
4932 re_char
*end1
, *end2
;
4934 /* Pointers into string1 and string2, just past the last characters in
4935 each to consider matching. */
4936 re_char
*end_match_1
, *end_match_2
;
4938 /* Where we are in the data, and the end of the current string. */
4941 /* Used sometimes to remember where we were before starting matching
4942 an operator so that we can go back in case of failure. This "atomic"
4943 behavior of matching opcodes is indispensable to the correctness
4944 of the on_failure_keep_string_jump optimization. */
4947 /* Where we are in the pattern, and the end of the pattern. */
4948 re_char
*p
= bufp
->buffer
;
4949 re_char
*pend
= p
+ bufp
->used
;
4951 /* We use this to map every character in the string. */
4952 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4954 /* Nonzero if BUFP is setup from a multibyte regex. */
4955 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4957 /* Nonzero if STRING1/STRING2 are multibyte. */
4958 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4960 /* Failure point stack. Each place that can handle a failure further
4961 down the line pushes a failure point on this stack. It consists of
4962 regstart, and regend for all registers corresponding to
4963 the subexpressions we're currently inside, plus the number of such
4964 registers, and, finally, two char *'s. The first char * is where
4965 to resume scanning the pattern; the second one is where to resume
4966 scanning the strings. */
4967 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4968 fail_stack_type fail_stack
;
4970 #ifdef DEBUG_COMPILES_ARGUMENTS
4971 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4974 #if defined REL_ALLOC && defined REGEX_MALLOC
4975 /* This holds the pointer to the failure stack, when
4976 it is allocated relocatably. */
4977 fail_stack_elt_t
*failure_stack_ptr
;
4980 /* We fill all the registers internally, independent of what we
4981 return, for use in backreferences. The number here includes
4982 an element for register zero. */
4983 size_t num_regs
= bufp
->re_nsub
+ 1;
4985 /* Information on the contents of registers. These are pointers into
4986 the input strings; they record just what was matched (on this
4987 attempt) by a subexpression part of the pattern, that is, the
4988 regnum-th regstart pointer points to where in the pattern we began
4989 matching and the regnum-th regend points to right after where we
4990 stopped matching the regnum-th subexpression. (The zeroth register
4991 keeps track of what the whole pattern matches.) */
4992 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4993 re_char
**regstart
, **regend
;
4996 /* The following record the register info as found in the above
4997 variables when we find a match better than any we've seen before.
4998 This happens as we backtrack through the failure points, which in
4999 turn happens only if we have not yet matched the entire string. */
5000 unsigned best_regs_set
= false;
5001 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5002 re_char
**best_regstart
, **best_regend
;
5005 /* Logically, this is `best_regend[0]'. But we don't want to have to
5006 allocate space for that if we're not allocating space for anything
5007 else (see below). Also, we never need info about register 0 for
5008 any of the other register vectors, and it seems rather a kludge to
5009 treat `best_regend' differently than the rest. So we keep track of
5010 the end of the best match so far in a separate variable. We
5011 initialize this to NULL so that when we backtrack the first time
5012 and need to test it, it's not garbage. */
5013 re_char
*match_end
= NULL
;
5015 #ifdef DEBUG_COMPILES_ARGUMENTS
5016 /* Counts the total number of registers pushed. */
5017 unsigned num_regs_pushed
= 0;
5020 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5024 #ifdef MATCH_MAY_ALLOCATE
5025 /* Do not bother to initialize all the register variables if there are
5026 no groups in the pattern, as it takes a fair amount of time. If
5027 there are groups, we include space for register 0 (the whole
5028 pattern), even though we never use it, since it simplifies the
5029 array indexing. We should fix this. */
5032 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5033 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5034 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5035 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5037 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5045 /* We must initialize all our variables to NULL, so that
5046 `FREE_VARIABLES' doesn't try to free them. */
5047 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5049 #endif /* MATCH_MAY_ALLOCATE */
5051 /* The starting position is bogus. */
5052 if (pos
< 0 || pos
> size1
+ size2
)
5058 /* Initialize subexpression text positions to -1 to mark ones that no
5059 start_memory/stop_memory has been seen for. Also initialize the
5060 register information struct. */
5061 for (reg
= 1; reg
< num_regs
; reg
++)
5062 regstart
[reg
] = regend
[reg
] = NULL
;
5064 /* We move `string1' into `string2' if the latter's empty -- but not if
5065 `string1' is null. */
5066 if (size2
== 0 && string1
!= NULL
)
5073 end1
= string1
+ size1
;
5074 end2
= string2
+ size2
;
5076 /* `p' scans through the pattern as `d' scans through the data.
5077 `dend' is the end of the input string that `d' points within. `d'
5078 is advanced into the following input string whenever necessary, but
5079 this happens before fetching; therefore, at the beginning of the
5080 loop, `d' can be pointing at the end of a string, but it cannot
5084 /* Only match within string2. */
5085 d
= string2
+ pos
- size1
;
5086 dend
= end_match_2
= string2
+ stop
- size1
;
5087 end_match_1
= end1
; /* Just to give it a value. */
5093 /* Only match within string1. */
5094 end_match_1
= string1
+ stop
;
5096 When we reach end_match_1, PREFETCH normally switches to string2.
5097 But in the present case, this means that just doing a PREFETCH
5098 makes us jump from `stop' to `gap' within the string.
5099 What we really want here is for the search to stop as
5100 soon as we hit end_match_1. That's why we set end_match_2
5101 to end_match_1 (since PREFETCH fails as soon as we hit
5103 end_match_2
= end_match_1
;
5106 { /* It's important to use this code when stop == size so that
5107 moving `d' from end1 to string2 will not prevent the d == dend
5108 check from catching the end of string. */
5110 end_match_2
= string2
+ stop
- size1
;
5116 DEBUG_PRINT ("The compiled pattern is: ");
5117 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5118 DEBUG_PRINT ("The string to match is: `");
5119 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5120 DEBUG_PRINT ("'\n");
5122 /* This loops over pattern commands. It exits by returning from the
5123 function if the match is complete, or it drops through if the match
5124 fails at this starting point in the input data. */
5127 DEBUG_PRINT ("\n%p: ", p
);
5133 /* End of pattern means we might have succeeded. */
5134 DEBUG_PRINT ("end of pattern ... ");
5136 /* If we haven't matched the entire string, and we want the
5137 longest match, try backtracking. */
5138 if (d
!= end_match_2
)
5140 /* 1 if this match ends in the same string (string1 or string2)
5141 as the best previous match. */
5142 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5143 == FIRST_STRING_P (d
));
5144 /* 1 if this match is the best seen so far. */
5145 boolean best_match_p
;
5147 /* AIX compiler got confused when this was combined
5148 with the previous declaration. */
5150 best_match_p
= d
> match_end
;
5152 best_match_p
= !FIRST_STRING_P (d
);
5154 DEBUG_PRINT ("backtracking.\n");
5156 if (!FAIL_STACK_EMPTY ())
5157 { /* More failure points to try. */
5159 /* If exceeds best match so far, save it. */
5160 if (!best_regs_set
|| best_match_p
)
5162 best_regs_set
= true;
5165 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5167 for (reg
= 1; reg
< num_regs
; reg
++)
5169 best_regstart
[reg
] = regstart
[reg
];
5170 best_regend
[reg
] = regend
[reg
];
5176 /* If no failure points, don't restore garbage. And if
5177 last match is real best match, don't restore second
5179 else if (best_regs_set
&& !best_match_p
)
5182 /* Restore best match. It may happen that `dend ==
5183 end_match_1' while the restored d is in string2.
5184 For example, the pattern `x.*y.*z' against the
5185 strings `x-' and `y-z-', if the two strings are
5186 not consecutive in memory. */
5187 DEBUG_PRINT ("Restoring best registers.\n");
5190 dend
= ((d
>= string1
&& d
<= end1
)
5191 ? end_match_1
: end_match_2
);
5193 for (reg
= 1; reg
< num_regs
; reg
++)
5195 regstart
[reg
] = best_regstart
[reg
];
5196 regend
[reg
] = best_regend
[reg
];
5199 } /* d != end_match_2 */
5202 DEBUG_PRINT ("Accepting match.\n");
5204 /* If caller wants register contents data back, do it. */
5205 if (regs
&& !bufp
->no_sub
)
5207 /* Have the register data arrays been allocated? */
5208 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5209 { /* No. So allocate them with malloc. We need one
5210 extra element beyond `num_regs' for the `-1' marker
5212 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5213 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5214 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5215 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5220 bufp
->regs_allocated
= REGS_REALLOCATE
;
5222 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5223 { /* Yes. If we need more elements than were already
5224 allocated, reallocate them. If we need fewer, just
5226 if (regs
->num_regs
< num_regs
+ 1)
5228 regs
->num_regs
= num_regs
+ 1;
5229 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5230 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5231 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5240 /* These braces fend off a "empty body in an else-statement"
5241 warning under GCC when assert expands to nothing. */
5242 assert (bufp
->regs_allocated
== REGS_FIXED
);
5245 /* Convert the pointer data in `regstart' and `regend' to
5246 indices. Register zero has to be set differently,
5247 since we haven't kept track of any info for it. */
5248 if (regs
->num_regs
> 0)
5250 regs
->start
[0] = pos
;
5251 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5254 /* Go through the first `min (num_regs, regs->num_regs)'
5255 registers, since that is all we initialized. */
5256 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5258 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5259 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5262 regs
->start
[reg
] = POINTER_TO_OFFSET (regstart
[reg
]);
5263 regs
->end
[reg
] = POINTER_TO_OFFSET (regend
[reg
]);
5267 /* If the regs structure we return has more elements than
5268 were in the pattern, set the extra elements to -1. If
5269 we (re)allocated the registers, this is the case,
5270 because we always allocate enough to have at least one
5272 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5273 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5274 } /* regs && !bufp->no_sub */
5276 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5277 nfailure_points_pushed
, nfailure_points_popped
,
5278 nfailure_points_pushed
- nfailure_points_popped
);
5279 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed
);
5281 dcnt
= POINTER_TO_OFFSET (d
) - pos
;
5283 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt
);
5289 /* Otherwise match next pattern command. */
5292 /* Ignore these. Used to ignore the n of succeed_n's which
5293 currently have n == 0. */
5295 DEBUG_PRINT ("EXECUTING no_op.\n");
5299 DEBUG_PRINT ("EXECUTING succeed.\n");
5302 /* Match the next n pattern characters exactly. The following
5303 byte in the pattern defines n, and the n bytes after that
5304 are the characters to match. */
5307 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt
);
5309 /* Remember the start point to rollback upon failure. */
5313 /* This is written out as an if-else so we don't waste time
5314 testing `translate' inside the loop. */
5315 if (RE_TRANSLATE_P (translate
))
5319 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5339 /* The cost of testing `translate' is comparatively small. */
5340 if (target_multibyte
)
5343 int pat_charlen
, buf_charlen
;
5348 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5351 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5354 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5356 if (TRANSLATE (buf_ch
) != pat_ch
)
5364 mcnt
-= pat_charlen
;
5376 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5377 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5384 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5385 if (! CHAR_BYTE8_P (buf_ch
))
5387 buf_ch
= TRANSLATE (buf_ch
);
5388 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5394 if (buf_ch
!= pat_ch
)
5407 /* Match any character except possibly a newline or a null. */
5413 DEBUG_PRINT ("EXECUTING anychar.\n");
5416 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5418 buf_ch
= TRANSLATE (buf_ch
);
5420 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5422 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5423 && buf_ch
== '\000'))
5426 DEBUG_PRINT (" Matched `%d'.\n", *d
);
5435 register unsigned int c
;
5436 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5439 /* Start of actual range_table, or end of bitmap if there is no
5441 re_char
*range_table
IF_LINT (= NULL
);
5443 /* Nonzero if there is a range table. */
5444 int range_table_exists
;
5446 /* Number of ranges of range table. This is not included
5447 in the initial byte-length of the command. */
5450 /* Whether matching against a unibyte character. */
5451 boolean unibyte_char
= false;
5453 DEBUG_PRINT ("EXECUTING charset%s.\n", not ? "_not" : "");
5455 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5457 if (range_table_exists
)
5459 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5460 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5464 c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5465 if (target_multibyte
)
5470 c1
= RE_CHAR_TO_UNIBYTE (c
);
5473 unibyte_char
= true;
5479 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5481 if (! CHAR_BYTE8_P (c1
))
5483 c1
= TRANSLATE (c1
);
5484 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5487 unibyte_char
= true;
5492 unibyte_char
= true;
5495 if (unibyte_char
&& c
< (1 << BYTEWIDTH
))
5496 { /* Lookup bitmap. */
5497 /* Cast to `unsigned' instead of `unsigned char' in
5498 case the bit list is a full 32 bytes long. */
5499 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5500 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5504 else if (range_table_exists
)
5506 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5508 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5509 | (class_bits
& BIT_MULTIBYTE
)
5510 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5511 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5512 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5513 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5516 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5520 if (range_table_exists
)
5521 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5523 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5525 if (!not) goto fail
;
5532 /* The beginning of a group is represented by start_memory.
5533 The argument is the register number. The text
5534 matched within the group is recorded (in the internal
5535 registers data structure) under the register number. */
5537 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p
);
5539 /* In case we need to undo this operation (via backtracking). */
5540 PUSH_FAILURE_REG (*p
);
5543 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5544 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart
[*p
]));
5546 /* Move past the register number and inner group count. */
5551 /* The stop_memory opcode represents the end of a group. Its
5552 argument is the same as start_memory's: the register number. */
5554 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p
);
5556 assert (!REG_UNSET (regstart
[*p
]));
5557 /* Strictly speaking, there should be code such as:
5559 assert (REG_UNSET (regend[*p]));
5560 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5562 But the only info to be pushed is regend[*p] and it is known to
5563 be UNSET, so there really isn't anything to push.
5564 Not pushing anything, on the other hand deprives us from the
5565 guarantee that regend[*p] is UNSET since undoing this operation
5566 will not reset its value properly. This is not important since
5567 the value will only be read on the next start_memory or at
5568 the very end and both events can only happen if this stop_memory
5572 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend
[*p
]));
5574 /* Move past the register number and the inner group count. */
5579 /* \<digit> has been turned into a `duplicate' command which is
5580 followed by the numeric value of <digit> as the register number. */
5583 register re_char
*d2
, *dend2
;
5584 int regno
= *p
++; /* Get which register to match against. */
5585 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno
);
5587 /* Can't back reference a group which we've never matched. */
5588 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5591 /* Where in input to try to start matching. */
5592 d2
= regstart
[regno
];
5594 /* Remember the start point to rollback upon failure. */
5597 /* Where to stop matching; if both the place to start and
5598 the place to stop matching are in the same string, then
5599 set to the place to stop, otherwise, for now have to use
5600 the end of the first string. */
5602 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5603 == FIRST_STRING_P (regend
[regno
]))
5604 ? regend
[regno
] : end_match_1
);
5609 /* If necessary, advance to next segment in register
5613 if (dend2
== end_match_2
) break;
5614 if (dend2
== regend
[regno
]) break;
5616 /* End of string1 => advance to string2. */
5618 dend2
= regend
[regno
];
5620 /* At end of register contents => success */
5621 if (d2
== dend2
) break;
5623 /* If necessary, advance to next segment in data. */
5626 /* How many characters left in this segment to match. */
5629 /* Want how many consecutive characters we can match in
5630 one shot, so, if necessary, adjust the count. */
5631 if (dcnt
> dend2
- d2
)
5634 /* Compare that many; failure if mismatch, else move
5636 if (RE_TRANSLATE_P (translate
)
5637 ? bcmp_translate (d
, d2
, dcnt
, translate
, target_multibyte
)
5638 : memcmp (d
, d2
, dcnt
))
5643 d
+= dcnt
, d2
+= dcnt
;
5649 /* begline matches the empty string at the beginning of the string
5650 (unless `not_bol' is set in `bufp'), and after newlines. */
5652 DEBUG_PRINT ("EXECUTING begline.\n");
5654 if (AT_STRINGS_BEG (d
))
5656 if (!bufp
->not_bol
) break;
5661 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5665 /* In all other cases, we fail. */
5669 /* endline is the dual of begline. */
5671 DEBUG_PRINT ("EXECUTING endline.\n");
5673 if (AT_STRINGS_END (d
))
5675 if (!bufp
->not_eol
) break;
5679 PREFETCH_NOLIMIT ();
5686 /* Match at the very beginning of the data. */
5688 DEBUG_PRINT ("EXECUTING begbuf.\n");
5689 if (AT_STRINGS_BEG (d
))
5694 /* Match at the very end of the data. */
5696 DEBUG_PRINT ("EXECUTING endbuf.\n");
5697 if (AT_STRINGS_END (d
))
5702 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5703 pushes NULL as the value for the string on the stack. Then
5704 `POP_FAILURE_POINT' will keep the current value for the
5705 string, instead of restoring it. To see why, consider
5706 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5707 then the . fails against the \n. But the next thing we want
5708 to do is match the \n against the \n; if we restored the
5709 string value, we would be back at the foo.
5711 Because this is used only in specific cases, we don't need to
5712 check all the things that `on_failure_jump' does, to make
5713 sure the right things get saved on the stack. Hence we don't
5714 share its code. The only reason to push anything on the
5715 stack at all is that otherwise we would have to change
5716 `anychar's code to do something besides goto fail in this
5717 case; that seems worse than this. */
5718 case on_failure_keep_string_jump
:
5719 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5720 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5723 PUSH_FAILURE_POINT (p
- 3, NULL
);
5726 /* A nasty loop is introduced by the non-greedy *? and +?.
5727 With such loops, the stack only ever contains one failure point
5728 at a time, so that a plain on_failure_jump_loop kind of
5729 cycle detection cannot work. Worse yet, such a detection
5730 can not only fail to detect a cycle, but it can also wrongly
5731 detect a cycle (between different instantiations of the same
5733 So the method used for those nasty loops is a little different:
5734 We use a special cycle-detection-stack-frame which is pushed
5735 when the on_failure_jump_nastyloop failure-point is *popped*.
5736 This special frame thus marks the beginning of one iteration
5737 through the loop and we can hence easily check right here
5738 whether something matched between the beginning and the end of
5740 case on_failure_jump_nastyloop
:
5741 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5742 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5745 assert ((re_opcode_t
)p
[-4] == no_op
);
5748 CHECK_INFINITE_LOOP (p
- 4, d
);
5750 /* If there's a cycle, just continue without pushing
5751 this failure point. The failure point is the "try again"
5752 option, which shouldn't be tried.
5753 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5754 PUSH_FAILURE_POINT (p
- 3, d
);
5758 /* Simple loop detecting on_failure_jump: just check on the
5759 failure stack if the same spot was already hit earlier. */
5760 case on_failure_jump_loop
:
5762 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5763 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5767 CHECK_INFINITE_LOOP (p
- 3, d
);
5769 /* If there's a cycle, get out of the loop, as if the matching
5770 had failed. We used to just `goto fail' here, but that was
5771 aborting the search a bit too early: we want to keep the
5772 empty-loop-match and keep matching after the loop.
5773 We want (x?)*y\1z to match both xxyz and xxyxz. */
5776 PUSH_FAILURE_POINT (p
- 3, d
);
5781 /* Uses of on_failure_jump:
5783 Each alternative starts with an on_failure_jump that points
5784 to the beginning of the next alternative. Each alternative
5785 except the last ends with a jump that in effect jumps past
5786 the rest of the alternatives. (They really jump to the
5787 ending jump of the following alternative, because tensioning
5788 these jumps is a hassle.)
5790 Repeats start with an on_failure_jump that points past both
5791 the repetition text and either the following jump or
5792 pop_failure_jump back to this on_failure_jump. */
5793 case on_failure_jump
:
5794 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5795 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5798 PUSH_FAILURE_POINT (p
-3, d
);
5801 /* This operation is used for greedy *.
5802 Compare the beginning of the repeat with what in the
5803 pattern follows its end. If we can establish that there
5804 is nothing that they would both match, i.e., that we
5805 would have to backtrack because of (as in, e.g., `a*a')
5806 then we can use a non-backtracking loop based on
5807 on_failure_keep_string_jump instead of on_failure_jump. */
5808 case on_failure_jump_smart
:
5809 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5810 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5813 re_char
*p1
= p
; /* Next operation. */
5814 /* Here, we discard `const', making re_match non-reentrant. */
5815 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5816 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5818 p
-= 3; /* Reset so that we will re-execute the
5819 instruction once it's been changed. */
5821 EXTRACT_NUMBER (mcnt
, p2
- 2);
5823 /* Ensure this is a indeed the trivial kind of loop
5824 we are expecting. */
5825 assert (skip_one_char (p1
) == p2
- 3);
5826 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5827 DEBUG_STATEMENT (debug
+= 2);
5828 if (mutually_exclusive_p (bufp
, p1
, p2
))
5830 /* Use a fast `on_failure_keep_string_jump' loop. */
5831 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5832 *p3
= (unsigned char) on_failure_keep_string_jump
;
5833 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5837 /* Default to a safe `on_failure_jump' loop. */
5838 DEBUG_PRINT (" smart default => slow loop.\n");
5839 *p3
= (unsigned char) on_failure_jump
;
5841 DEBUG_STATEMENT (debug
-= 2);
5845 /* Unconditionally jump (without popping any failure points). */
5848 IMMEDIATE_QUIT_CHECK
;
5849 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5850 DEBUG_PRINT ("EXECUTING jump %d ", mcnt
);
5851 p
+= mcnt
; /* Do the jump. */
5852 DEBUG_PRINT ("(to %p).\n", p
);
5856 /* Have to succeed matching what follows at least n times.
5857 After that, handle like `on_failure_jump'. */
5859 /* Signedness doesn't matter since we only compare MCNT to 0. */
5860 EXTRACT_NUMBER (mcnt
, p
+ 2);
5861 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt
);
5863 /* Originally, mcnt is how many times we HAVE to succeed. */
5866 /* Here, we discard `const', making re_match non-reentrant. */
5867 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5870 PUSH_NUMBER (p2
, mcnt
);
5873 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5878 /* Signedness doesn't matter since we only compare MCNT to 0. */
5879 EXTRACT_NUMBER (mcnt
, p
+ 2);
5880 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt
);
5882 /* Originally, this is how many times we CAN jump. */
5885 /* Here, we discard `const', making re_match non-reentrant. */
5886 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5888 PUSH_NUMBER (p2
, mcnt
);
5889 goto unconditional_jump
;
5891 /* If don't have to jump any more, skip over the rest of command. */
5898 unsigned char *p2
; /* Location of the counter. */
5899 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5901 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5902 /* Here, we discard `const', making re_match non-reentrant. */
5903 p2
= (unsigned char*) p
+ mcnt
;
5904 /* Signedness doesn't matter since we only copy MCNT's bits . */
5905 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5906 DEBUG_PRINT (" Setting %p to %d.\n", p2
, mcnt
);
5907 PUSH_NUMBER (p2
, mcnt
);
5914 boolean
not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5915 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5917 /* We SUCCEED (or FAIL) in one of the following cases: */
5919 /* Case 1: D is at the beginning or the end of string. */
5920 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5924 /* C1 is the character before D, S1 is the syntax of C1, C2
5925 is the character at D, and S2 is the syntax of C2. */
5930 ssize_t offset
= PTR_TO_OFFSET (d
- 1);
5931 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5932 UPDATE_SYNTAX_TABLE (charpos
);
5934 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5937 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5939 PREFETCH_NOLIMIT ();
5940 GET_CHAR_AFTER (c2
, d
, dummy
);
5943 if (/* Case 2: Only one of S1 and S2 is Sword. */
5944 ((s1
== Sword
) != (s2
== Sword
))
5945 /* Case 3: Both of S1 and S2 are Sword, and macro
5946 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5947 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5957 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5959 /* We FAIL in one of the following cases: */
5961 /* Case 1: D is at the end of string. */
5962 if (AT_STRINGS_END (d
))
5966 /* C1 is the character before D, S1 is the syntax of C1, C2
5967 is the character at D, and S2 is the syntax of C2. */
5972 ssize_t offset
= PTR_TO_OFFSET (d
);
5973 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5974 UPDATE_SYNTAX_TABLE (charpos
);
5977 GET_CHAR_AFTER (c2
, d
, dummy
);
5980 /* Case 2: S2 is not Sword. */
5984 /* Case 3: D is not at the beginning of string ... */
5985 if (!AT_STRINGS_BEG (d
))
5987 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5989 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5993 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5995 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6002 DEBUG_PRINT ("EXECUTING wordend.\n");
6004 /* We FAIL in one of the following cases: */
6006 /* Case 1: D is at the beginning of string. */
6007 if (AT_STRINGS_BEG (d
))
6011 /* C1 is the character before D, S1 is the syntax of C1, C2
6012 is the character at D, and S2 is the syntax of C2. */
6017 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6018 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6019 UPDATE_SYNTAX_TABLE (charpos
);
6021 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6024 /* Case 2: S1 is not Sword. */
6028 /* Case 3: D is not at the end of string ... */
6029 if (!AT_STRINGS_END (d
))
6031 PREFETCH_NOLIMIT ();
6032 GET_CHAR_AFTER (c2
, d
, dummy
);
6034 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6038 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6040 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6047 DEBUG_PRINT ("EXECUTING symbeg.\n");
6049 /* We FAIL in one of the following cases: */
6051 /* Case 1: D is at the end of string. */
6052 if (AT_STRINGS_END (d
))
6056 /* C1 is the character before D, S1 is the syntax of C1, C2
6057 is the character at D, and S2 is the syntax of C2. */
6061 ssize_t offset
= PTR_TO_OFFSET (d
);
6062 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6063 UPDATE_SYNTAX_TABLE (charpos
);
6066 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6069 /* Case 2: S2 is neither Sword nor Ssymbol. */
6070 if (s2
!= Sword
&& s2
!= Ssymbol
)
6073 /* Case 3: D is not at the beginning of string ... */
6074 if (!AT_STRINGS_BEG (d
))
6076 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6078 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6082 /* ... and S1 is Sword or Ssymbol. */
6083 if (s1
== Sword
|| s1
== Ssymbol
)
6090 DEBUG_PRINT ("EXECUTING symend.\n");
6092 /* We FAIL in one of the following cases: */
6094 /* Case 1: D is at the beginning of string. */
6095 if (AT_STRINGS_BEG (d
))
6099 /* C1 is the character before D, S1 is the syntax of C1, C2
6100 is the character at D, and S2 is the syntax of C2. */
6104 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6105 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6106 UPDATE_SYNTAX_TABLE (charpos
);
6108 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6111 /* Case 2: S1 is neither Ssymbol nor Sword. */
6112 if (s1
!= Sword
&& s1
!= Ssymbol
)
6115 /* Case 3: D is not at the end of string ... */
6116 if (!AT_STRINGS_END (d
))
6118 PREFETCH_NOLIMIT ();
6119 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6121 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6125 /* ... and S2 is Sword or Ssymbol. */
6126 if (s2
== Sword
|| s2
== Ssymbol
)
6135 boolean
not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6137 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6142 ssize_t offset
= PTR_TO_OFFSET (d
);
6143 ssize_t pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6144 UPDATE_SYNTAX_TABLE (pos1
);
6151 GET_CHAR_AFTER (c
, d
, len
);
6152 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6161 DEBUG_PRINT ("EXECUTING before_dot.\n");
6162 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6167 DEBUG_PRINT ("EXECUTING at_dot.\n");
6168 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6173 DEBUG_PRINT ("EXECUTING after_dot.\n");
6174 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6179 case notcategoryspec
:
6181 boolean
not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6183 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6184 not ? "not" : "", mcnt
);
6190 GET_CHAR_AFTER (c
, d
, len
);
6191 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6203 continue; /* Successfully executed one pattern command; keep going. */
6206 /* We goto here if a matching operation fails. */
6208 IMMEDIATE_QUIT_CHECK
;
6209 if (!FAIL_STACK_EMPTY ())
6212 /* A restart point is known. Restore to that state. */
6213 DEBUG_PRINT ("\nFAIL:\n");
6214 POP_FAILURE_POINT (str
, pat
);
6217 case on_failure_keep_string_jump
:
6218 assert (str
== NULL
);
6219 goto continue_failure_jump
;
6221 case on_failure_jump_nastyloop
:
6222 assert ((re_opcode_t
)pat
[-2] == no_op
);
6223 PUSH_FAILURE_POINT (pat
- 2, str
);
6226 case on_failure_jump_loop
:
6227 case on_failure_jump
:
6230 continue_failure_jump
:
6231 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6236 /* A special frame used for nastyloops. */
6243 assert (p
>= bufp
->buffer
&& p
<= pend
);
6245 if (d
>= string1
&& d
<= end1
)
6249 break; /* Matching at this starting point really fails. */
6253 goto restore_best_regs
;
6257 return -1; /* Failure to match. */
6260 /* Subroutine definitions for re_match_2. */
6262 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6263 bytes; nonzero otherwise. */
6266 bcmp_translate (const re_char
*s1
, const re_char
*s2
, register ssize_t len
,
6267 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6269 register re_char
*p1
= s1
, *p2
= s2
;
6270 re_char
*p1_end
= s1
+ len
;
6271 re_char
*p2_end
= s2
+ len
;
6273 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6274 different lengths, but relying on a single `len' would break this. -sm */
6275 while (p1
< p1_end
&& p2
< p2_end
)
6277 int p1_charlen
, p2_charlen
;
6278 re_wchar_t p1_ch
, p2_ch
;
6280 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6281 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6283 if (RE_TRANSLATE (translate
, p1_ch
)
6284 != RE_TRANSLATE (translate
, p2_ch
))
6287 p1
+= p1_charlen
, p2
+= p2_charlen
;
6290 if (p1
!= p1_end
|| p2
!= p2_end
)
6296 /* Entry points for GNU code. */
6298 /* re_compile_pattern is the GNU regular expression compiler: it
6299 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6300 Returns 0 if the pattern was valid, otherwise an error string.
6302 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6303 are set in BUFP on entry.
6305 We call regex_compile to do the actual compilation. */
6308 re_compile_pattern (const char *pattern
, size_t length
,
6309 struct re_pattern_buffer
*bufp
)
6313 /* GNU code is written to assume at least RE_NREGS registers will be set
6314 (and at least one extra will be -1). */
6315 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6317 /* And GNU code determines whether or not to get register information
6318 by passing null for the REGS argument to re_match, etc., not by
6322 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6326 return gettext (re_error_msgid
[(int) ret
]);
6328 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6330 /* Entry points compatible with 4.2 BSD regex library. We don't define
6331 them unless specifically requested. */
6333 #if defined _REGEX_RE_COMP || defined _LIBC
6335 /* BSD has one and only one pattern buffer. */
6336 static struct re_pattern_buffer re_comp_buf
;
6340 /* Make these definitions weak in libc, so POSIX programs can redefine
6341 these names if they don't use our functions, and still use
6342 regcomp/regexec below without link errors. */
6345 re_comp (const char *s
)
6351 if (!re_comp_buf
.buffer
)
6352 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6353 return (char *) gettext ("No previous regular expression");
6357 if (!re_comp_buf
.buffer
)
6359 re_comp_buf
.buffer
= malloc (200);
6360 if (re_comp_buf
.buffer
== NULL
)
6361 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6362 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6363 re_comp_buf
.allocated
= 200;
6365 re_comp_buf
.fastmap
= malloc (1 << BYTEWIDTH
);
6366 if (re_comp_buf
.fastmap
== NULL
)
6367 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6368 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6371 /* Since `re_exec' always passes NULL for the `regs' argument, we
6372 don't need to initialize the pattern buffer fields which affect it. */
6374 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6379 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6380 return (char *) gettext (re_error_msgid
[(int) ret
]);
6388 re_exec (const char *s
)
6390 const size_t len
= strlen (s
);
6391 return (re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0)
6394 #endif /* _REGEX_RE_COMP */
6396 /* POSIX.2 functions. Don't define these for Emacs. */
6400 /* regcomp takes a regular expression as a string and compiles it.
6402 PREG is a regex_t *. We do not expect any fields to be initialized,
6403 since POSIX says we shouldn't. Thus, we set
6405 `buffer' to the compiled pattern;
6406 `used' to the length of the compiled pattern;
6407 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6408 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6409 RE_SYNTAX_POSIX_BASIC;
6410 `fastmap' to an allocated space for the fastmap;
6411 `fastmap_accurate' to zero;
6412 `re_nsub' to the number of subexpressions in PATTERN.
6414 PATTERN is the address of the pattern string.
6416 CFLAGS is a series of bits which affect compilation.
6418 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6419 use POSIX basic syntax.
6421 If REG_NEWLINE is set, then . and [^...] don't match newline.
6422 Also, regexec will try a match beginning after every newline.
6424 If REG_ICASE is set, then we considers upper- and lowercase
6425 versions of letters to be equivalent when matching.
6427 If REG_NOSUB is set, then when PREG is passed to regexec, that
6428 routine will report only success or failure, and nothing about the
6431 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6432 the return codes and their meanings.) */
6435 regcomp (regex_t
*__restrict preg
, const char *__restrict pattern
,
6440 = (cflags
& REG_EXTENDED
) ?
6441 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6443 /* regex_compile will allocate the space for the compiled pattern. */
6445 preg
->allocated
= 0;
6448 /* Try to allocate space for the fastmap. */
6449 preg
->fastmap
= malloc (1 << BYTEWIDTH
);
6451 if (cflags
& REG_ICASE
)
6455 preg
->translate
= malloc (CHAR_SET_SIZE
* sizeof *preg
->translate
);
6456 if (preg
->translate
== NULL
)
6457 return (int) REG_ESPACE
;
6459 /* Map uppercase characters to corresponding lowercase ones. */
6460 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6461 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6464 preg
->translate
= NULL
;
6466 /* If REG_NEWLINE is set, newlines are treated differently. */
6467 if (cflags
& REG_NEWLINE
)
6468 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6469 syntax
&= ~RE_DOT_NEWLINE
;
6470 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6473 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6475 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6477 /* POSIX says a null character in the pattern terminates it, so we
6478 can use strlen here in compiling the pattern. */
6479 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6481 /* POSIX doesn't distinguish between an unmatched open-group and an
6482 unmatched close-group: both are REG_EPAREN. */
6483 if (ret
== REG_ERPAREN
)
6486 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6487 { /* Compute the fastmap now, since regexec cannot modify the pattern
6489 re_compile_fastmap (preg
);
6490 if (preg
->can_be_null
)
6491 { /* The fastmap can't be used anyway. */
6492 free (preg
->fastmap
);
6493 preg
->fastmap
= NULL
;
6498 WEAK_ALIAS (__regcomp
, regcomp
)
6501 /* regexec searches for a given pattern, specified by PREG, in the
6504 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6505 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6506 least NMATCH elements, and we set them to the offsets of the
6507 corresponding matched substrings.
6509 EFLAGS specifies `execution flags' which affect matching: if
6510 REG_NOTBOL is set, then ^ does not match at the beginning of the
6511 string; if REG_NOTEOL is set, then $ does not match at the end.
6513 We return 0 if we find a match and REG_NOMATCH if not. */
6516 regexec (const regex_t
*__restrict preg
, const char *__restrict string
,
6517 size_t nmatch
, regmatch_t pmatch
[__restrict_arr
], int eflags
)
6520 struct re_registers regs
;
6521 regex_t private_preg
;
6522 size_t len
= strlen (string
);
6523 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6525 private_preg
= *preg
;
6527 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6528 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6530 /* The user has told us exactly how many registers to return
6531 information about, via `nmatch'. We have to pass that on to the
6532 matching routines. */
6533 private_preg
.regs_allocated
= REGS_FIXED
;
6537 regs
.num_regs
= nmatch
;
6538 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6539 if (regs
.start
== NULL
)
6541 regs
.end
= regs
.start
+ nmatch
;
6544 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6545 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6546 was a little bit longer but still only matching the real part.
6547 This works because the `endline' will check for a '\n' and will find a
6548 '\0', correctly deciding that this is not the end of a line.
6549 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6550 a convenient '\0' there. For all we know, the string could be preceded
6551 by '\n' which would throw things off. */
6553 /* Perform the searching operation. */
6554 ret
= re_search (&private_preg
, string
, len
,
6555 /* start: */ 0, /* range: */ len
,
6556 want_reg_info
? ®s
: (struct re_registers
*) 0);
6558 /* Copy the register information to the POSIX structure. */
6565 for (r
= 0; r
< nmatch
; r
++)
6567 pmatch
[r
].rm_so
= regs
.start
[r
];
6568 pmatch
[r
].rm_eo
= regs
.end
[r
];
6572 /* If we needed the temporary register info, free the space now. */
6576 /* We want zero return to mean success, unlike `re_search'. */
6577 return ret
>= 0 ? REG_NOERROR
: REG_NOMATCH
;
6579 WEAK_ALIAS (__regexec
, regexec
)
6582 /* Returns a message corresponding to an error code, ERR_CODE, returned
6583 from either regcomp or regexec. We don't use PREG here.
6585 ERR_CODE was previously called ERRCODE, but that name causes an
6586 error with msvc8 compiler. */
6589 regerror (int err_code
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
6595 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6596 /* Only error codes returned by the rest of the code should be passed
6597 to this routine. If we are given anything else, or if other regex
6598 code generates an invalid error code, then the program has a bug.
6599 Dump core so we can fix it. */
6602 msg
= gettext (re_error_msgid
[err_code
]);
6604 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6606 if (errbuf_size
!= 0)
6608 if (msg_size
> errbuf_size
)
6610 memcpy (errbuf
, msg
, errbuf_size
- 1);
6611 errbuf
[errbuf_size
- 1] = 0;
6614 strcpy (errbuf
, msg
);
6619 WEAK_ALIAS (__regerror
, regerror
)
6622 /* Free dynamically allocated space used by PREG. */
6625 regfree (regex_t
*preg
)
6627 free (preg
->buffer
);
6628 preg
->buffer
= NULL
;
6630 preg
->allocated
= 0;
6633 free (preg
->fastmap
);
6634 preg
->fastmap
= NULL
;
6635 preg
->fastmap_accurate
= 0;
6637 free (preg
->translate
);
6638 preg
->translate
= NULL
;
6640 WEAK_ALIAS (__regfree
, regfree
)
6642 #endif /* not emacs */