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-2017 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 - structure the opcode space into opcode+flag.
22 - merge with glibc's regex.[ch].
23 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
24 need to modify the compiled regexp so that re_match can be reentrant.
25 - get rid of on_failure_jump_smart by doing the optimization in re_comp
26 rather than at run-time, so that re_match can be reentrant.
29 /* AIX requires this to be the first thing in the file. */
30 #if defined _AIX && !defined REGEX_MALLOC
34 /* Ignore some GCC warnings for now. This section should go away
35 once the Emacs and Gnulib regex code is merged. */
36 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__) || defined __clang__
37 # pragma GCC diagnostic ignored "-Wstrict-overflow"
39 # pragma GCC diagnostic ignored "-Wunused-function"
40 # pragma GCC diagnostic ignored "-Wunused-macros"
41 # pragma GCC diagnostic ignored "-Wunused-result"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
46 #if 4 < __GNUC__ + (6 <= __GNUC_MINOR__) && ! defined __clang__
47 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
56 /* We need this for `regex.h', and perhaps for the Emacs include files. */
57 # include <sys/types.h>
60 /* Whether to use ISO C Amendment 1 wide char functions.
61 Those should not be used for Emacs since it uses its own. */
63 #define WIDE_CHAR_SUPPORT 1
65 #define WIDE_CHAR_SUPPORT \
66 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
69 /* For platform which support the ISO C amendment 1 functionality we
70 support user defined character classes. */
72 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
78 /* We have to keep the namespace clean. */
79 # define regfree(preg) __regfree (preg)
80 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
81 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
82 # define regerror(err_code, preg, errbuf, errbuf_size) \
83 __regerror (err_code, preg, errbuf, errbuf_size)
84 # define re_set_registers(bu, re, nu, st, en) \
85 __re_set_registers (bu, re, nu, st, en)
86 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
87 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
88 # define re_match(bufp, string, size, pos, regs) \
89 __re_match (bufp, string, size, pos, regs)
90 # define re_search(bufp, string, size, startpos, range, regs) \
91 __re_search (bufp, string, size, startpos, range, regs)
92 # define re_compile_pattern(pattern, length, bufp) \
93 __re_compile_pattern (pattern, length, bufp)
94 # define re_set_syntax(syntax) __re_set_syntax (syntax)
95 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
96 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
97 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
99 /* Make sure we call libc's function even if the user overrides them. */
100 # define btowc __btowc
101 # define iswctype __iswctype
102 # define wctype __wctype
104 # define WEAK_ALIAS(a,b) weak_alias (a, b)
106 /* We are also using some library internals. */
107 # include <locale/localeinfo.h>
108 # include <locale/elem-hash.h>
109 # include <langinfo.h>
111 # define WEAK_ALIAS(a,b)
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
118 # define gettext(msgid) (msgid)
122 /* This define is so xgettext can find the internationalizable
124 # define gettext_noop(String) String
127 /* The `emacs' switch turns on certain matching commands
128 that make sense only in Emacs. */
132 # include "character.h"
136 # include "category.h"
138 /* Make syntax table lookup grant data in gl_state. */
139 # define SYNTAX(c) syntax_property (c, 1)
144 # define malloc xmalloc
148 # define realloc xrealloc
154 /* Converts the pointer to the char to BEG-based offset from the start. */
155 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
156 /* Strings are 0-indexed, buffers are 1-indexed; we pun on the boolean
157 result to get the right base index. */
158 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
160 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
161 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
162 # define RE_STRING_CHAR(p, multibyte) \
163 (multibyte ? (STRING_CHAR (p)) : (*(p)))
164 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
165 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
167 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
169 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
171 /* Set C a (possibly converted to multibyte) character before P. P
172 points into a string which is the virtual concatenation of STR1
173 (which ends at END1) or STR2 (which ends at END2). */
174 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
176 if (target_multibyte) \
178 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
179 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
180 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
181 c = STRING_CHAR (dtemp); \
185 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
190 /* Set C a (possibly converted to multibyte) character at P, and set
191 LEN to the byte length of that character. */
192 # define GET_CHAR_AFTER(c, p, len) \
194 if (target_multibyte) \
195 (c) = STRING_CHAR_AND_LENGTH (p, len); \
200 (c) = RE_CHAR_TO_MULTIBYTE (c); \
204 #else /* not emacs */
206 /* If we are not linking with Emacs proper,
207 we can't use the relocating allocator
208 even if config.h says that we can. */
213 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
216 xmalloc (size_t size
)
218 void *val
= malloc (size
);
221 write (STDERR_FILENO
, "virtual memory exhausted\n", 25);
228 xrealloc (void *block
, size_t size
)
231 /* We must call malloc explicitly when BLOCK is 0, since some
232 reallocs don't do this. */
236 val
= realloc (block
, size
);
239 write (STDERR_FILENO
, "virtual memory exhausted\n", 25);
248 # define malloc xmalloc
252 # define realloc xrealloc
254 # include <stdbool.h>
257 /* Define the syntax stuff for \<, \>, etc. */
259 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
260 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1, Ssymbol
= 2 };
262 /* Dummy macros for non-Emacs environments. */
263 # define MAX_MULTIBYTE_LENGTH 1
264 # define RE_MULTIBYTE_P(x) 0
265 # define RE_TARGET_MULTIBYTE_P(x) 0
266 # define WORD_BOUNDARY_P(c1, c2) (0)
267 # define BYTES_BY_CHAR_HEAD(p) (1)
268 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
269 # define STRING_CHAR(p) (*(p))
270 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
271 # define CHAR_STRING(c, s) (*(s) = (c), 1)
272 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
273 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
274 # define RE_CHAR_TO_MULTIBYTE(c) (c)
275 # define RE_CHAR_TO_UNIBYTE(c) (c)
276 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
277 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
278 # define GET_CHAR_AFTER(c, p, len) \
280 # define CHAR_BYTE8_P(c) (0)
281 # define CHAR_LEADING_CODE(c) (c)
283 #endif /* not emacs */
286 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
287 # define RE_TRANSLATE_P(TBL) (TBL)
290 /* Get the interface, including the syntax bits. */
293 /* isalpha etc. are used for the character classes. */
298 /* 1 if C is an ASCII character. */
299 # define IS_REAL_ASCII(c) ((c) < 0200)
301 /* 1 if C is a unibyte character. */
302 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
304 /* The Emacs definitions should not be directly affected by locales. */
306 /* In Emacs, these are only used for single-byte characters. */
307 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
308 # define ISCNTRL(c) ((c) < ' ')
309 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
310 || ((c) >= 'a' && (c) <= 'f') \
311 || ((c) >= 'A' && (c) <= 'F'))
313 /* The rest must handle multibyte characters. */
315 # define ISBLANK(c) (IS_REAL_ASCII (c) \
316 ? ((c) == ' ' || (c) == '\t') \
319 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
320 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0240) \
323 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
324 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
327 # define ISALNUM(c) (IS_REAL_ASCII (c) \
328 ? (((c) >= 'a' && (c) <= 'z') \
329 || ((c) >= 'A' && (c) <= 'Z') \
330 || ((c) >= '0' && (c) <= '9')) \
333 # define ISALPHA(c) (IS_REAL_ASCII (c) \
334 ? (((c) >= 'a' && (c) <= 'z') \
335 || ((c) >= 'A' && (c) <= 'Z')) \
338 # define ISLOWER(c) lowercasep (c)
340 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
341 ? ((c) > ' ' && (c) < 0177 \
342 && !(((c) >= 'a' && (c) <= 'z') \
343 || ((c) >= 'A' && (c) <= 'Z') \
344 || ((c) >= '0' && (c) <= '9'))) \
345 : SYNTAX (c) != Sword)
347 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
349 # define ISUPPER(c) uppercasep (c)
351 # define ISWORD(c) (SYNTAX (c) == Sword)
353 #else /* not emacs */
355 /* 1 if C is an ASCII character. */
356 # define IS_REAL_ASCII(c) ((c) < 0200)
358 /* This distinction is not meaningful, except in Emacs. */
359 # define ISUNIBYTE(c) 1
362 # define ISBLANK(c) isblank (c)
364 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
367 # define ISGRAPH(c) isgraph (c)
369 # define ISGRAPH(c) (isprint (c) && !isspace (c))
372 /* Solaris defines ISPRINT so we must undefine it first. */
374 # define ISPRINT(c) isprint (c)
375 # define ISDIGIT(c) isdigit (c)
376 # define ISALNUM(c) isalnum (c)
377 # define ISALPHA(c) isalpha (c)
378 # define ISCNTRL(c) iscntrl (c)
379 # define ISLOWER(c) islower (c)
380 # define ISPUNCT(c) ispunct (c)
381 # define ISSPACE(c) isspace (c)
382 # define ISUPPER(c) isupper (c)
383 # define ISXDIGIT(c) isxdigit (c)
385 # define ISWORD(c) ISALPHA (c)
388 # define TOLOWER(c) _tolower (c)
390 # define TOLOWER(c) tolower (c)
393 /* How many characters in the character set. */
394 # define CHAR_SET_SIZE 256
398 extern char *re_syntax_table
;
400 # else /* not SYNTAX_TABLE */
402 static char re_syntax_table
[CHAR_SET_SIZE
];
405 init_syntax_once (void)
413 memset (re_syntax_table
, 0, sizeof re_syntax_table
);
415 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
417 re_syntax_table
[c
] = Sword
;
419 re_syntax_table
['_'] = Ssymbol
;
424 # endif /* not SYNTAX_TABLE */
426 # define SYNTAX(c) re_syntax_table[(c)]
428 #endif /* not emacs */
430 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
432 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
433 use `alloca' instead of `malloc'. This is because using malloc in
434 re_search* or re_match* could cause memory leaks when C-g is used
435 in Emacs (note that SAFE_ALLOCA could also call malloc, but does so
436 via `record_xmalloc' which uses `unwind_protect' to ensure the
437 memory is freed even in case of non-local exits); also, malloc is
438 slower and causes storage fragmentation. On the other hand, malloc
439 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 */
454 /* This may be adjusted in main(), if the stack is successfully grown. */
455 ptrdiff_t emacs_re_safe_alloca
= MAX_ALLOCA
;
456 /* Like USE_SAFE_ALLOCA, but use emacs_re_safe_alloca. */
457 # define REGEX_USE_SAFE_ALLOCA \
458 ptrdiff_t sa_avail = emacs_re_safe_alloca; \
459 ptrdiff_t sa_count = SPECPDL_INDEX (); bool sa_must_free = false
461 # define REGEX_SAFE_FREE() SAFE_FREE ()
462 # define REGEX_ALLOCATE SAFE_ALLOCA
465 # define REGEX_ALLOCATE alloca
468 /* Assumes a `char *destination' variable. */
469 # define REGEX_REALLOCATE(source, osize, nsize) \
470 (destination = REGEX_ALLOCATE (nsize), \
471 memcpy (destination, source, osize))
473 /* No need to do anything to free, after alloca. */
474 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
476 #endif /* not REGEX_MALLOC */
478 #ifndef REGEX_USE_SAFE_ALLOCA
479 # define REGEX_USE_SAFE_ALLOCA ((void) 0)
480 # define REGEX_SAFE_FREE() ((void) 0)
483 /* Define how to allocate the failure stack. */
485 #if defined REL_ALLOC && defined REGEX_MALLOC
487 # define REGEX_ALLOCATE_STACK(size) \
488 r_alloc (&failure_stack_ptr, (size))
489 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
490 r_re_alloc (&failure_stack_ptr, (nsize))
491 # define REGEX_FREE_STACK(ptr) \
492 r_alloc_free (&failure_stack_ptr)
494 #else /* not using relocating allocator */
496 # define REGEX_ALLOCATE_STACK(size) REGEX_ALLOCATE (size)
497 # define REGEX_REALLOCATE_STACK(source, o, n) REGEX_REALLOCATE (source, o, n)
498 # define REGEX_FREE_STACK(ptr) REGEX_FREE (ptr)
500 #endif /* not using relocating allocator */
503 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
504 `string1' or just past its end. This works if PTR is NULL, which is
506 #define FIRST_STRING_P(ptr) \
507 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
509 /* (Re)Allocate N items of type T using malloc, or fail. */
510 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
511 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
512 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
514 #define BYTEWIDTH 8 /* In bits. */
519 # define max(a, b) ((a) > (b) ? (a) : (b))
520 # define min(a, b) ((a) < (b) ? (a) : (b))
523 /* Type of source-pattern and string chars. */
525 typedef unsigned char re_char
;
526 typedef const re_char const_re_char
;
528 typedef const unsigned char re_char
;
529 typedef re_char const_re_char
;
532 typedef char boolean
;
534 static regoff_t
re_match_2_internal (struct re_pattern_buffer
*bufp
,
535 re_char
*string1
, size_t size1
,
536 re_char
*string2
, size_t size2
,
538 struct re_registers
*regs
,
541 /* These are the command codes that appear in compiled regular
542 expressions. Some opcodes are followed by argument bytes. A
543 command code can specify any interpretation whatsoever for its
544 arguments. Zero bytes may appear in the compiled regular expression. */
550 /* Succeed right away--no more backtracking. */
553 /* Followed by one byte giving n, then by n literal bytes. */
556 /* Matches any (more or less) character. */
559 /* Matches any one char belonging to specified set. First
560 following byte is number of bitmap bytes. Then come bytes
561 for a bitmap saying which chars are in. Bits in each byte
562 are ordered low-bit-first. A character is in the set if its
563 bit is 1. A character too large to have a bit in the map is
564 automatically not in the set.
566 If the length byte has the 0x80 bit set, then that stuff
567 is followed by a range table:
568 2 bytes of flags for character sets (low 8 bits, high 8 bits)
569 See RANGE_TABLE_WORK_BITS below.
570 2 bytes, the number of pairs that follow (upto 32767)
571 pairs, each 2 multibyte characters,
572 each multibyte character represented as 3 bytes. */
575 /* Same parameters as charset, but match any character that is
576 not one of those specified. */
579 /* Start remembering the text that is matched, for storing in a
580 register. Followed by one byte with the register number, in
581 the range 0 to one less than the pattern buffer's re_nsub
585 /* Stop remembering the text that is matched and store it in a
586 memory register. Followed by one byte with the register
587 number, in the range 0 to one less than `re_nsub' in the
591 /* Match a duplicate of something remembered. Followed by one
592 byte containing the register number. */
595 /* Fail unless at beginning of line. */
598 /* Fail unless at end of line. */
601 /* Succeeds if at beginning of buffer (if emacs) or at beginning
602 of string to be matched (if not). */
605 /* Analogously, for end of buffer/string. */
608 /* Followed by two byte relative address to which to jump. */
611 /* Followed by two-byte relative address of place to resume at
612 in case of failure. */
615 /* Like on_failure_jump, but pushes a placeholder instead of the
616 current string position when executed. */
617 on_failure_keep_string_jump
,
619 /* Just like `on_failure_jump', except that it checks that we
620 don't get stuck in an infinite loop (matching an empty string
622 on_failure_jump_loop
,
624 /* Just like `on_failure_jump_loop', except that it checks for
625 a different kind of loop (the kind that shows up with non-greedy
626 operators). This operation has to be immediately preceded
628 on_failure_jump_nastyloop
,
630 /* A smart `on_failure_jump' used for greedy * and + operators.
631 It analyzes the loop before which it is put and if the
632 loop does not require backtracking, it changes itself to
633 `on_failure_keep_string_jump' and short-circuits the loop,
634 else it just defaults to changing itself into `on_failure_jump'.
635 It assumes that it is pointing to just past a `jump'. */
636 on_failure_jump_smart
,
638 /* Followed by two-byte relative address and two-byte number n.
639 After matching N times, jump to the address upon failure.
640 Does not work if N starts at 0: use on_failure_jump_loop
644 /* Followed by two-byte relative address, and two-byte number n.
645 Jump to the address N times, then fail. */
648 /* Set the following two-byte relative address to the
649 subsequent two-byte number. The address *includes* the two
653 wordbeg
, /* Succeeds if at word beginning. */
654 wordend
, /* Succeeds if at word end. */
656 wordbound
, /* Succeeds if at a word boundary. */
657 notwordbound
, /* Succeeds if not at a word boundary. */
659 symbeg
, /* Succeeds if at symbol beginning. */
660 symend
, /* Succeeds if at symbol end. */
662 /* Matches any character whose syntax is specified. Followed by
663 a byte which contains a syntax code, e.g., Sword. */
666 /* Matches any character whose syntax is not that specified. */
670 , at_dot
, /* Succeeds if at point. */
672 /* Matches any character whose category-set contains the specified
673 category. The operator is followed by a byte which contains a
674 category code (mnemonic ASCII character). */
677 /* Matches any character whose category-set does not contain the
678 specified category. The operator is followed by a byte which
679 contains the category code (mnemonic ASCII character). */
684 /* Common operations on the compiled pattern. */
686 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
688 #define STORE_NUMBER(destination, number) \
690 (destination)[0] = (number) & 0377; \
691 (destination)[1] = (number) >> 8; \
694 /* Same as STORE_NUMBER, except increment DESTINATION to
695 the byte after where the number is stored. Therefore, DESTINATION
696 must be an lvalue. */
698 #define STORE_NUMBER_AND_INCR(destination, number) \
700 STORE_NUMBER (destination, number); \
701 (destination) += 2; \
704 /* Put into DESTINATION a number stored in two contiguous bytes starting
707 #define EXTRACT_NUMBER(destination, source) \
708 ((destination) = extract_number (source))
711 extract_number (re_char
*source
)
713 unsigned leading_byte
= SIGN_EXTEND_CHAR (source
[1]);
714 return (leading_byte
<< 8) + source
[0];
717 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
718 SOURCE must be an lvalue. */
720 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
721 ((destination) = extract_number_and_incr (&source))
724 extract_number_and_incr (re_char
**source
)
726 int num
= extract_number (*source
);
731 /* Store a multibyte character in three contiguous bytes starting
732 DESTINATION, and increment DESTINATION to the byte after where the
733 character is stored. Therefore, DESTINATION must be an lvalue. */
735 #define STORE_CHARACTER_AND_INCR(destination, character) \
737 (destination)[0] = (character) & 0377; \
738 (destination)[1] = ((character) >> 8) & 0377; \
739 (destination)[2] = (character) >> 16; \
740 (destination) += 3; \
743 /* Put into DESTINATION a character stored in three contiguous bytes
744 starting at SOURCE. */
746 #define EXTRACT_CHARACTER(destination, source) \
748 (destination) = ((source)[0] \
749 | ((source)[1] << 8) \
750 | ((source)[2] << 16)); \
754 /* Macros for charset. */
756 /* Size of bitmap of charset P in bytes. P is a start of charset,
757 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
758 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
760 /* Nonzero if charset P has range table. */
761 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
763 /* Return the address of range table of charset P. But not the start
764 of table itself, but the before where the number of ranges is
765 stored. `2 +' means to skip re_opcode_t and size of bitmap,
766 and the 2 bytes of flags at the start of the range table. */
767 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
770 /* Extract the bit flags that start a range table. */
771 #define CHARSET_RANGE_TABLE_BITS(p) \
772 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
773 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
776 /* Return the address of end of RANGE_TABLE. COUNT is number of
777 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
778 is start of range and end of range. `* 3' is size of each start
780 #define CHARSET_RANGE_TABLE_END(range_table, count) \
781 ((range_table) + (count) * 2 * 3)
783 /* If DEBUG is defined, Regex prints many voluminous messages about what
784 it is doing (if the variable `debug' is nonzero). If linked with the
785 main program in `iregex.c', you can enter patterns and strings
786 interactively. And if linked with the main program in `main.c' and
787 the other test files, you can run the already-written tests. */
791 /* We use standard I/O for debugging. */
794 /* It is useful to test things that ``must'' be true when debugging. */
797 static int debug
= -100000;
799 # define DEBUG_STATEMENT(e) e
800 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
801 # define DEBUG_COMPILES_ARGUMENTS
802 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
803 if (debug > 0) print_partial_compiled_pattern (s, e)
804 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
805 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
808 /* Print the fastmap in human-readable form. */
811 print_fastmap (char *fastmap
)
813 unsigned was_a_range
= 0;
816 while (i
< (1 << BYTEWIDTH
))
822 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
838 /* Print a compiled pattern string in human-readable form, starting at
839 the START pointer into it and ending just before the pointer END. */
842 print_partial_compiled_pattern (re_char
*start
, re_char
*end
)
850 fprintf (stderr
, "(null)\n");
854 /* Loop over pattern commands. */
857 fprintf (stderr
, "%td:\t", p
- start
);
859 switch ((re_opcode_t
) *p
++)
862 fprintf (stderr
, "/no_op");
866 fprintf (stderr
, "/succeed");
871 fprintf (stderr
, "/exactn/%d", mcnt
);
874 fprintf (stderr
, "/%c", *p
++);
880 fprintf (stderr
, "/start_memory/%d", *p
++);
884 fprintf (stderr
, "/stop_memory/%d", *p
++);
888 fprintf (stderr
, "/duplicate/%d", *p
++);
892 fprintf (stderr
, "/anychar");
898 register int c
, last
= -100;
899 register int in_range
= 0;
900 int length
= CHARSET_BITMAP_SIZE (p
- 1);
901 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
903 fprintf (stderr
, "/charset [%s",
904 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
907 fprintf (stderr
, " !extends past end of pattern! ");
909 for (c
= 0; c
< 256; c
++)
911 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
913 /* Are we starting a range? */
914 if (last
+ 1 == c
&& ! in_range
)
916 fprintf (stderr
, "-");
919 /* Have we broken a range? */
920 else if (last
+ 1 != c
&& in_range
)
922 fprintf (stderr
, "%c", last
);
927 fprintf (stderr
, "%c", c
);
933 fprintf (stderr
, "%c", last
);
935 fprintf (stderr
, "]");
942 fprintf (stderr
, "has-range-table");
944 /* ??? Should print the range table; for now, just skip it. */
945 p
+= 2; /* skip range table bits */
946 EXTRACT_NUMBER_AND_INCR (count
, p
);
947 p
= CHARSET_RANGE_TABLE_END (p
, count
);
953 fprintf (stderr
, "/begline");
957 fprintf (stderr
, "/endline");
960 case on_failure_jump
:
961 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
962 fprintf (stderr
, "/on_failure_jump to %td", p
+ mcnt
- start
);
965 case on_failure_keep_string_jump
:
966 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
967 fprintf (stderr
, "/on_failure_keep_string_jump to %td",
971 case on_failure_jump_nastyloop
:
972 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
973 fprintf (stderr
, "/on_failure_jump_nastyloop to %td",
977 case on_failure_jump_loop
:
978 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
979 fprintf (stderr
, "/on_failure_jump_loop to %td",
983 case on_failure_jump_smart
:
984 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
985 fprintf (stderr
, "/on_failure_jump_smart to %td",
990 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
991 fprintf (stderr
, "/jump to %td", p
+ mcnt
- start
);
995 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
996 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
997 fprintf (stderr
, "/succeed_n to %td, %d times",
998 p
- 2 + mcnt
- start
, mcnt2
);
1002 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1003 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
1004 fprintf (stderr
, "/jump_n to %td, %d times",
1005 p
- 2 + mcnt
- start
, mcnt2
);
1009 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
1010 EXTRACT_NUMBER_AND_INCR (mcnt2
, p
);
1011 fprintf (stderr
, "/set_number_at location %td to %d",
1012 p
- 2 + mcnt
- start
, mcnt2
);
1016 fprintf (stderr
, "/wordbound");
1020 fprintf (stderr
, "/notwordbound");
1024 fprintf (stderr
, "/wordbeg");
1028 fprintf (stderr
, "/wordend");
1032 fprintf (stderr
, "/symbeg");
1036 fprintf (stderr
, "/symend");
1040 fprintf (stderr
, "/syntaxspec");
1042 fprintf (stderr
, "/%d", mcnt
);
1046 fprintf (stderr
, "/notsyntaxspec");
1048 fprintf (stderr
, "/%d", mcnt
);
1053 fprintf (stderr
, "/at_dot");
1057 fprintf (stderr
, "/categoryspec");
1059 fprintf (stderr
, "/%d", mcnt
);
1062 case notcategoryspec
:
1063 fprintf (stderr
, "/notcategoryspec");
1065 fprintf (stderr
, "/%d", mcnt
);
1070 fprintf (stderr
, "/begbuf");
1074 fprintf (stderr
, "/endbuf");
1078 fprintf (stderr
, "?%d", *(p
-1));
1081 fprintf (stderr
, "\n");
1084 fprintf (stderr
, "%td:\tend of pattern.\n", p
- start
);
1089 print_compiled_pattern (struct re_pattern_buffer
*bufp
)
1091 re_char
*buffer
= bufp
->buffer
;
1093 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1094 printf ("%ld bytes used/%ld bytes allocated.\n",
1095 bufp
->used
, bufp
->allocated
);
1097 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1099 printf ("fastmap: ");
1100 print_fastmap (bufp
->fastmap
);
1103 printf ("re_nsub: %zu\t", bufp
->re_nsub
);
1104 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1105 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1106 printf ("no_sub: %d\t", bufp
->no_sub
);
1107 printf ("not_bol: %d\t", bufp
->not_bol
);
1108 printf ("not_eol: %d\t", bufp
->not_eol
);
1110 printf ("syntax: %lx\n", bufp
->syntax
);
1113 /* Perhaps we should print the translate table? */
1118 print_double_string (re_char
*where
, re_char
*string1
, ssize_t size1
,
1119 re_char
*string2
, ssize_t size2
)
1127 if (FIRST_STRING_P (where
))
1129 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1130 putchar (string1
[this_char
]);
1135 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1136 putchar (string2
[this_char
]);
1140 #else /* not DEBUG */
1145 # define DEBUG_STATEMENT(e)
1146 # define DEBUG_PRINT(...)
1147 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1148 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1150 #endif /* not DEBUG */
1154 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1155 also be assigned to arbitrarily: each pattern buffer stores its own
1156 syntax, so it can be changed between regex compilations. */
1157 /* This has no initializer because initialized variables in Emacs
1158 become read-only after dumping. */
1159 reg_syntax_t re_syntax_options
;
1162 /* Specify the precise syntax of regexps for compilation. This provides
1163 for compatibility for various utilities which historically have
1164 different, incompatible syntaxes.
1166 The argument SYNTAX is a bit mask comprised of the various bits
1167 defined in regex.h. We return the old syntax. */
1170 re_set_syntax (reg_syntax_t syntax
)
1172 reg_syntax_t ret
= re_syntax_options
;
1174 re_syntax_options
= syntax
;
1177 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1181 /* This table gives an error message for each of the error codes listed
1182 in regex.h. Obviously the order here has to be same as there.
1183 POSIX doesn't require that we do anything for REG_NOERROR,
1184 but why not be nice? */
1186 static const char *re_error_msgid
[] =
1188 gettext_noop ("Success"), /* REG_NOERROR */
1189 gettext_noop ("No match"), /* REG_NOMATCH */
1190 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1191 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1192 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1193 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1194 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1195 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1196 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1197 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1198 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1199 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1200 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1201 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1202 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1203 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1204 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1205 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1208 /* Whether to allocate memory during matching. */
1210 /* Define MATCH_MAY_ALLOCATE to allow the searching and matching
1211 functions allocate memory for the failure stack and registers.
1212 Normally should be defined, because otherwise searching and
1213 matching routines will have much smaller memory resources at their
1214 disposal, and therefore might fail to handle complex regexps.
1215 Therefore undefine MATCH_MAY_ALLOCATE only in the following
1216 exceptional situations:
1218 . When running on a system where memory is at premium.
1219 . When alloca cannot be used at all, perhaps due to bugs in
1220 its implementation, or its being unavailable, or due to a
1221 very small stack size. This requires to define REGEX_MALLOC
1222 to use malloc instead, which in turn could lead to memory
1223 leaks if search is interrupted by a signal. (For these
1224 reasons, defining REGEX_MALLOC when building Emacs
1225 automatically undefines MATCH_MAY_ALLOCATE, but outside
1226 Emacs you may not care about memory leaks.) If you want to
1227 prevent the memory leaks, undefine MATCH_MAY_ALLOCATE.
1228 . When code that calls the searching and matching functions
1229 cannot allow memory allocation, for whatever reasons. */
1231 /* Normally, this is fine. */
1232 #define MATCH_MAY_ALLOCATE
1234 /* The match routines may not allocate if (1) they would do it with malloc
1235 and (2) it's not safe for them to use malloc.
1236 Note that if REL_ALLOC is defined, matching would not use malloc for the
1237 failure stack, but we would still use it for the register vectors;
1238 so REL_ALLOC should not affect this. */
1239 #if defined REGEX_MALLOC && defined emacs
1240 # undef MATCH_MAY_ALLOCATE
1244 /* Failure stack declarations and macros; both re_compile_fastmap and
1245 re_match_2 use a failure stack. These have to be macros because of
1246 REGEX_ALLOCATE_STACK. */
1249 /* Approximate number of failure points for which to initially allocate space
1250 when matching. If this number is exceeded, we allocate more
1251 space, so it is not a hard limit. */
1252 #ifndef INIT_FAILURE_ALLOC
1253 # define INIT_FAILURE_ALLOC 20
1256 /* Roughly the maximum number of failure points on the stack. Would be
1257 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1258 This is a variable only so users of regex can assign to it; we never
1259 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1260 before using it, so it should probably be a byte-count instead. */
1261 # if defined MATCH_MAY_ALLOCATE
1262 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1263 whose default stack limit is 2mb. In order for a larger
1264 value to work reliably, you have to try to make it accord
1265 with the process stack limit. */
1266 size_t emacs_re_max_failures
= 40000;
1268 size_t emacs_re_max_failures
= 4000;
1271 union fail_stack_elt
1274 /* This should be the biggest `int' that's no bigger than a pointer. */
1278 typedef union fail_stack_elt fail_stack_elt_t
;
1282 fail_stack_elt_t
*stack
;
1284 size_t avail
; /* Offset of next open position. */
1285 size_t frame
; /* Offset of the cur constructed frame. */
1288 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1291 /* Define macros to initialize and free the failure stack.
1292 Do `return -2' if the alloc fails. */
1294 #ifdef MATCH_MAY_ALLOCATE
1295 # define INIT_FAIL_STACK() \
1297 fail_stack.stack = \
1298 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1299 * sizeof (fail_stack_elt_t)); \
1301 if (fail_stack.stack == NULL) \
1304 fail_stack.size = INIT_FAILURE_ALLOC; \
1305 fail_stack.avail = 0; \
1306 fail_stack.frame = 0; \
1309 # define INIT_FAIL_STACK() \
1311 fail_stack.avail = 0; \
1312 fail_stack.frame = 0; \
1315 # define RETALLOC_IF(addr, n, t) \
1316 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1320 /* Double the size of FAIL_STACK, up to a limit
1321 which allows approximately `emacs_re_max_failures' items.
1323 Return 1 if succeeds, and 0 if either ran out of memory
1324 allocating space for it or it was already too large.
1326 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1328 /* Factor to increase the failure stack size by
1329 when we increase it.
1330 This used to be 2, but 2 was too wasteful
1331 because the old discarded stacks added up to as much space
1332 were as ultimate, maximum-size stack. */
1333 #define FAIL_STACK_GROWTH_FACTOR 4
1335 #define GROW_FAIL_STACK(fail_stack) \
1336 (((fail_stack).size >= emacs_re_max_failures * TYPICAL_FAILURE_SIZE) \
1338 : ((fail_stack).stack \
1339 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1340 (fail_stack).size * sizeof (fail_stack_elt_t), \
1341 min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1342 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR)) \
1343 * sizeof (fail_stack_elt_t)), \
1345 (fail_stack).stack == NULL \
1347 : ((fail_stack).size \
1348 = (min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1349 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR))), \
1353 /* Push a pointer value onto the failure stack.
1354 Assumes the variable `fail_stack'. Probably should only
1355 be called from within `PUSH_FAILURE_POINT'. */
1356 #define PUSH_FAILURE_POINTER(item) \
1357 fail_stack.stack[fail_stack.avail++].pointer = (item)
1359 /* This pushes an integer-valued item onto the failure stack.
1360 Assumes the variable `fail_stack'. Probably should only
1361 be called from within `PUSH_FAILURE_POINT'. */
1362 #define PUSH_FAILURE_INT(item) \
1363 fail_stack.stack[fail_stack.avail++].integer = (item)
1365 /* These POP... operations complement the PUSH... operations.
1366 All assume that `fail_stack' is nonempty. */
1367 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1368 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1370 /* Individual items aside from the registers. */
1371 #define NUM_NONREG_ITEMS 3
1373 /* Used to examine the stack (to detect infinite loops). */
1374 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1375 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1376 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1377 #define TOP_FAILURE_HANDLE() fail_stack.frame
1380 #define ENSURE_FAIL_STACK(space) \
1381 while (REMAINING_AVAIL_SLOTS <= space) { \
1382 if (!GROW_FAIL_STACK (fail_stack)) \
1384 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1385 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1388 /* Push register NUM onto the stack. */
1389 #define PUSH_FAILURE_REG(num) \
1391 char *destination; \
1393 ENSURE_FAIL_STACK(3); \
1394 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1395 n, regstart[n], regend[n]); \
1396 PUSH_FAILURE_POINTER (regstart[n]); \
1397 PUSH_FAILURE_POINTER (regend[n]); \
1398 PUSH_FAILURE_INT (n); \
1401 /* Change the counter's value to VAL, but make sure that it will
1402 be reset when backtracking. */
1403 #define PUSH_NUMBER(ptr,val) \
1405 char *destination; \
1407 ENSURE_FAIL_STACK(3); \
1408 EXTRACT_NUMBER (c, ptr); \
1409 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1410 PUSH_FAILURE_INT (c); \
1411 PUSH_FAILURE_POINTER (ptr); \
1412 PUSH_FAILURE_INT (-1); \
1413 STORE_NUMBER (ptr, val); \
1416 /* Pop a saved register off the stack. */
1417 #define POP_FAILURE_REG_OR_COUNT() \
1419 long pfreg = POP_FAILURE_INT (); \
1422 /* It's a counter. */ \
1423 /* Here, we discard `const', making re_match non-reentrant. */ \
1424 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1425 pfreg = POP_FAILURE_INT (); \
1426 STORE_NUMBER (ptr, pfreg); \
1427 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1431 regend[pfreg] = POP_FAILURE_POINTER (); \
1432 regstart[pfreg] = POP_FAILURE_POINTER (); \
1433 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1434 pfreg, regstart[pfreg], regend[pfreg]); \
1438 /* Check that we are not stuck in an infinite loop. */
1439 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1441 ssize_t failure = TOP_FAILURE_HANDLE (); \
1442 /* Check for infinite matching loops */ \
1443 while (failure > 0 \
1444 && (FAILURE_STR (failure) == string_place \
1445 || FAILURE_STR (failure) == NULL)) \
1447 assert (FAILURE_PAT (failure) >= bufp->buffer \
1448 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1449 if (FAILURE_PAT (failure) == pat_cur) \
1454 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1455 failure = NEXT_FAILURE_HANDLE(failure); \
1457 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1460 /* Push the information about the state we will need
1461 if we ever fail back to it.
1463 Requires variables fail_stack, regstart, regend and
1464 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1467 Does `return FAILURE_CODE' if runs out of memory. */
1469 #define PUSH_FAILURE_POINT(pattern, string_place) \
1471 char *destination; \
1472 /* Must be int, so when we don't save any registers, the arithmetic \
1473 of 0 + -1 isn't done as unsigned. */ \
1475 DEBUG_STATEMENT (nfailure_points_pushed++); \
1476 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1477 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1478 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1480 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1482 DEBUG_PRINT ("\n"); \
1484 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1485 PUSH_FAILURE_INT (fail_stack.frame); \
1487 DEBUG_PRINT (" Push string %p: \"", string_place); \
1488 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1489 DEBUG_PRINT ("\"\n"); \
1490 PUSH_FAILURE_POINTER (string_place); \
1492 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1493 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1494 PUSH_FAILURE_POINTER (pattern); \
1496 /* Close the frame by moving the frame pointer past it. */ \
1497 fail_stack.frame = fail_stack.avail; \
1500 /* Estimate the size of data pushed by a typical failure stack entry.
1501 An estimate is all we need, because all we use this for
1502 is to choose a limit for how big to make the failure stack. */
1503 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1504 #define TYPICAL_FAILURE_SIZE 20
1506 /* How many items can still be added to the stack without overflowing it. */
1507 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1510 /* Pops what PUSH_FAIL_STACK pushes.
1512 We restore into the parameters, all of which should be lvalues:
1513 STR -- the saved data position.
1514 PAT -- the saved pattern position.
1515 REGSTART, REGEND -- arrays of string positions.
1517 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1518 `pend', `string1', `size1', `string2', and `size2'. */
1520 #define POP_FAILURE_POINT(str, pat) \
1522 assert (!FAIL_STACK_EMPTY ()); \
1524 /* Remove failure points and point to how many regs pushed. */ \
1525 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1526 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1527 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1529 /* Pop the saved registers. */ \
1530 while (fail_stack.frame < fail_stack.avail) \
1531 POP_FAILURE_REG_OR_COUNT (); \
1533 pat = POP_FAILURE_POINTER (); \
1534 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1535 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1537 /* If the saved string location is NULL, it came from an \
1538 on_failure_keep_string_jump opcode, and we want to throw away the \
1539 saved NULL, thus retaining our current position in the string. */ \
1540 str = POP_FAILURE_POINTER (); \
1541 DEBUG_PRINT (" Popping string %p: \"", str); \
1542 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1543 DEBUG_PRINT ("\"\n"); \
1545 fail_stack.frame = POP_FAILURE_INT (); \
1546 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1548 assert (fail_stack.avail >= 0); \
1549 assert (fail_stack.frame <= fail_stack.avail); \
1551 DEBUG_STATEMENT (nfailure_points_popped++); \
1552 } while (0) /* POP_FAILURE_POINT */
1556 /* Registers are set to a sentinel when they haven't yet matched. */
1557 #define REG_UNSET(e) ((e) == NULL)
1559 /* Subroutine declarations and macros for regex_compile. */
1561 static reg_errcode_t
regex_compile (re_char
*pattern
, size_t size
,
1563 bool posix_backtracking
,
1564 const char *whitespace_regexp
,
1566 reg_syntax_t syntax
,
1568 struct re_pattern_buffer
*bufp
);
1569 static void store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
);
1570 static void store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
);
1571 static void insert_op1 (re_opcode_t op
, unsigned char *loc
,
1572 int arg
, unsigned char *end
);
1573 static void insert_op2 (re_opcode_t op
, unsigned char *loc
,
1574 int arg1
, int arg2
, unsigned char *end
);
1575 static boolean
at_begline_loc_p (re_char
*pattern
, re_char
*p
,
1576 reg_syntax_t syntax
);
1577 static boolean
at_endline_loc_p (re_char
*p
, re_char
*pend
,
1578 reg_syntax_t syntax
);
1579 static re_char
*skip_one_char (re_char
*p
);
1580 static int analyze_first (re_char
*p
, re_char
*pend
,
1581 char *fastmap
, const int multibyte
);
1583 /* Fetch the next character in the uncompiled pattern, with no
1585 #define PATFETCH(c) \
1588 if (p == pend) return REG_EEND; \
1589 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1594 /* If `translate' is non-null, return translate[D], else just D. We
1595 cast the subscript to translate because some data is declared as
1596 `char *', to avoid warnings when a string constant is passed. But
1597 when we use a character as a subscript we must make it unsigned. */
1599 # define TRANSLATE(d) \
1600 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1604 /* Macros for outputting the compiled pattern into `buffer'. */
1606 /* If the buffer isn't allocated when it comes in, use this. */
1607 #define INIT_BUF_SIZE 32
1609 /* Make sure we have at least N more bytes of space in buffer. */
1610 #define GET_BUFFER_SPACE(n) \
1611 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1614 /* Make sure we have one more byte of buffer space and then add C to it. */
1615 #define BUF_PUSH(c) \
1617 GET_BUFFER_SPACE (1); \
1618 *b++ = (unsigned char) (c); \
1622 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1623 #define BUF_PUSH_2(c1, c2) \
1625 GET_BUFFER_SPACE (2); \
1626 *b++ = (unsigned char) (c1); \
1627 *b++ = (unsigned char) (c2); \
1631 /* Store a jump with opcode OP at LOC to location TO. We store a
1632 relative address offset by the three bytes the jump itself occupies. */
1633 #define STORE_JUMP(op, loc, to) \
1634 store_op1 (op, loc, (to) - (loc) - 3)
1636 /* Likewise, for a two-argument jump. */
1637 #define STORE_JUMP2(op, loc, to, arg) \
1638 store_op2 (op, loc, (to) - (loc) - 3, arg)
1640 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1641 #define INSERT_JUMP(op, loc, to) \
1642 insert_op1 (op, loc, (to) - (loc) - 3, b)
1644 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1645 #define INSERT_JUMP2(op, loc, to, arg) \
1646 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1649 /* This is not an arbitrary limit: the arguments which represent offsets
1650 into the pattern are two bytes long. So if 2^15 bytes turns out to
1651 be too small, many things would have to change. */
1652 # define MAX_BUF_SIZE (1L << 15)
1654 /* Extend the buffer by twice its current size via realloc and
1655 reset the pointers that pointed into the old block to point to the
1656 correct places in the new one. If extending the buffer results in it
1657 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1658 #define EXTEND_BUFFER() \
1660 unsigned char *old_buffer = bufp->buffer; \
1661 if (bufp->allocated == MAX_BUF_SIZE) \
1663 bufp->allocated <<= 1; \
1664 if (bufp->allocated > MAX_BUF_SIZE) \
1665 bufp->allocated = MAX_BUF_SIZE; \
1666 ptrdiff_t b_off = b - old_buffer; \
1667 ptrdiff_t begalt_off = begalt - old_buffer; \
1668 bool fixup_alt_jump_set = !!fixup_alt_jump; \
1669 bool laststart_set = !!laststart; \
1670 bool pending_exact_set = !!pending_exact; \
1671 ptrdiff_t fixup_alt_jump_off, laststart_off, pending_exact_off; \
1672 if (fixup_alt_jump_set) fixup_alt_jump_off = fixup_alt_jump - old_buffer; \
1673 if (laststart_set) laststart_off = laststart - old_buffer; \
1674 if (pending_exact_set) pending_exact_off = pending_exact - old_buffer; \
1675 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1676 if (bufp->buffer == NULL) \
1677 return REG_ESPACE; \
1678 unsigned char *new_buffer = bufp->buffer; \
1679 b = new_buffer + b_off; \
1680 begalt = new_buffer + begalt_off; \
1681 if (fixup_alt_jump_set) fixup_alt_jump = new_buffer + fixup_alt_jump_off; \
1682 if (laststart_set) laststart = new_buffer + laststart_off; \
1683 if (pending_exact_set) pending_exact = new_buffer + pending_exact_off; \
1687 /* Since we have one byte reserved for the register number argument to
1688 {start,stop}_memory, the maximum number of groups we can report
1689 things about is what fits in that byte. */
1690 #define MAX_REGNUM 255
1692 /* But patterns can have more than `MAX_REGNUM' registers. We just
1693 ignore the excess. */
1694 typedef int regnum_t
;
1697 /* Macros for the compile stack. */
1699 /* Since offsets can go either forwards or backwards, this type needs to
1700 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1701 /* int may be not enough when sizeof(int) == 2. */
1702 typedef long pattern_offset_t
;
1706 pattern_offset_t begalt_offset
;
1707 pattern_offset_t fixup_alt_jump
;
1708 pattern_offset_t laststart_offset
;
1710 } compile_stack_elt_t
;
1715 compile_stack_elt_t
*stack
;
1717 size_t avail
; /* Offset of next open position. */
1718 } compile_stack_type
;
1721 #define INIT_COMPILE_STACK_SIZE 32
1723 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1724 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1726 /* The next available element. */
1727 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1729 /* Explicit quit checking is needed for Emacs, which uses polling to
1730 process input events. */
1732 # define IMMEDIATE_QUIT_CHECK (immediate_quit ? maybe_quit () : (void) 0)
1734 # define IMMEDIATE_QUIT_CHECK ((void) 0)
1737 /* Structure to manage work area for range table. */
1738 struct range_table_work_area
1740 int *table
; /* actual work area. */
1741 int allocated
; /* allocated size for work area in bytes. */
1742 int used
; /* actually used size in words. */
1743 int bits
; /* flag to record character classes */
1748 /* Make sure that WORK_AREA can hold more N multibyte characters.
1749 This is used only in set_image_of_range and set_image_of_range_1.
1750 It expects WORK_AREA to be a pointer.
1751 If it can't get the space, it returns from the surrounding function. */
1753 #define EXTEND_RANGE_TABLE(work_area, n) \
1755 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1757 extend_range_table_work_area (&work_area); \
1758 if ((work_area).table == 0) \
1759 return (REG_ESPACE); \
1763 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1764 (work_area).bits |= (bit)
1766 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1767 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1769 EXTEND_RANGE_TABLE ((work_area), 2); \
1770 (work_area).table[(work_area).used++] = (range_start); \
1771 (work_area).table[(work_area).used++] = (range_end); \
1776 /* Free allocated memory for WORK_AREA. */
1777 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1779 if ((work_area).table) \
1780 free ((work_area).table); \
1783 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1784 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1785 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1786 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1788 /* Bits used to implement the multibyte-part of the various character classes
1789 such as [:alnum:] in a charset's range table. The code currently assumes
1790 that only the low 16 bits are used. */
1791 #define BIT_WORD 0x1
1792 #define BIT_LOWER 0x2
1793 #define BIT_PUNCT 0x4
1794 #define BIT_SPACE 0x8
1795 #define BIT_UPPER 0x10
1796 #define BIT_MULTIBYTE 0x20
1797 #define BIT_ALPHA 0x40
1798 #define BIT_ALNUM 0x80
1799 #define BIT_GRAPH 0x100
1800 #define BIT_PRINT 0x200
1801 #define BIT_BLANK 0x400
1804 /* Set the bit for character C in a list. */
1805 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1810 /* Store characters in the range FROM to TO in the bitmap at B (for
1811 ASCII and unibyte characters) and WORK_AREA (for multibyte
1812 characters) while translating them and paying attention to the
1813 continuity of translated characters.
1815 Implementation note: It is better to implement these fairly big
1816 macros by a function, but it's not that easy because macros called
1817 in this macro assume various local variables already declared. */
1819 /* Both FROM and TO are ASCII characters. */
1821 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1825 for (C0 = (FROM); C0 <= (TO); C0++) \
1827 C1 = TRANSLATE (C0); \
1828 if (! ASCII_CHAR_P (C1)) \
1830 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1831 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1834 SET_LIST_BIT (C1); \
1839 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1841 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1843 int C0, C1, C2, I; \
1844 int USED = RANGE_TABLE_WORK_USED (work_area); \
1846 for (C0 = (FROM); C0 <= (TO); C0++) \
1848 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1849 if (CHAR_BYTE8_P (C1)) \
1850 SET_LIST_BIT (C0); \
1853 C2 = TRANSLATE (C1); \
1855 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1857 SET_LIST_BIT (C1); \
1858 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1860 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1861 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1863 if (C2 >= from - 1 && C2 <= to + 1) \
1865 if (C2 == from - 1) \
1866 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1867 else if (C2 == to + 1) \
1868 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1873 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1879 /* Both FROM and TO are multibyte characters. */
1881 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1883 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1885 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1886 for (C0 = (FROM); C0 <= (TO); C0++) \
1888 C1 = TRANSLATE (C0); \
1889 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1890 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1891 SET_LIST_BIT (C2); \
1892 if (C1 >= (FROM) && C1 <= (TO)) \
1894 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1896 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1897 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1899 if (C1 >= from - 1 && C1 <= to + 1) \
1901 if (C1 == from - 1) \
1902 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1903 else if (C1 == to + 1) \
1904 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1909 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1915 /* Get the next unsigned number in the uncompiled pattern. */
1916 #define GET_INTERVAL_COUNT(num) \
1919 FREE_STACK_RETURN (REG_EBRACE); \
1923 while ('0' <= c && c <= '9') \
1927 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
1928 FREE_STACK_RETURN (REG_BADBR); \
1929 num = num * 10 + c - '0'; \
1931 FREE_STACK_RETURN (REG_EBRACE); \
1937 #if ! WIDE_CHAR_SUPPORT
1939 /* Parse a character class, i.e. string such as "[:name:]". *strp
1940 points to the string to be parsed and limit is length, in bytes, of
1943 If *strp point to a string that begins with "[:name:]", where name is
1944 a non-empty sequence of lower case letters, *strp will be advanced past the
1945 closing square bracket and RECC_* constant which maps to the name will be
1946 returned. If name is not a valid character class name zero, or RECC_ERROR,
1949 Otherwise, if *strp doesn’t begin with "[:name:]", -1 is returned.
1951 The function can be used on ASCII and multibyte (UTF-8-encoded) strings.
1954 re_wctype_parse (const unsigned char **strp
, unsigned limit
)
1956 const char *beg
= (const char *)*strp
, *it
;
1958 if (limit
< 4 || beg
[0] != '[' || beg
[1] != ':')
1961 beg
+= 2; /* skip opening ‘[:’ */
1962 limit
-= 3; /* opening ‘[:’ and half of closing ‘:]’; --limit handles rest */
1963 for (it
= beg
; it
[0] != ':' || it
[1] != ']'; ++it
)
1967 *strp
= (const unsigned char *)(it
+ 2);
1969 /* Sort tests in the length=five case by frequency the classes to minimize
1970 number of times we fail the comparison. The frequencies of character class
1971 names used in Emacs sources as of 2016-07-27:
1973 $ find \( -name \*.c -o -name \*.el \) -exec grep -h '\[:[a-z]*:]' {} + |
1974 sed 's/]/]\n/g' |grep -o '\[:[a-z]*:]' |sort |uniq -c |sort -nr
1992 If you update this list, consider also updating chain of or’ed conditions
1993 in execute_charset function.
1998 if (!memcmp (beg
, "word", 4)) return RECC_WORD
;
2001 if (!memcmp (beg
, "alnum", 5)) return RECC_ALNUM
;
2002 if (!memcmp (beg
, "alpha", 5)) return RECC_ALPHA
;
2003 if (!memcmp (beg
, "space", 5)) return RECC_SPACE
;
2004 if (!memcmp (beg
, "digit", 5)) return RECC_DIGIT
;
2005 if (!memcmp (beg
, "blank", 5)) return RECC_BLANK
;
2006 if (!memcmp (beg
, "upper", 5)) return RECC_UPPER
;
2007 if (!memcmp (beg
, "lower", 5)) return RECC_LOWER
;
2008 if (!memcmp (beg
, "punct", 5)) return RECC_PUNCT
;
2009 if (!memcmp (beg
, "ascii", 5)) return RECC_ASCII
;
2010 if (!memcmp (beg
, "graph", 5)) return RECC_GRAPH
;
2011 if (!memcmp (beg
, "print", 5)) return RECC_PRINT
;
2012 if (!memcmp (beg
, "cntrl", 5)) return RECC_CNTRL
;
2015 if (!memcmp (beg
, "xdigit", 6)) return RECC_XDIGIT
;
2018 if (!memcmp (beg
, "unibyte", 7)) return RECC_UNIBYTE
;
2021 if (!memcmp (beg
, "nonascii", 8)) return RECC_NONASCII
;
2024 if (!memcmp (beg
, "multibyte", 9)) return RECC_MULTIBYTE
;
2031 /* True if CH is in the char class CC. */
2033 re_iswctype (int ch
, re_wctype_t cc
)
2037 case RECC_ALNUM
: return ISALNUM (ch
) != 0;
2038 case RECC_ALPHA
: return ISALPHA (ch
) != 0;
2039 case RECC_BLANK
: return ISBLANK (ch
) != 0;
2040 case RECC_CNTRL
: return ISCNTRL (ch
) != 0;
2041 case RECC_DIGIT
: return ISDIGIT (ch
) != 0;
2042 case RECC_GRAPH
: return ISGRAPH (ch
) != 0;
2043 case RECC_LOWER
: return ISLOWER (ch
) != 0;
2044 case RECC_PRINT
: return ISPRINT (ch
) != 0;
2045 case RECC_PUNCT
: return ISPUNCT (ch
) != 0;
2046 case RECC_SPACE
: return ISSPACE (ch
) != 0;
2047 case RECC_UPPER
: return ISUPPER (ch
) != 0;
2048 case RECC_XDIGIT
: return ISXDIGIT (ch
) != 0;
2049 case RECC_ASCII
: return IS_REAL_ASCII (ch
) != 0;
2050 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2051 case RECC_UNIBYTE
: return ISUNIBYTE (ch
) != 0;
2052 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2053 case RECC_WORD
: return ISWORD (ch
) != 0;
2054 case RECC_ERROR
: return false;
2060 /* Return a bit-pattern to use in the range-table bits to match multibyte
2061 chars of class CC. */
2063 re_wctype_to_bit (re_wctype_t cc
)
2068 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2069 case RECC_ALPHA
: return BIT_ALPHA
;
2070 case RECC_ALNUM
: return BIT_ALNUM
;
2071 case RECC_WORD
: return BIT_WORD
;
2072 case RECC_LOWER
: return BIT_LOWER
;
2073 case RECC_UPPER
: return BIT_UPPER
;
2074 case RECC_PUNCT
: return BIT_PUNCT
;
2075 case RECC_SPACE
: return BIT_SPACE
;
2076 case RECC_GRAPH
: return BIT_GRAPH
;
2077 case RECC_PRINT
: return BIT_PRINT
;
2078 case RECC_BLANK
: return BIT_BLANK
;
2079 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2080 case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2087 /* Filling in the work area of a range. */
2089 /* Actually extend the space in WORK_AREA. */
2092 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2094 work_area
->allocated
+= 16 * sizeof (int);
2095 work_area
->table
= realloc (work_area
->table
, work_area
->allocated
);
2101 /* Carefully find the ranges of codes that are equivalent
2102 under case conversion to the range start..end when passed through
2103 TRANSLATE. Handle the case where non-letters can come in between
2104 two upper-case letters (which happens in Latin-1).
2105 Also handle the case of groups of more than 2 case-equivalent chars.
2107 The basic method is to look at consecutive characters and see
2108 if they can form a run that can be handled as one.
2110 Returns -1 if successful, REG_ESPACE if ran out of space. */
2113 set_image_of_range_1 (struct range_table_work_area
*work_area
,
2114 re_wchar_t start
, re_wchar_t end
,
2115 RE_TRANSLATE_TYPE translate
)
2117 /* `one_case' indicates a character, or a run of characters,
2118 each of which is an isolate (no case-equivalents).
2119 This includes all ASCII non-letters.
2121 `two_case' indicates a character, or a run of characters,
2122 each of which has two case-equivalent forms.
2123 This includes all ASCII letters.
2125 `strange' indicates a character that has more than one
2128 enum case_type
{one_case
, two_case
, strange
};
2130 /* Describe the run that is in progress,
2131 which the next character can try to extend.
2132 If run_type is strange, that means there really is no run.
2133 If run_type is one_case, then run_start...run_end is the run.
2134 If run_type is two_case, then the run is run_start...run_end,
2135 and the case-equivalents end at run_eqv_end. */
2137 enum case_type run_type
= strange
;
2138 int run_start
, run_end
, run_eqv_end
;
2140 Lisp_Object eqv_table
;
2142 if (!RE_TRANSLATE_P (translate
))
2144 EXTEND_RANGE_TABLE (work_area
, 2);
2145 work_area
->table
[work_area
->used
++] = (start
);
2146 work_area
->table
[work_area
->used
++] = (end
);
2150 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2152 for (; start
<= end
; start
++)
2154 enum case_type this_type
;
2155 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2156 int minchar
, maxchar
;
2158 /* Classify this character */
2160 this_type
= one_case
;
2161 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2162 this_type
= two_case
;
2164 this_type
= strange
;
2167 minchar
= start
, maxchar
= eqv
;
2169 minchar
= eqv
, maxchar
= start
;
2171 /* Can this character extend the run in progress? */
2172 if (this_type
== strange
|| this_type
!= run_type
2173 || !(minchar
== run_end
+ 1
2174 && (run_type
== two_case
2175 ? maxchar
== run_eqv_end
+ 1 : 1)))
2178 Record each of its equivalent ranges. */
2179 if (run_type
== one_case
)
2181 EXTEND_RANGE_TABLE (work_area
, 2);
2182 work_area
->table
[work_area
->used
++] = run_start
;
2183 work_area
->table
[work_area
->used
++] = run_end
;
2185 else if (run_type
== two_case
)
2187 EXTEND_RANGE_TABLE (work_area
, 4);
2188 work_area
->table
[work_area
->used
++] = run_start
;
2189 work_area
->table
[work_area
->used
++] = run_end
;
2190 work_area
->table
[work_area
->used
++]
2191 = RE_TRANSLATE (eqv_table
, run_start
);
2192 work_area
->table
[work_area
->used
++]
2193 = RE_TRANSLATE (eqv_table
, run_end
);
2198 if (this_type
== strange
)
2200 /* For a strange character, add each of its equivalents, one
2201 by one. Don't start a range. */
2204 EXTEND_RANGE_TABLE (work_area
, 2);
2205 work_area
->table
[work_area
->used
++] = eqv
;
2206 work_area
->table
[work_area
->used
++] = eqv
;
2207 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2209 while (eqv
!= start
);
2212 /* Add this char to the run, or start a new run. */
2213 else if (run_type
== strange
)
2215 /* Initialize a new range. */
2216 run_type
= this_type
;
2219 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2223 /* Extend a running range. */
2225 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2229 /* If a run is still in progress at the end, finish it now
2230 by recording its equivalent ranges. */
2231 if (run_type
== one_case
)
2233 EXTEND_RANGE_TABLE (work_area
, 2);
2234 work_area
->table
[work_area
->used
++] = run_start
;
2235 work_area
->table
[work_area
->used
++] = run_end
;
2237 else if (run_type
== two_case
)
2239 EXTEND_RANGE_TABLE (work_area
, 4);
2240 work_area
->table
[work_area
->used
++] = run_start
;
2241 work_area
->table
[work_area
->used
++] = run_end
;
2242 work_area
->table
[work_area
->used
++]
2243 = RE_TRANSLATE (eqv_table
, run_start
);
2244 work_area
->table
[work_area
->used
++]
2245 = RE_TRANSLATE (eqv_table
, run_end
);
2253 /* Record the image of the range start..end when passed through
2254 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2255 and is not even necessarily contiguous.
2256 Normally we approximate it with the smallest contiguous range that contains
2257 all the chars we need. However, for Latin-1 we go to extra effort
2260 This function is not called for ASCII ranges.
2262 Returns -1 if successful, REG_ESPACE if ran out of space. */
2265 set_image_of_range (struct range_table_work_area
*work_area
,
2266 re_wchar_t start
, re_wchar_t end
,
2267 RE_TRANSLATE_TYPE translate
)
2269 re_wchar_t cmin
, cmax
;
2272 /* For Latin-1 ranges, use set_image_of_range_1
2273 to get proper handling of ranges that include letters and nonletters.
2274 For a range that includes the whole of Latin-1, this is not necessary.
2275 For other character sets, we don't bother to get this right. */
2276 if (RE_TRANSLATE_P (translate
) && start
< 04400
2277 && !(start
< 04200 && end
>= 04377))
2284 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2294 EXTEND_RANGE_TABLE (work_area
, 2);
2295 work_area
->table
[work_area
->used
++] = (start
);
2296 work_area
->table
[work_area
->used
++] = (end
);
2298 cmin
= -1, cmax
= -1;
2300 if (RE_TRANSLATE_P (translate
))
2304 for (ch
= start
; ch
<= end
; ch
++)
2306 re_wchar_t c
= TRANSLATE (ch
);
2307 if (! (start
<= c
&& c
<= end
))
2313 cmin
= min (cmin
, c
);
2314 cmax
= max (cmax
, c
);
2321 EXTEND_RANGE_TABLE (work_area
, 2);
2322 work_area
->table
[work_area
->used
++] = (cmin
);
2323 work_area
->table
[work_area
->used
++] = (cmax
);
2331 #ifndef MATCH_MAY_ALLOCATE
2333 /* If we cannot allocate large objects within re_match_2_internal,
2334 we make the fail stack and register vectors global.
2335 The fail stack, we grow to the maximum size when a regexp
2337 The register vectors, we adjust in size each time we
2338 compile a regexp, according to the number of registers it needs. */
2340 static fail_stack_type fail_stack
;
2342 /* Size with which the following vectors are currently allocated.
2343 That is so we can make them bigger as needed,
2344 but never make them smaller. */
2345 static int regs_allocated_size
;
2347 static re_char
** regstart
, ** regend
;
2348 static re_char
**best_regstart
, **best_regend
;
2350 /* Make the register vectors big enough for NUM_REGS registers,
2351 but don't make them smaller. */
2354 regex_grow_registers (int num_regs
)
2356 if (num_regs
> regs_allocated_size
)
2358 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2359 RETALLOC_IF (regend
, num_regs
, re_char
*);
2360 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2361 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2363 regs_allocated_size
= num_regs
;
2367 #endif /* not MATCH_MAY_ALLOCATE */
2369 static boolean
group_in_compile_stack (compile_stack_type compile_stack
,
2372 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2373 Returns one of error codes defined in `regex.h', or zero for success.
2375 If WHITESPACE_REGEXP is given (only #ifdef emacs), it is used instead of
2376 a space character in PATTERN.
2378 Assumes the `allocated' (and perhaps `buffer') and `translate'
2379 fields are set in BUFP on entry.
2381 If it succeeds, results are put in BUFP (if it returns an error, the
2382 contents of BUFP are undefined):
2383 `buffer' is the compiled pattern;
2384 `syntax' is set to SYNTAX;
2385 `used' is set to the length of the compiled pattern;
2386 `fastmap_accurate' is zero;
2387 `re_nsub' is the number of subexpressions in PATTERN;
2388 `not_bol' and `not_eol' are zero;
2390 The `fastmap' field is neither examined nor set. */
2392 /* Insert the `jump' from the end of last alternative to "here".
2393 The space for the jump has already been allocated. */
2394 #define FIXUP_ALT_JUMP() \
2396 if (fixup_alt_jump) \
2397 STORE_JUMP (jump, fixup_alt_jump, b); \
2401 /* Return, freeing storage we allocated. */
2402 #define FREE_STACK_RETURN(value) \
2404 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2405 free (compile_stack.stack); \
2409 static reg_errcode_t
2410 regex_compile (const_re_char
*pattern
, size_t size
,
2412 # define syntax RE_SYNTAX_EMACS
2413 bool posix_backtracking
,
2414 const char *whitespace_regexp
,
2416 reg_syntax_t syntax
,
2417 # define posix_backtracking (!(syntax & RE_NO_POSIX_BACKTRACKING))
2419 struct re_pattern_buffer
*bufp
)
2421 /* We fetch characters from PATTERN here. */
2422 register re_wchar_t c
, c1
;
2424 /* Points to the end of the buffer, where we should append. */
2425 register unsigned char *b
;
2427 /* Keeps track of unclosed groups. */
2428 compile_stack_type compile_stack
;
2430 /* Points to the current (ending) position in the pattern. */
2432 /* `const' makes AIX compiler fail. */
2433 unsigned char *p
= pattern
;
2435 re_char
*p
= pattern
;
2437 re_char
*pend
= pattern
+ size
;
2439 /* How to translate the characters in the pattern. */
2440 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2442 /* Address of the count-byte of the most recently inserted `exactn'
2443 command. This makes it possible to tell if a new exact-match
2444 character can be added to that command or if the character requires
2445 a new `exactn' command. */
2446 unsigned char *pending_exact
= 0;
2448 /* Address of start of the most recently finished expression.
2449 This tells, e.g., postfix * where to find the start of its
2450 operand. Reset at the beginning of groups and alternatives. */
2451 unsigned char *laststart
= 0;
2453 /* Address of beginning of regexp, or inside of last group. */
2454 unsigned char *begalt
;
2456 /* Place in the uncompiled pattern (i.e., the {) to
2457 which to go back if the interval is invalid. */
2458 re_char
*beg_interval
;
2460 /* Address of the place where a forward jump should go to the end of
2461 the containing expression. Each alternative of an `or' -- except the
2462 last -- ends with a forward jump of this sort. */
2463 unsigned char *fixup_alt_jump
= 0;
2465 /* Work area for range table of charset. */
2466 struct range_table_work_area range_table_work
;
2468 /* If the object matched can contain multibyte characters. */
2469 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2472 /* Nonzero if we have pushed down into a subpattern. */
2473 int in_subpattern
= 0;
2475 /* These hold the values of p, pattern, and pend from the main
2476 pattern when we have pushed into a subpattern. */
2478 re_char
*main_pattern
;
2484 DEBUG_PRINT ("\nCompiling pattern: ");
2487 unsigned debug_count
;
2489 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2490 putchar (pattern
[debug_count
]);
2495 /* Initialize the compile stack. */
2496 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2497 if (compile_stack
.stack
== NULL
)
2500 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2501 compile_stack
.avail
= 0;
2503 range_table_work
.table
= 0;
2504 range_table_work
.allocated
= 0;
2506 /* Initialize the pattern buffer. */
2508 bufp
->syntax
= syntax
;
2510 bufp
->fastmap_accurate
= 0;
2511 bufp
->not_bol
= bufp
->not_eol
= 0;
2512 bufp
->used_syntax
= 0;
2514 /* Set `used' to zero, so that if we return an error, the pattern
2515 printer (for debugging) will think there's no pattern. We reset it
2519 /* Always count groups, whether or not bufp->no_sub is set. */
2522 #if !defined emacs && !defined SYNTAX_TABLE
2523 /* Initialize the syntax table. */
2524 init_syntax_once ();
2527 if (bufp
->allocated
== 0)
2530 { /* If zero allocated, but buffer is non-null, try to realloc
2531 enough space. This loses if buffer's address is bogus, but
2532 that is the user's responsibility. */
2533 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2536 { /* Caller did not allocate a buffer. Do it for them. */
2537 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2539 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2541 bufp
->allocated
= INIT_BUF_SIZE
;
2544 begalt
= b
= bufp
->buffer
;
2546 /* Loop through the uncompiled pattern until we're at the end. */
2552 /* If this is the end of an included regexp,
2553 pop back to the main regexp and try again. */
2557 pattern
= main_pattern
;
2563 /* If this is the end of the main regexp, we are done. */
2576 /* If there's no special whitespace regexp, treat
2577 spaces normally. And don't try to do this recursively. */
2578 if (!whitespace_regexp
|| in_subpattern
)
2581 /* Peek past following spaces. */
2588 /* If the spaces are followed by a repetition op,
2589 treat them normally. */
2591 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2592 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2595 /* Replace the spaces with the whitespace regexp. */
2599 main_pattern
= pattern
;
2600 p
= pattern
= (re_char
*) whitespace_regexp
;
2601 pend
= p
+ strlen (whitespace_regexp
);
2608 if ( /* If at start of pattern, it's an operator. */
2610 /* If context independent, it's an operator. */
2611 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2612 /* Otherwise, depends on what's come before. */
2613 || at_begline_loc_p (pattern
, p
, syntax
))
2614 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2623 if ( /* If at end of pattern, it's an operator. */
2625 /* If context independent, it's an operator. */
2626 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2627 /* Otherwise, depends on what's next. */
2628 || at_endline_loc_p (p
, pend
, syntax
))
2629 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2638 if ((syntax
& RE_BK_PLUS_QM
)
2639 || (syntax
& RE_LIMITED_OPS
))
2643 /* If there is no previous pattern... */
2646 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2647 FREE_STACK_RETURN (REG_BADRPT
);
2648 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2653 /* 1 means zero (many) matches is allowed. */
2654 boolean zero_times_ok
= 0, many_times_ok
= 0;
2657 /* If there is a sequence of repetition chars, collapse it
2658 down to just one (the right one). We can't combine
2659 interval operators with these because of, e.g., `a{2}*',
2660 which should only match an even number of `a's. */
2664 if ((syntax
& RE_FRUGAL
)
2665 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2669 zero_times_ok
|= c
!= '+';
2670 many_times_ok
|= c
!= '?';
2676 || (!(syntax
& RE_BK_PLUS_QM
)
2677 && (*p
== '+' || *p
== '?')))
2679 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2682 FREE_STACK_RETURN (REG_EESCAPE
);
2683 if (p
[1] == '+' || p
[1] == '?')
2684 PATFETCH (c
); /* Gobble up the backslash. */
2690 /* If we get here, we found another repeat character. */
2694 /* Star, etc. applied to an empty pattern is equivalent
2695 to an empty pattern. */
2696 if (!laststart
|| laststart
== b
)
2699 /* Now we know whether or not zero matches is allowed
2700 and also whether or not two or more matches is allowed. */
2705 boolean simple
= skip_one_char (laststart
) == b
;
2706 size_t startoffset
= 0;
2708 /* Check if the loop can match the empty string. */
2709 (simple
|| !analyze_first (laststart
, b
, NULL
, 0))
2710 ? on_failure_jump
: on_failure_jump_loop
;
2711 assert (skip_one_char (laststart
) <= b
);
2713 if (!zero_times_ok
&& simple
)
2714 { /* Since simple * loops can be made faster by using
2715 on_failure_keep_string_jump, we turn simple P+
2716 into PP* if P is simple. */
2717 unsigned char *p1
, *p2
;
2718 startoffset
= b
- laststart
;
2719 GET_BUFFER_SPACE (startoffset
);
2720 p1
= b
; p2
= laststart
;
2726 GET_BUFFER_SPACE (6);
2729 STORE_JUMP (ofj
, b
, b
+ 6);
2731 /* Simple * loops can use on_failure_keep_string_jump
2732 depending on what follows. But since we don't know
2733 that yet, we leave the decision up to
2734 on_failure_jump_smart. */
2735 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2736 laststart
+ startoffset
, b
+ 6);
2738 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2743 /* A simple ? pattern. */
2744 assert (zero_times_ok
);
2745 GET_BUFFER_SPACE (3);
2746 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2750 else /* not greedy */
2751 { /* I wish the greedy and non-greedy cases could be merged. */
2753 GET_BUFFER_SPACE (7); /* We might use less. */
2756 boolean emptyp
= analyze_first (laststart
, b
, NULL
, 0);
2758 /* The non-greedy multiple match looks like
2759 a repeat..until: we only need a conditional jump
2760 at the end of the loop. */
2761 if (emptyp
) BUF_PUSH (no_op
);
2762 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2763 : on_failure_jump
, b
, laststart
);
2767 /* The repeat...until naturally matches one or more.
2768 To also match zero times, we need to first jump to
2769 the end of the loop (its conditional jump). */
2770 INSERT_JUMP (jump
, laststart
, b
);
2776 /* non-greedy a?? */
2777 INSERT_JUMP (jump
, laststart
, b
+ 3);
2779 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2798 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2800 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2802 /* Ensure that we have enough space to push a charset: the
2803 opcode, the length count, and the bitset; 34 bytes in all. */
2804 GET_BUFFER_SPACE (34);
2808 /* We test `*p == '^' twice, instead of using an if
2809 statement, so we only need one BUF_PUSH. */
2810 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2814 /* Remember the first position in the bracket expression. */
2817 /* Push the number of bytes in the bitmap. */
2818 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2820 /* Clear the whole map. */
2821 memset (b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2823 /* charset_not matches newline according to a syntax bit. */
2824 if ((re_opcode_t
) b
[-2] == charset_not
2825 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2826 SET_LIST_BIT ('\n');
2828 /* Read in characters and ranges, setting map bits. */
2831 boolean escaped_char
= false;
2832 const unsigned char *p2
= p
;
2836 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2838 /* See if we're at the beginning of a possible character
2840 if (syntax
& RE_CHAR_CLASSES
&&
2841 (cc
= re_wctype_parse(&p
, pend
- p
)) != -1)
2844 FREE_STACK_RETURN (REG_ECTYPE
);
2847 FREE_STACK_RETURN (REG_EBRACK
);
2850 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
2851 if (re_iswctype (btowc (ch
), cc
))
2854 if (c
< (1 << BYTEWIDTH
))
2858 /* Most character classes in a multibyte match just set
2859 a flag. Exceptions are is_blank, is_digit, is_cntrl, and
2860 is_xdigit, since they can only match ASCII characters.
2861 We don't need to handle them for multibyte. */
2863 /* Setup the gl_state object to its buffer-defined value.
2864 This hardcodes the buffer-global syntax-table for ASCII
2865 chars, while the other chars will obey syntax-table
2866 properties. It's not ideal, but it's the way it's been
2868 SETUP_BUFFER_SYNTAX_TABLE ();
2870 for (c
= 0; c
< 0x80; ++c
)
2871 if (re_iswctype (c
, cc
))
2877 if (ASCII_CHAR_P (c1
))
2879 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
2882 SET_RANGE_TABLE_WORK_AREA_BIT
2883 (range_table_work
, re_wctype_to_bit (cc
));
2885 /* In most cases the matching rule for char classes only
2886 uses the syntax table for multibyte chars, so that the
2887 content of the syntax-table is not hardcoded in the
2888 range_table. SPACE and WORD are the two exceptions. */
2889 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
2890 bufp
->used_syntax
= 1;
2892 /* Repeat the loop. */
2896 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2897 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2898 So the translation is done later in a loop. Example:
2899 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2902 /* \ might escape characters inside [...] and [^...]. */
2903 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2905 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2908 escaped_char
= true;
2912 /* Could be the end of the bracket expression. If it's
2913 not (i.e., when the bracket expression is `[]' so
2914 far), the ']' character bit gets set way below. */
2915 if (c
== ']' && p2
!= p1
)
2919 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2922 /* Discard the `-'. */
2925 /* Fetch the character which ends the range. */
2928 if (CHAR_BYTE8_P (c1
)
2929 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
2930 /* Treat the range from a multibyte character to
2931 raw-byte character as empty. */
2936 /* Range from C to C. */
2941 if (syntax
& RE_NO_EMPTY_RANGES
)
2942 FREE_STACK_RETURN (REG_ERANGEX
);
2943 /* Else, repeat the loop. */
2948 /* Set the range into bitmap */
2949 for (; c
<= c1
; c
++)
2952 if (ch
< (1 << BYTEWIDTH
))
2959 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
2961 if (CHAR_BYTE8_P (c1
))
2962 c
= BYTE8_TO_CHAR (128);
2966 if (CHAR_BYTE8_P (c
))
2968 c
= CHAR_TO_BYTE8 (c
);
2969 c1
= CHAR_TO_BYTE8 (c1
);
2970 for (; c
<= c1
; c
++)
2975 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
2979 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
2986 /* Discard any (non)matching list bytes that are all 0 at the
2987 end of the map. Decrease the map-length byte too. */
2988 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2992 /* Build real range table from work area. */
2993 if (RANGE_TABLE_WORK_USED (range_table_work
)
2994 || RANGE_TABLE_WORK_BITS (range_table_work
))
2997 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
2999 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3000 bytes for flags, two for COUNT, and three bytes for
3002 GET_BUFFER_SPACE (4 + used
* 3);
3004 /* Indicate the existence of range table. */
3005 laststart
[1] |= 0x80;
3007 /* Store the character class flag bits into the range table.
3008 If not in emacs, these flag bits are always 0. */
3009 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3010 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3012 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3013 for (i
= 0; i
< used
; i
++)
3014 STORE_CHARACTER_AND_INCR
3015 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3022 if (syntax
& RE_NO_BK_PARENS
)
3029 if (syntax
& RE_NO_BK_PARENS
)
3036 if (syntax
& RE_NEWLINE_ALT
)
3043 if (syntax
& RE_NO_BK_VBAR
)
3050 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3051 goto handle_interval
;
3057 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3059 /* Do not translate the character after the \, so that we can
3060 distinguish, e.g., \B from \b, even if we normally would
3061 translate, e.g., B to b. */
3067 if (syntax
& RE_NO_BK_PARENS
)
3068 goto normal_backslash
;
3073 regnum_t regnum
= 0;
3076 /* Look for a special (?...) construct */
3077 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3079 PATFETCH (c
); /* Gobble up the '?'. */
3085 case ':': shy
= 1; break;
3087 /* An explicitly specified regnum must start
3090 FREE_STACK_RETURN (REG_BADPAT
);
3091 case '1': case '2': case '3': case '4':
3092 case '5': case '6': case '7': case '8': case '9':
3093 regnum
= 10*regnum
+ (c
- '0'); break;
3095 /* Only (?:...) is supported right now. */
3096 FREE_STACK_RETURN (REG_BADPAT
);
3103 regnum
= ++bufp
->re_nsub
;
3105 { /* It's actually not shy, but explicitly numbered. */
3107 if (regnum
> bufp
->re_nsub
)
3108 bufp
->re_nsub
= regnum
;
3109 else if (regnum
> bufp
->re_nsub
3110 /* Ideally, we'd want to check that the specified
3111 group can't have matched (i.e. all subgroups
3112 using the same regnum are in other branches of
3113 OR patterns), but we don't currently keep track
3114 of enough info to do that easily. */
3115 || group_in_compile_stack (compile_stack
, regnum
))
3116 FREE_STACK_RETURN (REG_BADPAT
);
3119 /* It's really shy. */
3120 regnum
= - bufp
->re_nsub
;
3122 if (COMPILE_STACK_FULL
)
3124 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3125 compile_stack_elt_t
);
3126 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3128 compile_stack
.size
<<= 1;
3131 /* These are the values to restore when we hit end of this
3132 group. They are all relative offsets, so that if the
3133 whole pattern moves because of realloc, they will still
3135 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3136 COMPILE_STACK_TOP
.fixup_alt_jump
3137 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3138 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3139 COMPILE_STACK_TOP
.regnum
= regnum
;
3141 /* Do not push a start_memory for groups beyond the last one
3142 we can represent in the compiled pattern. */
3143 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3144 BUF_PUSH_2 (start_memory
, regnum
);
3146 compile_stack
.avail
++;
3151 /* If we've reached MAX_REGNUM groups, then this open
3152 won't actually generate any code, so we'll have to
3153 clear pending_exact explicitly. */
3159 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3161 if (COMPILE_STACK_EMPTY
)
3163 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3164 goto normal_backslash
;
3166 FREE_STACK_RETURN (REG_ERPAREN
);
3172 /* See similar code for backslashed left paren above. */
3173 if (COMPILE_STACK_EMPTY
)
3175 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3178 FREE_STACK_RETURN (REG_ERPAREN
);
3181 /* Since we just checked for an empty stack above, this
3182 ``can't happen''. */
3183 assert (compile_stack
.avail
!= 0);
3185 /* We don't just want to restore into `regnum', because
3186 later groups should continue to be numbered higher,
3187 as in `(ab)c(de)' -- the second group is #2. */
3190 compile_stack
.avail
--;
3191 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3193 = COMPILE_STACK_TOP
.fixup_alt_jump
3194 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3196 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3197 regnum
= COMPILE_STACK_TOP
.regnum
;
3198 /* If we've reached MAX_REGNUM groups, then this open
3199 won't actually generate any code, so we'll have to
3200 clear pending_exact explicitly. */
3203 /* We're at the end of the group, so now we know how many
3204 groups were inside this one. */
3205 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3206 BUF_PUSH_2 (stop_memory
, regnum
);
3211 case '|': /* `\|'. */
3212 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3213 goto normal_backslash
;
3215 if (syntax
& RE_LIMITED_OPS
)
3218 /* Insert before the previous alternative a jump which
3219 jumps to this alternative if the former fails. */
3220 GET_BUFFER_SPACE (3);
3221 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3225 /* The alternative before this one has a jump after it
3226 which gets executed if it gets matched. Adjust that
3227 jump so it will jump to this alternative's analogous
3228 jump (put in below, which in turn will jump to the next
3229 (if any) alternative's such jump, etc.). The last such
3230 jump jumps to the correct final destination. A picture:
3236 If we are at `b', then fixup_alt_jump right now points to a
3237 three-byte space after `a'. We'll put in the jump, set
3238 fixup_alt_jump to right after `b', and leave behind three
3239 bytes which we'll fill in when we get to after `c'. */
3243 /* Mark and leave space for a jump after this alternative,
3244 to be filled in later either by next alternative or
3245 when know we're at the end of a series of alternatives. */
3247 GET_BUFFER_SPACE (3);
3256 /* If \{ is a literal. */
3257 if (!(syntax
& RE_INTERVALS
)
3258 /* If we're at `\{' and it's not the open-interval
3260 || (syntax
& RE_NO_BK_BRACES
))
3261 goto normal_backslash
;
3265 /* If got here, then the syntax allows intervals. */
3267 /* At least (most) this many matches must be made. */
3268 int lower_bound
= 0, upper_bound
= -1;
3272 GET_INTERVAL_COUNT (lower_bound
);
3275 GET_INTERVAL_COUNT (upper_bound
);
3277 /* Interval such as `{1}' => match exactly once. */
3278 upper_bound
= lower_bound
;
3281 || (0 <= upper_bound
&& upper_bound
< lower_bound
))
3282 FREE_STACK_RETURN (REG_BADBR
);
3284 if (!(syntax
& RE_NO_BK_BRACES
))
3287 FREE_STACK_RETURN (REG_BADBR
);
3289 FREE_STACK_RETURN (REG_EESCAPE
);
3294 FREE_STACK_RETURN (REG_BADBR
);
3296 /* We just parsed a valid interval. */
3298 /* If it's invalid to have no preceding re. */
3301 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3302 FREE_STACK_RETURN (REG_BADRPT
);
3303 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3306 goto unfetch_interval
;
3309 if (upper_bound
== 0)
3310 /* If the upper bound is zero, just drop the sub pattern
3313 else if (lower_bound
== 1 && upper_bound
== 1)
3314 /* Just match it once: nothing to do here. */
3317 /* Otherwise, we have a nontrivial interval. When
3318 we're all done, the pattern will look like:
3319 set_number_at <jump count> <upper bound>
3320 set_number_at <succeed_n count> <lower bound>
3321 succeed_n <after jump addr> <succeed_n count>
3323 jump_n <succeed_n addr> <jump count>
3324 (The upper bound and `jump_n' are omitted if
3325 `upper_bound' is 1, though.) */
3327 { /* If the upper bound is > 1, we need to insert
3328 more at the end of the loop. */
3329 unsigned int nbytes
= (upper_bound
< 0 ? 3
3330 : upper_bound
> 1 ? 5 : 0);
3331 unsigned int startoffset
= 0;
3333 GET_BUFFER_SPACE (20); /* We might use less. */
3335 if (lower_bound
== 0)
3337 /* A succeed_n that starts with 0 is really a
3338 a simple on_failure_jump_loop. */
3339 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3345 /* Initialize lower bound of the `succeed_n', even
3346 though it will be set during matching by its
3347 attendant `set_number_at' (inserted next),
3348 because `re_compile_fastmap' needs to know.
3349 Jump to the `jump_n' we might insert below. */
3350 INSERT_JUMP2 (succeed_n
, laststart
,
3355 /* Code to initialize the lower bound. Insert
3356 before the `succeed_n'. The `5' is the last two
3357 bytes of this `set_number_at', plus 3 bytes of
3358 the following `succeed_n'. */
3359 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3364 if (upper_bound
< 0)
3366 /* A negative upper bound stands for infinity,
3367 in which case it degenerates to a plain jump. */
3368 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3371 else if (upper_bound
> 1)
3372 { /* More than one repetition is allowed, so
3373 append a backward jump to the `succeed_n'
3374 that starts this interval.
3376 When we've reached this during matching,
3377 we'll have matched the interval once, so
3378 jump back only `upper_bound - 1' times. */
3379 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3383 /* The location we want to set is the second
3384 parameter of the `jump_n'; that is `b-2' as
3385 an absolute address. `laststart' will be
3386 the `set_number_at' we're about to insert;
3387 `laststart+3' the number to set, the source
3388 for the relative address. But we are
3389 inserting into the middle of the pattern --
3390 so everything is getting moved up by 5.
3391 Conclusion: (b - 2) - (laststart + 3) + 5,
3392 i.e., b - laststart.
3394 We insert this at the beginning of the loop
3395 so that if we fail during matching, we'll
3396 reinitialize the bounds. */
3397 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3398 upper_bound
- 1, b
);
3403 beg_interval
= NULL
;
3408 /* If an invalid interval, match the characters as literals. */
3409 assert (beg_interval
);
3411 beg_interval
= NULL
;
3413 /* normal_char and normal_backslash need `c'. */
3416 if (!(syntax
& RE_NO_BK_BRACES
))
3418 assert (p
> pattern
&& p
[-1] == '\\');
3419 goto normal_backslash
;
3433 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3439 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3445 BUF_PUSH_2 (categoryspec
, c
);
3451 BUF_PUSH_2 (notcategoryspec
, c
);
3457 if (syntax
& RE_NO_GNU_OPS
)
3460 BUF_PUSH_2 (syntaxspec
, Sword
);
3465 if (syntax
& RE_NO_GNU_OPS
)
3468 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3473 if (syntax
& RE_NO_GNU_OPS
)
3480 if (syntax
& RE_NO_GNU_OPS
)
3487 if (syntax
& RE_NO_GNU_OPS
)
3496 FREE_STACK_RETURN (REG_BADPAT
);
3500 if (syntax
& RE_NO_GNU_OPS
)
3502 BUF_PUSH (wordbound
);
3506 if (syntax
& RE_NO_GNU_OPS
)
3508 BUF_PUSH (notwordbound
);
3512 if (syntax
& RE_NO_GNU_OPS
)
3518 if (syntax
& RE_NO_GNU_OPS
)
3523 case '1': case '2': case '3': case '4': case '5':
3524 case '6': case '7': case '8': case '9':
3528 if (syntax
& RE_NO_BK_REFS
)
3529 goto normal_backslash
;
3533 if (reg
> bufp
->re_nsub
|| reg
< 1
3534 /* Can't back reference to a subexp before its end. */
3535 || group_in_compile_stack (compile_stack
, reg
))
3536 FREE_STACK_RETURN (REG_ESUBREG
);
3539 BUF_PUSH_2 (duplicate
, reg
);
3546 if (syntax
& RE_BK_PLUS_QM
)
3549 goto normal_backslash
;
3553 /* You might think it would be useful for \ to mean
3554 not to translate; but if we don't translate it
3555 it will never match anything. */
3562 /* Expects the character in `c'. */
3564 /* If no exactn currently being built. */
3567 /* If last exactn not at current position. */
3568 || pending_exact
+ *pending_exact
+ 1 != b
3570 /* We have only one byte following the exactn for the count. */
3571 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3573 /* If followed by a repetition operator. */
3574 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3575 || ((syntax
& RE_BK_PLUS_QM
)
3576 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3577 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3578 || ((syntax
& RE_INTERVALS
)
3579 && ((syntax
& RE_NO_BK_BRACES
)
3580 ? p
!= pend
&& *p
== '{'
3581 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3583 /* Start building a new exactn. */
3587 BUF_PUSH_2 (exactn
, 0);
3588 pending_exact
= b
- 1;
3591 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3598 len
= CHAR_STRING (c
, b
);
3603 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3604 if (! CHAR_BYTE8_P (c1
))
3606 re_wchar_t c2
= TRANSLATE (c1
);
3608 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3614 (*pending_exact
) += len
;
3619 } /* while p != pend */
3622 /* Through the pattern now. */
3626 if (!COMPILE_STACK_EMPTY
)
3627 FREE_STACK_RETURN (REG_EPAREN
);
3629 /* If we don't want backtracking, force success
3630 the first time we reach the end of the compiled pattern. */
3631 if (!posix_backtracking
)
3634 /* We have succeeded; set the length of the buffer. */
3635 bufp
->used
= b
- bufp
->buffer
;
3640 re_compile_fastmap (bufp
);
3641 DEBUG_PRINT ("\nCompiled pattern: \n");
3642 print_compiled_pattern (bufp
);
3647 #ifndef MATCH_MAY_ALLOCATE
3648 /* Initialize the failure stack to the largest possible stack. This
3649 isn't necessary unless we're trying to avoid calling alloca in
3650 the search and match routines. */
3652 int num_regs
= bufp
->re_nsub
+ 1;
3654 if (fail_stack
.size
< emacs_re_max_failures
* TYPICAL_FAILURE_SIZE
)
3656 fail_stack
.size
= emacs_re_max_failures
* TYPICAL_FAILURE_SIZE
;
3657 falk_stack
.stack
= realloc (fail_stack
.stack
,
3658 fail_stack
.size
* sizeof *falk_stack
.stack
);
3661 regex_grow_registers (num_regs
);
3663 #endif /* not MATCH_MAY_ALLOCATE */
3665 FREE_STACK_RETURN (REG_NOERROR
);
3670 # undef posix_backtracking
3672 } /* regex_compile */
3674 /* Subroutines for `regex_compile'. */
3676 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3679 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3681 *loc
= (unsigned char) op
;
3682 STORE_NUMBER (loc
+ 1, arg
);
3686 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3689 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3691 *loc
= (unsigned char) op
;
3692 STORE_NUMBER (loc
+ 1, arg1
);
3693 STORE_NUMBER (loc
+ 3, arg2
);
3697 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3698 for OP followed by two-byte integer parameter ARG. */
3701 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3703 register unsigned char *pfrom
= end
;
3704 register unsigned char *pto
= end
+ 3;
3706 while (pfrom
!= loc
)
3709 store_op1 (op
, loc
, arg
);
3713 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3716 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3718 register unsigned char *pfrom
= end
;
3719 register unsigned char *pto
= end
+ 5;
3721 while (pfrom
!= loc
)
3724 store_op2 (op
, loc
, arg1
, arg2
);
3728 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3729 after an alternative or a begin-subexpression. We assume there is at
3730 least one character before the ^. */
3733 at_begline_loc_p (const_re_char
*pattern
, const_re_char
*p
, reg_syntax_t syntax
)
3735 re_char
*prev
= p
- 2;
3736 boolean odd_backslashes
;
3738 /* After a subexpression? */
3740 odd_backslashes
= (syntax
& RE_NO_BK_PARENS
) == 0;
3742 /* After an alternative? */
3743 else if (*prev
== '|')
3744 odd_backslashes
= (syntax
& RE_NO_BK_VBAR
) == 0;
3746 /* After a shy subexpression? */
3747 else if (*prev
== ':' && (syntax
& RE_SHY_GROUPS
))
3749 /* Skip over optional regnum. */
3750 while (prev
- 1 >= pattern
&& prev
[-1] >= '0' && prev
[-1] <= '9')
3753 if (!(prev
- 2 >= pattern
3754 && prev
[-1] == '?' && prev
[-2] == '('))
3757 odd_backslashes
= (syntax
& RE_NO_BK_PARENS
) == 0;
3762 /* Count the number of preceding backslashes. */
3764 while (prev
- 1 >= pattern
&& prev
[-1] == '\\')
3766 return (p
- prev
) & odd_backslashes
;
3770 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3771 at least one character after the $, i.e., `P < PEND'. */
3774 at_endline_loc_p (const_re_char
*p
, const_re_char
*pend
, reg_syntax_t syntax
)
3777 boolean next_backslash
= *next
== '\\';
3778 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3781 /* Before a subexpression? */
3782 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3783 : next_backslash
&& next_next
&& *next_next
== ')')
3784 /* Before an alternative? */
3785 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3786 : next_backslash
&& next_next
&& *next_next
== '|');
3790 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3791 false if it's not. */
3794 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3796 ssize_t this_element
;
3798 for (this_element
= compile_stack
.avail
- 1;
3801 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3808 If fastmap is non-NULL, go through the pattern and fill fastmap
3809 with all the possible leading chars. If fastmap is NULL, don't
3810 bother filling it up (obviously) and only return whether the
3811 pattern could potentially match the empty string.
3813 Return 1 if p..pend might match the empty string.
3814 Return 0 if p..pend matches at least one char.
3815 Return -1 if fastmap was not updated accurately. */
3818 analyze_first (const_re_char
*p
, const_re_char
*pend
, char *fastmap
,
3819 const int multibyte
)
3824 /* If all elements for base leading-codes in fastmap is set, this
3825 flag is set true. */
3826 boolean match_any_multibyte_characters
= false;
3830 /* The loop below works as follows:
3831 - It has a working-list kept in the PATTERN_STACK and which basically
3832 starts by only containing a pointer to the first operation.
3833 - If the opcode we're looking at is a match against some set of
3834 chars, then we add those chars to the fastmap and go on to the
3835 next work element from the worklist (done via `break').
3836 - If the opcode is a control operator on the other hand, we either
3837 ignore it (if it's meaningless at this point, such as `start_memory')
3838 or execute it (if it's a jump). If the jump has several destinations
3839 (i.e. `on_failure_jump'), then we push the other destination onto the
3841 We guarantee termination by ignoring backward jumps (more or less),
3842 so that `p' is monotonically increasing. More to the point, we
3843 never set `p' (or push) anything `<= p1'. */
3847 /* `p1' is used as a marker of how far back a `on_failure_jump'
3848 can go without being ignored. It is normally equal to `p'
3849 (which prevents any backward `on_failure_jump') except right
3850 after a plain `jump', to allow patterns such as:
3853 10: on_failure_jump 3
3854 as used for the *? operator. */
3863 /* If the first character has to match a backreference, that means
3864 that the group was empty (since it already matched). Since this
3865 is the only case that interests us here, we can assume that the
3866 backreference must match the empty string. */
3871 /* Following are the cases which match a character. These end
3877 /* If multibyte is nonzero, the first byte of each
3878 character is an ASCII or a leading code. Otherwise,
3879 each byte is a character. Thus, this works in both
3884 /* For the case of matching this unibyte regex
3885 against multibyte, we must set a leading code of
3886 the corresponding multibyte character. */
3887 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
3889 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
3896 /* We could put all the chars except for \n (and maybe \0)
3897 but we don't bother since it is generally not worth it. */
3898 if (!fastmap
) break;
3903 if (!fastmap
) break;
3905 /* Chars beyond end of bitmap are possible matches. */
3906 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3907 j
< (1 << BYTEWIDTH
); j
++)
3913 if (!fastmap
) break;
3914 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3915 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3917 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3921 if (/* Any leading code can possibly start a character
3922 which doesn't match the specified set of characters. */
3925 /* If we can match a character class, we can match any
3926 multibyte characters. */
3927 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3928 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3931 if (match_any_multibyte_characters
== false)
3933 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
3934 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
3936 match_any_multibyte_characters
= true;
3940 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3941 && match_any_multibyte_characters
== false)
3943 /* Set fastmap[I] to 1 where I is a leading code of each
3944 multibyte character in the range table. */
3946 unsigned char lc1
, lc2
;
3948 /* Make P points the range table. `+ 2' is to skip flag
3949 bits for a character class. */
3950 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3952 /* Extract the number of ranges in range table into COUNT. */
3953 EXTRACT_NUMBER_AND_INCR (count
, p
);
3954 for (; count
> 0; count
--, p
+= 3)
3956 /* Extract the start and end of each range. */
3957 EXTRACT_CHARACTER (c
, p
);
3958 lc1
= CHAR_LEADING_CODE (c
);
3960 EXTRACT_CHARACTER (c
, p
);
3961 lc2
= CHAR_LEADING_CODE (c
);
3962 for (j
= lc1
; j
<= lc2
; j
++)
3971 if (!fastmap
) break;
3973 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3975 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3976 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
3980 /* This match depends on text properties. These end with
3981 aborting optimizations. */
3985 case notcategoryspec
:
3986 if (!fastmap
) break;
3987 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
3989 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
3990 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
3993 /* Any leading code can possibly start a character which
3994 has or doesn't has the specified category. */
3995 if (match_any_multibyte_characters
== false)
3997 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
3998 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4000 match_any_multibyte_characters
= true;
4004 /* All cases after this match the empty string. These end with
4024 EXTRACT_NUMBER_AND_INCR (j
, p
);
4026 /* Backward jumps can only go back to code that we've already
4027 visited. `re_compile' should make sure this is true. */
4032 case on_failure_jump
:
4033 case on_failure_keep_string_jump
:
4034 case on_failure_jump_loop
:
4035 case on_failure_jump_nastyloop
:
4036 case on_failure_jump_smart
:
4042 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4043 to jump back to "just after here". */
4046 case on_failure_jump
:
4047 case on_failure_keep_string_jump
:
4048 case on_failure_jump_nastyloop
:
4049 case on_failure_jump_loop
:
4050 case on_failure_jump_smart
:
4051 EXTRACT_NUMBER_AND_INCR (j
, p
);
4053 ; /* Backward jump to be ignored. */
4055 { /* We have to look down both arms.
4056 We first go down the "straight" path so as to minimize
4057 stack usage when going through alternatives. */
4058 int r
= analyze_first (p
, pend
, fastmap
, multibyte
);
4066 /* This code simply does not properly handle forward jump_n. */
4067 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4069 /* jump_n can either jump or fall through. The (backward) jump
4070 case has already been handled, so we only need to look at the
4071 fallthrough case. */
4075 /* If N == 0, it should be an on_failure_jump_loop instead. */
4076 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4078 /* We only care about one iteration of the loop, so we don't
4079 need to consider the case where this behaves like an
4096 abort (); /* We have listed all the cases. */
4099 /* Getting here means we have found the possible starting
4100 characters for one path of the pattern -- and that the empty
4101 string does not match. We need not follow this path further. */
4105 /* We reached the end without matching anything. */
4108 } /* analyze_first */
4110 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4111 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4112 characters can start a string that matches the pattern. This fastmap
4113 is used by re_search to skip quickly over impossible starting points.
4115 Character codes above (1 << BYTEWIDTH) are not represented in the
4116 fastmap, but the leading codes are represented. Thus, the fastmap
4117 indicates which character sets could start a match.
4119 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4120 area as BUFP->fastmap.
4122 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4125 Returns 0 if we succeed, -2 if an internal error. */
4128 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4130 char *fastmap
= bufp
->fastmap
;
4133 assert (fastmap
&& bufp
->buffer
);
4135 memset (fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4136 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4138 analysis
= analyze_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4139 fastmap
, RE_MULTIBYTE_P (bufp
));
4140 bufp
->can_be_null
= (analysis
!= 0);
4142 } /* re_compile_fastmap */
4144 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4145 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4146 this memory for recording register information. STARTS and ENDS
4147 must be allocated using the malloc library routine, and must each
4148 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4150 If NUM_REGS == 0, then subsequent matches should allocate their own
4153 Unless this function is called, the first search or match using
4154 PATTERN_BUFFER will allocate its own register data, without
4155 freeing the old data. */
4158 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4162 bufp
->regs_allocated
= REGS_REALLOCATE
;
4163 regs
->num_regs
= num_regs
;
4164 regs
->start
= starts
;
4169 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4171 regs
->start
= regs
->end
= 0;
4174 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4176 /* Searching routines. */
4178 /* Like re_search_2, below, but only one string is specified, and
4179 doesn't let you say where to stop matching. */
4182 re_search (struct re_pattern_buffer
*bufp
, const char *string
, size_t size
,
4183 ssize_t startpos
, ssize_t range
, struct re_registers
*regs
)
4185 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4188 WEAK_ALIAS (__re_search
, re_search
)
4190 /* Head address of virtual concatenation of string. */
4191 #define HEAD_ADDR_VSTRING(P) \
4192 (((P) >= size1 ? string2 : string1))
4194 /* Address of POS in the concatenation of virtual string. */
4195 #define POS_ADDR_VSTRING(POS) \
4196 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4198 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4199 virtual concatenation of STRING1 and STRING2, starting first at index
4200 STARTPOS, then at STARTPOS + 1, and so on.
4202 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4204 RANGE is how far to scan while trying to match. RANGE = 0 means try
4205 only at STARTPOS; in general, the last start tried is STARTPOS +
4208 In REGS, return the indices of the virtual concatenation of STRING1
4209 and STRING2 that matched the entire BUFP->buffer and its contained
4212 Do not consider matching one past the index STOP in the virtual
4213 concatenation of STRING1 and STRING2.
4215 We return either the position in the strings at which the match was
4216 found, -1 if no match, or -2 if error (such as failure
4220 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, size_t size1
,
4221 const char *str2
, size_t size2
, ssize_t startpos
, ssize_t range
,
4222 struct re_registers
*regs
, ssize_t stop
)
4225 re_char
*string1
= (re_char
*) str1
;
4226 re_char
*string2
= (re_char
*) str2
;
4227 register char *fastmap
= bufp
->fastmap
;
4228 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4229 size_t total_size
= size1
+ size2
;
4230 ssize_t endpos
= startpos
+ range
;
4231 boolean anchored_start
;
4232 /* Nonzero if we are searching multibyte string. */
4233 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4235 /* Check for out-of-range STARTPOS. */
4236 if (startpos
< 0 || startpos
> total_size
)
4239 /* Fix up RANGE if it might eventually take us outside
4240 the virtual concatenation of STRING1 and STRING2.
4241 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4243 range
= 0 - startpos
;
4244 else if (endpos
> total_size
)
4245 range
= total_size
- startpos
;
4247 /* If the search isn't to be a backwards one, don't waste time in a
4248 search for a pattern anchored at beginning of buffer. */
4249 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4258 /* In a forward search for something that starts with \=.
4259 don't keep searching past point. */
4260 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4262 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4268 /* Update the fastmap now if not correct already. */
4269 if (fastmap
&& !bufp
->fastmap_accurate
)
4270 re_compile_fastmap (bufp
);
4272 /* See whether the pattern is anchored. */
4273 anchored_start
= (bufp
->buffer
[0] == begline
);
4276 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4278 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4280 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4284 /* Loop through the string, looking for a place to start matching. */
4287 /* If the pattern is anchored,
4288 skip quickly past places we cannot match.
4289 We don't bother to treat startpos == 0 specially
4290 because that case doesn't repeat. */
4291 if (anchored_start
&& startpos
> 0)
4293 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4294 : string2
[startpos
- size1
- 1])
4299 /* If a fastmap is supplied, skip quickly over characters that
4300 cannot be the start of a match. If the pattern can match the
4301 null string, however, we don't need to skip characters; we want
4302 the first null string. */
4303 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4305 register re_char
*d
;
4306 register re_wchar_t buf_ch
;
4308 d
= POS_ADDR_VSTRING (startpos
);
4310 if (range
> 0) /* Searching forwards. */
4312 ssize_t irange
= range
, lim
= 0;
4314 if (startpos
< size1
&& startpos
+ range
>= size1
)
4315 lim
= range
- (size1
- startpos
);
4317 /* Written out as an if-else to avoid testing `translate'
4319 if (RE_TRANSLATE_P (translate
))
4326 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4327 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4328 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4331 range
-= buf_charlen
;
4337 register re_wchar_t ch
, translated
;
4340 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4341 translated
= RE_TRANSLATE (translate
, ch
);
4342 if (translated
!= ch
4343 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4345 if (fastmap
[buf_ch
])
4358 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4359 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4361 range
-= buf_charlen
;
4365 while (range
> lim
&& !fastmap
[*d
])
4371 startpos
+= irange
- range
;
4373 else /* Searching backwards. */
4377 buf_ch
= STRING_CHAR (d
);
4378 buf_ch
= TRANSLATE (buf_ch
);
4379 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4384 register re_wchar_t ch
, translated
;
4387 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4388 translated
= TRANSLATE (ch
);
4389 if (translated
!= ch
4390 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4392 if (! fastmap
[TRANSLATE (buf_ch
)])
4398 /* If can't match the null string, and that's all we have left, fail. */
4399 if (range
>= 0 && startpos
== total_size
&& fastmap
4400 && !bufp
->can_be_null
)
4403 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4404 startpos
, regs
, stop
);
4417 /* Update STARTPOS to the next character boundary. */
4420 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4421 int len
= BYTES_BY_CHAR_HEAD (*p
);
4439 /* Update STARTPOS to the previous character boundary. */
4442 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4444 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4446 /* Find the head of multibyte form. */
4447 PREV_CHAR_BOUNDARY (p
, phead
);
4448 range
+= p0
- 1 - p
;
4452 startpos
-= p0
- 1 - p
;
4458 WEAK_ALIAS (__re_search_2
, re_search_2
)
4460 /* Declarations and macros for re_match_2. */
4462 static int bcmp_translate (re_char
*s1
, re_char
*s2
,
4463 register ssize_t len
,
4464 RE_TRANSLATE_TYPE translate
,
4465 const int multibyte
);
4467 /* This converts PTR, a pointer into one of the search strings `string1'
4468 and `string2' into an offset from the beginning of that string. */
4469 #define POINTER_TO_OFFSET(ptr) \
4470 (FIRST_STRING_P (ptr) \
4472 : (ptr) - string2 + (ptrdiff_t) size1)
4474 /* Call before fetching a character with *d. This switches over to
4475 string2 if necessary.
4476 Check re_match_2_internal for a discussion of why end_match_2 might
4477 not be within string2 (but be equal to end_match_1 instead). */
4478 #define PREFETCH() \
4481 /* End of string2 => fail. */ \
4482 if (dend == end_match_2) \
4484 /* End of string1 => advance to string2. */ \
4486 dend = end_match_2; \
4489 /* Call before fetching a char with *d if you already checked other limits.
4490 This is meant for use in lookahead operations like wordend, etc..
4491 where we might need to look at parts of the string that might be
4492 outside of the LIMITs (i.e past `stop'). */
4493 #define PREFETCH_NOLIMIT() \
4497 dend = end_match_2; \
4500 /* Test if at very beginning or at very end of the virtual concatenation
4501 of `string1' and `string2'. If only one string, it's `string2'. */
4502 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4503 #define AT_STRINGS_END(d) ((d) == end2)
4505 /* Disabled due to a compiler bug -- see comment at case wordbound */
4507 /* The comment at case wordbound is following one, but we don't use
4508 AT_WORD_BOUNDARY anymore to support multibyte form.
4510 The DEC Alpha C compiler 3.x generates incorrect code for the
4511 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4512 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4513 macro and introducing temporary variables works around the bug. */
4516 /* Test if D points to a character which is word-constituent. We have
4517 two special cases to check for: if past the end of string1, look at
4518 the first character in string2; and if before the beginning of
4519 string2, look at the last character in string1. */
4520 #define WORDCHAR_P(d) \
4521 (SYNTAX ((d) == end1 ? *string2 \
4522 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4525 /* Test if the character before D and the one at D differ with respect
4526 to being word-constituent. */
4527 #define AT_WORD_BOUNDARY(d) \
4528 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4529 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4532 /* Free everything we malloc. */
4533 #ifdef MATCH_MAY_ALLOCATE
4534 # define FREE_VAR(var) \
4542 # define FREE_VARIABLES() \
4544 REGEX_FREE_STACK (fail_stack.stack); \
4545 FREE_VAR (regstart); \
4546 FREE_VAR (regend); \
4547 FREE_VAR (best_regstart); \
4548 FREE_VAR (best_regend); \
4549 REGEX_SAFE_FREE (); \
4552 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4553 #endif /* not MATCH_MAY_ALLOCATE */
4556 /* Optimization routines. */
4558 /* If the operation is a match against one or more chars,
4559 return a pointer to the next operation, else return NULL. */
4561 skip_one_char (const_re_char
*p
)
4574 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4577 p
= CHARSET_RANGE_TABLE (p
- 1);
4578 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4579 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4582 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4589 case notcategoryspec
:
4601 /* Jump over non-matching operations. */
4603 skip_noops (const_re_char
*p
, const_re_char
*pend
)
4617 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4628 /* Test if C matches charset op. *PP points to the charset or charset_not
4629 opcode. When the function finishes, *PP will be advanced past that opcode.
4630 C is character to test (possibly after translations) and CORIG is original
4631 character (i.e. without any translations). UNIBYTE denotes whether c is
4632 unibyte or multibyte character. */
4634 execute_charset (const_re_char
**pp
, unsigned c
, unsigned corig
, bool unibyte
)
4636 re_char
*p
= *pp
, *rtp
= NULL
;
4637 bool not = (re_opcode_t
) *p
== charset_not
;
4639 if (CHARSET_RANGE_TABLE_EXISTS_P (p
))
4642 rtp
= CHARSET_RANGE_TABLE (p
);
4643 EXTRACT_NUMBER_AND_INCR (count
, rtp
);
4644 *pp
= CHARSET_RANGE_TABLE_END ((rtp
), (count
));
4647 *pp
+= 2 + CHARSET_BITMAP_SIZE (p
);
4649 if (unibyte
&& c
< (1 << BYTEWIDTH
))
4650 { /* Lookup bitmap. */
4651 /* Cast to `unsigned' instead of `unsigned char' in
4652 case the bit list is a full 32 bytes long. */
4653 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (p
) * BYTEWIDTH
)
4654 && p
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4660 int class_bits
= CHARSET_RANGE_TABLE_BITS (p
);
4661 re_wchar_t range_start
, range_end
;
4663 /* Sort tests by the most commonly used classes with some adjustment to which
4664 tests are easiest to perform. Take a look at comment in re_wctype_parse
4665 for table with frequencies of character class names. */
4667 if ((class_bits
& BIT_MULTIBYTE
) ||
4668 (class_bits
& BIT_ALNUM
&& ISALNUM (c
)) ||
4669 (class_bits
& BIT_ALPHA
&& ISALPHA (c
)) ||
4670 (class_bits
& BIT_SPACE
&& ISSPACE (c
)) ||
4671 (class_bits
& BIT_BLANK
&& ISBLANK (c
)) ||
4672 (class_bits
& BIT_WORD
&& ISWORD (c
)) ||
4673 ((class_bits
& BIT_UPPER
) &&
4674 (ISUPPER (c
) || (corig
!= c
&&
4675 c
== downcase (corig
) && ISLOWER (c
)))) ||
4676 ((class_bits
& BIT_LOWER
) &&
4677 (ISLOWER (c
) || (corig
!= c
&&
4678 c
== upcase (corig
) && ISUPPER(c
)))) ||
4679 (class_bits
& BIT_PUNCT
&& ISPUNCT (c
)) ||
4680 (class_bits
& BIT_GRAPH
&& ISGRAPH (c
)) ||
4681 (class_bits
& BIT_PRINT
&& ISPRINT (c
)))
4684 for (p
= *pp
; rtp
< p
; rtp
+= 2 * 3)
4686 EXTRACT_CHARACTER (range_start
, rtp
);
4687 EXTRACT_CHARACTER (range_end
, rtp
+ 3);
4688 if (range_start
<= c
&& c
<= range_end
)
4696 /* Non-zero if "p1 matches something" implies "p2 fails". */
4698 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const_re_char
*p1
,
4702 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4703 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4705 assert (p1
>= bufp
->buffer
&& p1
< pend
4706 && p2
>= bufp
->buffer
&& p2
<= pend
);
4708 /* Skip over open/close-group commands.
4709 If what follows this loop is a ...+ construct,
4710 look at what begins its body, since we will have to
4711 match at least one of that. */
4712 p2
= skip_noops (p2
, pend
);
4713 /* The same skip can be done for p1, except that this function
4714 is only used in the case where p1 is a simple match operator. */
4715 /* p1 = skip_noops (p1, pend); */
4717 assert (p1
>= bufp
->buffer
&& p1
< pend
4718 && p2
>= bufp
->buffer
&& p2
<= pend
);
4720 op2
= p2
== pend
? succeed
: *p2
;
4726 /* If we're at the end of the pattern, we can change. */
4727 if (skip_one_char (p1
))
4729 DEBUG_PRINT (" End of pattern: fast loop.\n");
4737 register re_wchar_t c
4738 = (re_opcode_t
) *p2
== endline
? '\n'
4739 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4741 if ((re_opcode_t
) *p1
== exactn
)
4743 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4745 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4750 else if ((re_opcode_t
) *p1
== charset
4751 || (re_opcode_t
) *p1
== charset_not
)
4753 if (!execute_charset (&p1
, c
, c
, !multibyte
|| IS_REAL_ASCII (c
)))
4755 DEBUG_PRINT (" No match => fast loop.\n");
4759 else if ((re_opcode_t
) *p1
== anychar
4762 DEBUG_PRINT (" . != \\n => fast loop.\n");
4770 if ((re_opcode_t
) *p1
== exactn
)
4771 /* Reuse the code above. */
4772 return mutually_exclusive_p (bufp
, p2
, p1
);
4774 /* It is hard to list up all the character in charset
4775 P2 if it includes multibyte character. Give up in
4777 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4779 /* Now, we are sure that P2 has no range table.
4780 So, for the size of bitmap in P2, `p2[1]' is
4781 enough. But P1 may have range table, so the
4782 size of bitmap table of P1 is extracted by
4783 using macro `CHARSET_BITMAP_SIZE'.
4785 In a multibyte case, we know that all the character
4786 listed in P2 is ASCII. In a unibyte case, P1 has only a
4787 bitmap table. So, in both cases, it is enough to test
4788 only the bitmap table of P1. */
4790 if ((re_opcode_t
) *p1
== charset
)
4793 /* We win if the charset inside the loop
4794 has no overlap with the one after the loop. */
4797 && idx
< CHARSET_BITMAP_SIZE (p1
));
4799 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4803 || idx
== CHARSET_BITMAP_SIZE (p1
))
4805 DEBUG_PRINT (" No match => fast loop.\n");
4809 else if ((re_opcode_t
) *p1
== charset_not
)
4812 /* We win if the charset_not inside the loop lists
4813 every character listed in the charset after. */
4814 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4815 if (! (p2
[2 + idx
] == 0
4816 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4817 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4822 DEBUG_PRINT (" No match => fast loop.\n");
4835 /* Reuse the code above. */
4836 return mutually_exclusive_p (bufp
, p2
, p1
);
4838 /* When we have two charset_not, it's very unlikely that
4839 they don't overlap. The union of the two sets of excluded
4840 chars should cover all possible chars, which, as a matter of
4841 fact, is virtually impossible in multibyte buffers. */
4847 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4849 return ((re_opcode_t
) *p1
== syntaxspec
4850 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4852 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4855 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4857 return ((re_opcode_t
) *p1
== notsyntaxspec
4858 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4860 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4863 return (((re_opcode_t
) *p1
== notsyntaxspec
4864 || (re_opcode_t
) *p1
== syntaxspec
)
4869 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4870 case notcategoryspec
:
4871 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4883 /* Matching routines. */
4885 #ifndef emacs /* Emacs never uses this. */
4886 /* re_match is like re_match_2 except it takes only a single string. */
4889 re_match (struct re_pattern_buffer
*bufp
, const char *string
,
4890 size_t size
, ssize_t pos
, struct re_registers
*regs
)
4892 regoff_t result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
,
4893 size
, pos
, regs
, size
);
4896 WEAK_ALIAS (__re_match
, re_match
)
4897 #endif /* not emacs */
4899 /* re_match_2 matches the compiled pattern in BUFP against the
4900 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4901 and SIZE2, respectively). We start matching at POS, and stop
4904 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4905 store offsets for the substring each group matched in REGS. See the
4906 documentation for exactly how many groups we fill.
4908 We return -1 if no match, -2 if an internal error (such as the
4909 failure stack overflowing). Otherwise, we return the length of the
4910 matched substring. */
4913 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
,
4914 size_t size1
, const char *string2
, size_t size2
, ssize_t pos
,
4915 struct re_registers
*regs
, ssize_t stop
)
4921 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4922 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4923 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4926 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4927 (re_char
*) string2
, size2
,
4931 WEAK_ALIAS (__re_match_2
, re_match_2
)
4934 /* This is a separate function so that we can force an alloca cleanup
4937 re_match_2_internal (struct re_pattern_buffer
*bufp
, const_re_char
*string1
,
4938 size_t size1
, const_re_char
*string2
, size_t size2
,
4939 ssize_t pos
, struct re_registers
*regs
, ssize_t stop
)
4941 /* General temporaries. */
4945 /* Just past the end of the corresponding string. */
4946 re_char
*end1
, *end2
;
4948 /* Pointers into string1 and string2, just past the last characters in
4949 each to consider matching. */
4950 re_char
*end_match_1
, *end_match_2
;
4952 /* Where we are in the data, and the end of the current string. */
4955 /* Used sometimes to remember where we were before starting matching
4956 an operator so that we can go back in case of failure. This "atomic"
4957 behavior of matching opcodes is indispensable to the correctness
4958 of the on_failure_keep_string_jump optimization. */
4961 /* Where we are in the pattern, and the end of the pattern. */
4962 re_char
*p
= bufp
->buffer
;
4963 re_char
*pend
= p
+ bufp
->used
;
4965 /* We use this to map every character in the string. */
4966 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4968 /* Nonzero if BUFP is setup from a multibyte regex. */
4969 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4971 /* Nonzero if STRING1/STRING2 are multibyte. */
4972 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4974 /* Failure point stack. Each place that can handle a failure further
4975 down the line pushes a failure point on this stack. It consists of
4976 regstart, and regend for all registers corresponding to
4977 the subexpressions we're currently inside, plus the number of such
4978 registers, and, finally, two char *'s. The first char * is where
4979 to resume scanning the pattern; the second one is where to resume
4980 scanning the strings. */
4981 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4982 fail_stack_type fail_stack
;
4984 #ifdef DEBUG_COMPILES_ARGUMENTS
4985 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4988 #if defined REL_ALLOC && defined REGEX_MALLOC
4989 /* This holds the pointer to the failure stack, when
4990 it is allocated relocatably. */
4991 fail_stack_elt_t
*failure_stack_ptr
;
4994 /* We fill all the registers internally, independent of what we
4995 return, for use in backreferences. The number here includes
4996 an element for register zero. */
4997 size_t num_regs
= bufp
->re_nsub
+ 1;
4999 /* Information on the contents of registers. These are pointers into
5000 the input strings; they record just what was matched (on this
5001 attempt) by a subexpression part of the pattern, that is, the
5002 regnum-th regstart pointer points to where in the pattern we began
5003 matching and the regnum-th regend points to right after where we
5004 stopped matching the regnum-th subexpression. (The zeroth register
5005 keeps track of what the whole pattern matches.) */
5006 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5007 re_char
**regstart
, **regend
;
5010 /* The following record the register info as found in the above
5011 variables when we find a match better than any we've seen before.
5012 This happens as we backtrack through the failure points, which in
5013 turn happens only if we have not yet matched the entire string. */
5014 unsigned best_regs_set
= false;
5015 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5016 re_char
**best_regstart
, **best_regend
;
5019 /* Logically, this is `best_regend[0]'. But we don't want to have to
5020 allocate space for that if we're not allocating space for anything
5021 else (see below). Also, we never need info about register 0 for
5022 any of the other register vectors, and it seems rather a kludge to
5023 treat `best_regend' differently than the rest. So we keep track of
5024 the end of the best match so far in a separate variable. We
5025 initialize this to NULL so that when we backtrack the first time
5026 and need to test it, it's not garbage. */
5027 re_char
*match_end
= NULL
;
5029 #ifdef DEBUG_COMPILES_ARGUMENTS
5030 /* Counts the total number of registers pushed. */
5031 unsigned num_regs_pushed
= 0;
5034 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5036 REGEX_USE_SAFE_ALLOCA
;
5040 #ifdef MATCH_MAY_ALLOCATE
5041 /* Do not bother to initialize all the register variables if there are
5042 no groups in the pattern, as it takes a fair amount of time. If
5043 there are groups, we include space for register 0 (the whole
5044 pattern), even though we never use it, since it simplifies the
5045 array indexing. We should fix this. */
5048 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5049 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5050 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5051 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5053 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5061 /* We must initialize all our variables to NULL, so that
5062 `FREE_VARIABLES' doesn't try to free them. */
5063 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5065 #endif /* MATCH_MAY_ALLOCATE */
5067 /* The starting position is bogus. */
5068 if (pos
< 0 || pos
> size1
+ size2
)
5074 /* Initialize subexpression text positions to -1 to mark ones that no
5075 start_memory/stop_memory has been seen for. Also initialize the
5076 register information struct. */
5077 for (reg
= 1; reg
< num_regs
; reg
++)
5078 regstart
[reg
] = regend
[reg
] = NULL
;
5080 /* We move `string1' into `string2' if the latter's empty -- but not if
5081 `string1' is null. */
5082 if (size2
== 0 && string1
!= NULL
)
5089 end1
= string1
+ size1
;
5090 end2
= string2
+ size2
;
5092 /* `p' scans through the pattern as `d' scans through the data.
5093 `dend' is the end of the input string that `d' points within. `d'
5094 is advanced into the following input string whenever necessary, but
5095 this happens before fetching; therefore, at the beginning of the
5096 loop, `d' can be pointing at the end of a string, but it cannot
5100 /* Only match within string2. */
5101 d
= string2
+ pos
- size1
;
5102 dend
= end_match_2
= string2
+ stop
- size1
;
5103 end_match_1
= end1
; /* Just to give it a value. */
5109 /* Only match within string1. */
5110 end_match_1
= string1
+ stop
;
5112 When we reach end_match_1, PREFETCH normally switches to string2.
5113 But in the present case, this means that just doing a PREFETCH
5114 makes us jump from `stop' to `gap' within the string.
5115 What we really want here is for the search to stop as
5116 soon as we hit end_match_1. That's why we set end_match_2
5117 to end_match_1 (since PREFETCH fails as soon as we hit
5119 end_match_2
= end_match_1
;
5122 { /* It's important to use this code when stop == size so that
5123 moving `d' from end1 to string2 will not prevent the d == dend
5124 check from catching the end of string. */
5126 end_match_2
= string2
+ stop
- size1
;
5132 DEBUG_PRINT ("The compiled pattern is: ");
5133 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5134 DEBUG_PRINT ("The string to match is: \"");
5135 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5136 DEBUG_PRINT ("\"\n");
5138 /* This loops over pattern commands. It exits by returning from the
5139 function if the match is complete, or it drops through if the match
5140 fails at this starting point in the input data. */
5143 DEBUG_PRINT ("\n%p: ", p
);
5147 /* End of pattern means we might have succeeded. */
5148 DEBUG_PRINT ("end of pattern ... ");
5150 /* If we haven't matched the entire string, and we want the
5151 longest match, try backtracking. */
5152 if (d
!= end_match_2
)
5154 /* True if this match is the best seen so far. */
5158 /* True if this match ends in the same string (string1
5159 or string2) as the best previous match. */
5160 bool same_str_p
= (FIRST_STRING_P (match_end
)
5161 == FIRST_STRING_P (d
));
5163 /* AIX compiler got confused when this was combined
5164 with the previous declaration. */
5166 best_match_p
= d
> match_end
;
5168 best_match_p
= !FIRST_STRING_P (d
);
5171 DEBUG_PRINT ("backtracking.\n");
5173 if (!FAIL_STACK_EMPTY ())
5174 { /* More failure points to try. */
5176 /* If exceeds best match so far, save it. */
5177 if (!best_regs_set
|| best_match_p
)
5179 best_regs_set
= true;
5182 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5184 for (reg
= 1; reg
< num_regs
; reg
++)
5186 best_regstart
[reg
] = regstart
[reg
];
5187 best_regend
[reg
] = regend
[reg
];
5193 /* If no failure points, don't restore garbage. And if
5194 last match is real best match, don't restore second
5196 else if (best_regs_set
&& !best_match_p
)
5199 /* Restore best match. It may happen that `dend ==
5200 end_match_1' while the restored d is in string2.
5201 For example, the pattern `x.*y.*z' against the
5202 strings `x-' and `y-z-', if the two strings are
5203 not consecutive in memory. */
5204 DEBUG_PRINT ("Restoring best registers.\n");
5207 dend
= ((d
>= string1
&& d
<= end1
)
5208 ? end_match_1
: end_match_2
);
5210 for (reg
= 1; reg
< num_regs
; reg
++)
5212 regstart
[reg
] = best_regstart
[reg
];
5213 regend
[reg
] = best_regend
[reg
];
5216 } /* d != end_match_2 */
5219 DEBUG_PRINT ("Accepting match.\n");
5221 /* If caller wants register contents data back, do it. */
5222 if (regs
&& !bufp
->no_sub
)
5224 /* Have the register data arrays been allocated? */
5225 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5226 { /* No. So allocate them with malloc. We need one
5227 extra element beyond `num_regs' for the `-1' marker
5229 regs
->num_regs
= max (RE_NREGS
, num_regs
+ 1);
5230 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5231 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5232 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5237 bufp
->regs_allocated
= REGS_REALLOCATE
;
5239 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5240 { /* Yes. If we need more elements than were already
5241 allocated, reallocate them. If we need fewer, just
5243 if (regs
->num_regs
< num_regs
+ 1)
5245 regs
->num_regs
= num_regs
+ 1;
5246 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5247 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5248 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5257 /* These braces fend off a "empty body in an else-statement"
5258 warning under GCC when assert expands to nothing. */
5259 assert (bufp
->regs_allocated
== REGS_FIXED
);
5262 /* Convert the pointer data in `regstart' and `regend' to
5263 indices. Register zero has to be set differently,
5264 since we haven't kept track of any info for it. */
5265 if (regs
->num_regs
> 0)
5267 regs
->start
[0] = pos
;
5268 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5271 /* Go through the first `min (num_regs, regs->num_regs)'
5272 registers, since that is all we initialized. */
5273 for (reg
= 1; reg
< min (num_regs
, regs
->num_regs
); reg
++)
5275 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5276 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5279 regs
->start
[reg
] = POINTER_TO_OFFSET (regstart
[reg
]);
5280 regs
->end
[reg
] = POINTER_TO_OFFSET (regend
[reg
]);
5284 /* If the regs structure we return has more elements than
5285 were in the pattern, set the extra elements to -1. If
5286 we (re)allocated the registers, this is the case,
5287 because we always allocate enough to have at least one
5289 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5290 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5291 } /* regs && !bufp->no_sub */
5293 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5294 nfailure_points_pushed
, nfailure_points_popped
,
5295 nfailure_points_pushed
- nfailure_points_popped
);
5296 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed
);
5298 ptrdiff_t dcnt
= POINTER_TO_OFFSET (d
) - pos
;
5300 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt
);
5306 /* Otherwise match next pattern command. */
5309 /* Ignore these. Used to ignore the n of succeed_n's which
5310 currently have n == 0. */
5312 DEBUG_PRINT ("EXECUTING no_op.\n");
5316 DEBUG_PRINT ("EXECUTING succeed.\n");
5319 /* Match the next n pattern characters exactly. The following
5320 byte in the pattern defines n, and the n bytes after that
5321 are the characters to match. */
5324 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt
);
5326 /* Remember the start point to rollback upon failure. */
5330 /* This is written out as an if-else so we don't waste time
5331 testing `translate' inside the loop. */
5332 if (RE_TRANSLATE_P (translate
))
5336 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5356 /* The cost of testing `translate' is comparatively small. */
5357 if (target_multibyte
)
5360 int pat_charlen
, buf_charlen
;
5365 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5368 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5371 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5373 if (TRANSLATE (buf_ch
) != pat_ch
)
5381 mcnt
-= pat_charlen
;
5393 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5394 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5401 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5402 if (! CHAR_BYTE8_P (buf_ch
))
5404 buf_ch
= TRANSLATE (buf_ch
);
5405 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5411 if (buf_ch
!= pat_ch
)
5424 /* Match any character except possibly a newline or a null. */
5429 reg_syntax_t syntax
;
5431 DEBUG_PRINT ("EXECUTING anychar.\n");
5434 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5436 buf_ch
= TRANSLATE (buf_ch
);
5439 syntax
= RE_SYNTAX_EMACS
;
5441 syntax
= bufp
->syntax
;
5444 if ((!(syntax
& RE_DOT_NEWLINE
) && buf_ch
== '\n')
5445 || ((syntax
& RE_DOT_NOT_NULL
) && buf_ch
== '\000'))
5448 DEBUG_PRINT (" Matched \"%d\".\n", *d
);
5457 register unsigned int c
, corig
;
5460 /* Whether matching against a unibyte character. */
5461 boolean unibyte_char
= false;
5463 DEBUG_PRINT ("EXECUTING charset%s.\n",
5464 (re_opcode_t
) *(p
- 1) == charset_not
? "_not" : "");
5467 corig
= c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5468 if (target_multibyte
)
5473 c1
= RE_CHAR_TO_UNIBYTE (c
);
5476 unibyte_char
= true;
5482 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5484 if (! CHAR_BYTE8_P (c1
))
5486 c1
= TRANSLATE (c1
);
5487 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5490 unibyte_char
= true;
5495 unibyte_char
= true;
5499 if (!execute_charset (&p
, c
, corig
, unibyte_char
))
5507 /* The beginning of a group is represented by start_memory.
5508 The argument is the register number. The text
5509 matched within the group is recorded (in the internal
5510 registers data structure) under the register number. */
5512 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p
);
5514 /* In case we need to undo this operation (via backtracking). */
5515 PUSH_FAILURE_REG (*p
);
5518 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5519 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart
[*p
]));
5521 /* Move past the register number and inner group count. */
5526 /* The stop_memory opcode represents the end of a group. Its
5527 argument is the same as start_memory's: the register number. */
5529 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p
);
5531 assert (!REG_UNSET (regstart
[*p
]));
5532 /* Strictly speaking, there should be code such as:
5534 assert (REG_UNSET (regend[*p]));
5535 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5537 But the only info to be pushed is regend[*p] and it is known to
5538 be UNSET, so there really isn't anything to push.
5539 Not pushing anything, on the other hand deprives us from the
5540 guarantee that regend[*p] is UNSET since undoing this operation
5541 will not reset its value properly. This is not important since
5542 the value will only be read on the next start_memory or at
5543 the very end and both events can only happen if this stop_memory
5547 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend
[*p
]));
5549 /* Move past the register number and the inner group count. */
5554 /* \<digit> has been turned into a `duplicate' command which is
5555 followed by the numeric value of <digit> as the register number. */
5558 register re_char
*d2
, *dend2
;
5559 int regno
= *p
++; /* Get which register to match against. */
5560 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno
);
5562 /* Can't back reference a group which we've never matched. */
5563 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5566 /* Where in input to try to start matching. */
5567 d2
= regstart
[regno
];
5569 /* Remember the start point to rollback upon failure. */
5572 /* Where to stop matching; if both the place to start and
5573 the place to stop matching are in the same string, then
5574 set to the place to stop, otherwise, for now have to use
5575 the end of the first string. */
5577 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5578 == FIRST_STRING_P (regend
[regno
]))
5579 ? regend
[regno
] : end_match_1
);
5584 /* If necessary, advance to next segment in register
5588 if (dend2
== end_match_2
) break;
5589 if (dend2
== regend
[regno
]) break;
5591 /* End of string1 => advance to string2. */
5593 dend2
= regend
[regno
];
5595 /* At end of register contents => success */
5596 if (d2
== dend2
) break;
5598 /* If necessary, advance to next segment in data. */
5601 /* How many characters left in this segment to match. */
5604 /* Want how many consecutive characters we can match in
5605 one shot, so, if necessary, adjust the count. */
5606 if (dcnt
> dend2
- d2
)
5609 /* Compare that many; failure if mismatch, else move
5611 if (RE_TRANSLATE_P (translate
)
5612 ? bcmp_translate (d
, d2
, dcnt
, translate
, target_multibyte
)
5613 : memcmp (d
, d2
, dcnt
))
5618 d
+= dcnt
, d2
+= dcnt
;
5624 /* begline matches the empty string at the beginning of the string
5625 (unless `not_bol' is set in `bufp'), and after newlines. */
5627 DEBUG_PRINT ("EXECUTING begline.\n");
5629 if (AT_STRINGS_BEG (d
))
5631 if (!bufp
->not_bol
) break;
5636 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5640 /* In all other cases, we fail. */
5644 /* endline is the dual of begline. */
5646 DEBUG_PRINT ("EXECUTING endline.\n");
5648 if (AT_STRINGS_END (d
))
5650 if (!bufp
->not_eol
) break;
5654 PREFETCH_NOLIMIT ();
5661 /* Match at the very beginning of the data. */
5663 DEBUG_PRINT ("EXECUTING begbuf.\n");
5664 if (AT_STRINGS_BEG (d
))
5669 /* Match at the very end of the data. */
5671 DEBUG_PRINT ("EXECUTING endbuf.\n");
5672 if (AT_STRINGS_END (d
))
5677 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5678 pushes NULL as the value for the string on the stack. Then
5679 `POP_FAILURE_POINT' will keep the current value for the
5680 string, instead of restoring it. To see why, consider
5681 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5682 then the . fails against the \n. But the next thing we want
5683 to do is match the \n against the \n; if we restored the
5684 string value, we would be back at the foo.
5686 Because this is used only in specific cases, we don't need to
5687 check all the things that `on_failure_jump' does, to make
5688 sure the right things get saved on the stack. Hence we don't
5689 share its code. The only reason to push anything on the
5690 stack at all is that otherwise we would have to change
5691 `anychar's code to do something besides goto fail in this
5692 case; that seems worse than this. */
5693 case on_failure_keep_string_jump
:
5694 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5695 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5698 PUSH_FAILURE_POINT (p
- 3, NULL
);
5701 /* A nasty loop is introduced by the non-greedy *? and +?.
5702 With such loops, the stack only ever contains one failure point
5703 at a time, so that a plain on_failure_jump_loop kind of
5704 cycle detection cannot work. Worse yet, such a detection
5705 can not only fail to detect a cycle, but it can also wrongly
5706 detect a cycle (between different instantiations of the same
5708 So the method used for those nasty loops is a little different:
5709 We use a special cycle-detection-stack-frame which is pushed
5710 when the on_failure_jump_nastyloop failure-point is *popped*.
5711 This special frame thus marks the beginning of one iteration
5712 through the loop and we can hence easily check right here
5713 whether something matched between the beginning and the end of
5715 case on_failure_jump_nastyloop
:
5716 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5717 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5720 assert ((re_opcode_t
)p
[-4] == no_op
);
5723 CHECK_INFINITE_LOOP (p
- 4, d
);
5725 /* If there's a cycle, just continue without pushing
5726 this failure point. The failure point is the "try again"
5727 option, which shouldn't be tried.
5728 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5729 PUSH_FAILURE_POINT (p
- 3, d
);
5733 /* Simple loop detecting on_failure_jump: just check on the
5734 failure stack if the same spot was already hit earlier. */
5735 case on_failure_jump_loop
:
5737 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5738 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5742 CHECK_INFINITE_LOOP (p
- 3, d
);
5744 /* If there's a cycle, get out of the loop, as if the matching
5745 had failed. We used to just `goto fail' here, but that was
5746 aborting the search a bit too early: we want to keep the
5747 empty-loop-match and keep matching after the loop.
5748 We want (x?)*y\1z to match both xxyz and xxyxz. */
5751 PUSH_FAILURE_POINT (p
- 3, d
);
5756 /* Uses of on_failure_jump:
5758 Each alternative starts with an on_failure_jump that points
5759 to the beginning of the next alternative. Each alternative
5760 except the last ends with a jump that in effect jumps past
5761 the rest of the alternatives. (They really jump to the
5762 ending jump of the following alternative, because tensioning
5763 these jumps is a hassle.)
5765 Repeats start with an on_failure_jump that points past both
5766 the repetition text and either the following jump or
5767 pop_failure_jump back to this on_failure_jump. */
5768 case on_failure_jump
:
5769 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5770 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5773 PUSH_FAILURE_POINT (p
-3, d
);
5776 /* This operation is used for greedy *.
5777 Compare the beginning of the repeat with what in the
5778 pattern follows its end. If we can establish that there
5779 is nothing that they would both match, i.e., that we
5780 would have to backtrack because of (as in, e.g., `a*a')
5781 then we can use a non-backtracking loop based on
5782 on_failure_keep_string_jump instead of on_failure_jump. */
5783 case on_failure_jump_smart
:
5784 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5785 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5788 re_char
*p1
= p
; /* Next operation. */
5789 /* Here, we discard `const', making re_match non-reentrant. */
5790 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5791 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5793 p
-= 3; /* Reset so that we will re-execute the
5794 instruction once it's been changed. */
5796 EXTRACT_NUMBER (mcnt
, p2
- 2);
5798 /* Ensure this is a indeed the trivial kind of loop
5799 we are expecting. */
5800 assert (skip_one_char (p1
) == p2
- 3);
5801 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5802 DEBUG_STATEMENT (debug
+= 2);
5803 if (mutually_exclusive_p (bufp
, p1
, p2
))
5805 /* Use a fast `on_failure_keep_string_jump' loop. */
5806 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5807 *p3
= (unsigned char) on_failure_keep_string_jump
;
5808 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5812 /* Default to a safe `on_failure_jump' loop. */
5813 DEBUG_PRINT (" smart default => slow loop.\n");
5814 *p3
= (unsigned char) on_failure_jump
;
5816 DEBUG_STATEMENT (debug
-= 2);
5820 /* Unconditionally jump (without popping any failure points). */
5823 IMMEDIATE_QUIT_CHECK
;
5824 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5825 DEBUG_PRINT ("EXECUTING jump %d ", mcnt
);
5826 p
+= mcnt
; /* Do the jump. */
5827 DEBUG_PRINT ("(to %p).\n", p
);
5831 /* Have to succeed matching what follows at least n times.
5832 After that, handle like `on_failure_jump'. */
5834 /* Signedness doesn't matter since we only compare MCNT to 0. */
5835 EXTRACT_NUMBER (mcnt
, p
+ 2);
5836 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt
);
5838 /* Originally, mcnt is how many times we HAVE to succeed. */
5841 /* Here, we discard `const', making re_match non-reentrant. */
5842 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5845 PUSH_NUMBER (p2
, mcnt
);
5848 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5853 /* Signedness doesn't matter since we only compare MCNT to 0. */
5854 EXTRACT_NUMBER (mcnt
, p
+ 2);
5855 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt
);
5857 /* Originally, this is how many times we CAN jump. */
5860 /* Here, we discard `const', making re_match non-reentrant. */
5861 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5863 PUSH_NUMBER (p2
, mcnt
);
5864 goto unconditional_jump
;
5866 /* If don't have to jump any more, skip over the rest of command. */
5873 unsigned char *p2
; /* Location of the counter. */
5874 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5876 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5877 /* Here, we discard `const', making re_match non-reentrant. */
5878 p2
= (unsigned char*) p
+ mcnt
;
5879 /* Signedness doesn't matter since we only copy MCNT's bits. */
5880 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5881 DEBUG_PRINT (" Setting %p to %d.\n", p2
, mcnt
);
5882 PUSH_NUMBER (p2
, mcnt
);
5889 boolean
not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5890 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5892 /* We SUCCEED (or FAIL) in one of the following cases: */
5894 /* Case 1: D is at the beginning or the end of string. */
5895 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5899 /* C1 is the character before D, S1 is the syntax of C1, C2
5900 is the character at D, and S2 is the syntax of C2. */
5905 ssize_t offset
= PTR_TO_OFFSET (d
- 1);
5906 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5907 UPDATE_SYNTAX_TABLE_FAST (charpos
);
5909 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5912 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos
+ 1);
5914 PREFETCH_NOLIMIT ();
5915 GET_CHAR_AFTER (c2
, d
, dummy
);
5918 if (/* Case 2: Only one of S1 and S2 is Sword. */
5919 ((s1
== Sword
) != (s2
== Sword
))
5920 /* Case 3: Both of S1 and S2 are Sword, and macro
5921 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5922 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5932 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5934 /* We FAIL in one of the following cases: */
5936 /* Case 1: D is at the end of string. */
5937 if (AT_STRINGS_END (d
))
5941 /* C1 is the character before D, S1 is the syntax of C1, C2
5942 is the character at D, and S2 is the syntax of C2. */
5947 ssize_t offset
= PTR_TO_OFFSET (d
);
5948 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5949 UPDATE_SYNTAX_TABLE_FAST (charpos
);
5952 GET_CHAR_AFTER (c2
, d
, dummy
);
5955 /* Case 2: S2 is not Sword. */
5959 /* Case 3: D is not at the beginning of string ... */
5960 if (!AT_STRINGS_BEG (d
))
5962 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5964 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5968 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5970 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5977 DEBUG_PRINT ("EXECUTING wordend.\n");
5979 /* We FAIL in one of the following cases: */
5981 /* Case 1: D is at the beginning of string. */
5982 if (AT_STRINGS_BEG (d
))
5986 /* C1 is the character before D, S1 is the syntax of C1, C2
5987 is the character at D, and S2 is the syntax of C2. */
5992 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
5993 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5994 UPDATE_SYNTAX_TABLE_FAST (charpos
);
5996 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5999 /* Case 2: S1 is not Sword. */
6003 /* Case 3: D is not at the end of string ... */
6004 if (!AT_STRINGS_END (d
))
6006 PREFETCH_NOLIMIT ();
6007 GET_CHAR_AFTER (c2
, d
, dummy
);
6009 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos
);
6013 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6015 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6022 DEBUG_PRINT ("EXECUTING symbeg.\n");
6024 /* We FAIL in one of the following cases: */
6026 /* Case 1: D is at the end of string. */
6027 if (AT_STRINGS_END (d
))
6031 /* C1 is the character before D, S1 is the syntax of C1, C2
6032 is the character at D, and S2 is the syntax of C2. */
6036 ssize_t offset
= PTR_TO_OFFSET (d
);
6037 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6038 UPDATE_SYNTAX_TABLE_FAST (charpos
);
6041 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6044 /* Case 2: S2 is neither Sword nor Ssymbol. */
6045 if (s2
!= Sword
&& s2
!= Ssymbol
)
6048 /* Case 3: D is not at the beginning of string ... */
6049 if (!AT_STRINGS_BEG (d
))
6051 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6053 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6057 /* ... and S1 is Sword or Ssymbol. */
6058 if (s1
== Sword
|| s1
== Ssymbol
)
6065 DEBUG_PRINT ("EXECUTING symend.\n");
6067 /* We FAIL in one of the following cases: */
6069 /* Case 1: D is at the beginning of string. */
6070 if (AT_STRINGS_BEG (d
))
6074 /* C1 is the character before D, S1 is the syntax of C1, C2
6075 is the character at D, and S2 is the syntax of C2. */
6079 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6080 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6081 UPDATE_SYNTAX_TABLE_FAST (charpos
);
6083 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6086 /* Case 2: S1 is neither Ssymbol nor Sword. */
6087 if (s1
!= Sword
&& s1
!= Ssymbol
)
6090 /* Case 3: D is not at the end of string ... */
6091 if (!AT_STRINGS_END (d
))
6093 PREFETCH_NOLIMIT ();
6094 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6096 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos
+ 1);
6100 /* ... and S2 is Sword or Ssymbol. */
6101 if (s2
== Sword
|| s2
== Ssymbol
)
6110 boolean
not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6112 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6117 ssize_t offset
= PTR_TO_OFFSET (d
);
6118 ssize_t pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6119 UPDATE_SYNTAX_TABLE_FAST (pos1
);
6126 GET_CHAR_AFTER (c
, d
, len
);
6127 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6136 DEBUG_PRINT ("EXECUTING at_dot.\n");
6137 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6142 case notcategoryspec
:
6144 boolean
not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6146 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6147 not ? "not" : "", mcnt
);
6153 GET_CHAR_AFTER (c
, d
, len
);
6154 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6166 continue; /* Successfully executed one pattern command; keep going. */
6169 /* We goto here if a matching operation fails. */
6171 IMMEDIATE_QUIT_CHECK
;
6172 if (!FAIL_STACK_EMPTY ())
6175 /* A restart point is known. Restore to that state. */
6176 DEBUG_PRINT ("\nFAIL:\n");
6177 POP_FAILURE_POINT (str
, pat
);
6180 case on_failure_keep_string_jump
:
6181 assert (str
== NULL
);
6182 goto continue_failure_jump
;
6184 case on_failure_jump_nastyloop
:
6185 assert ((re_opcode_t
)pat
[-2] == no_op
);
6186 PUSH_FAILURE_POINT (pat
- 2, str
);
6189 case on_failure_jump_loop
:
6190 case on_failure_jump
:
6193 continue_failure_jump
:
6194 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6199 /* A special frame used for nastyloops. */
6206 assert (p
>= bufp
->buffer
&& p
<= pend
);
6208 if (d
>= string1
&& d
<= end1
)
6212 break; /* Matching at this starting point really fails. */
6216 goto restore_best_regs
;
6220 return -1; /* Failure to match. */
6223 /* Subroutine definitions for re_match_2. */
6225 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6226 bytes; nonzero otherwise. */
6229 bcmp_translate (const_re_char
*s1
, const_re_char
*s2
, register ssize_t len
,
6230 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6232 register re_char
*p1
= s1
, *p2
= s2
;
6233 re_char
*p1_end
= s1
+ len
;
6234 re_char
*p2_end
= s2
+ len
;
6236 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6237 different lengths, but relying on a single `len' would break this. -sm */
6238 while (p1
< p1_end
&& p2
< p2_end
)
6240 int p1_charlen
, p2_charlen
;
6241 re_wchar_t p1_ch
, p2_ch
;
6243 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6244 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6246 if (RE_TRANSLATE (translate
, p1_ch
)
6247 != RE_TRANSLATE (translate
, p2_ch
))
6250 p1
+= p1_charlen
, p2
+= p2_charlen
;
6253 if (p1
!= p1_end
|| p2
!= p2_end
)
6259 /* Entry points for GNU code. */
6261 /* re_compile_pattern is the GNU regular expression compiler: it
6262 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6263 Returns 0 if the pattern was valid, otherwise an error string.
6265 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6266 are set in BUFP on entry.
6268 We call regex_compile to do the actual compilation. */
6271 re_compile_pattern (const char *pattern
, size_t length
,
6273 bool posix_backtracking
, const char *whitespace_regexp
,
6275 struct re_pattern_buffer
*bufp
)
6279 /* GNU code is written to assume at least RE_NREGS registers will be set
6280 (and at least one extra will be -1). */
6281 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6283 /* And GNU code determines whether or not to get register information
6284 by passing null for the REGS argument to re_match, etc., not by
6288 ret
= regex_compile ((re_char
*) pattern
, length
,
6299 return gettext (re_error_msgid
[(int) ret
]);
6301 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6303 /* Entry points compatible with 4.2 BSD regex library. We don't define
6304 them unless specifically requested. */
6306 #if defined _REGEX_RE_COMP || defined _LIBC
6308 /* BSD has one and only one pattern buffer. */
6309 static struct re_pattern_buffer re_comp_buf
;
6313 /* Make these definitions weak in libc, so POSIX programs can redefine
6314 these names if they don't use our functions, and still use
6315 regcomp/regexec below without link errors. */
6318 re_comp (const char *s
)
6324 if (!re_comp_buf
.buffer
)
6325 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6326 return (char *) gettext ("No previous regular expression");
6330 if (!re_comp_buf
.buffer
)
6332 re_comp_buf
.buffer
= malloc (200);
6333 if (re_comp_buf
.buffer
== NULL
)
6334 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6335 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6336 re_comp_buf
.allocated
= 200;
6338 re_comp_buf
.fastmap
= malloc (1 << BYTEWIDTH
);
6339 if (re_comp_buf
.fastmap
== NULL
)
6340 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6341 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6344 /* Since `re_exec' always passes NULL for the `regs' argument, we
6345 don't need to initialize the pattern buffer fields which affect it. */
6347 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6352 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6353 return (char *) gettext (re_error_msgid
[(int) ret
]);
6361 re_exec (const char *s
)
6363 const size_t len
= strlen (s
);
6364 return re_search (&re_comp_buf
, s
, len
, 0, len
, 0) >= 0;
6366 #endif /* _REGEX_RE_COMP */
6368 /* POSIX.2 functions. Don't define these for Emacs. */
6372 /* regcomp takes a regular expression as a string and compiles it.
6374 PREG is a regex_t *. We do not expect any fields to be initialized,
6375 since POSIX says we shouldn't. Thus, we set
6377 `buffer' to the compiled pattern;
6378 `used' to the length of the compiled pattern;
6379 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6380 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6381 RE_SYNTAX_POSIX_BASIC;
6382 `fastmap' to an allocated space for the fastmap;
6383 `fastmap_accurate' to zero;
6384 `re_nsub' to the number of subexpressions in PATTERN.
6386 PATTERN is the address of the pattern string.
6388 CFLAGS is a series of bits which affect compilation.
6390 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6391 use POSIX basic syntax.
6393 If REG_NEWLINE is set, then . and [^...] don't match newline.
6394 Also, regexec will try a match beginning after every newline.
6396 If REG_ICASE is set, then we considers upper- and lowercase
6397 versions of letters to be equivalent when matching.
6399 If REG_NOSUB is set, then when PREG is passed to regexec, that
6400 routine will report only success or failure, and nothing about the
6403 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6404 the return codes and their meanings.) */
6407 regcomp (regex_t
*_Restrict_ preg
, const char *_Restrict_ pattern
,
6412 = (cflags
& REG_EXTENDED
) ?
6413 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6415 /* regex_compile will allocate the space for the compiled pattern. */
6417 preg
->allocated
= 0;
6420 /* Try to allocate space for the fastmap. */
6421 preg
->fastmap
= malloc (1 << BYTEWIDTH
);
6423 if (cflags
& REG_ICASE
)
6427 preg
->translate
= malloc (CHAR_SET_SIZE
* sizeof *preg
->translate
);
6428 if (preg
->translate
== NULL
)
6429 return (int) REG_ESPACE
;
6431 /* Map uppercase characters to corresponding lowercase ones. */
6432 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6433 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6436 preg
->translate
= NULL
;
6438 /* If REG_NEWLINE is set, newlines are treated differently. */
6439 if (cflags
& REG_NEWLINE
)
6440 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6441 syntax
&= ~RE_DOT_NEWLINE
;
6442 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6445 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6447 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6449 /* POSIX says a null character in the pattern terminates it, so we
6450 can use strlen here in compiling the pattern. */
6451 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6453 /* POSIX doesn't distinguish between an unmatched open-group and an
6454 unmatched close-group: both are REG_EPAREN. */
6455 if (ret
== REG_ERPAREN
)
6458 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6459 { /* Compute the fastmap now, since regexec cannot modify the pattern
6461 re_compile_fastmap (preg
);
6462 if (preg
->can_be_null
)
6463 { /* The fastmap can't be used anyway. */
6464 free (preg
->fastmap
);
6465 preg
->fastmap
= NULL
;
6470 WEAK_ALIAS (__regcomp
, regcomp
)
6473 /* regexec searches for a given pattern, specified by PREG, in the
6476 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6477 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6478 least NMATCH elements, and we set them to the offsets of the
6479 corresponding matched substrings.
6481 EFLAGS specifies `execution flags' which affect matching: if
6482 REG_NOTBOL is set, then ^ does not match at the beginning of the
6483 string; if REG_NOTEOL is set, then $ does not match at the end.
6485 We return 0 if we find a match and REG_NOMATCH if not. */
6488 regexec (const regex_t
*_Restrict_ preg
, const char *_Restrict_ string
,
6489 size_t nmatch
, regmatch_t pmatch
[_Restrict_arr_
], int eflags
)
6492 struct re_registers regs
;
6493 regex_t private_preg
;
6494 size_t len
= strlen (string
);
6495 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6497 private_preg
= *preg
;
6499 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6500 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6502 /* The user has told us exactly how many registers to return
6503 information about, via `nmatch'. We have to pass that on to the
6504 matching routines. */
6505 private_preg
.regs_allocated
= REGS_FIXED
;
6509 regs
.num_regs
= nmatch
;
6510 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6511 if (regs
.start
== NULL
)
6513 regs
.end
= regs
.start
+ nmatch
;
6516 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6517 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6518 was a little bit longer but still only matching the real part.
6519 This works because the `endline' will check for a '\n' and will find a
6520 '\0', correctly deciding that this is not the end of a line.
6521 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6522 a convenient '\0' there. For all we know, the string could be preceded
6523 by '\n' which would throw things off. */
6525 /* Perform the searching operation. */
6526 ret
= re_search (&private_preg
, string
, len
,
6527 /* start: */ 0, /* range: */ len
,
6528 want_reg_info
? ®s
: 0);
6530 /* Copy the register information to the POSIX structure. */
6537 for (r
= 0; r
< nmatch
; r
++)
6539 pmatch
[r
].rm_so
= regs
.start
[r
];
6540 pmatch
[r
].rm_eo
= regs
.end
[r
];
6544 /* If we needed the temporary register info, free the space now. */
6548 /* We want zero return to mean success, unlike `re_search'. */
6549 return ret
>= 0 ? REG_NOERROR
: REG_NOMATCH
;
6551 WEAK_ALIAS (__regexec
, regexec
)
6554 /* Returns a message corresponding to an error code, ERR_CODE, returned
6555 from either regcomp or regexec. We don't use PREG here.
6557 ERR_CODE was previously called ERRCODE, but that name causes an
6558 error with msvc8 compiler. */
6561 regerror (int err_code
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
6567 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6568 /* Only error codes returned by the rest of the code should be passed
6569 to this routine. If we are given anything else, or if other regex
6570 code generates an invalid error code, then the program has a bug.
6571 Dump core so we can fix it. */
6574 msg
= gettext (re_error_msgid
[err_code
]);
6576 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6578 if (errbuf_size
!= 0)
6580 if (msg_size
> errbuf_size
)
6582 memcpy (errbuf
, msg
, errbuf_size
- 1);
6583 errbuf
[errbuf_size
- 1] = 0;
6586 strcpy (errbuf
, msg
);
6591 WEAK_ALIAS (__regerror
, regerror
)
6594 /* Free dynamically allocated space used by PREG. */
6597 regfree (regex_t
*preg
)
6599 free (preg
->buffer
);
6600 preg
->buffer
= NULL
;
6602 preg
->allocated
= 0;
6605 free (preg
->fastmap
);
6606 preg
->fastmap
= NULL
;
6607 preg
->fastmap_accurate
= 0;
6609 free (preg
->translate
);
6610 preg
->translate
= NULL
;
6612 WEAK_ALIAS (__regfree
, regfree
)
6614 #endif /* not emacs */