1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
6 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
7 Free Software Foundation, Inc.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25 - structure the opcode space into opcode+flag.
26 - merge with glibc's regex.[ch].
27 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
28 need to modify the compiled regexp so that re_match can be reentrant.
29 - get rid of on_failure_jump_smart by doing the optimization in re_comp
30 rather than at run-time, so that re_match can be reentrant.
33 /* AIX requires this to be the first thing in the file. */
34 #if defined _AIX && !defined REGEX_MALLOC
42 #if defined STDC_HEADERS && !defined emacs
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
49 /* Whether to use ISO C Amendment 1 wide char functions.
50 Those should not be used for Emacs since it uses its own. */
52 #define WIDE_CHAR_SUPPORT 1
54 #define WIDE_CHAR_SUPPORT \
55 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
58 /* For platform which support the ISO C amendement 1 functionality we
59 support user defined character classes. */
61 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
67 /* We have to keep the namespace clean. */
68 # define regfree(preg) __regfree (preg)
69 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
70 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
71 # define regerror(err_code, preg, errbuf, errbuf_size) \
72 __regerror(err_code, preg, errbuf, errbuf_size)
73 # define re_set_registers(bu, re, nu, st, en) \
74 __re_set_registers (bu, re, nu, st, en)
75 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
76 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
77 # define re_match(bufp, string, size, pos, regs) \
78 __re_match (bufp, string, size, pos, regs)
79 # define re_search(bufp, string, size, startpos, range, regs) \
80 __re_search (bufp, string, size, startpos, range, regs)
81 # define re_compile_pattern(pattern, length, bufp) \
82 __re_compile_pattern (pattern, length, bufp)
83 # define re_set_syntax(syntax) __re_set_syntax (syntax)
84 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
85 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
86 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
88 /* Make sure we call libc's function even if the user overrides them. */
89 # define btowc __btowc
90 # define iswctype __iswctype
91 # define wctype __wctype
93 # define WEAK_ALIAS(a,b) weak_alias (a, b)
95 /* We are also using some library internals. */
96 # include <locale/localeinfo.h>
97 # include <locale/elem-hash.h>
98 # include <langinfo.h>
100 # define WEAK_ALIAS(a,b)
103 /* This is for other GNU distributions with internationalized messages. */
104 #if HAVE_LIBINTL_H || defined _LIBC
105 # include <libintl.h>
107 # define gettext(msgid) (msgid)
111 /* This define is so xgettext can find the internationalizable
113 # define gettext_noop(String) String
116 /* The `emacs' switch turns on certain matching commands
117 that make sense only in Emacs. */
124 /* Make syntax table lookup grant data in gl_state. */
125 # define SYNTAX_ENTRY_VIA_PROPERTY
128 # include "character.h"
129 # include "category.h"
134 # define malloc xmalloc
138 # define realloc xrealloc
144 /* Converts the pointer to the char to BEG-based offset from the start. */
145 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
146 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
148 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
149 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
150 # define RE_STRING_CHAR(p, multibyte) \
151 (multibyte ? (STRING_CHAR (p)) : (*(p)))
152 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
153 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
155 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
157 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
159 /* Set C a (possibly converted to multibyte) character before P. P
160 points into a string which is the virtual concatenation of STR1
161 (which ends at END1) or STR2 (which ends at END2). */
162 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
164 if (target_multibyte) \
166 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
167 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
168 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
169 c = STRING_CHAR (dtemp); \
173 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
174 (c) = RE_CHAR_TO_MULTIBYTE (c); \
178 /* Set C a (possibly converted to multibyte) character at P, and set
179 LEN to the byte length of that character. */
180 # define GET_CHAR_AFTER(c, p, len) \
182 if (target_multibyte) \
183 (c) = STRING_CHAR_AND_LENGTH (p, len); \
188 (c) = RE_CHAR_TO_MULTIBYTE (c); \
192 #else /* not emacs */
194 /* If we are not linking with Emacs proper,
195 we can't use the relocating allocator
196 even if config.h says that we can. */
199 # ifdef HAVE_UNISTD_H
203 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
206 xmalloc (size_t size
)
209 val
= (void *) malloc (size
);
212 write (2, "virtual memory exhausted\n", 25);
219 xrealloc (void *block
, size_t size
)
222 /* We must call malloc explicitly when BLOCK is 0, since some
223 reallocs don't do this. */
225 val
= (void *) malloc (size
);
227 val
= (void *) realloc (block
, size
);
230 write (2, "virtual memory exhausted\n", 25);
239 # define malloc xmalloc
243 # define realloc xrealloc
245 /* This is the normal way of making sure we have memcpy, memcmp and memset. */
246 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
249 # include <strings.h>
251 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
254 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
258 /* Define the syntax stuff for \<, \>, etc. */
260 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
261 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1, Ssymbol
= 2 };
263 # define SWITCH_ENUM_CAST(x) (x)
265 /* Dummy macros for non-Emacs environments. */
266 # define CHAR_CHARSET(c) 0
267 # define CHARSET_LEADING_CODE_BASE(c) 0
268 # define MAX_MULTIBYTE_LENGTH 1
269 # define RE_MULTIBYTE_P(x) 0
270 # define RE_TARGET_MULTIBYTE_P(x) 0
271 # define WORD_BOUNDARY_P(c1, c2) (0)
272 # define CHAR_HEAD_P(p) (1)
273 # define SINGLE_BYTE_CHAR_P(c) (1)
274 # define SAME_CHARSET_P(c1, c2) (1)
275 # define BYTES_BY_CHAR_HEAD(p) (1)
276 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
277 # define STRING_CHAR(p) (*(p))
278 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
279 # define CHAR_STRING(c, s) (*(s) = (c), 1)
280 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
281 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
282 # define RE_CHAR_TO_MULTIBYTE(c) (c)
283 # define RE_CHAR_TO_UNIBYTE(c) (c)
284 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
285 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
286 # define GET_CHAR_AFTER(c, p, len) \
288 # define MAKE_CHAR(charset, c1, c2) (c1)
289 # define BYTE8_TO_CHAR(c) (c)
290 # define CHAR_BYTE8_P(c) (0)
291 # define CHAR_LEADING_CODE(c) (c)
293 #endif /* not emacs */
296 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
297 # define RE_TRANSLATE_P(TBL) (TBL)
300 /* Get the interface, including the syntax bits. */
303 /* isalpha etc. are used for the character classes. */
308 /* 1 if C is an ASCII character. */
309 # define IS_REAL_ASCII(c) ((c) < 0200)
311 /* 1 if C is a unibyte character. */
312 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
314 /* The Emacs definitions should not be directly affected by locales. */
316 /* In Emacs, these are only used for single-byte characters. */
317 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
318 # define ISCNTRL(c) ((c) < ' ')
319 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
320 || ((c) >= 'a' && (c) <= 'f') \
321 || ((c) >= 'A' && (c) <= 'F'))
323 /* This is only used for single-byte characters. */
324 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
326 /* The rest must handle multibyte characters. */
328 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
329 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
332 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
333 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
336 # define ISALNUM(c) (IS_REAL_ASCII (c) \
337 ? (((c) >= 'a' && (c) <= 'z') \
338 || ((c) >= 'A' && (c) <= 'Z') \
339 || ((c) >= '0' && (c) <= '9')) \
340 : SYNTAX (c) == Sword)
342 # define ISALPHA(c) (IS_REAL_ASCII (c) \
343 ? (((c) >= 'a' && (c) <= 'z') \
344 || ((c) >= 'A' && (c) <= 'Z')) \
345 : SYNTAX (c) == Sword)
347 # define ISLOWER(c) (LOWERCASEP (c))
349 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
350 ? ((c) > ' ' && (c) < 0177 \
351 && !(((c) >= 'a' && (c) <= 'z') \
352 || ((c) >= 'A' && (c) <= 'Z') \
353 || ((c) >= '0' && (c) <= '9'))) \
354 : SYNTAX (c) != Sword)
356 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
358 # define ISUPPER(c) (UPPERCASEP (c))
360 # define ISWORD(c) (SYNTAX (c) == Sword)
362 #else /* not emacs */
364 /* Jim Meyering writes:
366 "... Some ctype macros are valid only for character codes that
367 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
368 using /bin/cc or gcc but without giving an ansi option). So, all
369 ctype uses should be through macros like ISPRINT... If
370 STDC_HEADERS is defined, then autoconf has verified that the ctype
371 macros don't need to be guarded with references to isascii. ...
372 Defining isascii to 1 should let any compiler worth its salt
373 eliminate the && through constant folding."
374 Solaris defines some of these symbols so we must undefine them first. */
377 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
378 # define ISASCII(c) 1
380 # define ISASCII(c) isascii(c)
383 /* 1 if C is an ASCII character. */
384 # define IS_REAL_ASCII(c) ((c) < 0200)
386 /* This distinction is not meaningful, except in Emacs. */
387 # define ISUNIBYTE(c) 1
390 # define ISBLANK(c) (ISASCII (c) && isblank (c))
392 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
395 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
397 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
401 # define ISPRINT(c) (ISASCII (c) && isprint (c))
402 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
403 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
404 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
405 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
406 # define ISLOWER(c) (ISASCII (c) && islower (c))
407 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
408 # define ISSPACE(c) (ISASCII (c) && isspace (c))
409 # define ISUPPER(c) (ISASCII (c) && isupper (c))
410 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
412 # define ISWORD(c) ISALPHA(c)
415 # define TOLOWER(c) _tolower(c)
417 # define TOLOWER(c) tolower(c)
420 /* How many characters in the character set. */
421 # define CHAR_SET_SIZE 256
425 extern char *re_syntax_table
;
427 # else /* not SYNTAX_TABLE */
429 static char re_syntax_table
[CHAR_SET_SIZE
];
432 init_syntax_once (void)
440 memset (re_syntax_table
, 0, sizeof re_syntax_table
);
442 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
444 re_syntax_table
[c
] = Sword
;
446 re_syntax_table
['_'] = Ssymbol
;
451 # endif /* not SYNTAX_TABLE */
453 # define SYNTAX(c) re_syntax_table[(c)]
455 #endif /* not emacs */
458 # define NULL (void *)0
461 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
462 since ours (we hope) works properly with all combinations of
463 machines, compilers, `char' and `unsigned char' argument types.
464 (Per Bothner suggested the basic approach.) */
465 #undef SIGN_EXTEND_CHAR
467 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
468 #else /* not __STDC__ */
469 /* As in Harbison and Steele. */
470 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
473 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
474 use `alloca' instead of `malloc'. This is because using malloc in
475 re_search* or re_match* could cause memory leaks when C-g is used in
476 Emacs; also, malloc is slower and causes storage fragmentation. On
477 the other hand, malloc is more portable, and easier to debug.
479 Because we sometimes use alloca, some routines have to be macros,
480 not functions -- `alloca'-allocated space disappears at the end of the
481 function it is called in. */
485 # define REGEX_ALLOCATE malloc
486 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
487 # define REGEX_FREE free
489 #else /* not REGEX_MALLOC */
491 /* Emacs already defines alloca, sometimes. */
494 /* Make alloca work the best possible way. */
496 # define alloca __builtin_alloca
497 # else /* not __GNUC__ */
498 # ifdef HAVE_ALLOCA_H
500 # endif /* HAVE_ALLOCA_H */
501 # endif /* not __GNUC__ */
503 # endif /* not alloca */
505 # define REGEX_ALLOCATE alloca
507 /* Assumes a `char *destination' variable. */
508 # define REGEX_REALLOCATE(source, osize, nsize) \
509 (destination = (char *) alloca (nsize), \
510 memcpy (destination, source, osize))
512 /* No need to do anything to free, after alloca. */
513 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
515 #endif /* not REGEX_MALLOC */
517 /* Define how to allocate the failure stack. */
519 #if defined REL_ALLOC && defined REGEX_MALLOC
521 # define REGEX_ALLOCATE_STACK(size) \
522 r_alloc (&failure_stack_ptr, (size))
523 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
524 r_re_alloc (&failure_stack_ptr, (nsize))
525 # define REGEX_FREE_STACK(ptr) \
526 r_alloc_free (&failure_stack_ptr)
528 #else /* not using relocating allocator */
532 # define REGEX_ALLOCATE_STACK malloc
533 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
534 # define REGEX_FREE_STACK free
536 # else /* not REGEX_MALLOC */
538 # define REGEX_ALLOCATE_STACK alloca
540 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
541 REGEX_REALLOCATE (source, osize, nsize)
542 /* No need to explicitly free anything. */
543 # define REGEX_FREE_STACK(arg) ((void)0)
545 # endif /* not REGEX_MALLOC */
546 #endif /* not using relocating allocator */
549 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
550 `string1' or just past its end. This works if PTR is NULL, which is
552 #define FIRST_STRING_P(ptr) \
553 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
555 /* (Re)Allocate N items of type T using malloc, or fail. */
556 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
557 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
558 #define RETALLOC_IF(addr, n, t) \
559 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
560 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
562 #define BYTEWIDTH 8 /* In bits. */
564 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
568 #define MAX(a, b) ((a) > (b) ? (a) : (b))
569 #define MIN(a, b) ((a) < (b) ? (a) : (b))
571 /* Type of source-pattern and string chars. */
572 typedef const unsigned char re_char
;
574 typedef char boolean
;
578 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
579 re_char
*string1
, int size1
,
580 re_char
*string2
, int size2
,
582 struct re_registers
*regs
,
585 /* These are the command codes that appear in compiled regular
586 expressions. Some opcodes are followed by argument bytes. A
587 command code can specify any interpretation whatsoever for its
588 arguments. Zero bytes may appear in the compiled regular expression. */
594 /* Succeed right away--no more backtracking. */
597 /* Followed by one byte giving n, then by n literal bytes. */
600 /* Matches any (more or less) character. */
603 /* Matches any one char belonging to specified set. First
604 following byte is number of bitmap bytes. Then come bytes
605 for a bitmap saying which chars are in. Bits in each byte
606 are ordered low-bit-first. A character is in the set if its
607 bit is 1. A character too large to have a bit in the map is
608 automatically not in the set.
610 If the length byte has the 0x80 bit set, then that stuff
611 is followed by a range table:
612 2 bytes of flags for character sets (low 8 bits, high 8 bits)
613 See RANGE_TABLE_WORK_BITS below.
614 2 bytes, the number of pairs that follow (upto 32767)
615 pairs, each 2 multibyte characters,
616 each multibyte character represented as 3 bytes. */
619 /* Same parameters as charset, but match any character that is
620 not one of those specified. */
623 /* Start remembering the text that is matched, for storing in a
624 register. Followed by one byte with the register number, in
625 the range 0 to one less than the pattern buffer's re_nsub
629 /* Stop remembering the text that is matched and store it in a
630 memory register. Followed by one byte with the register
631 number, in the range 0 to one less than `re_nsub' in the
635 /* Match a duplicate of something remembered. Followed by one
636 byte containing the register number. */
639 /* Fail unless at beginning of line. */
642 /* Fail unless at end of line. */
645 /* Succeeds if at beginning of buffer (if emacs) or at beginning
646 of string to be matched (if not). */
649 /* Analogously, for end of buffer/string. */
652 /* Followed by two byte relative address to which to jump. */
655 /* Followed by two-byte relative address of place to resume at
656 in case of failure. */
659 /* Like on_failure_jump, but pushes a placeholder instead of the
660 current string position when executed. */
661 on_failure_keep_string_jump
,
663 /* Just like `on_failure_jump', except that it checks that we
664 don't get stuck in an infinite loop (matching an empty string
666 on_failure_jump_loop
,
668 /* Just like `on_failure_jump_loop', except that it checks for
669 a different kind of loop (the kind that shows up with non-greedy
670 operators). This operation has to be immediately preceded
672 on_failure_jump_nastyloop
,
674 /* A smart `on_failure_jump' used for greedy * and + operators.
675 It analyses the loop before which it is put and if the
676 loop does not require backtracking, it changes itself to
677 `on_failure_keep_string_jump' and short-circuits the loop,
678 else it just defaults to changing itself into `on_failure_jump'.
679 It assumes that it is pointing to just past a `jump'. */
680 on_failure_jump_smart
,
682 /* Followed by two-byte relative address and two-byte number n.
683 After matching N times, jump to the address upon failure.
684 Does not work if N starts at 0: use on_failure_jump_loop
688 /* Followed by two-byte relative address, and two-byte number n.
689 Jump to the address N times, then fail. */
692 /* Set the following two-byte relative address to the
693 subsequent two-byte number. The address *includes* the two
697 wordbeg
, /* Succeeds if at word beginning. */
698 wordend
, /* Succeeds if at word end. */
700 wordbound
, /* Succeeds if at a word boundary. */
701 notwordbound
, /* Succeeds if not at a word boundary. */
703 symbeg
, /* Succeeds if at symbol beginning. */
704 symend
, /* Succeeds if at symbol end. */
706 /* Matches any character whose syntax is specified. Followed by
707 a byte which contains a syntax code, e.g., Sword. */
710 /* Matches any character whose syntax is not that specified. */
714 ,before_dot
, /* Succeeds if before point. */
715 at_dot
, /* Succeeds if at point. */
716 after_dot
, /* Succeeds if after point. */
718 /* Matches any character whose category-set contains the specified
719 category. The operator is followed by a byte which contains a
720 category code (mnemonic ASCII character). */
723 /* Matches any character whose category-set does not contain the
724 specified category. The operator is followed by a byte which
725 contains the category code (mnemonic ASCII character). */
730 /* Common operations on the compiled pattern. */
732 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
734 #define STORE_NUMBER(destination, number) \
736 (destination)[0] = (number) & 0377; \
737 (destination)[1] = (number) >> 8; \
740 /* Same as STORE_NUMBER, except increment DESTINATION to
741 the byte after where the number is stored. Therefore, DESTINATION
742 must be an lvalue. */
744 #define STORE_NUMBER_AND_INCR(destination, number) \
746 STORE_NUMBER (destination, number); \
747 (destination) += 2; \
750 /* Put into DESTINATION a number stored in two contiguous bytes starting
753 #define EXTRACT_NUMBER(destination, source) \
755 (destination) = *(source) & 0377; \
756 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
760 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
762 extract_number (dest
, source
)
766 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
767 *dest
= *source
& 0377;
771 # ifndef EXTRACT_MACROS /* To debug the macros. */
772 # undef EXTRACT_NUMBER
773 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
774 # endif /* not EXTRACT_MACROS */
778 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
779 SOURCE must be an lvalue. */
781 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
783 EXTRACT_NUMBER (destination, source); \
788 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
791 extract_number_and_incr (destination
, source
)
795 extract_number (destination
, *source
);
799 # ifndef EXTRACT_MACROS
800 # undef EXTRACT_NUMBER_AND_INCR
801 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
802 extract_number_and_incr (&dest, &src)
803 # endif /* not EXTRACT_MACROS */
807 /* Store a multibyte character in three contiguous bytes starting
808 DESTINATION, and increment DESTINATION to the byte after where the
809 character is stored. Therefore, DESTINATION must be an lvalue. */
811 #define STORE_CHARACTER_AND_INCR(destination, character) \
813 (destination)[0] = (character) & 0377; \
814 (destination)[1] = ((character) >> 8) & 0377; \
815 (destination)[2] = (character) >> 16; \
816 (destination) += 3; \
819 /* Put into DESTINATION a character stored in three contiguous bytes
820 starting at SOURCE. */
822 #define EXTRACT_CHARACTER(destination, source) \
824 (destination) = ((source)[0] \
825 | ((source)[1] << 8) \
826 | ((source)[2] << 16)); \
830 /* Macros for charset. */
832 /* Size of bitmap of charset P in bytes. P is a start of charset,
833 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
834 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
836 /* Nonzero if charset P has range table. */
837 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
839 /* Return the address of range table of charset P. But not the start
840 of table itself, but the before where the number of ranges is
841 stored. `2 +' means to skip re_opcode_t and size of bitmap,
842 and the 2 bytes of flags at the start of the range table. */
843 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
845 /* Extract the bit flags that start a range table. */
846 #define CHARSET_RANGE_TABLE_BITS(p) \
847 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
848 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
850 /* Test if C is listed in the bitmap of charset P. */
851 #define CHARSET_LOOKUP_BITMAP(p, c) \
852 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
853 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
855 /* Return the address of end of RANGE_TABLE. COUNT is number of
856 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
857 is start of range and end of range. `* 3' is size of each start
859 #define CHARSET_RANGE_TABLE_END(range_table, count) \
860 ((range_table) + (count) * 2 * 3)
862 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
863 COUNT is number of ranges in RANGE_TABLE. */
864 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
867 re_wchar_t range_start, range_end; \
869 re_char *range_table_end \
870 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
872 for (p = (range_table); p < range_table_end; p += 2 * 3) \
874 EXTRACT_CHARACTER (range_start, p); \
875 EXTRACT_CHARACTER (range_end, p + 3); \
877 if (range_start <= (c) && (c) <= range_end) \
886 /* Test if C is in range table of CHARSET. The flag NOT is negated if
887 C is listed in it. */
888 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
891 /* Number of ranges in range table. */ \
893 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
895 EXTRACT_NUMBER_AND_INCR (count, range_table); \
896 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
900 /* If DEBUG is defined, Regex prints many voluminous messages about what
901 it is doing (if the variable `debug' is nonzero). If linked with the
902 main program in `iregex.c', you can enter patterns and strings
903 interactively. And if linked with the main program in `main.c' and
904 the other test files, you can run the already-written tests. */
908 /* We use standard I/O for debugging. */
911 /* It is useful to test things that ``must'' be true when debugging. */
914 static int debug
= -100000;
916 # define DEBUG_STATEMENT(e) e
917 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
918 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
919 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
920 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
921 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
922 if (debug > 0) print_partial_compiled_pattern (s, e)
923 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
924 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
927 /* Print the fastmap in human-readable form. */
930 print_fastmap (fastmap
)
933 unsigned was_a_range
= 0;
936 while (i
< (1 << BYTEWIDTH
))
942 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
958 /* Print a compiled pattern string in human-readable form, starting at
959 the START pointer into it and ending just before the pointer END. */
962 print_partial_compiled_pattern (start
, end
)
972 fprintf (stderr
, "(null)\n");
976 /* Loop over pattern commands. */
979 fprintf (stderr
, "%d:\t", p
- start
);
981 switch ((re_opcode_t
) *p
++)
984 fprintf (stderr
, "/no_op");
988 fprintf (stderr
, "/succeed");
993 fprintf (stderr
, "/exactn/%d", mcnt
);
996 fprintf (stderr
, "/%c", *p
++);
1002 fprintf (stderr
, "/start_memory/%d", *p
++);
1006 fprintf (stderr
, "/stop_memory/%d", *p
++);
1010 fprintf (stderr
, "/duplicate/%d", *p
++);
1014 fprintf (stderr
, "/anychar");
1020 register int c
, last
= -100;
1021 register int in_range
= 0;
1022 int length
= CHARSET_BITMAP_SIZE (p
- 1);
1023 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
1025 fprintf (stderr
, "/charset [%s",
1026 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
1029 fprintf (stderr
, " !extends past end of pattern! ");
1031 for (c
= 0; c
< 256; c
++)
1033 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
1035 /* Are we starting a range? */
1036 if (last
+ 1 == c
&& ! in_range
)
1038 fprintf (stderr
, "-");
1041 /* Have we broken a range? */
1042 else if (last
+ 1 != c
&& in_range
)
1044 fprintf (stderr
, "%c", last
);
1049 fprintf (stderr
, "%c", c
);
1055 fprintf (stderr
, "%c", last
);
1057 fprintf (stderr
, "]");
1061 if (has_range_table
)
1064 fprintf (stderr
, "has-range-table");
1066 /* ??? Should print the range table; for now, just skip it. */
1067 p
+= 2; /* skip range table bits */
1068 EXTRACT_NUMBER_AND_INCR (count
, p
);
1069 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1075 fprintf (stderr
, "/begline");
1079 fprintf (stderr
, "/endline");
1082 case on_failure_jump
:
1083 extract_number_and_incr (&mcnt
, &p
);
1084 fprintf (stderr
, "/on_failure_jump to %d", p
+ mcnt
- start
);
1087 case on_failure_keep_string_jump
:
1088 extract_number_and_incr (&mcnt
, &p
);
1089 fprintf (stderr
, "/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1092 case on_failure_jump_nastyloop
:
1093 extract_number_and_incr (&mcnt
, &p
);
1094 fprintf (stderr
, "/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1097 case on_failure_jump_loop
:
1098 extract_number_and_incr (&mcnt
, &p
);
1099 fprintf (stderr
, "/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1102 case on_failure_jump_smart
:
1103 extract_number_and_incr (&mcnt
, &p
);
1104 fprintf (stderr
, "/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1108 extract_number_and_incr (&mcnt
, &p
);
1109 fprintf (stderr
, "/jump to %d", p
+ mcnt
- start
);
1113 extract_number_and_incr (&mcnt
, &p
);
1114 extract_number_and_incr (&mcnt2
, &p
);
1115 fprintf (stderr
, "/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1119 extract_number_and_incr (&mcnt
, &p
);
1120 extract_number_and_incr (&mcnt2
, &p
);
1121 fprintf (stderr
, "/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1125 extract_number_and_incr (&mcnt
, &p
);
1126 extract_number_and_incr (&mcnt2
, &p
);
1127 fprintf (stderr
, "/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1131 fprintf (stderr
, "/wordbound");
1135 fprintf (stderr
, "/notwordbound");
1139 fprintf (stderr
, "/wordbeg");
1143 fprintf (stderr
, "/wordend");
1147 fprintf (stderr
, "/symbeg");
1151 fprintf (stderr
, "/symend");
1155 fprintf (stderr
, "/syntaxspec");
1157 fprintf (stderr
, "/%d", mcnt
);
1161 fprintf (stderr
, "/notsyntaxspec");
1163 fprintf (stderr
, "/%d", mcnt
);
1168 fprintf (stderr
, "/before_dot");
1172 fprintf (stderr
, "/at_dot");
1176 fprintf (stderr
, "/after_dot");
1180 fprintf (stderr
, "/categoryspec");
1182 fprintf (stderr
, "/%d", mcnt
);
1185 case notcategoryspec
:
1186 fprintf (stderr
, "/notcategoryspec");
1188 fprintf (stderr
, "/%d", mcnt
);
1193 fprintf (stderr
, "/begbuf");
1197 fprintf (stderr
, "/endbuf");
1201 fprintf (stderr
, "?%d", *(p
-1));
1204 fprintf (stderr
, "\n");
1207 fprintf (stderr
, "%d:\tend of pattern.\n", p
- start
);
1212 print_compiled_pattern (bufp
)
1213 struct re_pattern_buffer
*bufp
;
1215 re_char
*buffer
= bufp
->buffer
;
1217 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1218 printf ("%ld bytes used/%ld bytes allocated.\n",
1219 bufp
->used
, bufp
->allocated
);
1221 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1223 printf ("fastmap: ");
1224 print_fastmap (bufp
->fastmap
);
1227 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1228 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1229 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1230 printf ("no_sub: %d\t", bufp
->no_sub
);
1231 printf ("not_bol: %d\t", bufp
->not_bol
);
1232 printf ("not_eol: %d\t", bufp
->not_eol
);
1233 printf ("syntax: %lx\n", bufp
->syntax
);
1235 /* Perhaps we should print the translate table? */
1240 print_double_string (where
, string1
, size1
, string2
, size2
)
1253 if (FIRST_STRING_P (where
))
1255 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1256 putchar (string1
[this_char
]);
1261 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1262 putchar (string2
[this_char
]);
1266 #else /* not DEBUG */
1271 # define DEBUG_STATEMENT(e)
1272 # define DEBUG_PRINT1(x)
1273 # define DEBUG_PRINT2(x1, x2)
1274 # define DEBUG_PRINT3(x1, x2, x3)
1275 # define DEBUG_PRINT4(x1, x2, x3, x4)
1276 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1277 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1279 #endif /* not DEBUG */
1281 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1282 also be assigned to arbitrarily: each pattern buffer stores its own
1283 syntax, so it can be changed between regex compilations. */
1284 /* This has no initializer because initialized variables in Emacs
1285 become read-only after dumping. */
1286 reg_syntax_t re_syntax_options
;
1289 /* Specify the precise syntax of regexps for compilation. This provides
1290 for compatibility for various utilities which historically have
1291 different, incompatible syntaxes.
1293 The argument SYNTAX is a bit mask comprised of the various bits
1294 defined in regex.h. We return the old syntax. */
1297 re_set_syntax (reg_syntax_t syntax
)
1299 reg_syntax_t ret
= re_syntax_options
;
1301 re_syntax_options
= syntax
;
1304 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1306 /* Regexp to use to replace spaces, or NULL meaning don't. */
1307 static re_char
*whitespace_regexp
;
1310 re_set_whitespace_regexp (const char *regexp
)
1312 whitespace_regexp
= (re_char
*) regexp
;
1314 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1316 /* This table gives an error message for each of the error codes listed
1317 in regex.h. Obviously the order here has to be same as there.
1318 POSIX doesn't require that we do anything for REG_NOERROR,
1319 but why not be nice? */
1321 static const char *re_error_msgid
[] =
1323 gettext_noop ("Success"), /* REG_NOERROR */
1324 gettext_noop ("No match"), /* REG_NOMATCH */
1325 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1326 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1327 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1328 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1329 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1330 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1331 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1332 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1333 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1334 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1335 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1336 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1337 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1338 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1339 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1340 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1343 /* Avoiding alloca during matching, to placate r_alloc. */
1345 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1346 searching and matching functions should not call alloca. On some
1347 systems, alloca is implemented in terms of malloc, and if we're
1348 using the relocating allocator routines, then malloc could cause a
1349 relocation, which might (if the strings being searched are in the
1350 ralloc heap) shift the data out from underneath the regexp
1353 Here's another reason to avoid allocation: Emacs
1354 processes input from X in a signal handler; processing X input may
1355 call malloc; if input arrives while a matching routine is calling
1356 malloc, then we're scrod. But Emacs can't just block input while
1357 calling matching routines; then we don't notice interrupts when
1358 they come in. So, Emacs blocks input around all regexp calls
1359 except the matching calls, which it leaves unprotected, in the
1360 faith that they will not malloc. */
1362 /* Normally, this is fine. */
1363 #define MATCH_MAY_ALLOCATE
1365 /* The match routines may not allocate if (1) they would do it with malloc
1366 and (2) it's not safe for them to use malloc.
1367 Note that if REL_ALLOC is defined, matching would not use malloc for the
1368 failure stack, but we would still use it for the register vectors;
1369 so REL_ALLOC should not affect this. */
1370 #if defined REGEX_MALLOC && defined emacs
1371 # undef MATCH_MAY_ALLOCATE
1375 /* Failure stack declarations and macros; both re_compile_fastmap and
1376 re_match_2 use a failure stack. These have to be macros because of
1377 REGEX_ALLOCATE_STACK. */
1380 /* Approximate number of failure points for which to initially allocate space
1381 when matching. If this number is exceeded, we allocate more
1382 space, so it is not a hard limit. */
1383 #ifndef INIT_FAILURE_ALLOC
1384 # define INIT_FAILURE_ALLOC 20
1387 /* Roughly the maximum number of failure points on the stack. Would be
1388 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1389 This is a variable only so users of regex can assign to it; we never
1390 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1391 before using it, so it should probably be a byte-count instead. */
1392 # if defined MATCH_MAY_ALLOCATE
1393 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1394 whose default stack limit is 2mb. In order for a larger
1395 value to work reliably, you have to try to make it accord
1396 with the process stack limit. */
1397 size_t re_max_failures
= 40000;
1399 size_t re_max_failures
= 4000;
1402 union fail_stack_elt
1405 /* This should be the biggest `int' that's no bigger than a pointer. */
1409 typedef union fail_stack_elt fail_stack_elt_t
;
1413 fail_stack_elt_t
*stack
;
1415 size_t avail
; /* Offset of next open position. */
1416 size_t frame
; /* Offset of the cur constructed frame. */
1419 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1420 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1423 /* Define macros to initialize and free the failure stack.
1424 Do `return -2' if the alloc fails. */
1426 #ifdef MATCH_MAY_ALLOCATE
1427 # define INIT_FAIL_STACK() \
1429 fail_stack.stack = (fail_stack_elt_t *) \
1430 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1431 * sizeof (fail_stack_elt_t)); \
1433 if (fail_stack.stack == NULL) \
1436 fail_stack.size = INIT_FAILURE_ALLOC; \
1437 fail_stack.avail = 0; \
1438 fail_stack.frame = 0; \
1441 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1443 # define INIT_FAIL_STACK() \
1445 fail_stack.avail = 0; \
1446 fail_stack.frame = 0; \
1449 # define RESET_FAIL_STACK() ((void)0)
1453 /* Double the size of FAIL_STACK, up to a limit
1454 which allows approximately `re_max_failures' items.
1456 Return 1 if succeeds, and 0 if either ran out of memory
1457 allocating space for it or it was already too large.
1459 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1461 /* Factor to increase the failure stack size by
1462 when we increase it.
1463 This used to be 2, but 2 was too wasteful
1464 because the old discarded stacks added up to as much space
1465 were as ultimate, maximum-size stack. */
1466 #define FAIL_STACK_GROWTH_FACTOR 4
1468 #define GROW_FAIL_STACK(fail_stack) \
1469 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1470 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1472 : ((fail_stack).stack \
1473 = (fail_stack_elt_t *) \
1474 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1475 (fail_stack).size * sizeof (fail_stack_elt_t), \
1476 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1477 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1478 * FAIL_STACK_GROWTH_FACTOR))), \
1480 (fail_stack).stack == NULL \
1482 : ((fail_stack).size \
1483 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1484 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1485 * FAIL_STACK_GROWTH_FACTOR)) \
1486 / sizeof (fail_stack_elt_t)), \
1490 /* Push a pointer value onto the failure stack.
1491 Assumes the variable `fail_stack'. Probably should only
1492 be called from within `PUSH_FAILURE_POINT'. */
1493 #define PUSH_FAILURE_POINTER(item) \
1494 fail_stack.stack[fail_stack.avail++].pointer = (item)
1496 /* This pushes an integer-valued item onto the failure stack.
1497 Assumes the variable `fail_stack'. Probably should only
1498 be called from within `PUSH_FAILURE_POINT'. */
1499 #define PUSH_FAILURE_INT(item) \
1500 fail_stack.stack[fail_stack.avail++].integer = (item)
1502 /* Push a fail_stack_elt_t value onto the failure stack.
1503 Assumes the variable `fail_stack'. Probably should only
1504 be called from within `PUSH_FAILURE_POINT'. */
1505 #define PUSH_FAILURE_ELT(item) \
1506 fail_stack.stack[fail_stack.avail++] = (item)
1508 /* These three POP... operations complement the three PUSH... operations.
1509 All assume that `fail_stack' is nonempty. */
1510 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1511 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1512 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1514 /* Individual items aside from the registers. */
1515 #define NUM_NONREG_ITEMS 3
1517 /* Used to examine the stack (to detect infinite loops). */
1518 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1519 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1520 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1521 #define TOP_FAILURE_HANDLE() fail_stack.frame
1524 #define ENSURE_FAIL_STACK(space) \
1525 while (REMAINING_AVAIL_SLOTS <= space) { \
1526 if (!GROW_FAIL_STACK (fail_stack)) \
1528 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1529 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1532 /* Push register NUM onto the stack. */
1533 #define PUSH_FAILURE_REG(num) \
1535 char *destination; \
1536 ENSURE_FAIL_STACK(3); \
1537 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1538 num, regstart[num], regend[num]); \
1539 PUSH_FAILURE_POINTER (regstart[num]); \
1540 PUSH_FAILURE_POINTER (regend[num]); \
1541 PUSH_FAILURE_INT (num); \
1544 /* Change the counter's value to VAL, but make sure that it will
1545 be reset when backtracking. */
1546 #define PUSH_NUMBER(ptr,val) \
1548 char *destination; \
1550 ENSURE_FAIL_STACK(3); \
1551 EXTRACT_NUMBER (c, ptr); \
1552 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1553 PUSH_FAILURE_INT (c); \
1554 PUSH_FAILURE_POINTER (ptr); \
1555 PUSH_FAILURE_INT (-1); \
1556 STORE_NUMBER (ptr, val); \
1559 /* Pop a saved register off the stack. */
1560 #define POP_FAILURE_REG_OR_COUNT() \
1562 int reg = POP_FAILURE_INT (); \
1565 /* It's a counter. */ \
1566 /* Here, we discard `const', making re_match non-reentrant. */ \
1567 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1568 reg = POP_FAILURE_INT (); \
1569 STORE_NUMBER (ptr, reg); \
1570 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1574 regend[reg] = POP_FAILURE_POINTER (); \
1575 regstart[reg] = POP_FAILURE_POINTER (); \
1576 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1577 reg, regstart[reg], regend[reg]); \
1581 /* Check that we are not stuck in an infinite loop. */
1582 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1584 int failure = TOP_FAILURE_HANDLE (); \
1585 /* Check for infinite matching loops */ \
1586 while (failure > 0 \
1587 && (FAILURE_STR (failure) == string_place \
1588 || FAILURE_STR (failure) == NULL)) \
1590 assert (FAILURE_PAT (failure) >= bufp->buffer \
1591 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1592 if (FAILURE_PAT (failure) == pat_cur) \
1597 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1598 failure = NEXT_FAILURE_HANDLE(failure); \
1600 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1603 /* Push the information about the state we will need
1604 if we ever fail back to it.
1606 Requires variables fail_stack, regstart, regend and
1607 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1610 Does `return FAILURE_CODE' if runs out of memory. */
1612 #define PUSH_FAILURE_POINT(pattern, string_place) \
1614 char *destination; \
1615 /* Must be int, so when we don't save any registers, the arithmetic \
1616 of 0 + -1 isn't done as unsigned. */ \
1618 DEBUG_STATEMENT (nfailure_points_pushed++); \
1619 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1620 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1621 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1623 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1625 DEBUG_PRINT1 ("\n"); \
1627 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1628 PUSH_FAILURE_INT (fail_stack.frame); \
1630 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1631 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1632 DEBUG_PRINT1 ("'\n"); \
1633 PUSH_FAILURE_POINTER (string_place); \
1635 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1636 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1637 PUSH_FAILURE_POINTER (pattern); \
1639 /* Close the frame by moving the frame pointer past it. */ \
1640 fail_stack.frame = fail_stack.avail; \
1643 /* Estimate the size of data pushed by a typical failure stack entry.
1644 An estimate is all we need, because all we use this for
1645 is to choose a limit for how big to make the failure stack. */
1646 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1647 #define TYPICAL_FAILURE_SIZE 20
1649 /* How many items can still be added to the stack without overflowing it. */
1650 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1653 /* Pops what PUSH_FAIL_STACK pushes.
1655 We restore into the parameters, all of which should be lvalues:
1656 STR -- the saved data position.
1657 PAT -- the saved pattern position.
1658 REGSTART, REGEND -- arrays of string positions.
1660 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1661 `pend', `string1', `size1', `string2', and `size2'. */
1663 #define POP_FAILURE_POINT(str, pat) \
1665 assert (!FAIL_STACK_EMPTY ()); \
1667 /* Remove failure points and point to how many regs pushed. */ \
1668 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1669 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1670 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1672 /* Pop the saved registers. */ \
1673 while (fail_stack.frame < fail_stack.avail) \
1674 POP_FAILURE_REG_OR_COUNT (); \
1676 pat = POP_FAILURE_POINTER (); \
1677 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1678 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1680 /* If the saved string location is NULL, it came from an \
1681 on_failure_keep_string_jump opcode, and we want to throw away the \
1682 saved NULL, thus retaining our current position in the string. */ \
1683 str = POP_FAILURE_POINTER (); \
1684 DEBUG_PRINT2 (" Popping string %p: `", str); \
1685 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1686 DEBUG_PRINT1 ("'\n"); \
1688 fail_stack.frame = POP_FAILURE_INT (); \
1689 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1691 assert (fail_stack.avail >= 0); \
1692 assert (fail_stack.frame <= fail_stack.avail); \
1694 DEBUG_STATEMENT (nfailure_points_popped++); \
1695 } while (0) /* POP_FAILURE_POINT */
1699 /* Registers are set to a sentinel when they haven't yet matched. */
1700 #define REG_UNSET(e) ((e) == NULL)
1702 /* Subroutine declarations and macros for regex_compile. */
1704 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1705 reg_syntax_t syntax
,
1706 struct re_pattern_buffer
*bufp
));
1707 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1708 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1709 int arg1
, int arg2
));
1710 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1711 int arg
, unsigned char *end
));
1712 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1713 int arg1
, int arg2
, unsigned char *end
));
1714 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1716 reg_syntax_t syntax
));
1717 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1719 reg_syntax_t syntax
));
1720 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1721 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1722 char *fastmap
, const int multibyte
));
1724 /* Fetch the next character in the uncompiled pattern, with no
1726 #define PATFETCH(c) \
1729 if (p == pend) return REG_EEND; \
1730 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1735 /* If `translate' is non-null, return translate[D], else just D. We
1736 cast the subscript to translate because some data is declared as
1737 `char *', to avoid warnings when a string constant is passed. But
1738 when we use a character as a subscript we must make it unsigned. */
1740 # define TRANSLATE(d) \
1741 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1745 /* Macros for outputting the compiled pattern into `buffer'. */
1747 /* If the buffer isn't allocated when it comes in, use this. */
1748 #define INIT_BUF_SIZE 32
1750 /* Make sure we have at least N more bytes of space in buffer. */
1751 #define GET_BUFFER_SPACE(n) \
1752 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1755 /* Make sure we have one more byte of buffer space and then add C to it. */
1756 #define BUF_PUSH(c) \
1758 GET_BUFFER_SPACE (1); \
1759 *b++ = (unsigned char) (c); \
1763 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1764 #define BUF_PUSH_2(c1, c2) \
1766 GET_BUFFER_SPACE (2); \
1767 *b++ = (unsigned char) (c1); \
1768 *b++ = (unsigned char) (c2); \
1772 /* As with BUF_PUSH_2, except for three bytes. */
1773 #define BUF_PUSH_3(c1, c2, c3) \
1775 GET_BUFFER_SPACE (3); \
1776 *b++ = (unsigned char) (c1); \
1777 *b++ = (unsigned char) (c2); \
1778 *b++ = (unsigned char) (c3); \
1782 /* Store a jump with opcode OP at LOC to location TO. We store a
1783 relative address offset by the three bytes the jump itself occupies. */
1784 #define STORE_JUMP(op, loc, to) \
1785 store_op1 (op, loc, (to) - (loc) - 3)
1787 /* Likewise, for a two-argument jump. */
1788 #define STORE_JUMP2(op, loc, to, arg) \
1789 store_op2 (op, loc, (to) - (loc) - 3, arg)
1791 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1792 #define INSERT_JUMP(op, loc, to) \
1793 insert_op1 (op, loc, (to) - (loc) - 3, b)
1795 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1796 #define INSERT_JUMP2(op, loc, to, arg) \
1797 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1800 /* This is not an arbitrary limit: the arguments which represent offsets
1801 into the pattern are two bytes long. So if 2^15 bytes turns out to
1802 be too small, many things would have to change. */
1803 # define MAX_BUF_SIZE (1L << 15)
1805 #if 0 /* This is when we thought it could be 2^16 bytes. */
1806 /* Any other compiler which, like MSC, has allocation limit below 2^16
1807 bytes will have to use approach similar to what was done below for
1808 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1809 reallocating to 0 bytes. Such thing is not going to work too well.
1810 You have been warned!! */
1811 #if defined _MSC_VER && !defined WIN32
1812 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1813 # define MAX_BUF_SIZE 65500L
1815 # define MAX_BUF_SIZE (1L << 16)
1819 /* Extend the buffer by twice its current size via realloc and
1820 reset the pointers that pointed into the old block to point to the
1821 correct places in the new one. If extending the buffer results in it
1822 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1823 #if __BOUNDED_POINTERS__
1824 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1825 # define MOVE_BUFFER_POINTER(P) \
1826 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1827 SET_HIGH_BOUND (P), \
1828 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1829 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1832 SET_HIGH_BOUND (b); \
1833 SET_HIGH_BOUND (begalt); \
1834 if (fixup_alt_jump) \
1835 SET_HIGH_BOUND (fixup_alt_jump); \
1837 SET_HIGH_BOUND (laststart); \
1838 if (pending_exact) \
1839 SET_HIGH_BOUND (pending_exact); \
1842 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1843 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1845 #define EXTEND_BUFFER() \
1847 unsigned char *old_buffer = bufp->buffer; \
1848 if (bufp->allocated == MAX_BUF_SIZE) \
1850 bufp->allocated <<= 1; \
1851 if (bufp->allocated > MAX_BUF_SIZE) \
1852 bufp->allocated = MAX_BUF_SIZE; \
1853 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1854 if (bufp->buffer == NULL) \
1855 return REG_ESPACE; \
1856 /* If the buffer moved, move all the pointers into it. */ \
1857 if (old_buffer != bufp->buffer) \
1859 unsigned char *new_buffer = bufp->buffer; \
1860 MOVE_BUFFER_POINTER (b); \
1861 MOVE_BUFFER_POINTER (begalt); \
1862 if (fixup_alt_jump) \
1863 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1865 MOVE_BUFFER_POINTER (laststart); \
1866 if (pending_exact) \
1867 MOVE_BUFFER_POINTER (pending_exact); \
1869 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1873 /* Since we have one byte reserved for the register number argument to
1874 {start,stop}_memory, the maximum number of groups we can report
1875 things about is what fits in that byte. */
1876 #define MAX_REGNUM 255
1878 /* But patterns can have more than `MAX_REGNUM' registers. We just
1879 ignore the excess. */
1880 typedef int regnum_t
;
1883 /* Macros for the compile stack. */
1885 /* Since offsets can go either forwards or backwards, this type needs to
1886 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1887 /* int may be not enough when sizeof(int) == 2. */
1888 typedef long pattern_offset_t
;
1892 pattern_offset_t begalt_offset
;
1893 pattern_offset_t fixup_alt_jump
;
1894 pattern_offset_t laststart_offset
;
1896 } compile_stack_elt_t
;
1901 compile_stack_elt_t
*stack
;
1903 unsigned avail
; /* Offset of next open position. */
1904 } compile_stack_type
;
1907 #define INIT_COMPILE_STACK_SIZE 32
1909 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1910 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1912 /* The next available element. */
1913 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1915 /* Explicit quit checking is only used on NTemacs and whenever we
1916 use polling to process input events. */
1917 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1918 extern int immediate_quit
;
1919 # define IMMEDIATE_QUIT_CHECK \
1921 if (immediate_quit) QUIT; \
1924 # define IMMEDIATE_QUIT_CHECK ((void)0)
1927 /* Structure to manage work area for range table. */
1928 struct range_table_work_area
1930 int *table
; /* actual work area. */
1931 int allocated
; /* allocated size for work area in bytes. */
1932 int used
; /* actually used size in words. */
1933 int bits
; /* flag to record character classes */
1936 /* Make sure that WORK_AREA can hold more N multibyte characters.
1937 This is used only in set_image_of_range and set_image_of_range_1.
1938 It expects WORK_AREA to be a pointer.
1939 If it can't get the space, it returns from the surrounding function. */
1941 #define EXTEND_RANGE_TABLE(work_area, n) \
1943 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1945 extend_range_table_work_area (&work_area); \
1946 if ((work_area).table == 0) \
1947 return (REG_ESPACE); \
1951 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1952 (work_area).bits |= (bit)
1954 /* Bits used to implement the multibyte-part of the various character classes
1955 such as [:alnum:] in a charset's range table. */
1956 #define BIT_WORD 0x1
1957 #define BIT_LOWER 0x2
1958 #define BIT_PUNCT 0x4
1959 #define BIT_SPACE 0x8
1960 #define BIT_UPPER 0x10
1961 #define BIT_MULTIBYTE 0x20
1963 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1964 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1966 EXTEND_RANGE_TABLE ((work_area), 2); \
1967 (work_area).table[(work_area).used++] = (range_start); \
1968 (work_area).table[(work_area).used++] = (range_end); \
1971 /* Free allocated memory for WORK_AREA. */
1972 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1974 if ((work_area).table) \
1975 free ((work_area).table); \
1978 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1979 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1980 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1981 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1984 /* Set the bit for character C in a list. */
1985 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1990 /* Store characters in the range FROM to TO in the bitmap at B (for
1991 ASCII and unibyte characters) and WORK_AREA (for multibyte
1992 characters) while translating them and paying attention to the
1993 continuity of translated characters.
1995 Implementation note: It is better to implement these fairly big
1996 macros by a function, but it's not that easy because macros called
1997 in this macro assume various local variables already declared. */
1999 /* Both FROM and TO are ASCII characters. */
2001 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
2005 for (C0 = (FROM); C0 <= (TO); C0++) \
2007 C1 = TRANSLATE (C0); \
2008 if (! ASCII_CHAR_P (C1)) \
2010 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2011 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
2014 SET_LIST_BIT (C1); \
2019 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
2021 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
2023 int C0, C1, C2, I; \
2024 int USED = RANGE_TABLE_WORK_USED (work_area); \
2026 for (C0 = (FROM); C0 <= (TO); C0++) \
2028 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
2029 if (CHAR_BYTE8_P (C1)) \
2030 SET_LIST_BIT (C0); \
2033 C2 = TRANSLATE (C1); \
2035 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
2037 SET_LIST_BIT (C1); \
2038 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2040 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2041 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2043 if (C2 >= from - 1 && C2 <= to + 1) \
2045 if (C2 == from - 1) \
2046 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2047 else if (C2 == to + 1) \
2048 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2053 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
2059 /* Both FROM and TO are multibyte characters. */
2061 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2063 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2065 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2066 for (C0 = (FROM); C0 <= (TO); C0++) \
2068 C1 = TRANSLATE (C0); \
2069 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2070 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2071 SET_LIST_BIT (C2); \
2072 if (C1 >= (FROM) && C1 <= (TO)) \
2074 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2076 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2077 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2079 if (C1 >= from - 1 && C1 <= to + 1) \
2081 if (C1 == from - 1) \
2082 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2083 else if (C1 == to + 1) \
2084 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2089 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2095 /* Get the next unsigned number in the uncompiled pattern. */
2096 #define GET_UNSIGNED_NUMBER(num) \
2099 FREE_STACK_RETURN (REG_EBRACE); \
2103 while ('0' <= c && c <= '9') \
2109 num = num * 10 + c - '0'; \
2110 if (num / 10 != prev) \
2111 FREE_STACK_RETURN (REG_BADBR); \
2113 FREE_STACK_RETURN (REG_EBRACE); \
2119 #if ! WIDE_CHAR_SUPPORT
2121 /* Map a string to the char class it names (if any). */
2123 re_wctype (const re_char
*str
)
2125 const char *string
= str
;
2126 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
2127 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
2128 else if (STREQ (string
, "word")) return RECC_WORD
;
2129 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
2130 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
2131 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
2132 else if (STREQ (string
, "lower")) return RECC_LOWER
;
2133 else if (STREQ (string
, "print")) return RECC_PRINT
;
2134 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
2135 else if (STREQ (string
, "space")) return RECC_SPACE
;
2136 else if (STREQ (string
, "upper")) return RECC_UPPER
;
2137 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
2138 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
2139 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
2140 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
2141 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
2142 else if (STREQ (string
, "blank")) return RECC_BLANK
;
2146 /* True if CH is in the char class CC. */
2148 re_iswctype (int ch
, re_wctype_t cc
)
2152 case RECC_ALNUM
: return ISALNUM (ch
);
2153 case RECC_ALPHA
: return ISALPHA (ch
);
2154 case RECC_BLANK
: return ISBLANK (ch
);
2155 case RECC_CNTRL
: return ISCNTRL (ch
);
2156 case RECC_DIGIT
: return ISDIGIT (ch
);
2157 case RECC_GRAPH
: return ISGRAPH (ch
);
2158 case RECC_LOWER
: return ISLOWER (ch
);
2159 case RECC_PRINT
: return ISPRINT (ch
);
2160 case RECC_PUNCT
: return ISPUNCT (ch
);
2161 case RECC_SPACE
: return ISSPACE (ch
);
2162 case RECC_UPPER
: return ISUPPER (ch
);
2163 case RECC_XDIGIT
: return ISXDIGIT (ch
);
2164 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2165 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2166 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2167 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2168 case RECC_WORD
: return ISWORD (ch
);
2169 case RECC_ERROR
: return false;
2175 /* Return a bit-pattern to use in the range-table bits to match multibyte
2176 chars of class CC. */
2178 re_wctype_to_bit (re_wctype_t cc
)
2182 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2183 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2184 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2185 case RECC_LOWER
: return BIT_LOWER
;
2186 case RECC_UPPER
: return BIT_UPPER
;
2187 case RECC_PUNCT
: return BIT_PUNCT
;
2188 case RECC_SPACE
: return BIT_SPACE
;
2189 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2190 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2197 /* Filling in the work area of a range. */
2199 /* Actually extend the space in WORK_AREA. */
2202 extend_range_table_work_area (struct range_table_work_area
*work_area
)
2204 work_area
->allocated
+= 16 * sizeof (int);
2205 if (work_area
->table
)
2207 = (int *) realloc (work_area
->table
, work_area
->allocated
);
2210 = (int *) malloc (work_area
->allocated
);
2216 /* Carefully find the ranges of codes that are equivalent
2217 under case conversion to the range start..end when passed through
2218 TRANSLATE. Handle the case where non-letters can come in between
2219 two upper-case letters (which happens in Latin-1).
2220 Also handle the case of groups of more than 2 case-equivalent chars.
2222 The basic method is to look at consecutive characters and see
2223 if they can form a run that can be handled as one.
2225 Returns -1 if successful, REG_ESPACE if ran out of space. */
2228 set_image_of_range_1 (work_area
, start
, end
, translate
)
2229 RE_TRANSLATE_TYPE translate
;
2230 struct range_table_work_area
*work_area
;
2231 re_wchar_t start
, end
;
2233 /* `one_case' indicates a character, or a run of characters,
2234 each of which is an isolate (no case-equivalents).
2235 This includes all ASCII non-letters.
2237 `two_case' indicates a character, or a run of characters,
2238 each of which has two case-equivalent forms.
2239 This includes all ASCII letters.
2241 `strange' indicates a character that has more than one
2244 enum case_type
{one_case
, two_case
, strange
};
2246 /* Describe the run that is in progress,
2247 which the next character can try to extend.
2248 If run_type is strange, that means there really is no run.
2249 If run_type is one_case, then run_start...run_end is the run.
2250 If run_type is two_case, then the run is run_start...run_end,
2251 and the case-equivalents end at run_eqv_end. */
2253 enum case_type run_type
= strange
;
2254 int run_start
, run_end
, run_eqv_end
;
2256 Lisp_Object eqv_table
;
2258 if (!RE_TRANSLATE_P (translate
))
2260 EXTEND_RANGE_TABLE (work_area
, 2);
2261 work_area
->table
[work_area
->used
++] = (start
);
2262 work_area
->table
[work_area
->used
++] = (end
);
2266 eqv_table
= XCHAR_TABLE (translate
)->extras
[2];
2268 for (; start
<= end
; start
++)
2270 enum case_type this_type
;
2271 int eqv
= RE_TRANSLATE (eqv_table
, start
);
2272 int minchar
, maxchar
;
2274 /* Classify this character */
2276 this_type
= one_case
;
2277 else if (RE_TRANSLATE (eqv_table
, eqv
) == start
)
2278 this_type
= two_case
;
2280 this_type
= strange
;
2283 minchar
= start
, maxchar
= eqv
;
2285 minchar
= eqv
, maxchar
= start
;
2287 /* Can this character extend the run in progress? */
2288 if (this_type
== strange
|| this_type
!= run_type
2289 || !(minchar
== run_end
+ 1
2290 && (run_type
== two_case
2291 ? maxchar
== run_eqv_end
+ 1 : 1)))
2294 Record each of its equivalent ranges. */
2295 if (run_type
== one_case
)
2297 EXTEND_RANGE_TABLE (work_area
, 2);
2298 work_area
->table
[work_area
->used
++] = run_start
;
2299 work_area
->table
[work_area
->used
++] = run_end
;
2301 else if (run_type
== two_case
)
2303 EXTEND_RANGE_TABLE (work_area
, 4);
2304 work_area
->table
[work_area
->used
++] = run_start
;
2305 work_area
->table
[work_area
->used
++] = run_end
;
2306 work_area
->table
[work_area
->used
++]
2307 = RE_TRANSLATE (eqv_table
, run_start
);
2308 work_area
->table
[work_area
->used
++]
2309 = RE_TRANSLATE (eqv_table
, run_end
);
2314 if (this_type
== strange
)
2316 /* For a strange character, add each of its equivalents, one
2317 by one. Don't start a range. */
2320 EXTEND_RANGE_TABLE (work_area
, 2);
2321 work_area
->table
[work_area
->used
++] = eqv
;
2322 work_area
->table
[work_area
->used
++] = eqv
;
2323 eqv
= RE_TRANSLATE (eqv_table
, eqv
);
2325 while (eqv
!= start
);
2328 /* Add this char to the run, or start a new run. */
2329 else if (run_type
== strange
)
2331 /* Initialize a new range. */
2332 run_type
= this_type
;
2335 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2339 /* Extend a running range. */
2341 run_eqv_end
= RE_TRANSLATE (eqv_table
, run_end
);
2345 /* If a run is still in progress at the end, finish it now
2346 by recording its equivalent ranges. */
2347 if (run_type
== one_case
)
2349 EXTEND_RANGE_TABLE (work_area
, 2);
2350 work_area
->table
[work_area
->used
++] = run_start
;
2351 work_area
->table
[work_area
->used
++] = run_end
;
2353 else if (run_type
== two_case
)
2355 EXTEND_RANGE_TABLE (work_area
, 4);
2356 work_area
->table
[work_area
->used
++] = run_start
;
2357 work_area
->table
[work_area
->used
++] = run_end
;
2358 work_area
->table
[work_area
->used
++]
2359 = RE_TRANSLATE (eqv_table
, run_start
);
2360 work_area
->table
[work_area
->used
++]
2361 = RE_TRANSLATE (eqv_table
, run_end
);
2369 /* Record the image of the range start..end when passed through
2370 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2371 and is not even necessarily contiguous.
2372 Normally we approximate it with the smallest contiguous range that contains
2373 all the chars we need. However, for Latin-1 we go to extra effort
2376 This function is not called for ASCII ranges.
2378 Returns -1 if successful, REG_ESPACE if ran out of space. */
2381 set_image_of_range (work_area
, start
, end
, translate
)
2382 RE_TRANSLATE_TYPE translate
;
2383 struct range_table_work_area
*work_area
;
2384 re_wchar_t start
, end
;
2386 re_wchar_t cmin
, cmax
;
2389 /* For Latin-1 ranges, use set_image_of_range_1
2390 to get proper handling of ranges that include letters and nonletters.
2391 For a range that includes the whole of Latin-1, this is not necessary.
2392 For other character sets, we don't bother to get this right. */
2393 if (RE_TRANSLATE_P (translate
) && start
< 04400
2394 && !(start
< 04200 && end
>= 04377))
2401 tem
= set_image_of_range_1 (work_area
, start
, newend
, translate
);
2411 EXTEND_RANGE_TABLE (work_area
, 2);
2412 work_area
->table
[work_area
->used
++] = (start
);
2413 work_area
->table
[work_area
->used
++] = (end
);
2415 cmin
= -1, cmax
= -1;
2417 if (RE_TRANSLATE_P (translate
))
2421 for (ch
= start
; ch
<= end
; ch
++)
2423 re_wchar_t c
= TRANSLATE (ch
);
2424 if (! (start
<= c
&& c
<= end
))
2430 cmin
= MIN (cmin
, c
);
2431 cmax
= MAX (cmax
, c
);
2438 EXTEND_RANGE_TABLE (work_area
, 2);
2439 work_area
->table
[work_area
->used
++] = (cmin
);
2440 work_area
->table
[work_area
->used
++] = (cmax
);
2448 #ifndef MATCH_MAY_ALLOCATE
2450 /* If we cannot allocate large objects within re_match_2_internal,
2451 we make the fail stack and register vectors global.
2452 The fail stack, we grow to the maximum size when a regexp
2454 The register vectors, we adjust in size each time we
2455 compile a regexp, according to the number of registers it needs. */
2457 static fail_stack_type fail_stack
;
2459 /* Size with which the following vectors are currently allocated.
2460 That is so we can make them bigger as needed,
2461 but never make them smaller. */
2462 static int regs_allocated_size
;
2464 static re_char
** regstart
, ** regend
;
2465 static re_char
**best_regstart
, **best_regend
;
2467 /* Make the register vectors big enough for NUM_REGS registers,
2468 but don't make them smaller. */
2471 regex_grow_registers (num_regs
)
2474 if (num_regs
> regs_allocated_size
)
2476 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2477 RETALLOC_IF (regend
, num_regs
, re_char
*);
2478 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2479 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2481 regs_allocated_size
= num_regs
;
2485 #endif /* not MATCH_MAY_ALLOCATE */
2487 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2491 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2492 Returns one of error codes defined in `regex.h', or zero for success.
2494 Assumes the `allocated' (and perhaps `buffer') and `translate'
2495 fields are set in BUFP on entry.
2497 If it succeeds, results are put in BUFP (if it returns an error, the
2498 contents of BUFP are undefined):
2499 `buffer' is the compiled pattern;
2500 `syntax' is set to SYNTAX;
2501 `used' is set to the length of the compiled pattern;
2502 `fastmap_accurate' is zero;
2503 `re_nsub' is the number of subexpressions in PATTERN;
2504 `not_bol' and `not_eol' are zero;
2506 The `fastmap' field is neither examined nor set. */
2508 /* Insert the `jump' from the end of last alternative to "here".
2509 The space for the jump has already been allocated. */
2510 #define FIXUP_ALT_JUMP() \
2512 if (fixup_alt_jump) \
2513 STORE_JUMP (jump, fixup_alt_jump, b); \
2517 /* Return, freeing storage we allocated. */
2518 #define FREE_STACK_RETURN(value) \
2520 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2521 free (compile_stack.stack); \
2525 static reg_errcode_t
2526 regex_compile (const re_char
*pattern
, size_t size
, reg_syntax_t syntax
, struct re_pattern_buffer
*bufp
)
2528 /* We fetch characters from PATTERN here. */
2529 register re_wchar_t c
, c1
;
2531 /* A random temporary spot in PATTERN. */
2534 /* Points to the end of the buffer, where we should append. */
2535 register unsigned char *b
;
2537 /* Keeps track of unclosed groups. */
2538 compile_stack_type compile_stack
;
2540 /* Points to the current (ending) position in the pattern. */
2542 /* `const' makes AIX compiler fail. */
2543 unsigned char *p
= pattern
;
2545 re_char
*p
= pattern
;
2547 re_char
*pend
= pattern
+ size
;
2549 /* How to translate the characters in the pattern. */
2550 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2552 /* Address of the count-byte of the most recently inserted `exactn'
2553 command. This makes it possible to tell if a new exact-match
2554 character can be added to that command or if the character requires
2555 a new `exactn' command. */
2556 unsigned char *pending_exact
= 0;
2558 /* Address of start of the most recently finished expression.
2559 This tells, e.g., postfix * where to find the start of its
2560 operand. Reset at the beginning of groups and alternatives. */
2561 unsigned char *laststart
= 0;
2563 /* Address of beginning of regexp, or inside of last group. */
2564 unsigned char *begalt
;
2566 /* Place in the uncompiled pattern (i.e., the {) to
2567 which to go back if the interval is invalid. */
2568 re_char
*beg_interval
;
2570 /* Address of the place where a forward jump should go to the end of
2571 the containing expression. Each alternative of an `or' -- except the
2572 last -- ends with a forward jump of this sort. */
2573 unsigned char *fixup_alt_jump
= 0;
2575 /* Work area for range table of charset. */
2576 struct range_table_work_area range_table_work
;
2578 /* If the object matched can contain multibyte characters. */
2579 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2581 /* If a target of matching can contain multibyte characters. */
2582 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
2584 /* Nonzero if we have pushed down into a subpattern. */
2585 int in_subpattern
= 0;
2587 /* These hold the values of p, pattern, and pend from the main
2588 pattern when we have pushed into a subpattern. */
2590 re_char
*main_pattern
;
2595 DEBUG_PRINT1 ("\nCompiling pattern: ");
2598 unsigned debug_count
;
2600 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2601 putchar (pattern
[debug_count
]);
2606 /* Initialize the compile stack. */
2607 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2608 if (compile_stack
.stack
== NULL
)
2611 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2612 compile_stack
.avail
= 0;
2614 range_table_work
.table
= 0;
2615 range_table_work
.allocated
= 0;
2617 /* Initialize the pattern buffer. */
2618 bufp
->syntax
= syntax
;
2619 bufp
->fastmap_accurate
= 0;
2620 bufp
->not_bol
= bufp
->not_eol
= 0;
2621 bufp
->used_syntax
= 0;
2623 /* Set `used' to zero, so that if we return an error, the pattern
2624 printer (for debugging) will think there's no pattern. We reset it
2628 /* Always count groups, whether or not bufp->no_sub is set. */
2631 #if !defined emacs && !defined SYNTAX_TABLE
2632 /* Initialize the syntax table. */
2633 init_syntax_once ();
2636 if (bufp
->allocated
== 0)
2639 { /* If zero allocated, but buffer is non-null, try to realloc
2640 enough space. This loses if buffer's address is bogus, but
2641 that is the user's responsibility. */
2642 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2645 { /* Caller did not allocate a buffer. Do it for them. */
2646 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2648 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2650 bufp
->allocated
= INIT_BUF_SIZE
;
2653 begalt
= b
= bufp
->buffer
;
2655 /* Loop through the uncompiled pattern until we're at the end. */
2660 /* If this is the end of an included regexp,
2661 pop back to the main regexp and try again. */
2665 pattern
= main_pattern
;
2670 /* If this is the end of the main regexp, we are done. */
2682 /* If there's no special whitespace regexp, treat
2683 spaces normally. And don't try to do this recursively. */
2684 if (!whitespace_regexp
|| in_subpattern
)
2687 /* Peek past following spaces. */
2694 /* If the spaces are followed by a repetition op,
2695 treat them normally. */
2697 && (*p1
== '*' || *p1
== '+' || *p1
== '?'
2698 || (*p1
== '\\' && p1
+ 1 != pend
&& p1
[1] == '{')))
2701 /* Replace the spaces with the whitespace regexp. */
2705 main_pattern
= pattern
;
2706 p
= pattern
= whitespace_regexp
;
2707 pend
= p
+ strlen (p
);
2713 if ( /* If at start of pattern, it's an operator. */
2715 /* If context independent, it's an operator. */
2716 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2717 /* Otherwise, depends on what's come before. */
2718 || at_begline_loc_p (pattern
, p
, syntax
))
2719 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2728 if ( /* If at end of pattern, it's an operator. */
2730 /* If context independent, it's an operator. */
2731 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2732 /* Otherwise, depends on what's next. */
2733 || at_endline_loc_p (p
, pend
, syntax
))
2734 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2743 if ((syntax
& RE_BK_PLUS_QM
)
2744 || (syntax
& RE_LIMITED_OPS
))
2748 /* If there is no previous pattern... */
2751 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2752 FREE_STACK_RETURN (REG_BADRPT
);
2753 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2758 /* 1 means zero (many) matches is allowed. */
2759 boolean zero_times_ok
= 0, many_times_ok
= 0;
2762 /* If there is a sequence of repetition chars, collapse it
2763 down to just one (the right one). We can't combine
2764 interval operators with these because of, e.g., `a{2}*',
2765 which should only match an even number of `a's. */
2769 if ((syntax
& RE_FRUGAL
)
2770 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2774 zero_times_ok
|= c
!= '+';
2775 many_times_ok
|= c
!= '?';
2781 || (!(syntax
& RE_BK_PLUS_QM
)
2782 && (*p
== '+' || *p
== '?')))
2784 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2787 FREE_STACK_RETURN (REG_EESCAPE
);
2788 if (p
[1] == '+' || p
[1] == '?')
2789 PATFETCH (c
); /* Gobble up the backslash. */
2795 /* If we get here, we found another repeat character. */
2799 /* Star, etc. applied to an empty pattern is equivalent
2800 to an empty pattern. */
2801 if (!laststart
|| laststart
== b
)
2804 /* Now we know whether or not zero matches is allowed
2805 and also whether or not two or more matches is allowed. */
2810 boolean simple
= skip_one_char (laststart
) == b
;
2811 unsigned int startoffset
= 0;
2813 /* Check if the loop can match the empty string. */
2814 (simple
|| !analyse_first (laststart
, b
, NULL
, 0))
2815 ? on_failure_jump
: on_failure_jump_loop
;
2816 assert (skip_one_char (laststart
) <= b
);
2818 if (!zero_times_ok
&& simple
)
2819 { /* Since simple * loops can be made faster by using
2820 on_failure_keep_string_jump, we turn simple P+
2821 into PP* if P is simple. */
2822 unsigned char *p1
, *p2
;
2823 startoffset
= b
- laststart
;
2824 GET_BUFFER_SPACE (startoffset
);
2825 p1
= b
; p2
= laststart
;
2831 GET_BUFFER_SPACE (6);
2834 STORE_JUMP (ofj
, b
, b
+ 6);
2836 /* Simple * loops can use on_failure_keep_string_jump
2837 depending on what follows. But since we don't know
2838 that yet, we leave the decision up to
2839 on_failure_jump_smart. */
2840 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2841 laststart
+ startoffset
, b
+ 6);
2843 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2848 /* A simple ? pattern. */
2849 assert (zero_times_ok
);
2850 GET_BUFFER_SPACE (3);
2851 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2855 else /* not greedy */
2856 { /* I wish the greedy and non-greedy cases could be merged. */
2858 GET_BUFFER_SPACE (7); /* We might use less. */
2861 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2863 /* The non-greedy multiple match looks like
2864 a repeat..until: we only need a conditional jump
2865 at the end of the loop. */
2866 if (emptyp
) BUF_PUSH (no_op
);
2867 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2868 : on_failure_jump
, b
, laststart
);
2872 /* The repeat...until naturally matches one or more.
2873 To also match zero times, we need to first jump to
2874 the end of the loop (its conditional jump). */
2875 INSERT_JUMP (jump
, laststart
, b
);
2881 /* non-greedy a?? */
2882 INSERT_JUMP (jump
, laststart
, b
+ 3);
2884 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2901 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2903 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2905 /* Ensure that we have enough space to push a charset: the
2906 opcode, the length count, and the bitset; 34 bytes in all. */
2907 GET_BUFFER_SPACE (34);
2911 /* We test `*p == '^' twice, instead of using an if
2912 statement, so we only need one BUF_PUSH. */
2913 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2917 /* Remember the first position in the bracket expression. */
2920 /* Push the number of bytes in the bitmap. */
2921 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2923 /* Clear the whole map. */
2924 memset (b
, 0, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2926 /* charset_not matches newline according to a syntax bit. */
2927 if ((re_opcode_t
) b
[-2] == charset_not
2928 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2929 SET_LIST_BIT ('\n');
2931 /* Read in characters and ranges, setting map bits. */
2934 boolean escaped_char
= false;
2935 const unsigned char *p2
= p
;
2938 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2940 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2941 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2942 So the translation is done later in a loop. Example:
2943 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2946 /* \ might escape characters inside [...] and [^...]. */
2947 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2949 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2952 escaped_char
= true;
2956 /* Could be the end of the bracket expression. If it's
2957 not (i.e., when the bracket expression is `[]' so
2958 far), the ']' character bit gets set way below. */
2959 if (c
== ']' && p2
!= p1
)
2963 /* See if we're at the beginning of a possible character
2966 if (!escaped_char
&&
2967 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2969 /* Leave room for the null. */
2970 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2971 const unsigned char *class_beg
;
2977 /* If pattern is `[[:'. */
2978 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2983 if ((c
== ':' && *p
== ']') || p
== pend
)
2985 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2988 /* This is in any case an invalid class name. */
2993 /* If isn't a word bracketed by `[:' and `:]':
2994 undo the ending character, the letters, and
2995 leave the leading `:' and `[' (but set bits for
2997 if (c
== ':' && *p
== ']')
3002 cc
= re_wctype (str
);
3005 FREE_STACK_RETURN (REG_ECTYPE
);
3007 /* Throw away the ] at the end of the character
3011 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
3014 for (ch
= 0; ch
< (1 << BYTEWIDTH
); ++ch
)
3015 if (re_iswctype (btowc (ch
), cc
))
3018 if (c
< (1 << BYTEWIDTH
))
3022 /* Most character classes in a multibyte match
3023 just set a flag. Exceptions are is_blank,
3024 is_digit, is_cntrl, and is_xdigit, since
3025 they can only match ASCII characters. We
3026 don't need to handle them for multibyte.
3027 They are distinguished by a negative wctype. */
3029 /* Setup the gl_state object to its buffer-defined
3030 value. This hardcodes the buffer-global
3031 syntax-table for ASCII chars, while the other chars
3032 will obey syntax-table properties. It's not ideal,
3033 but it's the way it's been done until now. */
3034 SETUP_BUFFER_SYNTAX_TABLE ();
3036 for (ch
= 0; ch
< 256; ++ch
)
3038 c
= RE_CHAR_TO_MULTIBYTE (ch
);
3039 if (! CHAR_BYTE8_P (c
)
3040 && re_iswctype (c
, cc
))
3046 if (ASCII_CHAR_P (c1
))
3048 else if ((c1
= RE_CHAR_TO_UNIBYTE (c1
)) >= 0)
3052 SET_RANGE_TABLE_WORK_AREA_BIT
3053 (range_table_work
, re_wctype_to_bit (cc
));
3055 /* In most cases the matching rule for char classes
3056 only uses the syntax table for multibyte chars,
3057 so that the content of the syntax-table it is not
3058 hardcoded in the range_table. SPACE and WORD are
3059 the two exceptions. */
3060 if ((1 << cc
) & ((1 << RECC_SPACE
) | (1 << RECC_WORD
)))
3061 bufp
->used_syntax
= 1;
3063 /* Repeat the loop. */
3068 /* Go back to right after the "[:". */
3072 /* Because the `:' may starts the range, we
3073 can't simply set bit and repeat the loop.
3074 Instead, just set it to C and handle below. */
3079 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
3082 /* Discard the `-'. */
3085 /* Fetch the character which ends the range. */
3088 if (CHAR_BYTE8_P (c1
)
3089 && ! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
3090 /* Treat the range from a multibyte character to
3091 raw-byte character as empty. */
3096 /* Range from C to C. */
3101 if (syntax
& RE_NO_EMPTY_RANGES
)
3102 FREE_STACK_RETURN (REG_ERANGEX
);
3103 /* Else, repeat the loop. */
3108 /* Set the range into bitmap */
3109 for (; c
<= c1
; c
++)
3112 if (ch
< (1 << BYTEWIDTH
))
3119 SETUP_ASCII_RANGE (range_table_work
, c
, ch
);
3121 if (CHAR_BYTE8_P (c1
))
3122 c
= BYTE8_TO_CHAR (128);
3126 if (CHAR_BYTE8_P (c
))
3128 c
= CHAR_TO_BYTE8 (c
);
3129 c1
= CHAR_TO_BYTE8 (c1
);
3130 for (; c
<= c1
; c
++)
3135 SETUP_MULTIBYTE_RANGE (range_table_work
, c
, c1
);
3139 SETUP_UNIBYTE_RANGE (range_table_work
, c
, c1
);
3146 /* Discard any (non)matching list bytes that are all 0 at the
3147 end of the map. Decrease the map-length byte too. */
3148 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
3152 /* Build real range table from work area. */
3153 if (RANGE_TABLE_WORK_USED (range_table_work
)
3154 || RANGE_TABLE_WORK_BITS (range_table_work
))
3157 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
3159 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3160 bytes for flags, two for COUNT, and three bytes for
3162 GET_BUFFER_SPACE (4 + used
* 3);
3164 /* Indicate the existence of range table. */
3165 laststart
[1] |= 0x80;
3167 /* Store the character class flag bits into the range table.
3168 If not in emacs, these flag bits are always 0. */
3169 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
3170 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
3172 STORE_NUMBER_AND_INCR (b
, used
/ 2);
3173 for (i
= 0; i
< used
; i
++)
3174 STORE_CHARACTER_AND_INCR
3175 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
3182 if (syntax
& RE_NO_BK_PARENS
)
3189 if (syntax
& RE_NO_BK_PARENS
)
3196 if (syntax
& RE_NEWLINE_ALT
)
3203 if (syntax
& RE_NO_BK_VBAR
)
3210 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
3211 goto handle_interval
;
3217 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
3219 /* Do not translate the character after the \, so that we can
3220 distinguish, e.g., \B from \b, even if we normally would
3221 translate, e.g., B to b. */
3227 if (syntax
& RE_NO_BK_PARENS
)
3228 goto normal_backslash
;
3233 regnum_t regnum
= 0;
3236 /* Look for a special (?...) construct */
3237 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
3239 PATFETCH (c
); /* Gobble up the '?'. */
3245 case ':': shy
= 1; break;
3247 /* An explicitly specified regnum must start
3250 FREE_STACK_RETURN (REG_BADPAT
);
3251 case '1': case '2': case '3': case '4':
3252 case '5': case '6': case '7': case '8': case '9':
3253 regnum
= 10*regnum
+ (c
- '0'); break;
3255 /* Only (?:...) is supported right now. */
3256 FREE_STACK_RETURN (REG_BADPAT
);
3263 regnum
= ++bufp
->re_nsub
;
3265 { /* It's actually not shy, but explicitly numbered. */
3267 if (regnum
> bufp
->re_nsub
)
3268 bufp
->re_nsub
= regnum
;
3269 else if (regnum
> bufp
->re_nsub
3270 /* Ideally, we'd want to check that the specified
3271 group can't have matched (i.e. all subgroups
3272 using the same regnum are in other branches of
3273 OR patterns), but we don't currently keep track
3274 of enough info to do that easily. */
3275 || group_in_compile_stack (compile_stack
, regnum
))
3276 FREE_STACK_RETURN (REG_BADPAT
);
3279 /* It's really shy. */
3280 regnum
= - bufp
->re_nsub
;
3282 if (COMPILE_STACK_FULL
)
3284 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
3285 compile_stack_elt_t
);
3286 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
3288 compile_stack
.size
<<= 1;
3291 /* These are the values to restore when we hit end of this
3292 group. They are all relative offsets, so that if the
3293 whole pattern moves because of realloc, they will still
3295 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
3296 COMPILE_STACK_TOP
.fixup_alt_jump
3297 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
3298 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
3299 COMPILE_STACK_TOP
.regnum
= regnum
;
3301 /* Do not push a start_memory for groups beyond the last one
3302 we can represent in the compiled pattern. */
3303 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3304 BUF_PUSH_2 (start_memory
, regnum
);
3306 compile_stack
.avail
++;
3311 /* If we've reached MAX_REGNUM groups, then this open
3312 won't actually generate any code, so we'll have to
3313 clear pending_exact explicitly. */
3319 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
3321 if (COMPILE_STACK_EMPTY
)
3323 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3324 goto normal_backslash
;
3326 FREE_STACK_RETURN (REG_ERPAREN
);
3332 /* See similar code for backslashed left paren above. */
3333 if (COMPILE_STACK_EMPTY
)
3335 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
3338 FREE_STACK_RETURN (REG_ERPAREN
);
3341 /* Since we just checked for an empty stack above, this
3342 ``can't happen''. */
3343 assert (compile_stack
.avail
!= 0);
3345 /* We don't just want to restore into `regnum', because
3346 later groups should continue to be numbered higher,
3347 as in `(ab)c(de)' -- the second group is #2. */
3350 compile_stack
.avail
--;
3351 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
3353 = COMPILE_STACK_TOP
.fixup_alt_jump
3354 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
3356 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
3357 regnum
= COMPILE_STACK_TOP
.regnum
;
3358 /* If we've reached MAX_REGNUM groups, then this open
3359 won't actually generate any code, so we'll have to
3360 clear pending_exact explicitly. */
3363 /* We're at the end of the group, so now we know how many
3364 groups were inside this one. */
3365 if (regnum
<= MAX_REGNUM
&& regnum
> 0)
3366 BUF_PUSH_2 (stop_memory
, regnum
);
3371 case '|': /* `\|'. */
3372 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
3373 goto normal_backslash
;
3375 if (syntax
& RE_LIMITED_OPS
)
3378 /* Insert before the previous alternative a jump which
3379 jumps to this alternative if the former fails. */
3380 GET_BUFFER_SPACE (3);
3381 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
3385 /* The alternative before this one has a jump after it
3386 which gets executed if it gets matched. Adjust that
3387 jump so it will jump to this alternative's analogous
3388 jump (put in below, which in turn will jump to the next
3389 (if any) alternative's such jump, etc.). The last such
3390 jump jumps to the correct final destination. A picture:
3396 If we are at `b', then fixup_alt_jump right now points to a
3397 three-byte space after `a'. We'll put in the jump, set
3398 fixup_alt_jump to right after `b', and leave behind three
3399 bytes which we'll fill in when we get to after `c'. */
3403 /* Mark and leave space for a jump after this alternative,
3404 to be filled in later either by next alternative or
3405 when know we're at the end of a series of alternatives. */
3407 GET_BUFFER_SPACE (3);
3416 /* If \{ is a literal. */
3417 if (!(syntax
& RE_INTERVALS
)
3418 /* If we're at `\{' and it's not the open-interval
3420 || (syntax
& RE_NO_BK_BRACES
))
3421 goto normal_backslash
;
3425 /* If got here, then the syntax allows intervals. */
3427 /* At least (most) this many matches must be made. */
3428 int lower_bound
= 0, upper_bound
= -1;
3432 GET_UNSIGNED_NUMBER (lower_bound
);
3435 GET_UNSIGNED_NUMBER (upper_bound
);
3437 /* Interval such as `{1}' => match exactly once. */
3438 upper_bound
= lower_bound
;
3440 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
3441 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
3442 FREE_STACK_RETURN (REG_BADBR
);
3444 if (!(syntax
& RE_NO_BK_BRACES
))
3447 FREE_STACK_RETURN (REG_BADBR
);
3449 FREE_STACK_RETURN (REG_EESCAPE
);
3454 FREE_STACK_RETURN (REG_BADBR
);
3456 /* We just parsed a valid interval. */
3458 /* If it's invalid to have no preceding re. */
3461 if (syntax
& RE_CONTEXT_INVALID_OPS
)
3462 FREE_STACK_RETURN (REG_BADRPT
);
3463 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
3466 goto unfetch_interval
;
3469 if (upper_bound
== 0)
3470 /* If the upper bound is zero, just drop the sub pattern
3473 else if (lower_bound
== 1 && upper_bound
== 1)
3474 /* Just match it once: nothing to do here. */
3477 /* Otherwise, we have a nontrivial interval. When
3478 we're all done, the pattern will look like:
3479 set_number_at <jump count> <upper bound>
3480 set_number_at <succeed_n count> <lower bound>
3481 succeed_n <after jump addr> <succeed_n count>
3483 jump_n <succeed_n addr> <jump count>
3484 (The upper bound and `jump_n' are omitted if
3485 `upper_bound' is 1, though.) */
3487 { /* If the upper bound is > 1, we need to insert
3488 more at the end of the loop. */
3489 unsigned int nbytes
= (upper_bound
< 0 ? 3
3490 : upper_bound
> 1 ? 5 : 0);
3491 unsigned int startoffset
= 0;
3493 GET_BUFFER_SPACE (20); /* We might use less. */
3495 if (lower_bound
== 0)
3497 /* A succeed_n that starts with 0 is really a
3498 a simple on_failure_jump_loop. */
3499 INSERT_JUMP (on_failure_jump_loop
, laststart
,
3505 /* Initialize lower bound of the `succeed_n', even
3506 though it will be set during matching by its
3507 attendant `set_number_at' (inserted next),
3508 because `re_compile_fastmap' needs to know.
3509 Jump to the `jump_n' we might insert below. */
3510 INSERT_JUMP2 (succeed_n
, laststart
,
3515 /* Code to initialize the lower bound. Insert
3516 before the `succeed_n'. The `5' is the last two
3517 bytes of this `set_number_at', plus 3 bytes of
3518 the following `succeed_n'. */
3519 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3524 if (upper_bound
< 0)
3526 /* A negative upper bound stands for infinity,
3527 in which case it degenerates to a plain jump. */
3528 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3531 else if (upper_bound
> 1)
3532 { /* More than one repetition is allowed, so
3533 append a backward jump to the `succeed_n'
3534 that starts this interval.
3536 When we've reached this during matching,
3537 we'll have matched the interval once, so
3538 jump back only `upper_bound - 1' times. */
3539 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3543 /* The location we want to set is the second
3544 parameter of the `jump_n'; that is `b-2' as
3545 an absolute address. `laststart' will be
3546 the `set_number_at' we're about to insert;
3547 `laststart+3' the number to set, the source
3548 for the relative address. But we are
3549 inserting into the middle of the pattern --
3550 so everything is getting moved up by 5.
3551 Conclusion: (b - 2) - (laststart + 3) + 5,
3552 i.e., b - laststart.
3554 We insert this at the beginning of the loop
3555 so that if we fail during matching, we'll
3556 reinitialize the bounds. */
3557 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3558 upper_bound
- 1, b
);
3563 beg_interval
= NULL
;
3568 /* If an invalid interval, match the characters as literals. */
3569 assert (beg_interval
);
3571 beg_interval
= NULL
;
3573 /* normal_char and normal_backslash need `c'. */
3576 if (!(syntax
& RE_NO_BK_BRACES
))
3578 assert (p
> pattern
&& p
[-1] == '\\');
3579 goto normal_backslash
;
3585 /* There is no way to specify the before_dot and after_dot
3586 operators. rms says this is ok. --karl */
3594 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3600 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3606 BUF_PUSH_2 (categoryspec
, c
);
3612 BUF_PUSH_2 (notcategoryspec
, c
);
3618 if (syntax
& RE_NO_GNU_OPS
)
3621 BUF_PUSH_2 (syntaxspec
, Sword
);
3626 if (syntax
& RE_NO_GNU_OPS
)
3629 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3634 if (syntax
& RE_NO_GNU_OPS
)
3640 if (syntax
& RE_NO_GNU_OPS
)
3646 if (syntax
& RE_NO_GNU_OPS
)
3655 FREE_STACK_RETURN (REG_BADPAT
);
3659 if (syntax
& RE_NO_GNU_OPS
)
3661 BUF_PUSH (wordbound
);
3665 if (syntax
& RE_NO_GNU_OPS
)
3667 BUF_PUSH (notwordbound
);
3671 if (syntax
& RE_NO_GNU_OPS
)
3677 if (syntax
& RE_NO_GNU_OPS
)
3682 case '1': case '2': case '3': case '4': case '5':
3683 case '6': case '7': case '8': case '9':
3687 if (syntax
& RE_NO_BK_REFS
)
3688 goto normal_backslash
;
3692 if (reg
> bufp
->re_nsub
|| reg
< 1
3693 /* Can't back reference to a subexp before its end. */
3694 || group_in_compile_stack (compile_stack
, reg
))
3695 FREE_STACK_RETURN (REG_ESUBREG
);
3698 BUF_PUSH_2 (duplicate
, reg
);
3705 if (syntax
& RE_BK_PLUS_QM
)
3708 goto normal_backslash
;
3712 /* You might think it would be useful for \ to mean
3713 not to translate; but if we don't translate it
3714 it will never match anything. */
3721 /* Expects the character in `c'. */
3723 /* If no exactn currently being built. */
3726 /* If last exactn not at current position. */
3727 || pending_exact
+ *pending_exact
+ 1 != b
3729 /* We have only one byte following the exactn for the count. */
3730 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3732 /* If followed by a repetition operator. */
3733 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3734 || ((syntax
& RE_BK_PLUS_QM
)
3735 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3736 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3737 || ((syntax
& RE_INTERVALS
)
3738 && ((syntax
& RE_NO_BK_BRACES
)
3739 ? p
!= pend
&& *p
== '{'
3740 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3742 /* Start building a new exactn. */
3746 BUF_PUSH_2 (exactn
, 0);
3747 pending_exact
= b
- 1;
3750 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3757 len
= CHAR_STRING (c
, b
);
3762 c1
= RE_CHAR_TO_MULTIBYTE (c
);
3763 if (! CHAR_BYTE8_P (c1
))
3765 re_wchar_t c2
= TRANSLATE (c1
);
3767 if (c1
!= c2
&& (c1
= RE_CHAR_TO_UNIBYTE (c2
)) >= 0)
3773 (*pending_exact
) += len
;
3778 } /* while p != pend */
3781 /* Through the pattern now. */
3785 if (!COMPILE_STACK_EMPTY
)
3786 FREE_STACK_RETURN (REG_EPAREN
);
3788 /* If we don't want backtracking, force success
3789 the first time we reach the end of the compiled pattern. */
3790 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3793 /* We have succeeded; set the length of the buffer. */
3794 bufp
->used
= b
- bufp
->buffer
;
3799 re_compile_fastmap (bufp
);
3800 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3801 print_compiled_pattern (bufp
);
3806 #ifndef MATCH_MAY_ALLOCATE
3807 /* Initialize the failure stack to the largest possible stack. This
3808 isn't necessary unless we're trying to avoid calling alloca in
3809 the search and match routines. */
3811 int num_regs
= bufp
->re_nsub
+ 1;
3813 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3815 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3817 if (! fail_stack
.stack
)
3819 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3820 * sizeof (fail_stack_elt_t
));
3823 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3825 * sizeof (fail_stack_elt_t
)));
3828 regex_grow_registers (num_regs
);
3830 #endif /* not MATCH_MAY_ALLOCATE */
3832 FREE_STACK_RETURN (REG_NOERROR
);
3833 } /* regex_compile */
3835 /* Subroutines for `regex_compile'. */
3837 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3840 store_op1 (re_opcode_t op
, unsigned char *loc
, int arg
)
3842 *loc
= (unsigned char) op
;
3843 STORE_NUMBER (loc
+ 1, arg
);
3847 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3850 store_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
)
3852 *loc
= (unsigned char) op
;
3853 STORE_NUMBER (loc
+ 1, arg1
);
3854 STORE_NUMBER (loc
+ 3, arg2
);
3858 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3859 for OP followed by two-byte integer parameter ARG. */
3862 insert_op1 (re_opcode_t op
, unsigned char *loc
, int arg
, unsigned char *end
)
3864 register unsigned char *pfrom
= end
;
3865 register unsigned char *pto
= end
+ 3;
3867 while (pfrom
!= loc
)
3870 store_op1 (op
, loc
, arg
);
3874 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3877 insert_op2 (re_opcode_t op
, unsigned char *loc
, int arg1
, int arg2
, unsigned char *end
)
3879 register unsigned char *pfrom
= end
;
3880 register unsigned char *pto
= end
+ 5;
3882 while (pfrom
!= loc
)
3885 store_op2 (op
, loc
, arg1
, arg2
);
3889 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3890 after an alternative or a begin-subexpression. We assume there is at
3891 least one character before the ^. */
3894 at_begline_loc_p (const re_char
*pattern
, const re_char
*p
, reg_syntax_t syntax
)
3896 re_char
*prev
= p
- 2;
3897 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3900 /* After a subexpression? */
3901 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3902 /* After an alternative? */
3903 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3904 /* After a shy subexpression? */
3905 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3906 && prev
[-1] == '?' && prev
[-2] == '('
3907 && (syntax
& RE_NO_BK_PARENS
3908 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3912 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3913 at least one character after the $, i.e., `P < PEND'. */
3916 at_endline_loc_p (const re_char
*p
, const re_char
*pend
, reg_syntax_t syntax
)
3919 boolean next_backslash
= *next
== '\\';
3920 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3923 /* Before a subexpression? */
3924 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3925 : next_backslash
&& next_next
&& *next_next
== ')')
3926 /* Before an alternative? */
3927 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3928 : next_backslash
&& next_next
&& *next_next
== '|');
3932 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3933 false if it's not. */
3936 group_in_compile_stack (compile_stack_type compile_stack
, regnum_t regnum
)
3940 for (this_element
= compile_stack
.avail
- 1;
3943 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3950 If fastmap is non-NULL, go through the pattern and fill fastmap
3951 with all the possible leading chars. If fastmap is NULL, don't
3952 bother filling it up (obviously) and only return whether the
3953 pattern could potentially match the empty string.
3955 Return 1 if p..pend might match the empty string.
3956 Return 0 if p..pend matches at least one char.
3957 Return -1 if fastmap was not updated accurately. */
3960 analyse_first (const re_char
*p
, const re_char
*pend
, char *fastmap
, const int multibyte
)
3965 /* If all elements for base leading-codes in fastmap is set, this
3966 flag is set true. */
3967 boolean match_any_multibyte_characters
= false;
3971 /* The loop below works as follows:
3972 - It has a working-list kept in the PATTERN_STACK and which basically
3973 starts by only containing a pointer to the first operation.
3974 - If the opcode we're looking at is a match against some set of
3975 chars, then we add those chars to the fastmap and go on to the
3976 next work element from the worklist (done via `break').
3977 - If the opcode is a control operator on the other hand, we either
3978 ignore it (if it's meaningless at this point, such as `start_memory')
3979 or execute it (if it's a jump). If the jump has several destinations
3980 (i.e. `on_failure_jump'), then we push the other destination onto the
3982 We guarantee termination by ignoring backward jumps (more or less),
3983 so that `p' is monotonically increasing. More to the point, we
3984 never set `p' (or push) anything `<= p1'. */
3988 /* `p1' is used as a marker of how far back a `on_failure_jump'
3989 can go without being ignored. It is normally equal to `p'
3990 (which prevents any backward `on_failure_jump') except right
3991 after a plain `jump', to allow patterns such as:
3994 10: on_failure_jump 3
3995 as used for the *? operator. */
3998 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
4004 /* If the first character has to match a backreference, that means
4005 that the group was empty (since it already matched). Since this
4006 is the only case that interests us here, we can assume that the
4007 backreference must match the empty string. */
4012 /* Following are the cases which match a character. These end
4018 /* If multibyte is nonzero, the first byte of each
4019 character is an ASCII or a leading code. Otherwise,
4020 each byte is a character. Thus, this works in both
4025 /* For the case of matching this unibyte regex
4026 against multibyte, we must set a leading code of
4027 the corresponding multibyte character. */
4028 int c
= RE_CHAR_TO_MULTIBYTE (p
[1]);
4030 fastmap
[CHAR_LEADING_CODE (c
)] = 1;
4037 /* We could put all the chars except for \n (and maybe \0)
4038 but we don't bother since it is generally not worth it. */
4039 if (!fastmap
) break;
4044 if (!fastmap
) break;
4046 /* Chars beyond end of bitmap are possible matches. */
4047 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
4048 j
< (1 << BYTEWIDTH
); j
++)
4054 if (!fastmap
) break;
4055 not = (re_opcode_t
) *(p
- 1) == charset_not
;
4056 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
4058 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
4062 if (/* Any leading code can possibly start a character
4063 which doesn't match the specified set of characters. */
4066 /* If we can match a character class, we can match any
4067 multibyte characters. */
4068 (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4069 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
4072 if (match_any_multibyte_characters
== false)
4074 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4075 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4077 match_any_multibyte_characters
= true;
4081 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
4082 && match_any_multibyte_characters
== false)
4084 /* Set fastmap[I] to 1 where I is a leading code of each
4085 multibyte character in the range table. */
4087 unsigned char lc1
, lc2
;
4089 /* Make P points the range table. `+ 2' is to skip flag
4090 bits for a character class. */
4091 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
4093 /* Extract the number of ranges in range table into COUNT. */
4094 EXTRACT_NUMBER_AND_INCR (count
, p
);
4095 for (; count
> 0; count
--, p
+= 3)
4097 /* Extract the start and end of each range. */
4098 EXTRACT_CHARACTER (c
, p
);
4099 lc1
= CHAR_LEADING_CODE (c
);
4101 EXTRACT_CHARACTER (c
, p
);
4102 lc2
= CHAR_LEADING_CODE (c
);
4103 for (j
= lc1
; j
<= lc2
; j
++)
4112 if (!fastmap
) break;
4114 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
4116 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
4117 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
4121 /* This match depends on text properties. These end with
4122 aborting optimizations. */
4126 case notcategoryspec
:
4127 if (!fastmap
) break;
4128 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
4130 for (j
= (1 << BYTEWIDTH
); j
>= 0; j
--)
4131 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
4134 /* Any leading code can possibly start a character which
4135 has or doesn't has the specified category. */
4136 if (match_any_multibyte_characters
== false)
4138 for (j
= MIN_MULTIBYTE_LEADING_CODE
;
4139 j
<= MAX_MULTIBYTE_LEADING_CODE
; j
++)
4141 match_any_multibyte_characters
= true;
4145 /* All cases after this match the empty string. These end with
4167 EXTRACT_NUMBER_AND_INCR (j
, p
);
4169 /* Backward jumps can only go back to code that we've already
4170 visited. `re_compile' should make sure this is true. */
4173 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4175 case on_failure_jump
:
4176 case on_failure_keep_string_jump
:
4177 case on_failure_jump_loop
:
4178 case on_failure_jump_nastyloop
:
4179 case on_failure_jump_smart
:
4185 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4186 to jump back to "just after here". */
4189 case on_failure_jump
:
4190 case on_failure_keep_string_jump
:
4191 case on_failure_jump_nastyloop
:
4192 case on_failure_jump_loop
:
4193 case on_failure_jump_smart
:
4194 EXTRACT_NUMBER_AND_INCR (j
, p
);
4196 ; /* Backward jump to be ignored. */
4198 { /* We have to look down both arms.
4199 We first go down the "straight" path so as to minimize
4200 stack usage when going through alternatives. */
4201 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
4209 /* This code simply does not properly handle forward jump_n. */
4210 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
4212 /* jump_n can either jump or fall through. The (backward) jump
4213 case has already been handled, so we only need to look at the
4214 fallthrough case. */
4218 /* If N == 0, it should be an on_failure_jump_loop instead. */
4219 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
4221 /* We only care about one iteration of the loop, so we don't
4222 need to consider the case where this behaves like an
4239 abort (); /* We have listed all the cases. */
4242 /* Getting here means we have found the possible starting
4243 characters for one path of the pattern -- and that the empty
4244 string does not match. We need not follow this path further. */
4248 /* We reached the end without matching anything. */
4251 } /* analyse_first */
4253 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4254 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4255 characters can start a string that matches the pattern. This fastmap
4256 is used by re_search to skip quickly over impossible starting points.
4258 Character codes above (1 << BYTEWIDTH) are not represented in the
4259 fastmap, but the leading codes are represented. Thus, the fastmap
4260 indicates which character sets could start a match.
4262 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4263 area as BUFP->fastmap.
4265 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4268 Returns 0 if we succeed, -2 if an internal error. */
4271 re_compile_fastmap (struct re_pattern_buffer
*bufp
)
4273 char *fastmap
= bufp
->fastmap
;
4276 assert (fastmap
&& bufp
->buffer
);
4278 memset (fastmap
, 0, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
4279 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
4281 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
4282 fastmap
, RE_MULTIBYTE_P (bufp
));
4283 bufp
->can_be_null
= (analysis
!= 0);
4285 } /* re_compile_fastmap */
4287 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4288 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4289 this memory for recording register information. STARTS and ENDS
4290 must be allocated using the malloc library routine, and must each
4291 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4293 If NUM_REGS == 0, then subsequent matches should allocate their own
4296 Unless this function is called, the first search or match using
4297 PATTERN_BUFFER will allocate its own register data, without
4298 freeing the old data. */
4301 re_set_registers (struct re_pattern_buffer
*bufp
, struct re_registers
*regs
, unsigned int num_regs
, regoff_t
*starts
, regoff_t
*ends
)
4305 bufp
->regs_allocated
= REGS_REALLOCATE
;
4306 regs
->num_regs
= num_regs
;
4307 regs
->start
= starts
;
4312 bufp
->regs_allocated
= REGS_UNALLOCATED
;
4314 regs
->start
= regs
->end
= (regoff_t
*) 0;
4317 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
4319 /* Searching routines. */
4321 /* Like re_search_2, below, but only one string is specified, and
4322 doesn't let you say where to stop matching. */
4325 re_search (struct re_pattern_buffer
*bufp
, const char *string
, int size
, int startpos
, int range
, struct re_registers
*regs
)
4327 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
4330 WEAK_ALIAS (__re_search
, re_search
)
4332 /* Head address of virtual concatenation of string. */
4333 #define HEAD_ADDR_VSTRING(P) \
4334 (((P) >= size1 ? string2 : string1))
4336 /* End address of virtual concatenation of string. */
4337 #define STOP_ADDR_VSTRING(P) \
4338 (((P) >= size1 ? string2 + size2 : string1 + size1))
4340 /* Address of POS in the concatenation of virtual string. */
4341 #define POS_ADDR_VSTRING(POS) \
4342 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4344 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4345 virtual concatenation of STRING1 and STRING2, starting first at index
4346 STARTPOS, then at STARTPOS + 1, and so on.
4348 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4350 RANGE is how far to scan while trying to match. RANGE = 0 means try
4351 only at STARTPOS; in general, the last start tried is STARTPOS +
4354 In REGS, return the indices of the virtual concatenation of STRING1
4355 and STRING2 that matched the entire BUFP->buffer and its contained
4358 Do not consider matching one past the index STOP in the virtual
4359 concatenation of STRING1 and STRING2.
4361 We return either the position in the strings at which the match was
4362 found, -1 if no match, or -2 if error (such as failure
4366 re_search_2 (struct re_pattern_buffer
*bufp
, const char *str1
, int size1
, const char *str2
, int size2
, int startpos
, int range
, struct re_registers
*regs
, int stop
)
4369 re_char
*string1
= (re_char
*) str1
;
4370 re_char
*string2
= (re_char
*) str2
;
4371 register char *fastmap
= bufp
->fastmap
;
4372 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4373 int total_size
= size1
+ size2
;
4374 int endpos
= startpos
+ range
;
4375 boolean anchored_start
;
4376 /* Nonzero if we are searching multibyte string. */
4377 const boolean multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
4379 /* Check for out-of-range STARTPOS. */
4380 if (startpos
< 0 || startpos
> total_size
)
4383 /* Fix up RANGE if it might eventually take us outside
4384 the virtual concatenation of STRING1 and STRING2.
4385 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4387 range
= 0 - startpos
;
4388 else if (endpos
> total_size
)
4389 range
= total_size
- startpos
;
4391 /* If the search isn't to be a backwards one, don't waste time in a
4392 search for a pattern anchored at beginning of buffer. */
4393 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
4402 /* In a forward search for something that starts with \=.
4403 don't keep searching past point. */
4404 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
4406 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
4412 /* Update the fastmap now if not correct already. */
4413 if (fastmap
&& !bufp
->fastmap_accurate
)
4414 re_compile_fastmap (bufp
);
4416 /* See whether the pattern is anchored. */
4417 anchored_start
= (bufp
->buffer
[0] == begline
);
4420 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4422 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
4424 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4428 /* Loop through the string, looking for a place to start matching. */
4431 /* If the pattern is anchored,
4432 skip quickly past places we cannot match.
4433 We don't bother to treat startpos == 0 specially
4434 because that case doesn't repeat. */
4435 if (anchored_start
&& startpos
> 0)
4437 if (! ((startpos
<= size1
? string1
[startpos
- 1]
4438 : string2
[startpos
- size1
- 1])
4443 /* If a fastmap is supplied, skip quickly over characters that
4444 cannot be the start of a match. If the pattern can match the
4445 null string, however, we don't need to skip characters; we want
4446 the first null string. */
4447 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
4449 register re_char
*d
;
4450 register re_wchar_t buf_ch
;
4452 d
= POS_ADDR_VSTRING (startpos
);
4454 if (range
> 0) /* Searching forwards. */
4456 register int lim
= 0;
4459 if (startpos
< size1
&& startpos
+ range
>= size1
)
4460 lim
= range
- (size1
- startpos
);
4462 /* Written out as an if-else to avoid testing `translate'
4464 if (RE_TRANSLATE_P (translate
))
4471 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4472 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
4473 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4476 range
-= buf_charlen
;
4482 register re_wchar_t ch
, translated
;
4485 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4486 translated
= RE_TRANSLATE (translate
, ch
);
4487 if (translated
!= ch
4488 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4490 if (fastmap
[buf_ch
])
4503 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
4504 if (fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4506 range
-= buf_charlen
;
4510 while (range
> lim
&& !fastmap
[*d
])
4516 startpos
+= irange
- range
;
4518 else /* Searching backwards. */
4522 buf_ch
= STRING_CHAR (d
);
4523 buf_ch
= TRANSLATE (buf_ch
);
4524 if (! fastmap
[CHAR_LEADING_CODE (buf_ch
)])
4529 register re_wchar_t ch
, translated
;
4532 ch
= RE_CHAR_TO_MULTIBYTE (buf_ch
);
4533 translated
= TRANSLATE (ch
);
4534 if (translated
!= ch
4535 && (ch
= RE_CHAR_TO_UNIBYTE (translated
)) >= 0)
4537 if (! fastmap
[TRANSLATE (buf_ch
)])
4543 /* If can't match the null string, and that's all we have left, fail. */
4544 if (range
>= 0 && startpos
== total_size
&& fastmap
4545 && !bufp
->can_be_null
)
4548 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4549 startpos
, regs
, stop
);
4562 /* Update STARTPOS to the next character boundary. */
4565 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4566 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
4567 int len
= BYTES_BY_CHAR_HEAD (*p
);
4585 /* Update STARTPOS to the previous character boundary. */
4588 re_char
*p
= POS_ADDR_VSTRING (startpos
) + 1;
4590 re_char
*phead
= HEAD_ADDR_VSTRING (startpos
);
4592 /* Find the head of multibyte form. */
4593 PREV_CHAR_BOUNDARY (p
, phead
);
4594 range
+= p0
- 1 - p
;
4598 startpos
-= p0
- 1 - p
;
4604 WEAK_ALIAS (__re_search_2
, re_search_2
)
4606 /* Declarations and macros for re_match_2. */
4608 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4610 RE_TRANSLATE_TYPE translate
,
4611 const int multibyte
));
4613 /* This converts PTR, a pointer into one of the search strings `string1'
4614 and `string2' into an offset from the beginning of that string. */
4615 #define POINTER_TO_OFFSET(ptr) \
4616 (FIRST_STRING_P (ptr) \
4617 ? ((regoff_t) ((ptr) - string1)) \
4618 : ((regoff_t) ((ptr) - string2 + size1)))
4620 /* Call before fetching a character with *d. This switches over to
4621 string2 if necessary.
4622 Check re_match_2_internal for a discussion of why end_match_2 might
4623 not be within string2 (but be equal to end_match_1 instead). */
4624 #define PREFETCH() \
4627 /* End of string2 => fail. */ \
4628 if (dend == end_match_2) \
4630 /* End of string1 => advance to string2. */ \
4632 dend = end_match_2; \
4635 /* Call before fetching a char with *d if you already checked other limits.
4636 This is meant for use in lookahead operations like wordend, etc..
4637 where we might need to look at parts of the string that might be
4638 outside of the LIMITs (i.e past `stop'). */
4639 #define PREFETCH_NOLIMIT() \
4643 dend = end_match_2; \
4646 /* Test if at very beginning or at very end of the virtual concatenation
4647 of `string1' and `string2'. If only one string, it's `string2'. */
4648 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4649 #define AT_STRINGS_END(d) ((d) == end2)
4652 /* Test if D points to a character which is word-constituent. We have
4653 two special cases to check for: if past the end of string1, look at
4654 the first character in string2; and if before the beginning of
4655 string2, look at the last character in string1. */
4656 #define WORDCHAR_P(d) \
4657 (SYNTAX ((d) == end1 ? *string2 \
4658 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4661 /* Disabled due to a compiler bug -- see comment at case wordbound */
4663 /* The comment at case wordbound is following one, but we don't use
4664 AT_WORD_BOUNDARY anymore to support multibyte form.
4666 The DEC Alpha C compiler 3.x generates incorrect code for the
4667 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4668 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4669 macro and introducing temporary variables works around the bug. */
4672 /* Test if the character before D and the one at D differ with respect
4673 to being word-constituent. */
4674 #define AT_WORD_BOUNDARY(d) \
4675 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4676 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4679 /* Free everything we malloc. */
4680 #ifdef MATCH_MAY_ALLOCATE
4681 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4682 # define FREE_VARIABLES() \
4684 REGEX_FREE_STACK (fail_stack.stack); \
4685 FREE_VAR (regstart); \
4686 FREE_VAR (regend); \
4687 FREE_VAR (best_regstart); \
4688 FREE_VAR (best_regend); \
4691 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4692 #endif /* not MATCH_MAY_ALLOCATE */
4695 /* Optimization routines. */
4697 /* If the operation is a match against one or more chars,
4698 return a pointer to the next operation, else return NULL. */
4700 skip_one_char (const re_char
*p
)
4702 switch (SWITCH_ENUM_CAST (*p
++))
4713 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4716 p
= CHARSET_RANGE_TABLE (p
- 1);
4717 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4718 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4721 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4728 case notcategoryspec
:
4740 /* Jump over non-matching operations. */
4742 skip_noops (const re_char
*p
, const re_char
*pend
)
4747 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4756 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4767 /* Non-zero if "p1 matches something" implies "p2 fails". */
4769 mutually_exclusive_p (struct re_pattern_buffer
*bufp
, const re_char
*p1
, const re_char
*p2
)
4772 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4773 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4775 assert (p1
>= bufp
->buffer
&& p1
< pend
4776 && p2
>= bufp
->buffer
&& p2
<= pend
);
4778 /* Skip over open/close-group commands.
4779 If what follows this loop is a ...+ construct,
4780 look at what begins its body, since we will have to
4781 match at least one of that. */
4782 p2
= skip_noops (p2
, pend
);
4783 /* The same skip can be done for p1, except that this function
4784 is only used in the case where p1 is a simple match operator. */
4785 /* p1 = skip_noops (p1, pend); */
4787 assert (p1
>= bufp
->buffer
&& p1
< pend
4788 && p2
>= bufp
->buffer
&& p2
<= pend
);
4790 op2
= p2
== pend
? succeed
: *p2
;
4792 switch (SWITCH_ENUM_CAST (op2
))
4796 /* If we're at the end of the pattern, we can change. */
4797 if (skip_one_char (p1
))
4799 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4807 register re_wchar_t c
4808 = (re_opcode_t
) *p2
== endline
? '\n'
4809 : RE_STRING_CHAR (p2
+ 2, multibyte
);
4811 if ((re_opcode_t
) *p1
== exactn
)
4813 if (c
!= RE_STRING_CHAR (p1
+ 2, multibyte
))
4815 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4820 else if ((re_opcode_t
) *p1
== charset
4821 || (re_opcode_t
) *p1
== charset_not
)
4823 int not = (re_opcode_t
) *p1
== charset_not
;
4825 /* Test if C is listed in charset (or charset_not)
4827 if (! multibyte
|| IS_REAL_ASCII (c
))
4829 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4830 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4833 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4834 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4836 /* `not' is equal to 1 if c would match, which means
4837 that we can't change to pop_failure_jump. */
4840 DEBUG_PRINT1 (" No match => fast loop.\n");
4844 else if ((re_opcode_t
) *p1
== anychar
4847 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4855 if ((re_opcode_t
) *p1
== exactn
)
4856 /* Reuse the code above. */
4857 return mutually_exclusive_p (bufp
, p2
, p1
);
4859 /* It is hard to list up all the character in charset
4860 P2 if it includes multibyte character. Give up in
4862 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4864 /* Now, we are sure that P2 has no range table.
4865 So, for the size of bitmap in P2, `p2[1]' is
4866 enough. But P1 may have range table, so the
4867 size of bitmap table of P1 is extracted by
4868 using macro `CHARSET_BITMAP_SIZE'.
4870 In a multibyte case, we know that all the character
4871 listed in P2 is ASCII. In a unibyte case, P1 has only a
4872 bitmap table. So, in both cases, it is enough to test
4873 only the bitmap table of P1. */
4875 if ((re_opcode_t
) *p1
== charset
)
4878 /* We win if the charset inside the loop
4879 has no overlap with the one after the loop. */
4882 && idx
< CHARSET_BITMAP_SIZE (p1
));
4884 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4888 || idx
== CHARSET_BITMAP_SIZE (p1
))
4890 DEBUG_PRINT1 (" No match => fast loop.\n");
4894 else if ((re_opcode_t
) *p1
== charset_not
)
4897 /* We win if the charset_not inside the loop lists
4898 every character listed in the charset after. */
4899 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4900 if (! (p2
[2 + idx
] == 0
4901 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4902 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4907 DEBUG_PRINT1 (" No match => fast loop.\n");
4916 switch (SWITCH_ENUM_CAST (*p1
))
4920 /* Reuse the code above. */
4921 return mutually_exclusive_p (bufp
, p2
, p1
);
4923 /* When we have two charset_not, it's very unlikely that
4924 they don't overlap. The union of the two sets of excluded
4925 chars should cover all possible chars, which, as a matter of
4926 fact, is virtually impossible in multibyte buffers. */
4932 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == Sword
);
4934 return ((re_opcode_t
) *p1
== syntaxspec
4935 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4937 return ((re_opcode_t
) *p1
== syntaxspec
&& p1
[1] == p2
[1]);
4940 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == Sword
);
4942 return ((re_opcode_t
) *p1
== notsyntaxspec
4943 && (p1
[1] == Ssymbol
|| p1
[1] == Sword
));
4945 return ((re_opcode_t
) *p1
== notsyntaxspec
&& p1
[1] == p2
[1]);
4948 return (((re_opcode_t
) *p1
== notsyntaxspec
4949 || (re_opcode_t
) *p1
== syntaxspec
)
4954 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4955 case notcategoryspec
:
4956 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4968 /* Matching routines. */
4970 #ifndef emacs /* Emacs never uses this. */
4971 /* re_match is like re_match_2 except it takes only a single string. */
4974 re_match (struct re_pattern_buffer
*bufp
, const char *string
,
4975 int size
, int pos
, struct re_registers
*regs
)
4977 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
4981 WEAK_ALIAS (__re_match
, re_match
)
4982 #endif /* not emacs */
4985 /* In Emacs, this is the string or buffer in which we
4986 are matching. It is used for looking up syntax properties. */
4987 Lisp_Object re_match_object
;
4990 /* re_match_2 matches the compiled pattern in BUFP against the
4991 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4992 and SIZE2, respectively). We start matching at POS, and stop
4995 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4996 store offsets for the substring each group matched in REGS. See the
4997 documentation for exactly how many groups we fill.
4999 We return -1 if no match, -2 if an internal error (such as the
5000 failure stack overflowing). Otherwise, we return the length of the
5001 matched substring. */
5004 re_match_2 (struct re_pattern_buffer
*bufp
, const char *string1
, int size1
, const char *string2
, int size2
, int pos
, struct re_registers
*regs
, int stop
)
5010 gl_state
.object
= re_match_object
; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
5011 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
5012 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
5015 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
5016 (re_char
*) string2
, size2
,
5020 WEAK_ALIAS (__re_match_2
, re_match_2
)
5023 /* This is a separate function so that we can force an alloca cleanup
5026 re_match_2_internal (struct re_pattern_buffer
*bufp
, const re_char
*string1
, int size1
, const re_char
*string2
, int size2
, int pos
, struct re_registers
*regs
, int stop
)
5028 /* General temporaries. */
5033 /* Just past the end of the corresponding string. */
5034 re_char
*end1
, *end2
;
5036 /* Pointers into string1 and string2, just past the last characters in
5037 each to consider matching. */
5038 re_char
*end_match_1
, *end_match_2
;
5040 /* Where we are in the data, and the end of the current string. */
5043 /* Used sometimes to remember where we were before starting matching
5044 an operator so that we can go back in case of failure. This "atomic"
5045 behavior of matching opcodes is indispensable to the correctness
5046 of the on_failure_keep_string_jump optimization. */
5049 /* Where we are in the pattern, and the end of the pattern. */
5050 re_char
*p
= bufp
->buffer
;
5051 re_char
*pend
= p
+ bufp
->used
;
5053 /* We use this to map every character in the string. */
5054 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
5056 /* Nonzero if BUFP is setup from a multibyte regex. */
5057 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
5059 /* Nonzero if STRING1/STRING2 are multibyte. */
5060 const boolean target_multibyte
= RE_TARGET_MULTIBYTE_P (bufp
);
5062 /* Failure point stack. Each place that can handle a failure further
5063 down the line pushes a failure point on this stack. It consists of
5064 regstart, and regend for all registers corresponding to
5065 the subexpressions we're currently inside, plus the number of such
5066 registers, and, finally, two char *'s. The first char * is where
5067 to resume scanning the pattern; the second one is where to resume
5068 scanning the strings. */
5069 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5070 fail_stack_type fail_stack
;
5073 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
5076 #if defined REL_ALLOC && defined REGEX_MALLOC
5077 /* This holds the pointer to the failure stack, when
5078 it is allocated relocatably. */
5079 fail_stack_elt_t
*failure_stack_ptr
;
5082 /* We fill all the registers internally, independent of what we
5083 return, for use in backreferences. The number here includes
5084 an element for register zero. */
5085 size_t num_regs
= bufp
->re_nsub
+ 1;
5087 /* Information on the contents of registers. These are pointers into
5088 the input strings; they record just what was matched (on this
5089 attempt) by a subexpression part of the pattern, that is, the
5090 regnum-th regstart pointer points to where in the pattern we began
5091 matching and the regnum-th regend points to right after where we
5092 stopped matching the regnum-th subexpression. (The zeroth register
5093 keeps track of what the whole pattern matches.) */
5094 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5095 re_char
**regstart
, **regend
;
5098 /* The following record the register info as found in the above
5099 variables when we find a match better than any we've seen before.
5100 This happens as we backtrack through the failure points, which in
5101 turn happens only if we have not yet matched the entire string. */
5102 unsigned best_regs_set
= false;
5103 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5104 re_char
**best_regstart
, **best_regend
;
5107 /* Logically, this is `best_regend[0]'. But we don't want to have to
5108 allocate space for that if we're not allocating space for anything
5109 else (see below). Also, we never need info about register 0 for
5110 any of the other register vectors, and it seems rather a kludge to
5111 treat `best_regend' differently than the rest. So we keep track of
5112 the end of the best match so far in a separate variable. We
5113 initialize this to NULL so that when we backtrack the first time
5114 and need to test it, it's not garbage. */
5115 re_char
*match_end
= NULL
;
5118 /* Counts the total number of registers pushed. */
5119 unsigned num_regs_pushed
= 0;
5122 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5126 #ifdef MATCH_MAY_ALLOCATE
5127 /* Do not bother to initialize all the register variables if there are
5128 no groups in the pattern, as it takes a fair amount of time. If
5129 there are groups, we include space for register 0 (the whole
5130 pattern), even though we never use it, since it simplifies the
5131 array indexing. We should fix this. */
5134 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5135 regend
= REGEX_TALLOC (num_regs
, re_char
*);
5136 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
5137 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
5139 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
5147 /* We must initialize all our variables to NULL, so that
5148 `FREE_VARIABLES' doesn't try to free them. */
5149 regstart
= regend
= best_regstart
= best_regend
= NULL
;
5151 #endif /* MATCH_MAY_ALLOCATE */
5153 /* The starting position is bogus. */
5154 if (pos
< 0 || pos
> size1
+ size2
)
5160 /* Initialize subexpression text positions to -1 to mark ones that no
5161 start_memory/stop_memory has been seen for. Also initialize the
5162 register information struct. */
5163 for (reg
= 1; reg
< num_regs
; reg
++)
5164 regstart
[reg
] = regend
[reg
] = NULL
;
5166 /* We move `string1' into `string2' if the latter's empty -- but not if
5167 `string1' is null. */
5168 if (size2
== 0 && string1
!= NULL
)
5175 end1
= string1
+ size1
;
5176 end2
= string2
+ size2
;
5178 /* `p' scans through the pattern as `d' scans through the data.
5179 `dend' is the end of the input string that `d' points within. `d'
5180 is advanced into the following input string whenever necessary, but
5181 this happens before fetching; therefore, at the beginning of the
5182 loop, `d' can be pointing at the end of a string, but it cannot
5186 /* Only match within string2. */
5187 d
= string2
+ pos
- size1
;
5188 dend
= end_match_2
= string2
+ stop
- size1
;
5189 end_match_1
= end1
; /* Just to give it a value. */
5195 /* Only match within string1. */
5196 end_match_1
= string1
+ stop
;
5198 When we reach end_match_1, PREFETCH normally switches to string2.
5199 But in the present case, this means that just doing a PREFETCH
5200 makes us jump from `stop' to `gap' within the string.
5201 What we really want here is for the search to stop as
5202 soon as we hit end_match_1. That's why we set end_match_2
5203 to end_match_1 (since PREFETCH fails as soon as we hit
5205 end_match_2
= end_match_1
;
5208 { /* It's important to use this code when stop == size so that
5209 moving `d' from end1 to string2 will not prevent the d == dend
5210 check from catching the end of string. */
5212 end_match_2
= string2
+ stop
- size1
;
5218 DEBUG_PRINT1 ("The compiled pattern is: ");
5219 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
5220 DEBUG_PRINT1 ("The string to match is: `");
5221 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
5222 DEBUG_PRINT1 ("'\n");
5224 /* This loops over pattern commands. It exits by returning from the
5225 function if the match is complete, or it drops through if the match
5226 fails at this starting point in the input data. */
5229 DEBUG_PRINT2 ("\n%p: ", p
);
5232 { /* End of pattern means we might have succeeded. */
5233 DEBUG_PRINT1 ("end of pattern ... ");
5235 /* If we haven't matched the entire string, and we want the
5236 longest match, try backtracking. */
5237 if (d
!= end_match_2
)
5239 /* 1 if this match ends in the same string (string1 or string2)
5240 as the best previous match. */
5241 boolean same_str_p
= (FIRST_STRING_P (match_end
)
5242 == FIRST_STRING_P (d
));
5243 /* 1 if this match is the best seen so far. */
5244 boolean best_match_p
;
5246 /* AIX compiler got confused when this was combined
5247 with the previous declaration. */
5249 best_match_p
= d
> match_end
;
5251 best_match_p
= !FIRST_STRING_P (d
);
5253 DEBUG_PRINT1 ("backtracking.\n");
5255 if (!FAIL_STACK_EMPTY ())
5256 { /* More failure points to try. */
5258 /* If exceeds best match so far, save it. */
5259 if (!best_regs_set
|| best_match_p
)
5261 best_regs_set
= true;
5264 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5266 for (reg
= 1; reg
< num_regs
; reg
++)
5268 best_regstart
[reg
] = regstart
[reg
];
5269 best_regend
[reg
] = regend
[reg
];
5275 /* If no failure points, don't restore garbage. And if
5276 last match is real best match, don't restore second
5278 else if (best_regs_set
&& !best_match_p
)
5281 /* Restore best match. It may happen that `dend ==
5282 end_match_1' while the restored d is in string2.
5283 For example, the pattern `x.*y.*z' against the
5284 strings `x-' and `y-z-', if the two strings are
5285 not consecutive in memory. */
5286 DEBUG_PRINT1 ("Restoring best registers.\n");
5289 dend
= ((d
>= string1
&& d
<= end1
)
5290 ? end_match_1
: end_match_2
);
5292 for (reg
= 1; reg
< num_regs
; reg
++)
5294 regstart
[reg
] = best_regstart
[reg
];
5295 regend
[reg
] = best_regend
[reg
];
5298 } /* d != end_match_2 */
5301 DEBUG_PRINT1 ("Accepting match.\n");
5303 /* If caller wants register contents data back, do it. */
5304 if (regs
&& !bufp
->no_sub
)
5306 /* Have the register data arrays been allocated? */
5307 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
5308 { /* No. So allocate them with malloc. We need one
5309 extra element beyond `num_regs' for the `-1' marker
5311 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
5312 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
5313 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
5314 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5319 bufp
->regs_allocated
= REGS_REALLOCATE
;
5321 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
5322 { /* Yes. If we need more elements than were already
5323 allocated, reallocate them. If we need fewer, just
5325 if (regs
->num_regs
< num_regs
+ 1)
5327 regs
->num_regs
= num_regs
+ 1;
5328 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
5329 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
5330 if (regs
->start
== NULL
|| regs
->end
== NULL
)
5339 /* These braces fend off a "empty body in an else-statement"
5340 warning under GCC when assert expands to nothing. */
5341 assert (bufp
->regs_allocated
== REGS_FIXED
);
5344 /* Convert the pointer data in `regstart' and `regend' to
5345 indices. Register zero has to be set differently,
5346 since we haven't kept track of any info for it. */
5347 if (regs
->num_regs
> 0)
5349 regs
->start
[0] = pos
;
5350 regs
->end
[0] = POINTER_TO_OFFSET (d
);
5353 /* Go through the first `min (num_regs, regs->num_regs)'
5354 registers, since that is all we initialized. */
5355 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
5357 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
5358 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5362 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
5364 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
5368 /* If the regs structure we return has more elements than
5369 were in the pattern, set the extra elements to -1. If
5370 we (re)allocated the registers, this is the case,
5371 because we always allocate enough to have at least one
5373 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
5374 regs
->start
[reg
] = regs
->end
[reg
] = -1;
5375 } /* regs && !bufp->no_sub */
5377 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5378 nfailure_points_pushed
, nfailure_points_popped
,
5379 nfailure_points_pushed
- nfailure_points_popped
);
5380 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
5382 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
5384 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
5390 /* Otherwise match next pattern command. */
5391 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
5393 /* Ignore these. Used to ignore the n of succeed_n's which
5394 currently have n == 0. */
5396 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5400 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5403 /* Match the next n pattern characters exactly. The following
5404 byte in the pattern defines n, and the n bytes after that
5405 are the characters to match. */
5408 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
5410 /* Remember the start point to rollback upon failure. */
5414 /* This is written out as an if-else so we don't waste time
5415 testing `translate' inside the loop. */
5416 if (RE_TRANSLATE_P (translate
))
5420 if (RE_TRANSLATE (translate
, *d
) != *p
++)
5440 /* The cost of testing `translate' is comparatively small. */
5441 if (target_multibyte
)
5444 int pat_charlen
, buf_charlen
;
5449 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5452 pat_ch
= RE_CHAR_TO_MULTIBYTE (*p
);
5455 buf_ch
= STRING_CHAR_AND_LENGTH (d
, buf_charlen
);
5457 if (TRANSLATE (buf_ch
) != pat_ch
)
5465 mcnt
-= pat_charlen
;
5471 int pat_charlen
, buf_charlen
;
5477 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pat_charlen
);
5478 pat_ch
= RE_CHAR_TO_UNIBYTE (pat_ch
);
5485 buf_ch
= RE_CHAR_TO_MULTIBYTE (*d
);
5486 if (! CHAR_BYTE8_P (buf_ch
))
5488 buf_ch
= TRANSLATE (buf_ch
);
5489 buf_ch
= RE_CHAR_TO_UNIBYTE (buf_ch
);
5495 if (buf_ch
!= pat_ch
)
5508 /* Match any character except possibly a newline or a null. */
5514 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5517 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, buf_charlen
,
5519 buf_ch
= TRANSLATE (buf_ch
);
5521 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
5523 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
5524 && buf_ch
== '\000'))
5527 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
5536 register unsigned int c
;
5537 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
5540 /* Start of actual range_table, or end of bitmap if there is no
5542 re_char
*range_table
;
5544 /* Nonzero if there is a range table. */
5545 int range_table_exists
;
5547 /* Number of ranges of range table. This is not included
5548 in the initial byte-length of the command. */
5551 /* Whether matching against a unibyte character. */
5552 boolean unibyte_char
= false;
5554 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5556 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
5558 if (range_table_exists
)
5560 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5561 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5565 c
= RE_STRING_CHAR_AND_LENGTH (d
, len
, target_multibyte
);
5566 if (target_multibyte
)
5571 c1
= RE_CHAR_TO_UNIBYTE (c
);
5574 unibyte_char
= true;
5580 int c1
= RE_CHAR_TO_MULTIBYTE (c
);
5582 if (! CHAR_BYTE8_P (c1
))
5584 c1
= TRANSLATE (c1
);
5585 c1
= RE_CHAR_TO_UNIBYTE (c1
);
5588 unibyte_char
= true;
5593 unibyte_char
= true;
5596 if (unibyte_char
&& c
< (1 << BYTEWIDTH
))
5597 { /* Lookup bitmap. */
5598 /* Cast to `unsigned' instead of `unsigned char' in
5599 case the bit list is a full 32 bytes long. */
5600 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5601 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5605 else if (range_table_exists
)
5607 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5609 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5610 | (class_bits
& BIT_MULTIBYTE
)
5611 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5612 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5613 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5614 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5617 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5621 if (range_table_exists
)
5622 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5624 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5626 if (!not) goto fail
;
5633 /* The beginning of a group is represented by start_memory.
5634 The argument is the register number. The text
5635 matched within the group is recorded (in the internal
5636 registers data structure) under the register number. */
5638 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5640 /* In case we need to undo this operation (via backtracking). */
5641 PUSH_FAILURE_REG ((unsigned int)*p
);
5644 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5645 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5647 /* Move past the register number and inner group count. */
5652 /* The stop_memory opcode represents the end of a group. Its
5653 argument is the same as start_memory's: the register number. */
5655 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5657 assert (!REG_UNSET (regstart
[*p
]));
5658 /* Strictly speaking, there should be code such as:
5660 assert (REG_UNSET (regend[*p]));
5661 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5663 But the only info to be pushed is regend[*p] and it is known to
5664 be UNSET, so there really isn't anything to push.
5665 Not pushing anything, on the other hand deprives us from the
5666 guarantee that regend[*p] is UNSET since undoing this operation
5667 will not reset its value properly. This is not important since
5668 the value will only be read on the next start_memory or at
5669 the very end and both events can only happen if this stop_memory
5673 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5675 /* Move past the register number and the inner group count. */
5680 /* \<digit> has been turned into a `duplicate' command which is
5681 followed by the numeric value of <digit> as the register number. */
5684 register re_char
*d2
, *dend2
;
5685 int regno
= *p
++; /* Get which register to match against. */
5686 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5688 /* Can't back reference a group which we've never matched. */
5689 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5692 /* Where in input to try to start matching. */
5693 d2
= regstart
[regno
];
5695 /* Remember the start point to rollback upon failure. */
5698 /* Where to stop matching; if both the place to start and
5699 the place to stop matching are in the same string, then
5700 set to the place to stop, otherwise, for now have to use
5701 the end of the first string. */
5703 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5704 == FIRST_STRING_P (regend
[regno
]))
5705 ? regend
[regno
] : end_match_1
);
5708 /* If necessary, advance to next segment in register
5712 if (dend2
== end_match_2
) break;
5713 if (dend2
== regend
[regno
]) break;
5715 /* End of string1 => advance to string2. */
5717 dend2
= regend
[regno
];
5719 /* At end of register contents => success */
5720 if (d2
== dend2
) break;
5722 /* If necessary, advance to next segment in data. */
5725 /* How many characters left in this segment to match. */
5728 /* Want how many consecutive characters we can match in
5729 one shot, so, if necessary, adjust the count. */
5730 if (mcnt
> dend2
- d2
)
5733 /* Compare that many; failure if mismatch, else move
5735 if (RE_TRANSLATE_P (translate
)
5736 ? bcmp_translate (d
, d2
, mcnt
, translate
, target_multibyte
)
5737 : memcmp (d
, d2
, mcnt
))
5742 d
+= mcnt
, d2
+= mcnt
;
5748 /* begline matches the empty string at the beginning of the string
5749 (unless `not_bol' is set in `bufp'), and after newlines. */
5751 DEBUG_PRINT1 ("EXECUTING begline.\n");
5753 if (AT_STRINGS_BEG (d
))
5755 if (!bufp
->not_bol
) break;
5760 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5764 /* In all other cases, we fail. */
5768 /* endline is the dual of begline. */
5770 DEBUG_PRINT1 ("EXECUTING endline.\n");
5772 if (AT_STRINGS_END (d
))
5774 if (!bufp
->not_eol
) break;
5778 PREFETCH_NOLIMIT ();
5785 /* Match at the very beginning of the data. */
5787 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5788 if (AT_STRINGS_BEG (d
))
5793 /* Match at the very end of the data. */
5795 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5796 if (AT_STRINGS_END (d
))
5801 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5802 pushes NULL as the value for the string on the stack. Then
5803 `POP_FAILURE_POINT' will keep the current value for the
5804 string, instead of restoring it. To see why, consider
5805 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5806 then the . fails against the \n. But the next thing we want
5807 to do is match the \n against the \n; if we restored the
5808 string value, we would be back at the foo.
5810 Because this is used only in specific cases, we don't need to
5811 check all the things that `on_failure_jump' does, to make
5812 sure the right things get saved on the stack. Hence we don't
5813 share its code. The only reason to push anything on the
5814 stack at all is that otherwise we would have to change
5815 `anychar's code to do something besides goto fail in this
5816 case; that seems worse than this. */
5817 case on_failure_keep_string_jump
:
5818 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5819 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5822 PUSH_FAILURE_POINT (p
- 3, NULL
);
5825 /* A nasty loop is introduced by the non-greedy *? and +?.
5826 With such loops, the stack only ever contains one failure point
5827 at a time, so that a plain on_failure_jump_loop kind of
5828 cycle detection cannot work. Worse yet, such a detection
5829 can not only fail to detect a cycle, but it can also wrongly
5830 detect a cycle (between different instantiations of the same
5832 So the method used for those nasty loops is a little different:
5833 We use a special cycle-detection-stack-frame which is pushed
5834 when the on_failure_jump_nastyloop failure-point is *popped*.
5835 This special frame thus marks the beginning of one iteration
5836 through the loop and we can hence easily check right here
5837 whether something matched between the beginning and the end of
5839 case on_failure_jump_nastyloop
:
5840 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5841 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5844 assert ((re_opcode_t
)p
[-4] == no_op
);
5847 CHECK_INFINITE_LOOP (p
- 4, d
);
5849 /* If there's a cycle, just continue without pushing
5850 this failure point. The failure point is the "try again"
5851 option, which shouldn't be tried.
5852 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5853 PUSH_FAILURE_POINT (p
- 3, d
);
5857 /* Simple loop detecting on_failure_jump: just check on the
5858 failure stack if the same spot was already hit earlier. */
5859 case on_failure_jump_loop
:
5861 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5862 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5866 CHECK_INFINITE_LOOP (p
- 3, d
);
5868 /* If there's a cycle, get out of the loop, as if the matching
5869 had failed. We used to just `goto fail' here, but that was
5870 aborting the search a bit too early: we want to keep the
5871 empty-loop-match and keep matching after the loop.
5872 We want (x?)*y\1z to match both xxyz and xxyxz. */
5875 PUSH_FAILURE_POINT (p
- 3, d
);
5880 /* Uses of on_failure_jump:
5882 Each alternative starts with an on_failure_jump that points
5883 to the beginning of the next alternative. Each alternative
5884 except the last ends with a jump that in effect jumps past
5885 the rest of the alternatives. (They really jump to the
5886 ending jump of the following alternative, because tensioning
5887 these jumps is a hassle.)
5889 Repeats start with an on_failure_jump that points past both
5890 the repetition text and either the following jump or
5891 pop_failure_jump back to this on_failure_jump. */
5892 case on_failure_jump
:
5893 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5894 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5897 PUSH_FAILURE_POINT (p
-3, d
);
5900 /* This operation is used for greedy *.
5901 Compare the beginning of the repeat with what in the
5902 pattern follows its end. If we can establish that there
5903 is nothing that they would both match, i.e., that we
5904 would have to backtrack because of (as in, e.g., `a*a')
5905 then we can use a non-backtracking loop based on
5906 on_failure_keep_string_jump instead of on_failure_jump. */
5907 case on_failure_jump_smart
:
5908 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5909 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5912 re_char
*p1
= p
; /* Next operation. */
5913 /* Here, we discard `const', making re_match non-reentrant. */
5914 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5915 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5917 p
-= 3; /* Reset so that we will re-execute the
5918 instruction once it's been changed. */
5920 EXTRACT_NUMBER (mcnt
, p2
- 2);
5922 /* Ensure this is a indeed the trivial kind of loop
5923 we are expecting. */
5924 assert (skip_one_char (p1
) == p2
- 3);
5925 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5926 DEBUG_STATEMENT (debug
+= 2);
5927 if (mutually_exclusive_p (bufp
, p1
, p2
))
5929 /* Use a fast `on_failure_keep_string_jump' loop. */
5930 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5931 *p3
= (unsigned char) on_failure_keep_string_jump
;
5932 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5936 /* Default to a safe `on_failure_jump' loop. */
5937 DEBUG_PRINT1 (" smart default => slow loop.\n");
5938 *p3
= (unsigned char) on_failure_jump
;
5940 DEBUG_STATEMENT (debug
-= 2);
5944 /* Unconditionally jump (without popping any failure points). */
5947 IMMEDIATE_QUIT_CHECK
;
5948 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5949 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5950 p
+= mcnt
; /* Do the jump. */
5951 DEBUG_PRINT2 ("(to %p).\n", p
);
5955 /* Have to succeed matching what follows at least n times.
5956 After that, handle like `on_failure_jump'. */
5958 /* Signedness doesn't matter since we only compare MCNT to 0. */
5959 EXTRACT_NUMBER (mcnt
, p
+ 2);
5960 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5962 /* Originally, mcnt is how many times we HAVE to succeed. */
5965 /* Here, we discard `const', making re_match non-reentrant. */
5966 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5969 PUSH_NUMBER (p2
, mcnt
);
5972 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5977 /* Signedness doesn't matter since we only compare MCNT to 0. */
5978 EXTRACT_NUMBER (mcnt
, p
+ 2);
5979 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5981 /* Originally, this is how many times we CAN jump. */
5984 /* Here, we discard `const', making re_match non-reentrant. */
5985 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5987 PUSH_NUMBER (p2
, mcnt
);
5988 goto unconditional_jump
;
5990 /* If don't have to jump any more, skip over the rest of command. */
5997 unsigned char *p2
; /* Location of the counter. */
5998 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
6000 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
6001 /* Here, we discard `const', making re_match non-reentrant. */
6002 p2
= (unsigned char*) p
+ mcnt
;
6003 /* Signedness doesn't matter since we only copy MCNT's bits . */
6004 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
6005 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
6006 PUSH_NUMBER (p2
, mcnt
);
6012 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
6013 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
6015 /* We SUCCEED (or FAIL) in one of the following cases: */
6017 /* Case 1: D is at the beginning or the end of string. */
6018 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
6022 /* C1 is the character before D, S1 is the syntax of C1, C2
6023 is the character at D, and S2 is the syntax of C2. */
6028 int offset
= PTR_TO_OFFSET (d
- 1);
6029 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6030 UPDATE_SYNTAX_TABLE (charpos
);
6032 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6035 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6037 PREFETCH_NOLIMIT ();
6038 GET_CHAR_AFTER (c2
, d
, dummy
);
6041 if (/* Case 2: Only one of S1 and S2 is Sword. */
6042 ((s1
== Sword
) != (s2
== Sword
))
6043 /* Case 3: Both of S1 and S2 are Sword, and macro
6044 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
6045 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
6054 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
6056 /* We FAIL in one of the following cases: */
6058 /* Case 1: D is at the end of string. */
6059 if (AT_STRINGS_END (d
))
6063 /* C1 is the character before D, S1 is the syntax of C1, C2
6064 is the character at D, and S2 is the syntax of C2. */
6069 int offset
= PTR_TO_OFFSET (d
);
6070 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6071 UPDATE_SYNTAX_TABLE (charpos
);
6074 GET_CHAR_AFTER (c2
, d
, dummy
);
6077 /* Case 2: S2 is not Sword. */
6081 /* Case 3: D is not at the beginning of string ... */
6082 if (!AT_STRINGS_BEG (d
))
6084 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6086 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6090 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6092 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6099 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6101 /* We FAIL in one of the following cases: */
6103 /* Case 1: D is at the beginning of string. */
6104 if (AT_STRINGS_BEG (d
))
6108 /* C1 is the character before D, S1 is the syntax of C1, C2
6109 is the character at D, and S2 is the syntax of C2. */
6114 int offset
= PTR_TO_OFFSET (d
) - 1;
6115 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6116 UPDATE_SYNTAX_TABLE (charpos
);
6118 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6121 /* Case 2: S1 is not Sword. */
6125 /* Case 3: D is not at the end of string ... */
6126 if (!AT_STRINGS_END (d
))
6128 PREFETCH_NOLIMIT ();
6129 GET_CHAR_AFTER (c2
, d
, dummy
);
6131 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
6135 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6137 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
6144 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6146 /* We FAIL in one of the following cases: */
6148 /* Case 1: D is at the end of string. */
6149 if (AT_STRINGS_END (d
))
6153 /* C1 is the character before D, S1 is the syntax of C1, C2
6154 is the character at D, and S2 is the syntax of C2. */
6158 int offset
= PTR_TO_OFFSET (d
);
6159 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6160 UPDATE_SYNTAX_TABLE (charpos
);
6163 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6166 /* Case 2: S2 is neither Sword nor Ssymbol. */
6167 if (s2
!= Sword
&& s2
!= Ssymbol
)
6170 /* Case 3: D is not at the beginning of string ... */
6171 if (!AT_STRINGS_BEG (d
))
6173 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6175 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
6179 /* ... and S1 is Sword or Ssymbol. */
6180 if (s1
== Sword
|| s1
== Ssymbol
)
6187 DEBUG_PRINT1 ("EXECUTING symend.\n");
6189 /* We FAIL in one of the following cases: */
6191 /* Case 1: D is at the beginning of string. */
6192 if (AT_STRINGS_BEG (d
))
6196 /* C1 is the character before D, S1 is the syntax of C1, C2
6197 is the character at D, and S2 is the syntax of C2. */
6201 int offset
= PTR_TO_OFFSET (d
) - 1;
6202 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6203 UPDATE_SYNTAX_TABLE (charpos
);
6205 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
6208 /* Case 2: S1 is neither Ssymbol nor Sword. */
6209 if (s1
!= Sword
&& s1
!= Ssymbol
)
6212 /* Case 3: D is not at the end of string ... */
6213 if (!AT_STRINGS_END (d
))
6215 PREFETCH_NOLIMIT ();
6216 c2
= RE_STRING_CHAR (d
, target_multibyte
);
6218 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
6222 /* ... and S2 is Sword or Ssymbol. */
6223 if (s2
== Sword
|| s2
== Ssymbol
)
6231 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
6233 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
6237 int offset
= PTR_TO_OFFSET (d
);
6238 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
6239 UPDATE_SYNTAX_TABLE (pos1
);
6246 GET_CHAR_AFTER (c
, d
, len
);
6247 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
6255 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6256 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
6261 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6262 if (PTR_BYTE_POS (d
) != PT_BYTE
)
6267 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6268 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
6273 case notcategoryspec
:
6274 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
6276 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
6282 GET_CHAR_AFTER (c
, d
, len
);
6283 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
6294 continue; /* Successfully executed one pattern command; keep going. */
6297 /* We goto here if a matching operation fails. */
6299 IMMEDIATE_QUIT_CHECK
;
6300 if (!FAIL_STACK_EMPTY ())
6303 /* A restart point is known. Restore to that state. */
6304 DEBUG_PRINT1 ("\nFAIL:\n");
6305 POP_FAILURE_POINT (str
, pat
);
6306 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
6308 case on_failure_keep_string_jump
:
6309 assert (str
== NULL
);
6310 goto continue_failure_jump
;
6312 case on_failure_jump_nastyloop
:
6313 assert ((re_opcode_t
)pat
[-2] == no_op
);
6314 PUSH_FAILURE_POINT (pat
- 2, str
);
6317 case on_failure_jump_loop
:
6318 case on_failure_jump
:
6321 continue_failure_jump
:
6322 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
6327 /* A special frame used for nastyloops. */
6334 assert (p
>= bufp
->buffer
&& p
<= pend
);
6336 if (d
>= string1
&& d
<= end1
)
6340 break; /* Matching at this starting point really fails. */
6344 goto restore_best_regs
;
6348 return -1; /* Failure to match. */
6351 /* Subroutine definitions for re_match_2. */
6353 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6354 bytes; nonzero otherwise. */
6357 bcmp_translate (const re_char
*s1
, const re_char
*s2
, register int len
,
6358 RE_TRANSLATE_TYPE translate
, const int target_multibyte
)
6360 register re_char
*p1
= s1
, *p2
= s2
;
6361 re_char
*p1_end
= s1
+ len
;
6362 re_char
*p2_end
= s2
+ len
;
6364 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6365 different lengths, but relying on a single `len' would break this. -sm */
6366 while (p1
< p1_end
&& p2
< p2_end
)
6368 int p1_charlen
, p2_charlen
;
6369 re_wchar_t p1_ch
, p2_ch
;
6371 GET_CHAR_AFTER (p1_ch
, p1
, p1_charlen
);
6372 GET_CHAR_AFTER (p2_ch
, p2
, p2_charlen
);
6374 if (RE_TRANSLATE (translate
, p1_ch
)
6375 != RE_TRANSLATE (translate
, p2_ch
))
6378 p1
+= p1_charlen
, p2
+= p2_charlen
;
6381 if (p1
!= p1_end
|| p2
!= p2_end
)
6387 /* Entry points for GNU code. */
6389 /* re_compile_pattern is the GNU regular expression compiler: it
6390 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6391 Returns 0 if the pattern was valid, otherwise an error string.
6393 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6394 are set in BUFP on entry.
6396 We call regex_compile to do the actual compilation. */
6399 re_compile_pattern (const char *pattern
, size_t length
, struct re_pattern_buffer
*bufp
)
6403 /* GNU code is written to assume at least RE_NREGS registers will be set
6404 (and at least one extra will be -1). */
6405 bufp
->regs_allocated
= REGS_UNALLOCATED
;
6407 /* And GNU code determines whether or not to get register information
6408 by passing null for the REGS argument to re_match, etc., not by
6412 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
6416 return gettext (re_error_msgid
[(int) ret
]);
6418 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
6420 /* Entry points compatible with 4.2 BSD regex library. We don't define
6421 them unless specifically requested. */
6423 #if defined _REGEX_RE_COMP || defined _LIBC
6425 /* BSD has one and only one pattern buffer. */
6426 static struct re_pattern_buffer re_comp_buf
;
6430 /* Make these definitions weak in libc, so POSIX programs can redefine
6431 these names if they don't use our functions, and still use
6432 regcomp/regexec below without link errors. */
6442 if (!re_comp_buf
.buffer
)
6443 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6444 return (char *) gettext ("No previous regular expression");
6448 if (!re_comp_buf
.buffer
)
6450 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
6451 if (re_comp_buf
.buffer
== NULL
)
6452 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6453 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6454 re_comp_buf
.allocated
= 200;
6456 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6457 if (re_comp_buf
.fastmap
== NULL
)
6458 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6459 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
6462 /* Since `re_exec' always passes NULL for the `regs' argument, we
6463 don't need to initialize the pattern buffer fields which affect it. */
6465 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
6470 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6471 return (char *) gettext (re_error_msgid
[(int) ret
]);
6482 const int len
= strlen (s
);
6484 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
6486 #endif /* _REGEX_RE_COMP */
6488 /* POSIX.2 functions. Don't define these for Emacs. */
6492 /* regcomp takes a regular expression as a string and compiles it.
6494 PREG is a regex_t *. We do not expect any fields to be initialized,
6495 since POSIX says we shouldn't. Thus, we set
6497 `buffer' to the compiled pattern;
6498 `used' to the length of the compiled pattern;
6499 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6500 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6501 RE_SYNTAX_POSIX_BASIC;
6502 `fastmap' to an allocated space for the fastmap;
6503 `fastmap_accurate' to zero;
6504 `re_nsub' to the number of subexpressions in PATTERN.
6506 PATTERN is the address of the pattern string.
6508 CFLAGS is a series of bits which affect compilation.
6510 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6511 use POSIX basic syntax.
6513 If REG_NEWLINE is set, then . and [^...] don't match newline.
6514 Also, regexec will try a match beginning after every newline.
6516 If REG_ICASE is set, then we considers upper- and lowercase
6517 versions of letters to be equivalent when matching.
6519 If REG_NOSUB is set, then when PREG is passed to regexec, that
6520 routine will report only success or failure, and nothing about the
6523 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6524 the return codes and their meanings.) */
6527 regcomp (regex_t
*__restrict preg
, const char *__restrict pattern
,
6532 = (cflags
& REG_EXTENDED
) ?
6533 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
6535 /* regex_compile will allocate the space for the compiled pattern. */
6537 preg
->allocated
= 0;
6540 /* Try to allocate space for the fastmap. */
6541 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
6543 if (cflags
& REG_ICASE
)
6548 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
6549 * sizeof (*(RE_TRANSLATE_TYPE
)0));
6550 if (preg
->translate
== NULL
)
6551 return (int) REG_ESPACE
;
6553 /* Map uppercase characters to corresponding lowercase ones. */
6554 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
6555 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
6558 preg
->translate
= NULL
;
6560 /* If REG_NEWLINE is set, newlines are treated differently. */
6561 if (cflags
& REG_NEWLINE
)
6562 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6563 syntax
&= ~RE_DOT_NEWLINE
;
6564 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
6567 syntax
|= RE_NO_NEWLINE_ANCHOR
;
6569 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
6571 /* POSIX says a null character in the pattern terminates it, so we
6572 can use strlen here in compiling the pattern. */
6573 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
6575 /* POSIX doesn't distinguish between an unmatched open-group and an
6576 unmatched close-group: both are REG_EPAREN. */
6577 if (ret
== REG_ERPAREN
)
6580 if (ret
== REG_NOERROR
&& preg
->fastmap
)
6581 { /* Compute the fastmap now, since regexec cannot modify the pattern
6583 re_compile_fastmap (preg
);
6584 if (preg
->can_be_null
)
6585 { /* The fastmap can't be used anyway. */
6586 free (preg
->fastmap
);
6587 preg
->fastmap
= NULL
;
6592 WEAK_ALIAS (__regcomp
, regcomp
)
6595 /* regexec searches for a given pattern, specified by PREG, in the
6598 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6599 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6600 least NMATCH elements, and we set them to the offsets of the
6601 corresponding matched substrings.
6603 EFLAGS specifies `execution flags' which affect matching: if
6604 REG_NOTBOL is set, then ^ does not match at the beginning of the
6605 string; if REG_NOTEOL is set, then $ does not match at the end.
6607 We return 0 if we find a match and REG_NOMATCH if not. */
6610 regexec (const regex_t
*__restrict preg
, const char *__restrict string
,
6611 size_t nmatch
, regmatch_t pmatch
[__restrict_arr
], int eflags
)
6614 struct re_registers regs
;
6615 regex_t private_preg
;
6616 int len
= strlen (string
);
6617 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
6619 private_preg
= *preg
;
6621 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
6622 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
6624 /* The user has told us exactly how many registers to return
6625 information about, via `nmatch'. We have to pass that on to the
6626 matching routines. */
6627 private_preg
.regs_allocated
= REGS_FIXED
;
6631 regs
.num_regs
= nmatch
;
6632 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
6633 if (regs
.start
== NULL
)
6634 return (int) REG_NOMATCH
;
6635 regs
.end
= regs
.start
+ nmatch
;
6638 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6639 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6640 was a little bit longer but still only matching the real part.
6641 This works because the `endline' will check for a '\n' and will find a
6642 '\0', correctly deciding that this is not the end of a line.
6643 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6644 a convenient '\0' there. For all we know, the string could be preceded
6645 by '\n' which would throw things off. */
6647 /* Perform the searching operation. */
6648 ret
= re_search (&private_preg
, string
, len
,
6649 /* start: */ 0, /* range: */ len
,
6650 want_reg_info
? ®s
: (struct re_registers
*) 0);
6652 /* Copy the register information to the POSIX structure. */
6659 for (r
= 0; r
< nmatch
; r
++)
6661 pmatch
[r
].rm_so
= regs
.start
[r
];
6662 pmatch
[r
].rm_eo
= regs
.end
[r
];
6666 /* If we needed the temporary register info, free the space now. */
6670 /* We want zero return to mean success, unlike `re_search'. */
6671 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
6673 WEAK_ALIAS (__regexec
, regexec
)
6676 /* Returns a message corresponding to an error code, ERR_CODE, returned
6677 from either regcomp or regexec. We don't use PREG here.
6679 ERR_CODE was previously called ERRCODE, but that name causes an
6680 error with msvc8 compiler. */
6683 regerror (int err_code
, const regex_t
*preg
, char *errbuf
, size_t errbuf_size
)
6689 || err_code
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6690 /* Only error codes returned by the rest of the code should be passed
6691 to this routine. If we are given anything else, or if other regex
6692 code generates an invalid error code, then the program has a bug.
6693 Dump core so we can fix it. */
6696 msg
= gettext (re_error_msgid
[err_code
]);
6698 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6700 if (errbuf_size
!= 0)
6702 if (msg_size
> errbuf_size
)
6704 strncpy (errbuf
, msg
, errbuf_size
- 1);
6705 errbuf
[errbuf_size
- 1] = 0;
6708 strcpy (errbuf
, msg
);
6713 WEAK_ALIAS (__regerror
, regerror
)
6716 /* Free dynamically allocated space used by PREG. */
6719 regfree (regex_t
*preg
)
6721 free (preg
->buffer
);
6722 preg
->buffer
= NULL
;
6724 preg
->allocated
= 0;
6727 free (preg
->fastmap
);
6728 preg
->fastmap
= NULL
;
6729 preg
->fastmap_accurate
= 0;
6731 free (preg
->translate
);
6732 preg
->translate
= NULL
;
6734 WEAK_ALIAS (__regfree
, regfree
)
6736 #endif /* not emacs */