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-2011 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
26 need to modify the compiled regexp so that re_match can be reentrant.
27 - get rid of on_failure_jump_smart by doing the optimization in re_comp
28 rather than at run-time, so that re_match can be reentrant.
31 /* AIX requires this to be the first thing in the file. */
32 #if defined _AIX && !defined REGEX_MALLOC
40 #if defined STDC_HEADERS && !defined emacs
43 /* We need this for `regex.h', and perhaps for the Emacs include files. */
44 # include <sys/types.h>
47 /* Whether to use ISO C Amendment 1 wide char functions.
48 Those should not be used for Emacs since it uses its own. */
50 #define WIDE_CHAR_SUPPORT 1
52 #define WIDE_CHAR_SUPPORT \
53 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
56 /* For platform which support the ISO C amendement 1 functionality we
57 support user defined character classes. */
59 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
65 /* We have to keep the namespace clean. */
66 # define regfree(preg) __regfree (preg)
67 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
68 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
69 # define regerror(err_code, preg, errbuf, errbuf_size) \
70 __regerror(err_code, preg, errbuf, errbuf_size)
71 # define re_set_registers(bu, re, nu, st, en) \
72 __re_set_registers (bu, re, nu, st, en)
73 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
74 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
75 # define re_match(bufp, string, size, pos, regs) \
76 __re_match (bufp, string, size, pos, regs)
77 # define re_search(bufp, string, size, startpos, range, regs) \
78 __re_search (bufp, string, size, startpos, range, regs)
79 # define re_compile_pattern(pattern, length, bufp) \
80 __re_compile_pattern (pattern, length, bufp)
81 # define re_set_syntax(syntax) __re_set_syntax (syntax)
82 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
83 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
84 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
86 /* Make sure we call libc's function even if the user overrides them. */
87 # define btowc __btowc
88 # define iswctype __iswctype
89 # define wctype __wctype
91 # define WEAK_ALIAS(a,b) weak_alias (a, b)
93 /* We are also using some library internals. */
94 # include <locale/localeinfo.h>
95 # include <locale/elem-hash.h>
96 # include <langinfo.h>
98 # define WEAK_ALIAS(a,b)
101 /* This is for other GNU distributions with internationalized messages. */
102 #if HAVE_LIBINTL_H || defined _LIBC
103 # include <libintl.h>
105 # define gettext(msgid) (msgid)
109 /* This define is so xgettext can find the internationalizable
111 # define gettext_noop(String) String
114 /* The `emacs' switch turns on certain matching commands
115 that make sense only in Emacs. */
122 /* Make syntax table lookup grant data in gl_state. */
123 # define SYNTAX_ENTRY_VIA_PROPERTY
126 # include "character.h"
127 # include "category.h"
132 # define malloc xmalloc
136 # define realloc xrealloc
142 /* Converts the pointer to the char to BEG-based offset from the start. */
143 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
144 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
146 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
147 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
148 # define RE_STRING_CHAR(p, multibyte) \
149 (multibyte ? (STRING_CHAR (p)) : (*(p)))
150 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
151 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
153 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
155 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
157 /* Set C a (possibly converted to multibyte) character before P. P
158 points into a string which is the virtual concatenation of STR1
159 (which ends at END1) or STR2 (which ends at END2). */
160 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
162 if (target_multibyte) \
164 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
165 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
166 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
167 c = STRING_CHAR (dtemp); \
171 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
172 (c) = RE_CHAR_TO_MULTIBYTE (c); \
176 /* Set C a (possibly converted to multibyte) character at P, and set
177 LEN to the byte length of that character. */
178 # define GET_CHAR_AFTER(c, p, len) \
180 if (target_multibyte) \
181 (c) = STRING_CHAR_AND_LENGTH (p, len); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
190 #else /* not emacs */
192 /* If we are not linking with Emacs proper,
193 we can't use the relocating allocator
194 even if config.h says that we can. */
199 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
202 xmalloc (size_t size
)
205 val
= (void *) malloc (size
);
208 write (2, "virtual memory exhausted\n", 25);
215 xrealloc (void *block
, size_t size
)
218 /* We must call malloc explicitly when BLOCK is 0, since some
219 reallocs don't do this. */
221 val
= (void *) malloc (size
);
223 val
= (void *) realloc (block
, size
);
226 write (2, "virtual memory exhausted\n", 25);
235 # define malloc xmalloc
239 # define realloc xrealloc
243 /* Define the syntax stuff for \<, \>, etc. */
245 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
246 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1, Ssymbol
= 2 };
248 # define SWITCH_ENUM_CAST(x) (x)
250 /* Dummy macros for non-Emacs environments. */
251 # define CHAR_CHARSET(c) 0
252 # define CHARSET_LEADING_CODE_BASE(c) 0
253 # define MAX_MULTIBYTE_LENGTH 1
254 # define RE_MULTIBYTE_P(x) 0
255 # define RE_TARGET_MULTIBYTE_P(x) 0
256 # define WORD_BOUNDARY_P(c1, c2) (0)
257 # define CHAR_HEAD_P(p) (1)
258 # define SINGLE_BYTE_CHAR_P(c) (1)
259 # define SAME_CHARSET_P(c1, c2) (1)
260 # define BYTES_BY_CHAR_HEAD(p) (1)
261 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
262 # define STRING_CHAR(p) (*(p))
263 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
264 # define CHAR_STRING(c, s) (*(s) = (c), 1)
265 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
266 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
267 # define RE_CHAR_TO_MULTIBYTE(c) (c)
268 # define RE_CHAR_TO_UNIBYTE(c) (c)
269 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
270 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
271 # define GET_CHAR_AFTER(c, p, len) \
273 # define MAKE_CHAR(charset, c1, c2) (c1)
274 # define BYTE8_TO_CHAR(c) (c)
275 # define CHAR_BYTE8_P(c) (0)
276 # define CHAR_LEADING_CODE(c) (c)
278 #endif /* not emacs */
281 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
282 # define RE_TRANSLATE_P(TBL) (TBL)
285 /* Get the interface, including the syntax bits. */
288 /* isalpha etc. are used for the character classes. */
293 /* 1 if C is an ASCII character. */
294 # define IS_REAL_ASCII(c) ((c) < 0200)
296 /* 1 if C is a unibyte character. */
297 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
299 /* The Emacs definitions should not be directly affected by locales. */
301 /* In Emacs, these are only used for single-byte characters. */
302 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
303 # define ISCNTRL(c) ((c) < ' ')
304 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
305 || ((c) >= 'a' && (c) <= 'f') \
306 || ((c) >= 'A' && (c) <= 'F'))
308 /* This is only used for single-byte characters. */
309 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
311 /* The rest must handle multibyte characters. */
313 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
314 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
317 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
318 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
321 # define ISALNUM(c) (IS_REAL_ASCII (c) \
322 ? (((c) >= 'a' && (c) <= 'z') \
323 || ((c) >= 'A' && (c) <= 'Z') \
324 || ((c) >= '0' && (c) <= '9')) \
325 : SYNTAX (c) == Sword)
327 # define ISALPHA(c) (IS_REAL_ASCII (c) \
328 ? (((c) >= 'a' && (c) <= 'z') \
329 || ((c) >= 'A' && (c) <= 'Z')) \
330 : SYNTAX (c) == Sword)
332 # define ISLOWER(c) lowercasep (c)
334 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
335 ? ((c) > ' ' && (c) < 0177 \
336 && !(((c) >= 'a' && (c) <= 'z') \
337 || ((c) >= 'A' && (c) <= 'Z') \
338 || ((c) >= '0' && (c) <= '9'))) \
339 : SYNTAX (c) != Sword)
341 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
343 # define ISUPPER(c) uppercasep (c)
345 # define ISWORD(c) (SYNTAX (c) == Sword)
347 #else /* not emacs */
349 /* Jim Meyering writes:
351 "... Some ctype macros are valid only for character codes that
352 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
353 using /bin/cc or gcc but without giving an ansi option). So, all
354 ctype uses should be through macros like ISPRINT... If
355 STDC_HEADERS is defined, then autoconf has verified that the ctype
356 macros don't need to be guarded with references to isascii. ...
357 Defining isascii to 1 should let any compiler worth its salt
358 eliminate the && through constant folding."
359 Solaris defines some of these symbols so we must undefine them first. */
362 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
363 # define ISASCII(c) 1
365 # define ISASCII(c) isascii(c)
368 /* 1 if C is an ASCII character. */
369 # define IS_REAL_ASCII(c) ((c) < 0200)
371 /* This distinction is not meaningful, except in Emacs. */
372 # define ISUNIBYTE(c) 1
375 # define ISBLANK(c) (ISASCII (c) && isblank (c))
377 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
380 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
382 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
386 # define ISPRINT(c) (ISASCII (c) && isprint (c))
387 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
388 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
389 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
390 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
391 # define ISLOWER(c) (ISASCII (c) && islower (c))
392 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
393 # define ISSPACE(c) (ISASCII (c) && isspace (c))
394 # define ISUPPER(c) (ISASCII (c) && isupper (c))
395 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
397 # define ISWORD(c) ISALPHA(c)
400 # define TOLOWER(c) _tolower(c)
402 # define TOLOWER(c) tolower(c)
405 /* How many characters in the character set. */
406 # define CHAR_SET_SIZE 256
410 extern char *re_syntax_table
;
412 # else /* not SYNTAX_TABLE */
414 static char re_syntax_table
[CHAR_SET_SIZE
];
417 init_syntax_once (void)
425 memset (re_syntax_table
, 0, sizeof re_syntax_table
);
427 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
429 re_syntax_table
[c
] = Sword
;
431 re_syntax_table
['_'] = Ssymbol
;
436 # endif /* not SYNTAX_TABLE */
438 # define SYNTAX(c) re_syntax_table[(c)]
440 #endif /* not emacs */
443 # define NULL (void *)0
446 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
447 since ours (we hope) works properly with all combinations of
448 machines, compilers, `char' and `unsigned char' argument types.
449 (Per Bothner suggested the basic approach.) */
450 #undef SIGN_EXTEND_CHAR
452 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
453 #else /* not __STDC__ */
454 /* As in Harbison and Steele. */
455 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
458 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
459 use `alloca' instead of `malloc'. This is because using malloc in
460 re_search* or re_match* could cause memory leaks when C-g is used in
461 Emacs; also, malloc is slower and causes storage fragmentation. On
462 the other hand, malloc is more portable, and easier to debug.
464 Because we sometimes use alloca, some routines have to be macros,
465 not functions -- `alloca'-allocated space disappears at the end of the
466 function it is called in. */
470 # define REGEX_ALLOCATE malloc
471 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
472 # define REGEX_FREE free
474 #else /* not REGEX_MALLOC */
476 /* Emacs already defines alloca, sometimes. */
479 /* Make alloca work the best possible way. */
481 # define alloca __builtin_alloca
482 # else /* not __GNUC__ */
483 # ifdef HAVE_ALLOCA_H
485 # endif /* HAVE_ALLOCA_H */
486 # endif /* not __GNUC__ */
488 # endif /* not alloca */
490 # define REGEX_ALLOCATE alloca
492 /* Assumes a `char *destination' variable. */
493 # define REGEX_REALLOCATE(source, osize, nsize) \
494 (destination = (char *) alloca (nsize), \
495 memcpy (destination, source, osize))
497 /* No need to do anything to free, after alloca. */
498 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
500 #endif /* not REGEX_MALLOC */
502 /* Define how to allocate the failure stack. */
504 #if defined REL_ALLOC && defined REGEX_MALLOC
506 # define REGEX_ALLOCATE_STACK(size) \
507 r_alloc (&failure_stack_ptr, (size))
508 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
509 r_re_alloc (&failure_stack_ptr, (nsize))
510 # define REGEX_FREE_STACK(ptr) \
511 r_alloc_free (&failure_stack_ptr)
513 #else /* not using relocating allocator */
517 # define REGEX_ALLOCATE_STACK malloc
518 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
519 # define REGEX_FREE_STACK free
521 # else /* not REGEX_MALLOC */
523 # define REGEX_ALLOCATE_STACK alloca
525 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
526 REGEX_REALLOCATE (source, osize, nsize)
527 /* No need to explicitly free anything. */
528 # define REGEX_FREE_STACK(arg) ((void)0)
530 # endif /* not REGEX_MALLOC */
531 #endif /* not using relocating allocator */
534 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
535 `string1' or just past its end. This works if PTR is NULL, which is
537 #define FIRST_STRING_P(ptr) \
538 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
540 /* (Re)Allocate N items of type T using malloc, or fail. */
541 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
542 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
543 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
545 #define BYTEWIDTH 8 /* In bits. */
547 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
551 #define MAX(a, b) ((a) > (b) ? (a) : (b))
552 #define MIN(a, b) ((a) < (b) ? (a) : (b))
554 /* Type of source-pattern and string chars. */
555 typedef const unsigned char re_char
;
557 typedef char boolean
;
561 static regoff_t re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
562 re_char
*string1
, size_t size1
,
563 re_char
*string2
, size_t size2
,
565 struct re_registers
*regs
,
568 /* These are the command codes that appear in compiled regular
569 expressions. Some opcodes are followed by argument bytes. A
570 command code can specify any interpretation whatsoever for its
571 arguments. Zero bytes may appear in the compiled regular expression. */
577 /* Succeed right away--no more backtracking. */
580 /* Followed by one byte giving n, then by n literal bytes. */
583 /* Matches any (more or less) character. */
586 /* Matches any one char belonging to specified set. First
587 following byte is number of bitmap bytes. Then come bytes
588 for a bitmap saying which chars are in. Bits in each byte
589 are ordered low-bit-first. A character is in the set if its
590 bit is 1. A character too large to have a bit in the map is
591 automatically not in the set.
593 If the length byte has the 0x80 bit set, then that stuff
594 is followed by a range table:
595 2 bytes of flags for character sets (low 8 bits, high 8 bits)
596 See RANGE_TABLE_WORK_BITS below.
597 2 bytes, the number of pairs that follow (upto 32767)
598 pairs, each 2 multibyte characters,
599 each multibyte character represented as 3 bytes. */
602 /* Same parameters as charset, but match any character that is
603 not one of those specified. */
606 /* Start remembering the text that is matched, for storing in a
607 register. Followed by one byte with the register number, in
608 the range 0 to one less than the pattern buffer's re_nsub
612 /* Stop remembering the text that is matched and store it in a
613 memory register. Followed by one byte with the register
614 number, in the range 0 to one less than `re_nsub' in the
618 /* Match a duplicate of something remembered. Followed by one
619 byte containing the register number. */
622 /* Fail unless at beginning of line. */
625 /* Fail unless at end of line. */
628 /* Succeeds if at beginning of buffer (if emacs) or at beginning
629 of string to be matched (if not). */
632 /* Analogously, for end of buffer/string. */
635 /* Followed by two byte relative address to which to jump. */
638 /* Followed by two-byte relative address of place to resume at
639 in case of failure. */
642 /* Like on_failure_jump, but pushes a placeholder instead of the
643 current string position when executed. */
644 on_failure_keep_string_jump
,
646 /* Just like `on_failure_jump', except that it checks that we
647 don't get stuck in an infinite loop (matching an empty string
649 on_failure_jump_loop
,
651 /* Just like `on_failure_jump_loop', except that it checks for
652 a different kind of loop (the kind that shows up with non-greedy
653 operators). This operation has to be immediately preceded
655 on_failure_jump_nastyloop
,
657 /* A smart `on_failure_jump' used for greedy * and + operators.
658 It analyses the loop before which it is put and if the
659 loop does not require backtracking, it changes itself to
660 `on_failure_keep_string_jump' and short-circuits the loop,
661 else it just defaults to changing itself into `on_failure_jump'.
662 It assumes that it is pointing to just past a `jump'. */
663 on_failure_jump_smart
,
665 /* Followed by two-byte relative address and two-byte number n.
666 After matching N times, jump to the address upon failure.
667 Does not work if N starts at 0: use on_failure_jump_loop
671 /* Followed by two-byte relative address, and two-byte number n.
672 Jump to the address N times, then fail. */
675 /* Set the following two-byte relative address to the
676 subsequent two-byte number. The address *includes* the two
680 wordbeg
, /* Succeeds if at word beginning. */
681 wordend
, /* Succeeds if at word end. */
683 wordbound
, /* Succeeds if at a word boundary. */
684 notwordbound
, /* Succeeds if not at a word boundary. */
686 symbeg
, /* Succeeds if at symbol beginning. */
687 symend
, /* Succeeds if at symbol end. */
689 /* Matches any character whose syntax is specified. Followed by
690 a byte which contains a syntax code, e.g., Sword. */
693 /* Matches any character whose syntax is not that specified. */
697 ,before_dot
, /* Succeeds if before point. */
698 at_dot
, /* Succeeds if at point. */
699 after_dot
, /* Succeeds if after point. */
701 /* Matches any character whose category-set contains the specified
702 category. The operator is followed by a byte which contains a
703 category code (mnemonic ASCII character). */
706 /* Matches any character whose category-set does not contain the
707 specified category. The operator is followed by a byte which
708 contains the category code (mnemonic ASCII character). */
713 /* Common operations on the compiled pattern. */
715 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
717 #define STORE_NUMBER(destination, number) \
719 (destination)[0] = (number) & 0377; \
720 (destination)[1] = (number) >> 8; \
723 /* Same as STORE_NUMBER, except increment DESTINATION to
724 the byte after where the number is stored. Therefore, DESTINATION
725 must be an lvalue. */
727 #define STORE_NUMBER_AND_INCR(destination, number) \
729 STORE_NUMBER (destination, number); \
730 (destination) += 2; \
733 /* Put into DESTINATION a number stored in two contiguous bytes starting
736 #define EXTRACT_NUMBER(destination, source) \
738 (destination) = *(source) & 0377; \
739 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
743 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
745 extract_number (dest
, source
)
749 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
750 *dest
= *source
& 0377;
754 # ifndef EXTRACT_MACROS /* To debug the macros. */
755 # undef EXTRACT_NUMBER
756 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
757 # endif /* not EXTRACT_MACROS */
761 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
762 SOURCE must be an lvalue. */
764 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
766 EXTRACT_NUMBER (destination, source); \
771 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
774 extract_number_and_incr (destination
, source
)
778 extract_number (destination
, *source
);
782 # ifndef EXTRACT_MACROS
783 # undef EXTRACT_NUMBER_AND_INCR
784 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
785 extract_number_and_incr (&dest, &src)
786 # endif /* not EXTRACT_MACROS */
790 /* Store a multibyte character in three contiguous bytes starting
791 DESTINATION, and increment DESTINATION to the byte after where the
792 character is stored. Therefore, DESTINATION must be an lvalue. */
794 #define STORE_CHARACTER_AND_INCR(destination, character) \
796 (destination)[0] = (character) & 0377; \
797 (destination)[1] = ((character) >> 8) & 0377; \
798 (destination)[2] = (character) >> 16; \
799 (destination) += 3; \
802 /* Put into DESTINATION a character stored in three contiguous bytes
803 starting at SOURCE. */
805 #define EXTRACT_CHARACTER(destination, source) \
807 (destination) = ((source)[0] \
808 | ((source)[1] << 8) \
809 | ((source)[2] << 16)); \
813 /* Macros for charset. */
815 /* Size of bitmap of charset P in bytes. P is a start of charset,
816 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
817 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
819 /* Nonzero if charset P has range table. */
820 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
822 /* Return the address of range table of charset P. But not the start
823 of table itself, but the before where the number of ranges is
824 stored. `2 +' means to skip re_opcode_t and size of bitmap,
825 and the 2 bytes of flags at the start of the range table. */
826 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
828 /* Extract the bit flags that start a range table. */
829 #define CHARSET_RANGE_TABLE_BITS(p) \
830 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
831 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
833 /* Return the address of end of RANGE_TABLE. COUNT is number of
834 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
835 is start of range and end of range. `* 3' is size of each start
837 #define CHARSET_RANGE_TABLE_END(range_table, count) \
838 ((range_table) + (count) * 2 * 3)
840 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
841 COUNT is number of ranges in RANGE_TABLE. */
842 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
845 re_wchar_t range_start, range_end; \
847 re_char *range_table_end \
848 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
850 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
852 EXTRACT_CHARACTER (range_start, rtp); \
853 EXTRACT_CHARACTER (range_end, rtp + 3); \
855 if (range_start <= (c) && (c) <= range_end) \
864 /* Test if C is in range table of CHARSET. The flag NOT is negated if
865 C is listed in it. */
866 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
869 /* Number of ranges in range table. */ \
871 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
873 EXTRACT_NUMBER_AND_INCR (count, range_table); \
874 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
878 /* If DEBUG is defined, Regex prints many voluminous messages about what
879 it is doing (if the variable `debug' is nonzero). If linked with the
880 main program in `iregex.c', you can enter patterns and strings
881 interactively. And if linked with the main program in `main.c' and
882 the other test files, you can run the already-written tests. */
886 /* We use standard I/O for debugging. */
889 /* It is useful to test things that ``must'' be true when debugging. */
892 static int debug
= -100000;
894 # define DEBUG_STATEMENT(e) e
895 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
896 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
897 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
898 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
899 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
900 if (debug > 0) print_partial_compiled_pattern (s, e)
901 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
902 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
905 /* Print the fastmap in human-readable form. */
908 print_fastmap (fastmap
)
911 unsigned was_a_range
= 0;
914 while (i
< (1 << BYTEWIDTH
))
920 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
936 /* Print a compiled pattern string in human-readable form, starting at
937 the START pointer into it and ending just before the pointer END. */
940 print_partial_compiled_pattern (start
, end
)
950 fprintf (stderr
, "(null)\n");
954 /* Loop over pattern commands. */
957 fprintf (stderr
, "%d:\t", p
- start
);
959 switch ((re_opcode_t
) *p
++)
962 fprintf (stderr
, "/no_op");
966 fprintf (stderr
, "/succeed");
971 fprintf (stderr
, "/exactn/%d", mcnt
);
974 fprintf (stderr
, "/%c", *p
++);
980 fprintf (stderr
, "/start_memory/%d", *p
++);
984 fprintf (stderr
, "/stop_memory/%d", *p
++);
988 fprintf (stderr
, "/duplicate/%d", *p
++);
992 fprintf (stderr
, "/anychar");
998 register int c
, last
= -100;
999 register int in_range
= 0;
1000 int length
= CHARSET_BITMAP_SIZE (p
- 1);
1001 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
1003 fprintf (stderr
, "/charset [%s",
1004 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
1007 fprintf (stderr
, " !extends past end of pattern! ");
1009 for (c
= 0; c
< 256; c
++)
1011 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
1013 /* Are we starting a range? */
1014 if (last
+ 1 == c
&& ! in_range
)
1016 fprintf (stderr
, "-");
1019 /* Have we broken a range? */
1020 else if (last
+ 1 != c
&& in_range
)
1022 fprintf (stderr
, "%c", last
);
1027 fprintf (stderr
, "%c", c
);
1033 fprintf (stderr
, "%c", last
);
1035 fprintf (stderr
, "]");
1039 if (has_range_table
)
1042 fprintf (stderr
, "has-range-table");
1044 /* ??? Should print the range table; for now, just skip it. */
1045 p
+= 2; /* skip range table bits */
1046 EXTRACT_NUMBER_AND_INCR (count
, p
);
1047 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1053 fprintf (stderr
, "/begline");
1057 fprintf (stderr
, "/endline");
1060 case on_failure_jump
:
1061 extract_number_and_incr (&mcnt
, &p
);
1062 fprintf (stderr
, "/on_failure_jump to %d", p
+ mcnt
- start
);
1065 case on_failure_keep_string_jump
:
1066 extract_number_and_incr (&mcnt
, &p
);
1067 fprintf (stderr
, "/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1070 case on_failure_jump_nastyloop
:
1071 extract_number_and_incr (&mcnt
, &p
);
1072 fprintf (stderr
, "/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1075 case on_failure_jump_loop
:
1076 extract_number_and_incr (&mcnt
, &p
);
1077 fprintf (stderr
, "/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1080 case on_failure_jump_smart
:
1081 extract_number_and_incr (&mcnt
, &p
);
1082 fprintf (stderr
, "/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1086 extract_number_and_incr (&mcnt
, &p
);
1087 fprintf (stderr
, "/jump to %d", p
+ mcnt
- start
);
1091 extract_number_and_incr (&mcnt
, &p
);
1092 extract_number_and_incr (&mcnt2
, &p
);
1093 fprintf (stderr
, "/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1097 extract_number_and_incr (&mcnt
, &p
);
1098 extract_number_and_incr (&mcnt2
, &p
);
1099 fprintf (stderr
, "/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1103 extract_number_and_incr (&mcnt
, &p
);
1104 extract_number_and_incr (&mcnt2
, &p
);
1105 fprintf (stderr
, "/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1109 fprintf (stderr
, "/wordbound");
1113 fprintf (stderr
, "/notwordbound");
1117 fprintf (stderr
, "/wordbeg");
1121 fprintf (stderr
, "/wordend");
1125 fprintf (stderr
, "/symbeg");
1129 fprintf (stderr
, "/symend");
1133 fprintf (stderr
, "/syntaxspec");
1135 fprintf (stderr
, "/%d", mcnt
);
1139 fprintf (stderr
, "/notsyntaxspec");
1141 fprintf (stderr
, "/%d", mcnt
);
1146 fprintf (stderr
, "/before_dot");
1150 fprintf (stderr
, "/at_dot");
1154 fprintf (stderr
, "/after_dot");
1158 fprintf (stderr
, "/categoryspec");
1160 fprintf (stderr
, "/%d", mcnt
);
1163 case notcategoryspec
:
1164 fprintf (stderr
, "/notcategoryspec");
1166 fprintf (stderr
, "/%d", mcnt
);
1171 fprintf (stderr
, "/begbuf");
1175 fprintf (stderr
, "/endbuf");
1179 fprintf (stderr
, "?%d", *(p
-1));
1182 fprintf (stderr
, "\n");
1185 fprintf (stderr
, "%d:\tend of pattern.\n", p
- start
);
1190 print_compiled_pattern (bufp
)
1191 struct re_pattern_buffer
*bufp
;
1193 re_char
*buffer
= bufp
->buffer
;
1195 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1196 printf ("%ld bytes used/%ld bytes allocated.\n",
1197 bufp
->used
, bufp
->allocated
);
1199 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1201 printf ("fastmap: ");
1202 print_fastmap (bufp
->fastmap
);
1205 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1206 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1207 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1208 printf ("no_sub: %d\t", bufp
->no_sub
);
1209 printf ("not_bol: %d\t", bufp
->not_bol
);
1210 printf ("not_eol: %d\t", bufp
->not_eol
);
1211 printf ("syntax: %lx\n", bufp
->syntax
);
1213 /* Perhaps we should print the translate table? */
1218 print_double_string (where
, string1
, size1
, string2
, size2
)
1231 if (FIRST_STRING_P (where
))
1233 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1234 putchar (string1
[this_char
]);
1239 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1240 putchar (string2
[this_char
]);
1244 #else /* not DEBUG */
1249 # define DEBUG_STATEMENT(e)
1250 # define DEBUG_PRINT1(x)
1251 # define DEBUG_PRINT2(x1, x2)
1252 # define DEBUG_PRINT3(x1, x2, x3)
1253 # define DEBUG_PRINT4(x1, x2, x3, x4)
1254 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1255 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1257 #endif /* not DEBUG */
1259 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1261 # define IF_LINT(Code) Code
1263 # define IF_LINT(Code) /* empty */
1266 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1267 also be assigned to arbitrarily: each pattern buffer stores its own
1268 syntax, so it can be changed between regex compilations. */
1269 /* This has no initializer because initialized variables in Emacs
1270 become read-only after dumping. */
1271 reg_syntax_t re_syntax_options
;
1274 /* Specify the precise syntax of regexps for compilation. This provides
1275 for compatibility for various utilities which historically have
1276 different, incompatible syntaxes.
1278 The argument SYNTAX is a bit mask comprised of the various bits
1279 defined in regex.h. We return the old syntax. */
1282 re_set_syntax (reg_syntax_t syntax
)
1284 reg_syntax_t ret
= re_syntax_options
;
1286 re_syntax_options
= syntax
;
1289 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1291 /* Regexp to use to replace spaces, or NULL meaning don't. */
1292 static re_char
*whitespace_regexp
;
1295 re_set_whitespace_regexp (const char *regexp
)
1297 whitespace_regexp
= (re_char
*) regexp
;
1299 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1301 /* This table gives an error message for each of the error codes listed
1302 in regex.h. Obviously the order here has to be same as there.
1303 POSIX doesn't require that we do anything for REG_NOERROR,
1304 but why not be nice? */
1306 static const char *re_error_msgid
[] =
1308 gettext_noop ("Success"), /* REG_NOERROR */
1309 gettext_noop ("No match"), /* REG_NOMATCH */
1310 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1311 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1312 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1313 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1314 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1315 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1316 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1317 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1318 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1319 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1320 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1321 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1322 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1323 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1324 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1325 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1328 /* Avoiding alloca during matching, to placate r_alloc. */
1330 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1331 searching and matching functions should not call alloca. On some
1332 systems, alloca is implemented in terms of malloc, and if we're
1333 using the relocating allocator routines, then malloc could cause a
1334 relocation, which might (if the strings being searched are in the
1335 ralloc heap) shift the data out from underneath the regexp
1338 Here's another reason to avoid allocation: Emacs
1339 processes input from X in a signal handler; processing X input may
1340 call malloc; if input arrives while a matching routine is calling
1341 malloc, then we're scrod. But Emacs can't just block input while
1342 calling matching routines; then we don't notice interrupts when
1343 they come in. So, Emacs blocks input around all regexp calls
1344 except the matching calls, which it leaves unprotected, in the
1345 faith that they will not malloc. */
1347 /* Normally, this is fine. */
1348 #define MATCH_MAY_ALLOCATE
1350 /* The match routines may not allocate if (1) they would do it with malloc
1351 and (2) it's not safe for them to use malloc.
1352 Note that if REL_ALLOC is defined, matching would not use malloc for the
1353 failure stack, but we would still use it for the register vectors;
1354 so REL_ALLOC should not affect this. */
1355 #if defined REGEX_MALLOC && defined emacs
1356 # undef MATCH_MAY_ALLOCATE
1360 /* Failure stack declarations and macros; both re_compile_fastmap and
1361 re_match_2 use a failure stack. These have to be macros because of
1362 REGEX_ALLOCATE_STACK. */
1365 /* Approximate number of failure points for which to initially allocate space
1366 when matching. If this number is exceeded, we allocate more
1367 space, so it is not a hard limit. */
1368 #ifndef INIT_FAILURE_ALLOC
1369 # define INIT_FAILURE_ALLOC 20
1372 /* Roughly the maximum number of failure points on the stack. Would be
1373 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1374 This is a variable only so users of regex can assign to it; we never
1375 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1376 before using it, so it should probably be a byte-count instead. */
1377 # if defined MATCH_MAY_ALLOCATE
1378 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1379 whose default stack limit is 2mb. In order for a larger
1380 value to work reliably, you have to try to make it accord
1381 with the process stack limit. */
1382 size_t re_max_failures
= 40000;
1384 size_t re_max_failures
= 4000;
1387 union fail_stack_elt
1390 /* This should be the biggest `int' that's no bigger than a pointer. */
1394 typedef union fail_stack_elt fail_stack_elt_t
;
1398 fail_stack_elt_t
*stack
;
1400 size_t avail
; /* Offset of next open position. */
1401 size_t frame
; /* Offset of the cur constructed frame. */
1404 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1407 /* Define macros to initialize and free the failure stack.
1408 Do `return -2' if the alloc fails. */
1410 #ifdef MATCH_MAY_ALLOCATE
1411 # define INIT_FAIL_STACK() \
1413 fail_stack.stack = (fail_stack_elt_t *) \
1414 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1415 * sizeof (fail_stack_elt_t)); \
1417 if (fail_stack.stack == NULL) \
1420 fail_stack.size = INIT_FAILURE_ALLOC; \
1421 fail_stack.avail = 0; \
1422 fail_stack.frame = 0; \
1425 # define INIT_FAIL_STACK() \
1427 fail_stack.avail = 0; \
1428 fail_stack.frame = 0; \
1431 # define RETALLOC_IF(addr, n, t) \
1432 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1436 /* Double the size of FAIL_STACK, up to a limit
1437 which allows approximately `re_max_failures' items.
1439 Return 1 if succeeds, and 0 if either ran out of memory
1440 allocating space for it or it was already too large.
1442 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1444 /* Factor to increase the failure stack size by
1445 when we increase it.
1446 This used to be 2, but 2 was too wasteful
1447 because the old discarded stacks added up to as much space
1448 were as ultimate, maximum-size stack. */
1449 #define FAIL_STACK_GROWTH_FACTOR 4
1451 #define GROW_FAIL_STACK(fail_stack) \
1452 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1453 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1455 : ((fail_stack).stack \
1456 = (fail_stack_elt_t *) \
1457 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1458 (fail_stack).size * sizeof (fail_stack_elt_t), \
1459 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1460 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1461 * FAIL_STACK_GROWTH_FACTOR))), \
1463 (fail_stack).stack == NULL \
1465 : ((fail_stack).size \
1466 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1467 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1468 * FAIL_STACK_GROWTH_FACTOR)) \
1469 / sizeof (fail_stack_elt_t)), \
1473 /* Push a pointer value onto the failure stack.
1474 Assumes the variable `fail_stack'. Probably should only
1475 be called from within `PUSH_FAILURE_POINT'. */
1476 #define PUSH_FAILURE_POINTER(item) \
1477 fail_stack.stack[fail_stack.avail++].pointer = (item)
1479 /* This pushes an integer-valued item onto the failure stack.
1480 Assumes the variable `fail_stack'. Probably should only
1481 be called from within `PUSH_FAILURE_POINT'. */
1482 #define PUSH_FAILURE_INT(item) \
1483 fail_stack.stack[fail_stack.avail++].integer = (item)
1485 /* These POP... operations complement the PUSH... operations.
1486 All assume that `fail_stack' is nonempty. */
1487 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1488 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1490 /* Individual items aside from the registers. */
1491 #define NUM_NONREG_ITEMS 3
1493 /* Used to examine the stack (to detect infinite loops). */
1494 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1495 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1496 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1497 #define TOP_FAILURE_HANDLE() fail_stack.frame
1500 #define ENSURE_FAIL_STACK(space) \
1501 while (REMAINING_AVAIL_SLOTS <= space) { \
1502 if (!GROW_FAIL_STACK (fail_stack)) \
1504 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1505 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1508 /* Push register NUM onto the stack. */
1509 #define PUSH_FAILURE_REG(num) \
1511 char *destination; \
1512 ENSURE_FAIL_STACK(3); \
1513 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1514 num, regstart[num], regend[num]); \
1515 PUSH_FAILURE_POINTER (regstart[num]); \
1516 PUSH_FAILURE_POINTER (regend[num]); \
1517 PUSH_FAILURE_INT (num); \
1520 /* Change the counter's value to VAL, but make sure that it will
1521 be reset when backtracking. */
1522 #define PUSH_NUMBER(ptr,val) \
1524 char *destination; \
1526 ENSURE_FAIL_STACK(3); \
1527 EXTRACT_NUMBER (c, ptr); \
1528 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1529 PUSH_FAILURE_INT (c); \
1530 PUSH_FAILURE_POINTER (ptr); \
1531 PUSH_FAILURE_INT (-1); \
1532 STORE_NUMBER (ptr, val); \
1535 /* Pop a saved register off the stack. */
1536 #define POP_FAILURE_REG_OR_COUNT() \
1538 long pfreg = POP_FAILURE_INT (); \
1541 /* It's a counter. */ \
1542 /* Here, we discard `const', making re_match non-reentrant. */ \
1543 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1544 pfreg = POP_FAILURE_INT (); \
1545 STORE_NUMBER (ptr, pfreg); \
1546 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, pfreg); \
1550 regend[pfreg] = POP_FAILURE_POINTER (); \
1551 regstart[pfreg] = POP_FAILURE_POINTER (); \
1552 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1553 pfreg, regstart[pfreg], regend[pfreg]); \
1557 /* Check that we are not stuck in an infinite loop. */
1558 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1560 ssize_t failure = TOP_FAILURE_HANDLE (); \
1561 /* Check for infinite matching loops */ \
1562 while (failure > 0 \
1563 && (FAILURE_STR (failure) == string_place \
1564 || FAILURE_STR (failure) == NULL)) \
1566 assert (FAILURE_PAT (failure) >= bufp->buffer \
1567 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1568 if (FAILURE_PAT (failure) == pat_cur) \
1573 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1574 failure = NEXT_FAILURE_HANDLE(failure); \
1576 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1579 /* Push the information about the state we will need
1580 if we ever fail back to it.
1582 Requires variables fail_stack, regstart, regend and
1583 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1586 Does `return FAILURE_CODE' if runs out of memory. */
1588 #define PUSH_FAILURE_POINT(pattern, string_place) \
1590 char *destination; \
1591 /* Must be int, so when we don't save any registers, the arithmetic \
1592 of 0 + -1 isn't done as unsigned. */ \
1594 DEBUG_STATEMENT (nfailure_points_pushed++); \
1595 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1596 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1597 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1599 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1601 DEBUG_PRINT1 ("\n"); \
1603 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1604 PUSH_FAILURE_INT (fail_stack.frame); \
1606 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1607 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1608 DEBUG_PRINT1 ("'\n"); \
1609 PUSH_FAILURE_POINTER (string_place); \
1611 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1612 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1613 PUSH_FAILURE_POINTER (pattern); \
1615 /* Close the frame by moving the frame pointer past it. */ \
1616 fail_stack.frame = fail_stack.avail; \
1619 /* Estimate the size of data pushed by a typical failure stack entry.
1620 An estimate is all we need, because all we use this for
1621 is to choose a limit for how big to make the failure stack. */
1622 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1623 #define TYPICAL_FAILURE_SIZE 20
1625 /* How many items can still be added to the stack without overflowing it. */
1626 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1629 /* Pops what PUSH_FAIL_STACK pushes.
1631 We restore into the parameters, all of which should be lvalues:
1632 STR -- the saved data position.
1633 PAT -- the saved pattern position.
1634 REGSTART, REGEND -- arrays of string positions.
1636 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1637 `pend', `string1', `size1', `string2', and `size2'. */
1639 #define POP_FAILURE_POINT(str, pat) \
1641 assert (!FAIL_STACK_EMPTY ()); \
1643 /* Remove failure points and point to how many regs pushed. */ \
1644 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1645 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1646 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1648 /* Pop the saved registers. */ \
1649 while (fail_stack.frame < fail_stack.avail) \
1650 POP_FAILURE_REG_OR_COUNT (); \
1652 pat = POP_FAILURE_POINTER (); \
1653 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1654 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1656 /* If the saved string location is NULL, it came from an \
1657 on_failure_keep_string_jump opcode, and we want to throw away the \
1658 saved NULL, thus retaining our current position in the string. */ \
1659 str = POP_FAILURE_POINTER (); \
1660 DEBUG_PRINT2 (" Popping string %p: `", str); \
1661 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1662 DEBUG_PRINT1 ("'\n"); \
1664 fail_stack.frame = POP_FAILURE_INT (); \
1665 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1667 assert (fail_stack.avail >= 0); \
1668 assert (fail_stack.frame <= fail_stack.avail); \
1670 DEBUG_STATEMENT (nfailure_points_popped++); \
1671 } while (0) /* POP_FAILURE_POINT */
1675 /* Registers are set to a sentinel when they haven't yet matched. */
1676 #define REG_UNSET(e) ((e) == NULL)
1678 /* Subroutine declarations and macros for regex_compile. */
1680 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1681 reg_syntax_t syntax
,
1682 struct re_pattern_buffer
*bufp
));
1683 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1684 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1685 int arg1
, int arg2
));
1686 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1687 int arg
, unsigned char *end
));
1688 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1689 int arg1
, int arg2
, unsigned char *end
));
1690 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1692 reg_syntax_t syntax
));
1693 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1695 reg_syntax_t syntax
));
1696 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1697 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1698 char *fastmap
, const int multibyte
));
1700 /* Fetch the next character in the uncompiled pattern, with no
1702 #define PATFETCH(c) \
1705 if (p == pend) return REG_EEND; \
1706 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1711 /* If `translate' is non-null, return translate[D], else just D. We
1712 cast the subscript to translate because some data is declared as
1713 `char *', to avoid warnings when a string constant is passed. But
1714 when we use a character as a subscript we must make it unsigned. */
1716 # define TRANSLATE(d) \
1717 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1721 /* Macros for outputting the compiled pattern into `buffer'. */
1723 /* If the buffer isn't allocated when it comes in, use this. */
1724 #define INIT_BUF_SIZE 32
1726 /* Make sure we have at least N more bytes of space in buffer. */
1727 #define GET_BUFFER_SPACE(n) \
1728 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1731 /* Make sure we have one more byte of buffer space and then add C to it. */
1732 #define BUF_PUSH(c) \
1734 GET_BUFFER_SPACE (1); \
1735 *b++ = (unsigned char) (c); \
1739 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1740 #define BUF_PUSH_2(c1, c2) \
1742 GET_BUFFER_SPACE (2); \
1743 *b++ = (unsigned char) (c1); \
1744 *b++ = (unsigned char) (c2); \
1748 /* Store a jump with opcode OP at LOC to location TO. We store a
1749 relative address offset by the three bytes the jump itself occupies. */
1750 #define STORE_JUMP(op, loc, to) \
1751 store_op1 (op, loc, (to) - (loc) - 3)
1753 /* Likewise, for a two-argument jump. */
1754 #define STORE_JUMP2(op, loc, to, arg) \
1755 store_op2 (op, loc, (to) - (loc) - 3, arg)
1757 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1758 #define INSERT_JUMP(op, loc, to) \
1759 insert_op1 (op, loc, (to) - (loc) - 3, b)
1761 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1762 #define INSERT_JUMP2(op, loc, to, arg) \
1763 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1766 /* This is not an arbitrary limit: the arguments which represent offsets
1767 into the pattern are two bytes long. So if 2^15 bytes turns out to
1768 be too small, many things would have to change. */
1769 # define MAX_BUF_SIZE (1L << 15)
1771 #if 0 /* This is when we thought it could be 2^16 bytes. */
1772 /* Any other compiler which, like MSC, has allocation limit below 2^16
1773 bytes will have to use approach similar to what was done below for
1774 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1775 reallocating to 0 bytes. Such thing is not going to work too well.
1776 You have been warned!! */
1777 #if defined _MSC_VER && !defined WIN32
1778 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1779 # define MAX_BUF_SIZE 65500L
1781 # define MAX_BUF_SIZE (1L << 16)
1785 /* Extend the buffer by twice its current size via realloc and
1786 reset the pointers that pointed into the old block to point to the
1787 correct places in the new one. If extending the buffer results in it
1788 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1789 #if __BOUNDED_POINTERS__
1790 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1791 # define MOVE_BUFFER_POINTER(P) \
1792 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1793 SET_HIGH_BOUND (P), \
1794 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1795 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1798 SET_HIGH_BOUND (b); \
1799 SET_HIGH_BOUND (begalt); \
1800 if (fixup_alt_jump) \
1801 SET_HIGH_BOUND (fixup_alt_jump); \
1803 SET_HIGH_BOUND (laststart); \
1804 if (pending_exact) \
1805 SET_HIGH_BOUND (pending_exact); \
1808 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1809 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1811 #define EXTEND_BUFFER() \
1813 unsigned char *old_buffer = bufp->buffer; \
1814 if (bufp->allocated == MAX_BUF_SIZE) \
1816 bufp->allocated <<= 1; \
1817 if (bufp->allocated > MAX_BUF_SIZE) \
1818 bufp->allocated = MAX_BUF_SIZE; \
1819 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1820 if (bufp->buffer == NULL) \
1821 return REG_ESPACE; \
1822 /* If the buffer moved, move all the pointers into it. */ \
1823 if (old_buffer != bufp->buffer) \
1825 unsigned char *new_buffer = bufp->buffer; \
1826 MOVE_BUFFER_POINTER (b); \
1827 MOVE_BUFFER_POINTER (begalt); \
1828 if (fixup_alt_jump) \
1829 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1831 MOVE_BUFFER_POINTER (laststart); \
1832 if (pending_exact) \
1833 MOVE_BUFFER_POINTER (pending_exact); \
1835 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1839 /* Since we have one byte reserved for the register number argument to
1840 {start,stop}_memory, the maximum number of groups we can report
1841 things about is what fits in that byte. */
1842 #define MAX_REGNUM 255
1844 /* But patterns can have more than `MAX_REGNUM' registers. We just
1845 ignore the excess. */
1846 typedef int regnum_t
;
1849 /* Macros for the compile stack. */
1851 /* Since offsets can go either forwards or backwards, this type needs to
1852 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1853 /* int may be not enough when sizeof(int) == 2. */
1854 typedef long pattern_offset_t
;
1858 pattern_offset_t begalt_offset
;
1859 pattern_offset_t fixup_alt_jump
;
1860 pattern_offset_t laststart_offset
;
1862 } compile_stack_elt_t
;
1867 compile_stack_elt_t
*stack
;
1869 size_t avail
; /* Offset of next open position. */
1870 } compile_stack_type
;
1873 #define INIT_COMPILE_STACK_SIZE 32
1875 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1876 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1878 /* The next available element. */
1879 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1881 /* Explicit quit checking is only used on NTemacs and whenever we
1882 use polling to process input events. */
1883 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1884 extern int immediate_quit
;
1885 # define IMMEDIATE_QUIT_CHECK \
1887 if (immediate_quit) QUIT; \
1890 # define IMMEDIATE_QUIT_CHECK ((void)0)
1893 /* Structure to manage work area for range table. */
1894 struct range_table_work_area
1896 int *table
; /* actual work area. */
1897 int allocated
; /* allocated size for work area in bytes. */
1898 int used
; /* actually used size in words. */
1899 int bits
; /* flag to record character classes */
1902 /* Make sure that WORK_AREA can hold more N multibyte characters.
1903 This is used only in set_image_of_range and set_image_of_range_1.
1904 It expects WORK_AREA to be a pointer.
1905 If it can't get the space, it returns from the surrounding function. */
1907 #define EXTEND_RANGE_TABLE(work_area, n) \
1909 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1911 extend_range_table_work_area (&work_area); \
1912 if ((work_area).table == 0) \
1913 return (REG_ESPACE); \
1917 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1918 (work_area).bits |= (bit)
1920 /* Bits used to implement the multibyte-part of the various character classes
1921 such as [:alnum:] in a charset's range table. */
1922 #define BIT_WORD 0x1
1923 #define BIT_LOWER 0x2
1924 #define BIT_PUNCT 0x4
1925 #define BIT_SPACE 0x8
1926 #define BIT_UPPER 0x10
1927 #define BIT_MULTIBYTE 0x20
1929 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1930 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1932 EXTEND_RANGE_TABLE ((work_area), 2); \
1933 (work_area).table[(work_area).used++] = (range_start); \
1934 (work_area).table[(work_area).used++] = (range_end); \
1937 /* Free allocated memory for WORK_AREA. */
1938 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1940 if ((work_area).table) \
1941 free ((work_area).table); \
1944 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1945 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1946 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1947 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1950 /* Set the bit for character C in a list. */
1951 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1956 /* Store characters in the range FROM to TO in the bitmap at B (for
1957 ASCII and unibyte characters) and WORK_AREA (for multibyte
1958 characters) while translating them and paying attention to the
1959 continuity of translated characters.
1961 Implementation note: It is better to implement these fairly big
1962 macros by a function, but it's not that easy because macros called
1963 in this macro assume various local variables already declared. */
1965 /* Both FROM and TO are ASCII characters. */
1967 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1971 for (C0 = (FROM); C0 <= (TO); C0++) \
1973 C1 = TRANSLATE (C0); \
1974 if (! ASCII_CHAR_P (C1)) \
1976 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1977 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1980 SET_LIST_BIT (C1); \
1985 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1987 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1989 int C0, C1, C2, I; \
1990 int USED = RANGE_TABLE_WORK_USED (work_area); \
1992 for (C0 = (FROM); C0 <= (TO); C0++) \
1994 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1995 if (CHAR_BYTE8_P (C1)) \
1996 SET_LIST_BIT (C0); \
1999 C2 = TRANSLATE (C1); \
2001 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
2003 SET_LIST_BIT (C1); \
2004 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2006 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2007 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2009 if (C2 >= from - 1 && C2 <= to + 1) \
2011 if (C2 == from - 1) \
2012 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2013 else if (C2 == to + 1) \
2014 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2019 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
2025 /* Both FROM and TO are multibyte characters. */
2027 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2029 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2031 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2032 for (C0 = (FROM); C0 <= (TO); C0++) \
2034 C1 = TRANSLATE (C0); \
2035 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2036 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2037 SET_LIST_BIT (C2); \
2038 if (C1 >= (FROM) && C1 <= (TO)) \
2040 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2042 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2043 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2045 if (C1 >= from - 1 && C1 <= to + 1) \
2047 if (C1 == from - 1) \
2048 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2049 else if (C1 == to + 1) \
2050 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2055 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2061 /* Get the next unsigned number in the uncompiled pattern. */
2062 #define GET_UNSIGNED_NUMBER(num) \
2065 FREE_STACK_RETURN (REG_EBRACE); \
2069 while ('0' <= c && c <= '9') \
2075 num = num * 10 + c - '0'; \
2076 if (num / 10 != prev) \
2077 FREE_STACK_RETURN (REG_BADBR); \
2079 FREE_STACK_RETURN (REG_EBRACE); \
2085 #if ! WIDE_CHAR_SUPPORT
2087 /* Map a string to the char class it names (if any). */
2089 re_wctype (const re_char
*str
)
2091 const char *string
= (const char *) str
;
2092 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2093 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2094 else if (STREQ (string
, "word")) return RECC_WORD
;
2095 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2096 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2097 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2098 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2099 else if (STREQ (string
, "print")) return RECC_PRINT
;
2100 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2101 else if (STREQ (string
, "space")) return RECC_SPACE
;
2102 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2103 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2104 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2105 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2106 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2107 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2108 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2112 /* True if CH is in the char class CC. */
2114 re_iswctype (int ch
, re_wctype_t cc
)
2118 case RECC_ALNUM
: return ISALNUM (ch
);
2119 case RECC_ALPHA
: return ISALPHA (ch
);
2120 case RECC_BLANK
: return ISBLANK (ch
);
2121 case RECC_CNTRL
: return ISCNTRL (ch
);
2122 case RECC_DIGIT
: return ISDIGIT (ch
);
2123 case RECC_GRAPH
: return ISGRAPH (ch
);
2124 case RECC_LOWER
: return ISLOWER (ch
);
2125 case RECC_PRINT
: return ISPRINT (ch
);
2126 case RECC_PUNCT
: return ISPUNCT (ch
);
2127 case RECC_SPACE
: return ISSPACE (ch
);
2128 case RECC_UPPER
: return ISUPPER (ch
);
2129 case RECC_XDIGIT
: return ISXDIGIT (ch
);
2130 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2131 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2132 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2133 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2134 case RECC_WORD
: return ISWORD (ch
);
2135 case RECC_ERROR
: return false;
2141 /* Return a bit-pattern to use in the range-table bits to match multibyte
2142 chars of class CC. */
2144 re_wctype_to_bit (re_wctype_t cc
)
2148 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2149 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2150 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2151 case RECC_LOWER
: return BIT_LOWER
;
2152 case RECC_UPPER
: return BIT_UPPER
;
2153 case RECC_PUNCT
: return BIT_PUNCT
;
2154 case RECC_SPACE
: return BIT_SPACE
;
2155 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2156 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2163 /* Filling in the work area of a range. */
2165 /* Actually extend the space in WORK_AREA. */
2168 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2170 work_area
->allocated
+= 16 * sizeof (int);
2171 if (work_area
->table
)
2173 = (int *) realloc (work_area
->table
, work_area
->allocated
);
2176 = (int *) malloc (work_area
->allocated
);
2182 /* Carefully find the ranges of codes that are equivalent
2183 under case conversion to the range start..end when passed through
2184 TRANSLATE. Handle the case where non-letters can come in between
2185 two upper-case letters (which happens in Latin-1).
2186 Also handle the case of groups of more than 2 case-equivalent chars.
2188 The basic method is to look at consecutive characters and see
2189 if they can form a run that can be handled as one.
2191 Returns -1 if successful, REG_ESPACE if ran out of space. */
2194 set_image_of_range_1 (work_area
, start
, end
, translate
)
2195 RE_TRANSLATE_TYPE translate
;
2196 struct range_table_work_area
*work_area
;
2197 re_wchar_t start
, end
;
2199 /* `one_case' indicates a character, or a run of characters,
2200 each of which is an isolate (no case-equivalents).
2201 This includes all ASCII non-letters.
2203 `two_case' indicates a character, or a run of characters,
2204 each of which has two case-equivalent forms.
2205 This includes all ASCII letters.
2207 `strange' indicates a character that has more than one
2210 enum case_type
{one_case
, two_case
, strange
};
2212 /* Describe the run that is in progress,
2213 which the next character can try to extend.
2214 If run_type is strange, that means there really is no run.
2215 If run_type is one_case, then run_start...run_end is the run.
2216 If run_type is two_case, then the run is run_start...run_end,
2217 and the case-equivalents end at run_eqv_end. */
2219 enum case_type run_type
= strange
;
2220 int run_start
, run_end
, run_eqv_end
;
2222 Lisp_Object eqv_table
;
2224 if (!RE_TRANSLATE_P (translate
))
2226 EXTEND_RANGE_TABLE (work_area
, 2);
2227 work_area
->table
[work_area
->used
++] = (start
);
2228 work_area
->table
[work_area
->used
++] = (end
);
2232 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2234 for (; start
<= end
; start
++)
2236 enum case_type this_type
;
2237 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2238 int minchar
, maxchar
;
2240 /* Classify this character */
2242 this_type
= one_case
;
2243 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2244 this_type
= two_case
;
2246 this_type
= strange
;
2249 minchar
= start
, maxchar
= eqv
;
2251 minchar
= eqv
, maxchar
= start
;
2253 /* Can this character extend the run in progress? */
2254 if (this_type
== strange
|| this_type
!= run_type
2255 || !(minchar
== run_end
+ 1
2256 && (run_type
== two_case
2257 ? maxchar
== run_eqv_end
+ 1 : 1)))
2260 Record each of its equivalent ranges. */
2261 if (run_type
== one_case
)
2263 EXTEND_RANGE_TABLE (work_area
, 2);
2264 work_area
->table
[work_area
->used
++] = run_start
;
2265 work_area
->table
[work_area
->used
++] = run_end
;
2267 else if (run_type
== two_case
)
2269 EXTEND_RANGE_TABLE (work_area
, 4);
2270 work_area
->table
[work_area
->used
++] = run_start
;
2271 work_area
->table
[work_area
->used
++] = run_end
;
2272 work_area
->table
[work_area
->used
++]
2273 = RE_TRANSLATE (eqv_table
, run_start
);
2274 work_area
->table
[work_area
->used
++]
2275 = RE_TRANSLATE (eqv_table
, run_end
);
2280 if (this_type
== strange
)
2282 /* For a strange character, add each of its equivalents, one
2283 by one. Don't start a range. */
2286 EXTEND_RANGE_TABLE (work_area
, 2);
2287 work_area
->table
[work_area
->used
++] = eqv
;
2288 work_area
->table
[work_area
->used
++] = eqv
;
2289 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2291 while (eqv
!= start
);
2294 /* Add this char to the run, or start a new run. */
2295 else if (run_type
== strange
)
2297 /* Initialize a new range. */
2298 run_type
= this_type
;
2301 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2305 /* Extend a running range. */
2307 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2311 /* If a run is still in progress at the end, finish it now
2312 by recording its equivalent ranges. */
2313 if (run_type
== one_case
)
2315 EXTEND_RANGE_TABLE (work_area
, 2);
2316 work_area
->table
[work_area
->used
++] = run_start
;
2317 work_area
->table
[work_area
->used
++] = run_end
;
2319 else if (run_type
== two_case
)
2321 EXTEND_RANGE_TABLE (work_area
, 4);
2322 work_area
->table
[work_area
->used
++] = run_start
;
2323 work_area
->table
[work_area
->used
++] = run_end
;
2324 work_area
->table
[work_area
->used
++]
2325 = RE_TRANSLATE (eqv_table
, run_start
);
2326 work_area
->table
[work_area
->used
++]
2327 = RE_TRANSLATE (eqv_table
, run_end
);
2335 /* Record the image of the range start..end when passed through
2336 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2337 and is not even necessarily contiguous.
2338 Normally we approximate it with the smallest contiguous range that contains
2339 all the chars we need. However, for Latin-1 we go to extra effort
2342 This function is not called for ASCII ranges.
2344 Returns -1 if successful, REG_ESPACE if ran out of space. */
2347 set_image_of_range (work_area
, start
, end
, translate
)
2348 RE_TRANSLATE_TYPE translate
;
2349 struct range_table_work_area
*work_area
;
2350 re_wchar_t start
, end
;
2352 re_wchar_t cmin
, cmax
;
2355 /* For Latin-1 ranges, use set_image_of_range_1
2356 to get proper handling of ranges that include letters and nonletters.
2357 For a range that includes the whole of Latin-1, this is not necessary.
2358 For other character sets, we don't bother to get this right. */
2359 if (RE_TRANSLATE_P (translate
) && start
< 04400
2360 && !(start
< 04200 && end
>= 04377))
2367 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2377 EXTEND_RANGE_TABLE (work_area
, 2);
2378 work_area
->table
[work_area
->used
++] = (start
);
2379 work_area
->table
[work_area
->used
++] = (end
);
2381 cmin
= -1, cmax
= -1;
2383 if (RE_TRANSLATE_P (translate
))
2387 for (ch
= start
; ch
<= end
; ch
++)
2389 re_wchar_t c
= TRANSLATE (ch
);
2390 if (! (start
<= c
&& c
<= end
))
2396 cmin
= MIN (cmin
, c
);
2397 cmax
= MAX (cmax
, c
);
2404 EXTEND_RANGE_TABLE (work_area
, 2);
2405 work_area
->table
[work_area
->used
++] = (cmin
);
2406 work_area
->table
[work_area
->used
++] = (cmax
);
2414 #ifndef MATCH_MAY_ALLOCATE
2416 /* If we cannot allocate large objects within re_match_2_internal,
2417 we make the fail stack and register vectors global.
2418 The fail stack, we grow to the maximum size when a regexp
2420 The register vectors, we adjust in size each time we
2421 compile a regexp, according to the number of registers it needs. */
2423 static fail_stack_type fail_stack
;
2425 /* Size with which the following vectors are currently allocated.
2426 That is so we can make them bigger as needed,
2427 but never make them smaller. */
2428 static int regs_allocated_size
;
2430 static re_char
** regstart
, ** regend
;
2431 static re_char
**best_regstart
, **best_regend
;
2433 /* Make the register vectors big enough for NUM_REGS registers,
2434 but don't make them smaller. */
2437 regex_grow_registers (num_regs
)
2440 if (num_regs
> regs_allocated_size
)
2442 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2443 RETALLOC_IF (regend
, num_regs
, re_char
*);
2444 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2445 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2447 regs_allocated_size
= num_regs
;
2451 #endif /* not MATCH_MAY_ALLOCATE */
2453 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2457 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2458 Returns one of error codes defined in `regex.h', or zero for success.
2460 Assumes the `allocated' (and perhaps `buffer') and `translate'
2461 fields are set in BUFP on entry.
2463 If it succeeds, results are put in BUFP (if it returns an error, the
2464 contents of BUFP are undefined):
2465 `buffer' is the compiled pattern;
2466 `syntax' is set to SYNTAX;
2467 `used' is set to the length of the compiled pattern;
2468 `fastmap_accurate' is zero;
2469 `re_nsub' is the number of subexpressions in PATTERN;
2470 `not_bol' and `not_eol' are zero;
2472 The `fastmap' field is neither examined nor set. */
2474 /* Insert the `jump' from the end of last alternative to "here".
2475 The space for the jump has already been allocated. */
2476 #define FIXUP_ALT_JUMP() \
2478 if (fixup_alt_jump) \
2479 STORE_JUMP (jump, fixup_alt_jump, b); \
2483 /* Return, freeing storage we allocated. */
2484 #define FREE_STACK_RETURN(value) \
2486 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2487 free (compile_stack.stack); \
2491 static reg_errcode_t
2492 regex_compile (const re_char
*pattern
, size_t size
, reg_syntax_t syntax
, struct re_pattern_buffer
*bufp
)
2494 /* We fetch characters from PATTERN here. */
2495 register re_wchar_t c
, c1
;
2497 /* Points to the end of the buffer, where we should append. */
2498 register unsigned char *b
;
2500 /* Keeps track of unclosed groups. */
2501 compile_stack_type compile_stack
;
2503 /* Points to the current (ending) position in the pattern. */
2505 /* `const' makes AIX compiler fail. */
2506 unsigned char *p
= pattern
;
2508 re_char
*p
= pattern
;
2510 re_char
*pend
= pattern
+ size
;
2512 /* How to translate the characters in the pattern. */
2513 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2515 /* Address of the count-byte of the most recently inserted `exactn'
2516 command. This makes it possible to tell if a new exact-match
2517 character can be added to that command or if the character requires
2518 a new `exactn' command. */
2519 unsigned char *pending_exact
= 0;
2521 /* Address of start of the most recently finished expression.
2522 This tells, e.g., postfix * where to find the start of its
2523 operand. Reset at the beginning of groups and alternatives. */
2524 unsigned char *laststart
= 0;
2526 /* Address of beginning of regexp, or inside of last group. */
2527 unsigned char *begalt
;
2529 /* Place in the uncompiled pattern (i.e., the {) to
2530 which to go back if the interval is invalid. */
2531 re_char
*beg_interval
;
2533 /* Address of the place where a forward jump should go to the end of
2534 the containing expression. Each alternative of an `or' -- except the
2535 last -- ends with a forward jump of this sort. */
2536 unsigned char *fixup_alt_jump
= 0;
2538 /* Work area for range table of charset. */
2539 struct range_table_work_area range_table_work
;
2541 /* If the object matched can contain multibyte characters. */
2542 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2544 /* Nonzero if we have pushed down into a subpattern. */
2545 int in_subpattern
= 0;
2547 /* These hold the values of p, pattern, and pend from the main
2548 pattern when we have pushed into a subpattern. */
2549 re_char
*main_p
IF_LINT (= NULL
);
2550 re_char
*main_pattern
IF_LINT (= NULL
);
2551 re_char
*main_pend
IF_LINT (= NULL
);
2555 DEBUG_PRINT1 ("\nCompiling pattern: ");
2558 unsigned debug_count
;
2560 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2561 putchar (pattern
[debug_count
]);
2566 /* Initialize the compile stack. */
2567 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2568 if (compile_stack
.stack
== NULL
)
2571 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2572 compile_stack
.avail
= 0;
2574 range_table_work
.table
= 0;
2575 range_table_work
.allocated
= 0;
2577 /* Initialize the pattern buffer. */
2578 bufp
->syntax
= syntax
;
2579 bufp
->fastmap_accurate
= 0;
2580 bufp
->not_bol
= bufp
->not_eol
= 0;
2581 bufp
->used_syntax
= 0;
2583 /* Set `used' to zero, so that if we return an error, the pattern
2584 printer (for debugging) will think there's no pattern. We reset it
2588 /* Always count groups, whether or not bufp->no_sub is set. */
2591 #if !defined emacs && !defined SYNTAX_TABLE
2592 /* Initialize the syntax table. */
2593 init_syntax_once ();
2596 if (bufp
->allocated
== 0)
2599 { /* If zero allocated, but buffer is non-null, try to realloc
2600 enough space. This loses if buffer's address is bogus, but
2601 that is the user's responsibility. */
2602 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2605 { /* Caller did not allocate a buffer. Do it for them. */
2606 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2608 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2610 bufp
->allocated
= INIT_BUF_SIZE
;
2613 begalt
= b
= bufp
->buffer
;
2615 /* Loop through the uncompiled pattern until we're at the end. */
2620 /* If this is the end of an included regexp,
2621 pop back to the main regexp and try again. */
2625 pattern
= main_pattern
;
2630 /* If this is the end of the main regexp, we are done. */
2642 /* If there's no special whitespace regexp, treat
2643 spaces normally. And don't try to do this recursively. */
2644 if (!whitespace_regexp
|| in_subpattern
)
2647 /* Peek past following spaces. */
2654 /* If the spaces are followed by a repetition op,
2655 treat them normally. */
2657 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2658 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2661 /* Replace the spaces with the whitespace regexp. */
2665 main_pattern
= pattern
;
2666 p
= pattern
= whitespace_regexp
;
2667 pend
= p
+ strlen ((const char *) p
);
2673 if ( /* If at start of pattern, it's an operator. */
2675 /* If context independent, it's an operator. */
2676 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2677 /* Otherwise, depends on what's come before. */
2678 || at_begline_loc_p (pattern
, p
, syntax
))
2679 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2688 if ( /* If at end of pattern, it's an operator. */
2690 /* If context independent, it's an operator. */
2691 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2692 /* Otherwise, depends on what's next. */
2693 || at_endline_loc_p (p
, pend
, syntax
))
2694 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2703 if ((syntax
& RE_BK_PLUS_QM
)
2704 || (syntax
& RE_LIMITED_OPS
))
2708 /* If there is no previous pattern... */
2711 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2712 FREE_STACK_RETURN (REG_BADRPT
);
2713 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2718 /* 1 means zero (many) matches is allowed. */
2719 boolean zero_times_ok
= 0, many_times_ok
= 0;
2722 /* If there is a sequence of repetition chars, collapse it
2723 down to just one (the right one). We can't combine
2724 interval operators with these because of, e.g., `a{2}*',
2725 which should only match an even number of `a's. */
2729 if ((syntax
& RE_FRUGAL
)
2730 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2734 zero_times_ok
|= c
!= '+';
2735 many_times_ok
|= c
!= '?';
2741 || (!(syntax
& RE_BK_PLUS_QM
)
2742 && (*p
== '+' || *p
== '?')))
2744 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2747 FREE_STACK_RETURN (REG_EESCAPE
);
2748 if (p
[1] == '+' || p
[1] == '?')
2749 PATFETCH (c
); /* Gobble up the backslash. */
2755 /* If we get here, we found another repeat character. */
2759 /* Star, etc. applied to an empty pattern is equivalent
2760 to an empty pattern. */
2761 if (!laststart
|| laststart
== b
)
2764 /* Now we know whether or not zero matches is allowed
2765 and also whether or not two or more matches is allowed. */
2770 boolean simple
= skip_one_char (laststart
) == b
;
2771 size_t startoffset
= 0;
2773 /* Check if the loop can match the empty string. */
2774 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2775 ? on_failure_jump
: on_failure_jump_loop
;
2776 assert (skip_one_char (laststart
) <= b
);
2778 if (!zero_times_ok
&& simple
)
2779 { /* Since simple * loops can be made faster by using
2780 on_failure_keep_string_jump, we turn simple P+
2781 into PP* if P is simple. */
2782 unsigned char *p1
, *p2
;
2783 startoffset
= b
- laststart
;
2784 GET_BUFFER_SPACE (startoffset
);
2785 p1
= b
; p2
= laststart
;
2791 GET_BUFFER_SPACE (6);
2794 STORE_JUMP (ofj
, b
, b
+ 6);
2796 /* Simple * loops can use on_failure_keep_string_jump
2797 depending on what follows. But since we don't know
2798 that yet, we leave the decision up to
2799 on_failure_jump_smart. */
2800 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2801 laststart
+ startoffset
, b
+ 6);
2803 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2808 /* A simple ? pattern. */
2809 assert (zero_times_ok
);
2810 GET_BUFFER_SPACE (3);
2811 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2815 else /* not greedy */
2816 { /* I wish the greedy and non-greedy cases could be merged. */
2818 GET_BUFFER_SPACE (7); /* We might use less. */
2821 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2823 /* The non-greedy multiple match looks like
2824 a repeat..until: we only need a conditional jump
2825 at the end of the loop. */
2826 if (emptyp
) BUF_PUSH (no_op
);
2827 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2828 : on_failure_jump
, b
, laststart
);
2832 /* The repeat...until naturally matches one or more.
2833 To also match zero times, we need to first jump to
2834 the end of the loop (its conditional jump). */
2835 INSERT_JUMP (jump
, laststart
, b
);
2841 /* non-greedy a?? */
2842 INSERT_JUMP (jump
, laststart
, b
+ 3);
2844 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2863 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2865 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2867 /* Ensure that we have enough space to push a charset: the
2868 opcode, the length count, and the bitset; 34 bytes in all. */
2869 GET_BUFFER_SPACE (34);
2873 /* We test `*p == '^' twice, instead of using an if
2874 statement, so we only need one BUF_PUSH. */
2875 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2879 /* Remember the first position in the bracket expression. */
2882 /* Push the number of bytes in the bitmap. */
2883 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2885 /* Clear the whole map. */
2886 memset (b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2888 /* charset_not matches newline according to a syntax bit. */
2889 if ((re_opcode_t
) b
[-2] == charset_not
2890 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2891 SET_LIST_BIT ('\n');
2893 /* Read in characters and ranges, setting map bits. */
2896 boolean escaped_char
= false;
2897 const unsigned char *p2
= p
;
2900 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2902 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2903 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2904 So the translation is done later in a loop. Example:
2905 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2908 /* \ might escape characters inside [...] and [^...]. */
2909 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2911 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2914 escaped_char
= true;
2918 /* Could be the end of the bracket expression. If it's
2919 not (i.e., when the bracket expression is `[]' so
2920 far), the ']' character bit gets set way below. */
2921 if (c
== ']' && p2
!= p1
)
2925 /* See if we're at the beginning of a possible character
2928 if (!escaped_char
&&
2929 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2931 /* Leave room for the null. */
2932 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2933 const unsigned char *class_beg
;
2939 /* If pattern is `[[:'. */
2940 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2945 if ((c
== ':' && *p
== ']') || p
== pend
)
2947 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2950 /* This is in any case an invalid class name. */
2955 /* If isn't a word bracketed by `[:' and `:]':
2956 undo the ending character, the letters, and
2957 leave the leading `:' and `[' (but set bits for
2959 if (c
== ':' && *p
== ']')
2961 re_wctype_t cc
= re_wctype (str
);
2964 FREE_STACK_RETURN (REG_ECTYPE
);
2966 /* Throw away the ] at the end of the character
2970 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2973 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
2974 if (re_iswctype (btowc (ch
), cc
))
2977 if (c
< (1 << BYTEWIDTH
))
2981 /* Most character classes in a multibyte match
2982 just set a flag. Exceptions are is_blank,
2983 is_digit, is_cntrl, and is_xdigit, since
2984 they can only match ASCII characters. We
2985 don't need to handle them for multibyte.
2986 They are distinguished by a negative wctype. */
2988 /* Setup the gl_state object to its buffer-defined
2989 value. This hardcodes the buffer-global
2990 syntax-table for ASCII chars, while the other chars
2991 will obey syntax-table properties. It's not ideal,
2992 but it's the way it's been done until now. */
2993 SETUP_BUFFER_SYNTAX_TABLE ();
2995 for (ch
= 0; ch
< 256; ++ch
)
2997 c
= RE_CHAR_TO_MULTIBYTE (ch
);
2998 if (! CHAR_BYTE8_P (c
)
2999 && re_iswctype (c
, cc
))
3005 if (ASCII_CHAR_P (c1
))
3007 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
3011 SET_RANGE_TABLE_WORK_AREA_BIT
3012 (range_table_work
, re_wctype_to_bit (cc
));
3014 /* In most cases the matching rule for char classes
3015 only uses the syntax table for multibyte chars,
3016 so that the content of the syntax-table it is not
3017 hardcoded in the range_table. SPACE and WORD are
3018 the two exceptions. */
3019 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
3020 bufp
->used_syntax
= 1;
3022 /* Repeat the loop. */
3027 /* Go back to right after the "[:". */
3031 /* Because the `:' may starts the range, we
3032 can't simply set bit and repeat the loop.
3033 Instead, just set it to C and handle below. */
3038 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
3041 /* Discard the `-'. */
3044 /* Fetch the character which ends the range. */
3047 if (CHAR_BYTE8_P (c1
)
3048 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
3049 /* Treat the range from a multibyte character to
3050 raw-byte character as empty. */
3055 /* Range from C to C. */
3060 if (syntax
& RE_NO_EMPTY_RANGES
)
3061 FREE_STACK_RETURN (REG_ERANGEX
);
3062 /* Else, repeat the loop. */
3067 /* Set the range into bitmap */
3068 for (; c
<= c1
; c
++)
3071 if (ch
< (1 << BYTEWIDTH
))
3078 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
3080 if (CHAR_BYTE8_P (c1
))
3081 c
= BYTE8_TO_CHAR (128);
3085 if (CHAR_BYTE8_P (c
))
3087 c
= CHAR_TO_BYTE8 (c
);
3088 c1
= CHAR_TO_BYTE8 (c1
);
3089 for (; c
<= c1
; c
++)
3094 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
3098 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
3105 /* Discard any (non)matching list bytes that are all 0 at the
3106 end of the map. Decrease the map-length byte too. */
3107 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3111 /* Build real range table from work area. */
3112 if (RANGE_TABLE_WORK_USED (range_table_work
)
3113 || RANGE_TABLE_WORK_BITS (range_table_work
))
3116 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3118 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3119 bytes for flags, two for COUNT, and three bytes for
3121 GET_BUFFER_SPACE (4 + used
* 3);
3123 /* Indicate the existence of range table. */
3124 laststart
[1] |= 0x80;
3126 /* Store the character class flag bits into the range table.
3127 If not in emacs, these flag bits are always 0. */
3128 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3129 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3131 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3132 for (i
= 0; i
< used
; i
++)
3133 STORE_CHARACTER_AND_INCR
3134 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3141 if (syntax
& RE_NO_BK_PARENS
)
3148 if (syntax
& RE_NO_BK_PARENS
)
3155 if (syntax
& RE_NEWLINE_ALT
)
3162 if (syntax
& RE_NO_BK_VBAR
)
3169 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3170 goto handle_interval
;
3176 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3178 /* Do not translate the character after the \, so that we can
3179 distinguish, e.g., \B from \b, even if we normally would
3180 translate, e.g., B to b. */
3186 if (syntax
& RE_NO_BK_PARENS
)
3187 goto normal_backslash
;
3192 regnum_t regnum
= 0;
3195 /* Look for a special (?...) construct */
3196 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3198 PATFETCH (c
); /* Gobble up the '?'. */
3204 case ':': shy
= 1; break;
3206 /* An explicitly specified regnum must start
3209 FREE_STACK_RETURN (REG_BADPAT
);
3210 case '1': case '2': case '3': case '4':
3211 case '5': case '6': case '7': case '8': case '9':
3212 regnum
= 10*regnum
+ (c
- '0'); break;
3214 /* Only (?:...) is supported right now. */
3215 FREE_STACK_RETURN (REG_BADPAT
);
3222 regnum
= ++bufp
->re_nsub
;
3224 { /* It's actually not shy, but explicitly numbered. */
3226 if (regnum
> bufp
->re_nsub
)
3227 bufp
->re_nsub
= regnum
;
3228 else if (regnum
> bufp
->re_nsub
3229 /* Ideally, we'd want to check that the specified
3230 group can't have matched (i.e. all subgroups
3231 using the same regnum are in other branches of
3232 OR patterns), but we don't currently keep track
3233 of enough info to do that easily. */
3234 || group_in_compile_stack (compile_stack
, regnum
))
3235 FREE_STACK_RETURN (REG_BADPAT
);
3238 /* It's really shy. */
3239 regnum
= - bufp
->re_nsub
;
3241 if (COMPILE_STACK_FULL
)
3243 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3244 compile_stack_elt_t
);
3245 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3247 compile_stack
.size
<<= 1;
3250 /* These are the values to restore when we hit end of this
3251 group. They are all relative offsets, so that if the
3252 whole pattern moves because of realloc, they will still
3254 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3255 COMPILE_STACK_TOP
.fixup_alt_jump
3256 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3257 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3258 COMPILE_STACK_TOP
.regnum
= regnum
;
3260 /* Do not push a start_memory for groups beyond the last one
3261 we can represent in the compiled pattern. */
3262 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3263 BUF_PUSH_2 (start_memory
, regnum
);
3265 compile_stack
.avail
++;
3270 /* If we've reached MAX_REGNUM groups, then this open
3271 won't actually generate any code, so we'll have to
3272 clear pending_exact explicitly. */
3278 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3280 if (COMPILE_STACK_EMPTY
)
3282 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3283 goto normal_backslash
;
3285 FREE_STACK_RETURN (REG_ERPAREN
);
3291 /* See similar code for backslashed left paren above. */
3292 if (COMPILE_STACK_EMPTY
)
3294 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3297 FREE_STACK_RETURN (REG_ERPAREN
);
3300 /* Since we just checked for an empty stack above, this
3301 ``can't happen''. */
3302 assert (compile_stack
.avail
!= 0);
3304 /* We don't just want to restore into `regnum', because
3305 later groups should continue to be numbered higher,
3306 as in `(ab)c(de)' -- the second group is #2. */
3309 compile_stack
.avail
--;
3310 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3312 = COMPILE_STACK_TOP
.fixup_alt_jump
3313 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3315 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3316 regnum
= COMPILE_STACK_TOP
.regnum
;
3317 /* If we've reached MAX_REGNUM groups, then this open
3318 won't actually generate any code, so we'll have to
3319 clear pending_exact explicitly. */
3322 /* We're at the end of the group, so now we know how many
3323 groups were inside this one. */
3324 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3325 BUF_PUSH_2 (stop_memory
, regnum
);
3330 case '|': /* `\|'. */
3331 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3332 goto normal_backslash
;
3334 if (syntax
& RE_LIMITED_OPS
)
3337 /* Insert before the previous alternative a jump which
3338 jumps to this alternative if the former fails. */
3339 GET_BUFFER_SPACE (3);
3340 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3344 /* The alternative before this one has a jump after it
3345 which gets executed if it gets matched. Adjust that
3346 jump so it will jump to this alternative's analogous
3347 jump (put in below, which in turn will jump to the next
3348 (if any) alternative's such jump, etc.). The last such
3349 jump jumps to the correct final destination. A picture:
3355 If we are at `b', then fixup_alt_jump right now points to a
3356 three-byte space after `a'. We'll put in the jump, set
3357 fixup_alt_jump to right after `b', and leave behind three
3358 bytes which we'll fill in when we get to after `c'. */
3362 /* Mark and leave space for a jump after this alternative,
3363 to be filled in later either by next alternative or
3364 when know we're at the end of a series of alternatives. */
3366 GET_BUFFER_SPACE (3);
3375 /* If \{ is a literal. */
3376 if (!(syntax
& RE_INTERVALS
)
3377 /* If we're at `\{' and it's not the open-interval
3379 || (syntax
& RE_NO_BK_BRACES
))
3380 goto normal_backslash
;
3384 /* If got here, then the syntax allows intervals. */
3386 /* At least (most) this many matches must be made. */
3387 int lower_bound
= 0, upper_bound
= -1;
3391 GET_UNSIGNED_NUMBER (lower_bound
);
3394 GET_UNSIGNED_NUMBER (upper_bound
);
3396 /* Interval such as `{1}' => match exactly once. */
3397 upper_bound
= lower_bound
;
3399 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3400 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3401 FREE_STACK_RETURN (REG_BADBR
);
3403 if (!(syntax
& RE_NO_BK_BRACES
))
3406 FREE_STACK_RETURN (REG_BADBR
);
3408 FREE_STACK_RETURN (REG_EESCAPE
);
3413 FREE_STACK_RETURN (REG_BADBR
);
3415 /* We just parsed a valid interval. */
3417 /* If it's invalid to have no preceding re. */
3420 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3421 FREE_STACK_RETURN (REG_BADRPT
);
3422 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3425 goto unfetch_interval
;
3428 if (upper_bound
== 0)
3429 /* If the upper bound is zero, just drop the sub pattern
3432 else if (lower_bound
== 1 && upper_bound
== 1)
3433 /* Just match it once: nothing to do here. */
3436 /* Otherwise, we have a nontrivial interval. When
3437 we're all done, the pattern will look like:
3438 set_number_at <jump count> <upper bound>
3439 set_number_at <succeed_n count> <lower bound>
3440 succeed_n <after jump addr> <succeed_n count>
3442 jump_n <succeed_n addr> <jump count>
3443 (The upper bound and `jump_n' are omitted if
3444 `upper_bound' is 1, though.) */
3446 { /* If the upper bound is > 1, we need to insert
3447 more at the end of the loop. */
3448 unsigned int nbytes
= (upper_bound
< 0 ? 3
3449 : upper_bound
> 1 ? 5 : 0);
3450 unsigned int startoffset
= 0;
3452 GET_BUFFER_SPACE (20); /* We might use less. */
3454 if (lower_bound
== 0)
3456 /* A succeed_n that starts with 0 is really a
3457 a simple on_failure_jump_loop. */
3458 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3464 /* Initialize lower bound of the `succeed_n', even
3465 though it will be set during matching by its
3466 attendant `set_number_at' (inserted next),
3467 because `re_compile_fastmap' needs to know.
3468 Jump to the `jump_n' we might insert below. */
3469 INSERT_JUMP2 (succeed_n
, laststart
,
3474 /* Code to initialize the lower bound. Insert
3475 before the `succeed_n'. The `5' is the last two
3476 bytes of this `set_number_at', plus 3 bytes of
3477 the following `succeed_n'. */
3478 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3483 if (upper_bound
< 0)
3485 /* A negative upper bound stands for infinity,
3486 in which case it degenerates to a plain jump. */
3487 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3490 else if (upper_bound
> 1)
3491 { /* More than one repetition is allowed, so
3492 append a backward jump to the `succeed_n'
3493 that starts this interval.
3495 When we've reached this during matching,
3496 we'll have matched the interval once, so
3497 jump back only `upper_bound - 1' times. */
3498 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3502 /* The location we want to set is the second
3503 parameter of the `jump_n'; that is `b-2' as
3504 an absolute address. `laststart' will be
3505 the `set_number_at' we're about to insert;
3506 `laststart+3' the number to set, the source
3507 for the relative address. But we are
3508 inserting into the middle of the pattern --
3509 so everything is getting moved up by 5.
3510 Conclusion: (b - 2) - (laststart + 3) + 5,
3511 i.e., b - laststart.
3513 We insert this at the beginning of the loop
3514 so that if we fail during matching, we'll
3515 reinitialize the bounds. */
3516 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3517 upper_bound
- 1, b
);
3522 beg_interval
= NULL
;
3527 /* If an invalid interval, match the characters as literals. */
3528 assert (beg_interval
);
3530 beg_interval
= NULL
;
3532 /* normal_char and normal_backslash need `c'. */
3535 if (!(syntax
& RE_NO_BK_BRACES
))
3537 assert (p
> pattern
&& p
[-1] == '\\');
3538 goto normal_backslash
;
3544 /* There is no way to specify the before_dot and after_dot
3545 operators. rms says this is ok. --karl */
3553 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3559 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3565 BUF_PUSH_2 (categoryspec
, c
);
3571 BUF_PUSH_2 (notcategoryspec
, c
);
3577 if (syntax
& RE_NO_GNU_OPS
)
3580 BUF_PUSH_2 (syntaxspec
, Sword
);
3585 if (syntax
& RE_NO_GNU_OPS
)
3588 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3593 if (syntax
& RE_NO_GNU_OPS
)
3599 if (syntax
& RE_NO_GNU_OPS
)
3605 if (syntax
& RE_NO_GNU_OPS
)
3614 FREE_STACK_RETURN (REG_BADPAT
);
3618 if (syntax
& RE_NO_GNU_OPS
)
3620 BUF_PUSH (wordbound
);
3624 if (syntax
& RE_NO_GNU_OPS
)
3626 BUF_PUSH (notwordbound
);
3630 if (syntax
& RE_NO_GNU_OPS
)
3636 if (syntax
& RE_NO_GNU_OPS
)
3641 case '1': case '2': case '3': case '4': case '5':
3642 case '6': case '7': case '8': case '9':
3646 if (syntax
& RE_NO_BK_REFS
)
3647 goto normal_backslash
;
3651 if (reg
> bufp
->re_nsub
|| reg
< 1
3652 /* Can't back reference to a subexp before its end. */
3653 || group_in_compile_stack (compile_stack
, reg
))
3654 FREE_STACK_RETURN (REG_ESUBREG
);
3657 BUF_PUSH_2 (duplicate
, reg
);
3664 if (syntax
& RE_BK_PLUS_QM
)
3667 goto normal_backslash
;
3671 /* You might think it would be useful for \ to mean
3672 not to translate; but if we don't translate it
3673 it will never match anything. */
3680 /* Expects the character in `c'. */
3682 /* If no exactn currently being built. */
3685 /* If last exactn not at current position. */
3686 || pending_exact
+ *pending_exact
+ 1 != b
3688 /* We have only one byte following the exactn for the count. */
3689 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3691 /* If followed by a repetition operator. */
3692 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3693 || ((syntax
& RE_BK_PLUS_QM
)
3694 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3695 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3696 || ((syntax
& RE_INTERVALS
)
3697 && ((syntax
& RE_NO_BK_BRACES
)
3698 ? p
!= pend
&& *p
== '{'
3699 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3701 /* Start building a new exactn. */
3705 BUF_PUSH_2 (exactn
, 0);
3706 pending_exact
= b
- 1;
3709 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3716 len
= CHAR_STRING (c
, b
);
3721 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3722 if (! CHAR_BYTE8_P (c1
))
3724 re_wchar_t c2
= TRANSLATE (c1
);
3726 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3732 (*pending_exact
) += len
;
3737 } /* while p != pend */
3740 /* Through the pattern now. */
3744 if (!COMPILE_STACK_EMPTY
)
3745 FREE_STACK_RETURN (REG_EPAREN
);
3747 /* If we don't want backtracking, force success
3748 the first time we reach the end of the compiled pattern. */
3749 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3752 /* We have succeeded; set the length of the buffer. */
3753 bufp
->used
= b
- bufp
->buffer
;
3758 re_compile_fastmap (bufp
);
3759 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3760 print_compiled_pattern (bufp
);
3765 #ifndef MATCH_MAY_ALLOCATE
3766 /* Initialize the failure stack to the largest possible stack. This
3767 isn't necessary unless we're trying to avoid calling alloca in
3768 the search and match routines. */
3770 int num_regs
= bufp
->re_nsub
+ 1;
3772 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3774 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3776 if (! fail_stack
.stack
)
3778 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3779 * sizeof (fail_stack_elt_t
));
3782 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3784 * sizeof (fail_stack_elt_t
)));
3787 regex_grow_registers (num_regs
);
3789 #endif /* not MATCH_MAY_ALLOCATE */
3791 FREE_STACK_RETURN (REG_NOERROR
);
3792 } /* regex_compile */
3794 /* Subroutines for `regex_compile'. */
3796 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3799 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3801 *loc
= (unsigned char) op
;
3802 STORE_NUMBER (loc
+ 1, arg
);
3806 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3809 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3811 *loc
= (unsigned char) op
;
3812 STORE_NUMBER (loc
+ 1, arg1
);
3813 STORE_NUMBER (loc
+ 3, arg2
);
3817 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3818 for OP followed by two-byte integer parameter ARG. */
3821 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3823 register unsigned char *pfrom
= end
;
3824 register unsigned char *pto
= end
+ 3;
3826 while (pfrom
!= loc
)
3829 store_op1 (op
, loc
, arg
);
3833 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3836 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3838 register unsigned char *pfrom
= end
;
3839 register unsigned char *pto
= end
+ 5;
3841 while (pfrom
!= loc
)
3844 store_op2 (op
, loc
, arg1
, arg2
);
3848 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3849 after an alternative or a begin-subexpression. We assume there is at
3850 least one character before the ^. */
3853 at_begline_loc_p (const re_char
*pattern
, const re_char
*p
, reg_syntax_t syntax
)
3855 re_char
*prev
= p
- 2;
3856 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3859 /* After a subexpression? */
3860 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3861 /* After an alternative? */
3862 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3863 /* After a shy subexpression? */
3864 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3865 && prev
[-1] == '?' && prev
[-2] == '('
3866 && (syntax
& RE_NO_BK_PARENS
3867 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3871 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3872 at least one character after the $, i.e., `P < PEND'. */
3875 at_endline_loc_p (const re_char
*p
, const re_char
*pend
, reg_syntax_t syntax
)
3878 boolean next_backslash
= *next
== '\\';
3879 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3882 /* Before a subexpression? */
3883 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3884 : next_backslash
&& next_next
&& *next_next
== ')')
3885 /* Before an alternative? */
3886 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3887 : next_backslash
&& next_next
&& *next_next
== '|');
3891 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3892 false if it's not. */
3895 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3897 ssize_t this_element
;
3899 for (this_element
= compile_stack
.avail
- 1;
3902 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3909 If fastmap is non-NULL, go through the pattern and fill fastmap
3910 with all the possible leading chars. If fastmap is NULL, don't
3911 bother filling it up (obviously) and only return whether the
3912 pattern could potentially match the empty string.
3914 Return 1 if p..pend might match the empty string.
3915 Return 0 if p..pend matches at least one char.
3916 Return -1 if fastmap was not updated accurately. */
3919 analyse_first (const re_char
*p
, const re_char
*pend
, char *fastmap
, const int multibyte
)
3924 /* If all elements for base leading-codes in fastmap is set, this
3925 flag is set true. */
3926 boolean match_any_multibyte_characters
= false;
3930 /* The loop below works as follows:
3931 - It has a working-list kept in the PATTERN_STACK and which basically
3932 starts by only containing a pointer to the first operation.
3933 - If the opcode we're looking at is a match against some set of
3934 chars, then we add those chars to the fastmap and go on to the
3935 next work element from the worklist (done via `break').
3936 - If the opcode is a control operator on the other hand, we either
3937 ignore it (if it's meaningless at this point, such as `start_memory')
3938 or execute it (if it's a jump). If the jump has several destinations
3939 (i.e. `on_failure_jump'), then we push the other destination onto the
3941 We guarantee termination by ignoring backward jumps (more or less),
3942 so that `p' is monotonically increasing. More to the point, we
3943 never set `p' (or push) anything `<= p1'. */
3947 /* `p1' is used as a marker of how far back a `on_failure_jump'
3948 can go without being ignored. It is normally equal to `p'
3949 (which prevents any backward `on_failure_jump') except right
3950 after a plain `jump', to allow patterns such as:
3953 10: on_failure_jump 3
3954 as used for the *? operator. */
3957 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3963 /* If the first character has to match a backreference, that means
3964 that the group was empty (since it already matched). Since this
3965 is the only case that interests us here, we can assume that the
3966 backreference must match the empty string. */
3971 /* Following are the cases which match a character. These end
3977 /* If multibyte is nonzero, the first byte of each
3978 character is an ASCII or a leading code. Otherwise,
3979 each byte is a character. Thus, this works in both
3984 /* For the case of matching this unibyte regex
3985 against multibyte, we must set a leading code of
3986 the corresponding multibyte character. */
3987 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
3989 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
3996 /* We could put all the chars except for \n (and maybe \0)
3997 but we don't bother since it is generally not worth it. */
3998 if (!fastmap
) break;
4003 if (!fastmap
) break;
4005 /* Chars beyond end of bitmap are possible matches. */
4006 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
4007 j
< (1 << BYTEWIDTH
); j
++)
4013 if (!fastmap
) break;
4014 not = (re_opcode_t
) *(p
- 1) == charset_not
;
4015 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
4017 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
4021 if (/* Any leading code can possibly start a character
4022 which doesn't match the specified set of characters. */
4025 /* If we can match a character class, we can match any
4026 multibyte characters. */
4027 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4028 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
4031 if (match_any_multibyte_characters
== false)
4033 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4034 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4036 match_any_multibyte_characters
= true;
4040 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4041 && match_any_multibyte_characters
== false)
4043 /* Set fastmap[I] to 1 where I is a leading code of each
4044 multibyte character in the range table. */
4046 unsigned char lc1
, lc2
;
4048 /* Make P points the range table. `+ 2' is to skip flag
4049 bits for a character class. */
4050 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
4052 /* Extract the number of ranges in range table into COUNT. */
4053 EXTRACT_NUMBER_AND_INCR (count
, p
);
4054 for (; count
> 0; count
--, p
+= 3)
4056 /* Extract the start and end of each range. */
4057 EXTRACT_CHARACTER (c
, p
);
4058 lc1
= CHAR_LEADING_CODE (c
);
4060 EXTRACT_CHARACTER (c
, p
);
4061 lc2
= CHAR_LEADING_CODE (c
);
4062 for (j
= lc1
; j
<= lc2
; j
++)
4071 if (!fastmap
) break;
4073 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
4075 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4076 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4080 /* This match depends on text properties. These end with
4081 aborting optimizations. */
4085 case notcategoryspec
:
4086 if (!fastmap
) break;
4087 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4089 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
4090 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4093 /* Any leading code can possibly start a character which
4094 has or doesn't has the specified category. */
4095 if (match_any_multibyte_characters
== false)
4097 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4098 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4100 match_any_multibyte_characters
= true;
4104 /* All cases after this match the empty string. These end with
4126 EXTRACT_NUMBER_AND_INCR (j
, p
);
4128 /* Backward jumps can only go back to code that we've already
4129 visited. `re_compile' should make sure this is true. */
4132 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4134 case on_failure_jump
:
4135 case on_failure_keep_string_jump
:
4136 case on_failure_jump_loop
:
4137 case on_failure_jump_nastyloop
:
4138 case on_failure_jump_smart
:
4144 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4145 to jump back to "just after here". */
4148 case on_failure_jump
:
4149 case on_failure_keep_string_jump
:
4150 case on_failure_jump_nastyloop
:
4151 case on_failure_jump_loop
:
4152 case on_failure_jump_smart
:
4153 EXTRACT_NUMBER_AND_INCR (j
, p
);
4155 ; /* Backward jump to be ignored. */
4157 { /* We have to look down both arms.
4158 We first go down the "straight" path so as to minimize
4159 stack usage when going through alternatives. */
4160 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4168 /* This code simply does not properly handle forward jump_n. */
4169 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4171 /* jump_n can either jump or fall through. The (backward) jump
4172 case has already been handled, so we only need to look at the
4173 fallthrough case. */
4177 /* If N == 0, it should be an on_failure_jump_loop instead. */
4178 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4180 /* We only care about one iteration of the loop, so we don't
4181 need to consider the case where this behaves like an
4198 abort (); /* We have listed all the cases. */
4201 /* Getting here means we have found the possible starting
4202 characters for one path of the pattern -- and that the empty
4203 string does not match. We need not follow this path further. */
4207 /* We reached the end without matching anything. */
4210 } /* analyse_first */
4212 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4213 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4214 characters can start a string that matches the pattern. This fastmap
4215 is used by re_search to skip quickly over impossible starting points.
4217 Character codes above (1 << BYTEWIDTH) are not represented in the
4218 fastmap, but the leading codes are represented. Thus, the fastmap
4219 indicates which character sets could start a match.
4221 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4222 area as BUFP->fastmap.
4224 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4227 Returns 0 if we succeed, -2 if an internal error. */
4230 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4232 char *fastmap
= bufp
->fastmap
;
4235 assert (fastmap
&& bufp
->buffer
);
4237 memset (fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4238 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4240 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4241 fastmap
, RE_MULTIBYTE_P (bufp
));
4242 bufp
->can_be_null
= (analysis
!= 0);
4244 } /* re_compile_fastmap */
4246 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4247 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4248 this memory for recording register information. STARTS and ENDS
4249 must be allocated using the malloc library routine, and must each
4250 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4252 If NUM_REGS == 0, then subsequent matches should allocate their own
4255 Unless this function is called, the first search or match using
4256 PATTERN_BUFFER will allocate its own register data, without
4257 freeing the old data. */
4260 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4264 bufp
->regs_allocated
= REGS_REALLOCATE
;
4265 regs
->num_regs
= num_regs
;
4266 regs
->start
= starts
;
4271 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4273 regs
->start
= regs
->end
= (regoff_t
*) 0;
4276 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4278 /* Searching routines. */
4280 /* Like re_search_2, below, but only one string is specified, and
4281 doesn't let you say where to stop matching. */
4284 re_search (struct re_pattern_buffer
*bufp
, const char *string
, size_t size
,
4285 ssize_t startpos
, ssize_t range
, struct re_registers
*regs
)
4287 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4290 WEAK_ALIAS (__re_search
, re_search
)
4292 /* Head address of virtual concatenation of string. */
4293 #define HEAD_ADDR_VSTRING(P) \
4294 (((P) >= size1 ? string2 : string1))
4296 /* Address of POS in the concatenation of virtual string. */
4297 #define POS_ADDR_VSTRING(POS) \
4298 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4300 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4301 virtual concatenation of STRING1 and STRING2, starting first at index
4302 STARTPOS, then at STARTPOS + 1, and so on.
4304 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4306 RANGE is how far to scan while trying to match. RANGE = 0 means try
4307 only at STARTPOS; in general, the last start tried is STARTPOS +
4310 In REGS, return the indices of the virtual concatenation of STRING1
4311 and STRING2 that matched the entire BUFP->buffer and its contained
4314 Do not consider matching one past the index STOP in the virtual
4315 concatenation of STRING1 and STRING2.
4317 We return either the position in the strings at which the match was
4318 found, -1 if no match, or -2 if error (such as failure
4322 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, size_t size1
,
4323 const char *str2
, size_t size2
, ssize_t startpos
, ssize_t range
,
4324 struct re_registers
*regs
, ssize_t stop
)
4327 re_char
*string1
= (re_char
*) str1
;
4328 re_char
*string2
= (re_char
*) str2
;
4329 register char *fastmap
= bufp
->fastmap
;
4330 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4331 size_t total_size
= size1
+ size2
;
4332 ssize_t endpos
= startpos
+ range
;
4333 boolean anchored_start
;
4334 /* Nonzero if we are searching multibyte string. */
4335 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4337 /* Check for out-of-range STARTPOS. */
4338 if (startpos
< 0 || startpos
> total_size
)
4341 /* Fix up RANGE if it might eventually take us outside
4342 the virtual concatenation of STRING1 and STRING2.
4343 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4345 range
= 0 - startpos
;
4346 else if (endpos
> total_size
)
4347 range
= total_size
- startpos
;
4349 /* If the search isn't to be a backwards one, don't waste time in a
4350 search for a pattern anchored at beginning of buffer. */
4351 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4360 /* In a forward search for something that starts with \=.
4361 don't keep searching past point. */
4362 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4364 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4370 /* Update the fastmap now if not correct already. */
4371 if (fastmap
&& !bufp
->fastmap_accurate
)
4372 re_compile_fastmap (bufp
);
4374 /* See whether the pattern is anchored. */
4375 anchored_start
= (bufp
->buffer
[0] == begline
);
4378 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4380 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4382 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4386 /* Loop through the string, looking for a place to start matching. */
4389 /* If the pattern is anchored,
4390 skip quickly past places we cannot match.
4391 We don't bother to treat startpos == 0 specially
4392 because that case doesn't repeat. */
4393 if (anchored_start
&& startpos
> 0)
4395 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4396 : string2
[startpos
- size1
- 1])
4401 /* If a fastmap is supplied, skip quickly over characters that
4402 cannot be the start of a match. If the pattern can match the
4403 null string, however, we don't need to skip characters; we want
4404 the first null string. */
4405 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4407 register re_char
*d
;
4408 register re_wchar_t buf_ch
;
4410 d
= POS_ADDR_VSTRING (startpos
);
4412 if (range
> 0) /* Searching forwards. */
4414 register int lim
= 0;
4415 ssize_t irange
= range
;
4417 if (startpos
< size1
&& startpos
+ range
>= size1
)
4418 lim
= range
- (size1
- startpos
);
4420 /* Written out as an if-else to avoid testing `translate'
4422 if (RE_TRANSLATE_P (translate
))
4429 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4430 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4431 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4434 range
-= buf_charlen
;
4440 register re_wchar_t ch
, translated
;
4443 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4444 translated
= RE_TRANSLATE (translate
, ch
);
4445 if (translated
!= ch
4446 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4448 if (fastmap
[buf_ch
])
4461 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4462 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4464 range
-= buf_charlen
;
4468 while (range
> lim
&& !fastmap
[*d
])
4474 startpos
+= irange
- range
;
4476 else /* Searching backwards. */
4480 buf_ch
= STRING_CHAR (d
);
4481 buf_ch
= TRANSLATE (buf_ch
);
4482 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4487 register re_wchar_t ch
, translated
;
4490 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4491 translated
= TRANSLATE (ch
);
4492 if (translated
!= ch
4493 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4495 if (! fastmap
[TRANSLATE (buf_ch
)])
4501 /* If can't match the null string, and that's all we have left, fail. */
4502 if (range
>= 0 && startpos
== total_size
&& fastmap
4503 && !bufp
->can_be_null
)
4506 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4507 startpos
, regs
, stop
);
4520 /* Update STARTPOS to the next character boundary. */
4523 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4524 int len
= BYTES_BY_CHAR_HEAD (*p
);
4542 /* Update STARTPOS to the previous character boundary. */
4545 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4547 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4549 /* Find the head of multibyte form. */
4550 PREV_CHAR_BOUNDARY (p
, phead
);
4551 range
+= p0
- 1 - p
;
4555 startpos
-= p0
- 1 - p
;
4561 WEAK_ALIAS (__re_search_2
, re_search_2
)
4563 /* Declarations and macros for re_match_2. */
4565 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4566 register ssize_t len
,
4567 RE_TRANSLATE_TYPE translate
,
4568 const int multibyte
));
4570 /* This converts PTR, a pointer into one of the search strings `string1'
4571 and `string2' into an offset from the beginning of that string. */
4572 #define POINTER_TO_OFFSET(ptr) \
4573 (FIRST_STRING_P (ptr) \
4574 ? ((regoff_t) ((ptr) - string1)) \
4575 : ((regoff_t) ((ptr) - string2 + size1)))
4577 /* Call before fetching a character with *d. This switches over to
4578 string2 if necessary.
4579 Check re_match_2_internal for a discussion of why end_match_2 might
4580 not be within string2 (but be equal to end_match_1 instead). */
4581 #define PREFETCH() \
4584 /* End of string2 => fail. */ \
4585 if (dend == end_match_2) \
4587 /* End of string1 => advance to string2. */ \
4589 dend = end_match_2; \
4592 /* Call before fetching a char with *d if you already checked other limits.
4593 This is meant for use in lookahead operations like wordend, etc..
4594 where we might need to look at parts of the string that might be
4595 outside of the LIMITs (i.e past `stop'). */
4596 #define PREFETCH_NOLIMIT() \
4600 dend = end_match_2; \
4603 /* Test if at very beginning or at very end of the virtual concatenation
4604 of `string1' and `string2'. If only one string, it's `string2'. */
4605 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4606 #define AT_STRINGS_END(d) ((d) == end2)
4608 /* Disabled due to a compiler bug -- see comment at case wordbound */
4610 /* The comment at case wordbound is following one, but we don't use
4611 AT_WORD_BOUNDARY anymore to support multibyte form.
4613 The DEC Alpha C compiler 3.x generates incorrect code for the
4614 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4615 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4616 macro and introducing temporary variables works around the bug. */
4619 /* Test if D points to a character which is word-constituent. We have
4620 two special cases to check for: if past the end of string1, look at
4621 the first character in string2; and if before the beginning of
4622 string2, look at the last character in string1. */
4623 #define WORDCHAR_P(d) \
4624 (SYNTAX ((d) == end1 ? *string2 \
4625 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4628 /* Test if the character before D and the one at D differ with respect
4629 to being word-constituent. */
4630 #define AT_WORD_BOUNDARY(d) \
4631 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4632 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4635 /* Free everything we malloc. */
4636 #ifdef MATCH_MAY_ALLOCATE
4637 # define FREE_VAR(var) \
4645 # define FREE_VARIABLES() \
4647 REGEX_FREE_STACK (fail_stack.stack); \
4648 FREE_VAR (regstart); \
4649 FREE_VAR (regend); \
4650 FREE_VAR (best_regstart); \
4651 FREE_VAR (best_regend); \
4654 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4655 #endif /* not MATCH_MAY_ALLOCATE */
4658 /* Optimization routines. */
4660 /* If the operation is a match against one or more chars,
4661 return a pointer to the next operation, else return NULL. */
4663 skip_one_char (const re_char
*p
)
4665 switch (SWITCH_ENUM_CAST (*p
++))
4676 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4679 p
= CHARSET_RANGE_TABLE (p
- 1);
4680 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4681 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4684 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4691 case notcategoryspec
:
4703 /* Jump over non-matching operations. */
4705 skip_noops (const re_char
*p
, const re_char
*pend
)
4710 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4719 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4730 /* Non-zero if "p1 matches something" implies "p2 fails". */
4732 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const re_char
*p1
, const re_char
*p2
)
4735 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4736 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4738 assert (p1
>= bufp
->buffer
&& p1
< pend
4739 && p2
>= bufp
->buffer
&& p2
<= pend
);
4741 /* Skip over open/close-group commands.
4742 If what follows this loop is a ...+ construct,
4743 look at what begins its body, since we will have to
4744 match at least one of that. */
4745 p2
= skip_noops (p2
, pend
);
4746 /* The same skip can be done for p1, except that this function
4747 is only used in the case where p1 is a simple match operator. */
4748 /* p1 = skip_noops (p1, pend); */
4750 assert (p1
>= bufp
->buffer
&& p1
< pend
4751 && p2
>= bufp
->buffer
&& p2
<= pend
);
4753 op2
= p2
== pend
? succeed
: *p2
;
4755 switch (SWITCH_ENUM_CAST (op2
))
4759 /* If we're at the end of the pattern, we can change. */
4760 if (skip_one_char (p1
))
4762 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4770 register re_wchar_t c
4771 = (re_opcode_t
) *p2
== endline
? '\n'
4772 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4774 if ((re_opcode_t
) *p1
== exactn
)
4776 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4778 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4783 else if ((re_opcode_t
) *p1
== charset
4784 || (re_opcode_t
) *p1
== charset_not
)
4786 int not = (re_opcode_t
) *p1
== charset_not
;
4788 /* Test if C is listed in charset (or charset_not)
4790 if (! multibyte
|| IS_REAL_ASCII (c
))
4792 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4793 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4796 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4797 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4799 /* `not' is equal to 1 if c would match, which means
4800 that we can't change to pop_failure_jump. */
4803 DEBUG_PRINT1 (" No match => fast loop.\n");
4807 else if ((re_opcode_t
) *p1
== anychar
4810 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4818 if ((re_opcode_t
) *p1
== exactn
)
4819 /* Reuse the code above. */
4820 return mutually_exclusive_p (bufp
, p2
, p1
);
4822 /* It is hard to list up all the character in charset
4823 P2 if it includes multibyte character. Give up in
4825 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4827 /* Now, we are sure that P2 has no range table.
4828 So, for the size of bitmap in P2, `p2[1]' is
4829 enough. But P1 may have range table, so the
4830 size of bitmap table of P1 is extracted by
4831 using macro `CHARSET_BITMAP_SIZE'.
4833 In a multibyte case, we know that all the character
4834 listed in P2 is ASCII. In a unibyte case, P1 has only a
4835 bitmap table. So, in both cases, it is enough to test
4836 only the bitmap table of P1. */
4838 if ((re_opcode_t
) *p1
== charset
)
4841 /* We win if the charset inside the loop
4842 has no overlap with the one after the loop. */
4845 && idx
< CHARSET_BITMAP_SIZE (p1
));
4847 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4851 || idx
== CHARSET_BITMAP_SIZE (p1
))
4853 DEBUG_PRINT1 (" No match => fast loop.\n");
4857 else if ((re_opcode_t
) *p1
== charset_not
)
4860 /* We win if the charset_not inside the loop lists
4861 every character listed in the charset after. */
4862 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4863 if (! (p2
[2 + idx
] == 0
4864 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4865 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4870 DEBUG_PRINT1 (" No match => fast loop.\n");
4879 switch (SWITCH_ENUM_CAST (*p1
))
4883 /* Reuse the code above. */
4884 return mutually_exclusive_p (bufp
, p2
, p1
);
4886 /* When we have two charset_not, it's very unlikely that
4887 they don't overlap. The union of the two sets of excluded
4888 chars should cover all possible chars, which, as a matter of
4889 fact, is virtually impossible in multibyte buffers. */
4895 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4897 return ((re_opcode_t
) *p1
== syntaxspec
4898 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4900 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4903 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4905 return ((re_opcode_t
) *p1
== notsyntaxspec
4906 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4908 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4911 return (((re_opcode_t
) *p1
== notsyntaxspec
4912 || (re_opcode_t
) *p1
== syntaxspec
)
4917 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4918 case notcategoryspec
:
4919 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4931 /* Matching routines. */
4933 #ifndef emacs /* Emacs never uses this. */
4934 /* re_match is like re_match_2 except it takes only a single string. */
4937 re_match (struct re_pattern_buffer
*bufp
, const char *string
,
4938 size_t size
, ssize_t pos
, struct re_registers
*regs
)
4940 regoff_t result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
,
4941 size
, pos
, regs
, size
);
4944 WEAK_ALIAS (__re_match
, re_match
)
4945 #endif /* not emacs */
4948 /* In Emacs, this is the string or buffer in which we
4949 are matching. It is used for looking up syntax properties. */
4950 Lisp_Object re_match_object
;
4953 /* re_match_2 matches the compiled pattern in BUFP against the
4954 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4955 and SIZE2, respectively). We start matching at POS, and stop
4958 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4959 store offsets for the substring each group matched in REGS. See the
4960 documentation for exactly how many groups we fill.
4962 We return -1 if no match, -2 if an internal error (such as the
4963 failure stack overflowing). Otherwise, we return the length of the
4964 matched substring. */
4967 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
,
4968 size_t size1
, const char *string2
, size_t size2
, ssize_t pos
,
4969 struct re_registers
*regs
, ssize_t stop
)
4975 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4976 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4977 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4980 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4981 (re_char
*) string2
, size2
,
4985 WEAK_ALIAS (__re_match_2
, re_match_2
)
4988 /* This is a separate function so that we can force an alloca cleanup
4991 re_match_2_internal (struct re_pattern_buffer
*bufp
, const re_char
*string1
,
4992 size_t size1
, const re_char
*string2
, size_t size2
,
4993 ssize_t pos
, struct re_registers
*regs
, ssize_t stop
)
4995 /* General temporaries. */
4999 /* Just past the end of the corresponding string. */
5000 re_char
*end1
, *end2
;
5002 /* Pointers into string1 and string2, just past the last characters in
5003 each to consider matching. */
5004 re_char
*end_match_1
, *end_match_2
;
5006 /* Where we are in the data, and the end of the current string. */
5009 /* Used sometimes to remember where we were before starting matching
5010 an operator so that we can go back in case of failure. This "atomic"
5011 behavior of matching opcodes is indispensable to the correctness
5012 of the on_failure_keep_string_jump optimization. */
5015 /* Where we are in the pattern, and the end of the pattern. */
5016 re_char
*p
= bufp
->buffer
;
5017 re_char
*pend
= p
+ bufp
->used
;
5019 /* We use this to map every character in the string. */
5020 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
5022 /* Nonzero if BUFP is setup from a multibyte regex. */
5023 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
5025 /* Nonzero if STRING1/STRING2 are multibyte. */
5026 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
5028 /* Failure point stack. Each place that can handle a failure further
5029 down the line pushes a failure point on this stack. It consists of
5030 regstart, and regend for all registers corresponding to
5031 the subexpressions we're currently inside, plus the number of such
5032 registers, and, finally, two char *'s. The first char * is where
5033 to resume scanning the pattern; the second one is where to resume
5034 scanning the strings. */
5035 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5036 fail_stack_type fail_stack
;
5039 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
5042 #if defined REL_ALLOC && defined REGEX_MALLOC
5043 /* This holds the pointer to the failure stack, when
5044 it is allocated relocatably. */
5045 fail_stack_elt_t
*failure_stack_ptr
;
5048 /* We fill all the registers internally, independent of what we
5049 return, for use in backreferences. The number here includes
5050 an element for register zero. */
5051 size_t num_regs
= bufp
->re_nsub
+ 1;
5053 /* Information on the contents of registers. These are pointers into
5054 the input strings; they record just what was matched (on this
5055 attempt) by a subexpression part of the pattern, that is, the
5056 regnum-th regstart pointer points to where in the pattern we began
5057 matching and the regnum-th regend points to right after where we
5058 stopped matching the regnum-th subexpression. (The zeroth register
5059 keeps track of what the whole pattern matches.) */
5060 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5061 re_char
**regstart
, **regend
;
5064 /* The following record the register info as found in the above
5065 variables when we find a match better than any we've seen before.
5066 This happens as we backtrack through the failure points, which in
5067 turn happens only if we have not yet matched the entire string. */
5068 unsigned best_regs_set
= false;
5069 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5070 re_char
**best_regstart
, **best_regend
;
5073 /* Logically, this is `best_regend[0]'. But we don't want to have to
5074 allocate space for that if we're not allocating space for anything
5075 else (see below). Also, we never need info about register 0 for
5076 any of the other register vectors, and it seems rather a kludge to
5077 treat `best_regend' differently than the rest. So we keep track of
5078 the end of the best match so far in a separate variable. We
5079 initialize this to NULL so that when we backtrack the first time
5080 and need to test it, it's not garbage. */
5081 re_char
*match_end
= NULL
;
5084 /* Counts the total number of registers pushed. */
5085 unsigned num_regs_pushed
= 0;
5088 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5092 #ifdef MATCH_MAY_ALLOCATE
5093 /* Do not bother to initialize all the register variables if there are
5094 no groups in the pattern, as it takes a fair amount of time. If
5095 there are groups, we include space for register 0 (the whole
5096 pattern), even though we never use it, since it simplifies the
5097 array indexing. We should fix this. */
5100 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5101 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5102 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5103 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5105 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5113 /* We must initialize all our variables to NULL, so that
5114 `FREE_VARIABLES' doesn't try to free them. */
5115 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5117 #endif /* MATCH_MAY_ALLOCATE */
5119 /* The starting position is bogus. */
5120 if (pos
< 0 || pos
> size1
+ size2
)
5126 /* Initialize subexpression text positions to -1 to mark ones that no
5127 start_memory/stop_memory has been seen for. Also initialize the
5128 register information struct. */
5129 for (reg
= 1; reg
< num_regs
; reg
++)
5130 regstart
[reg
] = regend
[reg
] = NULL
;
5132 /* We move `string1' into `string2' if the latter's empty -- but not if
5133 `string1' is null. */
5134 if (size2
== 0 && string1
!= NULL
)
5141 end1
= string1
+ size1
;
5142 end2
= string2
+ size2
;
5144 /* `p' scans through the pattern as `d' scans through the data.
5145 `dend' is the end of the input string that `d' points within. `d'
5146 is advanced into the following input string whenever necessary, but
5147 this happens before fetching; therefore, at the beginning of the
5148 loop, `d' can be pointing at the end of a string, but it cannot
5152 /* Only match within string2. */
5153 d
= string2
+ pos
- size1
;
5154 dend
= end_match_2
= string2
+ stop
- size1
;
5155 end_match_1
= end1
; /* Just to give it a value. */
5161 /* Only match within string1. */
5162 end_match_1
= string1
+ stop
;
5164 When we reach end_match_1, PREFETCH normally switches to string2.
5165 But in the present case, this means that just doing a PREFETCH
5166 makes us jump from `stop' to `gap' within the string.
5167 What we really want here is for the search to stop as
5168 soon as we hit end_match_1. That's why we set end_match_2
5169 to end_match_1 (since PREFETCH fails as soon as we hit
5171 end_match_2
= end_match_1
;
5174 { /* It's important to use this code when stop == size so that
5175 moving `d' from end1 to string2 will not prevent the d == dend
5176 check from catching the end of string. */
5178 end_match_2
= string2
+ stop
- size1
;
5184 DEBUG_PRINT1 ("The compiled pattern is: ");
5185 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5186 DEBUG_PRINT1 ("The string to match is: `");
5187 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5188 DEBUG_PRINT1 ("'\n");
5190 /* This loops over pattern commands. It exits by returning from the
5191 function if the match is complete, or it drops through if the match
5192 fails at this starting point in the input data. */
5195 DEBUG_PRINT2 ("\n%p: ", p
);
5198 { /* End of pattern means we might have succeeded. */
5199 DEBUG_PRINT1 ("end of pattern ... ");
5201 /* If we haven't matched the entire string, and we want the
5202 longest match, try backtracking. */
5203 if (d
!= end_match_2
)
5205 /* 1 if this match ends in the same string (string1 or string2)
5206 as the best previous match. */
5207 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5208 == FIRST_STRING_P (d
));
5209 /* 1 if this match is the best seen so far. */
5210 boolean best_match_p
;
5212 /* AIX compiler got confused when this was combined
5213 with the previous declaration. */
5215 best_match_p
= d
> match_end
;
5217 best_match_p
= !FIRST_STRING_P (d
);
5219 DEBUG_PRINT1 ("backtracking.\n");
5221 if (!FAIL_STACK_EMPTY ())
5222 { /* More failure points to try. */
5224 /* If exceeds best match so far, save it. */
5225 if (!best_regs_set
|| best_match_p
)
5227 best_regs_set
= true;
5230 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5232 for (reg
= 1; reg
< num_regs
; reg
++)
5234 best_regstart
[reg
] = regstart
[reg
];
5235 best_regend
[reg
] = regend
[reg
];
5241 /* If no failure points, don't restore garbage. And if
5242 last match is real best match, don't restore second
5244 else if (best_regs_set
&& !best_match_p
)
5247 /* Restore best match. It may happen that `dend ==
5248 end_match_1' while the restored d is in string2.
5249 For example, the pattern `x.*y.*z' against the
5250 strings `x-' and `y-z-', if the two strings are
5251 not consecutive in memory. */
5252 DEBUG_PRINT1 ("Restoring best registers.\n");
5255 dend
= ((d
>= string1
&& d
<= end1
)
5256 ? end_match_1
: end_match_2
);
5258 for (reg
= 1; reg
< num_regs
; reg
++)
5260 regstart
[reg
] = best_regstart
[reg
];
5261 regend
[reg
] = best_regend
[reg
];
5264 } /* d != end_match_2 */
5267 DEBUG_PRINT1 ("Accepting match.\n");
5269 /* If caller wants register contents data back, do it. */
5270 if (regs
&& !bufp
->no_sub
)
5272 /* Have the register data arrays been allocated? */
5273 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5274 { /* No. So allocate them with malloc. We need one
5275 extra element beyond `num_regs' for the `-1' marker
5277 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5278 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5279 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5280 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5285 bufp
->regs_allocated
= REGS_REALLOCATE
;
5287 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5288 { /* Yes. If we need more elements than were already
5289 allocated, reallocate them. If we need fewer, just
5291 if (regs
->num_regs
< num_regs
+ 1)
5293 regs
->num_regs
= num_regs
+ 1;
5294 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5295 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5296 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5305 /* These braces fend off a "empty body in an else-statement"
5306 warning under GCC when assert expands to nothing. */
5307 assert (bufp
->regs_allocated
== REGS_FIXED
);
5310 /* Convert the pointer data in `regstart' and `regend' to
5311 indices. Register zero has to be set differently,
5312 since we haven't kept track of any info for it. */
5313 if (regs
->num_regs
> 0)
5315 regs
->start
[0] = pos
;
5316 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5319 /* Go through the first `min (num_regs, regs->num_regs)'
5320 registers, since that is all we initialized. */
5321 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5323 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5324 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5328 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
5330 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
5334 /* If the regs structure we return has more elements than
5335 were in the pattern, set the extra elements to -1. If
5336 we (re)allocated the registers, this is the case,
5337 because we always allocate enough to have at least one
5339 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5340 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5341 } /* regs && !bufp->no_sub */
5343 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5344 nfailure_points_pushed
, nfailure_points_popped
,
5345 nfailure_points_pushed
- nfailure_points_popped
);
5346 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
5348 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
5350 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5356 /* Otherwise match next pattern command. */
5357 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5359 /* Ignore these. Used to ignore the n of succeed_n's which
5360 currently have n == 0. */
5362 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5366 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5369 /* Match the next n pattern characters exactly. The following
5370 byte in the pattern defines n, and the n bytes after that
5371 are the characters to match. */
5374 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5376 /* Remember the start point to rollback upon failure. */
5380 /* This is written out as an if-else so we don't waste time
5381 testing `translate' inside the loop. */
5382 if (RE_TRANSLATE_P (translate
))
5386 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5406 /* The cost of testing `translate' is comparatively small. */
5407 if (target_multibyte
)
5410 int pat_charlen
, buf_charlen
;
5415 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5418 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5421 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5423 if (TRANSLATE (buf_ch
) != pat_ch
)
5431 mcnt
-= pat_charlen
;
5443 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5444 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5451 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5452 if (! CHAR_BYTE8_P (buf_ch
))
5454 buf_ch
= TRANSLATE (buf_ch
);
5455 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5461 if (buf_ch
!= pat_ch
)
5474 /* Match any character except possibly a newline or a null. */
5480 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5483 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5485 buf_ch
= TRANSLATE (buf_ch
);
5487 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5489 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5490 && buf_ch
== '\000'))
5493 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5502 register unsigned int c
;
5503 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5506 /* Start of actual range_table, or end of bitmap if there is no
5508 re_char
*range_table
IF_LINT (= NULL
);
5510 /* Nonzero if there is a range table. */
5511 int range_table_exists
;
5513 /* Number of ranges of range table. This is not included
5514 in the initial byte-length of the command. */
5517 /* Whether matching against a unibyte character. */
5518 boolean unibyte_char
= false;
5520 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5522 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5524 if (range_table_exists
)
5526 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5527 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5531 c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5532 if (target_multibyte
)
5537 c1
= RE_CHAR_TO_UNIBYTE (c
);
5540 unibyte_char
= true;
5546 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5548 if (! CHAR_BYTE8_P (c1
))
5550 c1
= TRANSLATE (c1
);
5551 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5554 unibyte_char
= true;
5559 unibyte_char
= true;
5562 if (unibyte_char
&& c
< (1 << BYTEWIDTH
))
5563 { /* Lookup bitmap. */
5564 /* Cast to `unsigned' instead of `unsigned char' in
5565 case the bit list is a full 32 bytes long. */
5566 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5567 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5571 else if (range_table_exists
)
5573 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5575 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5576 | (class_bits
& BIT_MULTIBYTE
)
5577 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5578 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5579 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5580 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5583 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5587 if (range_table_exists
)
5588 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5590 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5592 if (!not) goto fail
;
5599 /* The beginning of a group is represented by start_memory.
5600 The argument is the register number. The text
5601 matched within the group is recorded (in the internal
5602 registers data structure) under the register number. */
5604 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5606 /* In case we need to undo this operation (via backtracking). */
5607 PUSH_FAILURE_REG ((unsigned int)*p
);
5610 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5611 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5613 /* Move past the register number and inner group count. */
5618 /* The stop_memory opcode represents the end of a group. Its
5619 argument is the same as start_memory's: the register number. */
5621 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5623 assert (!REG_UNSET (regstart
[*p
]));
5624 /* Strictly speaking, there should be code such as:
5626 assert (REG_UNSET (regend[*p]));
5627 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5629 But the only info to be pushed is regend[*p] and it is known to
5630 be UNSET, so there really isn't anything to push.
5631 Not pushing anything, on the other hand deprives us from the
5632 guarantee that regend[*p] is UNSET since undoing this operation
5633 will not reset its value properly. This is not important since
5634 the value will only be read on the next start_memory or at
5635 the very end and both events can only happen if this stop_memory
5639 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5641 /* Move past the register number and the inner group count. */
5646 /* \<digit> has been turned into a `duplicate' command which is
5647 followed by the numeric value of <digit> as the register number. */
5650 register re_char
*d2
, *dend2
;
5651 int regno
= *p
++; /* Get which register to match against. */
5652 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5654 /* Can't back reference a group which we've never matched. */
5655 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5658 /* Where in input to try to start matching. */
5659 d2
= regstart
[regno
];
5661 /* Remember the start point to rollback upon failure. */
5664 /* Where to stop matching; if both the place to start and
5665 the place to stop matching are in the same string, then
5666 set to the place to stop, otherwise, for now have to use
5667 the end of the first string. */
5669 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5670 == FIRST_STRING_P (regend
[regno
]))
5671 ? regend
[regno
] : end_match_1
);
5674 /* If necessary, advance to next segment in register
5678 if (dend2
== end_match_2
) break;
5679 if (dend2
== regend
[regno
]) break;
5681 /* End of string1 => advance to string2. */
5683 dend2
= regend
[regno
];
5685 /* At end of register contents => success */
5686 if (d2
== dend2
) break;
5688 /* If necessary, advance to next segment in data. */
5691 /* How many characters left in this segment to match. */
5694 /* Want how many consecutive characters we can match in
5695 one shot, so, if necessary, adjust the count. */
5696 if (mcnt
> dend2
- d2
)
5699 /* Compare that many; failure if mismatch, else move
5701 if (RE_TRANSLATE_P (translate
)
5702 ? bcmp_translate (d
, d2
, mcnt
, translate
, target_multibyte
)
5703 : memcmp (d
, d2
, mcnt
))
5708 d
+= mcnt
, d2
+= mcnt
;
5714 /* begline matches the empty string at the beginning of the string
5715 (unless `not_bol' is set in `bufp'), and after newlines. */
5717 DEBUG_PRINT1 ("EXECUTING begline.\n");
5719 if (AT_STRINGS_BEG (d
))
5721 if (!bufp
->not_bol
) break;
5726 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5730 /* In all other cases, we fail. */
5734 /* endline is the dual of begline. */
5736 DEBUG_PRINT1 ("EXECUTING endline.\n");
5738 if (AT_STRINGS_END (d
))
5740 if (!bufp
->not_eol
) break;
5744 PREFETCH_NOLIMIT ();
5751 /* Match at the very beginning of the data. */
5753 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5754 if (AT_STRINGS_BEG (d
))
5759 /* Match at the very end of the data. */
5761 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5762 if (AT_STRINGS_END (d
))
5767 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5768 pushes NULL as the value for the string on the stack. Then
5769 `POP_FAILURE_POINT' will keep the current value for the
5770 string, instead of restoring it. To see why, consider
5771 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5772 then the . fails against the \n. But the next thing we want
5773 to do is match the \n against the \n; if we restored the
5774 string value, we would be back at the foo.
5776 Because this is used only in specific cases, we don't need to
5777 check all the things that `on_failure_jump' does, to make
5778 sure the right things get saved on the stack. Hence we don't
5779 share its code. The only reason to push anything on the
5780 stack at all is that otherwise we would have to change
5781 `anychar's code to do something besides goto fail in this
5782 case; that seems worse than this. */
5783 case on_failure_keep_string_jump
:
5784 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5785 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5788 PUSH_FAILURE_POINT (p
- 3, NULL
);
5791 /* A nasty loop is introduced by the non-greedy *? and +?.
5792 With such loops, the stack only ever contains one failure point
5793 at a time, so that a plain on_failure_jump_loop kind of
5794 cycle detection cannot work. Worse yet, such a detection
5795 can not only fail to detect a cycle, but it can also wrongly
5796 detect a cycle (between different instantiations of the same
5798 So the method used for those nasty loops is a little different:
5799 We use a special cycle-detection-stack-frame which is pushed
5800 when the on_failure_jump_nastyloop failure-point is *popped*.
5801 This special frame thus marks the beginning of one iteration
5802 through the loop and we can hence easily check right here
5803 whether something matched between the beginning and the end of
5805 case on_failure_jump_nastyloop
:
5806 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5807 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5810 assert ((re_opcode_t
)p
[-4] == no_op
);
5813 CHECK_INFINITE_LOOP (p
- 4, d
);
5815 /* If there's a cycle, just continue without pushing
5816 this failure point. The failure point is the "try again"
5817 option, which shouldn't be tried.
5818 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5819 PUSH_FAILURE_POINT (p
- 3, d
);
5823 /* Simple loop detecting on_failure_jump: just check on the
5824 failure stack if the same spot was already hit earlier. */
5825 case on_failure_jump_loop
:
5827 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5828 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5832 CHECK_INFINITE_LOOP (p
- 3, d
);
5834 /* If there's a cycle, get out of the loop, as if the matching
5835 had failed. We used to just `goto fail' here, but that was
5836 aborting the search a bit too early: we want to keep the
5837 empty-loop-match and keep matching after the loop.
5838 We want (x?)*y\1z to match both xxyz and xxyxz. */
5841 PUSH_FAILURE_POINT (p
- 3, d
);
5846 /* Uses of on_failure_jump:
5848 Each alternative starts with an on_failure_jump that points
5849 to the beginning of the next alternative. Each alternative
5850 except the last ends with a jump that in effect jumps past
5851 the rest of the alternatives. (They really jump to the
5852 ending jump of the following alternative, because tensioning
5853 these jumps is a hassle.)
5855 Repeats start with an on_failure_jump that points past both
5856 the repetition text and either the following jump or
5857 pop_failure_jump back to this on_failure_jump. */
5858 case on_failure_jump
:
5859 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5860 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5863 PUSH_FAILURE_POINT (p
-3, d
);
5866 /* This operation is used for greedy *.
5867 Compare the beginning of the repeat with what in the
5868 pattern follows its end. If we can establish that there
5869 is nothing that they would both match, i.e., that we
5870 would have to backtrack because of (as in, e.g., `a*a')
5871 then we can use a non-backtracking loop based on
5872 on_failure_keep_string_jump instead of on_failure_jump. */
5873 case on_failure_jump_smart
:
5874 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5875 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5878 re_char
*p1
= p
; /* Next operation. */
5879 /* Here, we discard `const', making re_match non-reentrant. */
5880 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5881 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5883 p
-= 3; /* Reset so that we will re-execute the
5884 instruction once it's been changed. */
5886 EXTRACT_NUMBER (mcnt
, p2
- 2);
5888 /* Ensure this is a indeed the trivial kind of loop
5889 we are expecting. */
5890 assert (skip_one_char (p1
) == p2
- 3);
5891 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5892 DEBUG_STATEMENT (debug
+= 2);
5893 if (mutually_exclusive_p (bufp
, p1
, p2
))
5895 /* Use a fast `on_failure_keep_string_jump' loop. */
5896 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5897 *p3
= (unsigned char) on_failure_keep_string_jump
;
5898 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5902 /* Default to a safe `on_failure_jump' loop. */
5903 DEBUG_PRINT1 (" smart default => slow loop.\n");
5904 *p3
= (unsigned char) on_failure_jump
;
5906 DEBUG_STATEMENT (debug
-= 2);
5910 /* Unconditionally jump (without popping any failure points). */
5913 IMMEDIATE_QUIT_CHECK
;
5914 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5915 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5916 p
+= mcnt
; /* Do the jump. */
5917 DEBUG_PRINT2 ("(to %p).\n", p
);
5921 /* Have to succeed matching what follows at least n times.
5922 After that, handle like `on_failure_jump'. */
5924 /* Signedness doesn't matter since we only compare MCNT to 0. */
5925 EXTRACT_NUMBER (mcnt
, p
+ 2);
5926 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5928 /* Originally, mcnt is how many times we HAVE to succeed. */
5931 /* Here, we discard `const', making re_match non-reentrant. */
5932 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5935 PUSH_NUMBER (p2
, mcnt
);
5938 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5943 /* Signedness doesn't matter since we only compare MCNT to 0. */
5944 EXTRACT_NUMBER (mcnt
, p
+ 2);
5945 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5947 /* Originally, this is how many times we CAN jump. */
5950 /* Here, we discard `const', making re_match non-reentrant. */
5951 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5953 PUSH_NUMBER (p2
, mcnt
);
5954 goto unconditional_jump
;
5956 /* If don't have to jump any more, skip over the rest of command. */
5963 unsigned char *p2
; /* Location of the counter. */
5964 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5966 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5967 /* Here, we discard `const', making re_match non-reentrant. */
5968 p2
= (unsigned char*) p
+ mcnt
;
5969 /* Signedness doesn't matter since we only copy MCNT's bits . */
5970 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5971 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5972 PUSH_NUMBER (p2
, mcnt
);
5979 boolean
not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5980 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5982 /* We SUCCEED (or FAIL) in one of the following cases: */
5984 /* Case 1: D is at the beginning or the end of string. */
5985 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5989 /* C1 is the character before D, S1 is the syntax of C1, C2
5990 is the character at D, and S2 is the syntax of C2. */
5995 ssize_t offset
= PTR_TO_OFFSET (d
- 1);
5996 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5997 UPDATE_SYNTAX_TABLE (charpos
);
5999 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6002 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6004 PREFETCH_NOLIMIT ();
6005 GET_CHAR_AFTER (c2
, d
, dummy
);
6008 if (/* Case 2: Only one of S1 and S2 is Sword. */
6009 ((s1
== Sword
) != (s2
== Sword
))
6010 /* Case 3: Both of S1 and S2 are Sword, and macro
6011 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
6012 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
6022 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
6024 /* We FAIL in one of the following cases: */
6026 /* Case 1: D is at the end of string. */
6027 if (AT_STRINGS_END (d
))
6031 /* C1 is the character before D, S1 is the syntax of C1, C2
6032 is the character at D, and S2 is the syntax of C2. */
6037 ssize_t offset
= PTR_TO_OFFSET (d
);
6038 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6039 UPDATE_SYNTAX_TABLE (charpos
);
6042 GET_CHAR_AFTER (c2
, d
, dummy
);
6045 /* Case 2: S2 is not Sword. */
6049 /* Case 3: D is not at the beginning of string ... */
6050 if (!AT_STRINGS_BEG (d
))
6052 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6054 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6058 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6060 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6067 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6069 /* We FAIL in one of the following cases: */
6071 /* Case 1: D is at the beginning of string. */
6072 if (AT_STRINGS_BEG (d
))
6076 /* C1 is the character before D, S1 is the syntax of C1, C2
6077 is the character at D, and S2 is the syntax of C2. */
6082 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6083 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6084 UPDATE_SYNTAX_TABLE (charpos
);
6086 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6089 /* Case 2: S1 is not Sword. */
6093 /* Case 3: D is not at the end of string ... */
6094 if (!AT_STRINGS_END (d
))
6096 PREFETCH_NOLIMIT ();
6097 GET_CHAR_AFTER (c2
, d
, dummy
);
6099 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6103 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6105 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6112 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6114 /* We FAIL in one of the following cases: */
6116 /* Case 1: D is at the end of string. */
6117 if (AT_STRINGS_END (d
))
6121 /* C1 is the character before D, S1 is the syntax of C1, C2
6122 is the character at D, and S2 is the syntax of C2. */
6126 ssize_t offset
= PTR_TO_OFFSET (d
);
6127 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6128 UPDATE_SYNTAX_TABLE (charpos
);
6131 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6134 /* Case 2: S2 is neither Sword nor Ssymbol. */
6135 if (s2
!= Sword
&& s2
!= Ssymbol
)
6138 /* Case 3: D is not at the beginning of string ... */
6139 if (!AT_STRINGS_BEG (d
))
6141 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6143 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6147 /* ... and S1 is Sword or Ssymbol. */
6148 if (s1
== Sword
|| s1
== Ssymbol
)
6155 DEBUG_PRINT1 ("EXECUTING symend.\n");
6157 /* We FAIL in one of the following cases: */
6159 /* Case 1: D is at the beginning of string. */
6160 if (AT_STRINGS_BEG (d
))
6164 /* C1 is the character before D, S1 is the syntax of C1, C2
6165 is the character at D, and S2 is the syntax of C2. */
6169 ssize_t offset
= PTR_TO_OFFSET (d
) - 1;
6170 ssize_t charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6171 UPDATE_SYNTAX_TABLE (charpos
);
6173 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6176 /* Case 2: S1 is neither Ssymbol nor Sword. */
6177 if (s1
!= Sword
&& s1
!= Ssymbol
)
6180 /* Case 3: D is not at the end of string ... */
6181 if (!AT_STRINGS_END (d
))
6183 PREFETCH_NOLIMIT ();
6184 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6186 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6190 /* ... and S2 is Sword or Ssymbol. */
6191 if (s2
== Sword
|| s2
== Ssymbol
)
6200 boolean
not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6202 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
6206 ssize_t offset
= PTR_TO_OFFSET (d
);
6207 ssize_t pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6208 UPDATE_SYNTAX_TABLE (pos1
);
6215 GET_CHAR_AFTER (c
, d
, len
);
6216 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6225 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6226 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6231 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6232 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6237 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6238 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6243 case notcategoryspec
:
6245 boolean
not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6247 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n",
6248 not?"not":"", mcnt
);
6254 GET_CHAR_AFTER (c
, d
, len
);
6255 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6267 continue; /* Successfully executed one pattern command; keep going. */
6270 /* We goto here if a matching operation fails. */
6272 IMMEDIATE_QUIT_CHECK
;
6273 if (!FAIL_STACK_EMPTY ())
6276 /* A restart point is known. Restore to that state. */
6277 DEBUG_PRINT1 ("\nFAIL:\n");
6278 POP_FAILURE_POINT (str
, pat
);
6279 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
6281 case on_failure_keep_string_jump
:
6282 assert (str
== NULL
);
6283 goto continue_failure_jump
;
6285 case on_failure_jump_nastyloop
:
6286 assert ((re_opcode_t
)pat
[-2] == no_op
);
6287 PUSH_FAILURE_POINT (pat
- 2, str
);
6290 case on_failure_jump_loop
:
6291 case on_failure_jump
:
6294 continue_failure_jump
:
6295 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6300 /* A special frame used for nastyloops. */
6307 assert (p
>= bufp
->buffer
&& p
<= pend
);
6309 if (d
>= string1
&& d
<= end1
)
6313 break; /* Matching at this starting point really fails. */
6317 goto restore_best_regs
;
6321 return -1; /* Failure to match. */
6324 /* Subroutine definitions for re_match_2. */
6326 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6327 bytes; nonzero otherwise. */
6330 bcmp_translate (const re_char
*s1
, const re_char
*s2
, register ssize_t len
,
6331 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6333 register re_char
*p1
= s1
, *p2
= s2
;
6334 re_char
*p1_end
= s1
+ len
;
6335 re_char
*p2_end
= s2
+ len
;
6337 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6338 different lengths, but relying on a single `len' would break this. -sm */
6339 while (p1
< p1_end
&& p2
< p2_end
)
6341 int p1_charlen
, p2_charlen
;
6342 re_wchar_t p1_ch
, p2_ch
;
6344 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6345 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6347 if (RE_TRANSLATE (translate
, p1_ch
)
6348 != RE_TRANSLATE (translate
, p2_ch
))
6351 p1
+= p1_charlen
, p2
+= p2_charlen
;
6354 if (p1
!= p1_end
|| p2
!= p2_end
)
6360 /* Entry points for GNU code. */
6362 /* re_compile_pattern is the GNU regular expression compiler: it
6363 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6364 Returns 0 if the pattern was valid, otherwise an error string.
6366 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6367 are set in BUFP on entry.
6369 We call regex_compile to do the actual compilation. */
6372 re_compile_pattern (const char *pattern
, size_t length
,
6373 struct re_pattern_buffer
*bufp
)
6377 /* GNU code is written to assume at least RE_NREGS registers will be set
6378 (and at least one extra will be -1). */
6379 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6381 /* And GNU code determines whether or not to get register information
6382 by passing null for the REGS argument to re_match, etc., not by
6386 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6390 return gettext (re_error_msgid
[(int) ret
]);
6392 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6394 /* Entry points compatible with 4.2 BSD regex library. We don't define
6395 them unless specifically requested. */
6397 #if defined _REGEX_RE_COMP || defined _LIBC
6399 /* BSD has one and only one pattern buffer. */
6400 static struct re_pattern_buffer re_comp_buf
;
6404 /* Make these definitions weak in libc, so POSIX programs can redefine
6405 these names if they don't use our functions, and still use
6406 regcomp/regexec below without link errors. */
6416 if (!re_comp_buf
.buffer
)
6417 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6418 return (char *) gettext ("No previous regular expression");
6422 if (!re_comp_buf
.buffer
)
6424 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
6425 if (re_comp_buf
.buffer
== NULL
)
6426 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6427 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6428 re_comp_buf
.allocated
= 200;
6430 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6431 if (re_comp_buf
.fastmap
== NULL
)
6432 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6433 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6436 /* Since `re_exec' always passes NULL for the `regs' argument, we
6437 don't need to initialize the pattern buffer fields which affect it. */
6439 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6444 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6445 return (char *) gettext (re_error_msgid
[(int) ret
]);
6453 re_exec (const char *s
)
6455 const size_t len
= strlen (s
);
6457 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
6459 #endif /* _REGEX_RE_COMP */
6461 /* POSIX.2 functions. Don't define these for Emacs. */
6465 /* regcomp takes a regular expression as a string and compiles it.
6467 PREG is a regex_t *. We do not expect any fields to be initialized,
6468 since POSIX says we shouldn't. Thus, we set
6470 `buffer' to the compiled pattern;
6471 `used' to the length of the compiled pattern;
6472 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6473 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6474 RE_SYNTAX_POSIX_BASIC;
6475 `fastmap' to an allocated space for the fastmap;
6476 `fastmap_accurate' to zero;
6477 `re_nsub' to the number of subexpressions in PATTERN.
6479 PATTERN is the address of the pattern string.
6481 CFLAGS is a series of bits which affect compilation.
6483 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6484 use POSIX basic syntax.
6486 If REG_NEWLINE is set, then . and [^...] don't match newline.
6487 Also, regexec will try a match beginning after every newline.
6489 If REG_ICASE is set, then we considers upper- and lowercase
6490 versions of letters to be equivalent when matching.
6492 If REG_NOSUB is set, then when PREG is passed to regexec, that
6493 routine will report only success or failure, and nothing about the
6496 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6497 the return codes and their meanings.) */
6500 regcomp (regex_t
*__restrict preg
, const char *__restrict pattern
,
6505 = (cflags
& REG_EXTENDED
) ?
6506 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6508 /* regex_compile will allocate the space for the compiled pattern. */
6510 preg
->allocated
= 0;
6513 /* Try to allocate space for the fastmap. */
6514 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6516 if (cflags
& REG_ICASE
)
6521 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6522 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6523 if (preg
->translate
== NULL
)
6524 return (int) REG_ESPACE
;
6526 /* Map uppercase characters to corresponding lowercase ones. */
6527 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6528 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6531 preg
->translate
= NULL
;
6533 /* If REG_NEWLINE is set, newlines are treated differently. */
6534 if (cflags
& REG_NEWLINE
)
6535 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6536 syntax
&= ~RE_DOT_NEWLINE
;
6537 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6540 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6542 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6544 /* POSIX says a null character in the pattern terminates it, so we
6545 can use strlen here in compiling the pattern. */
6546 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6548 /* POSIX doesn't distinguish between an unmatched open-group and an
6549 unmatched close-group: both are REG_EPAREN. */
6550 if (ret
== REG_ERPAREN
)
6553 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6554 { /* Compute the fastmap now, since regexec cannot modify the pattern
6556 re_compile_fastmap (preg
);
6557 if (preg
->can_be_null
)
6558 { /* The fastmap can't be used anyway. */
6559 free (preg
->fastmap
);
6560 preg
->fastmap
= NULL
;
6565 WEAK_ALIAS (__regcomp
, regcomp
)
6568 /* regexec searches for a given pattern, specified by PREG, in the
6571 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6572 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6573 least NMATCH elements, and we set them to the offsets of the
6574 corresponding matched substrings.
6576 EFLAGS specifies `execution flags' which affect matching: if
6577 REG_NOTBOL is set, then ^ does not match at the beginning of the
6578 string; if REG_NOTEOL is set, then $ does not match at the end.
6580 We return 0 if we find a match and REG_NOMATCH if not. */
6583 regexec (const regex_t
*__restrict preg
, const char *__restrict string
,
6584 size_t nmatch
, regmatch_t pmatch
[__restrict_arr
], int eflags
)
6587 struct re_registers regs
;
6588 regex_t private_preg
;
6589 size_t len
= strlen (string
);
6590 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6592 private_preg
= *preg
;
6594 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6595 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6597 /* The user has told us exactly how many registers to return
6598 information about, via `nmatch'. We have to pass that on to the
6599 matching routines. */
6600 private_preg
.regs_allocated
= REGS_FIXED
;
6604 regs
.num_regs
= nmatch
;
6605 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6606 if (regs
.start
== NULL
)
6608 regs
.end
= regs
.start
+ nmatch
;
6611 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6612 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6613 was a little bit longer but still only matching the real part.
6614 This works because the `endline' will check for a '\n' and will find a
6615 '\0', correctly deciding that this is not the end of a line.
6616 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6617 a convenient '\0' there. For all we know, the string could be preceded
6618 by '\n' which would throw things off. */
6620 /* Perform the searching operation. */
6621 ret
= re_search (&private_preg
, string
, len
,
6622 /* start: */ 0, /* range: */ len
,
6623 want_reg_info
? ®s
: (struct re_registers
*) 0);
6625 /* Copy the register information to the POSIX structure. */
6632 for (r
= 0; r
< nmatch
; r
++)
6634 pmatch
[r
].rm_so
= regs
.start
[r
];
6635 pmatch
[r
].rm_eo
= regs
.end
[r
];
6639 /* If we needed the temporary register info, free the space now. */
6643 /* We want zero return to mean success, unlike `re_search'. */
6644 return ret
>= 0 ? REG_NOERROR
: REG_NOMATCH
;
6646 WEAK_ALIAS (__regexec
, regexec
)
6649 /* Returns a message corresponding to an error code, ERR_CODE, returned
6650 from either regcomp or regexec. We don't use PREG here.
6652 ERR_CODE was previously called ERRCODE, but that name causes an
6653 error with msvc8 compiler. */
6656 regerror (int err_code
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
6662 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6663 /* Only error codes returned by the rest of the code should be passed
6664 to this routine. If we are given anything else, or if other regex
6665 code generates an invalid error code, then the program has a bug.
6666 Dump core so we can fix it. */
6669 msg
= gettext (re_error_msgid
[err_code
]);
6671 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6673 if (errbuf_size
!= 0)
6675 if (msg_size
> errbuf_size
)
6677 strncpy (errbuf
, msg
, errbuf_size
- 1);
6678 errbuf
[errbuf_size
- 1] = 0;
6681 strcpy (errbuf
, msg
);
6686 WEAK_ALIAS (__regerror
, regerror
)
6689 /* Free dynamically allocated space used by PREG. */
6692 regfree (regex_t
*preg
)
6694 free (preg
->buffer
);
6695 preg
->buffer
= NULL
;
6697 preg
->allocated
= 0;
6700 free (preg
->fastmap
);
6701 preg
->fastmap
= NULL
;
6702 preg
->fastmap_accurate
= 0;
6704 free (preg
->translate
);
6705 preg
->translate
= NULL
;
6707 WEAK_ALIAS (__regfree
, regfree
)
6709 #endif /* not emacs */