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, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
6 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
7 Free Software Foundation, Inc.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25 - structure the opcode space into opcode+flag.
26 - merge with glibc's regex.[ch].
27 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
28 need to modify the compiled regexp so that re_match can be reentrant.
29 - get rid of on_failure_jump_smart by doing the optimization in re_comp
30 rather than at run-time, so that re_match can be reentrant.
33 /* AIX requires this to be the first thing in the file. */
34 #if defined _AIX && !defined REGEX_MALLOC
42 #if defined STDC_HEADERS && !defined emacs
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
49 /* Whether to use ISO C Amendment 1 wide char functions.
50 Those should not be used for Emacs since it uses its own. */
52 #define WIDE_CHAR_SUPPORT 1
54 #define WIDE_CHAR_SUPPORT \
55 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
58 /* For platform which support the ISO C amendement 1 functionality we
59 support user defined character classes. */
61 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
67 /* We have to keep the namespace clean. */
68 # define regfree(preg) __regfree (preg)
69 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
70 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
71 # define regerror(err_code, preg, errbuf, errbuf_size) \
72 __regerror(err_code, preg, errbuf, errbuf_size)
73 # define re_set_registers(bu, re, nu, st, en) \
74 __re_set_registers (bu, re, nu, st, en)
75 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
76 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
77 # define re_match(bufp, string, size, pos, regs) \
78 __re_match (bufp, string, size, pos, regs)
79 # define re_search(bufp, string, size, startpos, range, regs) \
80 __re_search (bufp, string, size, startpos, range, regs)
81 # define re_compile_pattern(pattern, length, bufp) \
82 __re_compile_pattern (pattern, length, bufp)
83 # define re_set_syntax(syntax) __re_set_syntax (syntax)
84 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
85 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
86 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
88 /* Make sure we call libc's function even if the user overrides them. */
89 # define btowc __btowc
90 # define iswctype __iswctype
91 # define wctype __wctype
93 # define WEAK_ALIAS(a,b) weak_alias (a, b)
95 /* We are also using some library internals. */
96 # include <locale/localeinfo.h>
97 # include <locale/elem-hash.h>
98 # include <langinfo.h>
100 # define WEAK_ALIAS(a,b)
103 /* This is for other GNU distributions with internationalized messages. */
104 #if HAVE_LIBINTL_H || defined _LIBC
105 # include <libintl.h>
107 # define gettext(msgid) (msgid)
111 /* This define is so xgettext can find the internationalizable
113 # define gettext_noop(String) String
116 /* The `emacs' switch turns on certain matching commands
117 that make sense only in Emacs. */
124 /* Make syntax table lookup grant data in gl_state. */
125 # define SYNTAX_ENTRY_VIA_PROPERTY
128 # include "character.h"
129 # include "category.h"
134 # define malloc xmalloc
138 # define realloc xrealloc
144 /* Converts the pointer to the char to BEG-based offset from the start. */
145 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
146 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
148 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
149 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
150 # define RE_STRING_CHAR(p, multibyte) \
151 (multibyte ? (STRING_CHAR (p)) : (*(p)))
152 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
153 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
155 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
157 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
159 /* Set C a (possibly converted to multibyte) character before P. P
160 points into a string which is the virtual concatenation of STR1
161 (which ends at END1) or STR2 (which ends at END2). */
162 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
164 if (target_multibyte) \
166 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
167 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
168 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
169 c = STRING_CHAR (dtemp); \
173 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
174 (c) = RE_CHAR_TO_MULTIBYTE (c); \
178 /* Set C a (possibly converted to multibyte) character at P, and set
179 LEN to the byte length of that character. */
180 # define GET_CHAR_AFTER(c, p, len) \
182 if (target_multibyte) \
183 (c) = STRING_CHAR_AND_LENGTH (p, len); \
188 (c) = RE_CHAR_TO_MULTIBYTE (c); \
192 #else /* not emacs */
194 /* If we are not linking with Emacs proper,
195 we can't use the relocating allocator
196 even if config.h says that we can. */
199 # if defined STDC_HEADERS || defined _LIBC
206 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
213 val
= (void *) malloc (size
);
216 write (2, "virtual memory exhausted\n", 25);
223 xrealloc (block
, size
)
228 /* We must call malloc explicitly when BLOCK is 0, since some
229 reallocs don't do this. */
231 val
= (void *) malloc (size
);
233 val
= (void *) realloc (block
, size
);
236 write (2, "virtual memory exhausted\n", 25);
245 # define malloc xmalloc
249 # define realloc xrealloc
251 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
252 If nothing else has been done, use the method below. */
253 # ifdef INHIBIT_STRING_HEADER
254 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
255 # if !defined bzero && !defined bcopy
256 # undef INHIBIT_STRING_HEADER
261 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
262 This is used in most programs--a few other programs avoid this
263 by defining INHIBIT_STRING_HEADER. */
264 # ifndef INHIBIT_STRING_HEADER
265 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
269 # define bzero(s, n) (memset (s, '\0', n), (s))
271 # define bzero(s, n) __bzero (s, n)
275 # include <strings.h>
277 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
280 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
285 /* Define the syntax stuff for \<, \>, etc. */
287 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
288 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1, Ssymbol
= 2 };
290 # define SWITCH_ENUM_CAST(x) (x)
292 /* Dummy macros for non-Emacs environments. */
293 # define CHAR_CHARSET(c) 0
294 # define CHARSET_LEADING_CODE_BASE(c) 0
295 # define MAX_MULTIBYTE_LENGTH 1
296 # define RE_MULTIBYTE_P(x) 0
297 # define RE_TARGET_MULTIBYTE_P(x) 0
298 # define WORD_BOUNDARY_P(c1, c2) (0)
299 # define CHAR_HEAD_P(p) (1)
300 # define SINGLE_BYTE_CHAR_P(c) (1)
301 # define SAME_CHARSET_P(c1, c2) (1)
302 # define BYTES_BY_CHAR_HEAD(p) (1)
303 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
304 # define STRING_CHAR(p) (*(p))
305 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
306 # define CHAR_STRING(c, s) (*(s) = (c), 1)
307 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
308 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
309 # define RE_CHAR_TO_MULTIBYTE(c) (c)
310 # define RE_CHAR_TO_UNIBYTE(c) (c)
311 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
312 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
313 # define GET_CHAR_AFTER(c, p, len) \
315 # define MAKE_CHAR(charset, c1, c2) (c1)
316 # define BYTE8_TO_CHAR(c) (c)
317 # define CHAR_BYTE8_P(c) (0)
318 # define CHAR_LEADING_CODE(c) (c)
320 #endif /* not emacs */
323 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
324 # define RE_TRANSLATE_P(TBL) (TBL)
327 /* Get the interface, including the syntax bits. */
330 /* isalpha etc. are used for the character classes. */
335 /* 1 if C is an ASCII character. */
336 # define IS_REAL_ASCII(c) ((c) < 0200)
338 /* 1 if C is a unibyte character. */
339 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
341 /* The Emacs definitions should not be directly affected by locales. */
343 /* In Emacs, these are only used for single-byte characters. */
344 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
345 # define ISCNTRL(c) ((c) < ' ')
346 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
347 || ((c) >= 'a' && (c) <= 'f') \
348 || ((c) >= 'A' && (c) <= 'F'))
350 /* This is only used for single-byte characters. */
351 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
353 /* The rest must handle multibyte characters. */
355 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
356 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
359 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
360 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
363 # define ISALNUM(c) (IS_REAL_ASCII (c) \
364 ? (((c) >= 'a' && (c) <= 'z') \
365 || ((c) >= 'A' && (c) <= 'Z') \
366 || ((c) >= '0' && (c) <= '9')) \
367 : SYNTAX (c) == Sword)
369 # define ISALPHA(c) (IS_REAL_ASCII (c) \
370 ? (((c) >= 'a' && (c) <= 'z') \
371 || ((c) >= 'A' && (c) <= 'Z')) \
372 : SYNTAX (c) == Sword)
374 # define ISLOWER(c) (LOWERCASEP (c))
376 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
377 ? ((c) > ' ' && (c) < 0177 \
378 && !(((c) >= 'a' && (c) <= 'z') \
379 || ((c) >= 'A' && (c) <= 'Z') \
380 || ((c) >= '0' && (c) <= '9'))) \
381 : SYNTAX (c) != Sword)
383 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
385 # define ISUPPER(c) (UPPERCASEP (c))
387 # define ISWORD(c) (SYNTAX (c) == Sword)
389 #else /* not emacs */
391 /* Jim Meyering writes:
393 "... Some ctype macros are valid only for character codes that
394 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
395 using /bin/cc or gcc but without giving an ansi option). So, all
396 ctype uses should be through macros like ISPRINT... If
397 STDC_HEADERS is defined, then autoconf has verified that the ctype
398 macros don't need to be guarded with references to isascii. ...
399 Defining isascii to 1 should let any compiler worth its salt
400 eliminate the && through constant folding."
401 Solaris defines some of these symbols so we must undefine them first. */
404 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
405 # define ISASCII(c) 1
407 # define ISASCII(c) isascii(c)
410 /* 1 if C is an ASCII character. */
411 # define IS_REAL_ASCII(c) ((c) < 0200)
413 /* This distinction is not meaningful, except in Emacs. */
414 # define ISUNIBYTE(c) 1
417 # define ISBLANK(c) (ISASCII (c) && isblank (c))
419 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
422 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
424 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
428 # define ISPRINT(c) (ISASCII (c) && isprint (c))
429 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
430 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
431 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
432 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
433 # define ISLOWER(c) (ISASCII (c) && islower (c))
434 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
435 # define ISSPACE(c) (ISASCII (c) && isspace (c))
436 # define ISUPPER(c) (ISASCII (c) && isupper (c))
437 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
439 # define ISWORD(c) ISALPHA(c)
442 # define TOLOWER(c) _tolower(c)
444 # define TOLOWER(c) tolower(c)
447 /* How many characters in the character set. */
448 # define CHAR_SET_SIZE 256
452 extern char *re_syntax_table
;
454 # else /* not SYNTAX_TABLE */
456 static char re_syntax_table
[CHAR_SET_SIZE
];
467 bzero (re_syntax_table
, sizeof re_syntax_table
);
469 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
471 re_syntax_table
[c
] = Sword
;
473 re_syntax_table
['_'] = Ssymbol
;
478 # endif /* not SYNTAX_TABLE */
480 # define SYNTAX(c) re_syntax_table[(c)]
482 #endif /* not emacs */
485 # define NULL (void *)0
488 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
489 since ours (we hope) works properly with all combinations of
490 machines, compilers, `char' and `unsigned char' argument types.
491 (Per Bothner suggested the basic approach.) */
492 #undef SIGN_EXTEND_CHAR
494 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
495 #else /* not __STDC__ */
496 /* As in Harbison and Steele. */
497 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
500 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
501 use `alloca' instead of `malloc'. This is because using malloc in
502 re_search* or re_match* could cause memory leaks when C-g is used in
503 Emacs; also, malloc is slower and causes storage fragmentation. On
504 the other hand, malloc is more portable, and easier to debug.
506 Because we sometimes use alloca, some routines have to be macros,
507 not functions -- `alloca'-allocated space disappears at the end of the
508 function it is called in. */
512 # define REGEX_ALLOCATE malloc
513 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
514 # define REGEX_FREE free
516 #else /* not REGEX_MALLOC */
518 /* Emacs already defines alloca, sometimes. */
521 /* Make alloca work the best possible way. */
523 # define alloca __builtin_alloca
524 # else /* not __GNUC__ */
525 # ifdef HAVE_ALLOCA_H
527 # endif /* HAVE_ALLOCA_H */
528 # endif /* not __GNUC__ */
530 # endif /* not alloca */
532 # define REGEX_ALLOCATE alloca
534 /* Assumes a `char *destination' variable. */
535 # define REGEX_REALLOCATE(source, osize, nsize) \
536 (destination = (char *) alloca (nsize), \
537 memcpy (destination, source, osize))
539 /* No need to do anything to free, after alloca. */
540 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
542 #endif /* not REGEX_MALLOC */
544 /* Define how to allocate the failure stack. */
546 #if defined REL_ALLOC && defined REGEX_MALLOC
548 # define REGEX_ALLOCATE_STACK(size) \
549 r_alloc (&failure_stack_ptr, (size))
550 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
551 r_re_alloc (&failure_stack_ptr, (nsize))
552 # define REGEX_FREE_STACK(ptr) \
553 r_alloc_free (&failure_stack_ptr)
555 #else /* not using relocating allocator */
559 # define REGEX_ALLOCATE_STACK malloc
560 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
561 # define REGEX_FREE_STACK free
563 # else /* not REGEX_MALLOC */
565 # define REGEX_ALLOCATE_STACK alloca
567 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
568 REGEX_REALLOCATE (source, osize, nsize)
569 /* No need to explicitly free anything. */
570 # define REGEX_FREE_STACK(arg) ((void)0)
572 # endif /* not REGEX_MALLOC */
573 #endif /* not using relocating allocator */
576 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
577 `string1' or just past its end. This works if PTR is NULL, which is
579 #define FIRST_STRING_P(ptr) \
580 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
582 /* (Re)Allocate N items of type T using malloc, or fail. */
583 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
584 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
585 #define RETALLOC_IF(addr, n, t) \
586 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
587 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
589 #define BYTEWIDTH 8 /* In bits. */
591 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
595 #define MAX(a, b) ((a) > (b) ? (a) : (b))
596 #define MIN(a, b) ((a) < (b) ? (a) : (b))
598 /* Type of source-pattern and string chars. */
599 typedef const unsigned char re_char
;
601 typedef char boolean
;
605 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
606 re_char
*string1
, int size1
,
607 re_char
*string2
, int size2
,
609 struct re_registers
*regs
,
612 /* These are the command codes that appear in compiled regular
613 expressions. Some opcodes are followed by argument bytes. A
614 command code can specify any interpretation whatsoever for its
615 arguments. Zero bytes may appear in the compiled regular expression. */
621 /* Succeed right away--no more backtracking. */
624 /* Followed by one byte giving n, then by n literal bytes. */
627 /* Matches any (more or less) character. */
630 /* Matches any one char belonging to specified set. First
631 following byte is number of bitmap bytes. Then come bytes
632 for a bitmap saying which chars are in. Bits in each byte
633 are ordered low-bit-first. A character is in the set if its
634 bit is 1. A character too large to have a bit in the map is
635 automatically not in the set.
637 If the length byte has the 0x80 bit set, then that stuff
638 is followed by a range table:
639 2 bytes of flags for character sets (low 8 bits, high 8 bits)
640 See RANGE_TABLE_WORK_BITS below.
641 2 bytes, the number of pairs that follow (upto 32767)
642 pairs, each 2 multibyte characters,
643 each multibyte character represented as 3 bytes. */
646 /* Same parameters as charset, but match any character that is
647 not one of those specified. */
650 /* Start remembering the text that is matched, for storing in a
651 register. Followed by one byte with the register number, in
652 the range 0 to one less than the pattern buffer's re_nsub
656 /* Stop remembering the text that is matched and store it in a
657 memory register. Followed by one byte with the register
658 number, in the range 0 to one less than `re_nsub' in the
662 /* Match a duplicate of something remembered. Followed by one
663 byte containing the register number. */
666 /* Fail unless at beginning of line. */
669 /* Fail unless at end of line. */
672 /* Succeeds if at beginning of buffer (if emacs) or at beginning
673 of string to be matched (if not). */
676 /* Analogously, for end of buffer/string. */
679 /* Followed by two byte relative address to which to jump. */
682 /* Followed by two-byte relative address of place to resume at
683 in case of failure. */
686 /* Like on_failure_jump, but pushes a placeholder instead of the
687 current string position when executed. */
688 on_failure_keep_string_jump
,
690 /* Just like `on_failure_jump', except that it checks that we
691 don't get stuck in an infinite loop (matching an empty string
693 on_failure_jump_loop
,
695 /* Just like `on_failure_jump_loop', except that it checks for
696 a different kind of loop (the kind that shows up with non-greedy
697 operators). This operation has to be immediately preceded
699 on_failure_jump_nastyloop
,
701 /* A smart `on_failure_jump' used for greedy * and + operators.
702 It analyses the loop before which it is put and if the
703 loop does not require backtracking, it changes itself to
704 `on_failure_keep_string_jump' and short-circuits the loop,
705 else it just defaults to changing itself into `on_failure_jump'.
706 It assumes that it is pointing to just past a `jump'. */
707 on_failure_jump_smart
,
709 /* Followed by two-byte relative address and two-byte number n.
710 After matching N times, jump to the address upon failure.
711 Does not work if N starts at 0: use on_failure_jump_loop
715 /* Followed by two-byte relative address, and two-byte number n.
716 Jump to the address N times, then fail. */
719 /* Set the following two-byte relative address to the
720 subsequent two-byte number. The address *includes* the two
724 wordbeg
, /* Succeeds if at word beginning. */
725 wordend
, /* Succeeds if at word end. */
727 wordbound
, /* Succeeds if at a word boundary. */
728 notwordbound
, /* Succeeds if not at a word boundary. */
730 symbeg
, /* Succeeds if at symbol beginning. */
731 symend
, /* Succeeds if at symbol end. */
733 /* Matches any character whose syntax is specified. Followed by
734 a byte which contains a syntax code, e.g., Sword. */
737 /* Matches any character whose syntax is not that specified. */
741 ,before_dot
, /* Succeeds if before point. */
742 at_dot
, /* Succeeds if at point. */
743 after_dot
, /* Succeeds if after point. */
745 /* Matches any character whose category-set contains the specified
746 category. The operator is followed by a byte which contains a
747 category code (mnemonic ASCII character). */
750 /* Matches any character whose category-set does not contain the
751 specified category. The operator is followed by a byte which
752 contains the category code (mnemonic ASCII character). */
757 /* Common operations on the compiled pattern. */
759 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
761 #define STORE_NUMBER(destination, number) \
763 (destination)[0] = (number) & 0377; \
764 (destination)[1] = (number) >> 8; \
767 /* Same as STORE_NUMBER, except increment DESTINATION to
768 the byte after where the number is stored. Therefore, DESTINATION
769 must be an lvalue. */
771 #define STORE_NUMBER_AND_INCR(destination, number) \
773 STORE_NUMBER (destination, number); \
774 (destination) += 2; \
777 /* Put into DESTINATION a number stored in two contiguous bytes starting
780 #define EXTRACT_NUMBER(destination, source) \
782 (destination) = *(source) & 0377; \
783 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
787 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
789 extract_number (dest
, source
)
793 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
794 *dest
= *source
& 0377;
798 # ifndef EXTRACT_MACROS /* To debug the macros. */
799 # undef EXTRACT_NUMBER
800 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
801 # endif /* not EXTRACT_MACROS */
805 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
806 SOURCE must be an lvalue. */
808 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
810 EXTRACT_NUMBER (destination, source); \
815 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
818 extract_number_and_incr (destination
, source
)
822 extract_number (destination
, *source
);
826 # ifndef EXTRACT_MACROS
827 # undef EXTRACT_NUMBER_AND_INCR
828 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
829 extract_number_and_incr (&dest, &src)
830 # endif /* not EXTRACT_MACROS */
834 /* Store a multibyte character in three contiguous bytes starting
835 DESTINATION, and increment DESTINATION to the byte after where the
836 character is stored. Therefore, DESTINATION must be an lvalue. */
838 #define STORE_CHARACTER_AND_INCR(destination, character) \
840 (destination)[0] = (character) & 0377; \
841 (destination)[1] = ((character) >> 8) & 0377; \
842 (destination)[2] = (character) >> 16; \
843 (destination) += 3; \
846 /* Put into DESTINATION a character stored in three contiguous bytes
847 starting at SOURCE. */
849 #define EXTRACT_CHARACTER(destination, source) \
851 (destination) = ((source)[0] \
852 | ((source)[1] << 8) \
853 | ((source)[2] << 16)); \
857 /* Macros for charset. */
859 /* Size of bitmap of charset P in bytes. P is a start of charset,
860 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
861 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
863 /* Nonzero if charset P has range table. */
864 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
866 /* Return the address of range table of charset P. But not the start
867 of table itself, but the before where the number of ranges is
868 stored. `2 +' means to skip re_opcode_t and size of bitmap,
869 and the 2 bytes of flags at the start of the range table. */
870 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
872 /* Extract the bit flags that start a range table. */
873 #define CHARSET_RANGE_TABLE_BITS(p) \
874 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
875 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
877 /* Test if C is listed in the bitmap of charset P. */
878 #define CHARSET_LOOKUP_BITMAP(p, c) \
879 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
880 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
882 /* Return the address of end of RANGE_TABLE. COUNT is number of
883 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
884 is start of range and end of range. `* 3' is size of each start
886 #define CHARSET_RANGE_TABLE_END(range_table, count) \
887 ((range_table) + (count) * 2 * 3)
889 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
890 COUNT is number of ranges in RANGE_TABLE. */
891 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
894 re_wchar_t range_start, range_end; \
896 re_char *range_table_end \
897 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
899 for (p = (range_table); p < range_table_end; p += 2 * 3) \
901 EXTRACT_CHARACTER (range_start, p); \
902 EXTRACT_CHARACTER (range_end, p + 3); \
904 if (range_start <= (c) && (c) <= range_end) \
913 /* Test if C is in range table of CHARSET. The flag NOT is negated if
914 C is listed in it. */
915 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
918 /* Number of ranges in range table. */ \
920 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
922 EXTRACT_NUMBER_AND_INCR (count, range_table); \
923 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
927 /* If DEBUG is defined, Regex prints many voluminous messages about what
928 it is doing (if the variable `debug' is nonzero). If linked with the
929 main program in `iregex.c', you can enter patterns and strings
930 interactively. And if linked with the main program in `main.c' and
931 the other test files, you can run the already-written tests. */
935 /* We use standard I/O for debugging. */
938 /* It is useful to test things that ``must'' be true when debugging. */
941 static int debug
= -100000;
943 # define DEBUG_STATEMENT(e) e
944 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
945 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
946 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
947 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
948 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
949 if (debug > 0) print_partial_compiled_pattern (s, e)
950 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
951 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
954 /* Print the fastmap in human-readable form. */
957 print_fastmap (fastmap
)
960 unsigned was_a_range
= 0;
963 while (i
< (1 << BYTEWIDTH
))
969 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
985 /* Print a compiled pattern string in human-readable form, starting at
986 the START pointer into it and ending just before the pointer END. */
989 print_partial_compiled_pattern (start
, end
)
999 fprintf (stderr
, "(null)\n");
1003 /* Loop over pattern commands. */
1006 fprintf (stderr
, "%d:\t", p
- start
);
1008 switch ((re_opcode_t
) *p
++)
1011 fprintf (stderr
, "/no_op");
1015 fprintf (stderr
, "/succeed");
1020 fprintf (stderr
, "/exactn/%d", mcnt
);
1023 fprintf (stderr
, "/%c", *p
++);
1029 fprintf (stderr
, "/start_memory/%d", *p
++);
1033 fprintf (stderr
, "/stop_memory/%d", *p
++);
1037 fprintf (stderr
, "/duplicate/%d", *p
++);
1041 fprintf (stderr
, "/anychar");
1047 register int c
, last
= -100;
1048 register int in_range
= 0;
1049 int length
= CHARSET_BITMAP_SIZE (p
- 1);
1050 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
1052 fprintf (stderr
, "/charset [%s",
1053 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
1056 fprintf (stderr
, " !extends past end of pattern! ");
1058 for (c
= 0; c
< 256; c
++)
1060 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
1062 /* Are we starting a range? */
1063 if (last
+ 1 == c
&& ! in_range
)
1065 fprintf (stderr
, "-");
1068 /* Have we broken a range? */
1069 else if (last
+ 1 != c
&& in_range
)
1071 fprintf (stderr
, "%c", last
);
1076 fprintf (stderr
, "%c", c
);
1082 fprintf (stderr
, "%c", last
);
1084 fprintf (stderr
, "]");
1088 if (has_range_table
)
1091 fprintf (stderr
, "has-range-table");
1093 /* ??? Should print the range table; for now, just skip it. */
1094 p
+= 2; /* skip range table bits */
1095 EXTRACT_NUMBER_AND_INCR (count
, p
);
1096 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1102 fprintf (stderr
, "/begline");
1106 fprintf (stderr
, "/endline");
1109 case on_failure_jump
:
1110 extract_number_and_incr (&mcnt
, &p
);
1111 fprintf (stderr
, "/on_failure_jump to %d", p
+ mcnt
- start
);
1114 case on_failure_keep_string_jump
:
1115 extract_number_and_incr (&mcnt
, &p
);
1116 fprintf (stderr
, "/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1119 case on_failure_jump_nastyloop
:
1120 extract_number_and_incr (&mcnt
, &p
);
1121 fprintf (stderr
, "/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1124 case on_failure_jump_loop
:
1125 extract_number_and_incr (&mcnt
, &p
);
1126 fprintf (stderr
, "/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1129 case on_failure_jump_smart
:
1130 extract_number_and_incr (&mcnt
, &p
);
1131 fprintf (stderr
, "/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1135 extract_number_and_incr (&mcnt
, &p
);
1136 fprintf (stderr
, "/jump to %d", p
+ mcnt
- start
);
1140 extract_number_and_incr (&mcnt
, &p
);
1141 extract_number_and_incr (&mcnt2
, &p
);
1142 fprintf (stderr
, "/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1146 extract_number_and_incr (&mcnt
, &p
);
1147 extract_number_and_incr (&mcnt2
, &p
);
1148 fprintf (stderr
, "/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1152 extract_number_and_incr (&mcnt
, &p
);
1153 extract_number_and_incr (&mcnt2
, &p
);
1154 fprintf (stderr
, "/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1158 fprintf (stderr
, "/wordbound");
1162 fprintf (stderr
, "/notwordbound");
1166 fprintf (stderr
, "/wordbeg");
1170 fprintf (stderr
, "/wordend");
1174 fprintf (stderr
, "/symbeg");
1178 fprintf (stderr
, "/symend");
1182 fprintf (stderr
, "/syntaxspec");
1184 fprintf (stderr
, "/%d", mcnt
);
1188 fprintf (stderr
, "/notsyntaxspec");
1190 fprintf (stderr
, "/%d", mcnt
);
1195 fprintf (stderr
, "/before_dot");
1199 fprintf (stderr
, "/at_dot");
1203 fprintf (stderr
, "/after_dot");
1207 fprintf (stderr
, "/categoryspec");
1209 fprintf (stderr
, "/%d", mcnt
);
1212 case notcategoryspec
:
1213 fprintf (stderr
, "/notcategoryspec");
1215 fprintf (stderr
, "/%d", mcnt
);
1220 fprintf (stderr
, "/begbuf");
1224 fprintf (stderr
, "/endbuf");
1228 fprintf (stderr
, "?%d", *(p
-1));
1231 fprintf (stderr
, "\n");
1234 fprintf (stderr
, "%d:\tend of pattern.\n", p
- start
);
1239 print_compiled_pattern (bufp
)
1240 struct re_pattern_buffer
*bufp
;
1242 re_char
*buffer
= bufp
->buffer
;
1244 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1245 printf ("%ld bytes used/%ld bytes allocated.\n",
1246 bufp
->used
, bufp
->allocated
);
1248 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1250 printf ("fastmap: ");
1251 print_fastmap (bufp
->fastmap
);
1254 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1255 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1256 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1257 printf ("no_sub: %d\t", bufp
->no_sub
);
1258 printf ("not_bol: %d\t", bufp
->not_bol
);
1259 printf ("not_eol: %d\t", bufp
->not_eol
);
1260 printf ("syntax: %lx\n", bufp
->syntax
);
1262 /* Perhaps we should print the translate table? */
1267 print_double_string (where
, string1
, size1
, string2
, size2
)
1280 if (FIRST_STRING_P (where
))
1282 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1283 putchar (string1
[this_char
]);
1288 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1289 putchar (string2
[this_char
]);
1293 #else /* not DEBUG */
1298 # define DEBUG_STATEMENT(e)
1299 # define DEBUG_PRINT1(x)
1300 # define DEBUG_PRINT2(x1, x2)
1301 # define DEBUG_PRINT3(x1, x2, x3)
1302 # define DEBUG_PRINT4(x1, x2, x3, x4)
1303 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1304 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1306 #endif /* not DEBUG */
1308 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1309 also be assigned to arbitrarily: each pattern buffer stores its own
1310 syntax, so it can be changed between regex compilations. */
1311 /* This has no initializer because initialized variables in Emacs
1312 become read-only after dumping. */
1313 reg_syntax_t re_syntax_options
;
1316 /* Specify the precise syntax of regexps for compilation. This provides
1317 for compatibility for various utilities which historically have
1318 different, incompatible syntaxes.
1320 The argument SYNTAX is a bit mask comprised of the various bits
1321 defined in regex.h. We return the old syntax. */
1324 re_set_syntax (reg_syntax_t syntax
)
1326 reg_syntax_t ret
= re_syntax_options
;
1328 re_syntax_options
= syntax
;
1331 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1333 /* Regexp to use to replace spaces, or NULL meaning don't. */
1334 static re_char
*whitespace_regexp
;
1337 re_set_whitespace_regexp (const char *regexp
)
1339 whitespace_regexp
= (re_char
*) regexp
;
1341 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1343 /* This table gives an error message for each of the error codes listed
1344 in regex.h. Obviously the order here has to be same as there.
1345 POSIX doesn't require that we do anything for REG_NOERROR,
1346 but why not be nice? */
1348 static const char *re_error_msgid
[] =
1350 gettext_noop ("Success"), /* REG_NOERROR */
1351 gettext_noop ("No match"), /* REG_NOMATCH */
1352 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1353 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1354 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1355 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1356 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1357 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1358 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1359 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1360 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1361 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1362 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1363 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1364 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1365 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1366 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1367 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1370 /* Avoiding alloca during matching, to placate r_alloc. */
1372 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1373 searching and matching functions should not call alloca. On some
1374 systems, alloca is implemented in terms of malloc, and if we're
1375 using the relocating allocator routines, then malloc could cause a
1376 relocation, which might (if the strings being searched are in the
1377 ralloc heap) shift the data out from underneath the regexp
1380 Here's another reason to avoid allocation: Emacs
1381 processes input from X in a signal handler; processing X input may
1382 call malloc; if input arrives while a matching routine is calling
1383 malloc, then we're scrod. But Emacs can't just block input while
1384 calling matching routines; then we don't notice interrupts when
1385 they come in. So, Emacs blocks input around all regexp calls
1386 except the matching calls, which it leaves unprotected, in the
1387 faith that they will not malloc. */
1389 /* Normally, this is fine. */
1390 #define MATCH_MAY_ALLOCATE
1392 /* The match routines may not allocate if (1) they would do it with malloc
1393 and (2) it's not safe for them to use malloc.
1394 Note that if REL_ALLOC is defined, matching would not use malloc for the
1395 failure stack, but we would still use it for the register vectors;
1396 so REL_ALLOC should not affect this. */
1397 #if defined REGEX_MALLOC && defined emacs
1398 # undef MATCH_MAY_ALLOCATE
1402 /* Failure stack declarations and macros; both re_compile_fastmap and
1403 re_match_2 use a failure stack. These have to be macros because of
1404 REGEX_ALLOCATE_STACK. */
1407 /* Approximate number of failure points for which to initially allocate space
1408 when matching. If this number is exceeded, we allocate more
1409 space, so it is not a hard limit. */
1410 #ifndef INIT_FAILURE_ALLOC
1411 # define INIT_FAILURE_ALLOC 20
1414 /* Roughly the maximum number of failure points on the stack. Would be
1415 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1416 This is a variable only so users of regex can assign to it; we never
1417 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1418 before using it, so it should probably be a byte-count instead. */
1419 # if defined MATCH_MAY_ALLOCATE
1420 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1421 whose default stack limit is 2mb. In order for a larger
1422 value to work reliably, you have to try to make it accord
1423 with the process stack limit. */
1424 size_t re_max_failures
= 40000;
1426 size_t re_max_failures
= 4000;
1429 union fail_stack_elt
1432 /* This should be the biggest `int' that's no bigger than a pointer. */
1436 typedef union fail_stack_elt fail_stack_elt_t
;
1440 fail_stack_elt_t
*stack
;
1442 size_t avail
; /* Offset of next open position. */
1443 size_t frame
; /* Offset of the cur constructed frame. */
1446 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1447 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1450 /* Define macros to initialize and free the failure stack.
1451 Do `return -2' if the alloc fails. */
1453 #ifdef MATCH_MAY_ALLOCATE
1454 # define INIT_FAIL_STACK() \
1456 fail_stack.stack = (fail_stack_elt_t *) \
1457 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1458 * sizeof (fail_stack_elt_t)); \
1460 if (fail_stack.stack == NULL) \
1463 fail_stack.size = INIT_FAILURE_ALLOC; \
1464 fail_stack.avail = 0; \
1465 fail_stack.frame = 0; \
1468 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1470 # define INIT_FAIL_STACK() \
1472 fail_stack.avail = 0; \
1473 fail_stack.frame = 0; \
1476 # define RESET_FAIL_STACK() ((void)0)
1480 /* Double the size of FAIL_STACK, up to a limit
1481 which allows approximately `re_max_failures' items.
1483 Return 1 if succeeds, and 0 if either ran out of memory
1484 allocating space for it or it was already too large.
1486 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1488 /* Factor to increase the failure stack size by
1489 when we increase it.
1490 This used to be 2, but 2 was too wasteful
1491 because the old discarded stacks added up to as much space
1492 were as ultimate, maximum-size stack. */
1493 #define FAIL_STACK_GROWTH_FACTOR 4
1495 #define GROW_FAIL_STACK(fail_stack) \
1496 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1497 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1499 : ((fail_stack).stack \
1500 = (fail_stack_elt_t *) \
1501 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1502 (fail_stack).size * sizeof (fail_stack_elt_t), \
1503 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1504 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1505 * FAIL_STACK_GROWTH_FACTOR))), \
1507 (fail_stack).stack == NULL \
1509 : ((fail_stack).size \
1510 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1511 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1512 * FAIL_STACK_GROWTH_FACTOR)) \
1513 / sizeof (fail_stack_elt_t)), \
1517 /* Push a pointer value onto the failure stack.
1518 Assumes the variable `fail_stack'. Probably should only
1519 be called from within `PUSH_FAILURE_POINT'. */
1520 #define PUSH_FAILURE_POINTER(item) \
1521 fail_stack.stack[fail_stack.avail++].pointer = (item)
1523 /* This pushes an integer-valued item onto the failure stack.
1524 Assumes the variable `fail_stack'. Probably should only
1525 be called from within `PUSH_FAILURE_POINT'. */
1526 #define PUSH_FAILURE_INT(item) \
1527 fail_stack.stack[fail_stack.avail++].integer = (item)
1529 /* Push a fail_stack_elt_t value onto the failure stack.
1530 Assumes the variable `fail_stack'. Probably should only
1531 be called from within `PUSH_FAILURE_POINT'. */
1532 #define PUSH_FAILURE_ELT(item) \
1533 fail_stack.stack[fail_stack.avail++] = (item)
1535 /* These three POP... operations complement the three PUSH... operations.
1536 All assume that `fail_stack' is nonempty. */
1537 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1538 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1539 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1541 /* Individual items aside from the registers. */
1542 #define NUM_NONREG_ITEMS 3
1544 /* Used to examine the stack (to detect infinite loops). */
1545 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1546 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1547 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1548 #define TOP_FAILURE_HANDLE() fail_stack.frame
1551 #define ENSURE_FAIL_STACK(space) \
1552 while (REMAINING_AVAIL_SLOTS <= space) { \
1553 if (!GROW_FAIL_STACK (fail_stack)) \
1555 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1556 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1559 /* Push register NUM onto the stack. */
1560 #define PUSH_FAILURE_REG(num) \
1562 char *destination; \
1563 ENSURE_FAIL_STACK(3); \
1564 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1565 num, regstart[num], regend[num]); \
1566 PUSH_FAILURE_POINTER (regstart[num]); \
1567 PUSH_FAILURE_POINTER (regend[num]); \
1568 PUSH_FAILURE_INT (num); \
1571 /* Change the counter's value to VAL, but make sure that it will
1572 be reset when backtracking. */
1573 #define PUSH_NUMBER(ptr,val) \
1575 char *destination; \
1577 ENSURE_FAIL_STACK(3); \
1578 EXTRACT_NUMBER (c, ptr); \
1579 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1580 PUSH_FAILURE_INT (c); \
1581 PUSH_FAILURE_POINTER (ptr); \
1582 PUSH_FAILURE_INT (-1); \
1583 STORE_NUMBER (ptr, val); \
1586 /* Pop a saved register off the stack. */
1587 #define POP_FAILURE_REG_OR_COUNT() \
1589 int reg = POP_FAILURE_INT (); \
1592 /* It's a counter. */ \
1593 /* Here, we discard `const', making re_match non-reentrant. */ \
1594 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1595 reg = POP_FAILURE_INT (); \
1596 STORE_NUMBER (ptr, reg); \
1597 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1601 regend[reg] = POP_FAILURE_POINTER (); \
1602 regstart[reg] = POP_FAILURE_POINTER (); \
1603 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1604 reg, regstart[reg], regend[reg]); \
1608 /* Check that we are not stuck in an infinite loop. */
1609 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1611 int failure = TOP_FAILURE_HANDLE (); \
1612 /* Check for infinite matching loops */ \
1613 while (failure > 0 \
1614 && (FAILURE_STR (failure) == string_place \
1615 || FAILURE_STR (failure) == NULL)) \
1617 assert (FAILURE_PAT (failure) >= bufp->buffer \
1618 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1619 if (FAILURE_PAT (failure) == pat_cur) \
1624 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1625 failure = NEXT_FAILURE_HANDLE(failure); \
1627 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1630 /* Push the information about the state we will need
1631 if we ever fail back to it.
1633 Requires variables fail_stack, regstart, regend and
1634 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1637 Does `return FAILURE_CODE' if runs out of memory. */
1639 #define PUSH_FAILURE_POINT(pattern, string_place) \
1641 char *destination; \
1642 /* Must be int, so when we don't save any registers, the arithmetic \
1643 of 0 + -1 isn't done as unsigned. */ \
1645 DEBUG_STATEMENT (nfailure_points_pushed++); \
1646 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1647 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1648 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1650 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1652 DEBUG_PRINT1 ("\n"); \
1654 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1655 PUSH_FAILURE_INT (fail_stack.frame); \
1657 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1658 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1659 DEBUG_PRINT1 ("'\n"); \
1660 PUSH_FAILURE_POINTER (string_place); \
1662 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1663 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1664 PUSH_FAILURE_POINTER (pattern); \
1666 /* Close the frame by moving the frame pointer past it. */ \
1667 fail_stack.frame = fail_stack.avail; \
1670 /* Estimate the size of data pushed by a typical failure stack entry.
1671 An estimate is all we need, because all we use this for
1672 is to choose a limit for how big to make the failure stack. */
1673 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1674 #define TYPICAL_FAILURE_SIZE 20
1676 /* How many items can still be added to the stack without overflowing it. */
1677 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1680 /* Pops what PUSH_FAIL_STACK pushes.
1682 We restore into the parameters, all of which should be lvalues:
1683 STR -- the saved data position.
1684 PAT -- the saved pattern position.
1685 REGSTART, REGEND -- arrays of string positions.
1687 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1688 `pend', `string1', `size1', `string2', and `size2'. */
1690 #define POP_FAILURE_POINT(str, pat) \
1692 assert (!FAIL_STACK_EMPTY ()); \
1694 /* Remove failure points and point to how many regs pushed. */ \
1695 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1696 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1697 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1699 /* Pop the saved registers. */ \
1700 while (fail_stack.frame < fail_stack.avail) \
1701 POP_FAILURE_REG_OR_COUNT (); \
1703 pat = POP_FAILURE_POINTER (); \
1704 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1705 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1707 /* If the saved string location is NULL, it came from an \
1708 on_failure_keep_string_jump opcode, and we want to throw away the \
1709 saved NULL, thus retaining our current position in the string. */ \
1710 str = POP_FAILURE_POINTER (); \
1711 DEBUG_PRINT2 (" Popping string %p: `", str); \
1712 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1713 DEBUG_PRINT1 ("'\n"); \
1715 fail_stack.frame = POP_FAILURE_INT (); \
1716 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1718 assert (fail_stack.avail >= 0); \
1719 assert (fail_stack.frame <= fail_stack.avail); \
1721 DEBUG_STATEMENT (nfailure_points_popped++); \
1722 } while (0) /* POP_FAILURE_POINT */
1726 /* Registers are set to a sentinel when they haven't yet matched. */
1727 #define REG_UNSET(e) ((e) == NULL)
1729 /* Subroutine declarations and macros for regex_compile. */
1731 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1732 reg_syntax_t syntax
,
1733 struct re_pattern_buffer
*bufp
));
1734 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1735 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1736 int arg1
, int arg2
));
1737 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1738 int arg
, unsigned char *end
));
1739 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1740 int arg1
, int arg2
, unsigned char *end
));
1741 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1743 reg_syntax_t syntax
));
1744 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1746 reg_syntax_t syntax
));
1747 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1748 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1749 char *fastmap
, const int multibyte
));
1751 /* Fetch the next character in the uncompiled pattern, with no
1753 #define PATFETCH(c) \
1756 if (p == pend) return REG_EEND; \
1757 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1762 /* If `translate' is non-null, return translate[D], else just D. We
1763 cast the subscript to translate because some data is declared as
1764 `char *', to avoid warnings when a string constant is passed. But
1765 when we use a character as a subscript we must make it unsigned. */
1767 # define TRANSLATE(d) \
1768 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1772 /* Macros for outputting the compiled pattern into `buffer'. */
1774 /* If the buffer isn't allocated when it comes in, use this. */
1775 #define INIT_BUF_SIZE 32
1777 /* Make sure we have at least N more bytes of space in buffer. */
1778 #define GET_BUFFER_SPACE(n) \
1779 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1782 /* Make sure we have one more byte of buffer space and then add C to it. */
1783 #define BUF_PUSH(c) \
1785 GET_BUFFER_SPACE (1); \
1786 *b++ = (unsigned char) (c); \
1790 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1791 #define BUF_PUSH_2(c1, c2) \
1793 GET_BUFFER_SPACE (2); \
1794 *b++ = (unsigned char) (c1); \
1795 *b++ = (unsigned char) (c2); \
1799 /* As with BUF_PUSH_2, except for three bytes. */
1800 #define BUF_PUSH_3(c1, c2, c3) \
1802 GET_BUFFER_SPACE (3); \
1803 *b++ = (unsigned char) (c1); \
1804 *b++ = (unsigned char) (c2); \
1805 *b++ = (unsigned char) (c3); \
1809 /* Store a jump with opcode OP at LOC to location TO. We store a
1810 relative address offset by the three bytes the jump itself occupies. */
1811 #define STORE_JUMP(op, loc, to) \
1812 store_op1 (op, loc, (to) - (loc) - 3)
1814 /* Likewise, for a two-argument jump. */
1815 #define STORE_JUMP2(op, loc, to, arg) \
1816 store_op2 (op, loc, (to) - (loc) - 3, arg)
1818 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1819 #define INSERT_JUMP(op, loc, to) \
1820 insert_op1 (op, loc, (to) - (loc) - 3, b)
1822 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1823 #define INSERT_JUMP2(op, loc, to, arg) \
1824 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1827 /* This is not an arbitrary limit: the arguments which represent offsets
1828 into the pattern are two bytes long. So if 2^15 bytes turns out to
1829 be too small, many things would have to change. */
1830 # define MAX_BUF_SIZE (1L << 15)
1832 #if 0 /* This is when we thought it could be 2^16 bytes. */
1833 /* Any other compiler which, like MSC, has allocation limit below 2^16
1834 bytes will have to use approach similar to what was done below for
1835 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1836 reallocating to 0 bytes. Such thing is not going to work too well.
1837 You have been warned!! */
1838 #if defined _MSC_VER && !defined WIN32
1839 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1840 # define MAX_BUF_SIZE 65500L
1842 # define MAX_BUF_SIZE (1L << 16)
1846 /* Extend the buffer by twice its current size via realloc and
1847 reset the pointers that pointed into the old block to point to the
1848 correct places in the new one. If extending the buffer results in it
1849 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1850 #if __BOUNDED_POINTERS__
1851 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1852 # define MOVE_BUFFER_POINTER(P) \
1853 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1854 SET_HIGH_BOUND (P), \
1855 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1856 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1859 SET_HIGH_BOUND (b); \
1860 SET_HIGH_BOUND (begalt); \
1861 if (fixup_alt_jump) \
1862 SET_HIGH_BOUND (fixup_alt_jump); \
1864 SET_HIGH_BOUND (laststart); \
1865 if (pending_exact) \
1866 SET_HIGH_BOUND (pending_exact); \
1869 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1870 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1872 #define EXTEND_BUFFER() \
1874 unsigned char *old_buffer = bufp->buffer; \
1875 if (bufp->allocated == MAX_BUF_SIZE) \
1877 bufp->allocated <<= 1; \
1878 if (bufp->allocated > MAX_BUF_SIZE) \
1879 bufp->allocated = MAX_BUF_SIZE; \
1880 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1881 if (bufp->buffer == NULL) \
1882 return REG_ESPACE; \
1883 /* If the buffer moved, move all the pointers into it. */ \
1884 if (old_buffer != bufp->buffer) \
1886 unsigned char *new_buffer = bufp->buffer; \
1887 MOVE_BUFFER_POINTER (b); \
1888 MOVE_BUFFER_POINTER (begalt); \
1889 if (fixup_alt_jump) \
1890 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1892 MOVE_BUFFER_POINTER (laststart); \
1893 if (pending_exact) \
1894 MOVE_BUFFER_POINTER (pending_exact); \
1896 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1900 /* Since we have one byte reserved for the register number argument to
1901 {start,stop}_memory, the maximum number of groups we can report
1902 things about is what fits in that byte. */
1903 #define MAX_REGNUM 255
1905 /* But patterns can have more than `MAX_REGNUM' registers. We just
1906 ignore the excess. */
1907 typedef int regnum_t
;
1910 /* Macros for the compile stack. */
1912 /* Since offsets can go either forwards or backwards, this type needs to
1913 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1914 /* int may be not enough when sizeof(int) == 2. */
1915 typedef long pattern_offset_t
;
1919 pattern_offset_t begalt_offset
;
1920 pattern_offset_t fixup_alt_jump
;
1921 pattern_offset_t laststart_offset
;
1923 } compile_stack_elt_t
;
1928 compile_stack_elt_t
*stack
;
1930 unsigned avail
; /* Offset of next open position. */
1931 } compile_stack_type
;
1934 #define INIT_COMPILE_STACK_SIZE 32
1936 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1937 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1939 /* The next available element. */
1940 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1942 /* Explicit quit checking is only used on NTemacs and whenever we
1943 use polling to process input events. */
1944 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1945 extern int immediate_quit
;
1946 # define IMMEDIATE_QUIT_CHECK \
1948 if (immediate_quit) QUIT; \
1951 # define IMMEDIATE_QUIT_CHECK ((void)0)
1954 /* Structure to manage work area for range table. */
1955 struct range_table_work_area
1957 int *table
; /* actual work area. */
1958 int allocated
; /* allocated size for work area in bytes. */
1959 int used
; /* actually used size in words. */
1960 int bits
; /* flag to record character classes */
1963 /* Make sure that WORK_AREA can hold more N multibyte characters.
1964 This is used only in set_image_of_range and set_image_of_range_1.
1965 It expects WORK_AREA to be a pointer.
1966 If it can't get the space, it returns from the surrounding function. */
1968 #define EXTEND_RANGE_TABLE(work_area, n) \
1970 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1972 extend_range_table_work_area (&work_area); \
1973 if ((work_area).table == 0) \
1974 return (REG_ESPACE); \
1978 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1979 (work_area).bits |= (bit)
1981 /* Bits used to implement the multibyte-part of the various character classes
1982 such as [:alnum:] in a charset's range table. */
1983 #define BIT_WORD 0x1
1984 #define BIT_LOWER 0x2
1985 #define BIT_PUNCT 0x4
1986 #define BIT_SPACE 0x8
1987 #define BIT_UPPER 0x10
1988 #define BIT_MULTIBYTE 0x20
1990 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1991 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1993 EXTEND_RANGE_TABLE ((work_area), 2); \
1994 (work_area).table[(work_area).used++] = (range_start); \
1995 (work_area).table[(work_area).used++] = (range_end); \
1998 /* Free allocated memory for WORK_AREA. */
1999 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
2001 if ((work_area).table) \
2002 free ((work_area).table); \
2005 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
2006 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
2007 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
2008 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
2011 /* Set the bit for character C in a list. */
2012 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
2017 /* Store characters in the range FROM to TO in the bitmap at B (for
2018 ASCII and unibyte characters) and WORK_AREA (for multibyte
2019 characters) while translating them and paying attention to the
2020 continuity of translated characters.
2022 Implementation note: It is better to implement these fairly big
2023 macros by a function, but it's not that easy because macros called
2024 in this macro assume various local variables already declared. */
2026 /* Both FROM and TO are ASCII characters. */
2028 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
2032 for (C0 = (FROM); C0 <= (TO); C0++) \
2034 C1 = TRANSLATE (C0); \
2035 if (! ASCII_CHAR_P (C1)) \
2037 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2038 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
2041 SET_LIST_BIT (C1); \
2046 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
2048 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
2050 int C0, C1, C2, I; \
2051 int USED = RANGE_TABLE_WORK_USED (work_area); \
2053 for (C0 = (FROM); C0 <= (TO); C0++) \
2055 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
2056 if (CHAR_BYTE8_P (C1)) \
2057 SET_LIST_BIT (C0); \
2060 C2 = TRANSLATE (C1); \
2062 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
2064 SET_LIST_BIT (C1); \
2065 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2067 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2068 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2070 if (C2 >= from - 1 && C2 <= to + 1) \
2072 if (C2 == from - 1) \
2073 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2074 else if (C2 == to + 1) \
2075 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2080 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
2086 /* Both FROM and TO are multibyte characters. */
2088 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2090 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2092 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2093 for (C0 = (FROM); C0 <= (TO); C0++) \
2095 C1 = TRANSLATE (C0); \
2096 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2097 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2098 SET_LIST_BIT (C2); \
2099 if (C1 >= (FROM) && C1 <= (TO)) \
2101 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2103 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2104 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2106 if (C1 >= from - 1 && C1 <= to + 1) \
2108 if (C1 == from - 1) \
2109 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2110 else if (C1 == to + 1) \
2111 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2116 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2122 /* Get the next unsigned number in the uncompiled pattern. */
2123 #define GET_UNSIGNED_NUMBER(num) \
2126 FREE_STACK_RETURN (REG_EBRACE); \
2130 while ('0' <= c && c <= '9') \
2136 num = num * 10 + c - '0'; \
2137 if (num / 10 != prev) \
2138 FREE_STACK_RETURN (REG_BADBR); \
2140 FREE_STACK_RETURN (REG_EBRACE); \
2146 #if ! WIDE_CHAR_SUPPORT
2148 /* Map a string to the char class it names (if any). */
2150 re_wctype (const re_char
*str
)
2152 const char *string
= str
;
2153 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2154 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2155 else if (STREQ (string
, "word")) return RECC_WORD
;
2156 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2157 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2158 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2159 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2160 else if (STREQ (string
, "print")) return RECC_PRINT
;
2161 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2162 else if (STREQ (string
, "space")) return RECC_SPACE
;
2163 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2164 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2165 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2166 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2167 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2168 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2169 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2173 /* True if CH is in the char class CC. */
2175 re_iswctype (int ch
, re_wctype_t cc
)
2179 case RECC_ALNUM
: return ISALNUM (ch
);
2180 case RECC_ALPHA
: return ISALPHA (ch
);
2181 case RECC_BLANK
: return ISBLANK (ch
);
2182 case RECC_CNTRL
: return ISCNTRL (ch
);
2183 case RECC_DIGIT
: return ISDIGIT (ch
);
2184 case RECC_GRAPH
: return ISGRAPH (ch
);
2185 case RECC_LOWER
: return ISLOWER (ch
);
2186 case RECC_PRINT
: return ISPRINT (ch
);
2187 case RECC_PUNCT
: return ISPUNCT (ch
);
2188 case RECC_SPACE
: return ISSPACE (ch
);
2189 case RECC_UPPER
: return ISUPPER (ch
);
2190 case RECC_XDIGIT
: return ISXDIGIT (ch
);
2191 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2192 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2193 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2194 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2195 case RECC_WORD
: return ISWORD (ch
);
2196 case RECC_ERROR
: return false;
2202 /* Return a bit-pattern to use in the range-table bits to match multibyte
2203 chars of class CC. */
2205 re_wctype_to_bit (re_wctype_t cc
)
2209 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2210 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2211 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2212 case RECC_LOWER
: return BIT_LOWER
;
2213 case RECC_UPPER
: return BIT_UPPER
;
2214 case RECC_PUNCT
: return BIT_PUNCT
;
2215 case RECC_SPACE
: return BIT_SPACE
;
2216 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2217 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2224 /* Filling in the work area of a range. */
2226 /* Actually extend the space in WORK_AREA. */
2229 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2231 work_area
->allocated
+= 16 * sizeof (int);
2232 if (work_area
->table
)
2234 = (int *) realloc (work_area
->table
, work_area
->allocated
);
2237 = (int *) malloc (work_area
->allocated
);
2243 /* Carefully find the ranges of codes that are equivalent
2244 under case conversion to the range start..end when passed through
2245 TRANSLATE. Handle the case where non-letters can come in between
2246 two upper-case letters (which happens in Latin-1).
2247 Also handle the case of groups of more than 2 case-equivalent chars.
2249 The basic method is to look at consecutive characters and see
2250 if they can form a run that can be handled as one.
2252 Returns -1 if successful, REG_ESPACE if ran out of space. */
2255 set_image_of_range_1 (work_area
, start
, end
, translate
)
2256 RE_TRANSLATE_TYPE translate
;
2257 struct range_table_work_area
*work_area
;
2258 re_wchar_t start
, end
;
2260 /* `one_case' indicates a character, or a run of characters,
2261 each of which is an isolate (no case-equivalents).
2262 This includes all ASCII non-letters.
2264 `two_case' indicates a character, or a run of characters,
2265 each of which has two case-equivalent forms.
2266 This includes all ASCII letters.
2268 `strange' indicates a character that has more than one
2271 enum case_type
{one_case
, two_case
, strange
};
2273 /* Describe the run that is in progress,
2274 which the next character can try to extend.
2275 If run_type is strange, that means there really is no run.
2276 If run_type is one_case, then run_start...run_end is the run.
2277 If run_type is two_case, then the run is run_start...run_end,
2278 and the case-equivalents end at run_eqv_end. */
2280 enum case_type run_type
= strange
;
2281 int run_start
, run_end
, run_eqv_end
;
2283 Lisp_Object eqv_table
;
2285 if (!RE_TRANSLATE_P (translate
))
2287 EXTEND_RANGE_TABLE (work_area
, 2);
2288 work_area
->table
[work_area
->used
++] = (start
);
2289 work_area
->table
[work_area
->used
++] = (end
);
2293 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2295 for (; start
<= end
; start
++)
2297 enum case_type this_type
;
2298 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2299 int minchar
, maxchar
;
2301 /* Classify this character */
2303 this_type
= one_case
;
2304 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2305 this_type
= two_case
;
2307 this_type
= strange
;
2310 minchar
= start
, maxchar
= eqv
;
2312 minchar
= eqv
, maxchar
= start
;
2314 /* Can this character extend the run in progress? */
2315 if (this_type
== strange
|| this_type
!= run_type
2316 || !(minchar
== run_end
+ 1
2317 && (run_type
== two_case
2318 ? maxchar
== run_eqv_end
+ 1 : 1)))
2321 Record each of its equivalent ranges. */
2322 if (run_type
== one_case
)
2324 EXTEND_RANGE_TABLE (work_area
, 2);
2325 work_area
->table
[work_area
->used
++] = run_start
;
2326 work_area
->table
[work_area
->used
++] = run_end
;
2328 else if (run_type
== two_case
)
2330 EXTEND_RANGE_TABLE (work_area
, 4);
2331 work_area
->table
[work_area
->used
++] = run_start
;
2332 work_area
->table
[work_area
->used
++] = run_end
;
2333 work_area
->table
[work_area
->used
++]
2334 = RE_TRANSLATE (eqv_table
, run_start
);
2335 work_area
->table
[work_area
->used
++]
2336 = RE_TRANSLATE (eqv_table
, run_end
);
2341 if (this_type
== strange
)
2343 /* For a strange character, add each of its equivalents, one
2344 by one. Don't start a range. */
2347 EXTEND_RANGE_TABLE (work_area
, 2);
2348 work_area
->table
[work_area
->used
++] = eqv
;
2349 work_area
->table
[work_area
->used
++] = eqv
;
2350 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2352 while (eqv
!= start
);
2355 /* Add this char to the run, or start a new run. */
2356 else if (run_type
== strange
)
2358 /* Initialize a new range. */
2359 run_type
= this_type
;
2362 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2366 /* Extend a running range. */
2368 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2372 /* If a run is still in progress at the end, finish it now
2373 by recording its equivalent ranges. */
2374 if (run_type
== one_case
)
2376 EXTEND_RANGE_TABLE (work_area
, 2);
2377 work_area
->table
[work_area
->used
++] = run_start
;
2378 work_area
->table
[work_area
->used
++] = run_end
;
2380 else if (run_type
== two_case
)
2382 EXTEND_RANGE_TABLE (work_area
, 4);
2383 work_area
->table
[work_area
->used
++] = run_start
;
2384 work_area
->table
[work_area
->used
++] = run_end
;
2385 work_area
->table
[work_area
->used
++]
2386 = RE_TRANSLATE (eqv_table
, run_start
);
2387 work_area
->table
[work_area
->used
++]
2388 = RE_TRANSLATE (eqv_table
, run_end
);
2396 /* Record the image of the range start..end when passed through
2397 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2398 and is not even necessarily contiguous.
2399 Normally we approximate it with the smallest contiguous range that contains
2400 all the chars we need. However, for Latin-1 we go to extra effort
2403 This function is not called for ASCII ranges.
2405 Returns -1 if successful, REG_ESPACE if ran out of space. */
2408 set_image_of_range (work_area
, start
, end
, translate
)
2409 RE_TRANSLATE_TYPE translate
;
2410 struct range_table_work_area
*work_area
;
2411 re_wchar_t start
, end
;
2413 re_wchar_t cmin
, cmax
;
2416 /* For Latin-1 ranges, use set_image_of_range_1
2417 to get proper handling of ranges that include letters and nonletters.
2418 For a range that includes the whole of Latin-1, this is not necessary.
2419 For other character sets, we don't bother to get this right. */
2420 if (RE_TRANSLATE_P (translate
) && start
< 04400
2421 && !(start
< 04200 && end
>= 04377))
2428 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2438 EXTEND_RANGE_TABLE (work_area
, 2);
2439 work_area
->table
[work_area
->used
++] = (start
);
2440 work_area
->table
[work_area
->used
++] = (end
);
2442 cmin
= -1, cmax
= -1;
2444 if (RE_TRANSLATE_P (translate
))
2448 for (ch
= start
; ch
<= end
; ch
++)
2450 re_wchar_t c
= TRANSLATE (ch
);
2451 if (! (start
<= c
&& c
<= end
))
2457 cmin
= MIN (cmin
, c
);
2458 cmax
= MAX (cmax
, c
);
2465 EXTEND_RANGE_TABLE (work_area
, 2);
2466 work_area
->table
[work_area
->used
++] = (cmin
);
2467 work_area
->table
[work_area
->used
++] = (cmax
);
2475 #ifndef MATCH_MAY_ALLOCATE
2477 /* If we cannot allocate large objects within re_match_2_internal,
2478 we make the fail stack and register vectors global.
2479 The fail stack, we grow to the maximum size when a regexp
2481 The register vectors, we adjust in size each time we
2482 compile a regexp, according to the number of registers it needs. */
2484 static fail_stack_type fail_stack
;
2486 /* Size with which the following vectors are currently allocated.
2487 That is so we can make them bigger as needed,
2488 but never make them smaller. */
2489 static int regs_allocated_size
;
2491 static re_char
** regstart
, ** regend
;
2492 static re_char
**best_regstart
, **best_regend
;
2494 /* Make the register vectors big enough for NUM_REGS registers,
2495 but don't make them smaller. */
2498 regex_grow_registers (num_regs
)
2501 if (num_regs
> regs_allocated_size
)
2503 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2504 RETALLOC_IF (regend
, num_regs
, re_char
*);
2505 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2506 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2508 regs_allocated_size
= num_regs
;
2512 #endif /* not MATCH_MAY_ALLOCATE */
2514 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2518 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2519 Returns one of error codes defined in `regex.h', or zero for success.
2521 Assumes the `allocated' (and perhaps `buffer') and `translate'
2522 fields are set in BUFP on entry.
2524 If it succeeds, results are put in BUFP (if it returns an error, the
2525 contents of BUFP are undefined):
2526 `buffer' is the compiled pattern;
2527 `syntax' is set to SYNTAX;
2528 `used' is set to the length of the compiled pattern;
2529 `fastmap_accurate' is zero;
2530 `re_nsub' is the number of subexpressions in PATTERN;
2531 `not_bol' and `not_eol' are zero;
2533 The `fastmap' field is neither examined nor set. */
2535 /* Insert the `jump' from the end of last alternative to "here".
2536 The space for the jump has already been allocated. */
2537 #define FIXUP_ALT_JUMP() \
2539 if (fixup_alt_jump) \
2540 STORE_JUMP (jump, fixup_alt_jump, b); \
2544 /* Return, freeing storage we allocated. */
2545 #define FREE_STACK_RETURN(value) \
2547 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2548 free (compile_stack.stack); \
2552 static reg_errcode_t
2553 regex_compile (const re_char
*pattern
, size_t size
, reg_syntax_t syntax
, struct re_pattern_buffer
*bufp
)
2555 /* We fetch characters from PATTERN here. */
2556 register re_wchar_t c
, c1
;
2558 /* A random temporary spot in PATTERN. */
2561 /* Points to the end of the buffer, where we should append. */
2562 register unsigned char *b
;
2564 /* Keeps track of unclosed groups. */
2565 compile_stack_type compile_stack
;
2567 /* Points to the current (ending) position in the pattern. */
2569 /* `const' makes AIX compiler fail. */
2570 unsigned char *p
= pattern
;
2572 re_char
*p
= pattern
;
2574 re_char
*pend
= pattern
+ size
;
2576 /* How to translate the characters in the pattern. */
2577 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2579 /* Address of the count-byte of the most recently inserted `exactn'
2580 command. This makes it possible to tell if a new exact-match
2581 character can be added to that command or if the character requires
2582 a new `exactn' command. */
2583 unsigned char *pending_exact
= 0;
2585 /* Address of start of the most recently finished expression.
2586 This tells, e.g., postfix * where to find the start of its
2587 operand. Reset at the beginning of groups and alternatives. */
2588 unsigned char *laststart
= 0;
2590 /* Address of beginning of regexp, or inside of last group. */
2591 unsigned char *begalt
;
2593 /* Place in the uncompiled pattern (i.e., the {) to
2594 which to go back if the interval is invalid. */
2595 re_char
*beg_interval
;
2597 /* Address of the place where a forward jump should go to the end of
2598 the containing expression. Each alternative of an `or' -- except the
2599 last -- ends with a forward jump of this sort. */
2600 unsigned char *fixup_alt_jump
= 0;
2602 /* Work area for range table of charset. */
2603 struct range_table_work_area range_table_work
;
2605 /* If the object matched can contain multibyte characters. */
2606 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2608 /* If a target of matching can contain multibyte characters. */
2609 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
2611 /* Nonzero if we have pushed down into a subpattern. */
2612 int in_subpattern
= 0;
2614 /* These hold the values of p, pattern, and pend from the main
2615 pattern when we have pushed into a subpattern. */
2617 re_char
*main_pattern
;
2622 DEBUG_PRINT1 ("\nCompiling pattern: ");
2625 unsigned debug_count
;
2627 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2628 putchar (pattern
[debug_count
]);
2633 /* Initialize the compile stack. */
2634 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2635 if (compile_stack
.stack
== NULL
)
2638 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2639 compile_stack
.avail
= 0;
2641 range_table_work
.table
= 0;
2642 range_table_work
.allocated
= 0;
2644 /* Initialize the pattern buffer. */
2645 bufp
->syntax
= syntax
;
2646 bufp
->fastmap_accurate
= 0;
2647 bufp
->not_bol
= bufp
->not_eol
= 0;
2648 bufp
->used_syntax
= 0;
2650 /* Set `used' to zero, so that if we return an error, the pattern
2651 printer (for debugging) will think there's no pattern. We reset it
2655 /* Always count groups, whether or not bufp->no_sub is set. */
2658 #if !defined emacs && !defined SYNTAX_TABLE
2659 /* Initialize the syntax table. */
2660 init_syntax_once ();
2663 if (bufp
->allocated
== 0)
2666 { /* If zero allocated, but buffer is non-null, try to realloc
2667 enough space. This loses if buffer's address is bogus, but
2668 that is the user's responsibility. */
2669 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2672 { /* Caller did not allocate a buffer. Do it for them. */
2673 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2675 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2677 bufp
->allocated
= INIT_BUF_SIZE
;
2680 begalt
= b
= bufp
->buffer
;
2682 /* Loop through the uncompiled pattern until we're at the end. */
2687 /* If this is the end of an included regexp,
2688 pop back to the main regexp and try again. */
2692 pattern
= main_pattern
;
2697 /* If this is the end of the main regexp, we are done. */
2709 /* If there's no special whitespace regexp, treat
2710 spaces normally. And don't try to do this recursively. */
2711 if (!whitespace_regexp
|| in_subpattern
)
2714 /* Peek past following spaces. */
2721 /* If the spaces are followed by a repetition op,
2722 treat them normally. */
2724 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2725 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2728 /* Replace the spaces with the whitespace regexp. */
2732 main_pattern
= pattern
;
2733 p
= pattern
= whitespace_regexp
;
2734 pend
= p
+ strlen (p
);
2740 if ( /* If at start of pattern, it's an operator. */
2742 /* If context independent, it's an operator. */
2743 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2744 /* Otherwise, depends on what's come before. */
2745 || at_begline_loc_p (pattern
, p
, syntax
))
2746 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2755 if ( /* If at end of pattern, it's an operator. */
2757 /* If context independent, it's an operator. */
2758 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2759 /* Otherwise, depends on what's next. */
2760 || at_endline_loc_p (p
, pend
, syntax
))
2761 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2770 if ((syntax
& RE_BK_PLUS_QM
)
2771 || (syntax
& RE_LIMITED_OPS
))
2775 /* If there is no previous pattern... */
2778 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2779 FREE_STACK_RETURN (REG_BADRPT
);
2780 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2785 /* 1 means zero (many) matches is allowed. */
2786 boolean zero_times_ok
= 0, many_times_ok
= 0;
2789 /* If there is a sequence of repetition chars, collapse it
2790 down to just one (the right one). We can't combine
2791 interval operators with these because of, e.g., `a{2}*',
2792 which should only match an even number of `a's. */
2796 if ((syntax
& RE_FRUGAL
)
2797 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2801 zero_times_ok
|= c
!= '+';
2802 many_times_ok
|= c
!= '?';
2808 || (!(syntax
& RE_BK_PLUS_QM
)
2809 && (*p
== '+' || *p
== '?')))
2811 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2814 FREE_STACK_RETURN (REG_EESCAPE
);
2815 if (p
[1] == '+' || p
[1] == '?')
2816 PATFETCH (c
); /* Gobble up the backslash. */
2822 /* If we get here, we found another repeat character. */
2826 /* Star, etc. applied to an empty pattern is equivalent
2827 to an empty pattern. */
2828 if (!laststart
|| laststart
== b
)
2831 /* Now we know whether or not zero matches is allowed
2832 and also whether or not two or more matches is allowed. */
2837 boolean simple
= skip_one_char (laststart
) == b
;
2838 unsigned int startoffset
= 0;
2840 /* Check if the loop can match the empty string. */
2841 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2842 ? on_failure_jump
: on_failure_jump_loop
;
2843 assert (skip_one_char (laststart
) <= b
);
2845 if (!zero_times_ok
&& simple
)
2846 { /* Since simple * loops can be made faster by using
2847 on_failure_keep_string_jump, we turn simple P+
2848 into PP* if P is simple. */
2849 unsigned char *p1
, *p2
;
2850 startoffset
= b
- laststart
;
2851 GET_BUFFER_SPACE (startoffset
);
2852 p1
= b
; p2
= laststart
;
2858 GET_BUFFER_SPACE (6);
2861 STORE_JUMP (ofj
, b
, b
+ 6);
2863 /* Simple * loops can use on_failure_keep_string_jump
2864 depending on what follows. But since we don't know
2865 that yet, we leave the decision up to
2866 on_failure_jump_smart. */
2867 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2868 laststart
+ startoffset
, b
+ 6);
2870 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2875 /* A simple ? pattern. */
2876 assert (zero_times_ok
);
2877 GET_BUFFER_SPACE (3);
2878 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2882 else /* not greedy */
2883 { /* I wish the greedy and non-greedy cases could be merged. */
2885 GET_BUFFER_SPACE (7); /* We might use less. */
2888 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2890 /* The non-greedy multiple match looks like
2891 a repeat..until: we only need a conditional jump
2892 at the end of the loop. */
2893 if (emptyp
) BUF_PUSH (no_op
);
2894 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2895 : on_failure_jump
, b
, laststart
);
2899 /* The repeat...until naturally matches one or more.
2900 To also match zero times, we need to first jump to
2901 the end of the loop (its conditional jump). */
2902 INSERT_JUMP (jump
, laststart
, b
);
2908 /* non-greedy a?? */
2909 INSERT_JUMP (jump
, laststart
, b
+ 3);
2911 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2928 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2930 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2932 /* Ensure that we have enough space to push a charset: the
2933 opcode, the length count, and the bitset; 34 bytes in all. */
2934 GET_BUFFER_SPACE (34);
2938 /* We test `*p == '^' twice, instead of using an if
2939 statement, so we only need one BUF_PUSH. */
2940 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2944 /* Remember the first position in the bracket expression. */
2947 /* Push the number of bytes in the bitmap. */
2948 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2950 /* Clear the whole map. */
2951 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2953 /* charset_not matches newline according to a syntax bit. */
2954 if ((re_opcode_t
) b
[-2] == charset_not
2955 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2956 SET_LIST_BIT ('\n');
2958 /* Read in characters and ranges, setting map bits. */
2961 boolean escaped_char
= false;
2962 const unsigned char *p2
= p
;
2965 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2967 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2968 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2969 So the translation is done later in a loop. Example:
2970 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2973 /* \ might escape characters inside [...] and [^...]. */
2974 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2976 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2979 escaped_char
= true;
2983 /* Could be the end of the bracket expression. If it's
2984 not (i.e., when the bracket expression is `[]' so
2985 far), the ']' character bit gets set way below. */
2986 if (c
== ']' && p2
!= p1
)
2990 /* See if we're at the beginning of a possible character
2993 if (!escaped_char
&&
2994 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2996 /* Leave room for the null. */
2997 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2998 const unsigned char *class_beg
;
3004 /* If pattern is `[[:'. */
3005 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
3010 if ((c
== ':' && *p
== ']') || p
== pend
)
3012 if (c1
< CHAR_CLASS_MAX_LENGTH
)
3015 /* This is in any case an invalid class name. */
3020 /* If isn't a word bracketed by `[:' and `:]':
3021 undo the ending character, the letters, and
3022 leave the leading `:' and `[' (but set bits for
3024 if (c
== ':' && *p
== ']')
3029 cc
= re_wctype (str
);
3032 FREE_STACK_RETURN (REG_ECTYPE
);
3034 /* Throw away the ] at the end of the character
3038 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
3041 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
3042 if (re_iswctype (btowc (ch
), cc
))
3045 if (c
< (1 << BYTEWIDTH
))
3049 /* Most character classes in a multibyte match
3050 just set a flag. Exceptions are is_blank,
3051 is_digit, is_cntrl, and is_xdigit, since
3052 they can only match ASCII characters. We
3053 don't need to handle them for multibyte.
3054 They are distinguished by a negative wctype. */
3056 /* Setup the gl_state object to its buffer-defined
3057 value. This hardcodes the buffer-global
3058 syntax-table for ASCII chars, while the other chars
3059 will obey syntax-table properties. It's not ideal,
3060 but it's the way it's been done until now. */
3061 SETUP_BUFFER_SYNTAX_TABLE ();
3063 for (ch
= 0; ch
< 256; ++ch
)
3065 c
= RE_CHAR_TO_MULTIBYTE (ch
);
3066 if (! CHAR_BYTE8_P (c
)
3067 && re_iswctype (c
, cc
))
3073 if (ASCII_CHAR_P (c1
))
3075 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
3079 SET_RANGE_TABLE_WORK_AREA_BIT
3080 (range_table_work
, re_wctype_to_bit (cc
));
3082 /* In most cases the matching rule for char classes
3083 only uses the syntax table for multibyte chars,
3084 so that the content of the syntax-table it is not
3085 hardcoded in the range_table. SPACE and WORD are
3086 the two exceptions. */
3087 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
3088 bufp
->used_syntax
= 1;
3090 /* Repeat the loop. */
3095 /* Go back to right after the "[:". */
3099 /* Because the `:' may starts the range, we
3100 can't simply set bit and repeat the loop.
3101 Instead, just set it to C and handle below. */
3106 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
3109 /* Discard the `-'. */
3112 /* Fetch the character which ends the range. */
3115 if (CHAR_BYTE8_P (c1
)
3116 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
3117 /* Treat the range from a multibyte character to
3118 raw-byte character as empty. */
3123 /* Range from C to C. */
3128 if (syntax
& RE_NO_EMPTY_RANGES
)
3129 FREE_STACK_RETURN (REG_ERANGEX
);
3130 /* Else, repeat the loop. */
3135 /* Set the range into bitmap */
3136 for (; c
<= c1
; c
++)
3139 if (ch
< (1 << BYTEWIDTH
))
3146 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
3148 if (CHAR_BYTE8_P (c1
))
3149 c
= BYTE8_TO_CHAR (128);
3153 if (CHAR_BYTE8_P (c
))
3155 c
= CHAR_TO_BYTE8 (c
);
3156 c1
= CHAR_TO_BYTE8 (c1
);
3157 for (; c
<= c1
; c
++)
3162 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
3166 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
3173 /* Discard any (non)matching list bytes that are all 0 at the
3174 end of the map. Decrease the map-length byte too. */
3175 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3179 /* Build real range table from work area. */
3180 if (RANGE_TABLE_WORK_USED (range_table_work
)
3181 || RANGE_TABLE_WORK_BITS (range_table_work
))
3184 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3186 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3187 bytes for flags, two for COUNT, and three bytes for
3189 GET_BUFFER_SPACE (4 + used
* 3);
3191 /* Indicate the existence of range table. */
3192 laststart
[1] |= 0x80;
3194 /* Store the character class flag bits into the range table.
3195 If not in emacs, these flag bits are always 0. */
3196 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3197 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3199 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3200 for (i
= 0; i
< used
; i
++)
3201 STORE_CHARACTER_AND_INCR
3202 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3209 if (syntax
& RE_NO_BK_PARENS
)
3216 if (syntax
& RE_NO_BK_PARENS
)
3223 if (syntax
& RE_NEWLINE_ALT
)
3230 if (syntax
& RE_NO_BK_VBAR
)
3237 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3238 goto handle_interval
;
3244 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3246 /* Do not translate the character after the \, so that we can
3247 distinguish, e.g., \B from \b, even if we normally would
3248 translate, e.g., B to b. */
3254 if (syntax
& RE_NO_BK_PARENS
)
3255 goto normal_backslash
;
3260 regnum_t regnum
= 0;
3263 /* Look for a special (?...) construct */
3264 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3266 PATFETCH (c
); /* Gobble up the '?'. */
3272 case ':': shy
= 1; break;
3274 /* An explicitly specified regnum must start
3277 FREE_STACK_RETURN (REG_BADPAT
);
3278 case '1': case '2': case '3': case '4':
3279 case '5': case '6': case '7': case '8': case '9':
3280 regnum
= 10*regnum
+ (c
- '0'); break;
3282 /* Only (?:...) is supported right now. */
3283 FREE_STACK_RETURN (REG_BADPAT
);
3290 regnum
= ++bufp
->re_nsub
;
3292 { /* It's actually not shy, but explicitly numbered. */
3294 if (regnum
> bufp
->re_nsub
)
3295 bufp
->re_nsub
= regnum
;
3296 else if (regnum
> bufp
->re_nsub
3297 /* Ideally, we'd want to check that the specified
3298 group can't have matched (i.e. all subgroups
3299 using the same regnum are in other branches of
3300 OR patterns), but we don't currently keep track
3301 of enough info to do that easily. */
3302 || group_in_compile_stack (compile_stack
, regnum
))
3303 FREE_STACK_RETURN (REG_BADPAT
);
3306 /* It's really shy. */
3307 regnum
= - bufp
->re_nsub
;
3309 if (COMPILE_STACK_FULL
)
3311 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3312 compile_stack_elt_t
);
3313 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3315 compile_stack
.size
<<= 1;
3318 /* These are the values to restore when we hit end of this
3319 group. They are all relative offsets, so that if the
3320 whole pattern moves because of realloc, they will still
3322 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3323 COMPILE_STACK_TOP
.fixup_alt_jump
3324 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3325 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3326 COMPILE_STACK_TOP
.regnum
= regnum
;
3328 /* Do not push a start_memory for groups beyond the last one
3329 we can represent in the compiled pattern. */
3330 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3331 BUF_PUSH_2 (start_memory
, regnum
);
3333 compile_stack
.avail
++;
3338 /* If we've reached MAX_REGNUM groups, then this open
3339 won't actually generate any code, so we'll have to
3340 clear pending_exact explicitly. */
3346 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3348 if (COMPILE_STACK_EMPTY
)
3350 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3351 goto normal_backslash
;
3353 FREE_STACK_RETURN (REG_ERPAREN
);
3359 /* See similar code for backslashed left paren above. */
3360 if (COMPILE_STACK_EMPTY
)
3362 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3365 FREE_STACK_RETURN (REG_ERPAREN
);
3368 /* Since we just checked for an empty stack above, this
3369 ``can't happen''. */
3370 assert (compile_stack
.avail
!= 0);
3372 /* We don't just want to restore into `regnum', because
3373 later groups should continue to be numbered higher,
3374 as in `(ab)c(de)' -- the second group is #2. */
3377 compile_stack
.avail
--;
3378 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3380 = COMPILE_STACK_TOP
.fixup_alt_jump
3381 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3383 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3384 regnum
= COMPILE_STACK_TOP
.regnum
;
3385 /* If we've reached MAX_REGNUM groups, then this open
3386 won't actually generate any code, so we'll have to
3387 clear pending_exact explicitly. */
3390 /* We're at the end of the group, so now we know how many
3391 groups were inside this one. */
3392 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3393 BUF_PUSH_2 (stop_memory
, regnum
);
3398 case '|': /* `\|'. */
3399 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3400 goto normal_backslash
;
3402 if (syntax
& RE_LIMITED_OPS
)
3405 /* Insert before the previous alternative a jump which
3406 jumps to this alternative if the former fails. */
3407 GET_BUFFER_SPACE (3);
3408 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3412 /* The alternative before this one has a jump after it
3413 which gets executed if it gets matched. Adjust that
3414 jump so it will jump to this alternative's analogous
3415 jump (put in below, which in turn will jump to the next
3416 (if any) alternative's such jump, etc.). The last such
3417 jump jumps to the correct final destination. A picture:
3423 If we are at `b', then fixup_alt_jump right now points to a
3424 three-byte space after `a'. We'll put in the jump, set
3425 fixup_alt_jump to right after `b', and leave behind three
3426 bytes which we'll fill in when we get to after `c'. */
3430 /* Mark and leave space for a jump after this alternative,
3431 to be filled in later either by next alternative or
3432 when know we're at the end of a series of alternatives. */
3434 GET_BUFFER_SPACE (3);
3443 /* If \{ is a literal. */
3444 if (!(syntax
& RE_INTERVALS
)
3445 /* If we're at `\{' and it's not the open-interval
3447 || (syntax
& RE_NO_BK_BRACES
))
3448 goto normal_backslash
;
3452 /* If got here, then the syntax allows intervals. */
3454 /* At least (most) this many matches must be made. */
3455 int lower_bound
= 0, upper_bound
= -1;
3459 GET_UNSIGNED_NUMBER (lower_bound
);
3462 GET_UNSIGNED_NUMBER (upper_bound
);
3464 /* Interval such as `{1}' => match exactly once. */
3465 upper_bound
= lower_bound
;
3467 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3468 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3469 FREE_STACK_RETURN (REG_BADBR
);
3471 if (!(syntax
& RE_NO_BK_BRACES
))
3474 FREE_STACK_RETURN (REG_BADBR
);
3476 FREE_STACK_RETURN (REG_EESCAPE
);
3481 FREE_STACK_RETURN (REG_BADBR
);
3483 /* We just parsed a valid interval. */
3485 /* If it's invalid to have no preceding re. */
3488 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3489 FREE_STACK_RETURN (REG_BADRPT
);
3490 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3493 goto unfetch_interval
;
3496 if (upper_bound
== 0)
3497 /* If the upper bound is zero, just drop the sub pattern
3500 else if (lower_bound
== 1 && upper_bound
== 1)
3501 /* Just match it once: nothing to do here. */
3504 /* Otherwise, we have a nontrivial interval. When
3505 we're all done, the pattern will look like:
3506 set_number_at <jump count> <upper bound>
3507 set_number_at <succeed_n count> <lower bound>
3508 succeed_n <after jump addr> <succeed_n count>
3510 jump_n <succeed_n addr> <jump count>
3511 (The upper bound and `jump_n' are omitted if
3512 `upper_bound' is 1, though.) */
3514 { /* If the upper bound is > 1, we need to insert
3515 more at the end of the loop. */
3516 unsigned int nbytes
= (upper_bound
< 0 ? 3
3517 : upper_bound
> 1 ? 5 : 0);
3518 unsigned int startoffset
= 0;
3520 GET_BUFFER_SPACE (20); /* We might use less. */
3522 if (lower_bound
== 0)
3524 /* A succeed_n that starts with 0 is really a
3525 a simple on_failure_jump_loop. */
3526 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3532 /* Initialize lower bound of the `succeed_n', even
3533 though it will be set during matching by its
3534 attendant `set_number_at' (inserted next),
3535 because `re_compile_fastmap' needs to know.
3536 Jump to the `jump_n' we might insert below. */
3537 INSERT_JUMP2 (succeed_n
, laststart
,
3542 /* Code to initialize the lower bound. Insert
3543 before the `succeed_n'. The `5' is the last two
3544 bytes of this `set_number_at', plus 3 bytes of
3545 the following `succeed_n'. */
3546 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3551 if (upper_bound
< 0)
3553 /* A negative upper bound stands for infinity,
3554 in which case it degenerates to a plain jump. */
3555 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3558 else if (upper_bound
> 1)
3559 { /* More than one repetition is allowed, so
3560 append a backward jump to the `succeed_n'
3561 that starts this interval.
3563 When we've reached this during matching,
3564 we'll have matched the interval once, so
3565 jump back only `upper_bound - 1' times. */
3566 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3570 /* The location we want to set is the second
3571 parameter of the `jump_n'; that is `b-2' as
3572 an absolute address. `laststart' will be
3573 the `set_number_at' we're about to insert;
3574 `laststart+3' the number to set, the source
3575 for the relative address. But we are
3576 inserting into the middle of the pattern --
3577 so everything is getting moved up by 5.
3578 Conclusion: (b - 2) - (laststart + 3) + 5,
3579 i.e., b - laststart.
3581 We insert this at the beginning of the loop
3582 so that if we fail during matching, we'll
3583 reinitialize the bounds. */
3584 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3585 upper_bound
- 1, b
);
3590 beg_interval
= NULL
;
3595 /* If an invalid interval, match the characters as literals. */
3596 assert (beg_interval
);
3598 beg_interval
= NULL
;
3600 /* normal_char and normal_backslash need `c'. */
3603 if (!(syntax
& RE_NO_BK_BRACES
))
3605 assert (p
> pattern
&& p
[-1] == '\\');
3606 goto normal_backslash
;
3612 /* There is no way to specify the before_dot and after_dot
3613 operators. rms says this is ok. --karl */
3621 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3627 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3633 BUF_PUSH_2 (categoryspec
, c
);
3639 BUF_PUSH_2 (notcategoryspec
, c
);
3645 if (syntax
& RE_NO_GNU_OPS
)
3648 BUF_PUSH_2 (syntaxspec
, Sword
);
3653 if (syntax
& RE_NO_GNU_OPS
)
3656 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3661 if (syntax
& RE_NO_GNU_OPS
)
3667 if (syntax
& RE_NO_GNU_OPS
)
3673 if (syntax
& RE_NO_GNU_OPS
)
3682 FREE_STACK_RETURN (REG_BADPAT
);
3686 if (syntax
& RE_NO_GNU_OPS
)
3688 BUF_PUSH (wordbound
);
3692 if (syntax
& RE_NO_GNU_OPS
)
3694 BUF_PUSH (notwordbound
);
3698 if (syntax
& RE_NO_GNU_OPS
)
3704 if (syntax
& RE_NO_GNU_OPS
)
3709 case '1': case '2': case '3': case '4': case '5':
3710 case '6': case '7': case '8': case '9':
3714 if (syntax
& RE_NO_BK_REFS
)
3715 goto normal_backslash
;
3719 if (reg
> bufp
->re_nsub
|| reg
< 1
3720 /* Can't back reference to a subexp before its end. */
3721 || group_in_compile_stack (compile_stack
, reg
))
3722 FREE_STACK_RETURN (REG_ESUBREG
);
3725 BUF_PUSH_2 (duplicate
, reg
);
3732 if (syntax
& RE_BK_PLUS_QM
)
3735 goto normal_backslash
;
3739 /* You might think it would be useful for \ to mean
3740 not to translate; but if we don't translate it
3741 it will never match anything. */
3748 /* Expects the character in `c'. */
3750 /* If no exactn currently being built. */
3753 /* If last exactn not at current position. */
3754 || pending_exact
+ *pending_exact
+ 1 != b
3756 /* We have only one byte following the exactn for the count. */
3757 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3759 /* If followed by a repetition operator. */
3760 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3761 || ((syntax
& RE_BK_PLUS_QM
)
3762 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3763 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3764 || ((syntax
& RE_INTERVALS
)
3765 && ((syntax
& RE_NO_BK_BRACES
)
3766 ? p
!= pend
&& *p
== '{'
3767 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3769 /* Start building a new exactn. */
3773 BUF_PUSH_2 (exactn
, 0);
3774 pending_exact
= b
- 1;
3777 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3784 len
= CHAR_STRING (c
, b
);
3789 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3790 if (! CHAR_BYTE8_P (c1
))
3792 re_wchar_t c2
= TRANSLATE (c1
);
3794 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3800 (*pending_exact
) += len
;
3805 } /* while p != pend */
3808 /* Through the pattern now. */
3812 if (!COMPILE_STACK_EMPTY
)
3813 FREE_STACK_RETURN (REG_EPAREN
);
3815 /* If we don't want backtracking, force success
3816 the first time we reach the end of the compiled pattern. */
3817 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3820 /* We have succeeded; set the length of the buffer. */
3821 bufp
->used
= b
- bufp
->buffer
;
3826 re_compile_fastmap (bufp
);
3827 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3828 print_compiled_pattern (bufp
);
3833 #ifndef MATCH_MAY_ALLOCATE
3834 /* Initialize the failure stack to the largest possible stack. This
3835 isn't necessary unless we're trying to avoid calling alloca in
3836 the search and match routines. */
3838 int num_regs
= bufp
->re_nsub
+ 1;
3840 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3842 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3844 if (! fail_stack
.stack
)
3846 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3847 * sizeof (fail_stack_elt_t
));
3850 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3852 * sizeof (fail_stack_elt_t
)));
3855 regex_grow_registers (num_regs
);
3857 #endif /* not MATCH_MAY_ALLOCATE */
3859 FREE_STACK_RETURN (REG_NOERROR
);
3860 } /* regex_compile */
3862 /* Subroutines for `regex_compile'. */
3864 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3867 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3869 *loc
= (unsigned char) op
;
3870 STORE_NUMBER (loc
+ 1, arg
);
3874 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3877 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3879 *loc
= (unsigned char) op
;
3880 STORE_NUMBER (loc
+ 1, arg1
);
3881 STORE_NUMBER (loc
+ 3, arg2
);
3885 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3886 for OP followed by two-byte integer parameter ARG. */
3889 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3891 register unsigned char *pfrom
= end
;
3892 register unsigned char *pto
= end
+ 3;
3894 while (pfrom
!= loc
)
3897 store_op1 (op
, loc
, arg
);
3901 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3904 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3906 register unsigned char *pfrom
= end
;
3907 register unsigned char *pto
= end
+ 5;
3909 while (pfrom
!= loc
)
3912 store_op2 (op
, loc
, arg1
, arg2
);
3916 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3917 after an alternative or a begin-subexpression. We assume there is at
3918 least one character before the ^. */
3921 at_begline_loc_p (const re_char
*pattern
, const re_char
*p
, reg_syntax_t syntax
)
3923 re_char
*prev
= p
- 2;
3924 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3927 /* After a subexpression? */
3928 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3929 /* After an alternative? */
3930 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3931 /* After a shy subexpression? */
3932 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3933 && prev
[-1] == '?' && prev
[-2] == '('
3934 && (syntax
& RE_NO_BK_PARENS
3935 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3939 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3940 at least one character after the $, i.e., `P < PEND'. */
3943 at_endline_loc_p (const re_char
*p
, const re_char
*pend
, reg_syntax_t syntax
)
3946 boolean next_backslash
= *next
== '\\';
3947 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3950 /* Before a subexpression? */
3951 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3952 : next_backslash
&& next_next
&& *next_next
== ')')
3953 /* Before an alternative? */
3954 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3955 : next_backslash
&& next_next
&& *next_next
== '|');
3959 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3960 false if it's not. */
3963 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3967 for (this_element
= compile_stack
.avail
- 1;
3970 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3977 If fastmap is non-NULL, go through the pattern and fill fastmap
3978 with all the possible leading chars. If fastmap is NULL, don't
3979 bother filling it up (obviously) and only return whether the
3980 pattern could potentially match the empty string.
3982 Return 1 if p..pend might match the empty string.
3983 Return 0 if p..pend matches at least one char.
3984 Return -1 if fastmap was not updated accurately. */
3987 analyse_first (const re_char
*p
, const re_char
*pend
, char *fastmap
, const int multibyte
)
3992 /* If all elements for base leading-codes in fastmap is set, this
3993 flag is set true. */
3994 boolean match_any_multibyte_characters
= false;
3998 /* The loop below works as follows:
3999 - It has a working-list kept in the PATTERN_STACK and which basically
4000 starts by only containing a pointer to the first operation.
4001 - If the opcode we're looking at is a match against some set of
4002 chars, then we add those chars to the fastmap and go on to the
4003 next work element from the worklist (done via `break').
4004 - If the opcode is a control operator on the other hand, we either
4005 ignore it (if it's meaningless at this point, such as `start_memory')
4006 or execute it (if it's a jump). If the jump has several destinations
4007 (i.e. `on_failure_jump'), then we push the other destination onto the
4009 We guarantee termination by ignoring backward jumps (more or less),
4010 so that `p' is monotonically increasing. More to the point, we
4011 never set `p' (or push) anything `<= p1'. */
4015 /* `p1' is used as a marker of how far back a `on_failure_jump'
4016 can go without being ignored. It is normally equal to `p'
4017 (which prevents any backward `on_failure_jump') except right
4018 after a plain `jump', to allow patterns such as:
4021 10: on_failure_jump 3
4022 as used for the *? operator. */
4025 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
4032 /* If the first character has to match a backreference, that means
4033 that the group was empty (since it already matched). Since this
4034 is the only case that interests us here, we can assume that the
4035 backreference must match the empty string. */
4040 /* Following are the cases which match a character. These end
4046 /* If multibyte is nonzero, the first byte of each
4047 character is an ASCII or a leading code. Otherwise,
4048 each byte is a character. Thus, this works in both
4053 /* For the case of matching this unibyte regex
4054 against multibyte, we must set a leading code of
4055 the corresponding multibyte character. */
4056 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
4058 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
4065 /* We could put all the chars except for \n (and maybe \0)
4066 but we don't bother since it is generally not worth it. */
4067 if (!fastmap
) break;
4072 if (!fastmap
) break;
4074 /* Chars beyond end of bitmap are possible matches. */
4075 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
4076 j
< (1 << BYTEWIDTH
); j
++)
4082 if (!fastmap
) break;
4083 not = (re_opcode_t
) *(p
- 1) == charset_not
;
4084 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
4086 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
4090 if (/* Any leading code can possibly start a character
4091 which doesn't match the specified set of characters. */
4094 /* If we can match a character class, we can match any
4095 multibyte characters. */
4096 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4097 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
4100 if (match_any_multibyte_characters
== false)
4102 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4103 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4105 match_any_multibyte_characters
= true;
4109 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4110 && match_any_multibyte_characters
== false)
4112 /* Set fastmap[I] to 1 where I is a leading code of each
4113 multibyte characer in the range table. */
4115 unsigned char lc1
, lc2
;
4117 /* Make P points the range table. `+ 2' is to skip flag
4118 bits for a character class. */
4119 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
4121 /* Extract the number of ranges in range table into COUNT. */
4122 EXTRACT_NUMBER_AND_INCR (count
, p
);
4123 for (; count
> 0; count
--, p
+= 3)
4125 /* Extract the start and end of each range. */
4126 EXTRACT_CHARACTER (c
, p
);
4127 lc1
= CHAR_LEADING_CODE (c
);
4129 EXTRACT_CHARACTER (c
, p
);
4130 lc2
= CHAR_LEADING_CODE (c
);
4131 for (j
= lc1
; j
<= lc2
; j
++)
4140 if (!fastmap
) break;
4142 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
4144 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4145 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4149 /* This match depends on text properties. These end with
4150 aborting optimizations. */
4154 case notcategoryspec
:
4155 if (!fastmap
) break;
4156 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4158 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
4159 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4162 /* Any leading code can possibly start a character which
4163 has or doesn't has the specified category. */
4164 if (match_any_multibyte_characters
== false)
4166 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4167 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4169 match_any_multibyte_characters
= true;
4173 /* All cases after this match the empty string. These end with
4195 EXTRACT_NUMBER_AND_INCR (j
, p
);
4197 /* Backward jumps can only go back to code that we've already
4198 visited. `re_compile' should make sure this is true. */
4201 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4203 case on_failure_jump
:
4204 case on_failure_keep_string_jump
:
4205 case on_failure_jump_loop
:
4206 case on_failure_jump_nastyloop
:
4207 case on_failure_jump_smart
:
4213 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4214 to jump back to "just after here". */
4217 case on_failure_jump
:
4218 case on_failure_keep_string_jump
:
4219 case on_failure_jump_nastyloop
:
4220 case on_failure_jump_loop
:
4221 case on_failure_jump_smart
:
4222 EXTRACT_NUMBER_AND_INCR (j
, p
);
4224 ; /* Backward jump to be ignored. */
4226 { /* We have to look down both arms.
4227 We first go down the "straight" path so as to minimize
4228 stack usage when going through alternatives. */
4229 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4237 /* This code simply does not properly handle forward jump_n. */
4238 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4240 /* jump_n can either jump or fall through. The (backward) jump
4241 case has already been handled, so we only need to look at the
4242 fallthrough case. */
4246 /* If N == 0, it should be an on_failure_jump_loop instead. */
4247 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4249 /* We only care about one iteration of the loop, so we don't
4250 need to consider the case where this behaves like an
4267 abort (); /* We have listed all the cases. */
4270 /* Getting here means we have found the possible starting
4271 characters for one path of the pattern -- and that the empty
4272 string does not match. We need not follow this path further. */
4276 /* We reached the end without matching anything. */
4279 } /* analyse_first */
4281 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4282 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4283 characters can start a string that matches the pattern. This fastmap
4284 is used by re_search to skip quickly over impossible starting points.
4286 Character codes above (1 << BYTEWIDTH) are not represented in the
4287 fastmap, but the leading codes are represented. Thus, the fastmap
4288 indicates which character sets could start a match.
4290 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4291 area as BUFP->fastmap.
4293 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4296 Returns 0 if we succeed, -2 if an internal error. */
4299 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4301 char *fastmap
= bufp
->fastmap
;
4304 assert (fastmap
&& bufp
->buffer
);
4306 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4307 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4309 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4310 fastmap
, RE_MULTIBYTE_P (bufp
));
4311 bufp
->can_be_null
= (analysis
!= 0);
4313 } /* re_compile_fastmap */
4315 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4316 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4317 this memory for recording register information. STARTS and ENDS
4318 must be allocated using the malloc library routine, and must each
4319 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4321 If NUM_REGS == 0, then subsequent matches should allocate their own
4324 Unless this function is called, the first search or match using
4325 PATTERN_BUFFER will allocate its own register data, without
4326 freeing the old data. */
4329 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4333 bufp
->regs_allocated
= REGS_REALLOCATE
;
4334 regs
->num_regs
= num_regs
;
4335 regs
->start
= starts
;
4340 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4342 regs
->start
= regs
->end
= (regoff_t
*) 0;
4345 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4347 /* Searching routines. */
4349 /* Like re_search_2, below, but only one string is specified, and
4350 doesn't let you say where to stop matching. */
4353 re_search (struct re_pattern_buffer
*bufp
, const char *string
, int size
, int startpos
, int range
, struct re_registers
*regs
)
4355 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4358 WEAK_ALIAS (__re_search
, re_search
)
4360 /* Head address of virtual concatenation of string. */
4361 #define HEAD_ADDR_VSTRING(P) \
4362 (((P) >= size1 ? string2 : string1))
4364 /* End address of virtual concatenation of string. */
4365 #define STOP_ADDR_VSTRING(P) \
4366 (((P) >= size1 ? string2 + size2 : string1 + size1))
4368 /* Address of POS in the concatenation of virtual string. */
4369 #define POS_ADDR_VSTRING(POS) \
4370 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4372 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4373 virtual concatenation of STRING1 and STRING2, starting first at index
4374 STARTPOS, then at STARTPOS + 1, and so on.
4376 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4378 RANGE is how far to scan while trying to match. RANGE = 0 means try
4379 only at STARTPOS; in general, the last start tried is STARTPOS +
4382 In REGS, return the indices of the virtual concatenation of STRING1
4383 and STRING2 that matched the entire BUFP->buffer and its contained
4386 Do not consider matching one past the index STOP in the virtual
4387 concatenation of STRING1 and STRING2.
4389 We return either the position in the strings at which the match was
4390 found, -1 if no match, or -2 if error (such as failure
4394 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, int size1
, const char *str2
, int size2
, int startpos
, int range
, struct re_registers
*regs
, int stop
)
4397 re_char
*string1
= (re_char
*) str1
;
4398 re_char
*string2
= (re_char
*) str2
;
4399 register char *fastmap
= bufp
->fastmap
;
4400 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4401 int total_size
= size1
+ size2
;
4402 int endpos
= startpos
+ range
;
4403 boolean anchored_start
;
4404 /* Nonzero if we are searching multibyte string. */
4405 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4407 /* Check for out-of-range STARTPOS. */
4408 if (startpos
< 0 || startpos
> total_size
)
4411 /* Fix up RANGE if it might eventually take us outside
4412 the virtual concatenation of STRING1 and STRING2.
4413 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4415 range
= 0 - startpos
;
4416 else if (endpos
> total_size
)
4417 range
= total_size
- startpos
;
4419 /* If the search isn't to be a backwards one, don't waste time in a
4420 search for a pattern anchored at beginning of buffer. */
4421 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4430 /* In a forward search for something that starts with \=.
4431 don't keep searching past point. */
4432 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4434 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4440 /* Update the fastmap now if not correct already. */
4441 if (fastmap
&& !bufp
->fastmap_accurate
)
4442 re_compile_fastmap (bufp
);
4444 /* See whether the pattern is anchored. */
4445 anchored_start
= (bufp
->buffer
[0] == begline
);
4448 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4450 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4452 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4456 /* Loop through the string, looking for a place to start matching. */
4459 /* If the pattern is anchored,
4460 skip quickly past places we cannot match.
4461 We don't bother to treat startpos == 0 specially
4462 because that case doesn't repeat. */
4463 if (anchored_start
&& startpos
> 0)
4465 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4466 : string2
[startpos
- size1
- 1])
4471 /* If a fastmap is supplied, skip quickly over characters that
4472 cannot be the start of a match. If the pattern can match the
4473 null string, however, we don't need to skip characters; we want
4474 the first null string. */
4475 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4477 register re_char
*d
;
4478 register re_wchar_t buf_ch
;
4480 d
= POS_ADDR_VSTRING (startpos
);
4482 if (range
> 0) /* Searching forwards. */
4484 register int lim
= 0;
4487 if (startpos
< size1
&& startpos
+ range
>= size1
)
4488 lim
= range
- (size1
- startpos
);
4490 /* Written out as an if-else to avoid testing `translate'
4492 if (RE_TRANSLATE_P (translate
))
4499 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4500 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4501 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4504 range
-= buf_charlen
;
4510 register re_wchar_t ch
, translated
;
4513 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4514 translated
= RE_TRANSLATE (translate
, ch
);
4515 if (translated
!= ch
4516 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4518 if (fastmap
[buf_ch
])
4531 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4532 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4534 range
-= buf_charlen
;
4538 while (range
> lim
&& !fastmap
[*d
])
4544 startpos
+= irange
- range
;
4546 else /* Searching backwards. */
4550 buf_ch
= STRING_CHAR (d
);
4551 buf_ch
= TRANSLATE (buf_ch
);
4552 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4557 register re_wchar_t ch
, translated
;
4560 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4561 translated
= TRANSLATE (ch
);
4562 if (translated
!= ch
4563 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4565 if (! fastmap
[TRANSLATE (buf_ch
)])
4571 /* If can't match the null string, and that's all we have left, fail. */
4572 if (range
>= 0 && startpos
== total_size
&& fastmap
4573 && !bufp
->can_be_null
)
4576 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4577 startpos
, regs
, stop
);
4590 /* Update STARTPOS to the next character boundary. */
4593 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4594 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
4595 int len
= BYTES_BY_CHAR_HEAD (*p
);
4613 /* Update STARTPOS to the previous character boundary. */
4616 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4618 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4620 /* Find the head of multibyte form. */
4621 PREV_CHAR_BOUNDARY (p
, phead
);
4622 range
+= p0
- 1 - p
;
4626 startpos
-= p0
- 1 - p
;
4632 WEAK_ALIAS (__re_search_2
, re_search_2
)
4634 /* Declarations and macros for re_match_2. */
4636 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4638 RE_TRANSLATE_TYPE translate
,
4639 const int multibyte
));
4641 /* This converts PTR, a pointer into one of the search strings `string1'
4642 and `string2' into an offset from the beginning of that string. */
4643 #define POINTER_TO_OFFSET(ptr) \
4644 (FIRST_STRING_P (ptr) \
4645 ? ((regoff_t) ((ptr) - string1)) \
4646 : ((regoff_t) ((ptr) - string2 + size1)))
4648 /* Call before fetching a character with *d. This switches over to
4649 string2 if necessary.
4650 Check re_match_2_internal for a discussion of why end_match_2 might
4651 not be within string2 (but be equal to end_match_1 instead). */
4652 #define PREFETCH() \
4655 /* End of string2 => fail. */ \
4656 if (dend == end_match_2) \
4658 /* End of string1 => advance to string2. */ \
4660 dend = end_match_2; \
4663 /* Call before fetching a char with *d if you already checked other limits.
4664 This is meant for use in lookahead operations like wordend, etc..
4665 where we might need to look at parts of the string that might be
4666 outside of the LIMITs (i.e past `stop'). */
4667 #define PREFETCH_NOLIMIT() \
4671 dend = end_match_2; \
4674 /* Test if at very beginning or at very end of the virtual concatenation
4675 of `string1' and `string2'. If only one string, it's `string2'. */
4676 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4677 #define AT_STRINGS_END(d) ((d) == end2)
4680 /* Test if D points to a character which is word-constituent. We have
4681 two special cases to check for: if past the end of string1, look at
4682 the first character in string2; and if before the beginning of
4683 string2, look at the last character in string1. */
4684 #define WORDCHAR_P(d) \
4685 (SYNTAX ((d) == end1 ? *string2 \
4686 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4689 /* Disabled due to a compiler bug -- see comment at case wordbound */
4691 /* The comment at case wordbound is following one, but we don't use
4692 AT_WORD_BOUNDARY anymore to support multibyte form.
4694 The DEC Alpha C compiler 3.x generates incorrect code for the
4695 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4696 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4697 macro and introducing temporary variables works around the bug. */
4700 /* Test if the character before D and the one at D differ with respect
4701 to being word-constituent. */
4702 #define AT_WORD_BOUNDARY(d) \
4703 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4704 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4707 /* Free everything we malloc. */
4708 #ifdef MATCH_MAY_ALLOCATE
4709 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4710 # define FREE_VARIABLES() \
4712 REGEX_FREE_STACK (fail_stack.stack); \
4713 FREE_VAR (regstart); \
4714 FREE_VAR (regend); \
4715 FREE_VAR (best_regstart); \
4716 FREE_VAR (best_regend); \
4719 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4720 #endif /* not MATCH_MAY_ALLOCATE */
4723 /* Optimization routines. */
4725 /* If the operation is a match against one or more chars,
4726 return a pointer to the next operation, else return NULL. */
4728 skip_one_char (const re_char
*p
)
4730 switch (SWITCH_ENUM_CAST (*p
++))
4741 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4744 p
= CHARSET_RANGE_TABLE (p
- 1);
4745 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4746 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4749 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4756 case notcategoryspec
:
4768 /* Jump over non-matching operations. */
4770 skip_noops (const re_char
*p
, const re_char
*pend
)
4775 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4784 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4795 /* Non-zero if "p1 matches something" implies "p2 fails". */
4797 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const re_char
*p1
, const re_char
*p2
)
4800 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4801 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4803 assert (p1
>= bufp
->buffer
&& p1
< pend
4804 && p2
>= bufp
->buffer
&& p2
<= pend
);
4806 /* Skip over open/close-group commands.
4807 If what follows this loop is a ...+ construct,
4808 look at what begins its body, since we will have to
4809 match at least one of that. */
4810 p2
= skip_noops (p2
, pend
);
4811 /* The same skip can be done for p1, except that this function
4812 is only used in the case where p1 is a simple match operator. */
4813 /* p1 = skip_noops (p1, pend); */
4815 assert (p1
>= bufp
->buffer
&& p1
< pend
4816 && p2
>= bufp
->buffer
&& p2
<= pend
);
4818 op2
= p2
== pend
? succeed
: *p2
;
4820 switch (SWITCH_ENUM_CAST (op2
))
4824 /* If we're at the end of the pattern, we can change. */
4825 if (skip_one_char (p1
))
4827 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4835 register re_wchar_t c
4836 = (re_opcode_t
) *p2
== endline
? '\n'
4837 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4839 if ((re_opcode_t
) *p1
== exactn
)
4841 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4843 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4848 else if ((re_opcode_t
) *p1
== charset
4849 || (re_opcode_t
) *p1
== charset_not
)
4851 int not = (re_opcode_t
) *p1
== charset_not
;
4853 /* Test if C is listed in charset (or charset_not)
4855 if (! multibyte
|| IS_REAL_ASCII (c
))
4857 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4858 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4861 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4862 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4864 /* `not' is equal to 1 if c would match, which means
4865 that we can't change to pop_failure_jump. */
4868 DEBUG_PRINT1 (" No match => fast loop.\n");
4872 else if ((re_opcode_t
) *p1
== anychar
4875 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4883 if ((re_opcode_t
) *p1
== exactn
)
4884 /* Reuse the code above. */
4885 return mutually_exclusive_p (bufp
, p2
, p1
);
4887 /* It is hard to list up all the character in charset
4888 P2 if it includes multibyte character. Give up in
4890 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4892 /* Now, we are sure that P2 has no range table.
4893 So, for the size of bitmap in P2, `p2[1]' is
4894 enough. But P1 may have range table, so the
4895 size of bitmap table of P1 is extracted by
4896 using macro `CHARSET_BITMAP_SIZE'.
4898 In a multibyte case, we know that all the character
4899 listed in P2 is ASCII. In a unibyte case, P1 has only a
4900 bitmap table. So, in both cases, it is enough to test
4901 only the bitmap table of P1. */
4903 if ((re_opcode_t
) *p1
== charset
)
4906 /* We win if the charset inside the loop
4907 has no overlap with the one after the loop. */
4910 && idx
< CHARSET_BITMAP_SIZE (p1
));
4912 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4916 || idx
== CHARSET_BITMAP_SIZE (p1
))
4918 DEBUG_PRINT1 (" No match => fast loop.\n");
4922 else if ((re_opcode_t
) *p1
== charset_not
)
4925 /* We win if the charset_not inside the loop lists
4926 every character listed in the charset after. */
4927 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4928 if (! (p2
[2 + idx
] == 0
4929 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4930 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4935 DEBUG_PRINT1 (" No match => fast loop.\n");
4944 switch (SWITCH_ENUM_CAST (*p1
))
4948 /* Reuse the code above. */
4949 return mutually_exclusive_p (bufp
, p2
, p1
);
4951 /* When we have two charset_not, it's very unlikely that
4952 they don't overlap. The union of the two sets of excluded
4953 chars should cover all possible chars, which, as a matter of
4954 fact, is virtually impossible in multibyte buffers. */
4960 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4962 return ((re_opcode_t
) *p1
== syntaxspec
4963 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4965 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4968 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4970 return ((re_opcode_t
) *p1
== notsyntaxspec
4971 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4973 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4976 return (((re_opcode_t
) *p1
== notsyntaxspec
4977 || (re_opcode_t
) *p1
== syntaxspec
)
4982 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4983 case notcategoryspec
:
4984 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4996 /* Matching routines. */
4998 #ifndef emacs /* Emacs never uses this. */
4999 /* re_match is like re_match_2 except it takes only a single string. */
5002 re_match (bufp
, string
, size
, pos
, regs
)
5003 struct re_pattern_buffer
*bufp
;
5006 struct re_registers
*regs
;
5008 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
5012 WEAK_ALIAS (__re_match
, re_match
)
5013 #endif /* not emacs */
5016 /* In Emacs, this is the string or buffer in which we
5017 are matching. It is used for looking up syntax properties. */
5018 Lisp_Object re_match_object
;
5021 /* re_match_2 matches the compiled pattern in BUFP against the
5022 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5023 and SIZE2, respectively). We start matching at POS, and stop
5026 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5027 store offsets for the substring each group matched in REGS. See the
5028 documentation for exactly how many groups we fill.
5030 We return -1 if no match, -2 if an internal error (such as the
5031 failure stack overflowing). Otherwise, we return the length of the
5032 matched substring. */
5035 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
, int size1
, const char *string2
, int size2
, int pos
, struct re_registers
*regs
, int stop
)
5041 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
5042 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
5043 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
5046 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
5047 (re_char
*) string2
, size2
,
5051 WEAK_ALIAS (__re_match_2
, re_match_2
)
5054 /* This is a separate function so that we can force an alloca cleanup
5057 re_match_2_internal (struct re_pattern_buffer
*bufp
, const re_char
*string1
, int size1
, const re_char
*string2
, int size2
, int pos
, struct re_registers
*regs
, int stop
)
5059 /* General temporaries. */
5064 /* Just past the end of the corresponding string. */
5065 re_char
*end1
, *end2
;
5067 /* Pointers into string1 and string2, just past the last characters in
5068 each to consider matching. */
5069 re_char
*end_match_1
, *end_match_2
;
5071 /* Where we are in the data, and the end of the current string. */
5074 /* Used sometimes to remember where we were before starting matching
5075 an operator so that we can go back in case of failure. This "atomic"
5076 behavior of matching opcodes is indispensable to the correctness
5077 of the on_failure_keep_string_jump optimization. */
5080 /* Where we are in the pattern, and the end of the pattern. */
5081 re_char
*p
= bufp
->buffer
;
5082 re_char
*pend
= p
+ bufp
->used
;
5084 /* We use this to map every character in the string. */
5085 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
5087 /* Nonzero if BUFP is setup from a multibyte regex. */
5088 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
5090 /* Nonzero if STRING1/STRING2 are multibyte. */
5091 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
5093 /* Failure point stack. Each place that can handle a failure further
5094 down the line pushes a failure point on this stack. It consists of
5095 regstart, and regend for all registers corresponding to
5096 the subexpressions we're currently inside, plus the number of such
5097 registers, and, finally, two char *'s. The first char * is where
5098 to resume scanning the pattern; the second one is where to resume
5099 scanning the strings. */
5100 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5101 fail_stack_type fail_stack
;
5104 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
5107 #if defined REL_ALLOC && defined REGEX_MALLOC
5108 /* This holds the pointer to the failure stack, when
5109 it is allocated relocatably. */
5110 fail_stack_elt_t
*failure_stack_ptr
;
5113 /* We fill all the registers internally, independent of what we
5114 return, for use in backreferences. The number here includes
5115 an element for register zero. */
5116 size_t num_regs
= bufp
->re_nsub
+ 1;
5118 /* Information on the contents of registers. These are pointers into
5119 the input strings; they record just what was matched (on this
5120 attempt) by a subexpression part of the pattern, that is, the
5121 regnum-th regstart pointer points to where in the pattern we began
5122 matching and the regnum-th regend points to right after where we
5123 stopped matching the regnum-th subexpression. (The zeroth register
5124 keeps track of what the whole pattern matches.) */
5125 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5126 re_char
**regstart
, **regend
;
5129 /* The following record the register info as found in the above
5130 variables when we find a match better than any we've seen before.
5131 This happens as we backtrack through the failure points, which in
5132 turn happens only if we have not yet matched the entire string. */
5133 unsigned best_regs_set
= false;
5134 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5135 re_char
**best_regstart
, **best_regend
;
5138 /* Logically, this is `best_regend[0]'. But we don't want to have to
5139 allocate space for that if we're not allocating space for anything
5140 else (see below). Also, we never need info about register 0 for
5141 any of the other register vectors, and it seems rather a kludge to
5142 treat `best_regend' differently than the rest. So we keep track of
5143 the end of the best match so far in a separate variable. We
5144 initialize this to NULL so that when we backtrack the first time
5145 and need to test it, it's not garbage. */
5146 re_char
*match_end
= NULL
;
5149 /* Counts the total number of registers pushed. */
5150 unsigned num_regs_pushed
= 0;
5153 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5157 #ifdef MATCH_MAY_ALLOCATE
5158 /* Do not bother to initialize all the register variables if there are
5159 no groups in the pattern, as it takes a fair amount of time. If
5160 there are groups, we include space for register 0 (the whole
5161 pattern), even though we never use it, since it simplifies the
5162 array indexing. We should fix this. */
5165 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5166 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5167 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5168 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5170 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5178 /* We must initialize all our variables to NULL, so that
5179 `FREE_VARIABLES' doesn't try to free them. */
5180 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5182 #endif /* MATCH_MAY_ALLOCATE */
5184 /* The starting position is bogus. */
5185 if (pos
< 0 || pos
> size1
+ size2
)
5191 /* Initialize subexpression text positions to -1 to mark ones that no
5192 start_memory/stop_memory has been seen for. Also initialize the
5193 register information struct. */
5194 for (reg
= 1; reg
< num_regs
; reg
++)
5195 regstart
[reg
] = regend
[reg
] = NULL
;
5197 /* We move `string1' into `string2' if the latter's empty -- but not if
5198 `string1' is null. */
5199 if (size2
== 0 && string1
!= NULL
)
5206 end1
= string1
+ size1
;
5207 end2
= string2
+ size2
;
5209 /* `p' scans through the pattern as `d' scans through the data.
5210 `dend' is the end of the input string that `d' points within. `d'
5211 is advanced into the following input string whenever necessary, but
5212 this happens before fetching; therefore, at the beginning of the
5213 loop, `d' can be pointing at the end of a string, but it cannot
5217 /* Only match within string2. */
5218 d
= string2
+ pos
- size1
;
5219 dend
= end_match_2
= string2
+ stop
- size1
;
5220 end_match_1
= end1
; /* Just to give it a value. */
5226 /* Only match within string1. */
5227 end_match_1
= string1
+ stop
;
5229 When we reach end_match_1, PREFETCH normally switches to string2.
5230 But in the present case, this means that just doing a PREFETCH
5231 makes us jump from `stop' to `gap' within the string.
5232 What we really want here is for the search to stop as
5233 soon as we hit end_match_1. That's why we set end_match_2
5234 to end_match_1 (since PREFETCH fails as soon as we hit
5236 end_match_2
= end_match_1
;
5239 { /* It's important to use this code when stop == size so that
5240 moving `d' from end1 to string2 will not prevent the d == dend
5241 check from catching the end of string. */
5243 end_match_2
= string2
+ stop
- size1
;
5249 DEBUG_PRINT1 ("The compiled pattern is: ");
5250 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5251 DEBUG_PRINT1 ("The string to match is: `");
5252 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5253 DEBUG_PRINT1 ("'\n");
5255 /* This loops over pattern commands. It exits by returning from the
5256 function if the match is complete, or it drops through if the match
5257 fails at this starting point in the input data. */
5260 DEBUG_PRINT2 ("\n%p: ", p
);
5263 { /* End of pattern means we might have succeeded. */
5264 DEBUG_PRINT1 ("end of pattern ... ");
5266 /* If we haven't matched the entire string, and we want the
5267 longest match, try backtracking. */
5268 if (d
!= end_match_2
)
5270 /* 1 if this match ends in the same string (string1 or string2)
5271 as the best previous match. */
5272 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5273 == FIRST_STRING_P (d
));
5274 /* 1 if this match is the best seen so far. */
5275 boolean best_match_p
;
5277 /* AIX compiler got confused when this was combined
5278 with the previous declaration. */
5280 best_match_p
= d
> match_end
;
5282 best_match_p
= !FIRST_STRING_P (d
);
5284 DEBUG_PRINT1 ("backtracking.\n");
5286 if (!FAIL_STACK_EMPTY ())
5287 { /* More failure points to try. */
5289 /* If exceeds best match so far, save it. */
5290 if (!best_regs_set
|| best_match_p
)
5292 best_regs_set
= true;
5295 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5297 for (reg
= 1; reg
< num_regs
; reg
++)
5299 best_regstart
[reg
] = regstart
[reg
];
5300 best_regend
[reg
] = regend
[reg
];
5306 /* If no failure points, don't restore garbage. And if
5307 last match is real best match, don't restore second
5309 else if (best_regs_set
&& !best_match_p
)
5312 /* Restore best match. It may happen that `dend ==
5313 end_match_1' while the restored d is in string2.
5314 For example, the pattern `x.*y.*z' against the
5315 strings `x-' and `y-z-', if the two strings are
5316 not consecutive in memory. */
5317 DEBUG_PRINT1 ("Restoring best registers.\n");
5320 dend
= ((d
>= string1
&& d
<= end1
)
5321 ? end_match_1
: end_match_2
);
5323 for (reg
= 1; reg
< num_regs
; reg
++)
5325 regstart
[reg
] = best_regstart
[reg
];
5326 regend
[reg
] = best_regend
[reg
];
5329 } /* d != end_match_2 */
5332 DEBUG_PRINT1 ("Accepting match.\n");
5334 /* If caller wants register contents data back, do it. */
5335 if (regs
&& !bufp
->no_sub
)
5337 /* Have the register data arrays been allocated? */
5338 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5339 { /* No. So allocate them with malloc. We need one
5340 extra element beyond `num_regs' for the `-1' marker
5342 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5343 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5344 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5345 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5350 bufp
->regs_allocated
= REGS_REALLOCATE
;
5352 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5353 { /* Yes. If we need more elements than were already
5354 allocated, reallocate them. If we need fewer, just
5356 if (regs
->num_regs
< num_regs
+ 1)
5358 regs
->num_regs
= num_regs
+ 1;
5359 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5360 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5361 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5370 /* These braces fend off a "empty body in an else-statement"
5371 warning under GCC when assert expands to nothing. */
5372 assert (bufp
->regs_allocated
== REGS_FIXED
);
5375 /* Convert the pointer data in `regstart' and `regend' to
5376 indices. Register zero has to be set differently,
5377 since we haven't kept track of any info for it. */
5378 if (regs
->num_regs
> 0)
5380 regs
->start
[0] = pos
;
5381 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5384 /* Go through the first `min (num_regs, regs->num_regs)'
5385 registers, since that is all we initialized. */
5386 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5388 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5389 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5393 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
5395 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
5399 /* If the regs structure we return has more elements than
5400 were in the pattern, set the extra elements to -1. If
5401 we (re)allocated the registers, this is the case,
5402 because we always allocate enough to have at least one
5404 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5405 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5406 } /* regs && !bufp->no_sub */
5408 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5409 nfailure_points_pushed
, nfailure_points_popped
,
5410 nfailure_points_pushed
- nfailure_points_popped
);
5411 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
5413 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
5415 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5421 /* Otherwise match next pattern command. */
5422 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5424 /* Ignore these. Used to ignore the n of succeed_n's which
5425 currently have n == 0. */
5427 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5431 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5434 /* Match the next n pattern characters exactly. The following
5435 byte in the pattern defines n, and the n bytes after that
5436 are the characters to match. */
5439 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5441 /* Remember the start point to rollback upon failure. */
5445 /* This is written out as an if-else so we don't waste time
5446 testing `translate' inside the loop. */
5447 if (RE_TRANSLATE_P (translate
))
5451 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5471 /* The cost of testing `translate' is comparatively small. */
5472 if (target_multibyte
)
5475 int pat_charlen
, buf_charlen
;
5480 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5483 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5486 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5488 if (TRANSLATE (buf_ch
) != pat_ch
)
5496 mcnt
-= pat_charlen
;
5502 int pat_charlen
, buf_charlen
;
5508 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5509 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5516 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5517 if (! CHAR_BYTE8_P (buf_ch
))
5519 buf_ch
= TRANSLATE (buf_ch
);
5520 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5526 if (buf_ch
!= pat_ch
)
5539 /* Match any character except possibly a newline or a null. */
5545 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5548 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5550 buf_ch
= TRANSLATE (buf_ch
);
5552 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5554 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5555 && buf_ch
== '\000'))
5558 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5567 register unsigned int c
;
5568 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5571 /* Start of actual range_table, or end of bitmap if there is no
5573 re_char
*range_table
;
5575 /* Nonzero if there is a range table. */
5576 int range_table_exists
;
5578 /* Number of ranges of range table. This is not included
5579 in the initial byte-length of the command. */
5582 /* Whether matching against a unibyte character. */
5583 boolean unibyte_char
= false;
5585 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5587 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5589 if (range_table_exists
)
5591 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5592 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5596 c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5597 if (target_multibyte
)
5602 c1
= RE_CHAR_TO_UNIBYTE (c
);
5605 unibyte_char
= true;
5611 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5613 if (! CHAR_BYTE8_P (c1
))
5615 c1
= TRANSLATE (c1
);
5616 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5619 unibyte_char
= true;
5624 unibyte_char
= true;
5627 if (unibyte_char
&& c
< (1 << BYTEWIDTH
))
5628 { /* Lookup bitmap. */
5629 /* Cast to `unsigned' instead of `unsigned char' in
5630 case the bit list is a full 32 bytes long. */
5631 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5632 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5636 else if (range_table_exists
)
5638 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5640 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5641 | (class_bits
& BIT_MULTIBYTE
)
5642 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5643 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5644 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5645 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5648 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5652 if (range_table_exists
)
5653 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5655 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5657 if (!not) goto fail
;
5664 /* The beginning of a group is represented by start_memory.
5665 The argument is the register number. The text
5666 matched within the group is recorded (in the internal
5667 registers data structure) under the register number. */
5669 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5671 /* In case we need to undo this operation (via backtracking). */
5672 PUSH_FAILURE_REG ((unsigned int)*p
);
5675 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5676 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5678 /* Move past the register number and inner group count. */
5683 /* The stop_memory opcode represents the end of a group. Its
5684 argument is the same as start_memory's: the register number. */
5686 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5688 assert (!REG_UNSET (regstart
[*p
]));
5689 /* Strictly speaking, there should be code such as:
5691 assert (REG_UNSET (regend[*p]));
5692 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5694 But the only info to be pushed is regend[*p] and it is known to
5695 be UNSET, so there really isn't anything to push.
5696 Not pushing anything, on the other hand deprives us from the
5697 guarantee that regend[*p] is UNSET since undoing this operation
5698 will not reset its value properly. This is not important since
5699 the value will only be read on the next start_memory or at
5700 the very end and both events can only happen if this stop_memory
5704 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5706 /* Move past the register number and the inner group count. */
5711 /* \<digit> has been turned into a `duplicate' command which is
5712 followed by the numeric value of <digit> as the register number. */
5715 register re_char
*d2
, *dend2
;
5716 int regno
= *p
++; /* Get which register to match against. */
5717 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5719 /* Can't back reference a group which we've never matched. */
5720 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5723 /* Where in input to try to start matching. */
5724 d2
= regstart
[regno
];
5726 /* Remember the start point to rollback upon failure. */
5729 /* Where to stop matching; if both the place to start and
5730 the place to stop matching are in the same string, then
5731 set to the place to stop, otherwise, for now have to use
5732 the end of the first string. */
5734 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5735 == FIRST_STRING_P (regend
[regno
]))
5736 ? regend
[regno
] : end_match_1
);
5739 /* If necessary, advance to next segment in register
5743 if (dend2
== end_match_2
) break;
5744 if (dend2
== regend
[regno
]) break;
5746 /* End of string1 => advance to string2. */
5748 dend2
= regend
[regno
];
5750 /* At end of register contents => success */
5751 if (d2
== dend2
) break;
5753 /* If necessary, advance to next segment in data. */
5756 /* How many characters left in this segment to match. */
5759 /* Want how many consecutive characters we can match in
5760 one shot, so, if necessary, adjust the count. */
5761 if (mcnt
> dend2
- d2
)
5764 /* Compare that many; failure if mismatch, else move
5766 if (RE_TRANSLATE_P (translate
)
5767 ? bcmp_translate (d
, d2
, mcnt
, translate
, target_multibyte
)
5768 : memcmp (d
, d2
, mcnt
))
5773 d
+= mcnt
, d2
+= mcnt
;
5779 /* begline matches the empty string at the beginning of the string
5780 (unless `not_bol' is set in `bufp'), and after newlines. */
5782 DEBUG_PRINT1 ("EXECUTING begline.\n");
5784 if (AT_STRINGS_BEG (d
))
5786 if (!bufp
->not_bol
) break;
5791 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5795 /* In all other cases, we fail. */
5799 /* endline is the dual of begline. */
5801 DEBUG_PRINT1 ("EXECUTING endline.\n");
5803 if (AT_STRINGS_END (d
))
5805 if (!bufp
->not_eol
) break;
5809 PREFETCH_NOLIMIT ();
5816 /* Match at the very beginning of the data. */
5818 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5819 if (AT_STRINGS_BEG (d
))
5824 /* Match at the very end of the data. */
5826 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5827 if (AT_STRINGS_END (d
))
5832 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5833 pushes NULL as the value for the string on the stack. Then
5834 `POP_FAILURE_POINT' will keep the current value for the
5835 string, instead of restoring it. To see why, consider
5836 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5837 then the . fails against the \n. But the next thing we want
5838 to do is match the \n against the \n; if we restored the
5839 string value, we would be back at the foo.
5841 Because this is used only in specific cases, we don't need to
5842 check all the things that `on_failure_jump' does, to make
5843 sure the right things get saved on the stack. Hence we don't
5844 share its code. The only reason to push anything on the
5845 stack at all is that otherwise we would have to change
5846 `anychar's code to do something besides goto fail in this
5847 case; that seems worse than this. */
5848 case on_failure_keep_string_jump
:
5849 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5850 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5853 PUSH_FAILURE_POINT (p
- 3, NULL
);
5856 /* A nasty loop is introduced by the non-greedy *? and +?.
5857 With such loops, the stack only ever contains one failure point
5858 at a time, so that a plain on_failure_jump_loop kind of
5859 cycle detection cannot work. Worse yet, such a detection
5860 can not only fail to detect a cycle, but it can also wrongly
5861 detect a cycle (between different instantiations of the same
5863 So the method used for those nasty loops is a little different:
5864 We use a special cycle-detection-stack-frame which is pushed
5865 when the on_failure_jump_nastyloop failure-point is *popped*.
5866 This special frame thus marks the beginning of one iteration
5867 through the loop and we can hence easily check right here
5868 whether something matched between the beginning and the end of
5870 case on_failure_jump_nastyloop
:
5871 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5872 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5875 assert ((re_opcode_t
)p
[-4] == no_op
);
5878 CHECK_INFINITE_LOOP (p
- 4, d
);
5880 /* If there's a cycle, just continue without pushing
5881 this failure point. The failure point is the "try again"
5882 option, which shouldn't be tried.
5883 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5884 PUSH_FAILURE_POINT (p
- 3, d
);
5888 /* Simple loop detecting on_failure_jump: just check on the
5889 failure stack if the same spot was already hit earlier. */
5890 case on_failure_jump_loop
:
5892 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5893 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5897 CHECK_INFINITE_LOOP (p
- 3, d
);
5899 /* If there's a cycle, get out of the loop, as if the matching
5900 had failed. We used to just `goto fail' here, but that was
5901 aborting the search a bit too early: we want to keep the
5902 empty-loop-match and keep matching after the loop.
5903 We want (x?)*y\1z to match both xxyz and xxyxz. */
5906 PUSH_FAILURE_POINT (p
- 3, d
);
5911 /* Uses of on_failure_jump:
5913 Each alternative starts with an on_failure_jump that points
5914 to the beginning of the next alternative. Each alternative
5915 except the last ends with a jump that in effect jumps past
5916 the rest of the alternatives. (They really jump to the
5917 ending jump of the following alternative, because tensioning
5918 these jumps is a hassle.)
5920 Repeats start with an on_failure_jump that points past both
5921 the repetition text and either the following jump or
5922 pop_failure_jump back to this on_failure_jump. */
5923 case on_failure_jump
:
5924 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5925 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5928 PUSH_FAILURE_POINT (p
-3, d
);
5931 /* This operation is used for greedy *.
5932 Compare the beginning of the repeat with what in the
5933 pattern follows its end. If we can establish that there
5934 is nothing that they would both match, i.e., that we
5935 would have to backtrack because of (as in, e.g., `a*a')
5936 then we can use a non-backtracking loop based on
5937 on_failure_keep_string_jump instead of on_failure_jump. */
5938 case on_failure_jump_smart
:
5939 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5940 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5943 re_char
*p1
= p
; /* Next operation. */
5944 /* Here, we discard `const', making re_match non-reentrant. */
5945 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5946 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5948 p
-= 3; /* Reset so that we will re-execute the
5949 instruction once it's been changed. */
5951 EXTRACT_NUMBER (mcnt
, p2
- 2);
5953 /* Ensure this is a indeed the trivial kind of loop
5954 we are expecting. */
5955 assert (skip_one_char (p1
) == p2
- 3);
5956 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5957 DEBUG_STATEMENT (debug
+= 2);
5958 if (mutually_exclusive_p (bufp
, p1
, p2
))
5960 /* Use a fast `on_failure_keep_string_jump' loop. */
5961 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5962 *p3
= (unsigned char) on_failure_keep_string_jump
;
5963 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5967 /* Default to a safe `on_failure_jump' loop. */
5968 DEBUG_PRINT1 (" smart default => slow loop.\n");
5969 *p3
= (unsigned char) on_failure_jump
;
5971 DEBUG_STATEMENT (debug
-= 2);
5975 /* Unconditionally jump (without popping any failure points). */
5978 IMMEDIATE_QUIT_CHECK
;
5979 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5980 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5981 p
+= mcnt
; /* Do the jump. */
5982 DEBUG_PRINT2 ("(to %p).\n", p
);
5986 /* Have to succeed matching what follows at least n times.
5987 After that, handle like `on_failure_jump'. */
5989 /* Signedness doesn't matter since we only compare MCNT to 0. */
5990 EXTRACT_NUMBER (mcnt
, p
+ 2);
5991 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5993 /* Originally, mcnt is how many times we HAVE to succeed. */
5996 /* Here, we discard `const', making re_match non-reentrant. */
5997 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
6000 PUSH_NUMBER (p2
, mcnt
);
6003 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
6008 /* Signedness doesn't matter since we only compare MCNT to 0. */
6009 EXTRACT_NUMBER (mcnt
, p
+ 2);
6010 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
6012 /* Originally, this is how many times we CAN jump. */
6015 /* Here, we discard `const', making re_match non-reentrant. */
6016 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
6018 PUSH_NUMBER (p2
, mcnt
);
6019 goto unconditional_jump
;
6021 /* If don't have to jump any more, skip over the rest of command. */
6028 unsigned char *p2
; /* Location of the counter. */
6029 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
6031 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
6032 /* Here, we discard `const', making re_match non-reentrant. */
6033 p2
= (unsigned char*) p
+ mcnt
;
6034 /* Signedness doesn't matter since we only copy MCNT's bits . */
6035 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
6036 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
6037 PUSH_NUMBER (p2
, mcnt
);
6043 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
6044 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
6046 /* We SUCCEED (or FAIL) in one of the following cases: */
6048 /* Case 1: D is at the beginning or the end of string. */
6049 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
6053 /* C1 is the character before D, S1 is the syntax of C1, C2
6054 is the character at D, and S2 is the syntax of C2. */
6059 int offset
= PTR_TO_OFFSET (d
- 1);
6060 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6061 UPDATE_SYNTAX_TABLE (charpos
);
6063 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6066 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6068 PREFETCH_NOLIMIT ();
6069 GET_CHAR_AFTER (c2
, d
, dummy
);
6072 if (/* Case 2: Only one of S1 and S2 is Sword. */
6073 ((s1
== Sword
) != (s2
== Sword
))
6074 /* Case 3: Both of S1 and S2 are Sword, and macro
6075 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
6076 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
6085 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
6087 /* We FAIL in one of the following cases: */
6089 /* Case 1: D is at the end of string. */
6090 if (AT_STRINGS_END (d
))
6094 /* C1 is the character before D, S1 is the syntax of C1, C2
6095 is the character at D, and S2 is the syntax of C2. */
6100 int offset
= PTR_TO_OFFSET (d
);
6101 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6102 UPDATE_SYNTAX_TABLE (charpos
);
6105 GET_CHAR_AFTER (c2
, d
, dummy
);
6108 /* Case 2: S2 is not Sword. */
6112 /* Case 3: D is not at the beginning of string ... */
6113 if (!AT_STRINGS_BEG (d
))
6115 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6117 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6121 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6123 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6130 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6132 /* We FAIL in one of the following cases: */
6134 /* Case 1: D is at the beginning of string. */
6135 if (AT_STRINGS_BEG (d
))
6139 /* C1 is the character before D, S1 is the syntax of C1, C2
6140 is the character at D, and S2 is the syntax of C2. */
6145 int offset
= PTR_TO_OFFSET (d
) - 1;
6146 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6147 UPDATE_SYNTAX_TABLE (charpos
);
6149 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6152 /* Case 2: S1 is not Sword. */
6156 /* Case 3: D is not at the end of string ... */
6157 if (!AT_STRINGS_END (d
))
6159 PREFETCH_NOLIMIT ();
6160 GET_CHAR_AFTER (c2
, d
, dummy
);
6162 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6166 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6168 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6175 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6177 /* We FAIL in one of the following cases: */
6179 /* Case 1: D is at the end of string. */
6180 if (AT_STRINGS_END (d
))
6184 /* C1 is the character before D, S1 is the syntax of C1, C2
6185 is the character at D, and S2 is the syntax of C2. */
6189 int offset
= PTR_TO_OFFSET (d
);
6190 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6191 UPDATE_SYNTAX_TABLE (charpos
);
6194 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6197 /* Case 2: S2 is neither Sword nor Ssymbol. */
6198 if (s2
!= Sword
&& s2
!= Ssymbol
)
6201 /* Case 3: D is not at the beginning of string ... */
6202 if (!AT_STRINGS_BEG (d
))
6204 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6206 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6210 /* ... and S1 is Sword or Ssymbol. */
6211 if (s1
== Sword
|| s1
== Ssymbol
)
6218 DEBUG_PRINT1 ("EXECUTING symend.\n");
6220 /* We FAIL in one of the following cases: */
6222 /* Case 1: D is at the beginning of string. */
6223 if (AT_STRINGS_BEG (d
))
6227 /* C1 is the character before D, S1 is the syntax of C1, C2
6228 is the character at D, and S2 is the syntax of C2. */
6232 int offset
= PTR_TO_OFFSET (d
) - 1;
6233 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6234 UPDATE_SYNTAX_TABLE (charpos
);
6236 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6239 /* Case 2: S1 is neither Ssymbol nor Sword. */
6240 if (s1
!= Sword
&& s1
!= Ssymbol
)
6243 /* Case 3: D is not at the end of string ... */
6244 if (!AT_STRINGS_END (d
))
6246 PREFETCH_NOLIMIT ();
6247 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6249 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6253 /* ... and S2 is Sword or Ssymbol. */
6254 if (s2
== Sword
|| s2
== Ssymbol
)
6262 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6264 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
6268 int offset
= PTR_TO_OFFSET (d
);
6269 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6270 UPDATE_SYNTAX_TABLE (pos1
);
6277 GET_CHAR_AFTER (c
, d
, len
);
6278 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6286 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6287 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6292 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6293 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6298 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6299 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6304 case notcategoryspec
:
6305 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6307 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
6313 GET_CHAR_AFTER (c
, d
, len
);
6314 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6325 continue; /* Successfully executed one pattern command; keep going. */
6328 /* We goto here if a matching operation fails. */
6330 IMMEDIATE_QUIT_CHECK
;
6331 if (!FAIL_STACK_EMPTY ())
6334 /* A restart point is known. Restore to that state. */
6335 DEBUG_PRINT1 ("\nFAIL:\n");
6336 POP_FAILURE_POINT (str
, pat
);
6337 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
6339 case on_failure_keep_string_jump
:
6340 assert (str
== NULL
);
6341 goto continue_failure_jump
;
6343 case on_failure_jump_nastyloop
:
6344 assert ((re_opcode_t
)pat
[-2] == no_op
);
6345 PUSH_FAILURE_POINT (pat
- 2, str
);
6348 case on_failure_jump_loop
:
6349 case on_failure_jump
:
6352 continue_failure_jump
:
6353 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6358 /* A special frame used for nastyloops. */
6365 assert (p
>= bufp
->buffer
&& p
<= pend
);
6367 if (d
>= string1
&& d
<= end1
)
6371 break; /* Matching at this starting point really fails. */
6375 goto restore_best_regs
;
6379 return -1; /* Failure to match. */
6382 /* Subroutine definitions for re_match_2. */
6384 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6385 bytes; nonzero otherwise. */
6388 bcmp_translate (const re_char
*s1
, const re_char
*s2
, register int len
,
6389 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6391 register re_char
*p1
= s1
, *p2
= s2
;
6392 re_char
*p1_end
= s1
+ len
;
6393 re_char
*p2_end
= s2
+ len
;
6395 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6396 different lengths, but relying on a single `len' would break this. -sm */
6397 while (p1
< p1_end
&& p2
< p2_end
)
6399 int p1_charlen
, p2_charlen
;
6400 re_wchar_t p1_ch
, p2_ch
;
6402 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6403 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6405 if (RE_TRANSLATE (translate
, p1_ch
)
6406 != RE_TRANSLATE (translate
, p2_ch
))
6409 p1
+= p1_charlen
, p2
+= p2_charlen
;
6412 if (p1
!= p1_end
|| p2
!= p2_end
)
6418 /* Entry points for GNU code. */
6420 /* re_compile_pattern is the GNU regular expression compiler: it
6421 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6422 Returns 0 if the pattern was valid, otherwise an error string.
6424 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6425 are set in BUFP on entry.
6427 We call regex_compile to do the actual compilation. */
6430 re_compile_pattern (const char *pattern
, size_t length
, struct re_pattern_buffer
*bufp
)
6434 /* GNU code is written to assume at least RE_NREGS registers will be set
6435 (and at least one extra will be -1). */
6436 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6438 /* And GNU code determines whether or not to get register information
6439 by passing null for the REGS argument to re_match, etc., not by
6443 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6447 return gettext (re_error_msgid
[(int) ret
]);
6449 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6451 /* Entry points compatible with 4.2 BSD regex library. We don't define
6452 them unless specifically requested. */
6454 #if defined _REGEX_RE_COMP || defined _LIBC
6456 /* BSD has one and only one pattern buffer. */
6457 static struct re_pattern_buffer re_comp_buf
;
6461 /* Make these definitions weak in libc, so POSIX programs can redefine
6462 these names if they don't use our functions, and still use
6463 regcomp/regexec below without link errors. */
6473 if (!re_comp_buf
.buffer
)
6474 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6475 return (char *) gettext ("No previous regular expression");
6479 if (!re_comp_buf
.buffer
)
6481 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
6482 if (re_comp_buf
.buffer
== NULL
)
6483 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6484 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6485 re_comp_buf
.allocated
= 200;
6487 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6488 if (re_comp_buf
.fastmap
== NULL
)
6489 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6490 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6493 /* Since `re_exec' always passes NULL for the `regs' argument, we
6494 don't need to initialize the pattern buffer fields which affect it. */
6496 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6501 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6502 return (char *) gettext (re_error_msgid
[(int) ret
]);
6513 const int len
= strlen (s
);
6515 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
6517 #endif /* _REGEX_RE_COMP */
6519 /* POSIX.2 functions. Don't define these for Emacs. */
6523 /* regcomp takes a regular expression as a string and compiles it.
6525 PREG is a regex_t *. We do not expect any fields to be initialized,
6526 since POSIX says we shouldn't. Thus, we set
6528 `buffer' to the compiled pattern;
6529 `used' to the length of the compiled pattern;
6530 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6531 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6532 RE_SYNTAX_POSIX_BASIC;
6533 `fastmap' to an allocated space for the fastmap;
6534 `fastmap_accurate' to zero;
6535 `re_nsub' to the number of subexpressions in PATTERN.
6537 PATTERN is the address of the pattern string.
6539 CFLAGS is a series of bits which affect compilation.
6541 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6542 use POSIX basic syntax.
6544 If REG_NEWLINE is set, then . and [^...] don't match newline.
6545 Also, regexec will try a match beginning after every newline.
6547 If REG_ICASE is set, then we considers upper- and lowercase
6548 versions of letters to be equivalent when matching.
6550 If REG_NOSUB is set, then when PREG is passed to regexec, that
6551 routine will report only success or failure, and nothing about the
6554 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6555 the return codes and their meanings.) */
6558 regcomp (preg
, pattern
, cflags
)
6559 regex_t
*__restrict preg
;
6560 const char *__restrict pattern
;
6565 = (cflags
& REG_EXTENDED
) ?
6566 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6568 /* regex_compile will allocate the space for the compiled pattern. */
6570 preg
->allocated
= 0;
6573 /* Try to allocate space for the fastmap. */
6574 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6576 if (cflags
& REG_ICASE
)
6581 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6582 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6583 if (preg
->translate
== NULL
)
6584 return (int) REG_ESPACE
;
6586 /* Map uppercase characters to corresponding lowercase ones. */
6587 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6588 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6591 preg
->translate
= NULL
;
6593 /* If REG_NEWLINE is set, newlines are treated differently. */
6594 if (cflags
& REG_NEWLINE
)
6595 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6596 syntax
&= ~RE_DOT_NEWLINE
;
6597 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6600 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6602 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6604 /* POSIX says a null character in the pattern terminates it, so we
6605 can use strlen here in compiling the pattern. */
6606 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6608 /* POSIX doesn't distinguish between an unmatched open-group and an
6609 unmatched close-group: both are REG_EPAREN. */
6610 if (ret
== REG_ERPAREN
)
6613 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6614 { /* Compute the fastmap now, since regexec cannot modify the pattern
6616 re_compile_fastmap (preg
);
6617 if (preg
->can_be_null
)
6618 { /* The fastmap can't be used anyway. */
6619 free (preg
->fastmap
);
6620 preg
->fastmap
= NULL
;
6625 WEAK_ALIAS (__regcomp
, regcomp
)
6628 /* regexec searches for a given pattern, specified by PREG, in the
6631 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6632 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6633 least NMATCH elements, and we set them to the offsets of the
6634 corresponding matched substrings.
6636 EFLAGS specifies `execution flags' which affect matching: if
6637 REG_NOTBOL is set, then ^ does not match at the beginning of the
6638 string; if REG_NOTEOL is set, then $ does not match at the end.
6640 We return 0 if we find a match and REG_NOMATCH if not. */
6643 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
6644 const regex_t
*__restrict preg
;
6645 const char *__restrict string
;
6647 regmatch_t pmatch
[__restrict_arr
];
6651 struct re_registers regs
;
6652 regex_t private_preg
;
6653 int len
= strlen (string
);
6654 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6656 private_preg
= *preg
;
6658 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6659 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6661 /* The user has told us exactly how many registers to return
6662 information about, via `nmatch'. We have to pass that on to the
6663 matching routines. */
6664 private_preg
.regs_allocated
= REGS_FIXED
;
6668 regs
.num_regs
= nmatch
;
6669 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6670 if (regs
.start
== NULL
)
6671 return (int) REG_NOMATCH
;
6672 regs
.end
= regs
.start
+ nmatch
;
6675 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6676 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6677 was a little bit longer but still only matching the real part.
6678 This works because the `endline' will check for a '\n' and will find a
6679 '\0', correctly deciding that this is not the end of a line.
6680 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6681 a convenient '\0' there. For all we know, the string could be preceded
6682 by '\n' which would throw things off. */
6684 /* Perform the searching operation. */
6685 ret
= re_search (&private_preg
, string
, len
,
6686 /* start: */ 0, /* range: */ len
,
6687 want_reg_info
? ®s
: (struct re_registers
*) 0);
6689 /* Copy the register information to the POSIX structure. */
6696 for (r
= 0; r
< nmatch
; r
++)
6698 pmatch
[r
].rm_so
= regs
.start
[r
];
6699 pmatch
[r
].rm_eo
= regs
.end
[r
];
6703 /* If we needed the temporary register info, free the space now. */
6707 /* We want zero return to mean success, unlike `re_search'. */
6708 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
6710 WEAK_ALIAS (__regexec
, regexec
)
6713 /* Returns a message corresponding to an error code, ERR_CODE, returned
6714 from either regcomp or regexec. We don't use PREG here.
6716 ERR_CODE was previously called ERRCODE, but that name causes an
6717 error with msvc8 compiler. */
6720 regerror (err_code
, preg
, errbuf
, errbuf_size
)
6722 const regex_t
*preg
;
6730 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6731 /* Only error codes returned by the rest of the code should be passed
6732 to this routine. If we are given anything else, or if other regex
6733 code generates an invalid error code, then the program has a bug.
6734 Dump core so we can fix it. */
6737 msg
= gettext (re_error_msgid
[err_code
]);
6739 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6741 if (errbuf_size
!= 0)
6743 if (msg_size
> errbuf_size
)
6745 strncpy (errbuf
, msg
, errbuf_size
- 1);
6746 errbuf
[errbuf_size
- 1] = 0;
6749 strcpy (errbuf
, msg
);
6754 WEAK_ALIAS (__regerror
, regerror
)
6757 /* Free dynamically allocated space used by PREG. */
6763 free (preg
->buffer
);
6764 preg
->buffer
= NULL
;
6766 preg
->allocated
= 0;
6769 free (preg
->fastmap
);
6770 preg
->fastmap
= NULL
;
6771 preg
->fastmap_accurate
= 0;
6773 free (preg
->translate
);
6774 preg
->translate
= NULL
;
6776 WEAK_ALIAS (__regfree
, regfree
)
6778 #endif /* not emacs */
6780 /* arch-tag: 4ffd68ba-2a9e-435b-a21a-018990f9eeb2
6781 (do not change this comment) */