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"
54 /* We need this for `regex.h', and perhaps for the Emacs include files. */
55 # include <sys/types.h>
58 /* Whether to use ISO C Amendment 1 wide char functions.
59 Those should not be used for Emacs since it uses its own. */
61 #define WIDE_CHAR_SUPPORT 1
63 #define WIDE_CHAR_SUPPORT \
64 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
67 /* For platform which support the ISO C amendment 1 functionality we
68 support user defined character classes. */
70 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
76 /* We have to keep the namespace clean. */
77 # define regfree(preg) __regfree (preg)
78 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
79 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
80 # define regerror(err_code, preg, errbuf, errbuf_size) \
81 __regerror (err_code, preg, errbuf, errbuf_size)
82 # define re_set_registers(bu, re, nu, st, en) \
83 __re_set_registers (bu, re, nu, st, en)
84 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
85 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
86 # define re_match(bufp, string, size, pos, regs) \
87 __re_match (bufp, string, size, pos, regs)
88 # define re_search(bufp, string, size, startpos, range, regs) \
89 __re_search (bufp, string, size, startpos, range, regs)
90 # define re_compile_pattern(pattern, length, bufp) \
91 __re_compile_pattern (pattern, length, bufp)
92 # define re_set_syntax(syntax) __re_set_syntax (syntax)
93 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
94 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
95 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
97 /* Make sure we call libc's function even if the user overrides them. */
98 # define btowc __btowc
99 # define iswctype __iswctype
100 # define wctype __wctype
102 # define WEAK_ALIAS(a,b) weak_alias (a, b)
104 /* We are also using some library internals. */
105 # include <locale/localeinfo.h>
106 # include <locale/elem-hash.h>
107 # include <langinfo.h>
109 # define WEAK_ALIAS(a,b)
112 /* This is for other GNU distributions with internationalized messages. */
113 #if HAVE_LIBINTL_H || defined _LIBC
114 # include <libintl.h>
116 # define gettext(msgid) (msgid)
120 /* This define is so xgettext can find the internationalizable
122 # define gettext_noop(String) String
125 /* The `emacs' switch turns on certain matching commands
126 that make sense only in Emacs. */
131 # include "character.h"
134 /* Make syntax table lookup grant data in gl_state. */
135 # define SYNTAX_ENTRY_VIA_PROPERTY
138 # include "category.h"
143 # define malloc xmalloc
147 # define realloc xrealloc
153 /* Converts the pointer to the char to BEG-based offset from the start. */
154 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
155 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
157 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
158 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
159 # define RE_STRING_CHAR(p, multibyte) \
160 (multibyte ? (STRING_CHAR (p)) : (*(p)))
161 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
162 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
164 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
166 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
168 /* Set C a (possibly converted to multibyte) character before P. P
169 points into a string which is the virtual concatenation of STR1
170 (which ends at END1) or STR2 (which ends at END2). */
171 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
173 if (target_multibyte) \
175 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
176 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
177 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
178 c = STRING_CHAR (dtemp); \
182 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
183 (c) = RE_CHAR_TO_MULTIBYTE (c); \
187 /* Set C a (possibly converted to multibyte) character at P, and set
188 LEN to the byte length of that character. */
189 # define GET_CHAR_AFTER(c, p, len) \
191 if (target_multibyte) \
192 (c) = STRING_CHAR_AND_LENGTH (p, len); \
197 (c) = RE_CHAR_TO_MULTIBYTE (c); \
201 #else /* not emacs */
203 /* If we are not linking with Emacs proper,
204 we can't use the relocating allocator
205 even if config.h says that we can. */
210 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
213 xmalloc (size_t size
)
216 val
= (void *) malloc (size
);
219 write (2, "virtual memory exhausted\n", 25);
226 xrealloc (void *block
, size_t size
)
229 /* We must call malloc explicitly when BLOCK is 0, since some
230 reallocs don't do this. */
232 val
= (void *) malloc (size
);
234 val
= (void *) realloc (block
, size
);
237 write (2, "virtual memory exhausted\n", 25);
246 # define malloc xmalloc
250 # define realloc xrealloc
254 /* Define the syntax stuff for \<, \>, etc. */
256 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
257 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1, Ssymbol
= 2 };
259 # define SWITCH_ENUM_CAST(x) (x)
261 /* Dummy macros for non-Emacs environments. */
262 # define CHAR_CHARSET(c) 0
263 # define CHARSET_LEADING_CODE_BASE(c) 0
264 # define MAX_MULTIBYTE_LENGTH 1
265 # define RE_MULTIBYTE_P(x) 0
266 # define RE_TARGET_MULTIBYTE_P(x) 0
267 # define WORD_BOUNDARY_P(c1, c2) (0)
268 # define CHAR_HEAD_P(p) (1)
269 # define SINGLE_BYTE_CHAR_P(c) (1)
270 # define SAME_CHARSET_P(c1, c2) (1)
271 # define BYTES_BY_CHAR_HEAD(p) (1)
272 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
273 # define STRING_CHAR(p) (*(p))
274 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
275 # define CHAR_STRING(c, s) (*(s) = (c), 1)
276 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
277 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
278 # define RE_CHAR_TO_MULTIBYTE(c) (c)
279 # define RE_CHAR_TO_UNIBYTE(c) (c)
280 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
281 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
282 # define GET_CHAR_AFTER(c, p, len) \
284 # define MAKE_CHAR(charset, c1, c2) (c1)
285 # define BYTE8_TO_CHAR(c) (c)
286 # define CHAR_BYTE8_P(c) (0)
287 # define CHAR_LEADING_CODE(c) (c)
289 #endif /* not emacs */
292 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
293 # define RE_TRANSLATE_P(TBL) (TBL)
296 /* Get the interface, including the syntax bits. */
299 /* isalpha etc. are used for the character classes. */
304 /* 1 if C is an ASCII character. */
305 # define IS_REAL_ASCII(c) ((c) < 0200)
307 /* 1 if C is a unibyte character. */
308 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
310 /* The Emacs definitions should not be directly affected by locales. */
312 /* In Emacs, these are only used for single-byte characters. */
313 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
314 # define ISCNTRL(c) ((c) < ' ')
315 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
316 || ((c) >= 'a' && (c) <= 'f') \
317 || ((c) >= 'A' && (c) <= 'F'))
319 /* This is only used for single-byte characters. */
320 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
322 /* The rest must handle multibyte characters. */
324 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
325 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
328 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
329 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
332 # define ISALNUM(c) (IS_REAL_ASCII (c) \
333 ? (((c) >= 'a' && (c) <= 'z') \
334 || ((c) >= 'A' && (c) <= 'Z') \
335 || ((c) >= '0' && (c) <= '9')) \
336 : SYNTAX (c) == Sword)
338 # define ISALPHA(c) (IS_REAL_ASCII (c) \
339 ? (((c) >= 'a' && (c) <= 'z') \
340 || ((c) >= 'A' && (c) <= 'Z')) \
341 : SYNTAX (c) == Sword)
343 # define ISLOWER(c) lowercasep (c)
345 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
346 ? ((c) > ' ' && (c) < 0177 \
347 && !(((c) >= 'a' && (c) <= 'z') \
348 || ((c) >= 'A' && (c) <= 'Z') \
349 || ((c) >= '0' && (c) <= '9'))) \
350 : SYNTAX (c) != Sword)
352 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
354 # define ISUPPER(c) uppercasep (c)
356 # define ISWORD(c) (SYNTAX (c) == Sword)
358 #else /* not emacs */
360 /* 1 if C is an ASCII character. */
361 # define IS_REAL_ASCII(c) ((c) < 0200)
363 /* This distinction is not meaningful, except in Emacs. */
364 # define ISUNIBYTE(c) 1
367 # define ISBLANK(c) isblank (c)
369 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
372 # define ISGRAPH(c) isgraph (c)
374 # define ISGRAPH(c) (isprint (c) && !isspace (c))
377 /* Solaris defines ISPRINT so we must undefine it first. */
379 # define ISPRINT(c) isprint (c)
380 # define ISDIGIT(c) isdigit (c)
381 # define ISALNUM(c) isalnum (c)
382 # define ISALPHA(c) isalpha (c)
383 # define ISCNTRL(c) iscntrl (c)
384 # define ISLOWER(c) islower (c)
385 # define ISPUNCT(c) ispunct (c)
386 # define ISSPACE(c) isspace (c)
387 # define ISUPPER(c) isupper (c)
388 # define ISXDIGIT(c) isxdigit (c)
390 # define ISWORD(c) ISALPHA (c)
393 # define TOLOWER(c) _tolower (c)
395 # define TOLOWER(c) tolower (c)
398 /* How many characters in the character set. */
399 # define CHAR_SET_SIZE 256
403 extern char *re_syntax_table
;
405 # else /* not SYNTAX_TABLE */
407 static char re_syntax_table
[CHAR_SET_SIZE
];
410 init_syntax_once (void)
418 memset (re_syntax_table
, 0, sizeof re_syntax_table
);
420 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
422 re_syntax_table
[c
] = Sword
;
424 re_syntax_table
['_'] = Ssymbol
;
429 # endif /* not SYNTAX_TABLE */
431 # define SYNTAX(c) re_syntax_table[(c)]
433 #endif /* not emacs */
435 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
437 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
438 use `alloca' instead of `malloc'. This is because using malloc in
439 re_search* or re_match* could cause memory leaks when C-g is used in
440 Emacs; also, malloc is slower and causes storage fragmentation. On
441 the other hand, malloc is more portable, and easier to debug.
443 Because we sometimes use alloca, some routines have to be macros,
444 not functions -- `alloca'-allocated space disappears at the end of the
445 function it is called in. */
449 # define REGEX_ALLOCATE malloc
450 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
451 # define REGEX_FREE free
453 #else /* not REGEX_MALLOC */
455 /* Emacs already defines alloca, sometimes. */
458 /* Make alloca work the best possible way. */
460 # define alloca __builtin_alloca
461 # else /* not __GNUC__ */
462 # ifdef HAVE_ALLOCA_H
464 # endif /* HAVE_ALLOCA_H */
465 # endif /* not __GNUC__ */
467 # endif /* not alloca */
469 # define REGEX_ALLOCATE alloca
471 /* Assumes a `char *destination' variable. */
472 # define REGEX_REALLOCATE(source, osize, nsize) \
473 (destination = (char *) alloca (nsize), \
474 memcpy (destination, source, osize))
476 /* No need to do anything to free, after alloca. */
477 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
479 #endif /* not REGEX_MALLOC */
481 /* Define how to allocate the failure stack. */
483 #if defined REL_ALLOC && defined REGEX_MALLOC
485 # define REGEX_ALLOCATE_STACK(size) \
486 r_alloc (&failure_stack_ptr, (size))
487 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
488 r_re_alloc (&failure_stack_ptr, (nsize))
489 # define REGEX_FREE_STACK(ptr) \
490 r_alloc_free (&failure_stack_ptr)
492 #else /* not using relocating allocator */
496 # define REGEX_ALLOCATE_STACK malloc
497 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
498 # define REGEX_FREE_STACK free
500 # else /* not REGEX_MALLOC */
502 # define REGEX_ALLOCATE_STACK alloca
504 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
505 REGEX_REALLOCATE (source, osize, nsize)
506 /* No need to explicitly free anything. */
507 # define REGEX_FREE_STACK(arg) ((void)0)
509 # endif /* not REGEX_MALLOC */
510 #endif /* not using relocating allocator */
513 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
514 `string1' or just past its end. This works if PTR is NULL, which is
516 #define FIRST_STRING_P(ptr) \
517 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
519 /* (Re)Allocate N items of type T using malloc, or fail. */
520 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
521 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
522 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
524 #define BYTEWIDTH 8 /* In bits. */
526 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
530 #define MAX(a, b) ((a) > (b) ? (a) : (b))
531 #define MIN(a, b) ((a) < (b) ? (a) : (b))
533 /* Type of source-pattern and string chars. */
535 typedef unsigned char re_char
;
537 typedef const unsigned char re_char
;
540 typedef char boolean
;
544 static regoff_t
re_match_2_internal (struct re_pattern_buffer
*bufp
,
545 re_char
*string1
, size_t size1
,
546 re_char
*string2
, size_t size2
,
548 struct re_registers
*regs
,
551 /* These are the command codes that appear in compiled regular
552 expressions. Some opcodes are followed by argument bytes. A
553 command code can specify any interpretation whatsoever for its
554 arguments. Zero bytes may appear in the compiled regular expression. */
560 /* Succeed right away--no more backtracking. */
563 /* Followed by one byte giving n, then by n literal bytes. */
566 /* Matches any (more or less) character. */
569 /* Matches any one char belonging to specified set. First
570 following byte is number of bitmap bytes. Then come bytes
571 for a bitmap saying which chars are in. Bits in each byte
572 are ordered low-bit-first. A character is in the set if its
573 bit is 1. A character too large to have a bit in the map is
574 automatically not in the set.
576 If the length byte has the 0x80 bit set, then that stuff
577 is followed by a range table:
578 2 bytes of flags for character sets (low 8 bits, high 8 bits)
579 See RANGE_TABLE_WORK_BITS below.
580 2 bytes, the number of pairs that follow (upto 32767)
581 pairs, each 2 multibyte characters,
582 each multibyte character represented as 3 bytes. */
585 /* Same parameters as charset, but match any character that is
586 not one of those specified. */
589 /* Start remembering the text that is matched, for storing in a
590 register. Followed by one byte with the register number, in
591 the range 0 to one less than the pattern buffer's re_nsub
595 /* Stop remembering the text that is matched and store it in a
596 memory register. Followed by one byte with the register
597 number, in the range 0 to one less than `re_nsub' in the
601 /* Match a duplicate of something remembered. Followed by one
602 byte containing the register number. */
605 /* Fail unless at beginning of line. */
608 /* Fail unless at end of line. */
611 /* Succeeds if at beginning of buffer (if emacs) or at beginning
612 of string to be matched (if not). */
615 /* Analogously, for end of buffer/string. */
618 /* Followed by two byte relative address to which to jump. */
621 /* Followed by two-byte relative address of place to resume at
622 in case of failure. */
625 /* Like on_failure_jump, but pushes a placeholder instead of the
626 current string position when executed. */
627 on_failure_keep_string_jump
,
629 /* Just like `on_failure_jump', except that it checks that we
630 don't get stuck in an infinite loop (matching an empty string
632 on_failure_jump_loop
,
634 /* Just like `on_failure_jump_loop', except that it checks for
635 a different kind of loop (the kind that shows up with non-greedy
636 operators). This operation has to be immediately preceded
638 on_failure_jump_nastyloop
,
640 /* A smart `on_failure_jump' used for greedy * and + operators.
641 It analyzes the loop before which it is put and if the
642 loop does not require backtracking, it changes itself to
643 `on_failure_keep_string_jump' and short-circuits the loop,
644 else it just defaults to changing itself into `on_failure_jump'.
645 It assumes that it is pointing to just past a `jump'. */
646 on_failure_jump_smart
,
648 /* Followed by two-byte relative address and two-byte number n.
649 After matching N times, jump to the address upon failure.
650 Does not work if N starts at 0: use on_failure_jump_loop
654 /* Followed by two-byte relative address, and two-byte number n.
655 Jump to the address N times, then fail. */
658 /* Set the following two-byte relative address to the
659 subsequent two-byte number. The address *includes* the two
663 wordbeg
, /* Succeeds if at word beginning. */
664 wordend
, /* Succeeds if at word end. */
666 wordbound
, /* Succeeds if at a word boundary. */
667 notwordbound
, /* Succeeds if not at a word boundary. */
669 symbeg
, /* Succeeds if at symbol beginning. */
670 symend
, /* Succeeds if at symbol end. */
672 /* Matches any character whose syntax is specified. Followed by
673 a byte which contains a syntax code, e.g., Sword. */
676 /* Matches any character whose syntax is not that specified. */
680 ,before_dot
, /* Succeeds if before point. */
681 at_dot
, /* Succeeds if at point. */
682 after_dot
, /* Succeeds if after point. */
684 /* Matches any character whose category-set contains the specified
685 category. The operator is followed by a byte which contains a
686 category code (mnemonic ASCII character). */
689 /* Matches any character whose category-set does not contain the
690 specified category. The operator is followed by a byte which
691 contains the category code (mnemonic ASCII character). */
696 /* Common operations on the compiled pattern. */
698 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
700 #define STORE_NUMBER(destination, number) \
702 (destination)[0] = (number) & 0377; \
703 (destination)[1] = (number) >> 8; \
706 /* Same as STORE_NUMBER, except increment DESTINATION to
707 the byte after where the number is stored. Therefore, DESTINATION
708 must be an lvalue. */
710 #define STORE_NUMBER_AND_INCR(destination, number) \
712 STORE_NUMBER (destination, number); \
713 (destination) += 2; \
716 /* Put into DESTINATION a number stored in two contiguous bytes starting
719 #define EXTRACT_NUMBER(destination, source) \
721 (destination) = *(source) & 0377; \
722 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
727 extract_number (int *dest
, re_char
*source
)
729 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
730 *dest
= *source
& 0377;
734 # ifndef EXTRACT_MACROS /* To debug the macros. */
735 # undef EXTRACT_NUMBER
736 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
737 # endif /* not EXTRACT_MACROS */
741 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
742 SOURCE must be an lvalue. */
744 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
746 EXTRACT_NUMBER (destination, source); \
752 extract_number_and_incr (int *destination
, re_char
**source
)
754 extract_number (destination
, *source
);
758 # ifndef EXTRACT_MACROS
759 # undef EXTRACT_NUMBER_AND_INCR
760 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
761 extract_number_and_incr (&dest, &src)
762 # endif /* not EXTRACT_MACROS */
766 /* Store a multibyte character in three contiguous bytes starting
767 DESTINATION, and increment DESTINATION to the byte after where the
768 character is stored. Therefore, DESTINATION must be an lvalue. */
770 #define STORE_CHARACTER_AND_INCR(destination, character) \
772 (destination)[0] = (character) & 0377; \
773 (destination)[1] = ((character) >> 8) & 0377; \
774 (destination)[2] = (character) >> 16; \
775 (destination) += 3; \
778 /* Put into DESTINATION a character stored in three contiguous bytes
779 starting at SOURCE. */
781 #define EXTRACT_CHARACTER(destination, source) \
783 (destination) = ((source)[0] \
784 | ((source)[1] << 8) \
785 | ((source)[2] << 16)); \
789 /* Macros for charset. */
791 /* Size of bitmap of charset P in bytes. P is a start of charset,
792 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
793 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
795 /* Nonzero if charset P has range table. */
796 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
798 /* Return the address of range table of charset P. But not the start
799 of table itself, but the before where the number of ranges is
800 stored. `2 +' means to skip re_opcode_t and size of bitmap,
801 and the 2 bytes of flags at the start of the range table. */
802 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
804 /* Extract the bit flags that start a range table. */
805 #define CHARSET_RANGE_TABLE_BITS(p) \
806 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
807 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
809 /* Return the address of end of RANGE_TABLE. COUNT is number of
810 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
811 is start of range and end of range. `* 3' is size of each start
813 #define CHARSET_RANGE_TABLE_END(range_table, count) \
814 ((range_table) + (count) * 2 * 3)
816 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
817 COUNT is number of ranges in RANGE_TABLE. */
818 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
821 re_wchar_t range_start, range_end; \
823 re_char *range_table_end \
824 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
826 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
828 EXTRACT_CHARACTER (range_start, rtp); \
829 EXTRACT_CHARACTER (range_end, rtp + 3); \
831 if (range_start <= (c) && (c) <= range_end) \
840 /* Test if C is in range table of CHARSET. The flag NOT is negated if
841 C is listed in it. */
842 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
845 /* Number of ranges in range table. */ \
847 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
849 EXTRACT_NUMBER_AND_INCR (count, range_table); \
850 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
854 /* If DEBUG is defined, Regex prints many voluminous messages about what
855 it is doing (if the variable `debug' is nonzero). If linked with the
856 main program in `iregex.c', you can enter patterns and strings
857 interactively. And if linked with the main program in `main.c' and
858 the other test files, you can run the already-written tests. */
862 /* We use standard I/O for debugging. */
865 /* It is useful to test things that ``must'' be true when debugging. */
868 static int debug
= -100000;
870 # define DEBUG_STATEMENT(e) e
871 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
872 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
873 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
874 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
875 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
876 if (debug > 0) print_partial_compiled_pattern (s, e)
877 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
878 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
881 /* Print the fastmap in human-readable form. */
884 print_fastmap (fastmap
)
887 unsigned was_a_range
= 0;
890 while (i
< (1 << BYTEWIDTH
))
896 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
912 /* Print a compiled pattern string in human-readable form, starting at
913 the START pointer into it and ending just before the pointer END. */
916 print_partial_compiled_pattern (start
, end
)
926 fprintf (stderr
, "(null)\n");
930 /* Loop over pattern commands. */
933 fprintf (stderr
, "%d:\t", p
- start
);
935 switch ((re_opcode_t
) *p
++)
938 fprintf (stderr
, "/no_op");
942 fprintf (stderr
, "/succeed");
947 fprintf (stderr
, "/exactn/%d", mcnt
);
950 fprintf (stderr
, "/%c", *p
++);
956 fprintf (stderr
, "/start_memory/%d", *p
++);
960 fprintf (stderr
, "/stop_memory/%d", *p
++);
964 fprintf (stderr
, "/duplicate/%d", *p
++);
968 fprintf (stderr
, "/anychar");
974 register int c
, last
= -100;
975 register int in_range
= 0;
976 int length
= CHARSET_BITMAP_SIZE (p
- 1);
977 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
979 fprintf (stderr
, "/charset [%s",
980 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
983 fprintf (stderr
, " !extends past end of pattern! ");
985 for (c
= 0; c
< 256; c
++)
987 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
989 /* Are we starting a range? */
990 if (last
+ 1 == c
&& ! in_range
)
992 fprintf (stderr
, "-");
995 /* Have we broken a range? */
996 else if (last
+ 1 != c
&& in_range
)
998 fprintf (stderr
, "%c", last
);
1003 fprintf (stderr
, "%c", c
);
1009 fprintf (stderr
, "%c", last
);
1011 fprintf (stderr
, "]");
1015 if (has_range_table
)
1018 fprintf (stderr
, "has-range-table");
1020 /* ??? Should print the range table; for now, just skip it. */
1021 p
+= 2; /* skip range table bits */
1022 EXTRACT_NUMBER_AND_INCR (count
, p
);
1023 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1029 fprintf (stderr
, "/begline");
1033 fprintf (stderr
, "/endline");
1036 case on_failure_jump
:
1037 extract_number_and_incr (&mcnt
, &p
);
1038 fprintf (stderr
, "/on_failure_jump to %d", p
+ mcnt
- start
);
1041 case on_failure_keep_string_jump
:
1042 extract_number_and_incr (&mcnt
, &p
);
1043 fprintf (stderr
, "/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1046 case on_failure_jump_nastyloop
:
1047 extract_number_and_incr (&mcnt
, &p
);
1048 fprintf (stderr
, "/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1051 case on_failure_jump_loop
:
1052 extract_number_and_incr (&mcnt
, &p
);
1053 fprintf (stderr
, "/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1056 case on_failure_jump_smart
:
1057 extract_number_and_incr (&mcnt
, &p
);
1058 fprintf (stderr
, "/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1062 extract_number_and_incr (&mcnt
, &p
);
1063 fprintf (stderr
, "/jump to %d", p
+ mcnt
- start
);
1067 extract_number_and_incr (&mcnt
, &p
);
1068 extract_number_and_incr (&mcnt2
, &p
);
1069 fprintf (stderr
, "/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1073 extract_number_and_incr (&mcnt
, &p
);
1074 extract_number_and_incr (&mcnt2
, &p
);
1075 fprintf (stderr
, "/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1079 extract_number_and_incr (&mcnt
, &p
);
1080 extract_number_and_incr (&mcnt2
, &p
);
1081 fprintf (stderr
, "/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1085 fprintf (stderr
, "/wordbound");
1089 fprintf (stderr
, "/notwordbound");
1093 fprintf (stderr
, "/wordbeg");
1097 fprintf (stderr
, "/wordend");
1101 fprintf (stderr
, "/symbeg");
1105 fprintf (stderr
, "/symend");
1109 fprintf (stderr
, "/syntaxspec");
1111 fprintf (stderr
, "/%d", mcnt
);
1115 fprintf (stderr
, "/notsyntaxspec");
1117 fprintf (stderr
, "/%d", mcnt
);
1122 fprintf (stderr
, "/before_dot");
1126 fprintf (stderr
, "/at_dot");
1130 fprintf (stderr
, "/after_dot");
1134 fprintf (stderr
, "/categoryspec");
1136 fprintf (stderr
, "/%d", mcnt
);
1139 case notcategoryspec
:
1140 fprintf (stderr
, "/notcategoryspec");
1142 fprintf (stderr
, "/%d", mcnt
);
1147 fprintf (stderr
, "/begbuf");
1151 fprintf (stderr
, "/endbuf");
1155 fprintf (stderr
, "?%d", *(p
-1));
1158 fprintf (stderr
, "\n");
1161 fprintf (stderr
, "%d:\tend of pattern.\n", p
- start
);
1166 print_compiled_pattern (bufp
)
1167 struct re_pattern_buffer
*bufp
;
1169 re_char
*buffer
= bufp
->buffer
;
1171 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1172 printf ("%ld bytes used/%ld bytes allocated.\n",
1173 bufp
->used
, bufp
->allocated
);
1175 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1177 printf ("fastmap: ");
1178 print_fastmap (bufp
->fastmap
);
1181 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1182 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1183 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1184 printf ("no_sub: %d\t", bufp
->no_sub
);
1185 printf ("not_bol: %d\t", bufp
->not_bol
);
1186 printf ("not_eol: %d\t", bufp
->not_eol
);
1187 printf ("syntax: %lx\n", bufp
->syntax
);
1189 /* Perhaps we should print the translate table? */
1194 print_double_string (where
, string1
, size1
, string2
, size2
)
1207 if (FIRST_STRING_P (where
))
1209 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1210 putchar (string1
[this_char
]);
1215 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1216 putchar (string2
[this_char
]);
1220 #else /* not DEBUG */
1225 # define DEBUG_STATEMENT(e)
1226 # define DEBUG_PRINT1(x)
1227 # define DEBUG_PRINT2(x1, x2)
1228 # define DEBUG_PRINT3(x1, x2, x3)
1229 # define DEBUG_PRINT4(x1, x2, x3, x4)
1230 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1231 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1233 #endif /* not DEBUG */
1235 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1237 # define IF_LINT(Code) Code
1239 # define IF_LINT(Code) /* empty */
1242 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1243 also be assigned to arbitrarily: each pattern buffer stores its own
1244 syntax, so it can be changed between regex compilations. */
1245 /* This has no initializer because initialized variables in Emacs
1246 become read-only after dumping. */
1247 reg_syntax_t re_syntax_options
;
1250 /* Specify the precise syntax of regexps for compilation. This provides
1251 for compatibility for various utilities which historically have
1252 different, incompatible syntaxes.
1254 The argument SYNTAX is a bit mask comprised of the various bits
1255 defined in regex.h. We return the old syntax. */
1258 re_set_syntax (reg_syntax_t syntax
)
1260 reg_syntax_t ret
= re_syntax_options
;
1262 re_syntax_options
= syntax
;
1265 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1267 /* Regexp to use to replace spaces, or NULL meaning don't. */
1268 static re_char
*whitespace_regexp
;
1271 re_set_whitespace_regexp (const char *regexp
)
1273 whitespace_regexp
= (re_char
*) regexp
;
1275 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1277 /* This table gives an error message for each of the error codes listed
1278 in regex.h. Obviously the order here has to be same as there.
1279 POSIX doesn't require that we do anything for REG_NOERROR,
1280 but why not be nice? */
1282 static const char *re_error_msgid
[] =
1284 gettext_noop ("Success"), /* REG_NOERROR */
1285 gettext_noop ("No match"), /* REG_NOMATCH */
1286 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1287 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1288 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1289 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1290 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1291 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1292 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1293 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1294 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1295 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1296 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1297 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1298 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1299 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1300 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1301 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1304 /* Avoiding alloca during matching, to placate r_alloc. */
1306 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1307 searching and matching functions should not call alloca. On some
1308 systems, alloca is implemented in terms of malloc, and if we're
1309 using the relocating allocator routines, then malloc could cause a
1310 relocation, which might (if the strings being searched are in the
1311 ralloc heap) shift the data out from underneath the regexp
1314 Here's another reason to avoid allocation: Emacs
1315 processes input from X in a signal handler; processing X input may
1316 call malloc; if input arrives while a matching routine is calling
1317 malloc, then we're scrod. But Emacs can't just block input while
1318 calling matching routines; then we don't notice interrupts when
1319 they come in. So, Emacs blocks input around all regexp calls
1320 except the matching calls, which it leaves unprotected, in the
1321 faith that they will not malloc. */
1323 /* Normally, this is fine. */
1324 #define MATCH_MAY_ALLOCATE
1326 /* The match routines may not allocate if (1) they would do it with malloc
1327 and (2) it's not safe for them to use malloc.
1328 Note that if REL_ALLOC is defined, matching would not use malloc for the
1329 failure stack, but we would still use it for the register vectors;
1330 so REL_ALLOC should not affect this. */
1331 #if defined REGEX_MALLOC && defined emacs
1332 # undef MATCH_MAY_ALLOCATE
1336 /* Failure stack declarations and macros; both re_compile_fastmap and
1337 re_match_2 use a failure stack. These have to be macros because of
1338 REGEX_ALLOCATE_STACK. */
1341 /* Approximate number of failure points for which to initially allocate space
1342 when matching. If this number is exceeded, we allocate more
1343 space, so it is not a hard limit. */
1344 #ifndef INIT_FAILURE_ALLOC
1345 # define INIT_FAILURE_ALLOC 20
1348 /* Roughly the maximum number of failure points on the stack. Would be
1349 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1350 This is a variable only so users of regex can assign to it; we never
1351 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1352 before using it, so it should probably be a byte-count instead. */
1353 # if defined MATCH_MAY_ALLOCATE
1354 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1355 whose default stack limit is 2mb. In order for a larger
1356 value to work reliably, you have to try to make it accord
1357 with the process stack limit. */
1358 size_t re_max_failures
= 40000;
1360 size_t re_max_failures
= 4000;
1363 union fail_stack_elt
1366 /* This should be the biggest `int' that's no bigger than a pointer. */
1370 typedef union fail_stack_elt fail_stack_elt_t
;
1374 fail_stack_elt_t
*stack
;
1376 size_t avail
; /* Offset of next open position. */
1377 size_t frame
; /* Offset of the cur constructed frame. */
1380 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1383 /* Define macros to initialize and free the failure stack.
1384 Do `return -2' if the alloc fails. */
1386 #ifdef MATCH_MAY_ALLOCATE
1387 # define INIT_FAIL_STACK() \
1389 fail_stack.stack = (fail_stack_elt_t *) \
1390 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1391 * sizeof (fail_stack_elt_t)); \
1393 if (fail_stack.stack == NULL) \
1396 fail_stack.size = INIT_FAILURE_ALLOC; \
1397 fail_stack.avail = 0; \
1398 fail_stack.frame = 0; \
1401 # define INIT_FAIL_STACK() \
1403 fail_stack.avail = 0; \
1404 fail_stack.frame = 0; \
1407 # define RETALLOC_IF(addr, n, t) \
1408 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1412 /* Double the size of FAIL_STACK, up to a limit
1413 which allows approximately `re_max_failures' items.
1415 Return 1 if succeeds, and 0 if either ran out of memory
1416 allocating space for it or it was already too large.
1418 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1420 /* Factor to increase the failure stack size by
1421 when we increase it.
1422 This used to be 2, but 2 was too wasteful
1423 because the old discarded stacks added up to as much space
1424 were as ultimate, maximum-size stack. */
1425 #define FAIL_STACK_GROWTH_FACTOR 4
1427 #define GROW_FAIL_STACK(fail_stack) \
1428 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1429 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1431 : ((fail_stack).stack \
1432 = (fail_stack_elt_t *) \
1433 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1434 (fail_stack).size * sizeof (fail_stack_elt_t), \
1435 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1436 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1437 * FAIL_STACK_GROWTH_FACTOR))), \
1439 (fail_stack).stack == NULL \
1441 : ((fail_stack).size \
1442 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1443 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1444 * FAIL_STACK_GROWTH_FACTOR)) \
1445 / sizeof (fail_stack_elt_t)), \
1449 /* Push a pointer value onto the failure stack.
1450 Assumes the variable `fail_stack'. Probably should only
1451 be called from within `PUSH_FAILURE_POINT'. */
1452 #define PUSH_FAILURE_POINTER(item) \
1453 fail_stack.stack[fail_stack.avail++].pointer = (item)
1455 /* This pushes an integer-valued item onto the failure stack.
1456 Assumes the variable `fail_stack'. Probably should only
1457 be called from within `PUSH_FAILURE_POINT'. */
1458 #define PUSH_FAILURE_INT(item) \
1459 fail_stack.stack[fail_stack.avail++].integer = (item)
1461 /* These POP... operations complement the PUSH... operations.
1462 All assume that `fail_stack' is nonempty. */
1463 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1464 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1466 /* Individual items aside from the registers. */
1467 #define NUM_NONREG_ITEMS 3
1469 /* Used to examine the stack (to detect infinite loops). */
1470 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1471 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1472 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1473 #define TOP_FAILURE_HANDLE() fail_stack.frame
1476 #define ENSURE_FAIL_STACK(space) \
1477 while (REMAINING_AVAIL_SLOTS <= space) { \
1478 if (!GROW_FAIL_STACK (fail_stack)) \
1480 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1481 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1484 /* Push register NUM onto the stack. */
1485 #define PUSH_FAILURE_REG(num) \
1487 char *destination; \
1488 ENSURE_FAIL_STACK(3); \
1489 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1490 num, regstart[num], regend[num]); \
1491 PUSH_FAILURE_POINTER (regstart[num]); \
1492 PUSH_FAILURE_POINTER (regend[num]); \
1493 PUSH_FAILURE_INT (num); \
1496 /* Change the counter's value to VAL, but make sure that it will
1497 be reset when backtracking. */
1498 #define PUSH_NUMBER(ptr,val) \
1500 char *destination; \
1502 ENSURE_FAIL_STACK(3); \
1503 EXTRACT_NUMBER (c, ptr); \
1504 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1505 PUSH_FAILURE_INT (c); \
1506 PUSH_FAILURE_POINTER (ptr); \
1507 PUSH_FAILURE_INT (-1); \
1508 STORE_NUMBER (ptr, val); \
1511 /* Pop a saved register off the stack. */
1512 #define POP_FAILURE_REG_OR_COUNT() \
1514 long pfreg = POP_FAILURE_INT (); \
1517 /* It's a counter. */ \
1518 /* Here, we discard `const', making re_match non-reentrant. */ \
1519 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1520 pfreg = POP_FAILURE_INT (); \
1521 STORE_NUMBER (ptr, pfreg); \
1522 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, pfreg); \
1526 regend[pfreg] = POP_FAILURE_POINTER (); \
1527 regstart[pfreg] = POP_FAILURE_POINTER (); \
1528 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1529 pfreg, regstart[pfreg], regend[pfreg]); \
1533 /* Check that we are not stuck in an infinite loop. */
1534 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1536 ssize_t failure = TOP_FAILURE_HANDLE (); \
1537 /* Check for infinite matching loops */ \
1538 while (failure > 0 \
1539 && (FAILURE_STR (failure) == string_place \
1540 || FAILURE_STR (failure) == NULL)) \
1542 assert (FAILURE_PAT (failure) >= bufp->buffer \
1543 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1544 if (FAILURE_PAT (failure) == pat_cur) \
1549 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1550 failure = NEXT_FAILURE_HANDLE(failure); \
1552 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1555 /* Push the information about the state we will need
1556 if we ever fail back to it.
1558 Requires variables fail_stack, regstart, regend and
1559 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1562 Does `return FAILURE_CODE' if runs out of memory. */
1564 #define PUSH_FAILURE_POINT(pattern, string_place) \
1566 char *destination; \
1567 /* Must be int, so when we don't save any registers, the arithmetic \
1568 of 0 + -1 isn't done as unsigned. */ \
1570 DEBUG_STATEMENT (nfailure_points_pushed++); \
1571 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1572 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1573 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1575 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1577 DEBUG_PRINT1 ("\n"); \
1579 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1580 PUSH_FAILURE_INT (fail_stack.frame); \
1582 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1583 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1584 DEBUG_PRINT1 ("'\n"); \
1585 PUSH_FAILURE_POINTER (string_place); \
1587 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1588 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1589 PUSH_FAILURE_POINTER (pattern); \
1591 /* Close the frame by moving the frame pointer past it. */ \
1592 fail_stack.frame = fail_stack.avail; \
1595 /* Estimate the size of data pushed by a typical failure stack entry.
1596 An estimate is all we need, because all we use this for
1597 is to choose a limit for how big to make the failure stack. */
1598 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1599 #define TYPICAL_FAILURE_SIZE 20
1601 /* How many items can still be added to the stack without overflowing it. */
1602 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1605 /* Pops what PUSH_FAIL_STACK pushes.
1607 We restore into the parameters, all of which should be lvalues:
1608 STR -- the saved data position.
1609 PAT -- the saved pattern position.
1610 REGSTART, REGEND -- arrays of string positions.
1612 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1613 `pend', `string1', `size1', `string2', and `size2'. */
1615 #define POP_FAILURE_POINT(str, pat) \
1617 assert (!FAIL_STACK_EMPTY ()); \
1619 /* Remove failure points and point to how many regs pushed. */ \
1620 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1621 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1622 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1624 /* Pop the saved registers. */ \
1625 while (fail_stack.frame < fail_stack.avail) \
1626 POP_FAILURE_REG_OR_COUNT (); \
1628 pat = POP_FAILURE_POINTER (); \
1629 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1630 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1632 /* If the saved string location is NULL, it came from an \
1633 on_failure_keep_string_jump opcode, and we want to throw away the \
1634 saved NULL, thus retaining our current position in the string. */ \
1635 str = POP_FAILURE_POINTER (); \
1636 DEBUG_PRINT2 (" Popping string %p: `", str); \
1637 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1638 DEBUG_PRINT1 ("'\n"); \
1640 fail_stack.frame = POP_FAILURE_INT (); \
1641 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1643 assert (fail_stack.avail >= 0); \
1644 assert (fail_stack.frame <= fail_stack.avail); \
1646 DEBUG_STATEMENT (nfailure_points_popped++); \
1647 } while (0) /* POP_FAILURE_POINT */
1651 /* Registers are set to a sentinel when they haven't yet matched. */
1652 #define REG_UNSET(e) ((e) == NULL)
1654 /* Subroutine declarations and macros for regex_compile. */
1656 static reg_errcode_t
regex_compile (re_char
*pattern
, size_t size
,
1657 reg_syntax_t syntax
,
1658 struct re_pattern_buffer
*bufp
);
1659 static void store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
);
1660 static void store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
);
1661 static void insert_op1 (re_opcode_t op
, unsigned char *loc
,
1662 int arg
, unsigned char *end
);
1663 static void insert_op2 (re_opcode_t op
, unsigned char *loc
,
1664 int arg1
, int arg2
, unsigned char *end
);
1665 static boolean
at_begline_loc_p (re_char
*pattern
, re_char
*p
,
1666 reg_syntax_t syntax
);
1667 static boolean
at_endline_loc_p (re_char
*p
, re_char
*pend
,
1668 reg_syntax_t syntax
);
1669 static re_char
*skip_one_char (re_char
*p
);
1670 static int analyse_first (re_char
*p
, re_char
*pend
,
1671 char *fastmap
, const int multibyte
);
1673 /* Fetch the next character in the uncompiled pattern, with no
1675 #define PATFETCH(c) \
1678 if (p == pend) return REG_EEND; \
1679 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1684 /* If `translate' is non-null, return translate[D], else just D. We
1685 cast the subscript to translate because some data is declared as
1686 `char *', to avoid warnings when a string constant is passed. But
1687 when we use a character as a subscript we must make it unsigned. */
1689 # define TRANSLATE(d) \
1690 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1694 /* Macros for outputting the compiled pattern into `buffer'. */
1696 /* If the buffer isn't allocated when it comes in, use this. */
1697 #define INIT_BUF_SIZE 32
1699 /* Make sure we have at least N more bytes of space in buffer. */
1700 #define GET_BUFFER_SPACE(n) \
1701 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1704 /* Make sure we have one more byte of buffer space and then add C to it. */
1705 #define BUF_PUSH(c) \
1707 GET_BUFFER_SPACE (1); \
1708 *b++ = (unsigned char) (c); \
1712 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1713 #define BUF_PUSH_2(c1, c2) \
1715 GET_BUFFER_SPACE (2); \
1716 *b++ = (unsigned char) (c1); \
1717 *b++ = (unsigned char) (c2); \
1721 /* Store a jump with opcode OP at LOC to location TO. We store a
1722 relative address offset by the three bytes the jump itself occupies. */
1723 #define STORE_JUMP(op, loc, to) \
1724 store_op1 (op, loc, (to) - (loc) - 3)
1726 /* Likewise, for a two-argument jump. */
1727 #define STORE_JUMP2(op, loc, to, arg) \
1728 store_op2 (op, loc, (to) - (loc) - 3, arg)
1730 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1731 #define INSERT_JUMP(op, loc, to) \
1732 insert_op1 (op, loc, (to) - (loc) - 3, b)
1734 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1735 #define INSERT_JUMP2(op, loc, to, arg) \
1736 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1739 /* This is not an arbitrary limit: the arguments which represent offsets
1740 into the pattern are two bytes long. So if 2^15 bytes turns out to
1741 be too small, many things would have to change. */
1742 # define MAX_BUF_SIZE (1L << 15)
1744 #if 0 /* This is when we thought it could be 2^16 bytes. */
1745 /* Any other compiler which, like MSC, has allocation limit below 2^16
1746 bytes will have to use approach similar to what was done below for
1747 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1748 reallocating to 0 bytes. Such thing is not going to work too well.
1749 You have been warned!! */
1750 #if defined _MSC_VER && !defined WIN32
1751 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1752 # define MAX_BUF_SIZE 65500L
1754 # define MAX_BUF_SIZE (1L << 16)
1758 /* Extend the buffer by twice its current size via realloc and
1759 reset the pointers that pointed into the old block to point to the
1760 correct places in the new one. If extending the buffer results in it
1761 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1762 #if __BOUNDED_POINTERS__
1763 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1764 # define MOVE_BUFFER_POINTER(P) \
1765 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1766 SET_HIGH_BOUND (P), \
1767 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1768 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1771 SET_HIGH_BOUND (b); \
1772 SET_HIGH_BOUND (begalt); \
1773 if (fixup_alt_jump) \
1774 SET_HIGH_BOUND (fixup_alt_jump); \
1776 SET_HIGH_BOUND (laststart); \
1777 if (pending_exact) \
1778 SET_HIGH_BOUND (pending_exact); \
1781 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1782 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1784 #define EXTEND_BUFFER() \
1786 unsigned char *old_buffer = bufp->buffer; \
1787 if (bufp->allocated == MAX_BUF_SIZE) \
1789 bufp->allocated <<= 1; \
1790 if (bufp->allocated > MAX_BUF_SIZE) \
1791 bufp->allocated = MAX_BUF_SIZE; \
1792 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1793 if (bufp->buffer == NULL) \
1794 return REG_ESPACE; \
1795 /* If the buffer moved, move all the pointers into it. */ \
1796 if (old_buffer != bufp->buffer) \
1798 unsigned char *new_buffer = bufp->buffer; \
1799 MOVE_BUFFER_POINTER (b); \
1800 MOVE_BUFFER_POINTER (begalt); \
1801 if (fixup_alt_jump) \
1802 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1804 MOVE_BUFFER_POINTER (laststart); \
1805 if (pending_exact) \
1806 MOVE_BUFFER_POINTER (pending_exact); \
1808 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1812 /* Since we have one byte reserved for the register number argument to
1813 {start,stop}_memory, the maximum number of groups we can report
1814 things about is what fits in that byte. */
1815 #define MAX_REGNUM 255
1817 /* But patterns can have more than `MAX_REGNUM' registers. We just
1818 ignore the excess. */
1819 typedef int regnum_t
;
1822 /* Macros for the compile stack. */
1824 /* Since offsets can go either forwards or backwards, this type needs to
1825 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1826 /* int may be not enough when sizeof(int) == 2. */
1827 typedef long pattern_offset_t
;
1831 pattern_offset_t begalt_offset
;
1832 pattern_offset_t fixup_alt_jump
;
1833 pattern_offset_t laststart_offset
;
1835 } compile_stack_elt_t
;
1840 compile_stack_elt_t
*stack
;
1842 size_t avail
; /* Offset of next open position. */
1843 } compile_stack_type
;
1846 #define INIT_COMPILE_STACK_SIZE 32
1848 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1849 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1851 /* The next available element. */
1852 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1854 /* Explicit quit checking is only used on NTemacs and whenever we
1855 use polling to process input events. */
1856 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1857 extern int immediate_quit
;
1858 # define IMMEDIATE_QUIT_CHECK \
1860 if (immediate_quit) QUIT; \
1863 # define IMMEDIATE_QUIT_CHECK ((void)0)
1866 /* Structure to manage work area for range table. */
1867 struct range_table_work_area
1869 int *table
; /* actual work area. */
1870 int allocated
; /* allocated size for work area in bytes. */
1871 int used
; /* actually used size in words. */
1872 int bits
; /* flag to record character classes */
1875 /* Make sure that WORK_AREA can hold more N multibyte characters.
1876 This is used only in set_image_of_range and set_image_of_range_1.
1877 It expects WORK_AREA to be a pointer.
1878 If it can't get the space, it returns from the surrounding function. */
1880 #define EXTEND_RANGE_TABLE(work_area, n) \
1882 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1884 extend_range_table_work_area (&work_area); \
1885 if ((work_area).table == 0) \
1886 return (REG_ESPACE); \
1890 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1891 (work_area).bits |= (bit)
1893 /* Bits used to implement the multibyte-part of the various character classes
1894 such as [:alnum:] in a charset's range table. */
1895 #define BIT_WORD 0x1
1896 #define BIT_LOWER 0x2
1897 #define BIT_PUNCT 0x4
1898 #define BIT_SPACE 0x8
1899 #define BIT_UPPER 0x10
1900 #define BIT_MULTIBYTE 0x20
1902 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1903 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1905 EXTEND_RANGE_TABLE ((work_area), 2); \
1906 (work_area).table[(work_area).used++] = (range_start); \
1907 (work_area).table[(work_area).used++] = (range_end); \
1910 /* Free allocated memory for WORK_AREA. */
1911 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1913 if ((work_area).table) \
1914 free ((work_area).table); \
1917 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1918 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1919 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1920 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1923 /* Set the bit for character C in a list. */
1924 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1929 /* Store characters in the range FROM to TO in the bitmap at B (for
1930 ASCII and unibyte characters) and WORK_AREA (for multibyte
1931 characters) while translating them and paying attention to the
1932 continuity of translated characters.
1934 Implementation note: It is better to implement these fairly big
1935 macros by a function, but it's not that easy because macros called
1936 in this macro assume various local variables already declared. */
1938 /* Both FROM and TO are ASCII characters. */
1940 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1944 for (C0 = (FROM); C0 <= (TO); C0++) \
1946 C1 = TRANSLATE (C0); \
1947 if (! ASCII_CHAR_P (C1)) \
1949 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1950 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1953 SET_LIST_BIT (C1); \
1958 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1960 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1962 int C0, C1, C2, I; \
1963 int USED = RANGE_TABLE_WORK_USED (work_area); \
1965 for (C0 = (FROM); C0 <= (TO); C0++) \
1967 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1968 if (CHAR_BYTE8_P (C1)) \
1969 SET_LIST_BIT (C0); \
1972 C2 = TRANSLATE (C1); \
1974 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1976 SET_LIST_BIT (C1); \
1977 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1979 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1980 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1982 if (C2 >= from - 1 && C2 <= to + 1) \
1984 if (C2 == from - 1) \
1985 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1986 else if (C2 == to + 1) \
1987 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1992 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1998 /* Both FROM and TO are multibyte characters. */
2000 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2002 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2004 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2005 for (C0 = (FROM); C0 <= (TO); C0++) \
2007 C1 = TRANSLATE (C0); \
2008 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2009 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2010 SET_LIST_BIT (C2); \
2011 if (C1 >= (FROM) && C1 <= (TO)) \
2013 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2015 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2016 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2018 if (C1 >= from - 1 && C1 <= to + 1) \
2020 if (C1 == from - 1) \
2021 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2022 else if (C1 == to + 1) \
2023 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2028 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2034 /* Get the next unsigned number in the uncompiled pattern. */
2035 #define GET_UNSIGNED_NUMBER(num) \
2038 FREE_STACK_RETURN (REG_EBRACE); \
2042 while ('0' <= c && c <= '9') \
2048 num = num * 10 + c - '0'; \
2049 if (num / 10 != prev) \
2050 FREE_STACK_RETURN (REG_BADBR); \
2052 FREE_STACK_RETURN (REG_EBRACE); \
2058 #if ! WIDE_CHAR_SUPPORT
2060 /* Map a string to the char class it names (if any). */
2062 re_wctype (const re_char
*str
)
2064 const char *string
= (const char *) str
;
2065 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2066 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2067 else if (STREQ (string
, "word")) return RECC_WORD
;
2068 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2069 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2070 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2071 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2072 else if (STREQ (string
, "print")) return RECC_PRINT
;
2073 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2074 else if (STREQ (string
, "space")) return RECC_SPACE
;
2075 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2076 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2077 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2078 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2079 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2080 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2081 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2085 /* True if CH is in the char class CC. */
2087 re_iswctype (int ch
, re_wctype_t cc
)
2091 case RECC_ALNUM
: return ISALNUM (ch
) != 0;
2092 case RECC_ALPHA
: return ISALPHA (ch
) != 0;
2093 case RECC_BLANK
: return ISBLANK (ch
) != 0;
2094 case RECC_CNTRL
: return ISCNTRL (ch
) != 0;
2095 case RECC_DIGIT
: return ISDIGIT (ch
) != 0;
2096 case RECC_GRAPH
: return ISGRAPH (ch
) != 0;
2097 case RECC_LOWER
: return ISLOWER (ch
) != 0;
2098 case RECC_PRINT
: return ISPRINT (ch
) != 0;
2099 case RECC_PUNCT
: return ISPUNCT (ch
) != 0;
2100 case RECC_SPACE
: return ISSPACE (ch
) != 0;
2101 case RECC_UPPER
: return ISUPPER (ch
) != 0;
2102 case RECC_XDIGIT
: return ISXDIGIT (ch
) != 0;
2103 case RECC_ASCII
: return IS_REAL_ASCII (ch
) != 0;
2104 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2105 case RECC_UNIBYTE
: return ISUNIBYTE (ch
) != 0;
2106 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2107 case RECC_WORD
: return ISWORD (ch
) != 0;
2108 case RECC_ERROR
: return false;
2114 /* Return a bit-pattern to use in the range-table bits to match multibyte
2115 chars of class CC. */
2117 re_wctype_to_bit (re_wctype_t cc
)
2121 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2122 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2123 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2124 case RECC_LOWER
: return BIT_LOWER
;
2125 case RECC_UPPER
: return BIT_UPPER
;
2126 case RECC_PUNCT
: return BIT_PUNCT
;
2127 case RECC_SPACE
: return BIT_SPACE
;
2128 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2129 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2136 /* Filling in the work area of a range. */
2138 /* Actually extend the space in WORK_AREA. */
2141 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2143 work_area
->allocated
+= 16 * sizeof (int);
2144 if (work_area
->table
)
2146 = (int *) realloc (work_area
->table
, work_area
->allocated
);
2149 = (int *) malloc (work_area
->allocated
);
2155 /* Carefully find the ranges of codes that are equivalent
2156 under case conversion to the range start..end when passed through
2157 TRANSLATE. Handle the case where non-letters can come in between
2158 two upper-case letters (which happens in Latin-1).
2159 Also handle the case of groups of more than 2 case-equivalent chars.
2161 The basic method is to look at consecutive characters and see
2162 if they can form a run that can be handled as one.
2164 Returns -1 if successful, REG_ESPACE if ran out of space. */
2167 set_image_of_range_1 (struct range_table_work_area
*work_area
,
2168 re_wchar_t start
, re_wchar_t end
,
2169 RE_TRANSLATE_TYPE translate
)
2171 /* `one_case' indicates a character, or a run of characters,
2172 each of which is an isolate (no case-equivalents).
2173 This includes all ASCII non-letters.
2175 `two_case' indicates a character, or a run of characters,
2176 each of which has two case-equivalent forms.
2177 This includes all ASCII letters.
2179 `strange' indicates a character that has more than one
2182 enum case_type
{one_case
, two_case
, strange
};
2184 /* Describe the run that is in progress,
2185 which the next character can try to extend.
2186 If run_type is strange, that means there really is no run.
2187 If run_type is one_case, then run_start...run_end is the run.
2188 If run_type is two_case, then the run is run_start...run_end,
2189 and the case-equivalents end at run_eqv_end. */
2191 enum case_type run_type
= strange
;
2192 int run_start
, run_end
, run_eqv_end
;
2194 Lisp_Object eqv_table
;
2196 if (!RE_TRANSLATE_P (translate
))
2198 EXTEND_RANGE_TABLE (work_area
, 2);
2199 work_area
->table
[work_area
->used
++] = (start
);
2200 work_area
->table
[work_area
->used
++] = (end
);
2204 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2206 for (; start
<= end
; start
++)
2208 enum case_type this_type
;
2209 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2210 int minchar
, maxchar
;
2212 /* Classify this character */
2214 this_type
= one_case
;
2215 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2216 this_type
= two_case
;
2218 this_type
= strange
;
2221 minchar
= start
, maxchar
= eqv
;
2223 minchar
= eqv
, maxchar
= start
;
2225 /* Can this character extend the run in progress? */
2226 if (this_type
== strange
|| this_type
!= run_type
2227 || !(minchar
== run_end
+ 1
2228 && (run_type
== two_case
2229 ? maxchar
== run_eqv_end
+ 1 : 1)))
2232 Record each of its equivalent ranges. */
2233 if (run_type
== one_case
)
2235 EXTEND_RANGE_TABLE (work_area
, 2);
2236 work_area
->table
[work_area
->used
++] = run_start
;
2237 work_area
->table
[work_area
->used
++] = run_end
;
2239 else if (run_type
== two_case
)
2241 EXTEND_RANGE_TABLE (work_area
, 4);
2242 work_area
->table
[work_area
->used
++] = run_start
;
2243 work_area
->table
[work_area
->used
++] = run_end
;
2244 work_area
->table
[work_area
->used
++]
2245 = RE_TRANSLATE (eqv_table
, run_start
);
2246 work_area
->table
[work_area
->used
++]
2247 = RE_TRANSLATE (eqv_table
, run_end
);
2252 if (this_type
== strange
)
2254 /* For a strange character, add each of its equivalents, one
2255 by one. Don't start a range. */
2258 EXTEND_RANGE_TABLE (work_area
, 2);
2259 work_area
->table
[work_area
->used
++] = eqv
;
2260 work_area
->table
[work_area
->used
++] = eqv
;
2261 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2263 while (eqv
!= start
);
2266 /* Add this char to the run, or start a new run. */
2267 else if (run_type
== strange
)
2269 /* Initialize a new range. */
2270 run_type
= this_type
;
2273 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2277 /* Extend a running range. */
2279 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2283 /* If a run is still in progress at the end, finish it now
2284 by recording its equivalent ranges. */
2285 if (run_type
== one_case
)
2287 EXTEND_RANGE_TABLE (work_area
, 2);
2288 work_area
->table
[work_area
->used
++] = run_start
;
2289 work_area
->table
[work_area
->used
++] = run_end
;
2291 else if (run_type
== two_case
)
2293 EXTEND_RANGE_TABLE (work_area
, 4);
2294 work_area
->table
[work_area
->used
++] = run_start
;
2295 work_area
->table
[work_area
->used
++] = run_end
;
2296 work_area
->table
[work_area
->used
++]
2297 = RE_TRANSLATE (eqv_table
, run_start
);
2298 work_area
->table
[work_area
->used
++]
2299 = RE_TRANSLATE (eqv_table
, run_end
);
2307 /* Record the image of the range start..end when passed through
2308 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2309 and is not even necessarily contiguous.
2310 Normally we approximate it with the smallest contiguous range that contains
2311 all the chars we need. However, for Latin-1 we go to extra effort
2314 This function is not called for ASCII ranges.
2316 Returns -1 if successful, REG_ESPACE if ran out of space. */
2319 set_image_of_range (struct range_table_work_area
*work_area
,
2320 re_wchar_t start
, re_wchar_t end
,
2321 RE_TRANSLATE_TYPE translate
)
2323 re_wchar_t cmin
, cmax
;
2326 /* For Latin-1 ranges, use set_image_of_range_1
2327 to get proper handling of ranges that include letters and nonletters.
2328 For a range that includes the whole of Latin-1, this is not necessary.
2329 For other character sets, we don't bother to get this right. */
2330 if (RE_TRANSLATE_P (translate
) && start
< 04400
2331 && !(start
< 04200 && end
>= 04377))
2338 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2348 EXTEND_RANGE_TABLE (work_area
, 2);
2349 work_area
->table
[work_area
->used
++] = (start
);
2350 work_area
->table
[work_area
->used
++] = (end
);
2352 cmin
= -1, cmax
= -1;
2354 if (RE_TRANSLATE_P (translate
))
2358 for (ch
= start
; ch
<= end
; ch
++)
2360 re_wchar_t c
= TRANSLATE (ch
);
2361 if (! (start
<= c
&& c
<= end
))
2367 cmin
= MIN (cmin
, c
);
2368 cmax
= MAX (cmax
, c
);
2375 EXTEND_RANGE_TABLE (work_area
, 2);
2376 work_area
->table
[work_area
->used
++] = (cmin
);
2377 work_area
->table
[work_area
->used
++] = (cmax
);
2385 #ifndef MATCH_MAY_ALLOCATE
2387 /* If we cannot allocate large objects within re_match_2_internal,
2388 we make the fail stack and register vectors global.
2389 The fail stack, we grow to the maximum size when a regexp
2391 The register vectors, we adjust in size each time we
2392 compile a regexp, according to the number of registers it needs. */
2394 static fail_stack_type fail_stack
;
2396 /* Size with which the following vectors are currently allocated.
2397 That is so we can make them bigger as needed,
2398 but never make them smaller. */
2399 static int regs_allocated_size
;
2401 static re_char
** regstart
, ** regend
;
2402 static re_char
**best_regstart
, **best_regend
;
2404 /* Make the register vectors big enough for NUM_REGS registers,
2405 but don't make them smaller. */
2408 regex_grow_registers (int num_regs
)
2410 if (num_regs
> regs_allocated_size
)
2412 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2413 RETALLOC_IF (regend
, num_regs
, re_char
*);
2414 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2415 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2417 regs_allocated_size
= num_regs
;
2421 #endif /* not MATCH_MAY_ALLOCATE */
2423 static boolean
group_in_compile_stack (compile_stack_type compile_stack
,
2426 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2427 Returns one of error codes defined in `regex.h', or zero for success.
2429 Assumes the `allocated' (and perhaps `buffer') and `translate'
2430 fields are set in BUFP on entry.
2432 If it succeeds, results are put in BUFP (if it returns an error, the
2433 contents of BUFP are undefined):
2434 `buffer' is the compiled pattern;
2435 `syntax' is set to SYNTAX;
2436 `used' is set to the length of the compiled pattern;
2437 `fastmap_accurate' is zero;
2438 `re_nsub' is the number of subexpressions in PATTERN;
2439 `not_bol' and `not_eol' are zero;
2441 The `fastmap' field is neither examined nor set. */
2443 /* Insert the `jump' from the end of last alternative to "here".
2444 The space for the jump has already been allocated. */
2445 #define FIXUP_ALT_JUMP() \
2447 if (fixup_alt_jump) \
2448 STORE_JUMP (jump, fixup_alt_jump, b); \
2452 /* Return, freeing storage we allocated. */
2453 #define FREE_STACK_RETURN(value) \
2455 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2456 free (compile_stack.stack); \
2460 static reg_errcode_t
2461 regex_compile (const re_char
*pattern
, size_t size
, reg_syntax_t syntax
, struct re_pattern_buffer
*bufp
)
2463 /* We fetch characters from PATTERN here. */
2464 register re_wchar_t c
, c1
;
2466 /* Points to the end of the buffer, where we should append. */
2467 register unsigned char *b
;
2469 /* Keeps track of unclosed groups. */
2470 compile_stack_type compile_stack
;
2472 /* Points to the current (ending) position in the pattern. */
2474 /* `const' makes AIX compiler fail. */
2475 unsigned char *p
= pattern
;
2477 re_char
*p
= pattern
;
2479 re_char
*pend
= pattern
+ size
;
2481 /* How to translate the characters in the pattern. */
2482 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2484 /* Address of the count-byte of the most recently inserted `exactn'
2485 command. This makes it possible to tell if a new exact-match
2486 character can be added to that command or if the character requires
2487 a new `exactn' command. */
2488 unsigned char *pending_exact
= 0;
2490 /* Address of start of the most recently finished expression.
2491 This tells, e.g., postfix * where to find the start of its
2492 operand. Reset at the beginning of groups and alternatives. */
2493 unsigned char *laststart
= 0;
2495 /* Address of beginning of regexp, or inside of last group. */
2496 unsigned char *begalt
;
2498 /* Place in the uncompiled pattern (i.e., the {) to
2499 which to go back if the interval is invalid. */
2500 re_char
*beg_interval
;
2502 /* Address of the place where a forward jump should go to the end of
2503 the containing expression. Each alternative of an `or' -- except the
2504 last -- ends with a forward jump of this sort. */
2505 unsigned char *fixup_alt_jump
= 0;
2507 /* Work area for range table of charset. */
2508 struct range_table_work_area range_table_work
;
2510 /* If the object matched can contain multibyte characters. */
2511 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2513 /* Nonzero if we have pushed down into a subpattern. */
2514 int in_subpattern
= 0;
2516 /* These hold the values of p, pattern, and pend from the main
2517 pattern when we have pushed into a subpattern. */
2518 re_char
*main_p
IF_LINT (= NULL
);
2519 re_char
*main_pattern
IF_LINT (= NULL
);
2520 re_char
*main_pend
IF_LINT (= NULL
);
2524 DEBUG_PRINT1 ("\nCompiling pattern: ");
2527 unsigned debug_count
;
2529 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2530 putchar (pattern
[debug_count
]);
2535 /* Initialize the compile stack. */
2536 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2537 if (compile_stack
.stack
== NULL
)
2540 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2541 compile_stack
.avail
= 0;
2543 range_table_work
.table
= 0;
2544 range_table_work
.allocated
= 0;
2546 /* Initialize the pattern buffer. */
2547 bufp
->syntax
= syntax
;
2548 bufp
->fastmap_accurate
= 0;
2549 bufp
->not_bol
= bufp
->not_eol
= 0;
2550 bufp
->used_syntax
= 0;
2552 /* Set `used' to zero, so that if we return an error, the pattern
2553 printer (for debugging) will think there's no pattern. We reset it
2557 /* Always count groups, whether or not bufp->no_sub is set. */
2560 #if !defined emacs && !defined SYNTAX_TABLE
2561 /* Initialize the syntax table. */
2562 init_syntax_once ();
2565 if (bufp
->allocated
== 0)
2568 { /* If zero allocated, but buffer is non-null, try to realloc
2569 enough space. This loses if buffer's address is bogus, but
2570 that is the user's responsibility. */
2571 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2574 { /* Caller did not allocate a buffer. Do it for them. */
2575 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2577 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2579 bufp
->allocated
= INIT_BUF_SIZE
;
2582 begalt
= b
= bufp
->buffer
;
2584 /* Loop through the uncompiled pattern until we're at the end. */
2589 /* If this is the end of an included regexp,
2590 pop back to the main regexp and try again. */
2594 pattern
= main_pattern
;
2599 /* If this is the end of the main regexp, we are done. */
2611 /* If there's no special whitespace regexp, treat
2612 spaces normally. And don't try to do this recursively. */
2613 if (!whitespace_regexp
|| in_subpattern
)
2616 /* Peek past following spaces. */
2623 /* If the spaces are followed by a repetition op,
2624 treat them normally. */
2626 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2627 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2630 /* Replace the spaces with the whitespace regexp. */
2634 main_pattern
= pattern
;
2635 p
= pattern
= whitespace_regexp
;
2636 pend
= p
+ strlen ((const char *) p
);
2642 if ( /* If at start of pattern, it's an operator. */
2644 /* If context independent, it's an operator. */
2645 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2646 /* Otherwise, depends on what's come before. */
2647 || at_begline_loc_p (pattern
, p
, syntax
))
2648 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2657 if ( /* If at end of pattern, it's an operator. */
2659 /* If context independent, it's an operator. */
2660 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2661 /* Otherwise, depends on what's next. */
2662 || at_endline_loc_p (p
, pend
, syntax
))
2663 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2672 if ((syntax
& RE_BK_PLUS_QM
)
2673 || (syntax
& RE_LIMITED_OPS
))
2677 /* If there is no previous pattern... */
2680 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2681 FREE_STACK_RETURN (REG_BADRPT
);
2682 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2687 /* 1 means zero (many) matches is allowed. */
2688 boolean zero_times_ok
= 0, many_times_ok
= 0;
2691 /* If there is a sequence of repetition chars, collapse it
2692 down to just one (the right one). We can't combine
2693 interval operators with these because of, e.g., `a{2}*',
2694 which should only match an even number of `a's. */
2698 if ((syntax
& RE_FRUGAL
)
2699 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2703 zero_times_ok
|= c
!= '+';
2704 many_times_ok
|= c
!= '?';
2710 || (!(syntax
& RE_BK_PLUS_QM
)
2711 && (*p
== '+' || *p
== '?')))
2713 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2716 FREE_STACK_RETURN (REG_EESCAPE
);
2717 if (p
[1] == '+' || p
[1] == '?')
2718 PATFETCH (c
); /* Gobble up the backslash. */
2724 /* If we get here, we found another repeat character. */
2728 /* Star, etc. applied to an empty pattern is equivalent
2729 to an empty pattern. */
2730 if (!laststart
|| laststart
== b
)
2733 /* Now we know whether or not zero matches is allowed
2734 and also whether or not two or more matches is allowed. */
2739 boolean simple
= skip_one_char (laststart
) == b
;
2740 size_t startoffset
= 0;
2742 /* Check if the loop can match the empty string. */
2743 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2744 ? on_failure_jump
: on_failure_jump_loop
;
2745 assert (skip_one_char (laststart
) <= b
);
2747 if (!zero_times_ok
&& simple
)
2748 { /* Since simple * loops can be made faster by using
2749 on_failure_keep_string_jump, we turn simple P+
2750 into PP* if P is simple. */
2751 unsigned char *p1
, *p2
;
2752 startoffset
= b
- laststart
;
2753 GET_BUFFER_SPACE (startoffset
);
2754 p1
= b
; p2
= laststart
;
2760 GET_BUFFER_SPACE (6);
2763 STORE_JUMP (ofj
, b
, b
+ 6);
2765 /* Simple * loops can use on_failure_keep_string_jump
2766 depending on what follows. But since we don't know
2767 that yet, we leave the decision up to
2768 on_failure_jump_smart. */
2769 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2770 laststart
+ startoffset
, b
+ 6);
2772 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2777 /* A simple ? pattern. */
2778 assert (zero_times_ok
);
2779 GET_BUFFER_SPACE (3);
2780 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2784 else /* not greedy */
2785 { /* I wish the greedy and non-greedy cases could be merged. */
2787 GET_BUFFER_SPACE (7); /* We might use less. */
2790 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2792 /* The non-greedy multiple match looks like
2793 a repeat..until: we only need a conditional jump
2794 at the end of the loop. */
2795 if (emptyp
) BUF_PUSH (no_op
);
2796 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2797 : on_failure_jump
, b
, laststart
);
2801 /* The repeat...until naturally matches one or more.
2802 To also match zero times, we need to first jump to
2803 the end of the loop (its conditional jump). */
2804 INSERT_JUMP (jump
, laststart
, b
);
2810 /* non-greedy a?? */
2811 INSERT_JUMP (jump
, laststart
, b
+ 3);
2813 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2832 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2834 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2836 /* Ensure that we have enough space to push a charset: the
2837 opcode, the length count, and the bitset; 34 bytes in all. */
2838 GET_BUFFER_SPACE (34);
2842 /* We test `*p == '^' twice, instead of using an if
2843 statement, so we only need one BUF_PUSH. */
2844 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2848 /* Remember the first position in the bracket expression. */
2851 /* Push the number of bytes in the bitmap. */
2852 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2854 /* Clear the whole map. */
2855 memset (b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2857 /* charset_not matches newline according to a syntax bit. */
2858 if ((re_opcode_t
) b
[-2] == charset_not
2859 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2860 SET_LIST_BIT ('\n');
2862 /* Read in characters and ranges, setting map bits. */
2865 boolean escaped_char
= false;
2866 const unsigned char *p2
= p
;
2869 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2871 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2872 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2873 So the translation is done later in a loop. Example:
2874 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2877 /* \ might escape characters inside [...] and [^...]. */
2878 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2880 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2883 escaped_char
= true;
2887 /* Could be the end of the bracket expression. If it's
2888 not (i.e., when the bracket expression is `[]' so
2889 far), the ']' character bit gets set way below. */
2890 if (c
== ']' && p2
!= p1
)
2894 /* See if we're at the beginning of a possible character
2897 if (!escaped_char
&&
2898 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2900 /* Leave room for the null. */
2901 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2902 const unsigned char *class_beg
;
2908 /* If pattern is `[[:'. */
2909 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2914 if ((c
== ':' && *p
== ']') || p
== pend
)
2916 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2919 /* This is in any case an invalid class name. */
2924 /* If isn't a word bracketed by `[:' and `:]':
2925 undo the ending character, the letters, and
2926 leave the leading `:' and `[' (but set bits for
2928 if (c
== ':' && *p
== ']')
2930 re_wctype_t cc
= re_wctype (str
);
2933 FREE_STACK_RETURN (REG_ECTYPE
);
2935 /* Throw away the ] at the end of the character
2939 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2942 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
2943 if (re_iswctype (btowc (ch
), cc
))
2946 if (c
< (1 << BYTEWIDTH
))
2950 /* Most character classes in a multibyte match
2951 just set a flag. Exceptions are is_blank,
2952 is_digit, is_cntrl, and is_xdigit, since
2953 they can only match ASCII characters. We
2954 don't need to handle them for multibyte.
2955 They are distinguished by a negative wctype. */
2957 /* Setup the gl_state object to its buffer-defined
2958 value. This hardcodes the buffer-global
2959 syntax-table for ASCII chars, while the other chars
2960 will obey syntax-table properties. It's not ideal,
2961 but it's the way it's been done until now. */
2962 SETUP_BUFFER_SYNTAX_TABLE ();
2964 for (ch
= 0; ch
< 256; ++ch
)
2966 c
= RE_CHAR_TO_MULTIBYTE (ch
);
2967 if (! CHAR_BYTE8_P (c
)
2968 && re_iswctype (c
, cc
))
2974 if (ASCII_CHAR_P (c1
))
2976 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
2980 SET_RANGE_TABLE_WORK_AREA_BIT
2981 (range_table_work
, re_wctype_to_bit (cc
));
2983 /* In most cases the matching rule for char classes
2984 only uses the syntax table for multibyte chars,
2985 so that the content of the syntax-table it is not
2986 hardcoded in the range_table. SPACE and WORD are
2987 the two exceptions. */
2988 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
2989 bufp
->used_syntax
= 1;
2991 /* Repeat the loop. */
2996 /* Go back to right after the "[:". */
3000 /* Because the `:' may starts the range, we
3001 can't simply set bit and repeat the loop.
3002 Instead, just set it to C and handle below. */
3007 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
3010 /* Discard the `-'. */
3013 /* Fetch the character which ends the range. */
3016 if (CHAR_BYTE8_P (c1
)
3017 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
3018 /* Treat the range from a multibyte character to
3019 raw-byte character as empty. */
3024 /* Range from C to C. */
3029 if (syntax
& RE_NO_EMPTY_RANGES
)
3030 FREE_STACK_RETURN (REG_ERANGEX
);
3031 /* Else, repeat the loop. */
3036 /* Set the range into bitmap */
3037 for (; c
<= c1
; c
++)
3040 if (ch
< (1 << BYTEWIDTH
))
3047 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
3049 if (CHAR_BYTE8_P (c1
))
3050 c
= BYTE8_TO_CHAR (128);
3054 if (CHAR_BYTE8_P (c
))
3056 c
= CHAR_TO_BYTE8 (c
);
3057 c1
= CHAR_TO_BYTE8 (c1
);
3058 for (; c
<= c1
; c
++)
3063 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
3067 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
3074 /* Discard any (non)matching list bytes that are all 0 at the
3075 end of the map. Decrease the map-length byte too. */
3076 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3080 /* Build real range table from work area. */
3081 if (RANGE_TABLE_WORK_USED (range_table_work
)
3082 || RANGE_TABLE_WORK_BITS (range_table_work
))
3085 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3087 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3088 bytes for flags, two for COUNT, and three bytes for
3090 GET_BUFFER_SPACE (4 + used
* 3);
3092 /* Indicate the existence of range table. */
3093 laststart
[1] |= 0x80;
3095 /* Store the character class flag bits into the range table.
3096 If not in emacs, these flag bits are always 0. */
3097 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3098 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3100 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3101 for (i
= 0; i
< used
; i
++)
3102 STORE_CHARACTER_AND_INCR
3103 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3110 if (syntax
& RE_NO_BK_PARENS
)
3117 if (syntax
& RE_NO_BK_PARENS
)
3124 if (syntax
& RE_NEWLINE_ALT
)
3131 if (syntax
& RE_NO_BK_VBAR
)
3138 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3139 goto handle_interval
;
3145 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3147 /* Do not translate the character after the \, so that we can
3148 distinguish, e.g., \B from \b, even if we normally would
3149 translate, e.g., B to b. */
3155 if (syntax
& RE_NO_BK_PARENS
)
3156 goto normal_backslash
;
3161 regnum_t regnum
= 0;
3164 /* Look for a special (?...) construct */
3165 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3167 PATFETCH (c
); /* Gobble up the '?'. */
3173 case ':': shy
= 1; break;
3175 /* An explicitly specified regnum must start
3178 FREE_STACK_RETURN (REG_BADPAT
);
3179 case '1': case '2': case '3': case '4':
3180 case '5': case '6': case '7': case '8': case '9':
3181 regnum
= 10*regnum
+ (c
- '0'); break;
3183 /* Only (?:...) is supported right now. */
3184 FREE_STACK_RETURN (REG_BADPAT
);
3191 regnum
= ++bufp
->re_nsub
;
3193 { /* It's actually not shy, but explicitly numbered. */
3195 if (regnum
> bufp
->re_nsub
)
3196 bufp
->re_nsub
= regnum
;
3197 else if (regnum
> bufp
->re_nsub
3198 /* Ideally, we'd want to check that the specified
3199 group can't have matched (i.e. all subgroups
3200 using the same regnum are in other branches of
3201 OR patterns), but we don't currently keep track
3202 of enough info to do that easily. */
3203 || group_in_compile_stack (compile_stack
, regnum
))
3204 FREE_STACK_RETURN (REG_BADPAT
);
3207 /* It's really shy. */
3208 regnum
= - bufp
->re_nsub
;
3210 if (COMPILE_STACK_FULL
)
3212 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3213 compile_stack_elt_t
);
3214 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3216 compile_stack
.size
<<= 1;
3219 /* These are the values to restore when we hit end of this
3220 group. They are all relative offsets, so that if the
3221 whole pattern moves because of realloc, they will still
3223 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3224 COMPILE_STACK_TOP
.fixup_alt_jump
3225 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3226 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3227 COMPILE_STACK_TOP
.regnum
= regnum
;
3229 /* Do not push a start_memory for groups beyond the last one
3230 we can represent in the compiled pattern. */
3231 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3232 BUF_PUSH_2 (start_memory
, regnum
);
3234 compile_stack
.avail
++;
3239 /* If we've reached MAX_REGNUM groups, then this open
3240 won't actually generate any code, so we'll have to
3241 clear pending_exact explicitly. */
3247 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3249 if (COMPILE_STACK_EMPTY
)
3251 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3252 goto normal_backslash
;
3254 FREE_STACK_RETURN (REG_ERPAREN
);
3260 /* See similar code for backslashed left paren above. */
3261 if (COMPILE_STACK_EMPTY
)
3263 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3266 FREE_STACK_RETURN (REG_ERPAREN
);
3269 /* Since we just checked for an empty stack above, this
3270 ``can't happen''. */
3271 assert (compile_stack
.avail
!= 0);
3273 /* We don't just want to restore into `regnum', because
3274 later groups should continue to be numbered higher,
3275 as in `(ab)c(de)' -- the second group is #2. */
3278 compile_stack
.avail
--;
3279 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3281 = COMPILE_STACK_TOP
.fixup_alt_jump
3282 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3284 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3285 regnum
= COMPILE_STACK_TOP
.regnum
;
3286 /* If we've reached MAX_REGNUM groups, then this open
3287 won't actually generate any code, so we'll have to
3288 clear pending_exact explicitly. */
3291 /* We're at the end of the group, so now we know how many
3292 groups were inside this one. */
3293 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3294 BUF_PUSH_2 (stop_memory
, regnum
);
3299 case '|': /* `\|'. */
3300 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3301 goto normal_backslash
;
3303 if (syntax
& RE_LIMITED_OPS
)
3306 /* Insert before the previous alternative a jump which
3307 jumps to this alternative if the former fails. */
3308 GET_BUFFER_SPACE (3);
3309 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3313 /* The alternative before this one has a jump after it
3314 which gets executed if it gets matched. Adjust that
3315 jump so it will jump to this alternative's analogous
3316 jump (put in below, which in turn will jump to the next
3317 (if any) alternative's such jump, etc.). The last such
3318 jump jumps to the correct final destination. A picture:
3324 If we are at `b', then fixup_alt_jump right now points to a
3325 three-byte space after `a'. We'll put in the jump, set
3326 fixup_alt_jump to right after `b', and leave behind three
3327 bytes which we'll fill in when we get to after `c'. */
3331 /* Mark and leave space for a jump after this alternative,
3332 to be filled in later either by next alternative or
3333 when know we're at the end of a series of alternatives. */
3335 GET_BUFFER_SPACE (3);
3344 /* If \{ is a literal. */
3345 if (!(syntax
& RE_INTERVALS
)
3346 /* If we're at `\{' and it's not the open-interval
3348 || (syntax
& RE_NO_BK_BRACES
))
3349 goto normal_backslash
;
3353 /* If got here, then the syntax allows intervals. */
3355 /* At least (most) this many matches must be made. */
3356 int lower_bound
= 0, upper_bound
= -1;
3360 GET_UNSIGNED_NUMBER (lower_bound
);
3363 GET_UNSIGNED_NUMBER (upper_bound
);
3365 /* Interval such as `{1}' => match exactly once. */
3366 upper_bound
= lower_bound
;
3368 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3369 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3370 FREE_STACK_RETURN (REG_BADBR
);
3372 if (!(syntax
& RE_NO_BK_BRACES
))
3375 FREE_STACK_RETURN (REG_BADBR
);
3377 FREE_STACK_RETURN (REG_EESCAPE
);
3382 FREE_STACK_RETURN (REG_BADBR
);
3384 /* We just parsed a valid interval. */
3386 /* If it's invalid to have no preceding re. */
3389 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3390 FREE_STACK_RETURN (REG_BADRPT
);
3391 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3394 goto unfetch_interval
;
3397 if (upper_bound
== 0)
3398 /* If the upper bound is zero, just drop the sub pattern
3401 else if (lower_bound
== 1 && upper_bound
== 1)
3402 /* Just match it once: nothing to do here. */
3405 /* Otherwise, we have a nontrivial interval. When
3406 we're all done, the pattern will look like:
3407 set_number_at <jump count> <upper bound>
3408 set_number_at <succeed_n count> <lower bound>
3409 succeed_n <after jump addr> <succeed_n count>
3411 jump_n <succeed_n addr> <jump count>
3412 (The upper bound and `jump_n' are omitted if
3413 `upper_bound' is 1, though.) */
3415 { /* If the upper bound is > 1, we need to insert
3416 more at the end of the loop. */
3417 unsigned int nbytes
= (upper_bound
< 0 ? 3
3418 : upper_bound
> 1 ? 5 : 0);
3419 unsigned int startoffset
= 0;
3421 GET_BUFFER_SPACE (20); /* We might use less. */
3423 if (lower_bound
== 0)
3425 /* A succeed_n that starts with 0 is really a
3426 a simple on_failure_jump_loop. */
3427 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3433 /* Initialize lower bound of the `succeed_n', even
3434 though it will be set during matching by its
3435 attendant `set_number_at' (inserted next),
3436 because `re_compile_fastmap' needs to know.
3437 Jump to the `jump_n' we might insert below. */
3438 INSERT_JUMP2 (succeed_n
, laststart
,
3443 /* Code to initialize the lower bound. Insert
3444 before the `succeed_n'. The `5' is the last two
3445 bytes of this `set_number_at', plus 3 bytes of
3446 the following `succeed_n'. */
3447 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3452 if (upper_bound
< 0)
3454 /* A negative upper bound stands for infinity,
3455 in which case it degenerates to a plain jump. */
3456 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3459 else if (upper_bound
> 1)
3460 { /* More than one repetition is allowed, so
3461 append a backward jump to the `succeed_n'
3462 that starts this interval.
3464 When we've reached this during matching,
3465 we'll have matched the interval once, so
3466 jump back only `upper_bound - 1' times. */
3467 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3471 /* The location we want to set is the second
3472 parameter of the `jump_n'; that is `b-2' as
3473 an absolute address. `laststart' will be
3474 the `set_number_at' we're about to insert;
3475 `laststart+3' the number to set, the source
3476 for the relative address. But we are
3477 inserting into the middle of the pattern --
3478 so everything is getting moved up by 5.
3479 Conclusion: (b - 2) - (laststart + 3) + 5,
3480 i.e., b - laststart.
3482 We insert this at the beginning of the loop
3483 so that if we fail during matching, we'll
3484 reinitialize the bounds. */
3485 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3486 upper_bound
- 1, b
);
3491 beg_interval
= NULL
;
3496 /* If an invalid interval, match the characters as literals. */
3497 assert (beg_interval
);
3499 beg_interval
= NULL
;
3501 /* normal_char and normal_backslash need `c'. */
3504 if (!(syntax
& RE_NO_BK_BRACES
))
3506 assert (p
> pattern
&& p
[-1] == '\\');
3507 goto normal_backslash
;
3513 /* There is no way to specify the before_dot and after_dot
3514 operators. rms says this is ok. --karl */
3522 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3528 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3534 BUF_PUSH_2 (categoryspec
, c
);
3540 BUF_PUSH_2 (notcategoryspec
, c
);
3546 if (syntax
& RE_NO_GNU_OPS
)
3549 BUF_PUSH_2 (syntaxspec
, Sword
);
3554 if (syntax
& RE_NO_GNU_OPS
)
3557 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3562 if (syntax
& RE_NO_GNU_OPS
)
3568 if (syntax
& RE_NO_GNU_OPS
)
3574 if (syntax
& RE_NO_GNU_OPS
)
3583 FREE_STACK_RETURN (REG_BADPAT
);
3587 if (syntax
& RE_NO_GNU_OPS
)
3589 BUF_PUSH (wordbound
);
3593 if (syntax
& RE_NO_GNU_OPS
)
3595 BUF_PUSH (notwordbound
);
3599 if (syntax
& RE_NO_GNU_OPS
)
3605 if (syntax
& RE_NO_GNU_OPS
)
3610 case '1': case '2': case '3': case '4': case '5':
3611 case '6': case '7': case '8': case '9':
3615 if (syntax
& RE_NO_BK_REFS
)
3616 goto normal_backslash
;
3620 if (reg
> bufp
->re_nsub
|| reg
< 1
3621 /* Can't back reference to a subexp before its end. */
3622 || group_in_compile_stack (compile_stack
, reg
))
3623 FREE_STACK_RETURN (REG_ESUBREG
);
3626 BUF_PUSH_2 (duplicate
, reg
);
3633 if (syntax
& RE_BK_PLUS_QM
)
3636 goto normal_backslash
;
3640 /* You might think it would be useful for \ to mean
3641 not to translate; but if we don't translate it
3642 it will never match anything. */
3649 /* Expects the character in `c'. */
3651 /* If no exactn currently being built. */
3654 /* If last exactn not at current position. */
3655 || pending_exact
+ *pending_exact
+ 1 != b
3657 /* We have only one byte following the exactn for the count. */
3658 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3660 /* If followed by a repetition operator. */
3661 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3662 || ((syntax
& RE_BK_PLUS_QM
)
3663 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3664 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3665 || ((syntax
& RE_INTERVALS
)
3666 && ((syntax
& RE_NO_BK_BRACES
)
3667 ? p
!= pend
&& *p
== '{'
3668 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3670 /* Start building a new exactn. */
3674 BUF_PUSH_2 (exactn
, 0);
3675 pending_exact
= b
- 1;
3678 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3685 len
= CHAR_STRING (c
, b
);
3690 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3691 if (! CHAR_BYTE8_P (c1
))
3693 re_wchar_t c2
= TRANSLATE (c1
);
3695 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3701 (*pending_exact
) += len
;
3706 } /* while p != pend */
3709 /* Through the pattern now. */
3713 if (!COMPILE_STACK_EMPTY
)
3714 FREE_STACK_RETURN (REG_EPAREN
);
3716 /* If we don't want backtracking, force success
3717 the first time we reach the end of the compiled pattern. */
3718 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3721 /* We have succeeded; set the length of the buffer. */
3722 bufp
->used
= b
- bufp
->buffer
;
3727 re_compile_fastmap (bufp
);
3728 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3729 print_compiled_pattern (bufp
);
3734 #ifndef MATCH_MAY_ALLOCATE
3735 /* Initialize the failure stack to the largest possible stack. This
3736 isn't necessary unless we're trying to avoid calling alloca in
3737 the search and match routines. */
3739 int num_regs
= bufp
->re_nsub
+ 1;
3741 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3743 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3745 if (! fail_stack
.stack
)
3747 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3748 * sizeof (fail_stack_elt_t
));
3751 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3753 * sizeof (fail_stack_elt_t
)));
3756 regex_grow_registers (num_regs
);
3758 #endif /* not MATCH_MAY_ALLOCATE */
3760 FREE_STACK_RETURN (REG_NOERROR
);
3761 } /* regex_compile */
3763 /* Subroutines for `regex_compile'. */
3765 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3768 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3770 *loc
= (unsigned char) op
;
3771 STORE_NUMBER (loc
+ 1, arg
);
3775 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3778 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3780 *loc
= (unsigned char) op
;
3781 STORE_NUMBER (loc
+ 1, arg1
);
3782 STORE_NUMBER (loc
+ 3, arg2
);
3786 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3787 for OP followed by two-byte integer parameter ARG. */
3790 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3792 register unsigned char *pfrom
= end
;
3793 register unsigned char *pto
= end
+ 3;
3795 while (pfrom
!= loc
)
3798 store_op1 (op
, loc
, arg
);
3802 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3805 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3807 register unsigned char *pfrom
= end
;
3808 register unsigned char *pto
= end
+ 5;
3810 while (pfrom
!= loc
)
3813 store_op2 (op
, loc
, arg1
, arg2
);
3817 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3818 after an alternative or a begin-subexpression. We assume there is at
3819 least one character before the ^. */
3822 at_begline_loc_p (const re_char
*pattern
, const re_char
*p
, reg_syntax_t syntax
)
3824 re_char
*prev
= p
- 2;
3825 boolean odd_backslashes
;
3827 /* After a subexpression? */
3829 odd_backslashes
= (syntax
& RE_NO_BK_PARENS
) == 0;
3831 /* After an alternative? */
3832 else if (*prev
== '|')
3833 odd_backslashes
= (syntax
& RE_NO_BK_VBAR
) == 0;
3835 /* After a shy subexpression? */
3836 else if (*prev
== ':' && (syntax
& RE_SHY_GROUPS
))
3838 /* Skip over optional regnum. */
3839 while (prev
- 1 >= pattern
&& prev
[-1] >= '0' && prev
[-1] <= '9')
3842 if (!(prev
- 2 >= pattern
3843 && prev
[-1] == '?' && prev
[-2] == '('))
3846 odd_backslashes
= (syntax
& RE_NO_BK_PARENS
) == 0;
3851 /* Count the number of preceding backslashes. */
3853 while (prev
- 1 >= pattern
&& prev
[-1] == '\\')
3855 return (p
- prev
) & odd_backslashes
;
3859 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3860 at least one character after the $, i.e., `P < PEND'. */
3863 at_endline_loc_p (const re_char
*p
, const re_char
*pend
, reg_syntax_t syntax
)
3866 boolean next_backslash
= *next
== '\\';
3867 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3870 /* Before a subexpression? */
3871 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3872 : next_backslash
&& next_next
&& *next_next
== ')')
3873 /* Before an alternative? */
3874 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3875 : next_backslash
&& next_next
&& *next_next
== '|');
3879 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3880 false if it's not. */
3883 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3885 ssize_t this_element
;
3887 for (this_element
= compile_stack
.avail
- 1;
3890 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3897 If fastmap is non-NULL, go through the pattern and fill fastmap
3898 with all the possible leading chars. If fastmap is NULL, don't
3899 bother filling it up (obviously) and only return whether the
3900 pattern could potentially match the empty string.
3902 Return 1 if p..pend might match the empty string.
3903 Return 0 if p..pend matches at least one char.
3904 Return -1 if fastmap was not updated accurately. */
3907 analyse_first (const re_char
*p
, const re_char
*pend
, char *fastmap
, const int multibyte
)
3912 /* If all elements for base leading-codes in fastmap is set, this
3913 flag is set true. */
3914 boolean match_any_multibyte_characters
= false;
3918 /* The loop below works as follows:
3919 - It has a working-list kept in the PATTERN_STACK and which basically
3920 starts by only containing a pointer to the first operation.
3921 - If the opcode we're looking at is a match against some set of
3922 chars, then we add those chars to the fastmap and go on to the
3923 next work element from the worklist (done via `break').
3924 - If the opcode is a control operator on the other hand, we either
3925 ignore it (if it's meaningless at this point, such as `start_memory')
3926 or execute it (if it's a jump). If the jump has several destinations
3927 (i.e. `on_failure_jump'), then we push the other destination onto the
3929 We guarantee termination by ignoring backward jumps (more or less),
3930 so that `p' is monotonically increasing. More to the point, we
3931 never set `p' (or push) anything `<= p1'. */
3935 /* `p1' is used as a marker of how far back a `on_failure_jump'
3936 can go without being ignored. It is normally equal to `p'
3937 (which prevents any backward `on_failure_jump') except right
3938 after a plain `jump', to allow patterns such as:
3941 10: on_failure_jump 3
3942 as used for the *? operator. */
3945 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3951 /* If the first character has to match a backreference, that means
3952 that the group was empty (since it already matched). Since this
3953 is the only case that interests us here, we can assume that the
3954 backreference must match the empty string. */
3959 /* Following are the cases which match a character. These end
3965 /* If multibyte is nonzero, the first byte of each
3966 character is an ASCII or a leading code. Otherwise,
3967 each byte is a character. Thus, this works in both
3972 /* For the case of matching this unibyte regex
3973 against multibyte, we must set a leading code of
3974 the corresponding multibyte character. */
3975 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
3977 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
3984 /* We could put all the chars except for \n (and maybe \0)
3985 but we don't bother since it is generally not worth it. */
3986 if (!fastmap
) break;
3991 if (!fastmap
) break;
3993 /* Chars beyond end of bitmap are possible matches. */
3994 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3995 j
< (1 << BYTEWIDTH
); j
++)
4001 if (!fastmap
) break;
4002 not = (re_opcode_t
) *(p
- 1) == charset_not
;
4003 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
4005 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
4009 if (/* Any leading code can possibly start a character
4010 which doesn't match the specified set of characters. */
4013 /* If we can match a character class, we can match any
4014 multibyte characters. */
4015 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4016 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
4019 if (match_any_multibyte_characters
== false)
4021 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4022 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4024 match_any_multibyte_characters
= true;
4028 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4029 && match_any_multibyte_characters
== false)
4031 /* Set fastmap[I] to 1 where I is a leading code of each
4032 multibyte character in the range table. */
4034 unsigned char lc1
, lc2
;
4036 /* Make P points the range table. `+ 2' is to skip flag
4037 bits for a character class. */
4038 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
4040 /* Extract the number of ranges in range table into COUNT. */
4041 EXTRACT_NUMBER_AND_INCR (count
, p
);
4042 for (; count
> 0; count
--, p
+= 3)
4044 /* Extract the start and end of each range. */
4045 EXTRACT_CHARACTER (c
, p
);
4046 lc1
= CHAR_LEADING_CODE (c
);
4048 EXTRACT_CHARACTER (c
, p
);
4049 lc2
= CHAR_LEADING_CODE (c
);
4050 for (j
= lc1
; j
<= lc2
; j
++)
4059 if (!fastmap
) break;
4061 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
4063 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4064 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4068 /* This match depends on text properties. These end with
4069 aborting optimizations. */
4073 case notcategoryspec
:
4074 if (!fastmap
) break;
4075 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4077 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
4078 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4081 /* Any leading code can possibly start a character which
4082 has or doesn't has the specified category. */
4083 if (match_any_multibyte_characters
== false)
4085 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4086 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4088 match_any_multibyte_characters
= true;
4092 /* All cases after this match the empty string. These end with
4114 EXTRACT_NUMBER_AND_INCR (j
, p
);
4116 /* Backward jumps can only go back to code that we've already
4117 visited. `re_compile' should make sure this is true. */
4120 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4122 case on_failure_jump
:
4123 case on_failure_keep_string_jump
:
4124 case on_failure_jump_loop
:
4125 case on_failure_jump_nastyloop
:
4126 case on_failure_jump_smart
:
4132 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4133 to jump back to "just after here". */
4136 case on_failure_jump
:
4137 case on_failure_keep_string_jump
:
4138 case on_failure_jump_nastyloop
:
4139 case on_failure_jump_loop
:
4140 case on_failure_jump_smart
:
4141 EXTRACT_NUMBER_AND_INCR (j
, p
);
4143 ; /* Backward jump to be ignored. */
4145 { /* We have to look down both arms.
4146 We first go down the "straight" path so as to minimize
4147 stack usage when going through alternatives. */
4148 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4156 /* This code simply does not properly handle forward jump_n. */
4157 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4159 /* jump_n can either jump or fall through. The (backward) jump
4160 case has already been handled, so we only need to look at the
4161 fallthrough case. */
4165 /* If N == 0, it should be an on_failure_jump_loop instead. */
4166 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4168 /* We only care about one iteration of the loop, so we don't
4169 need to consider the case where this behaves like an
4186 abort (); /* We have listed all the cases. */
4189 /* Getting here means we have found the possible starting
4190 characters for one path of the pattern -- and that the empty
4191 string does not match. We need not follow this path further. */
4195 /* We reached the end without matching anything. */
4198 } /* analyse_first */
4200 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4201 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4202 characters can start a string that matches the pattern. This fastmap
4203 is used by re_search to skip quickly over impossible starting points.
4205 Character codes above (1 << BYTEWIDTH) are not represented in the
4206 fastmap, but the leading codes are represented. Thus, the fastmap
4207 indicates which character sets could start a match.
4209 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4210 area as BUFP->fastmap.
4212 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4215 Returns 0 if we succeed, -2 if an internal error. */
4218 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4220 char *fastmap
= bufp
->fastmap
;
4223 assert (fastmap
&& bufp
->buffer
);
4225 memset (fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4226 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4228 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4229 fastmap
, RE_MULTIBYTE_P (bufp
));
4230 bufp
->can_be_null
= (analysis
!= 0);
4232 } /* re_compile_fastmap */
4234 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4235 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4236 this memory for recording register information. STARTS and ENDS
4237 must be allocated using the malloc library routine, and must each
4238 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4240 If NUM_REGS == 0, then subsequent matches should allocate their own
4243 Unless this function is called, the first search or match using
4244 PATTERN_BUFFER will allocate its own register data, without
4245 freeing the old data. */
4248 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4252 bufp
->regs_allocated
= REGS_REALLOCATE
;
4253 regs
->num_regs
= num_regs
;
4254 regs
->start
= starts
;
4259 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4261 regs
->start
= regs
->end
= (regoff_t
*) 0;
4264 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4266 /* Searching routines. */
4268 /* Like re_search_2, below, but only one string is specified, and
4269 doesn't let you say where to stop matching. */
4272 re_search (struct re_pattern_buffer
*bufp
, const char *string
, size_t size
,
4273 ssize_t startpos
, ssize_t range
, struct re_registers
*regs
)
4275 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4278 WEAK_ALIAS (__re_search
, re_search
)
4280 /* Head address of virtual concatenation of string. */
4281 #define HEAD_ADDR_VSTRING(P) \
4282 (((P) >= size1 ? string2 : string1))
4284 /* Address of POS in the concatenation of virtual string. */
4285 #define POS_ADDR_VSTRING(POS) \
4286 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4288 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4289 virtual concatenation of STRING1 and STRING2, starting first at index
4290 STARTPOS, then at STARTPOS + 1, and so on.
4292 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4294 RANGE is how far to scan while trying to match. RANGE = 0 means try
4295 only at STARTPOS; in general, the last start tried is STARTPOS +
4298 In REGS, return the indices of the virtual concatenation of STRING1
4299 and STRING2 that matched the entire BUFP->buffer and its contained
4302 Do not consider matching one past the index STOP in the virtual
4303 concatenation of STRING1 and STRING2.
4305 We return either the position in the strings at which the match was
4306 found, -1 if no match, or -2 if error (such as failure
4310 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, size_t size1
,
4311 const char *str2
, size_t size2
, ssize_t startpos
, ssize_t range
,
4312 struct re_registers
*regs
, ssize_t stop
)
4315 re_char
*string1
= (re_char
*) str1
;
4316 re_char
*string2
= (re_char
*) str2
;
4317 register char *fastmap
= bufp
->fastmap
;
4318 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4319 size_t total_size
= size1
+ size2
;
4320 ssize_t endpos
= startpos
+ range
;
4321 boolean anchored_start
;
4322 /* Nonzero if we are searching multibyte string. */
4323 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4325 /* Check for out-of-range STARTPOS. */
4326 if (startpos
< 0 || startpos
> total_size
)
4329 /* Fix up RANGE if it might eventually take us outside
4330 the virtual concatenation of STRING1 and STRING2.
4331 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4333 range
= 0 - startpos
;
4334 else if (endpos
> total_size
)
4335 range
= total_size
- startpos
;
4337 /* If the search isn't to be a backwards one, don't waste time in a
4338 search for a pattern anchored at beginning of buffer. */
4339 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4348 /* In a forward search for something that starts with \=.
4349 don't keep searching past point. */
4350 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4352 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4358 /* Update the fastmap now if not correct already. */
4359 if (fastmap
&& !bufp
->fastmap_accurate
)
4360 re_compile_fastmap (bufp
);
4362 /* See whether the pattern is anchored. */
4363 anchored_start
= (bufp
->buffer
[0] == begline
);
4366 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4368 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4370 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4374 /* Loop through the string, looking for a place to start matching. */
4377 /* If the pattern is anchored,
4378 skip quickly past places we cannot match.
4379 We don't bother to treat startpos == 0 specially
4380 because that case doesn't repeat. */
4381 if (anchored_start
&& startpos
> 0)
4383 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4384 : string2
[startpos
- size1
- 1])
4389 /* If a fastmap is supplied, skip quickly over characters that
4390 cannot be the start of a match. If the pattern can match the
4391 null string, however, we don't need to skip characters; we want
4392 the first null string. */
4393 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4395 register re_char
*d
;
4396 register re_wchar_t buf_ch
;
4398 d
= POS_ADDR_VSTRING (startpos
);
4400 if (range
> 0) /* Searching forwards. */
4402 register int lim
= 0;
4403 ssize_t irange
= range
;
4405 if (startpos
< size1
&& startpos
+ range
>= size1
)
4406 lim
= range
- (size1
- startpos
);
4408 /* Written out as an if-else to avoid testing `translate'
4410 if (RE_TRANSLATE_P (translate
))
4417 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4418 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4419 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4422 range
-= buf_charlen
;
4428 register re_wchar_t ch
, translated
;
4431 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4432 translated
= RE_TRANSLATE (translate
, ch
);
4433 if (translated
!= ch
4434 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4436 if (fastmap
[buf_ch
])
4449 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4450 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4452 range
-= buf_charlen
;
4456 while (range
> lim
&& !fastmap
[*d
])
4462 startpos
+= irange
- range
;
4464 else /* Searching backwards. */
4468 buf_ch
= STRING_CHAR (d
);
4469 buf_ch
= TRANSLATE (buf_ch
);
4470 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4475 register re_wchar_t ch
, translated
;
4478 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4479 translated
= TRANSLATE (ch
);
4480 if (translated
!= ch
4481 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4483 if (! fastmap
[TRANSLATE (buf_ch
)])
4489 /* If can't match the null string, and that's all we have left, fail. */
4490 if (range
>= 0 && startpos
== total_size
&& fastmap
4491 && !bufp
->can_be_null
)
4494 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4495 startpos
, regs
, stop
);
4508 /* Update STARTPOS to the next character boundary. */
4511 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4512 int len
= BYTES_BY_CHAR_HEAD (*p
);
4530 /* Update STARTPOS to the previous character boundary. */
4533 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4535 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4537 /* Find the head of multibyte form. */
4538 PREV_CHAR_BOUNDARY (p
, phead
);
4539 range
+= p0
- 1 - p
;
4543 startpos
-= p0
- 1 - p
;
4549 WEAK_ALIAS (__re_search_2
, re_search_2
)
4551 /* Declarations and macros for re_match_2. */
4553 static int bcmp_translate (re_char
*s1
, re_char
*s2
,
4554 register ssize_t len
,
4555 RE_TRANSLATE_TYPE translate
,
4556 const int multibyte
);
4558 /* This converts PTR, a pointer into one of the search strings `string1'
4559 and `string2' into an offset from the beginning of that string. */
4560 #define POINTER_TO_OFFSET(ptr) \
4561 (FIRST_STRING_P (ptr) \
4562 ? ((regoff_t) ((ptr) - string1)) \
4563 : ((regoff_t) ((ptr) - string2 + size1)))
4565 /* Call before fetching a character with *d. This switches over to
4566 string2 if necessary.
4567 Check re_match_2_internal for a discussion of why end_match_2 might
4568 not be within string2 (but be equal to end_match_1 instead). */
4569 #define PREFETCH() \
4572 /* End of string2 => fail. */ \
4573 if (dend == end_match_2) \
4575 /* End of string1 => advance to string2. */ \
4577 dend = end_match_2; \
4580 /* Call before fetching a char with *d if you already checked other limits.
4581 This is meant for use in lookahead operations like wordend, etc..
4582 where we might need to look at parts of the string that might be
4583 outside of the LIMITs (i.e past `stop'). */
4584 #define PREFETCH_NOLIMIT() \
4588 dend = end_match_2; \
4591 /* Test if at very beginning or at very end of the virtual concatenation
4592 of `string1' and `string2'. If only one string, it's `string2'. */
4593 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4594 #define AT_STRINGS_END(d) ((d) == end2)
4596 /* Disabled due to a compiler bug -- see comment at case wordbound */
4598 /* The comment at case wordbound is following one, but we don't use
4599 AT_WORD_BOUNDARY anymore to support multibyte form.
4601 The DEC Alpha C compiler 3.x generates incorrect code for the
4602 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4603 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4604 macro and introducing temporary variables works around the bug. */
4607 /* Test if D points to a character which is word-constituent. We have
4608 two special cases to check for: if past the end of string1, look at
4609 the first character in string2; and if before the beginning of
4610 string2, look at the last character in string1. */
4611 #define WORDCHAR_P(d) \
4612 (SYNTAX ((d) == end1 ? *string2 \
4613 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4616 /* Test if the character before D and the one at D differ with respect
4617 to being word-constituent. */
4618 #define AT_WORD_BOUNDARY(d) \
4619 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4620 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4623 /* Free everything we malloc. */
4624 #ifdef MATCH_MAY_ALLOCATE
4625 # define FREE_VAR(var) \
4633 # define FREE_VARIABLES() \
4635 REGEX_FREE_STACK (fail_stack.stack); \
4636 FREE_VAR (regstart); \
4637 FREE_VAR (regend); \
4638 FREE_VAR (best_regstart); \
4639 FREE_VAR (best_regend); \
4642 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4643 #endif /* not MATCH_MAY_ALLOCATE */
4646 /* Optimization routines. */
4648 /* If the operation is a match against one or more chars,
4649 return a pointer to the next operation, else return NULL. */
4651 skip_one_char (const re_char
*p
)
4653 switch (SWITCH_ENUM_CAST (*p
++))
4664 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4667 p
= CHARSET_RANGE_TABLE (p
- 1);
4668 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4669 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4672 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4679 case notcategoryspec
:
4691 /* Jump over non-matching operations. */
4693 skip_noops (const re_char
*p
, const re_char
*pend
)
4698 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4707 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4718 /* Non-zero if "p1 matches something" implies "p2 fails". */
4720 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const re_char
*p1
, const re_char
*p2
)
4723 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4724 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4726 assert (p1
>= bufp
->buffer
&& p1
< pend
4727 && p2
>= bufp
->buffer
&& p2
<= pend
);
4729 /* Skip over open/close-group commands.
4730 If what follows this loop is a ...+ construct,
4731 look at what begins its body, since we will have to
4732 match at least one of that. */
4733 p2
= skip_noops (p2
, pend
);
4734 /* The same skip can be done for p1, except that this function
4735 is only used in the case where p1 is a simple match operator. */
4736 /* p1 = skip_noops (p1, pend); */
4738 assert (p1
>= bufp
->buffer
&& p1
< pend
4739 && p2
>= bufp
->buffer
&& p2
<= pend
);
4741 op2
= p2
== pend
? succeed
: *p2
;
4743 switch (SWITCH_ENUM_CAST (op2
))
4747 /* If we're at the end of the pattern, we can change. */
4748 if (skip_one_char (p1
))
4750 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4758 register re_wchar_t c
4759 = (re_opcode_t
) *p2
== endline
? '\n'
4760 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4762 if ((re_opcode_t
) *p1
== exactn
)
4764 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4766 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4771 else if ((re_opcode_t
) *p1
== charset
4772 || (re_opcode_t
) *p1
== charset_not
)
4774 int not = (re_opcode_t
) *p1
== charset_not
;
4776 /* Test if C is listed in charset (or charset_not)
4778 if (! multibyte
|| IS_REAL_ASCII (c
))
4780 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4781 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4784 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4785 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4787 /* `not' is equal to 1 if c would match, which means
4788 that we can't change to pop_failure_jump. */
4791 DEBUG_PRINT1 (" No match => fast loop.\n");
4795 else if ((re_opcode_t
) *p1
== anychar
4798 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4806 if ((re_opcode_t
) *p1
== exactn
)
4807 /* Reuse the code above. */
4808 return mutually_exclusive_p (bufp
, p2
, p1
);
4810 /* It is hard to list up all the character in charset
4811 P2 if it includes multibyte character. Give up in
4813 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4815 /* Now, we are sure that P2 has no range table.
4816 So, for the size of bitmap in P2, `p2[1]' is
4817 enough. But P1 may have range table, so the
4818 size of bitmap table of P1 is extracted by
4819 using macro `CHARSET_BITMAP_SIZE'.
4821 In a multibyte case, we know that all the character
4822 listed in P2 is ASCII. In a unibyte case, P1 has only a
4823 bitmap table. So, in both cases, it is enough to test
4824 only the bitmap table of P1. */
4826 if ((re_opcode_t
) *p1
== charset
)
4829 /* We win if the charset inside the loop
4830 has no overlap with the one after the loop. */
4833 && idx
< CHARSET_BITMAP_SIZE (p1
));
4835 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4839 || idx
== CHARSET_BITMAP_SIZE (p1
))
4841 DEBUG_PRINT1 (" No match => fast loop.\n");
4845 else if ((re_opcode_t
) *p1
== charset_not
)
4848 /* We win if the charset_not inside the loop lists
4849 every character listed in the charset after. */
4850 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4851 if (! (p2
[2 + idx
] == 0
4852 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4853 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4858 DEBUG_PRINT1 (" No match => fast loop.\n");
4867 switch (SWITCH_ENUM_CAST (*p1
))
4871 /* Reuse the code above. */
4872 return mutually_exclusive_p (bufp
, p2
, p1
);
4874 /* When we have two charset_not, it's very unlikely that
4875 they don't overlap. The union of the two sets of excluded
4876 chars should cover all possible chars, which, as a matter of
4877 fact, is virtually impossible in multibyte buffers. */
4883 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4885 return ((re_opcode_t
) *p1
== syntaxspec
4886 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4888 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4891 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4893 return ((re_opcode_t
) *p1
== notsyntaxspec
4894 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4896 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4899 return (((re_opcode_t
) *p1
== notsyntaxspec
4900 || (re_opcode_t
) *p1
== syntaxspec
)
4905 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4906 case notcategoryspec
:
4907 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4919 /* Matching routines. */
4921 #ifndef emacs /* Emacs never uses this. */
4922 /* re_match is like re_match_2 except it takes only a single string. */
4925 re_match (struct re_pattern_buffer
*bufp
, const char *string
,
4926 size_t size
, ssize_t pos
, struct re_registers
*regs
)
4928 regoff_t result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
,
4929 size
, pos
, regs
, size
);
4932 WEAK_ALIAS (__re_match
, re_match
)
4933 #endif /* not emacs */
4936 /* In Emacs, this is the string or buffer in which we
4937 are matching. It is used for looking up syntax properties. */
4938 Lisp_Object re_match_object
;
4941 /* re_match_2 matches the compiled pattern in BUFP against the
4942 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4943 and SIZE2, respectively). We start matching at POS, and stop
4946 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4947 store offsets for the substring each group matched in REGS. See the
4948 documentation for exactly how many groups we fill.
4950 We return -1 if no match, -2 if an internal error (such as the
4951 failure stack overflowing). Otherwise, we return the length of the
4952 matched substring. */
4955 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
,
4956 size_t size1
, const char *string2
, size_t size2
, ssize_t pos
,
4957 struct re_registers
*regs
, ssize_t stop
)
4963 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4964 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4965 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4968 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4969 (re_char
*) string2
, size2
,
4973 WEAK_ALIAS (__re_match_2
, re_match_2
)
4976 /* This is a separate function so that we can force an alloca cleanup
4979 re_match_2_internal (struct re_pattern_buffer
*bufp
, const re_char
*string1
,
4980 size_t size1
, const re_char
*string2
, size_t size2
,
4981 ssize_t pos
, struct re_registers
*regs
, ssize_t stop
)
4983 /* General temporaries. */
4987 /* Just past the end of the corresponding string. */
4988 re_char
*end1
, *end2
;
4990 /* Pointers into string1 and string2, just past the last characters in
4991 each to consider matching. */
4992 re_char
*end_match_1
, *end_match_2
;
4994 /* Where we are in the data, and the end of the current string. */
4997 /* Used sometimes to remember where we were before starting matching
4998 an operator so that we can go back in case of failure. This "atomic"
4999 behavior of matching opcodes is indispensable to the correctness
5000 of the on_failure_keep_string_jump optimization. */
5003 /* Where we are in the pattern, and the end of the pattern. */
5004 re_char
*p
= bufp
->buffer
;
5005 re_char
*pend
= p
+ bufp
->used
;
5007 /* We use this to map every character in the string. */
5008 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
5010 /* Nonzero if BUFP is setup from a multibyte regex. */
5011 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
5013 /* Nonzero if STRING1/STRING2 are multibyte. */
5014 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
5016 /* Failure point stack. Each place that can handle a failure further
5017 down the line pushes a failure point on this stack. It consists of
5018 regstart, and regend for all registers corresponding to
5019 the subexpressions we're currently inside, plus the number of such
5020 registers, and, finally, two char *'s. The first char * is where
5021 to resume scanning the pattern; the second one is where to resume
5022 scanning the strings. */
5023 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5024 fail_stack_type fail_stack
;
5027 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
5030 #if defined REL_ALLOC && defined REGEX_MALLOC
5031 /* This holds the pointer to the failure stack, when
5032 it is allocated relocatably. */
5033 fail_stack_elt_t
*failure_stack_ptr
;
5036 /* We fill all the registers internally, independent of what we
5037 return, for use in backreferences. The number here includes
5038 an element for register zero. */
5039 size_t num_regs
= bufp
->re_nsub
+ 1;
5041 /* Information on the contents of registers. These are pointers into
5042 the input strings; they record just what was matched (on this
5043 attempt) by a subexpression part of the pattern, that is, the
5044 regnum-th regstart pointer points to where in the pattern we began
5045 matching and the regnum-th regend points to right after where we
5046 stopped matching the regnum-th subexpression. (The zeroth register
5047 keeps track of what the whole pattern matches.) */
5048 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5049 re_char
**regstart
, **regend
;
5052 /* The following record the register info as found in the above
5053 variables when we find a match better than any we've seen before.
5054 This happens as we backtrack through the failure points, which in
5055 turn happens only if we have not yet matched the entire string. */
5056 unsigned best_regs_set
= false;
5057 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5058 re_char
**best_regstart
, **best_regend
;
5061 /* Logically, this is `best_regend[0]'. But we don't want to have to
5062 allocate space for that if we're not allocating space for anything
5063 else (see below). Also, we never need info about register 0 for
5064 any of the other register vectors, and it seems rather a kludge to
5065 treat `best_regend' differently than the rest. So we keep track of
5066 the end of the best match so far in a separate variable. We
5067 initialize this to NULL so that when we backtrack the first time
5068 and need to test it, it's not garbage. */
5069 re_char
*match_end
= NULL
;
5072 /* Counts the total number of registers pushed. */
5073 unsigned num_regs_pushed
= 0;
5076 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5080 #ifdef MATCH_MAY_ALLOCATE
5081 /* Do not bother to initialize all the register variables if there are
5082 no groups in the pattern, as it takes a fair amount of time. If
5083 there are groups, we include space for register 0 (the whole
5084 pattern), even though we never use it, since it simplifies the
5085 array indexing. We should fix this. */
5088 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5089 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5090 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5091 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5093 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5101 /* We must initialize all our variables to NULL, so that
5102 `FREE_VARIABLES' doesn't try to free them. */
5103 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5105 #endif /* MATCH_MAY_ALLOCATE */
5107 /* The starting position is bogus. */
5108 if (pos
< 0 || pos
> size1
+ size2
)
5114 /* Initialize subexpression text positions to -1 to mark ones that no
5115 start_memory/stop_memory has been seen for. Also initialize the
5116 register information struct. */
5117 for (reg
= 1; reg
< num_regs
; reg
++)
5118 regstart
[reg
] = regend
[reg
] = NULL
;
5120 /* We move `string1' into `string2' if the latter's empty -- but not if
5121 `string1' is null. */
5122 if (size2
== 0 && string1
!= NULL
)
5129 end1
= string1
+ size1
;
5130 end2
= string2
+ size2
;
5132 /* `p' scans through the pattern as `d' scans through the data.
5133 `dend' is the end of the input string that `d' points within. `d'
5134 is advanced into the following input string whenever necessary, but
5135 this happens before fetching; therefore, at the beginning of the
5136 loop, `d' can be pointing at the end of a string, but it cannot
5140 /* Only match within string2. */
5141 d
= string2
+ pos
- size1
;
5142 dend
= end_match_2
= string2
+ stop
- size1
;
5143 end_match_1
= end1
; /* Just to give it a value. */
5149 /* Only match within string1. */
5150 end_match_1
= string1
+ stop
;
5152 When we reach end_match_1, PREFETCH normally switches to string2.
5153 But in the present case, this means that just doing a PREFETCH
5154 makes us jump from `stop' to `gap' within the string.
5155 What we really want here is for the search to stop as
5156 soon as we hit end_match_1. That's why we set end_match_2
5157 to end_match_1 (since PREFETCH fails as soon as we hit
5159 end_match_2
= end_match_1
;
5162 { /* It's important to use this code when stop == size so that
5163 moving `d' from end1 to string2 will not prevent the d == dend
5164 check from catching the end of string. */
5166 end_match_2
= string2
+ stop
- size1
;
5172 DEBUG_PRINT1 ("The compiled pattern is: ");
5173 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5174 DEBUG_PRINT1 ("The string to match is: `");
5175 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5176 DEBUG_PRINT1 ("'\n");
5178 /* This loops over pattern commands. It exits by returning from the
5179 function if the match is complete, or it drops through if the match
5180 fails at this starting point in the input data. */
5183 DEBUG_PRINT2 ("\n%p: ", p
);
5186 { /* End of pattern means we might have succeeded. */
5187 DEBUG_PRINT1 ("end of pattern ... ");
5189 /* If we haven't matched the entire string, and we want the
5190 longest match, try backtracking. */
5191 if (d
!= end_match_2
)
5193 /* 1 if this match ends in the same string (string1 or string2)
5194 as the best previous match. */
5195 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5196 == FIRST_STRING_P (d
));
5197 /* 1 if this match is the best seen so far. */
5198 boolean best_match_p
;
5200 /* AIX compiler got confused when this was combined
5201 with the previous declaration. */
5203 best_match_p
= d
> match_end
;
5205 best_match_p
= !FIRST_STRING_P (d
);
5207 DEBUG_PRINT1 ("backtracking.\n");
5209 if (!FAIL_STACK_EMPTY ())
5210 { /* More failure points to try. */
5212 /* If exceeds best match so far, save it. */
5213 if (!best_regs_set
|| best_match_p
)
5215 best_regs_set
= true;
5218 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5220 for (reg
= 1; reg
< num_regs
; reg
++)
5222 best_regstart
[reg
] = regstart
[reg
];
5223 best_regend
[reg
] = regend
[reg
];
5229 /* If no failure points, don't restore garbage. And if
5230 last match is real best match, don't restore second
5232 else if (best_regs_set
&& !best_match_p
)
5235 /* Restore best match. It may happen that `dend ==
5236 end_match_1' while the restored d is in string2.
5237 For example, the pattern `x.*y.*z' against the
5238 strings `x-' and `y-z-', if the two strings are
5239 not consecutive in memory. */
5240 DEBUG_PRINT1 ("Restoring best registers.\n");
5243 dend
= ((d
>= string1
&& d
<= end1
)
5244 ? end_match_1
: end_match_2
);
5246 for (reg
= 1; reg
< num_regs
; reg
++)
5248 regstart
[reg
] = best_regstart
[reg
];
5249 regend
[reg
] = best_regend
[reg
];
5252 } /* d != end_match_2 */
5255 DEBUG_PRINT1 ("Accepting match.\n");
5257 /* If caller wants register contents data back, do it. */
5258 if (regs
&& !bufp
->no_sub
)
5260 /* Have the register data arrays been allocated? */
5261 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5262 { /* No. So allocate them with malloc. We need one
5263 extra element beyond `num_regs' for the `-1' marker
5265 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5266 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5267 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5268 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5273 bufp
->regs_allocated
= REGS_REALLOCATE
;
5275 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5276 { /* Yes. If we need more elements than were already
5277 allocated, reallocate them. If we need fewer, just
5279 if (regs
->num_regs
< num_regs
+ 1)
5281 regs
->num_regs
= num_regs
+ 1;
5282 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5283 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5284 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5293 /* These braces fend off a "empty body in an else-statement"
5294 warning under GCC when assert expands to nothing. */
5295 assert (bufp
->regs_allocated
== REGS_FIXED
);
5298 /* Convert the pointer data in `regstart' and `regend' to
5299 indices. Register zero has to be set differently,
5300 since we haven't kept track of any info for it. */
5301 if (regs
->num_regs
> 0)
5303 regs
->start
[0] = pos
;
5304 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5307 /* Go through the first `min (num_regs, regs->num_regs)'
5308 registers, since that is all we initialized. */
5309 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5311 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5312 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5316 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
5318 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
5322 /* If the regs structure we return has more elements than
5323 were in the pattern, set the extra elements to -1. If
5324 we (re)allocated the registers, this is the case,
5325 because we always allocate enough to have at least one
5327 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5328 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5329 } /* regs && !bufp->no_sub */
5331 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5332 nfailure_points_pushed
, nfailure_points_popped
,
5333 nfailure_points_pushed
- nfailure_points_popped
);
5334 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
5336 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
5338 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5344 /* Otherwise match next pattern command. */
5345 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5347 /* Ignore these. Used to ignore the n of succeed_n's which
5348 currently have n == 0. */
5350 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5354 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5357 /* Match the next n pattern characters exactly. The following
5358 byte in the pattern defines n, and the n bytes after that
5359 are the characters to match. */
5362 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5364 /* Remember the start point to rollback upon failure. */
5368 /* This is written out as an if-else so we don't waste time
5369 testing `translate' inside the loop. */
5370 if (RE_TRANSLATE_P (translate
))
5374 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5394 /* The cost of testing `translate' is comparatively small. */
5395 if (target_multibyte
)
5398 int pat_charlen
, buf_charlen
;
5403 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5406 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5409 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5411 if (TRANSLATE (buf_ch
) != pat_ch
)
5419 mcnt
-= pat_charlen
;
5431 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5432 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5439 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5440 if (! CHAR_BYTE8_P (buf_ch
))
5442 buf_ch
= TRANSLATE (buf_ch
);
5443 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5449 if (buf_ch
!= pat_ch
)
5462 /* Match any character except possibly a newline or a null. */
5468 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5471 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5473 buf_ch
= TRANSLATE (buf_ch
);
5475 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5477 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5478 && buf_ch
== '\000'))
5481 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5490 register unsigned int c
;
5491 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5494 /* Start of actual range_table, or end of bitmap if there is no
5496 re_char
*range_table
IF_LINT (= NULL
);
5498 /* Nonzero if there is a range table. */
5499 int range_table_exists
;
5501 /* Number of ranges of range table. This is not included
5502 in the initial byte-length of the command. */
5505 /* Whether matching against a unibyte character. */
5506 boolean unibyte_char
= false;
5508 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5510 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5512 if (range_table_exists
)
5514 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5515 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5519 c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5520 if (target_multibyte
)
5525 c1
= RE_CHAR_TO_UNIBYTE (c
);
5528 unibyte_char
= true;
5534 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5536 if (! CHAR_BYTE8_P (c1
))
5538 c1
= TRANSLATE (c1
);
5539 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5542 unibyte_char
= true;
5547 unibyte_char
= true;
5550 if (unibyte_char
&& c
< (1 << BYTEWIDTH
))
5551 { /* Lookup bitmap. */
5552 /* Cast to `unsigned' instead of `unsigned char' in
5553 case the bit list is a full 32 bytes long. */
5554 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5555 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5559 else if (range_table_exists
)
5561 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5563 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5564 | (class_bits
& BIT_MULTIBYTE
)
5565 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5566 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5567 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5568 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5571 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5575 if (range_table_exists
)
5576 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5578 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5580 if (!not) goto fail
;
5587 /* The beginning of a group is represented by start_memory.
5588 The argument is the register number. The text
5589 matched within the group is recorded (in the internal
5590 registers data structure) under the register number. */
5592 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5594 /* In case we need to undo this operation (via backtracking). */
5595 PUSH_FAILURE_REG ((unsigned int)*p
);
5598 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5599 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5601 /* Move past the register number and inner group count. */
5606 /* The stop_memory opcode represents the end of a group. Its
5607 argument is the same as start_memory's: the register number. */
5609 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5611 assert (!REG_UNSET (regstart
[*p
]));
5612 /* Strictly speaking, there should be code such as:
5614 assert (REG_UNSET (regend[*p]));
5615 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5617 But the only info to be pushed is regend[*p] and it is known to
5618 be UNSET, so there really isn't anything to push.
5619 Not pushing anything, on the other hand deprives us from the
5620 guarantee that regend[*p] is UNSET since undoing this operation
5621 will not reset its value properly. This is not important since
5622 the value will only be read on the next start_memory or at
5623 the very end and both events can only happen if this stop_memory
5627 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5629 /* Move past the register number and the inner group count. */
5634 /* \<digit> has been turned into a `duplicate' command which is
5635 followed by the numeric value of <digit> as the register number. */
5638 register re_char
*d2
, *dend2
;
5639 int regno
= *p
++; /* Get which register to match against. */
5640 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5642 /* Can't back reference a group which we've never matched. */
5643 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5646 /* Where in input to try to start matching. */
5647 d2
= regstart
[regno
];
5649 /* Remember the start point to rollback upon failure. */
5652 /* Where to stop matching; if both the place to start and
5653 the place to stop matching are in the same string, then
5654 set to the place to stop, otherwise, for now have to use
5655 the end of the first string. */
5657 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5658 == FIRST_STRING_P (regend
[regno
]))
5659 ? regend
[regno
] : end_match_1
);
5662 /* If necessary, advance to next segment in register
5666 if (dend2
== end_match_2
) break;
5667 if (dend2
== regend
[regno
]) break;
5669 /* End of string1 => advance to string2. */
5671 dend2
= regend
[regno
];
5673 /* At end of register contents => success */
5674 if (d2
== dend2
) break;
5676 /* If necessary, advance to next segment in data. */
5679 /* How many characters left in this segment to match. */
5682 /* Want how many consecutive characters we can match in
5683 one shot, so, if necessary, adjust the count. */
5684 if (mcnt
> dend2
- d2
)
5687 /* Compare that many; failure if mismatch, else move
5689 if (RE_TRANSLATE_P (translate
)
5690 ? bcmp_translate (d
, d2
, mcnt
, translate
, target_multibyte
)
5691 : memcmp (d
, d2
, mcnt
))
5696 d
+= mcnt
, d2
+= mcnt
;
5702 /* begline matches the empty string at the beginning of the string
5703 (unless `not_bol' is set in `bufp'), and after newlines. */
5705 DEBUG_PRINT1 ("EXECUTING begline.\n");
5707 if (AT_STRINGS_BEG (d
))
5709 if (!bufp
->not_bol
) break;
5714 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5718 /* In all other cases, we fail. */
5722 /* endline is the dual of begline. */
5724 DEBUG_PRINT1 ("EXECUTING endline.\n");
5726 if (AT_STRINGS_END (d
))
5728 if (!bufp
->not_eol
) break;
5732 PREFETCH_NOLIMIT ();
5739 /* Match at the very beginning of the data. */
5741 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5742 if (AT_STRINGS_BEG (d
))
5747 /* Match at the very end of the data. */
5749 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5750 if (AT_STRINGS_END (d
))
5755 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5756 pushes NULL as the value for the string on the stack. Then
5757 `POP_FAILURE_POINT' will keep the current value for the
5758 string, instead of restoring it. To see why, consider
5759 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5760 then the . fails against the \n. But the next thing we want
5761 to do is match the \n against the \n; if we restored the
5762 string value, we would be back at the foo.
5764 Because this is used only in specific cases, we don't need to
5765 check all the things that `on_failure_jump' does, to make
5766 sure the right things get saved on the stack. Hence we don't
5767 share its code. The only reason to push anything on the
5768 stack at all is that otherwise we would have to change
5769 `anychar's code to do something besides goto fail in this
5770 case; that seems worse than this. */
5771 case on_failure_keep_string_jump
:
5772 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5773 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5776 PUSH_FAILURE_POINT (p
- 3, NULL
);
5779 /* A nasty loop is introduced by the non-greedy *? and +?.
5780 With such loops, the stack only ever contains one failure point
5781 at a time, so that a plain on_failure_jump_loop kind of
5782 cycle detection cannot work. Worse yet, such a detection
5783 can not only fail to detect a cycle, but it can also wrongly
5784 detect a cycle (between different instantiations of the same
5786 So the method used for those nasty loops is a little different:
5787 We use a special cycle-detection-stack-frame which is pushed
5788 when the on_failure_jump_nastyloop failure-point is *popped*.
5789 This special frame thus marks the beginning of one iteration
5790 through the loop and we can hence easily check right here
5791 whether something matched between the beginning and the end of
5793 case on_failure_jump_nastyloop
:
5794 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5795 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5798 assert ((re_opcode_t
)p
[-4] == no_op
);
5801 CHECK_INFINITE_LOOP (p
- 4, d
);
5803 /* If there's a cycle, just continue without pushing
5804 this failure point. The failure point is the "try again"
5805 option, which shouldn't be tried.
5806 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5807 PUSH_FAILURE_POINT (p
- 3, d
);
5811 /* Simple loop detecting on_failure_jump: just check on the
5812 failure stack if the same spot was already hit earlier. */
5813 case on_failure_jump_loop
:
5815 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5816 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5820 CHECK_INFINITE_LOOP (p
- 3, d
);
5822 /* If there's a cycle, get out of the loop, as if the matching
5823 had failed. We used to just `goto fail' here, but that was
5824 aborting the search a bit too early: we want to keep the
5825 empty-loop-match and keep matching after the loop.
5826 We want (x?)*y\1z to match both xxyz and xxyxz. */
5829 PUSH_FAILURE_POINT (p
- 3, d
);
5834 /* Uses of on_failure_jump:
5836 Each alternative starts with an on_failure_jump that points
5837 to the beginning of the next alternative. Each alternative
5838 except the last ends with a jump that in effect jumps past
5839 the rest of the alternatives. (They really jump to the
5840 ending jump of the following alternative, because tensioning
5841 these jumps is a hassle.)
5843 Repeats start with an on_failure_jump that points past both
5844 the repetition text and either the following jump or
5845 pop_failure_jump back to this on_failure_jump. */
5846 case on_failure_jump
:
5847 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5848 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5851 PUSH_FAILURE_POINT (p
-3, d
);
5854 /* This operation is used for greedy *.
5855 Compare the beginning of the repeat with what in the
5856 pattern follows its end. If we can establish that there
5857 is nothing that they would both match, i.e., that we
5858 would have to backtrack because of (as in, e.g., `a*a')
5859 then we can use a non-backtracking loop based on
5860 on_failure_keep_string_jump instead of on_failure_jump. */
5861 case on_failure_jump_smart
:
5862 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5863 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5866 re_char
*p1
= p
; /* Next operation. */
5867 /* Here, we discard `const', making re_match non-reentrant. */
5868 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5869 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5871 p
-= 3; /* Reset so that we will re-execute the
5872 instruction once it's been changed. */
5874 EXTRACT_NUMBER (mcnt
, p2
- 2);
5876 /* Ensure this is a indeed the trivial kind of loop
5877 we are expecting. */
5878 assert (skip_one_char (p1
) == p2
- 3);
5879 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5880 DEBUG_STATEMENT (debug
+= 2);
5881 if (mutually_exclusive_p (bufp
, p1
, p2
))
5883 /* Use a fast `on_failure_keep_string_jump' loop. */
5884 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5885 *p3
= (unsigned char) on_failure_keep_string_jump
;
5886 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5890 /* Default to a safe `on_failure_jump' loop. */
5891 DEBUG_PRINT1 (" smart default => slow loop.\n");
5892 *p3
= (unsigned char) on_failure_jump
;
5894 DEBUG_STATEMENT (debug
-= 2);
5898 /* Unconditionally jump (without popping any failure points). */
5901 IMMEDIATE_QUIT_CHECK
;
5902 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5903 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5904 p
+= mcnt
; /* Do the jump. */
5905 DEBUG_PRINT2 ("(to %p).\n", p
);
5909 /* Have to succeed matching what follows at least n times.
5910 After that, handle like `on_failure_jump'. */
5912 /* Signedness doesn't matter since we only compare MCNT to 0. */
5913 EXTRACT_NUMBER (mcnt
, p
+ 2);
5914 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5916 /* Originally, mcnt is how many times we HAVE to succeed. */
5919 /* Here, we discard `const', making re_match non-reentrant. */
5920 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5923 PUSH_NUMBER (p2
, mcnt
);
5926 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5931 /* Signedness doesn't matter since we only compare MCNT to 0. */
5932 EXTRACT_NUMBER (mcnt
, p
+ 2);
5933 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5935 /* Originally, this is how many times we CAN jump. */
5938 /* Here, we discard `const', making re_match non-reentrant. */
5939 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5941 PUSH_NUMBER (p2
, mcnt
);
5942 goto unconditional_jump
;
5944 /* If don't have to jump any more, skip over the rest of command. */
5951 unsigned char *p2
; /* Location of the counter. */
5952 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5954 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5955 /* Here, we discard `const', making re_match non-reentrant. */
5956 p2
= (unsigned char*) p
+ mcnt
;
5957 /* Signedness doesn't matter since we only copy MCNT's bits . */
5958 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5959 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5960 PUSH_NUMBER (p2
, mcnt
);
5967 boolean
not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5968 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5970 /* We SUCCEED (or FAIL) in one of the following cases: */
5972 /* Case 1: D is at the beginning or the end of string. */
5973 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5977 /* C1 is the character before D, S1 is the syntax of C1, C2
5978 is the character at D, and S2 is the syntax of C2. */
5983 ssize_t offset
= PTR_TO_OFFSET (d
- 1);
5984 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5985 UPDATE_SYNTAX_TABLE (charpos
);
5987 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5990 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5992 PREFETCH_NOLIMIT ();
5993 GET_CHAR_AFTER (c2
, d
, dummy
);
5996 if (/* Case 2: Only one of S1 and S2 is Sword. */
5997 ((s1
== Sword
) != (s2
== Sword
))
5998 /* Case 3: Both of S1 and S2 are Sword, and macro
5999 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
6000 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
6010 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
6012 /* We FAIL in one of the following cases: */
6014 /* Case 1: D is at the end of string. */
6015 if (AT_STRINGS_END (d
))
6019 /* C1 is the character before D, S1 is the syntax of C1, C2
6020 is the character at D, and S2 is the syntax of C2. */
6025 ssize_t offset
= PTR_TO_OFFSET (d
);
6026 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6027 UPDATE_SYNTAX_TABLE (charpos
);
6030 GET_CHAR_AFTER (c2
, d
, dummy
);
6033 /* Case 2: S2 is not Sword. */
6037 /* Case 3: D is not at the beginning of string ... */
6038 if (!AT_STRINGS_BEG (d
))
6040 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6042 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6046 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6048 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6055 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6057 /* We FAIL in one of the following cases: */
6059 /* Case 1: D is at the beginning of string. */
6060 if (AT_STRINGS_BEG (d
))
6064 /* C1 is the character before D, S1 is the syntax of C1, C2
6065 is the character at D, and S2 is the syntax of C2. */
6070 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6071 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6072 UPDATE_SYNTAX_TABLE (charpos
);
6074 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6077 /* Case 2: S1 is not Sword. */
6081 /* Case 3: D is not at the end of string ... */
6082 if (!AT_STRINGS_END (d
))
6084 PREFETCH_NOLIMIT ();
6085 GET_CHAR_AFTER (c2
, d
, dummy
);
6087 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6091 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6093 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6100 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6102 /* We FAIL in one of the following cases: */
6104 /* Case 1: D is at the end of string. */
6105 if (AT_STRINGS_END (d
))
6109 /* C1 is the character before D, S1 is the syntax of C1, C2
6110 is the character at D, and S2 is the syntax of C2. */
6114 ssize_t offset
= PTR_TO_OFFSET (d
);
6115 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6116 UPDATE_SYNTAX_TABLE (charpos
);
6119 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6122 /* Case 2: S2 is neither Sword nor Ssymbol. */
6123 if (s2
!= Sword
&& s2
!= Ssymbol
)
6126 /* Case 3: D is not at the beginning of string ... */
6127 if (!AT_STRINGS_BEG (d
))
6129 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6131 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6135 /* ... and S1 is Sword or Ssymbol. */
6136 if (s1
== Sword
|| s1
== Ssymbol
)
6143 DEBUG_PRINT1 ("EXECUTING symend.\n");
6145 /* We FAIL in one of the following cases: */
6147 /* Case 1: D is at the beginning of string. */
6148 if (AT_STRINGS_BEG (d
))
6152 /* C1 is the character before D, S1 is the syntax of C1, C2
6153 is the character at D, and S2 is the syntax of C2. */
6157 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6158 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6159 UPDATE_SYNTAX_TABLE (charpos
);
6161 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6164 /* Case 2: S1 is neither Ssymbol nor Sword. */
6165 if (s1
!= Sword
&& s1
!= Ssymbol
)
6168 /* Case 3: D is not at the end of string ... */
6169 if (!AT_STRINGS_END (d
))
6171 PREFETCH_NOLIMIT ();
6172 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6174 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6178 /* ... and S2 is Sword or Ssymbol. */
6179 if (s2
== Sword
|| s2
== Ssymbol
)
6188 boolean
not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6190 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
6194 ssize_t offset
= PTR_TO_OFFSET (d
);
6195 ssize_t pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6196 UPDATE_SYNTAX_TABLE (pos1
);
6203 GET_CHAR_AFTER (c
, d
, len
);
6204 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6213 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6214 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6219 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6220 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6225 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6226 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6231 case notcategoryspec
:
6233 boolean
not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6235 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n",
6236 not?"not":"", mcnt
);
6242 GET_CHAR_AFTER (c
, d
, len
);
6243 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6255 continue; /* Successfully executed one pattern command; keep going. */
6258 /* We goto here if a matching operation fails. */
6260 IMMEDIATE_QUIT_CHECK
;
6261 if (!FAIL_STACK_EMPTY ())
6264 /* A restart point is known. Restore to that state. */
6265 DEBUG_PRINT1 ("\nFAIL:\n");
6266 POP_FAILURE_POINT (str
, pat
);
6267 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
6269 case on_failure_keep_string_jump
:
6270 assert (str
== NULL
);
6271 goto continue_failure_jump
;
6273 case on_failure_jump_nastyloop
:
6274 assert ((re_opcode_t
)pat
[-2] == no_op
);
6275 PUSH_FAILURE_POINT (pat
- 2, str
);
6278 case on_failure_jump_loop
:
6279 case on_failure_jump
:
6282 continue_failure_jump
:
6283 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6288 /* A special frame used for nastyloops. */
6295 assert (p
>= bufp
->buffer
&& p
<= pend
);
6297 if (d
>= string1
&& d
<= end1
)
6301 break; /* Matching at this starting point really fails. */
6305 goto restore_best_regs
;
6309 return -1; /* Failure to match. */
6312 /* Subroutine definitions for re_match_2. */
6314 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6315 bytes; nonzero otherwise. */
6318 bcmp_translate (const re_char
*s1
, const re_char
*s2
, register ssize_t len
,
6319 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6321 register re_char
*p1
= s1
, *p2
= s2
;
6322 re_char
*p1_end
= s1
+ len
;
6323 re_char
*p2_end
= s2
+ len
;
6325 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6326 different lengths, but relying on a single `len' would break this. -sm */
6327 while (p1
< p1_end
&& p2
< p2_end
)
6329 int p1_charlen
, p2_charlen
;
6330 re_wchar_t p1_ch
, p2_ch
;
6332 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6333 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6335 if (RE_TRANSLATE (translate
, p1_ch
)
6336 != RE_TRANSLATE (translate
, p2_ch
))
6339 p1
+= p1_charlen
, p2
+= p2_charlen
;
6342 if (p1
!= p1_end
|| p2
!= p2_end
)
6348 /* Entry points for GNU code. */
6350 /* re_compile_pattern is the GNU regular expression compiler: it
6351 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6352 Returns 0 if the pattern was valid, otherwise an error string.
6354 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6355 are set in BUFP on entry.
6357 We call regex_compile to do the actual compilation. */
6360 re_compile_pattern (const char *pattern
, size_t length
,
6361 struct re_pattern_buffer
*bufp
)
6365 /* GNU code is written to assume at least RE_NREGS registers will be set
6366 (and at least one extra will be -1). */
6367 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6369 /* And GNU code determines whether or not to get register information
6370 by passing null for the REGS argument to re_match, etc., not by
6374 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6378 return gettext (re_error_msgid
[(int) ret
]);
6380 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6382 /* Entry points compatible with 4.2 BSD regex library. We don't define
6383 them unless specifically requested. */
6385 #if defined _REGEX_RE_COMP || defined _LIBC
6387 /* BSD has one and only one pattern buffer. */
6388 static struct re_pattern_buffer re_comp_buf
;
6392 /* Make these definitions weak in libc, so POSIX programs can redefine
6393 these names if they don't use our functions, and still use
6394 regcomp/regexec below without link errors. */
6397 re_comp (const char *s
)
6403 if (!re_comp_buf
.buffer
)
6404 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6405 return (char *) gettext ("No previous regular expression");
6409 if (!re_comp_buf
.buffer
)
6411 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
6412 if (re_comp_buf
.buffer
== NULL
)
6413 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6414 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6415 re_comp_buf
.allocated
= 200;
6417 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6418 if (re_comp_buf
.fastmap
== NULL
)
6419 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6420 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6423 /* Since `re_exec' always passes NULL for the `regs' argument, we
6424 don't need to initialize the pattern buffer fields which affect it. */
6426 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6431 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6432 return (char *) gettext (re_error_msgid
[(int) ret
]);
6440 re_exec (const char *s
)
6442 const size_t len
= strlen (s
);
6444 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
6446 #endif /* _REGEX_RE_COMP */
6448 /* POSIX.2 functions. Don't define these for Emacs. */
6452 /* regcomp takes a regular expression as a string and compiles it.
6454 PREG is a regex_t *. We do not expect any fields to be initialized,
6455 since POSIX says we shouldn't. Thus, we set
6457 `buffer' to the compiled pattern;
6458 `used' to the length of the compiled pattern;
6459 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6460 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6461 RE_SYNTAX_POSIX_BASIC;
6462 `fastmap' to an allocated space for the fastmap;
6463 `fastmap_accurate' to zero;
6464 `re_nsub' to the number of subexpressions in PATTERN.
6466 PATTERN is the address of the pattern string.
6468 CFLAGS is a series of bits which affect compilation.
6470 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6471 use POSIX basic syntax.
6473 If REG_NEWLINE is set, then . and [^...] don't match newline.
6474 Also, regexec will try a match beginning after every newline.
6476 If REG_ICASE is set, then we considers upper- and lowercase
6477 versions of letters to be equivalent when matching.
6479 If REG_NOSUB is set, then when PREG is passed to regexec, that
6480 routine will report only success or failure, and nothing about the
6483 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6484 the return codes and their meanings.) */
6487 regcomp (regex_t
*__restrict preg
, const char *__restrict pattern
,
6492 = (cflags
& REG_EXTENDED
) ?
6493 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6495 /* regex_compile will allocate the space for the compiled pattern. */
6497 preg
->allocated
= 0;
6500 /* Try to allocate space for the fastmap. */
6501 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6503 if (cflags
& REG_ICASE
)
6508 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6509 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6510 if (preg
->translate
== NULL
)
6511 return (int) REG_ESPACE
;
6513 /* Map uppercase characters to corresponding lowercase ones. */
6514 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6515 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6518 preg
->translate
= NULL
;
6520 /* If REG_NEWLINE is set, newlines are treated differently. */
6521 if (cflags
& REG_NEWLINE
)
6522 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6523 syntax
&= ~RE_DOT_NEWLINE
;
6524 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6527 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6529 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6531 /* POSIX says a null character in the pattern terminates it, so we
6532 can use strlen here in compiling the pattern. */
6533 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6535 /* POSIX doesn't distinguish between an unmatched open-group and an
6536 unmatched close-group: both are REG_EPAREN. */
6537 if (ret
== REG_ERPAREN
)
6540 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6541 { /* Compute the fastmap now, since regexec cannot modify the pattern
6543 re_compile_fastmap (preg
);
6544 if (preg
->can_be_null
)
6545 { /* The fastmap can't be used anyway. */
6546 free (preg
->fastmap
);
6547 preg
->fastmap
= NULL
;
6552 WEAK_ALIAS (__regcomp
, regcomp
)
6555 /* regexec searches for a given pattern, specified by PREG, in the
6558 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6559 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6560 least NMATCH elements, and we set them to the offsets of the
6561 corresponding matched substrings.
6563 EFLAGS specifies `execution flags' which affect matching: if
6564 REG_NOTBOL is set, then ^ does not match at the beginning of the
6565 string; if REG_NOTEOL is set, then $ does not match at the end.
6567 We return 0 if we find a match and REG_NOMATCH if not. */
6570 regexec (const regex_t
*__restrict preg
, const char *__restrict string
,
6571 size_t nmatch
, regmatch_t pmatch
[__restrict_arr
], int eflags
)
6574 struct re_registers regs
;
6575 regex_t private_preg
;
6576 size_t len
= strlen (string
);
6577 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6579 private_preg
= *preg
;
6581 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6582 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6584 /* The user has told us exactly how many registers to return
6585 information about, via `nmatch'. We have to pass that on to the
6586 matching routines. */
6587 private_preg
.regs_allocated
= REGS_FIXED
;
6591 regs
.num_regs
= nmatch
;
6592 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6593 if (regs
.start
== NULL
)
6595 regs
.end
= regs
.start
+ nmatch
;
6598 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6599 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6600 was a little bit longer but still only matching the real part.
6601 This works because the `endline' will check for a '\n' and will find a
6602 '\0', correctly deciding that this is not the end of a line.
6603 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6604 a convenient '\0' there. For all we know, the string could be preceded
6605 by '\n' which would throw things off. */
6607 /* Perform the searching operation. */
6608 ret
= re_search (&private_preg
, string
, len
,
6609 /* start: */ 0, /* range: */ len
,
6610 want_reg_info
? ®s
: (struct re_registers
*) 0);
6612 /* Copy the register information to the POSIX structure. */
6619 for (r
= 0; r
< nmatch
; r
++)
6621 pmatch
[r
].rm_so
= regs
.start
[r
];
6622 pmatch
[r
].rm_eo
= regs
.end
[r
];
6626 /* If we needed the temporary register info, free the space now. */
6630 /* We want zero return to mean success, unlike `re_search'. */
6631 return ret
>= 0 ? REG_NOERROR
: REG_NOMATCH
;
6633 WEAK_ALIAS (__regexec
, regexec
)
6636 /* Returns a message corresponding to an error code, ERR_CODE, returned
6637 from either regcomp or regexec. We don't use PREG here.
6639 ERR_CODE was previously called ERRCODE, but that name causes an
6640 error with msvc8 compiler. */
6643 regerror (int err_code
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
6649 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6650 /* Only error codes returned by the rest of the code should be passed
6651 to this routine. If we are given anything else, or if other regex
6652 code generates an invalid error code, then the program has a bug.
6653 Dump core so we can fix it. */
6656 msg
= gettext (re_error_msgid
[err_code
]);
6658 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6660 if (errbuf_size
!= 0)
6662 if (msg_size
> errbuf_size
)
6664 strncpy (errbuf
, msg
, errbuf_size
- 1);
6665 errbuf
[errbuf_size
- 1] = 0;
6668 strcpy (errbuf
, msg
);
6673 WEAK_ALIAS (__regerror
, regerror
)
6676 /* Free dynamically allocated space used by PREG. */
6679 regfree (regex_t
*preg
)
6681 free (preg
->buffer
);
6682 preg
->buffer
= NULL
;
6684 preg
->allocated
= 0;
6687 free (preg
->fastmap
);
6688 preg
->fastmap
= NULL
;
6689 preg
->fastmap_accurate
= 0;
6691 free (preg
->translate
);
6692 preg
->translate
= NULL
;
6694 WEAK_ALIAS (__regfree
, regfree
)
6696 #endif /* not emacs */