Fix Bug#24432
[emacs.git] / src / regex.c
blob41c1d3f61065170af5b223e9cb10995bae1f99b0
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-2016 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* TODO:
21 - structure the opcode space into opcode+flag.
22 - merge with glibc's regex.[ch].
23 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
24 need to modify the compiled regexp so that re_match can be reentrant.
25 - get rid of on_failure_jump_smart by doing the optimization in re_comp
26 rather than at run-time, so that re_match can be reentrant.
29 /* AIX requires this to be the first thing in the file. */
30 #if defined _AIX && !defined REGEX_MALLOC
31 #pragma alloca
32 #endif
34 /* Ignore some GCC warnings for now. This section should go away
35 once the Emacs and Gnulib regex code is merged. */
36 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__) || defined __clang__
37 # pragma GCC diagnostic ignored "-Wstrict-overflow"
38 # ifndef emacs
39 # pragma GCC diagnostic ignored "-Wunused-function"
40 # pragma GCC diagnostic ignored "-Wunused-macros"
41 # pragma GCC diagnostic ignored "-Wunused-result"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
43 # endif
44 #endif
46 #if 4 < __GNUC__ + (6 <= __GNUC_MINOR__) && ! defined __clang__
47 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
48 #endif
50 #include <config.h>
52 #include <stddef.h>
54 #ifdef emacs
55 /* We need this for `regex.h', and perhaps for the Emacs include files. */
56 # include <sys/types.h>
57 #endif
59 /* Whether to use ISO C Amendment 1 wide char functions.
60 Those should not be used for Emacs since it uses its own. */
61 #if defined _LIBC
62 #define WIDE_CHAR_SUPPORT 1
63 #else
64 #define WIDE_CHAR_SUPPORT \
65 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
66 #endif
68 /* For platform which support the ISO C amendment 1 functionality we
69 support user defined character classes. */
70 #if WIDE_CHAR_SUPPORT
71 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
72 # include <wchar.h>
73 # include <wctype.h>
74 #endif
76 #ifdef _LIBC
77 /* We have to keep the namespace clean. */
78 # define regfree(preg) __regfree (preg)
79 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
80 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
81 # define regerror(err_code, preg, errbuf, errbuf_size) \
82 __regerror (err_code, preg, errbuf, errbuf_size)
83 # define re_set_registers(bu, re, nu, st, en) \
84 __re_set_registers (bu, re, nu, st, en)
85 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
86 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
87 # define re_match(bufp, string, size, pos, regs) \
88 __re_match (bufp, string, size, pos, regs)
89 # define re_search(bufp, string, size, startpos, range, regs) \
90 __re_search (bufp, string, size, startpos, range, regs)
91 # define re_compile_pattern(pattern, length, bufp) \
92 __re_compile_pattern (pattern, length, bufp)
93 # define re_set_syntax(syntax) __re_set_syntax (syntax)
94 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
95 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
96 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
98 /* Make sure we call libc's function even if the user overrides them. */
99 # define btowc __btowc
100 # define iswctype __iswctype
101 # define wctype __wctype
103 # define WEAK_ALIAS(a,b) weak_alias (a, b)
105 /* We are also using some library internals. */
106 # include <locale/localeinfo.h>
107 # include <locale/elem-hash.h>
108 # include <langinfo.h>
109 #else
110 # define WEAK_ALIAS(a,b)
111 #endif
113 /* This is for other GNU distributions with internationalized messages. */
114 #if HAVE_LIBINTL_H || defined _LIBC
115 # include <libintl.h>
116 #else
117 # define gettext(msgid) (msgid)
118 #endif
120 #ifndef gettext_noop
121 /* This define is so xgettext can find the internationalizable
122 strings. */
123 # define gettext_noop(String) String
124 #endif
126 /* The `emacs' switch turns on certain matching commands
127 that make sense only in Emacs. */
128 #ifdef emacs
130 # include "lisp.h"
131 # include "character.h"
132 # include "buffer.h"
134 # include "syntax.h"
135 # include "category.h"
137 /* Make syntax table lookup grant data in gl_state. */
138 # define SYNTAX(c) syntax_property (c, 1)
140 # ifdef malloc
141 # undef malloc
142 # endif
143 # define malloc xmalloc
144 # ifdef realloc
145 # undef realloc
146 # endif
147 # define realloc xrealloc
148 # ifdef free
149 # undef free
150 # endif
151 # define free xfree
153 /* Converts the pointer to the char to BEG-based offset from the start. */
154 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
155 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
157 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
158 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
159 # define RE_STRING_CHAR(p, multibyte) \
160 (multibyte ? (STRING_CHAR (p)) : (*(p)))
161 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
162 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
164 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
166 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
168 /* Set C a (possibly converted to multibyte) character before P. P
169 points into a string which is the virtual concatenation of STR1
170 (which ends at END1) or STR2 (which ends at END2). */
171 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
172 do { \
173 if (target_multibyte) \
175 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
176 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
177 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
178 c = STRING_CHAR (dtemp); \
180 else \
182 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
183 (c) = RE_CHAR_TO_MULTIBYTE (c); \
185 } while (0)
187 /* Set C a (possibly converted to multibyte) character at P, and set
188 LEN to the byte length of that character. */
189 # define GET_CHAR_AFTER(c, p, len) \
190 do { \
191 if (target_multibyte) \
192 (c) = STRING_CHAR_AND_LENGTH (p, len); \
193 else \
195 (c) = *p; \
196 len = 1; \
197 (c) = RE_CHAR_TO_MULTIBYTE (c); \
199 } while (0)
201 #else /* not emacs */
203 /* If we are not linking with Emacs proper,
204 we can't use the relocating allocator
205 even if config.h says that we can. */
206 # undef REL_ALLOC
208 # include <unistd.h>
210 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
212 static void *
213 xmalloc (size_t size)
215 void *val = malloc (size);
216 if (!val && size)
218 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
219 exit (1);
221 return val;
224 static void *
225 xrealloc (void *block, size_t size)
227 void *val;
228 /* We must call malloc explicitly when BLOCK is 0, since some
229 reallocs don't do this. */
230 if (! block)
231 val = malloc (size);
232 else
233 val = realloc (block, size);
234 if (!val && size)
236 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
237 exit (1);
239 return val;
242 # ifdef malloc
243 # undef malloc
244 # endif
245 # define malloc xmalloc
246 # ifdef realloc
247 # undef realloc
248 # endif
249 # define realloc xrealloc
251 # include <stdbool.h>
252 # include <string.h>
254 /* Define the syntax stuff for \<, \>, etc. */
256 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
257 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
259 /* Dummy macros for non-Emacs environments. */
260 # define MAX_MULTIBYTE_LENGTH 1
261 # define RE_MULTIBYTE_P(x) 0
262 # define RE_TARGET_MULTIBYTE_P(x) 0
263 # define WORD_BOUNDARY_P(c1, c2) (0)
264 # define BYTES_BY_CHAR_HEAD(p) (1)
265 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
266 # define STRING_CHAR(p) (*(p))
267 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
268 # define CHAR_STRING(c, s) (*(s) = (c), 1)
269 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
270 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
271 # define RE_CHAR_TO_MULTIBYTE(c) (c)
272 # define RE_CHAR_TO_UNIBYTE(c) (c)
273 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
274 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
275 # define GET_CHAR_AFTER(c, p, len) \
276 (c = *p, len = 1)
277 # define CHAR_BYTE8_P(c) (0)
278 # define CHAR_LEADING_CODE(c) (c)
280 #endif /* not emacs */
282 #ifndef RE_TRANSLATE
283 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
284 # define RE_TRANSLATE_P(TBL) (TBL)
285 #endif
287 /* Get the interface, including the syntax bits. */
288 #include "regex.h"
290 /* isalpha etc. are used for the character classes. */
291 #include <ctype.h>
293 #ifdef emacs
295 /* 1 if C is an ASCII character. */
296 # define IS_REAL_ASCII(c) ((c) < 0200)
298 /* 1 if C is a unibyte character. */
299 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
301 /* The Emacs definitions should not be directly affected by locales. */
303 /* In Emacs, these are only used for single-byte characters. */
304 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
305 # define ISCNTRL(c) ((c) < ' ')
306 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
307 || ((c) >= 'a' && (c) <= 'f') \
308 || ((c) >= 'A' && (c) <= 'F'))
310 /* This is only used for single-byte characters. */
311 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
313 /* The rest must handle multibyte characters. */
315 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
316 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0240) \
317 : graphicp (c))
319 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
320 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
321 : printablep (c))
323 # define ISALNUM(c) (IS_REAL_ASCII (c) \
324 ? (((c) >= 'a' && (c) <= 'z') \
325 || ((c) >= 'A' && (c) <= 'Z') \
326 || ((c) >= '0' && (c) <= '9')) \
327 : alphanumericp (c))
329 # define ISALPHA(c) (IS_REAL_ASCII (c) \
330 ? (((c) >= 'a' && (c) <= 'z') \
331 || ((c) >= 'A' && (c) <= 'Z')) \
332 : alphabeticp (c))
334 # define ISLOWER(c) lowercasep (c)
336 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
337 ? ((c) > ' ' && (c) < 0177 \
338 && !(((c) >= 'a' && (c) <= 'z') \
339 || ((c) >= 'A' && (c) <= 'Z') \
340 || ((c) >= '0' && (c) <= '9'))) \
341 : SYNTAX (c) != Sword)
343 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
345 # define ISUPPER(c) uppercasep (c)
347 # define ISWORD(c) (SYNTAX (c) == Sword)
349 #else /* not emacs */
351 /* 1 if C is an ASCII character. */
352 # define IS_REAL_ASCII(c) ((c) < 0200)
354 /* This distinction is not meaningful, except in Emacs. */
355 # define ISUNIBYTE(c) 1
357 # ifdef isblank
358 # define ISBLANK(c) isblank (c)
359 # else
360 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
361 # endif
362 # ifdef isgraph
363 # define ISGRAPH(c) isgraph (c)
364 # else
365 # define ISGRAPH(c) (isprint (c) && !isspace (c))
366 # endif
368 /* Solaris defines ISPRINT so we must undefine it first. */
369 # undef ISPRINT
370 # define ISPRINT(c) isprint (c)
371 # define ISDIGIT(c) isdigit (c)
372 # define ISALNUM(c) isalnum (c)
373 # define ISALPHA(c) isalpha (c)
374 # define ISCNTRL(c) iscntrl (c)
375 # define ISLOWER(c) islower (c)
376 # define ISPUNCT(c) ispunct (c)
377 # define ISSPACE(c) isspace (c)
378 # define ISUPPER(c) isupper (c)
379 # define ISXDIGIT(c) isxdigit (c)
381 # define ISWORD(c) ISALPHA (c)
383 # ifdef _tolower
384 # define TOLOWER(c) _tolower (c)
385 # else
386 # define TOLOWER(c) tolower (c)
387 # endif
389 /* How many characters in the character set. */
390 # define CHAR_SET_SIZE 256
392 # ifdef SYNTAX_TABLE
394 extern char *re_syntax_table;
396 # else /* not SYNTAX_TABLE */
398 static char re_syntax_table[CHAR_SET_SIZE];
400 static void
401 init_syntax_once (void)
403 register int c;
404 static int done = 0;
406 if (done)
407 return;
409 memset (re_syntax_table, 0, sizeof re_syntax_table);
411 for (c = 0; c < CHAR_SET_SIZE; ++c)
412 if (ISALNUM (c))
413 re_syntax_table[c] = Sword;
415 re_syntax_table['_'] = Ssymbol;
417 done = 1;
420 # endif /* not SYNTAX_TABLE */
422 # define SYNTAX(c) re_syntax_table[(c)]
424 #endif /* not emacs */
426 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
428 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
429 use `alloca' instead of `malloc'. This is because using malloc in
430 re_search* or re_match* could cause memory leaks when C-g is used in
431 Emacs; also, malloc is slower and causes storage fragmentation. On
432 the other hand, malloc is more portable, and easier to debug.
434 Because we sometimes use alloca, some routines have to be macros,
435 not functions -- `alloca'-allocated space disappears at the end of the
436 function it is called in. */
438 #ifdef REGEX_MALLOC
440 # define REGEX_ALLOCATE malloc
441 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
442 # define REGEX_FREE free
444 #else /* not REGEX_MALLOC */
446 /* Emacs already defines alloca, sometimes. */
447 # ifndef alloca
449 /* Make alloca work the best possible way. */
450 # ifdef __GNUC__
451 # define alloca __builtin_alloca
452 # else /* not __GNUC__ */
453 # ifdef HAVE_ALLOCA_H
454 # include <alloca.h>
455 # endif /* HAVE_ALLOCA_H */
456 # endif /* not __GNUC__ */
458 # endif /* not alloca */
460 # ifdef emacs
461 # define REGEX_USE_SAFE_ALLOCA USE_SAFE_ALLOCA
462 # define REGEX_SAFE_FREE() SAFE_FREE ()
463 # define REGEX_ALLOCATE SAFE_ALLOCA
464 # else
465 # define REGEX_ALLOCATE alloca
466 # endif
468 /* Assumes a `char *destination' variable. */
469 # define REGEX_REALLOCATE(source, osize, nsize) \
470 (destination = REGEX_ALLOCATE (nsize), \
471 memcpy (destination, source, osize))
473 /* No need to do anything to free, after alloca. */
474 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
476 #endif /* not REGEX_MALLOC */
478 #ifndef REGEX_USE_SAFE_ALLOCA
479 # define REGEX_USE_SAFE_ALLOCA ((void) 0)
480 # define REGEX_SAFE_FREE() ((void) 0)
481 #endif
483 /* Define how to allocate the failure stack. */
485 #if defined REL_ALLOC && defined REGEX_MALLOC
487 # define REGEX_ALLOCATE_STACK(size) \
488 r_alloc (&failure_stack_ptr, (size))
489 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
490 r_re_alloc (&failure_stack_ptr, (nsize))
491 # define REGEX_FREE_STACK(ptr) \
492 r_alloc_free (&failure_stack_ptr)
494 #else /* not using relocating allocator */
496 # define REGEX_ALLOCATE_STACK(size) REGEX_ALLOCATE (size)
497 # define REGEX_REALLOCATE_STACK(source, o, n) REGEX_REALLOCATE (source, o, n)
498 # define REGEX_FREE_STACK(ptr) REGEX_FREE (ptr)
500 #endif /* not using relocating allocator */
503 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
504 `string1' or just past its end. This works if PTR is NULL, which is
505 a good thing. */
506 #define FIRST_STRING_P(ptr) \
507 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
509 /* (Re)Allocate N items of type T using malloc, or fail. */
510 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
511 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
512 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
514 #define BYTEWIDTH 8 /* In bits. */
516 #ifndef emacs
517 # undef max
518 # undef min
519 # define max(a, b) ((a) > (b) ? (a) : (b))
520 # define min(a, b) ((a) < (b) ? (a) : (b))
521 #endif
523 /* Type of source-pattern and string chars. */
524 #ifdef _MSC_VER
525 typedef unsigned char re_char;
526 typedef const re_char const_re_char;
527 #else
528 typedef const unsigned char re_char;
529 typedef re_char const_re_char;
530 #endif
532 typedef char boolean;
534 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
535 re_char *string1, size_t size1,
536 re_char *string2, size_t size2,
537 ssize_t pos,
538 struct re_registers *regs,
539 ssize_t stop);
541 /* These are the command codes that appear in compiled regular
542 expressions. Some opcodes are followed by argument bytes. A
543 command code can specify any interpretation whatsoever for its
544 arguments. Zero bytes may appear in the compiled regular expression. */
546 typedef enum
548 no_op = 0,
550 /* Succeed right away--no more backtracking. */
551 succeed,
553 /* Followed by one byte giving n, then by n literal bytes. */
554 exactn,
556 /* Matches any (more or less) character. */
557 anychar,
559 /* Matches any one char belonging to specified set. First
560 following byte is number of bitmap bytes. Then come bytes
561 for a bitmap saying which chars are in. Bits in each byte
562 are ordered low-bit-first. A character is in the set if its
563 bit is 1. A character too large to have a bit in the map is
564 automatically not in the set.
566 If the length byte has the 0x80 bit set, then that stuff
567 is followed by a range table:
568 2 bytes of flags for character sets (low 8 bits, high 8 bits)
569 See RANGE_TABLE_WORK_BITS below.
570 2 bytes, the number of pairs that follow (upto 32767)
571 pairs, each 2 multibyte characters,
572 each multibyte character represented as 3 bytes. */
573 charset,
575 /* Same parameters as charset, but match any character that is
576 not one of those specified. */
577 charset_not,
579 /* Start remembering the text that is matched, for storing in a
580 register. Followed by one byte with the register number, in
581 the range 0 to one less than the pattern buffer's re_nsub
582 field. */
583 start_memory,
585 /* Stop remembering the text that is matched and store it in a
586 memory register. Followed by one byte with the register
587 number, in the range 0 to one less than `re_nsub' in the
588 pattern buffer. */
589 stop_memory,
591 /* Match a duplicate of something remembered. Followed by one
592 byte containing the register number. */
593 duplicate,
595 /* Fail unless at beginning of line. */
596 begline,
598 /* Fail unless at end of line. */
599 endline,
601 /* Succeeds if at beginning of buffer (if emacs) or at beginning
602 of string to be matched (if not). */
603 begbuf,
605 /* Analogously, for end of buffer/string. */
606 endbuf,
608 /* Followed by two byte relative address to which to jump. */
609 jump,
611 /* Followed by two-byte relative address of place to resume at
612 in case of failure. */
613 on_failure_jump,
615 /* Like on_failure_jump, but pushes a placeholder instead of the
616 current string position when executed. */
617 on_failure_keep_string_jump,
619 /* Just like `on_failure_jump', except that it checks that we
620 don't get stuck in an infinite loop (matching an empty string
621 indefinitely). */
622 on_failure_jump_loop,
624 /* Just like `on_failure_jump_loop', except that it checks for
625 a different kind of loop (the kind that shows up with non-greedy
626 operators). This operation has to be immediately preceded
627 by a `no_op'. */
628 on_failure_jump_nastyloop,
630 /* A smart `on_failure_jump' used for greedy * and + operators.
631 It analyzes the loop before which it is put and if the
632 loop does not require backtracking, it changes itself to
633 `on_failure_keep_string_jump' and short-circuits the loop,
634 else it just defaults to changing itself into `on_failure_jump'.
635 It assumes that it is pointing to just past a `jump'. */
636 on_failure_jump_smart,
638 /* Followed by two-byte relative address and two-byte number n.
639 After matching N times, jump to the address upon failure.
640 Does not work if N starts at 0: use on_failure_jump_loop
641 instead. */
642 succeed_n,
644 /* Followed by two-byte relative address, and two-byte number n.
645 Jump to the address N times, then fail. */
646 jump_n,
648 /* Set the following two-byte relative address to the
649 subsequent two-byte number. The address *includes* the two
650 bytes of number. */
651 set_number_at,
653 wordbeg, /* Succeeds if at word beginning. */
654 wordend, /* Succeeds if at word end. */
656 wordbound, /* Succeeds if at a word boundary. */
657 notwordbound, /* Succeeds if not at a word boundary. */
659 symbeg, /* Succeeds if at symbol beginning. */
660 symend, /* Succeeds if at symbol end. */
662 /* Matches any character whose syntax is specified. Followed by
663 a byte which contains a syntax code, e.g., Sword. */
664 syntaxspec,
666 /* Matches any character whose syntax is not that specified. */
667 notsyntaxspec
669 #ifdef emacs
670 , at_dot, /* Succeeds if at point. */
672 /* Matches any character whose category-set contains the specified
673 category. The operator is followed by a byte which contains a
674 category code (mnemonic ASCII character). */
675 categoryspec,
677 /* Matches any character whose category-set does not contain the
678 specified category. The operator is followed by a byte which
679 contains the category code (mnemonic ASCII character). */
680 notcategoryspec
681 #endif /* emacs */
682 } re_opcode_t;
684 /* Common operations on the compiled pattern. */
686 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
688 #define STORE_NUMBER(destination, number) \
689 do { \
690 (destination)[0] = (number) & 0377; \
691 (destination)[1] = (number) >> 8; \
692 } while (0)
694 /* Same as STORE_NUMBER, except increment DESTINATION to
695 the byte after where the number is stored. Therefore, DESTINATION
696 must be an lvalue. */
698 #define STORE_NUMBER_AND_INCR(destination, number) \
699 do { \
700 STORE_NUMBER (destination, number); \
701 (destination) += 2; \
702 } while (0)
704 /* Put into DESTINATION a number stored in two contiguous bytes starting
705 at SOURCE. */
707 #define EXTRACT_NUMBER(destination, source) \
708 ((destination) = extract_number (source))
710 static int
711 extract_number (re_char *source)
713 unsigned leading_byte = SIGN_EXTEND_CHAR (source[1]);
714 return (leading_byte << 8) + source[0];
717 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
718 SOURCE must be an lvalue. */
720 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
721 ((destination) = extract_number_and_incr (&source))
723 static int
724 extract_number_and_incr (re_char **source)
726 int num = extract_number (*source);
727 *source += 2;
728 return num;
731 /* Store a multibyte character in three contiguous bytes starting
732 DESTINATION, and increment DESTINATION to the byte after where the
733 character is stored. Therefore, DESTINATION must be an lvalue. */
735 #define STORE_CHARACTER_AND_INCR(destination, character) \
736 do { \
737 (destination)[0] = (character) & 0377; \
738 (destination)[1] = ((character) >> 8) & 0377; \
739 (destination)[2] = (character) >> 16; \
740 (destination) += 3; \
741 } while (0)
743 /* Put into DESTINATION a character stored in three contiguous bytes
744 starting at SOURCE. */
746 #define EXTRACT_CHARACTER(destination, source) \
747 do { \
748 (destination) = ((source)[0] \
749 | ((source)[1] << 8) \
750 | ((source)[2] << 16)); \
751 } while (0)
754 /* Macros for charset. */
756 /* Size of bitmap of charset P in bytes. P is a start of charset,
757 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
758 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
760 /* Nonzero if charset P has range table. */
761 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
763 /* Return the address of range table of charset P. But not the start
764 of table itself, but the before where the number of ranges is
765 stored. `2 +' means to skip re_opcode_t and size of bitmap,
766 and the 2 bytes of flags at the start of the range table. */
767 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
769 #ifdef emacs
770 /* Extract the bit flags that start a range table. */
771 #define CHARSET_RANGE_TABLE_BITS(p) \
772 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
773 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
774 #endif
776 /* Return the address of end of RANGE_TABLE. COUNT is number of
777 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
778 is start of range and end of range. `* 3' is size of each start
779 and end. */
780 #define CHARSET_RANGE_TABLE_END(range_table, count) \
781 ((range_table) + (count) * 2 * 3)
783 /* If DEBUG is defined, Regex prints many voluminous messages about what
784 it is doing (if the variable `debug' is nonzero). If linked with the
785 main program in `iregex.c', you can enter patterns and strings
786 interactively. And if linked with the main program in `main.c' and
787 the other test files, you can run the already-written tests. */
789 #ifdef DEBUG
791 /* We use standard I/O for debugging. */
792 # include <stdio.h>
794 /* It is useful to test things that ``must'' be true when debugging. */
795 # include <assert.h>
797 static int debug = -100000;
799 # define DEBUG_STATEMENT(e) e
800 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
801 # define DEBUG_COMPILES_ARGUMENTS
802 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
803 if (debug > 0) print_partial_compiled_pattern (s, e)
804 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
805 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
808 /* Print the fastmap in human-readable form. */
810 static void
811 print_fastmap (char *fastmap)
813 unsigned was_a_range = 0;
814 unsigned i = 0;
816 while (i < (1 << BYTEWIDTH))
818 if (fastmap[i++])
820 was_a_range = 0;
821 putchar (i - 1);
822 while (i < (1 << BYTEWIDTH) && fastmap[i])
824 was_a_range = 1;
825 i++;
827 if (was_a_range)
829 printf ("-");
830 putchar (i - 1);
834 putchar ('\n');
838 /* Print a compiled pattern string in human-readable form, starting at
839 the START pointer into it and ending just before the pointer END. */
841 static void
842 print_partial_compiled_pattern (re_char *start, re_char *end)
844 int mcnt, mcnt2;
845 re_char *p = start;
846 re_char *pend = end;
848 if (start == NULL)
850 fprintf (stderr, "(null)\n");
851 return;
854 /* Loop over pattern commands. */
855 while (p < pend)
857 fprintf (stderr, "%td:\t", p - start);
859 switch ((re_opcode_t) *p++)
861 case no_op:
862 fprintf (stderr, "/no_op");
863 break;
865 case succeed:
866 fprintf (stderr, "/succeed");
867 break;
869 case exactn:
870 mcnt = *p++;
871 fprintf (stderr, "/exactn/%d", mcnt);
874 fprintf (stderr, "/%c", *p++);
876 while (--mcnt);
877 break;
879 case start_memory:
880 fprintf (stderr, "/start_memory/%d", *p++);
881 break;
883 case stop_memory:
884 fprintf (stderr, "/stop_memory/%d", *p++);
885 break;
887 case duplicate:
888 fprintf (stderr, "/duplicate/%d", *p++);
889 break;
891 case anychar:
892 fprintf (stderr, "/anychar");
893 break;
895 case charset:
896 case charset_not:
898 register int c, last = -100;
899 register int in_range = 0;
900 int length = CHARSET_BITMAP_SIZE (p - 1);
901 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
903 fprintf (stderr, "/charset [%s",
904 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
906 if (p + *p >= pend)
907 fprintf (stderr, " !extends past end of pattern! ");
909 for (c = 0; c < 256; c++)
910 if (c / 8 < length
911 && (p[1 + (c/8)] & (1 << (c % 8))))
913 /* Are we starting a range? */
914 if (last + 1 == c && ! in_range)
916 fprintf (stderr, "-");
917 in_range = 1;
919 /* Have we broken a range? */
920 else if (last + 1 != c && in_range)
922 fprintf (stderr, "%c", last);
923 in_range = 0;
926 if (! in_range)
927 fprintf (stderr, "%c", c);
929 last = c;
932 if (in_range)
933 fprintf (stderr, "%c", last);
935 fprintf (stderr, "]");
937 p += 1 + length;
939 if (has_range_table)
941 int count;
942 fprintf (stderr, "has-range-table");
944 /* ??? Should print the range table; for now, just skip it. */
945 p += 2; /* skip range table bits */
946 EXTRACT_NUMBER_AND_INCR (count, p);
947 p = CHARSET_RANGE_TABLE_END (p, count);
950 break;
952 case begline:
953 fprintf (stderr, "/begline");
954 break;
956 case endline:
957 fprintf (stderr, "/endline");
958 break;
960 case on_failure_jump:
961 EXTRACT_NUMBER_AND_INCR (mcnt, p);
962 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
963 break;
965 case on_failure_keep_string_jump:
966 EXTRACT_NUMBER_AND_INCR (mcnt, p);
967 fprintf (stderr, "/on_failure_keep_string_jump to %td",
968 p + mcnt - start);
969 break;
971 case on_failure_jump_nastyloop:
972 EXTRACT_NUMBER_AND_INCR (mcnt, p);
973 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
974 p + mcnt - start);
975 break;
977 case on_failure_jump_loop:
978 EXTRACT_NUMBER_AND_INCR (mcnt, p);
979 fprintf (stderr, "/on_failure_jump_loop to %td",
980 p + mcnt - start);
981 break;
983 case on_failure_jump_smart:
984 EXTRACT_NUMBER_AND_INCR (mcnt, p);
985 fprintf (stderr, "/on_failure_jump_smart to %td",
986 p + mcnt - start);
987 break;
989 case jump:
990 EXTRACT_NUMBER_AND_INCR (mcnt, p);
991 fprintf (stderr, "/jump to %td", p + mcnt - start);
992 break;
994 case succeed_n:
995 EXTRACT_NUMBER_AND_INCR (mcnt, p);
996 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
997 fprintf (stderr, "/succeed_n to %td, %d times",
998 p - 2 + mcnt - start, mcnt2);
999 break;
1001 case jump_n:
1002 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1003 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1004 fprintf (stderr, "/jump_n to %td, %d times",
1005 p - 2 + mcnt - start, mcnt2);
1006 break;
1008 case set_number_at:
1009 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1010 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1011 fprintf (stderr, "/set_number_at location %td to %d",
1012 p - 2 + mcnt - start, mcnt2);
1013 break;
1015 case wordbound:
1016 fprintf (stderr, "/wordbound");
1017 break;
1019 case notwordbound:
1020 fprintf (stderr, "/notwordbound");
1021 break;
1023 case wordbeg:
1024 fprintf (stderr, "/wordbeg");
1025 break;
1027 case wordend:
1028 fprintf (stderr, "/wordend");
1029 break;
1031 case symbeg:
1032 fprintf (stderr, "/symbeg");
1033 break;
1035 case symend:
1036 fprintf (stderr, "/symend");
1037 break;
1039 case syntaxspec:
1040 fprintf (stderr, "/syntaxspec");
1041 mcnt = *p++;
1042 fprintf (stderr, "/%d", mcnt);
1043 break;
1045 case notsyntaxspec:
1046 fprintf (stderr, "/notsyntaxspec");
1047 mcnt = *p++;
1048 fprintf (stderr, "/%d", mcnt);
1049 break;
1051 # ifdef emacs
1052 case at_dot:
1053 fprintf (stderr, "/at_dot");
1054 break;
1056 case categoryspec:
1057 fprintf (stderr, "/categoryspec");
1058 mcnt = *p++;
1059 fprintf (stderr, "/%d", mcnt);
1060 break;
1062 case notcategoryspec:
1063 fprintf (stderr, "/notcategoryspec");
1064 mcnt = *p++;
1065 fprintf (stderr, "/%d", mcnt);
1066 break;
1067 # endif /* emacs */
1069 case begbuf:
1070 fprintf (stderr, "/begbuf");
1071 break;
1073 case endbuf:
1074 fprintf (stderr, "/endbuf");
1075 break;
1077 default:
1078 fprintf (stderr, "?%d", *(p-1));
1081 fprintf (stderr, "\n");
1084 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1088 static void
1089 print_compiled_pattern (struct re_pattern_buffer *bufp)
1091 re_char *buffer = bufp->buffer;
1093 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1094 printf ("%ld bytes used/%ld bytes allocated.\n",
1095 bufp->used, bufp->allocated);
1097 if (bufp->fastmap_accurate && bufp->fastmap)
1099 printf ("fastmap: ");
1100 print_fastmap (bufp->fastmap);
1103 printf ("re_nsub: %zu\t", bufp->re_nsub);
1104 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1105 printf ("can_be_null: %d\t", bufp->can_be_null);
1106 printf ("no_sub: %d\t", bufp->no_sub);
1107 printf ("not_bol: %d\t", bufp->not_bol);
1108 printf ("not_eol: %d\t", bufp->not_eol);
1109 #ifndef emacs
1110 printf ("syntax: %lx\n", bufp->syntax);
1111 #endif
1112 fflush (stdout);
1113 /* Perhaps we should print the translate table? */
1117 static void
1118 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1119 re_char *string2, ssize_t size2)
1121 ssize_t this_char;
1123 if (where == NULL)
1124 printf ("(null)");
1125 else
1127 if (FIRST_STRING_P (where))
1129 for (this_char = where - string1; this_char < size1; this_char++)
1130 putchar (string1[this_char]);
1132 where = string2;
1135 for (this_char = where - string2; this_char < size2; this_char++)
1136 putchar (string2[this_char]);
1140 #else /* not DEBUG */
1142 # undef assert
1143 # define assert(e)
1145 # define DEBUG_STATEMENT(e)
1146 # define DEBUG_PRINT(...)
1147 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1148 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1150 #endif /* not DEBUG */
1152 #ifndef emacs
1154 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1155 also be assigned to arbitrarily: each pattern buffer stores its own
1156 syntax, so it can be changed between regex compilations. */
1157 /* This has no initializer because initialized variables in Emacs
1158 become read-only after dumping. */
1159 reg_syntax_t re_syntax_options;
1162 /* Specify the precise syntax of regexps for compilation. This provides
1163 for compatibility for various utilities which historically have
1164 different, incompatible syntaxes.
1166 The argument SYNTAX is a bit mask comprised of the various bits
1167 defined in regex.h. We return the old syntax. */
1169 reg_syntax_t
1170 re_set_syntax (reg_syntax_t syntax)
1172 reg_syntax_t ret = re_syntax_options;
1174 re_syntax_options = syntax;
1175 return ret;
1177 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1179 #endif
1181 /* This table gives an error message for each of the error codes listed
1182 in regex.h. Obviously the order here has to be same as there.
1183 POSIX doesn't require that we do anything for REG_NOERROR,
1184 but why not be nice? */
1186 static const char *re_error_msgid[] =
1188 gettext_noop ("Success"), /* REG_NOERROR */
1189 gettext_noop ("No match"), /* REG_NOMATCH */
1190 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1191 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1192 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1193 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1194 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1195 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1196 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1197 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1198 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1199 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1200 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1201 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1202 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1203 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1204 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1205 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1208 /* Avoiding alloca during matching, to placate r_alloc. */
1210 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1211 searching and matching functions should not call alloca. On some
1212 systems, alloca is implemented in terms of malloc, and if we're
1213 using the relocating allocator routines, then malloc could cause a
1214 relocation, which might (if the strings being searched are in the
1215 ralloc heap) shift the data out from underneath the regexp
1216 routines.
1218 Here's another reason to avoid allocation: Emacs
1219 processes input from X in a signal handler; processing X input may
1220 call malloc; if input arrives while a matching routine is calling
1221 malloc, then we're scrod. But Emacs can't just block input while
1222 calling matching routines; then we don't notice interrupts when
1223 they come in. So, Emacs blocks input around all regexp calls
1224 except the matching calls, which it leaves unprotected, in the
1225 faith that they will not malloc. */
1227 /* Normally, this is fine. */
1228 #define MATCH_MAY_ALLOCATE
1230 /* The match routines may not allocate if (1) they would do it with malloc
1231 and (2) it's not safe for them to use malloc.
1232 Note that if REL_ALLOC is defined, matching would not use malloc for the
1233 failure stack, but we would still use it for the register vectors;
1234 so REL_ALLOC should not affect this. */
1235 #if defined REGEX_MALLOC && defined emacs
1236 # undef MATCH_MAY_ALLOCATE
1237 #endif
1240 /* Failure stack declarations and macros; both re_compile_fastmap and
1241 re_match_2 use a failure stack. These have to be macros because of
1242 REGEX_ALLOCATE_STACK. */
1245 /* Approximate number of failure points for which to initially allocate space
1246 when matching. If this number is exceeded, we allocate more
1247 space, so it is not a hard limit. */
1248 #ifndef INIT_FAILURE_ALLOC
1249 # define INIT_FAILURE_ALLOC 20
1250 #endif
1252 /* Roughly the maximum number of failure points on the stack. Would be
1253 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1254 This is a variable only so users of regex can assign to it; we never
1255 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1256 before using it, so it should probably be a byte-count instead. */
1257 # if defined MATCH_MAY_ALLOCATE
1258 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1259 whose default stack limit is 2mb. In order for a larger
1260 value to work reliably, you have to try to make it accord
1261 with the process stack limit. */
1262 size_t re_max_failures = 40000;
1263 # else
1264 size_t re_max_failures = 4000;
1265 # endif
1267 union fail_stack_elt
1269 re_char *pointer;
1270 /* This should be the biggest `int' that's no bigger than a pointer. */
1271 long integer;
1274 typedef union fail_stack_elt fail_stack_elt_t;
1276 typedef struct
1278 fail_stack_elt_t *stack;
1279 size_t size;
1280 size_t avail; /* Offset of next open position. */
1281 size_t frame; /* Offset of the cur constructed frame. */
1282 } fail_stack_type;
1284 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1287 /* Define macros to initialize and free the failure stack.
1288 Do `return -2' if the alloc fails. */
1290 #ifdef MATCH_MAY_ALLOCATE
1291 # define INIT_FAIL_STACK() \
1292 do { \
1293 fail_stack.stack = \
1294 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1295 * sizeof (fail_stack_elt_t)); \
1297 if (fail_stack.stack == NULL) \
1298 return -2; \
1300 fail_stack.size = INIT_FAILURE_ALLOC; \
1301 fail_stack.avail = 0; \
1302 fail_stack.frame = 0; \
1303 } while (0)
1304 #else
1305 # define INIT_FAIL_STACK() \
1306 do { \
1307 fail_stack.avail = 0; \
1308 fail_stack.frame = 0; \
1309 } while (0)
1311 # define RETALLOC_IF(addr, n, t) \
1312 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1313 #endif
1316 /* Double the size of FAIL_STACK, up to a limit
1317 which allows approximately `re_max_failures' items.
1319 Return 1 if succeeds, and 0 if either ran out of memory
1320 allocating space for it or it was already too large.
1322 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1324 /* Factor to increase the failure stack size by
1325 when we increase it.
1326 This used to be 2, but 2 was too wasteful
1327 because the old discarded stacks added up to as much space
1328 were as ultimate, maximum-size stack. */
1329 #define FAIL_STACK_GROWTH_FACTOR 4
1331 #define GROW_FAIL_STACK(fail_stack) \
1332 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1333 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1334 ? 0 \
1335 : ((fail_stack).stack \
1336 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1337 (fail_stack).size * sizeof (fail_stack_elt_t), \
1338 min (re_max_failures * TYPICAL_FAILURE_SIZE, \
1339 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1340 * FAIL_STACK_GROWTH_FACTOR))), \
1342 (fail_stack).stack == NULL \
1343 ? 0 \
1344 : ((fail_stack).size \
1345 = (min (re_max_failures * TYPICAL_FAILURE_SIZE, \
1346 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1347 * FAIL_STACK_GROWTH_FACTOR)) \
1348 / sizeof (fail_stack_elt_t)), \
1349 1)))
1352 /* Push a pointer value onto the failure stack.
1353 Assumes the variable `fail_stack'. Probably should only
1354 be called from within `PUSH_FAILURE_POINT'. */
1355 #define PUSH_FAILURE_POINTER(item) \
1356 fail_stack.stack[fail_stack.avail++].pointer = (item)
1358 /* This pushes an integer-valued item onto the failure stack.
1359 Assumes the variable `fail_stack'. Probably should only
1360 be called from within `PUSH_FAILURE_POINT'. */
1361 #define PUSH_FAILURE_INT(item) \
1362 fail_stack.stack[fail_stack.avail++].integer = (item)
1364 /* These POP... operations complement the PUSH... operations.
1365 All assume that `fail_stack' is nonempty. */
1366 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1367 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1369 /* Individual items aside from the registers. */
1370 #define NUM_NONREG_ITEMS 3
1372 /* Used to examine the stack (to detect infinite loops). */
1373 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1374 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1375 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1376 #define TOP_FAILURE_HANDLE() fail_stack.frame
1379 #define ENSURE_FAIL_STACK(space) \
1380 while (REMAINING_AVAIL_SLOTS <= space) { \
1381 if (!GROW_FAIL_STACK (fail_stack)) \
1382 return -2; \
1383 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1384 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1387 /* Push register NUM onto the stack. */
1388 #define PUSH_FAILURE_REG(num) \
1389 do { \
1390 char *destination; \
1391 long n = num; \
1392 ENSURE_FAIL_STACK(3); \
1393 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1394 n, regstart[n], regend[n]); \
1395 PUSH_FAILURE_POINTER (regstart[n]); \
1396 PUSH_FAILURE_POINTER (regend[n]); \
1397 PUSH_FAILURE_INT (n); \
1398 } while (0)
1400 /* Change the counter's value to VAL, but make sure that it will
1401 be reset when backtracking. */
1402 #define PUSH_NUMBER(ptr,val) \
1403 do { \
1404 char *destination; \
1405 int c; \
1406 ENSURE_FAIL_STACK(3); \
1407 EXTRACT_NUMBER (c, ptr); \
1408 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1409 PUSH_FAILURE_INT (c); \
1410 PUSH_FAILURE_POINTER (ptr); \
1411 PUSH_FAILURE_INT (-1); \
1412 STORE_NUMBER (ptr, val); \
1413 } while (0)
1415 /* Pop a saved register off the stack. */
1416 #define POP_FAILURE_REG_OR_COUNT() \
1417 do { \
1418 long pfreg = POP_FAILURE_INT (); \
1419 if (pfreg == -1) \
1421 /* It's a counter. */ \
1422 /* Here, we discard `const', making re_match non-reentrant. */ \
1423 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1424 pfreg = POP_FAILURE_INT (); \
1425 STORE_NUMBER (ptr, pfreg); \
1426 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1428 else \
1430 regend[pfreg] = POP_FAILURE_POINTER (); \
1431 regstart[pfreg] = POP_FAILURE_POINTER (); \
1432 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1433 pfreg, regstart[pfreg], regend[pfreg]); \
1435 } while (0)
1437 /* Check that we are not stuck in an infinite loop. */
1438 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1439 do { \
1440 ssize_t failure = TOP_FAILURE_HANDLE (); \
1441 /* Check for infinite matching loops */ \
1442 while (failure > 0 \
1443 && (FAILURE_STR (failure) == string_place \
1444 || FAILURE_STR (failure) == NULL)) \
1446 assert (FAILURE_PAT (failure) >= bufp->buffer \
1447 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1448 if (FAILURE_PAT (failure) == pat_cur) \
1450 cycle = 1; \
1451 break; \
1453 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1454 failure = NEXT_FAILURE_HANDLE(failure); \
1456 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1457 } while (0)
1459 /* Push the information about the state we will need
1460 if we ever fail back to it.
1462 Requires variables fail_stack, regstart, regend and
1463 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1464 declared.
1466 Does `return FAILURE_CODE' if runs out of memory. */
1468 #define PUSH_FAILURE_POINT(pattern, string_place) \
1469 do { \
1470 char *destination; \
1471 /* Must be int, so when we don't save any registers, the arithmetic \
1472 of 0 + -1 isn't done as unsigned. */ \
1474 DEBUG_STATEMENT (nfailure_points_pushed++); \
1475 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1476 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1477 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1479 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1481 DEBUG_PRINT ("\n"); \
1483 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1484 PUSH_FAILURE_INT (fail_stack.frame); \
1486 DEBUG_PRINT (" Push string %p: \"", string_place); \
1487 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1488 DEBUG_PRINT ("\"\n"); \
1489 PUSH_FAILURE_POINTER (string_place); \
1491 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1492 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1493 PUSH_FAILURE_POINTER (pattern); \
1495 /* Close the frame by moving the frame pointer past it. */ \
1496 fail_stack.frame = fail_stack.avail; \
1497 } while (0)
1499 /* Estimate the size of data pushed by a typical failure stack entry.
1500 An estimate is all we need, because all we use this for
1501 is to choose a limit for how big to make the failure stack. */
1502 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1503 #define TYPICAL_FAILURE_SIZE 20
1505 /* How many items can still be added to the stack without overflowing it. */
1506 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1509 /* Pops what PUSH_FAIL_STACK pushes.
1511 We restore into the parameters, all of which should be lvalues:
1512 STR -- the saved data position.
1513 PAT -- the saved pattern position.
1514 REGSTART, REGEND -- arrays of string positions.
1516 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1517 `pend', `string1', `size1', `string2', and `size2'. */
1519 #define POP_FAILURE_POINT(str, pat) \
1520 do { \
1521 assert (!FAIL_STACK_EMPTY ()); \
1523 /* Remove failure points and point to how many regs pushed. */ \
1524 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1525 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1526 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1528 /* Pop the saved registers. */ \
1529 while (fail_stack.frame < fail_stack.avail) \
1530 POP_FAILURE_REG_OR_COUNT (); \
1532 pat = POP_FAILURE_POINTER (); \
1533 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1534 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1536 /* If the saved string location is NULL, it came from an \
1537 on_failure_keep_string_jump opcode, and we want to throw away the \
1538 saved NULL, thus retaining our current position in the string. */ \
1539 str = POP_FAILURE_POINTER (); \
1540 DEBUG_PRINT (" Popping string %p: \"", str); \
1541 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1542 DEBUG_PRINT ("\"\n"); \
1544 fail_stack.frame = POP_FAILURE_INT (); \
1545 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1547 assert (fail_stack.avail >= 0); \
1548 assert (fail_stack.frame <= fail_stack.avail); \
1550 DEBUG_STATEMENT (nfailure_points_popped++); \
1551 } while (0) /* POP_FAILURE_POINT */
1555 /* Registers are set to a sentinel when they haven't yet matched. */
1556 #define REG_UNSET(e) ((e) == NULL)
1558 /* Subroutine declarations and macros for regex_compile. */
1560 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1561 #ifdef emacs
1562 bool posix_backtracking,
1563 const char *whitespace_regexp,
1564 #else
1565 reg_syntax_t syntax,
1566 #endif
1567 struct re_pattern_buffer *bufp);
1568 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1569 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1570 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1571 int arg, unsigned char *end);
1572 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1573 int arg1, int arg2, unsigned char *end);
1574 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1575 reg_syntax_t syntax);
1576 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1577 reg_syntax_t syntax);
1578 static re_char *skip_one_char (re_char *p);
1579 static int analyze_first (re_char *p, re_char *pend,
1580 char *fastmap, const int multibyte);
1582 /* Fetch the next character in the uncompiled pattern, with no
1583 translation. */
1584 #define PATFETCH(c) \
1585 do { \
1586 int len; \
1587 if (p == pend) return REG_EEND; \
1588 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1589 p += len; \
1590 } while (0)
1593 /* If `translate' is non-null, return translate[D], else just D. We
1594 cast the subscript to translate because some data is declared as
1595 `char *', to avoid warnings when a string constant is passed. But
1596 when we use a character as a subscript we must make it unsigned. */
1597 #ifndef TRANSLATE
1598 # define TRANSLATE(d) \
1599 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1600 #endif
1603 /* Macros for outputting the compiled pattern into `buffer'. */
1605 /* If the buffer isn't allocated when it comes in, use this. */
1606 #define INIT_BUF_SIZE 32
1608 /* Make sure we have at least N more bytes of space in buffer. */
1609 #define GET_BUFFER_SPACE(n) \
1610 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1611 EXTEND_BUFFER ()
1613 /* Make sure we have one more byte of buffer space and then add C to it. */
1614 #define BUF_PUSH(c) \
1615 do { \
1616 GET_BUFFER_SPACE (1); \
1617 *b++ = (unsigned char) (c); \
1618 } while (0)
1621 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1622 #define BUF_PUSH_2(c1, c2) \
1623 do { \
1624 GET_BUFFER_SPACE (2); \
1625 *b++ = (unsigned char) (c1); \
1626 *b++ = (unsigned char) (c2); \
1627 } while (0)
1630 /* Store a jump with opcode OP at LOC to location TO. We store a
1631 relative address offset by the three bytes the jump itself occupies. */
1632 #define STORE_JUMP(op, loc, to) \
1633 store_op1 (op, loc, (to) - (loc) - 3)
1635 /* Likewise, for a two-argument jump. */
1636 #define STORE_JUMP2(op, loc, to, arg) \
1637 store_op2 (op, loc, (to) - (loc) - 3, arg)
1639 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1640 #define INSERT_JUMP(op, loc, to) \
1641 insert_op1 (op, loc, (to) - (loc) - 3, b)
1643 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1644 #define INSERT_JUMP2(op, loc, to, arg) \
1645 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1648 /* This is not an arbitrary limit: the arguments which represent offsets
1649 into the pattern are two bytes long. So if 2^15 bytes turns out to
1650 be too small, many things would have to change. */
1651 # define MAX_BUF_SIZE (1L << 15)
1653 /* Extend the buffer by twice its current size via realloc and
1654 reset the pointers that pointed into the old block to point to the
1655 correct places in the new one. If extending the buffer results in it
1656 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1657 #if __BOUNDED_POINTERS__
1658 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1659 # define MOVE_BUFFER_POINTER(P) \
1660 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1661 SET_HIGH_BOUND (P), \
1662 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1663 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1664 else \
1666 SET_HIGH_BOUND (b); \
1667 SET_HIGH_BOUND (begalt); \
1668 if (fixup_alt_jump) \
1669 SET_HIGH_BOUND (fixup_alt_jump); \
1670 if (laststart) \
1671 SET_HIGH_BOUND (laststart); \
1672 if (pending_exact) \
1673 SET_HIGH_BOUND (pending_exact); \
1675 #else
1676 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1677 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1678 #endif
1679 #define EXTEND_BUFFER() \
1680 do { \
1681 unsigned char *old_buffer = bufp->buffer; \
1682 if (bufp->allocated == MAX_BUF_SIZE) \
1683 return REG_ESIZE; \
1684 bufp->allocated <<= 1; \
1685 if (bufp->allocated > MAX_BUF_SIZE) \
1686 bufp->allocated = MAX_BUF_SIZE; \
1687 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1688 if (bufp->buffer == NULL) \
1689 return REG_ESPACE; \
1690 /* If the buffer moved, move all the pointers into it. */ \
1691 if (old_buffer != bufp->buffer) \
1693 unsigned char *new_buffer = bufp->buffer; \
1694 MOVE_BUFFER_POINTER (b); \
1695 MOVE_BUFFER_POINTER (begalt); \
1696 if (fixup_alt_jump) \
1697 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1698 if (laststart) \
1699 MOVE_BUFFER_POINTER (laststart); \
1700 if (pending_exact) \
1701 MOVE_BUFFER_POINTER (pending_exact); \
1703 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1704 } while (0)
1707 /* Since we have one byte reserved for the register number argument to
1708 {start,stop}_memory, the maximum number of groups we can report
1709 things about is what fits in that byte. */
1710 #define MAX_REGNUM 255
1712 /* But patterns can have more than `MAX_REGNUM' registers. We just
1713 ignore the excess. */
1714 typedef int regnum_t;
1717 /* Macros for the compile stack. */
1719 /* Since offsets can go either forwards or backwards, this type needs to
1720 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1721 /* int may be not enough when sizeof(int) == 2. */
1722 typedef long pattern_offset_t;
1724 typedef struct
1726 pattern_offset_t begalt_offset;
1727 pattern_offset_t fixup_alt_jump;
1728 pattern_offset_t laststart_offset;
1729 regnum_t regnum;
1730 } compile_stack_elt_t;
1733 typedef struct
1735 compile_stack_elt_t *stack;
1736 size_t size;
1737 size_t avail; /* Offset of next open position. */
1738 } compile_stack_type;
1741 #define INIT_COMPILE_STACK_SIZE 32
1743 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1744 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1746 /* The next available element. */
1747 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1749 /* Explicit quit checking is needed for Emacs, which uses polling to
1750 process input events. */
1751 #ifdef emacs
1752 # define IMMEDIATE_QUIT_CHECK \
1753 do { \
1754 if (immediate_quit) QUIT; \
1755 } while (0)
1756 #else
1757 # define IMMEDIATE_QUIT_CHECK ((void)0)
1758 #endif
1760 /* Structure to manage work area for range table. */
1761 struct range_table_work_area
1763 int *table; /* actual work area. */
1764 int allocated; /* allocated size for work area in bytes. */
1765 int used; /* actually used size in words. */
1766 int bits; /* flag to record character classes */
1769 #ifdef emacs
1771 /* Make sure that WORK_AREA can hold more N multibyte characters.
1772 This is used only in set_image_of_range and set_image_of_range_1.
1773 It expects WORK_AREA to be a pointer.
1774 If it can't get the space, it returns from the surrounding function. */
1776 #define EXTEND_RANGE_TABLE(work_area, n) \
1777 do { \
1778 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1780 extend_range_table_work_area (&work_area); \
1781 if ((work_area).table == 0) \
1782 return (REG_ESPACE); \
1784 } while (0)
1786 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1787 (work_area).bits |= (bit)
1789 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1790 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1791 do { \
1792 EXTEND_RANGE_TABLE ((work_area), 2); \
1793 (work_area).table[(work_area).used++] = (range_start); \
1794 (work_area).table[(work_area).used++] = (range_end); \
1795 } while (0)
1797 #endif /* emacs */
1799 /* Free allocated memory for WORK_AREA. */
1800 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1801 do { \
1802 if ((work_area).table) \
1803 free ((work_area).table); \
1804 } while (0)
1806 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1807 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1808 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1809 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1811 /* Bits used to implement the multibyte-part of the various character classes
1812 such as [:alnum:] in a charset's range table. The code currently assumes
1813 that only the low 16 bits are used. */
1814 #define BIT_WORD 0x1
1815 #define BIT_LOWER 0x2
1816 #define BIT_PUNCT 0x4
1817 #define BIT_SPACE 0x8
1818 #define BIT_UPPER 0x10
1819 #define BIT_MULTIBYTE 0x20
1820 #define BIT_ALPHA 0x40
1821 #define BIT_ALNUM 0x80
1822 #define BIT_GRAPH 0x100
1823 #define BIT_PRINT 0x200
1826 /* Set the bit for character C in a list. */
1827 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1830 #ifdef emacs
1832 /* Store characters in the range FROM to TO in the bitmap at B (for
1833 ASCII and unibyte characters) and WORK_AREA (for multibyte
1834 characters) while translating them and paying attention to the
1835 continuity of translated characters.
1837 Implementation note: It is better to implement these fairly big
1838 macros by a function, but it's not that easy because macros called
1839 in this macro assume various local variables already declared. */
1841 /* Both FROM and TO are ASCII characters. */
1843 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1844 do { \
1845 int C0, C1; \
1847 for (C0 = (FROM); C0 <= (TO); C0++) \
1849 C1 = TRANSLATE (C0); \
1850 if (! ASCII_CHAR_P (C1)) \
1852 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1853 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1854 C1 = C0; \
1856 SET_LIST_BIT (C1); \
1858 } while (0)
1861 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1863 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1864 do { \
1865 int C0, C1, C2, I; \
1866 int USED = RANGE_TABLE_WORK_USED (work_area); \
1868 for (C0 = (FROM); C0 <= (TO); C0++) \
1870 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1871 if (CHAR_BYTE8_P (C1)) \
1872 SET_LIST_BIT (C0); \
1873 else \
1875 C2 = TRANSLATE (C1); \
1876 if (C2 == C1 \
1877 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1878 C1 = C0; \
1879 SET_LIST_BIT (C1); \
1880 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1882 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1883 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1885 if (C2 >= from - 1 && C2 <= to + 1) \
1887 if (C2 == from - 1) \
1888 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1889 else if (C2 == to + 1) \
1890 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1891 break; \
1894 if (I < USED) \
1895 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1898 } while (0)
1901 /* Both FROM and TO are multibyte characters. */
1903 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1904 do { \
1905 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1907 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1908 for (C0 = (FROM); C0 <= (TO); C0++) \
1910 C1 = TRANSLATE (C0); \
1911 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1912 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1913 SET_LIST_BIT (C2); \
1914 if (C1 >= (FROM) && C1 <= (TO)) \
1915 continue; \
1916 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1918 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1919 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1921 if (C1 >= from - 1 && C1 <= to + 1) \
1923 if (C1 == from - 1) \
1924 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1925 else if (C1 == to + 1) \
1926 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1927 break; \
1930 if (I < USED) \
1931 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1933 } while (0)
1935 #endif /* emacs */
1937 /* Get the next unsigned number in the uncompiled pattern. */
1938 #define GET_INTERVAL_COUNT(num) \
1939 do { \
1940 if (p == pend) \
1941 FREE_STACK_RETURN (REG_EBRACE); \
1942 else \
1944 PATFETCH (c); \
1945 while ('0' <= c && c <= '9') \
1947 if (num < 0) \
1948 num = 0; \
1949 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
1950 FREE_STACK_RETURN (REG_BADBR); \
1951 num = num * 10 + c - '0'; \
1952 if (p == pend) \
1953 FREE_STACK_RETURN (REG_EBRACE); \
1954 PATFETCH (c); \
1957 } while (0)
1959 #if ! WIDE_CHAR_SUPPORT
1961 /* Parse a character class, i.e. string such as "[:name:]". *strp
1962 points to the string to be parsed and limit is length, in bytes, of
1963 that string.
1965 If *strp point to a string that begins with "[:name:]", where name is
1966 a non-empty sequence of lower case letters, *strp will be advanced past the
1967 closing square bracket and RECC_* constant which maps to the name will be
1968 returned. If name is not a valid character class name zero, or RECC_ERROR,
1969 is returned.
1971 Otherwise, if *strp doesn’t begin with "[:name:]", -1 is returned.
1973 The function can be used on ASCII and multibyte (UTF-8-encoded) strings.
1975 re_wctype_t
1976 re_wctype_parse (const unsigned char **strp, unsigned limit)
1978 const char *beg = (const char *)*strp, *it;
1980 if (limit < 4 || beg[0] != '[' || beg[1] != ':')
1981 return -1;
1983 beg += 2; /* skip opening ‘[:’ */
1984 limit -= 3; /* opening ‘[:’ and half of closing ‘:]’; --limit handles rest */
1985 for (it = beg; it[0] != ':' || it[1] != ']'; ++it)
1986 if (!--limit)
1987 return -1;
1989 *strp = (const unsigned char *)(it + 2);
1991 /* Sort tests in the length=five case by frequency the classes to minimize
1992 number of times we fail the comparison. The frequencies of character class
1993 names used in Emacs sources as of 2016-07-27:
1995 $ find \( -name \*.c -o -name \*.el \) -exec grep -h '\[:[a-z]*:]' {} + |
1996 sed 's/]/]\n/g' |grep -o '\[:[a-z]*:]' |sort |uniq -c |sort -nr
1997 213 [:alnum:]
1998 104 [:alpha:]
1999 62 [:space:]
2000 39 [:digit:]
2001 36 [:blank:]
2002 26 [:word:]
2003 26 [:upper:]
2004 21 [:lower:]
2005 10 [:xdigit:]
2006 10 [:punct:]
2007 10 [:ascii:]
2008 4 [:nonascii:]
2009 4 [:graph:]
2010 2 [:print:]
2011 2 [:cntrl:]
2012 1 [:ff:]
2014 If you update this list, consider also updating chain of or’ed conditions
2015 in execute_charset function.
2018 switch (it - beg) {
2019 case 4:
2020 if (!memcmp (beg, "word", 4)) return RECC_WORD;
2021 break;
2022 case 5:
2023 if (!memcmp (beg, "alnum", 5)) return RECC_ALNUM;
2024 if (!memcmp (beg, "alpha", 5)) return RECC_ALPHA;
2025 if (!memcmp (beg, "space", 5)) return RECC_SPACE;
2026 if (!memcmp (beg, "digit", 5)) return RECC_DIGIT;
2027 if (!memcmp (beg, "blank", 5)) return RECC_BLANK;
2028 if (!memcmp (beg, "upper", 5)) return RECC_UPPER;
2029 if (!memcmp (beg, "lower", 5)) return RECC_LOWER;
2030 if (!memcmp (beg, "punct", 5)) return RECC_PUNCT;
2031 if (!memcmp (beg, "ascii", 5)) return RECC_ASCII;
2032 if (!memcmp (beg, "graph", 5)) return RECC_GRAPH;
2033 if (!memcmp (beg, "print", 5)) return RECC_PRINT;
2034 if (!memcmp (beg, "cntrl", 5)) return RECC_CNTRL;
2035 break;
2036 case 6:
2037 if (!memcmp (beg, "xdigit", 6)) return RECC_XDIGIT;
2038 break;
2039 case 7:
2040 if (!memcmp (beg, "unibyte", 7)) return RECC_UNIBYTE;
2041 break;
2042 case 8:
2043 if (!memcmp (beg, "nonascii", 8)) return RECC_NONASCII;
2044 break;
2045 case 9:
2046 if (!memcmp (beg, "multibyte", 9)) return RECC_MULTIBYTE;
2047 break;
2050 return RECC_ERROR;
2053 /* True if CH is in the char class CC. */
2054 boolean
2055 re_iswctype (int ch, re_wctype_t cc)
2057 switch (cc)
2059 case RECC_ALNUM: return ISALNUM (ch) != 0;
2060 case RECC_ALPHA: return ISALPHA (ch) != 0;
2061 case RECC_BLANK: return ISBLANK (ch) != 0;
2062 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2063 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2064 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2065 case RECC_LOWER: return ISLOWER (ch) != 0;
2066 case RECC_PRINT: return ISPRINT (ch) != 0;
2067 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2068 case RECC_SPACE: return ISSPACE (ch) != 0;
2069 case RECC_UPPER: return ISUPPER (ch) != 0;
2070 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2071 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2072 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2073 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2074 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2075 case RECC_WORD: return ISWORD (ch) != 0;
2076 case RECC_ERROR: return false;
2077 default:
2078 abort ();
2082 /* Return a bit-pattern to use in the range-table bits to match multibyte
2083 chars of class CC. */
2084 static int
2085 re_wctype_to_bit (re_wctype_t cc)
2087 switch (cc)
2089 case RECC_NONASCII:
2090 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2091 case RECC_ALPHA: return BIT_ALPHA;
2092 case RECC_ALNUM: return BIT_ALNUM;
2093 case RECC_WORD: return BIT_WORD;
2094 case RECC_LOWER: return BIT_LOWER;
2095 case RECC_UPPER: return BIT_UPPER;
2096 case RECC_PUNCT: return BIT_PUNCT;
2097 case RECC_SPACE: return BIT_SPACE;
2098 case RECC_GRAPH: return BIT_GRAPH;
2099 case RECC_PRINT: return BIT_PRINT;
2100 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2101 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2102 default:
2103 abort ();
2106 #endif
2108 /* Filling in the work area of a range. */
2110 /* Actually extend the space in WORK_AREA. */
2112 static void
2113 extend_range_table_work_area (struct range_table_work_area *work_area)
2115 work_area->allocated += 16 * sizeof (int);
2116 work_area->table = realloc (work_area->table, work_area->allocated);
2119 #if 0
2120 #ifdef emacs
2122 /* Carefully find the ranges of codes that are equivalent
2123 under case conversion to the range start..end when passed through
2124 TRANSLATE. Handle the case where non-letters can come in between
2125 two upper-case letters (which happens in Latin-1).
2126 Also handle the case of groups of more than 2 case-equivalent chars.
2128 The basic method is to look at consecutive characters and see
2129 if they can form a run that can be handled as one.
2131 Returns -1 if successful, REG_ESPACE if ran out of space. */
2133 static int
2134 set_image_of_range_1 (struct range_table_work_area *work_area,
2135 re_wchar_t start, re_wchar_t end,
2136 RE_TRANSLATE_TYPE translate)
2138 /* `one_case' indicates a character, or a run of characters,
2139 each of which is an isolate (no case-equivalents).
2140 This includes all ASCII non-letters.
2142 `two_case' indicates a character, or a run of characters,
2143 each of which has two case-equivalent forms.
2144 This includes all ASCII letters.
2146 `strange' indicates a character that has more than one
2147 case-equivalent. */
2149 enum case_type {one_case, two_case, strange};
2151 /* Describe the run that is in progress,
2152 which the next character can try to extend.
2153 If run_type is strange, that means there really is no run.
2154 If run_type is one_case, then run_start...run_end is the run.
2155 If run_type is two_case, then the run is run_start...run_end,
2156 and the case-equivalents end at run_eqv_end. */
2158 enum case_type run_type = strange;
2159 int run_start, run_end, run_eqv_end;
2161 Lisp_Object eqv_table;
2163 if (!RE_TRANSLATE_P (translate))
2165 EXTEND_RANGE_TABLE (work_area, 2);
2166 work_area->table[work_area->used++] = (start);
2167 work_area->table[work_area->used++] = (end);
2168 return -1;
2171 eqv_table = XCHAR_TABLE (translate)->extras[2];
2173 for (; start <= end; start++)
2175 enum case_type this_type;
2176 int eqv = RE_TRANSLATE (eqv_table, start);
2177 int minchar, maxchar;
2179 /* Classify this character */
2180 if (eqv == start)
2181 this_type = one_case;
2182 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2183 this_type = two_case;
2184 else
2185 this_type = strange;
2187 if (start < eqv)
2188 minchar = start, maxchar = eqv;
2189 else
2190 minchar = eqv, maxchar = start;
2192 /* Can this character extend the run in progress? */
2193 if (this_type == strange || this_type != run_type
2194 || !(minchar == run_end + 1
2195 && (run_type == two_case
2196 ? maxchar == run_eqv_end + 1 : 1)))
2198 /* No, end the run.
2199 Record each of its equivalent ranges. */
2200 if (run_type == one_case)
2202 EXTEND_RANGE_TABLE (work_area, 2);
2203 work_area->table[work_area->used++] = run_start;
2204 work_area->table[work_area->used++] = run_end;
2206 else if (run_type == two_case)
2208 EXTEND_RANGE_TABLE (work_area, 4);
2209 work_area->table[work_area->used++] = run_start;
2210 work_area->table[work_area->used++] = run_end;
2211 work_area->table[work_area->used++]
2212 = RE_TRANSLATE (eqv_table, run_start);
2213 work_area->table[work_area->used++]
2214 = RE_TRANSLATE (eqv_table, run_end);
2216 run_type = strange;
2219 if (this_type == strange)
2221 /* For a strange character, add each of its equivalents, one
2222 by one. Don't start a range. */
2225 EXTEND_RANGE_TABLE (work_area, 2);
2226 work_area->table[work_area->used++] = eqv;
2227 work_area->table[work_area->used++] = eqv;
2228 eqv = RE_TRANSLATE (eqv_table, eqv);
2230 while (eqv != start);
2233 /* Add this char to the run, or start a new run. */
2234 else if (run_type == strange)
2236 /* Initialize a new range. */
2237 run_type = this_type;
2238 run_start = start;
2239 run_end = start;
2240 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2242 else
2244 /* Extend a running range. */
2245 run_end = minchar;
2246 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2250 /* If a run is still in progress at the end, finish it now
2251 by recording its equivalent ranges. */
2252 if (run_type == one_case)
2254 EXTEND_RANGE_TABLE (work_area, 2);
2255 work_area->table[work_area->used++] = run_start;
2256 work_area->table[work_area->used++] = run_end;
2258 else if (run_type == two_case)
2260 EXTEND_RANGE_TABLE (work_area, 4);
2261 work_area->table[work_area->used++] = run_start;
2262 work_area->table[work_area->used++] = run_end;
2263 work_area->table[work_area->used++]
2264 = RE_TRANSLATE (eqv_table, run_start);
2265 work_area->table[work_area->used++]
2266 = RE_TRANSLATE (eqv_table, run_end);
2269 return -1;
2272 #endif /* emacs */
2274 /* Record the image of the range start..end when passed through
2275 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2276 and is not even necessarily contiguous.
2277 Normally we approximate it with the smallest contiguous range that contains
2278 all the chars we need. However, for Latin-1 we go to extra effort
2279 to do a better job.
2281 This function is not called for ASCII ranges.
2283 Returns -1 if successful, REG_ESPACE if ran out of space. */
2285 static int
2286 set_image_of_range (struct range_table_work_area *work_area,
2287 re_wchar_t start, re_wchar_t end,
2288 RE_TRANSLATE_TYPE translate)
2290 re_wchar_t cmin, cmax;
2292 #ifdef emacs
2293 /* For Latin-1 ranges, use set_image_of_range_1
2294 to get proper handling of ranges that include letters and nonletters.
2295 For a range that includes the whole of Latin-1, this is not necessary.
2296 For other character sets, we don't bother to get this right. */
2297 if (RE_TRANSLATE_P (translate) && start < 04400
2298 && !(start < 04200 && end >= 04377))
2300 int newend;
2301 int tem;
2302 newend = end;
2303 if (newend > 04377)
2304 newend = 04377;
2305 tem = set_image_of_range_1 (work_area, start, newend, translate);
2306 if (tem > 0)
2307 return tem;
2309 start = 04400;
2310 if (end < 04400)
2311 return -1;
2313 #endif
2315 EXTEND_RANGE_TABLE (work_area, 2);
2316 work_area->table[work_area->used++] = (start);
2317 work_area->table[work_area->used++] = (end);
2319 cmin = -1, cmax = -1;
2321 if (RE_TRANSLATE_P (translate))
2323 int ch;
2325 for (ch = start; ch <= end; ch++)
2327 re_wchar_t c = TRANSLATE (ch);
2328 if (! (start <= c && c <= end))
2330 if (cmin == -1)
2331 cmin = c, cmax = c;
2332 else
2334 cmin = min (cmin, c);
2335 cmax = max (cmax, c);
2340 if (cmin != -1)
2342 EXTEND_RANGE_TABLE (work_area, 2);
2343 work_area->table[work_area->used++] = (cmin);
2344 work_area->table[work_area->used++] = (cmax);
2348 return -1;
2350 #endif /* 0 */
2352 #ifndef MATCH_MAY_ALLOCATE
2354 /* If we cannot allocate large objects within re_match_2_internal,
2355 we make the fail stack and register vectors global.
2356 The fail stack, we grow to the maximum size when a regexp
2357 is compiled.
2358 The register vectors, we adjust in size each time we
2359 compile a regexp, according to the number of registers it needs. */
2361 static fail_stack_type fail_stack;
2363 /* Size with which the following vectors are currently allocated.
2364 That is so we can make them bigger as needed,
2365 but never make them smaller. */
2366 static int regs_allocated_size;
2368 static re_char ** regstart, ** regend;
2369 static re_char **best_regstart, **best_regend;
2371 /* Make the register vectors big enough for NUM_REGS registers,
2372 but don't make them smaller. */
2374 static
2375 regex_grow_registers (int num_regs)
2377 if (num_regs > regs_allocated_size)
2379 RETALLOC_IF (regstart, num_regs, re_char *);
2380 RETALLOC_IF (regend, num_regs, re_char *);
2381 RETALLOC_IF (best_regstart, num_regs, re_char *);
2382 RETALLOC_IF (best_regend, num_regs, re_char *);
2384 regs_allocated_size = num_regs;
2388 #endif /* not MATCH_MAY_ALLOCATE */
2390 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2391 regnum_t regnum);
2393 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2394 Returns one of error codes defined in `regex.h', or zero for success.
2396 If WHITESPACE_REGEXP is given (only #ifdef emacs), it is used instead of
2397 a space character in PATTERN.
2399 Assumes the `allocated' (and perhaps `buffer') and `translate'
2400 fields are set in BUFP on entry.
2402 If it succeeds, results are put in BUFP (if it returns an error, the
2403 contents of BUFP are undefined):
2404 `buffer' is the compiled pattern;
2405 `syntax' is set to SYNTAX;
2406 `used' is set to the length of the compiled pattern;
2407 `fastmap_accurate' is zero;
2408 `re_nsub' is the number of subexpressions in PATTERN;
2409 `not_bol' and `not_eol' are zero;
2411 The `fastmap' field is neither examined nor set. */
2413 /* Insert the `jump' from the end of last alternative to "here".
2414 The space for the jump has already been allocated. */
2415 #define FIXUP_ALT_JUMP() \
2416 do { \
2417 if (fixup_alt_jump) \
2418 STORE_JUMP (jump, fixup_alt_jump, b); \
2419 } while (0)
2422 /* Return, freeing storage we allocated. */
2423 #define FREE_STACK_RETURN(value) \
2424 do { \
2425 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2426 free (compile_stack.stack); \
2427 return value; \
2428 } while (0)
2430 static reg_errcode_t
2431 regex_compile (const_re_char *pattern, size_t size,
2432 #ifdef emacs
2433 # define syntax RE_SYNTAX_EMACS
2434 bool posix_backtracking,
2435 const char *whitespace_regexp,
2436 #else
2437 reg_syntax_t syntax,
2438 # define posix_backtracking (!(syntax & RE_NO_POSIX_BACKTRACKING))
2439 #endif
2440 struct re_pattern_buffer *bufp)
2442 /* We fetch characters from PATTERN here. */
2443 register re_wchar_t c, c1;
2445 /* Points to the end of the buffer, where we should append. */
2446 register unsigned char *b;
2448 /* Keeps track of unclosed groups. */
2449 compile_stack_type compile_stack;
2451 /* Points to the current (ending) position in the pattern. */
2452 #ifdef AIX
2453 /* `const' makes AIX compiler fail. */
2454 unsigned char *p = pattern;
2455 #else
2456 re_char *p = pattern;
2457 #endif
2458 re_char *pend = pattern + size;
2460 /* How to translate the characters in the pattern. */
2461 RE_TRANSLATE_TYPE translate = bufp->translate;
2463 /* Address of the count-byte of the most recently inserted `exactn'
2464 command. This makes it possible to tell if a new exact-match
2465 character can be added to that command or if the character requires
2466 a new `exactn' command. */
2467 unsigned char *pending_exact = 0;
2469 /* Address of start of the most recently finished expression.
2470 This tells, e.g., postfix * where to find the start of its
2471 operand. Reset at the beginning of groups and alternatives. */
2472 unsigned char *laststart = 0;
2474 /* Address of beginning of regexp, or inside of last group. */
2475 unsigned char *begalt;
2477 /* Place in the uncompiled pattern (i.e., the {) to
2478 which to go back if the interval is invalid. */
2479 re_char *beg_interval;
2481 /* Address of the place where a forward jump should go to the end of
2482 the containing expression. Each alternative of an `or' -- except the
2483 last -- ends with a forward jump of this sort. */
2484 unsigned char *fixup_alt_jump = 0;
2486 /* Work area for range table of charset. */
2487 struct range_table_work_area range_table_work;
2489 /* If the object matched can contain multibyte characters. */
2490 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2492 #ifdef emacs
2493 /* Nonzero if we have pushed down into a subpattern. */
2494 int in_subpattern = 0;
2496 /* These hold the values of p, pattern, and pend from the main
2497 pattern when we have pushed into a subpattern. */
2498 re_char *main_p;
2499 re_char *main_pattern;
2500 re_char *main_pend;
2501 #endif
2503 #ifdef DEBUG
2504 debug++;
2505 DEBUG_PRINT ("\nCompiling pattern: ");
2506 if (debug > 0)
2508 unsigned debug_count;
2510 for (debug_count = 0; debug_count < size; debug_count++)
2511 putchar (pattern[debug_count]);
2512 putchar ('\n');
2514 #endif /* DEBUG */
2516 /* Initialize the compile stack. */
2517 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2518 if (compile_stack.stack == NULL)
2519 return REG_ESPACE;
2521 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2522 compile_stack.avail = 0;
2524 range_table_work.table = 0;
2525 range_table_work.allocated = 0;
2527 /* Initialize the pattern buffer. */
2528 #ifndef emacs
2529 bufp->syntax = syntax;
2530 #endif
2531 bufp->fastmap_accurate = 0;
2532 bufp->not_bol = bufp->not_eol = 0;
2533 bufp->used_syntax = 0;
2535 /* Set `used' to zero, so that if we return an error, the pattern
2536 printer (for debugging) will think there's no pattern. We reset it
2537 at the end. */
2538 bufp->used = 0;
2540 /* Always count groups, whether or not bufp->no_sub is set. */
2541 bufp->re_nsub = 0;
2543 #if !defined emacs && !defined SYNTAX_TABLE
2544 /* Initialize the syntax table. */
2545 init_syntax_once ();
2546 #endif
2548 if (bufp->allocated == 0)
2550 if (bufp->buffer)
2551 { /* If zero allocated, but buffer is non-null, try to realloc
2552 enough space. This loses if buffer's address is bogus, but
2553 that is the user's responsibility. */
2554 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2556 else
2557 { /* Caller did not allocate a buffer. Do it for them. */
2558 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2560 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2562 bufp->allocated = INIT_BUF_SIZE;
2565 begalt = b = bufp->buffer;
2567 /* Loop through the uncompiled pattern until we're at the end. */
2568 while (1)
2570 if (p == pend)
2572 #ifdef emacs
2573 /* If this is the end of an included regexp,
2574 pop back to the main regexp and try again. */
2575 if (in_subpattern)
2577 in_subpattern = 0;
2578 pattern = main_pattern;
2579 p = main_p;
2580 pend = main_pend;
2581 continue;
2583 #endif
2584 /* If this is the end of the main regexp, we are done. */
2585 break;
2588 PATFETCH (c);
2590 switch (c)
2592 #ifdef emacs
2593 case ' ':
2595 re_char *p1 = p;
2597 /* If there's no special whitespace regexp, treat
2598 spaces normally. And don't try to do this recursively. */
2599 if (!whitespace_regexp || in_subpattern)
2600 goto normal_char;
2602 /* Peek past following spaces. */
2603 while (p1 != pend)
2605 if (*p1 != ' ')
2606 break;
2607 p1++;
2609 /* If the spaces are followed by a repetition op,
2610 treat them normally. */
2611 if (p1 != pend
2612 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2613 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2614 goto normal_char;
2616 /* Replace the spaces with the whitespace regexp. */
2617 in_subpattern = 1;
2618 main_p = p1;
2619 main_pend = pend;
2620 main_pattern = pattern;
2621 p = pattern = (re_char *) whitespace_regexp;
2622 pend = p + strlen (whitespace_regexp);
2623 break;
2625 #endif
2627 case '^':
2629 if ( /* If at start of pattern, it's an operator. */
2630 p == pattern + 1
2631 /* If context independent, it's an operator. */
2632 || syntax & RE_CONTEXT_INDEP_ANCHORS
2633 /* Otherwise, depends on what's come before. */
2634 || at_begline_loc_p (pattern, p, syntax))
2635 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2636 else
2637 goto normal_char;
2639 break;
2642 case '$':
2644 if ( /* If at end of pattern, it's an operator. */
2645 p == pend
2646 /* If context independent, it's an operator. */
2647 || syntax & RE_CONTEXT_INDEP_ANCHORS
2648 /* Otherwise, depends on what's next. */
2649 || at_endline_loc_p (p, pend, syntax))
2650 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2651 else
2652 goto normal_char;
2654 break;
2657 case '+':
2658 case '?':
2659 if ((syntax & RE_BK_PLUS_QM)
2660 || (syntax & RE_LIMITED_OPS))
2661 goto normal_char;
2662 handle_plus:
2663 case '*':
2664 /* If there is no previous pattern... */
2665 if (!laststart)
2667 if (syntax & RE_CONTEXT_INVALID_OPS)
2668 FREE_STACK_RETURN (REG_BADRPT);
2669 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2670 goto normal_char;
2674 /* 1 means zero (many) matches is allowed. */
2675 boolean zero_times_ok = 0, many_times_ok = 0;
2676 boolean greedy = 1;
2678 /* If there is a sequence of repetition chars, collapse it
2679 down to just one (the right one). We can't combine
2680 interval operators with these because of, e.g., `a{2}*',
2681 which should only match an even number of `a's. */
2683 for (;;)
2685 if ((syntax & RE_FRUGAL)
2686 && c == '?' && (zero_times_ok || many_times_ok))
2687 greedy = 0;
2688 else
2690 zero_times_ok |= c != '+';
2691 many_times_ok |= c != '?';
2694 if (p == pend)
2695 break;
2696 else if (*p == '*'
2697 || (!(syntax & RE_BK_PLUS_QM)
2698 && (*p == '+' || *p == '?')))
2700 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2702 if (p+1 == pend)
2703 FREE_STACK_RETURN (REG_EESCAPE);
2704 if (p[1] == '+' || p[1] == '?')
2705 PATFETCH (c); /* Gobble up the backslash. */
2706 else
2707 break;
2709 else
2710 break;
2711 /* If we get here, we found another repeat character. */
2712 PATFETCH (c);
2715 /* Star, etc. applied to an empty pattern is equivalent
2716 to an empty pattern. */
2717 if (!laststart || laststart == b)
2718 break;
2720 /* Now we know whether or not zero matches is allowed
2721 and also whether or not two or more matches is allowed. */
2722 if (greedy)
2724 if (many_times_ok)
2726 boolean simple = skip_one_char (laststart) == b;
2727 size_t startoffset = 0;
2728 re_opcode_t ofj =
2729 /* Check if the loop can match the empty string. */
2730 (simple || !analyze_first (laststart, b, NULL, 0))
2731 ? on_failure_jump : on_failure_jump_loop;
2732 assert (skip_one_char (laststart) <= b);
2734 if (!zero_times_ok && simple)
2735 { /* Since simple * loops can be made faster by using
2736 on_failure_keep_string_jump, we turn simple P+
2737 into PP* if P is simple. */
2738 unsigned char *p1, *p2;
2739 startoffset = b - laststart;
2740 GET_BUFFER_SPACE (startoffset);
2741 p1 = b; p2 = laststart;
2742 while (p2 < p1)
2743 *b++ = *p2++;
2744 zero_times_ok = 1;
2747 GET_BUFFER_SPACE (6);
2748 if (!zero_times_ok)
2749 /* A + loop. */
2750 STORE_JUMP (ofj, b, b + 6);
2751 else
2752 /* Simple * loops can use on_failure_keep_string_jump
2753 depending on what follows. But since we don't know
2754 that yet, we leave the decision up to
2755 on_failure_jump_smart. */
2756 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2757 laststart + startoffset, b + 6);
2758 b += 3;
2759 STORE_JUMP (jump, b, laststart + startoffset);
2760 b += 3;
2762 else
2764 /* A simple ? pattern. */
2765 assert (zero_times_ok);
2766 GET_BUFFER_SPACE (3);
2767 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2768 b += 3;
2771 else /* not greedy */
2772 { /* I wish the greedy and non-greedy cases could be merged. */
2774 GET_BUFFER_SPACE (7); /* We might use less. */
2775 if (many_times_ok)
2777 boolean emptyp = analyze_first (laststart, b, NULL, 0);
2779 /* The non-greedy multiple match looks like
2780 a repeat..until: we only need a conditional jump
2781 at the end of the loop. */
2782 if (emptyp) BUF_PUSH (no_op);
2783 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2784 : on_failure_jump, b, laststart);
2785 b += 3;
2786 if (zero_times_ok)
2788 /* The repeat...until naturally matches one or more.
2789 To also match zero times, we need to first jump to
2790 the end of the loop (its conditional jump). */
2791 INSERT_JUMP (jump, laststart, b);
2792 b += 3;
2795 else
2797 /* non-greedy a?? */
2798 INSERT_JUMP (jump, laststart, b + 3);
2799 b += 3;
2800 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2801 b += 3;
2805 pending_exact = 0;
2806 break;
2809 case '.':
2810 laststart = b;
2811 BUF_PUSH (anychar);
2812 break;
2815 case '[':
2817 re_char *p1;
2819 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2821 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2823 /* Ensure that we have enough space to push a charset: the
2824 opcode, the length count, and the bitset; 34 bytes in all. */
2825 GET_BUFFER_SPACE (34);
2827 laststart = b;
2829 /* We test `*p == '^' twice, instead of using an if
2830 statement, so we only need one BUF_PUSH. */
2831 BUF_PUSH (*p == '^' ? charset_not : charset);
2832 if (*p == '^')
2833 p++;
2835 /* Remember the first position in the bracket expression. */
2836 p1 = p;
2838 /* Push the number of bytes in the bitmap. */
2839 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2841 /* Clear the whole map. */
2842 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2844 /* charset_not matches newline according to a syntax bit. */
2845 if ((re_opcode_t) b[-2] == charset_not
2846 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2847 SET_LIST_BIT ('\n');
2849 /* Read in characters and ranges, setting map bits. */
2850 for (;;)
2852 boolean escaped_char = false;
2853 const unsigned char *p2 = p;
2854 re_wctype_t cc;
2855 re_wchar_t ch;
2857 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2859 /* See if we're at the beginning of a possible character
2860 class. */
2861 if (syntax & RE_CHAR_CLASSES &&
2862 (cc = re_wctype_parse(&p, pend - p)) != -1)
2864 if (cc == 0)
2865 FREE_STACK_RETURN (REG_ECTYPE);
2867 if (p == pend)
2868 FREE_STACK_RETURN (REG_EBRACK);
2870 #ifndef emacs
2871 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2872 if (re_iswctype (btowc (ch), cc))
2874 c = TRANSLATE (ch);
2875 if (c < (1 << BYTEWIDTH))
2876 SET_LIST_BIT (c);
2878 #else /* emacs */
2879 /* Most character classes in a multibyte match just set
2880 a flag. Exceptions are is_blank, is_digit, is_cntrl, and
2881 is_xdigit, since they can only match ASCII characters.
2882 We don't need to handle them for multibyte. */
2884 /* Setup the gl_state object to its buffer-defined value.
2885 This hardcodes the buffer-global syntax-table for ASCII
2886 chars, while the other chars will obey syntax-table
2887 properties. It's not ideal, but it's the way it's been
2888 done until now. */
2889 SETUP_BUFFER_SYNTAX_TABLE ();
2891 for (c = 0; c < 0x80; ++c)
2892 if (re_iswctype (c, cc))
2894 SET_LIST_BIT (c);
2895 c1 = TRANSLATE (c);
2896 if (c1 == c)
2897 continue;
2898 if (ASCII_CHAR_P (c1))
2899 SET_LIST_BIT (c1);
2900 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2901 SET_LIST_BIT (c1);
2903 SET_RANGE_TABLE_WORK_AREA_BIT
2904 (range_table_work, re_wctype_to_bit (cc));
2905 #endif /* emacs */
2906 /* In most cases the matching rule for char classes only
2907 uses the syntax table for multibyte chars, so that the
2908 content of the syntax-table is not hardcoded in the
2909 range_table. SPACE and WORD are the two exceptions. */
2910 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2911 bufp->used_syntax = 1;
2913 /* Repeat the loop. */
2914 continue;
2917 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2918 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2919 So the translation is done later in a loop. Example:
2920 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2921 PATFETCH (c);
2923 /* \ might escape characters inside [...] and [^...]. */
2924 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2926 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2928 PATFETCH (c);
2929 escaped_char = true;
2931 else
2933 /* Could be the end of the bracket expression. If it's
2934 not (i.e., when the bracket expression is `[]' so
2935 far), the ']' character bit gets set way below. */
2936 if (c == ']' && p2 != p1)
2937 break;
2940 if (p < pend && p[0] == '-' && p[1] != ']')
2943 /* Discard the `-'. */
2944 PATFETCH (c1);
2946 /* Fetch the character which ends the range. */
2947 PATFETCH (c1);
2948 #ifdef emacs
2949 if (CHAR_BYTE8_P (c1)
2950 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2951 /* Treat the range from a multibyte character to
2952 raw-byte character as empty. */
2953 c = c1 + 1;
2954 #endif /* emacs */
2956 else
2957 /* Range from C to C. */
2958 c1 = c;
2960 if (c > c1)
2962 if (syntax & RE_NO_EMPTY_RANGES)
2963 FREE_STACK_RETURN (REG_ERANGEX);
2964 /* Else, repeat the loop. */
2966 else
2968 #ifndef emacs
2969 /* Set the range into bitmap */
2970 for (; c <= c1; c++)
2972 ch = TRANSLATE (c);
2973 if (ch < (1 << BYTEWIDTH))
2974 SET_LIST_BIT (ch);
2976 #else /* emacs */
2977 if (c < 128)
2979 ch = min (127, c1);
2980 SETUP_ASCII_RANGE (range_table_work, c, ch);
2981 c = ch + 1;
2982 if (CHAR_BYTE8_P (c1))
2983 c = BYTE8_TO_CHAR (128);
2985 if (c <= c1)
2987 if (CHAR_BYTE8_P (c))
2989 c = CHAR_TO_BYTE8 (c);
2990 c1 = CHAR_TO_BYTE8 (c1);
2991 for (; c <= c1; c++)
2992 SET_LIST_BIT (c);
2994 else if (multibyte)
2996 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
2998 else
3000 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
3003 #endif /* emacs */
3007 /* Discard any (non)matching list bytes that are all 0 at the
3008 end of the map. Decrease the map-length byte too. */
3009 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3010 b[-1]--;
3011 b += b[-1];
3013 /* Build real range table from work area. */
3014 if (RANGE_TABLE_WORK_USED (range_table_work)
3015 || RANGE_TABLE_WORK_BITS (range_table_work))
3017 int i;
3018 int used = RANGE_TABLE_WORK_USED (range_table_work);
3020 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3021 bytes for flags, two for COUNT, and three bytes for
3022 each character. */
3023 GET_BUFFER_SPACE (4 + used * 3);
3025 /* Indicate the existence of range table. */
3026 laststart[1] |= 0x80;
3028 /* Store the character class flag bits into the range table.
3029 If not in emacs, these flag bits are always 0. */
3030 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3031 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3033 STORE_NUMBER_AND_INCR (b, used / 2);
3034 for (i = 0; i < used; i++)
3035 STORE_CHARACTER_AND_INCR
3036 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3039 break;
3042 case '(':
3043 if (syntax & RE_NO_BK_PARENS)
3044 goto handle_open;
3045 else
3046 goto normal_char;
3049 case ')':
3050 if (syntax & RE_NO_BK_PARENS)
3051 goto handle_close;
3052 else
3053 goto normal_char;
3056 case '\n':
3057 if (syntax & RE_NEWLINE_ALT)
3058 goto handle_alt;
3059 else
3060 goto normal_char;
3063 case '|':
3064 if (syntax & RE_NO_BK_VBAR)
3065 goto handle_alt;
3066 else
3067 goto normal_char;
3070 case '{':
3071 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3072 goto handle_interval;
3073 else
3074 goto normal_char;
3077 case '\\':
3078 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3080 /* Do not translate the character after the \, so that we can
3081 distinguish, e.g., \B from \b, even if we normally would
3082 translate, e.g., B to b. */
3083 PATFETCH (c);
3085 switch (c)
3087 case '(':
3088 if (syntax & RE_NO_BK_PARENS)
3089 goto normal_backslash;
3091 handle_open:
3093 int shy = 0;
3094 regnum_t regnum = 0;
3095 if (p+1 < pend)
3097 /* Look for a special (?...) construct */
3098 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3100 PATFETCH (c); /* Gobble up the '?'. */
3101 while (!shy)
3103 PATFETCH (c);
3104 switch (c)
3106 case ':': shy = 1; break;
3107 case '0':
3108 /* An explicitly specified regnum must start
3109 with non-0. */
3110 if (regnum == 0)
3111 FREE_STACK_RETURN (REG_BADPAT);
3112 case '1': case '2': case '3': case '4':
3113 case '5': case '6': case '7': case '8': case '9':
3114 regnum = 10*regnum + (c - '0'); break;
3115 default:
3116 /* Only (?:...) is supported right now. */
3117 FREE_STACK_RETURN (REG_BADPAT);
3123 if (!shy)
3124 regnum = ++bufp->re_nsub;
3125 else if (regnum)
3126 { /* It's actually not shy, but explicitly numbered. */
3127 shy = 0;
3128 if (regnum > bufp->re_nsub)
3129 bufp->re_nsub = regnum;
3130 else if (regnum > bufp->re_nsub
3131 /* Ideally, we'd want to check that the specified
3132 group can't have matched (i.e. all subgroups
3133 using the same regnum are in other branches of
3134 OR patterns), but we don't currently keep track
3135 of enough info to do that easily. */
3136 || group_in_compile_stack (compile_stack, regnum))
3137 FREE_STACK_RETURN (REG_BADPAT);
3139 else
3140 /* It's really shy. */
3141 regnum = - bufp->re_nsub;
3143 if (COMPILE_STACK_FULL)
3145 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3146 compile_stack_elt_t);
3147 if (compile_stack.stack == NULL) return REG_ESPACE;
3149 compile_stack.size <<= 1;
3152 /* These are the values to restore when we hit end of this
3153 group. They are all relative offsets, so that if the
3154 whole pattern moves because of realloc, they will still
3155 be valid. */
3156 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3157 COMPILE_STACK_TOP.fixup_alt_jump
3158 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3159 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3160 COMPILE_STACK_TOP.regnum = regnum;
3162 /* Do not push a start_memory for groups beyond the last one
3163 we can represent in the compiled pattern. */
3164 if (regnum <= MAX_REGNUM && regnum > 0)
3165 BUF_PUSH_2 (start_memory, regnum);
3167 compile_stack.avail++;
3169 fixup_alt_jump = 0;
3170 laststart = 0;
3171 begalt = b;
3172 /* If we've reached MAX_REGNUM groups, then this open
3173 won't actually generate any code, so we'll have to
3174 clear pending_exact explicitly. */
3175 pending_exact = 0;
3176 break;
3179 case ')':
3180 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3182 if (COMPILE_STACK_EMPTY)
3184 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3185 goto normal_backslash;
3186 else
3187 FREE_STACK_RETURN (REG_ERPAREN);
3190 handle_close:
3191 FIXUP_ALT_JUMP ();
3193 /* See similar code for backslashed left paren above. */
3194 if (COMPILE_STACK_EMPTY)
3196 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3197 goto normal_char;
3198 else
3199 FREE_STACK_RETURN (REG_ERPAREN);
3202 /* Since we just checked for an empty stack above, this
3203 ``can't happen''. */
3204 assert (compile_stack.avail != 0);
3206 /* We don't just want to restore into `regnum', because
3207 later groups should continue to be numbered higher,
3208 as in `(ab)c(de)' -- the second group is #2. */
3209 regnum_t regnum;
3211 compile_stack.avail--;
3212 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3213 fixup_alt_jump
3214 = COMPILE_STACK_TOP.fixup_alt_jump
3215 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3216 : 0;
3217 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3218 regnum = COMPILE_STACK_TOP.regnum;
3219 /* If we've reached MAX_REGNUM groups, then this open
3220 won't actually generate any code, so we'll have to
3221 clear pending_exact explicitly. */
3222 pending_exact = 0;
3224 /* We're at the end of the group, so now we know how many
3225 groups were inside this one. */
3226 if (regnum <= MAX_REGNUM && regnum > 0)
3227 BUF_PUSH_2 (stop_memory, regnum);
3229 break;
3232 case '|': /* `\|'. */
3233 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3234 goto normal_backslash;
3235 handle_alt:
3236 if (syntax & RE_LIMITED_OPS)
3237 goto normal_char;
3239 /* Insert before the previous alternative a jump which
3240 jumps to this alternative if the former fails. */
3241 GET_BUFFER_SPACE (3);
3242 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3243 pending_exact = 0;
3244 b += 3;
3246 /* The alternative before this one has a jump after it
3247 which gets executed if it gets matched. Adjust that
3248 jump so it will jump to this alternative's analogous
3249 jump (put in below, which in turn will jump to the next
3250 (if any) alternative's such jump, etc.). The last such
3251 jump jumps to the correct final destination. A picture:
3252 _____ _____
3253 | | | |
3254 | v | v
3255 a | b | c
3257 If we are at `b', then fixup_alt_jump right now points to a
3258 three-byte space after `a'. We'll put in the jump, set
3259 fixup_alt_jump to right after `b', and leave behind three
3260 bytes which we'll fill in when we get to after `c'. */
3262 FIXUP_ALT_JUMP ();
3264 /* Mark and leave space for a jump after this alternative,
3265 to be filled in later either by next alternative or
3266 when know we're at the end of a series of alternatives. */
3267 fixup_alt_jump = b;
3268 GET_BUFFER_SPACE (3);
3269 b += 3;
3271 laststart = 0;
3272 begalt = b;
3273 break;
3276 case '{':
3277 /* If \{ is a literal. */
3278 if (!(syntax & RE_INTERVALS)
3279 /* If we're at `\{' and it's not the open-interval
3280 operator. */
3281 || (syntax & RE_NO_BK_BRACES))
3282 goto normal_backslash;
3284 handle_interval:
3286 /* If got here, then the syntax allows intervals. */
3288 /* At least (most) this many matches must be made. */
3289 int lower_bound = 0, upper_bound = -1;
3291 beg_interval = p;
3293 GET_INTERVAL_COUNT (lower_bound);
3295 if (c == ',')
3296 GET_INTERVAL_COUNT (upper_bound);
3297 else
3298 /* Interval such as `{1}' => match exactly once. */
3299 upper_bound = lower_bound;
3301 if (lower_bound < 0
3302 || (0 <= upper_bound && upper_bound < lower_bound))
3303 FREE_STACK_RETURN (REG_BADBR);
3305 if (!(syntax & RE_NO_BK_BRACES))
3307 if (c != '\\')
3308 FREE_STACK_RETURN (REG_BADBR);
3309 if (p == pend)
3310 FREE_STACK_RETURN (REG_EESCAPE);
3311 PATFETCH (c);
3314 if (c != '}')
3315 FREE_STACK_RETURN (REG_BADBR);
3317 /* We just parsed a valid interval. */
3319 /* If it's invalid to have no preceding re. */
3320 if (!laststart)
3322 if (syntax & RE_CONTEXT_INVALID_OPS)
3323 FREE_STACK_RETURN (REG_BADRPT);
3324 else if (syntax & RE_CONTEXT_INDEP_OPS)
3325 laststart = b;
3326 else
3327 goto unfetch_interval;
3330 if (upper_bound == 0)
3331 /* If the upper bound is zero, just drop the sub pattern
3332 altogether. */
3333 b = laststart;
3334 else if (lower_bound == 1 && upper_bound == 1)
3335 /* Just match it once: nothing to do here. */
3338 /* Otherwise, we have a nontrivial interval. When
3339 we're all done, the pattern will look like:
3340 set_number_at <jump count> <upper bound>
3341 set_number_at <succeed_n count> <lower bound>
3342 succeed_n <after jump addr> <succeed_n count>
3343 <body of loop>
3344 jump_n <succeed_n addr> <jump count>
3345 (The upper bound and `jump_n' are omitted if
3346 `upper_bound' is 1, though.) */
3347 else
3348 { /* If the upper bound is > 1, we need to insert
3349 more at the end of the loop. */
3350 unsigned int nbytes = (upper_bound < 0 ? 3
3351 : upper_bound > 1 ? 5 : 0);
3352 unsigned int startoffset = 0;
3354 GET_BUFFER_SPACE (20); /* We might use less. */
3356 if (lower_bound == 0)
3358 /* A succeed_n that starts with 0 is really a
3359 a simple on_failure_jump_loop. */
3360 INSERT_JUMP (on_failure_jump_loop, laststart,
3361 b + 3 + nbytes);
3362 b += 3;
3364 else
3366 /* Initialize lower bound of the `succeed_n', even
3367 though it will be set during matching by its
3368 attendant `set_number_at' (inserted next),
3369 because `re_compile_fastmap' needs to know.
3370 Jump to the `jump_n' we might insert below. */
3371 INSERT_JUMP2 (succeed_n, laststart,
3372 b + 5 + nbytes,
3373 lower_bound);
3374 b += 5;
3376 /* Code to initialize the lower bound. Insert
3377 before the `succeed_n'. The `5' is the last two
3378 bytes of this `set_number_at', plus 3 bytes of
3379 the following `succeed_n'. */
3380 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3381 b += 5;
3382 startoffset += 5;
3385 if (upper_bound < 0)
3387 /* A negative upper bound stands for infinity,
3388 in which case it degenerates to a plain jump. */
3389 STORE_JUMP (jump, b, laststart + startoffset);
3390 b += 3;
3392 else if (upper_bound > 1)
3393 { /* More than one repetition is allowed, so
3394 append a backward jump to the `succeed_n'
3395 that starts this interval.
3397 When we've reached this during matching,
3398 we'll have matched the interval once, so
3399 jump back only `upper_bound - 1' times. */
3400 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3401 upper_bound - 1);
3402 b += 5;
3404 /* The location we want to set is the second
3405 parameter of the `jump_n'; that is `b-2' as
3406 an absolute address. `laststart' will be
3407 the `set_number_at' we're about to insert;
3408 `laststart+3' the number to set, the source
3409 for the relative address. But we are
3410 inserting into the middle of the pattern --
3411 so everything is getting moved up by 5.
3412 Conclusion: (b - 2) - (laststart + 3) + 5,
3413 i.e., b - laststart.
3415 We insert this at the beginning of the loop
3416 so that if we fail during matching, we'll
3417 reinitialize the bounds. */
3418 insert_op2 (set_number_at, laststart, b - laststart,
3419 upper_bound - 1, b);
3420 b += 5;
3423 pending_exact = 0;
3424 beg_interval = NULL;
3426 break;
3428 unfetch_interval:
3429 /* If an invalid interval, match the characters as literals. */
3430 assert (beg_interval);
3431 p = beg_interval;
3432 beg_interval = NULL;
3434 /* normal_char and normal_backslash need `c'. */
3435 c = '{';
3437 if (!(syntax & RE_NO_BK_BRACES))
3439 assert (p > pattern && p[-1] == '\\');
3440 goto normal_backslash;
3442 else
3443 goto normal_char;
3445 #ifdef emacs
3446 case '=':
3447 laststart = b;
3448 BUF_PUSH (at_dot);
3449 break;
3451 case 's':
3452 laststart = b;
3453 PATFETCH (c);
3454 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3455 break;
3457 case 'S':
3458 laststart = b;
3459 PATFETCH (c);
3460 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3461 break;
3463 case 'c':
3464 laststart = b;
3465 PATFETCH (c);
3466 BUF_PUSH_2 (categoryspec, c);
3467 break;
3469 case 'C':
3470 laststart = b;
3471 PATFETCH (c);
3472 BUF_PUSH_2 (notcategoryspec, c);
3473 break;
3474 #endif /* emacs */
3477 case 'w':
3478 if (syntax & RE_NO_GNU_OPS)
3479 goto normal_char;
3480 laststart = b;
3481 BUF_PUSH_2 (syntaxspec, Sword);
3482 break;
3485 case 'W':
3486 if (syntax & RE_NO_GNU_OPS)
3487 goto normal_char;
3488 laststart = b;
3489 BUF_PUSH_2 (notsyntaxspec, Sword);
3490 break;
3493 case '<':
3494 if (syntax & RE_NO_GNU_OPS)
3495 goto normal_char;
3496 laststart = b;
3497 BUF_PUSH (wordbeg);
3498 break;
3500 case '>':
3501 if (syntax & RE_NO_GNU_OPS)
3502 goto normal_char;
3503 laststart = b;
3504 BUF_PUSH (wordend);
3505 break;
3507 case '_':
3508 if (syntax & RE_NO_GNU_OPS)
3509 goto normal_char;
3510 laststart = b;
3511 PATFETCH (c);
3512 if (c == '<')
3513 BUF_PUSH (symbeg);
3514 else if (c == '>')
3515 BUF_PUSH (symend);
3516 else
3517 FREE_STACK_RETURN (REG_BADPAT);
3518 break;
3520 case 'b':
3521 if (syntax & RE_NO_GNU_OPS)
3522 goto normal_char;
3523 BUF_PUSH (wordbound);
3524 break;
3526 case 'B':
3527 if (syntax & RE_NO_GNU_OPS)
3528 goto normal_char;
3529 BUF_PUSH (notwordbound);
3530 break;
3532 case '`':
3533 if (syntax & RE_NO_GNU_OPS)
3534 goto normal_char;
3535 BUF_PUSH (begbuf);
3536 break;
3538 case '\'':
3539 if (syntax & RE_NO_GNU_OPS)
3540 goto normal_char;
3541 BUF_PUSH (endbuf);
3542 break;
3544 case '1': case '2': case '3': case '4': case '5':
3545 case '6': case '7': case '8': case '9':
3547 regnum_t reg;
3549 if (syntax & RE_NO_BK_REFS)
3550 goto normal_backslash;
3552 reg = c - '0';
3554 if (reg > bufp->re_nsub || reg < 1
3555 /* Can't back reference to a subexp before its end. */
3556 || group_in_compile_stack (compile_stack, reg))
3557 FREE_STACK_RETURN (REG_ESUBREG);
3559 laststart = b;
3560 BUF_PUSH_2 (duplicate, reg);
3562 break;
3565 case '+':
3566 case '?':
3567 if (syntax & RE_BK_PLUS_QM)
3568 goto handle_plus;
3569 else
3570 goto normal_backslash;
3572 default:
3573 normal_backslash:
3574 /* You might think it would be useful for \ to mean
3575 not to translate; but if we don't translate it
3576 it will never match anything. */
3577 goto normal_char;
3579 break;
3582 default:
3583 /* Expects the character in `c'. */
3584 normal_char:
3585 /* If no exactn currently being built. */
3586 if (!pending_exact
3588 /* If last exactn not at current position. */
3589 || pending_exact + *pending_exact + 1 != b
3591 /* We have only one byte following the exactn for the count. */
3592 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3594 /* If followed by a repetition operator. */
3595 || (p != pend && (*p == '*' || *p == '^'))
3596 || ((syntax & RE_BK_PLUS_QM)
3597 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3598 : p != pend && (*p == '+' || *p == '?'))
3599 || ((syntax & RE_INTERVALS)
3600 && ((syntax & RE_NO_BK_BRACES)
3601 ? p != pend && *p == '{'
3602 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3604 /* Start building a new exactn. */
3606 laststart = b;
3608 BUF_PUSH_2 (exactn, 0);
3609 pending_exact = b - 1;
3612 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3614 int len;
3616 if (multibyte)
3618 c = TRANSLATE (c);
3619 len = CHAR_STRING (c, b);
3620 b += len;
3622 else
3624 c1 = RE_CHAR_TO_MULTIBYTE (c);
3625 if (! CHAR_BYTE8_P (c1))
3627 re_wchar_t c2 = TRANSLATE (c1);
3629 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3630 c = c1;
3632 *b++ = c;
3633 len = 1;
3635 (*pending_exact) += len;
3638 break;
3639 } /* switch (c) */
3640 } /* while p != pend */
3643 /* Through the pattern now. */
3645 FIXUP_ALT_JUMP ();
3647 if (!COMPILE_STACK_EMPTY)
3648 FREE_STACK_RETURN (REG_EPAREN);
3650 /* If we don't want backtracking, force success
3651 the first time we reach the end of the compiled pattern. */
3652 if (!posix_backtracking)
3653 BUF_PUSH (succeed);
3655 /* We have succeeded; set the length of the buffer. */
3656 bufp->used = b - bufp->buffer;
3658 #ifdef DEBUG
3659 if (debug > 0)
3661 re_compile_fastmap (bufp);
3662 DEBUG_PRINT ("\nCompiled pattern: \n");
3663 print_compiled_pattern (bufp);
3665 debug--;
3666 #endif /* DEBUG */
3668 #ifndef MATCH_MAY_ALLOCATE
3669 /* Initialize the failure stack to the largest possible stack. This
3670 isn't necessary unless we're trying to avoid calling alloca in
3671 the search and match routines. */
3673 int num_regs = bufp->re_nsub + 1;
3675 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3677 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3678 falk_stack.stack = realloc (fail_stack.stack,
3679 fail_stack.size * sizeof *falk_stack.stack);
3682 regex_grow_registers (num_regs);
3684 #endif /* not MATCH_MAY_ALLOCATE */
3686 FREE_STACK_RETURN (REG_NOERROR);
3688 #ifdef emacs
3689 # undef syntax
3690 #else
3691 # undef posix_backtracking
3692 #endif
3693 } /* regex_compile */
3695 /* Subroutines for `regex_compile'. */
3697 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3699 static void
3700 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3702 *loc = (unsigned char) op;
3703 STORE_NUMBER (loc + 1, arg);
3707 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3709 static void
3710 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3712 *loc = (unsigned char) op;
3713 STORE_NUMBER (loc + 1, arg1);
3714 STORE_NUMBER (loc + 3, arg2);
3718 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3719 for OP followed by two-byte integer parameter ARG. */
3721 static void
3722 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3724 register unsigned char *pfrom = end;
3725 register unsigned char *pto = end + 3;
3727 while (pfrom != loc)
3728 *--pto = *--pfrom;
3730 store_op1 (op, loc, arg);
3734 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3736 static void
3737 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3739 register unsigned char *pfrom = end;
3740 register unsigned char *pto = end + 5;
3742 while (pfrom != loc)
3743 *--pto = *--pfrom;
3745 store_op2 (op, loc, arg1, arg2);
3749 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3750 after an alternative or a begin-subexpression. We assume there is at
3751 least one character before the ^. */
3753 static boolean
3754 at_begline_loc_p (const_re_char *pattern, const_re_char *p, reg_syntax_t syntax)
3756 re_char *prev = p - 2;
3757 boolean odd_backslashes;
3759 /* After a subexpression? */
3760 if (*prev == '(')
3761 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3763 /* After an alternative? */
3764 else if (*prev == '|')
3765 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3767 /* After a shy subexpression? */
3768 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3770 /* Skip over optional regnum. */
3771 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3772 --prev;
3774 if (!(prev - 2 >= pattern
3775 && prev[-1] == '?' && prev[-2] == '('))
3776 return false;
3777 prev -= 2;
3778 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3780 else
3781 return false;
3783 /* Count the number of preceding backslashes. */
3784 p = prev;
3785 while (prev - 1 >= pattern && prev[-1] == '\\')
3786 --prev;
3787 return (p - prev) & odd_backslashes;
3791 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3792 at least one character after the $, i.e., `P < PEND'. */
3794 static boolean
3795 at_endline_loc_p (const_re_char *p, const_re_char *pend, reg_syntax_t syntax)
3797 re_char *next = p;
3798 boolean next_backslash = *next == '\\';
3799 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3801 return
3802 /* Before a subexpression? */
3803 (syntax & RE_NO_BK_PARENS ? *next == ')'
3804 : next_backslash && next_next && *next_next == ')')
3805 /* Before an alternative? */
3806 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3807 : next_backslash && next_next && *next_next == '|');
3811 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3812 false if it's not. */
3814 static boolean
3815 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3817 ssize_t this_element;
3819 for (this_element = compile_stack.avail - 1;
3820 this_element >= 0;
3821 this_element--)
3822 if (compile_stack.stack[this_element].regnum == regnum)
3823 return true;
3825 return false;
3828 /* analyze_first.
3829 If fastmap is non-NULL, go through the pattern and fill fastmap
3830 with all the possible leading chars. If fastmap is NULL, don't
3831 bother filling it up (obviously) and only return whether the
3832 pattern could potentially match the empty string.
3834 Return 1 if p..pend might match the empty string.
3835 Return 0 if p..pend matches at least one char.
3836 Return -1 if fastmap was not updated accurately. */
3838 static int
3839 analyze_first (const_re_char *p, const_re_char *pend, char *fastmap,
3840 const int multibyte)
3842 int j, k;
3843 boolean not;
3845 /* If all elements for base leading-codes in fastmap is set, this
3846 flag is set true. */
3847 boolean match_any_multibyte_characters = false;
3849 assert (p);
3851 /* The loop below works as follows:
3852 - It has a working-list kept in the PATTERN_STACK and which basically
3853 starts by only containing a pointer to the first operation.
3854 - If the opcode we're looking at is a match against some set of
3855 chars, then we add those chars to the fastmap and go on to the
3856 next work element from the worklist (done via `break').
3857 - If the opcode is a control operator on the other hand, we either
3858 ignore it (if it's meaningless at this point, such as `start_memory')
3859 or execute it (if it's a jump). If the jump has several destinations
3860 (i.e. `on_failure_jump'), then we push the other destination onto the
3861 worklist.
3862 We guarantee termination by ignoring backward jumps (more or less),
3863 so that `p' is monotonically increasing. More to the point, we
3864 never set `p' (or push) anything `<= p1'. */
3866 while (p < pend)
3868 /* `p1' is used as a marker of how far back a `on_failure_jump'
3869 can go without being ignored. It is normally equal to `p'
3870 (which prevents any backward `on_failure_jump') except right
3871 after a plain `jump', to allow patterns such as:
3872 0: jump 10
3873 3..9: <body>
3874 10: on_failure_jump 3
3875 as used for the *? operator. */
3876 re_char *p1 = p;
3878 switch (*p++)
3880 case succeed:
3881 return 1;
3883 case duplicate:
3884 /* If the first character has to match a backreference, that means
3885 that the group was empty (since it already matched). Since this
3886 is the only case that interests us here, we can assume that the
3887 backreference must match the empty string. */
3888 p++;
3889 continue;
3892 /* Following are the cases which match a character. These end
3893 with `break'. */
3895 case exactn:
3896 if (fastmap)
3898 /* If multibyte is nonzero, the first byte of each
3899 character is an ASCII or a leading code. Otherwise,
3900 each byte is a character. Thus, this works in both
3901 cases. */
3902 fastmap[p[1]] = 1;
3903 if (! multibyte)
3905 /* For the case of matching this unibyte regex
3906 against multibyte, we must set a leading code of
3907 the corresponding multibyte character. */
3908 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3910 fastmap[CHAR_LEADING_CODE (c)] = 1;
3913 break;
3916 case anychar:
3917 /* We could put all the chars except for \n (and maybe \0)
3918 but we don't bother since it is generally not worth it. */
3919 if (!fastmap) break;
3920 return -1;
3923 case charset_not:
3924 if (!fastmap) break;
3926 /* Chars beyond end of bitmap are possible matches. */
3927 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3928 j < (1 << BYTEWIDTH); j++)
3929 fastmap[j] = 1;
3932 /* Fallthrough */
3933 case charset:
3934 if (!fastmap) break;
3935 not = (re_opcode_t) *(p - 1) == charset_not;
3936 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3937 j >= 0; j--)
3938 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3939 fastmap[j] = 1;
3941 #ifdef emacs
3942 if (/* Any leading code can possibly start a character
3943 which doesn't match the specified set of characters. */
3946 /* If we can match a character class, we can match any
3947 multibyte characters. */
3948 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3949 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3952 if (match_any_multibyte_characters == false)
3954 for (j = MIN_MULTIBYTE_LEADING_CODE;
3955 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3956 fastmap[j] = 1;
3957 match_any_multibyte_characters = true;
3961 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3962 && match_any_multibyte_characters == false)
3964 /* Set fastmap[I] to 1 where I is a leading code of each
3965 multibyte character in the range table. */
3966 int c, count;
3967 unsigned char lc1, lc2;
3969 /* Make P points the range table. `+ 2' is to skip flag
3970 bits for a character class. */
3971 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3973 /* Extract the number of ranges in range table into COUNT. */
3974 EXTRACT_NUMBER_AND_INCR (count, p);
3975 for (; count > 0; count--, p += 3)
3977 /* Extract the start and end of each range. */
3978 EXTRACT_CHARACTER (c, p);
3979 lc1 = CHAR_LEADING_CODE (c);
3980 p += 3;
3981 EXTRACT_CHARACTER (c, p);
3982 lc2 = CHAR_LEADING_CODE (c);
3983 for (j = lc1; j <= lc2; j++)
3984 fastmap[j] = 1;
3987 #endif
3988 break;
3990 case syntaxspec:
3991 case notsyntaxspec:
3992 if (!fastmap) break;
3993 #ifndef emacs
3994 not = (re_opcode_t)p[-1] == notsyntaxspec;
3995 k = *p++;
3996 for (j = 0; j < (1 << BYTEWIDTH); j++)
3997 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3998 fastmap[j] = 1;
3999 break;
4000 #else /* emacs */
4001 /* This match depends on text properties. These end with
4002 aborting optimizations. */
4003 return -1;
4005 case categoryspec:
4006 case notcategoryspec:
4007 if (!fastmap) break;
4008 not = (re_opcode_t)p[-1] == notcategoryspec;
4009 k = *p++;
4010 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4011 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4012 fastmap[j] = 1;
4014 /* Any leading code can possibly start a character which
4015 has or doesn't has the specified category. */
4016 if (match_any_multibyte_characters == false)
4018 for (j = MIN_MULTIBYTE_LEADING_CODE;
4019 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4020 fastmap[j] = 1;
4021 match_any_multibyte_characters = true;
4023 break;
4025 /* All cases after this match the empty string. These end with
4026 `continue'. */
4028 case at_dot:
4029 #endif /* !emacs */
4030 case no_op:
4031 case begline:
4032 case endline:
4033 case begbuf:
4034 case endbuf:
4035 case wordbound:
4036 case notwordbound:
4037 case wordbeg:
4038 case wordend:
4039 case symbeg:
4040 case symend:
4041 continue;
4044 case jump:
4045 EXTRACT_NUMBER_AND_INCR (j, p);
4046 if (j < 0)
4047 /* Backward jumps can only go back to code that we've already
4048 visited. `re_compile' should make sure this is true. */
4049 break;
4050 p += j;
4051 switch (*p)
4053 case on_failure_jump:
4054 case on_failure_keep_string_jump:
4055 case on_failure_jump_loop:
4056 case on_failure_jump_nastyloop:
4057 case on_failure_jump_smart:
4058 p++;
4059 break;
4060 default:
4061 continue;
4063 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4064 to jump back to "just after here". */
4065 /* Fallthrough */
4067 case on_failure_jump:
4068 case on_failure_keep_string_jump:
4069 case on_failure_jump_nastyloop:
4070 case on_failure_jump_loop:
4071 case on_failure_jump_smart:
4072 EXTRACT_NUMBER_AND_INCR (j, p);
4073 if (p + j <= p1)
4074 ; /* Backward jump to be ignored. */
4075 else
4076 { /* We have to look down both arms.
4077 We first go down the "straight" path so as to minimize
4078 stack usage when going through alternatives. */
4079 int r = analyze_first (p, pend, fastmap, multibyte);
4080 if (r) return r;
4081 p += j;
4083 continue;
4086 case jump_n:
4087 /* This code simply does not properly handle forward jump_n. */
4088 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4089 p += 4;
4090 /* jump_n can either jump or fall through. The (backward) jump
4091 case has already been handled, so we only need to look at the
4092 fallthrough case. */
4093 continue;
4095 case succeed_n:
4096 /* If N == 0, it should be an on_failure_jump_loop instead. */
4097 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4098 p += 4;
4099 /* We only care about one iteration of the loop, so we don't
4100 need to consider the case where this behaves like an
4101 on_failure_jump. */
4102 continue;
4105 case set_number_at:
4106 p += 4;
4107 continue;
4110 case start_memory:
4111 case stop_memory:
4112 p += 1;
4113 continue;
4116 default:
4117 abort (); /* We have listed all the cases. */
4118 } /* switch *p++ */
4120 /* Getting here means we have found the possible starting
4121 characters for one path of the pattern -- and that the empty
4122 string does not match. We need not follow this path further. */
4123 return 0;
4124 } /* while p */
4126 /* We reached the end without matching anything. */
4127 return 1;
4129 } /* analyze_first */
4131 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4132 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4133 characters can start a string that matches the pattern. This fastmap
4134 is used by re_search to skip quickly over impossible starting points.
4136 Character codes above (1 << BYTEWIDTH) are not represented in the
4137 fastmap, but the leading codes are represented. Thus, the fastmap
4138 indicates which character sets could start a match.
4140 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4141 area as BUFP->fastmap.
4143 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4144 the pattern buffer.
4146 Returns 0 if we succeed, -2 if an internal error. */
4149 re_compile_fastmap (struct re_pattern_buffer *bufp)
4151 char *fastmap = bufp->fastmap;
4152 int analysis;
4154 assert (fastmap && bufp->buffer);
4156 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4157 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4159 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4160 fastmap, RE_MULTIBYTE_P (bufp));
4161 bufp->can_be_null = (analysis != 0);
4162 return 0;
4163 } /* re_compile_fastmap */
4165 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4166 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4167 this memory for recording register information. STARTS and ENDS
4168 must be allocated using the malloc library routine, and must each
4169 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4171 If NUM_REGS == 0, then subsequent matches should allocate their own
4172 register data.
4174 Unless this function is called, the first search or match using
4175 PATTERN_BUFFER will allocate its own register data, without
4176 freeing the old data. */
4178 void
4179 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4181 if (num_regs)
4183 bufp->regs_allocated = REGS_REALLOCATE;
4184 regs->num_regs = num_regs;
4185 regs->start = starts;
4186 regs->end = ends;
4188 else
4190 bufp->regs_allocated = REGS_UNALLOCATED;
4191 regs->num_regs = 0;
4192 regs->start = regs->end = 0;
4195 WEAK_ALIAS (__re_set_registers, re_set_registers)
4197 /* Searching routines. */
4199 /* Like re_search_2, below, but only one string is specified, and
4200 doesn't let you say where to stop matching. */
4202 regoff_t
4203 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4204 ssize_t startpos, ssize_t range, struct re_registers *regs)
4206 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4207 regs, size);
4209 WEAK_ALIAS (__re_search, re_search)
4211 /* Head address of virtual concatenation of string. */
4212 #define HEAD_ADDR_VSTRING(P) \
4213 (((P) >= size1 ? string2 : string1))
4215 /* Address of POS in the concatenation of virtual string. */
4216 #define POS_ADDR_VSTRING(POS) \
4217 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4219 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4220 virtual concatenation of STRING1 and STRING2, starting first at index
4221 STARTPOS, then at STARTPOS + 1, and so on.
4223 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4225 RANGE is how far to scan while trying to match. RANGE = 0 means try
4226 only at STARTPOS; in general, the last start tried is STARTPOS +
4227 RANGE.
4229 In REGS, return the indices of the virtual concatenation of STRING1
4230 and STRING2 that matched the entire BUFP->buffer and its contained
4231 subexpressions.
4233 Do not consider matching one past the index STOP in the virtual
4234 concatenation of STRING1 and STRING2.
4236 We return either the position in the strings at which the match was
4237 found, -1 if no match, or -2 if error (such as failure
4238 stack overflow). */
4240 regoff_t
4241 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4242 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4243 struct re_registers *regs, ssize_t stop)
4245 regoff_t val;
4246 re_char *string1 = (re_char*) str1;
4247 re_char *string2 = (re_char*) str2;
4248 register char *fastmap = bufp->fastmap;
4249 register RE_TRANSLATE_TYPE translate = bufp->translate;
4250 size_t total_size = size1 + size2;
4251 ssize_t endpos = startpos + range;
4252 boolean anchored_start;
4253 /* Nonzero if we are searching multibyte string. */
4254 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4256 /* Check for out-of-range STARTPOS. */
4257 if (startpos < 0 || startpos > total_size)
4258 return -1;
4260 /* Fix up RANGE if it might eventually take us outside
4261 the virtual concatenation of STRING1 and STRING2.
4262 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4263 if (endpos < 0)
4264 range = 0 - startpos;
4265 else if (endpos > total_size)
4266 range = total_size - startpos;
4268 /* If the search isn't to be a backwards one, don't waste time in a
4269 search for a pattern anchored at beginning of buffer. */
4270 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4272 if (startpos > 0)
4273 return -1;
4274 else
4275 range = 0;
4278 #ifdef emacs
4279 /* In a forward search for something that starts with \=.
4280 don't keep searching past point. */
4281 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4283 range = PT_BYTE - BEGV_BYTE - startpos;
4284 if (range < 0)
4285 return -1;
4287 #endif /* emacs */
4289 /* Update the fastmap now if not correct already. */
4290 if (fastmap && !bufp->fastmap_accurate)
4291 re_compile_fastmap (bufp);
4293 /* See whether the pattern is anchored. */
4294 anchored_start = (bufp->buffer[0] == begline);
4296 #ifdef emacs
4297 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4299 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4301 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4303 #endif
4305 /* Loop through the string, looking for a place to start matching. */
4306 for (;;)
4308 /* If the pattern is anchored,
4309 skip quickly past places we cannot match.
4310 We don't bother to treat startpos == 0 specially
4311 because that case doesn't repeat. */
4312 if (anchored_start && startpos > 0)
4314 if (! ((startpos <= size1 ? string1[startpos - 1]
4315 : string2[startpos - size1 - 1])
4316 == '\n'))
4317 goto advance;
4320 /* If a fastmap is supplied, skip quickly over characters that
4321 cannot be the start of a match. If the pattern can match the
4322 null string, however, we don't need to skip characters; we want
4323 the first null string. */
4324 if (fastmap && startpos < total_size && !bufp->can_be_null)
4326 register re_char *d;
4327 register re_wchar_t buf_ch;
4329 d = POS_ADDR_VSTRING (startpos);
4331 if (range > 0) /* Searching forwards. */
4333 ssize_t irange = range, lim = 0;
4335 if (startpos < size1 && startpos + range >= size1)
4336 lim = range - (size1 - startpos);
4338 /* Written out as an if-else to avoid testing `translate'
4339 inside the loop. */
4340 if (RE_TRANSLATE_P (translate))
4342 if (multibyte)
4343 while (range > lim)
4345 int buf_charlen;
4347 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4348 buf_ch = RE_TRANSLATE (translate, buf_ch);
4349 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4350 break;
4352 range -= buf_charlen;
4353 d += buf_charlen;
4355 else
4356 while (range > lim)
4358 register re_wchar_t ch, translated;
4360 buf_ch = *d;
4361 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4362 translated = RE_TRANSLATE (translate, ch);
4363 if (translated != ch
4364 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4365 buf_ch = ch;
4366 if (fastmap[buf_ch])
4367 break;
4368 d++;
4369 range--;
4372 else
4374 if (multibyte)
4375 while (range > lim)
4377 int buf_charlen;
4379 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4380 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4381 break;
4382 range -= buf_charlen;
4383 d += buf_charlen;
4385 else
4386 while (range > lim && !fastmap[*d])
4388 d++;
4389 range--;
4392 startpos += irange - range;
4394 else /* Searching backwards. */
4396 if (multibyte)
4398 buf_ch = STRING_CHAR (d);
4399 buf_ch = TRANSLATE (buf_ch);
4400 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4401 goto advance;
4403 else
4405 register re_wchar_t ch, translated;
4407 buf_ch = *d;
4408 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4409 translated = TRANSLATE (ch);
4410 if (translated != ch
4411 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4412 buf_ch = ch;
4413 if (! fastmap[TRANSLATE (buf_ch)])
4414 goto advance;
4419 /* If can't match the null string, and that's all we have left, fail. */
4420 if (range >= 0 && startpos == total_size && fastmap
4421 && !bufp->can_be_null)
4422 return -1;
4424 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4425 startpos, regs, stop);
4427 if (val >= 0)
4428 return startpos;
4430 if (val == -2)
4431 return -2;
4433 advance:
4434 if (!range)
4435 break;
4436 else if (range > 0)
4438 /* Update STARTPOS to the next character boundary. */
4439 if (multibyte)
4441 re_char *p = POS_ADDR_VSTRING (startpos);
4442 int len = BYTES_BY_CHAR_HEAD (*p);
4444 range -= len;
4445 if (range < 0)
4446 break;
4447 startpos += len;
4449 else
4451 range--;
4452 startpos++;
4455 else
4457 range++;
4458 startpos--;
4460 /* Update STARTPOS to the previous character boundary. */
4461 if (multibyte)
4463 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4464 re_char *p0 = p;
4465 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4467 /* Find the head of multibyte form. */
4468 PREV_CHAR_BOUNDARY (p, phead);
4469 range += p0 - 1 - p;
4470 if (range > 0)
4471 break;
4473 startpos -= p0 - 1 - p;
4477 return -1;
4478 } /* re_search_2 */
4479 WEAK_ALIAS (__re_search_2, re_search_2)
4481 /* Declarations and macros for re_match_2. */
4483 static int bcmp_translate (re_char *s1, re_char *s2,
4484 register ssize_t len,
4485 RE_TRANSLATE_TYPE translate,
4486 const int multibyte);
4488 /* This converts PTR, a pointer into one of the search strings `string1'
4489 and `string2' into an offset from the beginning of that string. */
4490 #define POINTER_TO_OFFSET(ptr) \
4491 (FIRST_STRING_P (ptr) \
4492 ? (ptr) - string1 \
4493 : (ptr) - string2 + (ptrdiff_t) size1)
4495 /* Call before fetching a character with *d. This switches over to
4496 string2 if necessary.
4497 Check re_match_2_internal for a discussion of why end_match_2 might
4498 not be within string2 (but be equal to end_match_1 instead). */
4499 #define PREFETCH() \
4500 while (d == dend) \
4502 /* End of string2 => fail. */ \
4503 if (dend == end_match_2) \
4504 goto fail; \
4505 /* End of string1 => advance to string2. */ \
4506 d = string2; \
4507 dend = end_match_2; \
4510 /* Call before fetching a char with *d if you already checked other limits.
4511 This is meant for use in lookahead operations like wordend, etc..
4512 where we might need to look at parts of the string that might be
4513 outside of the LIMITs (i.e past `stop'). */
4514 #define PREFETCH_NOLIMIT() \
4515 if (d == end1) \
4517 d = string2; \
4518 dend = end_match_2; \
4521 /* Test if at very beginning or at very end of the virtual concatenation
4522 of `string1' and `string2'. If only one string, it's `string2'. */
4523 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4524 #define AT_STRINGS_END(d) ((d) == end2)
4526 /* Disabled due to a compiler bug -- see comment at case wordbound */
4528 /* The comment at case wordbound is following one, but we don't use
4529 AT_WORD_BOUNDARY anymore to support multibyte form.
4531 The DEC Alpha C compiler 3.x generates incorrect code for the
4532 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4533 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4534 macro and introducing temporary variables works around the bug. */
4536 #if 0
4537 /* Test if D points to a character which is word-constituent. We have
4538 two special cases to check for: if past the end of string1, look at
4539 the first character in string2; and if before the beginning of
4540 string2, look at the last character in string1. */
4541 #define WORDCHAR_P(d) \
4542 (SYNTAX ((d) == end1 ? *string2 \
4543 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4544 == Sword)
4546 /* Test if the character before D and the one at D differ with respect
4547 to being word-constituent. */
4548 #define AT_WORD_BOUNDARY(d) \
4549 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4550 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4551 #endif
4553 /* Free everything we malloc. */
4554 #ifdef MATCH_MAY_ALLOCATE
4555 # define FREE_VAR(var) \
4556 do { \
4557 if (var) \
4559 REGEX_FREE (var); \
4560 var = NULL; \
4562 } while (0)
4563 # define FREE_VARIABLES() \
4564 do { \
4565 REGEX_FREE_STACK (fail_stack.stack); \
4566 FREE_VAR (regstart); \
4567 FREE_VAR (regend); \
4568 FREE_VAR (best_regstart); \
4569 FREE_VAR (best_regend); \
4570 REGEX_SAFE_FREE (); \
4571 } while (0)
4572 #else
4573 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4574 #endif /* not MATCH_MAY_ALLOCATE */
4577 /* Optimization routines. */
4579 /* If the operation is a match against one or more chars,
4580 return a pointer to the next operation, else return NULL. */
4581 static re_char *
4582 skip_one_char (const_re_char *p)
4584 switch (*p++)
4586 case anychar:
4587 break;
4589 case exactn:
4590 p += *p + 1;
4591 break;
4593 case charset_not:
4594 case charset:
4595 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4597 int mcnt;
4598 p = CHARSET_RANGE_TABLE (p - 1);
4599 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4600 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4602 else
4603 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4604 break;
4606 case syntaxspec:
4607 case notsyntaxspec:
4608 #ifdef emacs
4609 case categoryspec:
4610 case notcategoryspec:
4611 #endif /* emacs */
4612 p++;
4613 break;
4615 default:
4616 p = NULL;
4618 return p;
4622 /* Jump over non-matching operations. */
4623 static re_char *
4624 skip_noops (const_re_char *p, const_re_char *pend)
4626 int mcnt;
4627 while (p < pend)
4629 switch (*p)
4631 case start_memory:
4632 case stop_memory:
4633 p += 2; break;
4634 case no_op:
4635 p += 1; break;
4636 case jump:
4637 p += 1;
4638 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4639 p += mcnt;
4640 break;
4641 default:
4642 return p;
4645 assert (p == pend);
4646 return p;
4649 /* Test if C matches charset op. *PP points to the charset or charset_not
4650 opcode. When the function finishes, *PP will be advanced past that opcode.
4651 C is character to test (possibly after translations) and CORIG is original
4652 character (i.e. without any translations). UNIBYTE denotes whether c is
4653 unibyte or multibyte character. */
4654 static bool
4655 execute_charset (const_re_char **pp, unsigned c, unsigned corig, bool unibyte)
4657 re_char *p = *pp, *rtp = NULL;
4658 bool not = (re_opcode_t) *p == charset_not;
4660 if (CHARSET_RANGE_TABLE_EXISTS_P (p))
4662 int count;
4663 rtp = CHARSET_RANGE_TABLE (p);
4664 EXTRACT_NUMBER_AND_INCR (count, rtp);
4665 *pp = CHARSET_RANGE_TABLE_END ((rtp), (count));
4667 else
4668 *pp += 2 + CHARSET_BITMAP_SIZE (p);
4670 if (unibyte && c < (1 << BYTEWIDTH))
4671 { /* Lookup bitmap. */
4672 /* Cast to `unsigned' instead of `unsigned char' in
4673 case the bit list is a full 32 bytes long. */
4674 if (c < (unsigned) (CHARSET_BITMAP_SIZE (p) * BYTEWIDTH)
4675 && p[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4676 return !not;
4678 #ifdef emacs
4679 else if (rtp)
4681 int class_bits = CHARSET_RANGE_TABLE_BITS (p);
4682 re_wchar_t range_start, range_end;
4684 /* Sort tests by the most commonly used classes with some adjustment to which
4685 tests are easiest to perform. Take a look at comment in re_wctype_parse
4686 for table with frequencies of character class names. */
4688 if ((class_bits & BIT_MULTIBYTE) ||
4689 (class_bits & BIT_ALNUM && ISALNUM (c)) ||
4690 (class_bits & BIT_ALPHA && ISALPHA (c)) ||
4691 (class_bits & BIT_SPACE && ISSPACE (c)) ||
4692 (class_bits & BIT_WORD && ISWORD (c)) ||
4693 ((class_bits & BIT_UPPER) &&
4694 (ISUPPER (c) || (corig != c &&
4695 c == downcase (corig) && ISLOWER (c)))) ||
4696 ((class_bits & BIT_LOWER) &&
4697 (ISLOWER (c) || (corig != c &&
4698 c == upcase (corig) && ISUPPER(c)))) ||
4699 (class_bits & BIT_PUNCT && ISPUNCT (c)) ||
4700 (class_bits & BIT_GRAPH && ISGRAPH (c)) ||
4701 (class_bits & BIT_PRINT && ISPRINT (c)))
4702 return !not;
4704 for (p = *pp; rtp < p; rtp += 2 * 3)
4706 EXTRACT_CHARACTER (range_start, rtp);
4707 EXTRACT_CHARACTER (range_end, rtp + 3);
4708 if (range_start <= c && c <= range_end)
4709 return !not;
4712 #endif /* emacs */
4713 return not;
4716 /* Non-zero if "p1 matches something" implies "p2 fails". */
4717 static int
4718 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4719 const_re_char *p2)
4721 re_opcode_t op2;
4722 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4723 unsigned char *pend = bufp->buffer + bufp->used;
4725 assert (p1 >= bufp->buffer && p1 < pend
4726 && p2 >= bufp->buffer && p2 <= pend);
4728 /* Skip over open/close-group commands.
4729 If what follows this loop is a ...+ construct,
4730 look at what begins its body, since we will have to
4731 match at least one of that. */
4732 p2 = skip_noops (p2, pend);
4733 /* The same skip can be done for p1, except that this function
4734 is only used in the case where p1 is a simple match operator. */
4735 /* p1 = skip_noops (p1, pend); */
4737 assert (p1 >= bufp->buffer && p1 < pend
4738 && p2 >= bufp->buffer && p2 <= pend);
4740 op2 = p2 == pend ? succeed : *p2;
4742 switch (op2)
4744 case succeed:
4745 case endbuf:
4746 /* If we're at the end of the pattern, we can change. */
4747 if (skip_one_char (p1))
4749 DEBUG_PRINT (" End of pattern: fast loop.\n");
4750 return 1;
4752 break;
4754 case endline:
4755 case exactn:
4757 register re_wchar_t c
4758 = (re_opcode_t) *p2 == endline ? '\n'
4759 : RE_STRING_CHAR (p2 + 2, multibyte);
4761 if ((re_opcode_t) *p1 == exactn)
4763 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4765 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4766 return 1;
4770 else if ((re_opcode_t) *p1 == charset
4771 || (re_opcode_t) *p1 == charset_not)
4773 if (!execute_charset (&p1, c, c, !multibyte || IS_REAL_ASCII (c)))
4775 DEBUG_PRINT (" No match => fast loop.\n");
4776 return 1;
4779 else if ((re_opcode_t) *p1 == anychar
4780 && c == '\n')
4782 DEBUG_PRINT (" . != \\n => fast loop.\n");
4783 return 1;
4786 break;
4788 case charset:
4790 if ((re_opcode_t) *p1 == exactn)
4791 /* Reuse the code above. */
4792 return mutually_exclusive_p (bufp, p2, p1);
4794 /* It is hard to list up all the character in charset
4795 P2 if it includes multibyte character. Give up in
4796 such case. */
4797 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4799 /* Now, we are sure that P2 has no range table.
4800 So, for the size of bitmap in P2, `p2[1]' is
4801 enough. But P1 may have range table, so the
4802 size of bitmap table of P1 is extracted by
4803 using macro `CHARSET_BITMAP_SIZE'.
4805 In a multibyte case, we know that all the character
4806 listed in P2 is ASCII. In a unibyte case, P1 has only a
4807 bitmap table. So, in both cases, it is enough to test
4808 only the bitmap table of P1. */
4810 if ((re_opcode_t) *p1 == charset)
4812 int idx;
4813 /* We win if the charset inside the loop
4814 has no overlap with the one after the loop. */
4815 for (idx = 0;
4816 (idx < (int) p2[1]
4817 && idx < CHARSET_BITMAP_SIZE (p1));
4818 idx++)
4819 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4820 break;
4822 if (idx == p2[1]
4823 || idx == CHARSET_BITMAP_SIZE (p1))
4825 DEBUG_PRINT (" No match => fast loop.\n");
4826 return 1;
4829 else if ((re_opcode_t) *p1 == charset_not)
4831 int idx;
4832 /* We win if the charset_not inside the loop lists
4833 every character listed in the charset after. */
4834 for (idx = 0; idx < (int) p2[1]; idx++)
4835 if (! (p2[2 + idx] == 0
4836 || (idx < CHARSET_BITMAP_SIZE (p1)
4837 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4838 break;
4840 if (idx == p2[1])
4842 DEBUG_PRINT (" No match => fast loop.\n");
4843 return 1;
4848 break;
4850 case charset_not:
4851 switch (*p1)
4853 case exactn:
4854 case charset:
4855 /* Reuse the code above. */
4856 return mutually_exclusive_p (bufp, p2, p1);
4857 case charset_not:
4858 /* When we have two charset_not, it's very unlikely that
4859 they don't overlap. The union of the two sets of excluded
4860 chars should cover all possible chars, which, as a matter of
4861 fact, is virtually impossible in multibyte buffers. */
4862 break;
4864 break;
4866 case wordend:
4867 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4868 case symend:
4869 return ((re_opcode_t) *p1 == syntaxspec
4870 && (p1[1] == Ssymbol || p1[1] == Sword));
4871 case notsyntaxspec:
4872 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4874 case wordbeg:
4875 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4876 case symbeg:
4877 return ((re_opcode_t) *p1 == notsyntaxspec
4878 && (p1[1] == Ssymbol || p1[1] == Sword));
4879 case syntaxspec:
4880 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4882 case wordbound:
4883 return (((re_opcode_t) *p1 == notsyntaxspec
4884 || (re_opcode_t) *p1 == syntaxspec)
4885 && p1[1] == Sword);
4887 #ifdef emacs
4888 case categoryspec:
4889 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4890 case notcategoryspec:
4891 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4892 #endif /* emacs */
4894 default:
4898 /* Safe default. */
4899 return 0;
4903 /* Matching routines. */
4905 #ifndef emacs /* Emacs never uses this. */
4906 /* re_match is like re_match_2 except it takes only a single string. */
4908 regoff_t
4909 re_match (struct re_pattern_buffer *bufp, const char *string,
4910 size_t size, ssize_t pos, struct re_registers *regs)
4912 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4913 size, pos, regs, size);
4914 return result;
4916 WEAK_ALIAS (__re_match, re_match)
4917 #endif /* not emacs */
4919 #ifdef emacs
4920 /* In Emacs, this is the string or buffer in which we
4921 are matching. It is used for looking up syntax properties. */
4922 Lisp_Object re_match_object;
4923 #endif
4925 /* re_match_2 matches the compiled pattern in BUFP against the
4926 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4927 and SIZE2, respectively). We start matching at POS, and stop
4928 matching at STOP.
4930 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4931 store offsets for the substring each group matched in REGS. See the
4932 documentation for exactly how many groups we fill.
4934 We return -1 if no match, -2 if an internal error (such as the
4935 failure stack overflowing). Otherwise, we return the length of the
4936 matched substring. */
4938 regoff_t
4939 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4940 size_t size1, const char *string2, size_t size2, ssize_t pos,
4941 struct re_registers *regs, ssize_t stop)
4943 regoff_t result;
4945 #ifdef emacs
4946 ssize_t charpos;
4947 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4948 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4949 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4950 #endif
4952 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4953 (re_char*) string2, size2,
4954 pos, regs, stop);
4955 return result;
4957 WEAK_ALIAS (__re_match_2, re_match_2)
4960 /* This is a separate function so that we can force an alloca cleanup
4961 afterwards. */
4962 static regoff_t
4963 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4964 size_t size1, const_re_char *string2, size_t size2,
4965 ssize_t pos, struct re_registers *regs, ssize_t stop)
4967 /* General temporaries. */
4968 int mcnt;
4969 size_t reg;
4971 /* Just past the end of the corresponding string. */
4972 re_char *end1, *end2;
4974 /* Pointers into string1 and string2, just past the last characters in
4975 each to consider matching. */
4976 re_char *end_match_1, *end_match_2;
4978 /* Where we are in the data, and the end of the current string. */
4979 re_char *d, *dend;
4981 /* Used sometimes to remember where we were before starting matching
4982 an operator so that we can go back in case of failure. This "atomic"
4983 behavior of matching opcodes is indispensable to the correctness
4984 of the on_failure_keep_string_jump optimization. */
4985 re_char *dfail;
4987 /* Where we are in the pattern, and the end of the pattern. */
4988 re_char *p = bufp->buffer;
4989 re_char *pend = p + bufp->used;
4991 /* We use this to map every character in the string. */
4992 RE_TRANSLATE_TYPE translate = bufp->translate;
4994 /* Nonzero if BUFP is setup from a multibyte regex. */
4995 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4997 /* Nonzero if STRING1/STRING2 are multibyte. */
4998 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
5000 /* Failure point stack. Each place that can handle a failure further
5001 down the line pushes a failure point on this stack. It consists of
5002 regstart, and regend for all registers corresponding to
5003 the subexpressions we're currently inside, plus the number of such
5004 registers, and, finally, two char *'s. The first char * is where
5005 to resume scanning the pattern; the second one is where to resume
5006 scanning the strings. */
5007 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5008 fail_stack_type fail_stack;
5009 #endif
5010 #ifdef DEBUG_COMPILES_ARGUMENTS
5011 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5012 #endif
5014 #if defined REL_ALLOC && defined REGEX_MALLOC
5015 /* This holds the pointer to the failure stack, when
5016 it is allocated relocatably. */
5017 fail_stack_elt_t *failure_stack_ptr;
5018 #endif
5020 /* We fill all the registers internally, independent of what we
5021 return, for use in backreferences. The number here includes
5022 an element for register zero. */
5023 size_t num_regs = bufp->re_nsub + 1;
5025 /* Information on the contents of registers. These are pointers into
5026 the input strings; they record just what was matched (on this
5027 attempt) by a subexpression part of the pattern, that is, the
5028 regnum-th regstart pointer points to where in the pattern we began
5029 matching and the regnum-th regend points to right after where we
5030 stopped matching the regnum-th subexpression. (The zeroth register
5031 keeps track of what the whole pattern matches.) */
5032 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5033 re_char **regstart, **regend;
5034 #endif
5036 /* The following record the register info as found in the above
5037 variables when we find a match better than any we've seen before.
5038 This happens as we backtrack through the failure points, which in
5039 turn happens only if we have not yet matched the entire string. */
5040 unsigned best_regs_set = false;
5041 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5042 re_char **best_regstart, **best_regend;
5043 #endif
5045 /* Logically, this is `best_regend[0]'. But we don't want to have to
5046 allocate space for that if we're not allocating space for anything
5047 else (see below). Also, we never need info about register 0 for
5048 any of the other register vectors, and it seems rather a kludge to
5049 treat `best_regend' differently than the rest. So we keep track of
5050 the end of the best match so far in a separate variable. We
5051 initialize this to NULL so that when we backtrack the first time
5052 and need to test it, it's not garbage. */
5053 re_char *match_end = NULL;
5055 #ifdef DEBUG_COMPILES_ARGUMENTS
5056 /* Counts the total number of registers pushed. */
5057 unsigned num_regs_pushed = 0;
5058 #endif
5060 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5062 REGEX_USE_SAFE_ALLOCA;
5064 INIT_FAIL_STACK ();
5066 #ifdef MATCH_MAY_ALLOCATE
5067 /* Do not bother to initialize all the register variables if there are
5068 no groups in the pattern, as it takes a fair amount of time. If
5069 there are groups, we include space for register 0 (the whole
5070 pattern), even though we never use it, since it simplifies the
5071 array indexing. We should fix this. */
5072 if (bufp->re_nsub)
5074 regstart = REGEX_TALLOC (num_regs, re_char *);
5075 regend = REGEX_TALLOC (num_regs, re_char *);
5076 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5077 best_regend = REGEX_TALLOC (num_regs, re_char *);
5079 if (!(regstart && regend && best_regstart && best_regend))
5081 FREE_VARIABLES ();
5082 return -2;
5085 else
5087 /* We must initialize all our variables to NULL, so that
5088 `FREE_VARIABLES' doesn't try to free them. */
5089 regstart = regend = best_regstart = best_regend = NULL;
5091 #endif /* MATCH_MAY_ALLOCATE */
5093 /* The starting position is bogus. */
5094 if (pos < 0 || pos > size1 + size2)
5096 FREE_VARIABLES ();
5097 return -1;
5100 /* Initialize subexpression text positions to -1 to mark ones that no
5101 start_memory/stop_memory has been seen for. Also initialize the
5102 register information struct. */
5103 for (reg = 1; reg < num_regs; reg++)
5104 regstart[reg] = regend[reg] = NULL;
5106 /* We move `string1' into `string2' if the latter's empty -- but not if
5107 `string1' is null. */
5108 if (size2 == 0 && string1 != NULL)
5110 string2 = string1;
5111 size2 = size1;
5112 string1 = 0;
5113 size1 = 0;
5115 end1 = string1 + size1;
5116 end2 = string2 + size2;
5118 /* `p' scans through the pattern as `d' scans through the data.
5119 `dend' is the end of the input string that `d' points within. `d'
5120 is advanced into the following input string whenever necessary, but
5121 this happens before fetching; therefore, at the beginning of the
5122 loop, `d' can be pointing at the end of a string, but it cannot
5123 equal `string2'. */
5124 if (pos >= size1)
5126 /* Only match within string2. */
5127 d = string2 + pos - size1;
5128 dend = end_match_2 = string2 + stop - size1;
5129 end_match_1 = end1; /* Just to give it a value. */
5131 else
5133 if (stop < size1)
5135 /* Only match within string1. */
5136 end_match_1 = string1 + stop;
5137 /* BEWARE!
5138 When we reach end_match_1, PREFETCH normally switches to string2.
5139 But in the present case, this means that just doing a PREFETCH
5140 makes us jump from `stop' to `gap' within the string.
5141 What we really want here is for the search to stop as
5142 soon as we hit end_match_1. That's why we set end_match_2
5143 to end_match_1 (since PREFETCH fails as soon as we hit
5144 end_match_2). */
5145 end_match_2 = end_match_1;
5147 else
5148 { /* It's important to use this code when stop == size so that
5149 moving `d' from end1 to string2 will not prevent the d == dend
5150 check from catching the end of string. */
5151 end_match_1 = end1;
5152 end_match_2 = string2 + stop - size1;
5154 d = string1 + pos;
5155 dend = end_match_1;
5158 DEBUG_PRINT ("The compiled pattern is: ");
5159 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5160 DEBUG_PRINT ("The string to match is: \"");
5161 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5162 DEBUG_PRINT ("\"\n");
5164 /* This loops over pattern commands. It exits by returning from the
5165 function if the match is complete, or it drops through if the match
5166 fails at this starting point in the input data. */
5167 for (;;)
5169 DEBUG_PRINT ("\n%p: ", p);
5171 if (p == pend)
5173 /* End of pattern means we might have succeeded. */
5174 DEBUG_PRINT ("end of pattern ... ");
5176 /* If we haven't matched the entire string, and we want the
5177 longest match, try backtracking. */
5178 if (d != end_match_2)
5180 /* True if this match is the best seen so far. */
5181 bool best_match_p;
5184 /* True if this match ends in the same string (string1
5185 or string2) as the best previous match. */
5186 bool same_str_p = (FIRST_STRING_P (match_end)
5187 == FIRST_STRING_P (d));
5189 /* AIX compiler got confused when this was combined
5190 with the previous declaration. */
5191 if (same_str_p)
5192 best_match_p = d > match_end;
5193 else
5194 best_match_p = !FIRST_STRING_P (d);
5197 DEBUG_PRINT ("backtracking.\n");
5199 if (!FAIL_STACK_EMPTY ())
5200 { /* More failure points to try. */
5202 /* If exceeds best match so far, save it. */
5203 if (!best_regs_set || best_match_p)
5205 best_regs_set = true;
5206 match_end = d;
5208 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5210 for (reg = 1; reg < num_regs; reg++)
5212 best_regstart[reg] = regstart[reg];
5213 best_regend[reg] = regend[reg];
5216 goto fail;
5219 /* If no failure points, don't restore garbage. And if
5220 last match is real best match, don't restore second
5221 best one. */
5222 else if (best_regs_set && !best_match_p)
5224 restore_best_regs:
5225 /* Restore best match. It may happen that `dend ==
5226 end_match_1' while the restored d is in string2.
5227 For example, the pattern `x.*y.*z' against the
5228 strings `x-' and `y-z-', if the two strings are
5229 not consecutive in memory. */
5230 DEBUG_PRINT ("Restoring best registers.\n");
5232 d = match_end;
5233 dend = ((d >= string1 && d <= end1)
5234 ? end_match_1 : end_match_2);
5236 for (reg = 1; reg < num_regs; reg++)
5238 regstart[reg] = best_regstart[reg];
5239 regend[reg] = best_regend[reg];
5242 } /* d != end_match_2 */
5244 succeed_label:
5245 DEBUG_PRINT ("Accepting match.\n");
5247 /* If caller wants register contents data back, do it. */
5248 if (regs && !bufp->no_sub)
5250 /* Have the register data arrays been allocated? */
5251 if (bufp->regs_allocated == REGS_UNALLOCATED)
5252 { /* No. So allocate them with malloc. We need one
5253 extra element beyond `num_regs' for the `-1' marker
5254 GNU code uses. */
5255 regs->num_regs = max (RE_NREGS, num_regs + 1);
5256 regs->start = TALLOC (regs->num_regs, regoff_t);
5257 regs->end = TALLOC (regs->num_regs, regoff_t);
5258 if (regs->start == NULL || regs->end == NULL)
5260 FREE_VARIABLES ();
5261 return -2;
5263 bufp->regs_allocated = REGS_REALLOCATE;
5265 else if (bufp->regs_allocated == REGS_REALLOCATE)
5266 { /* Yes. If we need more elements than were already
5267 allocated, reallocate them. If we need fewer, just
5268 leave it alone. */
5269 if (regs->num_regs < num_regs + 1)
5271 regs->num_regs = num_regs + 1;
5272 RETALLOC (regs->start, regs->num_regs, regoff_t);
5273 RETALLOC (regs->end, regs->num_regs, regoff_t);
5274 if (regs->start == NULL || regs->end == NULL)
5276 FREE_VARIABLES ();
5277 return -2;
5281 else
5283 /* These braces fend off a "empty body in an else-statement"
5284 warning under GCC when assert expands to nothing. */
5285 assert (bufp->regs_allocated == REGS_FIXED);
5288 /* Convert the pointer data in `regstart' and `regend' to
5289 indices. Register zero has to be set differently,
5290 since we haven't kept track of any info for it. */
5291 if (regs->num_regs > 0)
5293 regs->start[0] = pos;
5294 regs->end[0] = POINTER_TO_OFFSET (d);
5297 /* Go through the first `min (num_regs, regs->num_regs)'
5298 registers, since that is all we initialized. */
5299 for (reg = 1; reg < min (num_regs, regs->num_regs); reg++)
5301 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5302 regs->start[reg] = regs->end[reg] = -1;
5303 else
5305 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5306 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5310 /* If the regs structure we return has more elements than
5311 were in the pattern, set the extra elements to -1. If
5312 we (re)allocated the registers, this is the case,
5313 because we always allocate enough to have at least one
5314 -1 at the end. */
5315 for (reg = num_regs; reg < regs->num_regs; reg++)
5316 regs->start[reg] = regs->end[reg] = -1;
5317 } /* regs && !bufp->no_sub */
5319 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5320 nfailure_points_pushed, nfailure_points_popped,
5321 nfailure_points_pushed - nfailure_points_popped);
5322 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5324 ptrdiff_t dcnt = POINTER_TO_OFFSET (d) - pos;
5326 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5328 FREE_VARIABLES ();
5329 return dcnt;
5332 /* Otherwise match next pattern command. */
5333 switch (*p++)
5335 /* Ignore these. Used to ignore the n of succeed_n's which
5336 currently have n == 0. */
5337 case no_op:
5338 DEBUG_PRINT ("EXECUTING no_op.\n");
5339 break;
5341 case succeed:
5342 DEBUG_PRINT ("EXECUTING succeed.\n");
5343 goto succeed_label;
5345 /* Match the next n pattern characters exactly. The following
5346 byte in the pattern defines n, and the n bytes after that
5347 are the characters to match. */
5348 case exactn:
5349 mcnt = *p++;
5350 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5352 /* Remember the start point to rollback upon failure. */
5353 dfail = d;
5355 #ifndef emacs
5356 /* This is written out as an if-else so we don't waste time
5357 testing `translate' inside the loop. */
5358 if (RE_TRANSLATE_P (translate))
5361 PREFETCH ();
5362 if (RE_TRANSLATE (translate, *d) != *p++)
5364 d = dfail;
5365 goto fail;
5367 d++;
5369 while (--mcnt);
5370 else
5373 PREFETCH ();
5374 if (*d++ != *p++)
5376 d = dfail;
5377 goto fail;
5380 while (--mcnt);
5381 #else /* emacs */
5382 /* The cost of testing `translate' is comparatively small. */
5383 if (target_multibyte)
5386 int pat_charlen, buf_charlen;
5387 int pat_ch, buf_ch;
5389 PREFETCH ();
5390 if (multibyte)
5391 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5392 else
5394 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5395 pat_charlen = 1;
5397 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5399 if (TRANSLATE (buf_ch) != pat_ch)
5401 d = dfail;
5402 goto fail;
5405 p += pat_charlen;
5406 d += buf_charlen;
5407 mcnt -= pat_charlen;
5409 while (mcnt > 0);
5410 else
5413 int pat_charlen;
5414 int pat_ch, buf_ch;
5416 PREFETCH ();
5417 if (multibyte)
5419 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5420 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5422 else
5424 pat_ch = *p;
5425 pat_charlen = 1;
5427 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5428 if (! CHAR_BYTE8_P (buf_ch))
5430 buf_ch = TRANSLATE (buf_ch);
5431 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5432 if (buf_ch < 0)
5433 buf_ch = *d;
5435 else
5436 buf_ch = *d;
5437 if (buf_ch != pat_ch)
5439 d = dfail;
5440 goto fail;
5442 p += pat_charlen;
5443 d++;
5445 while (--mcnt);
5446 #endif
5447 break;
5450 /* Match any character except possibly a newline or a null. */
5451 case anychar:
5453 int buf_charlen;
5454 re_wchar_t buf_ch;
5455 reg_syntax_t syntax;
5457 DEBUG_PRINT ("EXECUTING anychar.\n");
5459 PREFETCH ();
5460 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5461 target_multibyte);
5462 buf_ch = TRANSLATE (buf_ch);
5464 #ifdef emacs
5465 syntax = RE_SYNTAX_EMACS;
5466 #else
5467 syntax = bufp->syntax;
5468 #endif
5470 if ((!(syntax & RE_DOT_NEWLINE) && buf_ch == '\n')
5471 || ((syntax & RE_DOT_NOT_NULL) && buf_ch == '\000'))
5472 goto fail;
5474 DEBUG_PRINT (" Matched \"%d\".\n", *d);
5475 d += buf_charlen;
5477 break;
5480 case charset:
5481 case charset_not:
5483 register unsigned int c, corig;
5484 int len;
5486 /* Whether matching against a unibyte character. */
5487 boolean unibyte_char = false;
5489 DEBUG_PRINT ("EXECUTING charset%s.\n",
5490 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
5492 PREFETCH ();
5493 corig = c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5494 if (target_multibyte)
5496 int c1;
5498 c = TRANSLATE (c);
5499 c1 = RE_CHAR_TO_UNIBYTE (c);
5500 if (c1 >= 0)
5502 unibyte_char = true;
5503 c = c1;
5506 else
5508 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5510 if (! CHAR_BYTE8_P (c1))
5512 c1 = TRANSLATE (c1);
5513 c1 = RE_CHAR_TO_UNIBYTE (c1);
5514 if (c1 >= 0)
5516 unibyte_char = true;
5517 c = c1;
5520 else
5521 unibyte_char = true;
5524 p -= 1;
5525 if (!execute_charset (&p, c, corig, unibyte_char))
5526 goto fail;
5528 d += len;
5530 break;
5533 /* The beginning of a group is represented by start_memory.
5534 The argument is the register number. The text
5535 matched within the group is recorded (in the internal
5536 registers data structure) under the register number. */
5537 case start_memory:
5538 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5540 /* In case we need to undo this operation (via backtracking). */
5541 PUSH_FAILURE_REG (*p);
5543 regstart[*p] = d;
5544 regend[*p] = NULL; /* probably unnecessary. -sm */
5545 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5547 /* Move past the register number and inner group count. */
5548 p += 1;
5549 break;
5552 /* The stop_memory opcode represents the end of a group. Its
5553 argument is the same as start_memory's: the register number. */
5554 case stop_memory:
5555 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5557 assert (!REG_UNSET (regstart[*p]));
5558 /* Strictly speaking, there should be code such as:
5560 assert (REG_UNSET (regend[*p]));
5561 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5563 But the only info to be pushed is regend[*p] and it is known to
5564 be UNSET, so there really isn't anything to push.
5565 Not pushing anything, on the other hand deprives us from the
5566 guarantee that regend[*p] is UNSET since undoing this operation
5567 will not reset its value properly. This is not important since
5568 the value will only be read on the next start_memory or at
5569 the very end and both events can only happen if this stop_memory
5570 is *not* undone. */
5572 regend[*p] = d;
5573 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5575 /* Move past the register number and the inner group count. */
5576 p += 1;
5577 break;
5580 /* \<digit> has been turned into a `duplicate' command which is
5581 followed by the numeric value of <digit> as the register number. */
5582 case duplicate:
5584 register re_char *d2, *dend2;
5585 int regno = *p++; /* Get which register to match against. */
5586 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5588 /* Can't back reference a group which we've never matched. */
5589 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5590 goto fail;
5592 /* Where in input to try to start matching. */
5593 d2 = regstart[regno];
5595 /* Remember the start point to rollback upon failure. */
5596 dfail = d;
5598 /* Where to stop matching; if both the place to start and
5599 the place to stop matching are in the same string, then
5600 set to the place to stop, otherwise, for now have to use
5601 the end of the first string. */
5603 dend2 = ((FIRST_STRING_P (regstart[regno])
5604 == FIRST_STRING_P (regend[regno]))
5605 ? regend[regno] : end_match_1);
5606 for (;;)
5608 ptrdiff_t dcnt;
5610 /* If necessary, advance to next segment in register
5611 contents. */
5612 while (d2 == dend2)
5614 if (dend2 == end_match_2) break;
5615 if (dend2 == regend[regno]) break;
5617 /* End of string1 => advance to string2. */
5618 d2 = string2;
5619 dend2 = regend[regno];
5621 /* At end of register contents => success */
5622 if (d2 == dend2) break;
5624 /* If necessary, advance to next segment in data. */
5625 PREFETCH ();
5627 /* How many characters left in this segment to match. */
5628 dcnt = dend - d;
5630 /* Want how many consecutive characters we can match in
5631 one shot, so, if necessary, adjust the count. */
5632 if (dcnt > dend2 - d2)
5633 dcnt = dend2 - d2;
5635 /* Compare that many; failure if mismatch, else move
5636 past them. */
5637 if (RE_TRANSLATE_P (translate)
5638 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5639 : memcmp (d, d2, dcnt))
5641 d = dfail;
5642 goto fail;
5644 d += dcnt, d2 += dcnt;
5647 break;
5650 /* begline matches the empty string at the beginning of the string
5651 (unless `not_bol' is set in `bufp'), and after newlines. */
5652 case begline:
5653 DEBUG_PRINT ("EXECUTING begline.\n");
5655 if (AT_STRINGS_BEG (d))
5657 if (!bufp->not_bol) break;
5659 else
5661 unsigned c;
5662 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5663 if (c == '\n')
5664 break;
5666 /* In all other cases, we fail. */
5667 goto fail;
5670 /* endline is the dual of begline. */
5671 case endline:
5672 DEBUG_PRINT ("EXECUTING endline.\n");
5674 if (AT_STRINGS_END (d))
5676 if (!bufp->not_eol) break;
5678 else
5680 PREFETCH_NOLIMIT ();
5681 if (*d == '\n')
5682 break;
5684 goto fail;
5687 /* Match at the very beginning of the data. */
5688 case begbuf:
5689 DEBUG_PRINT ("EXECUTING begbuf.\n");
5690 if (AT_STRINGS_BEG (d))
5691 break;
5692 goto fail;
5695 /* Match at the very end of the data. */
5696 case endbuf:
5697 DEBUG_PRINT ("EXECUTING endbuf.\n");
5698 if (AT_STRINGS_END (d))
5699 break;
5700 goto fail;
5703 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5704 pushes NULL as the value for the string on the stack. Then
5705 `POP_FAILURE_POINT' will keep the current value for the
5706 string, instead of restoring it. To see why, consider
5707 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5708 then the . fails against the \n. But the next thing we want
5709 to do is match the \n against the \n; if we restored the
5710 string value, we would be back at the foo.
5712 Because this is used only in specific cases, we don't need to
5713 check all the things that `on_failure_jump' does, to make
5714 sure the right things get saved on the stack. Hence we don't
5715 share its code. The only reason to push anything on the
5716 stack at all is that otherwise we would have to change
5717 `anychar's code to do something besides goto fail in this
5718 case; that seems worse than this. */
5719 case on_failure_keep_string_jump:
5720 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5721 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5722 mcnt, p + mcnt);
5724 PUSH_FAILURE_POINT (p - 3, NULL);
5725 break;
5727 /* A nasty loop is introduced by the non-greedy *? and +?.
5728 With such loops, the stack only ever contains one failure point
5729 at a time, so that a plain on_failure_jump_loop kind of
5730 cycle detection cannot work. Worse yet, such a detection
5731 can not only fail to detect a cycle, but it can also wrongly
5732 detect a cycle (between different instantiations of the same
5733 loop).
5734 So the method used for those nasty loops is a little different:
5735 We use a special cycle-detection-stack-frame which is pushed
5736 when the on_failure_jump_nastyloop failure-point is *popped*.
5737 This special frame thus marks the beginning of one iteration
5738 through the loop and we can hence easily check right here
5739 whether something matched between the beginning and the end of
5740 the loop. */
5741 case on_failure_jump_nastyloop:
5742 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5743 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5744 mcnt, p + mcnt);
5746 assert ((re_opcode_t)p[-4] == no_op);
5748 int cycle = 0;
5749 CHECK_INFINITE_LOOP (p - 4, d);
5750 if (!cycle)
5751 /* If there's a cycle, just continue without pushing
5752 this failure point. The failure point is the "try again"
5753 option, which shouldn't be tried.
5754 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5755 PUSH_FAILURE_POINT (p - 3, d);
5757 break;
5759 /* Simple loop detecting on_failure_jump: just check on the
5760 failure stack if the same spot was already hit earlier. */
5761 case on_failure_jump_loop:
5762 on_failure:
5763 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5764 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5765 mcnt, p + mcnt);
5767 int cycle = 0;
5768 CHECK_INFINITE_LOOP (p - 3, d);
5769 if (cycle)
5770 /* If there's a cycle, get out of the loop, as if the matching
5771 had failed. We used to just `goto fail' here, but that was
5772 aborting the search a bit too early: we want to keep the
5773 empty-loop-match and keep matching after the loop.
5774 We want (x?)*y\1z to match both xxyz and xxyxz. */
5775 p += mcnt;
5776 else
5777 PUSH_FAILURE_POINT (p - 3, d);
5779 break;
5782 /* Uses of on_failure_jump:
5784 Each alternative starts with an on_failure_jump that points
5785 to the beginning of the next alternative. Each alternative
5786 except the last ends with a jump that in effect jumps past
5787 the rest of the alternatives. (They really jump to the
5788 ending jump of the following alternative, because tensioning
5789 these jumps is a hassle.)
5791 Repeats start with an on_failure_jump that points past both
5792 the repetition text and either the following jump or
5793 pop_failure_jump back to this on_failure_jump. */
5794 case on_failure_jump:
5795 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5796 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5797 mcnt, p + mcnt);
5799 PUSH_FAILURE_POINT (p -3, d);
5800 break;
5802 /* This operation is used for greedy *.
5803 Compare the beginning of the repeat with what in the
5804 pattern follows its end. If we can establish that there
5805 is nothing that they would both match, i.e., that we
5806 would have to backtrack because of (as in, e.g., `a*a')
5807 then we can use a non-backtracking loop based on
5808 on_failure_keep_string_jump instead of on_failure_jump. */
5809 case on_failure_jump_smart:
5810 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5811 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5812 mcnt, p + mcnt);
5814 re_char *p1 = p; /* Next operation. */
5815 /* Here, we discard `const', making re_match non-reentrant. */
5816 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5817 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5819 p -= 3; /* Reset so that we will re-execute the
5820 instruction once it's been changed. */
5822 EXTRACT_NUMBER (mcnt, p2 - 2);
5824 /* Ensure this is a indeed the trivial kind of loop
5825 we are expecting. */
5826 assert (skip_one_char (p1) == p2 - 3);
5827 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5828 DEBUG_STATEMENT (debug += 2);
5829 if (mutually_exclusive_p (bufp, p1, p2))
5831 /* Use a fast `on_failure_keep_string_jump' loop. */
5832 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5833 *p3 = (unsigned char) on_failure_keep_string_jump;
5834 STORE_NUMBER (p2 - 2, mcnt + 3);
5836 else
5838 /* Default to a safe `on_failure_jump' loop. */
5839 DEBUG_PRINT (" smart default => slow loop.\n");
5840 *p3 = (unsigned char) on_failure_jump;
5842 DEBUG_STATEMENT (debug -= 2);
5844 break;
5846 /* Unconditionally jump (without popping any failure points). */
5847 case jump:
5848 unconditional_jump:
5849 IMMEDIATE_QUIT_CHECK;
5850 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5851 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5852 p += mcnt; /* Do the jump. */
5853 DEBUG_PRINT ("(to %p).\n", p);
5854 break;
5857 /* Have to succeed matching what follows at least n times.
5858 After that, handle like `on_failure_jump'. */
5859 case succeed_n:
5860 /* Signedness doesn't matter since we only compare MCNT to 0. */
5861 EXTRACT_NUMBER (mcnt, p + 2);
5862 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5864 /* Originally, mcnt is how many times we HAVE to succeed. */
5865 if (mcnt != 0)
5867 /* Here, we discard `const', making re_match non-reentrant. */
5868 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5869 mcnt--;
5870 p += 4;
5871 PUSH_NUMBER (p2, mcnt);
5873 else
5874 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5875 goto on_failure;
5876 break;
5878 case jump_n:
5879 /* Signedness doesn't matter since we only compare MCNT to 0. */
5880 EXTRACT_NUMBER (mcnt, p + 2);
5881 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5883 /* Originally, this is how many times we CAN jump. */
5884 if (mcnt != 0)
5886 /* Here, we discard `const', making re_match non-reentrant. */
5887 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5888 mcnt--;
5889 PUSH_NUMBER (p2, mcnt);
5890 goto unconditional_jump;
5892 /* If don't have to jump any more, skip over the rest of command. */
5893 else
5894 p += 4;
5895 break;
5897 case set_number_at:
5899 unsigned char *p2; /* Location of the counter. */
5900 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5902 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5903 /* Here, we discard `const', making re_match non-reentrant. */
5904 p2 = (unsigned char*) p + mcnt;
5905 /* Signedness doesn't matter since we only copy MCNT's bits. */
5906 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5907 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5908 PUSH_NUMBER (p2, mcnt);
5909 break;
5912 case wordbound:
5913 case notwordbound:
5915 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5916 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5918 /* We SUCCEED (or FAIL) in one of the following cases: */
5920 /* Case 1: D is at the beginning or the end of string. */
5921 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5922 not = !not;
5923 else
5925 /* C1 is the character before D, S1 is the syntax of C1, C2
5926 is the character at D, and S2 is the syntax of C2. */
5927 re_wchar_t c1, c2;
5928 int s1, s2;
5929 int dummy;
5930 #ifdef emacs
5931 ssize_t offset = PTR_TO_OFFSET (d - 1);
5932 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5933 UPDATE_SYNTAX_TABLE_FAST (charpos);
5934 #endif
5935 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5936 s1 = SYNTAX (c1);
5937 #ifdef emacs
5938 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
5939 #endif
5940 PREFETCH_NOLIMIT ();
5941 GET_CHAR_AFTER (c2, d, dummy);
5942 s2 = SYNTAX (c2);
5944 if (/* Case 2: Only one of S1 and S2 is Sword. */
5945 ((s1 == Sword) != (s2 == Sword))
5946 /* Case 3: Both of S1 and S2 are Sword, and macro
5947 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5948 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5949 not = !not;
5951 if (not)
5952 break;
5953 else
5954 goto fail;
5957 case wordbeg:
5958 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5960 /* We FAIL in one of the following cases: */
5962 /* Case 1: D is at the end of string. */
5963 if (AT_STRINGS_END (d))
5964 goto fail;
5965 else
5967 /* C1 is the character before D, S1 is the syntax of C1, C2
5968 is the character at D, and S2 is the syntax of C2. */
5969 re_wchar_t c1, c2;
5970 int s1, s2;
5971 int dummy;
5972 #ifdef emacs
5973 ssize_t offset = PTR_TO_OFFSET (d);
5974 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5975 UPDATE_SYNTAX_TABLE_FAST (charpos);
5976 #endif
5977 PREFETCH ();
5978 GET_CHAR_AFTER (c2, d, dummy);
5979 s2 = SYNTAX (c2);
5981 /* Case 2: S2 is not Sword. */
5982 if (s2 != Sword)
5983 goto fail;
5985 /* Case 3: D is not at the beginning of string ... */
5986 if (!AT_STRINGS_BEG (d))
5988 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5989 #ifdef emacs
5990 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5991 #endif
5992 s1 = SYNTAX (c1);
5994 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5995 returns 0. */
5996 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5997 goto fail;
6000 break;
6002 case wordend:
6003 DEBUG_PRINT ("EXECUTING wordend.\n");
6005 /* We FAIL in one of the following cases: */
6007 /* Case 1: D is at the beginning of string. */
6008 if (AT_STRINGS_BEG (d))
6009 goto fail;
6010 else
6012 /* C1 is the character before D, S1 is the syntax of C1, C2
6013 is the character at D, and S2 is the syntax of C2. */
6014 re_wchar_t c1, c2;
6015 int s1, s2;
6016 int dummy;
6017 #ifdef emacs
6018 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6019 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6020 UPDATE_SYNTAX_TABLE_FAST (charpos);
6021 #endif
6022 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6023 s1 = SYNTAX (c1);
6025 /* Case 2: S1 is not Sword. */
6026 if (s1 != Sword)
6027 goto fail;
6029 /* Case 3: D is not at the end of string ... */
6030 if (!AT_STRINGS_END (d))
6032 PREFETCH_NOLIMIT ();
6033 GET_CHAR_AFTER (c2, d, dummy);
6034 #ifdef emacs
6035 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos);
6036 #endif
6037 s2 = SYNTAX (c2);
6039 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6040 returns 0. */
6041 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6042 goto fail;
6045 break;
6047 case symbeg:
6048 DEBUG_PRINT ("EXECUTING symbeg.\n");
6050 /* We FAIL in one of the following cases: */
6052 /* Case 1: D is at the end of string. */
6053 if (AT_STRINGS_END (d))
6054 goto fail;
6055 else
6057 /* C1 is the character before D, S1 is the syntax of C1, C2
6058 is the character at D, and S2 is the syntax of C2. */
6059 re_wchar_t c1, c2;
6060 int s1, s2;
6061 #ifdef emacs
6062 ssize_t offset = PTR_TO_OFFSET (d);
6063 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6064 UPDATE_SYNTAX_TABLE_FAST (charpos);
6065 #endif
6066 PREFETCH ();
6067 c2 = RE_STRING_CHAR (d, target_multibyte);
6068 s2 = SYNTAX (c2);
6070 /* Case 2: S2 is neither Sword nor Ssymbol. */
6071 if (s2 != Sword && s2 != Ssymbol)
6072 goto fail;
6074 /* Case 3: D is not at the beginning of string ... */
6075 if (!AT_STRINGS_BEG (d))
6077 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6078 #ifdef emacs
6079 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6080 #endif
6081 s1 = SYNTAX (c1);
6083 /* ... and S1 is Sword or Ssymbol. */
6084 if (s1 == Sword || s1 == Ssymbol)
6085 goto fail;
6088 break;
6090 case symend:
6091 DEBUG_PRINT ("EXECUTING symend.\n");
6093 /* We FAIL in one of the following cases: */
6095 /* Case 1: D is at the beginning of string. */
6096 if (AT_STRINGS_BEG (d))
6097 goto fail;
6098 else
6100 /* C1 is the character before D, S1 is the syntax of C1, C2
6101 is the character at D, and S2 is the syntax of C2. */
6102 re_wchar_t c1, c2;
6103 int s1, s2;
6104 #ifdef emacs
6105 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6106 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6107 UPDATE_SYNTAX_TABLE_FAST (charpos);
6108 #endif
6109 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6110 s1 = SYNTAX (c1);
6112 /* Case 2: S1 is neither Ssymbol nor Sword. */
6113 if (s1 != Sword && s1 != Ssymbol)
6114 goto fail;
6116 /* Case 3: D is not at the end of string ... */
6117 if (!AT_STRINGS_END (d))
6119 PREFETCH_NOLIMIT ();
6120 c2 = RE_STRING_CHAR (d, target_multibyte);
6121 #ifdef emacs
6122 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
6123 #endif
6124 s2 = SYNTAX (c2);
6126 /* ... and S2 is Sword or Ssymbol. */
6127 if (s2 == Sword || s2 == Ssymbol)
6128 goto fail;
6131 break;
6133 case syntaxspec:
6134 case notsyntaxspec:
6136 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6137 mcnt = *p++;
6138 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6139 mcnt);
6140 PREFETCH ();
6141 #ifdef emacs
6143 ssize_t offset = PTR_TO_OFFSET (d);
6144 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6145 UPDATE_SYNTAX_TABLE_FAST (pos1);
6147 #endif
6149 int len;
6150 re_wchar_t c;
6152 GET_CHAR_AFTER (c, d, len);
6153 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6154 goto fail;
6155 d += len;
6158 break;
6160 #ifdef emacs
6161 case at_dot:
6162 DEBUG_PRINT ("EXECUTING at_dot.\n");
6163 if (PTR_BYTE_POS (d) != PT_BYTE)
6164 goto fail;
6165 break;
6167 case categoryspec:
6168 case notcategoryspec:
6170 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6171 mcnt = *p++;
6172 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6173 not ? "not" : "", mcnt);
6174 PREFETCH ();
6177 int len;
6178 re_wchar_t c;
6179 GET_CHAR_AFTER (c, d, len);
6180 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6181 goto fail;
6182 d += len;
6185 break;
6187 #endif /* emacs */
6189 default:
6190 abort ();
6192 continue; /* Successfully executed one pattern command; keep going. */
6195 /* We goto here if a matching operation fails. */
6196 fail:
6197 IMMEDIATE_QUIT_CHECK;
6198 if (!FAIL_STACK_EMPTY ())
6200 re_char *str, *pat;
6201 /* A restart point is known. Restore to that state. */
6202 DEBUG_PRINT ("\nFAIL:\n");
6203 POP_FAILURE_POINT (str, pat);
6204 switch (*pat++)
6206 case on_failure_keep_string_jump:
6207 assert (str == NULL);
6208 goto continue_failure_jump;
6210 case on_failure_jump_nastyloop:
6211 assert ((re_opcode_t)pat[-2] == no_op);
6212 PUSH_FAILURE_POINT (pat - 2, str);
6213 /* Fallthrough */
6215 case on_failure_jump_loop:
6216 case on_failure_jump:
6217 case succeed_n:
6218 d = str;
6219 continue_failure_jump:
6220 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6221 p = pat + mcnt;
6222 break;
6224 case no_op:
6225 /* A special frame used for nastyloops. */
6226 goto fail;
6228 default:
6229 abort ();
6232 assert (p >= bufp->buffer && p <= pend);
6234 if (d >= string1 && d <= end1)
6235 dend = end_match_1;
6237 else
6238 break; /* Matching at this starting point really fails. */
6239 } /* for (;;) */
6241 if (best_regs_set)
6242 goto restore_best_regs;
6244 FREE_VARIABLES ();
6246 return -1; /* Failure to match. */
6249 /* Subroutine definitions for re_match_2. */
6251 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6252 bytes; nonzero otherwise. */
6254 static int
6255 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6256 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6258 register re_char *p1 = s1, *p2 = s2;
6259 re_char *p1_end = s1 + len;
6260 re_char *p2_end = s2 + len;
6262 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6263 different lengths, but relying on a single `len' would break this. -sm */
6264 while (p1 < p1_end && p2 < p2_end)
6266 int p1_charlen, p2_charlen;
6267 re_wchar_t p1_ch, p2_ch;
6269 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6270 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6272 if (RE_TRANSLATE (translate, p1_ch)
6273 != RE_TRANSLATE (translate, p2_ch))
6274 return 1;
6276 p1 += p1_charlen, p2 += p2_charlen;
6279 if (p1 != p1_end || p2 != p2_end)
6280 return 1;
6282 return 0;
6285 /* Entry points for GNU code. */
6287 /* re_compile_pattern is the GNU regular expression compiler: it
6288 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6289 Returns 0 if the pattern was valid, otherwise an error string.
6291 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6292 are set in BUFP on entry.
6294 We call regex_compile to do the actual compilation. */
6296 const char *
6297 re_compile_pattern (const char *pattern, size_t length,
6298 #ifdef emacs
6299 bool posix_backtracking, const char *whitespace_regexp,
6300 #endif
6301 struct re_pattern_buffer *bufp)
6303 reg_errcode_t ret;
6305 /* GNU code is written to assume at least RE_NREGS registers will be set
6306 (and at least one extra will be -1). */
6307 bufp->regs_allocated = REGS_UNALLOCATED;
6309 /* And GNU code determines whether or not to get register information
6310 by passing null for the REGS argument to re_match, etc., not by
6311 setting no_sub. */
6312 bufp->no_sub = 0;
6314 ret = regex_compile ((re_char*) pattern, length,
6315 #ifdef emacs
6316 posix_backtracking,
6317 whitespace_regexp,
6318 #else
6319 re_syntax_options,
6320 #endif
6321 bufp);
6323 if (!ret)
6324 return NULL;
6325 return gettext (re_error_msgid[(int) ret]);
6327 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6329 /* Entry points compatible with 4.2 BSD regex library. We don't define
6330 them unless specifically requested. */
6332 #if defined _REGEX_RE_COMP || defined _LIBC
6334 /* BSD has one and only one pattern buffer. */
6335 static struct re_pattern_buffer re_comp_buf;
6337 char *
6338 # ifdef _LIBC
6339 /* Make these definitions weak in libc, so POSIX programs can redefine
6340 these names if they don't use our functions, and still use
6341 regcomp/regexec below without link errors. */
6342 weak_function
6343 # endif
6344 re_comp (const char *s)
6346 reg_errcode_t ret;
6348 if (!s)
6350 if (!re_comp_buf.buffer)
6351 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6352 return (char *) gettext ("No previous regular expression");
6353 return 0;
6356 if (!re_comp_buf.buffer)
6358 re_comp_buf.buffer = malloc (200);
6359 if (re_comp_buf.buffer == NULL)
6360 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6361 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6362 re_comp_buf.allocated = 200;
6364 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6365 if (re_comp_buf.fastmap == NULL)
6366 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6367 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6370 /* Since `re_exec' always passes NULL for the `regs' argument, we
6371 don't need to initialize the pattern buffer fields which affect it. */
6373 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6375 if (!ret)
6376 return NULL;
6378 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6379 return (char *) gettext (re_error_msgid[(int) ret]);
6384 # ifdef _LIBC
6385 weak_function
6386 # endif
6387 re_exec (const char *s)
6389 const size_t len = strlen (s);
6390 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6392 #endif /* _REGEX_RE_COMP */
6394 /* POSIX.2 functions. Don't define these for Emacs. */
6396 #ifndef emacs
6398 /* regcomp takes a regular expression as a string and compiles it.
6400 PREG is a regex_t *. We do not expect any fields to be initialized,
6401 since POSIX says we shouldn't. Thus, we set
6403 `buffer' to the compiled pattern;
6404 `used' to the length of the compiled pattern;
6405 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6406 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6407 RE_SYNTAX_POSIX_BASIC;
6408 `fastmap' to an allocated space for the fastmap;
6409 `fastmap_accurate' to zero;
6410 `re_nsub' to the number of subexpressions in PATTERN.
6412 PATTERN is the address of the pattern string.
6414 CFLAGS is a series of bits which affect compilation.
6416 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6417 use POSIX basic syntax.
6419 If REG_NEWLINE is set, then . and [^...] don't match newline.
6420 Also, regexec will try a match beginning after every newline.
6422 If REG_ICASE is set, then we considers upper- and lowercase
6423 versions of letters to be equivalent when matching.
6425 If REG_NOSUB is set, then when PREG is passed to regexec, that
6426 routine will report only success or failure, and nothing about the
6427 registers.
6429 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6430 the return codes and their meanings.) */
6432 reg_errcode_t
6433 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6434 int cflags)
6436 reg_errcode_t ret;
6437 reg_syntax_t syntax
6438 = (cflags & REG_EXTENDED) ?
6439 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6441 /* regex_compile will allocate the space for the compiled pattern. */
6442 preg->buffer = 0;
6443 preg->allocated = 0;
6444 preg->used = 0;
6446 /* Try to allocate space for the fastmap. */
6447 preg->fastmap = malloc (1 << BYTEWIDTH);
6449 if (cflags & REG_ICASE)
6451 unsigned i;
6453 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6454 if (preg->translate == NULL)
6455 return (int) REG_ESPACE;
6457 /* Map uppercase characters to corresponding lowercase ones. */
6458 for (i = 0; i < CHAR_SET_SIZE; i++)
6459 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6461 else
6462 preg->translate = NULL;
6464 /* If REG_NEWLINE is set, newlines are treated differently. */
6465 if (cflags & REG_NEWLINE)
6466 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6467 syntax &= ~RE_DOT_NEWLINE;
6468 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6470 else
6471 syntax |= RE_NO_NEWLINE_ANCHOR;
6473 preg->no_sub = !!(cflags & REG_NOSUB);
6475 /* POSIX says a null character in the pattern terminates it, so we
6476 can use strlen here in compiling the pattern. */
6477 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6479 /* POSIX doesn't distinguish between an unmatched open-group and an
6480 unmatched close-group: both are REG_EPAREN. */
6481 if (ret == REG_ERPAREN)
6482 ret = REG_EPAREN;
6484 if (ret == REG_NOERROR && preg->fastmap)
6485 { /* Compute the fastmap now, since regexec cannot modify the pattern
6486 buffer. */
6487 re_compile_fastmap (preg);
6488 if (preg->can_be_null)
6489 { /* The fastmap can't be used anyway. */
6490 free (preg->fastmap);
6491 preg->fastmap = NULL;
6494 return ret;
6496 WEAK_ALIAS (__regcomp, regcomp)
6499 /* regexec searches for a given pattern, specified by PREG, in the
6500 string STRING.
6502 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6503 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6504 least NMATCH elements, and we set them to the offsets of the
6505 corresponding matched substrings.
6507 EFLAGS specifies `execution flags' which affect matching: if
6508 REG_NOTBOL is set, then ^ does not match at the beginning of the
6509 string; if REG_NOTEOL is set, then $ does not match at the end.
6511 We return 0 if we find a match and REG_NOMATCH if not. */
6513 reg_errcode_t
6514 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6515 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6517 regoff_t ret;
6518 struct re_registers regs;
6519 regex_t private_preg;
6520 size_t len = strlen (string);
6521 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6523 private_preg = *preg;
6525 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6526 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6528 /* The user has told us exactly how many registers to return
6529 information about, via `nmatch'. We have to pass that on to the
6530 matching routines. */
6531 private_preg.regs_allocated = REGS_FIXED;
6533 if (want_reg_info)
6535 regs.num_regs = nmatch;
6536 regs.start = TALLOC (nmatch * 2, regoff_t);
6537 if (regs.start == NULL)
6538 return REG_NOMATCH;
6539 regs.end = regs.start + nmatch;
6542 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6543 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6544 was a little bit longer but still only matching the real part.
6545 This works because the `endline' will check for a '\n' and will find a
6546 '\0', correctly deciding that this is not the end of a line.
6547 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6548 a convenient '\0' there. For all we know, the string could be preceded
6549 by '\n' which would throw things off. */
6551 /* Perform the searching operation. */
6552 ret = re_search (&private_preg, string, len,
6553 /* start: */ 0, /* range: */ len,
6554 want_reg_info ? &regs : 0);
6556 /* Copy the register information to the POSIX structure. */
6557 if (want_reg_info)
6559 if (ret >= 0)
6561 unsigned r;
6563 for (r = 0; r < nmatch; r++)
6565 pmatch[r].rm_so = regs.start[r];
6566 pmatch[r].rm_eo = regs.end[r];
6570 /* If we needed the temporary register info, free the space now. */
6571 free (regs.start);
6574 /* We want zero return to mean success, unlike `re_search'. */
6575 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6577 WEAK_ALIAS (__regexec, regexec)
6580 /* Returns a message corresponding to an error code, ERR_CODE, returned
6581 from either regcomp or regexec. We don't use PREG here.
6583 ERR_CODE was previously called ERRCODE, but that name causes an
6584 error with msvc8 compiler. */
6586 size_t
6587 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6589 const char *msg;
6590 size_t msg_size;
6592 if (err_code < 0
6593 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6594 /* Only error codes returned by the rest of the code should be passed
6595 to this routine. If we are given anything else, or if other regex
6596 code generates an invalid error code, then the program has a bug.
6597 Dump core so we can fix it. */
6598 abort ();
6600 msg = gettext (re_error_msgid[err_code]);
6602 msg_size = strlen (msg) + 1; /* Includes the null. */
6604 if (errbuf_size != 0)
6606 if (msg_size > errbuf_size)
6608 memcpy (errbuf, msg, errbuf_size - 1);
6609 errbuf[errbuf_size - 1] = 0;
6611 else
6612 strcpy (errbuf, msg);
6615 return msg_size;
6617 WEAK_ALIAS (__regerror, regerror)
6620 /* Free dynamically allocated space used by PREG. */
6622 void
6623 regfree (regex_t *preg)
6625 free (preg->buffer);
6626 preg->buffer = NULL;
6628 preg->allocated = 0;
6629 preg->used = 0;
6631 free (preg->fastmap);
6632 preg->fastmap = NULL;
6633 preg->fastmap_accurate = 0;
6635 free (preg->translate);
6636 preg->translate = NULL;
6638 WEAK_ALIAS (__regfree, regfree)
6640 #endif /* not emacs */