* net/tramp-sh.el (tramp-histfile-override): Clarify docstring.
[emacs.git] / src / regex.c
blob85266458917efd9f5ea0f64bf53c00620d3f657e
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-2014 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 (2, "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 (2, "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) <= 0237) \
317 : 1)
319 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
320 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
321 : 1)
323 # define ISALNUM(c) (IS_REAL_ASCII (c) \
324 ? (((c) >= 'a' && (c) <= 'z') \
325 || ((c) >= 'A' && (c) <= 'Z') \
326 || ((c) >= '0' && (c) <= '9')) \
327 : SYNTAX (c) == Sword)
329 # define ISALPHA(c) (IS_REAL_ASCII (c) \
330 ? (((c) >= 'a' && (c) <= 'z') \
331 || ((c) >= 'A' && (c) <= 'Z')) \
332 : SYNTAX (c) == Sword)
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 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
518 #ifndef emacs
519 # undef max
520 # undef min
521 # define max(a, b) ((a) > (b) ? (a) : (b))
522 # define min(a, b) ((a) < (b) ? (a) : (b))
523 #endif
525 /* Type of source-pattern and string chars. */
526 #ifdef _MSC_VER
527 typedef unsigned char re_char;
528 typedef const re_char const_re_char;
529 #else
530 typedef const unsigned char re_char;
531 typedef re_char const_re_char;
532 #endif
534 typedef char boolean;
536 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
537 re_char *string1, size_t size1,
538 re_char *string2, size_t size2,
539 ssize_t pos,
540 struct re_registers *regs,
541 ssize_t stop);
543 /* These are the command codes that appear in compiled regular
544 expressions. Some opcodes are followed by argument bytes. A
545 command code can specify any interpretation whatsoever for its
546 arguments. Zero bytes may appear in the compiled regular expression. */
548 typedef enum
550 no_op = 0,
552 /* Succeed right away--no more backtracking. */
553 succeed,
555 /* Followed by one byte giving n, then by n literal bytes. */
556 exactn,
558 /* Matches any (more or less) character. */
559 anychar,
561 /* Matches any one char belonging to specified set. First
562 following byte is number of bitmap bytes. Then come bytes
563 for a bitmap saying which chars are in. Bits in each byte
564 are ordered low-bit-first. A character is in the set if its
565 bit is 1. A character too large to have a bit in the map is
566 automatically not in the set.
568 If the length byte has the 0x80 bit set, then that stuff
569 is followed by a range table:
570 2 bytes of flags for character sets (low 8 bits, high 8 bits)
571 See RANGE_TABLE_WORK_BITS below.
572 2 bytes, the number of pairs that follow (upto 32767)
573 pairs, each 2 multibyte characters,
574 each multibyte character represented as 3 bytes. */
575 charset,
577 /* Same parameters as charset, but match any character that is
578 not one of those specified. */
579 charset_not,
581 /* Start remembering the text that is matched, for storing in a
582 register. Followed by one byte with the register number, in
583 the range 0 to one less than the pattern buffer's re_nsub
584 field. */
585 start_memory,
587 /* Stop remembering the text that is matched and store it in a
588 memory register. Followed by one byte with the register
589 number, in the range 0 to one less than `re_nsub' in the
590 pattern buffer. */
591 stop_memory,
593 /* Match a duplicate of something remembered. Followed by one
594 byte containing the register number. */
595 duplicate,
597 /* Fail unless at beginning of line. */
598 begline,
600 /* Fail unless at end of line. */
601 endline,
603 /* Succeeds if at beginning of buffer (if emacs) or at beginning
604 of string to be matched (if not). */
605 begbuf,
607 /* Analogously, for end of buffer/string. */
608 endbuf,
610 /* Followed by two byte relative address to which to jump. */
611 jump,
613 /* Followed by two-byte relative address of place to resume at
614 in case of failure. */
615 on_failure_jump,
617 /* Like on_failure_jump, but pushes a placeholder instead of the
618 current string position when executed. */
619 on_failure_keep_string_jump,
621 /* Just like `on_failure_jump', except that it checks that we
622 don't get stuck in an infinite loop (matching an empty string
623 indefinitely). */
624 on_failure_jump_loop,
626 /* Just like `on_failure_jump_loop', except that it checks for
627 a different kind of loop (the kind that shows up with non-greedy
628 operators). This operation has to be immediately preceded
629 by a `no_op'. */
630 on_failure_jump_nastyloop,
632 /* A smart `on_failure_jump' used for greedy * and + operators.
633 It analyzes the loop before which it is put and if the
634 loop does not require backtracking, it changes itself to
635 `on_failure_keep_string_jump' and short-circuits the loop,
636 else it just defaults to changing itself into `on_failure_jump'.
637 It assumes that it is pointing to just past a `jump'. */
638 on_failure_jump_smart,
640 /* Followed by two-byte relative address and two-byte number n.
641 After matching N times, jump to the address upon failure.
642 Does not work if N starts at 0: use on_failure_jump_loop
643 instead. */
644 succeed_n,
646 /* Followed by two-byte relative address, and two-byte number n.
647 Jump to the address N times, then fail. */
648 jump_n,
650 /* Set the following two-byte relative address to the
651 subsequent two-byte number. The address *includes* the two
652 bytes of number. */
653 set_number_at,
655 wordbeg, /* Succeeds if at word beginning. */
656 wordend, /* Succeeds if at word end. */
658 wordbound, /* Succeeds if at a word boundary. */
659 notwordbound, /* Succeeds if not at a word boundary. */
661 symbeg, /* Succeeds if at symbol beginning. */
662 symend, /* Succeeds if at symbol end. */
664 /* Matches any character whose syntax is specified. Followed by
665 a byte which contains a syntax code, e.g., Sword. */
666 syntaxspec,
668 /* Matches any character whose syntax is not that specified. */
669 notsyntaxspec
671 #ifdef emacs
672 ,before_dot, /* Succeeds if before point. */
673 at_dot, /* Succeeds if at point. */
674 after_dot, /* Succeeds if after point. */
676 /* Matches any character whose category-set contains the specified
677 category. The operator is followed by a byte which contains a
678 category code (mnemonic ASCII character). */
679 categoryspec,
681 /* Matches any character whose category-set does not contain the
682 specified category. The operator is followed by a byte which
683 contains the category code (mnemonic ASCII character). */
684 notcategoryspec
685 #endif /* emacs */
686 } re_opcode_t;
688 /* Common operations on the compiled pattern. */
690 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
692 #define STORE_NUMBER(destination, number) \
693 do { \
694 (destination)[0] = (number) & 0377; \
695 (destination)[1] = (number) >> 8; \
696 } while (0)
698 /* Same as STORE_NUMBER, except increment DESTINATION to
699 the byte after where the number is stored. Therefore, DESTINATION
700 must be an lvalue. */
702 #define STORE_NUMBER_AND_INCR(destination, number) \
703 do { \
704 STORE_NUMBER (destination, number); \
705 (destination) += 2; \
706 } while (0)
708 /* Put into DESTINATION a number stored in two contiguous bytes starting
709 at SOURCE. */
711 #define EXTRACT_NUMBER(destination, source) \
712 ((destination) = extract_number (source))
714 static int
715 extract_number (re_char *source)
717 unsigned leading_byte = SIGN_EXTEND_CHAR (source[1]);
718 return (leading_byte << 8) + source[0];
721 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
722 SOURCE must be an lvalue. */
724 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
725 ((destination) = extract_number_and_incr (&source))
727 static int
728 extract_number_and_incr (re_char **source)
730 int num = extract_number (*source);
731 *source += 2;
732 return num;
735 /* Store a multibyte character in three contiguous bytes starting
736 DESTINATION, and increment DESTINATION to the byte after where the
737 character is stored. Therefore, DESTINATION must be an lvalue. */
739 #define STORE_CHARACTER_AND_INCR(destination, character) \
740 do { \
741 (destination)[0] = (character) & 0377; \
742 (destination)[1] = ((character) >> 8) & 0377; \
743 (destination)[2] = (character) >> 16; \
744 (destination) += 3; \
745 } while (0)
747 /* Put into DESTINATION a character stored in three contiguous bytes
748 starting at SOURCE. */
750 #define EXTRACT_CHARACTER(destination, source) \
751 do { \
752 (destination) = ((source)[0] \
753 | ((source)[1] << 8) \
754 | ((source)[2] << 16)); \
755 } while (0)
758 /* Macros for charset. */
760 /* Size of bitmap of charset P in bytes. P is a start of charset,
761 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
762 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
764 /* Nonzero if charset P has range table. */
765 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
767 /* Return the address of range table of charset P. But not the start
768 of table itself, but the before where the number of ranges is
769 stored. `2 +' means to skip re_opcode_t and size of bitmap,
770 and the 2 bytes of flags at the start of the range table. */
771 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
773 #ifdef emacs
774 /* Extract the bit flags that start a range table. */
775 #define CHARSET_RANGE_TABLE_BITS(p) \
776 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
777 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
778 #endif
780 /* Return the address of end of RANGE_TABLE. COUNT is number of
781 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
782 is start of range and end of range. `* 3' is size of each start
783 and end. */
784 #define CHARSET_RANGE_TABLE_END(range_table, count) \
785 ((range_table) + (count) * 2 * 3)
787 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
788 COUNT is number of ranges in RANGE_TABLE. */
789 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
790 do \
792 re_wchar_t range_start, range_end; \
793 re_char *rtp; \
794 re_char *range_table_end \
795 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
797 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
799 EXTRACT_CHARACTER (range_start, rtp); \
800 EXTRACT_CHARACTER (range_end, rtp + 3); \
802 if (range_start <= (c) && (c) <= range_end) \
804 (not) = !(not); \
805 break; \
809 while (0)
811 /* Test if C is in range table of CHARSET. The flag NOT is negated if
812 C is listed in it. */
813 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
814 do \
816 /* Number of ranges in range table. */ \
817 int count; \
818 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
820 EXTRACT_NUMBER_AND_INCR (count, range_table); \
821 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
823 while (0)
825 /* If DEBUG is defined, Regex prints many voluminous messages about what
826 it is doing (if the variable `debug' is nonzero). If linked with the
827 main program in `iregex.c', you can enter patterns and strings
828 interactively. And if linked with the main program in `main.c' and
829 the other test files, you can run the already-written tests. */
831 #ifdef DEBUG
833 /* We use standard I/O for debugging. */
834 # include <stdio.h>
836 /* It is useful to test things that ``must'' be true when debugging. */
837 # include <assert.h>
839 static int debug = -100000;
841 # define DEBUG_STATEMENT(e) e
842 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
843 # define DEBUG_COMPILES_ARGUMENTS
844 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
845 if (debug > 0) print_partial_compiled_pattern (s, e)
846 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
847 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
850 /* Print the fastmap in human-readable form. */
852 static void
853 print_fastmap (char *fastmap)
855 unsigned was_a_range = 0;
856 unsigned i = 0;
858 while (i < (1 << BYTEWIDTH))
860 if (fastmap[i++])
862 was_a_range = 0;
863 putchar (i - 1);
864 while (i < (1 << BYTEWIDTH) && fastmap[i])
866 was_a_range = 1;
867 i++;
869 if (was_a_range)
871 printf ("-");
872 putchar (i - 1);
876 putchar ('\n');
880 /* Print a compiled pattern string in human-readable form, starting at
881 the START pointer into it and ending just before the pointer END. */
883 static void
884 print_partial_compiled_pattern (re_char *start, re_char *end)
886 int mcnt, mcnt2;
887 re_char *p = start;
888 re_char *pend = end;
890 if (start == NULL)
892 fprintf (stderr, "(null)\n");
893 return;
896 /* Loop over pattern commands. */
897 while (p < pend)
899 fprintf (stderr, "%td:\t", p - start);
901 switch ((re_opcode_t) *p++)
903 case no_op:
904 fprintf (stderr, "/no_op");
905 break;
907 case succeed:
908 fprintf (stderr, "/succeed");
909 break;
911 case exactn:
912 mcnt = *p++;
913 fprintf (stderr, "/exactn/%d", mcnt);
916 fprintf (stderr, "/%c", *p++);
918 while (--mcnt);
919 break;
921 case start_memory:
922 fprintf (stderr, "/start_memory/%d", *p++);
923 break;
925 case stop_memory:
926 fprintf (stderr, "/stop_memory/%d", *p++);
927 break;
929 case duplicate:
930 fprintf (stderr, "/duplicate/%d", *p++);
931 break;
933 case anychar:
934 fprintf (stderr, "/anychar");
935 break;
937 case charset:
938 case charset_not:
940 register int c, last = -100;
941 register int in_range = 0;
942 int length = CHARSET_BITMAP_SIZE (p - 1);
943 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
945 fprintf (stderr, "/charset [%s",
946 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
948 if (p + *p >= pend)
949 fprintf (stderr, " !extends past end of pattern! ");
951 for (c = 0; c < 256; c++)
952 if (c / 8 < length
953 && (p[1 + (c/8)] & (1 << (c % 8))))
955 /* Are we starting a range? */
956 if (last + 1 == c && ! in_range)
958 fprintf (stderr, "-");
959 in_range = 1;
961 /* Have we broken a range? */
962 else if (last + 1 != c && in_range)
964 fprintf (stderr, "%c", last);
965 in_range = 0;
968 if (! in_range)
969 fprintf (stderr, "%c", c);
971 last = c;
974 if (in_range)
975 fprintf (stderr, "%c", last);
977 fprintf (stderr, "]");
979 p += 1 + length;
981 if (has_range_table)
983 int count;
984 fprintf (stderr, "has-range-table");
986 /* ??? Should print the range table; for now, just skip it. */
987 p += 2; /* skip range table bits */
988 EXTRACT_NUMBER_AND_INCR (count, p);
989 p = CHARSET_RANGE_TABLE_END (p, count);
992 break;
994 case begline:
995 fprintf (stderr, "/begline");
996 break;
998 case endline:
999 fprintf (stderr, "/endline");
1000 break;
1002 case on_failure_jump:
1003 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1004 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
1005 break;
1007 case on_failure_keep_string_jump:
1008 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1009 fprintf (stderr, "/on_failure_keep_string_jump to %td",
1010 p + mcnt - start);
1011 break;
1013 case on_failure_jump_nastyloop:
1014 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1015 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
1016 p + mcnt - start);
1017 break;
1019 case on_failure_jump_loop:
1020 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1021 fprintf (stderr, "/on_failure_jump_loop to %td",
1022 p + mcnt - start);
1023 break;
1025 case on_failure_jump_smart:
1026 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1027 fprintf (stderr, "/on_failure_jump_smart to %td",
1028 p + mcnt - start);
1029 break;
1031 case jump:
1032 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1033 fprintf (stderr, "/jump to %td", p + mcnt - start);
1034 break;
1036 case succeed_n:
1037 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1038 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1039 fprintf (stderr, "/succeed_n to %td, %d times",
1040 p - 2 + mcnt - start, mcnt2);
1041 break;
1043 case jump_n:
1044 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1045 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1046 fprintf (stderr, "/jump_n to %td, %d times",
1047 p - 2 + mcnt - start, mcnt2);
1048 break;
1050 case set_number_at:
1051 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1052 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1053 fprintf (stderr, "/set_number_at location %td to %d",
1054 p - 2 + mcnt - start, mcnt2);
1055 break;
1057 case wordbound:
1058 fprintf (stderr, "/wordbound");
1059 break;
1061 case notwordbound:
1062 fprintf (stderr, "/notwordbound");
1063 break;
1065 case wordbeg:
1066 fprintf (stderr, "/wordbeg");
1067 break;
1069 case wordend:
1070 fprintf (stderr, "/wordend");
1071 break;
1073 case symbeg:
1074 fprintf (stderr, "/symbeg");
1075 break;
1077 case symend:
1078 fprintf (stderr, "/symend");
1079 break;
1081 case syntaxspec:
1082 fprintf (stderr, "/syntaxspec");
1083 mcnt = *p++;
1084 fprintf (stderr, "/%d", mcnt);
1085 break;
1087 case notsyntaxspec:
1088 fprintf (stderr, "/notsyntaxspec");
1089 mcnt = *p++;
1090 fprintf (stderr, "/%d", mcnt);
1091 break;
1093 # ifdef emacs
1094 case before_dot:
1095 fprintf (stderr, "/before_dot");
1096 break;
1098 case at_dot:
1099 fprintf (stderr, "/at_dot");
1100 break;
1102 case after_dot:
1103 fprintf (stderr, "/after_dot");
1104 break;
1106 case categoryspec:
1107 fprintf (stderr, "/categoryspec");
1108 mcnt = *p++;
1109 fprintf (stderr, "/%d", mcnt);
1110 break;
1112 case notcategoryspec:
1113 fprintf (stderr, "/notcategoryspec");
1114 mcnt = *p++;
1115 fprintf (stderr, "/%d", mcnt);
1116 break;
1117 # endif /* emacs */
1119 case begbuf:
1120 fprintf (stderr, "/begbuf");
1121 break;
1123 case endbuf:
1124 fprintf (stderr, "/endbuf");
1125 break;
1127 default:
1128 fprintf (stderr, "?%d", *(p-1));
1131 fprintf (stderr, "\n");
1134 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1138 static void
1139 print_compiled_pattern (struct re_pattern_buffer *bufp)
1141 re_char *buffer = bufp->buffer;
1143 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1144 printf ("%ld bytes used/%ld bytes allocated.\n",
1145 bufp->used, bufp->allocated);
1147 if (bufp->fastmap_accurate && bufp->fastmap)
1149 printf ("fastmap: ");
1150 print_fastmap (bufp->fastmap);
1153 printf ("re_nsub: %zu\t", bufp->re_nsub);
1154 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1155 printf ("can_be_null: %d\t", bufp->can_be_null);
1156 printf ("no_sub: %d\t", bufp->no_sub);
1157 printf ("not_bol: %d\t", bufp->not_bol);
1158 printf ("not_eol: %d\t", bufp->not_eol);
1159 printf ("syntax: %lx\n", bufp->syntax);
1160 fflush (stdout);
1161 /* Perhaps we should print the translate table? */
1165 static void
1166 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1167 re_char *string2, ssize_t size2)
1169 ssize_t this_char;
1171 if (where == NULL)
1172 printf ("(null)");
1173 else
1175 if (FIRST_STRING_P (where))
1177 for (this_char = where - string1; this_char < size1; this_char++)
1178 putchar (string1[this_char]);
1180 where = string2;
1183 for (this_char = where - string2; this_char < size2; this_char++)
1184 putchar (string2[this_char]);
1188 #else /* not DEBUG */
1190 # undef assert
1191 # define assert(e)
1193 # define DEBUG_STATEMENT(e)
1194 # define DEBUG_PRINT(...)
1195 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1196 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1198 #endif /* not DEBUG */
1200 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1201 #ifdef lint
1202 # define IF_LINT(Code) Code
1203 #else
1204 # define IF_LINT(Code) /* empty */
1205 #endif
1207 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1208 also be assigned to arbitrarily: each pattern buffer stores its own
1209 syntax, so it can be changed between regex compilations. */
1210 /* This has no initializer because initialized variables in Emacs
1211 become read-only after dumping. */
1212 reg_syntax_t re_syntax_options;
1215 /* Specify the precise syntax of regexps for compilation. This provides
1216 for compatibility for various utilities which historically have
1217 different, incompatible syntaxes.
1219 The argument SYNTAX is a bit mask comprised of the various bits
1220 defined in regex.h. We return the old syntax. */
1222 reg_syntax_t
1223 re_set_syntax (reg_syntax_t syntax)
1225 reg_syntax_t ret = re_syntax_options;
1227 re_syntax_options = syntax;
1228 return ret;
1230 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1232 /* Regexp to use to replace spaces, or NULL meaning don't. */
1233 static const_re_char *whitespace_regexp;
1235 void
1236 re_set_whitespace_regexp (const char *regexp)
1238 whitespace_regexp = (const_re_char *) regexp;
1240 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1242 /* This table gives an error message for each of the error codes listed
1243 in regex.h. Obviously the order here has to be same as there.
1244 POSIX doesn't require that we do anything for REG_NOERROR,
1245 but why not be nice? */
1247 static const char *re_error_msgid[] =
1249 gettext_noop ("Success"), /* REG_NOERROR */
1250 gettext_noop ("No match"), /* REG_NOMATCH */
1251 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1252 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1253 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1254 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1255 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1256 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1257 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1258 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1259 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1260 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1261 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1262 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1263 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1264 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1265 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1266 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1269 /* Avoiding alloca during matching, to placate r_alloc. */
1271 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1272 searching and matching functions should not call alloca. On some
1273 systems, alloca is implemented in terms of malloc, and if we're
1274 using the relocating allocator routines, then malloc could cause a
1275 relocation, which might (if the strings being searched are in the
1276 ralloc heap) shift the data out from underneath the regexp
1277 routines.
1279 Here's another reason to avoid allocation: Emacs
1280 processes input from X in a signal handler; processing X input may
1281 call malloc; if input arrives while a matching routine is calling
1282 malloc, then we're scrod. But Emacs can't just block input while
1283 calling matching routines; then we don't notice interrupts when
1284 they come in. So, Emacs blocks input around all regexp calls
1285 except the matching calls, which it leaves unprotected, in the
1286 faith that they will not malloc. */
1288 /* Normally, this is fine. */
1289 #define MATCH_MAY_ALLOCATE
1291 /* The match routines may not allocate if (1) they would do it with malloc
1292 and (2) it's not safe for them to use malloc.
1293 Note that if REL_ALLOC is defined, matching would not use malloc for the
1294 failure stack, but we would still use it for the register vectors;
1295 so REL_ALLOC should not affect this. */
1296 #if defined REGEX_MALLOC && defined emacs
1297 # undef MATCH_MAY_ALLOCATE
1298 #endif
1301 /* Failure stack declarations and macros; both re_compile_fastmap and
1302 re_match_2 use a failure stack. These have to be macros because of
1303 REGEX_ALLOCATE_STACK. */
1306 /* Approximate number of failure points for which to initially allocate space
1307 when matching. If this number is exceeded, we allocate more
1308 space, so it is not a hard limit. */
1309 #ifndef INIT_FAILURE_ALLOC
1310 # define INIT_FAILURE_ALLOC 20
1311 #endif
1313 /* Roughly the maximum number of failure points on the stack. Would be
1314 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1315 This is a variable only so users of regex can assign to it; we never
1316 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1317 before using it, so it should probably be a byte-count instead. */
1318 # if defined MATCH_MAY_ALLOCATE
1319 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1320 whose default stack limit is 2mb. In order for a larger
1321 value to work reliably, you have to try to make it accord
1322 with the process stack limit. */
1323 size_t re_max_failures = 40000;
1324 # else
1325 size_t re_max_failures = 4000;
1326 # endif
1328 union fail_stack_elt
1330 re_char *pointer;
1331 /* This should be the biggest `int' that's no bigger than a pointer. */
1332 long integer;
1335 typedef union fail_stack_elt fail_stack_elt_t;
1337 typedef struct
1339 fail_stack_elt_t *stack;
1340 size_t size;
1341 size_t avail; /* Offset of next open position. */
1342 size_t frame; /* Offset of the cur constructed frame. */
1343 } fail_stack_type;
1345 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1348 /* Define macros to initialize and free the failure stack.
1349 Do `return -2' if the alloc fails. */
1351 #ifdef MATCH_MAY_ALLOCATE
1352 # define INIT_FAIL_STACK() \
1353 do { \
1354 fail_stack.stack = \
1355 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1356 * sizeof (fail_stack_elt_t)); \
1358 if (fail_stack.stack == NULL) \
1359 return -2; \
1361 fail_stack.size = INIT_FAILURE_ALLOC; \
1362 fail_stack.avail = 0; \
1363 fail_stack.frame = 0; \
1364 } while (0)
1365 #else
1366 # define INIT_FAIL_STACK() \
1367 do { \
1368 fail_stack.avail = 0; \
1369 fail_stack.frame = 0; \
1370 } while (0)
1372 # define RETALLOC_IF(addr, n, t) \
1373 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1374 #endif
1377 /* Double the size of FAIL_STACK, up to a limit
1378 which allows approximately `re_max_failures' items.
1380 Return 1 if succeeds, and 0 if either ran out of memory
1381 allocating space for it or it was already too large.
1383 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1385 /* Factor to increase the failure stack size by
1386 when we increase it.
1387 This used to be 2, but 2 was too wasteful
1388 because the old discarded stacks added up to as much space
1389 were as ultimate, maximum-size stack. */
1390 #define FAIL_STACK_GROWTH_FACTOR 4
1392 #define GROW_FAIL_STACK(fail_stack) \
1393 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1394 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1395 ? 0 \
1396 : ((fail_stack).stack \
1397 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1398 (fail_stack).size * sizeof (fail_stack_elt_t), \
1399 min (re_max_failures * TYPICAL_FAILURE_SIZE, \
1400 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1401 * FAIL_STACK_GROWTH_FACTOR))), \
1403 (fail_stack).stack == NULL \
1404 ? 0 \
1405 : ((fail_stack).size \
1406 = (min (re_max_failures * TYPICAL_FAILURE_SIZE, \
1407 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1408 * FAIL_STACK_GROWTH_FACTOR)) \
1409 / sizeof (fail_stack_elt_t)), \
1410 1)))
1413 /* Push a pointer value onto the failure stack.
1414 Assumes the variable `fail_stack'. Probably should only
1415 be called from within `PUSH_FAILURE_POINT'. */
1416 #define PUSH_FAILURE_POINTER(item) \
1417 fail_stack.stack[fail_stack.avail++].pointer = (item)
1419 /* This pushes an integer-valued item onto the failure stack.
1420 Assumes the variable `fail_stack'. Probably should only
1421 be called from within `PUSH_FAILURE_POINT'. */
1422 #define PUSH_FAILURE_INT(item) \
1423 fail_stack.stack[fail_stack.avail++].integer = (item)
1425 /* These POP... operations complement the PUSH... operations.
1426 All assume that `fail_stack' is nonempty. */
1427 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1428 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1430 /* Individual items aside from the registers. */
1431 #define NUM_NONREG_ITEMS 3
1433 /* Used to examine the stack (to detect infinite loops). */
1434 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1435 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1436 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1437 #define TOP_FAILURE_HANDLE() fail_stack.frame
1440 #define ENSURE_FAIL_STACK(space) \
1441 while (REMAINING_AVAIL_SLOTS <= space) { \
1442 if (!GROW_FAIL_STACK (fail_stack)) \
1443 return -2; \
1444 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1445 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1448 /* Push register NUM onto the stack. */
1449 #define PUSH_FAILURE_REG(num) \
1450 do { \
1451 char *destination; \
1452 long n = num; \
1453 ENSURE_FAIL_STACK(3); \
1454 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1455 n, regstart[n], regend[n]); \
1456 PUSH_FAILURE_POINTER (regstart[n]); \
1457 PUSH_FAILURE_POINTER (regend[n]); \
1458 PUSH_FAILURE_INT (n); \
1459 } while (0)
1461 /* Change the counter's value to VAL, but make sure that it will
1462 be reset when backtracking. */
1463 #define PUSH_NUMBER(ptr,val) \
1464 do { \
1465 char *destination; \
1466 int c; \
1467 ENSURE_FAIL_STACK(3); \
1468 EXTRACT_NUMBER (c, ptr); \
1469 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1470 PUSH_FAILURE_INT (c); \
1471 PUSH_FAILURE_POINTER (ptr); \
1472 PUSH_FAILURE_INT (-1); \
1473 STORE_NUMBER (ptr, val); \
1474 } while (0)
1476 /* Pop a saved register off the stack. */
1477 #define POP_FAILURE_REG_OR_COUNT() \
1478 do { \
1479 long pfreg = POP_FAILURE_INT (); \
1480 if (pfreg == -1) \
1482 /* It's a counter. */ \
1483 /* Here, we discard `const', making re_match non-reentrant. */ \
1484 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1485 pfreg = POP_FAILURE_INT (); \
1486 STORE_NUMBER (ptr, pfreg); \
1487 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1489 else \
1491 regend[pfreg] = POP_FAILURE_POINTER (); \
1492 regstart[pfreg] = POP_FAILURE_POINTER (); \
1493 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1494 pfreg, regstart[pfreg], regend[pfreg]); \
1496 } while (0)
1498 /* Check that we are not stuck in an infinite loop. */
1499 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1500 do { \
1501 ssize_t failure = TOP_FAILURE_HANDLE (); \
1502 /* Check for infinite matching loops */ \
1503 while (failure > 0 \
1504 && (FAILURE_STR (failure) == string_place \
1505 || FAILURE_STR (failure) == NULL)) \
1507 assert (FAILURE_PAT (failure) >= bufp->buffer \
1508 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1509 if (FAILURE_PAT (failure) == pat_cur) \
1511 cycle = 1; \
1512 break; \
1514 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1515 failure = NEXT_FAILURE_HANDLE(failure); \
1517 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1518 } while (0)
1520 /* Push the information about the state we will need
1521 if we ever fail back to it.
1523 Requires variables fail_stack, regstart, regend and
1524 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1525 declared.
1527 Does `return FAILURE_CODE' if runs out of memory. */
1529 #define PUSH_FAILURE_POINT(pattern, string_place) \
1530 do { \
1531 char *destination; \
1532 /* Must be int, so when we don't save any registers, the arithmetic \
1533 of 0 + -1 isn't done as unsigned. */ \
1535 DEBUG_STATEMENT (nfailure_points_pushed++); \
1536 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1537 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1538 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1540 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1542 DEBUG_PRINT ("\n"); \
1544 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1545 PUSH_FAILURE_INT (fail_stack.frame); \
1547 DEBUG_PRINT (" Push string %p: `", string_place); \
1548 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1549 DEBUG_PRINT ("'\n"); \
1550 PUSH_FAILURE_POINTER (string_place); \
1552 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1553 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1554 PUSH_FAILURE_POINTER (pattern); \
1556 /* Close the frame by moving the frame pointer past it. */ \
1557 fail_stack.frame = fail_stack.avail; \
1558 } while (0)
1560 /* Estimate the size of data pushed by a typical failure stack entry.
1561 An estimate is all we need, because all we use this for
1562 is to choose a limit for how big to make the failure stack. */
1563 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1564 #define TYPICAL_FAILURE_SIZE 20
1566 /* How many items can still be added to the stack without overflowing it. */
1567 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1570 /* Pops what PUSH_FAIL_STACK pushes.
1572 We restore into the parameters, all of which should be lvalues:
1573 STR -- the saved data position.
1574 PAT -- the saved pattern position.
1575 REGSTART, REGEND -- arrays of string positions.
1577 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1578 `pend', `string1', `size1', `string2', and `size2'. */
1580 #define POP_FAILURE_POINT(str, pat) \
1581 do { \
1582 assert (!FAIL_STACK_EMPTY ()); \
1584 /* Remove failure points and point to how many regs pushed. */ \
1585 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1586 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1587 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1589 /* Pop the saved registers. */ \
1590 while (fail_stack.frame < fail_stack.avail) \
1591 POP_FAILURE_REG_OR_COUNT (); \
1593 pat = POP_FAILURE_POINTER (); \
1594 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1595 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1597 /* If the saved string location is NULL, it came from an \
1598 on_failure_keep_string_jump opcode, and we want to throw away the \
1599 saved NULL, thus retaining our current position in the string. */ \
1600 str = POP_FAILURE_POINTER (); \
1601 DEBUG_PRINT (" Popping string %p: `", str); \
1602 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1603 DEBUG_PRINT ("'\n"); \
1605 fail_stack.frame = POP_FAILURE_INT (); \
1606 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1608 assert (fail_stack.avail >= 0); \
1609 assert (fail_stack.frame <= fail_stack.avail); \
1611 DEBUG_STATEMENT (nfailure_points_popped++); \
1612 } while (0) /* POP_FAILURE_POINT */
1616 /* Registers are set to a sentinel when they haven't yet matched. */
1617 #define REG_UNSET(e) ((e) == NULL)
1619 /* Subroutine declarations and macros for regex_compile. */
1621 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1622 reg_syntax_t syntax,
1623 struct re_pattern_buffer *bufp);
1624 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1625 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1626 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1627 int arg, unsigned char *end);
1628 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1629 int arg1, int arg2, unsigned char *end);
1630 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1631 reg_syntax_t syntax);
1632 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1633 reg_syntax_t syntax);
1634 static re_char *skip_one_char (re_char *p);
1635 static int analyze_first (re_char *p, re_char *pend,
1636 char *fastmap, const int multibyte);
1638 /* Fetch the next character in the uncompiled pattern, with no
1639 translation. */
1640 #define PATFETCH(c) \
1641 do { \
1642 int len; \
1643 if (p == pend) return REG_EEND; \
1644 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1645 p += len; \
1646 } while (0)
1649 /* If `translate' is non-null, return translate[D], else just D. We
1650 cast the subscript to translate because some data is declared as
1651 `char *', to avoid warnings when a string constant is passed. But
1652 when we use a character as a subscript we must make it unsigned. */
1653 #ifndef TRANSLATE
1654 # define TRANSLATE(d) \
1655 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1656 #endif
1659 /* Macros for outputting the compiled pattern into `buffer'. */
1661 /* If the buffer isn't allocated when it comes in, use this. */
1662 #define INIT_BUF_SIZE 32
1664 /* Make sure we have at least N more bytes of space in buffer. */
1665 #define GET_BUFFER_SPACE(n) \
1666 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1667 EXTEND_BUFFER ()
1669 /* Make sure we have one more byte of buffer space and then add C to it. */
1670 #define BUF_PUSH(c) \
1671 do { \
1672 GET_BUFFER_SPACE (1); \
1673 *b++ = (unsigned char) (c); \
1674 } while (0)
1677 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1678 #define BUF_PUSH_2(c1, c2) \
1679 do { \
1680 GET_BUFFER_SPACE (2); \
1681 *b++ = (unsigned char) (c1); \
1682 *b++ = (unsigned char) (c2); \
1683 } while (0)
1686 /* Store a jump with opcode OP at LOC to location TO. We store a
1687 relative address offset by the three bytes the jump itself occupies. */
1688 #define STORE_JUMP(op, loc, to) \
1689 store_op1 (op, loc, (to) - (loc) - 3)
1691 /* Likewise, for a two-argument jump. */
1692 #define STORE_JUMP2(op, loc, to, arg) \
1693 store_op2 (op, loc, (to) - (loc) - 3, arg)
1695 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1696 #define INSERT_JUMP(op, loc, to) \
1697 insert_op1 (op, loc, (to) - (loc) - 3, b)
1699 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1700 #define INSERT_JUMP2(op, loc, to, arg) \
1701 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1704 /* This is not an arbitrary limit: the arguments which represent offsets
1705 into the pattern are two bytes long. So if 2^15 bytes turns out to
1706 be too small, many things would have to change. */
1707 # define MAX_BUF_SIZE (1L << 15)
1709 /* Extend the buffer by twice its current size via realloc and
1710 reset the pointers that pointed into the old block to point to the
1711 correct places in the new one. If extending the buffer results in it
1712 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1713 #if __BOUNDED_POINTERS__
1714 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1715 # define MOVE_BUFFER_POINTER(P) \
1716 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1717 SET_HIGH_BOUND (P), \
1718 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1719 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1720 else \
1722 SET_HIGH_BOUND (b); \
1723 SET_HIGH_BOUND (begalt); \
1724 if (fixup_alt_jump) \
1725 SET_HIGH_BOUND (fixup_alt_jump); \
1726 if (laststart) \
1727 SET_HIGH_BOUND (laststart); \
1728 if (pending_exact) \
1729 SET_HIGH_BOUND (pending_exact); \
1731 #else
1732 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1733 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1734 #endif
1735 #define EXTEND_BUFFER() \
1736 do { \
1737 unsigned char *old_buffer = bufp->buffer; \
1738 if (bufp->allocated == MAX_BUF_SIZE) \
1739 return REG_ESIZE; \
1740 bufp->allocated <<= 1; \
1741 if (bufp->allocated > MAX_BUF_SIZE) \
1742 bufp->allocated = MAX_BUF_SIZE; \
1743 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1744 if (bufp->buffer == NULL) \
1745 return REG_ESPACE; \
1746 /* If the buffer moved, move all the pointers into it. */ \
1747 if (old_buffer != bufp->buffer) \
1749 unsigned char *new_buffer = bufp->buffer; \
1750 MOVE_BUFFER_POINTER (b); \
1751 MOVE_BUFFER_POINTER (begalt); \
1752 if (fixup_alt_jump) \
1753 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1754 if (laststart) \
1755 MOVE_BUFFER_POINTER (laststart); \
1756 if (pending_exact) \
1757 MOVE_BUFFER_POINTER (pending_exact); \
1759 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1760 } while (0)
1763 /* Since we have one byte reserved for the register number argument to
1764 {start,stop}_memory, the maximum number of groups we can report
1765 things about is what fits in that byte. */
1766 #define MAX_REGNUM 255
1768 /* But patterns can have more than `MAX_REGNUM' registers. We just
1769 ignore the excess. */
1770 typedef int regnum_t;
1773 /* Macros for the compile stack. */
1775 /* Since offsets can go either forwards or backwards, this type needs to
1776 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1777 /* int may be not enough when sizeof(int) == 2. */
1778 typedef long pattern_offset_t;
1780 typedef struct
1782 pattern_offset_t begalt_offset;
1783 pattern_offset_t fixup_alt_jump;
1784 pattern_offset_t laststart_offset;
1785 regnum_t regnum;
1786 } compile_stack_elt_t;
1789 typedef struct
1791 compile_stack_elt_t *stack;
1792 size_t size;
1793 size_t avail; /* Offset of next open position. */
1794 } compile_stack_type;
1797 #define INIT_COMPILE_STACK_SIZE 32
1799 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1800 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1802 /* The next available element. */
1803 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1805 /* Explicit quit checking is needed for Emacs, which uses polling to
1806 process input events. */
1807 #ifdef emacs
1808 # define IMMEDIATE_QUIT_CHECK \
1809 do { \
1810 if (immediate_quit) QUIT; \
1811 } while (0)
1812 #else
1813 # define IMMEDIATE_QUIT_CHECK ((void)0)
1814 #endif
1816 /* Structure to manage work area for range table. */
1817 struct range_table_work_area
1819 int *table; /* actual work area. */
1820 int allocated; /* allocated size for work area in bytes. */
1821 int used; /* actually used size in words. */
1822 int bits; /* flag to record character classes */
1825 #ifdef emacs
1827 /* Make sure that WORK_AREA can hold more N multibyte characters.
1828 This is used only in set_image_of_range and set_image_of_range_1.
1829 It expects WORK_AREA to be a pointer.
1830 If it can't get the space, it returns from the surrounding function. */
1832 #define EXTEND_RANGE_TABLE(work_area, n) \
1833 do { \
1834 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1836 extend_range_table_work_area (&work_area); \
1837 if ((work_area).table == 0) \
1838 return (REG_ESPACE); \
1840 } while (0)
1842 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1843 (work_area).bits |= (bit)
1845 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1846 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1847 do { \
1848 EXTEND_RANGE_TABLE ((work_area), 2); \
1849 (work_area).table[(work_area).used++] = (range_start); \
1850 (work_area).table[(work_area).used++] = (range_end); \
1851 } while (0)
1853 #endif /* emacs */
1855 /* Free allocated memory for WORK_AREA. */
1856 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1857 do { \
1858 if ((work_area).table) \
1859 free ((work_area).table); \
1860 } while (0)
1862 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1863 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1864 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1865 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1867 /* Bits used to implement the multibyte-part of the various character classes
1868 such as [:alnum:] in a charset's range table. */
1869 #define BIT_WORD 0x1
1870 #define BIT_LOWER 0x2
1871 #define BIT_PUNCT 0x4
1872 #define BIT_SPACE 0x8
1873 #define BIT_UPPER 0x10
1874 #define BIT_MULTIBYTE 0x20
1877 /* Set the bit for character C in a list. */
1878 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1881 #ifdef emacs
1883 /* Store characters in the range FROM to TO in the bitmap at B (for
1884 ASCII and unibyte characters) and WORK_AREA (for multibyte
1885 characters) while translating them and paying attention to the
1886 continuity of translated characters.
1888 Implementation note: It is better to implement these fairly big
1889 macros by a function, but it's not that easy because macros called
1890 in this macro assume various local variables already declared. */
1892 /* Both FROM and TO are ASCII characters. */
1894 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1895 do { \
1896 int C0, C1; \
1898 for (C0 = (FROM); C0 <= (TO); C0++) \
1900 C1 = TRANSLATE (C0); \
1901 if (! ASCII_CHAR_P (C1)) \
1903 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1904 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1905 C1 = C0; \
1907 SET_LIST_BIT (C1); \
1909 } while (0)
1912 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1914 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1915 do { \
1916 int C0, C1, C2, I; \
1917 int USED = RANGE_TABLE_WORK_USED (work_area); \
1919 for (C0 = (FROM); C0 <= (TO); C0++) \
1921 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1922 if (CHAR_BYTE8_P (C1)) \
1923 SET_LIST_BIT (C0); \
1924 else \
1926 C2 = TRANSLATE (C1); \
1927 if (C2 == C1 \
1928 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1929 C1 = C0; \
1930 SET_LIST_BIT (C1); \
1931 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1933 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1934 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1936 if (C2 >= from - 1 && C2 <= to + 1) \
1938 if (C2 == from - 1) \
1939 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1940 else if (C2 == to + 1) \
1941 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1942 break; \
1945 if (I < USED) \
1946 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1949 } while (0)
1952 /* Both FROM and TO are multibyte characters. */
1954 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1955 do { \
1956 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1958 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1959 for (C0 = (FROM); C0 <= (TO); C0++) \
1961 C1 = TRANSLATE (C0); \
1962 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1963 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1964 SET_LIST_BIT (C2); \
1965 if (C1 >= (FROM) && C1 <= (TO)) \
1966 continue; \
1967 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1969 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1970 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1972 if (C1 >= from - 1 && C1 <= to + 1) \
1974 if (C1 == from - 1) \
1975 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1976 else if (C1 == to + 1) \
1977 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1978 break; \
1981 if (I < USED) \
1982 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1984 } while (0)
1986 #endif /* emacs */
1988 /* Get the next unsigned number in the uncompiled pattern. */
1989 #define GET_INTERVAL_COUNT(num) \
1990 do { \
1991 if (p == pend) \
1992 FREE_STACK_RETURN (REG_EBRACE); \
1993 else \
1995 PATFETCH (c); \
1996 while ('0' <= c && c <= '9') \
1998 if (num < 0) \
1999 num = 0; \
2000 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
2001 FREE_STACK_RETURN (REG_BADBR); \
2002 num = num * 10 + c - '0'; \
2003 if (p == pend) \
2004 FREE_STACK_RETURN (REG_EBRACE); \
2005 PATFETCH (c); \
2008 } while (0)
2010 #if ! WIDE_CHAR_SUPPORT
2012 /* Map a string to the char class it names (if any). */
2013 re_wctype_t
2014 re_wctype (const_re_char *str)
2016 const char *string = (const char *) str;
2017 if (STREQ (string, "alnum")) return RECC_ALNUM;
2018 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2019 else if (STREQ (string, "word")) return RECC_WORD;
2020 else if (STREQ (string, "ascii")) return RECC_ASCII;
2021 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2022 else if (STREQ (string, "graph")) return RECC_GRAPH;
2023 else if (STREQ (string, "lower")) return RECC_LOWER;
2024 else if (STREQ (string, "print")) return RECC_PRINT;
2025 else if (STREQ (string, "punct")) return RECC_PUNCT;
2026 else if (STREQ (string, "space")) return RECC_SPACE;
2027 else if (STREQ (string, "upper")) return RECC_UPPER;
2028 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2029 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2030 else if (STREQ (string, "digit")) return RECC_DIGIT;
2031 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2032 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2033 else if (STREQ (string, "blank")) return RECC_BLANK;
2034 else return 0;
2037 /* True if CH is in the char class CC. */
2038 boolean
2039 re_iswctype (int ch, re_wctype_t cc)
2041 switch (cc)
2043 case RECC_ALNUM: return ISALNUM (ch) != 0;
2044 case RECC_ALPHA: return ISALPHA (ch) != 0;
2045 case RECC_BLANK: return ISBLANK (ch) != 0;
2046 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2047 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2048 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2049 case RECC_LOWER: return ISLOWER (ch) != 0;
2050 case RECC_PRINT: return ISPRINT (ch) != 0;
2051 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2052 case RECC_SPACE: return ISSPACE (ch) != 0;
2053 case RECC_UPPER: return ISUPPER (ch) != 0;
2054 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2055 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2056 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2057 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2058 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2059 case RECC_WORD: return ISWORD (ch) != 0;
2060 case RECC_ERROR: return false;
2061 default:
2062 abort ();
2066 /* Return a bit-pattern to use in the range-table bits to match multibyte
2067 chars of class CC. */
2068 static int
2069 re_wctype_to_bit (re_wctype_t cc)
2071 switch (cc)
2073 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2074 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2075 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2076 case RECC_LOWER: return BIT_LOWER;
2077 case RECC_UPPER: return BIT_UPPER;
2078 case RECC_PUNCT: return BIT_PUNCT;
2079 case RECC_SPACE: return BIT_SPACE;
2080 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2081 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2082 default:
2083 abort ();
2086 #endif
2088 /* Filling in the work area of a range. */
2090 /* Actually extend the space in WORK_AREA. */
2092 static void
2093 extend_range_table_work_area (struct range_table_work_area *work_area)
2095 work_area->allocated += 16 * sizeof (int);
2096 work_area->table = realloc (work_area->table, work_area->allocated);
2099 #if 0
2100 #ifdef emacs
2102 /* Carefully find the ranges of codes that are equivalent
2103 under case conversion to the range start..end when passed through
2104 TRANSLATE. Handle the case where non-letters can come in between
2105 two upper-case letters (which happens in Latin-1).
2106 Also handle the case of groups of more than 2 case-equivalent chars.
2108 The basic method is to look at consecutive characters and see
2109 if they can form a run that can be handled as one.
2111 Returns -1 if successful, REG_ESPACE if ran out of space. */
2113 static int
2114 set_image_of_range_1 (struct range_table_work_area *work_area,
2115 re_wchar_t start, re_wchar_t end,
2116 RE_TRANSLATE_TYPE translate)
2118 /* `one_case' indicates a character, or a run of characters,
2119 each of which is an isolate (no case-equivalents).
2120 This includes all ASCII non-letters.
2122 `two_case' indicates a character, or a run of characters,
2123 each of which has two case-equivalent forms.
2124 This includes all ASCII letters.
2126 `strange' indicates a character that has more than one
2127 case-equivalent. */
2129 enum case_type {one_case, two_case, strange};
2131 /* Describe the run that is in progress,
2132 which the next character can try to extend.
2133 If run_type is strange, that means there really is no run.
2134 If run_type is one_case, then run_start...run_end is the run.
2135 If run_type is two_case, then the run is run_start...run_end,
2136 and the case-equivalents end at run_eqv_end. */
2138 enum case_type run_type = strange;
2139 int run_start, run_end, run_eqv_end;
2141 Lisp_Object eqv_table;
2143 if (!RE_TRANSLATE_P (translate))
2145 EXTEND_RANGE_TABLE (work_area, 2);
2146 work_area->table[work_area->used++] = (start);
2147 work_area->table[work_area->used++] = (end);
2148 return -1;
2151 eqv_table = XCHAR_TABLE (translate)->extras[2];
2153 for (; start <= end; start++)
2155 enum case_type this_type;
2156 int eqv = RE_TRANSLATE (eqv_table, start);
2157 int minchar, maxchar;
2159 /* Classify this character */
2160 if (eqv == start)
2161 this_type = one_case;
2162 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2163 this_type = two_case;
2164 else
2165 this_type = strange;
2167 if (start < eqv)
2168 minchar = start, maxchar = eqv;
2169 else
2170 minchar = eqv, maxchar = start;
2172 /* Can this character extend the run in progress? */
2173 if (this_type == strange || this_type != run_type
2174 || !(minchar == run_end + 1
2175 && (run_type == two_case
2176 ? maxchar == run_eqv_end + 1 : 1)))
2178 /* No, end the run.
2179 Record each of its equivalent ranges. */
2180 if (run_type == one_case)
2182 EXTEND_RANGE_TABLE (work_area, 2);
2183 work_area->table[work_area->used++] = run_start;
2184 work_area->table[work_area->used++] = run_end;
2186 else if (run_type == two_case)
2188 EXTEND_RANGE_TABLE (work_area, 4);
2189 work_area->table[work_area->used++] = run_start;
2190 work_area->table[work_area->used++] = run_end;
2191 work_area->table[work_area->used++]
2192 = RE_TRANSLATE (eqv_table, run_start);
2193 work_area->table[work_area->used++]
2194 = RE_TRANSLATE (eqv_table, run_end);
2196 run_type = strange;
2199 if (this_type == strange)
2201 /* For a strange character, add each of its equivalents, one
2202 by one. Don't start a range. */
2205 EXTEND_RANGE_TABLE (work_area, 2);
2206 work_area->table[work_area->used++] = eqv;
2207 work_area->table[work_area->used++] = eqv;
2208 eqv = RE_TRANSLATE (eqv_table, eqv);
2210 while (eqv != start);
2213 /* Add this char to the run, or start a new run. */
2214 else if (run_type == strange)
2216 /* Initialize a new range. */
2217 run_type = this_type;
2218 run_start = start;
2219 run_end = start;
2220 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2222 else
2224 /* Extend a running range. */
2225 run_end = minchar;
2226 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2230 /* If a run is still in progress at the end, finish it now
2231 by recording its equivalent ranges. */
2232 if (run_type == one_case)
2234 EXTEND_RANGE_TABLE (work_area, 2);
2235 work_area->table[work_area->used++] = run_start;
2236 work_area->table[work_area->used++] = run_end;
2238 else if (run_type == two_case)
2240 EXTEND_RANGE_TABLE (work_area, 4);
2241 work_area->table[work_area->used++] = run_start;
2242 work_area->table[work_area->used++] = run_end;
2243 work_area->table[work_area->used++]
2244 = RE_TRANSLATE (eqv_table, run_start);
2245 work_area->table[work_area->used++]
2246 = RE_TRANSLATE (eqv_table, run_end);
2249 return -1;
2252 #endif /* emacs */
2254 /* Record the image of the range start..end when passed through
2255 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2256 and is not even necessarily contiguous.
2257 Normally we approximate it with the smallest contiguous range that contains
2258 all the chars we need. However, for Latin-1 we go to extra effort
2259 to do a better job.
2261 This function is not called for ASCII ranges.
2263 Returns -1 if successful, REG_ESPACE if ran out of space. */
2265 static int
2266 set_image_of_range (struct range_table_work_area *work_area,
2267 re_wchar_t start, re_wchar_t end,
2268 RE_TRANSLATE_TYPE translate)
2270 re_wchar_t cmin, cmax;
2272 #ifdef emacs
2273 /* For Latin-1 ranges, use set_image_of_range_1
2274 to get proper handling of ranges that include letters and nonletters.
2275 For a range that includes the whole of Latin-1, this is not necessary.
2276 For other character sets, we don't bother to get this right. */
2277 if (RE_TRANSLATE_P (translate) && start < 04400
2278 && !(start < 04200 && end >= 04377))
2280 int newend;
2281 int tem;
2282 newend = end;
2283 if (newend > 04377)
2284 newend = 04377;
2285 tem = set_image_of_range_1 (work_area, start, newend, translate);
2286 if (tem > 0)
2287 return tem;
2289 start = 04400;
2290 if (end < 04400)
2291 return -1;
2293 #endif
2295 EXTEND_RANGE_TABLE (work_area, 2);
2296 work_area->table[work_area->used++] = (start);
2297 work_area->table[work_area->used++] = (end);
2299 cmin = -1, cmax = -1;
2301 if (RE_TRANSLATE_P (translate))
2303 int ch;
2305 for (ch = start; ch <= end; ch++)
2307 re_wchar_t c = TRANSLATE (ch);
2308 if (! (start <= c && c <= end))
2310 if (cmin == -1)
2311 cmin = c, cmax = c;
2312 else
2314 cmin = min (cmin, c);
2315 cmax = max (cmax, c);
2320 if (cmin != -1)
2322 EXTEND_RANGE_TABLE (work_area, 2);
2323 work_area->table[work_area->used++] = (cmin);
2324 work_area->table[work_area->used++] = (cmax);
2328 return -1;
2330 #endif /* 0 */
2332 #ifndef MATCH_MAY_ALLOCATE
2334 /* If we cannot allocate large objects within re_match_2_internal,
2335 we make the fail stack and register vectors global.
2336 The fail stack, we grow to the maximum size when a regexp
2337 is compiled.
2338 The register vectors, we adjust in size each time we
2339 compile a regexp, according to the number of registers it needs. */
2341 static fail_stack_type fail_stack;
2343 /* Size with which the following vectors are currently allocated.
2344 That is so we can make them bigger as needed,
2345 but never make them smaller. */
2346 static int regs_allocated_size;
2348 static re_char ** regstart, ** regend;
2349 static re_char **best_regstart, **best_regend;
2351 /* Make the register vectors big enough for NUM_REGS registers,
2352 but don't make them smaller. */
2354 static
2355 regex_grow_registers (int num_regs)
2357 if (num_regs > regs_allocated_size)
2359 RETALLOC_IF (regstart, num_regs, re_char *);
2360 RETALLOC_IF (regend, num_regs, re_char *);
2361 RETALLOC_IF (best_regstart, num_regs, re_char *);
2362 RETALLOC_IF (best_regend, num_regs, re_char *);
2364 regs_allocated_size = num_regs;
2368 #endif /* not MATCH_MAY_ALLOCATE */
2370 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2371 regnum_t regnum);
2373 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2374 Returns one of error codes defined in `regex.h', or zero for success.
2376 Assumes the `allocated' (and perhaps `buffer') and `translate'
2377 fields are set in BUFP on entry.
2379 If it succeeds, results are put in BUFP (if it returns an error, the
2380 contents of BUFP are undefined):
2381 `buffer' is the compiled pattern;
2382 `syntax' is set to SYNTAX;
2383 `used' is set to the length of the compiled pattern;
2384 `fastmap_accurate' is zero;
2385 `re_nsub' is the number of subexpressions in PATTERN;
2386 `not_bol' and `not_eol' are zero;
2388 The `fastmap' field is neither examined nor set. */
2390 /* Insert the `jump' from the end of last alternative to "here".
2391 The space for the jump has already been allocated. */
2392 #define FIXUP_ALT_JUMP() \
2393 do { \
2394 if (fixup_alt_jump) \
2395 STORE_JUMP (jump, fixup_alt_jump, b); \
2396 } while (0)
2399 /* Return, freeing storage we allocated. */
2400 #define FREE_STACK_RETURN(value) \
2401 do { \
2402 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2403 free (compile_stack.stack); \
2404 return value; \
2405 } while (0)
2407 static reg_errcode_t
2408 regex_compile (const_re_char *pattern, size_t size, reg_syntax_t syntax,
2409 struct re_pattern_buffer *bufp)
2411 /* We fetch characters from PATTERN here. */
2412 register re_wchar_t c, c1;
2414 /* Points to the end of the buffer, where we should append. */
2415 register unsigned char *b;
2417 /* Keeps track of unclosed groups. */
2418 compile_stack_type compile_stack;
2420 /* Points to the current (ending) position in the pattern. */
2421 #ifdef AIX
2422 /* `const' makes AIX compiler fail. */
2423 unsigned char *p = pattern;
2424 #else
2425 re_char *p = pattern;
2426 #endif
2427 re_char *pend = pattern + size;
2429 /* How to translate the characters in the pattern. */
2430 RE_TRANSLATE_TYPE translate = bufp->translate;
2432 /* Address of the count-byte of the most recently inserted `exactn'
2433 command. This makes it possible to tell if a new exact-match
2434 character can be added to that command or if the character requires
2435 a new `exactn' command. */
2436 unsigned char *pending_exact = 0;
2438 /* Address of start of the most recently finished expression.
2439 This tells, e.g., postfix * where to find the start of its
2440 operand. Reset at the beginning of groups and alternatives. */
2441 unsigned char *laststart = 0;
2443 /* Address of beginning of regexp, or inside of last group. */
2444 unsigned char *begalt;
2446 /* Place in the uncompiled pattern (i.e., the {) to
2447 which to go back if the interval is invalid. */
2448 re_char *beg_interval;
2450 /* Address of the place where a forward jump should go to the end of
2451 the containing expression. Each alternative of an `or' -- except the
2452 last -- ends with a forward jump of this sort. */
2453 unsigned char *fixup_alt_jump = 0;
2455 /* Work area for range table of charset. */
2456 struct range_table_work_area range_table_work;
2458 /* If the object matched can contain multibyte characters. */
2459 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2461 /* Nonzero if we have pushed down into a subpattern. */
2462 int in_subpattern = 0;
2464 /* These hold the values of p, pattern, and pend from the main
2465 pattern when we have pushed into a subpattern. */
2466 re_char *main_p IF_LINT (= NULL);
2467 re_char *main_pattern IF_LINT (= NULL);
2468 re_char *main_pend IF_LINT (= NULL);
2470 #ifdef DEBUG
2471 debug++;
2472 DEBUG_PRINT ("\nCompiling pattern: ");
2473 if (debug > 0)
2475 unsigned debug_count;
2477 for (debug_count = 0; debug_count < size; debug_count++)
2478 putchar (pattern[debug_count]);
2479 putchar ('\n');
2481 #endif /* DEBUG */
2483 /* Initialize the compile stack. */
2484 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2485 if (compile_stack.stack == NULL)
2486 return REG_ESPACE;
2488 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2489 compile_stack.avail = 0;
2491 range_table_work.table = 0;
2492 range_table_work.allocated = 0;
2494 /* Initialize the pattern buffer. */
2495 bufp->syntax = syntax;
2496 bufp->fastmap_accurate = 0;
2497 bufp->not_bol = bufp->not_eol = 0;
2498 bufp->used_syntax = 0;
2500 /* Set `used' to zero, so that if we return an error, the pattern
2501 printer (for debugging) will think there's no pattern. We reset it
2502 at the end. */
2503 bufp->used = 0;
2505 /* Always count groups, whether or not bufp->no_sub is set. */
2506 bufp->re_nsub = 0;
2508 #if !defined emacs && !defined SYNTAX_TABLE
2509 /* Initialize the syntax table. */
2510 init_syntax_once ();
2511 #endif
2513 if (bufp->allocated == 0)
2515 if (bufp->buffer)
2516 { /* If zero allocated, but buffer is non-null, try to realloc
2517 enough space. This loses if buffer's address is bogus, but
2518 that is the user's responsibility. */
2519 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2521 else
2522 { /* Caller did not allocate a buffer. Do it for them. */
2523 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2525 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2527 bufp->allocated = INIT_BUF_SIZE;
2530 begalt = b = bufp->buffer;
2532 /* Loop through the uncompiled pattern until we're at the end. */
2533 while (1)
2535 if (p == pend)
2537 /* If this is the end of an included regexp,
2538 pop back to the main regexp and try again. */
2539 if (in_subpattern)
2541 in_subpattern = 0;
2542 pattern = main_pattern;
2543 p = main_p;
2544 pend = main_pend;
2545 continue;
2547 /* If this is the end of the main regexp, we are done. */
2548 break;
2551 PATFETCH (c);
2553 switch (c)
2555 case ' ':
2557 re_char *p1 = p;
2559 /* If there's no special whitespace regexp, treat
2560 spaces normally. And don't try to do this recursively. */
2561 if (!whitespace_regexp || in_subpattern)
2562 goto normal_char;
2564 /* Peek past following spaces. */
2565 while (p1 != pend)
2567 if (*p1 != ' ')
2568 break;
2569 p1++;
2571 /* If the spaces are followed by a repetition op,
2572 treat them normally. */
2573 if (p1 != pend
2574 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2575 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2576 goto normal_char;
2578 /* Replace the spaces with the whitespace regexp. */
2579 in_subpattern = 1;
2580 main_p = p1;
2581 main_pend = pend;
2582 main_pattern = pattern;
2583 p = pattern = whitespace_regexp;
2584 pend = p + strlen ((const char *) p);
2585 break;
2588 case '^':
2590 if ( /* If at start of pattern, it's an operator. */
2591 p == pattern + 1
2592 /* If context independent, it's an operator. */
2593 || syntax & RE_CONTEXT_INDEP_ANCHORS
2594 /* Otherwise, depends on what's come before. */
2595 || at_begline_loc_p (pattern, p, syntax))
2596 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2597 else
2598 goto normal_char;
2600 break;
2603 case '$':
2605 if ( /* If at end of pattern, it's an operator. */
2606 p == pend
2607 /* If context independent, it's an operator. */
2608 || syntax & RE_CONTEXT_INDEP_ANCHORS
2609 /* Otherwise, depends on what's next. */
2610 || at_endline_loc_p (p, pend, syntax))
2611 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2612 else
2613 goto normal_char;
2615 break;
2618 case '+':
2619 case '?':
2620 if ((syntax & RE_BK_PLUS_QM)
2621 || (syntax & RE_LIMITED_OPS))
2622 goto normal_char;
2623 handle_plus:
2624 case '*':
2625 /* If there is no previous pattern... */
2626 if (!laststart)
2628 if (syntax & RE_CONTEXT_INVALID_OPS)
2629 FREE_STACK_RETURN (REG_BADRPT);
2630 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2631 goto normal_char;
2635 /* 1 means zero (many) matches is allowed. */
2636 boolean zero_times_ok = 0, many_times_ok = 0;
2637 boolean greedy = 1;
2639 /* If there is a sequence of repetition chars, collapse it
2640 down to just one (the right one). We can't combine
2641 interval operators with these because of, e.g., `a{2}*',
2642 which should only match an even number of `a's. */
2644 for (;;)
2646 if ((syntax & RE_FRUGAL)
2647 && c == '?' && (zero_times_ok || many_times_ok))
2648 greedy = 0;
2649 else
2651 zero_times_ok |= c != '+';
2652 many_times_ok |= c != '?';
2655 if (p == pend)
2656 break;
2657 else if (*p == '*'
2658 || (!(syntax & RE_BK_PLUS_QM)
2659 && (*p == '+' || *p == '?')))
2661 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2663 if (p+1 == pend)
2664 FREE_STACK_RETURN (REG_EESCAPE);
2665 if (p[1] == '+' || p[1] == '?')
2666 PATFETCH (c); /* Gobble up the backslash. */
2667 else
2668 break;
2670 else
2671 break;
2672 /* If we get here, we found another repeat character. */
2673 PATFETCH (c);
2676 /* Star, etc. applied to an empty pattern is equivalent
2677 to an empty pattern. */
2678 if (!laststart || laststart == b)
2679 break;
2681 /* Now we know whether or not zero matches is allowed
2682 and also whether or not two or more matches is allowed. */
2683 if (greedy)
2685 if (many_times_ok)
2687 boolean simple = skip_one_char (laststart) == b;
2688 size_t startoffset = 0;
2689 re_opcode_t ofj =
2690 /* Check if the loop can match the empty string. */
2691 (simple || !analyze_first (laststart, b, NULL, 0))
2692 ? on_failure_jump : on_failure_jump_loop;
2693 assert (skip_one_char (laststart) <= b);
2695 if (!zero_times_ok && simple)
2696 { /* Since simple * loops can be made faster by using
2697 on_failure_keep_string_jump, we turn simple P+
2698 into PP* if P is simple. */
2699 unsigned char *p1, *p2;
2700 startoffset = b - laststart;
2701 GET_BUFFER_SPACE (startoffset);
2702 p1 = b; p2 = laststart;
2703 while (p2 < p1)
2704 *b++ = *p2++;
2705 zero_times_ok = 1;
2708 GET_BUFFER_SPACE (6);
2709 if (!zero_times_ok)
2710 /* A + loop. */
2711 STORE_JUMP (ofj, b, b + 6);
2712 else
2713 /* Simple * loops can use on_failure_keep_string_jump
2714 depending on what follows. But since we don't know
2715 that yet, we leave the decision up to
2716 on_failure_jump_smart. */
2717 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2718 laststart + startoffset, b + 6);
2719 b += 3;
2720 STORE_JUMP (jump, b, laststart + startoffset);
2721 b += 3;
2723 else
2725 /* A simple ? pattern. */
2726 assert (zero_times_ok);
2727 GET_BUFFER_SPACE (3);
2728 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2729 b += 3;
2732 else /* not greedy */
2733 { /* I wish the greedy and non-greedy cases could be merged. */
2735 GET_BUFFER_SPACE (7); /* We might use less. */
2736 if (many_times_ok)
2738 boolean emptyp = analyze_first (laststart, b, NULL, 0);
2740 /* The non-greedy multiple match looks like
2741 a repeat..until: we only need a conditional jump
2742 at the end of the loop. */
2743 if (emptyp) BUF_PUSH (no_op);
2744 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2745 : on_failure_jump, b, laststart);
2746 b += 3;
2747 if (zero_times_ok)
2749 /* The repeat...until naturally matches one or more.
2750 To also match zero times, we need to first jump to
2751 the end of the loop (its conditional jump). */
2752 INSERT_JUMP (jump, laststart, b);
2753 b += 3;
2756 else
2758 /* non-greedy a?? */
2759 INSERT_JUMP (jump, laststart, b + 3);
2760 b += 3;
2761 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2762 b += 3;
2766 pending_exact = 0;
2767 break;
2770 case '.':
2771 laststart = b;
2772 BUF_PUSH (anychar);
2773 break;
2776 case '[':
2778 re_char *p1;
2780 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2782 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2784 /* Ensure that we have enough space to push a charset: the
2785 opcode, the length count, and the bitset; 34 bytes in all. */
2786 GET_BUFFER_SPACE (34);
2788 laststart = b;
2790 /* We test `*p == '^' twice, instead of using an if
2791 statement, so we only need one BUF_PUSH. */
2792 BUF_PUSH (*p == '^' ? charset_not : charset);
2793 if (*p == '^')
2794 p++;
2796 /* Remember the first position in the bracket expression. */
2797 p1 = p;
2799 /* Push the number of bytes in the bitmap. */
2800 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2802 /* Clear the whole map. */
2803 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2805 /* charset_not matches newline according to a syntax bit. */
2806 if ((re_opcode_t) b[-2] == charset_not
2807 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2808 SET_LIST_BIT ('\n');
2810 /* Read in characters and ranges, setting map bits. */
2811 for (;;)
2813 boolean escaped_char = false;
2814 const unsigned char *p2 = p;
2815 re_wchar_t ch;
2817 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2819 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2820 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2821 So the translation is done later in a loop. Example:
2822 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2823 PATFETCH (c);
2825 /* \ might escape characters inside [...] and [^...]. */
2826 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2828 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2830 PATFETCH (c);
2831 escaped_char = true;
2833 else
2835 /* Could be the end of the bracket expression. If it's
2836 not (i.e., when the bracket expression is `[]' so
2837 far), the ']' character bit gets set way below. */
2838 if (c == ']' && p2 != p1)
2839 break;
2842 /* See if we're at the beginning of a possible character
2843 class. */
2845 if (!escaped_char &&
2846 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2848 /* Leave room for the null. */
2849 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2850 const unsigned char *class_beg;
2852 PATFETCH (c);
2853 c1 = 0;
2854 class_beg = p;
2856 /* If pattern is `[[:'. */
2857 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2859 for (;;)
2861 PATFETCH (c);
2862 if ((c == ':' && *p == ']') || p == pend)
2863 break;
2864 if (c1 < CHAR_CLASS_MAX_LENGTH)
2865 str[c1++] = c;
2866 else
2867 /* This is in any case an invalid class name. */
2868 str[0] = '\0';
2870 str[c1] = '\0';
2872 /* If isn't a word bracketed by `[:' and `:]':
2873 undo the ending character, the letters, and
2874 leave the leading `:' and `[' (but set bits for
2875 them). */
2876 if (c == ':' && *p == ']')
2878 re_wctype_t cc = re_wctype (str);
2880 if (cc == 0)
2881 FREE_STACK_RETURN (REG_ECTYPE);
2883 /* Throw away the ] at the end of the character
2884 class. */
2885 PATFETCH (c);
2887 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2889 #ifndef emacs
2890 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2891 if (re_iswctype (btowc (ch), cc))
2893 c = TRANSLATE (ch);
2894 if (c < (1 << BYTEWIDTH))
2895 SET_LIST_BIT (c);
2897 #else /* emacs */
2898 /* Most character classes in a multibyte match
2899 just set a flag. Exceptions are is_blank,
2900 is_digit, is_cntrl, and is_xdigit, since
2901 they can only match ASCII characters. We
2902 don't need to handle them for multibyte.
2903 They are distinguished by a negative wctype. */
2905 /* Setup the gl_state object to its buffer-defined
2906 value. This hardcodes the buffer-global
2907 syntax-table for ASCII chars, while the other chars
2908 will obey syntax-table properties. It's not ideal,
2909 but it's the way it's been done until now. */
2910 SETUP_BUFFER_SYNTAX_TABLE ();
2912 for (ch = 0; ch < 256; ++ch)
2914 c = RE_CHAR_TO_MULTIBYTE (ch);
2915 if (! CHAR_BYTE8_P (c)
2916 && re_iswctype (c, cc))
2918 SET_LIST_BIT (ch);
2919 c1 = TRANSLATE (c);
2920 if (c1 == c)
2921 continue;
2922 if (ASCII_CHAR_P (c1))
2923 SET_LIST_BIT (c1);
2924 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2925 SET_LIST_BIT (c1);
2928 SET_RANGE_TABLE_WORK_AREA_BIT
2929 (range_table_work, re_wctype_to_bit (cc));
2930 #endif /* emacs */
2931 /* In most cases the matching rule for char classes
2932 only uses the syntax table for multibyte chars,
2933 so that the content of the syntax-table it is not
2934 hardcoded in the range_table. SPACE and WORD are
2935 the two exceptions. */
2936 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2937 bufp->used_syntax = 1;
2939 /* Repeat the loop. */
2940 continue;
2942 else
2944 /* Go back to right after the "[:". */
2945 p = class_beg;
2946 SET_LIST_BIT ('[');
2948 /* Because the `:' may starts the range, we
2949 can't simply set bit and repeat the loop.
2950 Instead, just set it to C and handle below. */
2951 c = ':';
2955 if (p < pend && p[0] == '-' && p[1] != ']')
2958 /* Discard the `-'. */
2959 PATFETCH (c1);
2961 /* Fetch the character which ends the range. */
2962 PATFETCH (c1);
2963 #ifdef emacs
2964 if (CHAR_BYTE8_P (c1)
2965 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2966 /* Treat the range from a multibyte character to
2967 raw-byte character as empty. */
2968 c = c1 + 1;
2969 #endif /* emacs */
2971 else
2972 /* Range from C to C. */
2973 c1 = c;
2975 if (c > c1)
2977 if (syntax & RE_NO_EMPTY_RANGES)
2978 FREE_STACK_RETURN (REG_ERANGEX);
2979 /* Else, repeat the loop. */
2981 else
2983 #ifndef emacs
2984 /* Set the range into bitmap */
2985 for (; c <= c1; c++)
2987 ch = TRANSLATE (c);
2988 if (ch < (1 << BYTEWIDTH))
2989 SET_LIST_BIT (ch);
2991 #else /* emacs */
2992 if (c < 128)
2994 ch = min (127, c1);
2995 SETUP_ASCII_RANGE (range_table_work, c, ch);
2996 c = ch + 1;
2997 if (CHAR_BYTE8_P (c1))
2998 c = BYTE8_TO_CHAR (128);
3000 if (c <= c1)
3002 if (CHAR_BYTE8_P (c))
3004 c = CHAR_TO_BYTE8 (c);
3005 c1 = CHAR_TO_BYTE8 (c1);
3006 for (; c <= c1; c++)
3007 SET_LIST_BIT (c);
3009 else if (multibyte)
3011 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
3013 else
3015 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
3018 #endif /* emacs */
3022 /* Discard any (non)matching list bytes that are all 0 at the
3023 end of the map. Decrease the map-length byte too. */
3024 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3025 b[-1]--;
3026 b += b[-1];
3028 /* Build real range table from work area. */
3029 if (RANGE_TABLE_WORK_USED (range_table_work)
3030 || RANGE_TABLE_WORK_BITS (range_table_work))
3032 int i;
3033 int used = RANGE_TABLE_WORK_USED (range_table_work);
3035 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3036 bytes for flags, two for COUNT, and three bytes for
3037 each character. */
3038 GET_BUFFER_SPACE (4 + used * 3);
3040 /* Indicate the existence of range table. */
3041 laststart[1] |= 0x80;
3043 /* Store the character class flag bits into the range table.
3044 If not in emacs, these flag bits are always 0. */
3045 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3046 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3048 STORE_NUMBER_AND_INCR (b, used / 2);
3049 for (i = 0; i < used; i++)
3050 STORE_CHARACTER_AND_INCR
3051 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3054 break;
3057 case '(':
3058 if (syntax & RE_NO_BK_PARENS)
3059 goto handle_open;
3060 else
3061 goto normal_char;
3064 case ')':
3065 if (syntax & RE_NO_BK_PARENS)
3066 goto handle_close;
3067 else
3068 goto normal_char;
3071 case '\n':
3072 if (syntax & RE_NEWLINE_ALT)
3073 goto handle_alt;
3074 else
3075 goto normal_char;
3078 case '|':
3079 if (syntax & RE_NO_BK_VBAR)
3080 goto handle_alt;
3081 else
3082 goto normal_char;
3085 case '{':
3086 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3087 goto handle_interval;
3088 else
3089 goto normal_char;
3092 case '\\':
3093 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3095 /* Do not translate the character after the \, so that we can
3096 distinguish, e.g., \B from \b, even if we normally would
3097 translate, e.g., B to b. */
3098 PATFETCH (c);
3100 switch (c)
3102 case '(':
3103 if (syntax & RE_NO_BK_PARENS)
3104 goto normal_backslash;
3106 handle_open:
3108 int shy = 0;
3109 regnum_t regnum = 0;
3110 if (p+1 < pend)
3112 /* Look for a special (?...) construct */
3113 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3115 PATFETCH (c); /* Gobble up the '?'. */
3116 while (!shy)
3118 PATFETCH (c);
3119 switch (c)
3121 case ':': shy = 1; break;
3122 case '0':
3123 /* An explicitly specified regnum must start
3124 with non-0. */
3125 if (regnum == 0)
3126 FREE_STACK_RETURN (REG_BADPAT);
3127 case '1': case '2': case '3': case '4':
3128 case '5': case '6': case '7': case '8': case '9':
3129 regnum = 10*regnum + (c - '0'); break;
3130 default:
3131 /* Only (?:...) is supported right now. */
3132 FREE_STACK_RETURN (REG_BADPAT);
3138 if (!shy)
3139 regnum = ++bufp->re_nsub;
3140 else if (regnum)
3141 { /* It's actually not shy, but explicitly numbered. */
3142 shy = 0;
3143 if (regnum > bufp->re_nsub)
3144 bufp->re_nsub = regnum;
3145 else if (regnum > bufp->re_nsub
3146 /* Ideally, we'd want to check that the specified
3147 group can't have matched (i.e. all subgroups
3148 using the same regnum are in other branches of
3149 OR patterns), but we don't currently keep track
3150 of enough info to do that easily. */
3151 || group_in_compile_stack (compile_stack, regnum))
3152 FREE_STACK_RETURN (REG_BADPAT);
3154 else
3155 /* It's really shy. */
3156 regnum = - bufp->re_nsub;
3158 if (COMPILE_STACK_FULL)
3160 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3161 compile_stack_elt_t);
3162 if (compile_stack.stack == NULL) return REG_ESPACE;
3164 compile_stack.size <<= 1;
3167 /* These are the values to restore when we hit end of this
3168 group. They are all relative offsets, so that if the
3169 whole pattern moves because of realloc, they will still
3170 be valid. */
3171 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3172 COMPILE_STACK_TOP.fixup_alt_jump
3173 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3174 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3175 COMPILE_STACK_TOP.regnum = regnum;
3177 /* Do not push a start_memory for groups beyond the last one
3178 we can represent in the compiled pattern. */
3179 if (regnum <= MAX_REGNUM && regnum > 0)
3180 BUF_PUSH_2 (start_memory, regnum);
3182 compile_stack.avail++;
3184 fixup_alt_jump = 0;
3185 laststart = 0;
3186 begalt = b;
3187 /* If we've reached MAX_REGNUM groups, then this open
3188 won't actually generate any code, so we'll have to
3189 clear pending_exact explicitly. */
3190 pending_exact = 0;
3191 break;
3194 case ')':
3195 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3197 if (COMPILE_STACK_EMPTY)
3199 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3200 goto normal_backslash;
3201 else
3202 FREE_STACK_RETURN (REG_ERPAREN);
3205 handle_close:
3206 FIXUP_ALT_JUMP ();
3208 /* See similar code for backslashed left paren above. */
3209 if (COMPILE_STACK_EMPTY)
3211 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3212 goto normal_char;
3213 else
3214 FREE_STACK_RETURN (REG_ERPAREN);
3217 /* Since we just checked for an empty stack above, this
3218 ``can't happen''. */
3219 assert (compile_stack.avail != 0);
3221 /* We don't just want to restore into `regnum', because
3222 later groups should continue to be numbered higher,
3223 as in `(ab)c(de)' -- the second group is #2. */
3224 regnum_t regnum;
3226 compile_stack.avail--;
3227 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3228 fixup_alt_jump
3229 = COMPILE_STACK_TOP.fixup_alt_jump
3230 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3231 : 0;
3232 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3233 regnum = COMPILE_STACK_TOP.regnum;
3234 /* If we've reached MAX_REGNUM groups, then this open
3235 won't actually generate any code, so we'll have to
3236 clear pending_exact explicitly. */
3237 pending_exact = 0;
3239 /* We're at the end of the group, so now we know how many
3240 groups were inside this one. */
3241 if (regnum <= MAX_REGNUM && regnum > 0)
3242 BUF_PUSH_2 (stop_memory, regnum);
3244 break;
3247 case '|': /* `\|'. */
3248 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3249 goto normal_backslash;
3250 handle_alt:
3251 if (syntax & RE_LIMITED_OPS)
3252 goto normal_char;
3254 /* Insert before the previous alternative a jump which
3255 jumps to this alternative if the former fails. */
3256 GET_BUFFER_SPACE (3);
3257 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3258 pending_exact = 0;
3259 b += 3;
3261 /* The alternative before this one has a jump after it
3262 which gets executed if it gets matched. Adjust that
3263 jump so it will jump to this alternative's analogous
3264 jump (put in below, which in turn will jump to the next
3265 (if any) alternative's such jump, etc.). The last such
3266 jump jumps to the correct final destination. A picture:
3267 _____ _____
3268 | | | |
3269 | v | v
3270 a | b | c
3272 If we are at `b', then fixup_alt_jump right now points to a
3273 three-byte space after `a'. We'll put in the jump, set
3274 fixup_alt_jump to right after `b', and leave behind three
3275 bytes which we'll fill in when we get to after `c'. */
3277 FIXUP_ALT_JUMP ();
3279 /* Mark and leave space for a jump after this alternative,
3280 to be filled in later either by next alternative or
3281 when know we're at the end of a series of alternatives. */
3282 fixup_alt_jump = b;
3283 GET_BUFFER_SPACE (3);
3284 b += 3;
3286 laststart = 0;
3287 begalt = b;
3288 break;
3291 case '{':
3292 /* If \{ is a literal. */
3293 if (!(syntax & RE_INTERVALS)
3294 /* If we're at `\{' and it's not the open-interval
3295 operator. */
3296 || (syntax & RE_NO_BK_BRACES))
3297 goto normal_backslash;
3299 handle_interval:
3301 /* If got here, then the syntax allows intervals. */
3303 /* At least (most) this many matches must be made. */
3304 int lower_bound = 0, upper_bound = -1;
3306 beg_interval = p;
3308 GET_INTERVAL_COUNT (lower_bound);
3310 if (c == ',')
3311 GET_INTERVAL_COUNT (upper_bound);
3312 else
3313 /* Interval such as `{1}' => match exactly once. */
3314 upper_bound = lower_bound;
3316 if (lower_bound < 0
3317 || (0 <= upper_bound && upper_bound < lower_bound))
3318 FREE_STACK_RETURN (REG_BADBR);
3320 if (!(syntax & RE_NO_BK_BRACES))
3322 if (c != '\\')
3323 FREE_STACK_RETURN (REG_BADBR);
3324 if (p == pend)
3325 FREE_STACK_RETURN (REG_EESCAPE);
3326 PATFETCH (c);
3329 if (c != '}')
3330 FREE_STACK_RETURN (REG_BADBR);
3332 /* We just parsed a valid interval. */
3334 /* If it's invalid to have no preceding re. */
3335 if (!laststart)
3337 if (syntax & RE_CONTEXT_INVALID_OPS)
3338 FREE_STACK_RETURN (REG_BADRPT);
3339 else if (syntax & RE_CONTEXT_INDEP_OPS)
3340 laststart = b;
3341 else
3342 goto unfetch_interval;
3345 if (upper_bound == 0)
3346 /* If the upper bound is zero, just drop the sub pattern
3347 altogether. */
3348 b = laststart;
3349 else if (lower_bound == 1 && upper_bound == 1)
3350 /* Just match it once: nothing to do here. */
3353 /* Otherwise, we have a nontrivial interval. When
3354 we're all done, the pattern will look like:
3355 set_number_at <jump count> <upper bound>
3356 set_number_at <succeed_n count> <lower bound>
3357 succeed_n <after jump addr> <succeed_n count>
3358 <body of loop>
3359 jump_n <succeed_n addr> <jump count>
3360 (The upper bound and `jump_n' are omitted if
3361 `upper_bound' is 1, though.) */
3362 else
3363 { /* If the upper bound is > 1, we need to insert
3364 more at the end of the loop. */
3365 unsigned int nbytes = (upper_bound < 0 ? 3
3366 : upper_bound > 1 ? 5 : 0);
3367 unsigned int startoffset = 0;
3369 GET_BUFFER_SPACE (20); /* We might use less. */
3371 if (lower_bound == 0)
3373 /* A succeed_n that starts with 0 is really a
3374 a simple on_failure_jump_loop. */
3375 INSERT_JUMP (on_failure_jump_loop, laststart,
3376 b + 3 + nbytes);
3377 b += 3;
3379 else
3381 /* Initialize lower bound of the `succeed_n', even
3382 though it will be set during matching by its
3383 attendant `set_number_at' (inserted next),
3384 because `re_compile_fastmap' needs to know.
3385 Jump to the `jump_n' we might insert below. */
3386 INSERT_JUMP2 (succeed_n, laststart,
3387 b + 5 + nbytes,
3388 lower_bound);
3389 b += 5;
3391 /* Code to initialize the lower bound. Insert
3392 before the `succeed_n'. The `5' is the last two
3393 bytes of this `set_number_at', plus 3 bytes of
3394 the following `succeed_n'. */
3395 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3396 b += 5;
3397 startoffset += 5;
3400 if (upper_bound < 0)
3402 /* A negative upper bound stands for infinity,
3403 in which case it degenerates to a plain jump. */
3404 STORE_JUMP (jump, b, laststart + startoffset);
3405 b += 3;
3407 else if (upper_bound > 1)
3408 { /* More than one repetition is allowed, so
3409 append a backward jump to the `succeed_n'
3410 that starts this interval.
3412 When we've reached this during matching,
3413 we'll have matched the interval once, so
3414 jump back only `upper_bound - 1' times. */
3415 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3416 upper_bound - 1);
3417 b += 5;
3419 /* The location we want to set is the second
3420 parameter of the `jump_n'; that is `b-2' as
3421 an absolute address. `laststart' will be
3422 the `set_number_at' we're about to insert;
3423 `laststart+3' the number to set, the source
3424 for the relative address. But we are
3425 inserting into the middle of the pattern --
3426 so everything is getting moved up by 5.
3427 Conclusion: (b - 2) - (laststart + 3) + 5,
3428 i.e., b - laststart.
3430 We insert this at the beginning of the loop
3431 so that if we fail during matching, we'll
3432 reinitialize the bounds. */
3433 insert_op2 (set_number_at, laststart, b - laststart,
3434 upper_bound - 1, b);
3435 b += 5;
3438 pending_exact = 0;
3439 beg_interval = NULL;
3441 break;
3443 unfetch_interval:
3444 /* If an invalid interval, match the characters as literals. */
3445 assert (beg_interval);
3446 p = beg_interval;
3447 beg_interval = NULL;
3449 /* normal_char and normal_backslash need `c'. */
3450 c = '{';
3452 if (!(syntax & RE_NO_BK_BRACES))
3454 assert (p > pattern && p[-1] == '\\');
3455 goto normal_backslash;
3457 else
3458 goto normal_char;
3460 #ifdef emacs
3461 /* There is no way to specify the before_dot and after_dot
3462 operators. rms says this is ok. --karl */
3463 case '=':
3464 laststart = b;
3465 BUF_PUSH (at_dot);
3466 break;
3468 case 's':
3469 laststart = b;
3470 PATFETCH (c);
3471 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3472 break;
3474 case 'S':
3475 laststart = b;
3476 PATFETCH (c);
3477 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3478 break;
3480 case 'c':
3481 laststart = b;
3482 PATFETCH (c);
3483 BUF_PUSH_2 (categoryspec, c);
3484 break;
3486 case 'C':
3487 laststart = b;
3488 PATFETCH (c);
3489 BUF_PUSH_2 (notcategoryspec, c);
3490 break;
3491 #endif /* emacs */
3494 case 'w':
3495 if (syntax & RE_NO_GNU_OPS)
3496 goto normal_char;
3497 laststart = b;
3498 BUF_PUSH_2 (syntaxspec, Sword);
3499 break;
3502 case 'W':
3503 if (syntax & RE_NO_GNU_OPS)
3504 goto normal_char;
3505 laststart = b;
3506 BUF_PUSH_2 (notsyntaxspec, Sword);
3507 break;
3510 case '<':
3511 if (syntax & RE_NO_GNU_OPS)
3512 goto normal_char;
3513 laststart = b;
3514 BUF_PUSH (wordbeg);
3515 break;
3517 case '>':
3518 if (syntax & RE_NO_GNU_OPS)
3519 goto normal_char;
3520 laststart = b;
3521 BUF_PUSH (wordend);
3522 break;
3524 case '_':
3525 if (syntax & RE_NO_GNU_OPS)
3526 goto normal_char;
3527 laststart = b;
3528 PATFETCH (c);
3529 if (c == '<')
3530 BUF_PUSH (symbeg);
3531 else if (c == '>')
3532 BUF_PUSH (symend);
3533 else
3534 FREE_STACK_RETURN (REG_BADPAT);
3535 break;
3537 case 'b':
3538 if (syntax & RE_NO_GNU_OPS)
3539 goto normal_char;
3540 BUF_PUSH (wordbound);
3541 break;
3543 case 'B':
3544 if (syntax & RE_NO_GNU_OPS)
3545 goto normal_char;
3546 BUF_PUSH (notwordbound);
3547 break;
3549 case '`':
3550 if (syntax & RE_NO_GNU_OPS)
3551 goto normal_char;
3552 BUF_PUSH (begbuf);
3553 break;
3555 case '\'':
3556 if (syntax & RE_NO_GNU_OPS)
3557 goto normal_char;
3558 BUF_PUSH (endbuf);
3559 break;
3561 case '1': case '2': case '3': case '4': case '5':
3562 case '6': case '7': case '8': case '9':
3564 regnum_t reg;
3566 if (syntax & RE_NO_BK_REFS)
3567 goto normal_backslash;
3569 reg = c - '0';
3571 if (reg > bufp->re_nsub || reg < 1
3572 /* Can't back reference to a subexp before its end. */
3573 || group_in_compile_stack (compile_stack, reg))
3574 FREE_STACK_RETURN (REG_ESUBREG);
3576 laststart = b;
3577 BUF_PUSH_2 (duplicate, reg);
3579 break;
3582 case '+':
3583 case '?':
3584 if (syntax & RE_BK_PLUS_QM)
3585 goto handle_plus;
3586 else
3587 goto normal_backslash;
3589 default:
3590 normal_backslash:
3591 /* You might think it would be useful for \ to mean
3592 not to translate; but if we don't translate it
3593 it will never match anything. */
3594 goto normal_char;
3596 break;
3599 default:
3600 /* Expects the character in `c'. */
3601 normal_char:
3602 /* If no exactn currently being built. */
3603 if (!pending_exact
3605 /* If last exactn not at current position. */
3606 || pending_exact + *pending_exact + 1 != b
3608 /* We have only one byte following the exactn for the count. */
3609 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3611 /* If followed by a repetition operator. */
3612 || (p != pend && (*p == '*' || *p == '^'))
3613 || ((syntax & RE_BK_PLUS_QM)
3614 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3615 : p != pend && (*p == '+' || *p == '?'))
3616 || ((syntax & RE_INTERVALS)
3617 && ((syntax & RE_NO_BK_BRACES)
3618 ? p != pend && *p == '{'
3619 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3621 /* Start building a new exactn. */
3623 laststart = b;
3625 BUF_PUSH_2 (exactn, 0);
3626 pending_exact = b - 1;
3629 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3631 int len;
3633 if (multibyte)
3635 c = TRANSLATE (c);
3636 len = CHAR_STRING (c, b);
3637 b += len;
3639 else
3641 c1 = RE_CHAR_TO_MULTIBYTE (c);
3642 if (! CHAR_BYTE8_P (c1))
3644 re_wchar_t c2 = TRANSLATE (c1);
3646 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3647 c = c1;
3649 *b++ = c;
3650 len = 1;
3652 (*pending_exact) += len;
3655 break;
3656 } /* switch (c) */
3657 } /* while p != pend */
3660 /* Through the pattern now. */
3662 FIXUP_ALT_JUMP ();
3664 if (!COMPILE_STACK_EMPTY)
3665 FREE_STACK_RETURN (REG_EPAREN);
3667 /* If we don't want backtracking, force success
3668 the first time we reach the end of the compiled pattern. */
3669 if (syntax & RE_NO_POSIX_BACKTRACKING)
3670 BUF_PUSH (succeed);
3672 /* We have succeeded; set the length of the buffer. */
3673 bufp->used = b - bufp->buffer;
3675 #ifdef DEBUG
3676 if (debug > 0)
3678 re_compile_fastmap (bufp);
3679 DEBUG_PRINT ("\nCompiled pattern: \n");
3680 print_compiled_pattern (bufp);
3682 debug--;
3683 #endif /* DEBUG */
3685 #ifndef MATCH_MAY_ALLOCATE
3686 /* Initialize the failure stack to the largest possible stack. This
3687 isn't necessary unless we're trying to avoid calling alloca in
3688 the search and match routines. */
3690 int num_regs = bufp->re_nsub + 1;
3692 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3694 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3695 falk_stack.stack = realloc (fail_stack.stack,
3696 fail_stack.size * sizeof *falk_stack.stack);
3699 regex_grow_registers (num_regs);
3701 #endif /* not MATCH_MAY_ALLOCATE */
3703 FREE_STACK_RETURN (REG_NOERROR);
3704 } /* regex_compile */
3706 /* Subroutines for `regex_compile'. */
3708 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3710 static void
3711 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3713 *loc = (unsigned char) op;
3714 STORE_NUMBER (loc + 1, arg);
3718 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3720 static void
3721 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3723 *loc = (unsigned char) op;
3724 STORE_NUMBER (loc + 1, arg1);
3725 STORE_NUMBER (loc + 3, arg2);
3729 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3730 for OP followed by two-byte integer parameter ARG. */
3732 static void
3733 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3735 register unsigned char *pfrom = end;
3736 register unsigned char *pto = end + 3;
3738 while (pfrom != loc)
3739 *--pto = *--pfrom;
3741 store_op1 (op, loc, arg);
3745 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3747 static void
3748 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3750 register unsigned char *pfrom = end;
3751 register unsigned char *pto = end + 5;
3753 while (pfrom != loc)
3754 *--pto = *--pfrom;
3756 store_op2 (op, loc, arg1, arg2);
3760 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3761 after an alternative or a begin-subexpression. We assume there is at
3762 least one character before the ^. */
3764 static boolean
3765 at_begline_loc_p (const_re_char *pattern, const_re_char *p, reg_syntax_t syntax)
3767 re_char *prev = p - 2;
3768 boolean odd_backslashes;
3770 /* After a subexpression? */
3771 if (*prev == '(')
3772 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3774 /* After an alternative? */
3775 else if (*prev == '|')
3776 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3778 /* After a shy subexpression? */
3779 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3781 /* Skip over optional regnum. */
3782 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3783 --prev;
3785 if (!(prev - 2 >= pattern
3786 && prev[-1] == '?' && prev[-2] == '('))
3787 return false;
3788 prev -= 2;
3789 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3791 else
3792 return false;
3794 /* Count the number of preceding backslashes. */
3795 p = prev;
3796 while (prev - 1 >= pattern && prev[-1] == '\\')
3797 --prev;
3798 return (p - prev) & odd_backslashes;
3802 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3803 at least one character after the $, i.e., `P < PEND'. */
3805 static boolean
3806 at_endline_loc_p (const_re_char *p, const_re_char *pend, reg_syntax_t syntax)
3808 re_char *next = p;
3809 boolean next_backslash = *next == '\\';
3810 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3812 return
3813 /* Before a subexpression? */
3814 (syntax & RE_NO_BK_PARENS ? *next == ')'
3815 : next_backslash && next_next && *next_next == ')')
3816 /* Before an alternative? */
3817 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3818 : next_backslash && next_next && *next_next == '|');
3822 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3823 false if it's not. */
3825 static boolean
3826 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3828 ssize_t this_element;
3830 for (this_element = compile_stack.avail - 1;
3831 this_element >= 0;
3832 this_element--)
3833 if (compile_stack.stack[this_element].regnum == regnum)
3834 return true;
3836 return false;
3839 /* analyze_first.
3840 If fastmap is non-NULL, go through the pattern and fill fastmap
3841 with all the possible leading chars. If fastmap is NULL, don't
3842 bother filling it up (obviously) and only return whether the
3843 pattern could potentially match the empty string.
3845 Return 1 if p..pend might match the empty string.
3846 Return 0 if p..pend matches at least one char.
3847 Return -1 if fastmap was not updated accurately. */
3849 static int
3850 analyze_first (const_re_char *p, const_re_char *pend, char *fastmap,
3851 const int multibyte)
3853 int j, k;
3854 boolean not;
3856 /* If all elements for base leading-codes in fastmap is set, this
3857 flag is set true. */
3858 boolean match_any_multibyte_characters = false;
3860 assert (p);
3862 /* The loop below works as follows:
3863 - It has a working-list kept in the PATTERN_STACK and which basically
3864 starts by only containing a pointer to the first operation.
3865 - If the opcode we're looking at is a match against some set of
3866 chars, then we add those chars to the fastmap and go on to the
3867 next work element from the worklist (done via `break').
3868 - If the opcode is a control operator on the other hand, we either
3869 ignore it (if it's meaningless at this point, such as `start_memory')
3870 or execute it (if it's a jump). If the jump has several destinations
3871 (i.e. `on_failure_jump'), then we push the other destination onto the
3872 worklist.
3873 We guarantee termination by ignoring backward jumps (more or less),
3874 so that `p' is monotonically increasing. More to the point, we
3875 never set `p' (or push) anything `<= p1'. */
3877 while (p < pend)
3879 /* `p1' is used as a marker of how far back a `on_failure_jump'
3880 can go without being ignored. It is normally equal to `p'
3881 (which prevents any backward `on_failure_jump') except right
3882 after a plain `jump', to allow patterns such as:
3883 0: jump 10
3884 3..9: <body>
3885 10: on_failure_jump 3
3886 as used for the *? operator. */
3887 re_char *p1 = p;
3889 switch (*p++)
3891 case succeed:
3892 return 1;
3894 case duplicate:
3895 /* If the first character has to match a backreference, that means
3896 that the group was empty (since it already matched). Since this
3897 is the only case that interests us here, we can assume that the
3898 backreference must match the empty string. */
3899 p++;
3900 continue;
3903 /* Following are the cases which match a character. These end
3904 with `break'. */
3906 case exactn:
3907 if (fastmap)
3909 /* If multibyte is nonzero, the first byte of each
3910 character is an ASCII or a leading code. Otherwise,
3911 each byte is a character. Thus, this works in both
3912 cases. */
3913 fastmap[p[1]] = 1;
3914 if (! multibyte)
3916 /* For the case of matching this unibyte regex
3917 against multibyte, we must set a leading code of
3918 the corresponding multibyte character. */
3919 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3921 fastmap[CHAR_LEADING_CODE (c)] = 1;
3924 break;
3927 case anychar:
3928 /* We could put all the chars except for \n (and maybe \0)
3929 but we don't bother since it is generally not worth it. */
3930 if (!fastmap) break;
3931 return -1;
3934 case charset_not:
3935 if (!fastmap) break;
3937 /* Chars beyond end of bitmap are possible matches. */
3938 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3939 j < (1 << BYTEWIDTH); j++)
3940 fastmap[j] = 1;
3943 /* Fallthrough */
3944 case charset:
3945 if (!fastmap) break;
3946 not = (re_opcode_t) *(p - 1) == charset_not;
3947 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3948 j >= 0; j--)
3949 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3950 fastmap[j] = 1;
3952 #ifdef emacs
3953 if (/* Any leading code can possibly start a character
3954 which doesn't match the specified set of characters. */
3957 /* If we can match a character class, we can match any
3958 multibyte characters. */
3959 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3960 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3963 if (match_any_multibyte_characters == false)
3965 for (j = MIN_MULTIBYTE_LEADING_CODE;
3966 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3967 fastmap[j] = 1;
3968 match_any_multibyte_characters = true;
3972 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3973 && match_any_multibyte_characters == false)
3975 /* Set fastmap[I] to 1 where I is a leading code of each
3976 multibyte character in the range table. */
3977 int c, count;
3978 unsigned char lc1, lc2;
3980 /* Make P points the range table. `+ 2' is to skip flag
3981 bits for a character class. */
3982 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3984 /* Extract the number of ranges in range table into COUNT. */
3985 EXTRACT_NUMBER_AND_INCR (count, p);
3986 for (; count > 0; count--, p += 3)
3988 /* Extract the start and end of each range. */
3989 EXTRACT_CHARACTER (c, p);
3990 lc1 = CHAR_LEADING_CODE (c);
3991 p += 3;
3992 EXTRACT_CHARACTER (c, p);
3993 lc2 = CHAR_LEADING_CODE (c);
3994 for (j = lc1; j <= lc2; j++)
3995 fastmap[j] = 1;
3998 #endif
3999 break;
4001 case syntaxspec:
4002 case notsyntaxspec:
4003 if (!fastmap) break;
4004 #ifndef emacs
4005 not = (re_opcode_t)p[-1] == notsyntaxspec;
4006 k = *p++;
4007 for (j = 0; j < (1 << BYTEWIDTH); j++)
4008 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
4009 fastmap[j] = 1;
4010 break;
4011 #else /* emacs */
4012 /* This match depends on text properties. These end with
4013 aborting optimizations. */
4014 return -1;
4016 case categoryspec:
4017 case notcategoryspec:
4018 if (!fastmap) break;
4019 not = (re_opcode_t)p[-1] == notcategoryspec;
4020 k = *p++;
4021 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4022 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4023 fastmap[j] = 1;
4025 /* Any leading code can possibly start a character which
4026 has or doesn't has the specified category. */
4027 if (match_any_multibyte_characters == false)
4029 for (j = MIN_MULTIBYTE_LEADING_CODE;
4030 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4031 fastmap[j] = 1;
4032 match_any_multibyte_characters = true;
4034 break;
4036 /* All cases after this match the empty string. These end with
4037 `continue'. */
4039 case before_dot:
4040 case at_dot:
4041 case after_dot:
4042 #endif /* !emacs */
4043 case no_op:
4044 case begline:
4045 case endline:
4046 case begbuf:
4047 case endbuf:
4048 case wordbound:
4049 case notwordbound:
4050 case wordbeg:
4051 case wordend:
4052 case symbeg:
4053 case symend:
4054 continue;
4057 case jump:
4058 EXTRACT_NUMBER_AND_INCR (j, p);
4059 if (j < 0)
4060 /* Backward jumps can only go back to code that we've already
4061 visited. `re_compile' should make sure this is true. */
4062 break;
4063 p += j;
4064 switch (*p)
4066 case on_failure_jump:
4067 case on_failure_keep_string_jump:
4068 case on_failure_jump_loop:
4069 case on_failure_jump_nastyloop:
4070 case on_failure_jump_smart:
4071 p++;
4072 break;
4073 default:
4074 continue;
4076 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4077 to jump back to "just after here". */
4078 /* Fallthrough */
4080 case on_failure_jump:
4081 case on_failure_keep_string_jump:
4082 case on_failure_jump_nastyloop:
4083 case on_failure_jump_loop:
4084 case on_failure_jump_smart:
4085 EXTRACT_NUMBER_AND_INCR (j, p);
4086 if (p + j <= p1)
4087 ; /* Backward jump to be ignored. */
4088 else
4089 { /* We have to look down both arms.
4090 We first go down the "straight" path so as to minimize
4091 stack usage when going through alternatives. */
4092 int r = analyze_first (p, pend, fastmap, multibyte);
4093 if (r) return r;
4094 p += j;
4096 continue;
4099 case jump_n:
4100 /* This code simply does not properly handle forward jump_n. */
4101 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4102 p += 4;
4103 /* jump_n can either jump or fall through. The (backward) jump
4104 case has already been handled, so we only need to look at the
4105 fallthrough case. */
4106 continue;
4108 case succeed_n:
4109 /* If N == 0, it should be an on_failure_jump_loop instead. */
4110 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4111 p += 4;
4112 /* We only care about one iteration of the loop, so we don't
4113 need to consider the case where this behaves like an
4114 on_failure_jump. */
4115 continue;
4118 case set_number_at:
4119 p += 4;
4120 continue;
4123 case start_memory:
4124 case stop_memory:
4125 p += 1;
4126 continue;
4129 default:
4130 abort (); /* We have listed all the cases. */
4131 } /* switch *p++ */
4133 /* Getting here means we have found the possible starting
4134 characters for one path of the pattern -- and that the empty
4135 string does not match. We need not follow this path further. */
4136 return 0;
4137 } /* while p */
4139 /* We reached the end without matching anything. */
4140 return 1;
4142 } /* analyze_first */
4144 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4145 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4146 characters can start a string that matches the pattern. This fastmap
4147 is used by re_search to skip quickly over impossible starting points.
4149 Character codes above (1 << BYTEWIDTH) are not represented in the
4150 fastmap, but the leading codes are represented. Thus, the fastmap
4151 indicates which character sets could start a match.
4153 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4154 area as BUFP->fastmap.
4156 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4157 the pattern buffer.
4159 Returns 0 if we succeed, -2 if an internal error. */
4162 re_compile_fastmap (struct re_pattern_buffer *bufp)
4164 char *fastmap = bufp->fastmap;
4165 int analysis;
4167 assert (fastmap && bufp->buffer);
4169 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4170 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4172 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4173 fastmap, RE_MULTIBYTE_P (bufp));
4174 bufp->can_be_null = (analysis != 0);
4175 return 0;
4176 } /* re_compile_fastmap */
4178 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4179 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4180 this memory for recording register information. STARTS and ENDS
4181 must be allocated using the malloc library routine, and must each
4182 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4184 If NUM_REGS == 0, then subsequent matches should allocate their own
4185 register data.
4187 Unless this function is called, the first search or match using
4188 PATTERN_BUFFER will allocate its own register data, without
4189 freeing the old data. */
4191 void
4192 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4194 if (num_regs)
4196 bufp->regs_allocated = REGS_REALLOCATE;
4197 regs->num_regs = num_regs;
4198 regs->start = starts;
4199 regs->end = ends;
4201 else
4203 bufp->regs_allocated = REGS_UNALLOCATED;
4204 regs->num_regs = 0;
4205 regs->start = regs->end = 0;
4208 WEAK_ALIAS (__re_set_registers, re_set_registers)
4210 /* Searching routines. */
4212 /* Like re_search_2, below, but only one string is specified, and
4213 doesn't let you say where to stop matching. */
4215 regoff_t
4216 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4217 ssize_t startpos, ssize_t range, struct re_registers *regs)
4219 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4220 regs, size);
4222 WEAK_ALIAS (__re_search, re_search)
4224 /* Head address of virtual concatenation of string. */
4225 #define HEAD_ADDR_VSTRING(P) \
4226 (((P) >= size1 ? string2 : string1))
4228 /* Address of POS in the concatenation of virtual string. */
4229 #define POS_ADDR_VSTRING(POS) \
4230 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4232 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4233 virtual concatenation of STRING1 and STRING2, starting first at index
4234 STARTPOS, then at STARTPOS + 1, and so on.
4236 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4238 RANGE is how far to scan while trying to match. RANGE = 0 means try
4239 only at STARTPOS; in general, the last start tried is STARTPOS +
4240 RANGE.
4242 In REGS, return the indices of the virtual concatenation of STRING1
4243 and STRING2 that matched the entire BUFP->buffer and its contained
4244 subexpressions.
4246 Do not consider matching one past the index STOP in the virtual
4247 concatenation of STRING1 and STRING2.
4249 We return either the position in the strings at which the match was
4250 found, -1 if no match, or -2 if error (such as failure
4251 stack overflow). */
4253 regoff_t
4254 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4255 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4256 struct re_registers *regs, ssize_t stop)
4258 regoff_t val;
4259 re_char *string1 = (re_char*) str1;
4260 re_char *string2 = (re_char*) str2;
4261 register char *fastmap = bufp->fastmap;
4262 register RE_TRANSLATE_TYPE translate = bufp->translate;
4263 size_t total_size = size1 + size2;
4264 ssize_t endpos = startpos + range;
4265 boolean anchored_start;
4266 /* Nonzero if we are searching multibyte string. */
4267 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4269 /* Check for out-of-range STARTPOS. */
4270 if (startpos < 0 || startpos > total_size)
4271 return -1;
4273 /* Fix up RANGE if it might eventually take us outside
4274 the virtual concatenation of STRING1 and STRING2.
4275 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4276 if (endpos < 0)
4277 range = 0 - startpos;
4278 else if (endpos > total_size)
4279 range = total_size - startpos;
4281 /* If the search isn't to be a backwards one, don't waste time in a
4282 search for a pattern anchored at beginning of buffer. */
4283 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4285 if (startpos > 0)
4286 return -1;
4287 else
4288 range = 0;
4291 #ifdef emacs
4292 /* In a forward search for something that starts with \=.
4293 don't keep searching past point. */
4294 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4296 range = PT_BYTE - BEGV_BYTE - startpos;
4297 if (range < 0)
4298 return -1;
4300 #endif /* emacs */
4302 /* Update the fastmap now if not correct already. */
4303 if (fastmap && !bufp->fastmap_accurate)
4304 re_compile_fastmap (bufp);
4306 /* See whether the pattern is anchored. */
4307 anchored_start = (bufp->buffer[0] == begline);
4309 #ifdef emacs
4310 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4312 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4314 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4316 #endif
4318 /* Loop through the string, looking for a place to start matching. */
4319 for (;;)
4321 /* If the pattern is anchored,
4322 skip quickly past places we cannot match.
4323 We don't bother to treat startpos == 0 specially
4324 because that case doesn't repeat. */
4325 if (anchored_start && startpos > 0)
4327 if (! ((startpos <= size1 ? string1[startpos - 1]
4328 : string2[startpos - size1 - 1])
4329 == '\n'))
4330 goto advance;
4333 /* If a fastmap is supplied, skip quickly over characters that
4334 cannot be the start of a match. If the pattern can match the
4335 null string, however, we don't need to skip characters; we want
4336 the first null string. */
4337 if (fastmap && startpos < total_size && !bufp->can_be_null)
4339 register re_char *d;
4340 register re_wchar_t buf_ch;
4342 d = POS_ADDR_VSTRING (startpos);
4344 if (range > 0) /* Searching forwards. */
4346 ssize_t irange = range, lim = 0;
4348 if (startpos < size1 && startpos + range >= size1)
4349 lim = range - (size1 - startpos);
4351 /* Written out as an if-else to avoid testing `translate'
4352 inside the loop. */
4353 if (RE_TRANSLATE_P (translate))
4355 if (multibyte)
4356 while (range > lim)
4358 int buf_charlen;
4360 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4361 buf_ch = RE_TRANSLATE (translate, buf_ch);
4362 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4363 break;
4365 range -= buf_charlen;
4366 d += buf_charlen;
4368 else
4369 while (range > lim)
4371 register re_wchar_t ch, translated;
4373 buf_ch = *d;
4374 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4375 translated = RE_TRANSLATE (translate, ch);
4376 if (translated != ch
4377 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4378 buf_ch = ch;
4379 if (fastmap[buf_ch])
4380 break;
4381 d++;
4382 range--;
4385 else
4387 if (multibyte)
4388 while (range > lim)
4390 int buf_charlen;
4392 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4393 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4394 break;
4395 range -= buf_charlen;
4396 d += buf_charlen;
4398 else
4399 while (range > lim && !fastmap[*d])
4401 d++;
4402 range--;
4405 startpos += irange - range;
4407 else /* Searching backwards. */
4409 if (multibyte)
4411 buf_ch = STRING_CHAR (d);
4412 buf_ch = TRANSLATE (buf_ch);
4413 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4414 goto advance;
4416 else
4418 register re_wchar_t ch, translated;
4420 buf_ch = *d;
4421 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4422 translated = TRANSLATE (ch);
4423 if (translated != ch
4424 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4425 buf_ch = ch;
4426 if (! fastmap[TRANSLATE (buf_ch)])
4427 goto advance;
4432 /* If can't match the null string, and that's all we have left, fail. */
4433 if (range >= 0 && startpos == total_size && fastmap
4434 && !bufp->can_be_null)
4435 return -1;
4437 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4438 startpos, regs, stop);
4440 if (val >= 0)
4441 return startpos;
4443 if (val == -2)
4444 return -2;
4446 advance:
4447 if (!range)
4448 break;
4449 else if (range > 0)
4451 /* Update STARTPOS to the next character boundary. */
4452 if (multibyte)
4454 re_char *p = POS_ADDR_VSTRING (startpos);
4455 int len = BYTES_BY_CHAR_HEAD (*p);
4457 range -= len;
4458 if (range < 0)
4459 break;
4460 startpos += len;
4462 else
4464 range--;
4465 startpos++;
4468 else
4470 range++;
4471 startpos--;
4473 /* Update STARTPOS to the previous character boundary. */
4474 if (multibyte)
4476 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4477 re_char *p0 = p;
4478 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4480 /* Find the head of multibyte form. */
4481 PREV_CHAR_BOUNDARY (p, phead);
4482 range += p0 - 1 - p;
4483 if (range > 0)
4484 break;
4486 startpos -= p0 - 1 - p;
4490 return -1;
4491 } /* re_search_2 */
4492 WEAK_ALIAS (__re_search_2, re_search_2)
4494 /* Declarations and macros for re_match_2. */
4496 static int bcmp_translate (re_char *s1, re_char *s2,
4497 register ssize_t len,
4498 RE_TRANSLATE_TYPE translate,
4499 const int multibyte);
4501 /* This converts PTR, a pointer into one of the search strings `string1'
4502 and `string2' into an offset from the beginning of that string. */
4503 #define POINTER_TO_OFFSET(ptr) \
4504 (FIRST_STRING_P (ptr) \
4505 ? (ptr) - string1 \
4506 : (ptr) - string2 + (ptrdiff_t) size1)
4508 /* Call before fetching a character with *d. This switches over to
4509 string2 if necessary.
4510 Check re_match_2_internal for a discussion of why end_match_2 might
4511 not be within string2 (but be equal to end_match_1 instead). */
4512 #define PREFETCH() \
4513 while (d == dend) \
4515 /* End of string2 => fail. */ \
4516 if (dend == end_match_2) \
4517 goto fail; \
4518 /* End of string1 => advance to string2. */ \
4519 d = string2; \
4520 dend = end_match_2; \
4523 /* Call before fetching a char with *d if you already checked other limits.
4524 This is meant for use in lookahead operations like wordend, etc..
4525 where we might need to look at parts of the string that might be
4526 outside of the LIMITs (i.e past `stop'). */
4527 #define PREFETCH_NOLIMIT() \
4528 if (d == end1) \
4530 d = string2; \
4531 dend = end_match_2; \
4534 /* Test if at very beginning or at very end of the virtual concatenation
4535 of `string1' and `string2'. If only one string, it's `string2'. */
4536 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4537 #define AT_STRINGS_END(d) ((d) == end2)
4539 /* Disabled due to a compiler bug -- see comment at case wordbound */
4541 /* The comment at case wordbound is following one, but we don't use
4542 AT_WORD_BOUNDARY anymore to support multibyte form.
4544 The DEC Alpha C compiler 3.x generates incorrect code for the
4545 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4546 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4547 macro and introducing temporary variables works around the bug. */
4549 #if 0
4550 /* Test if D points to a character which is word-constituent. We have
4551 two special cases to check for: if past the end of string1, look at
4552 the first character in string2; and if before the beginning of
4553 string2, look at the last character in string1. */
4554 #define WORDCHAR_P(d) \
4555 (SYNTAX ((d) == end1 ? *string2 \
4556 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4557 == Sword)
4559 /* Test if the character before D and the one at D differ with respect
4560 to being word-constituent. */
4561 #define AT_WORD_BOUNDARY(d) \
4562 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4563 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4564 #endif
4566 /* Free everything we malloc. */
4567 #ifdef MATCH_MAY_ALLOCATE
4568 # define FREE_VAR(var) \
4569 do { \
4570 if (var) \
4572 REGEX_FREE (var); \
4573 var = NULL; \
4575 } while (0)
4576 # define FREE_VARIABLES() \
4577 do { \
4578 REGEX_FREE_STACK (fail_stack.stack); \
4579 FREE_VAR (regstart); \
4580 FREE_VAR (regend); \
4581 FREE_VAR (best_regstart); \
4582 FREE_VAR (best_regend); \
4583 REGEX_SAFE_FREE (); \
4584 } while (0)
4585 #else
4586 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4587 #endif /* not MATCH_MAY_ALLOCATE */
4590 /* Optimization routines. */
4592 /* If the operation is a match against one or more chars,
4593 return a pointer to the next operation, else return NULL. */
4594 static re_char *
4595 skip_one_char (const_re_char *p)
4597 switch (*p++)
4599 case anychar:
4600 break;
4602 case exactn:
4603 p += *p + 1;
4604 break;
4606 case charset_not:
4607 case charset:
4608 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4610 int mcnt;
4611 p = CHARSET_RANGE_TABLE (p - 1);
4612 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4613 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4615 else
4616 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4617 break;
4619 case syntaxspec:
4620 case notsyntaxspec:
4621 #ifdef emacs
4622 case categoryspec:
4623 case notcategoryspec:
4624 #endif /* emacs */
4625 p++;
4626 break;
4628 default:
4629 p = NULL;
4631 return p;
4635 /* Jump over non-matching operations. */
4636 static re_char *
4637 skip_noops (const_re_char *p, const_re_char *pend)
4639 int mcnt;
4640 while (p < pend)
4642 switch (*p)
4644 case start_memory:
4645 case stop_memory:
4646 p += 2; break;
4647 case no_op:
4648 p += 1; break;
4649 case jump:
4650 p += 1;
4651 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4652 p += mcnt;
4653 break;
4654 default:
4655 return p;
4658 assert (p == pend);
4659 return p;
4662 /* Non-zero if "p1 matches something" implies "p2 fails". */
4663 static int
4664 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4665 const_re_char *p2)
4667 re_opcode_t op2;
4668 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4669 unsigned char *pend = bufp->buffer + bufp->used;
4671 assert (p1 >= bufp->buffer && p1 < pend
4672 && p2 >= bufp->buffer && p2 <= pend);
4674 /* Skip over open/close-group commands.
4675 If what follows this loop is a ...+ construct,
4676 look at what begins its body, since we will have to
4677 match at least one of that. */
4678 p2 = skip_noops (p2, pend);
4679 /* The same skip can be done for p1, except that this function
4680 is only used in the case where p1 is a simple match operator. */
4681 /* p1 = skip_noops (p1, pend); */
4683 assert (p1 >= bufp->buffer && p1 < pend
4684 && p2 >= bufp->buffer && p2 <= pend);
4686 op2 = p2 == pend ? succeed : *p2;
4688 switch (op2)
4690 case succeed:
4691 case endbuf:
4692 /* If we're at the end of the pattern, we can change. */
4693 if (skip_one_char (p1))
4695 DEBUG_PRINT (" End of pattern: fast loop.\n");
4696 return 1;
4698 break;
4700 case endline:
4701 case exactn:
4703 register re_wchar_t c
4704 = (re_opcode_t) *p2 == endline ? '\n'
4705 : RE_STRING_CHAR (p2 + 2, multibyte);
4707 if ((re_opcode_t) *p1 == exactn)
4709 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4711 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4712 return 1;
4716 else if ((re_opcode_t) *p1 == charset
4717 || (re_opcode_t) *p1 == charset_not)
4719 int not = (re_opcode_t) *p1 == charset_not;
4721 /* Test if C is listed in charset (or charset_not)
4722 at `p1'. */
4723 if (! multibyte || IS_REAL_ASCII (c))
4725 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4726 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4727 not = !not;
4729 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4730 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4732 /* `not' is equal to 1 if c would match, which means
4733 that we can't change to pop_failure_jump. */
4734 if (!not)
4736 DEBUG_PRINT (" No match => fast loop.\n");
4737 return 1;
4740 else if ((re_opcode_t) *p1 == anychar
4741 && c == '\n')
4743 DEBUG_PRINT (" . != \\n => fast loop.\n");
4744 return 1;
4747 break;
4749 case charset:
4751 if ((re_opcode_t) *p1 == exactn)
4752 /* Reuse the code above. */
4753 return mutually_exclusive_p (bufp, p2, p1);
4755 /* It is hard to list up all the character in charset
4756 P2 if it includes multibyte character. Give up in
4757 such case. */
4758 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4760 /* Now, we are sure that P2 has no range table.
4761 So, for the size of bitmap in P2, `p2[1]' is
4762 enough. But P1 may have range table, so the
4763 size of bitmap table of P1 is extracted by
4764 using macro `CHARSET_BITMAP_SIZE'.
4766 In a multibyte case, we know that all the character
4767 listed in P2 is ASCII. In a unibyte case, P1 has only a
4768 bitmap table. So, in both cases, it is enough to test
4769 only the bitmap table of P1. */
4771 if ((re_opcode_t) *p1 == charset)
4773 int idx;
4774 /* We win if the charset inside the loop
4775 has no overlap with the one after the loop. */
4776 for (idx = 0;
4777 (idx < (int) p2[1]
4778 && idx < CHARSET_BITMAP_SIZE (p1));
4779 idx++)
4780 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4781 break;
4783 if (idx == p2[1]
4784 || idx == CHARSET_BITMAP_SIZE (p1))
4786 DEBUG_PRINT (" No match => fast loop.\n");
4787 return 1;
4790 else if ((re_opcode_t) *p1 == charset_not)
4792 int idx;
4793 /* We win if the charset_not inside the loop lists
4794 every character listed in the charset after. */
4795 for (idx = 0; idx < (int) p2[1]; idx++)
4796 if (! (p2[2 + idx] == 0
4797 || (idx < CHARSET_BITMAP_SIZE (p1)
4798 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4799 break;
4801 if (idx == p2[1])
4803 DEBUG_PRINT (" No match => fast loop.\n");
4804 return 1;
4809 break;
4811 case charset_not:
4812 switch (*p1)
4814 case exactn:
4815 case charset:
4816 /* Reuse the code above. */
4817 return mutually_exclusive_p (bufp, p2, p1);
4818 case charset_not:
4819 /* When we have two charset_not, it's very unlikely that
4820 they don't overlap. The union of the two sets of excluded
4821 chars should cover all possible chars, which, as a matter of
4822 fact, is virtually impossible in multibyte buffers. */
4823 break;
4825 break;
4827 case wordend:
4828 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4829 case symend:
4830 return ((re_opcode_t) *p1 == syntaxspec
4831 && (p1[1] == Ssymbol || p1[1] == Sword));
4832 case notsyntaxspec:
4833 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4835 case wordbeg:
4836 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4837 case symbeg:
4838 return ((re_opcode_t) *p1 == notsyntaxspec
4839 && (p1[1] == Ssymbol || p1[1] == Sword));
4840 case syntaxspec:
4841 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4843 case wordbound:
4844 return (((re_opcode_t) *p1 == notsyntaxspec
4845 || (re_opcode_t) *p1 == syntaxspec)
4846 && p1[1] == Sword);
4848 #ifdef emacs
4849 case categoryspec:
4850 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4851 case notcategoryspec:
4852 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4853 #endif /* emacs */
4855 default:
4859 /* Safe default. */
4860 return 0;
4864 /* Matching routines. */
4866 #ifndef emacs /* Emacs never uses this. */
4867 /* re_match is like re_match_2 except it takes only a single string. */
4869 regoff_t
4870 re_match (struct re_pattern_buffer *bufp, const char *string,
4871 size_t size, ssize_t pos, struct re_registers *regs)
4873 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4874 size, pos, regs, size);
4875 return result;
4877 WEAK_ALIAS (__re_match, re_match)
4878 #endif /* not emacs */
4880 #ifdef emacs
4881 /* In Emacs, this is the string or buffer in which we
4882 are matching. It is used for looking up syntax properties. */
4883 Lisp_Object re_match_object;
4884 #endif
4886 /* re_match_2 matches the compiled pattern in BUFP against the
4887 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4888 and SIZE2, respectively). We start matching at POS, and stop
4889 matching at STOP.
4891 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4892 store offsets for the substring each group matched in REGS. See the
4893 documentation for exactly how many groups we fill.
4895 We return -1 if no match, -2 if an internal error (such as the
4896 failure stack overflowing). Otherwise, we return the length of the
4897 matched substring. */
4899 regoff_t
4900 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4901 size_t size1, const char *string2, size_t size2, ssize_t pos,
4902 struct re_registers *regs, ssize_t stop)
4904 regoff_t result;
4906 #ifdef emacs
4907 ssize_t charpos;
4908 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4909 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4910 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4911 #endif
4913 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4914 (re_char*) string2, size2,
4915 pos, regs, stop);
4916 return result;
4918 WEAK_ALIAS (__re_match_2, re_match_2)
4921 /* This is a separate function so that we can force an alloca cleanup
4922 afterwards. */
4923 static regoff_t
4924 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4925 size_t size1, const_re_char *string2, size_t size2,
4926 ssize_t pos, struct re_registers *regs, ssize_t stop)
4928 /* General temporaries. */
4929 int mcnt;
4930 size_t reg;
4932 /* Just past the end of the corresponding string. */
4933 re_char *end1, *end2;
4935 /* Pointers into string1 and string2, just past the last characters in
4936 each to consider matching. */
4937 re_char *end_match_1, *end_match_2;
4939 /* Where we are in the data, and the end of the current string. */
4940 re_char *d, *dend;
4942 /* Used sometimes to remember where we were before starting matching
4943 an operator so that we can go back in case of failure. This "atomic"
4944 behavior of matching opcodes is indispensable to the correctness
4945 of the on_failure_keep_string_jump optimization. */
4946 re_char *dfail;
4948 /* Where we are in the pattern, and the end of the pattern. */
4949 re_char *p = bufp->buffer;
4950 re_char *pend = p + bufp->used;
4952 /* We use this to map every character in the string. */
4953 RE_TRANSLATE_TYPE translate = bufp->translate;
4955 /* Nonzero if BUFP is setup from a multibyte regex. */
4956 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4958 /* Nonzero if STRING1/STRING2 are multibyte. */
4959 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4961 /* Failure point stack. Each place that can handle a failure further
4962 down the line pushes a failure point on this stack. It consists of
4963 regstart, and regend for all registers corresponding to
4964 the subexpressions we're currently inside, plus the number of such
4965 registers, and, finally, two char *'s. The first char * is where
4966 to resume scanning the pattern; the second one is where to resume
4967 scanning the strings. */
4968 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4969 fail_stack_type fail_stack;
4970 #endif
4971 #ifdef DEBUG_COMPILES_ARGUMENTS
4972 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4973 #endif
4975 #if defined REL_ALLOC && defined REGEX_MALLOC
4976 /* This holds the pointer to the failure stack, when
4977 it is allocated relocatably. */
4978 fail_stack_elt_t *failure_stack_ptr;
4979 #endif
4981 /* We fill all the registers internally, independent of what we
4982 return, for use in backreferences. The number here includes
4983 an element for register zero. */
4984 size_t num_regs = bufp->re_nsub + 1;
4986 /* Information on the contents of registers. These are pointers into
4987 the input strings; they record just what was matched (on this
4988 attempt) by a subexpression part of the pattern, that is, the
4989 regnum-th regstart pointer points to where in the pattern we began
4990 matching and the regnum-th regend points to right after where we
4991 stopped matching the regnum-th subexpression. (The zeroth register
4992 keeps track of what the whole pattern matches.) */
4993 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4994 re_char **regstart, **regend;
4995 #endif
4997 /* The following record the register info as found in the above
4998 variables when we find a match better than any we've seen before.
4999 This happens as we backtrack through the failure points, which in
5000 turn happens only if we have not yet matched the entire string. */
5001 unsigned best_regs_set = false;
5002 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5003 re_char **best_regstart, **best_regend;
5004 #endif
5006 /* Logically, this is `best_regend[0]'. But we don't want to have to
5007 allocate space for that if we're not allocating space for anything
5008 else (see below). Also, we never need info about register 0 for
5009 any of the other register vectors, and it seems rather a kludge to
5010 treat `best_regend' differently than the rest. So we keep track of
5011 the end of the best match so far in a separate variable. We
5012 initialize this to NULL so that when we backtrack the first time
5013 and need to test it, it's not garbage. */
5014 re_char *match_end = NULL;
5016 #ifdef DEBUG_COMPILES_ARGUMENTS
5017 /* Counts the total number of registers pushed. */
5018 unsigned num_regs_pushed = 0;
5019 #endif
5021 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5023 REGEX_USE_SAFE_ALLOCA;
5025 INIT_FAIL_STACK ();
5027 #ifdef MATCH_MAY_ALLOCATE
5028 /* Do not bother to initialize all the register variables if there are
5029 no groups in the pattern, as it takes a fair amount of time. If
5030 there are groups, we include space for register 0 (the whole
5031 pattern), even though we never use it, since it simplifies the
5032 array indexing. We should fix this. */
5033 if (bufp->re_nsub)
5035 regstart = REGEX_TALLOC (num_regs, re_char *);
5036 regend = REGEX_TALLOC (num_regs, re_char *);
5037 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5038 best_regend = REGEX_TALLOC (num_regs, re_char *);
5040 if (!(regstart && regend && best_regstart && best_regend))
5042 FREE_VARIABLES ();
5043 return -2;
5046 else
5048 /* We must initialize all our variables to NULL, so that
5049 `FREE_VARIABLES' doesn't try to free them. */
5050 regstart = regend = best_regstart = best_regend = NULL;
5052 #endif /* MATCH_MAY_ALLOCATE */
5054 /* The starting position is bogus. */
5055 if (pos < 0 || pos > size1 + size2)
5057 FREE_VARIABLES ();
5058 return -1;
5061 /* Initialize subexpression text positions to -1 to mark ones that no
5062 start_memory/stop_memory has been seen for. Also initialize the
5063 register information struct. */
5064 for (reg = 1; reg < num_regs; reg++)
5065 regstart[reg] = regend[reg] = NULL;
5067 /* We move `string1' into `string2' if the latter's empty -- but not if
5068 `string1' is null. */
5069 if (size2 == 0 && string1 != NULL)
5071 string2 = string1;
5072 size2 = size1;
5073 string1 = 0;
5074 size1 = 0;
5076 end1 = string1 + size1;
5077 end2 = string2 + size2;
5079 /* `p' scans through the pattern as `d' scans through the data.
5080 `dend' is the end of the input string that `d' points within. `d'
5081 is advanced into the following input string whenever necessary, but
5082 this happens before fetching; therefore, at the beginning of the
5083 loop, `d' can be pointing at the end of a string, but it cannot
5084 equal `string2'. */
5085 if (pos >= size1)
5087 /* Only match within string2. */
5088 d = string2 + pos - size1;
5089 dend = end_match_2 = string2 + stop - size1;
5090 end_match_1 = end1; /* Just to give it a value. */
5092 else
5094 if (stop < size1)
5096 /* Only match within string1. */
5097 end_match_1 = string1 + stop;
5098 /* BEWARE!
5099 When we reach end_match_1, PREFETCH normally switches to string2.
5100 But in the present case, this means that just doing a PREFETCH
5101 makes us jump from `stop' to `gap' within the string.
5102 What we really want here is for the search to stop as
5103 soon as we hit end_match_1. That's why we set end_match_2
5104 to end_match_1 (since PREFETCH fails as soon as we hit
5105 end_match_2). */
5106 end_match_2 = end_match_1;
5108 else
5109 { /* It's important to use this code when stop == size so that
5110 moving `d' from end1 to string2 will not prevent the d == dend
5111 check from catching the end of string. */
5112 end_match_1 = end1;
5113 end_match_2 = string2 + stop - size1;
5115 d = string1 + pos;
5116 dend = end_match_1;
5119 DEBUG_PRINT ("The compiled pattern is: ");
5120 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5121 DEBUG_PRINT ("The string to match is: `");
5122 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5123 DEBUG_PRINT ("'\n");
5125 /* This loops over pattern commands. It exits by returning from the
5126 function if the match is complete, or it drops through if the match
5127 fails at this starting point in the input data. */
5128 for (;;)
5130 DEBUG_PRINT ("\n%p: ", p);
5132 if (p == pend)
5134 ptrdiff_t dcnt;
5136 /* End of pattern means we might have succeeded. */
5137 DEBUG_PRINT ("end of pattern ... ");
5139 /* If we haven't matched the entire string, and we want the
5140 longest match, try backtracking. */
5141 if (d != end_match_2)
5143 /* 1 if this match ends in the same string (string1 or string2)
5144 as the best previous match. */
5145 boolean same_str_p = (FIRST_STRING_P (match_end)
5146 == FIRST_STRING_P (d));
5147 /* 1 if this match is the best seen so far. */
5148 boolean best_match_p;
5150 /* AIX compiler got confused when this was combined
5151 with the previous declaration. */
5152 if (same_str_p)
5153 best_match_p = d > match_end;
5154 else
5155 best_match_p = !FIRST_STRING_P (d);
5157 DEBUG_PRINT ("backtracking.\n");
5159 if (!FAIL_STACK_EMPTY ())
5160 { /* More failure points to try. */
5162 /* If exceeds best match so far, save it. */
5163 if (!best_regs_set || best_match_p)
5165 best_regs_set = true;
5166 match_end = d;
5168 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5170 for (reg = 1; reg < num_regs; reg++)
5172 best_regstart[reg] = regstart[reg];
5173 best_regend[reg] = regend[reg];
5176 goto fail;
5179 /* If no failure points, don't restore garbage. And if
5180 last match is real best match, don't restore second
5181 best one. */
5182 else if (best_regs_set && !best_match_p)
5184 restore_best_regs:
5185 /* Restore best match. It may happen that `dend ==
5186 end_match_1' while the restored d is in string2.
5187 For example, the pattern `x.*y.*z' against the
5188 strings `x-' and `y-z-', if the two strings are
5189 not consecutive in memory. */
5190 DEBUG_PRINT ("Restoring best registers.\n");
5192 d = match_end;
5193 dend = ((d >= string1 && d <= end1)
5194 ? end_match_1 : end_match_2);
5196 for (reg = 1; reg < num_regs; reg++)
5198 regstart[reg] = best_regstart[reg];
5199 regend[reg] = best_regend[reg];
5202 } /* d != end_match_2 */
5204 succeed_label:
5205 DEBUG_PRINT ("Accepting match.\n");
5207 /* If caller wants register contents data back, do it. */
5208 if (regs && !bufp->no_sub)
5210 /* Have the register data arrays been allocated? */
5211 if (bufp->regs_allocated == REGS_UNALLOCATED)
5212 { /* No. So allocate them with malloc. We need one
5213 extra element beyond `num_regs' for the `-1' marker
5214 GNU code uses. */
5215 regs->num_regs = max (RE_NREGS, num_regs + 1);
5216 regs->start = TALLOC (regs->num_regs, regoff_t);
5217 regs->end = TALLOC (regs->num_regs, regoff_t);
5218 if (regs->start == NULL || regs->end == NULL)
5220 FREE_VARIABLES ();
5221 return -2;
5223 bufp->regs_allocated = REGS_REALLOCATE;
5225 else if (bufp->regs_allocated == REGS_REALLOCATE)
5226 { /* Yes. If we need more elements than were already
5227 allocated, reallocate them. If we need fewer, just
5228 leave it alone. */
5229 if (regs->num_regs < num_regs + 1)
5231 regs->num_regs = num_regs + 1;
5232 RETALLOC (regs->start, regs->num_regs, regoff_t);
5233 RETALLOC (regs->end, regs->num_regs, regoff_t);
5234 if (regs->start == NULL || regs->end == NULL)
5236 FREE_VARIABLES ();
5237 return -2;
5241 else
5243 /* These braces fend off a "empty body in an else-statement"
5244 warning under GCC when assert expands to nothing. */
5245 assert (bufp->regs_allocated == REGS_FIXED);
5248 /* Convert the pointer data in `regstart' and `regend' to
5249 indices. Register zero has to be set differently,
5250 since we haven't kept track of any info for it. */
5251 if (regs->num_regs > 0)
5253 regs->start[0] = pos;
5254 regs->end[0] = POINTER_TO_OFFSET (d);
5257 /* Go through the first `min (num_regs, regs->num_regs)'
5258 registers, since that is all we initialized. */
5259 for (reg = 1; reg < min (num_regs, regs->num_regs); reg++)
5261 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5262 regs->start[reg] = regs->end[reg] = -1;
5263 else
5265 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5266 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5270 /* If the regs structure we return has more elements than
5271 were in the pattern, set the extra elements to -1. If
5272 we (re)allocated the registers, this is the case,
5273 because we always allocate enough to have at least one
5274 -1 at the end. */
5275 for (reg = num_regs; reg < regs->num_regs; reg++)
5276 regs->start[reg] = regs->end[reg] = -1;
5277 } /* regs && !bufp->no_sub */
5279 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5280 nfailure_points_pushed, nfailure_points_popped,
5281 nfailure_points_pushed - nfailure_points_popped);
5282 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5284 dcnt = POINTER_TO_OFFSET (d) - pos;
5286 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5288 FREE_VARIABLES ();
5289 return dcnt;
5292 /* Otherwise match next pattern command. */
5293 switch (*p++)
5295 /* Ignore these. Used to ignore the n of succeed_n's which
5296 currently have n == 0. */
5297 case no_op:
5298 DEBUG_PRINT ("EXECUTING no_op.\n");
5299 break;
5301 case succeed:
5302 DEBUG_PRINT ("EXECUTING succeed.\n");
5303 goto succeed_label;
5305 /* Match the next n pattern characters exactly. The following
5306 byte in the pattern defines n, and the n bytes after that
5307 are the characters to match. */
5308 case exactn:
5309 mcnt = *p++;
5310 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5312 /* Remember the start point to rollback upon failure. */
5313 dfail = d;
5315 #ifndef emacs
5316 /* This is written out as an if-else so we don't waste time
5317 testing `translate' inside the loop. */
5318 if (RE_TRANSLATE_P (translate))
5321 PREFETCH ();
5322 if (RE_TRANSLATE (translate, *d) != *p++)
5324 d = dfail;
5325 goto fail;
5327 d++;
5329 while (--mcnt);
5330 else
5333 PREFETCH ();
5334 if (*d++ != *p++)
5336 d = dfail;
5337 goto fail;
5340 while (--mcnt);
5341 #else /* emacs */
5342 /* The cost of testing `translate' is comparatively small. */
5343 if (target_multibyte)
5346 int pat_charlen, buf_charlen;
5347 int pat_ch, buf_ch;
5349 PREFETCH ();
5350 if (multibyte)
5351 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5352 else
5354 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5355 pat_charlen = 1;
5357 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5359 if (TRANSLATE (buf_ch) != pat_ch)
5361 d = dfail;
5362 goto fail;
5365 p += pat_charlen;
5366 d += buf_charlen;
5367 mcnt -= pat_charlen;
5369 while (mcnt > 0);
5370 else
5373 int pat_charlen;
5374 int pat_ch, buf_ch;
5376 PREFETCH ();
5377 if (multibyte)
5379 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5380 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5382 else
5384 pat_ch = *p;
5385 pat_charlen = 1;
5387 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5388 if (! CHAR_BYTE8_P (buf_ch))
5390 buf_ch = TRANSLATE (buf_ch);
5391 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5392 if (buf_ch < 0)
5393 buf_ch = *d;
5395 else
5396 buf_ch = *d;
5397 if (buf_ch != pat_ch)
5399 d = dfail;
5400 goto fail;
5402 p += pat_charlen;
5403 d++;
5405 while (--mcnt);
5406 #endif
5407 break;
5410 /* Match any character except possibly a newline or a null. */
5411 case anychar:
5413 int buf_charlen;
5414 re_wchar_t buf_ch;
5416 DEBUG_PRINT ("EXECUTING anychar.\n");
5418 PREFETCH ();
5419 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5420 target_multibyte);
5421 buf_ch = TRANSLATE (buf_ch);
5423 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5424 && buf_ch == '\n')
5425 || ((bufp->syntax & RE_DOT_NOT_NULL)
5426 && buf_ch == '\000'))
5427 goto fail;
5429 DEBUG_PRINT (" Matched `%d'.\n", *d);
5430 d += buf_charlen;
5432 break;
5435 case charset:
5436 case charset_not:
5438 register unsigned int c;
5439 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5440 int len;
5442 /* Start of actual range_table, or end of bitmap if there is no
5443 range table. */
5444 re_char *range_table IF_LINT (= NULL);
5446 /* Nonzero if there is a range table. */
5447 int range_table_exists;
5449 /* Number of ranges of range table. This is not included
5450 in the initial byte-length of the command. */
5451 int count = 0;
5453 /* Whether matching against a unibyte character. */
5454 boolean unibyte_char = false;
5456 DEBUG_PRINT ("EXECUTING charset%s.\n", not ? "_not" : "");
5458 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5460 if (range_table_exists)
5462 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5463 EXTRACT_NUMBER_AND_INCR (count, range_table);
5466 PREFETCH ();
5467 c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5468 if (target_multibyte)
5470 int c1;
5472 c = TRANSLATE (c);
5473 c1 = RE_CHAR_TO_UNIBYTE (c);
5474 if (c1 >= 0)
5476 unibyte_char = true;
5477 c = c1;
5480 else
5482 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5484 if (! CHAR_BYTE8_P (c1))
5486 c1 = TRANSLATE (c1);
5487 c1 = RE_CHAR_TO_UNIBYTE (c1);
5488 if (c1 >= 0)
5490 unibyte_char = true;
5491 c = c1;
5494 else
5495 unibyte_char = true;
5498 if (unibyte_char && c < (1 << BYTEWIDTH))
5499 { /* Lookup bitmap. */
5500 /* Cast to `unsigned' instead of `unsigned char' in
5501 case the bit list is a full 32 bytes long. */
5502 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5503 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5504 not = !not;
5506 #ifdef emacs
5507 else if (range_table_exists)
5509 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5511 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5512 | (class_bits & BIT_MULTIBYTE)
5513 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5514 | (class_bits & BIT_SPACE && ISSPACE (c))
5515 | (class_bits & BIT_UPPER && ISUPPER (c))
5516 | (class_bits & BIT_WORD && ISWORD (c)))
5517 not = !not;
5518 else
5519 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5521 #endif /* emacs */
5523 if (range_table_exists)
5524 p = CHARSET_RANGE_TABLE_END (range_table, count);
5525 else
5526 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5528 if (!not) goto fail;
5530 d += len;
5532 break;
5535 /* The beginning of a group is represented by start_memory.
5536 The argument is the register number. The text
5537 matched within the group is recorded (in the internal
5538 registers data structure) under the register number. */
5539 case start_memory:
5540 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5542 /* In case we need to undo this operation (via backtracking). */
5543 PUSH_FAILURE_REG (*p);
5545 regstart[*p] = d;
5546 regend[*p] = NULL; /* probably unnecessary. -sm */
5547 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5549 /* Move past the register number and inner group count. */
5550 p += 1;
5551 break;
5554 /* The stop_memory opcode represents the end of a group. Its
5555 argument is the same as start_memory's: the register number. */
5556 case stop_memory:
5557 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5559 assert (!REG_UNSET (regstart[*p]));
5560 /* Strictly speaking, there should be code such as:
5562 assert (REG_UNSET (regend[*p]));
5563 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5565 But the only info to be pushed is regend[*p] and it is known to
5566 be UNSET, so there really isn't anything to push.
5567 Not pushing anything, on the other hand deprives us from the
5568 guarantee that regend[*p] is UNSET since undoing this operation
5569 will not reset its value properly. This is not important since
5570 the value will only be read on the next start_memory or at
5571 the very end and both events can only happen if this stop_memory
5572 is *not* undone. */
5574 regend[*p] = d;
5575 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5577 /* Move past the register number and the inner group count. */
5578 p += 1;
5579 break;
5582 /* \<digit> has been turned into a `duplicate' command which is
5583 followed by the numeric value of <digit> as the register number. */
5584 case duplicate:
5586 register re_char *d2, *dend2;
5587 int regno = *p++; /* Get which register to match against. */
5588 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5590 /* Can't back reference a group which we've never matched. */
5591 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5592 goto fail;
5594 /* Where in input to try to start matching. */
5595 d2 = regstart[regno];
5597 /* Remember the start point to rollback upon failure. */
5598 dfail = d;
5600 /* Where to stop matching; if both the place to start and
5601 the place to stop matching are in the same string, then
5602 set to the place to stop, otherwise, for now have to use
5603 the end of the first string. */
5605 dend2 = ((FIRST_STRING_P (regstart[regno])
5606 == FIRST_STRING_P (regend[regno]))
5607 ? regend[regno] : end_match_1);
5608 for (;;)
5610 ptrdiff_t dcnt;
5612 /* If necessary, advance to next segment in register
5613 contents. */
5614 while (d2 == dend2)
5616 if (dend2 == end_match_2) break;
5617 if (dend2 == regend[regno]) break;
5619 /* End of string1 => advance to string2. */
5620 d2 = string2;
5621 dend2 = regend[regno];
5623 /* At end of register contents => success */
5624 if (d2 == dend2) break;
5626 /* If necessary, advance to next segment in data. */
5627 PREFETCH ();
5629 /* How many characters left in this segment to match. */
5630 dcnt = dend - d;
5632 /* Want how many consecutive characters we can match in
5633 one shot, so, if necessary, adjust the count. */
5634 if (dcnt > dend2 - d2)
5635 dcnt = dend2 - d2;
5637 /* Compare that many; failure if mismatch, else move
5638 past them. */
5639 if (RE_TRANSLATE_P (translate)
5640 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5641 : memcmp (d, d2, dcnt))
5643 d = dfail;
5644 goto fail;
5646 d += dcnt, d2 += dcnt;
5649 break;
5652 /* begline matches the empty string at the beginning of the string
5653 (unless `not_bol' is set in `bufp'), and after newlines. */
5654 case begline:
5655 DEBUG_PRINT ("EXECUTING begline.\n");
5657 if (AT_STRINGS_BEG (d))
5659 if (!bufp->not_bol) break;
5661 else
5663 unsigned c;
5664 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5665 if (c == '\n')
5666 break;
5668 /* In all other cases, we fail. */
5669 goto fail;
5672 /* endline is the dual of begline. */
5673 case endline:
5674 DEBUG_PRINT ("EXECUTING endline.\n");
5676 if (AT_STRINGS_END (d))
5678 if (!bufp->not_eol) break;
5680 else
5682 PREFETCH_NOLIMIT ();
5683 if (*d == '\n')
5684 break;
5686 goto fail;
5689 /* Match at the very beginning of the data. */
5690 case begbuf:
5691 DEBUG_PRINT ("EXECUTING begbuf.\n");
5692 if (AT_STRINGS_BEG (d))
5693 break;
5694 goto fail;
5697 /* Match at the very end of the data. */
5698 case endbuf:
5699 DEBUG_PRINT ("EXECUTING endbuf.\n");
5700 if (AT_STRINGS_END (d))
5701 break;
5702 goto fail;
5705 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5706 pushes NULL as the value for the string on the stack. Then
5707 `POP_FAILURE_POINT' will keep the current value for the
5708 string, instead of restoring it. To see why, consider
5709 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5710 then the . fails against the \n. But the next thing we want
5711 to do is match the \n against the \n; if we restored the
5712 string value, we would be back at the foo.
5714 Because this is used only in specific cases, we don't need to
5715 check all the things that `on_failure_jump' does, to make
5716 sure the right things get saved on the stack. Hence we don't
5717 share its code. The only reason to push anything on the
5718 stack at all is that otherwise we would have to change
5719 `anychar's code to do something besides goto fail in this
5720 case; that seems worse than this. */
5721 case on_failure_keep_string_jump:
5722 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5723 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5724 mcnt, p + mcnt);
5726 PUSH_FAILURE_POINT (p - 3, NULL);
5727 break;
5729 /* A nasty loop is introduced by the non-greedy *? and +?.
5730 With such loops, the stack only ever contains one failure point
5731 at a time, so that a plain on_failure_jump_loop kind of
5732 cycle detection cannot work. Worse yet, such a detection
5733 can not only fail to detect a cycle, but it can also wrongly
5734 detect a cycle (between different instantiations of the same
5735 loop).
5736 So the method used for those nasty loops is a little different:
5737 We use a special cycle-detection-stack-frame which is pushed
5738 when the on_failure_jump_nastyloop failure-point is *popped*.
5739 This special frame thus marks the beginning of one iteration
5740 through the loop and we can hence easily check right here
5741 whether something matched between the beginning and the end of
5742 the loop. */
5743 case on_failure_jump_nastyloop:
5744 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5745 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5746 mcnt, p + mcnt);
5748 assert ((re_opcode_t)p[-4] == no_op);
5750 int cycle = 0;
5751 CHECK_INFINITE_LOOP (p - 4, d);
5752 if (!cycle)
5753 /* If there's a cycle, just continue without pushing
5754 this failure point. The failure point is the "try again"
5755 option, which shouldn't be tried.
5756 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5757 PUSH_FAILURE_POINT (p - 3, d);
5759 break;
5761 /* Simple loop detecting on_failure_jump: just check on the
5762 failure stack if the same spot was already hit earlier. */
5763 case on_failure_jump_loop:
5764 on_failure:
5765 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5766 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5767 mcnt, p + mcnt);
5769 int cycle = 0;
5770 CHECK_INFINITE_LOOP (p - 3, d);
5771 if (cycle)
5772 /* If there's a cycle, get out of the loop, as if the matching
5773 had failed. We used to just `goto fail' here, but that was
5774 aborting the search a bit too early: we want to keep the
5775 empty-loop-match and keep matching after the loop.
5776 We want (x?)*y\1z to match both xxyz and xxyxz. */
5777 p += mcnt;
5778 else
5779 PUSH_FAILURE_POINT (p - 3, d);
5781 break;
5784 /* Uses of on_failure_jump:
5786 Each alternative starts with an on_failure_jump that points
5787 to the beginning of the next alternative. Each alternative
5788 except the last ends with a jump that in effect jumps past
5789 the rest of the alternatives. (They really jump to the
5790 ending jump of the following alternative, because tensioning
5791 these jumps is a hassle.)
5793 Repeats start with an on_failure_jump that points past both
5794 the repetition text and either the following jump or
5795 pop_failure_jump back to this on_failure_jump. */
5796 case on_failure_jump:
5797 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5798 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5799 mcnt, p + mcnt);
5801 PUSH_FAILURE_POINT (p -3, d);
5802 break;
5804 /* This operation is used for greedy *.
5805 Compare the beginning of the repeat with what in the
5806 pattern follows its end. If we can establish that there
5807 is nothing that they would both match, i.e., that we
5808 would have to backtrack because of (as in, e.g., `a*a')
5809 then we can use a non-backtracking loop based on
5810 on_failure_keep_string_jump instead of on_failure_jump. */
5811 case on_failure_jump_smart:
5812 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5813 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5814 mcnt, p + mcnt);
5816 re_char *p1 = p; /* Next operation. */
5817 /* Here, we discard `const', making re_match non-reentrant. */
5818 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5819 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5821 p -= 3; /* Reset so that we will re-execute the
5822 instruction once it's been changed. */
5824 EXTRACT_NUMBER (mcnt, p2 - 2);
5826 /* Ensure this is a indeed the trivial kind of loop
5827 we are expecting. */
5828 assert (skip_one_char (p1) == p2 - 3);
5829 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5830 DEBUG_STATEMENT (debug += 2);
5831 if (mutually_exclusive_p (bufp, p1, p2))
5833 /* Use a fast `on_failure_keep_string_jump' loop. */
5834 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5835 *p3 = (unsigned char) on_failure_keep_string_jump;
5836 STORE_NUMBER (p2 - 2, mcnt + 3);
5838 else
5840 /* Default to a safe `on_failure_jump' loop. */
5841 DEBUG_PRINT (" smart default => slow loop.\n");
5842 *p3 = (unsigned char) on_failure_jump;
5844 DEBUG_STATEMENT (debug -= 2);
5846 break;
5848 /* Unconditionally jump (without popping any failure points). */
5849 case jump:
5850 unconditional_jump:
5851 IMMEDIATE_QUIT_CHECK;
5852 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5853 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5854 p += mcnt; /* Do the jump. */
5855 DEBUG_PRINT ("(to %p).\n", p);
5856 break;
5859 /* Have to succeed matching what follows at least n times.
5860 After that, handle like `on_failure_jump'. */
5861 case succeed_n:
5862 /* Signedness doesn't matter since we only compare MCNT to 0. */
5863 EXTRACT_NUMBER (mcnt, p + 2);
5864 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5866 /* Originally, mcnt is how many times we HAVE to succeed. */
5867 if (mcnt != 0)
5869 /* Here, we discard `const', making re_match non-reentrant. */
5870 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5871 mcnt--;
5872 p += 4;
5873 PUSH_NUMBER (p2, mcnt);
5875 else
5876 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5877 goto on_failure;
5878 break;
5880 case jump_n:
5881 /* Signedness doesn't matter since we only compare MCNT to 0. */
5882 EXTRACT_NUMBER (mcnt, p + 2);
5883 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5885 /* Originally, this is how many times we CAN jump. */
5886 if (mcnt != 0)
5888 /* Here, we discard `const', making re_match non-reentrant. */
5889 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5890 mcnt--;
5891 PUSH_NUMBER (p2, mcnt);
5892 goto unconditional_jump;
5894 /* If don't have to jump any more, skip over the rest of command. */
5895 else
5896 p += 4;
5897 break;
5899 case set_number_at:
5901 unsigned char *p2; /* Location of the counter. */
5902 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5904 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5905 /* Here, we discard `const', making re_match non-reentrant. */
5906 p2 = (unsigned char*) p + mcnt;
5907 /* Signedness doesn't matter since we only copy MCNT's bits. */
5908 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5909 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5910 PUSH_NUMBER (p2, mcnt);
5911 break;
5914 case wordbound:
5915 case notwordbound:
5917 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5918 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5920 /* We SUCCEED (or FAIL) in one of the following cases: */
5922 /* Case 1: D is at the beginning or the end of string. */
5923 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5924 not = !not;
5925 else
5927 /* C1 is the character before D, S1 is the syntax of C1, C2
5928 is the character at D, and S2 is the syntax of C2. */
5929 re_wchar_t c1, c2;
5930 int s1, s2;
5931 int dummy;
5932 #ifdef emacs
5933 ssize_t offset = PTR_TO_OFFSET (d - 1);
5934 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5935 UPDATE_SYNTAX_TABLE (charpos);
5936 #endif
5937 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5938 s1 = SYNTAX (c1);
5939 #ifdef emacs
5940 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5941 #endif
5942 PREFETCH_NOLIMIT ();
5943 GET_CHAR_AFTER (c2, d, dummy);
5944 s2 = SYNTAX (c2);
5946 if (/* Case 2: Only one of S1 and S2 is Sword. */
5947 ((s1 == Sword) != (s2 == Sword))
5948 /* Case 3: Both of S1 and S2 are Sword, and macro
5949 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5950 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5951 not = !not;
5953 if (not)
5954 break;
5955 else
5956 goto fail;
5959 case wordbeg:
5960 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5962 /* We FAIL in one of the following cases: */
5964 /* Case 1: D is at the end of string. */
5965 if (AT_STRINGS_END (d))
5966 goto fail;
5967 else
5969 /* C1 is the character before D, S1 is the syntax of C1, C2
5970 is the character at D, and S2 is the syntax of C2. */
5971 re_wchar_t c1, c2;
5972 int s1, s2;
5973 int dummy;
5974 #ifdef emacs
5975 ssize_t offset = PTR_TO_OFFSET (d);
5976 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5977 UPDATE_SYNTAX_TABLE (charpos);
5978 #endif
5979 PREFETCH ();
5980 GET_CHAR_AFTER (c2, d, dummy);
5981 s2 = SYNTAX (c2);
5983 /* Case 2: S2 is not Sword. */
5984 if (s2 != Sword)
5985 goto fail;
5987 /* Case 3: D is not at the beginning of string ... */
5988 if (!AT_STRINGS_BEG (d))
5990 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5991 #ifdef emacs
5992 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5993 #endif
5994 s1 = SYNTAX (c1);
5996 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5997 returns 0. */
5998 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5999 goto fail;
6002 break;
6004 case wordend:
6005 DEBUG_PRINT ("EXECUTING wordend.\n");
6007 /* We FAIL in one of the following cases: */
6009 /* Case 1: D is at the beginning of string. */
6010 if (AT_STRINGS_BEG (d))
6011 goto fail;
6012 else
6014 /* C1 is the character before D, S1 is the syntax of C1, C2
6015 is the character at D, and S2 is the syntax of C2. */
6016 re_wchar_t c1, c2;
6017 int s1, s2;
6018 int dummy;
6019 #ifdef emacs
6020 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6021 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6022 UPDATE_SYNTAX_TABLE (charpos);
6023 #endif
6024 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6025 s1 = SYNTAX (c1);
6027 /* Case 2: S1 is not Sword. */
6028 if (s1 != Sword)
6029 goto fail;
6031 /* Case 3: D is not at the end of string ... */
6032 if (!AT_STRINGS_END (d))
6034 PREFETCH_NOLIMIT ();
6035 GET_CHAR_AFTER (c2, d, dummy);
6036 #ifdef emacs
6037 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
6038 #endif
6039 s2 = SYNTAX (c2);
6041 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6042 returns 0. */
6043 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6044 goto fail;
6047 break;
6049 case symbeg:
6050 DEBUG_PRINT ("EXECUTING symbeg.\n");
6052 /* We FAIL in one of the following cases: */
6054 /* Case 1: D is at the end of string. */
6055 if (AT_STRINGS_END (d))
6056 goto fail;
6057 else
6059 /* C1 is the character before D, S1 is the syntax of C1, C2
6060 is the character at D, and S2 is the syntax of C2. */
6061 re_wchar_t c1, c2;
6062 int s1, s2;
6063 #ifdef emacs
6064 ssize_t offset = PTR_TO_OFFSET (d);
6065 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6066 UPDATE_SYNTAX_TABLE (charpos);
6067 #endif
6068 PREFETCH ();
6069 c2 = RE_STRING_CHAR (d, target_multibyte);
6070 s2 = SYNTAX (c2);
6072 /* Case 2: S2 is neither Sword nor Ssymbol. */
6073 if (s2 != Sword && s2 != Ssymbol)
6074 goto fail;
6076 /* Case 3: D is not at the beginning of string ... */
6077 if (!AT_STRINGS_BEG (d))
6079 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6080 #ifdef emacs
6081 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6082 #endif
6083 s1 = SYNTAX (c1);
6085 /* ... and S1 is Sword or Ssymbol. */
6086 if (s1 == Sword || s1 == Ssymbol)
6087 goto fail;
6090 break;
6092 case symend:
6093 DEBUG_PRINT ("EXECUTING symend.\n");
6095 /* We FAIL in one of the following cases: */
6097 /* Case 1: D is at the beginning of string. */
6098 if (AT_STRINGS_BEG (d))
6099 goto fail;
6100 else
6102 /* C1 is the character before D, S1 is the syntax of C1, C2
6103 is the character at D, and S2 is the syntax of C2. */
6104 re_wchar_t c1, c2;
6105 int s1, s2;
6106 #ifdef emacs
6107 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6108 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6109 UPDATE_SYNTAX_TABLE (charpos);
6110 #endif
6111 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6112 s1 = SYNTAX (c1);
6114 /* Case 2: S1 is neither Ssymbol nor Sword. */
6115 if (s1 != Sword && s1 != Ssymbol)
6116 goto fail;
6118 /* Case 3: D is not at the end of string ... */
6119 if (!AT_STRINGS_END (d))
6121 PREFETCH_NOLIMIT ();
6122 c2 = RE_STRING_CHAR (d, target_multibyte);
6123 #ifdef emacs
6124 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6125 #endif
6126 s2 = SYNTAX (c2);
6128 /* ... and S2 is Sword or Ssymbol. */
6129 if (s2 == Sword || s2 == Ssymbol)
6130 goto fail;
6133 break;
6135 case syntaxspec:
6136 case notsyntaxspec:
6138 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6139 mcnt = *p++;
6140 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6141 mcnt);
6142 PREFETCH ();
6143 #ifdef emacs
6145 ssize_t offset = PTR_TO_OFFSET (d);
6146 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6147 UPDATE_SYNTAX_TABLE (pos1);
6149 #endif
6151 int len;
6152 re_wchar_t c;
6154 GET_CHAR_AFTER (c, d, len);
6155 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6156 goto fail;
6157 d += len;
6160 break;
6162 #ifdef emacs
6163 case before_dot:
6164 DEBUG_PRINT ("EXECUTING before_dot.\n");
6165 if (PTR_BYTE_POS (d) >= PT_BYTE)
6166 goto fail;
6167 break;
6169 case at_dot:
6170 DEBUG_PRINT ("EXECUTING at_dot.\n");
6171 if (PTR_BYTE_POS (d) != PT_BYTE)
6172 goto fail;
6173 break;
6175 case after_dot:
6176 DEBUG_PRINT ("EXECUTING after_dot.\n");
6177 if (PTR_BYTE_POS (d) <= PT_BYTE)
6178 goto fail;
6179 break;
6181 case categoryspec:
6182 case notcategoryspec:
6184 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6185 mcnt = *p++;
6186 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6187 not ? "not" : "", mcnt);
6188 PREFETCH ();
6191 int len;
6192 re_wchar_t c;
6193 GET_CHAR_AFTER (c, d, len);
6194 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6195 goto fail;
6196 d += len;
6199 break;
6201 #endif /* emacs */
6203 default:
6204 abort ();
6206 continue; /* Successfully executed one pattern command; keep going. */
6209 /* We goto here if a matching operation fails. */
6210 fail:
6211 IMMEDIATE_QUIT_CHECK;
6212 if (!FAIL_STACK_EMPTY ())
6214 re_char *str, *pat;
6215 /* A restart point is known. Restore to that state. */
6216 DEBUG_PRINT ("\nFAIL:\n");
6217 POP_FAILURE_POINT (str, pat);
6218 switch (*pat++)
6220 case on_failure_keep_string_jump:
6221 assert (str == NULL);
6222 goto continue_failure_jump;
6224 case on_failure_jump_nastyloop:
6225 assert ((re_opcode_t)pat[-2] == no_op);
6226 PUSH_FAILURE_POINT (pat - 2, str);
6227 /* Fallthrough */
6229 case on_failure_jump_loop:
6230 case on_failure_jump:
6231 case succeed_n:
6232 d = str;
6233 continue_failure_jump:
6234 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6235 p = pat + mcnt;
6236 break;
6238 case no_op:
6239 /* A special frame used for nastyloops. */
6240 goto fail;
6242 default:
6243 abort ();
6246 assert (p >= bufp->buffer && p <= pend);
6248 if (d >= string1 && d <= end1)
6249 dend = end_match_1;
6251 else
6252 break; /* Matching at this starting point really fails. */
6253 } /* for (;;) */
6255 if (best_regs_set)
6256 goto restore_best_regs;
6258 FREE_VARIABLES ();
6260 return -1; /* Failure to match. */
6263 /* Subroutine definitions for re_match_2. */
6265 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6266 bytes; nonzero otherwise. */
6268 static int
6269 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6270 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6272 register re_char *p1 = s1, *p2 = s2;
6273 re_char *p1_end = s1 + len;
6274 re_char *p2_end = s2 + len;
6276 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6277 different lengths, but relying on a single `len' would break this. -sm */
6278 while (p1 < p1_end && p2 < p2_end)
6280 int p1_charlen, p2_charlen;
6281 re_wchar_t p1_ch, p2_ch;
6283 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6284 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6286 if (RE_TRANSLATE (translate, p1_ch)
6287 != RE_TRANSLATE (translate, p2_ch))
6288 return 1;
6290 p1 += p1_charlen, p2 += p2_charlen;
6293 if (p1 != p1_end || p2 != p2_end)
6294 return 1;
6296 return 0;
6299 /* Entry points for GNU code. */
6301 /* re_compile_pattern is the GNU regular expression compiler: it
6302 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6303 Returns 0 if the pattern was valid, otherwise an error string.
6305 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6306 are set in BUFP on entry.
6308 We call regex_compile to do the actual compilation. */
6310 const char *
6311 re_compile_pattern (const char *pattern, size_t length,
6312 struct re_pattern_buffer *bufp)
6314 reg_errcode_t ret;
6316 /* GNU code is written to assume at least RE_NREGS registers will be set
6317 (and at least one extra will be -1). */
6318 bufp->regs_allocated = REGS_UNALLOCATED;
6320 /* And GNU code determines whether or not to get register information
6321 by passing null for the REGS argument to re_match, etc., not by
6322 setting no_sub. */
6323 bufp->no_sub = 0;
6325 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
6327 if (!ret)
6328 return NULL;
6329 return gettext (re_error_msgid[(int) ret]);
6331 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6333 /* Entry points compatible with 4.2 BSD regex library. We don't define
6334 them unless specifically requested. */
6336 #if defined _REGEX_RE_COMP || defined _LIBC
6338 /* BSD has one and only one pattern buffer. */
6339 static struct re_pattern_buffer re_comp_buf;
6341 char *
6342 # ifdef _LIBC
6343 /* Make these definitions weak in libc, so POSIX programs can redefine
6344 these names if they don't use our functions, and still use
6345 regcomp/regexec below without link errors. */
6346 weak_function
6347 # endif
6348 re_comp (const char *s)
6350 reg_errcode_t ret;
6352 if (!s)
6354 if (!re_comp_buf.buffer)
6355 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6356 return (char *) gettext ("No previous regular expression");
6357 return 0;
6360 if (!re_comp_buf.buffer)
6362 re_comp_buf.buffer = malloc (200);
6363 if (re_comp_buf.buffer == NULL)
6364 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6365 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6366 re_comp_buf.allocated = 200;
6368 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6369 if (re_comp_buf.fastmap == NULL)
6370 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6371 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6374 /* Since `re_exec' always passes NULL for the `regs' argument, we
6375 don't need to initialize the pattern buffer fields which affect it. */
6377 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6379 if (!ret)
6380 return NULL;
6382 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6383 return (char *) gettext (re_error_msgid[(int) ret]);
6388 # ifdef _LIBC
6389 weak_function
6390 # endif
6391 re_exec (const char *s)
6393 const size_t len = strlen (s);
6394 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6396 #endif /* _REGEX_RE_COMP */
6398 /* POSIX.2 functions. Don't define these for Emacs. */
6400 #ifndef emacs
6402 /* regcomp takes a regular expression as a string and compiles it.
6404 PREG is a regex_t *. We do not expect any fields to be initialized,
6405 since POSIX says we shouldn't. Thus, we set
6407 `buffer' to the compiled pattern;
6408 `used' to the length of the compiled pattern;
6409 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6410 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6411 RE_SYNTAX_POSIX_BASIC;
6412 `fastmap' to an allocated space for the fastmap;
6413 `fastmap_accurate' to zero;
6414 `re_nsub' to the number of subexpressions in PATTERN.
6416 PATTERN is the address of the pattern string.
6418 CFLAGS is a series of bits which affect compilation.
6420 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6421 use POSIX basic syntax.
6423 If REG_NEWLINE is set, then . and [^...] don't match newline.
6424 Also, regexec will try a match beginning after every newline.
6426 If REG_ICASE is set, then we considers upper- and lowercase
6427 versions of letters to be equivalent when matching.
6429 If REG_NOSUB is set, then when PREG is passed to regexec, that
6430 routine will report only success or failure, and nothing about the
6431 registers.
6433 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6434 the return codes and their meanings.) */
6436 reg_errcode_t
6437 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6438 int cflags)
6440 reg_errcode_t ret;
6441 reg_syntax_t syntax
6442 = (cflags & REG_EXTENDED) ?
6443 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6445 /* regex_compile will allocate the space for the compiled pattern. */
6446 preg->buffer = 0;
6447 preg->allocated = 0;
6448 preg->used = 0;
6450 /* Try to allocate space for the fastmap. */
6451 preg->fastmap = malloc (1 << BYTEWIDTH);
6453 if (cflags & REG_ICASE)
6455 unsigned i;
6457 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6458 if (preg->translate == NULL)
6459 return (int) REG_ESPACE;
6461 /* Map uppercase characters to corresponding lowercase ones. */
6462 for (i = 0; i < CHAR_SET_SIZE; i++)
6463 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6465 else
6466 preg->translate = NULL;
6468 /* If REG_NEWLINE is set, newlines are treated differently. */
6469 if (cflags & REG_NEWLINE)
6470 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6471 syntax &= ~RE_DOT_NEWLINE;
6472 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6474 else
6475 syntax |= RE_NO_NEWLINE_ANCHOR;
6477 preg->no_sub = !!(cflags & REG_NOSUB);
6479 /* POSIX says a null character in the pattern terminates it, so we
6480 can use strlen here in compiling the pattern. */
6481 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6483 /* POSIX doesn't distinguish between an unmatched open-group and an
6484 unmatched close-group: both are REG_EPAREN. */
6485 if (ret == REG_ERPAREN)
6486 ret = REG_EPAREN;
6488 if (ret == REG_NOERROR && preg->fastmap)
6489 { /* Compute the fastmap now, since regexec cannot modify the pattern
6490 buffer. */
6491 re_compile_fastmap (preg);
6492 if (preg->can_be_null)
6493 { /* The fastmap can't be used anyway. */
6494 free (preg->fastmap);
6495 preg->fastmap = NULL;
6498 return ret;
6500 WEAK_ALIAS (__regcomp, regcomp)
6503 /* regexec searches for a given pattern, specified by PREG, in the
6504 string STRING.
6506 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6507 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6508 least NMATCH elements, and we set them to the offsets of the
6509 corresponding matched substrings.
6511 EFLAGS specifies `execution flags' which affect matching: if
6512 REG_NOTBOL is set, then ^ does not match at the beginning of the
6513 string; if REG_NOTEOL is set, then $ does not match at the end.
6515 We return 0 if we find a match and REG_NOMATCH if not. */
6517 reg_errcode_t
6518 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6519 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6521 regoff_t ret;
6522 struct re_registers regs;
6523 regex_t private_preg;
6524 size_t len = strlen (string);
6525 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6527 private_preg = *preg;
6529 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6530 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6532 /* The user has told us exactly how many registers to return
6533 information about, via `nmatch'. We have to pass that on to the
6534 matching routines. */
6535 private_preg.regs_allocated = REGS_FIXED;
6537 if (want_reg_info)
6539 regs.num_regs = nmatch;
6540 regs.start = TALLOC (nmatch * 2, regoff_t);
6541 if (regs.start == NULL)
6542 return REG_NOMATCH;
6543 regs.end = regs.start + nmatch;
6546 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6547 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6548 was a little bit longer but still only matching the real part.
6549 This works because the `endline' will check for a '\n' and will find a
6550 '\0', correctly deciding that this is not the end of a line.
6551 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6552 a convenient '\0' there. For all we know, the string could be preceded
6553 by '\n' which would throw things off. */
6555 /* Perform the searching operation. */
6556 ret = re_search (&private_preg, string, len,
6557 /* start: */ 0, /* range: */ len,
6558 want_reg_info ? &regs : 0);
6560 /* Copy the register information to the POSIX structure. */
6561 if (want_reg_info)
6563 if (ret >= 0)
6565 unsigned r;
6567 for (r = 0; r < nmatch; r++)
6569 pmatch[r].rm_so = regs.start[r];
6570 pmatch[r].rm_eo = regs.end[r];
6574 /* If we needed the temporary register info, free the space now. */
6575 free (regs.start);
6578 /* We want zero return to mean success, unlike `re_search'. */
6579 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6581 WEAK_ALIAS (__regexec, regexec)
6584 /* Returns a message corresponding to an error code, ERR_CODE, returned
6585 from either regcomp or regexec. We don't use PREG here.
6587 ERR_CODE was previously called ERRCODE, but that name causes an
6588 error with msvc8 compiler. */
6590 size_t
6591 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6593 const char *msg;
6594 size_t msg_size;
6596 if (err_code < 0
6597 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6598 /* Only error codes returned by the rest of the code should be passed
6599 to this routine. If we are given anything else, or if other regex
6600 code generates an invalid error code, then the program has a bug.
6601 Dump core so we can fix it. */
6602 abort ();
6604 msg = gettext (re_error_msgid[err_code]);
6606 msg_size = strlen (msg) + 1; /* Includes the null. */
6608 if (errbuf_size != 0)
6610 if (msg_size > errbuf_size)
6612 memcpy (errbuf, msg, errbuf_size - 1);
6613 errbuf[errbuf_size - 1] = 0;
6615 else
6616 strcpy (errbuf, msg);
6619 return msg_size;
6621 WEAK_ALIAS (__regerror, regerror)
6624 /* Free dynamically allocated space used by PREG. */
6626 void
6627 regfree (regex_t *preg)
6629 free (preg->buffer);
6630 preg->buffer = NULL;
6632 preg->allocated = 0;
6633 preg->used = 0;
6635 free (preg->fastmap);
6636 preg->fastmap = NULL;
6637 preg->fastmap_accurate = 0;
6639 free (preg->translate);
6640 preg->translate = NULL;
6642 WEAK_ALIAS (__regfree, regfree)
6644 #endif /* not emacs */