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-2012 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
26 need to modify the compiled regexp so that re_match can be reentrant.
27 - get rid of on_failure_jump_smart by doing the optimization in re_comp
28 rather than at run-time, so that re_match can be reentrant.
31 /* AIX requires this to be the first thing in the file. */
32 #if defined _AIX && !defined REGEX_MALLOC
36 /* Ignore some GCC warnings for now. This section should go away
37 once the Emacs and Gnulib regex code is merged. */
38 #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
39 # pragma GCC diagnostic ignored "-Wstrict-overflow"
41 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
42 # pragma GCC diagnostic ignored "-Wunused-function"
43 # pragma GCC diagnostic ignored "-Wunused-macros"
44 # pragma GCC diagnostic ignored "-Wunused-result"
45 # pragma GCC diagnostic ignored "-Wunused-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. */
135 /* Make syntax table lookup grant data in gl_state. */
136 # define SYNTAX_ENTRY_VIA_PROPERTY
139 # include "character.h"
140 # include "category.h"
145 # define malloc xmalloc
149 # define realloc xrealloc
155 /* Converts the pointer to the char to BEG-based offset from the start. */
156 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
157 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
159 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
160 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
161 # define RE_STRING_CHAR(p, multibyte) \
162 (multibyte ? (STRING_CHAR (p)) : (*(p)))
163 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
164 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
166 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
168 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
170 /* Set C a (possibly converted to multibyte) character before P. P
171 points into a string which is the virtual concatenation of STR1
172 (which ends at END1) or STR2 (which ends at END2). */
173 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
175 if (target_multibyte) \
177 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
178 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
179 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
180 c = STRING_CHAR (dtemp); \
184 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
185 (c) = RE_CHAR_TO_MULTIBYTE (c); \
189 /* Set C a (possibly converted to multibyte) character at P, and set
190 LEN to the byte length of that character. */
191 # define GET_CHAR_AFTER(c, p, len) \
193 if (target_multibyte) \
194 (c) = STRING_CHAR_AND_LENGTH (p, len); \
199 (c) = RE_CHAR_TO_MULTIBYTE (c); \
203 #else /* not emacs */
205 /* If we are not linking with Emacs proper,
206 we can't use the relocating allocator
207 even if config.h says that we can. */
212 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
215 xmalloc (size_t size
)
218 val
= (void *) malloc (size
);
221 write (2, "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. */
234 val
= (void *) malloc (size
);
236 val
= (void *) realloc (block
, size
);
239 write (2, "virtual memory exhausted\n", 25);
248 # define malloc xmalloc
252 # define realloc xrealloc
256 /* Define the syntax stuff for \<, \>, etc. */
258 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
259 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1, Ssymbol
= 2 };
261 # define SWITCH_ENUM_CAST(x) (x)
263 /* Dummy macros for non-Emacs environments. */
264 # define CHAR_CHARSET(c) 0
265 # define CHARSET_LEADING_CODE_BASE(c) 0
266 # define MAX_MULTIBYTE_LENGTH 1
267 # define RE_MULTIBYTE_P(x) 0
268 # define RE_TARGET_MULTIBYTE_P(x) 0
269 # define WORD_BOUNDARY_P(c1, c2) (0)
270 # define CHAR_HEAD_P(p) (1)
271 # define SINGLE_BYTE_CHAR_P(c) (1)
272 # define SAME_CHARSET_P(c1, c2) (1)
273 # define BYTES_BY_CHAR_HEAD(p) (1)
274 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
275 # define STRING_CHAR(p) (*(p))
276 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
277 # define CHAR_STRING(c, s) (*(s) = (c), 1)
278 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
279 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
280 # define RE_CHAR_TO_MULTIBYTE(c) (c)
281 # define RE_CHAR_TO_UNIBYTE(c) (c)
282 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
283 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
284 # define GET_CHAR_AFTER(c, p, len) \
286 # define MAKE_CHAR(charset, c1, c2) (c1)
287 # define BYTE8_TO_CHAR(c) (c)
288 # define CHAR_BYTE8_P(c) (0)
289 # define CHAR_LEADING_CODE(c) (c)
291 #endif /* not emacs */
294 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
295 # define RE_TRANSLATE_P(TBL) (TBL)
298 /* Get the interface, including the syntax bits. */
301 /* isalpha etc. are used for the character classes. */
306 /* 1 if C is an ASCII character. */
307 # define IS_REAL_ASCII(c) ((c) < 0200)
309 /* 1 if C is a unibyte character. */
310 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
312 /* The Emacs definitions should not be directly affected by locales. */
314 /* In Emacs, these are only used for single-byte characters. */
315 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
316 # define ISCNTRL(c) ((c) < ' ')
317 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
318 || ((c) >= 'a' && (c) <= 'f') \
319 || ((c) >= 'A' && (c) <= 'F'))
321 /* This is only used for single-byte characters. */
322 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
324 /* The rest must handle multibyte characters. */
326 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
327 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
330 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
331 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
334 # define ISALNUM(c) (IS_REAL_ASCII (c) \
335 ? (((c) >= 'a' && (c) <= 'z') \
336 || ((c) >= 'A' && (c) <= 'Z') \
337 || ((c) >= '0' && (c) <= '9')) \
338 : SYNTAX (c) == Sword)
340 # define ISALPHA(c) (IS_REAL_ASCII (c) \
341 ? (((c) >= 'a' && (c) <= 'z') \
342 || ((c) >= 'A' && (c) <= 'Z')) \
343 : SYNTAX (c) == Sword)
345 # define ISLOWER(c) lowercasep (c)
347 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
348 ? ((c) > ' ' && (c) < 0177 \
349 && !(((c) >= 'a' && (c) <= 'z') \
350 || ((c) >= 'A' && (c) <= 'Z') \
351 || ((c) >= '0' && (c) <= '9'))) \
352 : SYNTAX (c) != Sword)
354 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
356 # define ISUPPER(c) uppercasep (c)
358 # define ISWORD(c) (SYNTAX (c) == Sword)
360 #else /* not emacs */
362 /* 1 if C is an ASCII character. */
363 # define IS_REAL_ASCII(c) ((c) < 0200)
365 /* This distinction is not meaningful, except in Emacs. */
366 # define ISUNIBYTE(c) 1
369 # define ISBLANK(c) isblank (c)
371 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
374 # define ISGRAPH(c) isgraph (c)
376 # define ISGRAPH(c) (isprint (c) && !isspace (c))
379 /* Solaris defines ISPRINT so we must undefine it first. */
381 # define ISPRINT(c) isprint (c)
382 # define ISDIGIT(c) isdigit (c)
383 # define ISALNUM(c) isalnum (c)
384 # define ISALPHA(c) isalpha (c)
385 # define ISCNTRL(c) iscntrl (c)
386 # define ISLOWER(c) islower (c)
387 # define ISPUNCT(c) ispunct (c)
388 # define ISSPACE(c) isspace (c)
389 # define ISUPPER(c) isupper (c)
390 # define ISXDIGIT(c) isxdigit (c)
392 # define ISWORD(c) ISALPHA (c)
395 # define TOLOWER(c) _tolower (c)
397 # define TOLOWER(c) tolower (c)
400 /* How many characters in the character set. */
401 # define CHAR_SET_SIZE 256
405 extern char *re_syntax_table
;
407 # else /* not SYNTAX_TABLE */
409 static char re_syntax_table
[CHAR_SET_SIZE
];
412 init_syntax_once (void)
420 memset (re_syntax_table
, 0, sizeof re_syntax_table
);
422 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
424 re_syntax_table
[c
] = Sword
;
426 re_syntax_table
['_'] = Ssymbol
;
431 # endif /* not SYNTAX_TABLE */
433 # define SYNTAX(c) re_syntax_table[(c)]
435 #endif /* not emacs */
437 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
439 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
440 use `alloca' instead of `malloc'. This is because using malloc in
441 re_search* or re_match* could cause memory leaks when C-g is used in
442 Emacs; also, malloc is slower and causes storage fragmentation. On
443 the other hand, malloc is more portable, and easier to debug.
445 Because we sometimes use alloca, some routines have to be macros,
446 not functions -- `alloca'-allocated space disappears at the end of the
447 function it is called in. */
451 # define REGEX_ALLOCATE malloc
452 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
453 # define REGEX_FREE free
455 #else /* not REGEX_MALLOC */
457 /* Emacs already defines alloca, sometimes. */
460 /* Make alloca work the best possible way. */
462 # define alloca __builtin_alloca
463 # else /* not __GNUC__ */
464 # ifdef HAVE_ALLOCA_H
466 # endif /* HAVE_ALLOCA_H */
467 # endif /* not __GNUC__ */
469 # endif /* not alloca */
471 # define REGEX_ALLOCATE alloca
473 /* Assumes a `char *destination' variable. */
474 # define REGEX_REALLOCATE(source, osize, nsize) \
475 (destination = (char *) alloca (nsize), \
476 memcpy (destination, source, osize))
478 /* No need to do anything to free, after alloca. */
479 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
481 #endif /* not REGEX_MALLOC */
483 /* Define how to allocate the failure stack. */
485 #if defined REL_ALLOC && defined REGEX_MALLOC
487 # define REGEX_ALLOCATE_STACK(size) \
488 r_alloc (&failure_stack_ptr, (size))
489 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
490 r_re_alloc (&failure_stack_ptr, (nsize))
491 # define REGEX_FREE_STACK(ptr) \
492 r_alloc_free (&failure_stack_ptr)
494 #else /* not using relocating allocator */
498 # define REGEX_ALLOCATE_STACK malloc
499 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
500 # define REGEX_FREE_STACK free
502 # else /* not REGEX_MALLOC */
504 # define REGEX_ALLOCATE_STACK alloca
506 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
507 REGEX_REALLOCATE (source, osize, nsize)
508 /* No need to explicitly free anything. */
509 # define REGEX_FREE_STACK(arg) ((void)0)
511 # endif /* not REGEX_MALLOC */
512 #endif /* not using relocating allocator */
515 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
516 `string1' or just past its end. This works if PTR is NULL, which is
518 #define FIRST_STRING_P(ptr) \
519 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
521 /* (Re)Allocate N items of type T using malloc, or fail. */
522 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
523 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
524 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
526 #define BYTEWIDTH 8 /* In bits. */
528 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
532 #define MAX(a, b) ((a) > (b) ? (a) : (b))
533 #define MIN(a, b) ((a) < (b) ? (a) : (b))
535 /* Type of source-pattern and string chars. */
537 typedef unsigned char re_char
;
539 typedef const unsigned char re_char
;
542 typedef char boolean
;
546 static regoff_t
re_match_2_internal (struct re_pattern_buffer
*bufp
,
547 re_char
*string1
, size_t size1
,
548 re_char
*string2
, size_t size2
,
550 struct re_registers
*regs
,
553 /* These are the command codes that appear in compiled regular
554 expressions. Some opcodes are followed by argument bytes. A
555 command code can specify any interpretation whatsoever for its
556 arguments. Zero bytes may appear in the compiled regular expression. */
562 /* Succeed right away--no more backtracking. */
565 /* Followed by one byte giving n, then by n literal bytes. */
568 /* Matches any (more or less) character. */
571 /* Matches any one char belonging to specified set. First
572 following byte is number of bitmap bytes. Then come bytes
573 for a bitmap saying which chars are in. Bits in each byte
574 are ordered low-bit-first. A character is in the set if its
575 bit is 1. A character too large to have a bit in the map is
576 automatically not in the set.
578 If the length byte has the 0x80 bit set, then that stuff
579 is followed by a range table:
580 2 bytes of flags for character sets (low 8 bits, high 8 bits)
581 See RANGE_TABLE_WORK_BITS below.
582 2 bytes, the number of pairs that follow (upto 32767)
583 pairs, each 2 multibyte characters,
584 each multibyte character represented as 3 bytes. */
587 /* Same parameters as charset, but match any character that is
588 not one of those specified. */
591 /* Start remembering the text that is matched, for storing in a
592 register. Followed by one byte with the register number, in
593 the range 0 to one less than the pattern buffer's re_nsub
597 /* Stop remembering the text that is matched and store it in a
598 memory register. Followed by one byte with the register
599 number, in the range 0 to one less than `re_nsub' in the
603 /* Match a duplicate of something remembered. Followed by one
604 byte containing the register number. */
607 /* Fail unless at beginning of line. */
610 /* Fail unless at end of line. */
613 /* Succeeds if at beginning of buffer (if emacs) or at beginning
614 of string to be matched (if not). */
617 /* Analogously, for end of buffer/string. */
620 /* Followed by two byte relative address to which to jump. */
623 /* Followed by two-byte relative address of place to resume at
624 in case of failure. */
627 /* Like on_failure_jump, but pushes a placeholder instead of the
628 current string position when executed. */
629 on_failure_keep_string_jump
,
631 /* Just like `on_failure_jump', except that it checks that we
632 don't get stuck in an infinite loop (matching an empty string
634 on_failure_jump_loop
,
636 /* Just like `on_failure_jump_loop', except that it checks for
637 a different kind of loop (the kind that shows up with non-greedy
638 operators). This operation has to be immediately preceded
640 on_failure_jump_nastyloop
,
642 /* A smart `on_failure_jump' used for greedy * and + operators.
643 It analyzes the loop before which it is put and if the
644 loop does not require backtracking, it changes itself to
645 `on_failure_keep_string_jump' and short-circuits the loop,
646 else it just defaults to changing itself into `on_failure_jump'.
647 It assumes that it is pointing to just past a `jump'. */
648 on_failure_jump_smart
,
650 /* Followed by two-byte relative address and two-byte number n.
651 After matching N times, jump to the address upon failure.
652 Does not work if N starts at 0: use on_failure_jump_loop
656 /* Followed by two-byte relative address, and two-byte number n.
657 Jump to the address N times, then fail. */
660 /* Set the following two-byte relative address to the
661 subsequent two-byte number. The address *includes* the two
665 wordbeg
, /* Succeeds if at word beginning. */
666 wordend
, /* Succeeds if at word end. */
668 wordbound
, /* Succeeds if at a word boundary. */
669 notwordbound
, /* Succeeds if not at a word boundary. */
671 symbeg
, /* Succeeds if at symbol beginning. */
672 symend
, /* Succeeds if at symbol end. */
674 /* Matches any character whose syntax is specified. Followed by
675 a byte which contains a syntax code, e.g., Sword. */
678 /* Matches any character whose syntax is not that specified. */
682 ,before_dot
, /* Succeeds if before point. */
683 at_dot
, /* Succeeds if at point. */
684 after_dot
, /* Succeeds if after point. */
686 /* Matches any character whose category-set contains the specified
687 category. The operator is followed by a byte which contains a
688 category code (mnemonic ASCII character). */
691 /* Matches any character whose category-set does not contain the
692 specified category. The operator is followed by a byte which
693 contains the category code (mnemonic ASCII character). */
698 /* Common operations on the compiled pattern. */
700 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
702 #define STORE_NUMBER(destination, number) \
704 (destination)[0] = (number) & 0377; \
705 (destination)[1] = (number) >> 8; \
708 /* Same as STORE_NUMBER, except increment DESTINATION to
709 the byte after where the number is stored. Therefore, DESTINATION
710 must be an lvalue. */
712 #define STORE_NUMBER_AND_INCR(destination, number) \
714 STORE_NUMBER (destination, number); \
715 (destination) += 2; \
718 /* Put into DESTINATION a number stored in two contiguous bytes starting
721 #define EXTRACT_NUMBER(destination, source) \
723 (destination) = *(source) & 0377; \
724 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
729 extract_number (int *dest
, re_char
*source
)
731 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
732 *dest
= *source
& 0377;
736 # ifndef EXTRACT_MACROS /* To debug the macros. */
737 # undef EXTRACT_NUMBER
738 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
739 # endif /* not EXTRACT_MACROS */
743 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
744 SOURCE must be an lvalue. */
746 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
748 EXTRACT_NUMBER (destination, source); \
754 extract_number_and_incr (int *destination
, re_char
**source
)
756 extract_number (destination
, *source
);
760 # ifndef EXTRACT_MACROS
761 # undef EXTRACT_NUMBER_AND_INCR
762 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
763 extract_number_and_incr (&dest, &src)
764 # endif /* not EXTRACT_MACROS */
768 /* Store a multibyte character in three contiguous bytes starting
769 DESTINATION, and increment DESTINATION to the byte after where the
770 character is stored. Therefore, DESTINATION must be an lvalue. */
772 #define STORE_CHARACTER_AND_INCR(destination, character) \
774 (destination)[0] = (character) & 0377; \
775 (destination)[1] = ((character) >> 8) & 0377; \
776 (destination)[2] = (character) >> 16; \
777 (destination) += 3; \
780 /* Put into DESTINATION a character stored in three contiguous bytes
781 starting at SOURCE. */
783 #define EXTRACT_CHARACTER(destination, source) \
785 (destination) = ((source)[0] \
786 | ((source)[1] << 8) \
787 | ((source)[2] << 16)); \
791 /* Macros for charset. */
793 /* Size of bitmap of charset P in bytes. P is a start of charset,
794 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
795 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
797 /* Nonzero if charset P has range table. */
798 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
800 /* Return the address of range table of charset P. But not the start
801 of table itself, but the before where the number of ranges is
802 stored. `2 +' means to skip re_opcode_t and size of bitmap,
803 and the 2 bytes of flags at the start of the range table. */
804 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
806 /* Extract the bit flags that start a range table. */
807 #define CHARSET_RANGE_TABLE_BITS(p) \
808 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
809 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
811 /* Return the address of end of RANGE_TABLE. COUNT is number of
812 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
813 is start of range and end of range. `* 3' is size of each start
815 #define CHARSET_RANGE_TABLE_END(range_table, count) \
816 ((range_table) + (count) * 2 * 3)
818 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
819 COUNT is number of ranges in RANGE_TABLE. */
820 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
823 re_wchar_t range_start, range_end; \
825 re_char *range_table_end \
826 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
828 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
830 EXTRACT_CHARACTER (range_start, rtp); \
831 EXTRACT_CHARACTER (range_end, rtp + 3); \
833 if (range_start <= (c) && (c) <= range_end) \
842 /* Test if C is in range table of CHARSET. The flag NOT is negated if
843 C is listed in it. */
844 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
847 /* Number of ranges in range table. */ \
849 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
851 EXTRACT_NUMBER_AND_INCR (count, range_table); \
852 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
856 /* If DEBUG is defined, Regex prints many voluminous messages about what
857 it is doing (if the variable `debug' is nonzero). If linked with the
858 main program in `iregex.c', you can enter patterns and strings
859 interactively. And if linked with the main program in `main.c' and
860 the other test files, you can run the already-written tests. */
864 /* We use standard I/O for debugging. */
867 /* It is useful to test things that ``must'' be true when debugging. */
870 static int debug
= -100000;
872 # define DEBUG_STATEMENT(e) e
873 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
874 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
875 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
876 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
877 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
878 if (debug > 0) print_partial_compiled_pattern (s, e)
879 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
880 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
883 /* Print the fastmap in human-readable form. */
886 print_fastmap (fastmap
)
889 unsigned was_a_range
= 0;
892 while (i
< (1 << BYTEWIDTH
))
898 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
914 /* Print a compiled pattern string in human-readable form, starting at
915 the START pointer into it and ending just before the pointer END. */
918 print_partial_compiled_pattern (start
, end
)
928 fprintf (stderr
, "(null)\n");
932 /* Loop over pattern commands. */
935 fprintf (stderr
, "%d:\t", p
- start
);
937 switch ((re_opcode_t
) *p
++)
940 fprintf (stderr
, "/no_op");
944 fprintf (stderr
, "/succeed");
949 fprintf (stderr
, "/exactn/%d", mcnt
);
952 fprintf (stderr
, "/%c", *p
++);
958 fprintf (stderr
, "/start_memory/%d", *p
++);
962 fprintf (stderr
, "/stop_memory/%d", *p
++);
966 fprintf (stderr
, "/duplicate/%d", *p
++);
970 fprintf (stderr
, "/anychar");
976 register int c
, last
= -100;
977 register int in_range
= 0;
978 int length
= CHARSET_BITMAP_SIZE (p
- 1);
979 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
981 fprintf (stderr
, "/charset [%s",
982 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
985 fprintf (stderr
, " !extends past end of pattern! ");
987 for (c
= 0; c
< 256; c
++)
989 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
991 /* Are we starting a range? */
992 if (last
+ 1 == c
&& ! in_range
)
994 fprintf (stderr
, "-");
997 /* Have we broken a range? */
998 else if (last
+ 1 != c
&& in_range
)
1000 fprintf (stderr
, "%c", last
);
1005 fprintf (stderr
, "%c", c
);
1011 fprintf (stderr
, "%c", last
);
1013 fprintf (stderr
, "]");
1017 if (has_range_table
)
1020 fprintf (stderr
, "has-range-table");
1022 /* ??? Should print the range table; for now, just skip it. */
1023 p
+= 2; /* skip range table bits */
1024 EXTRACT_NUMBER_AND_INCR (count
, p
);
1025 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1031 fprintf (stderr
, "/begline");
1035 fprintf (stderr
, "/endline");
1038 case on_failure_jump
:
1039 extract_number_and_incr (&mcnt
, &p
);
1040 fprintf (stderr
, "/on_failure_jump to %d", p
+ mcnt
- start
);
1043 case on_failure_keep_string_jump
:
1044 extract_number_and_incr (&mcnt
, &p
);
1045 fprintf (stderr
, "/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1048 case on_failure_jump_nastyloop
:
1049 extract_number_and_incr (&mcnt
, &p
);
1050 fprintf (stderr
, "/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1053 case on_failure_jump_loop
:
1054 extract_number_and_incr (&mcnt
, &p
);
1055 fprintf (stderr
, "/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1058 case on_failure_jump_smart
:
1059 extract_number_and_incr (&mcnt
, &p
);
1060 fprintf (stderr
, "/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1064 extract_number_and_incr (&mcnt
, &p
);
1065 fprintf (stderr
, "/jump to %d", p
+ mcnt
- start
);
1069 extract_number_and_incr (&mcnt
, &p
);
1070 extract_number_and_incr (&mcnt2
, &p
);
1071 fprintf (stderr
, "/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1075 extract_number_and_incr (&mcnt
, &p
);
1076 extract_number_and_incr (&mcnt2
, &p
);
1077 fprintf (stderr
, "/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1081 extract_number_and_incr (&mcnt
, &p
);
1082 extract_number_and_incr (&mcnt2
, &p
);
1083 fprintf (stderr
, "/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1087 fprintf (stderr
, "/wordbound");
1091 fprintf (stderr
, "/notwordbound");
1095 fprintf (stderr
, "/wordbeg");
1099 fprintf (stderr
, "/wordend");
1103 fprintf (stderr
, "/symbeg");
1107 fprintf (stderr
, "/symend");
1111 fprintf (stderr
, "/syntaxspec");
1113 fprintf (stderr
, "/%d", mcnt
);
1117 fprintf (stderr
, "/notsyntaxspec");
1119 fprintf (stderr
, "/%d", mcnt
);
1124 fprintf (stderr
, "/before_dot");
1128 fprintf (stderr
, "/at_dot");
1132 fprintf (stderr
, "/after_dot");
1136 fprintf (stderr
, "/categoryspec");
1138 fprintf (stderr
, "/%d", mcnt
);
1141 case notcategoryspec
:
1142 fprintf (stderr
, "/notcategoryspec");
1144 fprintf (stderr
, "/%d", mcnt
);
1149 fprintf (stderr
, "/begbuf");
1153 fprintf (stderr
, "/endbuf");
1157 fprintf (stderr
, "?%d", *(p
-1));
1160 fprintf (stderr
, "\n");
1163 fprintf (stderr
, "%d:\tend of pattern.\n", p
- start
);
1168 print_compiled_pattern (bufp
)
1169 struct re_pattern_buffer
*bufp
;
1171 re_char
*buffer
= bufp
->buffer
;
1173 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1174 printf ("%ld bytes used/%ld bytes allocated.\n",
1175 bufp
->used
, bufp
->allocated
);
1177 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1179 printf ("fastmap: ");
1180 print_fastmap (bufp
->fastmap
);
1183 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1184 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1185 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1186 printf ("no_sub: %d\t", bufp
->no_sub
);
1187 printf ("not_bol: %d\t", bufp
->not_bol
);
1188 printf ("not_eol: %d\t", bufp
->not_eol
);
1189 printf ("syntax: %lx\n", bufp
->syntax
);
1191 /* Perhaps we should print the translate table? */
1196 print_double_string (where
, string1
, size1
, string2
, size2
)
1209 if (FIRST_STRING_P (where
))
1211 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1212 putchar (string1
[this_char
]);
1217 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1218 putchar (string2
[this_char
]);
1222 #else /* not DEBUG */
1227 # define DEBUG_STATEMENT(e)
1228 # define DEBUG_PRINT1(x)
1229 # define DEBUG_PRINT2(x1, x2)
1230 # define DEBUG_PRINT3(x1, x2, x3)
1231 # define DEBUG_PRINT4(x1, x2, x3, x4)
1232 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1233 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1235 #endif /* not DEBUG */
1237 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1239 # define IF_LINT(Code) Code
1241 # define IF_LINT(Code) /* empty */
1244 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1245 also be assigned to arbitrarily: each pattern buffer stores its own
1246 syntax, so it can be changed between regex compilations. */
1247 /* This has no initializer because initialized variables in Emacs
1248 become read-only after dumping. */
1249 reg_syntax_t re_syntax_options
;
1252 /* Specify the precise syntax of regexps for compilation. This provides
1253 for compatibility for various utilities which historically have
1254 different, incompatible syntaxes.
1256 The argument SYNTAX is a bit mask comprised of the various bits
1257 defined in regex.h. We return the old syntax. */
1260 re_set_syntax (reg_syntax_t syntax
)
1262 reg_syntax_t ret
= re_syntax_options
;
1264 re_syntax_options
= syntax
;
1267 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1269 /* Regexp to use to replace spaces, or NULL meaning don't. */
1270 static re_char
*whitespace_regexp
;
1273 re_set_whitespace_regexp (const char *regexp
)
1275 whitespace_regexp
= (re_char
*) regexp
;
1277 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1279 /* This table gives an error message for each of the error codes listed
1280 in regex.h. Obviously the order here has to be same as there.
1281 POSIX doesn't require that we do anything for REG_NOERROR,
1282 but why not be nice? */
1284 static const char *re_error_msgid
[] =
1286 gettext_noop ("Success"), /* REG_NOERROR */
1287 gettext_noop ("No match"), /* REG_NOMATCH */
1288 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1289 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1290 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1291 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1292 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1293 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1294 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1295 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1296 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1297 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1298 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1299 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1300 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1301 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1302 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1303 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1306 /* Avoiding alloca during matching, to placate r_alloc. */
1308 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1309 searching and matching functions should not call alloca. On some
1310 systems, alloca is implemented in terms of malloc, and if we're
1311 using the relocating allocator routines, then malloc could cause a
1312 relocation, which might (if the strings being searched are in the
1313 ralloc heap) shift the data out from underneath the regexp
1316 Here's another reason to avoid allocation: Emacs
1317 processes input from X in a signal handler; processing X input may
1318 call malloc; if input arrives while a matching routine is calling
1319 malloc, then we're scrod. But Emacs can't just block input while
1320 calling matching routines; then we don't notice interrupts when
1321 they come in. So, Emacs blocks input around all regexp calls
1322 except the matching calls, which it leaves unprotected, in the
1323 faith that they will not malloc. */
1325 /* Normally, this is fine. */
1326 #define MATCH_MAY_ALLOCATE
1328 /* The match routines may not allocate if (1) they would do it with malloc
1329 and (2) it's not safe for them to use malloc.
1330 Note that if REL_ALLOC is defined, matching would not use malloc for the
1331 failure stack, but we would still use it for the register vectors;
1332 so REL_ALLOC should not affect this. */
1333 #if defined REGEX_MALLOC && defined emacs
1334 # undef MATCH_MAY_ALLOCATE
1338 /* Failure stack declarations and macros; both re_compile_fastmap and
1339 re_match_2 use a failure stack. These have to be macros because of
1340 REGEX_ALLOCATE_STACK. */
1343 /* Approximate number of failure points for which to initially allocate space
1344 when matching. If this number is exceeded, we allocate more
1345 space, so it is not a hard limit. */
1346 #ifndef INIT_FAILURE_ALLOC
1347 # define INIT_FAILURE_ALLOC 20
1350 /* Roughly the maximum number of failure points on the stack. Would be
1351 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1352 This is a variable only so users of regex can assign to it; we never
1353 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1354 before using it, so it should probably be a byte-count instead. */
1355 # if defined MATCH_MAY_ALLOCATE
1356 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1357 whose default stack limit is 2mb. In order for a larger
1358 value to work reliably, you have to try to make it accord
1359 with the process stack limit. */
1360 size_t re_max_failures
= 40000;
1362 size_t re_max_failures
= 4000;
1365 union fail_stack_elt
1368 /* This should be the biggest `int' that's no bigger than a pointer. */
1372 typedef union fail_stack_elt fail_stack_elt_t
;
1376 fail_stack_elt_t
*stack
;
1378 size_t avail
; /* Offset of next open position. */
1379 size_t frame
; /* Offset of the cur constructed frame. */
1382 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1385 /* Define macros to initialize and free the failure stack.
1386 Do `return -2' if the alloc fails. */
1388 #ifdef MATCH_MAY_ALLOCATE
1389 # define INIT_FAIL_STACK() \
1391 fail_stack.stack = (fail_stack_elt_t *) \
1392 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1393 * sizeof (fail_stack_elt_t)); \
1395 if (fail_stack.stack == NULL) \
1398 fail_stack.size = INIT_FAILURE_ALLOC; \
1399 fail_stack.avail = 0; \
1400 fail_stack.frame = 0; \
1403 # define INIT_FAIL_STACK() \
1405 fail_stack.avail = 0; \
1406 fail_stack.frame = 0; \
1409 # define RETALLOC_IF(addr, n, t) \
1410 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1414 /* Double the size of FAIL_STACK, up to a limit
1415 which allows approximately `re_max_failures' items.
1417 Return 1 if succeeds, and 0 if either ran out of memory
1418 allocating space for it or it was already too large.
1420 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1422 /* Factor to increase the failure stack size by
1423 when we increase it.
1424 This used to be 2, but 2 was too wasteful
1425 because the old discarded stacks added up to as much space
1426 were as ultimate, maximum-size stack. */
1427 #define FAIL_STACK_GROWTH_FACTOR 4
1429 #define GROW_FAIL_STACK(fail_stack) \
1430 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1431 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1433 : ((fail_stack).stack \
1434 = (fail_stack_elt_t *) \
1435 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1436 (fail_stack).size * sizeof (fail_stack_elt_t), \
1437 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1438 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1439 * FAIL_STACK_GROWTH_FACTOR))), \
1441 (fail_stack).stack == NULL \
1443 : ((fail_stack).size \
1444 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1445 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1446 * FAIL_STACK_GROWTH_FACTOR)) \
1447 / sizeof (fail_stack_elt_t)), \
1451 /* Push a pointer value onto the failure stack.
1452 Assumes the variable `fail_stack'. Probably should only
1453 be called from within `PUSH_FAILURE_POINT'. */
1454 #define PUSH_FAILURE_POINTER(item) \
1455 fail_stack.stack[fail_stack.avail++].pointer = (item)
1457 /* This pushes an integer-valued item onto the failure stack.
1458 Assumes the variable `fail_stack'. Probably should only
1459 be called from within `PUSH_FAILURE_POINT'. */
1460 #define PUSH_FAILURE_INT(item) \
1461 fail_stack.stack[fail_stack.avail++].integer = (item)
1463 /* These POP... operations complement the PUSH... operations.
1464 All assume that `fail_stack' is nonempty. */
1465 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1466 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1468 /* Individual items aside from the registers. */
1469 #define NUM_NONREG_ITEMS 3
1471 /* Used to examine the stack (to detect infinite loops). */
1472 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1473 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1474 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1475 #define TOP_FAILURE_HANDLE() fail_stack.frame
1478 #define ENSURE_FAIL_STACK(space) \
1479 while (REMAINING_AVAIL_SLOTS <= space) { \
1480 if (!GROW_FAIL_STACK (fail_stack)) \
1482 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1483 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1486 /* Push register NUM onto the stack. */
1487 #define PUSH_FAILURE_REG(num) \
1489 char *destination; \
1490 ENSURE_FAIL_STACK(3); \
1491 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1492 num, regstart[num], regend[num]); \
1493 PUSH_FAILURE_POINTER (regstart[num]); \
1494 PUSH_FAILURE_POINTER (regend[num]); \
1495 PUSH_FAILURE_INT (num); \
1498 /* Change the counter's value to VAL, but make sure that it will
1499 be reset when backtracking. */
1500 #define PUSH_NUMBER(ptr,val) \
1502 char *destination; \
1504 ENSURE_FAIL_STACK(3); \
1505 EXTRACT_NUMBER (c, ptr); \
1506 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1507 PUSH_FAILURE_INT (c); \
1508 PUSH_FAILURE_POINTER (ptr); \
1509 PUSH_FAILURE_INT (-1); \
1510 STORE_NUMBER (ptr, val); \
1513 /* Pop a saved register off the stack. */
1514 #define POP_FAILURE_REG_OR_COUNT() \
1516 long pfreg = POP_FAILURE_INT (); \
1519 /* It's a counter. */ \
1520 /* Here, we discard `const', making re_match non-reentrant. */ \
1521 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1522 pfreg = POP_FAILURE_INT (); \
1523 STORE_NUMBER (ptr, pfreg); \
1524 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, pfreg); \
1528 regend[pfreg] = POP_FAILURE_POINTER (); \
1529 regstart[pfreg] = POP_FAILURE_POINTER (); \
1530 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1531 pfreg, regstart[pfreg], regend[pfreg]); \
1535 /* Check that we are not stuck in an infinite loop. */
1536 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1538 ssize_t failure = TOP_FAILURE_HANDLE (); \
1539 /* Check for infinite matching loops */ \
1540 while (failure > 0 \
1541 && (FAILURE_STR (failure) == string_place \
1542 || FAILURE_STR (failure) == NULL)) \
1544 assert (FAILURE_PAT (failure) >= bufp->buffer \
1545 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1546 if (FAILURE_PAT (failure) == pat_cur) \
1551 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1552 failure = NEXT_FAILURE_HANDLE(failure); \
1554 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1557 /* Push the information about the state we will need
1558 if we ever fail back to it.
1560 Requires variables fail_stack, regstart, regend and
1561 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1564 Does `return FAILURE_CODE' if runs out of memory. */
1566 #define PUSH_FAILURE_POINT(pattern, string_place) \
1568 char *destination; \
1569 /* Must be int, so when we don't save any registers, the arithmetic \
1570 of 0 + -1 isn't done as unsigned. */ \
1572 DEBUG_STATEMENT (nfailure_points_pushed++); \
1573 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1574 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1575 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1577 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1579 DEBUG_PRINT1 ("\n"); \
1581 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1582 PUSH_FAILURE_INT (fail_stack.frame); \
1584 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1585 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1586 DEBUG_PRINT1 ("'\n"); \
1587 PUSH_FAILURE_POINTER (string_place); \
1589 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1590 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1591 PUSH_FAILURE_POINTER (pattern); \
1593 /* Close the frame by moving the frame pointer past it. */ \
1594 fail_stack.frame = fail_stack.avail; \
1597 /* Estimate the size of data pushed by a typical failure stack entry.
1598 An estimate is all we need, because all we use this for
1599 is to choose a limit for how big to make the failure stack. */
1600 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1601 #define TYPICAL_FAILURE_SIZE 20
1603 /* How many items can still be added to the stack without overflowing it. */
1604 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1607 /* Pops what PUSH_FAIL_STACK pushes.
1609 We restore into the parameters, all of which should be lvalues:
1610 STR -- the saved data position.
1611 PAT -- the saved pattern position.
1612 REGSTART, REGEND -- arrays of string positions.
1614 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1615 `pend', `string1', `size1', `string2', and `size2'. */
1617 #define POP_FAILURE_POINT(str, pat) \
1619 assert (!FAIL_STACK_EMPTY ()); \
1621 /* Remove failure points and point to how many regs pushed. */ \
1622 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1623 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1624 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1626 /* Pop the saved registers. */ \
1627 while (fail_stack.frame < fail_stack.avail) \
1628 POP_FAILURE_REG_OR_COUNT (); \
1630 pat = POP_FAILURE_POINTER (); \
1631 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1632 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1634 /* If the saved string location is NULL, it came from an \
1635 on_failure_keep_string_jump opcode, and we want to throw away the \
1636 saved NULL, thus retaining our current position in the string. */ \
1637 str = POP_FAILURE_POINTER (); \
1638 DEBUG_PRINT2 (" Popping string %p: `", str); \
1639 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1640 DEBUG_PRINT1 ("'\n"); \
1642 fail_stack.frame = POP_FAILURE_INT (); \
1643 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1645 assert (fail_stack.avail >= 0); \
1646 assert (fail_stack.frame <= fail_stack.avail); \
1648 DEBUG_STATEMENT (nfailure_points_popped++); \
1649 } while (0) /* POP_FAILURE_POINT */
1653 /* Registers are set to a sentinel when they haven't yet matched. */
1654 #define REG_UNSET(e) ((e) == NULL)
1656 /* Subroutine declarations and macros for regex_compile. */
1658 static reg_errcode_t
regex_compile (re_char
*pattern
, size_t size
,
1659 reg_syntax_t syntax
,
1660 struct re_pattern_buffer
*bufp
);
1661 static void store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
);
1662 static void store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
);
1663 static void insert_op1 (re_opcode_t op
, unsigned char *loc
,
1664 int arg
, unsigned char *end
);
1665 static void insert_op2 (re_opcode_t op
, unsigned char *loc
,
1666 int arg1
, int arg2
, unsigned char *end
);
1667 static boolean
at_begline_loc_p (re_char
*pattern
, re_char
*p
,
1668 reg_syntax_t syntax
);
1669 static boolean
at_endline_loc_p (re_char
*p
, re_char
*pend
,
1670 reg_syntax_t syntax
);
1671 static re_char
*skip_one_char (re_char
*p
);
1672 static int analyse_first (re_char
*p
, re_char
*pend
,
1673 char *fastmap
, const int multibyte
);
1675 /* Fetch the next character in the uncompiled pattern, with no
1677 #define PATFETCH(c) \
1680 if (p == pend) return REG_EEND; \
1681 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1686 /* If `translate' is non-null, return translate[D], else just D. We
1687 cast the subscript to translate because some data is declared as
1688 `char *', to avoid warnings when a string constant is passed. But
1689 when we use a character as a subscript we must make it unsigned. */
1691 # define TRANSLATE(d) \
1692 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1696 /* Macros for outputting the compiled pattern into `buffer'. */
1698 /* If the buffer isn't allocated when it comes in, use this. */
1699 #define INIT_BUF_SIZE 32
1701 /* Make sure we have at least N more bytes of space in buffer. */
1702 #define GET_BUFFER_SPACE(n) \
1703 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1706 /* Make sure we have one more byte of buffer space and then add C to it. */
1707 #define BUF_PUSH(c) \
1709 GET_BUFFER_SPACE (1); \
1710 *b++ = (unsigned char) (c); \
1714 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1715 #define BUF_PUSH_2(c1, c2) \
1717 GET_BUFFER_SPACE (2); \
1718 *b++ = (unsigned char) (c1); \
1719 *b++ = (unsigned char) (c2); \
1723 /* Store a jump with opcode OP at LOC to location TO. We store a
1724 relative address offset by the three bytes the jump itself occupies. */
1725 #define STORE_JUMP(op, loc, to) \
1726 store_op1 (op, loc, (to) - (loc) - 3)
1728 /* Likewise, for a two-argument jump. */
1729 #define STORE_JUMP2(op, loc, to, arg) \
1730 store_op2 (op, loc, (to) - (loc) - 3, arg)
1732 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1733 #define INSERT_JUMP(op, loc, to) \
1734 insert_op1 (op, loc, (to) - (loc) - 3, b)
1736 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1737 #define INSERT_JUMP2(op, loc, to, arg) \
1738 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1741 /* This is not an arbitrary limit: the arguments which represent offsets
1742 into the pattern are two bytes long. So if 2^15 bytes turns out to
1743 be too small, many things would have to change. */
1744 # define MAX_BUF_SIZE (1L << 15)
1746 #if 0 /* This is when we thought it could be 2^16 bytes. */
1747 /* Any other compiler which, like MSC, has allocation limit below 2^16
1748 bytes will have to use approach similar to what was done below for
1749 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1750 reallocating to 0 bytes. Such thing is not going to work too well.
1751 You have been warned!! */
1752 #if defined _MSC_VER && !defined WIN32
1753 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1754 # define MAX_BUF_SIZE 65500L
1756 # define MAX_BUF_SIZE (1L << 16)
1760 /* Extend the buffer by twice its current size via realloc and
1761 reset the pointers that pointed into the old block to point to the
1762 correct places in the new one. If extending the buffer results in it
1763 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1764 #if __BOUNDED_POINTERS__
1765 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1766 # define MOVE_BUFFER_POINTER(P) \
1767 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1768 SET_HIGH_BOUND (P), \
1769 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1770 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1773 SET_HIGH_BOUND (b); \
1774 SET_HIGH_BOUND (begalt); \
1775 if (fixup_alt_jump) \
1776 SET_HIGH_BOUND (fixup_alt_jump); \
1778 SET_HIGH_BOUND (laststart); \
1779 if (pending_exact) \
1780 SET_HIGH_BOUND (pending_exact); \
1783 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1784 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1786 #define EXTEND_BUFFER() \
1788 unsigned char *old_buffer = bufp->buffer; \
1789 if (bufp->allocated == MAX_BUF_SIZE) \
1791 bufp->allocated <<= 1; \
1792 if (bufp->allocated > MAX_BUF_SIZE) \
1793 bufp->allocated = MAX_BUF_SIZE; \
1794 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1795 if (bufp->buffer == NULL) \
1796 return REG_ESPACE; \
1797 /* If the buffer moved, move all the pointers into it. */ \
1798 if (old_buffer != bufp->buffer) \
1800 unsigned char *new_buffer = bufp->buffer; \
1801 MOVE_BUFFER_POINTER (b); \
1802 MOVE_BUFFER_POINTER (begalt); \
1803 if (fixup_alt_jump) \
1804 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1806 MOVE_BUFFER_POINTER (laststart); \
1807 if (pending_exact) \
1808 MOVE_BUFFER_POINTER (pending_exact); \
1810 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1814 /* Since we have one byte reserved for the register number argument to
1815 {start,stop}_memory, the maximum number of groups we can report
1816 things about is what fits in that byte. */
1817 #define MAX_REGNUM 255
1819 /* But patterns can have more than `MAX_REGNUM' registers. We just
1820 ignore the excess. */
1821 typedef int regnum_t
;
1824 /* Macros for the compile stack. */
1826 /* Since offsets can go either forwards or backwards, this type needs to
1827 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1828 /* int may be not enough when sizeof(int) == 2. */
1829 typedef long pattern_offset_t
;
1833 pattern_offset_t begalt_offset
;
1834 pattern_offset_t fixup_alt_jump
;
1835 pattern_offset_t laststart_offset
;
1837 } compile_stack_elt_t
;
1842 compile_stack_elt_t
*stack
;
1844 size_t avail
; /* Offset of next open position. */
1845 } compile_stack_type
;
1848 #define INIT_COMPILE_STACK_SIZE 32
1850 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1851 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1853 /* The next available element. */
1854 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1856 /* Explicit quit checking is only used on NTemacs and whenever we
1857 use polling to process input events. */
1858 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1859 extern int immediate_quit
;
1860 # define IMMEDIATE_QUIT_CHECK \
1862 if (immediate_quit) QUIT; \
1865 # define IMMEDIATE_QUIT_CHECK ((void)0)
1868 /* Structure to manage work area for range table. */
1869 struct range_table_work_area
1871 int *table
; /* actual work area. */
1872 int allocated
; /* allocated size for work area in bytes. */
1873 int used
; /* actually used size in words. */
1874 int bits
; /* flag to record character classes */
1877 /* Make sure that WORK_AREA can hold more N multibyte characters.
1878 This is used only in set_image_of_range and set_image_of_range_1.
1879 It expects WORK_AREA to be a pointer.
1880 If it can't get the space, it returns from the surrounding function. */
1882 #define EXTEND_RANGE_TABLE(work_area, n) \
1884 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1886 extend_range_table_work_area (&work_area); \
1887 if ((work_area).table == 0) \
1888 return (REG_ESPACE); \
1892 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1893 (work_area).bits |= (bit)
1895 /* Bits used to implement the multibyte-part of the various character classes
1896 such as [:alnum:] in a charset's range table. */
1897 #define BIT_WORD 0x1
1898 #define BIT_LOWER 0x2
1899 #define BIT_PUNCT 0x4
1900 #define BIT_SPACE 0x8
1901 #define BIT_UPPER 0x10
1902 #define BIT_MULTIBYTE 0x20
1904 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1905 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1907 EXTEND_RANGE_TABLE ((work_area), 2); \
1908 (work_area).table[(work_area).used++] = (range_start); \
1909 (work_area).table[(work_area).used++] = (range_end); \
1912 /* Free allocated memory for WORK_AREA. */
1913 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1915 if ((work_area).table) \
1916 free ((work_area).table); \
1919 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1920 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1921 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1922 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1925 /* Set the bit for character C in a list. */
1926 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1931 /* Store characters in the range FROM to TO in the bitmap at B (for
1932 ASCII and unibyte characters) and WORK_AREA (for multibyte
1933 characters) while translating them and paying attention to the
1934 continuity of translated characters.
1936 Implementation note: It is better to implement these fairly big
1937 macros by a function, but it's not that easy because macros called
1938 in this macro assume various local variables already declared. */
1940 /* Both FROM and TO are ASCII characters. */
1942 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1946 for (C0 = (FROM); C0 <= (TO); C0++) \
1948 C1 = TRANSLATE (C0); \
1949 if (! ASCII_CHAR_P (C1)) \
1951 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1952 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1955 SET_LIST_BIT (C1); \
1960 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1962 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1964 int C0, C1, C2, I; \
1965 int USED = RANGE_TABLE_WORK_USED (work_area); \
1967 for (C0 = (FROM); C0 <= (TO); C0++) \
1969 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1970 if (CHAR_BYTE8_P (C1)) \
1971 SET_LIST_BIT (C0); \
1974 C2 = TRANSLATE (C1); \
1976 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1978 SET_LIST_BIT (C1); \
1979 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1981 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1982 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1984 if (C2 >= from - 1 && C2 <= to + 1) \
1986 if (C2 == from - 1) \
1987 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1988 else if (C2 == to + 1) \
1989 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1994 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
2000 /* Both FROM and TO are multibyte characters. */
2002 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2004 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2006 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2007 for (C0 = (FROM); C0 <= (TO); C0++) \
2009 C1 = TRANSLATE (C0); \
2010 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2011 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2012 SET_LIST_BIT (C2); \
2013 if (C1 >= (FROM) && C1 <= (TO)) \
2015 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2017 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2018 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2020 if (C1 >= from - 1 && C1 <= to + 1) \
2022 if (C1 == from - 1) \
2023 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2024 else if (C1 == to + 1) \
2025 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2030 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2036 /* Get the next unsigned number in the uncompiled pattern. */
2037 #define GET_UNSIGNED_NUMBER(num) \
2040 FREE_STACK_RETURN (REG_EBRACE); \
2044 while ('0' <= c && c <= '9') \
2050 num = num * 10 + c - '0'; \
2051 if (num / 10 != prev) \
2052 FREE_STACK_RETURN (REG_BADBR); \
2054 FREE_STACK_RETURN (REG_EBRACE); \
2060 #if ! WIDE_CHAR_SUPPORT
2062 /* Map a string to the char class it names (if any). */
2064 re_wctype (const re_char
*str
)
2066 const char *string
= (const char *) str
;
2067 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2068 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2069 else if (STREQ (string
, "word")) return RECC_WORD
;
2070 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2071 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2072 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2073 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2074 else if (STREQ (string
, "print")) return RECC_PRINT
;
2075 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2076 else if (STREQ (string
, "space")) return RECC_SPACE
;
2077 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2078 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2079 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2080 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2081 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2082 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2083 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2087 /* True if CH is in the char class CC. */
2089 re_iswctype (int ch
, re_wctype_t cc
)
2093 case RECC_ALNUM
: return ISALNUM (ch
) != 0;
2094 case RECC_ALPHA
: return ISALPHA (ch
) != 0;
2095 case RECC_BLANK
: return ISBLANK (ch
) != 0;
2096 case RECC_CNTRL
: return ISCNTRL (ch
) != 0;
2097 case RECC_DIGIT
: return ISDIGIT (ch
) != 0;
2098 case RECC_GRAPH
: return ISGRAPH (ch
) != 0;
2099 case RECC_LOWER
: return ISLOWER (ch
) != 0;
2100 case RECC_PRINT
: return ISPRINT (ch
) != 0;
2101 case RECC_PUNCT
: return ISPUNCT (ch
) != 0;
2102 case RECC_SPACE
: return ISSPACE (ch
) != 0;
2103 case RECC_UPPER
: return ISUPPER (ch
) != 0;
2104 case RECC_XDIGIT
: return ISXDIGIT (ch
) != 0;
2105 case RECC_ASCII
: return IS_REAL_ASCII (ch
) != 0;
2106 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2107 case RECC_UNIBYTE
: return ISUNIBYTE (ch
) != 0;
2108 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2109 case RECC_WORD
: return ISWORD (ch
) != 0;
2110 case RECC_ERROR
: return false;
2116 /* Return a bit-pattern to use in the range-table bits to match multibyte
2117 chars of class CC. */
2119 re_wctype_to_bit (re_wctype_t cc
)
2123 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2124 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2125 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2126 case RECC_LOWER
: return BIT_LOWER
;
2127 case RECC_UPPER
: return BIT_UPPER
;
2128 case RECC_PUNCT
: return BIT_PUNCT
;
2129 case RECC_SPACE
: return BIT_SPACE
;
2130 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2131 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2138 /* Filling in the work area of a range. */
2140 /* Actually extend the space in WORK_AREA. */
2143 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2145 work_area
->allocated
+= 16 * sizeof (int);
2146 if (work_area
->table
)
2148 = (int *) realloc (work_area
->table
, work_area
->allocated
);
2151 = (int *) malloc (work_area
->allocated
);
2157 /* Carefully find the ranges of codes that are equivalent
2158 under case conversion to the range start..end when passed through
2159 TRANSLATE. Handle the case where non-letters can come in between
2160 two upper-case letters (which happens in Latin-1).
2161 Also handle the case of groups of more than 2 case-equivalent chars.
2163 The basic method is to look at consecutive characters and see
2164 if they can form a run that can be handled as one.
2166 Returns -1 if successful, REG_ESPACE if ran out of space. */
2169 set_image_of_range_1 (struct range_table_work_area
*work_area
,
2170 re_wchar_t start
, re_wchar_t end
,
2171 RE_TRANSLATE_TYPE translate
)
2173 /* `one_case' indicates a character, or a run of characters,
2174 each of which is an isolate (no case-equivalents).
2175 This includes all ASCII non-letters.
2177 `two_case' indicates a character, or a run of characters,
2178 each of which has two case-equivalent forms.
2179 This includes all ASCII letters.
2181 `strange' indicates a character that has more than one
2184 enum case_type
{one_case
, two_case
, strange
};
2186 /* Describe the run that is in progress,
2187 which the next character can try to extend.
2188 If run_type is strange, that means there really is no run.
2189 If run_type is one_case, then run_start...run_end is the run.
2190 If run_type is two_case, then the run is run_start...run_end,
2191 and the case-equivalents end at run_eqv_end. */
2193 enum case_type run_type
= strange
;
2194 int run_start
, run_end
, run_eqv_end
;
2196 Lisp_Object eqv_table
;
2198 if (!RE_TRANSLATE_P (translate
))
2200 EXTEND_RANGE_TABLE (work_area
, 2);
2201 work_area
->table
[work_area
->used
++] = (start
);
2202 work_area
->table
[work_area
->used
++] = (end
);
2206 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2208 for (; start
<= end
; start
++)
2210 enum case_type this_type
;
2211 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2212 int minchar
, maxchar
;
2214 /* Classify this character */
2216 this_type
= one_case
;
2217 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2218 this_type
= two_case
;
2220 this_type
= strange
;
2223 minchar
= start
, maxchar
= eqv
;
2225 minchar
= eqv
, maxchar
= start
;
2227 /* Can this character extend the run in progress? */
2228 if (this_type
== strange
|| this_type
!= run_type
2229 || !(minchar
== run_end
+ 1
2230 && (run_type
== two_case
2231 ? maxchar
== run_eqv_end
+ 1 : 1)))
2234 Record each of its equivalent ranges. */
2235 if (run_type
== one_case
)
2237 EXTEND_RANGE_TABLE (work_area
, 2);
2238 work_area
->table
[work_area
->used
++] = run_start
;
2239 work_area
->table
[work_area
->used
++] = run_end
;
2241 else if (run_type
== two_case
)
2243 EXTEND_RANGE_TABLE (work_area
, 4);
2244 work_area
->table
[work_area
->used
++] = run_start
;
2245 work_area
->table
[work_area
->used
++] = run_end
;
2246 work_area
->table
[work_area
->used
++]
2247 = RE_TRANSLATE (eqv_table
, run_start
);
2248 work_area
->table
[work_area
->used
++]
2249 = RE_TRANSLATE (eqv_table
, run_end
);
2254 if (this_type
== strange
)
2256 /* For a strange character, add each of its equivalents, one
2257 by one. Don't start a range. */
2260 EXTEND_RANGE_TABLE (work_area
, 2);
2261 work_area
->table
[work_area
->used
++] = eqv
;
2262 work_area
->table
[work_area
->used
++] = eqv
;
2263 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2265 while (eqv
!= start
);
2268 /* Add this char to the run, or start a new run. */
2269 else if (run_type
== strange
)
2271 /* Initialize a new range. */
2272 run_type
= this_type
;
2275 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2279 /* Extend a running range. */
2281 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2285 /* If a run is still in progress at the end, finish it now
2286 by recording its equivalent ranges. */
2287 if (run_type
== one_case
)
2289 EXTEND_RANGE_TABLE (work_area
, 2);
2290 work_area
->table
[work_area
->used
++] = run_start
;
2291 work_area
->table
[work_area
->used
++] = run_end
;
2293 else if (run_type
== two_case
)
2295 EXTEND_RANGE_TABLE (work_area
, 4);
2296 work_area
->table
[work_area
->used
++] = run_start
;
2297 work_area
->table
[work_area
->used
++] = run_end
;
2298 work_area
->table
[work_area
->used
++]
2299 = RE_TRANSLATE (eqv_table
, run_start
);
2300 work_area
->table
[work_area
->used
++]
2301 = RE_TRANSLATE (eqv_table
, run_end
);
2309 /* Record the image of the range start..end when passed through
2310 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2311 and is not even necessarily contiguous.
2312 Normally we approximate it with the smallest contiguous range that contains
2313 all the chars we need. However, for Latin-1 we go to extra effort
2316 This function is not called for ASCII ranges.
2318 Returns -1 if successful, REG_ESPACE if ran out of space. */
2321 set_image_of_range (struct range_table_work_area
*work_area
,
2322 re_wchar_t start
, re_wchar_t end
,
2323 RE_TRANSLATE_TYPE translate
)
2325 re_wchar_t cmin
, cmax
;
2328 /* For Latin-1 ranges, use set_image_of_range_1
2329 to get proper handling of ranges that include letters and nonletters.
2330 For a range that includes the whole of Latin-1, this is not necessary.
2331 For other character sets, we don't bother to get this right. */
2332 if (RE_TRANSLATE_P (translate
) && start
< 04400
2333 && !(start
< 04200 && end
>= 04377))
2340 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2350 EXTEND_RANGE_TABLE (work_area
, 2);
2351 work_area
->table
[work_area
->used
++] = (start
);
2352 work_area
->table
[work_area
->used
++] = (end
);
2354 cmin
= -1, cmax
= -1;
2356 if (RE_TRANSLATE_P (translate
))
2360 for (ch
= start
; ch
<= end
; ch
++)
2362 re_wchar_t c
= TRANSLATE (ch
);
2363 if (! (start
<= c
&& c
<= end
))
2369 cmin
= MIN (cmin
, c
);
2370 cmax
= MAX (cmax
, c
);
2377 EXTEND_RANGE_TABLE (work_area
, 2);
2378 work_area
->table
[work_area
->used
++] = (cmin
);
2379 work_area
->table
[work_area
->used
++] = (cmax
);
2387 #ifndef MATCH_MAY_ALLOCATE
2389 /* If we cannot allocate large objects within re_match_2_internal,
2390 we make the fail stack and register vectors global.
2391 The fail stack, we grow to the maximum size when a regexp
2393 The register vectors, we adjust in size each time we
2394 compile a regexp, according to the number of registers it needs. */
2396 static fail_stack_type fail_stack
;
2398 /* Size with which the following vectors are currently allocated.
2399 That is so we can make them bigger as needed,
2400 but never make them smaller. */
2401 static int regs_allocated_size
;
2403 static re_char
** regstart
, ** regend
;
2404 static re_char
**best_regstart
, **best_regend
;
2406 /* Make the register vectors big enough for NUM_REGS registers,
2407 but don't make them smaller. */
2410 regex_grow_registers (int num_regs
)
2412 if (num_regs
> regs_allocated_size
)
2414 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2415 RETALLOC_IF (regend
, num_regs
, re_char
*);
2416 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2417 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2419 regs_allocated_size
= num_regs
;
2423 #endif /* not MATCH_MAY_ALLOCATE */
2425 static boolean
group_in_compile_stack (compile_stack_type compile_stack
,
2428 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2429 Returns one of error codes defined in `regex.h', or zero for success.
2431 Assumes the `allocated' (and perhaps `buffer') and `translate'
2432 fields are set in BUFP on entry.
2434 If it succeeds, results are put in BUFP (if it returns an error, the
2435 contents of BUFP are undefined):
2436 `buffer' is the compiled pattern;
2437 `syntax' is set to SYNTAX;
2438 `used' is set to the length of the compiled pattern;
2439 `fastmap_accurate' is zero;
2440 `re_nsub' is the number of subexpressions in PATTERN;
2441 `not_bol' and `not_eol' are zero;
2443 The `fastmap' field is neither examined nor set. */
2445 /* Insert the `jump' from the end of last alternative to "here".
2446 The space for the jump has already been allocated. */
2447 #define FIXUP_ALT_JUMP() \
2449 if (fixup_alt_jump) \
2450 STORE_JUMP (jump, fixup_alt_jump, b); \
2454 /* Return, freeing storage we allocated. */
2455 #define FREE_STACK_RETURN(value) \
2457 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2458 free (compile_stack.stack); \
2462 static reg_errcode_t
2463 regex_compile (const re_char
*pattern
, size_t size
, reg_syntax_t syntax
, struct re_pattern_buffer
*bufp
)
2465 /* We fetch characters from PATTERN here. */
2466 register re_wchar_t c
, c1
;
2468 /* Points to the end of the buffer, where we should append. */
2469 register unsigned char *b
;
2471 /* Keeps track of unclosed groups. */
2472 compile_stack_type compile_stack
;
2474 /* Points to the current (ending) position in the pattern. */
2476 /* `const' makes AIX compiler fail. */
2477 unsigned char *p
= pattern
;
2479 re_char
*p
= pattern
;
2481 re_char
*pend
= pattern
+ size
;
2483 /* How to translate the characters in the pattern. */
2484 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2486 /* Address of the count-byte of the most recently inserted `exactn'
2487 command. This makes it possible to tell if a new exact-match
2488 character can be added to that command or if the character requires
2489 a new `exactn' command. */
2490 unsigned char *pending_exact
= 0;
2492 /* Address of start of the most recently finished expression.
2493 This tells, e.g., postfix * where to find the start of its
2494 operand. Reset at the beginning of groups and alternatives. */
2495 unsigned char *laststart
= 0;
2497 /* Address of beginning of regexp, or inside of last group. */
2498 unsigned char *begalt
;
2500 /* Place in the uncompiled pattern (i.e., the {) to
2501 which to go back if the interval is invalid. */
2502 re_char
*beg_interval
;
2504 /* Address of the place where a forward jump should go to the end of
2505 the containing expression. Each alternative of an `or' -- except the
2506 last -- ends with a forward jump of this sort. */
2507 unsigned char *fixup_alt_jump
= 0;
2509 /* Work area for range table of charset. */
2510 struct range_table_work_area range_table_work
;
2512 /* If the object matched can contain multibyte characters. */
2513 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2515 /* Nonzero if we have pushed down into a subpattern. */
2516 int in_subpattern
= 0;
2518 /* These hold the values of p, pattern, and pend from the main
2519 pattern when we have pushed into a subpattern. */
2520 re_char
*main_p
IF_LINT (= NULL
);
2521 re_char
*main_pattern
IF_LINT (= NULL
);
2522 re_char
*main_pend
IF_LINT (= NULL
);
2526 DEBUG_PRINT1 ("\nCompiling pattern: ");
2529 unsigned debug_count
;
2531 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2532 putchar (pattern
[debug_count
]);
2537 /* Initialize the compile stack. */
2538 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2539 if (compile_stack
.stack
== NULL
)
2542 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2543 compile_stack
.avail
= 0;
2545 range_table_work
.table
= 0;
2546 range_table_work
.allocated
= 0;
2548 /* Initialize the pattern buffer. */
2549 bufp
->syntax
= syntax
;
2550 bufp
->fastmap_accurate
= 0;
2551 bufp
->not_bol
= bufp
->not_eol
= 0;
2552 bufp
->used_syntax
= 0;
2554 /* Set `used' to zero, so that if we return an error, the pattern
2555 printer (for debugging) will think there's no pattern. We reset it
2559 /* Always count groups, whether or not bufp->no_sub is set. */
2562 #if !defined emacs && !defined SYNTAX_TABLE
2563 /* Initialize the syntax table. */
2564 init_syntax_once ();
2567 if (bufp
->allocated
== 0)
2570 { /* If zero allocated, but buffer is non-null, try to realloc
2571 enough space. This loses if buffer's address is bogus, but
2572 that is the user's responsibility. */
2573 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2576 { /* Caller did not allocate a buffer. Do it for them. */
2577 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2579 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2581 bufp
->allocated
= INIT_BUF_SIZE
;
2584 begalt
= b
= bufp
->buffer
;
2586 /* Loop through the uncompiled pattern until we're at the end. */
2591 /* If this is the end of an included regexp,
2592 pop back to the main regexp and try again. */
2596 pattern
= main_pattern
;
2601 /* If this is the end of the main regexp, we are done. */
2613 /* If there's no special whitespace regexp, treat
2614 spaces normally. And don't try to do this recursively. */
2615 if (!whitespace_regexp
|| in_subpattern
)
2618 /* Peek past following spaces. */
2625 /* If the spaces are followed by a repetition op,
2626 treat them normally. */
2628 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2629 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2632 /* Replace the spaces with the whitespace regexp. */
2636 main_pattern
= pattern
;
2637 p
= pattern
= whitespace_regexp
;
2638 pend
= p
+ strlen ((const char *) p
);
2644 if ( /* If at start of pattern, it's an operator. */
2646 /* If context independent, it's an operator. */
2647 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2648 /* Otherwise, depends on what's come before. */
2649 || at_begline_loc_p (pattern
, p
, syntax
))
2650 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2659 if ( /* If at end of pattern, it's an operator. */
2661 /* If context independent, it's an operator. */
2662 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2663 /* Otherwise, depends on what's next. */
2664 || at_endline_loc_p (p
, pend
, syntax
))
2665 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2674 if ((syntax
& RE_BK_PLUS_QM
)
2675 || (syntax
& RE_LIMITED_OPS
))
2679 /* If there is no previous pattern... */
2682 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2683 FREE_STACK_RETURN (REG_BADRPT
);
2684 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2689 /* 1 means zero (many) matches is allowed. */
2690 boolean zero_times_ok
= 0, many_times_ok
= 0;
2693 /* If there is a sequence of repetition chars, collapse it
2694 down to just one (the right one). We can't combine
2695 interval operators with these because of, e.g., `a{2}*',
2696 which should only match an even number of `a's. */
2700 if ((syntax
& RE_FRUGAL
)
2701 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2705 zero_times_ok
|= c
!= '+';
2706 many_times_ok
|= c
!= '?';
2712 || (!(syntax
& RE_BK_PLUS_QM
)
2713 && (*p
== '+' || *p
== '?')))
2715 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2718 FREE_STACK_RETURN (REG_EESCAPE
);
2719 if (p
[1] == '+' || p
[1] == '?')
2720 PATFETCH (c
); /* Gobble up the backslash. */
2726 /* If we get here, we found another repeat character. */
2730 /* Star, etc. applied to an empty pattern is equivalent
2731 to an empty pattern. */
2732 if (!laststart
|| laststart
== b
)
2735 /* Now we know whether or not zero matches is allowed
2736 and also whether or not two or more matches is allowed. */
2741 boolean simple
= skip_one_char (laststart
) == b
;
2742 size_t startoffset
= 0;
2744 /* Check if the loop can match the empty string. */
2745 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2746 ? on_failure_jump
: on_failure_jump_loop
;
2747 assert (skip_one_char (laststart
) <= b
);
2749 if (!zero_times_ok
&& simple
)
2750 { /* Since simple * loops can be made faster by using
2751 on_failure_keep_string_jump, we turn simple P+
2752 into PP* if P is simple. */
2753 unsigned char *p1
, *p2
;
2754 startoffset
= b
- laststart
;
2755 GET_BUFFER_SPACE (startoffset
);
2756 p1
= b
; p2
= laststart
;
2762 GET_BUFFER_SPACE (6);
2765 STORE_JUMP (ofj
, b
, b
+ 6);
2767 /* Simple * loops can use on_failure_keep_string_jump
2768 depending on what follows. But since we don't know
2769 that yet, we leave the decision up to
2770 on_failure_jump_smart. */
2771 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2772 laststart
+ startoffset
, b
+ 6);
2774 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2779 /* A simple ? pattern. */
2780 assert (zero_times_ok
);
2781 GET_BUFFER_SPACE (3);
2782 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2786 else /* not greedy */
2787 { /* I wish the greedy and non-greedy cases could be merged. */
2789 GET_BUFFER_SPACE (7); /* We might use less. */
2792 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2794 /* The non-greedy multiple match looks like
2795 a repeat..until: we only need a conditional jump
2796 at the end of the loop. */
2797 if (emptyp
) BUF_PUSH (no_op
);
2798 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2799 : on_failure_jump
, b
, laststart
);
2803 /* The repeat...until naturally matches one or more.
2804 To also match zero times, we need to first jump to
2805 the end of the loop (its conditional jump). */
2806 INSERT_JUMP (jump
, laststart
, b
);
2812 /* non-greedy a?? */
2813 INSERT_JUMP (jump
, laststart
, b
+ 3);
2815 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2834 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2836 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2838 /* Ensure that we have enough space to push a charset: the
2839 opcode, the length count, and the bitset; 34 bytes in all. */
2840 GET_BUFFER_SPACE (34);
2844 /* We test `*p == '^' twice, instead of using an if
2845 statement, so we only need one BUF_PUSH. */
2846 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2850 /* Remember the first position in the bracket expression. */
2853 /* Push the number of bytes in the bitmap. */
2854 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2856 /* Clear the whole map. */
2857 memset (b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2859 /* charset_not matches newline according to a syntax bit. */
2860 if ((re_opcode_t
) b
[-2] == charset_not
2861 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2862 SET_LIST_BIT ('\n');
2864 /* Read in characters and ranges, setting map bits. */
2867 boolean escaped_char
= false;
2868 const unsigned char *p2
= p
;
2871 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2873 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2874 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2875 So the translation is done later in a loop. Example:
2876 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2879 /* \ might escape characters inside [...] and [^...]. */
2880 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2882 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2885 escaped_char
= true;
2889 /* Could be the end of the bracket expression. If it's
2890 not (i.e., when the bracket expression is `[]' so
2891 far), the ']' character bit gets set way below. */
2892 if (c
== ']' && p2
!= p1
)
2896 /* See if we're at the beginning of a possible character
2899 if (!escaped_char
&&
2900 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2902 /* Leave room for the null. */
2903 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2904 const unsigned char *class_beg
;
2910 /* If pattern is `[[:'. */
2911 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2916 if ((c
== ':' && *p
== ']') || p
== pend
)
2918 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2921 /* This is in any case an invalid class name. */
2926 /* If isn't a word bracketed by `[:' and `:]':
2927 undo the ending character, the letters, and
2928 leave the leading `:' and `[' (but set bits for
2930 if (c
== ':' && *p
== ']')
2932 re_wctype_t cc
= re_wctype (str
);
2935 FREE_STACK_RETURN (REG_ECTYPE
);
2937 /* Throw away the ] at the end of the character
2941 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2944 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
2945 if (re_iswctype (btowc (ch
), cc
))
2948 if (c
< (1 << BYTEWIDTH
))
2952 /* Most character classes in a multibyte match
2953 just set a flag. Exceptions are is_blank,
2954 is_digit, is_cntrl, and is_xdigit, since
2955 they can only match ASCII characters. We
2956 don't need to handle them for multibyte.
2957 They are distinguished by a negative wctype. */
2959 /* Setup the gl_state object to its buffer-defined
2960 value. This hardcodes the buffer-global
2961 syntax-table for ASCII chars, while the other chars
2962 will obey syntax-table properties. It's not ideal,
2963 but it's the way it's been done until now. */
2964 SETUP_BUFFER_SYNTAX_TABLE ();
2966 for (ch
= 0; ch
< 256; ++ch
)
2968 c
= RE_CHAR_TO_MULTIBYTE (ch
);
2969 if (! CHAR_BYTE8_P (c
)
2970 && re_iswctype (c
, cc
))
2976 if (ASCII_CHAR_P (c1
))
2978 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
2982 SET_RANGE_TABLE_WORK_AREA_BIT
2983 (range_table_work
, re_wctype_to_bit (cc
));
2985 /* In most cases the matching rule for char classes
2986 only uses the syntax table for multibyte chars,
2987 so that the content of the syntax-table it is not
2988 hardcoded in the range_table. SPACE and WORD are
2989 the two exceptions. */
2990 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
2991 bufp
->used_syntax
= 1;
2993 /* Repeat the loop. */
2998 /* Go back to right after the "[:". */
3002 /* Because the `:' may starts the range, we
3003 can't simply set bit and repeat the loop.
3004 Instead, just set it to C and handle below. */
3009 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
3012 /* Discard the `-'. */
3015 /* Fetch the character which ends the range. */
3018 if (CHAR_BYTE8_P (c1
)
3019 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
3020 /* Treat the range from a multibyte character to
3021 raw-byte character as empty. */
3026 /* Range from C to C. */
3031 if (syntax
& RE_NO_EMPTY_RANGES
)
3032 FREE_STACK_RETURN (REG_ERANGEX
);
3033 /* Else, repeat the loop. */
3038 /* Set the range into bitmap */
3039 for (; c
<= c1
; c
++)
3042 if (ch
< (1 << BYTEWIDTH
))
3049 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
3051 if (CHAR_BYTE8_P (c1
))
3052 c
= BYTE8_TO_CHAR (128);
3056 if (CHAR_BYTE8_P (c
))
3058 c
= CHAR_TO_BYTE8 (c
);
3059 c1
= CHAR_TO_BYTE8 (c1
);
3060 for (; c
<= c1
; c
++)
3065 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
3069 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
3076 /* Discard any (non)matching list bytes that are all 0 at the
3077 end of the map. Decrease the map-length byte too. */
3078 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3082 /* Build real range table from work area. */
3083 if (RANGE_TABLE_WORK_USED (range_table_work
)
3084 || RANGE_TABLE_WORK_BITS (range_table_work
))
3087 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3089 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3090 bytes for flags, two for COUNT, and three bytes for
3092 GET_BUFFER_SPACE (4 + used
* 3);
3094 /* Indicate the existence of range table. */
3095 laststart
[1] |= 0x80;
3097 /* Store the character class flag bits into the range table.
3098 If not in emacs, these flag bits are always 0. */
3099 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3100 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3102 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3103 for (i
= 0; i
< used
; i
++)
3104 STORE_CHARACTER_AND_INCR
3105 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3112 if (syntax
& RE_NO_BK_PARENS
)
3119 if (syntax
& RE_NO_BK_PARENS
)
3126 if (syntax
& RE_NEWLINE_ALT
)
3133 if (syntax
& RE_NO_BK_VBAR
)
3140 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3141 goto handle_interval
;
3147 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3149 /* Do not translate the character after the \, so that we can
3150 distinguish, e.g., \B from \b, even if we normally would
3151 translate, e.g., B to b. */
3157 if (syntax
& RE_NO_BK_PARENS
)
3158 goto normal_backslash
;
3163 regnum_t regnum
= 0;
3166 /* Look for a special (?...) construct */
3167 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3169 PATFETCH (c
); /* Gobble up the '?'. */
3175 case ':': shy
= 1; break;
3177 /* An explicitly specified regnum must start
3180 FREE_STACK_RETURN (REG_BADPAT
);
3181 case '1': case '2': case '3': case '4':
3182 case '5': case '6': case '7': case '8': case '9':
3183 regnum
= 10*regnum
+ (c
- '0'); break;
3185 /* Only (?:...) is supported right now. */
3186 FREE_STACK_RETURN (REG_BADPAT
);
3193 regnum
= ++bufp
->re_nsub
;
3195 { /* It's actually not shy, but explicitly numbered. */
3197 if (regnum
> bufp
->re_nsub
)
3198 bufp
->re_nsub
= regnum
;
3199 else if (regnum
> bufp
->re_nsub
3200 /* Ideally, we'd want to check that the specified
3201 group can't have matched (i.e. all subgroups
3202 using the same regnum are in other branches of
3203 OR patterns), but we don't currently keep track
3204 of enough info to do that easily. */
3205 || group_in_compile_stack (compile_stack
, regnum
))
3206 FREE_STACK_RETURN (REG_BADPAT
);
3209 /* It's really shy. */
3210 regnum
= - bufp
->re_nsub
;
3212 if (COMPILE_STACK_FULL
)
3214 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3215 compile_stack_elt_t
);
3216 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3218 compile_stack
.size
<<= 1;
3221 /* These are the values to restore when we hit end of this
3222 group. They are all relative offsets, so that if the
3223 whole pattern moves because of realloc, they will still
3225 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3226 COMPILE_STACK_TOP
.fixup_alt_jump
3227 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3228 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3229 COMPILE_STACK_TOP
.regnum
= regnum
;
3231 /* Do not push a start_memory for groups beyond the last one
3232 we can represent in the compiled pattern. */
3233 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3234 BUF_PUSH_2 (start_memory
, regnum
);
3236 compile_stack
.avail
++;
3241 /* If we've reached MAX_REGNUM groups, then this open
3242 won't actually generate any code, so we'll have to
3243 clear pending_exact explicitly. */
3249 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3251 if (COMPILE_STACK_EMPTY
)
3253 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3254 goto normal_backslash
;
3256 FREE_STACK_RETURN (REG_ERPAREN
);
3262 /* See similar code for backslashed left paren above. */
3263 if (COMPILE_STACK_EMPTY
)
3265 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3268 FREE_STACK_RETURN (REG_ERPAREN
);
3271 /* Since we just checked for an empty stack above, this
3272 ``can't happen''. */
3273 assert (compile_stack
.avail
!= 0);
3275 /* We don't just want to restore into `regnum', because
3276 later groups should continue to be numbered higher,
3277 as in `(ab)c(de)' -- the second group is #2. */
3280 compile_stack
.avail
--;
3281 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3283 = COMPILE_STACK_TOP
.fixup_alt_jump
3284 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3286 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3287 regnum
= COMPILE_STACK_TOP
.regnum
;
3288 /* If we've reached MAX_REGNUM groups, then this open
3289 won't actually generate any code, so we'll have to
3290 clear pending_exact explicitly. */
3293 /* We're at the end of the group, so now we know how many
3294 groups were inside this one. */
3295 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3296 BUF_PUSH_2 (stop_memory
, regnum
);
3301 case '|': /* `\|'. */
3302 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3303 goto normal_backslash
;
3305 if (syntax
& RE_LIMITED_OPS
)
3308 /* Insert before the previous alternative a jump which
3309 jumps to this alternative if the former fails. */
3310 GET_BUFFER_SPACE (3);
3311 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3315 /* The alternative before this one has a jump after it
3316 which gets executed if it gets matched. Adjust that
3317 jump so it will jump to this alternative's analogous
3318 jump (put in below, which in turn will jump to the next
3319 (if any) alternative's such jump, etc.). The last such
3320 jump jumps to the correct final destination. A picture:
3326 If we are at `b', then fixup_alt_jump right now points to a
3327 three-byte space after `a'. We'll put in the jump, set
3328 fixup_alt_jump to right after `b', and leave behind three
3329 bytes which we'll fill in when we get to after `c'. */
3333 /* Mark and leave space for a jump after this alternative,
3334 to be filled in later either by next alternative or
3335 when know we're at the end of a series of alternatives. */
3337 GET_BUFFER_SPACE (3);
3346 /* If \{ is a literal. */
3347 if (!(syntax
& RE_INTERVALS
)
3348 /* If we're at `\{' and it's not the open-interval
3350 || (syntax
& RE_NO_BK_BRACES
))
3351 goto normal_backslash
;
3355 /* If got here, then the syntax allows intervals. */
3357 /* At least (most) this many matches must be made. */
3358 int lower_bound
= 0, upper_bound
= -1;
3362 GET_UNSIGNED_NUMBER (lower_bound
);
3365 GET_UNSIGNED_NUMBER (upper_bound
);
3367 /* Interval such as `{1}' => match exactly once. */
3368 upper_bound
= lower_bound
;
3370 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3371 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3372 FREE_STACK_RETURN (REG_BADBR
);
3374 if (!(syntax
& RE_NO_BK_BRACES
))
3377 FREE_STACK_RETURN (REG_BADBR
);
3379 FREE_STACK_RETURN (REG_EESCAPE
);
3384 FREE_STACK_RETURN (REG_BADBR
);
3386 /* We just parsed a valid interval. */
3388 /* If it's invalid to have no preceding re. */
3391 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3392 FREE_STACK_RETURN (REG_BADRPT
);
3393 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3396 goto unfetch_interval
;
3399 if (upper_bound
== 0)
3400 /* If the upper bound is zero, just drop the sub pattern
3403 else if (lower_bound
== 1 && upper_bound
== 1)
3404 /* Just match it once: nothing to do here. */
3407 /* Otherwise, we have a nontrivial interval. When
3408 we're all done, the pattern will look like:
3409 set_number_at <jump count> <upper bound>
3410 set_number_at <succeed_n count> <lower bound>
3411 succeed_n <after jump addr> <succeed_n count>
3413 jump_n <succeed_n addr> <jump count>
3414 (The upper bound and `jump_n' are omitted if
3415 `upper_bound' is 1, though.) */
3417 { /* If the upper bound is > 1, we need to insert
3418 more at the end of the loop. */
3419 unsigned int nbytes
= (upper_bound
< 0 ? 3
3420 : upper_bound
> 1 ? 5 : 0);
3421 unsigned int startoffset
= 0;
3423 GET_BUFFER_SPACE (20); /* We might use less. */
3425 if (lower_bound
== 0)
3427 /* A succeed_n that starts with 0 is really a
3428 a simple on_failure_jump_loop. */
3429 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3435 /* Initialize lower bound of the `succeed_n', even
3436 though it will be set during matching by its
3437 attendant `set_number_at' (inserted next),
3438 because `re_compile_fastmap' needs to know.
3439 Jump to the `jump_n' we might insert below. */
3440 INSERT_JUMP2 (succeed_n
, laststart
,
3445 /* Code to initialize the lower bound. Insert
3446 before the `succeed_n'. The `5' is the last two
3447 bytes of this `set_number_at', plus 3 bytes of
3448 the following `succeed_n'. */
3449 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3454 if (upper_bound
< 0)
3456 /* A negative upper bound stands for infinity,
3457 in which case it degenerates to a plain jump. */
3458 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3461 else if (upper_bound
> 1)
3462 { /* More than one repetition is allowed, so
3463 append a backward jump to the `succeed_n'
3464 that starts this interval.
3466 When we've reached this during matching,
3467 we'll have matched the interval once, so
3468 jump back only `upper_bound - 1' times. */
3469 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3473 /* The location we want to set is the second
3474 parameter of the `jump_n'; that is `b-2' as
3475 an absolute address. `laststart' will be
3476 the `set_number_at' we're about to insert;
3477 `laststart+3' the number to set, the source
3478 for the relative address. But we are
3479 inserting into the middle of the pattern --
3480 so everything is getting moved up by 5.
3481 Conclusion: (b - 2) - (laststart + 3) + 5,
3482 i.e., b - laststart.
3484 We insert this at the beginning of the loop
3485 so that if we fail during matching, we'll
3486 reinitialize the bounds. */
3487 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3488 upper_bound
- 1, b
);
3493 beg_interval
= NULL
;
3498 /* If an invalid interval, match the characters as literals. */
3499 assert (beg_interval
);
3501 beg_interval
= NULL
;
3503 /* normal_char and normal_backslash need `c'. */
3506 if (!(syntax
& RE_NO_BK_BRACES
))
3508 assert (p
> pattern
&& p
[-1] == '\\');
3509 goto normal_backslash
;
3515 /* There is no way to specify the before_dot and after_dot
3516 operators. rms says this is ok. --karl */
3524 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3530 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3536 BUF_PUSH_2 (categoryspec
, c
);
3542 BUF_PUSH_2 (notcategoryspec
, c
);
3548 if (syntax
& RE_NO_GNU_OPS
)
3551 BUF_PUSH_2 (syntaxspec
, Sword
);
3556 if (syntax
& RE_NO_GNU_OPS
)
3559 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3564 if (syntax
& RE_NO_GNU_OPS
)
3570 if (syntax
& RE_NO_GNU_OPS
)
3576 if (syntax
& RE_NO_GNU_OPS
)
3585 FREE_STACK_RETURN (REG_BADPAT
);
3589 if (syntax
& RE_NO_GNU_OPS
)
3591 BUF_PUSH (wordbound
);
3595 if (syntax
& RE_NO_GNU_OPS
)
3597 BUF_PUSH (notwordbound
);
3601 if (syntax
& RE_NO_GNU_OPS
)
3607 if (syntax
& RE_NO_GNU_OPS
)
3612 case '1': case '2': case '3': case '4': case '5':
3613 case '6': case '7': case '8': case '9':
3617 if (syntax
& RE_NO_BK_REFS
)
3618 goto normal_backslash
;
3622 if (reg
> bufp
->re_nsub
|| reg
< 1
3623 /* Can't back reference to a subexp before its end. */
3624 || group_in_compile_stack (compile_stack
, reg
))
3625 FREE_STACK_RETURN (REG_ESUBREG
);
3628 BUF_PUSH_2 (duplicate
, reg
);
3635 if (syntax
& RE_BK_PLUS_QM
)
3638 goto normal_backslash
;
3642 /* You might think it would be useful for \ to mean
3643 not to translate; but if we don't translate it
3644 it will never match anything. */
3651 /* Expects the character in `c'. */
3653 /* If no exactn currently being built. */
3656 /* If last exactn not at current position. */
3657 || pending_exact
+ *pending_exact
+ 1 != b
3659 /* We have only one byte following the exactn for the count. */
3660 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3662 /* If followed by a repetition operator. */
3663 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3664 || ((syntax
& RE_BK_PLUS_QM
)
3665 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3666 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3667 || ((syntax
& RE_INTERVALS
)
3668 && ((syntax
& RE_NO_BK_BRACES
)
3669 ? p
!= pend
&& *p
== '{'
3670 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3672 /* Start building a new exactn. */
3676 BUF_PUSH_2 (exactn
, 0);
3677 pending_exact
= b
- 1;
3680 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3687 len
= CHAR_STRING (c
, b
);
3692 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3693 if (! CHAR_BYTE8_P (c1
))
3695 re_wchar_t c2
= TRANSLATE (c1
);
3697 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3703 (*pending_exact
) += len
;
3708 } /* while p != pend */
3711 /* Through the pattern now. */
3715 if (!COMPILE_STACK_EMPTY
)
3716 FREE_STACK_RETURN (REG_EPAREN
);
3718 /* If we don't want backtracking, force success
3719 the first time we reach the end of the compiled pattern. */
3720 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3723 /* We have succeeded; set the length of the buffer. */
3724 bufp
->used
= b
- bufp
->buffer
;
3729 re_compile_fastmap (bufp
);
3730 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3731 print_compiled_pattern (bufp
);
3736 #ifndef MATCH_MAY_ALLOCATE
3737 /* Initialize the failure stack to the largest possible stack. This
3738 isn't necessary unless we're trying to avoid calling alloca in
3739 the search and match routines. */
3741 int num_regs
= bufp
->re_nsub
+ 1;
3743 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3745 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3747 if (! fail_stack
.stack
)
3749 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3750 * sizeof (fail_stack_elt_t
));
3753 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3755 * sizeof (fail_stack_elt_t
)));
3758 regex_grow_registers (num_regs
);
3760 #endif /* not MATCH_MAY_ALLOCATE */
3762 FREE_STACK_RETURN (REG_NOERROR
);
3763 } /* regex_compile */
3765 /* Subroutines for `regex_compile'. */
3767 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3770 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3772 *loc
= (unsigned char) op
;
3773 STORE_NUMBER (loc
+ 1, arg
);
3777 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3780 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3782 *loc
= (unsigned char) op
;
3783 STORE_NUMBER (loc
+ 1, arg1
);
3784 STORE_NUMBER (loc
+ 3, arg2
);
3788 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3789 for OP followed by two-byte integer parameter ARG. */
3792 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3794 register unsigned char *pfrom
= end
;
3795 register unsigned char *pto
= end
+ 3;
3797 while (pfrom
!= loc
)
3800 store_op1 (op
, loc
, arg
);
3804 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3807 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3809 register unsigned char *pfrom
= end
;
3810 register unsigned char *pto
= end
+ 5;
3812 while (pfrom
!= loc
)
3815 store_op2 (op
, loc
, arg1
, arg2
);
3819 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3820 after an alternative or a begin-subexpression. We assume there is at
3821 least one character before the ^. */
3824 at_begline_loc_p (const re_char
*pattern
, const re_char
*p
, reg_syntax_t syntax
)
3826 re_char
*prev
= p
- 2;
3827 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3830 /* After a subexpression? */
3831 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3832 /* After an alternative? */
3833 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3834 /* After a shy subexpression? */
3835 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3836 && prev
[-1] == '?' && prev
[-2] == '('
3837 && (syntax
& RE_NO_BK_PARENS
3838 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3842 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3843 at least one character after the $, i.e., `P < PEND'. */
3846 at_endline_loc_p (const re_char
*p
, const re_char
*pend
, reg_syntax_t syntax
)
3849 boolean next_backslash
= *next
== '\\';
3850 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3853 /* Before a subexpression? */
3854 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3855 : next_backslash
&& next_next
&& *next_next
== ')')
3856 /* Before an alternative? */
3857 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3858 : next_backslash
&& next_next
&& *next_next
== '|');
3862 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3863 false if it's not. */
3866 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3868 ssize_t this_element
;
3870 for (this_element
= compile_stack
.avail
- 1;
3873 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3880 If fastmap is non-NULL, go through the pattern and fill fastmap
3881 with all the possible leading chars. If fastmap is NULL, don't
3882 bother filling it up (obviously) and only return whether the
3883 pattern could potentially match the empty string.
3885 Return 1 if p..pend might match the empty string.
3886 Return 0 if p..pend matches at least one char.
3887 Return -1 if fastmap was not updated accurately. */
3890 analyse_first (const re_char
*p
, const re_char
*pend
, char *fastmap
, const int multibyte
)
3895 /* If all elements for base leading-codes in fastmap is set, this
3896 flag is set true. */
3897 boolean match_any_multibyte_characters
= false;
3901 /* The loop below works as follows:
3902 - It has a working-list kept in the PATTERN_STACK and which basically
3903 starts by only containing a pointer to the first operation.
3904 - If the opcode we're looking at is a match against some set of
3905 chars, then we add those chars to the fastmap and go on to the
3906 next work element from the worklist (done via `break').
3907 - If the opcode is a control operator on the other hand, we either
3908 ignore it (if it's meaningless at this point, such as `start_memory')
3909 or execute it (if it's a jump). If the jump has several destinations
3910 (i.e. `on_failure_jump'), then we push the other destination onto the
3912 We guarantee termination by ignoring backward jumps (more or less),
3913 so that `p' is monotonically increasing. More to the point, we
3914 never set `p' (or push) anything `<= p1'. */
3918 /* `p1' is used as a marker of how far back a `on_failure_jump'
3919 can go without being ignored. It is normally equal to `p'
3920 (which prevents any backward `on_failure_jump') except right
3921 after a plain `jump', to allow patterns such as:
3924 10: on_failure_jump 3
3925 as used for the *? operator. */
3928 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3934 /* If the first character has to match a backreference, that means
3935 that the group was empty (since it already matched). Since this
3936 is the only case that interests us here, we can assume that the
3937 backreference must match the empty string. */
3942 /* Following are the cases which match a character. These end
3948 /* If multibyte is nonzero, the first byte of each
3949 character is an ASCII or a leading code. Otherwise,
3950 each byte is a character. Thus, this works in both
3955 /* For the case of matching this unibyte regex
3956 against multibyte, we must set a leading code of
3957 the corresponding multibyte character. */
3958 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
3960 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
3967 /* We could put all the chars except for \n (and maybe \0)
3968 but we don't bother since it is generally not worth it. */
3969 if (!fastmap
) break;
3974 if (!fastmap
) break;
3976 /* Chars beyond end of bitmap are possible matches. */
3977 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3978 j
< (1 << BYTEWIDTH
); j
++)
3984 if (!fastmap
) break;
3985 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3986 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3988 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3992 if (/* Any leading code can possibly start a character
3993 which doesn't match the specified set of characters. */
3996 /* If we can match a character class, we can match any
3997 multibyte characters. */
3998 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3999 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
4002 if (match_any_multibyte_characters
== false)
4004 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4005 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4007 match_any_multibyte_characters
= true;
4011 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4012 && match_any_multibyte_characters
== false)
4014 /* Set fastmap[I] to 1 where I is a leading code of each
4015 multibyte character in the range table. */
4017 unsigned char lc1
, lc2
;
4019 /* Make P points the range table. `+ 2' is to skip flag
4020 bits for a character class. */
4021 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
4023 /* Extract the number of ranges in range table into COUNT. */
4024 EXTRACT_NUMBER_AND_INCR (count
, p
);
4025 for (; count
> 0; count
--, p
+= 3)
4027 /* Extract the start and end of each range. */
4028 EXTRACT_CHARACTER (c
, p
);
4029 lc1
= CHAR_LEADING_CODE (c
);
4031 EXTRACT_CHARACTER (c
, p
);
4032 lc2
= CHAR_LEADING_CODE (c
);
4033 for (j
= lc1
; j
<= lc2
; j
++)
4042 if (!fastmap
) break;
4044 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
4046 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4047 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4051 /* This match depends on text properties. These end with
4052 aborting optimizations. */
4056 case notcategoryspec
:
4057 if (!fastmap
) break;
4058 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4060 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
4061 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4064 /* Any leading code can possibly start a character which
4065 has or doesn't has the specified category. */
4066 if (match_any_multibyte_characters
== false)
4068 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4069 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4071 match_any_multibyte_characters
= true;
4075 /* All cases after this match the empty string. These end with
4097 EXTRACT_NUMBER_AND_INCR (j
, p
);
4099 /* Backward jumps can only go back to code that we've already
4100 visited. `re_compile' should make sure this is true. */
4103 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4105 case on_failure_jump
:
4106 case on_failure_keep_string_jump
:
4107 case on_failure_jump_loop
:
4108 case on_failure_jump_nastyloop
:
4109 case on_failure_jump_smart
:
4115 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4116 to jump back to "just after here". */
4119 case on_failure_jump
:
4120 case on_failure_keep_string_jump
:
4121 case on_failure_jump_nastyloop
:
4122 case on_failure_jump_loop
:
4123 case on_failure_jump_smart
:
4124 EXTRACT_NUMBER_AND_INCR (j
, p
);
4126 ; /* Backward jump to be ignored. */
4128 { /* We have to look down both arms.
4129 We first go down the "straight" path so as to minimize
4130 stack usage when going through alternatives. */
4131 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4139 /* This code simply does not properly handle forward jump_n. */
4140 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4142 /* jump_n can either jump or fall through. The (backward) jump
4143 case has already been handled, so we only need to look at the
4144 fallthrough case. */
4148 /* If N == 0, it should be an on_failure_jump_loop instead. */
4149 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4151 /* We only care about one iteration of the loop, so we don't
4152 need to consider the case where this behaves like an
4169 abort (); /* We have listed all the cases. */
4172 /* Getting here means we have found the possible starting
4173 characters for one path of the pattern -- and that the empty
4174 string does not match. We need not follow this path further. */
4178 /* We reached the end without matching anything. */
4181 } /* analyse_first */
4183 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4184 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4185 characters can start a string that matches the pattern. This fastmap
4186 is used by re_search to skip quickly over impossible starting points.
4188 Character codes above (1 << BYTEWIDTH) are not represented in the
4189 fastmap, but the leading codes are represented. Thus, the fastmap
4190 indicates which character sets could start a match.
4192 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4193 area as BUFP->fastmap.
4195 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4198 Returns 0 if we succeed, -2 if an internal error. */
4201 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4203 char *fastmap
= bufp
->fastmap
;
4206 assert (fastmap
&& bufp
->buffer
);
4208 memset (fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4209 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4211 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4212 fastmap
, RE_MULTIBYTE_P (bufp
));
4213 bufp
->can_be_null
= (analysis
!= 0);
4215 } /* re_compile_fastmap */
4217 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4218 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4219 this memory for recording register information. STARTS and ENDS
4220 must be allocated using the malloc library routine, and must each
4221 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4223 If NUM_REGS == 0, then subsequent matches should allocate their own
4226 Unless this function is called, the first search or match using
4227 PATTERN_BUFFER will allocate its own register data, without
4228 freeing the old data. */
4231 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4235 bufp
->regs_allocated
= REGS_REALLOCATE
;
4236 regs
->num_regs
= num_regs
;
4237 regs
->start
= starts
;
4242 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4244 regs
->start
= regs
->end
= (regoff_t
*) 0;
4247 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4249 /* Searching routines. */
4251 /* Like re_search_2, below, but only one string is specified, and
4252 doesn't let you say where to stop matching. */
4255 re_search (struct re_pattern_buffer
*bufp
, const char *string
, size_t size
,
4256 ssize_t startpos
, ssize_t range
, struct re_registers
*regs
)
4258 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4261 WEAK_ALIAS (__re_search
, re_search
)
4263 /* Head address of virtual concatenation of string. */
4264 #define HEAD_ADDR_VSTRING(P) \
4265 (((P) >= size1 ? string2 : string1))
4267 /* Address of POS in the concatenation of virtual string. */
4268 #define POS_ADDR_VSTRING(POS) \
4269 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4271 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4272 virtual concatenation of STRING1 and STRING2, starting first at index
4273 STARTPOS, then at STARTPOS + 1, and so on.
4275 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4277 RANGE is how far to scan while trying to match. RANGE = 0 means try
4278 only at STARTPOS; in general, the last start tried is STARTPOS +
4281 In REGS, return the indices of the virtual concatenation of STRING1
4282 and STRING2 that matched the entire BUFP->buffer and its contained
4285 Do not consider matching one past the index STOP in the virtual
4286 concatenation of STRING1 and STRING2.
4288 We return either the position in the strings at which the match was
4289 found, -1 if no match, or -2 if error (such as failure
4293 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, size_t size1
,
4294 const char *str2
, size_t size2
, ssize_t startpos
, ssize_t range
,
4295 struct re_registers
*regs
, ssize_t stop
)
4298 re_char
*string1
= (re_char
*) str1
;
4299 re_char
*string2
= (re_char
*) str2
;
4300 register char *fastmap
= bufp
->fastmap
;
4301 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4302 size_t total_size
= size1
+ size2
;
4303 ssize_t endpos
= startpos
+ range
;
4304 boolean anchored_start
;
4305 /* Nonzero if we are searching multibyte string. */
4306 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4308 /* Check for out-of-range STARTPOS. */
4309 if (startpos
< 0 || startpos
> total_size
)
4312 /* Fix up RANGE if it might eventually take us outside
4313 the virtual concatenation of STRING1 and STRING2.
4314 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4316 range
= 0 - startpos
;
4317 else if (endpos
> total_size
)
4318 range
= total_size
- startpos
;
4320 /* If the search isn't to be a backwards one, don't waste time in a
4321 search for a pattern anchored at beginning of buffer. */
4322 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4331 /* In a forward search for something that starts with \=.
4332 don't keep searching past point. */
4333 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4335 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4341 /* Update the fastmap now if not correct already. */
4342 if (fastmap
&& !bufp
->fastmap_accurate
)
4343 re_compile_fastmap (bufp
);
4345 /* See whether the pattern is anchored. */
4346 anchored_start
= (bufp
->buffer
[0] == begline
);
4349 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4351 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4353 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4357 /* Loop through the string, looking for a place to start matching. */
4360 /* If the pattern is anchored,
4361 skip quickly past places we cannot match.
4362 We don't bother to treat startpos == 0 specially
4363 because that case doesn't repeat. */
4364 if (anchored_start
&& startpos
> 0)
4366 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4367 : string2
[startpos
- size1
- 1])
4372 /* If a fastmap is supplied, skip quickly over characters that
4373 cannot be the start of a match. If the pattern can match the
4374 null string, however, we don't need to skip characters; we want
4375 the first null string. */
4376 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4378 register re_char
*d
;
4379 register re_wchar_t buf_ch
;
4381 d
= POS_ADDR_VSTRING (startpos
);
4383 if (range
> 0) /* Searching forwards. */
4385 register int lim
= 0;
4386 ssize_t irange
= range
;
4388 if (startpos
< size1
&& startpos
+ range
>= size1
)
4389 lim
= range
- (size1
- startpos
);
4391 /* Written out as an if-else to avoid testing `translate'
4393 if (RE_TRANSLATE_P (translate
))
4400 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4401 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4402 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4405 range
-= buf_charlen
;
4411 register re_wchar_t ch
, translated
;
4414 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4415 translated
= RE_TRANSLATE (translate
, ch
);
4416 if (translated
!= ch
4417 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4419 if (fastmap
[buf_ch
])
4432 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4433 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4435 range
-= buf_charlen
;
4439 while (range
> lim
&& !fastmap
[*d
])
4445 startpos
+= irange
- range
;
4447 else /* Searching backwards. */
4451 buf_ch
= STRING_CHAR (d
);
4452 buf_ch
= TRANSLATE (buf_ch
);
4453 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4458 register re_wchar_t ch
, translated
;
4461 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4462 translated
= TRANSLATE (ch
);
4463 if (translated
!= ch
4464 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4466 if (! fastmap
[TRANSLATE (buf_ch
)])
4472 /* If can't match the null string, and that's all we have left, fail. */
4473 if (range
>= 0 && startpos
== total_size
&& fastmap
4474 && !bufp
->can_be_null
)
4477 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4478 startpos
, regs
, stop
);
4491 /* Update STARTPOS to the next character boundary. */
4494 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4495 int len
= BYTES_BY_CHAR_HEAD (*p
);
4513 /* Update STARTPOS to the previous character boundary. */
4516 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4518 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4520 /* Find the head of multibyte form. */
4521 PREV_CHAR_BOUNDARY (p
, phead
);
4522 range
+= p0
- 1 - p
;
4526 startpos
-= p0
- 1 - p
;
4532 WEAK_ALIAS (__re_search_2
, re_search_2
)
4534 /* Declarations and macros for re_match_2. */
4536 static int bcmp_translate (re_char
*s1
, re_char
*s2
,
4537 register ssize_t len
,
4538 RE_TRANSLATE_TYPE translate
,
4539 const int multibyte
);
4541 /* This converts PTR, a pointer into one of the search strings `string1'
4542 and `string2' into an offset from the beginning of that string. */
4543 #define POINTER_TO_OFFSET(ptr) \
4544 (FIRST_STRING_P (ptr) \
4545 ? ((regoff_t) ((ptr) - string1)) \
4546 : ((regoff_t) ((ptr) - string2 + size1)))
4548 /* Call before fetching a character with *d. This switches over to
4549 string2 if necessary.
4550 Check re_match_2_internal for a discussion of why end_match_2 might
4551 not be within string2 (but be equal to end_match_1 instead). */
4552 #define PREFETCH() \
4555 /* End of string2 => fail. */ \
4556 if (dend == end_match_2) \
4558 /* End of string1 => advance to string2. */ \
4560 dend = end_match_2; \
4563 /* Call before fetching a char with *d if you already checked other limits.
4564 This is meant for use in lookahead operations like wordend, etc..
4565 where we might need to look at parts of the string that might be
4566 outside of the LIMITs (i.e past `stop'). */
4567 #define PREFETCH_NOLIMIT() \
4571 dend = end_match_2; \
4574 /* Test if at very beginning or at very end of the virtual concatenation
4575 of `string1' and `string2'. If only one string, it's `string2'. */
4576 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4577 #define AT_STRINGS_END(d) ((d) == end2)
4579 /* Disabled due to a compiler bug -- see comment at case wordbound */
4581 /* The comment at case wordbound is following one, but we don't use
4582 AT_WORD_BOUNDARY anymore to support multibyte form.
4584 The DEC Alpha C compiler 3.x generates incorrect code for the
4585 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4586 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4587 macro and introducing temporary variables works around the bug. */
4590 /* Test if D points to a character which is word-constituent. We have
4591 two special cases to check for: if past the end of string1, look at
4592 the first character in string2; and if before the beginning of
4593 string2, look at the last character in string1. */
4594 #define WORDCHAR_P(d) \
4595 (SYNTAX ((d) == end1 ? *string2 \
4596 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4599 /* Test if the character before D and the one at D differ with respect
4600 to being word-constituent. */
4601 #define AT_WORD_BOUNDARY(d) \
4602 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4603 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4606 /* Free everything we malloc. */
4607 #ifdef MATCH_MAY_ALLOCATE
4608 # define FREE_VAR(var) \
4616 # define FREE_VARIABLES() \
4618 REGEX_FREE_STACK (fail_stack.stack); \
4619 FREE_VAR (regstart); \
4620 FREE_VAR (regend); \
4621 FREE_VAR (best_regstart); \
4622 FREE_VAR (best_regend); \
4625 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4626 #endif /* not MATCH_MAY_ALLOCATE */
4629 /* Optimization routines. */
4631 /* If the operation is a match against one or more chars,
4632 return a pointer to the next operation, else return NULL. */
4634 skip_one_char (const re_char
*p
)
4636 switch (SWITCH_ENUM_CAST (*p
++))
4647 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4650 p
= CHARSET_RANGE_TABLE (p
- 1);
4651 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4652 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4655 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4662 case notcategoryspec
:
4674 /* Jump over non-matching operations. */
4676 skip_noops (const re_char
*p
, const re_char
*pend
)
4681 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4690 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4701 /* Non-zero if "p1 matches something" implies "p2 fails". */
4703 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const re_char
*p1
, const re_char
*p2
)
4706 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4707 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4709 assert (p1
>= bufp
->buffer
&& p1
< pend
4710 && p2
>= bufp
->buffer
&& p2
<= pend
);
4712 /* Skip over open/close-group commands.
4713 If what follows this loop is a ...+ construct,
4714 look at what begins its body, since we will have to
4715 match at least one of that. */
4716 p2
= skip_noops (p2
, pend
);
4717 /* The same skip can be done for p1, except that this function
4718 is only used in the case where p1 is a simple match operator. */
4719 /* p1 = skip_noops (p1, pend); */
4721 assert (p1
>= bufp
->buffer
&& p1
< pend
4722 && p2
>= bufp
->buffer
&& p2
<= pend
);
4724 op2
= p2
== pend
? succeed
: *p2
;
4726 switch (SWITCH_ENUM_CAST (op2
))
4730 /* If we're at the end of the pattern, we can change. */
4731 if (skip_one_char (p1
))
4733 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4741 register re_wchar_t c
4742 = (re_opcode_t
) *p2
== endline
? '\n'
4743 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4745 if ((re_opcode_t
) *p1
== exactn
)
4747 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4749 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4754 else if ((re_opcode_t
) *p1
== charset
4755 || (re_opcode_t
) *p1
== charset_not
)
4757 int not = (re_opcode_t
) *p1
== charset_not
;
4759 /* Test if C is listed in charset (or charset_not)
4761 if (! multibyte
|| IS_REAL_ASCII (c
))
4763 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4764 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4767 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4768 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4770 /* `not' is equal to 1 if c would match, which means
4771 that we can't change to pop_failure_jump. */
4774 DEBUG_PRINT1 (" No match => fast loop.\n");
4778 else if ((re_opcode_t
) *p1
== anychar
4781 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4789 if ((re_opcode_t
) *p1
== exactn
)
4790 /* Reuse the code above. */
4791 return mutually_exclusive_p (bufp
, p2
, p1
);
4793 /* It is hard to list up all the character in charset
4794 P2 if it includes multibyte character. Give up in
4796 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4798 /* Now, we are sure that P2 has no range table.
4799 So, for the size of bitmap in P2, `p2[1]' is
4800 enough. But P1 may have range table, so the
4801 size of bitmap table of P1 is extracted by
4802 using macro `CHARSET_BITMAP_SIZE'.
4804 In a multibyte case, we know that all the character
4805 listed in P2 is ASCII. In a unibyte case, P1 has only a
4806 bitmap table. So, in both cases, it is enough to test
4807 only the bitmap table of P1. */
4809 if ((re_opcode_t
) *p1
== charset
)
4812 /* We win if the charset inside the loop
4813 has no overlap with the one after the loop. */
4816 && idx
< CHARSET_BITMAP_SIZE (p1
));
4818 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4822 || idx
== CHARSET_BITMAP_SIZE (p1
))
4824 DEBUG_PRINT1 (" No match => fast loop.\n");
4828 else if ((re_opcode_t
) *p1
== charset_not
)
4831 /* We win if the charset_not inside the loop lists
4832 every character listed in the charset after. */
4833 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4834 if (! (p2
[2 + idx
] == 0
4835 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4836 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4841 DEBUG_PRINT1 (" No match => fast loop.\n");
4850 switch (SWITCH_ENUM_CAST (*p1
))
4854 /* Reuse the code above. */
4855 return mutually_exclusive_p (bufp
, p2
, p1
);
4857 /* When we have two charset_not, it's very unlikely that
4858 they don't overlap. The union of the two sets of excluded
4859 chars should cover all possible chars, which, as a matter of
4860 fact, is virtually impossible in multibyte buffers. */
4866 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4868 return ((re_opcode_t
) *p1
== syntaxspec
4869 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4871 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4874 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4876 return ((re_opcode_t
) *p1
== notsyntaxspec
4877 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4879 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4882 return (((re_opcode_t
) *p1
== notsyntaxspec
4883 || (re_opcode_t
) *p1
== syntaxspec
)
4888 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4889 case notcategoryspec
:
4890 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4902 /* Matching routines. */
4904 #ifndef emacs /* Emacs never uses this. */
4905 /* re_match is like re_match_2 except it takes only a single string. */
4908 re_match (struct re_pattern_buffer
*bufp
, const char *string
,
4909 size_t size
, ssize_t pos
, struct re_registers
*regs
)
4911 regoff_t result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
,
4912 size
, pos
, regs
, size
);
4915 WEAK_ALIAS (__re_match
, re_match
)
4916 #endif /* not emacs */
4919 /* In Emacs, this is the string or buffer in which we
4920 are matching. It is used for looking up syntax properties. */
4921 Lisp_Object re_match_object
;
4924 /* re_match_2 matches the compiled pattern in BUFP against the
4925 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4926 and SIZE2, respectively). We start matching at POS, and stop
4929 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4930 store offsets for the substring each group matched in REGS. See the
4931 documentation for exactly how many groups we fill.
4933 We return -1 if no match, -2 if an internal error (such as the
4934 failure stack overflowing). Otherwise, we return the length of the
4935 matched substring. */
4938 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
,
4939 size_t size1
, const char *string2
, size_t size2
, ssize_t pos
,
4940 struct re_registers
*regs
, ssize_t stop
)
4946 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4947 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4948 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4951 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4952 (re_char
*) string2
, size2
,
4956 WEAK_ALIAS (__re_match_2
, re_match_2
)
4959 /* This is a separate function so that we can force an alloca cleanup
4962 re_match_2_internal (struct re_pattern_buffer
*bufp
, const re_char
*string1
,
4963 size_t size1
, const re_char
*string2
, size_t size2
,
4964 ssize_t pos
, struct re_registers
*regs
, ssize_t stop
)
4966 /* General temporaries. */
4970 /* Just past the end of the corresponding string. */
4971 re_char
*end1
, *end2
;
4973 /* Pointers into string1 and string2, just past the last characters in
4974 each to consider matching. */
4975 re_char
*end_match_1
, *end_match_2
;
4977 /* Where we are in the data, and the end of the current string. */
4980 /* Used sometimes to remember where we were before starting matching
4981 an operator so that we can go back in case of failure. This "atomic"
4982 behavior of matching opcodes is indispensable to the correctness
4983 of the on_failure_keep_string_jump optimization. */
4986 /* Where we are in the pattern, and the end of the pattern. */
4987 re_char
*p
= bufp
->buffer
;
4988 re_char
*pend
= p
+ bufp
->used
;
4990 /* We use this to map every character in the string. */
4991 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4993 /* Nonzero if BUFP is setup from a multibyte regex. */
4994 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4996 /* Nonzero if STRING1/STRING2 are multibyte. */
4997 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4999 /* Failure point stack. Each place that can handle a failure further
5000 down the line pushes a failure point on this stack. It consists of
5001 regstart, and regend for all registers corresponding to
5002 the subexpressions we're currently inside, plus the number of such
5003 registers, and, finally, two char *'s. The first char * is where
5004 to resume scanning the pattern; the second one is where to resume
5005 scanning the strings. */
5006 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5007 fail_stack_type fail_stack
;
5010 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
5013 #if defined REL_ALLOC && defined REGEX_MALLOC
5014 /* This holds the pointer to the failure stack, when
5015 it is allocated relocatably. */
5016 fail_stack_elt_t
*failure_stack_ptr
;
5019 /* We fill all the registers internally, independent of what we
5020 return, for use in backreferences. The number here includes
5021 an element for register zero. */
5022 size_t num_regs
= bufp
->re_nsub
+ 1;
5024 /* Information on the contents of registers. These are pointers into
5025 the input strings; they record just what was matched (on this
5026 attempt) by a subexpression part of the pattern, that is, the
5027 regnum-th regstart pointer points to where in the pattern we began
5028 matching and the regnum-th regend points to right after where we
5029 stopped matching the regnum-th subexpression. (The zeroth register
5030 keeps track of what the whole pattern matches.) */
5031 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5032 re_char
**regstart
, **regend
;
5035 /* The following record the register info as found in the above
5036 variables when we find a match better than any we've seen before.
5037 This happens as we backtrack through the failure points, which in
5038 turn happens only if we have not yet matched the entire string. */
5039 unsigned best_regs_set
= false;
5040 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5041 re_char
**best_regstart
, **best_regend
;
5044 /* Logically, this is `best_regend[0]'. But we don't want to have to
5045 allocate space for that if we're not allocating space for anything
5046 else (see below). Also, we never need info about register 0 for
5047 any of the other register vectors, and it seems rather a kludge to
5048 treat `best_regend' differently than the rest. So we keep track of
5049 the end of the best match so far in a separate variable. We
5050 initialize this to NULL so that when we backtrack the first time
5051 and need to test it, it's not garbage. */
5052 re_char
*match_end
= NULL
;
5055 /* Counts the total number of registers pushed. */
5056 unsigned num_regs_pushed
= 0;
5059 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5063 #ifdef MATCH_MAY_ALLOCATE
5064 /* Do not bother to initialize all the register variables if there are
5065 no groups in the pattern, as it takes a fair amount of time. If
5066 there are groups, we include space for register 0 (the whole
5067 pattern), even though we never use it, since it simplifies the
5068 array indexing. We should fix this. */
5071 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5072 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5073 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5074 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5076 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5084 /* We must initialize all our variables to NULL, so that
5085 `FREE_VARIABLES' doesn't try to free them. */
5086 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5088 #endif /* MATCH_MAY_ALLOCATE */
5090 /* The starting position is bogus. */
5091 if (pos
< 0 || pos
> size1
+ size2
)
5097 /* Initialize subexpression text positions to -1 to mark ones that no
5098 start_memory/stop_memory has been seen for. Also initialize the
5099 register information struct. */
5100 for (reg
= 1; reg
< num_regs
; reg
++)
5101 regstart
[reg
] = regend
[reg
] = NULL
;
5103 /* We move `string1' into `string2' if the latter's empty -- but not if
5104 `string1' is null. */
5105 if (size2
== 0 && string1
!= NULL
)
5112 end1
= string1
+ size1
;
5113 end2
= string2
+ size2
;
5115 /* `p' scans through the pattern as `d' scans through the data.
5116 `dend' is the end of the input string that `d' points within. `d'
5117 is advanced into the following input string whenever necessary, but
5118 this happens before fetching; therefore, at the beginning of the
5119 loop, `d' can be pointing at the end of a string, but it cannot
5123 /* Only match within string2. */
5124 d
= string2
+ pos
- size1
;
5125 dend
= end_match_2
= string2
+ stop
- size1
;
5126 end_match_1
= end1
; /* Just to give it a value. */
5132 /* Only match within string1. */
5133 end_match_1
= string1
+ stop
;
5135 When we reach end_match_1, PREFETCH normally switches to string2.
5136 But in the present case, this means that just doing a PREFETCH
5137 makes us jump from `stop' to `gap' within the string.
5138 What we really want here is for the search to stop as
5139 soon as we hit end_match_1. That's why we set end_match_2
5140 to end_match_1 (since PREFETCH fails as soon as we hit
5142 end_match_2
= end_match_1
;
5145 { /* It's important to use this code when stop == size so that
5146 moving `d' from end1 to string2 will not prevent the d == dend
5147 check from catching the end of string. */
5149 end_match_2
= string2
+ stop
- size1
;
5155 DEBUG_PRINT1 ("The compiled pattern is: ");
5156 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5157 DEBUG_PRINT1 ("The string to match is: `");
5158 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5159 DEBUG_PRINT1 ("'\n");
5161 /* This loops over pattern commands. It exits by returning from the
5162 function if the match is complete, or it drops through if the match
5163 fails at this starting point in the input data. */
5166 DEBUG_PRINT2 ("\n%p: ", p
);
5169 { /* End of pattern means we might have succeeded. */
5170 DEBUG_PRINT1 ("end of pattern ... ");
5172 /* If we haven't matched the entire string, and we want the
5173 longest match, try backtracking. */
5174 if (d
!= end_match_2
)
5176 /* 1 if this match ends in the same string (string1 or string2)
5177 as the best previous match. */
5178 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5179 == FIRST_STRING_P (d
));
5180 /* 1 if this match is the best seen so far. */
5181 boolean best_match_p
;
5183 /* AIX compiler got confused when this was combined
5184 with the previous declaration. */
5186 best_match_p
= d
> match_end
;
5188 best_match_p
= !FIRST_STRING_P (d
);
5190 DEBUG_PRINT1 ("backtracking.\n");
5192 if (!FAIL_STACK_EMPTY ())
5193 { /* More failure points to try. */
5195 /* If exceeds best match so far, save it. */
5196 if (!best_regs_set
|| best_match_p
)
5198 best_regs_set
= true;
5201 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5203 for (reg
= 1; reg
< num_regs
; reg
++)
5205 best_regstart
[reg
] = regstart
[reg
];
5206 best_regend
[reg
] = regend
[reg
];
5212 /* If no failure points, don't restore garbage. And if
5213 last match is real best match, don't restore second
5215 else if (best_regs_set
&& !best_match_p
)
5218 /* Restore best match. It may happen that `dend ==
5219 end_match_1' while the restored d is in string2.
5220 For example, the pattern `x.*y.*z' against the
5221 strings `x-' and `y-z-', if the two strings are
5222 not consecutive in memory. */
5223 DEBUG_PRINT1 ("Restoring best registers.\n");
5226 dend
= ((d
>= string1
&& d
<= end1
)
5227 ? end_match_1
: end_match_2
);
5229 for (reg
= 1; reg
< num_regs
; reg
++)
5231 regstart
[reg
] = best_regstart
[reg
];
5232 regend
[reg
] = best_regend
[reg
];
5235 } /* d != end_match_2 */
5238 DEBUG_PRINT1 ("Accepting match.\n");
5240 /* If caller wants register contents data back, do it. */
5241 if (regs
&& !bufp
->no_sub
)
5243 /* Have the register data arrays been allocated? */
5244 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5245 { /* No. So allocate them with malloc. We need one
5246 extra element beyond `num_regs' for the `-1' marker
5248 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5249 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5250 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5251 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5256 bufp
->regs_allocated
= REGS_REALLOCATE
;
5258 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5259 { /* Yes. If we need more elements than were already
5260 allocated, reallocate them. If we need fewer, just
5262 if (regs
->num_regs
< num_regs
+ 1)
5264 regs
->num_regs
= num_regs
+ 1;
5265 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5266 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5267 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5276 /* These braces fend off a "empty body in an else-statement"
5277 warning under GCC when assert expands to nothing. */
5278 assert (bufp
->regs_allocated
== REGS_FIXED
);
5281 /* Convert the pointer data in `regstart' and `regend' to
5282 indices. Register zero has to be set differently,
5283 since we haven't kept track of any info for it. */
5284 if (regs
->num_regs
> 0)
5286 regs
->start
[0] = pos
;
5287 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5290 /* Go through the first `min (num_regs, regs->num_regs)'
5291 registers, since that is all we initialized. */
5292 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5294 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5295 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5299 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
5301 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
5305 /* If the regs structure we return has more elements than
5306 were in the pattern, set the extra elements to -1. If
5307 we (re)allocated the registers, this is the case,
5308 because we always allocate enough to have at least one
5310 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5311 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5312 } /* regs && !bufp->no_sub */
5314 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5315 nfailure_points_pushed
, nfailure_points_popped
,
5316 nfailure_points_pushed
- nfailure_points_popped
);
5317 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
5319 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
5321 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5327 /* Otherwise match next pattern command. */
5328 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5330 /* Ignore these. Used to ignore the n of succeed_n's which
5331 currently have n == 0. */
5333 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5337 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5340 /* Match the next n pattern characters exactly. The following
5341 byte in the pattern defines n, and the n bytes after that
5342 are the characters to match. */
5345 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5347 /* Remember the start point to rollback upon failure. */
5351 /* This is written out as an if-else so we don't waste time
5352 testing `translate' inside the loop. */
5353 if (RE_TRANSLATE_P (translate
))
5357 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5377 /* The cost of testing `translate' is comparatively small. */
5378 if (target_multibyte
)
5381 int pat_charlen
, buf_charlen
;
5386 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5389 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5392 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5394 if (TRANSLATE (buf_ch
) != pat_ch
)
5402 mcnt
-= pat_charlen
;
5414 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5415 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5422 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5423 if (! CHAR_BYTE8_P (buf_ch
))
5425 buf_ch
= TRANSLATE (buf_ch
);
5426 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5432 if (buf_ch
!= pat_ch
)
5445 /* Match any character except possibly a newline or a null. */
5451 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5454 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5456 buf_ch
= TRANSLATE (buf_ch
);
5458 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5460 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5461 && buf_ch
== '\000'))
5464 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5473 register unsigned int c
;
5474 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5477 /* Start of actual range_table, or end of bitmap if there is no
5479 re_char
*range_table
IF_LINT (= NULL
);
5481 /* Nonzero if there is a range table. */
5482 int range_table_exists
;
5484 /* Number of ranges of range table. This is not included
5485 in the initial byte-length of the command. */
5488 /* Whether matching against a unibyte character. */
5489 boolean unibyte_char
= false;
5491 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5493 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5495 if (range_table_exists
)
5497 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5498 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5502 c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5503 if (target_multibyte
)
5508 c1
= RE_CHAR_TO_UNIBYTE (c
);
5511 unibyte_char
= true;
5517 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5519 if (! CHAR_BYTE8_P (c1
))
5521 c1
= TRANSLATE (c1
);
5522 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5525 unibyte_char
= true;
5530 unibyte_char
= true;
5533 if (unibyte_char
&& c
< (1 << BYTEWIDTH
))
5534 { /* Lookup bitmap. */
5535 /* Cast to `unsigned' instead of `unsigned char' in
5536 case the bit list is a full 32 bytes long. */
5537 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5538 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5542 else if (range_table_exists
)
5544 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5546 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5547 | (class_bits
& BIT_MULTIBYTE
)
5548 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5549 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5550 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5551 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5554 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5558 if (range_table_exists
)
5559 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5561 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5563 if (!not) goto fail
;
5570 /* The beginning of a group is represented by start_memory.
5571 The argument is the register number. The text
5572 matched within the group is recorded (in the internal
5573 registers data structure) under the register number. */
5575 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5577 /* In case we need to undo this operation (via backtracking). */
5578 PUSH_FAILURE_REG ((unsigned int)*p
);
5581 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5582 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5584 /* Move past the register number and inner group count. */
5589 /* The stop_memory opcode represents the end of a group. Its
5590 argument is the same as start_memory's: the register number. */
5592 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5594 assert (!REG_UNSET (regstart
[*p
]));
5595 /* Strictly speaking, there should be code such as:
5597 assert (REG_UNSET (regend[*p]));
5598 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5600 But the only info to be pushed is regend[*p] and it is known to
5601 be UNSET, so there really isn't anything to push.
5602 Not pushing anything, on the other hand deprives us from the
5603 guarantee that regend[*p] is UNSET since undoing this operation
5604 will not reset its value properly. This is not important since
5605 the value will only be read on the next start_memory or at
5606 the very end and both events can only happen if this stop_memory
5610 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5612 /* Move past the register number and the inner group count. */
5617 /* \<digit> has been turned into a `duplicate' command which is
5618 followed by the numeric value of <digit> as the register number. */
5621 register re_char
*d2
, *dend2
;
5622 int regno
= *p
++; /* Get which register to match against. */
5623 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5625 /* Can't back reference a group which we've never matched. */
5626 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5629 /* Where in input to try to start matching. */
5630 d2
= regstart
[regno
];
5632 /* Remember the start point to rollback upon failure. */
5635 /* Where to stop matching; if both the place to start and
5636 the place to stop matching are in the same string, then
5637 set to the place to stop, otherwise, for now have to use
5638 the end of the first string. */
5640 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5641 == FIRST_STRING_P (regend
[regno
]))
5642 ? regend
[regno
] : end_match_1
);
5645 /* If necessary, advance to next segment in register
5649 if (dend2
== end_match_2
) break;
5650 if (dend2
== regend
[regno
]) break;
5652 /* End of string1 => advance to string2. */
5654 dend2
= regend
[regno
];
5656 /* At end of register contents => success */
5657 if (d2
== dend2
) break;
5659 /* If necessary, advance to next segment in data. */
5662 /* How many characters left in this segment to match. */
5665 /* Want how many consecutive characters we can match in
5666 one shot, so, if necessary, adjust the count. */
5667 if (mcnt
> dend2
- d2
)
5670 /* Compare that many; failure if mismatch, else move
5672 if (RE_TRANSLATE_P (translate
)
5673 ? bcmp_translate (d
, d2
, mcnt
, translate
, target_multibyte
)
5674 : memcmp (d
, d2
, mcnt
))
5679 d
+= mcnt
, d2
+= mcnt
;
5685 /* begline matches the empty string at the beginning of the string
5686 (unless `not_bol' is set in `bufp'), and after newlines. */
5688 DEBUG_PRINT1 ("EXECUTING begline.\n");
5690 if (AT_STRINGS_BEG (d
))
5692 if (!bufp
->not_bol
) break;
5697 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5701 /* In all other cases, we fail. */
5705 /* endline is the dual of begline. */
5707 DEBUG_PRINT1 ("EXECUTING endline.\n");
5709 if (AT_STRINGS_END (d
))
5711 if (!bufp
->not_eol
) break;
5715 PREFETCH_NOLIMIT ();
5722 /* Match at the very beginning of the data. */
5724 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5725 if (AT_STRINGS_BEG (d
))
5730 /* Match at the very end of the data. */
5732 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5733 if (AT_STRINGS_END (d
))
5738 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5739 pushes NULL as the value for the string on the stack. Then
5740 `POP_FAILURE_POINT' will keep the current value for the
5741 string, instead of restoring it. To see why, consider
5742 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5743 then the . fails against the \n. But the next thing we want
5744 to do is match the \n against the \n; if we restored the
5745 string value, we would be back at the foo.
5747 Because this is used only in specific cases, we don't need to
5748 check all the things that `on_failure_jump' does, to make
5749 sure the right things get saved on the stack. Hence we don't
5750 share its code. The only reason to push anything on the
5751 stack at all is that otherwise we would have to change
5752 `anychar's code to do something besides goto fail in this
5753 case; that seems worse than this. */
5754 case on_failure_keep_string_jump
:
5755 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5756 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5759 PUSH_FAILURE_POINT (p
- 3, NULL
);
5762 /* A nasty loop is introduced by the non-greedy *? and +?.
5763 With such loops, the stack only ever contains one failure point
5764 at a time, so that a plain on_failure_jump_loop kind of
5765 cycle detection cannot work. Worse yet, such a detection
5766 can not only fail to detect a cycle, but it can also wrongly
5767 detect a cycle (between different instantiations of the same
5769 So the method used for those nasty loops is a little different:
5770 We use a special cycle-detection-stack-frame which is pushed
5771 when the on_failure_jump_nastyloop failure-point is *popped*.
5772 This special frame thus marks the beginning of one iteration
5773 through the loop and we can hence easily check right here
5774 whether something matched between the beginning and the end of
5776 case on_failure_jump_nastyloop
:
5777 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5778 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5781 assert ((re_opcode_t
)p
[-4] == no_op
);
5784 CHECK_INFINITE_LOOP (p
- 4, d
);
5786 /* If there's a cycle, just continue without pushing
5787 this failure point. The failure point is the "try again"
5788 option, which shouldn't be tried.
5789 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5790 PUSH_FAILURE_POINT (p
- 3, d
);
5794 /* Simple loop detecting on_failure_jump: just check on the
5795 failure stack if the same spot was already hit earlier. */
5796 case on_failure_jump_loop
:
5798 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5799 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5803 CHECK_INFINITE_LOOP (p
- 3, d
);
5805 /* If there's a cycle, get out of the loop, as if the matching
5806 had failed. We used to just `goto fail' here, but that was
5807 aborting the search a bit too early: we want to keep the
5808 empty-loop-match and keep matching after the loop.
5809 We want (x?)*y\1z to match both xxyz and xxyxz. */
5812 PUSH_FAILURE_POINT (p
- 3, d
);
5817 /* Uses of on_failure_jump:
5819 Each alternative starts with an on_failure_jump that points
5820 to the beginning of the next alternative. Each alternative
5821 except the last ends with a jump that in effect jumps past
5822 the rest of the alternatives. (They really jump to the
5823 ending jump of the following alternative, because tensioning
5824 these jumps is a hassle.)
5826 Repeats start with an on_failure_jump that points past both
5827 the repetition text and either the following jump or
5828 pop_failure_jump back to this on_failure_jump. */
5829 case on_failure_jump
:
5830 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5831 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5834 PUSH_FAILURE_POINT (p
-3, d
);
5837 /* This operation is used for greedy *.
5838 Compare the beginning of the repeat with what in the
5839 pattern follows its end. If we can establish that there
5840 is nothing that they would both match, i.e., that we
5841 would have to backtrack because of (as in, e.g., `a*a')
5842 then we can use a non-backtracking loop based on
5843 on_failure_keep_string_jump instead of on_failure_jump. */
5844 case on_failure_jump_smart
:
5845 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5846 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5849 re_char
*p1
= p
; /* Next operation. */
5850 /* Here, we discard `const', making re_match non-reentrant. */
5851 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5852 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5854 p
-= 3; /* Reset so that we will re-execute the
5855 instruction once it's been changed. */
5857 EXTRACT_NUMBER (mcnt
, p2
- 2);
5859 /* Ensure this is a indeed the trivial kind of loop
5860 we are expecting. */
5861 assert (skip_one_char (p1
) == p2
- 3);
5862 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5863 DEBUG_STATEMENT (debug
+= 2);
5864 if (mutually_exclusive_p (bufp
, p1
, p2
))
5866 /* Use a fast `on_failure_keep_string_jump' loop. */
5867 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5868 *p3
= (unsigned char) on_failure_keep_string_jump
;
5869 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5873 /* Default to a safe `on_failure_jump' loop. */
5874 DEBUG_PRINT1 (" smart default => slow loop.\n");
5875 *p3
= (unsigned char) on_failure_jump
;
5877 DEBUG_STATEMENT (debug
-= 2);
5881 /* Unconditionally jump (without popping any failure points). */
5884 IMMEDIATE_QUIT_CHECK
;
5885 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5886 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5887 p
+= mcnt
; /* Do the jump. */
5888 DEBUG_PRINT2 ("(to %p).\n", p
);
5892 /* Have to succeed matching what follows at least n times.
5893 After that, handle like `on_failure_jump'. */
5895 /* Signedness doesn't matter since we only compare MCNT to 0. */
5896 EXTRACT_NUMBER (mcnt
, p
+ 2);
5897 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5899 /* Originally, mcnt is how many times we HAVE to succeed. */
5902 /* Here, we discard `const', making re_match non-reentrant. */
5903 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5906 PUSH_NUMBER (p2
, mcnt
);
5909 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5914 /* Signedness doesn't matter since we only compare MCNT to 0. */
5915 EXTRACT_NUMBER (mcnt
, p
+ 2);
5916 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5918 /* Originally, this is how many times we CAN jump. */
5921 /* Here, we discard `const', making re_match non-reentrant. */
5922 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5924 PUSH_NUMBER (p2
, mcnt
);
5925 goto unconditional_jump
;
5927 /* If don't have to jump any more, skip over the rest of command. */
5934 unsigned char *p2
; /* Location of the counter. */
5935 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5937 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5938 /* Here, we discard `const', making re_match non-reentrant. */
5939 p2
= (unsigned char*) p
+ mcnt
;
5940 /* Signedness doesn't matter since we only copy MCNT's bits . */
5941 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5942 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5943 PUSH_NUMBER (p2
, mcnt
);
5950 boolean
not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5951 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5953 /* We SUCCEED (or FAIL) in one of the following cases: */
5955 /* Case 1: D is at the beginning or the end of string. */
5956 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5960 /* C1 is the character before D, S1 is the syntax of C1, C2
5961 is the character at D, and S2 is the syntax of C2. */
5966 ssize_t offset
= PTR_TO_OFFSET (d
- 1);
5967 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5968 UPDATE_SYNTAX_TABLE (charpos
);
5970 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5973 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5975 PREFETCH_NOLIMIT ();
5976 GET_CHAR_AFTER (c2
, d
, dummy
);
5979 if (/* Case 2: Only one of S1 and S2 is Sword. */
5980 ((s1
== Sword
) != (s2
== Sword
))
5981 /* Case 3: Both of S1 and S2 are Sword, and macro
5982 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5983 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5993 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5995 /* We FAIL in one of the following cases: */
5997 /* Case 1: D is at the end of string. */
5998 if (AT_STRINGS_END (d
))
6002 /* C1 is the character before D, S1 is the syntax of C1, C2
6003 is the character at D, and S2 is the syntax of C2. */
6008 ssize_t offset
= PTR_TO_OFFSET (d
);
6009 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6010 UPDATE_SYNTAX_TABLE (charpos
);
6013 GET_CHAR_AFTER (c2
, d
, dummy
);
6016 /* Case 2: S2 is not Sword. */
6020 /* Case 3: D is not at the beginning of string ... */
6021 if (!AT_STRINGS_BEG (d
))
6023 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6025 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6029 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6031 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6038 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6040 /* We FAIL in one of the following cases: */
6042 /* Case 1: D is at the beginning of string. */
6043 if (AT_STRINGS_BEG (d
))
6047 /* C1 is the character before D, S1 is the syntax of C1, C2
6048 is the character at D, and S2 is the syntax of C2. */
6053 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6054 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6055 UPDATE_SYNTAX_TABLE (charpos
);
6057 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6060 /* Case 2: S1 is not Sword. */
6064 /* Case 3: D is not at the end of string ... */
6065 if (!AT_STRINGS_END (d
))
6067 PREFETCH_NOLIMIT ();
6068 GET_CHAR_AFTER (c2
, d
, dummy
);
6070 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6074 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6076 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6083 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6085 /* We FAIL in one of the following cases: */
6087 /* Case 1: D is at the end of string. */
6088 if (AT_STRINGS_END (d
))
6092 /* C1 is the character before D, S1 is the syntax of C1, C2
6093 is the character at D, and S2 is the syntax of C2. */
6097 ssize_t offset
= PTR_TO_OFFSET (d
);
6098 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6099 UPDATE_SYNTAX_TABLE (charpos
);
6102 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6105 /* Case 2: S2 is neither Sword nor Ssymbol. */
6106 if (s2
!= Sword
&& s2
!= Ssymbol
)
6109 /* Case 3: D is not at the beginning of string ... */
6110 if (!AT_STRINGS_BEG (d
))
6112 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6114 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6118 /* ... and S1 is Sword or Ssymbol. */
6119 if (s1
== Sword
|| s1
== Ssymbol
)
6126 DEBUG_PRINT1 ("EXECUTING symend.\n");
6128 /* We FAIL in one of the following cases: */
6130 /* Case 1: D is at the beginning of string. */
6131 if (AT_STRINGS_BEG (d
))
6135 /* C1 is the character before D, S1 is the syntax of C1, C2
6136 is the character at D, and S2 is the syntax of C2. */
6140 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6141 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6142 UPDATE_SYNTAX_TABLE (charpos
);
6144 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6147 /* Case 2: S1 is neither Ssymbol nor Sword. */
6148 if (s1
!= Sword
&& s1
!= Ssymbol
)
6151 /* Case 3: D is not at the end of string ... */
6152 if (!AT_STRINGS_END (d
))
6154 PREFETCH_NOLIMIT ();
6155 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6157 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6161 /* ... and S2 is Sword or Ssymbol. */
6162 if (s2
== Sword
|| s2
== Ssymbol
)
6171 boolean
not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6173 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
6177 ssize_t offset
= PTR_TO_OFFSET (d
);
6178 ssize_t pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6179 UPDATE_SYNTAX_TABLE (pos1
);
6186 GET_CHAR_AFTER (c
, d
, len
);
6187 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6196 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6197 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6202 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6203 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6208 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6209 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6214 case notcategoryspec
:
6216 boolean
not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6218 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n",
6219 not?"not":"", mcnt
);
6225 GET_CHAR_AFTER (c
, d
, len
);
6226 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6238 continue; /* Successfully executed one pattern command; keep going. */
6241 /* We goto here if a matching operation fails. */
6243 IMMEDIATE_QUIT_CHECK
;
6244 if (!FAIL_STACK_EMPTY ())
6247 /* A restart point is known. Restore to that state. */
6248 DEBUG_PRINT1 ("\nFAIL:\n");
6249 POP_FAILURE_POINT (str
, pat
);
6250 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
6252 case on_failure_keep_string_jump
:
6253 assert (str
== NULL
);
6254 goto continue_failure_jump
;
6256 case on_failure_jump_nastyloop
:
6257 assert ((re_opcode_t
)pat
[-2] == no_op
);
6258 PUSH_FAILURE_POINT (pat
- 2, str
);
6261 case on_failure_jump_loop
:
6262 case on_failure_jump
:
6265 continue_failure_jump
:
6266 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6271 /* A special frame used for nastyloops. */
6278 assert (p
>= bufp
->buffer
&& p
<= pend
);
6280 if (d
>= string1
&& d
<= end1
)
6284 break; /* Matching at this starting point really fails. */
6288 goto restore_best_regs
;
6292 return -1; /* Failure to match. */
6295 /* Subroutine definitions for re_match_2. */
6297 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6298 bytes; nonzero otherwise. */
6301 bcmp_translate (const re_char
*s1
, const re_char
*s2
, register ssize_t len
,
6302 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6304 register re_char
*p1
= s1
, *p2
= s2
;
6305 re_char
*p1_end
= s1
+ len
;
6306 re_char
*p2_end
= s2
+ len
;
6308 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6309 different lengths, but relying on a single `len' would break this. -sm */
6310 while (p1
< p1_end
&& p2
< p2_end
)
6312 int p1_charlen
, p2_charlen
;
6313 re_wchar_t p1_ch
, p2_ch
;
6315 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6316 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6318 if (RE_TRANSLATE (translate
, p1_ch
)
6319 != RE_TRANSLATE (translate
, p2_ch
))
6322 p1
+= p1_charlen
, p2
+= p2_charlen
;
6325 if (p1
!= p1_end
|| p2
!= p2_end
)
6331 /* Entry points for GNU code. */
6333 /* re_compile_pattern is the GNU regular expression compiler: it
6334 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6335 Returns 0 if the pattern was valid, otherwise an error string.
6337 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6338 are set in BUFP on entry.
6340 We call regex_compile to do the actual compilation. */
6343 re_compile_pattern (const char *pattern
, size_t length
,
6344 struct re_pattern_buffer
*bufp
)
6348 /* GNU code is written to assume at least RE_NREGS registers will be set
6349 (and at least one extra will be -1). */
6350 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6352 /* And GNU code determines whether or not to get register information
6353 by passing null for the REGS argument to re_match, etc., not by
6357 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6361 return gettext (re_error_msgid
[(int) ret
]);
6363 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6365 /* Entry points compatible with 4.2 BSD regex library. We don't define
6366 them unless specifically requested. */
6368 #if defined _REGEX_RE_COMP || defined _LIBC
6370 /* BSD has one and only one pattern buffer. */
6371 static struct re_pattern_buffer re_comp_buf
;
6375 /* Make these definitions weak in libc, so POSIX programs can redefine
6376 these names if they don't use our functions, and still use
6377 regcomp/regexec below without link errors. */
6380 re_comp (const char *s
)
6386 if (!re_comp_buf
.buffer
)
6387 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6388 return (char *) gettext ("No previous regular expression");
6392 if (!re_comp_buf
.buffer
)
6394 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
6395 if (re_comp_buf
.buffer
== NULL
)
6396 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6397 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6398 re_comp_buf
.allocated
= 200;
6400 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6401 if (re_comp_buf
.fastmap
== NULL
)
6402 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6403 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6406 /* Since `re_exec' always passes NULL for the `regs' argument, we
6407 don't need to initialize the pattern buffer fields which affect it. */
6409 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6414 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6415 return (char *) gettext (re_error_msgid
[(int) ret
]);
6423 re_exec (const char *s
)
6425 const size_t len
= strlen (s
);
6427 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
6429 #endif /* _REGEX_RE_COMP */
6431 /* POSIX.2 functions. Don't define these for Emacs. */
6435 /* regcomp takes a regular expression as a string and compiles it.
6437 PREG is a regex_t *. We do not expect any fields to be initialized,
6438 since POSIX says we shouldn't. Thus, we set
6440 `buffer' to the compiled pattern;
6441 `used' to the length of the compiled pattern;
6442 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6443 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6444 RE_SYNTAX_POSIX_BASIC;
6445 `fastmap' to an allocated space for the fastmap;
6446 `fastmap_accurate' to zero;
6447 `re_nsub' to the number of subexpressions in PATTERN.
6449 PATTERN is the address of the pattern string.
6451 CFLAGS is a series of bits which affect compilation.
6453 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6454 use POSIX basic syntax.
6456 If REG_NEWLINE is set, then . and [^...] don't match newline.
6457 Also, regexec will try a match beginning after every newline.
6459 If REG_ICASE is set, then we considers upper- and lowercase
6460 versions of letters to be equivalent when matching.
6462 If REG_NOSUB is set, then when PREG is passed to regexec, that
6463 routine will report only success or failure, and nothing about the
6466 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6467 the return codes and their meanings.) */
6470 regcomp (regex_t
*__restrict preg
, const char *__restrict pattern
,
6475 = (cflags
& REG_EXTENDED
) ?
6476 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6478 /* regex_compile will allocate the space for the compiled pattern. */
6480 preg
->allocated
= 0;
6483 /* Try to allocate space for the fastmap. */
6484 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6486 if (cflags
& REG_ICASE
)
6491 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6492 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6493 if (preg
->translate
== NULL
)
6494 return (int) REG_ESPACE
;
6496 /* Map uppercase characters to corresponding lowercase ones. */
6497 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6498 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6501 preg
->translate
= NULL
;
6503 /* If REG_NEWLINE is set, newlines are treated differently. */
6504 if (cflags
& REG_NEWLINE
)
6505 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6506 syntax
&= ~RE_DOT_NEWLINE
;
6507 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6510 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6512 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6514 /* POSIX says a null character in the pattern terminates it, so we
6515 can use strlen here in compiling the pattern. */
6516 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6518 /* POSIX doesn't distinguish between an unmatched open-group and an
6519 unmatched close-group: both are REG_EPAREN. */
6520 if (ret
== REG_ERPAREN
)
6523 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6524 { /* Compute the fastmap now, since regexec cannot modify the pattern
6526 re_compile_fastmap (preg
);
6527 if (preg
->can_be_null
)
6528 { /* The fastmap can't be used anyway. */
6529 free (preg
->fastmap
);
6530 preg
->fastmap
= NULL
;
6535 WEAK_ALIAS (__regcomp
, regcomp
)
6538 /* regexec searches for a given pattern, specified by PREG, in the
6541 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6542 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6543 least NMATCH elements, and we set them to the offsets of the
6544 corresponding matched substrings.
6546 EFLAGS specifies `execution flags' which affect matching: if
6547 REG_NOTBOL is set, then ^ does not match at the beginning of the
6548 string; if REG_NOTEOL is set, then $ does not match at the end.
6550 We return 0 if we find a match and REG_NOMATCH if not. */
6553 regexec (const regex_t
*__restrict preg
, const char *__restrict string
,
6554 size_t nmatch
, regmatch_t pmatch
[__restrict_arr
], int eflags
)
6557 struct re_registers regs
;
6558 regex_t private_preg
;
6559 size_t len
= strlen (string
);
6560 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6562 private_preg
= *preg
;
6564 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6565 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6567 /* The user has told us exactly how many registers to return
6568 information about, via `nmatch'. We have to pass that on to the
6569 matching routines. */
6570 private_preg
.regs_allocated
= REGS_FIXED
;
6574 regs
.num_regs
= nmatch
;
6575 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6576 if (regs
.start
== NULL
)
6578 regs
.end
= regs
.start
+ nmatch
;
6581 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6582 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6583 was a little bit longer but still only matching the real part.
6584 This works because the `endline' will check for a '\n' and will find a
6585 '\0', correctly deciding that this is not the end of a line.
6586 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6587 a convenient '\0' there. For all we know, the string could be preceded
6588 by '\n' which would throw things off. */
6590 /* Perform the searching operation. */
6591 ret
= re_search (&private_preg
, string
, len
,
6592 /* start: */ 0, /* range: */ len
,
6593 want_reg_info
? ®s
: (struct re_registers
*) 0);
6595 /* Copy the register information to the POSIX structure. */
6602 for (r
= 0; r
< nmatch
; r
++)
6604 pmatch
[r
].rm_so
= regs
.start
[r
];
6605 pmatch
[r
].rm_eo
= regs
.end
[r
];
6609 /* If we needed the temporary register info, free the space now. */
6613 /* We want zero return to mean success, unlike `re_search'. */
6614 return ret
>= 0 ? REG_NOERROR
: REG_NOMATCH
;
6616 WEAK_ALIAS (__regexec
, regexec
)
6619 /* Returns a message corresponding to an error code, ERR_CODE, returned
6620 from either regcomp or regexec. We don't use PREG here.
6622 ERR_CODE was previously called ERRCODE, but that name causes an
6623 error with msvc8 compiler. */
6626 regerror (int err_code
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
6632 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6633 /* Only error codes returned by the rest of the code should be passed
6634 to this routine. If we are given anything else, or if other regex
6635 code generates an invalid error code, then the program has a bug.
6636 Dump core so we can fix it. */
6639 msg
= gettext (re_error_msgid
[err_code
]);
6641 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6643 if (errbuf_size
!= 0)
6645 if (msg_size
> errbuf_size
)
6647 strncpy (errbuf
, msg
, errbuf_size
- 1);
6648 errbuf
[errbuf_size
- 1] = 0;
6651 strcpy (errbuf
, msg
);
6656 WEAK_ALIAS (__regerror
, regerror
)
6659 /* Free dynamically allocated space used by PREG. */
6662 regfree (regex_t
*preg
)
6664 free (preg
->buffer
);
6665 preg
->buffer
= NULL
;
6667 preg
->allocated
= 0;
6670 free (preg
->fastmap
);
6671 preg
->fastmap
= NULL
;
6672 preg
->fastmap_accurate
= 0;
6674 free (preg
->translate
);
6675 preg
->translate
= NULL
;
6677 WEAK_ALIAS (__regfree
, regfree
)
6679 #endif /* not emacs */