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