1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
6 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
24 - structure the opcode space into opcode+flag.
25 - merge with glibc's regex.[ch].
26 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
27 need to modify the compiled regexp so that re_match can be reentrant.
28 - get rid of on_failure_jump_smart by doing the optimization in re_comp
29 rather than at run-time, so that re_match can be reentrant.
32 /* AIX requires this to be the first thing in the file. */
33 #if defined _AIX && !defined REGEX_MALLOC
41 #if defined STDC_HEADERS && !defined emacs
44 /* We need this for `regex.h', and perhaps for the Emacs include files. */
45 # include <sys/types.h>
48 /* Whether to use ISO C Amendment 1 wide char functions.
49 Those should not be used for Emacs since it uses its own. */
51 #define WIDE_CHAR_SUPPORT 1
53 #define WIDE_CHAR_SUPPORT \
54 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
57 /* For platform which support the ISO C amendement 1 functionality we
58 support user defined character classes. */
60 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
66 /* We have to keep the namespace clean. */
67 # define regfree(preg) __regfree (preg)
68 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
69 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
70 # define regerror(errcode, preg, errbuf, errbuf_size) \
71 __regerror(errcode, preg, errbuf, errbuf_size)
72 # define re_set_registers(bu, re, nu, st, en) \
73 __re_set_registers (bu, re, nu, st, en)
74 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
75 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
76 # define re_match(bufp, string, size, pos, regs) \
77 __re_match (bufp, string, size, pos, regs)
78 # define re_search(bufp, string, size, startpos, range, regs) \
79 __re_search (bufp, string, size, startpos, range, regs)
80 # define re_compile_pattern(pattern, length, bufp) \
81 __re_compile_pattern (pattern, length, bufp)
82 # define re_set_syntax(syntax) __re_set_syntax (syntax)
83 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
84 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
85 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
87 /* Make sure we call libc's function even if the user overrides them. */
88 # define btowc __btowc
89 # define iswctype __iswctype
90 # define wctype __wctype
92 # define WEAK_ALIAS(a,b) weak_alias (a, b)
94 /* We are also using some library internals. */
95 # include <locale/localeinfo.h>
96 # include <locale/elem-hash.h>
97 # include <langinfo.h>
99 # define WEAK_ALIAS(a,b)
102 /* This is for other GNU distributions with internationalized messages. */
103 #if HAVE_LIBINTL_H || defined _LIBC
104 # include <libintl.h>
106 # define gettext(msgid) (msgid)
110 /* This define is so xgettext can find the internationalizable
112 # define gettext_noop(String) String
115 /* The `emacs' switch turns on certain matching commands
116 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, s) \
149 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
150 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
151 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
153 /* Set C a (possibly converted to multibyte) character before P. P
154 points into a string which is the virtual concatenation of STR1
155 (which ends at END1) or STR2 (which ends at END2). */
156 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
160 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
161 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
162 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
163 c = STRING_CHAR (dtemp, (p) - dtemp); \
167 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
168 MAKE_CHAR_MULTIBYTE (c); \
172 /* Set C a (possibly converted to multibyte) character at P, and set
173 LEN to the byte length of that character. */
174 # define GET_CHAR_AFTER(c, p, len) \
177 c = STRING_CHAR_AND_LENGTH (p, 0, len); \
182 MAKE_CHAR_MULTIBYTE (c); \
186 #else /* not emacs */
188 /* If we are not linking with Emacs proper,
189 we can't use the relocating allocator
190 even if config.h says that we can. */
193 # if defined STDC_HEADERS || defined _LIBC
200 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
201 If nothing else has been done, use the method below. */
202 # ifdef INHIBIT_STRING_HEADER
203 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
204 # if !defined bzero && !defined bcopy
205 # undef INHIBIT_STRING_HEADER
210 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
211 This is used in most programs--a few other programs avoid this
212 by defining INHIBIT_STRING_HEADER. */
213 # ifndef INHIBIT_STRING_HEADER
214 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
218 # define bzero(s, n) (memset (s, '\0', n), (s))
220 # define bzero(s, n) __bzero (s, n)
224 # include <strings.h>
226 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
229 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
234 /* Define the syntax stuff for \<, \>, etc. */
236 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
237 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1, Ssymbol
= 2 };
239 # ifdef SWITCH_ENUM_BUG
240 # define SWITCH_ENUM_CAST(x) ((int)(x))
242 # define SWITCH_ENUM_CAST(x) (x)
245 /* Dummy macros for non-Emacs environments. */
246 # define BASE_LEADING_CODE_P(c) (0)
247 # define CHAR_CHARSET(c) 0
248 # define CHARSET_LEADING_CODE_BASE(c) 0
249 # define MAX_MULTIBYTE_LENGTH 1
250 # define RE_MULTIBYTE_P(x) 0
251 # define RE_TARGET_MULTIBYTE_P(x) 0
252 # define WORD_BOUNDARY_P(c1, c2) (0)
253 # define CHAR_HEAD_P(p) (1)
254 # define SINGLE_BYTE_CHAR_P(c) (1)
255 # define SAME_CHARSET_P(c1, c2) (1)
256 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
257 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
258 # define STRING_CHAR(p, s) (*(p))
259 # define RE_STRING_CHAR STRING_CHAR
260 # define CHAR_STRING(c, s) (*(s) = (c), 1)
261 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
262 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
263 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
264 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
265 # define GET_CHAR_AFTER(c, p, len) \
267 # define MAKE_CHAR(charset, c1, c2) (c1)
268 # define BYTE8_TO_CHAR(c) (c)
269 # define CHAR_BYTE8_P(c) (0)
270 # define MAKE_CHAR_MULTIBYTE(c) (c)
271 # define MAKE_CHAR_UNIBYTE(c) (c)
272 # define CHAR_LEADING_CODE(c) (c)
274 #endif /* not emacs */
277 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
278 # define RE_TRANSLATE_P(TBL) (TBL)
281 /* Get the interface, including the syntax bits. */
284 /* isalpha etc. are used for the character classes. */
289 /* 1 if C is an ASCII character. */
290 # define IS_REAL_ASCII(c) ((c) < 0200)
292 /* 1 if C is a unibyte character. */
293 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
295 /* The Emacs definitions should not be directly affected by locales. */
297 /* In Emacs, these are only used for single-byte characters. */
298 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
299 # define ISCNTRL(c) ((c) < ' ')
300 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
301 || ((c) >= 'a' && (c) <= 'f') \
302 || ((c) >= 'A' && (c) <= 'F'))
304 /* This is only used for single-byte characters. */
305 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
307 /* The rest must handle multibyte characters. */
309 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
310 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
313 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
314 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
317 # define ISALNUM(c) (IS_REAL_ASCII (c) \
318 ? (((c) >= 'a' && (c) <= 'z') \
319 || ((c) >= 'A' && (c) <= 'Z') \
320 || ((c) >= '0' && (c) <= '9')) \
321 : SYNTAX (c) == Sword)
323 # define ISALPHA(c) (IS_REAL_ASCII (c) \
324 ? (((c) >= 'a' && (c) <= 'z') \
325 || ((c) >= 'A' && (c) <= 'Z')) \
326 : SYNTAX (c) == Sword)
328 # define ISLOWER(c) (LOWERCASEP (c))
330 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
331 ? ((c) > ' ' && (c) < 0177 \
332 && !(((c) >= 'a' && (c) <= 'z') \
333 || ((c) >= 'A' && (c) <= 'Z') \
334 || ((c) >= '0' && (c) <= '9'))) \
335 : SYNTAX (c) != Sword)
337 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
339 # define ISUPPER(c) (UPPERCASEP (c))
341 # define ISWORD(c) (SYNTAX (c) == Sword)
343 #else /* not emacs */
345 /* Jim Meyering writes:
347 "... Some ctype macros are valid only for character codes that
348 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
349 using /bin/cc or gcc but without giving an ansi option). So, all
350 ctype uses should be through macros like ISPRINT... If
351 STDC_HEADERS is defined, then autoconf has verified that the ctype
352 macros don't need to be guarded with references to isascii. ...
353 Defining isascii to 1 should let any compiler worth its salt
354 eliminate the && through constant folding."
355 Solaris defines some of these symbols so we must undefine them first. */
358 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
359 # define ISASCII(c) 1
361 # define ISASCII(c) isascii(c)
364 /* 1 if C is an ASCII character. */
365 # define IS_REAL_ASCII(c) ((c) < 0200)
367 /* This distinction is not meaningful, except in Emacs. */
368 # define ISUNIBYTE(c) 1
371 # define ISBLANK(c) (ISASCII (c) && isblank (c))
373 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
376 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
378 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
382 # define ISPRINT(c) (ISASCII (c) && isprint (c))
383 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
384 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
385 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
386 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
387 # define ISLOWER(c) (ISASCII (c) && islower (c))
388 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
389 # define ISSPACE(c) (ISASCII (c) && isspace (c))
390 # define ISUPPER(c) (ISASCII (c) && isupper (c))
391 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
393 # define ISWORD(c) ISALPHA(c)
396 # define TOLOWER(c) _tolower(c)
398 # define TOLOWER(c) tolower(c)
401 /* How many characters in the character set. */
402 # define CHAR_SET_SIZE 256
406 extern char *re_syntax_table
;
408 # else /* not SYNTAX_TABLE */
410 static char re_syntax_table
[CHAR_SET_SIZE
];
421 bzero (re_syntax_table
, sizeof re_syntax_table
);
423 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
425 re_syntax_table
[c
] = Sword
;
427 re_syntax_table
['_'] = Ssymbol
;
432 # endif /* not SYNTAX_TABLE */
434 # define SYNTAX(c) re_syntax_table[(c)]
436 #endif /* not emacs */
439 # define NULL (void *)0
442 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
443 since ours (we hope) works properly with all combinations of
444 machines, compilers, `char' and `unsigned char' argument types.
445 (Per Bothner suggested the basic approach.) */
446 #undef SIGN_EXTEND_CHAR
448 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
449 #else /* not __STDC__ */
450 /* As in Harbison and Steele. */
451 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
454 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
455 use `alloca' instead of `malloc'. This is because using malloc in
456 re_search* or re_match* could cause memory leaks when C-g is used in
457 Emacs; also, malloc is slower and causes storage fragmentation. On
458 the other hand, malloc is more portable, and easier to debug.
460 Because we sometimes use alloca, some routines have to be macros,
461 not functions -- `alloca'-allocated space disappears at the end of the
462 function it is called in. */
466 # define REGEX_ALLOCATE malloc
467 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
468 # define REGEX_FREE free
470 #else /* not REGEX_MALLOC */
472 /* Emacs already defines alloca, sometimes. */
475 /* Make alloca work the best possible way. */
477 # define alloca __builtin_alloca
478 # else /* not __GNUC__ */
479 # ifdef HAVE_ALLOCA_H
481 # endif /* HAVE_ALLOCA_H */
482 # endif /* not __GNUC__ */
484 # endif /* not alloca */
486 # define REGEX_ALLOCATE alloca
488 /* Assumes a `char *destination' variable. */
489 # define REGEX_REALLOCATE(source, osize, nsize) \
490 (destination = (char *) alloca (nsize), \
491 memcpy (destination, source, osize))
493 /* No need to do anything to free, after alloca. */
494 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
496 #endif /* not REGEX_MALLOC */
498 /* Define how to allocate the failure stack. */
500 #if defined REL_ALLOC && defined REGEX_MALLOC
502 # define REGEX_ALLOCATE_STACK(size) \
503 r_alloc (&failure_stack_ptr, (size))
504 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
505 r_re_alloc (&failure_stack_ptr, (nsize))
506 # define REGEX_FREE_STACK(ptr) \
507 r_alloc_free (&failure_stack_ptr)
509 #else /* not using relocating allocator */
513 # define REGEX_ALLOCATE_STACK malloc
514 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
515 # define REGEX_FREE_STACK free
517 # else /* not REGEX_MALLOC */
519 # define REGEX_ALLOCATE_STACK alloca
521 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
522 REGEX_REALLOCATE (source, osize, nsize)
523 /* No need to explicitly free anything. */
524 # define REGEX_FREE_STACK(arg) ((void)0)
526 # endif /* not REGEX_MALLOC */
527 #endif /* not using relocating allocator */
530 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
531 `string1' or just past its end. This works if PTR is NULL, which is
533 #define FIRST_STRING_P(ptr) \
534 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
536 /* (Re)Allocate N items of type T using malloc, or fail. */
537 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
538 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
539 #define RETALLOC_IF(addr, n, t) \
540 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
541 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
543 #define BYTEWIDTH 8 /* In bits. */
545 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
549 #define MAX(a, b) ((a) > (b) ? (a) : (b))
550 #define MIN(a, b) ((a) < (b) ? (a) : (b))
552 /* Type of source-pattern and string chars. */
553 typedef const unsigned char re_char
;
555 typedef char boolean
;
559 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
560 re_char
*string1
, int size1
,
561 re_char
*string2
, int size2
,
563 struct re_registers
*regs
,
566 /* These are the command codes that appear in compiled regular
567 expressions. Some opcodes are followed by argument bytes. A
568 command code can specify any interpretation whatsoever for its
569 arguments. Zero bytes may appear in the compiled regular expression. */
575 /* Succeed right away--no more backtracking. */
578 /* Followed by one byte giving n, then by n literal bytes. */
581 /* Matches any (more or less) character. */
584 /* Matches any one char belonging to specified set. First
585 following byte is number of bitmap bytes. Then come bytes
586 for a bitmap saying which chars are in. Bits in each byte
587 are ordered low-bit-first. A character is in the set if its
588 bit is 1. A character too large to have a bit in the map is
589 automatically not in the set.
591 If the length byte has the 0x80 bit set, then that stuff
592 is followed by a range table:
593 2 bytes of flags for character sets (low 8 bits, high 8 bits)
594 See RANGE_TABLE_WORK_BITS below.
595 2 bytes, the number of pairs that follow (upto 32767)
596 pairs, each 2 multibyte characters,
597 each multibyte character represented as 3 bytes. */
600 /* Same parameters as charset, but match any character that is
601 not one of those specified. */
604 /* Start remembering the text that is matched, for storing in a
605 register. Followed by one byte with the register number, in
606 the range 0 to one less than the pattern buffer's re_nsub
610 /* Stop remembering the text that is matched and store it in a
611 memory register. Followed by one byte with the register
612 number, in the range 0 to one less than `re_nsub' in the
616 /* Match a duplicate of something remembered. Followed by one
617 byte containing the register number. */
620 /* Fail unless at beginning of line. */
623 /* Fail unless at end of line. */
626 /* Succeeds if at beginning of buffer (if emacs) or at beginning
627 of string to be matched (if not). */
630 /* Analogously, for end of buffer/string. */
633 /* Followed by two byte relative address to which to jump. */
636 /* Followed by two-byte relative address of place to resume at
637 in case of failure. */
640 /* Like on_failure_jump, but pushes a placeholder instead of the
641 current string position when executed. */
642 on_failure_keep_string_jump
,
644 /* Just like `on_failure_jump', except that it checks that we
645 don't get stuck in an infinite loop (matching an empty string
647 on_failure_jump_loop
,
649 /* Just like `on_failure_jump_loop', except that it checks for
650 a different kind of loop (the kind that shows up with non-greedy
651 operators). This operation has to be immediately preceded
653 on_failure_jump_nastyloop
,
655 /* A smart `on_failure_jump' used for greedy * and + operators.
656 It analyses the loop before which it is put and if the
657 loop does not require backtracking, it changes itself to
658 `on_failure_keep_string_jump' and short-circuits the loop,
659 else it just defaults to changing itself into `on_failure_jump'.
660 It assumes that it is pointing to just past a `jump'. */
661 on_failure_jump_smart
,
663 /* Followed by two-byte relative address and two-byte number n.
664 After matching N times, jump to the address upon failure.
665 Does not work if N starts at 0: use on_failure_jump_loop
669 /* Followed by two-byte relative address, and two-byte number n.
670 Jump to the address N times, then fail. */
673 /* Set the following two-byte relative address to the
674 subsequent two-byte number. The address *includes* the two
678 wordbeg
, /* Succeeds if at word beginning. */
679 wordend
, /* Succeeds if at word end. */
681 wordbound
, /* Succeeds if at a word boundary. */
682 notwordbound
, /* Succeeds if not at a word boundary. */
684 symbeg
, /* Succeeds if at symbol beginning. */
685 symend
, /* Succeeds if at symbol end. */
687 /* Matches any character whose syntax is specified. Followed by
688 a byte which contains a syntax code, e.g., Sword. */
691 /* Matches any character whose syntax is not that specified. */
695 ,before_dot
, /* Succeeds if before point. */
696 at_dot
, /* Succeeds if at point. */
697 after_dot
, /* Succeeds if after point. */
699 /* Matches any character whose category-set contains the specified
700 category. The operator is followed by a byte which contains a
701 category code (mnemonic ASCII character). */
704 /* Matches any character whose category-set does not contain the
705 specified category. The operator is followed by a byte which
706 contains the category code (mnemonic ASCII character). */
711 /* Common operations on the compiled pattern. */
713 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
715 #define STORE_NUMBER(destination, number) \
717 (destination)[0] = (number) & 0377; \
718 (destination)[1] = (number) >> 8; \
721 /* Same as STORE_NUMBER, except increment DESTINATION to
722 the byte after where the number is stored. Therefore, DESTINATION
723 must be an lvalue. */
725 #define STORE_NUMBER_AND_INCR(destination, number) \
727 STORE_NUMBER (destination, number); \
728 (destination) += 2; \
731 /* Put into DESTINATION a number stored in two contiguous bytes starting
734 #define EXTRACT_NUMBER(destination, source) \
736 (destination) = *(source) & 0377; \
737 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
741 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
743 extract_number (dest
, source
)
747 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
748 *dest
= *source
& 0377;
752 # ifndef EXTRACT_MACROS /* To debug the macros. */
753 # undef EXTRACT_NUMBER
754 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
755 # endif /* not EXTRACT_MACROS */
759 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
760 SOURCE must be an lvalue. */
762 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
764 EXTRACT_NUMBER (destination, source); \
769 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
772 extract_number_and_incr (destination
, source
)
776 extract_number (destination
, *source
);
780 # ifndef EXTRACT_MACROS
781 # undef EXTRACT_NUMBER_AND_INCR
782 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
783 extract_number_and_incr (&dest, &src)
784 # endif /* not EXTRACT_MACROS */
788 /* Store a multibyte character in three contiguous bytes starting
789 DESTINATION, and increment DESTINATION to the byte after where the
790 character is stored. Therefore, DESTINATION must be an lvalue. */
792 #define STORE_CHARACTER_AND_INCR(destination, character) \
794 (destination)[0] = (character) & 0377; \
795 (destination)[1] = ((character) >> 8) & 0377; \
796 (destination)[2] = (character) >> 16; \
797 (destination) += 3; \
800 /* Put into DESTINATION a character stored in three contiguous bytes
801 starting at SOURCE. */
803 #define EXTRACT_CHARACTER(destination, source) \
805 (destination) = ((source)[0] \
806 | ((source)[1] << 8) \
807 | ((source)[2] << 16)); \
811 /* Macros for charset. */
813 /* Size of bitmap of charset P in bytes. P is a start of charset,
814 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
815 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
817 /* Nonzero if charset P has range table. */
818 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
820 /* Return the address of range table of charset P. But not the start
821 of table itself, but the before where the number of ranges is
822 stored. `2 +' means to skip re_opcode_t and size of bitmap,
823 and the 2 bytes of flags at the start of the range table. */
824 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
826 /* Extract the bit flags that start a range table. */
827 #define CHARSET_RANGE_TABLE_BITS(p) \
828 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
829 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
831 /* Test if C is listed in the bitmap of charset P. */
832 #define CHARSET_LOOKUP_BITMAP(p, c) \
833 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
834 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
836 /* Return the address of end of RANGE_TABLE. COUNT is number of
837 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
838 is start of range and end of range. `* 3' is size of each start
840 #define CHARSET_RANGE_TABLE_END(range_table, count) \
841 ((range_table) + (count) * 2 * 3)
843 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
844 COUNT is number of ranges in RANGE_TABLE. */
845 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
848 re_wchar_t range_start, range_end; \
850 re_char *range_table_end \
851 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
853 for (p = (range_table); p < range_table_end; p += 2 * 3) \
855 EXTRACT_CHARACTER (range_start, p); \
856 EXTRACT_CHARACTER (range_end, p + 3); \
858 if (range_start <= (c) && (c) <= range_end) \
867 /* Test if C is in range table of CHARSET. The flag NOT is negated if
868 C is listed in it. */
869 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
872 /* Number of ranges in range table. */ \
874 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
876 EXTRACT_NUMBER_AND_INCR (count, range_table); \
877 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
881 /* If DEBUG is defined, Regex prints many voluminous messages about what
882 it is doing (if the variable `debug' is nonzero). If linked with the
883 main program in `iregex.c', you can enter patterns and strings
884 interactively. And if linked with the main program in `main.c' and
885 the other test files, you can run the already-written tests. */
889 /* We use standard I/O for debugging. */
892 /* It is useful to test things that ``must'' be true when debugging. */
895 static int debug
= -100000;
897 # define DEBUG_STATEMENT(e) e
898 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
899 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
900 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
901 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
902 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
903 if (debug > 0) print_partial_compiled_pattern (s, e)
904 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
905 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
908 /* Print the fastmap in human-readable form. */
911 print_fastmap (fastmap
)
914 unsigned was_a_range
= 0;
917 while (i
< (1 << BYTEWIDTH
))
923 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
939 /* Print a compiled pattern string in human-readable form, starting at
940 the START pointer into it and ending just before the pointer END. */
943 print_partial_compiled_pattern (start
, end
)
953 fprintf (stderr
, "(null)\n");
957 /* Loop over pattern commands. */
960 fprintf (stderr
, "%d:\t", p
- start
);
962 switch ((re_opcode_t
) *p
++)
965 fprintf (stderr
, "/no_op");
969 fprintf (stderr
, "/succeed");
974 fprintf (stderr
, "/exactn/%d", mcnt
);
977 fprintf (stderr
, "/%c", *p
++);
983 fprintf (stderr
, "/start_memory/%d", *p
++);
987 fprintf (stderr
, "/stop_memory/%d", *p
++);
991 fprintf (stderr
, "/duplicate/%d", *p
++);
995 fprintf (stderr
, "/anychar");
1001 register int c
, last
= -100;
1002 register int in_range
= 0;
1003 int length
= CHARSET_BITMAP_SIZE (p
- 1);
1004 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
1006 fprintf (stderr
, "/charset [%s",
1007 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
1010 fprintf (stderr
, " !extends past end of pattern! ");
1012 for (c
= 0; c
< 256; c
++)
1014 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
1016 /* Are we starting a range? */
1017 if (last
+ 1 == c
&& ! in_range
)
1019 fprintf (stderr
, "-");
1022 /* Have we broken a range? */
1023 else if (last
+ 1 != c
&& in_range
)
1025 fprintf (stderr
, "%c", last
);
1030 fprintf (stderr
, "%c", c
);
1036 fprintf (stderr
, "%c", last
);
1038 fprintf (stderr
, "]");
1042 if (has_range_table
)
1045 fprintf (stderr
, "has-range-table");
1047 /* ??? Should print the range table; for now, just skip it. */
1048 p
+= 2; /* skip range table bits */
1049 EXTRACT_NUMBER_AND_INCR (count
, p
);
1050 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1056 fprintf (stderr
, "/begline");
1060 fprintf (stderr
, "/endline");
1063 case on_failure_jump
:
1064 extract_number_and_incr (&mcnt
, &p
);
1065 fprintf (stderr
, "/on_failure_jump to %d", p
+ mcnt
- start
);
1068 case on_failure_keep_string_jump
:
1069 extract_number_and_incr (&mcnt
, &p
);
1070 fprintf (stderr
, "/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1073 case on_failure_jump_nastyloop
:
1074 extract_number_and_incr (&mcnt
, &p
);
1075 fprintf (stderr
, "/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1078 case on_failure_jump_loop
:
1079 extract_number_and_incr (&mcnt
, &p
);
1080 fprintf (stderr
, "/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1083 case on_failure_jump_smart
:
1084 extract_number_and_incr (&mcnt
, &p
);
1085 fprintf (stderr
, "/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1089 extract_number_and_incr (&mcnt
, &p
);
1090 fprintf (stderr
, "/jump to %d", p
+ mcnt
- start
);
1094 extract_number_and_incr (&mcnt
, &p
);
1095 extract_number_and_incr (&mcnt2
, &p
);
1096 fprintf (stderr
, "/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1100 extract_number_and_incr (&mcnt
, &p
);
1101 extract_number_and_incr (&mcnt2
, &p
);
1102 fprintf (stderr
, "/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1106 extract_number_and_incr (&mcnt
, &p
);
1107 extract_number_and_incr (&mcnt2
, &p
);
1108 fprintf (stderr
, "/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1112 fprintf (stderr
, "/wordbound");
1116 fprintf (stderr
, "/notwordbound");
1120 fprintf (stderr
, "/wordbeg");
1124 fprintf (stderr
, "/wordend");
1128 fprintf (stderr
, "/symbeg");
1132 fprintf (stderr
, "/symend");
1136 fprintf (stderr
, "/syntaxspec");
1138 fprintf (stderr
, "/%d", mcnt
);
1142 fprintf (stderr
, "/notsyntaxspec");
1144 fprintf (stderr
, "/%d", mcnt
);
1149 fprintf (stderr
, "/before_dot");
1153 fprintf (stderr
, "/at_dot");
1157 fprintf (stderr
, "/after_dot");
1161 fprintf (stderr
, "/categoryspec");
1163 fprintf (stderr
, "/%d", mcnt
);
1166 case notcategoryspec
:
1167 fprintf (stderr
, "/notcategoryspec");
1169 fprintf (stderr
, "/%d", mcnt
);
1174 fprintf (stderr
, "/begbuf");
1178 fprintf (stderr
, "/endbuf");
1182 fprintf (stderr
, "?%d", *(p
-1));
1185 fprintf (stderr
, "\n");
1188 fprintf (stderr
, "%d:\tend of pattern.\n", p
- start
);
1193 print_compiled_pattern (bufp
)
1194 struct re_pattern_buffer
*bufp
;
1196 re_char
*buffer
= bufp
->buffer
;
1198 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1199 printf ("%ld bytes used/%ld bytes allocated.\n",
1200 bufp
->used
, bufp
->allocated
);
1202 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1204 printf ("fastmap: ");
1205 print_fastmap (bufp
->fastmap
);
1208 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1209 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1210 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1211 printf ("no_sub: %d\t", bufp
->no_sub
);
1212 printf ("not_bol: %d\t", bufp
->not_bol
);
1213 printf ("not_eol: %d\t", bufp
->not_eol
);
1214 printf ("syntax: %lx\n", bufp
->syntax
);
1216 /* Perhaps we should print the translate table? */
1221 print_double_string (where
, string1
, size1
, string2
, size2
)
1234 if (FIRST_STRING_P (where
))
1236 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1237 putchar (string1
[this_char
]);
1242 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1243 putchar (string2
[this_char
]);
1247 #else /* not DEBUG */
1252 # define DEBUG_STATEMENT(e)
1253 # define DEBUG_PRINT1(x)
1254 # define DEBUG_PRINT2(x1, x2)
1255 # define DEBUG_PRINT3(x1, x2, x3)
1256 # define DEBUG_PRINT4(x1, x2, x3, x4)
1257 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1258 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1260 #endif /* not DEBUG */
1262 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1263 also be assigned to arbitrarily: each pattern buffer stores its own
1264 syntax, so it can be changed between regex compilations. */
1265 /* This has no initializer because initialized variables in Emacs
1266 become read-only after dumping. */
1267 reg_syntax_t re_syntax_options
;
1270 /* Specify the precise syntax of regexps for compilation. This provides
1271 for compatibility for various utilities which historically have
1272 different, incompatible syntaxes.
1274 The argument SYNTAX is a bit mask comprised of the various bits
1275 defined in regex.h. We return the old syntax. */
1278 re_set_syntax (syntax
)
1279 reg_syntax_t syntax
;
1281 reg_syntax_t ret
= re_syntax_options
;
1283 re_syntax_options
= syntax
;
1286 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1288 /* Regexp to use to replace spaces, or NULL meaning don't. */
1289 static re_char
*whitespace_regexp
;
1292 re_set_whitespace_regexp (regexp
)
1295 whitespace_regexp
= (re_char
*) regexp
;
1297 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1299 /* This table gives an error message for each of the error codes listed
1300 in regex.h. Obviously the order here has to be same as there.
1301 POSIX doesn't require that we do anything for REG_NOERROR,
1302 but why not be nice? */
1304 static const char *re_error_msgid
[] =
1306 gettext_noop ("Success"), /* REG_NOERROR */
1307 gettext_noop ("No match"), /* REG_NOMATCH */
1308 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1309 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1310 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1311 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1312 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1313 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1314 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1315 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1316 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1317 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1318 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1319 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1320 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1321 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1322 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1323 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1326 /* Avoiding alloca during matching, to placate r_alloc. */
1328 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1329 searching and matching functions should not call alloca. On some
1330 systems, alloca is implemented in terms of malloc, and if we're
1331 using the relocating allocator routines, then malloc could cause a
1332 relocation, which might (if the strings being searched are in the
1333 ralloc heap) shift the data out from underneath the regexp
1336 Here's another reason to avoid allocation: Emacs
1337 processes input from X in a signal handler; processing X input may
1338 call malloc; if input arrives while a matching routine is calling
1339 malloc, then we're scrod. But Emacs can't just block input while
1340 calling matching routines; then we don't notice interrupts when
1341 they come in. So, Emacs blocks input around all regexp calls
1342 except the matching calls, which it leaves unprotected, in the
1343 faith that they will not malloc. */
1345 /* Normally, this is fine. */
1346 #define MATCH_MAY_ALLOCATE
1348 /* When using GNU C, we are not REALLY using the C alloca, no matter
1349 what config.h may say. So don't take precautions for it. */
1354 /* The match routines may not allocate if (1) they would do it with malloc
1355 and (2) it's not safe for them to use malloc.
1356 Note that if REL_ALLOC is defined, matching would not use malloc for the
1357 failure stack, but we would still use it for the register vectors;
1358 so REL_ALLOC should not affect this. */
1359 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1360 # undef MATCH_MAY_ALLOCATE
1364 /* Failure stack declarations and macros; both re_compile_fastmap and
1365 re_match_2 use a failure stack. These have to be macros because of
1366 REGEX_ALLOCATE_STACK. */
1369 /* Approximate number of failure points for which to initially allocate space
1370 when matching. If this number is exceeded, we allocate more
1371 space, so it is not a hard limit. */
1372 #ifndef INIT_FAILURE_ALLOC
1373 # define INIT_FAILURE_ALLOC 20
1376 /* Roughly the maximum number of failure points on the stack. Would be
1377 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1378 This is a variable only so users of regex can assign to it; we never
1379 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1380 before using it, so it should probably be a byte-count instead. */
1381 # if defined MATCH_MAY_ALLOCATE
1382 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1383 whose default stack limit is 2mb. In order for a larger
1384 value to work reliably, you have to try to make it accord
1385 with the process stack limit. */
1386 size_t re_max_failures
= 40000;
1388 size_t re_max_failures
= 4000;
1391 union fail_stack_elt
1394 /* This should be the biggest `int' that's no bigger than a pointer. */
1398 typedef union fail_stack_elt fail_stack_elt_t
;
1402 fail_stack_elt_t
*stack
;
1404 size_t avail
; /* Offset of next open position. */
1405 size_t frame
; /* Offset of the cur constructed frame. */
1408 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1409 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1412 /* Define macros to initialize and free the failure stack.
1413 Do `return -2' if the alloc fails. */
1415 #ifdef MATCH_MAY_ALLOCATE
1416 # define INIT_FAIL_STACK() \
1418 fail_stack.stack = (fail_stack_elt_t *) \
1419 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1420 * sizeof (fail_stack_elt_t)); \
1422 if (fail_stack.stack == NULL) \
1425 fail_stack.size = INIT_FAILURE_ALLOC; \
1426 fail_stack.avail = 0; \
1427 fail_stack.frame = 0; \
1430 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1432 # define INIT_FAIL_STACK() \
1434 fail_stack.avail = 0; \
1435 fail_stack.frame = 0; \
1438 # define RESET_FAIL_STACK() ((void)0)
1442 /* Double the size of FAIL_STACK, up to a limit
1443 which allows approximately `re_max_failures' items.
1445 Return 1 if succeeds, and 0 if either ran out of memory
1446 allocating space for it or it was already too large.
1448 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1450 /* Factor to increase the failure stack size by
1451 when we increase it.
1452 This used to be 2, but 2 was too wasteful
1453 because the old discarded stacks added up to as much space
1454 were as ultimate, maximum-size stack. */
1455 #define FAIL_STACK_GROWTH_FACTOR 4
1457 #define GROW_FAIL_STACK(fail_stack) \
1458 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1459 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1461 : ((fail_stack).stack \
1462 = (fail_stack_elt_t *) \
1463 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1464 (fail_stack).size * sizeof (fail_stack_elt_t), \
1465 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1466 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1467 * FAIL_STACK_GROWTH_FACTOR))), \
1469 (fail_stack).stack == NULL \
1471 : ((fail_stack).size \
1472 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1473 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1474 * FAIL_STACK_GROWTH_FACTOR)) \
1475 / sizeof (fail_stack_elt_t)), \
1479 /* Push a pointer value 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_POINTER(item) \
1483 fail_stack.stack[fail_stack.avail++].pointer = (item)
1485 /* This pushes an integer-valued item onto the failure stack.
1486 Assumes the variable `fail_stack'. Probably should only
1487 be called from within `PUSH_FAILURE_POINT'. */
1488 #define PUSH_FAILURE_INT(item) \
1489 fail_stack.stack[fail_stack.avail++].integer = (item)
1491 /* Push a fail_stack_elt_t value onto the failure stack.
1492 Assumes the variable `fail_stack'. Probably should only
1493 be called from within `PUSH_FAILURE_POINT'. */
1494 #define PUSH_FAILURE_ELT(item) \
1495 fail_stack.stack[fail_stack.avail++] = (item)
1497 /* These three POP... operations complement the three PUSH... operations.
1498 All assume that `fail_stack' is nonempty. */
1499 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1500 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1501 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1503 /* Individual items aside from the registers. */
1504 #define NUM_NONREG_ITEMS 3
1506 /* Used to examine the stack (to detect infinite loops). */
1507 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1508 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1509 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1510 #define TOP_FAILURE_HANDLE() fail_stack.frame
1513 #define ENSURE_FAIL_STACK(space) \
1514 while (REMAINING_AVAIL_SLOTS <= space) { \
1515 if (!GROW_FAIL_STACK (fail_stack)) \
1517 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1518 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1521 /* Push register NUM onto the stack. */
1522 #define PUSH_FAILURE_REG(num) \
1524 char *destination; \
1525 ENSURE_FAIL_STACK(3); \
1526 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1527 num, regstart[num], regend[num]); \
1528 PUSH_FAILURE_POINTER (regstart[num]); \
1529 PUSH_FAILURE_POINTER (regend[num]); \
1530 PUSH_FAILURE_INT (num); \
1533 /* Change the counter's value to VAL, but make sure that it will
1534 be reset when backtracking. */
1535 #define PUSH_NUMBER(ptr,val) \
1537 char *destination; \
1539 ENSURE_FAIL_STACK(3); \
1540 EXTRACT_NUMBER (c, ptr); \
1541 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1542 PUSH_FAILURE_INT (c); \
1543 PUSH_FAILURE_POINTER (ptr); \
1544 PUSH_FAILURE_INT (-1); \
1545 STORE_NUMBER (ptr, val); \
1548 /* Pop a saved register off the stack. */
1549 #define POP_FAILURE_REG_OR_COUNT() \
1551 int reg = POP_FAILURE_INT (); \
1554 /* It's a counter. */ \
1555 /* Here, we discard `const', making re_match non-reentrant. */ \
1556 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1557 reg = POP_FAILURE_INT (); \
1558 STORE_NUMBER (ptr, reg); \
1559 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1563 regend[reg] = POP_FAILURE_POINTER (); \
1564 regstart[reg] = POP_FAILURE_POINTER (); \
1565 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1566 reg, regstart[reg], regend[reg]); \
1570 /* Check that we are not stuck in an infinite loop. */
1571 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1573 int failure = TOP_FAILURE_HANDLE (); \
1574 /* Check for infinite matching loops */ \
1575 while (failure > 0 \
1576 && (FAILURE_STR (failure) == string_place \
1577 || FAILURE_STR (failure) == NULL)) \
1579 assert (FAILURE_PAT (failure) >= bufp->buffer \
1580 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1581 if (FAILURE_PAT (failure) == pat_cur) \
1586 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1587 failure = NEXT_FAILURE_HANDLE(failure); \
1589 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1592 /* Push the information about the state we will need
1593 if we ever fail back to it.
1595 Requires variables fail_stack, regstart, regend and
1596 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1599 Does `return FAILURE_CODE' if runs out of memory. */
1601 #define PUSH_FAILURE_POINT(pattern, string_place) \
1603 char *destination; \
1604 /* Must be int, so when we don't save any registers, the arithmetic \
1605 of 0 + -1 isn't done as unsigned. */ \
1607 DEBUG_STATEMENT (nfailure_points_pushed++); \
1608 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1609 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1610 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1612 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1614 DEBUG_PRINT1 ("\n"); \
1616 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1617 PUSH_FAILURE_INT (fail_stack.frame); \
1619 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1620 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1621 DEBUG_PRINT1 ("'\n"); \
1622 PUSH_FAILURE_POINTER (string_place); \
1624 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1625 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1626 PUSH_FAILURE_POINTER (pattern); \
1628 /* Close the frame by moving the frame pointer past it. */ \
1629 fail_stack.frame = fail_stack.avail; \
1632 /* Estimate the size of data pushed by a typical failure stack entry.
1633 An estimate is all we need, because all we use this for
1634 is to choose a limit for how big to make the failure stack. */
1635 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1636 #define TYPICAL_FAILURE_SIZE 20
1638 /* How many items can still be added to the stack without overflowing it. */
1639 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1642 /* Pops what PUSH_FAIL_STACK pushes.
1644 We restore into the parameters, all of which should be lvalues:
1645 STR -- the saved data position.
1646 PAT -- the saved pattern position.
1647 REGSTART, REGEND -- arrays of string positions.
1649 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1650 `pend', `string1', `size1', `string2', and `size2'. */
1652 #define POP_FAILURE_POINT(str, pat) \
1654 assert (!FAIL_STACK_EMPTY ()); \
1656 /* Remove failure points and point to how many regs pushed. */ \
1657 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1658 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1659 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1661 /* Pop the saved registers. */ \
1662 while (fail_stack.frame < fail_stack.avail) \
1663 POP_FAILURE_REG_OR_COUNT (); \
1665 pat = POP_FAILURE_POINTER (); \
1666 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1667 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1669 /* If the saved string location is NULL, it came from an \
1670 on_failure_keep_string_jump opcode, and we want to throw away the \
1671 saved NULL, thus retaining our current position in the string. */ \
1672 str = POP_FAILURE_POINTER (); \
1673 DEBUG_PRINT2 (" Popping string %p: `", str); \
1674 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1675 DEBUG_PRINT1 ("'\n"); \
1677 fail_stack.frame = POP_FAILURE_INT (); \
1678 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1680 assert (fail_stack.avail >= 0); \
1681 assert (fail_stack.frame <= fail_stack.avail); \
1683 DEBUG_STATEMENT (nfailure_points_popped++); \
1684 } while (0) /* POP_FAILURE_POINT */
1688 /* Registers are set to a sentinel when they haven't yet matched. */
1689 #define REG_UNSET(e) ((e) == NULL)
1691 /* Subroutine declarations and macros for regex_compile. */
1693 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1694 reg_syntax_t syntax
,
1695 struct re_pattern_buffer
*bufp
));
1696 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1697 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1698 int arg1
, int arg2
));
1699 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1700 int arg
, unsigned char *end
));
1701 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1702 int arg1
, int arg2
, unsigned char *end
));
1703 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1705 reg_syntax_t syntax
));
1706 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1708 reg_syntax_t syntax
));
1709 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1710 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1711 char *fastmap
, const int multibyte
));
1713 /* Fetch the next character in the uncompiled pattern, with no
1715 #define PATFETCH(c) \
1718 if (p == pend) return REG_EEND; \
1719 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1724 /* If `translate' is non-null, return translate[D], else just D. We
1725 cast the subscript to translate because some data is declared as
1726 `char *', to avoid warnings when a string constant is passed. But
1727 when we use a character as a subscript we must make it unsigned. */
1729 # define TRANSLATE(d) \
1730 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1734 /* Macros for outputting the compiled pattern into `buffer'. */
1736 /* If the buffer isn't allocated when it comes in, use this. */
1737 #define INIT_BUF_SIZE 32
1739 /* Make sure we have at least N more bytes of space in buffer. */
1740 #define GET_BUFFER_SPACE(n) \
1741 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1744 /* Make sure we have one more byte of buffer space and then add C to it. */
1745 #define BUF_PUSH(c) \
1747 GET_BUFFER_SPACE (1); \
1748 *b++ = (unsigned char) (c); \
1752 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1753 #define BUF_PUSH_2(c1, c2) \
1755 GET_BUFFER_SPACE (2); \
1756 *b++ = (unsigned char) (c1); \
1757 *b++ = (unsigned char) (c2); \
1761 /* As with BUF_PUSH_2, except for three bytes. */
1762 #define BUF_PUSH_3(c1, c2, c3) \
1764 GET_BUFFER_SPACE (3); \
1765 *b++ = (unsigned char) (c1); \
1766 *b++ = (unsigned char) (c2); \
1767 *b++ = (unsigned char) (c3); \
1771 /* Store a jump with opcode OP at LOC to location TO. We store a
1772 relative address offset by the three bytes the jump itself occupies. */
1773 #define STORE_JUMP(op, loc, to) \
1774 store_op1 (op, loc, (to) - (loc) - 3)
1776 /* Likewise, for a two-argument jump. */
1777 #define STORE_JUMP2(op, loc, to, arg) \
1778 store_op2 (op, loc, (to) - (loc) - 3, arg)
1780 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1781 #define INSERT_JUMP(op, loc, to) \
1782 insert_op1 (op, loc, (to) - (loc) - 3, b)
1784 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1785 #define INSERT_JUMP2(op, loc, to, arg) \
1786 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1789 /* This is not an arbitrary limit: the arguments which represent offsets
1790 into the pattern are two bytes long. So if 2^15 bytes turns out to
1791 be too small, many things would have to change. */
1792 # define MAX_BUF_SIZE (1L << 15)
1794 #if 0 /* This is when we thought it could be 2^16 bytes. */
1795 /* Any other compiler which, like MSC, has allocation limit below 2^16
1796 bytes will have to use approach similar to what was done below for
1797 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1798 reallocating to 0 bytes. Such thing is not going to work too well.
1799 You have been warned!! */
1800 #if defined _MSC_VER && !defined WIN32
1801 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1802 # define MAX_BUF_SIZE 65500L
1804 # define MAX_BUF_SIZE (1L << 16)
1808 /* Extend the buffer by twice its current size via realloc and
1809 reset the pointers that pointed into the old block to point to the
1810 correct places in the new one. If extending the buffer results in it
1811 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1812 #if __BOUNDED_POINTERS__
1813 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1814 # define MOVE_BUFFER_POINTER(P) \
1815 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1816 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1819 SET_HIGH_BOUND (b); \
1820 SET_HIGH_BOUND (begalt); \
1821 if (fixup_alt_jump) \
1822 SET_HIGH_BOUND (fixup_alt_jump); \
1824 SET_HIGH_BOUND (laststart); \
1825 if (pending_exact) \
1826 SET_HIGH_BOUND (pending_exact); \
1829 # define MOVE_BUFFER_POINTER(P) (P) += incr
1830 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1832 #define EXTEND_BUFFER() \
1834 re_char *old_buffer = bufp->buffer; \
1835 if (bufp->allocated == MAX_BUF_SIZE) \
1837 bufp->allocated <<= 1; \
1838 if (bufp->allocated > MAX_BUF_SIZE) \
1839 bufp->allocated = MAX_BUF_SIZE; \
1840 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1841 if (bufp->buffer == NULL) \
1842 return REG_ESPACE; \
1843 /* If the buffer moved, move all the pointers into it. */ \
1844 if (old_buffer != bufp->buffer) \
1846 int incr = bufp->buffer - old_buffer; \
1847 MOVE_BUFFER_POINTER (b); \
1848 MOVE_BUFFER_POINTER (begalt); \
1849 if (fixup_alt_jump) \
1850 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1852 MOVE_BUFFER_POINTER (laststart); \
1853 if (pending_exact) \
1854 MOVE_BUFFER_POINTER (pending_exact); \
1856 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1860 /* Since we have one byte reserved for the register number argument to
1861 {start,stop}_memory, the maximum number of groups we can report
1862 things about is what fits in that byte. */
1863 #define MAX_REGNUM 255
1865 /* But patterns can have more than `MAX_REGNUM' registers. We just
1866 ignore the excess. */
1867 typedef int regnum_t
;
1870 /* Macros for the compile stack. */
1872 /* Since offsets can go either forwards or backwards, this type needs to
1873 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1874 /* int may be not enough when sizeof(int) == 2. */
1875 typedef long pattern_offset_t
;
1879 pattern_offset_t begalt_offset
;
1880 pattern_offset_t fixup_alt_jump
;
1881 pattern_offset_t laststart_offset
;
1883 } compile_stack_elt_t
;
1888 compile_stack_elt_t
*stack
;
1890 unsigned avail
; /* Offset of next open position. */
1891 } compile_stack_type
;
1894 #define INIT_COMPILE_STACK_SIZE 32
1896 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1897 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1899 /* The next available element. */
1900 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1902 /* Explicit quit checking is only used on NTemacs and whenever we
1903 use polling to process input events. */
1904 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1905 extern int immediate_quit
;
1906 # define IMMEDIATE_QUIT_CHECK \
1908 if (immediate_quit) QUIT; \
1911 # define IMMEDIATE_QUIT_CHECK ((void)0)
1914 /* Structure to manage work area for range table. */
1915 struct range_table_work_area
1917 int *table
; /* actual work area. */
1918 int allocated
; /* allocated size for work area in bytes. */
1919 int used
; /* actually used size in words. */
1920 int bits
; /* flag to record character classes */
1923 /* Make sure that WORK_AREA can hold more N multibyte characters.
1924 This is used only in set_image_of_range and set_image_of_range_1.
1925 It expects WORK_AREA to be a pointer.
1926 If it can't get the space, it returns from the surrounding function. */
1928 #define EXTEND_RANGE_TABLE(work_area, n) \
1930 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1932 extend_range_table_work_area (&work_area); \
1933 if ((work_area).table == 0) \
1934 return (REG_ESPACE); \
1938 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1939 (work_area).bits |= (bit)
1941 /* Bits used to implement the multibyte-part of the various character classes
1942 such as [:alnum:] in a charset's range table. */
1943 #define BIT_WORD 0x1
1944 #define BIT_LOWER 0x2
1945 #define BIT_PUNCT 0x4
1946 #define BIT_SPACE 0x8
1947 #define BIT_UPPER 0x10
1948 #define BIT_MULTIBYTE 0x20
1950 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1951 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1953 EXTEND_RANGE_TABLE ((work_area), 2); \
1954 (work_area).table[(work_area).used++] = (range_start); \
1955 (work_area).table[(work_area).used++] = (range_end); \
1958 /* Free allocated memory for WORK_AREA. */
1959 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1961 if ((work_area).table) \
1962 free ((work_area).table); \
1965 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1966 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1967 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1968 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1971 /* Set the bit for character C in a list. */
1972 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1977 /* Store characters in the rage range C0 to C1 in WORK_AREA while
1978 translating them and paying attention to the continuity of
1979 translated characters.
1981 Implementation note: It is better to implement this fairly big
1982 macro by a function, but it's not that easy because macros called
1983 in this macro assume various local variables already declared. */
1985 #define SETUP_MULTIBYTE_RANGE(work_area, c0, c1) \
1987 re_wchar_t c, t, t_last; \
1991 t_last = multibyte ? TRANSLATE (c) : TRANSLATE (MAKE_CHAR_MULTIBYTE (c)); \
1992 for (c++, n = 1; c <= (c1); c++, n++) \
1994 t = multibyte ? TRANSLATE (c) : TRANSLATE (MAKE_CHAR_MULTIBYTE (c)); \
1995 if (t_last + n == t) \
1997 SET_RANGE_TABLE_WORK_AREA ((work_area), t_last, t_last + n - 1); \
2002 SET_RANGE_TABLE_WORK_AREA ((work_area), t_last, t_last + n - 1); \
2007 /* Get the next unsigned number in the uncompiled pattern. */
2008 #define GET_UNSIGNED_NUMBER(num) \
2011 FREE_STACK_RETURN (REG_EBRACE); \
2015 while ('0' <= c && c <= '9') \
2021 num = num * 10 + c - '0'; \
2022 if (num / 10 != prev) \
2023 FREE_STACK_RETURN (REG_BADBR); \
2025 FREE_STACK_RETURN (REG_EBRACE); \
2031 #if ! WIDE_CHAR_SUPPORT
2033 /* Map a string to the char class it names (if any). */
2038 const char *string
= str
;
2039 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2040 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2041 else if (STREQ (string
, "word")) return RECC_WORD
;
2042 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2043 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2044 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2045 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2046 else if (STREQ (string
, "print")) return RECC_PRINT
;
2047 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2048 else if (STREQ (string
, "space")) return RECC_SPACE
;
2049 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2050 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2051 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2052 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2053 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2054 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2055 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2059 /* True iff CH is in the char class CC. */
2061 re_iswctype (ch
, cc
)
2067 case RECC_ALNUM
: return ISALNUM (ch
);
2068 case RECC_ALPHA
: return ISALPHA (ch
);
2069 case RECC_BLANK
: return ISBLANK (ch
);
2070 case RECC_CNTRL
: return ISCNTRL (ch
);
2071 case RECC_DIGIT
: return ISDIGIT (ch
);
2072 case RECC_GRAPH
: return ISGRAPH (ch
);
2073 case RECC_LOWER
: return ISLOWER (ch
);
2074 case RECC_PRINT
: return ISPRINT (ch
);
2075 case RECC_PUNCT
: return ISPUNCT (ch
);
2076 case RECC_SPACE
: return ISSPACE (ch
);
2077 case RECC_UPPER
: return ISUPPER (ch
);
2078 case RECC_XDIGIT
: return ISXDIGIT (ch
);
2079 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2080 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2081 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2082 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2083 case RECC_WORD
: return ISWORD (ch
);
2084 case RECC_ERROR
: return false;
2090 /* Return a bit-pattern to use in the range-table bits to match multibyte
2091 chars of class CC. */
2093 re_wctype_to_bit (cc
)
2098 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2099 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2100 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2101 case RECC_LOWER
: return BIT_LOWER
;
2102 case RECC_UPPER
: return BIT_UPPER
;
2103 case RECC_PUNCT
: return BIT_PUNCT
;
2104 case RECC_SPACE
: return BIT_SPACE
;
2105 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2106 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2113 /* Filling in the work area of a range. */
2115 /* Actually extend the space in WORK_AREA. */
2118 extend_range_table_work_area (work_area
)
2119 struct range_table_work_area
*work_area
;
2121 work_area
->allocated
+= 16 * sizeof (int);
2122 if (work_area
->table
)
2124 = (int *) realloc (work_area
->table
, work_area
->allocated
);
2127 = (int *) malloc (work_area
->allocated
);
2133 /* Carefully find the ranges of codes that are equivalent
2134 under case conversion to the range start..end when passed through
2135 TRANSLATE. Handle the case where non-letters can come in between
2136 two upper-case letters (which happens in Latin-1).
2137 Also handle the case of groups of more than 2 case-equivalent chars.
2139 The basic method is to look at consecutive characters and see
2140 if they can form a run that can be handled as one.
2142 Returns -1 if successful, REG_ESPACE if ran out of space. */
2145 set_image_of_range_1 (work_area
, start
, end
, translate
)
2146 RE_TRANSLATE_TYPE translate
;
2147 struct range_table_work_area
*work_area
;
2148 re_wchar_t start
, end
;
2150 /* `one_case' indicates a character, or a run of characters,
2151 each of which is an isolate (no case-equivalents).
2152 This includes all ASCII non-letters.
2154 `two_case' indicates a character, or a run of characters,
2155 each of which has two case-equivalent forms.
2156 This includes all ASCII letters.
2158 `strange' indicates a character that has more than one
2161 enum case_type
{one_case
, two_case
, strange
};
2163 /* Describe the run that is in progress,
2164 which the next character can try to extend.
2165 If run_type is strange, that means there really is no run.
2166 If run_type is one_case, then run_start...run_end is the run.
2167 If run_type is two_case, then the run is run_start...run_end,
2168 and the case-equivalents end at run_eqv_end. */
2170 enum case_type run_type
= strange
;
2171 int run_start
, run_end
, run_eqv_end
;
2173 Lisp_Object eqv_table
;
2175 if (!RE_TRANSLATE_P (translate
))
2177 EXTEND_RANGE_TABLE (work_area
, 2);
2178 work_area
->table
[work_area
->used
++] = (start
);
2179 work_area
->table
[work_area
->used
++] = (end
);
2183 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2185 for (; start
<= end
; start
++)
2187 enum case_type this_type
;
2188 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2189 int minchar
, maxchar
;
2191 /* Classify this character */
2193 this_type
= one_case
;
2194 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2195 this_type
= two_case
;
2197 this_type
= strange
;
2200 minchar
= start
, maxchar
= eqv
;
2202 minchar
= eqv
, maxchar
= start
;
2204 /* Can this character extend the run in progress? */
2205 if (this_type
== strange
|| this_type
!= run_type
2206 || !(minchar
== run_end
+ 1
2207 && (run_type
== two_case
2208 ? maxchar
== run_eqv_end
+ 1 : 1)))
2211 Record each of its equivalent ranges. */
2212 if (run_type
== one_case
)
2214 EXTEND_RANGE_TABLE (work_area
, 2);
2215 work_area
->table
[work_area
->used
++] = run_start
;
2216 work_area
->table
[work_area
->used
++] = run_end
;
2218 else if (run_type
== two_case
)
2220 EXTEND_RANGE_TABLE (work_area
, 4);
2221 work_area
->table
[work_area
->used
++] = run_start
;
2222 work_area
->table
[work_area
->used
++] = run_end
;
2223 work_area
->table
[work_area
->used
++]
2224 = RE_TRANSLATE (eqv_table
, run_start
);
2225 work_area
->table
[work_area
->used
++]
2226 = RE_TRANSLATE (eqv_table
, run_end
);
2231 if (this_type
== strange
)
2233 /* For a strange character, add each of its equivalents, one
2234 by one. Don't start a range. */
2237 EXTEND_RANGE_TABLE (work_area
, 2);
2238 work_area
->table
[work_area
->used
++] = eqv
;
2239 work_area
->table
[work_area
->used
++] = eqv
;
2240 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2242 while (eqv
!= start
);
2245 /* Add this char to the run, or start a new run. */
2246 else if (run_type
== strange
)
2248 /* Initialize a new range. */
2249 run_type
= this_type
;
2252 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2256 /* Extend a running range. */
2258 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2262 /* If a run is still in progress at the end, finish it now
2263 by recording its equivalent ranges. */
2264 if (run_type
== one_case
)
2266 EXTEND_RANGE_TABLE (work_area
, 2);
2267 work_area
->table
[work_area
->used
++] = run_start
;
2268 work_area
->table
[work_area
->used
++] = run_end
;
2270 else if (run_type
== two_case
)
2272 EXTEND_RANGE_TABLE (work_area
, 4);
2273 work_area
->table
[work_area
->used
++] = run_start
;
2274 work_area
->table
[work_area
->used
++] = run_end
;
2275 work_area
->table
[work_area
->used
++]
2276 = RE_TRANSLATE (eqv_table
, run_start
);
2277 work_area
->table
[work_area
->used
++]
2278 = RE_TRANSLATE (eqv_table
, run_end
);
2286 /* Record the the image of the range start..end when passed through
2287 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2288 and is not even necessarily contiguous.
2289 Normally we approximate it with the smallest contiguous range that contains
2290 all the chars we need. However, for Latin-1 we go to extra effort
2293 This function is not called for ASCII ranges.
2295 Returns -1 if successful, REG_ESPACE if ran out of space. */
2298 set_image_of_range (work_area
, start
, end
, translate
)
2299 RE_TRANSLATE_TYPE translate
;
2300 struct range_table_work_area
*work_area
;
2301 re_wchar_t start
, end
;
2303 re_wchar_t cmin
, cmax
;
2306 /* For Latin-1 ranges, use set_image_of_range_1
2307 to get proper handling of ranges that include letters and nonletters.
2308 For a range that includes the whole of Latin-1, this is not necessary.
2309 For other character sets, we don't bother to get this right. */
2310 if (RE_TRANSLATE_P (translate
) && start
< 04400
2311 && !(start
< 04200 && end
>= 04377))
2318 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2328 EXTEND_RANGE_TABLE (work_area
, 2);
2329 work_area
->table
[work_area
->used
++] = (start
);
2330 work_area
->table
[work_area
->used
++] = (end
);
2332 cmin
= -1, cmax
= -1;
2334 if (RE_TRANSLATE_P (translate
))
2338 for (ch
= start
; ch
<= end
; ch
++)
2340 re_wchar_t c
= TRANSLATE (ch
);
2341 if (! (start
<= c
&& c
<= end
))
2347 cmin
= MIN (cmin
, c
);
2348 cmax
= MAX (cmax
, c
);
2355 EXTEND_RANGE_TABLE (work_area
, 2);
2356 work_area
->table
[work_area
->used
++] = (cmin
);
2357 work_area
->table
[work_area
->used
++] = (cmax
);
2365 #ifndef MATCH_MAY_ALLOCATE
2367 /* If we cannot allocate large objects within re_match_2_internal,
2368 we make the fail stack and register vectors global.
2369 The fail stack, we grow to the maximum size when a regexp
2371 The register vectors, we adjust in size each time we
2372 compile a regexp, according to the number of registers it needs. */
2374 static fail_stack_type fail_stack
;
2376 /* Size with which the following vectors are currently allocated.
2377 That is so we can make them bigger as needed,
2378 but never make them smaller. */
2379 static int regs_allocated_size
;
2381 static re_char
** regstart
, ** regend
;
2382 static re_char
**best_regstart
, **best_regend
;
2384 /* Make the register vectors big enough for NUM_REGS registers,
2385 but don't make them smaller. */
2388 regex_grow_registers (num_regs
)
2391 if (num_regs
> regs_allocated_size
)
2393 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2394 RETALLOC_IF (regend
, num_regs
, re_char
*);
2395 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2396 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2398 regs_allocated_size
= num_regs
;
2402 #endif /* not MATCH_MAY_ALLOCATE */
2404 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2408 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2409 Returns one of error codes defined in `regex.h', or zero for success.
2411 Assumes the `allocated' (and perhaps `buffer') and `translate'
2412 fields are set in BUFP on entry.
2414 If it succeeds, results are put in BUFP (if it returns an error, the
2415 contents of BUFP are undefined):
2416 `buffer' is the compiled pattern;
2417 `syntax' is set to SYNTAX;
2418 `used' is set to the length of the compiled pattern;
2419 `fastmap_accurate' is zero;
2420 `re_nsub' is the number of subexpressions in PATTERN;
2421 `not_bol' and `not_eol' are zero;
2423 The `fastmap' field is neither examined nor set. */
2425 /* Insert the `jump' from the end of last alternative to "here".
2426 The space for the jump has already been allocated. */
2427 #define FIXUP_ALT_JUMP() \
2429 if (fixup_alt_jump) \
2430 STORE_JUMP (jump, fixup_alt_jump, b); \
2434 /* Return, freeing storage we allocated. */
2435 #define FREE_STACK_RETURN(value) \
2437 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2438 free (compile_stack.stack); \
2442 static reg_errcode_t
2443 regex_compile (pattern
, size
, syntax
, bufp
)
2446 reg_syntax_t syntax
;
2447 struct re_pattern_buffer
*bufp
;
2449 /* We fetch characters from PATTERN here. */
2450 register re_wchar_t c
, c1
;
2452 /* A random temporary spot in PATTERN. */
2455 /* Points to the end of the buffer, where we should append. */
2456 register unsigned char *b
;
2458 /* Keeps track of unclosed groups. */
2459 compile_stack_type compile_stack
;
2461 /* Points to the current (ending) position in the pattern. */
2463 /* `const' makes AIX compiler fail. */
2464 unsigned char *p
= pattern
;
2466 re_char
*p
= pattern
;
2468 re_char
*pend
= pattern
+ size
;
2470 /* How to translate the characters in the pattern. */
2471 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2473 /* Address of the count-byte of the most recently inserted `exactn'
2474 command. This makes it possible to tell if a new exact-match
2475 character can be added to that command or if the character requires
2476 a new `exactn' command. */
2477 unsigned char *pending_exact
= 0;
2479 /* Address of start of the most recently finished expression.
2480 This tells, e.g., postfix * where to find the start of its
2481 operand. Reset at the beginning of groups and alternatives. */
2482 unsigned char *laststart
= 0;
2484 /* Address of beginning of regexp, or inside of last group. */
2485 unsigned char *begalt
;
2487 /* Place in the uncompiled pattern (i.e., the {) to
2488 which to go back if the interval is invalid. */
2489 re_char
*beg_interval
;
2491 /* Address of the place where a forward jump should go to the end of
2492 the containing expression. Each alternative of an `or' -- except the
2493 last -- ends with a forward jump of this sort. */
2494 unsigned char *fixup_alt_jump
= 0;
2496 /* Counts open-groups as they are encountered. Remembered for the
2497 matching close-group on the compile stack, so the same register
2498 number is put in the stop_memory as the start_memory. */
2499 regnum_t regnum
= 0;
2501 /* Work area for range table of charset. */
2502 struct range_table_work_area range_table_work
;
2504 /* If the object matched can contain multibyte characters. */
2505 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2507 /* If a target of matching can contain multibyte characters. */
2508 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
2510 /* Nonzero if we have pushed down into a subpattern. */
2511 int in_subpattern
= 0;
2513 /* These hold the values of p, pattern, and pend from the main
2514 pattern when we have pushed into a subpattern. */
2516 re_char
*main_pattern
;
2521 DEBUG_PRINT1 ("\nCompiling pattern: ");
2524 unsigned debug_count
;
2526 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2527 putchar (pattern
[debug_count
]);
2532 /* Initialize the compile stack. */
2533 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2534 if (compile_stack
.stack
== NULL
)
2537 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2538 compile_stack
.avail
= 0;
2540 range_table_work
.table
= 0;
2541 range_table_work
.allocated
= 0;
2543 /* Initialize the pattern buffer. */
2544 bufp
->syntax
= syntax
;
2545 bufp
->fastmap_accurate
= 0;
2546 bufp
->not_bol
= bufp
->not_eol
= 0;
2548 /* Set `used' to zero, so that if we return an error, the pattern
2549 printer (for debugging) will think there's no pattern. We reset it
2553 /* Always count groups, whether or not bufp->no_sub is set. */
2556 #if !defined emacs && !defined SYNTAX_TABLE
2557 /* Initialize the syntax table. */
2558 init_syntax_once ();
2561 if (bufp
->allocated
== 0)
2564 { /* If zero allocated, but buffer is non-null, try to realloc
2565 enough space. This loses if buffer's address is bogus, but
2566 that is the user's responsibility. */
2567 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2570 { /* Caller did not allocate a buffer. Do it for them. */
2571 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2573 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2575 bufp
->allocated
= INIT_BUF_SIZE
;
2578 begalt
= b
= bufp
->buffer
;
2580 /* Loop through the uncompiled pattern until we're at the end. */
2585 /* If this is the end of an included regexp,
2586 pop back to the main regexp and try again. */
2590 pattern
= main_pattern
;
2595 /* If this is the end of the main regexp, we are done. */
2607 /* If there's no special whitespace regexp, treat
2608 spaces normally. And don't try to do this recursively. */
2609 if (!whitespace_regexp
|| in_subpattern
)
2612 /* Peek past following spaces. */
2619 /* If the spaces are followed by a repetition op,
2620 treat them normally. */
2622 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2623 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2626 /* Replace the spaces with the whitespace regexp. */
2630 main_pattern
= pattern
;
2631 p
= pattern
= whitespace_regexp
;
2632 pend
= p
+ strlen (p
);
2638 if ( /* If at start of pattern, it's an operator. */
2640 /* If context independent, it's an operator. */
2641 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2642 /* Otherwise, depends on what's come before. */
2643 || at_begline_loc_p (pattern
, p
, syntax
))
2644 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2653 if ( /* If at end of pattern, it's an operator. */
2655 /* If context independent, it's an operator. */
2656 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2657 /* Otherwise, depends on what's next. */
2658 || at_endline_loc_p (p
, pend
, syntax
))
2659 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2668 if ((syntax
& RE_BK_PLUS_QM
)
2669 || (syntax
& RE_LIMITED_OPS
))
2673 /* If there is no previous pattern... */
2676 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2677 FREE_STACK_RETURN (REG_BADRPT
);
2678 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2683 /* 1 means zero (many) matches is allowed. */
2684 boolean zero_times_ok
= 0, many_times_ok
= 0;
2687 /* If there is a sequence of repetition chars, collapse it
2688 down to just one (the right one). We can't combine
2689 interval operators with these because of, e.g., `a{2}*',
2690 which should only match an even number of `a's. */
2694 if ((syntax
& RE_FRUGAL
)
2695 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2699 zero_times_ok
|= c
!= '+';
2700 many_times_ok
|= c
!= '?';
2706 || (!(syntax
& RE_BK_PLUS_QM
)
2707 && (*p
== '+' || *p
== '?')))
2709 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2712 FREE_STACK_RETURN (REG_EESCAPE
);
2713 if (p
[1] == '+' || p
[1] == '?')
2714 PATFETCH (c
); /* Gobble up the backslash. */
2720 /* If we get here, we found another repeat character. */
2724 /* Star, etc. applied to an empty pattern is equivalent
2725 to an empty pattern. */
2726 if (!laststart
|| laststart
== b
)
2729 /* Now we know whether or not zero matches is allowed
2730 and also whether or not two or more matches is allowed. */
2735 boolean simple
= skip_one_char (laststart
) == b
;
2736 unsigned int startoffset
= 0;
2738 /* Check if the loop can match the empty string. */
2739 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2740 ? on_failure_jump
: on_failure_jump_loop
;
2741 assert (skip_one_char (laststart
) <= b
);
2743 if (!zero_times_ok
&& simple
)
2744 { /* Since simple * loops can be made faster by using
2745 on_failure_keep_string_jump, we turn simple P+
2746 into PP* if P is simple. */
2747 unsigned char *p1
, *p2
;
2748 startoffset
= b
- laststart
;
2749 GET_BUFFER_SPACE (startoffset
);
2750 p1
= b
; p2
= laststart
;
2756 GET_BUFFER_SPACE (6);
2759 STORE_JUMP (ofj
, b
, b
+ 6);
2761 /* Simple * loops can use on_failure_keep_string_jump
2762 depending on what follows. But since we don't know
2763 that yet, we leave the decision up to
2764 on_failure_jump_smart. */
2765 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2766 laststart
+ startoffset
, b
+ 6);
2768 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2773 /* A simple ? pattern. */
2774 assert (zero_times_ok
);
2775 GET_BUFFER_SPACE (3);
2776 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2780 else /* not greedy */
2781 { /* I wish the greedy and non-greedy cases could be merged. */
2783 GET_BUFFER_SPACE (7); /* We might use less. */
2786 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2788 /* The non-greedy multiple match looks like
2789 a repeat..until: we only need a conditional jump
2790 at the end of the loop. */
2791 if (emptyp
) BUF_PUSH (no_op
);
2792 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2793 : on_failure_jump
, b
, laststart
);
2797 /* The repeat...until naturally matches one or more.
2798 To also match zero times, we need to first jump to
2799 the end of the loop (its conditional jump). */
2800 INSERT_JUMP (jump
, laststart
, b
);
2806 /* non-greedy a?? */
2807 INSERT_JUMP (jump
, laststart
, b
+ 3);
2809 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2826 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2828 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2830 /* Ensure that we have enough space to push a charset: the
2831 opcode, the length count, and the bitset; 34 bytes in all. */
2832 GET_BUFFER_SPACE (34);
2836 /* We test `*p == '^' twice, instead of using an if
2837 statement, so we only need one BUF_PUSH. */
2838 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2842 /* Remember the first position in the bracket expression. */
2845 /* Push the number of bytes in the bitmap. */
2846 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2848 /* Clear the whole map. */
2849 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2851 /* charset_not matches newline according to a syntax bit. */
2852 if ((re_opcode_t
) b
[-2] == charset_not
2853 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2854 SET_LIST_BIT ('\n');
2856 /* Read in characters and ranges, setting map bits. */
2859 boolean escaped_char
= false;
2860 const unsigned char *p2
= p
;
2862 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2864 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2865 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2866 So the translation is done later in a loop. Example:
2867 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2870 /* \ might escape characters inside [...] and [^...]. */
2871 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2873 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2876 escaped_char
= true;
2880 /* Could be the end of the bracket expression. If it's
2881 not (i.e., when the bracket expression is `[]' so
2882 far), the ']' character bit gets set way below. */
2883 if (c
== ']' && p2
!= p1
)
2887 /* See if we're at the beginning of a possible character
2890 if (!escaped_char
&&
2891 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2893 /* Leave room for the null. */
2894 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2895 const unsigned char *class_beg
;
2901 /* If pattern is `[[:'. */
2902 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2907 if ((c
== ':' && *p
== ']') || p
== pend
)
2909 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2912 /* This is in any case an invalid class name. */
2917 /* If isn't a word bracketed by `[:' and `:]':
2918 undo the ending character, the letters, and
2919 leave the leading `:' and `[' (but set bits for
2921 if (c
== ':' && *p
== ']')
2927 cc
= re_wctype (str
);
2930 FREE_STACK_RETURN (REG_ECTYPE
);
2932 /* Throw away the ] at the end of the character
2936 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2938 /* Most character classes in a multibyte match
2939 just set a flag. Exceptions are is_blank,
2940 is_digit, is_cntrl, and is_xdigit, since
2941 they can only match ASCII characters. We
2942 don't need to handle them for multibyte.
2943 They are distinguished by a negative wctype. */
2945 for (ch
= 0; ch
< 128; ++ch
)
2946 if (re_iswctype (btowc (ch
), cc
))
2952 if (target_multibyte
)
2954 SET_RANGE_TABLE_WORK_AREA_BIT
2955 (range_table_work
, re_wctype_to_bit (cc
));
2959 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
2962 MAKE_CHAR_MULTIBYTE (c
);
2963 if (re_iswctype (btowc (c
), cc
))
2966 MAKE_CHAR_UNIBYTE (c
);
2972 /* Repeat the loop. */
2977 /* Go back to right after the "[:". */
2981 /* Because the `:' may starts the range, we
2982 can't simply set bit and repeat the loop.
2983 Instead, just set it to C and handle below. */
2988 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2991 /* Discard the `-'. */
2994 /* Fetch the character which ends the range. */
2998 if (syntax
& RE_NO_EMPTY_RANGES
)
2999 FREE_STACK_RETURN (REG_ERANGEX
);
3000 /* Else, repeat the loop. */
3004 /* Range from C to C. */
3009 c1
= TRANSLATE (c1
);
3010 /* Set the range into bitmap */
3011 for (; c
<= c1
; c
++)
3012 SET_LIST_BIT (TRANSLATE (c
));
3013 #else /* not emacs */
3014 if (target_multibyte
)
3018 re_wchar_t c0
= MAX (c
, 128);
3020 SETUP_MULTIBYTE_RANGE (range_table_work
, c0
, c1
);
3023 for (; c
<= c1
; c
++)
3024 SET_LIST_BIT (TRANSLATE (c
));
3030 for (; c
<= c1
; c
++)
3034 MAKE_CHAR_MULTIBYTE (c0
);
3035 c0
= TRANSLATE (c0
);
3036 MAKE_CHAR_UNIBYTE (c0
);
3040 #endif /* not emacs */
3043 /* Discard any (non)matching list bytes that are all 0 at the
3044 end of the map. Decrease the map-length byte too. */
3045 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3049 /* Build real range table from work area. */
3050 if (RANGE_TABLE_WORK_USED (range_table_work
)
3051 || RANGE_TABLE_WORK_BITS (range_table_work
))
3054 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3056 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3057 bytes for flags, two for COUNT, and three bytes for
3059 GET_BUFFER_SPACE (4 + used
* 3);
3061 /* Indicate the existence of range table. */
3062 laststart
[1] |= 0x80;
3064 /* Store the character class flag bits into the range table.
3065 If not in emacs, these flag bits are always 0. */
3066 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3067 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3069 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3070 for (i
= 0; i
< used
; i
++)
3071 STORE_CHARACTER_AND_INCR
3072 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3079 if (syntax
& RE_NO_BK_PARENS
)
3086 if (syntax
& RE_NO_BK_PARENS
)
3093 if (syntax
& RE_NEWLINE_ALT
)
3100 if (syntax
& RE_NO_BK_VBAR
)
3107 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3108 goto handle_interval
;
3114 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3116 /* Do not translate the character after the \, so that we can
3117 distinguish, e.g., \B from \b, even if we normally would
3118 translate, e.g., B to b. */
3124 if (syntax
& RE_NO_BK_PARENS
)
3125 goto normal_backslash
;
3132 /* Look for a special (?...) construct */
3133 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3135 PATFETCH (c
); /* Gobble up the '?'. */
3139 case ':': shy
= 1; break;
3141 /* Only (?:...) is supported right now. */
3142 FREE_STACK_RETURN (REG_BADPAT
);
3153 if (COMPILE_STACK_FULL
)
3155 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3156 compile_stack_elt_t
);
3157 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3159 compile_stack
.size
<<= 1;
3162 /* These are the values to restore when we hit end of this
3163 group. They are all relative offsets, so that if the
3164 whole pattern moves because of realloc, they will still
3166 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3167 COMPILE_STACK_TOP
.fixup_alt_jump
3168 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3169 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3170 COMPILE_STACK_TOP
.regnum
= shy
? -regnum
: regnum
;
3173 start_memory for groups beyond the last one we can
3174 represent in the compiled pattern. */
3175 if (regnum
<= MAX_REGNUM
&& !shy
)
3176 BUF_PUSH_2 (start_memory
, regnum
);
3178 compile_stack
.avail
++;
3183 /* If we've reached MAX_REGNUM groups, then this open
3184 won't actually generate any code, so we'll have to
3185 clear pending_exact explicitly. */
3191 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3193 if (COMPILE_STACK_EMPTY
)
3195 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3196 goto normal_backslash
;
3198 FREE_STACK_RETURN (REG_ERPAREN
);
3204 /* See similar code for backslashed left paren above. */
3205 if (COMPILE_STACK_EMPTY
)
3207 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3210 FREE_STACK_RETURN (REG_ERPAREN
);
3213 /* Since we just checked for an empty stack above, this
3214 ``can't happen''. */
3215 assert (compile_stack
.avail
!= 0);
3217 /* We don't just want to restore into `regnum', because
3218 later groups should continue to be numbered higher,
3219 as in `(ab)c(de)' -- the second group is #2. */
3220 regnum_t this_group_regnum
;
3222 compile_stack
.avail
--;
3223 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3225 = COMPILE_STACK_TOP
.fixup_alt_jump
3226 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3228 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3229 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
3230 /* If we've reached MAX_REGNUM groups, then this open
3231 won't actually generate any code, so we'll have to
3232 clear pending_exact explicitly. */
3235 /* We're at the end of the group, so now we know how many
3236 groups were inside this one. */
3237 if (this_group_regnum
<= MAX_REGNUM
&& this_group_regnum
> 0)
3238 BUF_PUSH_2 (stop_memory
, this_group_regnum
);
3243 case '|': /* `\|'. */
3244 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3245 goto normal_backslash
;
3247 if (syntax
& RE_LIMITED_OPS
)
3250 /* Insert before the previous alternative a jump which
3251 jumps to this alternative if the former fails. */
3252 GET_BUFFER_SPACE (3);
3253 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3257 /* The alternative before this one has a jump after it
3258 which gets executed if it gets matched. Adjust that
3259 jump so it will jump to this alternative's analogous
3260 jump (put in below, which in turn will jump to the next
3261 (if any) alternative's such jump, etc.). The last such
3262 jump jumps to the correct final destination. A picture:
3268 If we are at `b', then fixup_alt_jump right now points to a
3269 three-byte space after `a'. We'll put in the jump, set
3270 fixup_alt_jump to right after `b', and leave behind three
3271 bytes which we'll fill in when we get to after `c'. */
3275 /* Mark and leave space for a jump after this alternative,
3276 to be filled in later either by next alternative or
3277 when know we're at the end of a series of alternatives. */
3279 GET_BUFFER_SPACE (3);
3288 /* If \{ is a literal. */
3289 if (!(syntax
& RE_INTERVALS
)
3290 /* If we're at `\{' and it's not the open-interval
3292 || (syntax
& RE_NO_BK_BRACES
))
3293 goto normal_backslash
;
3297 /* If got here, then the syntax allows intervals. */
3299 /* At least (most) this many matches must be made. */
3300 int lower_bound
= 0, upper_bound
= -1;
3304 GET_UNSIGNED_NUMBER (lower_bound
);
3307 GET_UNSIGNED_NUMBER (upper_bound
);
3309 /* Interval such as `{1}' => match exactly once. */
3310 upper_bound
= lower_bound
;
3312 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3313 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3314 FREE_STACK_RETURN (REG_BADBR
);
3316 if (!(syntax
& RE_NO_BK_BRACES
))
3319 FREE_STACK_RETURN (REG_BADBR
);
3321 FREE_STACK_RETURN (REG_EESCAPE
);
3326 FREE_STACK_RETURN (REG_BADBR
);
3328 /* We just parsed a valid interval. */
3330 /* If it's invalid to have no preceding re. */
3333 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3334 FREE_STACK_RETURN (REG_BADRPT
);
3335 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3338 goto unfetch_interval
;
3341 if (upper_bound
== 0)
3342 /* If the upper bound is zero, just drop the sub pattern
3345 else if (lower_bound
== 1 && upper_bound
== 1)
3346 /* Just match it once: nothing to do here. */
3349 /* Otherwise, we have a nontrivial interval. When
3350 we're all done, the pattern will look like:
3351 set_number_at <jump count> <upper bound>
3352 set_number_at <succeed_n count> <lower bound>
3353 succeed_n <after jump addr> <succeed_n count>
3355 jump_n <succeed_n addr> <jump count>
3356 (The upper bound and `jump_n' are omitted if
3357 `upper_bound' is 1, though.) */
3359 { /* If the upper bound is > 1, we need to insert
3360 more at the end of the loop. */
3361 unsigned int nbytes
= (upper_bound
< 0 ? 3
3362 : upper_bound
> 1 ? 5 : 0);
3363 unsigned int startoffset
= 0;
3365 GET_BUFFER_SPACE (20); /* We might use less. */
3367 if (lower_bound
== 0)
3369 /* A succeed_n that starts with 0 is really a
3370 a simple on_failure_jump_loop. */
3371 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3377 /* Initialize lower bound of the `succeed_n', even
3378 though it will be set during matching by its
3379 attendant `set_number_at' (inserted next),
3380 because `re_compile_fastmap' needs to know.
3381 Jump to the `jump_n' we might insert below. */
3382 INSERT_JUMP2 (succeed_n
, laststart
,
3387 /* Code to initialize the lower bound. Insert
3388 before the `succeed_n'. The `5' is the last two
3389 bytes of this `set_number_at', plus 3 bytes of
3390 the following `succeed_n'. */
3391 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3396 if (upper_bound
< 0)
3398 /* A negative upper bound stands for infinity,
3399 in which case it degenerates to a plain jump. */
3400 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3403 else if (upper_bound
> 1)
3404 { /* More than one repetition is allowed, so
3405 append a backward jump to the `succeed_n'
3406 that starts this interval.
3408 When we've reached this during matching,
3409 we'll have matched the interval once, so
3410 jump back only `upper_bound - 1' times. */
3411 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3415 /* The location we want to set is the second
3416 parameter of the `jump_n'; that is `b-2' as
3417 an absolute address. `laststart' will be
3418 the `set_number_at' we're about to insert;
3419 `laststart+3' the number to set, the source
3420 for the relative address. But we are
3421 inserting into the middle of the pattern --
3422 so everything is getting moved up by 5.
3423 Conclusion: (b - 2) - (laststart + 3) + 5,
3424 i.e., b - laststart.
3426 We insert this at the beginning of the loop
3427 so that if we fail during matching, we'll
3428 reinitialize the bounds. */
3429 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3430 upper_bound
- 1, b
);
3435 beg_interval
= NULL
;
3440 /* If an invalid interval, match the characters as literals. */
3441 assert (beg_interval
);
3443 beg_interval
= NULL
;
3445 /* normal_char and normal_backslash need `c'. */
3448 if (!(syntax
& RE_NO_BK_BRACES
))
3450 assert (p
> pattern
&& p
[-1] == '\\');
3451 goto normal_backslash
;
3457 /* There is no way to specify the before_dot and after_dot
3458 operators. rms says this is ok. --karl */
3466 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3472 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3478 BUF_PUSH_2 (categoryspec
, c
);
3484 BUF_PUSH_2 (notcategoryspec
, c
);
3490 if (syntax
& RE_NO_GNU_OPS
)
3493 BUF_PUSH_2 (syntaxspec
, Sword
);
3498 if (syntax
& RE_NO_GNU_OPS
)
3501 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3506 if (syntax
& RE_NO_GNU_OPS
)
3512 if (syntax
& RE_NO_GNU_OPS
)
3518 if (syntax
& RE_NO_GNU_OPS
)
3527 FREE_STACK_RETURN (REG_BADPAT
);
3531 if (syntax
& RE_NO_GNU_OPS
)
3533 BUF_PUSH (wordbound
);
3537 if (syntax
& RE_NO_GNU_OPS
)
3539 BUF_PUSH (notwordbound
);
3543 if (syntax
& RE_NO_GNU_OPS
)
3549 if (syntax
& RE_NO_GNU_OPS
)
3554 case '1': case '2': case '3': case '4': case '5':
3555 case '6': case '7': case '8': case '9':
3559 if (syntax
& RE_NO_BK_REFS
)
3560 goto normal_backslash
;
3564 /* Can't back reference to a subexpression before its end. */
3565 if (reg
> regnum
|| group_in_compile_stack (compile_stack
, reg
))
3566 FREE_STACK_RETURN (REG_ESUBREG
);
3569 BUF_PUSH_2 (duplicate
, reg
);
3576 if (syntax
& RE_BK_PLUS_QM
)
3579 goto normal_backslash
;
3583 /* You might think it would be useful for \ to mean
3584 not to translate; but if we don't translate it
3585 it will never match anything. */
3592 /* Expects the character in `c'. */
3594 /* If no exactn currently being built. */
3597 /* If last exactn not at current position. */
3598 || pending_exact
+ *pending_exact
+ 1 != b
3600 /* We have only one byte following the exactn for the count. */
3601 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3603 /* If followed by a repetition operator. */
3604 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3605 || ((syntax
& RE_BK_PLUS_QM
)
3606 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3607 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3608 || ((syntax
& RE_INTERVALS
)
3609 && ((syntax
& RE_NO_BK_BRACES
)
3610 ? p
!= pend
&& *p
== '{'
3611 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3613 /* Start building a new exactn. */
3617 BUF_PUSH_2 (exactn
, 0);
3618 pending_exact
= b
- 1;
3621 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3626 MAKE_CHAR_MULTIBYTE (c
);
3628 if (target_multibyte
)
3630 len
= CHAR_STRING (c
, b
);
3635 MAKE_CHAR_UNIBYTE (c
);
3639 (*pending_exact
) += len
;
3644 } /* while p != pend */
3647 /* Through the pattern now. */
3651 if (!COMPILE_STACK_EMPTY
)
3652 FREE_STACK_RETURN (REG_EPAREN
);
3654 /* If we don't want backtracking, force success
3655 the first time we reach the end of the compiled pattern. */
3656 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3659 /* We have succeeded; set the length of the buffer. */
3660 bufp
->used
= b
- bufp
->buffer
;
3663 /* Now the buffer is adjusted for the multibyteness of a target. */
3664 bufp
->multibyte
= bufp
->target_multibyte
;
3670 re_compile_fastmap (bufp
);
3671 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3672 print_compiled_pattern (bufp
);
3677 #ifndef MATCH_MAY_ALLOCATE
3678 /* Initialize the failure stack to the largest possible stack. This
3679 isn't necessary unless we're trying to avoid calling alloca in
3680 the search and match routines. */
3682 int num_regs
= bufp
->re_nsub
+ 1;
3684 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3686 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3688 if (! fail_stack
.stack
)
3690 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3691 * sizeof (fail_stack_elt_t
));
3694 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3696 * sizeof (fail_stack_elt_t
)));
3699 regex_grow_registers (num_regs
);
3701 #endif /* not MATCH_MAY_ALLOCATE */
3703 FREE_STACK_RETURN (REG_NOERROR
);
3704 } /* regex_compile */
3706 /* Subroutines for `regex_compile'. */
3708 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3711 store_op1 (op
, loc
, arg
)
3716 *loc
= (unsigned char) op
;
3717 STORE_NUMBER (loc
+ 1, arg
);
3721 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3724 store_op2 (op
, loc
, arg1
, arg2
)
3729 *loc
= (unsigned char) op
;
3730 STORE_NUMBER (loc
+ 1, arg1
);
3731 STORE_NUMBER (loc
+ 3, arg2
);
3735 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3736 for OP followed by two-byte integer parameter ARG. */
3739 insert_op1 (op
, loc
, arg
, end
)
3745 register unsigned char *pfrom
= end
;
3746 register unsigned char *pto
= end
+ 3;
3748 while (pfrom
!= loc
)
3751 store_op1 (op
, loc
, arg
);
3755 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3758 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3764 register unsigned char *pfrom
= end
;
3765 register unsigned char *pto
= end
+ 5;
3767 while (pfrom
!= loc
)
3770 store_op2 (op
, loc
, arg1
, arg2
);
3774 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3775 after an alternative or a begin-subexpression. We assume there is at
3776 least one character before the ^. */
3779 at_begline_loc_p (pattern
, p
, syntax
)
3780 re_char
*pattern
, *p
;
3781 reg_syntax_t syntax
;
3783 re_char
*prev
= p
- 2;
3784 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3787 /* After a subexpression? */
3788 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3789 /* After an alternative? */
3790 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3791 /* After a shy subexpression? */
3792 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3793 && prev
[-1] == '?' && prev
[-2] == '('
3794 && (syntax
& RE_NO_BK_PARENS
3795 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3799 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3800 at least one character after the $, i.e., `P < PEND'. */
3803 at_endline_loc_p (p
, pend
, syntax
)
3805 reg_syntax_t syntax
;
3808 boolean next_backslash
= *next
== '\\';
3809 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3812 /* Before a subexpression? */
3813 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3814 : next_backslash
&& next_next
&& *next_next
== ')')
3815 /* Before an alternative? */
3816 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3817 : next_backslash
&& next_next
&& *next_next
== '|');
3821 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3822 false if it's not. */
3825 group_in_compile_stack (compile_stack
, regnum
)
3826 compile_stack_type compile_stack
;
3831 for (this_element
= compile_stack
.avail
- 1;
3834 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3841 If fastmap is non-NULL, go through the pattern and fill fastmap
3842 with all the possible leading chars. If fastmap is NULL, don't
3843 bother filling it up (obviously) and only return whether the
3844 pattern could potentially match the empty string.
3846 Return 1 if p..pend might match the empty string.
3847 Return 0 if p..pend matches at least one char.
3848 Return -1 if fastmap was not updated accurately. */
3851 analyse_first (p
, pend
, fastmap
, multibyte
)
3854 const int multibyte
;
3859 /* If all elements for base leading-codes in fastmap is set, this
3860 flag is set true. */
3861 boolean match_any_multibyte_characters
= false;
3865 /* The loop below works as follows:
3866 - It has a working-list kept in the PATTERN_STACK and which basically
3867 starts by only containing a pointer to the first operation.
3868 - If the opcode we're looking at is a match against some set of
3869 chars, then we add those chars to the fastmap and go on to the
3870 next work element from the worklist (done via `break').
3871 - If the opcode is a control operator on the other hand, we either
3872 ignore it (if it's meaningless at this point, such as `start_memory')
3873 or execute it (if it's a jump). If the jump has several destinations
3874 (i.e. `on_failure_jump'), then we push the other destination onto the
3876 We guarantee termination by ignoring backward jumps (more or less),
3877 so that `p' is monotonically increasing. More to the point, we
3878 never set `p' (or push) anything `<= p1'. */
3882 /* `p1' is used as a marker of how far back a `on_failure_jump'
3883 can go without being ignored. It is normally equal to `p'
3884 (which prevents any backward `on_failure_jump') except right
3885 after a plain `jump', to allow patterns such as:
3888 10: on_failure_jump 3
3889 as used for the *? operator. */
3892 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3899 /* If the first character has to match a backreference, that means
3900 that the group was empty (since it already matched). Since this
3901 is the only case that interests us here, we can assume that the
3902 backreference must match the empty string. */
3907 /* Following are the cases which match a character. These end
3912 /* If multibyte is nonzero, the first byte of each
3913 character is an ASCII or a leading code. Otherwise,
3914 each byte is a character. Thus, this works in both
3921 /* We could put all the chars except for \n (and maybe \0)
3922 but we don't bother since it is generally not worth it. */
3923 if (!fastmap
) break;
3928 if (!fastmap
) break;
3930 /* Chars beyond end of bitmap are possible matches. */
3931 /* In a multibyte case, the bitmap is used only for ASCII
3933 int limit
= multibyte
? 128 : (1 << BYTEWIDTH
);
3935 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3942 if (!fastmap
) break;
3943 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3944 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3946 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3949 if ((not && multibyte
)
3950 /* Any leading code can possibly start a character
3951 which doesn't match the specified set of characters. */
3952 || (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3953 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3954 /* If we can match a character class, we can match
3955 any multibyte characters. */
3957 if (match_any_multibyte_characters
== false)
3959 for (j
= 0x80; j
< (1 << BYTEWIDTH
); j
++)
3961 match_any_multibyte_characters
= true;
3965 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3966 && match_any_multibyte_characters
== false)
3968 /* Set fastmap[I] to 1 where I is a leading code of each
3969 multibyte characer in the range table. */
3971 unsigned char lc1
, lc2
;
3973 /* Make P points the range table. `+ 2' is to skip flag
3974 bits for a character class. */
3975 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3977 /* Extract the number of ranges in range table into COUNT. */
3978 EXTRACT_NUMBER_AND_INCR (count
, p
);
3979 for (; count
> 0; count
--, p
+= 2 * 3) /* XXX */
3981 /* Extract the start and end of each range. */
3982 EXTRACT_CHARACTER (c
, p
);
3983 lc1
= CHAR_LEADING_CODE (c
);
3985 EXTRACT_CHARACTER (c
, p
);
3986 lc2
= CHAR_LEADING_CODE (c
);
3987 for (j
= lc1
; j
<= lc2
; j
++)
3995 if (!fastmap
) break;
3997 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3999 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4000 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4004 /* This match depends on text properties. These end with
4005 aborting optimizations. */
4009 case notcategoryspec
:
4010 if (!fastmap
) break;
4011 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4013 for (j
= (multibyte
? 127 : (1 << BYTEWIDTH
)); j
>= 0; j
--)
4014 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4019 /* Any character set can possibly contain a character
4020 whose category is K (or not). */
4021 if (match_any_multibyte_characters
== false)
4023 for (j
= 0x80; j
< (1 << BYTEWIDTH
); j
++)
4025 match_any_multibyte_characters
= true;
4030 /* All cases after this match the empty string. These end with
4052 EXTRACT_NUMBER_AND_INCR (j
, p
);
4054 /* Backward jumps can only go back to code that we've already
4055 visited. `re_compile' should make sure this is true. */
4058 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4060 case on_failure_jump
:
4061 case on_failure_keep_string_jump
:
4062 case on_failure_jump_loop
:
4063 case on_failure_jump_nastyloop
:
4064 case on_failure_jump_smart
:
4070 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4071 to jump back to "just after here". */
4074 case on_failure_jump
:
4075 case on_failure_keep_string_jump
:
4076 case on_failure_jump_nastyloop
:
4077 case on_failure_jump_loop
:
4078 case on_failure_jump_smart
:
4079 EXTRACT_NUMBER_AND_INCR (j
, p
);
4081 ; /* Backward jump to be ignored. */
4083 { /* We have to look down both arms.
4084 We first go down the "straight" path so as to minimize
4085 stack usage when going through alternatives. */
4086 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4094 /* This code simply does not properly handle forward jump_n. */
4095 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4097 /* jump_n can either jump or fall through. The (backward) jump
4098 case has already been handled, so we only need to look at the
4099 fallthrough case. */
4103 /* If N == 0, it should be an on_failure_jump_loop instead. */
4104 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4106 /* We only care about one iteration of the loop, so we don't
4107 need to consider the case where this behaves like an
4124 abort (); /* We have listed all the cases. */
4127 /* Getting here means we have found the possible starting
4128 characters for one path of the pattern -- and that the empty
4129 string does not match. We need not follow this path further. */
4133 /* We reached the end without matching anything. */
4136 } /* analyse_first */
4138 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4139 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4140 characters can start a string that matches the pattern. This fastmap
4141 is used by re_search to skip quickly over impossible starting points.
4143 Character codes above (1 << BYTEWIDTH) are not represented in the
4144 fastmap, but the leading codes are represented. Thus, the fastmap
4145 indicates which character sets could start a match.
4147 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4148 area as BUFP->fastmap.
4150 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4153 Returns 0 if we succeed, -2 if an internal error. */
4156 re_compile_fastmap (bufp
)
4157 struct re_pattern_buffer
*bufp
;
4159 char *fastmap
= bufp
->fastmap
;
4162 assert (fastmap
&& bufp
->buffer
);
4164 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4165 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4167 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4168 fastmap
, RE_MULTIBYTE_P (bufp
));
4169 bufp
->can_be_null
= (analysis
!= 0);
4171 } /* re_compile_fastmap */
4173 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4174 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4175 this memory for recording register information. STARTS and ENDS
4176 must be allocated using the malloc library routine, and must each
4177 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4179 If NUM_REGS == 0, then subsequent matches should allocate their own
4182 Unless this function is called, the first search or match using
4183 PATTERN_BUFFER will allocate its own register data, without
4184 freeing the old data. */
4187 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
4188 struct re_pattern_buffer
*bufp
;
4189 struct re_registers
*regs
;
4191 regoff_t
*starts
, *ends
;
4195 bufp
->regs_allocated
= REGS_REALLOCATE
;
4196 regs
->num_regs
= num_regs
;
4197 regs
->start
= starts
;
4202 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4204 regs
->start
= regs
->end
= (regoff_t
*) 0;
4207 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4209 /* Searching routines. */
4211 /* Like re_search_2, below, but only one string is specified, and
4212 doesn't let you say where to stop matching. */
4215 re_search (bufp
, string
, size
, startpos
, range
, regs
)
4216 struct re_pattern_buffer
*bufp
;
4218 int size
, startpos
, range
;
4219 struct re_registers
*regs
;
4221 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4224 WEAK_ALIAS (__re_search
, re_search
)
4226 /* Head address of virtual concatenation of string. */
4227 #define HEAD_ADDR_VSTRING(P) \
4228 (((P) >= size1 ? string2 : string1))
4230 /* End address of virtual concatenation of string. */
4231 #define STOP_ADDR_VSTRING(P) \
4232 (((P) >= size1 ? string2 + size2 : string1 + size1))
4234 /* Address of POS in the concatenation of virtual string. */
4235 #define POS_ADDR_VSTRING(POS) \
4236 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4238 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4239 virtual concatenation of STRING1 and STRING2, starting first at index
4240 STARTPOS, then at STARTPOS + 1, and so on.
4242 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4244 RANGE is how far to scan while trying to match. RANGE = 0 means try
4245 only at STARTPOS; in general, the last start tried is STARTPOS +
4248 In REGS, return the indices of the virtual concatenation of STRING1
4249 and STRING2 that matched the entire BUFP->buffer and its contained
4252 Do not consider matching one past the index STOP in the virtual
4253 concatenation of STRING1 and STRING2.
4255 We return either the position in the strings at which the match was
4256 found, -1 if no match, or -2 if error (such as failure
4260 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
4261 struct re_pattern_buffer
*bufp
;
4262 const char *str1
, *str2
;
4266 struct re_registers
*regs
;
4270 re_char
*string1
= (re_char
*) str1
;
4271 re_char
*string2
= (re_char
*) str2
;
4272 register char *fastmap
= bufp
->fastmap
;
4273 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4274 int total_size
= size1
+ size2
;
4275 int endpos
= startpos
+ range
;
4276 boolean anchored_start
;
4277 /* Nonzero if BUFP is setup for multibyte characters. We are sure
4278 that it is the same as RE_TARGET_MULTIBYTE_P (bufp). */
4279 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4281 /* Check for out-of-range STARTPOS. */
4282 if (startpos
< 0 || startpos
> total_size
)
4285 /* Fix up RANGE if it might eventually take us outside
4286 the virtual concatenation of STRING1 and STRING2.
4287 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4289 range
= 0 - startpos
;
4290 else if (endpos
> total_size
)
4291 range
= total_size
- startpos
;
4293 /* If the search isn't to be a backwards one, don't waste time in a
4294 search for a pattern anchored at beginning of buffer. */
4295 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4304 /* In a forward search for something that starts with \=.
4305 don't keep searching past point. */
4306 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4308 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4314 /* Update the fastmap now if not correct already. */
4315 if (fastmap
&& !bufp
->fastmap_accurate
)
4316 re_compile_fastmap (bufp
);
4318 /* See whether the pattern is anchored. */
4319 anchored_start
= (bufp
->buffer
[0] == begline
);
4322 gl_state
.object
= re_match_object
;
4324 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4326 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4330 /* Loop through the string, looking for a place to start matching. */
4333 /* If the pattern is anchored,
4334 skip quickly past places we cannot match.
4335 We don't bother to treat startpos == 0 specially
4336 because that case doesn't repeat. */
4337 if (anchored_start
&& startpos
> 0)
4339 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4340 : string2
[startpos
- size1
- 1])
4345 /* If a fastmap is supplied, skip quickly over characters that
4346 cannot be the start of a match. If the pattern can match the
4347 null string, however, we don't need to skip characters; we want
4348 the first null string. */
4349 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4351 register re_char
*d
;
4352 register re_wchar_t buf_ch
;
4354 d
= POS_ADDR_VSTRING (startpos
);
4356 if (range
> 0) /* Searching forwards. */
4358 register int lim
= 0;
4361 if (startpos
< size1
&& startpos
+ range
>= size1
)
4362 lim
= range
- (size1
- startpos
);
4364 /* Written out as an if-else to avoid testing `translate'
4366 if (RE_TRANSLATE_P (translate
))
4373 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
4375 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4376 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4379 range
-= buf_charlen
;
4386 MAKE_CHAR_MULTIBYTE (buf_ch
);
4387 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4388 MAKE_CHAR_UNIBYTE (buf_ch
);
4389 if (fastmap
[buf_ch
])
4402 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
4404 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4406 range
-= buf_charlen
;
4410 while (range
> lim
&& !fastmap
[*d
])
4416 startpos
+= irange
- range
;
4418 else /* Searching backwards. */
4420 int room
= (startpos
>= size1
4421 ? size2
+ size1
- startpos
4422 : size1
- startpos
);
4425 buf_ch
= STRING_CHAR (d
, room
);
4426 buf_ch
= TRANSLATE (buf_ch
);
4427 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4432 if (! fastmap
[TRANSLATE (*d
)])
4438 /* If can't match the null string, and that's all we have left, fail. */
4439 if (range
>= 0 && startpos
== total_size
&& fastmap
4440 && !bufp
->can_be_null
)
4443 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4444 startpos
, regs
, stop
);
4445 #ifndef REGEX_MALLOC
4462 /* Update STARTPOS to the next character boundary. */
4465 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4466 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
4467 int len
= MULTIBYTE_FORM_LENGTH (p
, pend
- p
);
4485 /* Update STARTPOS to the previous character boundary. */
4488 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4490 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4492 /* Find the head of multibyte form. */
4493 PREV_CHAR_BOUNDARY (p
, phead
);
4494 range
+= p0
- 1 - p
;
4498 startpos
-= p0
- 1 - p
;
4504 WEAK_ALIAS (__re_search_2
, re_search_2
)
4506 /* Declarations and macros for re_match_2. */
4508 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4510 RE_TRANSLATE_TYPE translate
,
4511 const int multibyte
));
4513 /* This converts PTR, a pointer into one of the search strings `string1'
4514 and `string2' into an offset from the beginning of that string. */
4515 #define POINTER_TO_OFFSET(ptr) \
4516 (FIRST_STRING_P (ptr) \
4517 ? ((regoff_t) ((ptr) - string1)) \
4518 : ((regoff_t) ((ptr) - string2 + size1)))
4520 /* Call before fetching a character with *d. This switches over to
4521 string2 if necessary.
4522 Check re_match_2_internal for a discussion of why end_match_2 might
4523 not be within string2 (but be equal to end_match_1 instead). */
4524 #define PREFETCH() \
4527 /* End of string2 => fail. */ \
4528 if (dend == end_match_2) \
4530 /* End of string1 => advance to string2. */ \
4532 dend = end_match_2; \
4535 /* Call before fetching a char with *d if you already checked other limits.
4536 This is meant for use in lookahead operations like wordend, etc..
4537 where we might need to look at parts of the string that might be
4538 outside of the LIMITs (i.e past `stop'). */
4539 #define PREFETCH_NOLIMIT() \
4543 dend = end_match_2; \
4546 /* Test if at very beginning or at very end of the virtual concatenation
4547 of `string1' and `string2'. If only one string, it's `string2'. */
4548 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4549 #define AT_STRINGS_END(d) ((d) == end2)
4552 /* Test if D points to a character which is word-constituent. We have
4553 two special cases to check for: if past the end of string1, look at
4554 the first character in string2; and if before the beginning of
4555 string2, look at the last character in string1. */
4556 #define WORDCHAR_P(d) \
4557 (SYNTAX ((d) == end1 ? *string2 \
4558 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4561 /* Disabled due to a compiler bug -- see comment at case wordbound */
4563 /* The comment at case wordbound is following one, but we don't use
4564 AT_WORD_BOUNDARY anymore to support multibyte form.
4566 The DEC Alpha C compiler 3.x generates incorrect code for the
4567 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4568 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4569 macro and introducing temporary variables works around the bug. */
4572 /* Test if the character before D and the one at D differ with respect
4573 to being word-constituent. */
4574 #define AT_WORD_BOUNDARY(d) \
4575 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4576 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4579 /* Free everything we malloc. */
4580 #ifdef MATCH_MAY_ALLOCATE
4581 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4582 # define FREE_VARIABLES() \
4584 REGEX_FREE_STACK (fail_stack.stack); \
4585 FREE_VAR (regstart); \
4586 FREE_VAR (regend); \
4587 FREE_VAR (best_regstart); \
4588 FREE_VAR (best_regend); \
4591 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4592 #endif /* not MATCH_MAY_ALLOCATE */
4595 /* Optimization routines. */
4597 /* If the operation is a match against one or more chars,
4598 return a pointer to the next operation, else return NULL. */
4603 switch (SWITCH_ENUM_CAST (*p
++))
4614 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4617 p
= CHARSET_RANGE_TABLE (p
- 1);
4618 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4619 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4622 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4629 case notcategoryspec
:
4641 /* Jump over non-matching operations. */
4643 skip_noops (p
, pend
)
4649 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4658 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4669 /* Non-zero if "p1 matches something" implies "p2 fails". */
4671 mutually_exclusive_p (bufp
, p1
, p2
)
4672 struct re_pattern_buffer
*bufp
;
4676 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4677 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4679 assert (p1
>= bufp
->buffer
&& p1
< pend
4680 && p2
>= bufp
->buffer
&& p2
<= pend
);
4682 /* Skip over open/close-group commands.
4683 If what follows this loop is a ...+ construct,
4684 look at what begins its body, since we will have to
4685 match at least one of that. */
4686 p2
= skip_noops (p2
, pend
);
4687 /* The same skip can be done for p1, except that this function
4688 is only used in the case where p1 is a simple match operator. */
4689 /* p1 = skip_noops (p1, pend); */
4691 assert (p1
>= bufp
->buffer
&& p1
< pend
4692 && p2
>= bufp
->buffer
&& p2
<= pend
);
4694 op2
= p2
== pend
? succeed
: *p2
;
4696 switch (SWITCH_ENUM_CAST (op2
))
4700 /* If we're at the end of the pattern, we can change. */
4701 if (skip_one_char (p1
))
4703 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4711 register re_wchar_t c
4712 = (re_opcode_t
) *p2
== endline
? '\n'
4713 : RE_STRING_CHAR (p2
+ 2, pend
- p2
- 2);
4715 if ((re_opcode_t
) *p1
== exactn
)
4717 if (c
!= RE_STRING_CHAR (p1
+ 2, pend
- p1
- 2))
4719 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4724 else if ((re_opcode_t
) *p1
== charset
4725 || (re_opcode_t
) *p1
== charset_not
)
4727 int not = (re_opcode_t
) *p1
== charset_not
;
4729 /* Test if C is listed in charset (or charset_not)
4731 if (! multibyte
|| IS_REAL_ASCII (c
))
4733 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4734 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4737 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4738 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4740 /* `not' is equal to 1 if c would match, which means
4741 that we can't change to pop_failure_jump. */
4744 DEBUG_PRINT1 (" No match => fast loop.\n");
4748 else if ((re_opcode_t
) *p1
== anychar
4751 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4759 if ((re_opcode_t
) *p1
== exactn
)
4760 /* Reuse the code above. */
4761 return mutually_exclusive_p (bufp
, p2
, p1
);
4763 /* It is hard to list up all the character in charset
4764 P2 if it includes multibyte character. Give up in
4766 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4768 /* Now, we are sure that P2 has no range table.
4769 So, for the size of bitmap in P2, `p2[1]' is
4770 enough. But P1 may have range table, so the
4771 size of bitmap table of P1 is extracted by
4772 using macro `CHARSET_BITMAP_SIZE'.
4774 In a multibyte case, we know that all the character
4775 listed in P2 is ASCII. In a unibyte case, P1 has only a
4776 bitmap table. So, in both cases, it is enough to test
4777 only the bitmap table of P1. */
4779 if ((re_opcode_t
) *p1
== charset
)
4782 /* We win if the charset inside the loop
4783 has no overlap with the one after the loop. */
4786 && idx
< CHARSET_BITMAP_SIZE (p1
));
4788 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4792 || idx
== CHARSET_BITMAP_SIZE (p1
))
4794 DEBUG_PRINT1 (" No match => fast loop.\n");
4798 else if ((re_opcode_t
) *p1
== charset_not
)
4801 /* We win if the charset_not inside the loop lists
4802 every character listed in the charset after. */
4803 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4804 if (! (p2
[2 + idx
] == 0
4805 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4806 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4811 DEBUG_PRINT1 (" No match => fast loop.\n");
4820 switch (SWITCH_ENUM_CAST (*p1
))
4824 /* Reuse the code above. */
4825 return mutually_exclusive_p (bufp
, p2
, p1
);
4827 /* When we have two charset_not, it's very unlikely that
4828 they don't overlap. The union of the two sets of excluded
4829 chars should cover all possible chars, which, as a matter of
4830 fact, is virtually impossible in multibyte buffers. */
4836 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4838 return ((re_opcode_t
) *p1
== syntaxspec
4839 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4841 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4844 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4846 return ((re_opcode_t
) *p1
== notsyntaxspec
4847 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4849 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4852 return (((re_opcode_t
) *p1
== notsyntaxspec
4853 || (re_opcode_t
) *p1
== syntaxspec
)
4858 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4859 case notcategoryspec
:
4860 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4872 /* Matching routines. */
4874 #ifndef emacs /* Emacs never uses this. */
4875 /* re_match is like re_match_2 except it takes only a single string. */
4878 re_match (bufp
, string
, size
, pos
, regs
)
4879 struct re_pattern_buffer
*bufp
;
4882 struct re_registers
*regs
;
4884 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
4886 # if defined C_ALLOCA && !defined REGEX_MALLOC
4891 WEAK_ALIAS (__re_match
, re_match
)
4892 #endif /* not emacs */
4895 /* In Emacs, this is the string or buffer in which we
4896 are matching. It is used for looking up syntax properties. */
4897 Lisp_Object re_match_object
;
4900 /* re_match_2 matches the compiled pattern in BUFP against the
4901 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4902 and SIZE2, respectively). We start matching at POS, and stop
4905 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4906 store offsets for the substring each group matched in REGS. See the
4907 documentation for exactly how many groups we fill.
4909 We return -1 if no match, -2 if an internal error (such as the
4910 failure stack overflowing). Otherwise, we return the length of the
4911 matched substring. */
4914 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4915 struct re_pattern_buffer
*bufp
;
4916 const char *string1
, *string2
;
4919 struct re_registers
*regs
;
4926 gl_state
.object
= re_match_object
;
4927 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4928 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4931 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4932 (re_char
*) string2
, size2
,
4934 #if defined C_ALLOCA && !defined REGEX_MALLOC
4939 WEAK_ALIAS (__re_match_2
, re_match_2
)
4942 #define TRANSLATE_VIA_MULTIBYTE(c) \
4945 (c) = TRANSLATE (c); \
4948 MAKE_CHAR_MULTIBYTE (c); \
4949 (c) = TRANSLATE (c); \
4950 MAKE_CHAR_UNIBYTE (c); \
4955 #define TRANSLATE_VIA_MULTIBYTE(c) ((c) = TRANSLATE (c))
4959 /* This is a separate function so that we can force an alloca cleanup
4962 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4963 struct re_pattern_buffer
*bufp
;
4964 re_char
*string1
, *string2
;
4967 struct re_registers
*regs
;
4970 /* General temporaries. */
4975 /* Just past the end of the corresponding string. */
4976 re_char
*end1
, *end2
;
4978 /* Pointers into string1 and string2, just past the last characters in
4979 each to consider matching. */
4980 re_char
*end_match_1
, *end_match_2
;
4982 /* Where we are in the data, and the end of the current string. */
4985 /* Used sometimes to remember where we were before starting matching
4986 an operator so that we can go back in case of failure. This "atomic"
4987 behavior of matching opcodes is indispensable to the correctness
4988 of the on_failure_keep_string_jump optimization. */
4991 /* Where we are in the pattern, and the end of the pattern. */
4992 re_char
*p
= bufp
->buffer
;
4993 re_char
*pend
= p
+ bufp
->used
;
4995 /* We use this to map every character in the string. */
4996 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4998 /* Nonzero if BUFP is setup for multibyte characters. We are sure
4999 that it is the same as RE_TARGET_MULTIBYTE_P (bufp). */
5000 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
5002 /* Failure point stack. Each place that can handle a failure further
5003 down the line pushes a failure point on this stack. It consists of
5004 regstart, and regend for all registers corresponding to
5005 the subexpressions we're currently inside, plus the number of such
5006 registers, and, finally, two char *'s. The first char * is where
5007 to resume scanning the pattern; the second one is where to resume
5008 scanning the strings. */
5009 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5010 fail_stack_type fail_stack
;
5013 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
5016 #if defined REL_ALLOC && defined REGEX_MALLOC
5017 /* This holds the pointer to the failure stack, when
5018 it is allocated relocatably. */
5019 fail_stack_elt_t
*failure_stack_ptr
;
5022 /* We fill all the registers internally, independent of what we
5023 return, for use in backreferences. The number here includes
5024 an element for register zero. */
5025 size_t num_regs
= bufp
->re_nsub
+ 1;
5027 /* Information on the contents of registers. These are pointers into
5028 the input strings; they record just what was matched (on this
5029 attempt) by a subexpression part of the pattern, that is, the
5030 regnum-th regstart pointer points to where in the pattern we began
5031 matching and the regnum-th regend points to right after where we
5032 stopped matching the regnum-th subexpression. (The zeroth register
5033 keeps track of what the whole pattern matches.) */
5034 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5035 re_char
**regstart
, **regend
;
5038 /* The following record the register info as found in the above
5039 variables when we find a match better than any we've seen before.
5040 This happens as we backtrack through the failure points, which in
5041 turn happens only if we have not yet matched the entire string. */
5042 unsigned best_regs_set
= false;
5043 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5044 re_char
**best_regstart
, **best_regend
;
5047 /* Logically, this is `best_regend[0]'. But we don't want to have to
5048 allocate space for that if we're not allocating space for anything
5049 else (see below). Also, we never need info about register 0 for
5050 any of the other register vectors, and it seems rather a kludge to
5051 treat `best_regend' differently than the rest. So we keep track of
5052 the end of the best match so far in a separate variable. We
5053 initialize this to NULL so that when we backtrack the first time
5054 and need to test it, it's not garbage. */
5055 re_char
*match_end
= NULL
;
5058 /* Counts the total number of registers pushed. */
5059 unsigned num_regs_pushed
= 0;
5062 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5066 #ifdef MATCH_MAY_ALLOCATE
5067 /* Do not bother to initialize all the register variables if there are
5068 no groups in the pattern, as it takes a fair amount of time. If
5069 there are groups, we include space for register 0 (the whole
5070 pattern), even though we never use it, since it simplifies the
5071 array indexing. We should fix this. */
5074 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5075 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5076 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5077 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5079 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5087 /* We must initialize all our variables to NULL, so that
5088 `FREE_VARIABLES' doesn't try to free them. */
5089 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5091 #endif /* MATCH_MAY_ALLOCATE */
5093 /* The starting position is bogus. */
5094 if (pos
< 0 || pos
> size1
+ size2
)
5100 /* Initialize subexpression text positions to -1 to mark ones that no
5101 start_memory/stop_memory has been seen for. Also initialize the
5102 register information struct. */
5103 for (reg
= 1; reg
< num_regs
; reg
++)
5104 regstart
[reg
] = regend
[reg
] = NULL
;
5106 /* We move `string1' into `string2' if the latter's empty -- but not if
5107 `string1' is null. */
5108 if (size2
== 0 && string1
!= NULL
)
5115 end1
= string1
+ size1
;
5116 end2
= string2
+ size2
;
5118 /* `p' scans through the pattern as `d' scans through the data.
5119 `dend' is the end of the input string that `d' points within. `d'
5120 is advanced into the following input string whenever necessary, but
5121 this happens before fetching; therefore, at the beginning of the
5122 loop, `d' can be pointing at the end of a string, but it cannot
5126 /* Only match within string2. */
5127 d
= string2
+ pos
- size1
;
5128 dend
= end_match_2
= string2
+ stop
- size1
;
5129 end_match_1
= end1
; /* Just to give it a value. */
5135 /* Only match within string1. */
5136 end_match_1
= string1
+ stop
;
5138 When we reach end_match_1, PREFETCH normally switches to string2.
5139 But in the present case, this means that just doing a PREFETCH
5140 makes us jump from `stop' to `gap' within the string.
5141 What we really want here is for the search to stop as
5142 soon as we hit end_match_1. That's why we set end_match_2
5143 to end_match_1 (since PREFETCH fails as soon as we hit
5145 end_match_2
= end_match_1
;
5148 { /* It's important to use this code when stop == size so that
5149 moving `d' from end1 to string2 will not prevent the d == dend
5150 check from catching the end of string. */
5152 end_match_2
= string2
+ stop
- size1
;
5158 DEBUG_PRINT1 ("The compiled pattern is: ");
5159 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5160 DEBUG_PRINT1 ("The string to match is: `");
5161 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5162 DEBUG_PRINT1 ("'\n");
5164 /* This loops over pattern commands. It exits by returning from the
5165 function if the match is complete, or it drops through if the match
5166 fails at this starting point in the input data. */
5169 DEBUG_PRINT2 ("\n%p: ", p
);
5172 { /* End of pattern means we might have succeeded. */
5173 DEBUG_PRINT1 ("end of pattern ... ");
5175 /* If we haven't matched the entire string, and we want the
5176 longest match, try backtracking. */
5177 if (d
!= end_match_2
)
5179 /* 1 if this match ends in the same string (string1 or string2)
5180 as the best previous match. */
5181 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5182 == FIRST_STRING_P (d
));
5183 /* 1 if this match is the best seen so far. */
5184 boolean best_match_p
;
5186 /* AIX compiler got confused when this was combined
5187 with the previous declaration. */
5189 best_match_p
= d
> match_end
;
5191 best_match_p
= !FIRST_STRING_P (d
);
5193 DEBUG_PRINT1 ("backtracking.\n");
5195 if (!FAIL_STACK_EMPTY ())
5196 { /* More failure points to try. */
5198 /* If exceeds best match so far, save it. */
5199 if (!best_regs_set
|| best_match_p
)
5201 best_regs_set
= true;
5204 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5206 for (reg
= 1; reg
< num_regs
; reg
++)
5208 best_regstart
[reg
] = regstart
[reg
];
5209 best_regend
[reg
] = regend
[reg
];
5215 /* If no failure points, don't restore garbage. And if
5216 last match is real best match, don't restore second
5218 else if (best_regs_set
&& !best_match_p
)
5221 /* Restore best match. It may happen that `dend ==
5222 end_match_1' while the restored d is in string2.
5223 For example, the pattern `x.*y.*z' against the
5224 strings `x-' and `y-z-', if the two strings are
5225 not consecutive in memory. */
5226 DEBUG_PRINT1 ("Restoring best registers.\n");
5229 dend
= ((d
>= string1
&& d
<= end1
)
5230 ? end_match_1
: end_match_2
);
5232 for (reg
= 1; reg
< num_regs
; reg
++)
5234 regstart
[reg
] = best_regstart
[reg
];
5235 regend
[reg
] = best_regend
[reg
];
5238 } /* d != end_match_2 */
5241 DEBUG_PRINT1 ("Accepting match.\n");
5243 /* If caller wants register contents data back, do it. */
5244 if (regs
&& !bufp
->no_sub
)
5246 /* Have the register data arrays been allocated? */
5247 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5248 { /* No. So allocate them with malloc. We need one
5249 extra element beyond `num_regs' for the `-1' marker
5251 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5252 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5253 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5254 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5259 bufp
->regs_allocated
= REGS_REALLOCATE
;
5261 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5262 { /* Yes. If we need more elements than were already
5263 allocated, reallocate them. If we need fewer, just
5265 if (regs
->num_regs
< num_regs
+ 1)
5267 regs
->num_regs
= num_regs
+ 1;
5268 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5269 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5270 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5279 /* These braces fend off a "empty body in an else-statement"
5280 warning under GCC when assert expands to nothing. */
5281 assert (bufp
->regs_allocated
== REGS_FIXED
);
5284 /* Convert the pointer data in `regstart' and `regend' to
5285 indices. Register zero has to be set differently,
5286 since we haven't kept track of any info for it. */
5287 if (regs
->num_regs
> 0)
5289 regs
->start
[0] = pos
;
5290 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5293 /* Go through the first `min (num_regs, regs->num_regs)'
5294 registers, since that is all we initialized. */
5295 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5297 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5298 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5302 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
5304 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
5308 /* If the regs structure we return has more elements than
5309 were in the pattern, set the extra elements to -1. If
5310 we (re)allocated the registers, this is the case,
5311 because we always allocate enough to have at least one
5313 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5314 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5315 } /* regs && !bufp->no_sub */
5317 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5318 nfailure_points_pushed
, nfailure_points_popped
,
5319 nfailure_points_pushed
- nfailure_points_popped
);
5320 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
5322 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
5324 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5330 /* Otherwise match next pattern command. */
5331 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5333 /* Ignore these. Used to ignore the n of succeed_n's which
5334 currently have n == 0. */
5336 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5340 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5343 /* Match the next n pattern characters exactly. The following
5344 byte in the pattern defines n, and the n bytes after that
5345 are the characters to match. */
5348 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5350 /* Remember the start point to rollback upon failure. */
5354 /* This is written out as an if-else so we don't waste time
5355 testing `translate' inside the loop. */
5356 if (RE_TRANSLATE_P (translate
))
5360 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5380 /* The cost of testing `translate' is comparatively small. */
5384 int pat_charlen
, buf_charlen
;
5385 unsigned int pat_ch
, buf_ch
;
5388 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
5389 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
5391 if (TRANSLATE (buf_ch
) != pat_ch
)
5399 mcnt
-= pat_charlen
;
5405 unsigned int buf_ch
;
5409 TRANSLATE_VIA_MULTIBYTE (buf_ch
);
5421 /* Match any character except possibly a newline or a null. */
5427 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5430 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
5431 buf_ch
= TRANSLATE (buf_ch
);
5433 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5435 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5436 && buf_ch
== '\000'))
5439 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5448 register unsigned int c
;
5449 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5452 /* Start of actual range_table, or end of bitmap if there is no
5454 re_char
*range_table
;
5456 /* Nonzero if there is a range table. */
5457 int range_table_exists
;
5459 /* Number of ranges of range table. This is not included
5460 in the initial byte-length of the command. */
5463 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5465 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5467 if (range_table_exists
)
5469 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5470 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5474 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5475 TRANSLATE_VIA_MULTIBYTE (c
); /* The character to match. */
5477 if (! multibyte
|| IS_REAL_ASCII (c
))
5478 { /* Lookup bitmap. */
5479 /* Cast to `unsigned' instead of `unsigned char' in
5480 case the bit list is a full 32 bytes long. */
5481 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5482 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5486 else if (range_table_exists
)
5488 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5490 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5491 | (class_bits
& BIT_MULTIBYTE
)
5492 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5493 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5494 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5495 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5498 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5502 if (range_table_exists
)
5503 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5505 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5507 if (!not) goto fail
;
5514 /* The beginning of a group is represented by start_memory.
5515 The argument is the register number. The text
5516 matched within the group is recorded (in the internal
5517 registers data structure) under the register number. */
5519 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5521 /* In case we need to undo this operation (via backtracking). */
5522 PUSH_FAILURE_REG ((unsigned int)*p
);
5525 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5526 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5528 /* Move past the register number and inner group count. */
5533 /* The stop_memory opcode represents the end of a group. Its
5534 argument is the same as start_memory's: the register number. */
5536 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5538 assert (!REG_UNSET (regstart
[*p
]));
5539 /* Strictly speaking, there should be code such as:
5541 assert (REG_UNSET (regend[*p]));
5542 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5544 But the only info to be pushed is regend[*p] and it is known to
5545 be UNSET, so there really isn't anything to push.
5546 Not pushing anything, on the other hand deprives us from the
5547 guarantee that regend[*p] is UNSET since undoing this operation
5548 will not reset its value properly. This is not important since
5549 the value will only be read on the next start_memory or at
5550 the very end and both events can only happen if this stop_memory
5554 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5556 /* Move past the register number and the inner group count. */
5561 /* \<digit> has been turned into a `duplicate' command which is
5562 followed by the numeric value of <digit> as the register number. */
5565 register re_char
*d2
, *dend2
;
5566 int regno
= *p
++; /* Get which register to match against. */
5567 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5569 /* Can't back reference a group which we've never matched. */
5570 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5573 /* Where in input to try to start matching. */
5574 d2
= regstart
[regno
];
5576 /* Remember the start point to rollback upon failure. */
5579 /* Where to stop matching; if both the place to start and
5580 the place to stop matching are in the same string, then
5581 set to the place to stop, otherwise, for now have to use
5582 the end of the first string. */
5584 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5585 == FIRST_STRING_P (regend
[regno
]))
5586 ? regend
[regno
] : end_match_1
);
5589 /* If necessary, advance to next segment in register
5593 if (dend2
== end_match_2
) break;
5594 if (dend2
== regend
[regno
]) break;
5596 /* End of string1 => advance to string2. */
5598 dend2
= regend
[regno
];
5600 /* At end of register contents => success */
5601 if (d2
== dend2
) break;
5603 /* If necessary, advance to next segment in data. */
5606 /* How many characters left in this segment to match. */
5609 /* Want how many consecutive characters we can match in
5610 one shot, so, if necessary, adjust the count. */
5611 if (mcnt
> dend2
- d2
)
5614 /* Compare that many; failure if mismatch, else move
5616 if (RE_TRANSLATE_P (translate
)
5617 ? bcmp_translate (d
, d2
, mcnt
, translate
, multibyte
)
5618 : memcmp (d
, d2
, mcnt
))
5623 d
+= mcnt
, d2
+= mcnt
;
5629 /* begline matches the empty string at the beginning of the string
5630 (unless `not_bol' is set in `bufp'), and after newlines. */
5632 DEBUG_PRINT1 ("EXECUTING begline.\n");
5634 if (AT_STRINGS_BEG (d
))
5636 if (!bufp
->not_bol
) break;
5641 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5645 /* In all other cases, we fail. */
5649 /* endline is the dual of begline. */
5651 DEBUG_PRINT1 ("EXECUTING endline.\n");
5653 if (AT_STRINGS_END (d
))
5655 if (!bufp
->not_eol
) break;
5659 PREFETCH_NOLIMIT ();
5666 /* Match at the very beginning of the data. */
5668 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5669 if (AT_STRINGS_BEG (d
))
5674 /* Match at the very end of the data. */
5676 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5677 if (AT_STRINGS_END (d
))
5682 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5683 pushes NULL as the value for the string on the stack. Then
5684 `POP_FAILURE_POINT' will keep the current value for the
5685 string, instead of restoring it. To see why, consider
5686 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5687 then the . fails against the \n. But the next thing we want
5688 to do is match the \n against the \n; if we restored the
5689 string value, we would be back at the foo.
5691 Because this is used only in specific cases, we don't need to
5692 check all the things that `on_failure_jump' does, to make
5693 sure the right things get saved on the stack. Hence we don't
5694 share its code. The only reason to push anything on the
5695 stack at all is that otherwise we would have to change
5696 `anychar's code to do something besides goto fail in this
5697 case; that seems worse than this. */
5698 case on_failure_keep_string_jump
:
5699 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5700 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5703 PUSH_FAILURE_POINT (p
- 3, NULL
);
5706 /* A nasty loop is introduced by the non-greedy *? and +?.
5707 With such loops, the stack only ever contains one failure point
5708 at a time, so that a plain on_failure_jump_loop kind of
5709 cycle detection cannot work. Worse yet, such a detection
5710 can not only fail to detect a cycle, but it can also wrongly
5711 detect a cycle (between different instantiations of the same
5713 So the method used for those nasty loops is a little different:
5714 We use a special cycle-detection-stack-frame which is pushed
5715 when the on_failure_jump_nastyloop failure-point is *popped*.
5716 This special frame thus marks the beginning of one iteration
5717 through the loop and we can hence easily check right here
5718 whether something matched between the beginning and the end of
5720 case on_failure_jump_nastyloop
:
5721 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5722 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5725 assert ((re_opcode_t
)p
[-4] == no_op
);
5728 CHECK_INFINITE_LOOP (p
- 4, d
);
5730 /* If there's a cycle, just continue without pushing
5731 this failure point. The failure point is the "try again"
5732 option, which shouldn't be tried.
5733 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5734 PUSH_FAILURE_POINT (p
- 3, d
);
5738 /* Simple loop detecting on_failure_jump: just check on the
5739 failure stack if the same spot was already hit earlier. */
5740 case on_failure_jump_loop
:
5742 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5743 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5747 CHECK_INFINITE_LOOP (p
- 3, d
);
5749 /* If there's a cycle, get out of the loop, as if the matching
5750 had failed. We used to just `goto fail' here, but that was
5751 aborting the search a bit too early: we want to keep the
5752 empty-loop-match and keep matching after the loop.
5753 We want (x?)*y\1z to match both xxyz and xxyxz. */
5756 PUSH_FAILURE_POINT (p
- 3, d
);
5761 /* Uses of on_failure_jump:
5763 Each alternative starts with an on_failure_jump that points
5764 to the beginning of the next alternative. Each alternative
5765 except the last ends with a jump that in effect jumps past
5766 the rest of the alternatives. (They really jump to the
5767 ending jump of the following alternative, because tensioning
5768 these jumps is a hassle.)
5770 Repeats start with an on_failure_jump that points past both
5771 the repetition text and either the following jump or
5772 pop_failure_jump back to this on_failure_jump. */
5773 case on_failure_jump
:
5774 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5775 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5778 PUSH_FAILURE_POINT (p
-3, d
);
5781 /* This operation is used for greedy *.
5782 Compare the beginning of the repeat with what in the
5783 pattern follows its end. If we can establish that there
5784 is nothing that they would both match, i.e., that we
5785 would have to backtrack because of (as in, e.g., `a*a')
5786 then we can use a non-backtracking loop based on
5787 on_failure_keep_string_jump instead of on_failure_jump. */
5788 case on_failure_jump_smart
:
5789 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5790 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5793 re_char
*p1
= p
; /* Next operation. */
5794 /* Here, we discard `const', making re_match non-reentrant. */
5795 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5796 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5798 p
-= 3; /* Reset so that we will re-execute the
5799 instruction once it's been changed. */
5801 EXTRACT_NUMBER (mcnt
, p2
- 2);
5803 /* Ensure this is a indeed the trivial kind of loop
5804 we are expecting. */
5805 assert (skip_one_char (p1
) == p2
- 3);
5806 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5807 DEBUG_STATEMENT (debug
+= 2);
5808 if (mutually_exclusive_p (bufp
, p1
, p2
))
5810 /* Use a fast `on_failure_keep_string_jump' loop. */
5811 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5812 *p3
= (unsigned char) on_failure_keep_string_jump
;
5813 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5817 /* Default to a safe `on_failure_jump' loop. */
5818 DEBUG_PRINT1 (" smart default => slow loop.\n");
5819 *p3
= (unsigned char) on_failure_jump
;
5821 DEBUG_STATEMENT (debug
-= 2);
5825 /* Unconditionally jump (without popping any failure points). */
5828 IMMEDIATE_QUIT_CHECK
;
5829 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5830 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5831 p
+= mcnt
; /* Do the jump. */
5832 DEBUG_PRINT2 ("(to %p).\n", p
);
5836 /* Have to succeed matching what follows at least n times.
5837 After that, handle like `on_failure_jump'. */
5839 /* Signedness doesn't matter since we only compare MCNT to 0. */
5840 EXTRACT_NUMBER (mcnt
, p
+ 2);
5841 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5843 /* Originally, mcnt is how many times we HAVE to succeed. */
5846 /* Here, we discard `const', making re_match non-reentrant. */
5847 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5850 PUSH_NUMBER (p2
, mcnt
);
5853 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5858 /* Signedness doesn't matter since we only compare MCNT to 0. */
5859 EXTRACT_NUMBER (mcnt
, p
+ 2);
5860 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5862 /* Originally, this is how many times we CAN jump. */
5865 /* Here, we discard `const', making re_match non-reentrant. */
5866 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5868 PUSH_NUMBER (p2
, mcnt
);
5869 goto unconditional_jump
;
5871 /* If don't have to jump any more, skip over the rest of command. */
5878 unsigned char *p2
; /* Location of the counter. */
5879 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5881 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5882 /* Here, we discard `const', making re_match non-reentrant. */
5883 p2
= (unsigned char*) p
+ mcnt
;
5884 /* Signedness doesn't matter since we only copy MCNT's bits . */
5885 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5886 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5887 PUSH_NUMBER (p2
, mcnt
);
5893 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5894 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5896 /* We SUCCEED (or FAIL) in one of the following cases: */
5898 /* Case 1: D is at the beginning or the end of string. */
5899 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5903 /* C1 is the character before D, S1 is the syntax of C1, C2
5904 is the character at D, and S2 is the syntax of C2. */
5909 int offset
= PTR_TO_OFFSET (d
- 1);
5910 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5911 UPDATE_SYNTAX_TABLE (charpos
);
5913 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5916 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5918 PREFETCH_NOLIMIT ();
5919 GET_CHAR_AFTER (c2
, d
, dummy
);
5922 if (/* Case 2: Only one of S1 and S2 is Sword. */
5923 ((s1
== Sword
) != (s2
== Sword
))
5924 /* Case 3: Both of S1 and S2 are Sword, and macro
5925 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5926 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5935 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5937 /* We FAIL in one of the following cases: */
5939 /* Case 1: D is at the end of string. */
5940 if (AT_STRINGS_END (d
))
5944 /* C1 is the character before D, S1 is the syntax of C1, C2
5945 is the character at D, and S2 is the syntax of C2. */
5950 int offset
= PTR_TO_OFFSET (d
);
5951 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5952 UPDATE_SYNTAX_TABLE (charpos
);
5955 GET_CHAR_AFTER (c2
, d
, dummy
);
5958 /* Case 2: S2 is not Sword. */
5962 /* Case 3: D is not at the beginning of string ... */
5963 if (!AT_STRINGS_BEG (d
))
5965 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5967 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5971 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5973 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5980 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5982 /* We FAIL in one of the following cases: */
5984 /* Case 1: D is at the beginning of string. */
5985 if (AT_STRINGS_BEG (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 int offset
= PTR_TO_OFFSET (d
) - 1;
5996 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5997 UPDATE_SYNTAX_TABLE (charpos
);
5999 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6002 /* Case 2: S1 is not Sword. */
6006 /* Case 3: D is not at the end of string ... */
6007 if (!AT_STRINGS_END (d
))
6009 PREFETCH_NOLIMIT ();
6010 GET_CHAR_AFTER (c2
, d
, dummy
);
6012 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6016 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6018 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6025 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6027 /* We FAIL in one of the following cases: */
6029 /* Case 1: D is at the end of string. */
6030 if (AT_STRINGS_END (d
))
6034 /* C1 is the character before D, S1 is the syntax of C1, C2
6035 is the character at D, and S2 is the syntax of C2. */
6039 int offset
= PTR_TO_OFFSET (d
);
6040 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6041 UPDATE_SYNTAX_TABLE (charpos
);
6044 c2
= RE_STRING_CHAR (d
, dend
- d
);
6047 /* Case 2: S2 is neither Sword nor Ssymbol. */
6048 if (s2
!= Sword
&& s2
!= Ssymbol
)
6051 /* Case 3: D is not at the beginning of string ... */
6052 if (!AT_STRINGS_BEG (d
))
6054 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6056 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6060 /* ... and S1 is Sword or Ssymbol. */
6061 if (s1
== Sword
|| s1
== Ssymbol
)
6068 DEBUG_PRINT1 ("EXECUTING symend.\n");
6070 /* We FAIL in one of the following cases: */
6072 /* Case 1: D is at the beginning of string. */
6073 if (AT_STRINGS_BEG (d
))
6077 /* C1 is the character before D, S1 is the syntax of C1, C2
6078 is the character at D, and S2 is the syntax of C2. */
6082 int offset
= PTR_TO_OFFSET (d
) - 1;
6083 int 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 neither Ssymbol nor Sword. */
6090 if (s1
!= Sword
&& s1
!= Ssymbol
)
6093 /* Case 3: D is not at the end of string ... */
6094 if (!AT_STRINGS_END (d
))
6096 PREFETCH_NOLIMIT ();
6097 c2
= RE_STRING_CHAR (d
, dend
- d
);
6099 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6103 /* ... and S2 is Sword or Ssymbol. */
6104 if (s2
== Sword
|| s2
== Ssymbol
)
6112 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6114 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
6118 int offset
= PTR_TO_OFFSET (d
);
6119 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6120 UPDATE_SYNTAX_TABLE (pos1
);
6127 GET_CHAR_AFTER (c
, d
, len
);
6128 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6136 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6137 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6142 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6143 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6148 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6149 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6154 case notcategoryspec
:
6155 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6157 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
6163 GET_CHAR_AFTER (c
, d
, len
);
6164 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6175 continue; /* Successfully executed one pattern command; keep going. */
6178 /* We goto here if a matching operation fails. */
6180 IMMEDIATE_QUIT_CHECK
;
6181 if (!FAIL_STACK_EMPTY ())
6184 /* A restart point is known. Restore to that state. */
6185 DEBUG_PRINT1 ("\nFAIL:\n");
6186 POP_FAILURE_POINT (str
, pat
);
6187 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
6189 case on_failure_keep_string_jump
:
6190 assert (str
== NULL
);
6191 goto continue_failure_jump
;
6193 case on_failure_jump_nastyloop
:
6194 assert ((re_opcode_t
)pat
[-2] == no_op
);
6195 PUSH_FAILURE_POINT (pat
- 2, str
);
6198 case on_failure_jump_loop
:
6199 case on_failure_jump
:
6202 continue_failure_jump
:
6203 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6208 /* A special frame used for nastyloops. */
6215 assert (p
>= bufp
->buffer
&& p
<= pend
);
6217 if (d
>= string1
&& d
<= end1
)
6221 break; /* Matching at this starting point really fails. */
6225 goto restore_best_regs
;
6229 return -1; /* Failure to match. */
6232 /* Subroutine definitions for re_match_2. */
6234 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6235 bytes; nonzero otherwise. */
6238 bcmp_translate (s1
, s2
, len
, translate
, multibyte
)
6241 RE_TRANSLATE_TYPE translate
;
6242 const int multibyte
;
6244 register re_char
*p1
= s1
, *p2
= s2
;
6245 re_char
*p1_end
= s1
+ len
;
6246 re_char
*p2_end
= s2
+ len
;
6248 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6249 different lengths, but relying on a single `len' would break this. -sm */
6250 while (p1
< p1_end
&& p2
< p2_end
)
6252 int p1_charlen
, p2_charlen
;
6253 re_wchar_t p1_ch
, p2_ch
;
6255 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6256 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6258 if (RE_TRANSLATE (translate
, p1_ch
)
6259 != RE_TRANSLATE (translate
, p2_ch
))
6262 p1
+= p1_charlen
, p2
+= p2_charlen
;
6265 if (p1
!= p1_end
|| p2
!= p2_end
)
6271 /* Entry points for GNU code. */
6273 /* re_compile_pattern is the GNU regular expression compiler: it
6274 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6275 Returns 0 if the pattern was valid, otherwise an error string.
6277 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6278 are set in BUFP on entry.
6280 We call regex_compile to do the actual compilation. */
6283 re_compile_pattern (pattern
, length
, bufp
)
6284 const char *pattern
;
6286 struct re_pattern_buffer
*bufp
;
6290 /* GNU code is written to assume at least RE_NREGS registers will be set
6291 (and at least one extra will be -1). */
6292 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6294 /* And GNU code determines whether or not to get register information
6295 by passing null for the REGS argument to re_match, etc., not by
6299 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6303 return gettext (re_error_msgid
[(int) ret
]);
6305 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6307 /* Entry points compatible with 4.2 BSD regex library. We don't define
6308 them unless specifically requested. */
6310 #if defined _REGEX_RE_COMP || defined _LIBC
6312 /* BSD has one and only one pattern buffer. */
6313 static struct re_pattern_buffer re_comp_buf
;
6317 /* Make these definitions weak in libc, so POSIX programs can redefine
6318 these names if they don't use our functions, and still use
6319 regcomp/regexec below without link errors. */
6329 if (!re_comp_buf
.buffer
)
6330 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6331 return (char *) gettext ("No previous regular expression");
6335 if (!re_comp_buf
.buffer
)
6337 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
6338 if (re_comp_buf
.buffer
== NULL
)
6339 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6340 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6341 re_comp_buf
.allocated
= 200;
6343 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6344 if (re_comp_buf
.fastmap
== NULL
)
6345 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6346 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6349 /* Since `re_exec' always passes NULL for the `regs' argument, we
6350 don't need to initialize the pattern buffer fields which affect it. */
6352 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6357 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6358 return (char *) gettext (re_error_msgid
[(int) ret
]);
6369 const int len
= strlen (s
);
6371 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
6373 #endif /* _REGEX_RE_COMP */
6375 /* POSIX.2 functions. Don't define these for Emacs. */
6379 /* regcomp takes a regular expression as a string and compiles it.
6381 PREG is a regex_t *. We do not expect any fields to be initialized,
6382 since POSIX says we shouldn't. Thus, we set
6384 `buffer' to the compiled pattern;
6385 `used' to the length of the compiled pattern;
6386 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6387 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6388 RE_SYNTAX_POSIX_BASIC;
6389 `fastmap' to an allocated space for the fastmap;
6390 `fastmap_accurate' to zero;
6391 `re_nsub' to the number of subexpressions in PATTERN.
6393 PATTERN is the address of the pattern string.
6395 CFLAGS is a series of bits which affect compilation.
6397 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6398 use POSIX basic syntax.
6400 If REG_NEWLINE is set, then . and [^...] don't match newline.
6401 Also, regexec will try a match beginning after every newline.
6403 If REG_ICASE is set, then we considers upper- and lowercase
6404 versions of letters to be equivalent when matching.
6406 If REG_NOSUB is set, then when PREG is passed to regexec, that
6407 routine will report only success or failure, and nothing about the
6410 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6411 the return codes and their meanings.) */
6414 regcomp (preg
, pattern
, cflags
)
6415 regex_t
*__restrict preg
;
6416 const char *__restrict pattern
;
6421 = (cflags
& REG_EXTENDED
) ?
6422 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6424 /* regex_compile will allocate the space for the compiled pattern. */
6426 preg
->allocated
= 0;
6429 /* Try to allocate space for the fastmap. */
6430 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6432 if (cflags
& REG_ICASE
)
6437 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6438 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6439 if (preg
->translate
== NULL
)
6440 return (int) REG_ESPACE
;
6442 /* Map uppercase characters to corresponding lowercase ones. */
6443 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6444 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6447 preg
->translate
= NULL
;
6449 /* If REG_NEWLINE is set, newlines are treated differently. */
6450 if (cflags
& REG_NEWLINE
)
6451 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6452 syntax
&= ~RE_DOT_NEWLINE
;
6453 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6456 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6458 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6460 /* POSIX says a null character in the pattern terminates it, so we
6461 can use strlen here in compiling the pattern. */
6462 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6464 /* POSIX doesn't distinguish between an unmatched open-group and an
6465 unmatched close-group: both are REG_EPAREN. */
6466 if (ret
== REG_ERPAREN
)
6469 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6470 { /* Compute the fastmap now, since regexec cannot modify the pattern
6472 re_compile_fastmap (preg
);
6473 if (preg
->can_be_null
)
6474 { /* The fastmap can't be used anyway. */
6475 free (preg
->fastmap
);
6476 preg
->fastmap
= NULL
;
6481 WEAK_ALIAS (__regcomp
, regcomp
)
6484 /* regexec searches for a given pattern, specified by PREG, in the
6487 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6488 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6489 least NMATCH elements, and we set them to the offsets of the
6490 corresponding matched substrings.
6492 EFLAGS specifies `execution flags' which affect matching: if
6493 REG_NOTBOL is set, then ^ does not match at the beginning of the
6494 string; if REG_NOTEOL is set, then $ does not match at the end.
6496 We return 0 if we find a match and REG_NOMATCH if not. */
6499 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
6500 const regex_t
*__restrict preg
;
6501 const char *__restrict string
;
6503 regmatch_t pmatch
[__restrict_arr
];
6507 struct re_registers regs
;
6508 regex_t private_preg
;
6509 int len
= strlen (string
);
6510 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6512 private_preg
= *preg
;
6514 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6515 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6517 /* The user has told us exactly how many registers to return
6518 information about, via `nmatch'. We have to pass that on to the
6519 matching routines. */
6520 private_preg
.regs_allocated
= REGS_FIXED
;
6524 regs
.num_regs
= nmatch
;
6525 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6526 if (regs
.start
== NULL
)
6527 return (int) REG_NOMATCH
;
6528 regs
.end
= regs
.start
+ nmatch
;
6531 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6532 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6533 was a little bit longer but still only matching the real part.
6534 This works because the `endline' will check for a '\n' and will find a
6535 '\0', correctly deciding that this is not the end of a line.
6536 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6537 a convenient '\0' there. For all we know, the string could be preceded
6538 by '\n' which would throw things off. */
6540 /* Perform the searching operation. */
6541 ret
= re_search (&private_preg
, string
, len
,
6542 /* start: */ 0, /* range: */ len
,
6543 want_reg_info
? ®s
: (struct re_registers
*) 0);
6545 /* Copy the register information to the POSIX structure. */
6552 for (r
= 0; r
< nmatch
; r
++)
6554 pmatch
[r
].rm_so
= regs
.start
[r
];
6555 pmatch
[r
].rm_eo
= regs
.end
[r
];
6559 /* If we needed the temporary register info, free the space now. */
6563 /* We want zero return to mean success, unlike `re_search'. */
6564 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
6566 WEAK_ALIAS (__regexec
, regexec
)
6569 /* Returns a message corresponding to an error code, ERRCODE, returned
6570 from either regcomp or regexec. We don't use PREG here. */
6573 regerror (errcode
, preg
, errbuf
, errbuf_size
)
6575 const regex_t
*preg
;
6583 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6584 /* Only error codes returned by the rest of the code should be passed
6585 to this routine. If we are given anything else, or if other regex
6586 code generates an invalid error code, then the program has a bug.
6587 Dump core so we can fix it. */
6590 msg
= gettext (re_error_msgid
[errcode
]);
6592 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6594 if (errbuf_size
!= 0)
6596 if (msg_size
> errbuf_size
)
6598 strncpy (errbuf
, msg
, errbuf_size
- 1);
6599 errbuf
[errbuf_size
- 1] = 0;
6602 strcpy (errbuf
, msg
);
6607 WEAK_ALIAS (__regerror
, regerror
)
6610 /* Free dynamically allocated space used by PREG. */
6616 if (preg
->buffer
!= NULL
)
6617 free (preg
->buffer
);
6618 preg
->buffer
= NULL
;
6620 preg
->allocated
= 0;
6623 if (preg
->fastmap
!= NULL
)
6624 free (preg
->fastmap
);
6625 preg
->fastmap
= NULL
;
6626 preg
->fastmap_accurate
= 0;
6628 if (preg
->translate
!= NULL
)
6629 free (preg
->translate
);
6630 preg
->translate
= NULL
;
6632 WEAK_ALIAS (__regfree
, regfree
)
6634 #endif /* not emacs */
6636 /* arch-tag: 4ffd68ba-2a9e-435b-a21a-018990f9eeb2
6637 (do not change this comment) */