Merge from gnulib
[emacs.git] / src / regex.c
blobdb3f0c16a2d4080e9eb1a8639e6646806f7d7392
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-2017 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>
53 #include <stdlib.h>
55 #ifdef emacs
56 /* We need this for `regex.h', and perhaps for the Emacs include files. */
57 # include <sys/types.h>
58 #endif
60 /* Whether to use ISO C Amendment 1 wide char functions.
61 Those should not be used for Emacs since it uses its own. */
62 #if defined _LIBC
63 #define WIDE_CHAR_SUPPORT 1
64 #else
65 #define WIDE_CHAR_SUPPORT \
66 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
67 #endif
69 /* For platform which support the ISO C amendment 1 functionality we
70 support user defined character classes. */
71 #if WIDE_CHAR_SUPPORT
72 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
73 # include <wchar.h>
74 # include <wctype.h>
75 #endif
77 #ifdef _LIBC
78 /* We have to keep the namespace clean. */
79 # define regfree(preg) __regfree (preg)
80 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
81 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
82 # define regerror(err_code, preg, errbuf, errbuf_size) \
83 __regerror (err_code, preg, errbuf, errbuf_size)
84 # define re_set_registers(bu, re, nu, st, en) \
85 __re_set_registers (bu, re, nu, st, en)
86 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
87 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
88 # define re_match(bufp, string, size, pos, regs) \
89 __re_match (bufp, string, size, pos, regs)
90 # define re_search(bufp, string, size, startpos, range, regs) \
91 __re_search (bufp, string, size, startpos, range, regs)
92 # define re_compile_pattern(pattern, length, bufp) \
93 __re_compile_pattern (pattern, length, bufp)
94 # define re_set_syntax(syntax) __re_set_syntax (syntax)
95 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
96 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
97 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
99 /* Make sure we call libc's function even if the user overrides them. */
100 # define btowc __btowc
101 # define iswctype __iswctype
102 # define wctype __wctype
104 # define WEAK_ALIAS(a,b) weak_alias (a, b)
106 /* We are also using some library internals. */
107 # include <locale/localeinfo.h>
108 # include <locale/elem-hash.h>
109 # include <langinfo.h>
110 #else
111 # define WEAK_ALIAS(a,b)
112 #endif
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
117 #else
118 # define gettext(msgid) (msgid)
119 #endif
121 #ifndef gettext_noop
122 /* This define is so xgettext can find the internationalizable
123 strings. */
124 # define gettext_noop(String) String
125 #endif
127 /* The `emacs' switch turns on certain matching commands
128 that make sense only in Emacs. */
129 #ifdef emacs
131 # include "lisp.h"
132 # include "character.h"
133 # include "buffer.h"
135 # include "syntax.h"
136 # include "category.h"
138 /* Make syntax table lookup grant data in gl_state. */
139 # define SYNTAX(c) syntax_property (c, 1)
141 # ifdef malloc
142 # undef malloc
143 # endif
144 # define malloc xmalloc
145 # ifdef realloc
146 # undef realloc
147 # endif
148 # define realloc xrealloc
149 # ifdef free
150 # undef free
151 # endif
152 # define free xfree
154 /* Converts the pointer to the char to BEG-based offset from the start. */
155 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
156 /* Strings are 0-indexed, buffers are 1-indexed; we pun on the boolean
157 result to get the right base index. */
158 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
160 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
161 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
162 # define RE_STRING_CHAR(p, multibyte) \
163 (multibyte ? (STRING_CHAR (p)) : (*(p)))
164 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
165 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
167 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
169 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
171 /* Set C a (possibly converted to multibyte) character before P. P
172 points into a string which is the virtual concatenation of STR1
173 (which ends at END1) or STR2 (which ends at END2). */
174 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
175 do { \
176 if (target_multibyte) \
178 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
179 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
180 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
181 c = STRING_CHAR (dtemp); \
183 else \
185 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
188 } while (0)
190 /* Set C a (possibly converted to multibyte) character at P, and set
191 LEN to the byte length of that character. */
192 # define GET_CHAR_AFTER(c, p, len) \
193 do { \
194 if (target_multibyte) \
195 (c) = STRING_CHAR_AND_LENGTH (p, len); \
196 else \
198 (c) = *p; \
199 len = 1; \
200 (c) = RE_CHAR_TO_MULTIBYTE (c); \
202 } while (0)
204 #else /* not emacs */
206 /* If we are not linking with Emacs proper,
207 we can't use the relocating allocator
208 even if config.h says that we can. */
209 # undef REL_ALLOC
211 # include <unistd.h>
213 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
215 static void *
216 xmalloc (size_t size)
218 void *val = malloc (size);
219 if (!val && size)
221 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
222 exit (1);
224 return val;
227 static void *
228 xrealloc (void *block, size_t size)
230 void *val;
231 /* We must call malloc explicitly when BLOCK is 0, since some
232 reallocs don't do this. */
233 if (! block)
234 val = malloc (size);
235 else
236 val = realloc (block, size);
237 if (!val && size)
239 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
240 exit (1);
242 return val;
245 # ifdef malloc
246 # undef malloc
247 # endif
248 # define malloc xmalloc
249 # ifdef realloc
250 # undef realloc
251 # endif
252 # define realloc xrealloc
254 # include <stdbool.h>
255 # include <string.h>
257 /* Define the syntax stuff for \<, \>, etc. */
259 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
260 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
262 /* Dummy macros for non-Emacs environments. */
263 # define MAX_MULTIBYTE_LENGTH 1
264 # define RE_MULTIBYTE_P(x) 0
265 # define RE_TARGET_MULTIBYTE_P(x) 0
266 # define WORD_BOUNDARY_P(c1, c2) (0)
267 # define BYTES_BY_CHAR_HEAD(p) (1)
268 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
269 # define STRING_CHAR(p) (*(p))
270 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
271 # define CHAR_STRING(c, s) (*(s) = (c), 1)
272 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
273 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
274 # define RE_CHAR_TO_MULTIBYTE(c) (c)
275 # define RE_CHAR_TO_UNIBYTE(c) (c)
276 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
277 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
278 # define GET_CHAR_AFTER(c, p, len) \
279 (c = *p, len = 1)
280 # define CHAR_BYTE8_P(c) (0)
281 # define CHAR_LEADING_CODE(c) (c)
283 #endif /* not emacs */
285 #ifndef RE_TRANSLATE
286 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
287 # define RE_TRANSLATE_P(TBL) (TBL)
288 #endif
290 /* Get the interface, including the syntax bits. */
291 #include "regex.h"
293 /* isalpha etc. are used for the character classes. */
294 #include <ctype.h>
296 #ifdef emacs
298 /* 1 if C is an ASCII character. */
299 # define IS_REAL_ASCII(c) ((c) < 0200)
301 /* 1 if C is a unibyte character. */
302 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
304 /* The Emacs definitions should not be directly affected by locales. */
306 /* In Emacs, these are only used for single-byte characters. */
307 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
308 # define ISCNTRL(c) ((c) < ' ')
309 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
310 || ((c) >= 'a' && (c) <= 'f') \
311 || ((c) >= 'A' && (c) <= 'F'))
313 /* The rest must handle multibyte characters. */
315 # define ISBLANK(c) (IS_REAL_ASCII (c) \
316 ? ((c) == ' ' || (c) == '\t') \
317 : blankp (c))
319 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
320 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0240) \
321 : graphicp (c))
323 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
324 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
325 : printablep (c))
327 # define ISALNUM(c) (IS_REAL_ASCII (c) \
328 ? (((c) >= 'a' && (c) <= 'z') \
329 || ((c) >= 'A' && (c) <= 'Z') \
330 || ((c) >= '0' && (c) <= '9')) \
331 : alphanumericp (c))
333 # define ISALPHA(c) (IS_REAL_ASCII (c) \
334 ? (((c) >= 'a' && (c) <= 'z') \
335 || ((c) >= 'A' && (c) <= 'Z')) \
336 : alphabeticp (c))
338 # define ISLOWER(c) lowercasep (c)
340 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
341 ? ((c) > ' ' && (c) < 0177 \
342 && !(((c) >= 'a' && (c) <= 'z') \
343 || ((c) >= 'A' && (c) <= 'Z') \
344 || ((c) >= '0' && (c) <= '9'))) \
345 : SYNTAX (c) != Sword)
347 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
349 # define ISUPPER(c) uppercasep (c)
351 # define ISWORD(c) (SYNTAX (c) == Sword)
353 #else /* not emacs */
355 /* 1 if C is an ASCII character. */
356 # define IS_REAL_ASCII(c) ((c) < 0200)
358 /* This distinction is not meaningful, except in Emacs. */
359 # define ISUNIBYTE(c) 1
361 # ifdef isblank
362 # define ISBLANK(c) isblank (c)
363 # else
364 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
365 # endif
366 # ifdef isgraph
367 # define ISGRAPH(c) isgraph (c)
368 # else
369 # define ISGRAPH(c) (isprint (c) && !isspace (c))
370 # endif
372 /* Solaris defines ISPRINT so we must undefine it first. */
373 # undef ISPRINT
374 # define ISPRINT(c) isprint (c)
375 # define ISDIGIT(c) isdigit (c)
376 # define ISALNUM(c) isalnum (c)
377 # define ISALPHA(c) isalpha (c)
378 # define ISCNTRL(c) iscntrl (c)
379 # define ISLOWER(c) islower (c)
380 # define ISPUNCT(c) ispunct (c)
381 # define ISSPACE(c) isspace (c)
382 # define ISUPPER(c) isupper (c)
383 # define ISXDIGIT(c) isxdigit (c)
385 # define ISWORD(c) ISALPHA (c)
387 # ifdef _tolower
388 # define TOLOWER(c) _tolower (c)
389 # else
390 # define TOLOWER(c) tolower (c)
391 # endif
393 /* How many characters in the character set. */
394 # define CHAR_SET_SIZE 256
396 # ifdef SYNTAX_TABLE
398 extern char *re_syntax_table;
400 # else /* not SYNTAX_TABLE */
402 static char re_syntax_table[CHAR_SET_SIZE];
404 static void
405 init_syntax_once (void)
407 register int c;
408 static int done = 0;
410 if (done)
411 return;
413 memset (re_syntax_table, 0, sizeof re_syntax_table);
415 for (c = 0; c < CHAR_SET_SIZE; ++c)
416 if (ISALNUM (c))
417 re_syntax_table[c] = Sword;
419 re_syntax_table['_'] = Ssymbol;
421 done = 1;
424 # endif /* not SYNTAX_TABLE */
426 # define SYNTAX(c) re_syntax_table[(c)]
428 #endif /* not emacs */
430 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
432 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
433 use `alloca' instead of `malloc'. This is because using malloc in
434 re_search* or re_match* could cause memory leaks when C-g is used
435 in Emacs (note that SAFE_ALLOCA could also call malloc, but does so
436 via `record_xmalloc' which uses `unwind_protect' to ensure the
437 memory is freed even in case of non-local exits); also, malloc is
438 slower and causes storage fragmentation. On the other hand, malloc
439 is more portable, and easier to debug.
441 Because we sometimes use alloca, some routines have to be macros,
442 not functions -- `alloca'-allocated space disappears at the end of the
443 function it is called in. */
445 #ifdef REGEX_MALLOC
447 # define REGEX_ALLOCATE malloc
448 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
449 # define REGEX_FREE free
451 #else /* not REGEX_MALLOC */
453 # ifdef emacs
454 /* This may be adjusted in main(), if the stack is successfully grown. */
455 ptrdiff_t emacs_re_safe_alloca = MAX_ALLOCA;
456 /* Like USE_SAFE_ALLOCA, but use emacs_re_safe_alloca. */
457 # define REGEX_USE_SAFE_ALLOCA \
458 ptrdiff_t sa_avail = emacs_re_safe_alloca; \
459 ptrdiff_t sa_count = SPECPDL_INDEX (); bool sa_must_free = false
461 # define REGEX_SAFE_FREE() SAFE_FREE ()
462 # define REGEX_ALLOCATE SAFE_ALLOCA
463 # else
464 # include <alloca.h>
465 # define REGEX_ALLOCATE alloca
466 # endif
468 /* Assumes a `char *destination' variable. */
469 # define REGEX_REALLOCATE(source, osize, nsize) \
470 (destination = REGEX_ALLOCATE (nsize), \
471 memcpy (destination, source, osize))
473 /* No need to do anything to free, after alloca. */
474 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
476 #endif /* not REGEX_MALLOC */
478 #ifndef REGEX_USE_SAFE_ALLOCA
479 # define REGEX_USE_SAFE_ALLOCA ((void) 0)
480 # define REGEX_SAFE_FREE() ((void) 0)
481 #endif
483 /* Define how to allocate the failure stack. */
485 #if defined REL_ALLOC && defined REGEX_MALLOC
487 # define REGEX_ALLOCATE_STACK(size) \
488 r_alloc (&failure_stack_ptr, (size))
489 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
490 r_re_alloc (&failure_stack_ptr, (nsize))
491 # define REGEX_FREE_STACK(ptr) \
492 r_alloc_free (&failure_stack_ptr)
494 #else /* not using relocating allocator */
496 # define REGEX_ALLOCATE_STACK(size) REGEX_ALLOCATE (size)
497 # define REGEX_REALLOCATE_STACK(source, o, n) REGEX_REALLOCATE (source, o, n)
498 # define REGEX_FREE_STACK(ptr) REGEX_FREE (ptr)
500 #endif /* not using relocating allocator */
503 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
504 `string1' or just past its end. This works if PTR is NULL, which is
505 a good thing. */
506 #define FIRST_STRING_P(ptr) \
507 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
509 /* (Re)Allocate N items of type T using malloc, or fail. */
510 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
511 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
512 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
514 #define BYTEWIDTH 8 /* In bits. */
516 #ifndef emacs
517 # undef max
518 # undef min
519 # define max(a, b) ((a) > (b) ? (a) : (b))
520 # define min(a, b) ((a) < (b) ? (a) : (b))
521 #endif
523 /* Type of source-pattern and string chars. */
524 #ifdef _MSC_VER
525 typedef unsigned char re_char;
526 typedef const re_char const_re_char;
527 #else
528 typedef const unsigned char re_char;
529 typedef re_char const_re_char;
530 #endif
532 typedef char boolean;
534 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
535 re_char *string1, size_t size1,
536 re_char *string2, size_t size2,
537 ssize_t pos,
538 struct re_registers *regs,
539 ssize_t stop);
541 /* These are the command codes that appear in compiled regular
542 expressions. Some opcodes are followed by argument bytes. A
543 command code can specify any interpretation whatsoever for its
544 arguments. Zero bytes may appear in the compiled regular expression. */
546 typedef enum
548 no_op = 0,
550 /* Succeed right away--no more backtracking. */
551 succeed,
553 /* Followed by one byte giving n, then by n literal bytes. */
554 exactn,
556 /* Matches any (more or less) character. */
557 anychar,
559 /* Matches any one char belonging to specified set. First
560 following byte is number of bitmap bytes. Then come bytes
561 for a bitmap saying which chars are in. Bits in each byte
562 are ordered low-bit-first. A character is in the set if its
563 bit is 1. A character too large to have a bit in the map is
564 automatically not in the set.
566 If the length byte has the 0x80 bit set, then that stuff
567 is followed by a range table:
568 2 bytes of flags for character sets (low 8 bits, high 8 bits)
569 See RANGE_TABLE_WORK_BITS below.
570 2 bytes, the number of pairs that follow (upto 32767)
571 pairs, each 2 multibyte characters,
572 each multibyte character represented as 3 bytes. */
573 charset,
575 /* Same parameters as charset, but match any character that is
576 not one of those specified. */
577 charset_not,
579 /* Start remembering the text that is matched, for storing in a
580 register. Followed by one byte with the register number, in
581 the range 0 to one less than the pattern buffer's re_nsub
582 field. */
583 start_memory,
585 /* Stop remembering the text that is matched and store it in a
586 memory register. Followed by one byte with the register
587 number, in the range 0 to one less than `re_nsub' in the
588 pattern buffer. */
589 stop_memory,
591 /* Match a duplicate of something remembered. Followed by one
592 byte containing the register number. */
593 duplicate,
595 /* Fail unless at beginning of line. */
596 begline,
598 /* Fail unless at end of line. */
599 endline,
601 /* Succeeds if at beginning of buffer (if emacs) or at beginning
602 of string to be matched (if not). */
603 begbuf,
605 /* Analogously, for end of buffer/string. */
606 endbuf,
608 /* Followed by two byte relative address to which to jump. */
609 jump,
611 /* Followed by two-byte relative address of place to resume at
612 in case of failure. */
613 on_failure_jump,
615 /* Like on_failure_jump, but pushes a placeholder instead of the
616 current string position when executed. */
617 on_failure_keep_string_jump,
619 /* Just like `on_failure_jump', except that it checks that we
620 don't get stuck in an infinite loop (matching an empty string
621 indefinitely). */
622 on_failure_jump_loop,
624 /* Just like `on_failure_jump_loop', except that it checks for
625 a different kind of loop (the kind that shows up with non-greedy
626 operators). This operation has to be immediately preceded
627 by a `no_op'. */
628 on_failure_jump_nastyloop,
630 /* A smart `on_failure_jump' used for greedy * and + operators.
631 It analyzes the loop before which it is put and if the
632 loop does not require backtracking, it changes itself to
633 `on_failure_keep_string_jump' and short-circuits the loop,
634 else it just defaults to changing itself into `on_failure_jump'.
635 It assumes that it is pointing to just past a `jump'. */
636 on_failure_jump_smart,
638 /* Followed by two-byte relative address and two-byte number n.
639 After matching N times, jump to the address upon failure.
640 Does not work if N starts at 0: use on_failure_jump_loop
641 instead. */
642 succeed_n,
644 /* Followed by two-byte relative address, and two-byte number n.
645 Jump to the address N times, then fail. */
646 jump_n,
648 /* Set the following two-byte relative address to the
649 subsequent two-byte number. The address *includes* the two
650 bytes of number. */
651 set_number_at,
653 wordbeg, /* Succeeds if at word beginning. */
654 wordend, /* Succeeds if at word end. */
656 wordbound, /* Succeeds if at a word boundary. */
657 notwordbound, /* Succeeds if not at a word boundary. */
659 symbeg, /* Succeeds if at symbol beginning. */
660 symend, /* Succeeds if at symbol end. */
662 /* Matches any character whose syntax is specified. Followed by
663 a byte which contains a syntax code, e.g., Sword. */
664 syntaxspec,
666 /* Matches any character whose syntax is not that specified. */
667 notsyntaxspec
669 #ifdef emacs
670 , at_dot, /* Succeeds if at point. */
672 /* Matches any character whose category-set contains the specified
673 category. The operator is followed by a byte which contains a
674 category code (mnemonic ASCII character). */
675 categoryspec,
677 /* Matches any character whose category-set does not contain the
678 specified category. The operator is followed by a byte which
679 contains the category code (mnemonic ASCII character). */
680 notcategoryspec
681 #endif /* emacs */
682 } re_opcode_t;
684 /* Common operations on the compiled pattern. */
686 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
688 #define STORE_NUMBER(destination, number) \
689 do { \
690 (destination)[0] = (number) & 0377; \
691 (destination)[1] = (number) >> 8; \
692 } while (0)
694 /* Same as STORE_NUMBER, except increment DESTINATION to
695 the byte after where the number is stored. Therefore, DESTINATION
696 must be an lvalue. */
698 #define STORE_NUMBER_AND_INCR(destination, number) \
699 do { \
700 STORE_NUMBER (destination, number); \
701 (destination) += 2; \
702 } while (0)
704 /* Put into DESTINATION a number stored in two contiguous bytes starting
705 at SOURCE. */
707 #define EXTRACT_NUMBER(destination, source) \
708 ((destination) = extract_number (source))
710 static int
711 extract_number (re_char *source)
713 unsigned leading_byte = SIGN_EXTEND_CHAR (source[1]);
714 return (leading_byte << 8) + source[0];
717 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
718 SOURCE must be an lvalue. */
720 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
721 ((destination) = extract_number_and_incr (&source))
723 static int
724 extract_number_and_incr (re_char **source)
726 int num = extract_number (*source);
727 *source += 2;
728 return num;
731 /* Store a multibyte character in three contiguous bytes starting
732 DESTINATION, and increment DESTINATION to the byte after where the
733 character is stored. Therefore, DESTINATION must be an lvalue. */
735 #define STORE_CHARACTER_AND_INCR(destination, character) \
736 do { \
737 (destination)[0] = (character) & 0377; \
738 (destination)[1] = ((character) >> 8) & 0377; \
739 (destination)[2] = (character) >> 16; \
740 (destination) += 3; \
741 } while (0)
743 /* Put into DESTINATION a character stored in three contiguous bytes
744 starting at SOURCE. */
746 #define EXTRACT_CHARACTER(destination, source) \
747 do { \
748 (destination) = ((source)[0] \
749 | ((source)[1] << 8) \
750 | ((source)[2] << 16)); \
751 } while (0)
754 /* Macros for charset. */
756 /* Size of bitmap of charset P in bytes. P is a start of charset,
757 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
758 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
760 /* Nonzero if charset P has range table. */
761 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
763 /* Return the address of range table of charset P. But not the start
764 of table itself, but the before where the number of ranges is
765 stored. `2 +' means to skip re_opcode_t and size of bitmap,
766 and the 2 bytes of flags at the start of the range table. */
767 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
769 #ifdef emacs
770 /* Extract the bit flags that start a range table. */
771 #define CHARSET_RANGE_TABLE_BITS(p) \
772 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
773 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
774 #endif
776 /* Return the address of end of RANGE_TABLE. COUNT is number of
777 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
778 is start of range and end of range. `* 3' is size of each start
779 and end. */
780 #define CHARSET_RANGE_TABLE_END(range_table, count) \
781 ((range_table) + (count) * 2 * 3)
783 /* If DEBUG is defined, Regex prints many voluminous messages about what
784 it is doing (if the variable `debug' is nonzero). If linked with the
785 main program in `iregex.c', you can enter patterns and strings
786 interactively. And if linked with the main program in `main.c' and
787 the other test files, you can run the already-written tests. */
789 #ifdef DEBUG
791 /* We use standard I/O for debugging. */
792 # include <stdio.h>
794 /* It is useful to test things that ``must'' be true when debugging. */
795 # include <assert.h>
797 static int debug = -100000;
799 # define DEBUG_STATEMENT(e) e
800 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
801 # define DEBUG_COMPILES_ARGUMENTS
802 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
803 if (debug > 0) print_partial_compiled_pattern (s, e)
804 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
805 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
808 /* Print the fastmap in human-readable form. */
810 static void
811 print_fastmap (char *fastmap)
813 unsigned was_a_range = 0;
814 unsigned i = 0;
816 while (i < (1 << BYTEWIDTH))
818 if (fastmap[i++])
820 was_a_range = 0;
821 putchar (i - 1);
822 while (i < (1 << BYTEWIDTH) && fastmap[i])
824 was_a_range = 1;
825 i++;
827 if (was_a_range)
829 printf ("-");
830 putchar (i - 1);
834 putchar ('\n');
838 /* Print a compiled pattern string in human-readable form, starting at
839 the START pointer into it and ending just before the pointer END. */
841 static void
842 print_partial_compiled_pattern (re_char *start, re_char *end)
844 int mcnt, mcnt2;
845 re_char *p = start;
846 re_char *pend = end;
848 if (start == NULL)
850 fprintf (stderr, "(null)\n");
851 return;
854 /* Loop over pattern commands. */
855 while (p < pend)
857 fprintf (stderr, "%td:\t", p - start);
859 switch ((re_opcode_t) *p++)
861 case no_op:
862 fprintf (stderr, "/no_op");
863 break;
865 case succeed:
866 fprintf (stderr, "/succeed");
867 break;
869 case exactn:
870 mcnt = *p++;
871 fprintf (stderr, "/exactn/%d", mcnt);
874 fprintf (stderr, "/%c", *p++);
876 while (--mcnt);
877 break;
879 case start_memory:
880 fprintf (stderr, "/start_memory/%d", *p++);
881 break;
883 case stop_memory:
884 fprintf (stderr, "/stop_memory/%d", *p++);
885 break;
887 case duplicate:
888 fprintf (stderr, "/duplicate/%d", *p++);
889 break;
891 case anychar:
892 fprintf (stderr, "/anychar");
893 break;
895 case charset:
896 case charset_not:
898 register int c, last = -100;
899 register int in_range = 0;
900 int length = CHARSET_BITMAP_SIZE (p - 1);
901 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
903 fprintf (stderr, "/charset [%s",
904 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
906 if (p + *p >= pend)
907 fprintf (stderr, " !extends past end of pattern! ");
909 for (c = 0; c < 256; c++)
910 if (c / 8 < length
911 && (p[1 + (c/8)] & (1 << (c % 8))))
913 /* Are we starting a range? */
914 if (last + 1 == c && ! in_range)
916 fprintf (stderr, "-");
917 in_range = 1;
919 /* Have we broken a range? */
920 else if (last + 1 != c && in_range)
922 fprintf (stderr, "%c", last);
923 in_range = 0;
926 if (! in_range)
927 fprintf (stderr, "%c", c);
929 last = c;
932 if (in_range)
933 fprintf (stderr, "%c", last);
935 fprintf (stderr, "]");
937 p += 1 + length;
939 if (has_range_table)
941 int count;
942 fprintf (stderr, "has-range-table");
944 /* ??? Should print the range table; for now, just skip it. */
945 p += 2; /* skip range table bits */
946 EXTRACT_NUMBER_AND_INCR (count, p);
947 p = CHARSET_RANGE_TABLE_END (p, count);
950 break;
952 case begline:
953 fprintf (stderr, "/begline");
954 break;
956 case endline:
957 fprintf (stderr, "/endline");
958 break;
960 case on_failure_jump:
961 EXTRACT_NUMBER_AND_INCR (mcnt, p);
962 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
963 break;
965 case on_failure_keep_string_jump:
966 EXTRACT_NUMBER_AND_INCR (mcnt, p);
967 fprintf (stderr, "/on_failure_keep_string_jump to %td",
968 p + mcnt - start);
969 break;
971 case on_failure_jump_nastyloop:
972 EXTRACT_NUMBER_AND_INCR (mcnt, p);
973 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
974 p + mcnt - start);
975 break;
977 case on_failure_jump_loop:
978 EXTRACT_NUMBER_AND_INCR (mcnt, p);
979 fprintf (stderr, "/on_failure_jump_loop to %td",
980 p + mcnt - start);
981 break;
983 case on_failure_jump_smart:
984 EXTRACT_NUMBER_AND_INCR (mcnt, p);
985 fprintf (stderr, "/on_failure_jump_smart to %td",
986 p + mcnt - start);
987 break;
989 case jump:
990 EXTRACT_NUMBER_AND_INCR (mcnt, p);
991 fprintf (stderr, "/jump to %td", p + mcnt - start);
992 break;
994 case succeed_n:
995 EXTRACT_NUMBER_AND_INCR (mcnt, p);
996 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
997 fprintf (stderr, "/succeed_n to %td, %d times",
998 p - 2 + mcnt - start, mcnt2);
999 break;
1001 case jump_n:
1002 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1003 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1004 fprintf (stderr, "/jump_n to %td, %d times",
1005 p - 2 + mcnt - start, mcnt2);
1006 break;
1008 case set_number_at:
1009 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1010 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1011 fprintf (stderr, "/set_number_at location %td to %d",
1012 p - 2 + mcnt - start, mcnt2);
1013 break;
1015 case wordbound:
1016 fprintf (stderr, "/wordbound");
1017 break;
1019 case notwordbound:
1020 fprintf (stderr, "/notwordbound");
1021 break;
1023 case wordbeg:
1024 fprintf (stderr, "/wordbeg");
1025 break;
1027 case wordend:
1028 fprintf (stderr, "/wordend");
1029 break;
1031 case symbeg:
1032 fprintf (stderr, "/symbeg");
1033 break;
1035 case symend:
1036 fprintf (stderr, "/symend");
1037 break;
1039 case syntaxspec:
1040 fprintf (stderr, "/syntaxspec");
1041 mcnt = *p++;
1042 fprintf (stderr, "/%d", mcnt);
1043 break;
1045 case notsyntaxspec:
1046 fprintf (stderr, "/notsyntaxspec");
1047 mcnt = *p++;
1048 fprintf (stderr, "/%d", mcnt);
1049 break;
1051 # ifdef emacs
1052 case at_dot:
1053 fprintf (stderr, "/at_dot");
1054 break;
1056 case categoryspec:
1057 fprintf (stderr, "/categoryspec");
1058 mcnt = *p++;
1059 fprintf (stderr, "/%d", mcnt);
1060 break;
1062 case notcategoryspec:
1063 fprintf (stderr, "/notcategoryspec");
1064 mcnt = *p++;
1065 fprintf (stderr, "/%d", mcnt);
1066 break;
1067 # endif /* emacs */
1069 case begbuf:
1070 fprintf (stderr, "/begbuf");
1071 break;
1073 case endbuf:
1074 fprintf (stderr, "/endbuf");
1075 break;
1077 default:
1078 fprintf (stderr, "?%d", *(p-1));
1081 fprintf (stderr, "\n");
1084 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1088 static void
1089 print_compiled_pattern (struct re_pattern_buffer *bufp)
1091 re_char *buffer = bufp->buffer;
1093 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1094 printf ("%ld bytes used/%ld bytes allocated.\n",
1095 bufp->used, bufp->allocated);
1097 if (bufp->fastmap_accurate && bufp->fastmap)
1099 printf ("fastmap: ");
1100 print_fastmap (bufp->fastmap);
1103 printf ("re_nsub: %zu\t", bufp->re_nsub);
1104 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1105 printf ("can_be_null: %d\t", bufp->can_be_null);
1106 printf ("no_sub: %d\t", bufp->no_sub);
1107 printf ("not_bol: %d\t", bufp->not_bol);
1108 printf ("not_eol: %d\t", bufp->not_eol);
1109 #ifndef emacs
1110 printf ("syntax: %lx\n", bufp->syntax);
1111 #endif
1112 fflush (stdout);
1113 /* Perhaps we should print the translate table? */
1117 static void
1118 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1119 re_char *string2, ssize_t size2)
1121 ssize_t this_char;
1123 if (where == NULL)
1124 printf ("(null)");
1125 else
1127 if (FIRST_STRING_P (where))
1129 for (this_char = where - string1; this_char < size1; this_char++)
1130 putchar (string1[this_char]);
1132 where = string2;
1135 for (this_char = where - string2; this_char < size2; this_char++)
1136 putchar (string2[this_char]);
1140 #else /* not DEBUG */
1142 # undef assert
1143 # define assert(e)
1145 # define DEBUG_STATEMENT(e)
1146 # define DEBUG_PRINT(...)
1147 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1148 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1150 #endif /* not DEBUG */
1152 #ifndef emacs
1154 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1155 also be assigned to arbitrarily: each pattern buffer stores its own
1156 syntax, so it can be changed between regex compilations. */
1157 /* This has no initializer because initialized variables in Emacs
1158 become read-only after dumping. */
1159 reg_syntax_t re_syntax_options;
1162 /* Specify the precise syntax of regexps for compilation. This provides
1163 for compatibility for various utilities which historically have
1164 different, incompatible syntaxes.
1166 The argument SYNTAX is a bit mask comprised of the various bits
1167 defined in regex.h. We return the old syntax. */
1169 reg_syntax_t
1170 re_set_syntax (reg_syntax_t syntax)
1172 reg_syntax_t ret = re_syntax_options;
1174 re_syntax_options = syntax;
1175 return ret;
1177 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1179 #endif
1181 /* This table gives an error message for each of the error codes listed
1182 in regex.h. Obviously the order here has to be same as there.
1183 POSIX doesn't require that we do anything for REG_NOERROR,
1184 but why not be nice? */
1186 static const char *re_error_msgid[] =
1188 gettext_noop ("Success"), /* REG_NOERROR */
1189 gettext_noop ("No match"), /* REG_NOMATCH */
1190 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1191 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1192 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1193 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1194 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1195 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1196 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1197 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1198 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1199 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1200 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1201 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1202 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1203 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1204 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1205 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1208 /* Whether to allocate memory during matching. */
1210 /* Define MATCH_MAY_ALLOCATE to allow the searching and matching
1211 functions allocate memory for the failure stack and registers.
1212 Normally should be defined, because otherwise searching and
1213 matching routines will have much smaller memory resources at their
1214 disposal, and therefore might fail to handle complex regexps.
1215 Therefore undefine MATCH_MAY_ALLOCATE only in the following
1216 exceptional situations:
1218 . When running on a system where memory is at premium.
1219 . When alloca cannot be used at all, perhaps due to bugs in
1220 its implementation, or its being unavailable, or due to a
1221 very small stack size. This requires to define REGEX_MALLOC
1222 to use malloc instead, which in turn could lead to memory
1223 leaks if search is interrupted by a signal. (For these
1224 reasons, defining REGEX_MALLOC when building Emacs
1225 automatically undefines MATCH_MAY_ALLOCATE, but outside
1226 Emacs you may not care about memory leaks.) If you want to
1227 prevent the memory leaks, undefine MATCH_MAY_ALLOCATE.
1228 . When code that calls the searching and matching functions
1229 cannot allow memory allocation, for whatever reasons. */
1231 /* Normally, this is fine. */
1232 #define MATCH_MAY_ALLOCATE
1234 /* The match routines may not allocate if (1) they would do it with malloc
1235 and (2) it's not safe for them to use malloc.
1236 Note that if REL_ALLOC is defined, matching would not use malloc for the
1237 failure stack, but we would still use it for the register vectors;
1238 so REL_ALLOC should not affect this. */
1239 #if defined REGEX_MALLOC && defined emacs
1240 # undef MATCH_MAY_ALLOCATE
1241 #endif
1244 /* Failure stack declarations and macros; both re_compile_fastmap and
1245 re_match_2 use a failure stack. These have to be macros because of
1246 REGEX_ALLOCATE_STACK. */
1249 /* Approximate number of failure points for which to initially allocate space
1250 when matching. If this number is exceeded, we allocate more
1251 space, so it is not a hard limit. */
1252 #ifndef INIT_FAILURE_ALLOC
1253 # define INIT_FAILURE_ALLOC 20
1254 #endif
1256 /* Roughly the maximum number of failure points on the stack. Would be
1257 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1258 This is a variable only so users of regex can assign to it; we never
1259 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1260 before using it, so it should probably be a byte-count instead. */
1261 # if defined MATCH_MAY_ALLOCATE
1262 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1263 whose default stack limit is 2mb. In order for a larger
1264 value to work reliably, you have to try to make it accord
1265 with the process stack limit. */
1266 size_t emacs_re_max_failures = 40000;
1267 # else
1268 size_t emacs_re_max_failures = 4000;
1269 # endif
1271 union fail_stack_elt
1273 re_char *pointer;
1274 /* This should be the biggest `int' that's no bigger than a pointer. */
1275 long integer;
1278 typedef union fail_stack_elt fail_stack_elt_t;
1280 typedef struct
1282 fail_stack_elt_t *stack;
1283 size_t size;
1284 size_t avail; /* Offset of next open position. */
1285 size_t frame; /* Offset of the cur constructed frame. */
1286 } fail_stack_type;
1288 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1291 /* Define macros to initialize and free the failure stack.
1292 Do `return -2' if the alloc fails. */
1294 #ifdef MATCH_MAY_ALLOCATE
1295 # define INIT_FAIL_STACK() \
1296 do { \
1297 fail_stack.stack = \
1298 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1299 * sizeof (fail_stack_elt_t)); \
1301 if (fail_stack.stack == NULL) \
1302 return -2; \
1304 fail_stack.size = INIT_FAILURE_ALLOC; \
1305 fail_stack.avail = 0; \
1306 fail_stack.frame = 0; \
1307 } while (0)
1308 #else
1309 # define INIT_FAIL_STACK() \
1310 do { \
1311 fail_stack.avail = 0; \
1312 fail_stack.frame = 0; \
1313 } while (0)
1315 # define RETALLOC_IF(addr, n, t) \
1316 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1317 #endif
1320 /* Double the size of FAIL_STACK, up to a limit
1321 which allows approximately `emacs_re_max_failures' items.
1323 Return 1 if succeeds, and 0 if either ran out of memory
1324 allocating space for it or it was already too large.
1326 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1328 /* Factor to increase the failure stack size by
1329 when we increase it.
1330 This used to be 2, but 2 was too wasteful
1331 because the old discarded stacks added up to as much space
1332 were as ultimate, maximum-size stack. */
1333 #define FAIL_STACK_GROWTH_FACTOR 4
1335 #define GROW_FAIL_STACK(fail_stack) \
1336 (((fail_stack).size >= emacs_re_max_failures * TYPICAL_FAILURE_SIZE) \
1337 ? 0 \
1338 : ((fail_stack).stack \
1339 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1340 (fail_stack).size * sizeof (fail_stack_elt_t), \
1341 min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1342 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR)) \
1343 * sizeof (fail_stack_elt_t)), \
1345 (fail_stack).stack == NULL \
1346 ? 0 \
1347 : ((fail_stack).size \
1348 = (min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1349 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR))), \
1350 1)))
1353 /* Push a pointer value onto the failure stack.
1354 Assumes the variable `fail_stack'. Probably should only
1355 be called from within `PUSH_FAILURE_POINT'. */
1356 #define PUSH_FAILURE_POINTER(item) \
1357 fail_stack.stack[fail_stack.avail++].pointer = (item)
1359 /* This pushes an integer-valued item onto the failure stack.
1360 Assumes the variable `fail_stack'. Probably should only
1361 be called from within `PUSH_FAILURE_POINT'. */
1362 #define PUSH_FAILURE_INT(item) \
1363 fail_stack.stack[fail_stack.avail++].integer = (item)
1365 /* These POP... operations complement the PUSH... operations.
1366 All assume that `fail_stack' is nonempty. */
1367 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1368 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1370 /* Individual items aside from the registers. */
1371 #define NUM_NONREG_ITEMS 3
1373 /* Used to examine the stack (to detect infinite loops). */
1374 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1375 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1376 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1377 #define TOP_FAILURE_HANDLE() fail_stack.frame
1380 #define ENSURE_FAIL_STACK(space) \
1381 while (REMAINING_AVAIL_SLOTS <= space) { \
1382 if (!GROW_FAIL_STACK (fail_stack)) \
1383 return -2; \
1384 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1385 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1388 /* Push register NUM onto the stack. */
1389 #define PUSH_FAILURE_REG(num) \
1390 do { \
1391 char *destination; \
1392 long n = num; \
1393 ENSURE_FAIL_STACK(3); \
1394 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1395 n, regstart[n], regend[n]); \
1396 PUSH_FAILURE_POINTER (regstart[n]); \
1397 PUSH_FAILURE_POINTER (regend[n]); \
1398 PUSH_FAILURE_INT (n); \
1399 } while (0)
1401 /* Change the counter's value to VAL, but make sure that it will
1402 be reset when backtracking. */
1403 #define PUSH_NUMBER(ptr,val) \
1404 do { \
1405 char *destination; \
1406 int c; \
1407 ENSURE_FAIL_STACK(3); \
1408 EXTRACT_NUMBER (c, ptr); \
1409 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1410 PUSH_FAILURE_INT (c); \
1411 PUSH_FAILURE_POINTER (ptr); \
1412 PUSH_FAILURE_INT (-1); \
1413 STORE_NUMBER (ptr, val); \
1414 } while (0)
1416 /* Pop a saved register off the stack. */
1417 #define POP_FAILURE_REG_OR_COUNT() \
1418 do { \
1419 long pfreg = POP_FAILURE_INT (); \
1420 if (pfreg == -1) \
1422 /* It's a counter. */ \
1423 /* Here, we discard `const', making re_match non-reentrant. */ \
1424 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1425 pfreg = POP_FAILURE_INT (); \
1426 STORE_NUMBER (ptr, pfreg); \
1427 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1429 else \
1431 regend[pfreg] = POP_FAILURE_POINTER (); \
1432 regstart[pfreg] = POP_FAILURE_POINTER (); \
1433 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1434 pfreg, regstart[pfreg], regend[pfreg]); \
1436 } while (0)
1438 /* Check that we are not stuck in an infinite loop. */
1439 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1440 do { \
1441 ssize_t failure = TOP_FAILURE_HANDLE (); \
1442 /* Check for infinite matching loops */ \
1443 while (failure > 0 \
1444 && (FAILURE_STR (failure) == string_place \
1445 || FAILURE_STR (failure) == NULL)) \
1447 assert (FAILURE_PAT (failure) >= bufp->buffer \
1448 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1449 if (FAILURE_PAT (failure) == pat_cur) \
1451 cycle = 1; \
1452 break; \
1454 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1455 failure = NEXT_FAILURE_HANDLE(failure); \
1457 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1458 } while (0)
1460 /* Push the information about the state we will need
1461 if we ever fail back to it.
1463 Requires variables fail_stack, regstart, regend and
1464 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1465 declared.
1467 Does `return FAILURE_CODE' if runs out of memory. */
1469 #define PUSH_FAILURE_POINT(pattern, string_place) \
1470 do { \
1471 char *destination; \
1472 /* Must be int, so when we don't save any registers, the arithmetic \
1473 of 0 + -1 isn't done as unsigned. */ \
1475 DEBUG_STATEMENT (nfailure_points_pushed++); \
1476 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1477 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1478 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1480 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1482 DEBUG_PRINT ("\n"); \
1484 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1485 PUSH_FAILURE_INT (fail_stack.frame); \
1487 DEBUG_PRINT (" Push string %p: \"", string_place); \
1488 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1489 DEBUG_PRINT ("\"\n"); \
1490 PUSH_FAILURE_POINTER (string_place); \
1492 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1493 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1494 PUSH_FAILURE_POINTER (pattern); \
1496 /* Close the frame by moving the frame pointer past it. */ \
1497 fail_stack.frame = fail_stack.avail; \
1498 } while (0)
1500 /* Estimate the size of data pushed by a typical failure stack entry.
1501 An estimate is all we need, because all we use this for
1502 is to choose a limit for how big to make the failure stack. */
1503 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1504 #define TYPICAL_FAILURE_SIZE 20
1506 /* How many items can still be added to the stack without overflowing it. */
1507 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1510 /* Pops what PUSH_FAIL_STACK pushes.
1512 We restore into the parameters, all of which should be lvalues:
1513 STR -- the saved data position.
1514 PAT -- the saved pattern position.
1515 REGSTART, REGEND -- arrays of string positions.
1517 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1518 `pend', `string1', `size1', `string2', and `size2'. */
1520 #define POP_FAILURE_POINT(str, pat) \
1521 do { \
1522 assert (!FAIL_STACK_EMPTY ()); \
1524 /* Remove failure points and point to how many regs pushed. */ \
1525 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1526 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1527 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1529 /* Pop the saved registers. */ \
1530 while (fail_stack.frame < fail_stack.avail) \
1531 POP_FAILURE_REG_OR_COUNT (); \
1533 pat = POP_FAILURE_POINTER (); \
1534 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1535 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1537 /* If the saved string location is NULL, it came from an \
1538 on_failure_keep_string_jump opcode, and we want to throw away the \
1539 saved NULL, thus retaining our current position in the string. */ \
1540 str = POP_FAILURE_POINTER (); \
1541 DEBUG_PRINT (" Popping string %p: \"", str); \
1542 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1543 DEBUG_PRINT ("\"\n"); \
1545 fail_stack.frame = POP_FAILURE_INT (); \
1546 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1548 assert (fail_stack.avail >= 0); \
1549 assert (fail_stack.frame <= fail_stack.avail); \
1551 DEBUG_STATEMENT (nfailure_points_popped++); \
1552 } while (0) /* POP_FAILURE_POINT */
1556 /* Registers are set to a sentinel when they haven't yet matched. */
1557 #define REG_UNSET(e) ((e) == NULL)
1559 /* Subroutine declarations and macros for regex_compile. */
1561 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1562 #ifdef emacs
1563 bool posix_backtracking,
1564 const char *whitespace_regexp,
1565 #else
1566 reg_syntax_t syntax,
1567 #endif
1568 struct re_pattern_buffer *bufp);
1569 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1570 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1571 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1572 int arg, unsigned char *end);
1573 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1574 int arg1, int arg2, unsigned char *end);
1575 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1576 reg_syntax_t syntax);
1577 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1578 reg_syntax_t syntax);
1579 static re_char *skip_one_char (re_char *p);
1580 static int analyze_first (re_char *p, re_char *pend,
1581 char *fastmap, const int multibyte);
1583 /* Fetch the next character in the uncompiled pattern, with no
1584 translation. */
1585 #define PATFETCH(c) \
1586 do { \
1587 int len; \
1588 if (p == pend) return REG_EEND; \
1589 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1590 p += len; \
1591 } while (0)
1594 /* If `translate' is non-null, return translate[D], else just D. We
1595 cast the subscript to translate because some data is declared as
1596 `char *', to avoid warnings when a string constant is passed. But
1597 when we use a character as a subscript we must make it unsigned. */
1598 #ifndef TRANSLATE
1599 # define TRANSLATE(d) \
1600 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1601 #endif
1604 /* Macros for outputting the compiled pattern into `buffer'. */
1606 /* If the buffer isn't allocated when it comes in, use this. */
1607 #define INIT_BUF_SIZE 32
1609 /* Make sure we have at least N more bytes of space in buffer. */
1610 #define GET_BUFFER_SPACE(n) \
1611 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1612 EXTEND_BUFFER ()
1614 /* Make sure we have one more byte of buffer space and then add C to it. */
1615 #define BUF_PUSH(c) \
1616 do { \
1617 GET_BUFFER_SPACE (1); \
1618 *b++ = (unsigned char) (c); \
1619 } while (0)
1622 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1623 #define BUF_PUSH_2(c1, c2) \
1624 do { \
1625 GET_BUFFER_SPACE (2); \
1626 *b++ = (unsigned char) (c1); \
1627 *b++ = (unsigned char) (c2); \
1628 } while (0)
1631 /* Store a jump with opcode OP at LOC to location TO. We store a
1632 relative address offset by the three bytes the jump itself occupies. */
1633 #define STORE_JUMP(op, loc, to) \
1634 store_op1 (op, loc, (to) - (loc) - 3)
1636 /* Likewise, for a two-argument jump. */
1637 #define STORE_JUMP2(op, loc, to, arg) \
1638 store_op2 (op, loc, (to) - (loc) - 3, arg)
1640 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1641 #define INSERT_JUMP(op, loc, to) \
1642 insert_op1 (op, loc, (to) - (loc) - 3, b)
1644 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1645 #define INSERT_JUMP2(op, loc, to, arg) \
1646 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1649 /* This is not an arbitrary limit: the arguments which represent offsets
1650 into the pattern are two bytes long. So if 2^15 bytes turns out to
1651 be too small, many things would have to change. */
1652 # define MAX_BUF_SIZE (1L << 15)
1654 /* Extend the buffer by twice its current size via realloc and
1655 reset the pointers that pointed into the old block to point to the
1656 correct places in the new one. If extending the buffer results in it
1657 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1658 #define EXTEND_BUFFER() \
1659 do { \
1660 unsigned char *old_buffer = bufp->buffer; \
1661 if (bufp->allocated == MAX_BUF_SIZE) \
1662 return REG_ESIZE; \
1663 bufp->allocated <<= 1; \
1664 if (bufp->allocated > MAX_BUF_SIZE) \
1665 bufp->allocated = MAX_BUF_SIZE; \
1666 ptrdiff_t b_off = b - old_buffer; \
1667 ptrdiff_t begalt_off = begalt - old_buffer; \
1668 bool fixup_alt_jump_set = !!fixup_alt_jump; \
1669 bool laststart_set = !!laststart; \
1670 bool pending_exact_set = !!pending_exact; \
1671 ptrdiff_t fixup_alt_jump_off, laststart_off, pending_exact_off; \
1672 if (fixup_alt_jump_set) fixup_alt_jump_off = fixup_alt_jump - old_buffer; \
1673 if (laststart_set) laststart_off = laststart - old_buffer; \
1674 if (pending_exact_set) pending_exact_off = pending_exact - old_buffer; \
1675 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1676 if (bufp->buffer == NULL) \
1677 return REG_ESPACE; \
1678 unsigned char *new_buffer = bufp->buffer; \
1679 b = new_buffer + b_off; \
1680 begalt = new_buffer + begalt_off; \
1681 if (fixup_alt_jump_set) fixup_alt_jump = new_buffer + fixup_alt_jump_off; \
1682 if (laststart_set) laststart = new_buffer + laststart_off; \
1683 if (pending_exact_set) pending_exact = new_buffer + pending_exact_off; \
1684 } while (0)
1687 /* Since we have one byte reserved for the register number argument to
1688 {start,stop}_memory, the maximum number of groups we can report
1689 things about is what fits in that byte. */
1690 #define MAX_REGNUM 255
1692 /* But patterns can have more than `MAX_REGNUM' registers. We just
1693 ignore the excess. */
1694 typedef int regnum_t;
1697 /* Macros for the compile stack. */
1699 /* Since offsets can go either forwards or backwards, this type needs to
1700 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1701 /* int may be not enough when sizeof(int) == 2. */
1702 typedef long pattern_offset_t;
1704 typedef struct
1706 pattern_offset_t begalt_offset;
1707 pattern_offset_t fixup_alt_jump;
1708 pattern_offset_t laststart_offset;
1709 regnum_t regnum;
1710 } compile_stack_elt_t;
1713 typedef struct
1715 compile_stack_elt_t *stack;
1716 size_t size;
1717 size_t avail; /* Offset of next open position. */
1718 } compile_stack_type;
1721 #define INIT_COMPILE_STACK_SIZE 32
1723 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1724 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1726 /* The next available element. */
1727 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1729 /* Explicit quit checking is needed for Emacs, which uses polling to
1730 process input events. */
1731 #ifdef emacs
1732 # define IMMEDIATE_QUIT_CHECK \
1733 do { \
1734 if (immediate_quit) QUIT; \
1735 } while (0)
1736 #else
1737 # define IMMEDIATE_QUIT_CHECK ((void)0)
1738 #endif
1740 /* Structure to manage work area for range table. */
1741 struct range_table_work_area
1743 int *table; /* actual work area. */
1744 int allocated; /* allocated size for work area in bytes. */
1745 int used; /* actually used size in words. */
1746 int bits; /* flag to record character classes */
1749 #ifdef emacs
1751 /* Make sure that WORK_AREA can hold more N multibyte characters.
1752 This is used only in set_image_of_range and set_image_of_range_1.
1753 It expects WORK_AREA to be a pointer.
1754 If it can't get the space, it returns from the surrounding function. */
1756 #define EXTEND_RANGE_TABLE(work_area, n) \
1757 do { \
1758 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1760 extend_range_table_work_area (&work_area); \
1761 if ((work_area).table == 0) \
1762 return (REG_ESPACE); \
1764 } while (0)
1766 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1767 (work_area).bits |= (bit)
1769 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1770 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1771 do { \
1772 EXTEND_RANGE_TABLE ((work_area), 2); \
1773 (work_area).table[(work_area).used++] = (range_start); \
1774 (work_area).table[(work_area).used++] = (range_end); \
1775 } while (0)
1777 #endif /* emacs */
1779 /* Free allocated memory for WORK_AREA. */
1780 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1781 do { \
1782 if ((work_area).table) \
1783 free ((work_area).table); \
1784 } while (0)
1786 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1787 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1788 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1789 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1791 /* Bits used to implement the multibyte-part of the various character classes
1792 such as [:alnum:] in a charset's range table. The code currently assumes
1793 that only the low 16 bits are used. */
1794 #define BIT_WORD 0x1
1795 #define BIT_LOWER 0x2
1796 #define BIT_PUNCT 0x4
1797 #define BIT_SPACE 0x8
1798 #define BIT_UPPER 0x10
1799 #define BIT_MULTIBYTE 0x20
1800 #define BIT_ALPHA 0x40
1801 #define BIT_ALNUM 0x80
1802 #define BIT_GRAPH 0x100
1803 #define BIT_PRINT 0x200
1804 #define BIT_BLANK 0x400
1807 /* Set the bit for character C in a list. */
1808 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1811 #ifdef emacs
1813 /* Store characters in the range FROM to TO in the bitmap at B (for
1814 ASCII and unibyte characters) and WORK_AREA (for multibyte
1815 characters) while translating them and paying attention to the
1816 continuity of translated characters.
1818 Implementation note: It is better to implement these fairly big
1819 macros by a function, but it's not that easy because macros called
1820 in this macro assume various local variables already declared. */
1822 /* Both FROM and TO are ASCII characters. */
1824 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1825 do { \
1826 int C0, C1; \
1828 for (C0 = (FROM); C0 <= (TO); C0++) \
1830 C1 = TRANSLATE (C0); \
1831 if (! ASCII_CHAR_P (C1)) \
1833 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1834 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1835 C1 = C0; \
1837 SET_LIST_BIT (C1); \
1839 } while (0)
1842 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1844 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1845 do { \
1846 int C0, C1, C2, I; \
1847 int USED = RANGE_TABLE_WORK_USED (work_area); \
1849 for (C0 = (FROM); C0 <= (TO); C0++) \
1851 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1852 if (CHAR_BYTE8_P (C1)) \
1853 SET_LIST_BIT (C0); \
1854 else \
1856 C2 = TRANSLATE (C1); \
1857 if (C2 == C1 \
1858 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1859 C1 = C0; \
1860 SET_LIST_BIT (C1); \
1861 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1863 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1864 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1866 if (C2 >= from - 1 && C2 <= to + 1) \
1868 if (C2 == from - 1) \
1869 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1870 else if (C2 == to + 1) \
1871 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1872 break; \
1875 if (I < USED) \
1876 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1879 } while (0)
1882 /* Both FROM and TO are multibyte characters. */
1884 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1885 do { \
1886 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1888 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1889 for (C0 = (FROM); C0 <= (TO); C0++) \
1891 C1 = TRANSLATE (C0); \
1892 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1893 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1894 SET_LIST_BIT (C2); \
1895 if (C1 >= (FROM) && C1 <= (TO)) \
1896 continue; \
1897 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1899 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1900 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1902 if (C1 >= from - 1 && C1 <= to + 1) \
1904 if (C1 == from - 1) \
1905 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1906 else if (C1 == to + 1) \
1907 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1908 break; \
1911 if (I < USED) \
1912 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1914 } while (0)
1916 #endif /* emacs */
1918 /* Get the next unsigned number in the uncompiled pattern. */
1919 #define GET_INTERVAL_COUNT(num) \
1920 do { \
1921 if (p == pend) \
1922 FREE_STACK_RETURN (REG_EBRACE); \
1923 else \
1925 PATFETCH (c); \
1926 while ('0' <= c && c <= '9') \
1928 if (num < 0) \
1929 num = 0; \
1930 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
1931 FREE_STACK_RETURN (REG_BADBR); \
1932 num = num * 10 + c - '0'; \
1933 if (p == pend) \
1934 FREE_STACK_RETURN (REG_EBRACE); \
1935 PATFETCH (c); \
1938 } while (0)
1940 #if ! WIDE_CHAR_SUPPORT
1942 /* Parse a character class, i.e. string such as "[:name:]". *strp
1943 points to the string to be parsed and limit is length, in bytes, of
1944 that string.
1946 If *strp point to a string that begins with "[:name:]", where name is
1947 a non-empty sequence of lower case letters, *strp will be advanced past the
1948 closing square bracket and RECC_* constant which maps to the name will be
1949 returned. If name is not a valid character class name zero, or RECC_ERROR,
1950 is returned.
1952 Otherwise, if *strp doesn’t begin with "[:name:]", -1 is returned.
1954 The function can be used on ASCII and multibyte (UTF-8-encoded) strings.
1956 re_wctype_t
1957 re_wctype_parse (const unsigned char **strp, unsigned limit)
1959 const char *beg = (const char *)*strp, *it;
1961 if (limit < 4 || beg[0] != '[' || beg[1] != ':')
1962 return -1;
1964 beg += 2; /* skip opening ‘[:’ */
1965 limit -= 3; /* opening ‘[:’ and half of closing ‘:]’; --limit handles rest */
1966 for (it = beg; it[0] != ':' || it[1] != ']'; ++it)
1967 if (!--limit)
1968 return -1;
1970 *strp = (const unsigned char *)(it + 2);
1972 /* Sort tests in the length=five case by frequency the classes to minimize
1973 number of times we fail the comparison. The frequencies of character class
1974 names used in Emacs sources as of 2016-07-27:
1976 $ find \( -name \*.c -o -name \*.el \) -exec grep -h '\[:[a-z]*:]' {} + |
1977 sed 's/]/]\n/g' |grep -o '\[:[a-z]*:]' |sort |uniq -c |sort -nr
1978 213 [:alnum:]
1979 104 [:alpha:]
1980 62 [:space:]
1981 39 [:digit:]
1982 36 [:blank:]
1983 26 [:word:]
1984 26 [:upper:]
1985 21 [:lower:]
1986 10 [:xdigit:]
1987 10 [:punct:]
1988 10 [:ascii:]
1989 4 [:nonascii:]
1990 4 [:graph:]
1991 2 [:print:]
1992 2 [:cntrl:]
1993 1 [:ff:]
1995 If you update this list, consider also updating chain of or’ed conditions
1996 in execute_charset function.
1999 switch (it - beg) {
2000 case 4:
2001 if (!memcmp (beg, "word", 4)) return RECC_WORD;
2002 break;
2003 case 5:
2004 if (!memcmp (beg, "alnum", 5)) return RECC_ALNUM;
2005 if (!memcmp (beg, "alpha", 5)) return RECC_ALPHA;
2006 if (!memcmp (beg, "space", 5)) return RECC_SPACE;
2007 if (!memcmp (beg, "digit", 5)) return RECC_DIGIT;
2008 if (!memcmp (beg, "blank", 5)) return RECC_BLANK;
2009 if (!memcmp (beg, "upper", 5)) return RECC_UPPER;
2010 if (!memcmp (beg, "lower", 5)) return RECC_LOWER;
2011 if (!memcmp (beg, "punct", 5)) return RECC_PUNCT;
2012 if (!memcmp (beg, "ascii", 5)) return RECC_ASCII;
2013 if (!memcmp (beg, "graph", 5)) return RECC_GRAPH;
2014 if (!memcmp (beg, "print", 5)) return RECC_PRINT;
2015 if (!memcmp (beg, "cntrl", 5)) return RECC_CNTRL;
2016 break;
2017 case 6:
2018 if (!memcmp (beg, "xdigit", 6)) return RECC_XDIGIT;
2019 break;
2020 case 7:
2021 if (!memcmp (beg, "unibyte", 7)) return RECC_UNIBYTE;
2022 break;
2023 case 8:
2024 if (!memcmp (beg, "nonascii", 8)) return RECC_NONASCII;
2025 break;
2026 case 9:
2027 if (!memcmp (beg, "multibyte", 9)) return RECC_MULTIBYTE;
2028 break;
2031 return RECC_ERROR;
2034 /* True if CH is in the char class CC. */
2035 boolean
2036 re_iswctype (int ch, re_wctype_t cc)
2038 switch (cc)
2040 case RECC_ALNUM: return ISALNUM (ch) != 0;
2041 case RECC_ALPHA: return ISALPHA (ch) != 0;
2042 case RECC_BLANK: return ISBLANK (ch) != 0;
2043 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2044 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2045 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2046 case RECC_LOWER: return ISLOWER (ch) != 0;
2047 case RECC_PRINT: return ISPRINT (ch) != 0;
2048 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2049 case RECC_SPACE: return ISSPACE (ch) != 0;
2050 case RECC_UPPER: return ISUPPER (ch) != 0;
2051 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2052 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2053 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2054 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2055 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2056 case RECC_WORD: return ISWORD (ch) != 0;
2057 case RECC_ERROR: return false;
2058 default:
2059 abort ();
2063 /* Return a bit-pattern to use in the range-table bits to match multibyte
2064 chars of class CC. */
2065 static int
2066 re_wctype_to_bit (re_wctype_t cc)
2068 switch (cc)
2070 case RECC_NONASCII:
2071 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2072 case RECC_ALPHA: return BIT_ALPHA;
2073 case RECC_ALNUM: return BIT_ALNUM;
2074 case RECC_WORD: return BIT_WORD;
2075 case RECC_LOWER: return BIT_LOWER;
2076 case RECC_UPPER: return BIT_UPPER;
2077 case RECC_PUNCT: return BIT_PUNCT;
2078 case RECC_SPACE: return BIT_SPACE;
2079 case RECC_GRAPH: return BIT_GRAPH;
2080 case RECC_PRINT: return BIT_PRINT;
2081 case RECC_BLANK: return BIT_BLANK;
2082 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2083 case RECC_UNIBYTE: case RECC_ERROR: return 0;
2084 default:
2085 abort ();
2088 #endif
2090 /* Filling in the work area of a range. */
2092 /* Actually extend the space in WORK_AREA. */
2094 static void
2095 extend_range_table_work_area (struct range_table_work_area *work_area)
2097 work_area->allocated += 16 * sizeof (int);
2098 work_area->table = realloc (work_area->table, work_area->allocated);
2101 #if 0
2102 #ifdef emacs
2104 /* Carefully find the ranges of codes that are equivalent
2105 under case conversion to the range start..end when passed through
2106 TRANSLATE. Handle the case where non-letters can come in between
2107 two upper-case letters (which happens in Latin-1).
2108 Also handle the case of groups of more than 2 case-equivalent chars.
2110 The basic method is to look at consecutive characters and see
2111 if they can form a run that can be handled as one.
2113 Returns -1 if successful, REG_ESPACE if ran out of space. */
2115 static int
2116 set_image_of_range_1 (struct range_table_work_area *work_area,
2117 re_wchar_t start, re_wchar_t end,
2118 RE_TRANSLATE_TYPE translate)
2120 /* `one_case' indicates a character, or a run of characters,
2121 each of which is an isolate (no case-equivalents).
2122 This includes all ASCII non-letters.
2124 `two_case' indicates a character, or a run of characters,
2125 each of which has two case-equivalent forms.
2126 This includes all ASCII letters.
2128 `strange' indicates a character that has more than one
2129 case-equivalent. */
2131 enum case_type {one_case, two_case, strange};
2133 /* Describe the run that is in progress,
2134 which the next character can try to extend.
2135 If run_type is strange, that means there really is no run.
2136 If run_type is one_case, then run_start...run_end is the run.
2137 If run_type is two_case, then the run is run_start...run_end,
2138 and the case-equivalents end at run_eqv_end. */
2140 enum case_type run_type = strange;
2141 int run_start, run_end, run_eqv_end;
2143 Lisp_Object eqv_table;
2145 if (!RE_TRANSLATE_P (translate))
2147 EXTEND_RANGE_TABLE (work_area, 2);
2148 work_area->table[work_area->used++] = (start);
2149 work_area->table[work_area->used++] = (end);
2150 return -1;
2153 eqv_table = XCHAR_TABLE (translate)->extras[2];
2155 for (; start <= end; start++)
2157 enum case_type this_type;
2158 int eqv = RE_TRANSLATE (eqv_table, start);
2159 int minchar, maxchar;
2161 /* Classify this character */
2162 if (eqv == start)
2163 this_type = one_case;
2164 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2165 this_type = two_case;
2166 else
2167 this_type = strange;
2169 if (start < eqv)
2170 minchar = start, maxchar = eqv;
2171 else
2172 minchar = eqv, maxchar = start;
2174 /* Can this character extend the run in progress? */
2175 if (this_type == strange || this_type != run_type
2176 || !(minchar == run_end + 1
2177 && (run_type == two_case
2178 ? maxchar == run_eqv_end + 1 : 1)))
2180 /* No, end the run.
2181 Record each of its equivalent ranges. */
2182 if (run_type == one_case)
2184 EXTEND_RANGE_TABLE (work_area, 2);
2185 work_area->table[work_area->used++] = run_start;
2186 work_area->table[work_area->used++] = run_end;
2188 else if (run_type == two_case)
2190 EXTEND_RANGE_TABLE (work_area, 4);
2191 work_area->table[work_area->used++] = run_start;
2192 work_area->table[work_area->used++] = run_end;
2193 work_area->table[work_area->used++]
2194 = RE_TRANSLATE (eqv_table, run_start);
2195 work_area->table[work_area->used++]
2196 = RE_TRANSLATE (eqv_table, run_end);
2198 run_type = strange;
2201 if (this_type == strange)
2203 /* For a strange character, add each of its equivalents, one
2204 by one. Don't start a range. */
2207 EXTEND_RANGE_TABLE (work_area, 2);
2208 work_area->table[work_area->used++] = eqv;
2209 work_area->table[work_area->used++] = eqv;
2210 eqv = RE_TRANSLATE (eqv_table, eqv);
2212 while (eqv != start);
2215 /* Add this char to the run, or start a new run. */
2216 else if (run_type == strange)
2218 /* Initialize a new range. */
2219 run_type = this_type;
2220 run_start = start;
2221 run_end = start;
2222 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2224 else
2226 /* Extend a running range. */
2227 run_end = minchar;
2228 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2232 /* If a run is still in progress at the end, finish it now
2233 by recording its equivalent ranges. */
2234 if (run_type == one_case)
2236 EXTEND_RANGE_TABLE (work_area, 2);
2237 work_area->table[work_area->used++] = run_start;
2238 work_area->table[work_area->used++] = run_end;
2240 else if (run_type == two_case)
2242 EXTEND_RANGE_TABLE (work_area, 4);
2243 work_area->table[work_area->used++] = run_start;
2244 work_area->table[work_area->used++] = run_end;
2245 work_area->table[work_area->used++]
2246 = RE_TRANSLATE (eqv_table, run_start);
2247 work_area->table[work_area->used++]
2248 = RE_TRANSLATE (eqv_table, run_end);
2251 return -1;
2254 #endif /* emacs */
2256 /* Record the image of the range start..end when passed through
2257 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2258 and is not even necessarily contiguous.
2259 Normally we approximate it with the smallest contiguous range that contains
2260 all the chars we need. However, for Latin-1 we go to extra effort
2261 to do a better job.
2263 This function is not called for ASCII ranges.
2265 Returns -1 if successful, REG_ESPACE if ran out of space. */
2267 static int
2268 set_image_of_range (struct range_table_work_area *work_area,
2269 re_wchar_t start, re_wchar_t end,
2270 RE_TRANSLATE_TYPE translate)
2272 re_wchar_t cmin, cmax;
2274 #ifdef emacs
2275 /* For Latin-1 ranges, use set_image_of_range_1
2276 to get proper handling of ranges that include letters and nonletters.
2277 For a range that includes the whole of Latin-1, this is not necessary.
2278 For other character sets, we don't bother to get this right. */
2279 if (RE_TRANSLATE_P (translate) && start < 04400
2280 && !(start < 04200 && end >= 04377))
2282 int newend;
2283 int tem;
2284 newend = end;
2285 if (newend > 04377)
2286 newend = 04377;
2287 tem = set_image_of_range_1 (work_area, start, newend, translate);
2288 if (tem > 0)
2289 return tem;
2291 start = 04400;
2292 if (end < 04400)
2293 return -1;
2295 #endif
2297 EXTEND_RANGE_TABLE (work_area, 2);
2298 work_area->table[work_area->used++] = (start);
2299 work_area->table[work_area->used++] = (end);
2301 cmin = -1, cmax = -1;
2303 if (RE_TRANSLATE_P (translate))
2305 int ch;
2307 for (ch = start; ch <= end; ch++)
2309 re_wchar_t c = TRANSLATE (ch);
2310 if (! (start <= c && c <= end))
2312 if (cmin == -1)
2313 cmin = c, cmax = c;
2314 else
2316 cmin = min (cmin, c);
2317 cmax = max (cmax, c);
2322 if (cmin != -1)
2324 EXTEND_RANGE_TABLE (work_area, 2);
2325 work_area->table[work_area->used++] = (cmin);
2326 work_area->table[work_area->used++] = (cmax);
2330 return -1;
2332 #endif /* 0 */
2334 #ifndef MATCH_MAY_ALLOCATE
2336 /* If we cannot allocate large objects within re_match_2_internal,
2337 we make the fail stack and register vectors global.
2338 The fail stack, we grow to the maximum size when a regexp
2339 is compiled.
2340 The register vectors, we adjust in size each time we
2341 compile a regexp, according to the number of registers it needs. */
2343 static fail_stack_type fail_stack;
2345 /* Size with which the following vectors are currently allocated.
2346 That is so we can make them bigger as needed,
2347 but never make them smaller. */
2348 static int regs_allocated_size;
2350 static re_char ** regstart, ** regend;
2351 static re_char **best_regstart, **best_regend;
2353 /* Make the register vectors big enough for NUM_REGS registers,
2354 but don't make them smaller. */
2356 static
2357 regex_grow_registers (int num_regs)
2359 if (num_regs > regs_allocated_size)
2361 RETALLOC_IF (regstart, num_regs, re_char *);
2362 RETALLOC_IF (regend, num_regs, re_char *);
2363 RETALLOC_IF (best_regstart, num_regs, re_char *);
2364 RETALLOC_IF (best_regend, num_regs, re_char *);
2366 regs_allocated_size = num_regs;
2370 #endif /* not MATCH_MAY_ALLOCATE */
2372 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2373 regnum_t regnum);
2375 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2376 Returns one of error codes defined in `regex.h', or zero for success.
2378 If WHITESPACE_REGEXP is given (only #ifdef emacs), it is used instead of
2379 a space character in PATTERN.
2381 Assumes the `allocated' (and perhaps `buffer') and `translate'
2382 fields are set in BUFP on entry.
2384 If it succeeds, results are put in BUFP (if it returns an error, the
2385 contents of BUFP are undefined):
2386 `buffer' is the compiled pattern;
2387 `syntax' is set to SYNTAX;
2388 `used' is set to the length of the compiled pattern;
2389 `fastmap_accurate' is zero;
2390 `re_nsub' is the number of subexpressions in PATTERN;
2391 `not_bol' and `not_eol' are zero;
2393 The `fastmap' field is neither examined nor set. */
2395 /* Insert the `jump' from the end of last alternative to "here".
2396 The space for the jump has already been allocated. */
2397 #define FIXUP_ALT_JUMP() \
2398 do { \
2399 if (fixup_alt_jump) \
2400 STORE_JUMP (jump, fixup_alt_jump, b); \
2401 } while (0)
2404 /* Return, freeing storage we allocated. */
2405 #define FREE_STACK_RETURN(value) \
2406 do { \
2407 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2408 free (compile_stack.stack); \
2409 return value; \
2410 } while (0)
2412 static reg_errcode_t
2413 regex_compile (const_re_char *pattern, size_t size,
2414 #ifdef emacs
2415 # define syntax RE_SYNTAX_EMACS
2416 bool posix_backtracking,
2417 const char *whitespace_regexp,
2418 #else
2419 reg_syntax_t syntax,
2420 # define posix_backtracking (!(syntax & RE_NO_POSIX_BACKTRACKING))
2421 #endif
2422 struct re_pattern_buffer *bufp)
2424 /* We fetch characters from PATTERN here. */
2425 register re_wchar_t c, c1;
2427 /* Points to the end of the buffer, where we should append. */
2428 register unsigned char *b;
2430 /* Keeps track of unclosed groups. */
2431 compile_stack_type compile_stack;
2433 /* Points to the current (ending) position in the pattern. */
2434 #ifdef AIX
2435 /* `const' makes AIX compiler fail. */
2436 unsigned char *p = pattern;
2437 #else
2438 re_char *p = pattern;
2439 #endif
2440 re_char *pend = pattern + size;
2442 /* How to translate the characters in the pattern. */
2443 RE_TRANSLATE_TYPE translate = bufp->translate;
2445 /* Address of the count-byte of the most recently inserted `exactn'
2446 command. This makes it possible to tell if a new exact-match
2447 character can be added to that command or if the character requires
2448 a new `exactn' command. */
2449 unsigned char *pending_exact = 0;
2451 /* Address of start of the most recently finished expression.
2452 This tells, e.g., postfix * where to find the start of its
2453 operand. Reset at the beginning of groups and alternatives. */
2454 unsigned char *laststart = 0;
2456 /* Address of beginning of regexp, or inside of last group. */
2457 unsigned char *begalt;
2459 /* Place in the uncompiled pattern (i.e., the {) to
2460 which to go back if the interval is invalid. */
2461 re_char *beg_interval;
2463 /* Address of the place where a forward jump should go to the end of
2464 the containing expression. Each alternative of an `or' -- except the
2465 last -- ends with a forward jump of this sort. */
2466 unsigned char *fixup_alt_jump = 0;
2468 /* Work area for range table of charset. */
2469 struct range_table_work_area range_table_work;
2471 /* If the object matched can contain multibyte characters. */
2472 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2474 #ifdef emacs
2475 /* Nonzero if we have pushed down into a subpattern. */
2476 int in_subpattern = 0;
2478 /* These hold the values of p, pattern, and pend from the main
2479 pattern when we have pushed into a subpattern. */
2480 re_char *main_p;
2481 re_char *main_pattern;
2482 re_char *main_pend;
2483 #endif
2485 #ifdef DEBUG
2486 debug++;
2487 DEBUG_PRINT ("\nCompiling pattern: ");
2488 if (debug > 0)
2490 unsigned debug_count;
2492 for (debug_count = 0; debug_count < size; debug_count++)
2493 putchar (pattern[debug_count]);
2494 putchar ('\n');
2496 #endif /* DEBUG */
2498 /* Initialize the compile stack. */
2499 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2500 if (compile_stack.stack == NULL)
2501 return REG_ESPACE;
2503 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2504 compile_stack.avail = 0;
2506 range_table_work.table = 0;
2507 range_table_work.allocated = 0;
2509 /* Initialize the pattern buffer. */
2510 #ifndef emacs
2511 bufp->syntax = syntax;
2512 #endif
2513 bufp->fastmap_accurate = 0;
2514 bufp->not_bol = bufp->not_eol = 0;
2515 bufp->used_syntax = 0;
2517 /* Set `used' to zero, so that if we return an error, the pattern
2518 printer (for debugging) will think there's no pattern. We reset it
2519 at the end. */
2520 bufp->used = 0;
2522 /* Always count groups, whether or not bufp->no_sub is set. */
2523 bufp->re_nsub = 0;
2525 #if !defined emacs && !defined SYNTAX_TABLE
2526 /* Initialize the syntax table. */
2527 init_syntax_once ();
2528 #endif
2530 if (bufp->allocated == 0)
2532 if (bufp->buffer)
2533 { /* If zero allocated, but buffer is non-null, try to realloc
2534 enough space. This loses if buffer's address is bogus, but
2535 that is the user's responsibility. */
2536 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2538 else
2539 { /* Caller did not allocate a buffer. Do it for them. */
2540 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2542 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2544 bufp->allocated = INIT_BUF_SIZE;
2547 begalt = b = bufp->buffer;
2549 /* Loop through the uncompiled pattern until we're at the end. */
2550 while (1)
2552 if (p == pend)
2554 #ifdef emacs
2555 /* If this is the end of an included regexp,
2556 pop back to the main regexp and try again. */
2557 if (in_subpattern)
2559 in_subpattern = 0;
2560 pattern = main_pattern;
2561 p = main_p;
2562 pend = main_pend;
2563 continue;
2565 #endif
2566 /* If this is the end of the main regexp, we are done. */
2567 break;
2570 PATFETCH (c);
2572 switch (c)
2574 #ifdef emacs
2575 case ' ':
2577 re_char *p1 = p;
2579 /* If there's no special whitespace regexp, treat
2580 spaces normally. And don't try to do this recursively. */
2581 if (!whitespace_regexp || in_subpattern)
2582 goto normal_char;
2584 /* Peek past following spaces. */
2585 while (p1 != pend)
2587 if (*p1 != ' ')
2588 break;
2589 p1++;
2591 /* If the spaces are followed by a repetition op,
2592 treat them normally. */
2593 if (p1 != pend
2594 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2595 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2596 goto normal_char;
2598 /* Replace the spaces with the whitespace regexp. */
2599 in_subpattern = 1;
2600 main_p = p1;
2601 main_pend = pend;
2602 main_pattern = pattern;
2603 p = pattern = (re_char *) whitespace_regexp;
2604 pend = p + strlen (whitespace_regexp);
2605 break;
2607 #endif
2609 case '^':
2611 if ( /* If at start of pattern, it's an operator. */
2612 p == pattern + 1
2613 /* If context independent, it's an operator. */
2614 || syntax & RE_CONTEXT_INDEP_ANCHORS
2615 /* Otherwise, depends on what's come before. */
2616 || at_begline_loc_p (pattern, p, syntax))
2617 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2618 else
2619 goto normal_char;
2621 break;
2624 case '$':
2626 if ( /* If at end of pattern, it's an operator. */
2627 p == pend
2628 /* If context independent, it's an operator. */
2629 || syntax & RE_CONTEXT_INDEP_ANCHORS
2630 /* Otherwise, depends on what's next. */
2631 || at_endline_loc_p (p, pend, syntax))
2632 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2633 else
2634 goto normal_char;
2636 break;
2639 case '+':
2640 case '?':
2641 if ((syntax & RE_BK_PLUS_QM)
2642 || (syntax & RE_LIMITED_OPS))
2643 goto normal_char;
2644 handle_plus:
2645 case '*':
2646 /* If there is no previous pattern... */
2647 if (!laststart)
2649 if (syntax & RE_CONTEXT_INVALID_OPS)
2650 FREE_STACK_RETURN (REG_BADRPT);
2651 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2652 goto normal_char;
2656 /* 1 means zero (many) matches is allowed. */
2657 boolean zero_times_ok = 0, many_times_ok = 0;
2658 boolean greedy = 1;
2660 /* If there is a sequence of repetition chars, collapse it
2661 down to just one (the right one). We can't combine
2662 interval operators with these because of, e.g., `a{2}*',
2663 which should only match an even number of `a's. */
2665 for (;;)
2667 if ((syntax & RE_FRUGAL)
2668 && c == '?' && (zero_times_ok || many_times_ok))
2669 greedy = 0;
2670 else
2672 zero_times_ok |= c != '+';
2673 many_times_ok |= c != '?';
2676 if (p == pend)
2677 break;
2678 else if (*p == '*'
2679 || (!(syntax & RE_BK_PLUS_QM)
2680 && (*p == '+' || *p == '?')))
2682 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2684 if (p+1 == pend)
2685 FREE_STACK_RETURN (REG_EESCAPE);
2686 if (p[1] == '+' || p[1] == '?')
2687 PATFETCH (c); /* Gobble up the backslash. */
2688 else
2689 break;
2691 else
2692 break;
2693 /* If we get here, we found another repeat character. */
2694 PATFETCH (c);
2697 /* Star, etc. applied to an empty pattern is equivalent
2698 to an empty pattern. */
2699 if (!laststart || laststart == b)
2700 break;
2702 /* Now we know whether or not zero matches is allowed
2703 and also whether or not two or more matches is allowed. */
2704 if (greedy)
2706 if (many_times_ok)
2708 boolean simple = skip_one_char (laststart) == b;
2709 size_t startoffset = 0;
2710 re_opcode_t ofj =
2711 /* Check if the loop can match the empty string. */
2712 (simple || !analyze_first (laststart, b, NULL, 0))
2713 ? on_failure_jump : on_failure_jump_loop;
2714 assert (skip_one_char (laststart) <= b);
2716 if (!zero_times_ok && simple)
2717 { /* Since simple * loops can be made faster by using
2718 on_failure_keep_string_jump, we turn simple P+
2719 into PP* if P is simple. */
2720 unsigned char *p1, *p2;
2721 startoffset = b - laststart;
2722 GET_BUFFER_SPACE (startoffset);
2723 p1 = b; p2 = laststart;
2724 while (p2 < p1)
2725 *b++ = *p2++;
2726 zero_times_ok = 1;
2729 GET_BUFFER_SPACE (6);
2730 if (!zero_times_ok)
2731 /* A + loop. */
2732 STORE_JUMP (ofj, b, b + 6);
2733 else
2734 /* Simple * loops can use on_failure_keep_string_jump
2735 depending on what follows. But since we don't know
2736 that yet, we leave the decision up to
2737 on_failure_jump_smart. */
2738 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2739 laststart + startoffset, b + 6);
2740 b += 3;
2741 STORE_JUMP (jump, b, laststart + startoffset);
2742 b += 3;
2744 else
2746 /* A simple ? pattern. */
2747 assert (zero_times_ok);
2748 GET_BUFFER_SPACE (3);
2749 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2750 b += 3;
2753 else /* not greedy */
2754 { /* I wish the greedy and non-greedy cases could be merged. */
2756 GET_BUFFER_SPACE (7); /* We might use less. */
2757 if (many_times_ok)
2759 boolean emptyp = analyze_first (laststart, b, NULL, 0);
2761 /* The non-greedy multiple match looks like
2762 a repeat..until: we only need a conditional jump
2763 at the end of the loop. */
2764 if (emptyp) BUF_PUSH (no_op);
2765 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2766 : on_failure_jump, b, laststart);
2767 b += 3;
2768 if (zero_times_ok)
2770 /* The repeat...until naturally matches one or more.
2771 To also match zero times, we need to first jump to
2772 the end of the loop (its conditional jump). */
2773 INSERT_JUMP (jump, laststart, b);
2774 b += 3;
2777 else
2779 /* non-greedy a?? */
2780 INSERT_JUMP (jump, laststart, b + 3);
2781 b += 3;
2782 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2783 b += 3;
2787 pending_exact = 0;
2788 break;
2791 case '.':
2792 laststart = b;
2793 BUF_PUSH (anychar);
2794 break;
2797 case '[':
2799 re_char *p1;
2801 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2803 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2805 /* Ensure that we have enough space to push a charset: the
2806 opcode, the length count, and the bitset; 34 bytes in all. */
2807 GET_BUFFER_SPACE (34);
2809 laststart = b;
2811 /* We test `*p == '^' twice, instead of using an if
2812 statement, so we only need one BUF_PUSH. */
2813 BUF_PUSH (*p == '^' ? charset_not : charset);
2814 if (*p == '^')
2815 p++;
2817 /* Remember the first position in the bracket expression. */
2818 p1 = p;
2820 /* Push the number of bytes in the bitmap. */
2821 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2823 /* Clear the whole map. */
2824 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2826 /* charset_not matches newline according to a syntax bit. */
2827 if ((re_opcode_t) b[-2] == charset_not
2828 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2829 SET_LIST_BIT ('\n');
2831 /* Read in characters and ranges, setting map bits. */
2832 for (;;)
2834 boolean escaped_char = false;
2835 const unsigned char *p2 = p;
2836 re_wctype_t cc;
2837 re_wchar_t ch;
2839 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2841 /* See if we're at the beginning of a possible character
2842 class. */
2843 if (syntax & RE_CHAR_CLASSES &&
2844 (cc = re_wctype_parse(&p, pend - p)) != -1)
2846 if (cc == 0)
2847 FREE_STACK_RETURN (REG_ECTYPE);
2849 if (p == pend)
2850 FREE_STACK_RETURN (REG_EBRACK);
2852 #ifndef emacs
2853 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2854 if (re_iswctype (btowc (ch), cc))
2856 c = TRANSLATE (ch);
2857 if (c < (1 << BYTEWIDTH))
2858 SET_LIST_BIT (c);
2860 #else /* emacs */
2861 /* Most character classes in a multibyte match just set
2862 a flag. Exceptions are is_blank, is_digit, is_cntrl, and
2863 is_xdigit, since they can only match ASCII characters.
2864 We don't need to handle them for multibyte. */
2866 /* Setup the gl_state object to its buffer-defined value.
2867 This hardcodes the buffer-global syntax-table for ASCII
2868 chars, while the other chars will obey syntax-table
2869 properties. It's not ideal, but it's the way it's been
2870 done until now. */
2871 SETUP_BUFFER_SYNTAX_TABLE ();
2873 for (c = 0; c < 0x80; ++c)
2874 if (re_iswctype (c, cc))
2876 SET_LIST_BIT (c);
2877 c1 = TRANSLATE (c);
2878 if (c1 == c)
2879 continue;
2880 if (ASCII_CHAR_P (c1))
2881 SET_LIST_BIT (c1);
2882 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2883 SET_LIST_BIT (c1);
2885 SET_RANGE_TABLE_WORK_AREA_BIT
2886 (range_table_work, re_wctype_to_bit (cc));
2887 #endif /* emacs */
2888 /* In most cases the matching rule for char classes only
2889 uses the syntax table for multibyte chars, so that the
2890 content of the syntax-table is not hardcoded in the
2891 range_table. SPACE and WORD are the two exceptions. */
2892 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2893 bufp->used_syntax = 1;
2895 /* Repeat the loop. */
2896 continue;
2899 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2900 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2901 So the translation is done later in a loop. Example:
2902 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2903 PATFETCH (c);
2905 /* \ might escape characters inside [...] and [^...]. */
2906 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2908 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2910 PATFETCH (c);
2911 escaped_char = true;
2913 else
2915 /* Could be the end of the bracket expression. If it's
2916 not (i.e., when the bracket expression is `[]' so
2917 far), the ']' character bit gets set way below. */
2918 if (c == ']' && p2 != p1)
2919 break;
2922 if (p < pend && p[0] == '-' && p[1] != ']')
2925 /* Discard the `-'. */
2926 PATFETCH (c1);
2928 /* Fetch the character which ends the range. */
2929 PATFETCH (c1);
2930 #ifdef emacs
2931 if (CHAR_BYTE8_P (c1)
2932 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2933 /* Treat the range from a multibyte character to
2934 raw-byte character as empty. */
2935 c = c1 + 1;
2936 #endif /* emacs */
2938 else
2939 /* Range from C to C. */
2940 c1 = c;
2942 if (c > c1)
2944 if (syntax & RE_NO_EMPTY_RANGES)
2945 FREE_STACK_RETURN (REG_ERANGEX);
2946 /* Else, repeat the loop. */
2948 else
2950 #ifndef emacs
2951 /* Set the range into bitmap */
2952 for (; c <= c1; c++)
2954 ch = TRANSLATE (c);
2955 if (ch < (1 << BYTEWIDTH))
2956 SET_LIST_BIT (ch);
2958 #else /* emacs */
2959 if (c < 128)
2961 ch = min (127, c1);
2962 SETUP_ASCII_RANGE (range_table_work, c, ch);
2963 c = ch + 1;
2964 if (CHAR_BYTE8_P (c1))
2965 c = BYTE8_TO_CHAR (128);
2967 if (c <= c1)
2969 if (CHAR_BYTE8_P (c))
2971 c = CHAR_TO_BYTE8 (c);
2972 c1 = CHAR_TO_BYTE8 (c1);
2973 for (; c <= c1; c++)
2974 SET_LIST_BIT (c);
2976 else if (multibyte)
2978 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
2980 else
2982 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
2985 #endif /* emacs */
2989 /* Discard any (non)matching list bytes that are all 0 at the
2990 end of the map. Decrease the map-length byte too. */
2991 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2992 b[-1]--;
2993 b += b[-1];
2995 /* Build real range table from work area. */
2996 if (RANGE_TABLE_WORK_USED (range_table_work)
2997 || RANGE_TABLE_WORK_BITS (range_table_work))
2999 int i;
3000 int used = RANGE_TABLE_WORK_USED (range_table_work);
3002 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3003 bytes for flags, two for COUNT, and three bytes for
3004 each character. */
3005 GET_BUFFER_SPACE (4 + used * 3);
3007 /* Indicate the existence of range table. */
3008 laststart[1] |= 0x80;
3010 /* Store the character class flag bits into the range table.
3011 If not in emacs, these flag bits are always 0. */
3012 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3013 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3015 STORE_NUMBER_AND_INCR (b, used / 2);
3016 for (i = 0; i < used; i++)
3017 STORE_CHARACTER_AND_INCR
3018 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3021 break;
3024 case '(':
3025 if (syntax & RE_NO_BK_PARENS)
3026 goto handle_open;
3027 else
3028 goto normal_char;
3031 case ')':
3032 if (syntax & RE_NO_BK_PARENS)
3033 goto handle_close;
3034 else
3035 goto normal_char;
3038 case '\n':
3039 if (syntax & RE_NEWLINE_ALT)
3040 goto handle_alt;
3041 else
3042 goto normal_char;
3045 case '|':
3046 if (syntax & RE_NO_BK_VBAR)
3047 goto handle_alt;
3048 else
3049 goto normal_char;
3052 case '{':
3053 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3054 goto handle_interval;
3055 else
3056 goto normal_char;
3059 case '\\':
3060 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3062 /* Do not translate the character after the \, so that we can
3063 distinguish, e.g., \B from \b, even if we normally would
3064 translate, e.g., B to b. */
3065 PATFETCH (c);
3067 switch (c)
3069 case '(':
3070 if (syntax & RE_NO_BK_PARENS)
3071 goto normal_backslash;
3073 handle_open:
3075 int shy = 0;
3076 regnum_t regnum = 0;
3077 if (p+1 < pend)
3079 /* Look for a special (?...) construct */
3080 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3082 PATFETCH (c); /* Gobble up the '?'. */
3083 while (!shy)
3085 PATFETCH (c);
3086 switch (c)
3088 case ':': shy = 1; break;
3089 case '0':
3090 /* An explicitly specified regnum must start
3091 with non-0. */
3092 if (regnum == 0)
3093 FREE_STACK_RETURN (REG_BADPAT);
3094 case '1': case '2': case '3': case '4':
3095 case '5': case '6': case '7': case '8': case '9':
3096 regnum = 10*regnum + (c - '0'); break;
3097 default:
3098 /* Only (?:...) is supported right now. */
3099 FREE_STACK_RETURN (REG_BADPAT);
3105 if (!shy)
3106 regnum = ++bufp->re_nsub;
3107 else if (regnum)
3108 { /* It's actually not shy, but explicitly numbered. */
3109 shy = 0;
3110 if (regnum > bufp->re_nsub)
3111 bufp->re_nsub = regnum;
3112 else if (regnum > bufp->re_nsub
3113 /* Ideally, we'd want to check that the specified
3114 group can't have matched (i.e. all subgroups
3115 using the same regnum are in other branches of
3116 OR patterns), but we don't currently keep track
3117 of enough info to do that easily. */
3118 || group_in_compile_stack (compile_stack, regnum))
3119 FREE_STACK_RETURN (REG_BADPAT);
3121 else
3122 /* It's really shy. */
3123 regnum = - bufp->re_nsub;
3125 if (COMPILE_STACK_FULL)
3127 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3128 compile_stack_elt_t);
3129 if (compile_stack.stack == NULL) return REG_ESPACE;
3131 compile_stack.size <<= 1;
3134 /* These are the values to restore when we hit end of this
3135 group. They are all relative offsets, so that if the
3136 whole pattern moves because of realloc, they will still
3137 be valid. */
3138 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3139 COMPILE_STACK_TOP.fixup_alt_jump
3140 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3141 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3142 COMPILE_STACK_TOP.regnum = regnum;
3144 /* Do not push a start_memory for groups beyond the last one
3145 we can represent in the compiled pattern. */
3146 if (regnum <= MAX_REGNUM && regnum > 0)
3147 BUF_PUSH_2 (start_memory, regnum);
3149 compile_stack.avail++;
3151 fixup_alt_jump = 0;
3152 laststart = 0;
3153 begalt = b;
3154 /* If we've reached MAX_REGNUM groups, then this open
3155 won't actually generate any code, so we'll have to
3156 clear pending_exact explicitly. */
3157 pending_exact = 0;
3158 break;
3161 case ')':
3162 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3164 if (COMPILE_STACK_EMPTY)
3166 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3167 goto normal_backslash;
3168 else
3169 FREE_STACK_RETURN (REG_ERPAREN);
3172 handle_close:
3173 FIXUP_ALT_JUMP ();
3175 /* See similar code for backslashed left paren above. */
3176 if (COMPILE_STACK_EMPTY)
3178 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3179 goto normal_char;
3180 else
3181 FREE_STACK_RETURN (REG_ERPAREN);
3184 /* Since we just checked for an empty stack above, this
3185 ``can't happen''. */
3186 assert (compile_stack.avail != 0);
3188 /* We don't just want to restore into `regnum', because
3189 later groups should continue to be numbered higher,
3190 as in `(ab)c(de)' -- the second group is #2. */
3191 regnum_t regnum;
3193 compile_stack.avail--;
3194 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3195 fixup_alt_jump
3196 = COMPILE_STACK_TOP.fixup_alt_jump
3197 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3198 : 0;
3199 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3200 regnum = COMPILE_STACK_TOP.regnum;
3201 /* If we've reached MAX_REGNUM groups, then this open
3202 won't actually generate any code, so we'll have to
3203 clear pending_exact explicitly. */
3204 pending_exact = 0;
3206 /* We're at the end of the group, so now we know how many
3207 groups were inside this one. */
3208 if (regnum <= MAX_REGNUM && regnum > 0)
3209 BUF_PUSH_2 (stop_memory, regnum);
3211 break;
3214 case '|': /* `\|'. */
3215 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3216 goto normal_backslash;
3217 handle_alt:
3218 if (syntax & RE_LIMITED_OPS)
3219 goto normal_char;
3221 /* Insert before the previous alternative a jump which
3222 jumps to this alternative if the former fails. */
3223 GET_BUFFER_SPACE (3);
3224 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3225 pending_exact = 0;
3226 b += 3;
3228 /* The alternative before this one has a jump after it
3229 which gets executed if it gets matched. Adjust that
3230 jump so it will jump to this alternative's analogous
3231 jump (put in below, which in turn will jump to the next
3232 (if any) alternative's such jump, etc.). The last such
3233 jump jumps to the correct final destination. A picture:
3234 _____ _____
3235 | | | |
3236 | v | v
3237 a | b | c
3239 If we are at `b', then fixup_alt_jump right now points to a
3240 three-byte space after `a'. We'll put in the jump, set
3241 fixup_alt_jump to right after `b', and leave behind three
3242 bytes which we'll fill in when we get to after `c'. */
3244 FIXUP_ALT_JUMP ();
3246 /* Mark and leave space for a jump after this alternative,
3247 to be filled in later either by next alternative or
3248 when know we're at the end of a series of alternatives. */
3249 fixup_alt_jump = b;
3250 GET_BUFFER_SPACE (3);
3251 b += 3;
3253 laststart = 0;
3254 begalt = b;
3255 break;
3258 case '{':
3259 /* If \{ is a literal. */
3260 if (!(syntax & RE_INTERVALS)
3261 /* If we're at `\{' and it's not the open-interval
3262 operator. */
3263 || (syntax & RE_NO_BK_BRACES))
3264 goto normal_backslash;
3266 handle_interval:
3268 /* If got here, then the syntax allows intervals. */
3270 /* At least (most) this many matches must be made. */
3271 int lower_bound = 0, upper_bound = -1;
3273 beg_interval = p;
3275 GET_INTERVAL_COUNT (lower_bound);
3277 if (c == ',')
3278 GET_INTERVAL_COUNT (upper_bound);
3279 else
3280 /* Interval such as `{1}' => match exactly once. */
3281 upper_bound = lower_bound;
3283 if (lower_bound < 0
3284 || (0 <= upper_bound && upper_bound < lower_bound))
3285 FREE_STACK_RETURN (REG_BADBR);
3287 if (!(syntax & RE_NO_BK_BRACES))
3289 if (c != '\\')
3290 FREE_STACK_RETURN (REG_BADBR);
3291 if (p == pend)
3292 FREE_STACK_RETURN (REG_EESCAPE);
3293 PATFETCH (c);
3296 if (c != '}')
3297 FREE_STACK_RETURN (REG_BADBR);
3299 /* We just parsed a valid interval. */
3301 /* If it's invalid to have no preceding re. */
3302 if (!laststart)
3304 if (syntax & RE_CONTEXT_INVALID_OPS)
3305 FREE_STACK_RETURN (REG_BADRPT);
3306 else if (syntax & RE_CONTEXT_INDEP_OPS)
3307 laststart = b;
3308 else
3309 goto unfetch_interval;
3312 if (upper_bound == 0)
3313 /* If the upper bound is zero, just drop the sub pattern
3314 altogether. */
3315 b = laststart;
3316 else if (lower_bound == 1 && upper_bound == 1)
3317 /* Just match it once: nothing to do here. */
3320 /* Otherwise, we have a nontrivial interval. When
3321 we're all done, the pattern will look like:
3322 set_number_at <jump count> <upper bound>
3323 set_number_at <succeed_n count> <lower bound>
3324 succeed_n <after jump addr> <succeed_n count>
3325 <body of loop>
3326 jump_n <succeed_n addr> <jump count>
3327 (The upper bound and `jump_n' are omitted if
3328 `upper_bound' is 1, though.) */
3329 else
3330 { /* If the upper bound is > 1, we need to insert
3331 more at the end of the loop. */
3332 unsigned int nbytes = (upper_bound < 0 ? 3
3333 : upper_bound > 1 ? 5 : 0);
3334 unsigned int startoffset = 0;
3336 GET_BUFFER_SPACE (20); /* We might use less. */
3338 if (lower_bound == 0)
3340 /* A succeed_n that starts with 0 is really a
3341 a simple on_failure_jump_loop. */
3342 INSERT_JUMP (on_failure_jump_loop, laststart,
3343 b + 3 + nbytes);
3344 b += 3;
3346 else
3348 /* Initialize lower bound of the `succeed_n', even
3349 though it will be set during matching by its
3350 attendant `set_number_at' (inserted next),
3351 because `re_compile_fastmap' needs to know.
3352 Jump to the `jump_n' we might insert below. */
3353 INSERT_JUMP2 (succeed_n, laststart,
3354 b + 5 + nbytes,
3355 lower_bound);
3356 b += 5;
3358 /* Code to initialize the lower bound. Insert
3359 before the `succeed_n'. The `5' is the last two
3360 bytes of this `set_number_at', plus 3 bytes of
3361 the following `succeed_n'. */
3362 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3363 b += 5;
3364 startoffset += 5;
3367 if (upper_bound < 0)
3369 /* A negative upper bound stands for infinity,
3370 in which case it degenerates to a plain jump. */
3371 STORE_JUMP (jump, b, laststart + startoffset);
3372 b += 3;
3374 else if (upper_bound > 1)
3375 { /* More than one repetition is allowed, so
3376 append a backward jump to the `succeed_n'
3377 that starts this interval.
3379 When we've reached this during matching,
3380 we'll have matched the interval once, so
3381 jump back only `upper_bound - 1' times. */
3382 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3383 upper_bound - 1);
3384 b += 5;
3386 /* The location we want to set is the second
3387 parameter of the `jump_n'; that is `b-2' as
3388 an absolute address. `laststart' will be
3389 the `set_number_at' we're about to insert;
3390 `laststart+3' the number to set, the source
3391 for the relative address. But we are
3392 inserting into the middle of the pattern --
3393 so everything is getting moved up by 5.
3394 Conclusion: (b - 2) - (laststart + 3) + 5,
3395 i.e., b - laststart.
3397 We insert this at the beginning of the loop
3398 so that if we fail during matching, we'll
3399 reinitialize the bounds. */
3400 insert_op2 (set_number_at, laststart, b - laststart,
3401 upper_bound - 1, b);
3402 b += 5;
3405 pending_exact = 0;
3406 beg_interval = NULL;
3408 break;
3410 unfetch_interval:
3411 /* If an invalid interval, match the characters as literals. */
3412 assert (beg_interval);
3413 p = beg_interval;
3414 beg_interval = NULL;
3416 /* normal_char and normal_backslash need `c'. */
3417 c = '{';
3419 if (!(syntax & RE_NO_BK_BRACES))
3421 assert (p > pattern && p[-1] == '\\');
3422 goto normal_backslash;
3424 else
3425 goto normal_char;
3427 #ifdef emacs
3428 case '=':
3429 laststart = b;
3430 BUF_PUSH (at_dot);
3431 break;
3433 case 's':
3434 laststart = b;
3435 PATFETCH (c);
3436 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3437 break;
3439 case 'S':
3440 laststart = b;
3441 PATFETCH (c);
3442 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3443 break;
3445 case 'c':
3446 laststart = b;
3447 PATFETCH (c);
3448 BUF_PUSH_2 (categoryspec, c);
3449 break;
3451 case 'C':
3452 laststart = b;
3453 PATFETCH (c);
3454 BUF_PUSH_2 (notcategoryspec, c);
3455 break;
3456 #endif /* emacs */
3459 case 'w':
3460 if (syntax & RE_NO_GNU_OPS)
3461 goto normal_char;
3462 laststart = b;
3463 BUF_PUSH_2 (syntaxspec, Sword);
3464 break;
3467 case 'W':
3468 if (syntax & RE_NO_GNU_OPS)
3469 goto normal_char;
3470 laststart = b;
3471 BUF_PUSH_2 (notsyntaxspec, Sword);
3472 break;
3475 case '<':
3476 if (syntax & RE_NO_GNU_OPS)
3477 goto normal_char;
3478 laststart = b;
3479 BUF_PUSH (wordbeg);
3480 break;
3482 case '>':
3483 if (syntax & RE_NO_GNU_OPS)
3484 goto normal_char;
3485 laststart = b;
3486 BUF_PUSH (wordend);
3487 break;
3489 case '_':
3490 if (syntax & RE_NO_GNU_OPS)
3491 goto normal_char;
3492 laststart = b;
3493 PATFETCH (c);
3494 if (c == '<')
3495 BUF_PUSH (symbeg);
3496 else if (c == '>')
3497 BUF_PUSH (symend);
3498 else
3499 FREE_STACK_RETURN (REG_BADPAT);
3500 break;
3502 case 'b':
3503 if (syntax & RE_NO_GNU_OPS)
3504 goto normal_char;
3505 BUF_PUSH (wordbound);
3506 break;
3508 case 'B':
3509 if (syntax & RE_NO_GNU_OPS)
3510 goto normal_char;
3511 BUF_PUSH (notwordbound);
3512 break;
3514 case '`':
3515 if (syntax & RE_NO_GNU_OPS)
3516 goto normal_char;
3517 BUF_PUSH (begbuf);
3518 break;
3520 case '\'':
3521 if (syntax & RE_NO_GNU_OPS)
3522 goto normal_char;
3523 BUF_PUSH (endbuf);
3524 break;
3526 case '1': case '2': case '3': case '4': case '5':
3527 case '6': case '7': case '8': case '9':
3529 regnum_t reg;
3531 if (syntax & RE_NO_BK_REFS)
3532 goto normal_backslash;
3534 reg = c - '0';
3536 if (reg > bufp->re_nsub || reg < 1
3537 /* Can't back reference to a subexp before its end. */
3538 || group_in_compile_stack (compile_stack, reg))
3539 FREE_STACK_RETURN (REG_ESUBREG);
3541 laststart = b;
3542 BUF_PUSH_2 (duplicate, reg);
3544 break;
3547 case '+':
3548 case '?':
3549 if (syntax & RE_BK_PLUS_QM)
3550 goto handle_plus;
3551 else
3552 goto normal_backslash;
3554 default:
3555 normal_backslash:
3556 /* You might think it would be useful for \ to mean
3557 not to translate; but if we don't translate it
3558 it will never match anything. */
3559 goto normal_char;
3561 break;
3564 default:
3565 /* Expects the character in `c'. */
3566 normal_char:
3567 /* If no exactn currently being built. */
3568 if (!pending_exact
3570 /* If last exactn not at current position. */
3571 || pending_exact + *pending_exact + 1 != b
3573 /* We have only one byte following the exactn for the count. */
3574 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3576 /* If followed by a repetition operator. */
3577 || (p != pend && (*p == '*' || *p == '^'))
3578 || ((syntax & RE_BK_PLUS_QM)
3579 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3580 : p != pend && (*p == '+' || *p == '?'))
3581 || ((syntax & RE_INTERVALS)
3582 && ((syntax & RE_NO_BK_BRACES)
3583 ? p != pend && *p == '{'
3584 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3586 /* Start building a new exactn. */
3588 laststart = b;
3590 BUF_PUSH_2 (exactn, 0);
3591 pending_exact = b - 1;
3594 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3596 int len;
3598 if (multibyte)
3600 c = TRANSLATE (c);
3601 len = CHAR_STRING (c, b);
3602 b += len;
3604 else
3606 c1 = RE_CHAR_TO_MULTIBYTE (c);
3607 if (! CHAR_BYTE8_P (c1))
3609 re_wchar_t c2 = TRANSLATE (c1);
3611 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3612 c = c1;
3614 *b++ = c;
3615 len = 1;
3617 (*pending_exact) += len;
3620 break;
3621 } /* switch (c) */
3622 } /* while p != pend */
3625 /* Through the pattern now. */
3627 FIXUP_ALT_JUMP ();
3629 if (!COMPILE_STACK_EMPTY)
3630 FREE_STACK_RETURN (REG_EPAREN);
3632 /* If we don't want backtracking, force success
3633 the first time we reach the end of the compiled pattern. */
3634 if (!posix_backtracking)
3635 BUF_PUSH (succeed);
3637 /* We have succeeded; set the length of the buffer. */
3638 bufp->used = b - bufp->buffer;
3640 #ifdef DEBUG
3641 if (debug > 0)
3643 re_compile_fastmap (bufp);
3644 DEBUG_PRINT ("\nCompiled pattern: \n");
3645 print_compiled_pattern (bufp);
3647 debug--;
3648 #endif /* DEBUG */
3650 #ifndef MATCH_MAY_ALLOCATE
3651 /* Initialize the failure stack to the largest possible stack. This
3652 isn't necessary unless we're trying to avoid calling alloca in
3653 the search and match routines. */
3655 int num_regs = bufp->re_nsub + 1;
3657 if (fail_stack.size < emacs_re_max_failures * TYPICAL_FAILURE_SIZE)
3659 fail_stack.size = emacs_re_max_failures * TYPICAL_FAILURE_SIZE;
3660 falk_stack.stack = realloc (fail_stack.stack,
3661 fail_stack.size * sizeof *falk_stack.stack);
3664 regex_grow_registers (num_regs);
3666 #endif /* not MATCH_MAY_ALLOCATE */
3668 FREE_STACK_RETURN (REG_NOERROR);
3670 #ifdef emacs
3671 # undef syntax
3672 #else
3673 # undef posix_backtracking
3674 #endif
3675 } /* regex_compile */
3677 /* Subroutines for `regex_compile'. */
3679 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3681 static void
3682 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3684 *loc = (unsigned char) op;
3685 STORE_NUMBER (loc + 1, arg);
3689 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3691 static void
3692 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3694 *loc = (unsigned char) op;
3695 STORE_NUMBER (loc + 1, arg1);
3696 STORE_NUMBER (loc + 3, arg2);
3700 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3701 for OP followed by two-byte integer parameter ARG. */
3703 static void
3704 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3706 register unsigned char *pfrom = end;
3707 register unsigned char *pto = end + 3;
3709 while (pfrom != loc)
3710 *--pto = *--pfrom;
3712 store_op1 (op, loc, arg);
3716 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3718 static void
3719 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3721 register unsigned char *pfrom = end;
3722 register unsigned char *pto = end + 5;
3724 while (pfrom != loc)
3725 *--pto = *--pfrom;
3727 store_op2 (op, loc, arg1, arg2);
3731 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3732 after an alternative or a begin-subexpression. We assume there is at
3733 least one character before the ^. */
3735 static boolean
3736 at_begline_loc_p (const_re_char *pattern, const_re_char *p, reg_syntax_t syntax)
3738 re_char *prev = p - 2;
3739 boolean odd_backslashes;
3741 /* After a subexpression? */
3742 if (*prev == '(')
3743 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3745 /* After an alternative? */
3746 else if (*prev == '|')
3747 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3749 /* After a shy subexpression? */
3750 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3752 /* Skip over optional regnum. */
3753 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3754 --prev;
3756 if (!(prev - 2 >= pattern
3757 && prev[-1] == '?' && prev[-2] == '('))
3758 return false;
3759 prev -= 2;
3760 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3762 else
3763 return false;
3765 /* Count the number of preceding backslashes. */
3766 p = prev;
3767 while (prev - 1 >= pattern && prev[-1] == '\\')
3768 --prev;
3769 return (p - prev) & odd_backslashes;
3773 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3774 at least one character after the $, i.e., `P < PEND'. */
3776 static boolean
3777 at_endline_loc_p (const_re_char *p, const_re_char *pend, reg_syntax_t syntax)
3779 re_char *next = p;
3780 boolean next_backslash = *next == '\\';
3781 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3783 return
3784 /* Before a subexpression? */
3785 (syntax & RE_NO_BK_PARENS ? *next == ')'
3786 : next_backslash && next_next && *next_next == ')')
3787 /* Before an alternative? */
3788 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3789 : next_backslash && next_next && *next_next == '|');
3793 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3794 false if it's not. */
3796 static boolean
3797 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3799 ssize_t this_element;
3801 for (this_element = compile_stack.avail - 1;
3802 this_element >= 0;
3803 this_element--)
3804 if (compile_stack.stack[this_element].regnum == regnum)
3805 return true;
3807 return false;
3810 /* analyze_first.
3811 If fastmap is non-NULL, go through the pattern and fill fastmap
3812 with all the possible leading chars. If fastmap is NULL, don't
3813 bother filling it up (obviously) and only return whether the
3814 pattern could potentially match the empty string.
3816 Return 1 if p..pend might match the empty string.
3817 Return 0 if p..pend matches at least one char.
3818 Return -1 if fastmap was not updated accurately. */
3820 static int
3821 analyze_first (const_re_char *p, const_re_char *pend, char *fastmap,
3822 const int multibyte)
3824 int j, k;
3825 boolean not;
3827 /* If all elements for base leading-codes in fastmap is set, this
3828 flag is set true. */
3829 boolean match_any_multibyte_characters = false;
3831 assert (p);
3833 /* The loop below works as follows:
3834 - It has a working-list kept in the PATTERN_STACK and which basically
3835 starts by only containing a pointer to the first operation.
3836 - If the opcode we're looking at is a match against some set of
3837 chars, then we add those chars to the fastmap and go on to the
3838 next work element from the worklist (done via `break').
3839 - If the opcode is a control operator on the other hand, we either
3840 ignore it (if it's meaningless at this point, such as `start_memory')
3841 or execute it (if it's a jump). If the jump has several destinations
3842 (i.e. `on_failure_jump'), then we push the other destination onto the
3843 worklist.
3844 We guarantee termination by ignoring backward jumps (more or less),
3845 so that `p' is monotonically increasing. More to the point, we
3846 never set `p' (or push) anything `<= p1'. */
3848 while (p < pend)
3850 /* `p1' is used as a marker of how far back a `on_failure_jump'
3851 can go without being ignored. It is normally equal to `p'
3852 (which prevents any backward `on_failure_jump') except right
3853 after a plain `jump', to allow patterns such as:
3854 0: jump 10
3855 3..9: <body>
3856 10: on_failure_jump 3
3857 as used for the *? operator. */
3858 re_char *p1 = p;
3860 switch (*p++)
3862 case succeed:
3863 return 1;
3865 case duplicate:
3866 /* If the first character has to match a backreference, that means
3867 that the group was empty (since it already matched). Since this
3868 is the only case that interests us here, we can assume that the
3869 backreference must match the empty string. */
3870 p++;
3871 continue;
3874 /* Following are the cases which match a character. These end
3875 with `break'. */
3877 case exactn:
3878 if (fastmap)
3880 /* If multibyte is nonzero, the first byte of each
3881 character is an ASCII or a leading code. Otherwise,
3882 each byte is a character. Thus, this works in both
3883 cases. */
3884 fastmap[p[1]] = 1;
3885 if (! multibyte)
3887 /* For the case of matching this unibyte regex
3888 against multibyte, we must set a leading code of
3889 the corresponding multibyte character. */
3890 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3892 fastmap[CHAR_LEADING_CODE (c)] = 1;
3895 break;
3898 case anychar:
3899 /* We could put all the chars except for \n (and maybe \0)
3900 but we don't bother since it is generally not worth it. */
3901 if (!fastmap) break;
3902 return -1;
3905 case charset_not:
3906 if (!fastmap) break;
3908 /* Chars beyond end of bitmap are possible matches. */
3909 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3910 j < (1 << BYTEWIDTH); j++)
3911 fastmap[j] = 1;
3914 /* Fallthrough */
3915 case charset:
3916 if (!fastmap) break;
3917 not = (re_opcode_t) *(p - 1) == charset_not;
3918 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3919 j >= 0; j--)
3920 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3921 fastmap[j] = 1;
3923 #ifdef emacs
3924 if (/* Any leading code can possibly start a character
3925 which doesn't match the specified set of characters. */
3928 /* If we can match a character class, we can match any
3929 multibyte characters. */
3930 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3931 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3934 if (match_any_multibyte_characters == false)
3936 for (j = MIN_MULTIBYTE_LEADING_CODE;
3937 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3938 fastmap[j] = 1;
3939 match_any_multibyte_characters = true;
3943 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3944 && match_any_multibyte_characters == false)
3946 /* Set fastmap[I] to 1 where I is a leading code of each
3947 multibyte character in the range table. */
3948 int c, count;
3949 unsigned char lc1, lc2;
3951 /* Make P points the range table. `+ 2' is to skip flag
3952 bits for a character class. */
3953 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3955 /* Extract the number of ranges in range table into COUNT. */
3956 EXTRACT_NUMBER_AND_INCR (count, p);
3957 for (; count > 0; count--, p += 3)
3959 /* Extract the start and end of each range. */
3960 EXTRACT_CHARACTER (c, p);
3961 lc1 = CHAR_LEADING_CODE (c);
3962 p += 3;
3963 EXTRACT_CHARACTER (c, p);
3964 lc2 = CHAR_LEADING_CODE (c);
3965 for (j = lc1; j <= lc2; j++)
3966 fastmap[j] = 1;
3969 #endif
3970 break;
3972 case syntaxspec:
3973 case notsyntaxspec:
3974 if (!fastmap) break;
3975 #ifndef emacs
3976 not = (re_opcode_t)p[-1] == notsyntaxspec;
3977 k = *p++;
3978 for (j = 0; j < (1 << BYTEWIDTH); j++)
3979 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3980 fastmap[j] = 1;
3981 break;
3982 #else /* emacs */
3983 /* This match depends on text properties. These end with
3984 aborting optimizations. */
3985 return -1;
3987 case categoryspec:
3988 case notcategoryspec:
3989 if (!fastmap) break;
3990 not = (re_opcode_t)p[-1] == notcategoryspec;
3991 k = *p++;
3992 for (j = (1 << BYTEWIDTH); j >= 0; j--)
3993 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3994 fastmap[j] = 1;
3996 /* Any leading code can possibly start a character which
3997 has or doesn't has the specified category. */
3998 if (match_any_multibyte_characters == false)
4000 for (j = MIN_MULTIBYTE_LEADING_CODE;
4001 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4002 fastmap[j] = 1;
4003 match_any_multibyte_characters = true;
4005 break;
4007 /* All cases after this match the empty string. These end with
4008 `continue'. */
4010 case at_dot:
4011 #endif /* !emacs */
4012 case no_op:
4013 case begline:
4014 case endline:
4015 case begbuf:
4016 case endbuf:
4017 case wordbound:
4018 case notwordbound:
4019 case wordbeg:
4020 case wordend:
4021 case symbeg:
4022 case symend:
4023 continue;
4026 case jump:
4027 EXTRACT_NUMBER_AND_INCR (j, p);
4028 if (j < 0)
4029 /* Backward jumps can only go back to code that we've already
4030 visited. `re_compile' should make sure this is true. */
4031 break;
4032 p += j;
4033 switch (*p)
4035 case on_failure_jump:
4036 case on_failure_keep_string_jump:
4037 case on_failure_jump_loop:
4038 case on_failure_jump_nastyloop:
4039 case on_failure_jump_smart:
4040 p++;
4041 break;
4042 default:
4043 continue;
4045 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4046 to jump back to "just after here". */
4047 /* Fallthrough */
4049 case on_failure_jump:
4050 case on_failure_keep_string_jump:
4051 case on_failure_jump_nastyloop:
4052 case on_failure_jump_loop:
4053 case on_failure_jump_smart:
4054 EXTRACT_NUMBER_AND_INCR (j, p);
4055 if (p + j <= p1)
4056 ; /* Backward jump to be ignored. */
4057 else
4058 { /* We have to look down both arms.
4059 We first go down the "straight" path so as to minimize
4060 stack usage when going through alternatives. */
4061 int r = analyze_first (p, pend, fastmap, multibyte);
4062 if (r) return r;
4063 p += j;
4065 continue;
4068 case jump_n:
4069 /* This code simply does not properly handle forward jump_n. */
4070 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4071 p += 4;
4072 /* jump_n can either jump or fall through. The (backward) jump
4073 case has already been handled, so we only need to look at the
4074 fallthrough case. */
4075 continue;
4077 case succeed_n:
4078 /* If N == 0, it should be an on_failure_jump_loop instead. */
4079 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4080 p += 4;
4081 /* We only care about one iteration of the loop, so we don't
4082 need to consider the case where this behaves like an
4083 on_failure_jump. */
4084 continue;
4087 case set_number_at:
4088 p += 4;
4089 continue;
4092 case start_memory:
4093 case stop_memory:
4094 p += 1;
4095 continue;
4098 default:
4099 abort (); /* We have listed all the cases. */
4100 } /* switch *p++ */
4102 /* Getting here means we have found the possible starting
4103 characters for one path of the pattern -- and that the empty
4104 string does not match. We need not follow this path further. */
4105 return 0;
4106 } /* while p */
4108 /* We reached the end without matching anything. */
4109 return 1;
4111 } /* analyze_first */
4113 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4114 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4115 characters can start a string that matches the pattern. This fastmap
4116 is used by re_search to skip quickly over impossible starting points.
4118 Character codes above (1 << BYTEWIDTH) are not represented in the
4119 fastmap, but the leading codes are represented. Thus, the fastmap
4120 indicates which character sets could start a match.
4122 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4123 area as BUFP->fastmap.
4125 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4126 the pattern buffer.
4128 Returns 0 if we succeed, -2 if an internal error. */
4131 re_compile_fastmap (struct re_pattern_buffer *bufp)
4133 char *fastmap = bufp->fastmap;
4134 int analysis;
4136 assert (fastmap && bufp->buffer);
4138 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4139 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4141 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4142 fastmap, RE_MULTIBYTE_P (bufp));
4143 bufp->can_be_null = (analysis != 0);
4144 return 0;
4145 } /* re_compile_fastmap */
4147 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4148 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4149 this memory for recording register information. STARTS and ENDS
4150 must be allocated using the malloc library routine, and must each
4151 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4153 If NUM_REGS == 0, then subsequent matches should allocate their own
4154 register data.
4156 Unless this function is called, the first search or match using
4157 PATTERN_BUFFER will allocate its own register data, without
4158 freeing the old data. */
4160 void
4161 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4163 if (num_regs)
4165 bufp->regs_allocated = REGS_REALLOCATE;
4166 regs->num_regs = num_regs;
4167 regs->start = starts;
4168 regs->end = ends;
4170 else
4172 bufp->regs_allocated = REGS_UNALLOCATED;
4173 regs->num_regs = 0;
4174 regs->start = regs->end = 0;
4177 WEAK_ALIAS (__re_set_registers, re_set_registers)
4179 /* Searching routines. */
4181 /* Like re_search_2, below, but only one string is specified, and
4182 doesn't let you say where to stop matching. */
4184 regoff_t
4185 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4186 ssize_t startpos, ssize_t range, struct re_registers *regs)
4188 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4189 regs, size);
4191 WEAK_ALIAS (__re_search, re_search)
4193 /* Head address of virtual concatenation of string. */
4194 #define HEAD_ADDR_VSTRING(P) \
4195 (((P) >= size1 ? string2 : string1))
4197 /* Address of POS in the concatenation of virtual string. */
4198 #define POS_ADDR_VSTRING(POS) \
4199 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4201 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4202 virtual concatenation of STRING1 and STRING2, starting first at index
4203 STARTPOS, then at STARTPOS + 1, and so on.
4205 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4207 RANGE is how far to scan while trying to match. RANGE = 0 means try
4208 only at STARTPOS; in general, the last start tried is STARTPOS +
4209 RANGE.
4211 In REGS, return the indices of the virtual concatenation of STRING1
4212 and STRING2 that matched the entire BUFP->buffer and its contained
4213 subexpressions.
4215 Do not consider matching one past the index STOP in the virtual
4216 concatenation of STRING1 and STRING2.
4218 We return either the position in the strings at which the match was
4219 found, -1 if no match, or -2 if error (such as failure
4220 stack overflow). */
4222 regoff_t
4223 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4224 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4225 struct re_registers *regs, ssize_t stop)
4227 regoff_t val;
4228 re_char *string1 = (re_char*) str1;
4229 re_char *string2 = (re_char*) str2;
4230 register char *fastmap = bufp->fastmap;
4231 register RE_TRANSLATE_TYPE translate = bufp->translate;
4232 size_t total_size = size1 + size2;
4233 ssize_t endpos = startpos + range;
4234 boolean anchored_start;
4235 /* Nonzero if we are searching multibyte string. */
4236 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4238 /* Check for out-of-range STARTPOS. */
4239 if (startpos < 0 || startpos > total_size)
4240 return -1;
4242 /* Fix up RANGE if it might eventually take us outside
4243 the virtual concatenation of STRING1 and STRING2.
4244 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4245 if (endpos < 0)
4246 range = 0 - startpos;
4247 else if (endpos > total_size)
4248 range = total_size - startpos;
4250 /* If the search isn't to be a backwards one, don't waste time in a
4251 search for a pattern anchored at beginning of buffer. */
4252 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4254 if (startpos > 0)
4255 return -1;
4256 else
4257 range = 0;
4260 #ifdef emacs
4261 /* In a forward search for something that starts with \=.
4262 don't keep searching past point. */
4263 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4265 range = PT_BYTE - BEGV_BYTE - startpos;
4266 if (range < 0)
4267 return -1;
4269 #endif /* emacs */
4271 /* Update the fastmap now if not correct already. */
4272 if (fastmap && !bufp->fastmap_accurate)
4273 re_compile_fastmap (bufp);
4275 /* See whether the pattern is anchored. */
4276 anchored_start = (bufp->buffer[0] == begline);
4278 #ifdef emacs
4279 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4281 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4283 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4285 #endif
4287 /* Loop through the string, looking for a place to start matching. */
4288 for (;;)
4290 /* If the pattern is anchored,
4291 skip quickly past places we cannot match.
4292 We don't bother to treat startpos == 0 specially
4293 because that case doesn't repeat. */
4294 if (anchored_start && startpos > 0)
4296 if (! ((startpos <= size1 ? string1[startpos - 1]
4297 : string2[startpos - size1 - 1])
4298 == '\n'))
4299 goto advance;
4302 /* If a fastmap is supplied, skip quickly over characters that
4303 cannot be the start of a match. If the pattern can match the
4304 null string, however, we don't need to skip characters; we want
4305 the first null string. */
4306 if (fastmap && startpos < total_size && !bufp->can_be_null)
4308 register re_char *d;
4309 register re_wchar_t buf_ch;
4311 d = POS_ADDR_VSTRING (startpos);
4313 if (range > 0) /* Searching forwards. */
4315 ssize_t irange = range, lim = 0;
4317 if (startpos < size1 && startpos + range >= size1)
4318 lim = range - (size1 - startpos);
4320 /* Written out as an if-else to avoid testing `translate'
4321 inside the loop. */
4322 if (RE_TRANSLATE_P (translate))
4324 if (multibyte)
4325 while (range > lim)
4327 int buf_charlen;
4329 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4330 buf_ch = RE_TRANSLATE (translate, buf_ch);
4331 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4332 break;
4334 range -= buf_charlen;
4335 d += buf_charlen;
4337 else
4338 while (range > lim)
4340 register re_wchar_t ch, translated;
4342 buf_ch = *d;
4343 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4344 translated = RE_TRANSLATE (translate, ch);
4345 if (translated != ch
4346 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4347 buf_ch = ch;
4348 if (fastmap[buf_ch])
4349 break;
4350 d++;
4351 range--;
4354 else
4356 if (multibyte)
4357 while (range > lim)
4359 int buf_charlen;
4361 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4362 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4363 break;
4364 range -= buf_charlen;
4365 d += buf_charlen;
4367 else
4368 while (range > lim && !fastmap[*d])
4370 d++;
4371 range--;
4374 startpos += irange - range;
4376 else /* Searching backwards. */
4378 if (multibyte)
4380 buf_ch = STRING_CHAR (d);
4381 buf_ch = TRANSLATE (buf_ch);
4382 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4383 goto advance;
4385 else
4387 register re_wchar_t ch, translated;
4389 buf_ch = *d;
4390 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4391 translated = TRANSLATE (ch);
4392 if (translated != ch
4393 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4394 buf_ch = ch;
4395 if (! fastmap[TRANSLATE (buf_ch)])
4396 goto advance;
4401 /* If can't match the null string, and that's all we have left, fail. */
4402 if (range >= 0 && startpos == total_size && fastmap
4403 && !bufp->can_be_null)
4404 return -1;
4406 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4407 startpos, regs, stop);
4409 if (val >= 0)
4410 return startpos;
4412 if (val == -2)
4413 return -2;
4415 advance:
4416 if (!range)
4417 break;
4418 else if (range > 0)
4420 /* Update STARTPOS to the next character boundary. */
4421 if (multibyte)
4423 re_char *p = POS_ADDR_VSTRING (startpos);
4424 int len = BYTES_BY_CHAR_HEAD (*p);
4426 range -= len;
4427 if (range < 0)
4428 break;
4429 startpos += len;
4431 else
4433 range--;
4434 startpos++;
4437 else
4439 range++;
4440 startpos--;
4442 /* Update STARTPOS to the previous character boundary. */
4443 if (multibyte)
4445 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4446 re_char *p0 = p;
4447 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4449 /* Find the head of multibyte form. */
4450 PREV_CHAR_BOUNDARY (p, phead);
4451 range += p0 - 1 - p;
4452 if (range > 0)
4453 break;
4455 startpos -= p0 - 1 - p;
4459 return -1;
4460 } /* re_search_2 */
4461 WEAK_ALIAS (__re_search_2, re_search_2)
4463 /* Declarations and macros for re_match_2. */
4465 static int bcmp_translate (re_char *s1, re_char *s2,
4466 register ssize_t len,
4467 RE_TRANSLATE_TYPE translate,
4468 const int multibyte);
4470 /* This converts PTR, a pointer into one of the search strings `string1'
4471 and `string2' into an offset from the beginning of that string. */
4472 #define POINTER_TO_OFFSET(ptr) \
4473 (FIRST_STRING_P (ptr) \
4474 ? (ptr) - string1 \
4475 : (ptr) - string2 + (ptrdiff_t) size1)
4477 /* Call before fetching a character with *d. This switches over to
4478 string2 if necessary.
4479 Check re_match_2_internal for a discussion of why end_match_2 might
4480 not be within string2 (but be equal to end_match_1 instead). */
4481 #define PREFETCH() \
4482 while (d == dend) \
4484 /* End of string2 => fail. */ \
4485 if (dend == end_match_2) \
4486 goto fail; \
4487 /* End of string1 => advance to string2. */ \
4488 d = string2; \
4489 dend = end_match_2; \
4492 /* Call before fetching a char with *d if you already checked other limits.
4493 This is meant for use in lookahead operations like wordend, etc..
4494 where we might need to look at parts of the string that might be
4495 outside of the LIMITs (i.e past `stop'). */
4496 #define PREFETCH_NOLIMIT() \
4497 if (d == end1) \
4499 d = string2; \
4500 dend = end_match_2; \
4503 /* Test if at very beginning or at very end of the virtual concatenation
4504 of `string1' and `string2'. If only one string, it's `string2'. */
4505 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4506 #define AT_STRINGS_END(d) ((d) == end2)
4508 /* Disabled due to a compiler bug -- see comment at case wordbound */
4510 /* The comment at case wordbound is following one, but we don't use
4511 AT_WORD_BOUNDARY anymore to support multibyte form.
4513 The DEC Alpha C compiler 3.x generates incorrect code for the
4514 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4515 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4516 macro and introducing temporary variables works around the bug. */
4518 #if 0
4519 /* Test if D points to a character which is word-constituent. We have
4520 two special cases to check for: if past the end of string1, look at
4521 the first character in string2; and if before the beginning of
4522 string2, look at the last character in string1. */
4523 #define WORDCHAR_P(d) \
4524 (SYNTAX ((d) == end1 ? *string2 \
4525 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4526 == Sword)
4528 /* Test if the character before D and the one at D differ with respect
4529 to being word-constituent. */
4530 #define AT_WORD_BOUNDARY(d) \
4531 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4532 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4533 #endif
4535 /* Free everything we malloc. */
4536 #ifdef MATCH_MAY_ALLOCATE
4537 # define FREE_VAR(var) \
4538 do { \
4539 if (var) \
4541 REGEX_FREE (var); \
4542 var = NULL; \
4544 } while (0)
4545 # define FREE_VARIABLES() \
4546 do { \
4547 REGEX_FREE_STACK (fail_stack.stack); \
4548 FREE_VAR (regstart); \
4549 FREE_VAR (regend); \
4550 FREE_VAR (best_regstart); \
4551 FREE_VAR (best_regend); \
4552 REGEX_SAFE_FREE (); \
4553 } while (0)
4554 #else
4555 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4556 #endif /* not MATCH_MAY_ALLOCATE */
4559 /* Optimization routines. */
4561 /* If the operation is a match against one or more chars,
4562 return a pointer to the next operation, else return NULL. */
4563 static re_char *
4564 skip_one_char (const_re_char *p)
4566 switch (*p++)
4568 case anychar:
4569 break;
4571 case exactn:
4572 p += *p + 1;
4573 break;
4575 case charset_not:
4576 case charset:
4577 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4579 int mcnt;
4580 p = CHARSET_RANGE_TABLE (p - 1);
4581 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4582 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4584 else
4585 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4586 break;
4588 case syntaxspec:
4589 case notsyntaxspec:
4590 #ifdef emacs
4591 case categoryspec:
4592 case notcategoryspec:
4593 #endif /* emacs */
4594 p++;
4595 break;
4597 default:
4598 p = NULL;
4600 return p;
4604 /* Jump over non-matching operations. */
4605 static re_char *
4606 skip_noops (const_re_char *p, const_re_char *pend)
4608 int mcnt;
4609 while (p < pend)
4611 switch (*p)
4613 case start_memory:
4614 case stop_memory:
4615 p += 2; break;
4616 case no_op:
4617 p += 1; break;
4618 case jump:
4619 p += 1;
4620 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4621 p += mcnt;
4622 break;
4623 default:
4624 return p;
4627 assert (p == pend);
4628 return p;
4631 /* Test if C matches charset op. *PP points to the charset or charset_not
4632 opcode. When the function finishes, *PP will be advanced past that opcode.
4633 C is character to test (possibly after translations) and CORIG is original
4634 character (i.e. without any translations). UNIBYTE denotes whether c is
4635 unibyte or multibyte character. */
4636 static bool
4637 execute_charset (const_re_char **pp, unsigned c, unsigned corig, bool unibyte)
4639 re_char *p = *pp, *rtp = NULL;
4640 bool not = (re_opcode_t) *p == charset_not;
4642 if (CHARSET_RANGE_TABLE_EXISTS_P (p))
4644 int count;
4645 rtp = CHARSET_RANGE_TABLE (p);
4646 EXTRACT_NUMBER_AND_INCR (count, rtp);
4647 *pp = CHARSET_RANGE_TABLE_END ((rtp), (count));
4649 else
4650 *pp += 2 + CHARSET_BITMAP_SIZE (p);
4652 if (unibyte && c < (1 << BYTEWIDTH))
4653 { /* Lookup bitmap. */
4654 /* Cast to `unsigned' instead of `unsigned char' in
4655 case the bit list is a full 32 bytes long. */
4656 if (c < (unsigned) (CHARSET_BITMAP_SIZE (p) * BYTEWIDTH)
4657 && p[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4658 return !not;
4660 #ifdef emacs
4661 else if (rtp)
4663 int class_bits = CHARSET_RANGE_TABLE_BITS (p);
4664 re_wchar_t range_start, range_end;
4666 /* Sort tests by the most commonly used classes with some adjustment to which
4667 tests are easiest to perform. Take a look at comment in re_wctype_parse
4668 for table with frequencies of character class names. */
4670 if ((class_bits & BIT_MULTIBYTE) ||
4671 (class_bits & BIT_ALNUM && ISALNUM (c)) ||
4672 (class_bits & BIT_ALPHA && ISALPHA (c)) ||
4673 (class_bits & BIT_SPACE && ISSPACE (c)) ||
4674 (class_bits & BIT_BLANK && ISBLANK (c)) ||
4675 (class_bits & BIT_WORD && ISWORD (c)) ||
4676 ((class_bits & BIT_UPPER) &&
4677 (ISUPPER (c) || (corig != c &&
4678 c == downcase (corig) && ISLOWER (c)))) ||
4679 ((class_bits & BIT_LOWER) &&
4680 (ISLOWER (c) || (corig != c &&
4681 c == upcase (corig) && ISUPPER(c)))) ||
4682 (class_bits & BIT_PUNCT && ISPUNCT (c)) ||
4683 (class_bits & BIT_GRAPH && ISGRAPH (c)) ||
4684 (class_bits & BIT_PRINT && ISPRINT (c)))
4685 return !not;
4687 for (p = *pp; rtp < p; rtp += 2 * 3)
4689 EXTRACT_CHARACTER (range_start, rtp);
4690 EXTRACT_CHARACTER (range_end, rtp + 3);
4691 if (range_start <= c && c <= range_end)
4692 return !not;
4695 #endif /* emacs */
4696 return not;
4699 /* Non-zero if "p1 matches something" implies "p2 fails". */
4700 static int
4701 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4702 const_re_char *p2)
4704 re_opcode_t op2;
4705 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4706 unsigned char *pend = bufp->buffer + bufp->used;
4708 assert (p1 >= bufp->buffer && p1 < pend
4709 && p2 >= bufp->buffer && p2 <= pend);
4711 /* Skip over open/close-group commands.
4712 If what follows this loop is a ...+ construct,
4713 look at what begins its body, since we will have to
4714 match at least one of that. */
4715 p2 = skip_noops (p2, pend);
4716 /* The same skip can be done for p1, except that this function
4717 is only used in the case where p1 is a simple match operator. */
4718 /* p1 = skip_noops (p1, pend); */
4720 assert (p1 >= bufp->buffer && p1 < pend
4721 && p2 >= bufp->buffer && p2 <= pend);
4723 op2 = p2 == pend ? succeed : *p2;
4725 switch (op2)
4727 case succeed:
4728 case endbuf:
4729 /* If we're at the end of the pattern, we can change. */
4730 if (skip_one_char (p1))
4732 DEBUG_PRINT (" End of pattern: fast loop.\n");
4733 return 1;
4735 break;
4737 case endline:
4738 case exactn:
4740 register re_wchar_t c
4741 = (re_opcode_t) *p2 == endline ? '\n'
4742 : RE_STRING_CHAR (p2 + 2, multibyte);
4744 if ((re_opcode_t) *p1 == exactn)
4746 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4748 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4749 return 1;
4753 else if ((re_opcode_t) *p1 == charset
4754 || (re_opcode_t) *p1 == charset_not)
4756 if (!execute_charset (&p1, c, c, !multibyte || IS_REAL_ASCII (c)))
4758 DEBUG_PRINT (" No match => fast loop.\n");
4759 return 1;
4762 else if ((re_opcode_t) *p1 == anychar
4763 && c == '\n')
4765 DEBUG_PRINT (" . != \\n => fast loop.\n");
4766 return 1;
4769 break;
4771 case charset:
4773 if ((re_opcode_t) *p1 == exactn)
4774 /* Reuse the code above. */
4775 return mutually_exclusive_p (bufp, p2, p1);
4777 /* It is hard to list up all the character in charset
4778 P2 if it includes multibyte character. Give up in
4779 such case. */
4780 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4782 /* Now, we are sure that P2 has no range table.
4783 So, for the size of bitmap in P2, `p2[1]' is
4784 enough. But P1 may have range table, so the
4785 size of bitmap table of P1 is extracted by
4786 using macro `CHARSET_BITMAP_SIZE'.
4788 In a multibyte case, we know that all the character
4789 listed in P2 is ASCII. In a unibyte case, P1 has only a
4790 bitmap table. So, in both cases, it is enough to test
4791 only the bitmap table of P1. */
4793 if ((re_opcode_t) *p1 == charset)
4795 int idx;
4796 /* We win if the charset inside the loop
4797 has no overlap with the one after the loop. */
4798 for (idx = 0;
4799 (idx < (int) p2[1]
4800 && idx < CHARSET_BITMAP_SIZE (p1));
4801 idx++)
4802 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4803 break;
4805 if (idx == p2[1]
4806 || idx == CHARSET_BITMAP_SIZE (p1))
4808 DEBUG_PRINT (" No match => fast loop.\n");
4809 return 1;
4812 else if ((re_opcode_t) *p1 == charset_not)
4814 int idx;
4815 /* We win if the charset_not inside the loop lists
4816 every character listed in the charset after. */
4817 for (idx = 0; idx < (int) p2[1]; idx++)
4818 if (! (p2[2 + idx] == 0
4819 || (idx < CHARSET_BITMAP_SIZE (p1)
4820 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4821 break;
4823 if (idx == p2[1])
4825 DEBUG_PRINT (" No match => fast loop.\n");
4826 return 1;
4831 break;
4833 case charset_not:
4834 switch (*p1)
4836 case exactn:
4837 case charset:
4838 /* Reuse the code above. */
4839 return mutually_exclusive_p (bufp, p2, p1);
4840 case charset_not:
4841 /* When we have two charset_not, it's very unlikely that
4842 they don't overlap. The union of the two sets of excluded
4843 chars should cover all possible chars, which, as a matter of
4844 fact, is virtually impossible in multibyte buffers. */
4845 break;
4847 break;
4849 case wordend:
4850 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4851 case symend:
4852 return ((re_opcode_t) *p1 == syntaxspec
4853 && (p1[1] == Ssymbol || p1[1] == Sword));
4854 case notsyntaxspec:
4855 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4857 case wordbeg:
4858 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4859 case symbeg:
4860 return ((re_opcode_t) *p1 == notsyntaxspec
4861 && (p1[1] == Ssymbol || p1[1] == Sword));
4862 case syntaxspec:
4863 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4865 case wordbound:
4866 return (((re_opcode_t) *p1 == notsyntaxspec
4867 || (re_opcode_t) *p1 == syntaxspec)
4868 && p1[1] == Sword);
4870 #ifdef emacs
4871 case categoryspec:
4872 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4873 case notcategoryspec:
4874 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4875 #endif /* emacs */
4877 default:
4881 /* Safe default. */
4882 return 0;
4886 /* Matching routines. */
4888 #ifndef emacs /* Emacs never uses this. */
4889 /* re_match is like re_match_2 except it takes only a single string. */
4891 regoff_t
4892 re_match (struct re_pattern_buffer *bufp, const char *string,
4893 size_t size, ssize_t pos, struct re_registers *regs)
4895 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4896 size, pos, regs, size);
4897 return result;
4899 WEAK_ALIAS (__re_match, re_match)
4900 #endif /* not emacs */
4902 /* re_match_2 matches the compiled pattern in BUFP against the
4903 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4904 and SIZE2, respectively). We start matching at POS, and stop
4905 matching at STOP.
4907 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4908 store offsets for the substring each group matched in REGS. See the
4909 documentation for exactly how many groups we fill.
4911 We return -1 if no match, -2 if an internal error (such as the
4912 failure stack overflowing). Otherwise, we return the length of the
4913 matched substring. */
4915 regoff_t
4916 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4917 size_t size1, const char *string2, size_t size2, ssize_t pos,
4918 struct re_registers *regs, ssize_t stop)
4920 regoff_t result;
4922 #ifdef emacs
4923 ssize_t charpos;
4924 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4925 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4926 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4927 #endif
4929 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4930 (re_char*) string2, size2,
4931 pos, regs, stop);
4932 return result;
4934 WEAK_ALIAS (__re_match_2, re_match_2)
4937 /* This is a separate function so that we can force an alloca cleanup
4938 afterwards. */
4939 static regoff_t
4940 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4941 size_t size1, const_re_char *string2, size_t size2,
4942 ssize_t pos, struct re_registers *regs, ssize_t stop)
4944 /* General temporaries. */
4945 int mcnt;
4946 size_t reg;
4948 /* Just past the end of the corresponding string. */
4949 re_char *end1, *end2;
4951 /* Pointers into string1 and string2, just past the last characters in
4952 each to consider matching. */
4953 re_char *end_match_1, *end_match_2;
4955 /* Where we are in the data, and the end of the current string. */
4956 re_char *d, *dend;
4958 /* Used sometimes to remember where we were before starting matching
4959 an operator so that we can go back in case of failure. This "atomic"
4960 behavior of matching opcodes is indispensable to the correctness
4961 of the on_failure_keep_string_jump optimization. */
4962 re_char *dfail;
4964 /* Where we are in the pattern, and the end of the pattern. */
4965 re_char *p = bufp->buffer;
4966 re_char *pend = p + bufp->used;
4968 /* We use this to map every character in the string. */
4969 RE_TRANSLATE_TYPE translate = bufp->translate;
4971 /* Nonzero if BUFP is setup from a multibyte regex. */
4972 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4974 /* Nonzero if STRING1/STRING2 are multibyte. */
4975 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4977 /* Failure point stack. Each place that can handle a failure further
4978 down the line pushes a failure point on this stack. It consists of
4979 regstart, and regend for all registers corresponding to
4980 the subexpressions we're currently inside, plus the number of such
4981 registers, and, finally, two char *'s. The first char * is where
4982 to resume scanning the pattern; the second one is where to resume
4983 scanning the strings. */
4984 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4985 fail_stack_type fail_stack;
4986 #endif
4987 #ifdef DEBUG_COMPILES_ARGUMENTS
4988 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4989 #endif
4991 #if defined REL_ALLOC && defined REGEX_MALLOC
4992 /* This holds the pointer to the failure stack, when
4993 it is allocated relocatably. */
4994 fail_stack_elt_t *failure_stack_ptr;
4995 #endif
4997 /* We fill all the registers internally, independent of what we
4998 return, for use in backreferences. The number here includes
4999 an element for register zero. */
5000 size_t num_regs = bufp->re_nsub + 1;
5002 /* Information on the contents of registers. These are pointers into
5003 the input strings; they record just what was matched (on this
5004 attempt) by a subexpression part of the pattern, that is, the
5005 regnum-th regstart pointer points to where in the pattern we began
5006 matching and the regnum-th regend points to right after where we
5007 stopped matching the regnum-th subexpression. (The zeroth register
5008 keeps track of what the whole pattern matches.) */
5009 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5010 re_char **regstart, **regend;
5011 #endif
5013 /* The following record the register info as found in the above
5014 variables when we find a match better than any we've seen before.
5015 This happens as we backtrack through the failure points, which in
5016 turn happens only if we have not yet matched the entire string. */
5017 unsigned best_regs_set = false;
5018 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5019 re_char **best_regstart, **best_regend;
5020 #endif
5022 /* Logically, this is `best_regend[0]'. But we don't want to have to
5023 allocate space for that if we're not allocating space for anything
5024 else (see below). Also, we never need info about register 0 for
5025 any of the other register vectors, and it seems rather a kludge to
5026 treat `best_regend' differently than the rest. So we keep track of
5027 the end of the best match so far in a separate variable. We
5028 initialize this to NULL so that when we backtrack the first time
5029 and need to test it, it's not garbage. */
5030 re_char *match_end = NULL;
5032 #ifdef DEBUG_COMPILES_ARGUMENTS
5033 /* Counts the total number of registers pushed. */
5034 unsigned num_regs_pushed = 0;
5035 #endif
5037 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5039 REGEX_USE_SAFE_ALLOCA;
5041 INIT_FAIL_STACK ();
5043 #ifdef MATCH_MAY_ALLOCATE
5044 /* Do not bother to initialize all the register variables if there are
5045 no groups in the pattern, as it takes a fair amount of time. If
5046 there are groups, we include space for register 0 (the whole
5047 pattern), even though we never use it, since it simplifies the
5048 array indexing. We should fix this. */
5049 if (bufp->re_nsub)
5051 regstart = REGEX_TALLOC (num_regs, re_char *);
5052 regend = REGEX_TALLOC (num_regs, re_char *);
5053 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5054 best_regend = REGEX_TALLOC (num_regs, re_char *);
5056 if (!(regstart && regend && best_regstart && best_regend))
5058 FREE_VARIABLES ();
5059 return -2;
5062 else
5064 /* We must initialize all our variables to NULL, so that
5065 `FREE_VARIABLES' doesn't try to free them. */
5066 regstart = regend = best_regstart = best_regend = NULL;
5068 #endif /* MATCH_MAY_ALLOCATE */
5070 /* The starting position is bogus. */
5071 if (pos < 0 || pos > size1 + size2)
5073 FREE_VARIABLES ();
5074 return -1;
5077 /* Initialize subexpression text positions to -1 to mark ones that no
5078 start_memory/stop_memory has been seen for. Also initialize the
5079 register information struct. */
5080 for (reg = 1; reg < num_regs; reg++)
5081 regstart[reg] = regend[reg] = NULL;
5083 /* We move `string1' into `string2' if the latter's empty -- but not if
5084 `string1' is null. */
5085 if (size2 == 0 && string1 != NULL)
5087 string2 = string1;
5088 size2 = size1;
5089 string1 = 0;
5090 size1 = 0;
5092 end1 = string1 + size1;
5093 end2 = string2 + size2;
5095 /* `p' scans through the pattern as `d' scans through the data.
5096 `dend' is the end of the input string that `d' points within. `d'
5097 is advanced into the following input string whenever necessary, but
5098 this happens before fetching; therefore, at the beginning of the
5099 loop, `d' can be pointing at the end of a string, but it cannot
5100 equal `string2'. */
5101 if (pos >= size1)
5103 /* Only match within string2. */
5104 d = string2 + pos - size1;
5105 dend = end_match_2 = string2 + stop - size1;
5106 end_match_1 = end1; /* Just to give it a value. */
5108 else
5110 if (stop < size1)
5112 /* Only match within string1. */
5113 end_match_1 = string1 + stop;
5114 /* BEWARE!
5115 When we reach end_match_1, PREFETCH normally switches to string2.
5116 But in the present case, this means that just doing a PREFETCH
5117 makes us jump from `stop' to `gap' within the string.
5118 What we really want here is for the search to stop as
5119 soon as we hit end_match_1. That's why we set end_match_2
5120 to end_match_1 (since PREFETCH fails as soon as we hit
5121 end_match_2). */
5122 end_match_2 = end_match_1;
5124 else
5125 { /* It's important to use this code when stop == size so that
5126 moving `d' from end1 to string2 will not prevent the d == dend
5127 check from catching the end of string. */
5128 end_match_1 = end1;
5129 end_match_2 = string2 + stop - size1;
5131 d = string1 + pos;
5132 dend = end_match_1;
5135 DEBUG_PRINT ("The compiled pattern is: ");
5136 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5137 DEBUG_PRINT ("The string to match is: \"");
5138 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5139 DEBUG_PRINT ("\"\n");
5141 /* This loops over pattern commands. It exits by returning from the
5142 function if the match is complete, or it drops through if the match
5143 fails at this starting point in the input data. */
5144 for (;;)
5146 DEBUG_PRINT ("\n%p: ", p);
5148 if (p == pend)
5150 /* End of pattern means we might have succeeded. */
5151 DEBUG_PRINT ("end of pattern ... ");
5153 /* If we haven't matched the entire string, and we want the
5154 longest match, try backtracking. */
5155 if (d != end_match_2)
5157 /* True if this match is the best seen so far. */
5158 bool best_match_p;
5161 /* True if this match ends in the same string (string1
5162 or string2) as the best previous match. */
5163 bool same_str_p = (FIRST_STRING_P (match_end)
5164 == FIRST_STRING_P (d));
5166 /* AIX compiler got confused when this was combined
5167 with the previous declaration. */
5168 if (same_str_p)
5169 best_match_p = d > match_end;
5170 else
5171 best_match_p = !FIRST_STRING_P (d);
5174 DEBUG_PRINT ("backtracking.\n");
5176 if (!FAIL_STACK_EMPTY ())
5177 { /* More failure points to try. */
5179 /* If exceeds best match so far, save it. */
5180 if (!best_regs_set || best_match_p)
5182 best_regs_set = true;
5183 match_end = d;
5185 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5187 for (reg = 1; reg < num_regs; reg++)
5189 best_regstart[reg] = regstart[reg];
5190 best_regend[reg] = regend[reg];
5193 goto fail;
5196 /* If no failure points, don't restore garbage. And if
5197 last match is real best match, don't restore second
5198 best one. */
5199 else if (best_regs_set && !best_match_p)
5201 restore_best_regs:
5202 /* Restore best match. It may happen that `dend ==
5203 end_match_1' while the restored d is in string2.
5204 For example, the pattern `x.*y.*z' against the
5205 strings `x-' and `y-z-', if the two strings are
5206 not consecutive in memory. */
5207 DEBUG_PRINT ("Restoring best registers.\n");
5209 d = match_end;
5210 dend = ((d >= string1 && d <= end1)
5211 ? end_match_1 : end_match_2);
5213 for (reg = 1; reg < num_regs; reg++)
5215 regstart[reg] = best_regstart[reg];
5216 regend[reg] = best_regend[reg];
5219 } /* d != end_match_2 */
5221 succeed_label:
5222 DEBUG_PRINT ("Accepting match.\n");
5224 /* If caller wants register contents data back, do it. */
5225 if (regs && !bufp->no_sub)
5227 /* Have the register data arrays been allocated? */
5228 if (bufp->regs_allocated == REGS_UNALLOCATED)
5229 { /* No. So allocate them with malloc. We need one
5230 extra element beyond `num_regs' for the `-1' marker
5231 GNU code uses. */
5232 regs->num_regs = max (RE_NREGS, num_regs + 1);
5233 regs->start = TALLOC (regs->num_regs, regoff_t);
5234 regs->end = TALLOC (regs->num_regs, regoff_t);
5235 if (regs->start == NULL || regs->end == NULL)
5237 FREE_VARIABLES ();
5238 return -2;
5240 bufp->regs_allocated = REGS_REALLOCATE;
5242 else if (bufp->regs_allocated == REGS_REALLOCATE)
5243 { /* Yes. If we need more elements than were already
5244 allocated, reallocate them. If we need fewer, just
5245 leave it alone. */
5246 if (regs->num_regs < num_regs + 1)
5248 regs->num_regs = num_regs + 1;
5249 RETALLOC (regs->start, regs->num_regs, regoff_t);
5250 RETALLOC (regs->end, regs->num_regs, regoff_t);
5251 if (regs->start == NULL || regs->end == NULL)
5253 FREE_VARIABLES ();
5254 return -2;
5258 else
5260 /* These braces fend off a "empty body in an else-statement"
5261 warning under GCC when assert expands to nothing. */
5262 assert (bufp->regs_allocated == REGS_FIXED);
5265 /* Convert the pointer data in `regstart' and `regend' to
5266 indices. Register zero has to be set differently,
5267 since we haven't kept track of any info for it. */
5268 if (regs->num_regs > 0)
5270 regs->start[0] = pos;
5271 regs->end[0] = POINTER_TO_OFFSET (d);
5274 /* Go through the first `min (num_regs, regs->num_regs)'
5275 registers, since that is all we initialized. */
5276 for (reg = 1; reg < min (num_regs, regs->num_regs); reg++)
5278 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5279 regs->start[reg] = regs->end[reg] = -1;
5280 else
5282 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5283 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5287 /* If the regs structure we return has more elements than
5288 were in the pattern, set the extra elements to -1. If
5289 we (re)allocated the registers, this is the case,
5290 because we always allocate enough to have at least one
5291 -1 at the end. */
5292 for (reg = num_regs; reg < regs->num_regs; reg++)
5293 regs->start[reg] = regs->end[reg] = -1;
5294 } /* regs && !bufp->no_sub */
5296 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5297 nfailure_points_pushed, nfailure_points_popped,
5298 nfailure_points_pushed - nfailure_points_popped);
5299 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5301 ptrdiff_t dcnt = POINTER_TO_OFFSET (d) - pos;
5303 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5305 FREE_VARIABLES ();
5306 return dcnt;
5309 /* Otherwise match next pattern command. */
5310 switch (*p++)
5312 /* Ignore these. Used to ignore the n of succeed_n's which
5313 currently have n == 0. */
5314 case no_op:
5315 DEBUG_PRINT ("EXECUTING no_op.\n");
5316 break;
5318 case succeed:
5319 DEBUG_PRINT ("EXECUTING succeed.\n");
5320 goto succeed_label;
5322 /* Match the next n pattern characters exactly. The following
5323 byte in the pattern defines n, and the n bytes after that
5324 are the characters to match. */
5325 case exactn:
5326 mcnt = *p++;
5327 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5329 /* Remember the start point to rollback upon failure. */
5330 dfail = d;
5332 #ifndef emacs
5333 /* This is written out as an if-else so we don't waste time
5334 testing `translate' inside the loop. */
5335 if (RE_TRANSLATE_P (translate))
5338 PREFETCH ();
5339 if (RE_TRANSLATE (translate, *d) != *p++)
5341 d = dfail;
5342 goto fail;
5344 d++;
5346 while (--mcnt);
5347 else
5350 PREFETCH ();
5351 if (*d++ != *p++)
5353 d = dfail;
5354 goto fail;
5357 while (--mcnt);
5358 #else /* emacs */
5359 /* The cost of testing `translate' is comparatively small. */
5360 if (target_multibyte)
5363 int pat_charlen, buf_charlen;
5364 int pat_ch, buf_ch;
5366 PREFETCH ();
5367 if (multibyte)
5368 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5369 else
5371 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5372 pat_charlen = 1;
5374 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5376 if (TRANSLATE (buf_ch) != pat_ch)
5378 d = dfail;
5379 goto fail;
5382 p += pat_charlen;
5383 d += buf_charlen;
5384 mcnt -= pat_charlen;
5386 while (mcnt > 0);
5387 else
5390 int pat_charlen;
5391 int pat_ch, buf_ch;
5393 PREFETCH ();
5394 if (multibyte)
5396 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5397 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5399 else
5401 pat_ch = *p;
5402 pat_charlen = 1;
5404 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5405 if (! CHAR_BYTE8_P (buf_ch))
5407 buf_ch = TRANSLATE (buf_ch);
5408 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5409 if (buf_ch < 0)
5410 buf_ch = *d;
5412 else
5413 buf_ch = *d;
5414 if (buf_ch != pat_ch)
5416 d = dfail;
5417 goto fail;
5419 p += pat_charlen;
5420 d++;
5422 while (--mcnt);
5423 #endif
5424 break;
5427 /* Match any character except possibly a newline or a null. */
5428 case anychar:
5430 int buf_charlen;
5431 re_wchar_t buf_ch;
5432 reg_syntax_t syntax;
5434 DEBUG_PRINT ("EXECUTING anychar.\n");
5436 PREFETCH ();
5437 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5438 target_multibyte);
5439 buf_ch = TRANSLATE (buf_ch);
5441 #ifdef emacs
5442 syntax = RE_SYNTAX_EMACS;
5443 #else
5444 syntax = bufp->syntax;
5445 #endif
5447 if ((!(syntax & RE_DOT_NEWLINE) && buf_ch == '\n')
5448 || ((syntax & RE_DOT_NOT_NULL) && buf_ch == '\000'))
5449 goto fail;
5451 DEBUG_PRINT (" Matched \"%d\".\n", *d);
5452 d += buf_charlen;
5454 break;
5457 case charset:
5458 case charset_not:
5460 register unsigned int c, corig;
5461 int len;
5463 /* Whether matching against a unibyte character. */
5464 boolean unibyte_char = false;
5466 DEBUG_PRINT ("EXECUTING charset%s.\n",
5467 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
5469 PREFETCH ();
5470 corig = c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5471 if (target_multibyte)
5473 int c1;
5475 c = TRANSLATE (c);
5476 c1 = RE_CHAR_TO_UNIBYTE (c);
5477 if (c1 >= 0)
5479 unibyte_char = true;
5480 c = c1;
5483 else
5485 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5487 if (! CHAR_BYTE8_P (c1))
5489 c1 = TRANSLATE (c1);
5490 c1 = RE_CHAR_TO_UNIBYTE (c1);
5491 if (c1 >= 0)
5493 unibyte_char = true;
5494 c = c1;
5497 else
5498 unibyte_char = true;
5501 p -= 1;
5502 if (!execute_charset (&p, c, corig, unibyte_char))
5503 goto fail;
5505 d += len;
5507 break;
5510 /* The beginning of a group is represented by start_memory.
5511 The argument is the register number. The text
5512 matched within the group is recorded (in the internal
5513 registers data structure) under the register number. */
5514 case start_memory:
5515 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5517 /* In case we need to undo this operation (via backtracking). */
5518 PUSH_FAILURE_REG (*p);
5520 regstart[*p] = d;
5521 regend[*p] = NULL; /* probably unnecessary. -sm */
5522 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5524 /* Move past the register number and inner group count. */
5525 p += 1;
5526 break;
5529 /* The stop_memory opcode represents the end of a group. Its
5530 argument is the same as start_memory's: the register number. */
5531 case stop_memory:
5532 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5534 assert (!REG_UNSET (regstart[*p]));
5535 /* Strictly speaking, there should be code such as:
5537 assert (REG_UNSET (regend[*p]));
5538 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5540 But the only info to be pushed is regend[*p] and it is known to
5541 be UNSET, so there really isn't anything to push.
5542 Not pushing anything, on the other hand deprives us from the
5543 guarantee that regend[*p] is UNSET since undoing this operation
5544 will not reset its value properly. This is not important since
5545 the value will only be read on the next start_memory or at
5546 the very end and both events can only happen if this stop_memory
5547 is *not* undone. */
5549 regend[*p] = d;
5550 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5552 /* Move past the register number and the inner group count. */
5553 p += 1;
5554 break;
5557 /* \<digit> has been turned into a `duplicate' command which is
5558 followed by the numeric value of <digit> as the register number. */
5559 case duplicate:
5561 register re_char *d2, *dend2;
5562 int regno = *p++; /* Get which register to match against. */
5563 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5565 /* Can't back reference a group which we've never matched. */
5566 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5567 goto fail;
5569 /* Where in input to try to start matching. */
5570 d2 = regstart[regno];
5572 /* Remember the start point to rollback upon failure. */
5573 dfail = d;
5575 /* Where to stop matching; if both the place to start and
5576 the place to stop matching are in the same string, then
5577 set to the place to stop, otherwise, for now have to use
5578 the end of the first string. */
5580 dend2 = ((FIRST_STRING_P (regstart[regno])
5581 == FIRST_STRING_P (regend[regno]))
5582 ? regend[regno] : end_match_1);
5583 for (;;)
5585 ptrdiff_t dcnt;
5587 /* If necessary, advance to next segment in register
5588 contents. */
5589 while (d2 == dend2)
5591 if (dend2 == end_match_2) break;
5592 if (dend2 == regend[regno]) break;
5594 /* End of string1 => advance to string2. */
5595 d2 = string2;
5596 dend2 = regend[regno];
5598 /* At end of register contents => success */
5599 if (d2 == dend2) break;
5601 /* If necessary, advance to next segment in data. */
5602 PREFETCH ();
5604 /* How many characters left in this segment to match. */
5605 dcnt = dend - d;
5607 /* Want how many consecutive characters we can match in
5608 one shot, so, if necessary, adjust the count. */
5609 if (dcnt > dend2 - d2)
5610 dcnt = dend2 - d2;
5612 /* Compare that many; failure if mismatch, else move
5613 past them. */
5614 if (RE_TRANSLATE_P (translate)
5615 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5616 : memcmp (d, d2, dcnt))
5618 d = dfail;
5619 goto fail;
5621 d += dcnt, d2 += dcnt;
5624 break;
5627 /* begline matches the empty string at the beginning of the string
5628 (unless `not_bol' is set in `bufp'), and after newlines. */
5629 case begline:
5630 DEBUG_PRINT ("EXECUTING begline.\n");
5632 if (AT_STRINGS_BEG (d))
5634 if (!bufp->not_bol) break;
5636 else
5638 unsigned c;
5639 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5640 if (c == '\n')
5641 break;
5643 /* In all other cases, we fail. */
5644 goto fail;
5647 /* endline is the dual of begline. */
5648 case endline:
5649 DEBUG_PRINT ("EXECUTING endline.\n");
5651 if (AT_STRINGS_END (d))
5653 if (!bufp->not_eol) break;
5655 else
5657 PREFETCH_NOLIMIT ();
5658 if (*d == '\n')
5659 break;
5661 goto fail;
5664 /* Match at the very beginning of the data. */
5665 case begbuf:
5666 DEBUG_PRINT ("EXECUTING begbuf.\n");
5667 if (AT_STRINGS_BEG (d))
5668 break;
5669 goto fail;
5672 /* Match at the very end of the data. */
5673 case endbuf:
5674 DEBUG_PRINT ("EXECUTING endbuf.\n");
5675 if (AT_STRINGS_END (d))
5676 break;
5677 goto fail;
5680 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5681 pushes NULL as the value for the string on the stack. Then
5682 `POP_FAILURE_POINT' will keep the current value for the
5683 string, instead of restoring it. To see why, consider
5684 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5685 then the . fails against the \n. But the next thing we want
5686 to do is match the \n against the \n; if we restored the
5687 string value, we would be back at the foo.
5689 Because this is used only in specific cases, we don't need to
5690 check all the things that `on_failure_jump' does, to make
5691 sure the right things get saved on the stack. Hence we don't
5692 share its code. The only reason to push anything on the
5693 stack at all is that otherwise we would have to change
5694 `anychar's code to do something besides goto fail in this
5695 case; that seems worse than this. */
5696 case on_failure_keep_string_jump:
5697 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5698 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5699 mcnt, p + mcnt);
5701 PUSH_FAILURE_POINT (p - 3, NULL);
5702 break;
5704 /* A nasty loop is introduced by the non-greedy *? and +?.
5705 With such loops, the stack only ever contains one failure point
5706 at a time, so that a plain on_failure_jump_loop kind of
5707 cycle detection cannot work. Worse yet, such a detection
5708 can not only fail to detect a cycle, but it can also wrongly
5709 detect a cycle (between different instantiations of the same
5710 loop).
5711 So the method used for those nasty loops is a little different:
5712 We use a special cycle-detection-stack-frame which is pushed
5713 when the on_failure_jump_nastyloop failure-point is *popped*.
5714 This special frame thus marks the beginning of one iteration
5715 through the loop and we can hence easily check right here
5716 whether something matched between the beginning and the end of
5717 the loop. */
5718 case on_failure_jump_nastyloop:
5719 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5720 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5721 mcnt, p + mcnt);
5723 assert ((re_opcode_t)p[-4] == no_op);
5725 int cycle = 0;
5726 CHECK_INFINITE_LOOP (p - 4, d);
5727 if (!cycle)
5728 /* If there's a cycle, just continue without pushing
5729 this failure point. The failure point is the "try again"
5730 option, which shouldn't be tried.
5731 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5732 PUSH_FAILURE_POINT (p - 3, d);
5734 break;
5736 /* Simple loop detecting on_failure_jump: just check on the
5737 failure stack if the same spot was already hit earlier. */
5738 case on_failure_jump_loop:
5739 on_failure:
5740 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5741 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5742 mcnt, p + mcnt);
5744 int cycle = 0;
5745 CHECK_INFINITE_LOOP (p - 3, d);
5746 if (cycle)
5747 /* If there's a cycle, get out of the loop, as if the matching
5748 had failed. We used to just `goto fail' here, but that was
5749 aborting the search a bit too early: we want to keep the
5750 empty-loop-match and keep matching after the loop.
5751 We want (x?)*y\1z to match both xxyz and xxyxz. */
5752 p += mcnt;
5753 else
5754 PUSH_FAILURE_POINT (p - 3, d);
5756 break;
5759 /* Uses of on_failure_jump:
5761 Each alternative starts with an on_failure_jump that points
5762 to the beginning of the next alternative. Each alternative
5763 except the last ends with a jump that in effect jumps past
5764 the rest of the alternatives. (They really jump to the
5765 ending jump of the following alternative, because tensioning
5766 these jumps is a hassle.)
5768 Repeats start with an on_failure_jump that points past both
5769 the repetition text and either the following jump or
5770 pop_failure_jump back to this on_failure_jump. */
5771 case on_failure_jump:
5772 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5773 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5774 mcnt, p + mcnt);
5776 PUSH_FAILURE_POINT (p -3, d);
5777 break;
5779 /* This operation is used for greedy *.
5780 Compare the beginning of the repeat with what in the
5781 pattern follows its end. If we can establish that there
5782 is nothing that they would both match, i.e., that we
5783 would have to backtrack because of (as in, e.g., `a*a')
5784 then we can use a non-backtracking loop based on
5785 on_failure_keep_string_jump instead of on_failure_jump. */
5786 case on_failure_jump_smart:
5787 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5788 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5789 mcnt, p + mcnt);
5791 re_char *p1 = p; /* Next operation. */
5792 /* Here, we discard `const', making re_match non-reentrant. */
5793 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5794 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5796 p -= 3; /* Reset so that we will re-execute the
5797 instruction once it's been changed. */
5799 EXTRACT_NUMBER (mcnt, p2 - 2);
5801 /* Ensure this is a indeed the trivial kind of loop
5802 we are expecting. */
5803 assert (skip_one_char (p1) == p2 - 3);
5804 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5805 DEBUG_STATEMENT (debug += 2);
5806 if (mutually_exclusive_p (bufp, p1, p2))
5808 /* Use a fast `on_failure_keep_string_jump' loop. */
5809 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5810 *p3 = (unsigned char) on_failure_keep_string_jump;
5811 STORE_NUMBER (p2 - 2, mcnt + 3);
5813 else
5815 /* Default to a safe `on_failure_jump' loop. */
5816 DEBUG_PRINT (" smart default => slow loop.\n");
5817 *p3 = (unsigned char) on_failure_jump;
5819 DEBUG_STATEMENT (debug -= 2);
5821 break;
5823 /* Unconditionally jump (without popping any failure points). */
5824 case jump:
5825 unconditional_jump:
5826 IMMEDIATE_QUIT_CHECK;
5827 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5828 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5829 p += mcnt; /* Do the jump. */
5830 DEBUG_PRINT ("(to %p).\n", p);
5831 break;
5834 /* Have to succeed matching what follows at least n times.
5835 After that, handle like `on_failure_jump'. */
5836 case succeed_n:
5837 /* Signedness doesn't matter since we only compare MCNT to 0. */
5838 EXTRACT_NUMBER (mcnt, p + 2);
5839 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5841 /* Originally, mcnt is how many times we HAVE to succeed. */
5842 if (mcnt != 0)
5844 /* Here, we discard `const', making re_match non-reentrant. */
5845 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5846 mcnt--;
5847 p += 4;
5848 PUSH_NUMBER (p2, mcnt);
5850 else
5851 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5852 goto on_failure;
5853 break;
5855 case jump_n:
5856 /* Signedness doesn't matter since we only compare MCNT to 0. */
5857 EXTRACT_NUMBER (mcnt, p + 2);
5858 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5860 /* Originally, this is how many times we CAN jump. */
5861 if (mcnt != 0)
5863 /* Here, we discard `const', making re_match non-reentrant. */
5864 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5865 mcnt--;
5866 PUSH_NUMBER (p2, mcnt);
5867 goto unconditional_jump;
5869 /* If don't have to jump any more, skip over the rest of command. */
5870 else
5871 p += 4;
5872 break;
5874 case set_number_at:
5876 unsigned char *p2; /* Location of the counter. */
5877 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5879 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5880 /* Here, we discard `const', making re_match non-reentrant. */
5881 p2 = (unsigned char*) p + mcnt;
5882 /* Signedness doesn't matter since we only copy MCNT's bits. */
5883 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5884 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5885 PUSH_NUMBER (p2, mcnt);
5886 break;
5889 case wordbound:
5890 case notwordbound:
5892 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5893 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5895 /* We SUCCEED (or FAIL) in one of the following cases: */
5897 /* Case 1: D is at the beginning or the end of string. */
5898 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5899 not = !not;
5900 else
5902 /* C1 is the character before D, S1 is the syntax of C1, C2
5903 is the character at D, and S2 is the syntax of C2. */
5904 re_wchar_t c1, c2;
5905 int s1, s2;
5906 int dummy;
5907 #ifdef emacs
5908 ssize_t offset = PTR_TO_OFFSET (d - 1);
5909 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5910 UPDATE_SYNTAX_TABLE_FAST (charpos);
5911 #endif
5912 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5913 s1 = SYNTAX (c1);
5914 #ifdef emacs
5915 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
5916 #endif
5917 PREFETCH_NOLIMIT ();
5918 GET_CHAR_AFTER (c2, d, dummy);
5919 s2 = SYNTAX (c2);
5921 if (/* Case 2: Only one of S1 and S2 is Sword. */
5922 ((s1 == Sword) != (s2 == Sword))
5923 /* Case 3: Both of S1 and S2 are Sword, and macro
5924 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5925 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5926 not = !not;
5928 if (not)
5929 break;
5930 else
5931 goto fail;
5934 case wordbeg:
5935 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5937 /* We FAIL in one of the following cases: */
5939 /* Case 1: D is at the end of string. */
5940 if (AT_STRINGS_END (d))
5941 goto fail;
5942 else
5944 /* C1 is the character before D, S1 is the syntax of C1, C2
5945 is the character at D, and S2 is the syntax of C2. */
5946 re_wchar_t c1, c2;
5947 int s1, s2;
5948 int dummy;
5949 #ifdef emacs
5950 ssize_t offset = PTR_TO_OFFSET (d);
5951 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5952 UPDATE_SYNTAX_TABLE_FAST (charpos);
5953 #endif
5954 PREFETCH ();
5955 GET_CHAR_AFTER (c2, d, dummy);
5956 s2 = SYNTAX (c2);
5958 /* Case 2: S2 is not Sword. */
5959 if (s2 != Sword)
5960 goto fail;
5962 /* Case 3: D is not at the beginning of string ... */
5963 if (!AT_STRINGS_BEG (d))
5965 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5966 #ifdef emacs
5967 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5968 #endif
5969 s1 = SYNTAX (c1);
5971 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5972 returns 0. */
5973 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5974 goto fail;
5977 break;
5979 case wordend:
5980 DEBUG_PRINT ("EXECUTING wordend.\n");
5982 /* We FAIL in one of the following cases: */
5984 /* Case 1: D is at the beginning of string. */
5985 if (AT_STRINGS_BEG (d))
5986 goto fail;
5987 else
5989 /* C1 is the character before D, S1 is the syntax of C1, C2
5990 is the character at D, and S2 is the syntax of C2. */
5991 re_wchar_t c1, c2;
5992 int s1, s2;
5993 int dummy;
5994 #ifdef emacs
5995 ssize_t offset = PTR_TO_OFFSET (d) - 1;
5996 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5997 UPDATE_SYNTAX_TABLE_FAST (charpos);
5998 #endif
5999 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6000 s1 = SYNTAX (c1);
6002 /* Case 2: S1 is not Sword. */
6003 if (s1 != Sword)
6004 goto fail;
6006 /* Case 3: D is not at the end of string ... */
6007 if (!AT_STRINGS_END (d))
6009 PREFETCH_NOLIMIT ();
6010 GET_CHAR_AFTER (c2, d, dummy);
6011 #ifdef emacs
6012 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos);
6013 #endif
6014 s2 = SYNTAX (c2);
6016 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6017 returns 0. */
6018 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6019 goto fail;
6022 break;
6024 case symbeg:
6025 DEBUG_PRINT ("EXECUTING symbeg.\n");
6027 /* We FAIL in one of the following cases: */
6029 /* Case 1: D is at the end of string. */
6030 if (AT_STRINGS_END (d))
6031 goto fail;
6032 else
6034 /* C1 is the character before D, S1 is the syntax of C1, C2
6035 is the character at D, and S2 is the syntax of C2. */
6036 re_wchar_t c1, c2;
6037 int s1, s2;
6038 #ifdef emacs
6039 ssize_t offset = PTR_TO_OFFSET (d);
6040 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6041 UPDATE_SYNTAX_TABLE_FAST (charpos);
6042 #endif
6043 PREFETCH ();
6044 c2 = RE_STRING_CHAR (d, target_multibyte);
6045 s2 = SYNTAX (c2);
6047 /* Case 2: S2 is neither Sword nor Ssymbol. */
6048 if (s2 != Sword && s2 != Ssymbol)
6049 goto fail;
6051 /* Case 3: D is not at the beginning of string ... */
6052 if (!AT_STRINGS_BEG (d))
6054 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6055 #ifdef emacs
6056 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6057 #endif
6058 s1 = SYNTAX (c1);
6060 /* ... and S1 is Sword or Ssymbol. */
6061 if (s1 == Sword || s1 == Ssymbol)
6062 goto fail;
6065 break;
6067 case symend:
6068 DEBUG_PRINT ("EXECUTING symend.\n");
6070 /* We FAIL in one of the following cases: */
6072 /* Case 1: D is at the beginning of string. */
6073 if (AT_STRINGS_BEG (d))
6074 goto fail;
6075 else
6077 /* C1 is the character before D, S1 is the syntax of C1, C2
6078 is the character at D, and S2 is the syntax of C2. */
6079 re_wchar_t c1, c2;
6080 int s1, s2;
6081 #ifdef emacs
6082 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6083 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6084 UPDATE_SYNTAX_TABLE_FAST (charpos);
6085 #endif
6086 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6087 s1 = SYNTAX (c1);
6089 /* Case 2: S1 is neither Ssymbol nor Sword. */
6090 if (s1 != Sword && s1 != Ssymbol)
6091 goto fail;
6093 /* Case 3: D is not at the end of string ... */
6094 if (!AT_STRINGS_END (d))
6096 PREFETCH_NOLIMIT ();
6097 c2 = RE_STRING_CHAR (d, target_multibyte);
6098 #ifdef emacs
6099 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
6100 #endif
6101 s2 = SYNTAX (c2);
6103 /* ... and S2 is Sword or Ssymbol. */
6104 if (s2 == Sword || s2 == Ssymbol)
6105 goto fail;
6108 break;
6110 case syntaxspec:
6111 case notsyntaxspec:
6113 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6114 mcnt = *p++;
6115 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6116 mcnt);
6117 PREFETCH ();
6118 #ifdef emacs
6120 ssize_t offset = PTR_TO_OFFSET (d);
6121 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6122 UPDATE_SYNTAX_TABLE_FAST (pos1);
6124 #endif
6126 int len;
6127 re_wchar_t c;
6129 GET_CHAR_AFTER (c, d, len);
6130 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6131 goto fail;
6132 d += len;
6135 break;
6137 #ifdef emacs
6138 case at_dot:
6139 DEBUG_PRINT ("EXECUTING at_dot.\n");
6140 if (PTR_BYTE_POS (d) != PT_BYTE)
6141 goto fail;
6142 break;
6144 case categoryspec:
6145 case notcategoryspec:
6147 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6148 mcnt = *p++;
6149 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6150 not ? "not" : "", mcnt);
6151 PREFETCH ();
6154 int len;
6155 re_wchar_t c;
6156 GET_CHAR_AFTER (c, d, len);
6157 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6158 goto fail;
6159 d += len;
6162 break;
6164 #endif /* emacs */
6166 default:
6167 abort ();
6169 continue; /* Successfully executed one pattern command; keep going. */
6172 /* We goto here if a matching operation fails. */
6173 fail:
6174 IMMEDIATE_QUIT_CHECK;
6175 if (!FAIL_STACK_EMPTY ())
6177 re_char *str, *pat;
6178 /* A restart point is known. Restore to that state. */
6179 DEBUG_PRINT ("\nFAIL:\n");
6180 POP_FAILURE_POINT (str, pat);
6181 switch (*pat++)
6183 case on_failure_keep_string_jump:
6184 assert (str == NULL);
6185 goto continue_failure_jump;
6187 case on_failure_jump_nastyloop:
6188 assert ((re_opcode_t)pat[-2] == no_op);
6189 PUSH_FAILURE_POINT (pat - 2, str);
6190 /* Fallthrough */
6192 case on_failure_jump_loop:
6193 case on_failure_jump:
6194 case succeed_n:
6195 d = str;
6196 continue_failure_jump:
6197 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6198 p = pat + mcnt;
6199 break;
6201 case no_op:
6202 /* A special frame used for nastyloops. */
6203 goto fail;
6205 default:
6206 abort ();
6209 assert (p >= bufp->buffer && p <= pend);
6211 if (d >= string1 && d <= end1)
6212 dend = end_match_1;
6214 else
6215 break; /* Matching at this starting point really fails. */
6216 } /* for (;;) */
6218 if (best_regs_set)
6219 goto restore_best_regs;
6221 FREE_VARIABLES ();
6223 return -1; /* Failure to match. */
6226 /* Subroutine definitions for re_match_2. */
6228 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6229 bytes; nonzero otherwise. */
6231 static int
6232 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6233 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6235 register re_char *p1 = s1, *p2 = s2;
6236 re_char *p1_end = s1 + len;
6237 re_char *p2_end = s2 + len;
6239 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6240 different lengths, but relying on a single `len' would break this. -sm */
6241 while (p1 < p1_end && p2 < p2_end)
6243 int p1_charlen, p2_charlen;
6244 re_wchar_t p1_ch, p2_ch;
6246 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6247 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6249 if (RE_TRANSLATE (translate, p1_ch)
6250 != RE_TRANSLATE (translate, p2_ch))
6251 return 1;
6253 p1 += p1_charlen, p2 += p2_charlen;
6256 if (p1 != p1_end || p2 != p2_end)
6257 return 1;
6259 return 0;
6262 /* Entry points for GNU code. */
6264 /* re_compile_pattern is the GNU regular expression compiler: it
6265 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6266 Returns 0 if the pattern was valid, otherwise an error string.
6268 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6269 are set in BUFP on entry.
6271 We call regex_compile to do the actual compilation. */
6273 const char *
6274 re_compile_pattern (const char *pattern, size_t length,
6275 #ifdef emacs
6276 bool posix_backtracking, const char *whitespace_regexp,
6277 #endif
6278 struct re_pattern_buffer *bufp)
6280 reg_errcode_t ret;
6282 /* GNU code is written to assume at least RE_NREGS registers will be set
6283 (and at least one extra will be -1). */
6284 bufp->regs_allocated = REGS_UNALLOCATED;
6286 /* And GNU code determines whether or not to get register information
6287 by passing null for the REGS argument to re_match, etc., not by
6288 setting no_sub. */
6289 bufp->no_sub = 0;
6291 ret = regex_compile ((re_char*) pattern, length,
6292 #ifdef emacs
6293 posix_backtracking,
6294 whitespace_regexp,
6295 #else
6296 re_syntax_options,
6297 #endif
6298 bufp);
6300 if (!ret)
6301 return NULL;
6302 return gettext (re_error_msgid[(int) ret]);
6304 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6306 /* Entry points compatible with 4.2 BSD regex library. We don't define
6307 them unless specifically requested. */
6309 #if defined _REGEX_RE_COMP || defined _LIBC
6311 /* BSD has one and only one pattern buffer. */
6312 static struct re_pattern_buffer re_comp_buf;
6314 char *
6315 # ifdef _LIBC
6316 /* Make these definitions weak in libc, so POSIX programs can redefine
6317 these names if they don't use our functions, and still use
6318 regcomp/regexec below without link errors. */
6319 weak_function
6320 # endif
6321 re_comp (const char *s)
6323 reg_errcode_t ret;
6325 if (!s)
6327 if (!re_comp_buf.buffer)
6328 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6329 return (char *) gettext ("No previous regular expression");
6330 return 0;
6333 if (!re_comp_buf.buffer)
6335 re_comp_buf.buffer = malloc (200);
6336 if (re_comp_buf.buffer == NULL)
6337 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6338 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6339 re_comp_buf.allocated = 200;
6341 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6342 if (re_comp_buf.fastmap == NULL)
6343 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6344 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6347 /* Since `re_exec' always passes NULL for the `regs' argument, we
6348 don't need to initialize the pattern buffer fields which affect it. */
6350 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6352 if (!ret)
6353 return NULL;
6355 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6356 return (char *) gettext (re_error_msgid[(int) ret]);
6361 # ifdef _LIBC
6362 weak_function
6363 # endif
6364 re_exec (const char *s)
6366 const size_t len = strlen (s);
6367 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6369 #endif /* _REGEX_RE_COMP */
6371 /* POSIX.2 functions. Don't define these for Emacs. */
6373 #ifndef emacs
6375 /* regcomp takes a regular expression as a string and compiles it.
6377 PREG is a regex_t *. We do not expect any fields to be initialized,
6378 since POSIX says we shouldn't. Thus, we set
6380 `buffer' to the compiled pattern;
6381 `used' to the length of the compiled pattern;
6382 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6383 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6384 RE_SYNTAX_POSIX_BASIC;
6385 `fastmap' to an allocated space for the fastmap;
6386 `fastmap_accurate' to zero;
6387 `re_nsub' to the number of subexpressions in PATTERN.
6389 PATTERN is the address of the pattern string.
6391 CFLAGS is a series of bits which affect compilation.
6393 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6394 use POSIX basic syntax.
6396 If REG_NEWLINE is set, then . and [^...] don't match newline.
6397 Also, regexec will try a match beginning after every newline.
6399 If REG_ICASE is set, then we considers upper- and lowercase
6400 versions of letters to be equivalent when matching.
6402 If REG_NOSUB is set, then when PREG is passed to regexec, that
6403 routine will report only success or failure, and nothing about the
6404 registers.
6406 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6407 the return codes and their meanings.) */
6409 reg_errcode_t
6410 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6411 int cflags)
6413 reg_errcode_t ret;
6414 reg_syntax_t syntax
6415 = (cflags & REG_EXTENDED) ?
6416 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6418 /* regex_compile will allocate the space for the compiled pattern. */
6419 preg->buffer = 0;
6420 preg->allocated = 0;
6421 preg->used = 0;
6423 /* Try to allocate space for the fastmap. */
6424 preg->fastmap = malloc (1 << BYTEWIDTH);
6426 if (cflags & REG_ICASE)
6428 unsigned i;
6430 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6431 if (preg->translate == NULL)
6432 return (int) REG_ESPACE;
6434 /* Map uppercase characters to corresponding lowercase ones. */
6435 for (i = 0; i < CHAR_SET_SIZE; i++)
6436 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6438 else
6439 preg->translate = NULL;
6441 /* If REG_NEWLINE is set, newlines are treated differently. */
6442 if (cflags & REG_NEWLINE)
6443 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6444 syntax &= ~RE_DOT_NEWLINE;
6445 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6447 else
6448 syntax |= RE_NO_NEWLINE_ANCHOR;
6450 preg->no_sub = !!(cflags & REG_NOSUB);
6452 /* POSIX says a null character in the pattern terminates it, so we
6453 can use strlen here in compiling the pattern. */
6454 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6456 /* POSIX doesn't distinguish between an unmatched open-group and an
6457 unmatched close-group: both are REG_EPAREN. */
6458 if (ret == REG_ERPAREN)
6459 ret = REG_EPAREN;
6461 if (ret == REG_NOERROR && preg->fastmap)
6462 { /* Compute the fastmap now, since regexec cannot modify the pattern
6463 buffer. */
6464 re_compile_fastmap (preg);
6465 if (preg->can_be_null)
6466 { /* The fastmap can't be used anyway. */
6467 free (preg->fastmap);
6468 preg->fastmap = NULL;
6471 return ret;
6473 WEAK_ALIAS (__regcomp, regcomp)
6476 /* regexec searches for a given pattern, specified by PREG, in the
6477 string STRING.
6479 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6480 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6481 least NMATCH elements, and we set them to the offsets of the
6482 corresponding matched substrings.
6484 EFLAGS specifies `execution flags' which affect matching: if
6485 REG_NOTBOL is set, then ^ does not match at the beginning of the
6486 string; if REG_NOTEOL is set, then $ does not match at the end.
6488 We return 0 if we find a match and REG_NOMATCH if not. */
6490 reg_errcode_t
6491 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6492 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6494 regoff_t ret;
6495 struct re_registers regs;
6496 regex_t private_preg;
6497 size_t len = strlen (string);
6498 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6500 private_preg = *preg;
6502 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6503 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6505 /* The user has told us exactly how many registers to return
6506 information about, via `nmatch'. We have to pass that on to the
6507 matching routines. */
6508 private_preg.regs_allocated = REGS_FIXED;
6510 if (want_reg_info)
6512 regs.num_regs = nmatch;
6513 regs.start = TALLOC (nmatch * 2, regoff_t);
6514 if (regs.start == NULL)
6515 return REG_NOMATCH;
6516 regs.end = regs.start + nmatch;
6519 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6520 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6521 was a little bit longer but still only matching the real part.
6522 This works because the `endline' will check for a '\n' and will find a
6523 '\0', correctly deciding that this is not the end of a line.
6524 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6525 a convenient '\0' there. For all we know, the string could be preceded
6526 by '\n' which would throw things off. */
6528 /* Perform the searching operation. */
6529 ret = re_search (&private_preg, string, len,
6530 /* start: */ 0, /* range: */ len,
6531 want_reg_info ? &regs : 0);
6533 /* Copy the register information to the POSIX structure. */
6534 if (want_reg_info)
6536 if (ret >= 0)
6538 unsigned r;
6540 for (r = 0; r < nmatch; r++)
6542 pmatch[r].rm_so = regs.start[r];
6543 pmatch[r].rm_eo = regs.end[r];
6547 /* If we needed the temporary register info, free the space now. */
6548 free (regs.start);
6551 /* We want zero return to mean success, unlike `re_search'. */
6552 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6554 WEAK_ALIAS (__regexec, regexec)
6557 /* Returns a message corresponding to an error code, ERR_CODE, returned
6558 from either regcomp or regexec. We don't use PREG here.
6560 ERR_CODE was previously called ERRCODE, but that name causes an
6561 error with msvc8 compiler. */
6563 size_t
6564 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6566 const char *msg;
6567 size_t msg_size;
6569 if (err_code < 0
6570 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6571 /* Only error codes returned by the rest of the code should be passed
6572 to this routine. If we are given anything else, or if other regex
6573 code generates an invalid error code, then the program has a bug.
6574 Dump core so we can fix it. */
6575 abort ();
6577 msg = gettext (re_error_msgid[err_code]);
6579 msg_size = strlen (msg) + 1; /* Includes the null. */
6581 if (errbuf_size != 0)
6583 if (msg_size > errbuf_size)
6585 memcpy (errbuf, msg, errbuf_size - 1);
6586 errbuf[errbuf_size - 1] = 0;
6588 else
6589 strcpy (errbuf, msg);
6592 return msg_size;
6594 WEAK_ALIAS (__regerror, regerror)
6597 /* Free dynamically allocated space used by PREG. */
6599 void
6600 regfree (regex_t *preg)
6602 free (preg->buffer);
6603 preg->buffer = NULL;
6605 preg->allocated = 0;
6606 preg->used = 0;
6608 free (preg->fastmap);
6609 preg->fastmap = NULL;
6610 preg->fastmap_accurate = 0;
6612 free (preg->translate);
6613 preg->translate = NULL;
6615 WEAK_ALIAS (__regfree, regfree)
6617 #endif /* not emacs */