Do not use map.el in seq-tests.el
[emacs.git] / src / regex.c
blob1c6c9e5c18b68be8491edf6e51c0f33bb841408a
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>
53 #include <stdlib.h>
55 #ifdef emacs
56 /* We need this for `regex.h', and perhaps for the Emacs include files. */
57 # include <sys/types.h>
58 #endif
60 /* Whether to use ISO C Amendment 1 wide char functions.
61 Those should not be used for Emacs since it uses its own. */
62 #if defined _LIBC
63 #define WIDE_CHAR_SUPPORT 1
64 #else
65 #define WIDE_CHAR_SUPPORT \
66 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
67 #endif
69 /* For platform which support the ISO C amendment 1 functionality we
70 support user defined character classes. */
71 #if WIDE_CHAR_SUPPORT
72 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
73 # include <wchar.h>
74 # include <wctype.h>
75 #endif
77 #ifdef _LIBC
78 /* We have to keep the namespace clean. */
79 # define regfree(preg) __regfree (preg)
80 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
81 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
82 # define regerror(err_code, preg, errbuf, errbuf_size) \
83 __regerror (err_code, preg, errbuf, errbuf_size)
84 # define re_set_registers(bu, re, nu, st, en) \
85 __re_set_registers (bu, re, nu, st, en)
86 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
87 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
88 # define re_match(bufp, string, size, pos, regs) \
89 __re_match (bufp, string, size, pos, regs)
90 # define re_search(bufp, string, size, startpos, range, regs) \
91 __re_search (bufp, string, size, startpos, range, regs)
92 # define re_compile_pattern(pattern, length, bufp) \
93 __re_compile_pattern (pattern, length, bufp)
94 # define re_set_syntax(syntax) __re_set_syntax (syntax)
95 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
96 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
97 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
99 /* Make sure we call libc's function even if the user overrides them. */
100 # define btowc __btowc
101 # define iswctype __iswctype
102 # define wctype __wctype
104 # define WEAK_ALIAS(a,b) weak_alias (a, b)
106 /* We are also using some library internals. */
107 # include <locale/localeinfo.h>
108 # include <locale/elem-hash.h>
109 # include <langinfo.h>
110 #else
111 # define WEAK_ALIAS(a,b)
112 #endif
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
117 #else
118 # define gettext(msgid) (msgid)
119 #endif
121 #ifndef gettext_noop
122 /* This define is so xgettext can find the internationalizable
123 strings. */
124 # define gettext_noop(String) String
125 #endif
127 /* The `emacs' switch turns on certain matching commands
128 that make sense only in Emacs. */
129 #ifdef emacs
131 # include "lisp.h"
132 # include "character.h"
133 # include "buffer.h"
135 # include "syntax.h"
136 # include "category.h"
138 /* Make syntax table lookup grant data in gl_state. */
139 # define SYNTAX(c) syntax_property (c, 1)
141 # ifdef malloc
142 # undef malloc
143 # endif
144 # define malloc xmalloc
145 # ifdef realloc
146 # undef realloc
147 # endif
148 # define realloc xrealloc
149 # ifdef free
150 # undef free
151 # endif
152 # define free xfree
154 /* Converts the pointer to the char to BEG-based offset from the start. */
155 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
156 /* Strings are 0-indexed, buffers are 1-indexed; we pun on the boolean
157 result to get the right base index. */
158 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
160 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
161 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
162 # define RE_STRING_CHAR(p, multibyte) \
163 (multibyte ? (STRING_CHAR (p)) : (*(p)))
164 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
165 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
167 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
169 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
171 /* Set C a (possibly converted to multibyte) character before P. P
172 points into a string which is the virtual concatenation of STR1
173 (which ends at END1) or STR2 (which ends at END2). */
174 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
175 do { \
176 if (target_multibyte) \
178 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
179 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
180 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
181 c = STRING_CHAR (dtemp); \
183 else \
185 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
188 } while (0)
190 /* Set C a (possibly converted to multibyte) character at P, and set
191 LEN to the byte length of that character. */
192 # define GET_CHAR_AFTER(c, p, len) \
193 do { \
194 if (target_multibyte) \
195 (c) = STRING_CHAR_AND_LENGTH (p, len); \
196 else \
198 (c) = *p; \
199 len = 1; \
200 (c) = RE_CHAR_TO_MULTIBYTE (c); \
202 } while (0)
204 #else /* not emacs */
206 /* If we are not linking with Emacs proper,
207 we can't use the relocating allocator
208 even if config.h says that we can. */
209 # undef REL_ALLOC
211 # include <unistd.h>
213 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
215 static void *
216 xmalloc (size_t size)
218 void *val = malloc (size);
219 if (!val && size)
221 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
222 exit (1);
224 return val;
227 static void *
228 xrealloc (void *block, size_t size)
230 void *val;
231 /* We must call malloc explicitly when BLOCK is 0, since some
232 reallocs don't do this. */
233 if (! block)
234 val = malloc (size);
235 else
236 val = realloc (block, size);
237 if (!val && size)
239 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
240 exit (1);
242 return val;
245 # ifdef malloc
246 # undef malloc
247 # endif
248 # define malloc xmalloc
249 # ifdef realloc
250 # undef realloc
251 # endif
252 # define realloc xrealloc
254 # include <stdbool.h>
255 # include <string.h>
257 /* Define the syntax stuff for \<, \>, etc. */
259 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
260 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
262 /* Dummy macros for non-Emacs environments. */
263 # define MAX_MULTIBYTE_LENGTH 1
264 # define RE_MULTIBYTE_P(x) 0
265 # define RE_TARGET_MULTIBYTE_P(x) 0
266 # define WORD_BOUNDARY_P(c1, c2) (0)
267 # define BYTES_BY_CHAR_HEAD(p) (1)
268 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
269 # define STRING_CHAR(p) (*(p))
270 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
271 # define CHAR_STRING(c, s) (*(s) = (c), 1)
272 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
273 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
274 # define RE_CHAR_TO_MULTIBYTE(c) (c)
275 # define RE_CHAR_TO_UNIBYTE(c) (c)
276 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
277 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
278 # define GET_CHAR_AFTER(c, p, len) \
279 (c = *p, len = 1)
280 # define CHAR_BYTE8_P(c) (0)
281 # define CHAR_LEADING_CODE(c) (c)
283 #endif /* not emacs */
285 #ifndef RE_TRANSLATE
286 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
287 # define RE_TRANSLATE_P(TBL) (TBL)
288 #endif
290 /* Get the interface, including the syntax bits. */
291 #include "regex.h"
293 /* isalpha etc. are used for the character classes. */
294 #include <ctype.h>
296 #ifdef emacs
298 /* 1 if C is an ASCII character. */
299 # define IS_REAL_ASCII(c) ((c) < 0200)
301 /* 1 if C is a unibyte character. */
302 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
304 /* The Emacs definitions should not be directly affected by locales. */
306 /* In Emacs, these are only used for single-byte characters. */
307 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
308 # define ISCNTRL(c) ((c) < ' ')
309 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
310 || ((c) >= 'a' && (c) <= 'f') \
311 || ((c) >= 'A' && (c) <= 'F'))
313 /* This is only used for single-byte characters. */
314 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
316 /* The rest must handle multibyte characters. */
318 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
319 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0240) \
320 : graphicp (c))
322 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
323 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
324 : printablep (c))
326 # define ISALNUM(c) (IS_REAL_ASCII (c) \
327 ? (((c) >= 'a' && (c) <= 'z') \
328 || ((c) >= 'A' && (c) <= 'Z') \
329 || ((c) >= '0' && (c) <= '9')) \
330 : alphanumericp (c))
332 # define ISALPHA(c) (IS_REAL_ASCII (c) \
333 ? (((c) >= 'a' && (c) <= 'z') \
334 || ((c) >= 'A' && (c) <= 'Z')) \
335 : alphabeticp (c))
337 # define ISLOWER(c) lowercasep (c)
339 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
340 ? ((c) > ' ' && (c) < 0177 \
341 && !(((c) >= 'a' && (c) <= 'z') \
342 || ((c) >= 'A' && (c) <= 'Z') \
343 || ((c) >= '0' && (c) <= '9'))) \
344 : SYNTAX (c) != Sword)
346 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
348 # define ISUPPER(c) uppercasep (c)
350 # define ISWORD(c) (SYNTAX (c) == Sword)
352 #else /* not emacs */
354 /* 1 if C is an ASCII character. */
355 # define IS_REAL_ASCII(c) ((c) < 0200)
357 /* This distinction is not meaningful, except in Emacs. */
358 # define ISUNIBYTE(c) 1
360 # ifdef isblank
361 # define ISBLANK(c) isblank (c)
362 # else
363 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
364 # endif
365 # ifdef isgraph
366 # define ISGRAPH(c) isgraph (c)
367 # else
368 # define ISGRAPH(c) (isprint (c) && !isspace (c))
369 # endif
371 /* Solaris defines ISPRINT so we must undefine it first. */
372 # undef ISPRINT
373 # define ISPRINT(c) isprint (c)
374 # define ISDIGIT(c) isdigit (c)
375 # define ISALNUM(c) isalnum (c)
376 # define ISALPHA(c) isalpha (c)
377 # define ISCNTRL(c) iscntrl (c)
378 # define ISLOWER(c) islower (c)
379 # define ISPUNCT(c) ispunct (c)
380 # define ISSPACE(c) isspace (c)
381 # define ISUPPER(c) isupper (c)
382 # define ISXDIGIT(c) isxdigit (c)
384 # define ISWORD(c) ISALPHA (c)
386 # ifdef _tolower
387 # define TOLOWER(c) _tolower (c)
388 # else
389 # define TOLOWER(c) tolower (c)
390 # endif
392 /* How many characters in the character set. */
393 # define CHAR_SET_SIZE 256
395 # ifdef SYNTAX_TABLE
397 extern char *re_syntax_table;
399 # else /* not SYNTAX_TABLE */
401 static char re_syntax_table[CHAR_SET_SIZE];
403 static void
404 init_syntax_once (void)
406 register int c;
407 static int done = 0;
409 if (done)
410 return;
412 memset (re_syntax_table, 0, sizeof re_syntax_table);
414 for (c = 0; c < CHAR_SET_SIZE; ++c)
415 if (ISALNUM (c))
416 re_syntax_table[c] = Sword;
418 re_syntax_table['_'] = Ssymbol;
420 done = 1;
423 # endif /* not SYNTAX_TABLE */
425 # define SYNTAX(c) re_syntax_table[(c)]
427 #endif /* not emacs */
429 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
431 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
432 use `alloca' instead of `malloc'. This is because using malloc in
433 re_search* or re_match* could cause memory leaks when C-g is used in
434 Emacs; also, malloc is slower and causes storage fragmentation. On
435 the other hand, malloc is more portable, and easier to debug.
437 Because we sometimes use alloca, some routines have to be macros,
438 not functions -- `alloca'-allocated space disappears at the end of the
439 function it is called in. */
441 #ifdef REGEX_MALLOC
443 # define REGEX_ALLOCATE malloc
444 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
445 # define REGEX_FREE free
447 #else /* not REGEX_MALLOC */
449 # ifdef emacs
450 # define REGEX_USE_SAFE_ALLOCA USE_SAFE_ALLOCA
451 # define REGEX_SAFE_FREE() SAFE_FREE ()
452 # define REGEX_ALLOCATE SAFE_ALLOCA
453 # else
454 # include <alloca.h>
455 # define REGEX_ALLOCATE alloca
456 # endif
458 /* Assumes a `char *destination' variable. */
459 # define REGEX_REALLOCATE(source, osize, nsize) \
460 (destination = REGEX_ALLOCATE (nsize), \
461 memcpy (destination, source, osize))
463 /* No need to do anything to free, after alloca. */
464 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
466 #endif /* not REGEX_MALLOC */
468 #ifndef REGEX_USE_SAFE_ALLOCA
469 # define REGEX_USE_SAFE_ALLOCA ((void) 0)
470 # define REGEX_SAFE_FREE() ((void) 0)
471 #endif
473 /* Define how to allocate the failure stack. */
475 #if defined REL_ALLOC && defined REGEX_MALLOC
477 # define REGEX_ALLOCATE_STACK(size) \
478 r_alloc (&failure_stack_ptr, (size))
479 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
480 r_re_alloc (&failure_stack_ptr, (nsize))
481 # define REGEX_FREE_STACK(ptr) \
482 r_alloc_free (&failure_stack_ptr)
484 #else /* not using relocating allocator */
486 # define REGEX_ALLOCATE_STACK(size) REGEX_ALLOCATE (size)
487 # define REGEX_REALLOCATE_STACK(source, o, n) REGEX_REALLOCATE (source, o, n)
488 # define REGEX_FREE_STACK(ptr) REGEX_FREE (ptr)
490 #endif /* not using relocating allocator */
493 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
494 `string1' or just past its end. This works if PTR is NULL, which is
495 a good thing. */
496 #define FIRST_STRING_P(ptr) \
497 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
499 /* (Re)Allocate N items of type T using malloc, or fail. */
500 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
501 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
502 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
504 #define BYTEWIDTH 8 /* In bits. */
506 #ifndef emacs
507 # undef max
508 # undef min
509 # define max(a, b) ((a) > (b) ? (a) : (b))
510 # define min(a, b) ((a) < (b) ? (a) : (b))
511 #endif
513 /* Type of source-pattern and string chars. */
514 #ifdef _MSC_VER
515 typedef unsigned char re_char;
516 typedef const re_char const_re_char;
517 #else
518 typedef const unsigned char re_char;
519 typedef re_char const_re_char;
520 #endif
522 typedef char boolean;
524 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
525 re_char *string1, size_t size1,
526 re_char *string2, size_t size2,
527 ssize_t pos,
528 struct re_registers *regs,
529 ssize_t stop);
531 /* These are the command codes that appear in compiled regular
532 expressions. Some opcodes are followed by argument bytes. A
533 command code can specify any interpretation whatsoever for its
534 arguments. Zero bytes may appear in the compiled regular expression. */
536 typedef enum
538 no_op = 0,
540 /* Succeed right away--no more backtracking. */
541 succeed,
543 /* Followed by one byte giving n, then by n literal bytes. */
544 exactn,
546 /* Matches any (more or less) character. */
547 anychar,
549 /* Matches any one char belonging to specified set. First
550 following byte is number of bitmap bytes. Then come bytes
551 for a bitmap saying which chars are in. Bits in each byte
552 are ordered low-bit-first. A character is in the set if its
553 bit is 1. A character too large to have a bit in the map is
554 automatically not in the set.
556 If the length byte has the 0x80 bit set, then that stuff
557 is followed by a range table:
558 2 bytes of flags for character sets (low 8 bits, high 8 bits)
559 See RANGE_TABLE_WORK_BITS below.
560 2 bytes, the number of pairs that follow (upto 32767)
561 pairs, each 2 multibyte characters,
562 each multibyte character represented as 3 bytes. */
563 charset,
565 /* Same parameters as charset, but match any character that is
566 not one of those specified. */
567 charset_not,
569 /* Start remembering the text that is matched, for storing in a
570 register. Followed by one byte with the register number, in
571 the range 0 to one less than the pattern buffer's re_nsub
572 field. */
573 start_memory,
575 /* Stop remembering the text that is matched and store it in a
576 memory register. Followed by one byte with the register
577 number, in the range 0 to one less than `re_nsub' in the
578 pattern buffer. */
579 stop_memory,
581 /* Match a duplicate of something remembered. Followed by one
582 byte containing the register number. */
583 duplicate,
585 /* Fail unless at beginning of line. */
586 begline,
588 /* Fail unless at end of line. */
589 endline,
591 /* Succeeds if at beginning of buffer (if emacs) or at beginning
592 of string to be matched (if not). */
593 begbuf,
595 /* Analogously, for end of buffer/string. */
596 endbuf,
598 /* Followed by two byte relative address to which to jump. */
599 jump,
601 /* Followed by two-byte relative address of place to resume at
602 in case of failure. */
603 on_failure_jump,
605 /* Like on_failure_jump, but pushes a placeholder instead of the
606 current string position when executed. */
607 on_failure_keep_string_jump,
609 /* Just like `on_failure_jump', except that it checks that we
610 don't get stuck in an infinite loop (matching an empty string
611 indefinitely). */
612 on_failure_jump_loop,
614 /* Just like `on_failure_jump_loop', except that it checks for
615 a different kind of loop (the kind that shows up with non-greedy
616 operators). This operation has to be immediately preceded
617 by a `no_op'. */
618 on_failure_jump_nastyloop,
620 /* A smart `on_failure_jump' used for greedy * and + operators.
621 It analyzes the loop before which it is put and if the
622 loop does not require backtracking, it changes itself to
623 `on_failure_keep_string_jump' and short-circuits the loop,
624 else it just defaults to changing itself into `on_failure_jump'.
625 It assumes that it is pointing to just past a `jump'. */
626 on_failure_jump_smart,
628 /* Followed by two-byte relative address and two-byte number n.
629 After matching N times, jump to the address upon failure.
630 Does not work if N starts at 0: use on_failure_jump_loop
631 instead. */
632 succeed_n,
634 /* Followed by two-byte relative address, and two-byte number n.
635 Jump to the address N times, then fail. */
636 jump_n,
638 /* Set the following two-byte relative address to the
639 subsequent two-byte number. The address *includes* the two
640 bytes of number. */
641 set_number_at,
643 wordbeg, /* Succeeds if at word beginning. */
644 wordend, /* Succeeds if at word end. */
646 wordbound, /* Succeeds if at a word boundary. */
647 notwordbound, /* Succeeds if not at a word boundary. */
649 symbeg, /* Succeeds if at symbol beginning. */
650 symend, /* Succeeds if at symbol end. */
652 /* Matches any character whose syntax is specified. Followed by
653 a byte which contains a syntax code, e.g., Sword. */
654 syntaxspec,
656 /* Matches any character whose syntax is not that specified. */
657 notsyntaxspec
659 #ifdef emacs
660 , at_dot, /* Succeeds if at point. */
662 /* Matches any character whose category-set contains the specified
663 category. The operator is followed by a byte which contains a
664 category code (mnemonic ASCII character). */
665 categoryspec,
667 /* Matches any character whose category-set does not contain the
668 specified category. The operator is followed by a byte which
669 contains the category code (mnemonic ASCII character). */
670 notcategoryspec
671 #endif /* emacs */
672 } re_opcode_t;
674 /* Common operations on the compiled pattern. */
676 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
678 #define STORE_NUMBER(destination, number) \
679 do { \
680 (destination)[0] = (number) & 0377; \
681 (destination)[1] = (number) >> 8; \
682 } while (0)
684 /* Same as STORE_NUMBER, except increment DESTINATION to
685 the byte after where the number is stored. Therefore, DESTINATION
686 must be an lvalue. */
688 #define STORE_NUMBER_AND_INCR(destination, number) \
689 do { \
690 STORE_NUMBER (destination, number); \
691 (destination) += 2; \
692 } while (0)
694 /* Put into DESTINATION a number stored in two contiguous bytes starting
695 at SOURCE. */
697 #define EXTRACT_NUMBER(destination, source) \
698 ((destination) = extract_number (source))
700 static int
701 extract_number (re_char *source)
703 unsigned leading_byte = SIGN_EXTEND_CHAR (source[1]);
704 return (leading_byte << 8) + source[0];
707 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
708 SOURCE must be an lvalue. */
710 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
711 ((destination) = extract_number_and_incr (&source))
713 static int
714 extract_number_and_incr (re_char **source)
716 int num = extract_number (*source);
717 *source += 2;
718 return num;
721 /* Store a multibyte character in three contiguous bytes starting
722 DESTINATION, and increment DESTINATION to the byte after where the
723 character is stored. Therefore, DESTINATION must be an lvalue. */
725 #define STORE_CHARACTER_AND_INCR(destination, character) \
726 do { \
727 (destination)[0] = (character) & 0377; \
728 (destination)[1] = ((character) >> 8) & 0377; \
729 (destination)[2] = (character) >> 16; \
730 (destination) += 3; \
731 } while (0)
733 /* Put into DESTINATION a character stored in three contiguous bytes
734 starting at SOURCE. */
736 #define EXTRACT_CHARACTER(destination, source) \
737 do { \
738 (destination) = ((source)[0] \
739 | ((source)[1] << 8) \
740 | ((source)[2] << 16)); \
741 } while (0)
744 /* Macros for charset. */
746 /* Size of bitmap of charset P in bytes. P is a start of charset,
747 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
748 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
750 /* Nonzero if charset P has range table. */
751 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
753 /* Return the address of range table of charset P. But not the start
754 of table itself, but the before where the number of ranges is
755 stored. `2 +' means to skip re_opcode_t and size of bitmap,
756 and the 2 bytes of flags at the start of the range table. */
757 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
759 #ifdef emacs
760 /* Extract the bit flags that start a range table. */
761 #define CHARSET_RANGE_TABLE_BITS(p) \
762 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
763 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
764 #endif
766 /* Return the address of end of RANGE_TABLE. COUNT is number of
767 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
768 is start of range and end of range. `* 3' is size of each start
769 and end. */
770 #define CHARSET_RANGE_TABLE_END(range_table, count) \
771 ((range_table) + (count) * 2 * 3)
773 /* If DEBUG is defined, Regex prints many voluminous messages about what
774 it is doing (if the variable `debug' is nonzero). If linked with the
775 main program in `iregex.c', you can enter patterns and strings
776 interactively. And if linked with the main program in `main.c' and
777 the other test files, you can run the already-written tests. */
779 #ifdef DEBUG
781 /* We use standard I/O for debugging. */
782 # include <stdio.h>
784 /* It is useful to test things that ``must'' be true when debugging. */
785 # include <assert.h>
787 static int debug = -100000;
789 # define DEBUG_STATEMENT(e) e
790 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
791 # define DEBUG_COMPILES_ARGUMENTS
792 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
793 if (debug > 0) print_partial_compiled_pattern (s, e)
794 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
795 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
798 /* Print the fastmap in human-readable form. */
800 static void
801 print_fastmap (char *fastmap)
803 unsigned was_a_range = 0;
804 unsigned i = 0;
806 while (i < (1 << BYTEWIDTH))
808 if (fastmap[i++])
810 was_a_range = 0;
811 putchar (i - 1);
812 while (i < (1 << BYTEWIDTH) && fastmap[i])
814 was_a_range = 1;
815 i++;
817 if (was_a_range)
819 printf ("-");
820 putchar (i - 1);
824 putchar ('\n');
828 /* Print a compiled pattern string in human-readable form, starting at
829 the START pointer into it and ending just before the pointer END. */
831 static void
832 print_partial_compiled_pattern (re_char *start, re_char *end)
834 int mcnt, mcnt2;
835 re_char *p = start;
836 re_char *pend = end;
838 if (start == NULL)
840 fprintf (stderr, "(null)\n");
841 return;
844 /* Loop over pattern commands. */
845 while (p < pend)
847 fprintf (stderr, "%td:\t", p - start);
849 switch ((re_opcode_t) *p++)
851 case no_op:
852 fprintf (stderr, "/no_op");
853 break;
855 case succeed:
856 fprintf (stderr, "/succeed");
857 break;
859 case exactn:
860 mcnt = *p++;
861 fprintf (stderr, "/exactn/%d", mcnt);
864 fprintf (stderr, "/%c", *p++);
866 while (--mcnt);
867 break;
869 case start_memory:
870 fprintf (stderr, "/start_memory/%d", *p++);
871 break;
873 case stop_memory:
874 fprintf (stderr, "/stop_memory/%d", *p++);
875 break;
877 case duplicate:
878 fprintf (stderr, "/duplicate/%d", *p++);
879 break;
881 case anychar:
882 fprintf (stderr, "/anychar");
883 break;
885 case charset:
886 case charset_not:
888 register int c, last = -100;
889 register int in_range = 0;
890 int length = CHARSET_BITMAP_SIZE (p - 1);
891 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
893 fprintf (stderr, "/charset [%s",
894 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
896 if (p + *p >= pend)
897 fprintf (stderr, " !extends past end of pattern! ");
899 for (c = 0; c < 256; c++)
900 if (c / 8 < length
901 && (p[1 + (c/8)] & (1 << (c % 8))))
903 /* Are we starting a range? */
904 if (last + 1 == c && ! in_range)
906 fprintf (stderr, "-");
907 in_range = 1;
909 /* Have we broken a range? */
910 else if (last + 1 != c && in_range)
912 fprintf (stderr, "%c", last);
913 in_range = 0;
916 if (! in_range)
917 fprintf (stderr, "%c", c);
919 last = c;
922 if (in_range)
923 fprintf (stderr, "%c", last);
925 fprintf (stderr, "]");
927 p += 1 + length;
929 if (has_range_table)
931 int count;
932 fprintf (stderr, "has-range-table");
934 /* ??? Should print the range table; for now, just skip it. */
935 p += 2; /* skip range table bits */
936 EXTRACT_NUMBER_AND_INCR (count, p);
937 p = CHARSET_RANGE_TABLE_END (p, count);
940 break;
942 case begline:
943 fprintf (stderr, "/begline");
944 break;
946 case endline:
947 fprintf (stderr, "/endline");
948 break;
950 case on_failure_jump:
951 EXTRACT_NUMBER_AND_INCR (mcnt, p);
952 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
953 break;
955 case on_failure_keep_string_jump:
956 EXTRACT_NUMBER_AND_INCR (mcnt, p);
957 fprintf (stderr, "/on_failure_keep_string_jump to %td",
958 p + mcnt - start);
959 break;
961 case on_failure_jump_nastyloop:
962 EXTRACT_NUMBER_AND_INCR (mcnt, p);
963 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
964 p + mcnt - start);
965 break;
967 case on_failure_jump_loop:
968 EXTRACT_NUMBER_AND_INCR (mcnt, p);
969 fprintf (stderr, "/on_failure_jump_loop to %td",
970 p + mcnt - start);
971 break;
973 case on_failure_jump_smart:
974 EXTRACT_NUMBER_AND_INCR (mcnt, p);
975 fprintf (stderr, "/on_failure_jump_smart to %td",
976 p + mcnt - start);
977 break;
979 case jump:
980 EXTRACT_NUMBER_AND_INCR (mcnt, p);
981 fprintf (stderr, "/jump to %td", p + mcnt - start);
982 break;
984 case succeed_n:
985 EXTRACT_NUMBER_AND_INCR (mcnt, p);
986 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
987 fprintf (stderr, "/succeed_n to %td, %d times",
988 p - 2 + mcnt - start, mcnt2);
989 break;
991 case jump_n:
992 EXTRACT_NUMBER_AND_INCR (mcnt, p);
993 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
994 fprintf (stderr, "/jump_n to %td, %d times",
995 p - 2 + mcnt - start, mcnt2);
996 break;
998 case set_number_at:
999 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1000 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1001 fprintf (stderr, "/set_number_at location %td to %d",
1002 p - 2 + mcnt - start, mcnt2);
1003 break;
1005 case wordbound:
1006 fprintf (stderr, "/wordbound");
1007 break;
1009 case notwordbound:
1010 fprintf (stderr, "/notwordbound");
1011 break;
1013 case wordbeg:
1014 fprintf (stderr, "/wordbeg");
1015 break;
1017 case wordend:
1018 fprintf (stderr, "/wordend");
1019 break;
1021 case symbeg:
1022 fprintf (stderr, "/symbeg");
1023 break;
1025 case symend:
1026 fprintf (stderr, "/symend");
1027 break;
1029 case syntaxspec:
1030 fprintf (stderr, "/syntaxspec");
1031 mcnt = *p++;
1032 fprintf (stderr, "/%d", mcnt);
1033 break;
1035 case notsyntaxspec:
1036 fprintf (stderr, "/notsyntaxspec");
1037 mcnt = *p++;
1038 fprintf (stderr, "/%d", mcnt);
1039 break;
1041 # ifdef emacs
1042 case at_dot:
1043 fprintf (stderr, "/at_dot");
1044 break;
1046 case categoryspec:
1047 fprintf (stderr, "/categoryspec");
1048 mcnt = *p++;
1049 fprintf (stderr, "/%d", mcnt);
1050 break;
1052 case notcategoryspec:
1053 fprintf (stderr, "/notcategoryspec");
1054 mcnt = *p++;
1055 fprintf (stderr, "/%d", mcnt);
1056 break;
1057 # endif /* emacs */
1059 case begbuf:
1060 fprintf (stderr, "/begbuf");
1061 break;
1063 case endbuf:
1064 fprintf (stderr, "/endbuf");
1065 break;
1067 default:
1068 fprintf (stderr, "?%d", *(p-1));
1071 fprintf (stderr, "\n");
1074 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1078 static void
1079 print_compiled_pattern (struct re_pattern_buffer *bufp)
1081 re_char *buffer = bufp->buffer;
1083 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1084 printf ("%ld bytes used/%ld bytes allocated.\n",
1085 bufp->used, bufp->allocated);
1087 if (bufp->fastmap_accurate && bufp->fastmap)
1089 printf ("fastmap: ");
1090 print_fastmap (bufp->fastmap);
1093 printf ("re_nsub: %zu\t", bufp->re_nsub);
1094 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1095 printf ("can_be_null: %d\t", bufp->can_be_null);
1096 printf ("no_sub: %d\t", bufp->no_sub);
1097 printf ("not_bol: %d\t", bufp->not_bol);
1098 printf ("not_eol: %d\t", bufp->not_eol);
1099 #ifndef emacs
1100 printf ("syntax: %lx\n", bufp->syntax);
1101 #endif
1102 fflush (stdout);
1103 /* Perhaps we should print the translate table? */
1107 static void
1108 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1109 re_char *string2, ssize_t size2)
1111 ssize_t this_char;
1113 if (where == NULL)
1114 printf ("(null)");
1115 else
1117 if (FIRST_STRING_P (where))
1119 for (this_char = where - string1; this_char < size1; this_char++)
1120 putchar (string1[this_char]);
1122 where = string2;
1125 for (this_char = where - string2; this_char < size2; this_char++)
1126 putchar (string2[this_char]);
1130 #else /* not DEBUG */
1132 # undef assert
1133 # define assert(e)
1135 # define DEBUG_STATEMENT(e)
1136 # define DEBUG_PRINT(...)
1137 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1138 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1140 #endif /* not DEBUG */
1142 #ifndef emacs
1144 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1145 also be assigned to arbitrarily: each pattern buffer stores its own
1146 syntax, so it can be changed between regex compilations. */
1147 /* This has no initializer because initialized variables in Emacs
1148 become read-only after dumping. */
1149 reg_syntax_t re_syntax_options;
1152 /* Specify the precise syntax of regexps for compilation. This provides
1153 for compatibility for various utilities which historically have
1154 different, incompatible syntaxes.
1156 The argument SYNTAX is a bit mask comprised of the various bits
1157 defined in regex.h. We return the old syntax. */
1159 reg_syntax_t
1160 re_set_syntax (reg_syntax_t syntax)
1162 reg_syntax_t ret = re_syntax_options;
1164 re_syntax_options = syntax;
1165 return ret;
1167 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1169 #endif
1171 /* This table gives an error message for each of the error codes listed
1172 in regex.h. Obviously the order here has to be same as there.
1173 POSIX doesn't require that we do anything for REG_NOERROR,
1174 but why not be nice? */
1176 static const char *re_error_msgid[] =
1178 gettext_noop ("Success"), /* REG_NOERROR */
1179 gettext_noop ("No match"), /* REG_NOMATCH */
1180 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1181 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1182 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1183 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1184 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1185 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1186 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1187 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1188 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1189 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1190 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1191 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1192 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1193 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1194 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1195 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1198 /* Avoiding alloca during matching, to placate r_alloc. */
1200 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1201 searching and matching functions should not call alloca. On some
1202 systems, alloca is implemented in terms of malloc, and if we're
1203 using the relocating allocator routines, then malloc could cause a
1204 relocation, which might (if the strings being searched are in the
1205 ralloc heap) shift the data out from underneath the regexp
1206 routines.
1208 Here's another reason to avoid allocation: Emacs
1209 processes input from X in a signal handler; processing X input may
1210 call malloc; if input arrives while a matching routine is calling
1211 malloc, then we're scrod. But Emacs can't just block input while
1212 calling matching routines; then we don't notice interrupts when
1213 they come in. So, Emacs blocks input around all regexp calls
1214 except the matching calls, which it leaves unprotected, in the
1215 faith that they will not malloc. */
1217 /* Normally, this is fine. */
1218 #define MATCH_MAY_ALLOCATE
1220 /* The match routines may not allocate if (1) they would do it with malloc
1221 and (2) it's not safe for them to use malloc.
1222 Note that if REL_ALLOC is defined, matching would not use malloc for the
1223 failure stack, but we would still use it for the register vectors;
1224 so REL_ALLOC should not affect this. */
1225 #if defined REGEX_MALLOC && defined emacs
1226 # undef MATCH_MAY_ALLOCATE
1227 #endif
1230 /* Failure stack declarations and macros; both re_compile_fastmap and
1231 re_match_2 use a failure stack. These have to be macros because of
1232 REGEX_ALLOCATE_STACK. */
1235 /* Approximate number of failure points for which to initially allocate space
1236 when matching. If this number is exceeded, we allocate more
1237 space, so it is not a hard limit. */
1238 #ifndef INIT_FAILURE_ALLOC
1239 # define INIT_FAILURE_ALLOC 20
1240 #endif
1242 /* Roughly the maximum number of failure points on the stack. Would be
1243 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1244 This is a variable only so users of regex can assign to it; we never
1245 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1246 before using it, so it should probably be a byte-count instead. */
1247 # if defined MATCH_MAY_ALLOCATE
1248 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1249 whose default stack limit is 2mb. In order for a larger
1250 value to work reliably, you have to try to make it accord
1251 with the process stack limit. */
1252 size_t re_max_failures = 40000;
1253 # else
1254 size_t re_max_failures = 4000;
1255 # endif
1257 union fail_stack_elt
1259 re_char *pointer;
1260 /* This should be the biggest `int' that's no bigger than a pointer. */
1261 long integer;
1264 typedef union fail_stack_elt fail_stack_elt_t;
1266 typedef struct
1268 fail_stack_elt_t *stack;
1269 size_t size;
1270 size_t avail; /* Offset of next open position. */
1271 size_t frame; /* Offset of the cur constructed frame. */
1272 } fail_stack_type;
1274 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1277 /* Define macros to initialize and free the failure stack.
1278 Do `return -2' if the alloc fails. */
1280 #ifdef MATCH_MAY_ALLOCATE
1281 # define INIT_FAIL_STACK() \
1282 do { \
1283 fail_stack.stack = \
1284 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1285 * sizeof (fail_stack_elt_t)); \
1287 if (fail_stack.stack == NULL) \
1288 return -2; \
1290 fail_stack.size = INIT_FAILURE_ALLOC; \
1291 fail_stack.avail = 0; \
1292 fail_stack.frame = 0; \
1293 } while (0)
1294 #else
1295 # define INIT_FAIL_STACK() \
1296 do { \
1297 fail_stack.avail = 0; \
1298 fail_stack.frame = 0; \
1299 } while (0)
1301 # define RETALLOC_IF(addr, n, t) \
1302 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1303 #endif
1306 /* Double the size of FAIL_STACK, up to a limit
1307 which allows approximately `re_max_failures' items.
1309 Return 1 if succeeds, and 0 if either ran out of memory
1310 allocating space for it or it was already too large.
1312 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1314 /* Factor to increase the failure stack size by
1315 when we increase it.
1316 This used to be 2, but 2 was too wasteful
1317 because the old discarded stacks added up to as much space
1318 were as ultimate, maximum-size stack. */
1319 #define FAIL_STACK_GROWTH_FACTOR 4
1321 #define GROW_FAIL_STACK(fail_stack) \
1322 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1323 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1324 ? 0 \
1325 : ((fail_stack).stack \
1326 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1327 (fail_stack).size * sizeof (fail_stack_elt_t), \
1328 min (re_max_failures * TYPICAL_FAILURE_SIZE, \
1329 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1330 * FAIL_STACK_GROWTH_FACTOR))), \
1332 (fail_stack).stack == NULL \
1333 ? 0 \
1334 : ((fail_stack).size \
1335 = (min (re_max_failures * TYPICAL_FAILURE_SIZE, \
1336 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1337 * FAIL_STACK_GROWTH_FACTOR)) \
1338 / sizeof (fail_stack_elt_t)), \
1339 1)))
1342 /* Push a pointer value onto the failure stack.
1343 Assumes the variable `fail_stack'. Probably should only
1344 be called from within `PUSH_FAILURE_POINT'. */
1345 #define PUSH_FAILURE_POINTER(item) \
1346 fail_stack.stack[fail_stack.avail++].pointer = (item)
1348 /* This pushes an integer-valued item onto the failure stack.
1349 Assumes the variable `fail_stack'. Probably should only
1350 be called from within `PUSH_FAILURE_POINT'. */
1351 #define PUSH_FAILURE_INT(item) \
1352 fail_stack.stack[fail_stack.avail++].integer = (item)
1354 /* These POP... operations complement the PUSH... operations.
1355 All assume that `fail_stack' is nonempty. */
1356 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1357 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1359 /* Individual items aside from the registers. */
1360 #define NUM_NONREG_ITEMS 3
1362 /* Used to examine the stack (to detect infinite loops). */
1363 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1364 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1365 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1366 #define TOP_FAILURE_HANDLE() fail_stack.frame
1369 #define ENSURE_FAIL_STACK(space) \
1370 while (REMAINING_AVAIL_SLOTS <= space) { \
1371 if (!GROW_FAIL_STACK (fail_stack)) \
1372 return -2; \
1373 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1374 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1377 /* Push register NUM onto the stack. */
1378 #define PUSH_FAILURE_REG(num) \
1379 do { \
1380 char *destination; \
1381 long n = num; \
1382 ENSURE_FAIL_STACK(3); \
1383 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1384 n, regstart[n], regend[n]); \
1385 PUSH_FAILURE_POINTER (regstart[n]); \
1386 PUSH_FAILURE_POINTER (regend[n]); \
1387 PUSH_FAILURE_INT (n); \
1388 } while (0)
1390 /* Change the counter's value to VAL, but make sure that it will
1391 be reset when backtracking. */
1392 #define PUSH_NUMBER(ptr,val) \
1393 do { \
1394 char *destination; \
1395 int c; \
1396 ENSURE_FAIL_STACK(3); \
1397 EXTRACT_NUMBER (c, ptr); \
1398 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1399 PUSH_FAILURE_INT (c); \
1400 PUSH_FAILURE_POINTER (ptr); \
1401 PUSH_FAILURE_INT (-1); \
1402 STORE_NUMBER (ptr, val); \
1403 } while (0)
1405 /* Pop a saved register off the stack. */
1406 #define POP_FAILURE_REG_OR_COUNT() \
1407 do { \
1408 long pfreg = POP_FAILURE_INT (); \
1409 if (pfreg == -1) \
1411 /* It's a counter. */ \
1412 /* Here, we discard `const', making re_match non-reentrant. */ \
1413 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1414 pfreg = POP_FAILURE_INT (); \
1415 STORE_NUMBER (ptr, pfreg); \
1416 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1418 else \
1420 regend[pfreg] = POP_FAILURE_POINTER (); \
1421 regstart[pfreg] = POP_FAILURE_POINTER (); \
1422 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1423 pfreg, regstart[pfreg], regend[pfreg]); \
1425 } while (0)
1427 /* Check that we are not stuck in an infinite loop. */
1428 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1429 do { \
1430 ssize_t failure = TOP_FAILURE_HANDLE (); \
1431 /* Check for infinite matching loops */ \
1432 while (failure > 0 \
1433 && (FAILURE_STR (failure) == string_place \
1434 || FAILURE_STR (failure) == NULL)) \
1436 assert (FAILURE_PAT (failure) >= bufp->buffer \
1437 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1438 if (FAILURE_PAT (failure) == pat_cur) \
1440 cycle = 1; \
1441 break; \
1443 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1444 failure = NEXT_FAILURE_HANDLE(failure); \
1446 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1447 } while (0)
1449 /* Push the information about the state we will need
1450 if we ever fail back to it.
1452 Requires variables fail_stack, regstart, regend and
1453 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1454 declared.
1456 Does `return FAILURE_CODE' if runs out of memory. */
1458 #define PUSH_FAILURE_POINT(pattern, string_place) \
1459 do { \
1460 char *destination; \
1461 /* Must be int, so when we don't save any registers, the arithmetic \
1462 of 0 + -1 isn't done as unsigned. */ \
1464 DEBUG_STATEMENT (nfailure_points_pushed++); \
1465 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1466 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1467 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1469 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1471 DEBUG_PRINT ("\n"); \
1473 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1474 PUSH_FAILURE_INT (fail_stack.frame); \
1476 DEBUG_PRINT (" Push string %p: \"", string_place); \
1477 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1478 DEBUG_PRINT ("\"\n"); \
1479 PUSH_FAILURE_POINTER (string_place); \
1481 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1482 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1483 PUSH_FAILURE_POINTER (pattern); \
1485 /* Close the frame by moving the frame pointer past it. */ \
1486 fail_stack.frame = fail_stack.avail; \
1487 } while (0)
1489 /* Estimate the size of data pushed by a typical failure stack entry.
1490 An estimate is all we need, because all we use this for
1491 is to choose a limit for how big to make the failure stack. */
1492 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1493 #define TYPICAL_FAILURE_SIZE 20
1495 /* How many items can still be added to the stack without overflowing it. */
1496 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1499 /* Pops what PUSH_FAIL_STACK pushes.
1501 We restore into the parameters, all of which should be lvalues:
1502 STR -- the saved data position.
1503 PAT -- the saved pattern position.
1504 REGSTART, REGEND -- arrays of string positions.
1506 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1507 `pend', `string1', `size1', `string2', and `size2'. */
1509 #define POP_FAILURE_POINT(str, pat) \
1510 do { \
1511 assert (!FAIL_STACK_EMPTY ()); \
1513 /* Remove failure points and point to how many regs pushed. */ \
1514 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1515 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1516 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1518 /* Pop the saved registers. */ \
1519 while (fail_stack.frame < fail_stack.avail) \
1520 POP_FAILURE_REG_OR_COUNT (); \
1522 pat = POP_FAILURE_POINTER (); \
1523 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1524 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1526 /* If the saved string location is NULL, it came from an \
1527 on_failure_keep_string_jump opcode, and we want to throw away the \
1528 saved NULL, thus retaining our current position in the string. */ \
1529 str = POP_FAILURE_POINTER (); \
1530 DEBUG_PRINT (" Popping string %p: \"", str); \
1531 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1532 DEBUG_PRINT ("\"\n"); \
1534 fail_stack.frame = POP_FAILURE_INT (); \
1535 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1537 assert (fail_stack.avail >= 0); \
1538 assert (fail_stack.frame <= fail_stack.avail); \
1540 DEBUG_STATEMENT (nfailure_points_popped++); \
1541 } while (0) /* POP_FAILURE_POINT */
1545 /* Registers are set to a sentinel when they haven't yet matched. */
1546 #define REG_UNSET(e) ((e) == NULL)
1548 /* Subroutine declarations and macros for regex_compile. */
1550 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1551 #ifdef emacs
1552 bool posix_backtracking,
1553 const char *whitespace_regexp,
1554 #else
1555 reg_syntax_t syntax,
1556 #endif
1557 struct re_pattern_buffer *bufp);
1558 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1559 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1560 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1561 int arg, unsigned char *end);
1562 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1563 int arg1, int arg2, unsigned char *end);
1564 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1565 reg_syntax_t syntax);
1566 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1567 reg_syntax_t syntax);
1568 static re_char *skip_one_char (re_char *p);
1569 static int analyze_first (re_char *p, re_char *pend,
1570 char *fastmap, const int multibyte);
1572 /* Fetch the next character in the uncompiled pattern, with no
1573 translation. */
1574 #define PATFETCH(c) \
1575 do { \
1576 int len; \
1577 if (p == pend) return REG_EEND; \
1578 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1579 p += len; \
1580 } while (0)
1583 /* If `translate' is non-null, return translate[D], else just D. We
1584 cast the subscript to translate because some data is declared as
1585 `char *', to avoid warnings when a string constant is passed. But
1586 when we use a character as a subscript we must make it unsigned. */
1587 #ifndef TRANSLATE
1588 # define TRANSLATE(d) \
1589 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1590 #endif
1593 /* Macros for outputting the compiled pattern into `buffer'. */
1595 /* If the buffer isn't allocated when it comes in, use this. */
1596 #define INIT_BUF_SIZE 32
1598 /* Make sure we have at least N more bytes of space in buffer. */
1599 #define GET_BUFFER_SPACE(n) \
1600 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1601 EXTEND_BUFFER ()
1603 /* Make sure we have one more byte of buffer space and then add C to it. */
1604 #define BUF_PUSH(c) \
1605 do { \
1606 GET_BUFFER_SPACE (1); \
1607 *b++ = (unsigned char) (c); \
1608 } while (0)
1611 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1612 #define BUF_PUSH_2(c1, c2) \
1613 do { \
1614 GET_BUFFER_SPACE (2); \
1615 *b++ = (unsigned char) (c1); \
1616 *b++ = (unsigned char) (c2); \
1617 } while (0)
1620 /* Store a jump with opcode OP at LOC to location TO. We store a
1621 relative address offset by the three bytes the jump itself occupies. */
1622 #define STORE_JUMP(op, loc, to) \
1623 store_op1 (op, loc, (to) - (loc) - 3)
1625 /* Likewise, for a two-argument jump. */
1626 #define STORE_JUMP2(op, loc, to, arg) \
1627 store_op2 (op, loc, (to) - (loc) - 3, arg)
1629 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1630 #define INSERT_JUMP(op, loc, to) \
1631 insert_op1 (op, loc, (to) - (loc) - 3, b)
1633 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1634 #define INSERT_JUMP2(op, loc, to, arg) \
1635 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1638 /* This is not an arbitrary limit: the arguments which represent offsets
1639 into the pattern are two bytes long. So if 2^15 bytes turns out to
1640 be too small, many things would have to change. */
1641 # define MAX_BUF_SIZE (1L << 15)
1643 /* Extend the buffer by twice its current size via realloc and
1644 reset the pointers that pointed into the old block to point to the
1645 correct places in the new one. If extending the buffer results in it
1646 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1647 #if __BOUNDED_POINTERS__
1648 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1649 # define MOVE_BUFFER_POINTER(P) \
1650 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1651 SET_HIGH_BOUND (P), \
1652 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1653 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1654 else \
1656 SET_HIGH_BOUND (b); \
1657 SET_HIGH_BOUND (begalt); \
1658 if (fixup_alt_jump) \
1659 SET_HIGH_BOUND (fixup_alt_jump); \
1660 if (laststart) \
1661 SET_HIGH_BOUND (laststart); \
1662 if (pending_exact) \
1663 SET_HIGH_BOUND (pending_exact); \
1665 #else
1666 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1667 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1668 #endif
1669 #define EXTEND_BUFFER() \
1670 do { \
1671 unsigned char *old_buffer = bufp->buffer; \
1672 if (bufp->allocated == MAX_BUF_SIZE) \
1673 return REG_ESIZE; \
1674 bufp->allocated <<= 1; \
1675 if (bufp->allocated > MAX_BUF_SIZE) \
1676 bufp->allocated = MAX_BUF_SIZE; \
1677 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1678 if (bufp->buffer == NULL) \
1679 return REG_ESPACE; \
1680 /* If the buffer moved, move all the pointers into it. */ \
1681 if (old_buffer != bufp->buffer) \
1683 unsigned char *new_buffer = bufp->buffer; \
1684 MOVE_BUFFER_POINTER (b); \
1685 MOVE_BUFFER_POINTER (begalt); \
1686 if (fixup_alt_jump) \
1687 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1688 if (laststart) \
1689 MOVE_BUFFER_POINTER (laststart); \
1690 if (pending_exact) \
1691 MOVE_BUFFER_POINTER (pending_exact); \
1693 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1694 } while (0)
1697 /* Since we have one byte reserved for the register number argument to
1698 {start,stop}_memory, the maximum number of groups we can report
1699 things about is what fits in that byte. */
1700 #define MAX_REGNUM 255
1702 /* But patterns can have more than `MAX_REGNUM' registers. We just
1703 ignore the excess. */
1704 typedef int regnum_t;
1707 /* Macros for the compile stack. */
1709 /* Since offsets can go either forwards or backwards, this type needs to
1710 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1711 /* int may be not enough when sizeof(int) == 2. */
1712 typedef long pattern_offset_t;
1714 typedef struct
1716 pattern_offset_t begalt_offset;
1717 pattern_offset_t fixup_alt_jump;
1718 pattern_offset_t laststart_offset;
1719 regnum_t regnum;
1720 } compile_stack_elt_t;
1723 typedef struct
1725 compile_stack_elt_t *stack;
1726 size_t size;
1727 size_t avail; /* Offset of next open position. */
1728 } compile_stack_type;
1731 #define INIT_COMPILE_STACK_SIZE 32
1733 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1734 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1736 /* The next available element. */
1737 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1739 /* Explicit quit checking is needed for Emacs, which uses polling to
1740 process input events. */
1741 #ifdef emacs
1742 # define IMMEDIATE_QUIT_CHECK \
1743 do { \
1744 if (immediate_quit) QUIT; \
1745 } while (0)
1746 #else
1747 # define IMMEDIATE_QUIT_CHECK ((void)0)
1748 #endif
1750 /* Structure to manage work area for range table. */
1751 struct range_table_work_area
1753 int *table; /* actual work area. */
1754 int allocated; /* allocated size for work area in bytes. */
1755 int used; /* actually used size in words. */
1756 int bits; /* flag to record character classes */
1759 #ifdef emacs
1761 /* Make sure that WORK_AREA can hold more N multibyte characters.
1762 This is used only in set_image_of_range and set_image_of_range_1.
1763 It expects WORK_AREA to be a pointer.
1764 If it can't get the space, it returns from the surrounding function. */
1766 #define EXTEND_RANGE_TABLE(work_area, n) \
1767 do { \
1768 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1770 extend_range_table_work_area (&work_area); \
1771 if ((work_area).table == 0) \
1772 return (REG_ESPACE); \
1774 } while (0)
1776 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1777 (work_area).bits |= (bit)
1779 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1780 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1781 do { \
1782 EXTEND_RANGE_TABLE ((work_area), 2); \
1783 (work_area).table[(work_area).used++] = (range_start); \
1784 (work_area).table[(work_area).used++] = (range_end); \
1785 } while (0)
1787 #endif /* emacs */
1789 /* Free allocated memory for WORK_AREA. */
1790 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1791 do { \
1792 if ((work_area).table) \
1793 free ((work_area).table); \
1794 } while (0)
1796 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1797 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1798 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1799 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1801 /* Bits used to implement the multibyte-part of the various character classes
1802 such as [:alnum:] in a charset's range table. The code currently assumes
1803 that only the low 16 bits are used. */
1804 #define BIT_WORD 0x1
1805 #define BIT_LOWER 0x2
1806 #define BIT_PUNCT 0x4
1807 #define BIT_SPACE 0x8
1808 #define BIT_UPPER 0x10
1809 #define BIT_MULTIBYTE 0x20
1810 #define BIT_ALPHA 0x40
1811 #define BIT_ALNUM 0x80
1812 #define BIT_GRAPH 0x100
1813 #define BIT_PRINT 0x200
1816 /* Set the bit for character C in a list. */
1817 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1820 #ifdef emacs
1822 /* Store characters in the range FROM to TO in the bitmap at B (for
1823 ASCII and unibyte characters) and WORK_AREA (for multibyte
1824 characters) while translating them and paying attention to the
1825 continuity of translated characters.
1827 Implementation note: It is better to implement these fairly big
1828 macros by a function, but it's not that easy because macros called
1829 in this macro assume various local variables already declared. */
1831 /* Both FROM and TO are ASCII characters. */
1833 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1834 do { \
1835 int C0, C1; \
1837 for (C0 = (FROM); C0 <= (TO); C0++) \
1839 C1 = TRANSLATE (C0); \
1840 if (! ASCII_CHAR_P (C1)) \
1842 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1843 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1844 C1 = C0; \
1846 SET_LIST_BIT (C1); \
1848 } while (0)
1851 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1853 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1854 do { \
1855 int C0, C1, C2, I; \
1856 int USED = RANGE_TABLE_WORK_USED (work_area); \
1858 for (C0 = (FROM); C0 <= (TO); C0++) \
1860 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1861 if (CHAR_BYTE8_P (C1)) \
1862 SET_LIST_BIT (C0); \
1863 else \
1865 C2 = TRANSLATE (C1); \
1866 if (C2 == C1 \
1867 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1868 C1 = C0; \
1869 SET_LIST_BIT (C1); \
1870 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1872 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1873 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1875 if (C2 >= from - 1 && C2 <= to + 1) \
1877 if (C2 == from - 1) \
1878 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1879 else if (C2 == to + 1) \
1880 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1881 break; \
1884 if (I < USED) \
1885 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1888 } while (0)
1891 /* Both FROM and TO are multibyte characters. */
1893 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1894 do { \
1895 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1897 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1898 for (C0 = (FROM); C0 <= (TO); C0++) \
1900 C1 = TRANSLATE (C0); \
1901 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1902 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1903 SET_LIST_BIT (C2); \
1904 if (C1 >= (FROM) && C1 <= (TO)) \
1905 continue; \
1906 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1908 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1909 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1911 if (C1 >= from - 1 && C1 <= to + 1) \
1913 if (C1 == from - 1) \
1914 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1915 else if (C1 == to + 1) \
1916 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1917 break; \
1920 if (I < USED) \
1921 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1923 } while (0)
1925 #endif /* emacs */
1927 /* Get the next unsigned number in the uncompiled pattern. */
1928 #define GET_INTERVAL_COUNT(num) \
1929 do { \
1930 if (p == pend) \
1931 FREE_STACK_RETURN (REG_EBRACE); \
1932 else \
1934 PATFETCH (c); \
1935 while ('0' <= c && c <= '9') \
1937 if (num < 0) \
1938 num = 0; \
1939 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
1940 FREE_STACK_RETURN (REG_BADBR); \
1941 num = num * 10 + c - '0'; \
1942 if (p == pend) \
1943 FREE_STACK_RETURN (REG_EBRACE); \
1944 PATFETCH (c); \
1947 } while (0)
1949 #if ! WIDE_CHAR_SUPPORT
1951 /* Parse a character class, i.e. string such as "[:name:]". *strp
1952 points to the string to be parsed and limit is length, in bytes, of
1953 that string.
1955 If *strp point to a string that begins with "[:name:]", where name is
1956 a non-empty sequence of lower case letters, *strp will be advanced past the
1957 closing square bracket and RECC_* constant which maps to the name will be
1958 returned. If name is not a valid character class name zero, or RECC_ERROR,
1959 is returned.
1961 Otherwise, if *strp doesn’t begin with "[:name:]", -1 is returned.
1963 The function can be used on ASCII and multibyte (UTF-8-encoded) strings.
1965 re_wctype_t
1966 re_wctype_parse (const unsigned char **strp, unsigned limit)
1968 const char *beg = (const char *)*strp, *it;
1970 if (limit < 4 || beg[0] != '[' || beg[1] != ':')
1971 return -1;
1973 beg += 2; /* skip opening ‘[:’ */
1974 limit -= 3; /* opening ‘[:’ and half of closing ‘:]’; --limit handles rest */
1975 for (it = beg; it[0] != ':' || it[1] != ']'; ++it)
1976 if (!--limit)
1977 return -1;
1979 *strp = (const unsigned char *)(it + 2);
1981 /* Sort tests in the length=five case by frequency the classes to minimize
1982 number of times we fail the comparison. The frequencies of character class
1983 names used in Emacs sources as of 2016-07-27:
1985 $ find \( -name \*.c -o -name \*.el \) -exec grep -h '\[:[a-z]*:]' {} + |
1986 sed 's/]/]\n/g' |grep -o '\[:[a-z]*:]' |sort |uniq -c |sort -nr
1987 213 [:alnum:]
1988 104 [:alpha:]
1989 62 [:space:]
1990 39 [:digit:]
1991 36 [:blank:]
1992 26 [:word:]
1993 26 [:upper:]
1994 21 [:lower:]
1995 10 [:xdigit:]
1996 10 [:punct:]
1997 10 [:ascii:]
1998 4 [:nonascii:]
1999 4 [:graph:]
2000 2 [:print:]
2001 2 [:cntrl:]
2002 1 [:ff:]
2004 If you update this list, consider also updating chain of or’ed conditions
2005 in execute_charset function.
2008 switch (it - beg) {
2009 case 4:
2010 if (!memcmp (beg, "word", 4)) return RECC_WORD;
2011 break;
2012 case 5:
2013 if (!memcmp (beg, "alnum", 5)) return RECC_ALNUM;
2014 if (!memcmp (beg, "alpha", 5)) return RECC_ALPHA;
2015 if (!memcmp (beg, "space", 5)) return RECC_SPACE;
2016 if (!memcmp (beg, "digit", 5)) return RECC_DIGIT;
2017 if (!memcmp (beg, "blank", 5)) return RECC_BLANK;
2018 if (!memcmp (beg, "upper", 5)) return RECC_UPPER;
2019 if (!memcmp (beg, "lower", 5)) return RECC_LOWER;
2020 if (!memcmp (beg, "punct", 5)) return RECC_PUNCT;
2021 if (!memcmp (beg, "ascii", 5)) return RECC_ASCII;
2022 if (!memcmp (beg, "graph", 5)) return RECC_GRAPH;
2023 if (!memcmp (beg, "print", 5)) return RECC_PRINT;
2024 if (!memcmp (beg, "cntrl", 5)) return RECC_CNTRL;
2025 break;
2026 case 6:
2027 if (!memcmp (beg, "xdigit", 6)) return RECC_XDIGIT;
2028 break;
2029 case 7:
2030 if (!memcmp (beg, "unibyte", 7)) return RECC_UNIBYTE;
2031 break;
2032 case 8:
2033 if (!memcmp (beg, "nonascii", 8)) return RECC_NONASCII;
2034 break;
2035 case 9:
2036 if (!memcmp (beg, "multibyte", 9)) return RECC_MULTIBYTE;
2037 break;
2040 return RECC_ERROR;
2043 /* True if CH is in the char class CC. */
2044 boolean
2045 re_iswctype (int ch, re_wctype_t cc)
2047 switch (cc)
2049 case RECC_ALNUM: return ISALNUM (ch) != 0;
2050 case RECC_ALPHA: return ISALPHA (ch) != 0;
2051 case RECC_BLANK: return ISBLANK (ch) != 0;
2052 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2053 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2054 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2055 case RECC_LOWER: return ISLOWER (ch) != 0;
2056 case RECC_PRINT: return ISPRINT (ch) != 0;
2057 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2058 case RECC_SPACE: return ISSPACE (ch) != 0;
2059 case RECC_UPPER: return ISUPPER (ch) != 0;
2060 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2061 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2062 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2063 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2064 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2065 case RECC_WORD: return ISWORD (ch) != 0;
2066 case RECC_ERROR: return false;
2067 default:
2068 abort ();
2072 /* Return a bit-pattern to use in the range-table bits to match multibyte
2073 chars of class CC. */
2074 static int
2075 re_wctype_to_bit (re_wctype_t cc)
2077 switch (cc)
2079 case RECC_NONASCII:
2080 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2081 case RECC_ALPHA: return BIT_ALPHA;
2082 case RECC_ALNUM: return BIT_ALNUM;
2083 case RECC_WORD: return BIT_WORD;
2084 case RECC_LOWER: return BIT_LOWER;
2085 case RECC_UPPER: return BIT_UPPER;
2086 case RECC_PUNCT: return BIT_PUNCT;
2087 case RECC_SPACE: return BIT_SPACE;
2088 case RECC_GRAPH: return BIT_GRAPH;
2089 case RECC_PRINT: return BIT_PRINT;
2090 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2091 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2092 default:
2093 abort ();
2096 #endif
2098 /* Filling in the work area of a range. */
2100 /* Actually extend the space in WORK_AREA. */
2102 static void
2103 extend_range_table_work_area (struct range_table_work_area *work_area)
2105 work_area->allocated += 16 * sizeof (int);
2106 work_area->table = realloc (work_area->table, work_area->allocated);
2109 #if 0
2110 #ifdef emacs
2112 /* Carefully find the ranges of codes that are equivalent
2113 under case conversion to the range start..end when passed through
2114 TRANSLATE. Handle the case where non-letters can come in between
2115 two upper-case letters (which happens in Latin-1).
2116 Also handle the case of groups of more than 2 case-equivalent chars.
2118 The basic method is to look at consecutive characters and see
2119 if they can form a run that can be handled as one.
2121 Returns -1 if successful, REG_ESPACE if ran out of space. */
2123 static int
2124 set_image_of_range_1 (struct range_table_work_area *work_area,
2125 re_wchar_t start, re_wchar_t end,
2126 RE_TRANSLATE_TYPE translate)
2128 /* `one_case' indicates a character, or a run of characters,
2129 each of which is an isolate (no case-equivalents).
2130 This includes all ASCII non-letters.
2132 `two_case' indicates a character, or a run of characters,
2133 each of which has two case-equivalent forms.
2134 This includes all ASCII letters.
2136 `strange' indicates a character that has more than one
2137 case-equivalent. */
2139 enum case_type {one_case, two_case, strange};
2141 /* Describe the run that is in progress,
2142 which the next character can try to extend.
2143 If run_type is strange, that means there really is no run.
2144 If run_type is one_case, then run_start...run_end is the run.
2145 If run_type is two_case, then the run is run_start...run_end,
2146 and the case-equivalents end at run_eqv_end. */
2148 enum case_type run_type = strange;
2149 int run_start, run_end, run_eqv_end;
2151 Lisp_Object eqv_table;
2153 if (!RE_TRANSLATE_P (translate))
2155 EXTEND_RANGE_TABLE (work_area, 2);
2156 work_area->table[work_area->used++] = (start);
2157 work_area->table[work_area->used++] = (end);
2158 return -1;
2161 eqv_table = XCHAR_TABLE (translate)->extras[2];
2163 for (; start <= end; start++)
2165 enum case_type this_type;
2166 int eqv = RE_TRANSLATE (eqv_table, start);
2167 int minchar, maxchar;
2169 /* Classify this character */
2170 if (eqv == start)
2171 this_type = one_case;
2172 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2173 this_type = two_case;
2174 else
2175 this_type = strange;
2177 if (start < eqv)
2178 minchar = start, maxchar = eqv;
2179 else
2180 minchar = eqv, maxchar = start;
2182 /* Can this character extend the run in progress? */
2183 if (this_type == strange || this_type != run_type
2184 || !(minchar == run_end + 1
2185 && (run_type == two_case
2186 ? maxchar == run_eqv_end + 1 : 1)))
2188 /* No, end the run.
2189 Record each of its equivalent ranges. */
2190 if (run_type == one_case)
2192 EXTEND_RANGE_TABLE (work_area, 2);
2193 work_area->table[work_area->used++] = run_start;
2194 work_area->table[work_area->used++] = run_end;
2196 else if (run_type == two_case)
2198 EXTEND_RANGE_TABLE (work_area, 4);
2199 work_area->table[work_area->used++] = run_start;
2200 work_area->table[work_area->used++] = run_end;
2201 work_area->table[work_area->used++]
2202 = RE_TRANSLATE (eqv_table, run_start);
2203 work_area->table[work_area->used++]
2204 = RE_TRANSLATE (eqv_table, run_end);
2206 run_type = strange;
2209 if (this_type == strange)
2211 /* For a strange character, add each of its equivalents, one
2212 by one. Don't start a range. */
2215 EXTEND_RANGE_TABLE (work_area, 2);
2216 work_area->table[work_area->used++] = eqv;
2217 work_area->table[work_area->used++] = eqv;
2218 eqv = RE_TRANSLATE (eqv_table, eqv);
2220 while (eqv != start);
2223 /* Add this char to the run, or start a new run. */
2224 else if (run_type == strange)
2226 /* Initialize a new range. */
2227 run_type = this_type;
2228 run_start = start;
2229 run_end = start;
2230 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2232 else
2234 /* Extend a running range. */
2235 run_end = minchar;
2236 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2240 /* If a run is still in progress at the end, finish it now
2241 by recording its equivalent ranges. */
2242 if (run_type == one_case)
2244 EXTEND_RANGE_TABLE (work_area, 2);
2245 work_area->table[work_area->used++] = run_start;
2246 work_area->table[work_area->used++] = run_end;
2248 else if (run_type == two_case)
2250 EXTEND_RANGE_TABLE (work_area, 4);
2251 work_area->table[work_area->used++] = run_start;
2252 work_area->table[work_area->used++] = run_end;
2253 work_area->table[work_area->used++]
2254 = RE_TRANSLATE (eqv_table, run_start);
2255 work_area->table[work_area->used++]
2256 = RE_TRANSLATE (eqv_table, run_end);
2259 return -1;
2262 #endif /* emacs */
2264 /* Record the image of the range start..end when passed through
2265 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2266 and is not even necessarily contiguous.
2267 Normally we approximate it with the smallest contiguous range that contains
2268 all the chars we need. However, for Latin-1 we go to extra effort
2269 to do a better job.
2271 This function is not called for ASCII ranges.
2273 Returns -1 if successful, REG_ESPACE if ran out of space. */
2275 static int
2276 set_image_of_range (struct range_table_work_area *work_area,
2277 re_wchar_t start, re_wchar_t end,
2278 RE_TRANSLATE_TYPE translate)
2280 re_wchar_t cmin, cmax;
2282 #ifdef emacs
2283 /* For Latin-1 ranges, use set_image_of_range_1
2284 to get proper handling of ranges that include letters and nonletters.
2285 For a range that includes the whole of Latin-1, this is not necessary.
2286 For other character sets, we don't bother to get this right. */
2287 if (RE_TRANSLATE_P (translate) && start < 04400
2288 && !(start < 04200 && end >= 04377))
2290 int newend;
2291 int tem;
2292 newend = end;
2293 if (newend > 04377)
2294 newend = 04377;
2295 tem = set_image_of_range_1 (work_area, start, newend, translate);
2296 if (tem > 0)
2297 return tem;
2299 start = 04400;
2300 if (end < 04400)
2301 return -1;
2303 #endif
2305 EXTEND_RANGE_TABLE (work_area, 2);
2306 work_area->table[work_area->used++] = (start);
2307 work_area->table[work_area->used++] = (end);
2309 cmin = -1, cmax = -1;
2311 if (RE_TRANSLATE_P (translate))
2313 int ch;
2315 for (ch = start; ch <= end; ch++)
2317 re_wchar_t c = TRANSLATE (ch);
2318 if (! (start <= c && c <= end))
2320 if (cmin == -1)
2321 cmin = c, cmax = c;
2322 else
2324 cmin = min (cmin, c);
2325 cmax = max (cmax, c);
2330 if (cmin != -1)
2332 EXTEND_RANGE_TABLE (work_area, 2);
2333 work_area->table[work_area->used++] = (cmin);
2334 work_area->table[work_area->used++] = (cmax);
2338 return -1;
2340 #endif /* 0 */
2342 #ifndef MATCH_MAY_ALLOCATE
2344 /* If we cannot allocate large objects within re_match_2_internal,
2345 we make the fail stack and register vectors global.
2346 The fail stack, we grow to the maximum size when a regexp
2347 is compiled.
2348 The register vectors, we adjust in size each time we
2349 compile a regexp, according to the number of registers it needs. */
2351 static fail_stack_type fail_stack;
2353 /* Size with which the following vectors are currently allocated.
2354 That is so we can make them bigger as needed,
2355 but never make them smaller. */
2356 static int regs_allocated_size;
2358 static re_char ** regstart, ** regend;
2359 static re_char **best_regstart, **best_regend;
2361 /* Make the register vectors big enough for NUM_REGS registers,
2362 but don't make them smaller. */
2364 static
2365 regex_grow_registers (int num_regs)
2367 if (num_regs > regs_allocated_size)
2369 RETALLOC_IF (regstart, num_regs, re_char *);
2370 RETALLOC_IF (regend, num_regs, re_char *);
2371 RETALLOC_IF (best_regstart, num_regs, re_char *);
2372 RETALLOC_IF (best_regend, num_regs, re_char *);
2374 regs_allocated_size = num_regs;
2378 #endif /* not MATCH_MAY_ALLOCATE */
2380 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2381 regnum_t regnum);
2383 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2384 Returns one of error codes defined in `regex.h', or zero for success.
2386 If WHITESPACE_REGEXP is given (only #ifdef emacs), it is used instead of
2387 a space character in PATTERN.
2389 Assumes the `allocated' (and perhaps `buffer') and `translate'
2390 fields are set in BUFP on entry.
2392 If it succeeds, results are put in BUFP (if it returns an error, the
2393 contents of BUFP are undefined):
2394 `buffer' is the compiled pattern;
2395 `syntax' is set to SYNTAX;
2396 `used' is set to the length of the compiled pattern;
2397 `fastmap_accurate' is zero;
2398 `re_nsub' is the number of subexpressions in PATTERN;
2399 `not_bol' and `not_eol' are zero;
2401 The `fastmap' field is neither examined nor set. */
2403 /* Insert the `jump' from the end of last alternative to "here".
2404 The space for the jump has already been allocated. */
2405 #define FIXUP_ALT_JUMP() \
2406 do { \
2407 if (fixup_alt_jump) \
2408 STORE_JUMP (jump, fixup_alt_jump, b); \
2409 } while (0)
2412 /* Return, freeing storage we allocated. */
2413 #define FREE_STACK_RETURN(value) \
2414 do { \
2415 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2416 free (compile_stack.stack); \
2417 return value; \
2418 } while (0)
2420 static reg_errcode_t
2421 regex_compile (const_re_char *pattern, size_t size,
2422 #ifdef emacs
2423 # define syntax RE_SYNTAX_EMACS
2424 bool posix_backtracking,
2425 const char *whitespace_regexp,
2426 #else
2427 reg_syntax_t syntax,
2428 # define posix_backtracking (!(syntax & RE_NO_POSIX_BACKTRACKING))
2429 #endif
2430 struct re_pattern_buffer *bufp)
2432 /* We fetch characters from PATTERN here. */
2433 register re_wchar_t c, c1;
2435 /* Points to the end of the buffer, where we should append. */
2436 register unsigned char *b;
2438 /* Keeps track of unclosed groups. */
2439 compile_stack_type compile_stack;
2441 /* Points to the current (ending) position in the pattern. */
2442 #ifdef AIX
2443 /* `const' makes AIX compiler fail. */
2444 unsigned char *p = pattern;
2445 #else
2446 re_char *p = pattern;
2447 #endif
2448 re_char *pend = pattern + size;
2450 /* How to translate the characters in the pattern. */
2451 RE_TRANSLATE_TYPE translate = bufp->translate;
2453 /* Address of the count-byte of the most recently inserted `exactn'
2454 command. This makes it possible to tell if a new exact-match
2455 character can be added to that command or if the character requires
2456 a new `exactn' command. */
2457 unsigned char *pending_exact = 0;
2459 /* Address of start of the most recently finished expression.
2460 This tells, e.g., postfix * where to find the start of its
2461 operand. Reset at the beginning of groups and alternatives. */
2462 unsigned char *laststart = 0;
2464 /* Address of beginning of regexp, or inside of last group. */
2465 unsigned char *begalt;
2467 /* Place in the uncompiled pattern (i.e., the {) to
2468 which to go back if the interval is invalid. */
2469 re_char *beg_interval;
2471 /* Address of the place where a forward jump should go to the end of
2472 the containing expression. Each alternative of an `or' -- except the
2473 last -- ends with a forward jump of this sort. */
2474 unsigned char *fixup_alt_jump = 0;
2476 /* Work area for range table of charset. */
2477 struct range_table_work_area range_table_work;
2479 /* If the object matched can contain multibyte characters. */
2480 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2482 #ifdef emacs
2483 /* Nonzero if we have pushed down into a subpattern. */
2484 int in_subpattern = 0;
2486 /* These hold the values of p, pattern, and pend from the main
2487 pattern when we have pushed into a subpattern. */
2488 re_char *main_p;
2489 re_char *main_pattern;
2490 re_char *main_pend;
2491 #endif
2493 #ifdef DEBUG
2494 debug++;
2495 DEBUG_PRINT ("\nCompiling pattern: ");
2496 if (debug > 0)
2498 unsigned debug_count;
2500 for (debug_count = 0; debug_count < size; debug_count++)
2501 putchar (pattern[debug_count]);
2502 putchar ('\n');
2504 #endif /* DEBUG */
2506 /* Initialize the compile stack. */
2507 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2508 if (compile_stack.stack == NULL)
2509 return REG_ESPACE;
2511 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2512 compile_stack.avail = 0;
2514 range_table_work.table = 0;
2515 range_table_work.allocated = 0;
2517 /* Initialize the pattern buffer. */
2518 #ifndef emacs
2519 bufp->syntax = syntax;
2520 #endif
2521 bufp->fastmap_accurate = 0;
2522 bufp->not_bol = bufp->not_eol = 0;
2523 bufp->used_syntax = 0;
2525 /* Set `used' to zero, so that if we return an error, the pattern
2526 printer (for debugging) will think there's no pattern. We reset it
2527 at the end. */
2528 bufp->used = 0;
2530 /* Always count groups, whether or not bufp->no_sub is set. */
2531 bufp->re_nsub = 0;
2533 #if !defined emacs && !defined SYNTAX_TABLE
2534 /* Initialize the syntax table. */
2535 init_syntax_once ();
2536 #endif
2538 if (bufp->allocated == 0)
2540 if (bufp->buffer)
2541 { /* If zero allocated, but buffer is non-null, try to realloc
2542 enough space. This loses if buffer's address is bogus, but
2543 that is the user's responsibility. */
2544 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2546 else
2547 { /* Caller did not allocate a buffer. Do it for them. */
2548 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2550 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2552 bufp->allocated = INIT_BUF_SIZE;
2555 begalt = b = bufp->buffer;
2557 /* Loop through the uncompiled pattern until we're at the end. */
2558 while (1)
2560 if (p == pend)
2562 #ifdef emacs
2563 /* If this is the end of an included regexp,
2564 pop back to the main regexp and try again. */
2565 if (in_subpattern)
2567 in_subpattern = 0;
2568 pattern = main_pattern;
2569 p = main_p;
2570 pend = main_pend;
2571 continue;
2573 #endif
2574 /* If this is the end of the main regexp, we are done. */
2575 break;
2578 PATFETCH (c);
2580 switch (c)
2582 #ifdef emacs
2583 case ' ':
2585 re_char *p1 = p;
2587 /* If there's no special whitespace regexp, treat
2588 spaces normally. And don't try to do this recursively. */
2589 if (!whitespace_regexp || in_subpattern)
2590 goto normal_char;
2592 /* Peek past following spaces. */
2593 while (p1 != pend)
2595 if (*p1 != ' ')
2596 break;
2597 p1++;
2599 /* If the spaces are followed by a repetition op,
2600 treat them normally. */
2601 if (p1 != pend
2602 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2603 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2604 goto normal_char;
2606 /* Replace the spaces with the whitespace regexp. */
2607 in_subpattern = 1;
2608 main_p = p1;
2609 main_pend = pend;
2610 main_pattern = pattern;
2611 p = pattern = (re_char *) whitespace_regexp;
2612 pend = p + strlen (whitespace_regexp);
2613 break;
2615 #endif
2617 case '^':
2619 if ( /* If at start of pattern, it's an operator. */
2620 p == pattern + 1
2621 /* If context independent, it's an operator. */
2622 || syntax & RE_CONTEXT_INDEP_ANCHORS
2623 /* Otherwise, depends on what's come before. */
2624 || at_begline_loc_p (pattern, p, syntax))
2625 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2626 else
2627 goto normal_char;
2629 break;
2632 case '$':
2634 if ( /* If at end of pattern, it's an operator. */
2635 p == pend
2636 /* If context independent, it's an operator. */
2637 || syntax & RE_CONTEXT_INDEP_ANCHORS
2638 /* Otherwise, depends on what's next. */
2639 || at_endline_loc_p (p, pend, syntax))
2640 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2641 else
2642 goto normal_char;
2644 break;
2647 case '+':
2648 case '?':
2649 if ((syntax & RE_BK_PLUS_QM)
2650 || (syntax & RE_LIMITED_OPS))
2651 goto normal_char;
2652 handle_plus:
2653 case '*':
2654 /* If there is no previous pattern... */
2655 if (!laststart)
2657 if (syntax & RE_CONTEXT_INVALID_OPS)
2658 FREE_STACK_RETURN (REG_BADRPT);
2659 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2660 goto normal_char;
2664 /* 1 means zero (many) matches is allowed. */
2665 boolean zero_times_ok = 0, many_times_ok = 0;
2666 boolean greedy = 1;
2668 /* If there is a sequence of repetition chars, collapse it
2669 down to just one (the right one). We can't combine
2670 interval operators with these because of, e.g., `a{2}*',
2671 which should only match an even number of `a's. */
2673 for (;;)
2675 if ((syntax & RE_FRUGAL)
2676 && c == '?' && (zero_times_ok || many_times_ok))
2677 greedy = 0;
2678 else
2680 zero_times_ok |= c != '+';
2681 many_times_ok |= c != '?';
2684 if (p == pend)
2685 break;
2686 else if (*p == '*'
2687 || (!(syntax & RE_BK_PLUS_QM)
2688 && (*p == '+' || *p == '?')))
2690 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2692 if (p+1 == pend)
2693 FREE_STACK_RETURN (REG_EESCAPE);
2694 if (p[1] == '+' || p[1] == '?')
2695 PATFETCH (c); /* Gobble up the backslash. */
2696 else
2697 break;
2699 else
2700 break;
2701 /* If we get here, we found another repeat character. */
2702 PATFETCH (c);
2705 /* Star, etc. applied to an empty pattern is equivalent
2706 to an empty pattern. */
2707 if (!laststart || laststart == b)
2708 break;
2710 /* Now we know whether or not zero matches is allowed
2711 and also whether or not two or more matches is allowed. */
2712 if (greedy)
2714 if (many_times_ok)
2716 boolean simple = skip_one_char (laststart) == b;
2717 size_t startoffset = 0;
2718 re_opcode_t ofj =
2719 /* Check if the loop can match the empty string. */
2720 (simple || !analyze_first (laststart, b, NULL, 0))
2721 ? on_failure_jump : on_failure_jump_loop;
2722 assert (skip_one_char (laststart) <= b);
2724 if (!zero_times_ok && simple)
2725 { /* Since simple * loops can be made faster by using
2726 on_failure_keep_string_jump, we turn simple P+
2727 into PP* if P is simple. */
2728 unsigned char *p1, *p2;
2729 startoffset = b - laststart;
2730 GET_BUFFER_SPACE (startoffset);
2731 p1 = b; p2 = laststart;
2732 while (p2 < p1)
2733 *b++ = *p2++;
2734 zero_times_ok = 1;
2737 GET_BUFFER_SPACE (6);
2738 if (!zero_times_ok)
2739 /* A + loop. */
2740 STORE_JUMP (ofj, b, b + 6);
2741 else
2742 /* Simple * loops can use on_failure_keep_string_jump
2743 depending on what follows. But since we don't know
2744 that yet, we leave the decision up to
2745 on_failure_jump_smart. */
2746 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2747 laststart + startoffset, b + 6);
2748 b += 3;
2749 STORE_JUMP (jump, b, laststart + startoffset);
2750 b += 3;
2752 else
2754 /* A simple ? pattern. */
2755 assert (zero_times_ok);
2756 GET_BUFFER_SPACE (3);
2757 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2758 b += 3;
2761 else /* not greedy */
2762 { /* I wish the greedy and non-greedy cases could be merged. */
2764 GET_BUFFER_SPACE (7); /* We might use less. */
2765 if (many_times_ok)
2767 boolean emptyp = analyze_first (laststart, b, NULL, 0);
2769 /* The non-greedy multiple match looks like
2770 a repeat..until: we only need a conditional jump
2771 at the end of the loop. */
2772 if (emptyp) BUF_PUSH (no_op);
2773 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2774 : on_failure_jump, b, laststart);
2775 b += 3;
2776 if (zero_times_ok)
2778 /* The repeat...until naturally matches one or more.
2779 To also match zero times, we need to first jump to
2780 the end of the loop (its conditional jump). */
2781 INSERT_JUMP (jump, laststart, b);
2782 b += 3;
2785 else
2787 /* non-greedy a?? */
2788 INSERT_JUMP (jump, laststart, b + 3);
2789 b += 3;
2790 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2791 b += 3;
2795 pending_exact = 0;
2796 break;
2799 case '.':
2800 laststart = b;
2801 BUF_PUSH (anychar);
2802 break;
2805 case '[':
2807 re_char *p1;
2809 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2811 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2813 /* Ensure that we have enough space to push a charset: the
2814 opcode, the length count, and the bitset; 34 bytes in all. */
2815 GET_BUFFER_SPACE (34);
2817 laststart = b;
2819 /* We test `*p == '^' twice, instead of using an if
2820 statement, so we only need one BUF_PUSH. */
2821 BUF_PUSH (*p == '^' ? charset_not : charset);
2822 if (*p == '^')
2823 p++;
2825 /* Remember the first position in the bracket expression. */
2826 p1 = p;
2828 /* Push the number of bytes in the bitmap. */
2829 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2831 /* Clear the whole map. */
2832 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2834 /* charset_not matches newline according to a syntax bit. */
2835 if ((re_opcode_t) b[-2] == charset_not
2836 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2837 SET_LIST_BIT ('\n');
2839 /* Read in characters and ranges, setting map bits. */
2840 for (;;)
2842 boolean escaped_char = false;
2843 const unsigned char *p2 = p;
2844 re_wctype_t cc;
2845 re_wchar_t ch;
2847 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2849 /* See if we're at the beginning of a possible character
2850 class. */
2851 if (syntax & RE_CHAR_CLASSES &&
2852 (cc = re_wctype_parse(&p, pend - p)) != -1)
2854 if (cc == 0)
2855 FREE_STACK_RETURN (REG_ECTYPE);
2857 if (p == pend)
2858 FREE_STACK_RETURN (REG_EBRACK);
2860 #ifndef emacs
2861 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2862 if (re_iswctype (btowc (ch), cc))
2864 c = TRANSLATE (ch);
2865 if (c < (1 << BYTEWIDTH))
2866 SET_LIST_BIT (c);
2868 #else /* emacs */
2869 /* Most character classes in a multibyte match just set
2870 a flag. Exceptions are is_blank, is_digit, is_cntrl, and
2871 is_xdigit, since they can only match ASCII characters.
2872 We don't need to handle them for multibyte. */
2874 /* Setup the gl_state object to its buffer-defined value.
2875 This hardcodes the buffer-global syntax-table for ASCII
2876 chars, while the other chars will obey syntax-table
2877 properties. It's not ideal, but it's the way it's been
2878 done until now. */
2879 SETUP_BUFFER_SYNTAX_TABLE ();
2881 for (c = 0; c < 0x80; ++c)
2882 if (re_iswctype (c, cc))
2884 SET_LIST_BIT (c);
2885 c1 = TRANSLATE (c);
2886 if (c1 == c)
2887 continue;
2888 if (ASCII_CHAR_P (c1))
2889 SET_LIST_BIT (c1);
2890 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2891 SET_LIST_BIT (c1);
2893 SET_RANGE_TABLE_WORK_AREA_BIT
2894 (range_table_work, re_wctype_to_bit (cc));
2895 #endif /* emacs */
2896 /* In most cases the matching rule for char classes only
2897 uses the syntax table for multibyte chars, so that the
2898 content of the syntax-table is not hardcoded in the
2899 range_table. SPACE and WORD are the two exceptions. */
2900 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2901 bufp->used_syntax = 1;
2903 /* Repeat the loop. */
2904 continue;
2907 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2908 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2909 So the translation is done later in a loop. Example:
2910 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2911 PATFETCH (c);
2913 /* \ might escape characters inside [...] and [^...]. */
2914 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2916 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2918 PATFETCH (c);
2919 escaped_char = true;
2921 else
2923 /* Could be the end of the bracket expression. If it's
2924 not (i.e., when the bracket expression is `[]' so
2925 far), the ']' character bit gets set way below. */
2926 if (c == ']' && p2 != p1)
2927 break;
2930 if (p < pend && p[0] == '-' && p[1] != ']')
2933 /* Discard the `-'. */
2934 PATFETCH (c1);
2936 /* Fetch the character which ends the range. */
2937 PATFETCH (c1);
2938 #ifdef emacs
2939 if (CHAR_BYTE8_P (c1)
2940 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2941 /* Treat the range from a multibyte character to
2942 raw-byte character as empty. */
2943 c = c1 + 1;
2944 #endif /* emacs */
2946 else
2947 /* Range from C to C. */
2948 c1 = c;
2950 if (c > c1)
2952 if (syntax & RE_NO_EMPTY_RANGES)
2953 FREE_STACK_RETURN (REG_ERANGEX);
2954 /* Else, repeat the loop. */
2956 else
2958 #ifndef emacs
2959 /* Set the range into bitmap */
2960 for (; c <= c1; c++)
2962 ch = TRANSLATE (c);
2963 if (ch < (1 << BYTEWIDTH))
2964 SET_LIST_BIT (ch);
2966 #else /* emacs */
2967 if (c < 128)
2969 ch = min (127, c1);
2970 SETUP_ASCII_RANGE (range_table_work, c, ch);
2971 c = ch + 1;
2972 if (CHAR_BYTE8_P (c1))
2973 c = BYTE8_TO_CHAR (128);
2975 if (c <= c1)
2977 if (CHAR_BYTE8_P (c))
2979 c = CHAR_TO_BYTE8 (c);
2980 c1 = CHAR_TO_BYTE8 (c1);
2981 for (; c <= c1; c++)
2982 SET_LIST_BIT (c);
2984 else if (multibyte)
2986 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
2988 else
2990 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
2993 #endif /* emacs */
2997 /* Discard any (non)matching list bytes that are all 0 at the
2998 end of the map. Decrease the map-length byte too. */
2999 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3000 b[-1]--;
3001 b += b[-1];
3003 /* Build real range table from work area. */
3004 if (RANGE_TABLE_WORK_USED (range_table_work)
3005 || RANGE_TABLE_WORK_BITS (range_table_work))
3007 int i;
3008 int used = RANGE_TABLE_WORK_USED (range_table_work);
3010 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3011 bytes for flags, two for COUNT, and three bytes for
3012 each character. */
3013 GET_BUFFER_SPACE (4 + used * 3);
3015 /* Indicate the existence of range table. */
3016 laststart[1] |= 0x80;
3018 /* Store the character class flag bits into the range table.
3019 If not in emacs, these flag bits are always 0. */
3020 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3021 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3023 STORE_NUMBER_AND_INCR (b, used / 2);
3024 for (i = 0; i < used; i++)
3025 STORE_CHARACTER_AND_INCR
3026 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3029 break;
3032 case '(':
3033 if (syntax & RE_NO_BK_PARENS)
3034 goto handle_open;
3035 else
3036 goto normal_char;
3039 case ')':
3040 if (syntax & RE_NO_BK_PARENS)
3041 goto handle_close;
3042 else
3043 goto normal_char;
3046 case '\n':
3047 if (syntax & RE_NEWLINE_ALT)
3048 goto handle_alt;
3049 else
3050 goto normal_char;
3053 case '|':
3054 if (syntax & RE_NO_BK_VBAR)
3055 goto handle_alt;
3056 else
3057 goto normal_char;
3060 case '{':
3061 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3062 goto handle_interval;
3063 else
3064 goto normal_char;
3067 case '\\':
3068 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3070 /* Do not translate the character after the \, so that we can
3071 distinguish, e.g., \B from \b, even if we normally would
3072 translate, e.g., B to b. */
3073 PATFETCH (c);
3075 switch (c)
3077 case '(':
3078 if (syntax & RE_NO_BK_PARENS)
3079 goto normal_backslash;
3081 handle_open:
3083 int shy = 0;
3084 regnum_t regnum = 0;
3085 if (p+1 < pend)
3087 /* Look for a special (?...) construct */
3088 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3090 PATFETCH (c); /* Gobble up the '?'. */
3091 while (!shy)
3093 PATFETCH (c);
3094 switch (c)
3096 case ':': shy = 1; break;
3097 case '0':
3098 /* An explicitly specified regnum must start
3099 with non-0. */
3100 if (regnum == 0)
3101 FREE_STACK_RETURN (REG_BADPAT);
3102 case '1': case '2': case '3': case '4':
3103 case '5': case '6': case '7': case '8': case '9':
3104 regnum = 10*regnum + (c - '0'); break;
3105 default:
3106 /* Only (?:...) is supported right now. */
3107 FREE_STACK_RETURN (REG_BADPAT);
3113 if (!shy)
3114 regnum = ++bufp->re_nsub;
3115 else if (regnum)
3116 { /* It's actually not shy, but explicitly numbered. */
3117 shy = 0;
3118 if (regnum > bufp->re_nsub)
3119 bufp->re_nsub = regnum;
3120 else if (regnum > bufp->re_nsub
3121 /* Ideally, we'd want to check that the specified
3122 group can't have matched (i.e. all subgroups
3123 using the same regnum are in other branches of
3124 OR patterns), but we don't currently keep track
3125 of enough info to do that easily. */
3126 || group_in_compile_stack (compile_stack, regnum))
3127 FREE_STACK_RETURN (REG_BADPAT);
3129 else
3130 /* It's really shy. */
3131 regnum = - bufp->re_nsub;
3133 if (COMPILE_STACK_FULL)
3135 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3136 compile_stack_elt_t);
3137 if (compile_stack.stack == NULL) return REG_ESPACE;
3139 compile_stack.size <<= 1;
3142 /* These are the values to restore when we hit end of this
3143 group. They are all relative offsets, so that if the
3144 whole pattern moves because of realloc, they will still
3145 be valid. */
3146 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3147 COMPILE_STACK_TOP.fixup_alt_jump
3148 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3149 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3150 COMPILE_STACK_TOP.regnum = regnum;
3152 /* Do not push a start_memory for groups beyond the last one
3153 we can represent in the compiled pattern. */
3154 if (regnum <= MAX_REGNUM && regnum > 0)
3155 BUF_PUSH_2 (start_memory, regnum);
3157 compile_stack.avail++;
3159 fixup_alt_jump = 0;
3160 laststart = 0;
3161 begalt = b;
3162 /* If we've reached MAX_REGNUM groups, then this open
3163 won't actually generate any code, so we'll have to
3164 clear pending_exact explicitly. */
3165 pending_exact = 0;
3166 break;
3169 case ')':
3170 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3172 if (COMPILE_STACK_EMPTY)
3174 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3175 goto normal_backslash;
3176 else
3177 FREE_STACK_RETURN (REG_ERPAREN);
3180 handle_close:
3181 FIXUP_ALT_JUMP ();
3183 /* See similar code for backslashed left paren above. */
3184 if (COMPILE_STACK_EMPTY)
3186 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3187 goto normal_char;
3188 else
3189 FREE_STACK_RETURN (REG_ERPAREN);
3192 /* Since we just checked for an empty stack above, this
3193 ``can't happen''. */
3194 assert (compile_stack.avail != 0);
3196 /* We don't just want to restore into `regnum', because
3197 later groups should continue to be numbered higher,
3198 as in `(ab)c(de)' -- the second group is #2. */
3199 regnum_t regnum;
3201 compile_stack.avail--;
3202 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3203 fixup_alt_jump
3204 = COMPILE_STACK_TOP.fixup_alt_jump
3205 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3206 : 0;
3207 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3208 regnum = COMPILE_STACK_TOP.regnum;
3209 /* If we've reached MAX_REGNUM groups, then this open
3210 won't actually generate any code, so we'll have to
3211 clear pending_exact explicitly. */
3212 pending_exact = 0;
3214 /* We're at the end of the group, so now we know how many
3215 groups were inside this one. */
3216 if (regnum <= MAX_REGNUM && regnum > 0)
3217 BUF_PUSH_2 (stop_memory, regnum);
3219 break;
3222 case '|': /* `\|'. */
3223 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3224 goto normal_backslash;
3225 handle_alt:
3226 if (syntax & RE_LIMITED_OPS)
3227 goto normal_char;
3229 /* Insert before the previous alternative a jump which
3230 jumps to this alternative if the former fails. */
3231 GET_BUFFER_SPACE (3);
3232 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3233 pending_exact = 0;
3234 b += 3;
3236 /* The alternative before this one has a jump after it
3237 which gets executed if it gets matched. Adjust that
3238 jump so it will jump to this alternative's analogous
3239 jump (put in below, which in turn will jump to the next
3240 (if any) alternative's such jump, etc.). The last such
3241 jump jumps to the correct final destination. A picture:
3242 _____ _____
3243 | | | |
3244 | v | v
3245 a | b | c
3247 If we are at `b', then fixup_alt_jump right now points to a
3248 three-byte space after `a'. We'll put in the jump, set
3249 fixup_alt_jump to right after `b', and leave behind three
3250 bytes which we'll fill in when we get to after `c'. */
3252 FIXUP_ALT_JUMP ();
3254 /* Mark and leave space for a jump after this alternative,
3255 to be filled in later either by next alternative or
3256 when know we're at the end of a series of alternatives. */
3257 fixup_alt_jump = b;
3258 GET_BUFFER_SPACE (3);
3259 b += 3;
3261 laststart = 0;
3262 begalt = b;
3263 break;
3266 case '{':
3267 /* If \{ is a literal. */
3268 if (!(syntax & RE_INTERVALS)
3269 /* If we're at `\{' and it's not the open-interval
3270 operator. */
3271 || (syntax & RE_NO_BK_BRACES))
3272 goto normal_backslash;
3274 handle_interval:
3276 /* If got here, then the syntax allows intervals. */
3278 /* At least (most) this many matches must be made. */
3279 int lower_bound = 0, upper_bound = -1;
3281 beg_interval = p;
3283 GET_INTERVAL_COUNT (lower_bound);
3285 if (c == ',')
3286 GET_INTERVAL_COUNT (upper_bound);
3287 else
3288 /* Interval such as `{1}' => match exactly once. */
3289 upper_bound = lower_bound;
3291 if (lower_bound < 0
3292 || (0 <= upper_bound && upper_bound < lower_bound))
3293 FREE_STACK_RETURN (REG_BADBR);
3295 if (!(syntax & RE_NO_BK_BRACES))
3297 if (c != '\\')
3298 FREE_STACK_RETURN (REG_BADBR);
3299 if (p == pend)
3300 FREE_STACK_RETURN (REG_EESCAPE);
3301 PATFETCH (c);
3304 if (c != '}')
3305 FREE_STACK_RETURN (REG_BADBR);
3307 /* We just parsed a valid interval. */
3309 /* If it's invalid to have no preceding re. */
3310 if (!laststart)
3312 if (syntax & RE_CONTEXT_INVALID_OPS)
3313 FREE_STACK_RETURN (REG_BADRPT);
3314 else if (syntax & RE_CONTEXT_INDEP_OPS)
3315 laststart = b;
3316 else
3317 goto unfetch_interval;
3320 if (upper_bound == 0)
3321 /* If the upper bound is zero, just drop the sub pattern
3322 altogether. */
3323 b = laststart;
3324 else if (lower_bound == 1 && upper_bound == 1)
3325 /* Just match it once: nothing to do here. */
3328 /* Otherwise, we have a nontrivial interval. When
3329 we're all done, the pattern will look like:
3330 set_number_at <jump count> <upper bound>
3331 set_number_at <succeed_n count> <lower bound>
3332 succeed_n <after jump addr> <succeed_n count>
3333 <body of loop>
3334 jump_n <succeed_n addr> <jump count>
3335 (The upper bound and `jump_n' are omitted if
3336 `upper_bound' is 1, though.) */
3337 else
3338 { /* If the upper bound is > 1, we need to insert
3339 more at the end of the loop. */
3340 unsigned int nbytes = (upper_bound < 0 ? 3
3341 : upper_bound > 1 ? 5 : 0);
3342 unsigned int startoffset = 0;
3344 GET_BUFFER_SPACE (20); /* We might use less. */
3346 if (lower_bound == 0)
3348 /* A succeed_n that starts with 0 is really a
3349 a simple on_failure_jump_loop. */
3350 INSERT_JUMP (on_failure_jump_loop, laststart,
3351 b + 3 + nbytes);
3352 b += 3;
3354 else
3356 /* Initialize lower bound of the `succeed_n', even
3357 though it will be set during matching by its
3358 attendant `set_number_at' (inserted next),
3359 because `re_compile_fastmap' needs to know.
3360 Jump to the `jump_n' we might insert below. */
3361 INSERT_JUMP2 (succeed_n, laststart,
3362 b + 5 + nbytes,
3363 lower_bound);
3364 b += 5;
3366 /* Code to initialize the lower bound. Insert
3367 before the `succeed_n'. The `5' is the last two
3368 bytes of this `set_number_at', plus 3 bytes of
3369 the following `succeed_n'. */
3370 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3371 b += 5;
3372 startoffset += 5;
3375 if (upper_bound < 0)
3377 /* A negative upper bound stands for infinity,
3378 in which case it degenerates to a plain jump. */
3379 STORE_JUMP (jump, b, laststart + startoffset);
3380 b += 3;
3382 else if (upper_bound > 1)
3383 { /* More than one repetition is allowed, so
3384 append a backward jump to the `succeed_n'
3385 that starts this interval.
3387 When we've reached this during matching,
3388 we'll have matched the interval once, so
3389 jump back only `upper_bound - 1' times. */
3390 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3391 upper_bound - 1);
3392 b += 5;
3394 /* The location we want to set is the second
3395 parameter of the `jump_n'; that is `b-2' as
3396 an absolute address. `laststart' will be
3397 the `set_number_at' we're about to insert;
3398 `laststart+3' the number to set, the source
3399 for the relative address. But we are
3400 inserting into the middle of the pattern --
3401 so everything is getting moved up by 5.
3402 Conclusion: (b - 2) - (laststart + 3) + 5,
3403 i.e., b - laststart.
3405 We insert this at the beginning of the loop
3406 so that if we fail during matching, we'll
3407 reinitialize the bounds. */
3408 insert_op2 (set_number_at, laststart, b - laststart,
3409 upper_bound - 1, b);
3410 b += 5;
3413 pending_exact = 0;
3414 beg_interval = NULL;
3416 break;
3418 unfetch_interval:
3419 /* If an invalid interval, match the characters as literals. */
3420 assert (beg_interval);
3421 p = beg_interval;
3422 beg_interval = NULL;
3424 /* normal_char and normal_backslash need `c'. */
3425 c = '{';
3427 if (!(syntax & RE_NO_BK_BRACES))
3429 assert (p > pattern && p[-1] == '\\');
3430 goto normal_backslash;
3432 else
3433 goto normal_char;
3435 #ifdef emacs
3436 case '=':
3437 laststart = b;
3438 BUF_PUSH (at_dot);
3439 break;
3441 case 's':
3442 laststart = b;
3443 PATFETCH (c);
3444 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3445 break;
3447 case 'S':
3448 laststart = b;
3449 PATFETCH (c);
3450 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3451 break;
3453 case 'c':
3454 laststart = b;
3455 PATFETCH (c);
3456 BUF_PUSH_2 (categoryspec, c);
3457 break;
3459 case 'C':
3460 laststart = b;
3461 PATFETCH (c);
3462 BUF_PUSH_2 (notcategoryspec, c);
3463 break;
3464 #endif /* emacs */
3467 case 'w':
3468 if (syntax & RE_NO_GNU_OPS)
3469 goto normal_char;
3470 laststart = b;
3471 BUF_PUSH_2 (syntaxspec, Sword);
3472 break;
3475 case 'W':
3476 if (syntax & RE_NO_GNU_OPS)
3477 goto normal_char;
3478 laststart = b;
3479 BUF_PUSH_2 (notsyntaxspec, Sword);
3480 break;
3483 case '<':
3484 if (syntax & RE_NO_GNU_OPS)
3485 goto normal_char;
3486 laststart = b;
3487 BUF_PUSH (wordbeg);
3488 break;
3490 case '>':
3491 if (syntax & RE_NO_GNU_OPS)
3492 goto normal_char;
3493 laststart = b;
3494 BUF_PUSH (wordend);
3495 break;
3497 case '_':
3498 if (syntax & RE_NO_GNU_OPS)
3499 goto normal_char;
3500 laststart = b;
3501 PATFETCH (c);
3502 if (c == '<')
3503 BUF_PUSH (symbeg);
3504 else if (c == '>')
3505 BUF_PUSH (symend);
3506 else
3507 FREE_STACK_RETURN (REG_BADPAT);
3508 break;
3510 case 'b':
3511 if (syntax & RE_NO_GNU_OPS)
3512 goto normal_char;
3513 BUF_PUSH (wordbound);
3514 break;
3516 case 'B':
3517 if (syntax & RE_NO_GNU_OPS)
3518 goto normal_char;
3519 BUF_PUSH (notwordbound);
3520 break;
3522 case '`':
3523 if (syntax & RE_NO_GNU_OPS)
3524 goto normal_char;
3525 BUF_PUSH (begbuf);
3526 break;
3528 case '\'':
3529 if (syntax & RE_NO_GNU_OPS)
3530 goto normal_char;
3531 BUF_PUSH (endbuf);
3532 break;
3534 case '1': case '2': case '3': case '4': case '5':
3535 case '6': case '7': case '8': case '9':
3537 regnum_t reg;
3539 if (syntax & RE_NO_BK_REFS)
3540 goto normal_backslash;
3542 reg = c - '0';
3544 if (reg > bufp->re_nsub || reg < 1
3545 /* Can't back reference to a subexp before its end. */
3546 || group_in_compile_stack (compile_stack, reg))
3547 FREE_STACK_RETURN (REG_ESUBREG);
3549 laststart = b;
3550 BUF_PUSH_2 (duplicate, reg);
3552 break;
3555 case '+':
3556 case '?':
3557 if (syntax & RE_BK_PLUS_QM)
3558 goto handle_plus;
3559 else
3560 goto normal_backslash;
3562 default:
3563 normal_backslash:
3564 /* You might think it would be useful for \ to mean
3565 not to translate; but if we don't translate it
3566 it will never match anything. */
3567 goto normal_char;
3569 break;
3572 default:
3573 /* Expects the character in `c'. */
3574 normal_char:
3575 /* If no exactn currently being built. */
3576 if (!pending_exact
3578 /* If last exactn not at current position. */
3579 || pending_exact + *pending_exact + 1 != b
3581 /* We have only one byte following the exactn for the count. */
3582 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3584 /* If followed by a repetition operator. */
3585 || (p != pend && (*p == '*' || *p == '^'))
3586 || ((syntax & RE_BK_PLUS_QM)
3587 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3588 : p != pend && (*p == '+' || *p == '?'))
3589 || ((syntax & RE_INTERVALS)
3590 && ((syntax & RE_NO_BK_BRACES)
3591 ? p != pend && *p == '{'
3592 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3594 /* Start building a new exactn. */
3596 laststart = b;
3598 BUF_PUSH_2 (exactn, 0);
3599 pending_exact = b - 1;
3602 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3604 int len;
3606 if (multibyte)
3608 c = TRANSLATE (c);
3609 len = CHAR_STRING (c, b);
3610 b += len;
3612 else
3614 c1 = RE_CHAR_TO_MULTIBYTE (c);
3615 if (! CHAR_BYTE8_P (c1))
3617 re_wchar_t c2 = TRANSLATE (c1);
3619 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3620 c = c1;
3622 *b++ = c;
3623 len = 1;
3625 (*pending_exact) += len;
3628 break;
3629 } /* switch (c) */
3630 } /* while p != pend */
3633 /* Through the pattern now. */
3635 FIXUP_ALT_JUMP ();
3637 if (!COMPILE_STACK_EMPTY)
3638 FREE_STACK_RETURN (REG_EPAREN);
3640 /* If we don't want backtracking, force success
3641 the first time we reach the end of the compiled pattern. */
3642 if (!posix_backtracking)
3643 BUF_PUSH (succeed);
3645 /* We have succeeded; set the length of the buffer. */
3646 bufp->used = b - bufp->buffer;
3648 #ifdef DEBUG
3649 if (debug > 0)
3651 re_compile_fastmap (bufp);
3652 DEBUG_PRINT ("\nCompiled pattern: \n");
3653 print_compiled_pattern (bufp);
3655 debug--;
3656 #endif /* DEBUG */
3658 #ifndef MATCH_MAY_ALLOCATE
3659 /* Initialize the failure stack to the largest possible stack. This
3660 isn't necessary unless we're trying to avoid calling alloca in
3661 the search and match routines. */
3663 int num_regs = bufp->re_nsub + 1;
3665 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3667 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3668 falk_stack.stack = realloc (fail_stack.stack,
3669 fail_stack.size * sizeof *falk_stack.stack);
3672 regex_grow_registers (num_regs);
3674 #endif /* not MATCH_MAY_ALLOCATE */
3676 FREE_STACK_RETURN (REG_NOERROR);
3678 #ifdef emacs
3679 # undef syntax
3680 #else
3681 # undef posix_backtracking
3682 #endif
3683 } /* regex_compile */
3685 /* Subroutines for `regex_compile'. */
3687 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3689 static void
3690 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3692 *loc = (unsigned char) op;
3693 STORE_NUMBER (loc + 1, arg);
3697 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3699 static void
3700 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3702 *loc = (unsigned char) op;
3703 STORE_NUMBER (loc + 1, arg1);
3704 STORE_NUMBER (loc + 3, arg2);
3708 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3709 for OP followed by two-byte integer parameter ARG. */
3711 static void
3712 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3714 register unsigned char *pfrom = end;
3715 register unsigned char *pto = end + 3;
3717 while (pfrom != loc)
3718 *--pto = *--pfrom;
3720 store_op1 (op, loc, arg);
3724 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3726 static void
3727 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3729 register unsigned char *pfrom = end;
3730 register unsigned char *pto = end + 5;
3732 while (pfrom != loc)
3733 *--pto = *--pfrom;
3735 store_op2 (op, loc, arg1, arg2);
3739 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3740 after an alternative or a begin-subexpression. We assume there is at
3741 least one character before the ^. */
3743 static boolean
3744 at_begline_loc_p (const_re_char *pattern, const_re_char *p, reg_syntax_t syntax)
3746 re_char *prev = p - 2;
3747 boolean odd_backslashes;
3749 /* After a subexpression? */
3750 if (*prev == '(')
3751 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3753 /* After an alternative? */
3754 else if (*prev == '|')
3755 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3757 /* After a shy subexpression? */
3758 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3760 /* Skip over optional regnum. */
3761 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3762 --prev;
3764 if (!(prev - 2 >= pattern
3765 && prev[-1] == '?' && prev[-2] == '('))
3766 return false;
3767 prev -= 2;
3768 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3770 else
3771 return false;
3773 /* Count the number of preceding backslashes. */
3774 p = prev;
3775 while (prev - 1 >= pattern && prev[-1] == '\\')
3776 --prev;
3777 return (p - prev) & odd_backslashes;
3781 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3782 at least one character after the $, i.e., `P < PEND'. */
3784 static boolean
3785 at_endline_loc_p (const_re_char *p, const_re_char *pend, reg_syntax_t syntax)
3787 re_char *next = p;
3788 boolean next_backslash = *next == '\\';
3789 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3791 return
3792 /* Before a subexpression? */
3793 (syntax & RE_NO_BK_PARENS ? *next == ')'
3794 : next_backslash && next_next && *next_next == ')')
3795 /* Before an alternative? */
3796 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3797 : next_backslash && next_next && *next_next == '|');
3801 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3802 false if it's not. */
3804 static boolean
3805 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3807 ssize_t this_element;
3809 for (this_element = compile_stack.avail - 1;
3810 this_element >= 0;
3811 this_element--)
3812 if (compile_stack.stack[this_element].regnum == regnum)
3813 return true;
3815 return false;
3818 /* analyze_first.
3819 If fastmap is non-NULL, go through the pattern and fill fastmap
3820 with all the possible leading chars. If fastmap is NULL, don't
3821 bother filling it up (obviously) and only return whether the
3822 pattern could potentially match the empty string.
3824 Return 1 if p..pend might match the empty string.
3825 Return 0 if p..pend matches at least one char.
3826 Return -1 if fastmap was not updated accurately. */
3828 static int
3829 analyze_first (const_re_char *p, const_re_char *pend, char *fastmap,
3830 const int multibyte)
3832 int j, k;
3833 boolean not;
3835 /* If all elements for base leading-codes in fastmap is set, this
3836 flag is set true. */
3837 boolean match_any_multibyte_characters = false;
3839 assert (p);
3841 /* The loop below works as follows:
3842 - It has a working-list kept in the PATTERN_STACK and which basically
3843 starts by only containing a pointer to the first operation.
3844 - If the opcode we're looking at is a match against some set of
3845 chars, then we add those chars to the fastmap and go on to the
3846 next work element from the worklist (done via `break').
3847 - If the opcode is a control operator on the other hand, we either
3848 ignore it (if it's meaningless at this point, such as `start_memory')
3849 or execute it (if it's a jump). If the jump has several destinations
3850 (i.e. `on_failure_jump'), then we push the other destination onto the
3851 worklist.
3852 We guarantee termination by ignoring backward jumps (more or less),
3853 so that `p' is monotonically increasing. More to the point, we
3854 never set `p' (or push) anything `<= p1'. */
3856 while (p < pend)
3858 /* `p1' is used as a marker of how far back a `on_failure_jump'
3859 can go without being ignored. It is normally equal to `p'
3860 (which prevents any backward `on_failure_jump') except right
3861 after a plain `jump', to allow patterns such as:
3862 0: jump 10
3863 3..9: <body>
3864 10: on_failure_jump 3
3865 as used for the *? operator. */
3866 re_char *p1 = p;
3868 switch (*p++)
3870 case succeed:
3871 return 1;
3873 case duplicate:
3874 /* If the first character has to match a backreference, that means
3875 that the group was empty (since it already matched). Since this
3876 is the only case that interests us here, we can assume that the
3877 backreference must match the empty string. */
3878 p++;
3879 continue;
3882 /* Following are the cases which match a character. These end
3883 with `break'. */
3885 case exactn:
3886 if (fastmap)
3888 /* If multibyte is nonzero, the first byte of each
3889 character is an ASCII or a leading code. Otherwise,
3890 each byte is a character. Thus, this works in both
3891 cases. */
3892 fastmap[p[1]] = 1;
3893 if (! multibyte)
3895 /* For the case of matching this unibyte regex
3896 against multibyte, we must set a leading code of
3897 the corresponding multibyte character. */
3898 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3900 fastmap[CHAR_LEADING_CODE (c)] = 1;
3903 break;
3906 case anychar:
3907 /* We could put all the chars except for \n (and maybe \0)
3908 but we don't bother since it is generally not worth it. */
3909 if (!fastmap) break;
3910 return -1;
3913 case charset_not:
3914 if (!fastmap) break;
3916 /* Chars beyond end of bitmap are possible matches. */
3917 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3918 j < (1 << BYTEWIDTH); j++)
3919 fastmap[j] = 1;
3922 /* Fallthrough */
3923 case charset:
3924 if (!fastmap) break;
3925 not = (re_opcode_t) *(p - 1) == charset_not;
3926 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3927 j >= 0; j--)
3928 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3929 fastmap[j] = 1;
3931 #ifdef emacs
3932 if (/* Any leading code can possibly start a character
3933 which doesn't match the specified set of characters. */
3936 /* If we can match a character class, we can match any
3937 multibyte characters. */
3938 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3939 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3942 if (match_any_multibyte_characters == false)
3944 for (j = MIN_MULTIBYTE_LEADING_CODE;
3945 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3946 fastmap[j] = 1;
3947 match_any_multibyte_characters = true;
3951 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3952 && match_any_multibyte_characters == false)
3954 /* Set fastmap[I] to 1 where I is a leading code of each
3955 multibyte character in the range table. */
3956 int c, count;
3957 unsigned char lc1, lc2;
3959 /* Make P points the range table. `+ 2' is to skip flag
3960 bits for a character class. */
3961 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3963 /* Extract the number of ranges in range table into COUNT. */
3964 EXTRACT_NUMBER_AND_INCR (count, p);
3965 for (; count > 0; count--, p += 3)
3967 /* Extract the start and end of each range. */
3968 EXTRACT_CHARACTER (c, p);
3969 lc1 = CHAR_LEADING_CODE (c);
3970 p += 3;
3971 EXTRACT_CHARACTER (c, p);
3972 lc2 = CHAR_LEADING_CODE (c);
3973 for (j = lc1; j <= lc2; j++)
3974 fastmap[j] = 1;
3977 #endif
3978 break;
3980 case syntaxspec:
3981 case notsyntaxspec:
3982 if (!fastmap) break;
3983 #ifndef emacs
3984 not = (re_opcode_t)p[-1] == notsyntaxspec;
3985 k = *p++;
3986 for (j = 0; j < (1 << BYTEWIDTH); j++)
3987 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3988 fastmap[j] = 1;
3989 break;
3990 #else /* emacs */
3991 /* This match depends on text properties. These end with
3992 aborting optimizations. */
3993 return -1;
3995 case categoryspec:
3996 case notcategoryspec:
3997 if (!fastmap) break;
3998 not = (re_opcode_t)p[-1] == notcategoryspec;
3999 k = *p++;
4000 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4001 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4002 fastmap[j] = 1;
4004 /* Any leading code can possibly start a character which
4005 has or doesn't has the specified category. */
4006 if (match_any_multibyte_characters == false)
4008 for (j = MIN_MULTIBYTE_LEADING_CODE;
4009 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4010 fastmap[j] = 1;
4011 match_any_multibyte_characters = true;
4013 break;
4015 /* All cases after this match the empty string. These end with
4016 `continue'. */
4018 case at_dot:
4019 #endif /* !emacs */
4020 case no_op:
4021 case begline:
4022 case endline:
4023 case begbuf:
4024 case endbuf:
4025 case wordbound:
4026 case notwordbound:
4027 case wordbeg:
4028 case wordend:
4029 case symbeg:
4030 case symend:
4031 continue;
4034 case jump:
4035 EXTRACT_NUMBER_AND_INCR (j, p);
4036 if (j < 0)
4037 /* Backward jumps can only go back to code that we've already
4038 visited. `re_compile' should make sure this is true. */
4039 break;
4040 p += j;
4041 switch (*p)
4043 case on_failure_jump:
4044 case on_failure_keep_string_jump:
4045 case on_failure_jump_loop:
4046 case on_failure_jump_nastyloop:
4047 case on_failure_jump_smart:
4048 p++;
4049 break;
4050 default:
4051 continue;
4053 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4054 to jump back to "just after here". */
4055 /* Fallthrough */
4057 case on_failure_jump:
4058 case on_failure_keep_string_jump:
4059 case on_failure_jump_nastyloop:
4060 case on_failure_jump_loop:
4061 case on_failure_jump_smart:
4062 EXTRACT_NUMBER_AND_INCR (j, p);
4063 if (p + j <= p1)
4064 ; /* Backward jump to be ignored. */
4065 else
4066 { /* We have to look down both arms.
4067 We first go down the "straight" path so as to minimize
4068 stack usage when going through alternatives. */
4069 int r = analyze_first (p, pend, fastmap, multibyte);
4070 if (r) return r;
4071 p += j;
4073 continue;
4076 case jump_n:
4077 /* This code simply does not properly handle forward jump_n. */
4078 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4079 p += 4;
4080 /* jump_n can either jump or fall through. The (backward) jump
4081 case has already been handled, so we only need to look at the
4082 fallthrough case. */
4083 continue;
4085 case succeed_n:
4086 /* If N == 0, it should be an on_failure_jump_loop instead. */
4087 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4088 p += 4;
4089 /* We only care about one iteration of the loop, so we don't
4090 need to consider the case where this behaves like an
4091 on_failure_jump. */
4092 continue;
4095 case set_number_at:
4096 p += 4;
4097 continue;
4100 case start_memory:
4101 case stop_memory:
4102 p += 1;
4103 continue;
4106 default:
4107 abort (); /* We have listed all the cases. */
4108 } /* switch *p++ */
4110 /* Getting here means we have found the possible starting
4111 characters for one path of the pattern -- and that the empty
4112 string does not match. We need not follow this path further. */
4113 return 0;
4114 } /* while p */
4116 /* We reached the end without matching anything. */
4117 return 1;
4119 } /* analyze_first */
4121 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4122 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4123 characters can start a string that matches the pattern. This fastmap
4124 is used by re_search to skip quickly over impossible starting points.
4126 Character codes above (1 << BYTEWIDTH) are not represented in the
4127 fastmap, but the leading codes are represented. Thus, the fastmap
4128 indicates which character sets could start a match.
4130 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4131 area as BUFP->fastmap.
4133 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4134 the pattern buffer.
4136 Returns 0 if we succeed, -2 if an internal error. */
4139 re_compile_fastmap (struct re_pattern_buffer *bufp)
4141 char *fastmap = bufp->fastmap;
4142 int analysis;
4144 assert (fastmap && bufp->buffer);
4146 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4147 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4149 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4150 fastmap, RE_MULTIBYTE_P (bufp));
4151 bufp->can_be_null = (analysis != 0);
4152 return 0;
4153 } /* re_compile_fastmap */
4155 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4156 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4157 this memory for recording register information. STARTS and ENDS
4158 must be allocated using the malloc library routine, and must each
4159 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4161 If NUM_REGS == 0, then subsequent matches should allocate their own
4162 register data.
4164 Unless this function is called, the first search or match using
4165 PATTERN_BUFFER will allocate its own register data, without
4166 freeing the old data. */
4168 void
4169 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4171 if (num_regs)
4173 bufp->regs_allocated = REGS_REALLOCATE;
4174 regs->num_regs = num_regs;
4175 regs->start = starts;
4176 regs->end = ends;
4178 else
4180 bufp->regs_allocated = REGS_UNALLOCATED;
4181 regs->num_regs = 0;
4182 regs->start = regs->end = 0;
4185 WEAK_ALIAS (__re_set_registers, re_set_registers)
4187 /* Searching routines. */
4189 /* Like re_search_2, below, but only one string is specified, and
4190 doesn't let you say where to stop matching. */
4192 regoff_t
4193 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4194 ssize_t startpos, ssize_t range, struct re_registers *regs)
4196 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4197 regs, size);
4199 WEAK_ALIAS (__re_search, re_search)
4201 /* Head address of virtual concatenation of string. */
4202 #define HEAD_ADDR_VSTRING(P) \
4203 (((P) >= size1 ? string2 : string1))
4205 /* Address of POS in the concatenation of virtual string. */
4206 #define POS_ADDR_VSTRING(POS) \
4207 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4209 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4210 virtual concatenation of STRING1 and STRING2, starting first at index
4211 STARTPOS, then at STARTPOS + 1, and so on.
4213 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4215 RANGE is how far to scan while trying to match. RANGE = 0 means try
4216 only at STARTPOS; in general, the last start tried is STARTPOS +
4217 RANGE.
4219 In REGS, return the indices of the virtual concatenation of STRING1
4220 and STRING2 that matched the entire BUFP->buffer and its contained
4221 subexpressions.
4223 Do not consider matching one past the index STOP in the virtual
4224 concatenation of STRING1 and STRING2.
4226 We return either the position in the strings at which the match was
4227 found, -1 if no match, or -2 if error (such as failure
4228 stack overflow). */
4230 regoff_t
4231 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4232 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4233 struct re_registers *regs, ssize_t stop)
4235 regoff_t val;
4236 re_char *string1 = (re_char*) str1;
4237 re_char *string2 = (re_char*) str2;
4238 register char *fastmap = bufp->fastmap;
4239 register RE_TRANSLATE_TYPE translate = bufp->translate;
4240 size_t total_size = size1 + size2;
4241 ssize_t endpos = startpos + range;
4242 boolean anchored_start;
4243 /* Nonzero if we are searching multibyte string. */
4244 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4246 /* Check for out-of-range STARTPOS. */
4247 if (startpos < 0 || startpos > total_size)
4248 return -1;
4250 /* Fix up RANGE if it might eventually take us outside
4251 the virtual concatenation of STRING1 and STRING2.
4252 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4253 if (endpos < 0)
4254 range = 0 - startpos;
4255 else if (endpos > total_size)
4256 range = total_size - startpos;
4258 /* If the search isn't to be a backwards one, don't waste time in a
4259 search for a pattern anchored at beginning of buffer. */
4260 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4262 if (startpos > 0)
4263 return -1;
4264 else
4265 range = 0;
4268 #ifdef emacs
4269 /* In a forward search for something that starts with \=.
4270 don't keep searching past point. */
4271 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4273 range = PT_BYTE - BEGV_BYTE - startpos;
4274 if (range < 0)
4275 return -1;
4277 #endif /* emacs */
4279 /* Update the fastmap now if not correct already. */
4280 if (fastmap && !bufp->fastmap_accurate)
4281 re_compile_fastmap (bufp);
4283 /* See whether the pattern is anchored. */
4284 anchored_start = (bufp->buffer[0] == begline);
4286 #ifdef emacs
4287 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4289 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4291 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4293 #endif
4295 /* Loop through the string, looking for a place to start matching. */
4296 for (;;)
4298 /* If the pattern is anchored,
4299 skip quickly past places we cannot match.
4300 We don't bother to treat startpos == 0 specially
4301 because that case doesn't repeat. */
4302 if (anchored_start && startpos > 0)
4304 if (! ((startpos <= size1 ? string1[startpos - 1]
4305 : string2[startpos - size1 - 1])
4306 == '\n'))
4307 goto advance;
4310 /* If a fastmap is supplied, skip quickly over characters that
4311 cannot be the start of a match. If the pattern can match the
4312 null string, however, we don't need to skip characters; we want
4313 the first null string. */
4314 if (fastmap && startpos < total_size && !bufp->can_be_null)
4316 register re_char *d;
4317 register re_wchar_t buf_ch;
4319 d = POS_ADDR_VSTRING (startpos);
4321 if (range > 0) /* Searching forwards. */
4323 ssize_t irange = range, lim = 0;
4325 if (startpos < size1 && startpos + range >= size1)
4326 lim = range - (size1 - startpos);
4328 /* Written out as an if-else to avoid testing `translate'
4329 inside the loop. */
4330 if (RE_TRANSLATE_P (translate))
4332 if (multibyte)
4333 while (range > lim)
4335 int buf_charlen;
4337 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4338 buf_ch = RE_TRANSLATE (translate, buf_ch);
4339 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4340 break;
4342 range -= buf_charlen;
4343 d += buf_charlen;
4345 else
4346 while (range > lim)
4348 register re_wchar_t ch, translated;
4350 buf_ch = *d;
4351 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4352 translated = RE_TRANSLATE (translate, ch);
4353 if (translated != ch
4354 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4355 buf_ch = ch;
4356 if (fastmap[buf_ch])
4357 break;
4358 d++;
4359 range--;
4362 else
4364 if (multibyte)
4365 while (range > lim)
4367 int buf_charlen;
4369 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4370 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4371 break;
4372 range -= buf_charlen;
4373 d += buf_charlen;
4375 else
4376 while (range > lim && !fastmap[*d])
4378 d++;
4379 range--;
4382 startpos += irange - range;
4384 else /* Searching backwards. */
4386 if (multibyte)
4388 buf_ch = STRING_CHAR (d);
4389 buf_ch = TRANSLATE (buf_ch);
4390 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4391 goto advance;
4393 else
4395 register re_wchar_t ch, translated;
4397 buf_ch = *d;
4398 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4399 translated = TRANSLATE (ch);
4400 if (translated != ch
4401 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4402 buf_ch = ch;
4403 if (! fastmap[TRANSLATE (buf_ch)])
4404 goto advance;
4409 /* If can't match the null string, and that's all we have left, fail. */
4410 if (range >= 0 && startpos == total_size && fastmap
4411 && !bufp->can_be_null)
4412 return -1;
4414 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4415 startpos, regs, stop);
4417 if (val >= 0)
4418 return startpos;
4420 if (val == -2)
4421 return -2;
4423 advance:
4424 if (!range)
4425 break;
4426 else if (range > 0)
4428 /* Update STARTPOS to the next character boundary. */
4429 if (multibyte)
4431 re_char *p = POS_ADDR_VSTRING (startpos);
4432 int len = BYTES_BY_CHAR_HEAD (*p);
4434 range -= len;
4435 if (range < 0)
4436 break;
4437 startpos += len;
4439 else
4441 range--;
4442 startpos++;
4445 else
4447 range++;
4448 startpos--;
4450 /* Update STARTPOS to the previous character boundary. */
4451 if (multibyte)
4453 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4454 re_char *p0 = p;
4455 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4457 /* Find the head of multibyte form. */
4458 PREV_CHAR_BOUNDARY (p, phead);
4459 range += p0 - 1 - p;
4460 if (range > 0)
4461 break;
4463 startpos -= p0 - 1 - p;
4467 return -1;
4468 } /* re_search_2 */
4469 WEAK_ALIAS (__re_search_2, re_search_2)
4471 /* Declarations and macros for re_match_2. */
4473 static int bcmp_translate (re_char *s1, re_char *s2,
4474 register ssize_t len,
4475 RE_TRANSLATE_TYPE translate,
4476 const int multibyte);
4478 /* This converts PTR, a pointer into one of the search strings `string1'
4479 and `string2' into an offset from the beginning of that string. */
4480 #define POINTER_TO_OFFSET(ptr) \
4481 (FIRST_STRING_P (ptr) \
4482 ? (ptr) - string1 \
4483 : (ptr) - string2 + (ptrdiff_t) size1)
4485 /* Call before fetching a character with *d. This switches over to
4486 string2 if necessary.
4487 Check re_match_2_internal for a discussion of why end_match_2 might
4488 not be within string2 (but be equal to end_match_1 instead). */
4489 #define PREFETCH() \
4490 while (d == dend) \
4492 /* End of string2 => fail. */ \
4493 if (dend == end_match_2) \
4494 goto fail; \
4495 /* End of string1 => advance to string2. */ \
4496 d = string2; \
4497 dend = end_match_2; \
4500 /* Call before fetching a char with *d if you already checked other limits.
4501 This is meant for use in lookahead operations like wordend, etc..
4502 where we might need to look at parts of the string that might be
4503 outside of the LIMITs (i.e past `stop'). */
4504 #define PREFETCH_NOLIMIT() \
4505 if (d == end1) \
4507 d = string2; \
4508 dend = end_match_2; \
4511 /* Test if at very beginning or at very end of the virtual concatenation
4512 of `string1' and `string2'. If only one string, it's `string2'. */
4513 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4514 #define AT_STRINGS_END(d) ((d) == end2)
4516 /* Disabled due to a compiler bug -- see comment at case wordbound */
4518 /* The comment at case wordbound is following one, but we don't use
4519 AT_WORD_BOUNDARY anymore to support multibyte form.
4521 The DEC Alpha C compiler 3.x generates incorrect code for the
4522 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4523 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4524 macro and introducing temporary variables works around the bug. */
4526 #if 0
4527 /* Test if D points to a character which is word-constituent. We have
4528 two special cases to check for: if past the end of string1, look at
4529 the first character in string2; and if before the beginning of
4530 string2, look at the last character in string1. */
4531 #define WORDCHAR_P(d) \
4532 (SYNTAX ((d) == end1 ? *string2 \
4533 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4534 == Sword)
4536 /* Test if the character before D and the one at D differ with respect
4537 to being word-constituent. */
4538 #define AT_WORD_BOUNDARY(d) \
4539 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4540 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4541 #endif
4543 /* Free everything we malloc. */
4544 #ifdef MATCH_MAY_ALLOCATE
4545 # define FREE_VAR(var) \
4546 do { \
4547 if (var) \
4549 REGEX_FREE (var); \
4550 var = NULL; \
4552 } while (0)
4553 # define FREE_VARIABLES() \
4554 do { \
4555 REGEX_FREE_STACK (fail_stack.stack); \
4556 FREE_VAR (regstart); \
4557 FREE_VAR (regend); \
4558 FREE_VAR (best_regstart); \
4559 FREE_VAR (best_regend); \
4560 REGEX_SAFE_FREE (); \
4561 } while (0)
4562 #else
4563 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4564 #endif /* not MATCH_MAY_ALLOCATE */
4567 /* Optimization routines. */
4569 /* If the operation is a match against one or more chars,
4570 return a pointer to the next operation, else return NULL. */
4571 static re_char *
4572 skip_one_char (const_re_char *p)
4574 switch (*p++)
4576 case anychar:
4577 break;
4579 case exactn:
4580 p += *p + 1;
4581 break;
4583 case charset_not:
4584 case charset:
4585 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4587 int mcnt;
4588 p = CHARSET_RANGE_TABLE (p - 1);
4589 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4590 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4592 else
4593 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4594 break;
4596 case syntaxspec:
4597 case notsyntaxspec:
4598 #ifdef emacs
4599 case categoryspec:
4600 case notcategoryspec:
4601 #endif /* emacs */
4602 p++;
4603 break;
4605 default:
4606 p = NULL;
4608 return p;
4612 /* Jump over non-matching operations. */
4613 static re_char *
4614 skip_noops (const_re_char *p, const_re_char *pend)
4616 int mcnt;
4617 while (p < pend)
4619 switch (*p)
4621 case start_memory:
4622 case stop_memory:
4623 p += 2; break;
4624 case no_op:
4625 p += 1; break;
4626 case jump:
4627 p += 1;
4628 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4629 p += mcnt;
4630 break;
4631 default:
4632 return p;
4635 assert (p == pend);
4636 return p;
4639 /* Test if C matches charset op. *PP points to the charset or charset_not
4640 opcode. When the function finishes, *PP will be advanced past that opcode.
4641 C is character to test (possibly after translations) and CORIG is original
4642 character (i.e. without any translations). UNIBYTE denotes whether c is
4643 unibyte or multibyte character. */
4644 static bool
4645 execute_charset (const_re_char **pp, unsigned c, unsigned corig, bool unibyte)
4647 re_char *p = *pp, *rtp = NULL;
4648 bool not = (re_opcode_t) *p == charset_not;
4650 if (CHARSET_RANGE_TABLE_EXISTS_P (p))
4652 int count;
4653 rtp = CHARSET_RANGE_TABLE (p);
4654 EXTRACT_NUMBER_AND_INCR (count, rtp);
4655 *pp = CHARSET_RANGE_TABLE_END ((rtp), (count));
4657 else
4658 *pp += 2 + CHARSET_BITMAP_SIZE (p);
4660 if (unibyte && c < (1 << BYTEWIDTH))
4661 { /* Lookup bitmap. */
4662 /* Cast to `unsigned' instead of `unsigned char' in
4663 case the bit list is a full 32 bytes long. */
4664 if (c < (unsigned) (CHARSET_BITMAP_SIZE (p) * BYTEWIDTH)
4665 && p[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4666 return !not;
4668 #ifdef emacs
4669 else if (rtp)
4671 int class_bits = CHARSET_RANGE_TABLE_BITS (p);
4672 re_wchar_t range_start, range_end;
4674 /* Sort tests by the most commonly used classes with some adjustment to which
4675 tests are easiest to perform. Take a look at comment in re_wctype_parse
4676 for table with frequencies of character class names. */
4678 if ((class_bits & BIT_MULTIBYTE) ||
4679 (class_bits & BIT_ALNUM && ISALNUM (c)) ||
4680 (class_bits & BIT_ALPHA && ISALPHA (c)) ||
4681 (class_bits & BIT_SPACE && ISSPACE (c)) ||
4682 (class_bits & BIT_WORD && ISWORD (c)) ||
4683 ((class_bits & BIT_UPPER) &&
4684 (ISUPPER (c) || (corig != c &&
4685 c == downcase (corig) && ISLOWER (c)))) ||
4686 ((class_bits & BIT_LOWER) &&
4687 (ISLOWER (c) || (corig != c &&
4688 c == upcase (corig) && ISUPPER(c)))) ||
4689 (class_bits & BIT_PUNCT && ISPUNCT (c)) ||
4690 (class_bits & BIT_GRAPH && ISGRAPH (c)) ||
4691 (class_bits & BIT_PRINT && ISPRINT (c)))
4692 return !not;
4694 for (p = *pp; rtp < p; rtp += 2 * 3)
4696 EXTRACT_CHARACTER (range_start, rtp);
4697 EXTRACT_CHARACTER (range_end, rtp + 3);
4698 if (range_start <= c && c <= range_end)
4699 return !not;
4702 #endif /* emacs */
4703 return not;
4706 /* Non-zero if "p1 matches something" implies "p2 fails". */
4707 static int
4708 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4709 const_re_char *p2)
4711 re_opcode_t op2;
4712 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4713 unsigned char *pend = bufp->buffer + bufp->used;
4715 assert (p1 >= bufp->buffer && p1 < pend
4716 && p2 >= bufp->buffer && p2 <= pend);
4718 /* Skip over open/close-group commands.
4719 If what follows this loop is a ...+ construct,
4720 look at what begins its body, since we will have to
4721 match at least one of that. */
4722 p2 = skip_noops (p2, pend);
4723 /* The same skip can be done for p1, except that this function
4724 is only used in the case where p1 is a simple match operator. */
4725 /* p1 = skip_noops (p1, pend); */
4727 assert (p1 >= bufp->buffer && p1 < pend
4728 && p2 >= bufp->buffer && p2 <= pend);
4730 op2 = p2 == pend ? succeed : *p2;
4732 switch (op2)
4734 case succeed:
4735 case endbuf:
4736 /* If we're at the end of the pattern, we can change. */
4737 if (skip_one_char (p1))
4739 DEBUG_PRINT (" End of pattern: fast loop.\n");
4740 return 1;
4742 break;
4744 case endline:
4745 case exactn:
4747 register re_wchar_t c
4748 = (re_opcode_t) *p2 == endline ? '\n'
4749 : RE_STRING_CHAR (p2 + 2, multibyte);
4751 if ((re_opcode_t) *p1 == exactn)
4753 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4755 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4756 return 1;
4760 else if ((re_opcode_t) *p1 == charset
4761 || (re_opcode_t) *p1 == charset_not)
4763 if (!execute_charset (&p1, c, c, !multibyte || IS_REAL_ASCII (c)))
4765 DEBUG_PRINT (" No match => fast loop.\n");
4766 return 1;
4769 else if ((re_opcode_t) *p1 == anychar
4770 && c == '\n')
4772 DEBUG_PRINT (" . != \\n => fast loop.\n");
4773 return 1;
4776 break;
4778 case charset:
4780 if ((re_opcode_t) *p1 == exactn)
4781 /* Reuse the code above. */
4782 return mutually_exclusive_p (bufp, p2, p1);
4784 /* It is hard to list up all the character in charset
4785 P2 if it includes multibyte character. Give up in
4786 such case. */
4787 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4789 /* Now, we are sure that P2 has no range table.
4790 So, for the size of bitmap in P2, `p2[1]' is
4791 enough. But P1 may have range table, so the
4792 size of bitmap table of P1 is extracted by
4793 using macro `CHARSET_BITMAP_SIZE'.
4795 In a multibyte case, we know that all the character
4796 listed in P2 is ASCII. In a unibyte case, P1 has only a
4797 bitmap table. So, in both cases, it is enough to test
4798 only the bitmap table of P1. */
4800 if ((re_opcode_t) *p1 == charset)
4802 int idx;
4803 /* We win if the charset inside the loop
4804 has no overlap with the one after the loop. */
4805 for (idx = 0;
4806 (idx < (int) p2[1]
4807 && idx < CHARSET_BITMAP_SIZE (p1));
4808 idx++)
4809 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4810 break;
4812 if (idx == p2[1]
4813 || idx == CHARSET_BITMAP_SIZE (p1))
4815 DEBUG_PRINT (" No match => fast loop.\n");
4816 return 1;
4819 else if ((re_opcode_t) *p1 == charset_not)
4821 int idx;
4822 /* We win if the charset_not inside the loop lists
4823 every character listed in the charset after. */
4824 for (idx = 0; idx < (int) p2[1]; idx++)
4825 if (! (p2[2 + idx] == 0
4826 || (idx < CHARSET_BITMAP_SIZE (p1)
4827 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4828 break;
4830 if (idx == p2[1])
4832 DEBUG_PRINT (" No match => fast loop.\n");
4833 return 1;
4838 break;
4840 case charset_not:
4841 switch (*p1)
4843 case exactn:
4844 case charset:
4845 /* Reuse the code above. */
4846 return mutually_exclusive_p (bufp, p2, p1);
4847 case charset_not:
4848 /* When we have two charset_not, it's very unlikely that
4849 they don't overlap. The union of the two sets of excluded
4850 chars should cover all possible chars, which, as a matter of
4851 fact, is virtually impossible in multibyte buffers. */
4852 break;
4854 break;
4856 case wordend:
4857 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4858 case symend:
4859 return ((re_opcode_t) *p1 == syntaxspec
4860 && (p1[1] == Ssymbol || p1[1] == Sword));
4861 case notsyntaxspec:
4862 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4864 case wordbeg:
4865 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4866 case symbeg:
4867 return ((re_opcode_t) *p1 == notsyntaxspec
4868 && (p1[1] == Ssymbol || p1[1] == Sword));
4869 case syntaxspec:
4870 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4872 case wordbound:
4873 return (((re_opcode_t) *p1 == notsyntaxspec
4874 || (re_opcode_t) *p1 == syntaxspec)
4875 && p1[1] == Sword);
4877 #ifdef emacs
4878 case categoryspec:
4879 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4880 case notcategoryspec:
4881 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4882 #endif /* emacs */
4884 default:
4888 /* Safe default. */
4889 return 0;
4893 /* Matching routines. */
4895 #ifndef emacs /* Emacs never uses this. */
4896 /* re_match is like re_match_2 except it takes only a single string. */
4898 regoff_t
4899 re_match (struct re_pattern_buffer *bufp, const char *string,
4900 size_t size, ssize_t pos, struct re_registers *regs)
4902 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4903 size, pos, regs, size);
4904 return result;
4906 WEAK_ALIAS (__re_match, re_match)
4907 #endif /* not emacs */
4909 #ifdef emacs
4910 /* In Emacs, this is the string or buffer in which we are matching.
4911 See the declaration in regex.h for details. */
4912 Lisp_Object re_match_object;
4913 #endif
4915 /* re_match_2 matches the compiled pattern in BUFP against the
4916 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4917 and SIZE2, respectively). We start matching at POS, and stop
4918 matching at STOP.
4920 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4921 store offsets for the substring each group matched in REGS. See the
4922 documentation for exactly how many groups we fill.
4924 We return -1 if no match, -2 if an internal error (such as the
4925 failure stack overflowing). Otherwise, we return the length of the
4926 matched substring. */
4928 regoff_t
4929 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4930 size_t size1, const char *string2, size_t size2, ssize_t pos,
4931 struct re_registers *regs, ssize_t stop)
4933 regoff_t result;
4935 #ifdef emacs
4936 ssize_t charpos;
4937 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4938 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4939 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4940 #endif
4942 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4943 (re_char*) string2, size2,
4944 pos, regs, stop);
4945 return result;
4947 WEAK_ALIAS (__re_match_2, re_match_2)
4950 /* This is a separate function so that we can force an alloca cleanup
4951 afterwards. */
4952 static regoff_t
4953 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4954 size_t size1, const_re_char *string2, size_t size2,
4955 ssize_t pos, struct re_registers *regs, ssize_t stop)
4957 /* General temporaries. */
4958 int mcnt;
4959 size_t reg;
4961 /* Just past the end of the corresponding string. */
4962 re_char *end1, *end2;
4964 /* Pointers into string1 and string2, just past the last characters in
4965 each to consider matching. */
4966 re_char *end_match_1, *end_match_2;
4968 /* Where we are in the data, and the end of the current string. */
4969 re_char *d, *dend;
4971 /* Used sometimes to remember where we were before starting matching
4972 an operator so that we can go back in case of failure. This "atomic"
4973 behavior of matching opcodes is indispensable to the correctness
4974 of the on_failure_keep_string_jump optimization. */
4975 re_char *dfail;
4977 /* Where we are in the pattern, and the end of the pattern. */
4978 re_char *p = bufp->buffer;
4979 re_char *pend = p + bufp->used;
4981 /* We use this to map every character in the string. */
4982 RE_TRANSLATE_TYPE translate = bufp->translate;
4984 /* Nonzero if BUFP is setup from a multibyte regex. */
4985 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4987 /* Nonzero if STRING1/STRING2 are multibyte. */
4988 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4990 /* Failure point stack. Each place that can handle a failure further
4991 down the line pushes a failure point on this stack. It consists of
4992 regstart, and regend for all registers corresponding to
4993 the subexpressions we're currently inside, plus the number of such
4994 registers, and, finally, two char *'s. The first char * is where
4995 to resume scanning the pattern; the second one is where to resume
4996 scanning the strings. */
4997 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4998 fail_stack_type fail_stack;
4999 #endif
5000 #ifdef DEBUG_COMPILES_ARGUMENTS
5001 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5002 #endif
5004 #if defined REL_ALLOC && defined REGEX_MALLOC
5005 /* This holds the pointer to the failure stack, when
5006 it is allocated relocatably. */
5007 fail_stack_elt_t *failure_stack_ptr;
5008 #endif
5010 /* We fill all the registers internally, independent of what we
5011 return, for use in backreferences. The number here includes
5012 an element for register zero. */
5013 size_t num_regs = bufp->re_nsub + 1;
5015 /* Information on the contents of registers. These are pointers into
5016 the input strings; they record just what was matched (on this
5017 attempt) by a subexpression part of the pattern, that is, the
5018 regnum-th regstart pointer points to where in the pattern we began
5019 matching and the regnum-th regend points to right after where we
5020 stopped matching the regnum-th subexpression. (The zeroth register
5021 keeps track of what the whole pattern matches.) */
5022 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5023 re_char **regstart, **regend;
5024 #endif
5026 /* The following record the register info as found in the above
5027 variables when we find a match better than any we've seen before.
5028 This happens as we backtrack through the failure points, which in
5029 turn happens only if we have not yet matched the entire string. */
5030 unsigned best_regs_set = false;
5031 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5032 re_char **best_regstart, **best_regend;
5033 #endif
5035 /* Logically, this is `best_regend[0]'. But we don't want to have to
5036 allocate space for that if we're not allocating space for anything
5037 else (see below). Also, we never need info about register 0 for
5038 any of the other register vectors, and it seems rather a kludge to
5039 treat `best_regend' differently than the rest. So we keep track of
5040 the end of the best match so far in a separate variable. We
5041 initialize this to NULL so that when we backtrack the first time
5042 and need to test it, it's not garbage. */
5043 re_char *match_end = NULL;
5045 #ifdef DEBUG_COMPILES_ARGUMENTS
5046 /* Counts the total number of registers pushed. */
5047 unsigned num_regs_pushed = 0;
5048 #endif
5050 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5052 REGEX_USE_SAFE_ALLOCA;
5054 INIT_FAIL_STACK ();
5056 #ifdef MATCH_MAY_ALLOCATE
5057 /* Do not bother to initialize all the register variables if there are
5058 no groups in the pattern, as it takes a fair amount of time. If
5059 there are groups, we include space for register 0 (the whole
5060 pattern), even though we never use it, since it simplifies the
5061 array indexing. We should fix this. */
5062 if (bufp->re_nsub)
5064 regstart = REGEX_TALLOC (num_regs, re_char *);
5065 regend = REGEX_TALLOC (num_regs, re_char *);
5066 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5067 best_regend = REGEX_TALLOC (num_regs, re_char *);
5069 if (!(regstart && regend && best_regstart && best_regend))
5071 FREE_VARIABLES ();
5072 return -2;
5075 else
5077 /* We must initialize all our variables to NULL, so that
5078 `FREE_VARIABLES' doesn't try to free them. */
5079 regstart = regend = best_regstart = best_regend = NULL;
5081 #endif /* MATCH_MAY_ALLOCATE */
5083 /* The starting position is bogus. */
5084 if (pos < 0 || pos > size1 + size2)
5086 FREE_VARIABLES ();
5087 return -1;
5090 /* Initialize subexpression text positions to -1 to mark ones that no
5091 start_memory/stop_memory has been seen for. Also initialize the
5092 register information struct. */
5093 for (reg = 1; reg < num_regs; reg++)
5094 regstart[reg] = regend[reg] = NULL;
5096 /* We move `string1' into `string2' if the latter's empty -- but not if
5097 `string1' is null. */
5098 if (size2 == 0 && string1 != NULL)
5100 string2 = string1;
5101 size2 = size1;
5102 string1 = 0;
5103 size1 = 0;
5105 end1 = string1 + size1;
5106 end2 = string2 + size2;
5108 /* `p' scans through the pattern as `d' scans through the data.
5109 `dend' is the end of the input string that `d' points within. `d'
5110 is advanced into the following input string whenever necessary, but
5111 this happens before fetching; therefore, at the beginning of the
5112 loop, `d' can be pointing at the end of a string, but it cannot
5113 equal `string2'. */
5114 if (pos >= size1)
5116 /* Only match within string2. */
5117 d = string2 + pos - size1;
5118 dend = end_match_2 = string2 + stop - size1;
5119 end_match_1 = end1; /* Just to give it a value. */
5121 else
5123 if (stop < size1)
5125 /* Only match within string1. */
5126 end_match_1 = string1 + stop;
5127 /* BEWARE!
5128 When we reach end_match_1, PREFETCH normally switches to string2.
5129 But in the present case, this means that just doing a PREFETCH
5130 makes us jump from `stop' to `gap' within the string.
5131 What we really want here is for the search to stop as
5132 soon as we hit end_match_1. That's why we set end_match_2
5133 to end_match_1 (since PREFETCH fails as soon as we hit
5134 end_match_2). */
5135 end_match_2 = end_match_1;
5137 else
5138 { /* It's important to use this code when stop == size so that
5139 moving `d' from end1 to string2 will not prevent the d == dend
5140 check from catching the end of string. */
5141 end_match_1 = end1;
5142 end_match_2 = string2 + stop - size1;
5144 d = string1 + pos;
5145 dend = end_match_1;
5148 DEBUG_PRINT ("The compiled pattern is: ");
5149 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5150 DEBUG_PRINT ("The string to match is: \"");
5151 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5152 DEBUG_PRINT ("\"\n");
5154 /* This loops over pattern commands. It exits by returning from the
5155 function if the match is complete, or it drops through if the match
5156 fails at this starting point in the input data. */
5157 for (;;)
5159 DEBUG_PRINT ("\n%p: ", p);
5161 if (p == pend)
5163 /* End of pattern means we might have succeeded. */
5164 DEBUG_PRINT ("end of pattern ... ");
5166 /* If we haven't matched the entire string, and we want the
5167 longest match, try backtracking. */
5168 if (d != end_match_2)
5170 /* True if this match is the best seen so far. */
5171 bool best_match_p;
5174 /* True if this match ends in the same string (string1
5175 or string2) as the best previous match. */
5176 bool same_str_p = (FIRST_STRING_P (match_end)
5177 == FIRST_STRING_P (d));
5179 /* AIX compiler got confused when this was combined
5180 with the previous declaration. */
5181 if (same_str_p)
5182 best_match_p = d > match_end;
5183 else
5184 best_match_p = !FIRST_STRING_P (d);
5187 DEBUG_PRINT ("backtracking.\n");
5189 if (!FAIL_STACK_EMPTY ())
5190 { /* More failure points to try. */
5192 /* If exceeds best match so far, save it. */
5193 if (!best_regs_set || best_match_p)
5195 best_regs_set = true;
5196 match_end = d;
5198 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5200 for (reg = 1; reg < num_regs; reg++)
5202 best_regstart[reg] = regstart[reg];
5203 best_regend[reg] = regend[reg];
5206 goto fail;
5209 /* If no failure points, don't restore garbage. And if
5210 last match is real best match, don't restore second
5211 best one. */
5212 else if (best_regs_set && !best_match_p)
5214 restore_best_regs:
5215 /* Restore best match. It may happen that `dend ==
5216 end_match_1' while the restored d is in string2.
5217 For example, the pattern `x.*y.*z' against the
5218 strings `x-' and `y-z-', if the two strings are
5219 not consecutive in memory. */
5220 DEBUG_PRINT ("Restoring best registers.\n");
5222 d = match_end;
5223 dend = ((d >= string1 && d <= end1)
5224 ? end_match_1 : end_match_2);
5226 for (reg = 1; reg < num_regs; reg++)
5228 regstart[reg] = best_regstart[reg];
5229 regend[reg] = best_regend[reg];
5232 } /* d != end_match_2 */
5234 succeed_label:
5235 DEBUG_PRINT ("Accepting match.\n");
5237 /* If caller wants register contents data back, do it. */
5238 if (regs && !bufp->no_sub)
5240 /* Have the register data arrays been allocated? */
5241 if (bufp->regs_allocated == REGS_UNALLOCATED)
5242 { /* No. So allocate them with malloc. We need one
5243 extra element beyond `num_regs' for the `-1' marker
5244 GNU code uses. */
5245 regs->num_regs = max (RE_NREGS, num_regs + 1);
5246 regs->start = TALLOC (regs->num_regs, regoff_t);
5247 regs->end = TALLOC (regs->num_regs, regoff_t);
5248 if (regs->start == NULL || regs->end == NULL)
5250 FREE_VARIABLES ();
5251 return -2;
5253 bufp->regs_allocated = REGS_REALLOCATE;
5255 else if (bufp->regs_allocated == REGS_REALLOCATE)
5256 { /* Yes. If we need more elements than were already
5257 allocated, reallocate them. If we need fewer, just
5258 leave it alone. */
5259 if (regs->num_regs < num_regs + 1)
5261 regs->num_regs = num_regs + 1;
5262 RETALLOC (regs->start, regs->num_regs, regoff_t);
5263 RETALLOC (regs->end, regs->num_regs, regoff_t);
5264 if (regs->start == NULL || regs->end == NULL)
5266 FREE_VARIABLES ();
5267 return -2;
5271 else
5273 /* These braces fend off a "empty body in an else-statement"
5274 warning under GCC when assert expands to nothing. */
5275 assert (bufp->regs_allocated == REGS_FIXED);
5278 /* Convert the pointer data in `regstart' and `regend' to
5279 indices. Register zero has to be set differently,
5280 since we haven't kept track of any info for it. */
5281 if (regs->num_regs > 0)
5283 regs->start[0] = pos;
5284 regs->end[0] = POINTER_TO_OFFSET (d);
5287 /* Go through the first `min (num_regs, regs->num_regs)'
5288 registers, since that is all we initialized. */
5289 for (reg = 1; reg < min (num_regs, regs->num_regs); reg++)
5291 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5292 regs->start[reg] = regs->end[reg] = -1;
5293 else
5295 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5296 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5300 /* If the regs structure we return has more elements than
5301 were in the pattern, set the extra elements to -1. If
5302 we (re)allocated the registers, this is the case,
5303 because we always allocate enough to have at least one
5304 -1 at the end. */
5305 for (reg = num_regs; reg < regs->num_regs; reg++)
5306 regs->start[reg] = regs->end[reg] = -1;
5307 } /* regs && !bufp->no_sub */
5309 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5310 nfailure_points_pushed, nfailure_points_popped,
5311 nfailure_points_pushed - nfailure_points_popped);
5312 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5314 ptrdiff_t dcnt = POINTER_TO_OFFSET (d) - pos;
5316 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5318 FREE_VARIABLES ();
5319 return dcnt;
5322 /* Otherwise match next pattern command. */
5323 switch (*p++)
5325 /* Ignore these. Used to ignore the n of succeed_n's which
5326 currently have n == 0. */
5327 case no_op:
5328 DEBUG_PRINT ("EXECUTING no_op.\n");
5329 break;
5331 case succeed:
5332 DEBUG_PRINT ("EXECUTING succeed.\n");
5333 goto succeed_label;
5335 /* Match the next n pattern characters exactly. The following
5336 byte in the pattern defines n, and the n bytes after that
5337 are the characters to match. */
5338 case exactn:
5339 mcnt = *p++;
5340 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5342 /* Remember the start point to rollback upon failure. */
5343 dfail = d;
5345 #ifndef emacs
5346 /* This is written out as an if-else so we don't waste time
5347 testing `translate' inside the loop. */
5348 if (RE_TRANSLATE_P (translate))
5351 PREFETCH ();
5352 if (RE_TRANSLATE (translate, *d) != *p++)
5354 d = dfail;
5355 goto fail;
5357 d++;
5359 while (--mcnt);
5360 else
5363 PREFETCH ();
5364 if (*d++ != *p++)
5366 d = dfail;
5367 goto fail;
5370 while (--mcnt);
5371 #else /* emacs */
5372 /* The cost of testing `translate' is comparatively small. */
5373 if (target_multibyte)
5376 int pat_charlen, buf_charlen;
5377 int pat_ch, buf_ch;
5379 PREFETCH ();
5380 if (multibyte)
5381 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5382 else
5384 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5385 pat_charlen = 1;
5387 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5389 if (TRANSLATE (buf_ch) != pat_ch)
5391 d = dfail;
5392 goto fail;
5395 p += pat_charlen;
5396 d += buf_charlen;
5397 mcnt -= pat_charlen;
5399 while (mcnt > 0);
5400 else
5403 int pat_charlen;
5404 int pat_ch, buf_ch;
5406 PREFETCH ();
5407 if (multibyte)
5409 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5410 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5412 else
5414 pat_ch = *p;
5415 pat_charlen = 1;
5417 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5418 if (! CHAR_BYTE8_P (buf_ch))
5420 buf_ch = TRANSLATE (buf_ch);
5421 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5422 if (buf_ch < 0)
5423 buf_ch = *d;
5425 else
5426 buf_ch = *d;
5427 if (buf_ch != pat_ch)
5429 d = dfail;
5430 goto fail;
5432 p += pat_charlen;
5433 d++;
5435 while (--mcnt);
5436 #endif
5437 break;
5440 /* Match any character except possibly a newline or a null. */
5441 case anychar:
5443 int buf_charlen;
5444 re_wchar_t buf_ch;
5445 reg_syntax_t syntax;
5447 DEBUG_PRINT ("EXECUTING anychar.\n");
5449 PREFETCH ();
5450 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5451 target_multibyte);
5452 buf_ch = TRANSLATE (buf_ch);
5454 #ifdef emacs
5455 syntax = RE_SYNTAX_EMACS;
5456 #else
5457 syntax = bufp->syntax;
5458 #endif
5460 if ((!(syntax & RE_DOT_NEWLINE) && buf_ch == '\n')
5461 || ((syntax & RE_DOT_NOT_NULL) && buf_ch == '\000'))
5462 goto fail;
5464 DEBUG_PRINT (" Matched \"%d\".\n", *d);
5465 d += buf_charlen;
5467 break;
5470 case charset:
5471 case charset_not:
5473 register unsigned int c, corig;
5474 int len;
5476 /* Whether matching against a unibyte character. */
5477 boolean unibyte_char = false;
5479 DEBUG_PRINT ("EXECUTING charset%s.\n",
5480 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
5482 PREFETCH ();
5483 corig = c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5484 if (target_multibyte)
5486 int c1;
5488 c = TRANSLATE (c);
5489 c1 = RE_CHAR_TO_UNIBYTE (c);
5490 if (c1 >= 0)
5492 unibyte_char = true;
5493 c = c1;
5496 else
5498 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5500 if (! CHAR_BYTE8_P (c1))
5502 c1 = TRANSLATE (c1);
5503 c1 = RE_CHAR_TO_UNIBYTE (c1);
5504 if (c1 >= 0)
5506 unibyte_char = true;
5507 c = c1;
5510 else
5511 unibyte_char = true;
5514 p -= 1;
5515 if (!execute_charset (&p, c, corig, unibyte_char))
5516 goto fail;
5518 d += len;
5520 break;
5523 /* The beginning of a group is represented by start_memory.
5524 The argument is the register number. The text
5525 matched within the group is recorded (in the internal
5526 registers data structure) under the register number. */
5527 case start_memory:
5528 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5530 /* In case we need to undo this operation (via backtracking). */
5531 PUSH_FAILURE_REG (*p);
5533 regstart[*p] = d;
5534 regend[*p] = NULL; /* probably unnecessary. -sm */
5535 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5537 /* Move past the register number and inner group count. */
5538 p += 1;
5539 break;
5542 /* The stop_memory opcode represents the end of a group. Its
5543 argument is the same as start_memory's: the register number. */
5544 case stop_memory:
5545 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5547 assert (!REG_UNSET (regstart[*p]));
5548 /* Strictly speaking, there should be code such as:
5550 assert (REG_UNSET (regend[*p]));
5551 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5553 But the only info to be pushed is regend[*p] and it is known to
5554 be UNSET, so there really isn't anything to push.
5555 Not pushing anything, on the other hand deprives us from the
5556 guarantee that regend[*p] is UNSET since undoing this operation
5557 will not reset its value properly. This is not important since
5558 the value will only be read on the next start_memory or at
5559 the very end and both events can only happen if this stop_memory
5560 is *not* undone. */
5562 regend[*p] = d;
5563 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5565 /* Move past the register number and the inner group count. */
5566 p += 1;
5567 break;
5570 /* \<digit> has been turned into a `duplicate' command which is
5571 followed by the numeric value of <digit> as the register number. */
5572 case duplicate:
5574 register re_char *d2, *dend2;
5575 int regno = *p++; /* Get which register to match against. */
5576 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5578 /* Can't back reference a group which we've never matched. */
5579 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5580 goto fail;
5582 /* Where in input to try to start matching. */
5583 d2 = regstart[regno];
5585 /* Remember the start point to rollback upon failure. */
5586 dfail = d;
5588 /* Where to stop matching; if both the place to start and
5589 the place to stop matching are in the same string, then
5590 set to the place to stop, otherwise, for now have to use
5591 the end of the first string. */
5593 dend2 = ((FIRST_STRING_P (regstart[regno])
5594 == FIRST_STRING_P (regend[regno]))
5595 ? regend[regno] : end_match_1);
5596 for (;;)
5598 ptrdiff_t dcnt;
5600 /* If necessary, advance to next segment in register
5601 contents. */
5602 while (d2 == dend2)
5604 if (dend2 == end_match_2) break;
5605 if (dend2 == regend[regno]) break;
5607 /* End of string1 => advance to string2. */
5608 d2 = string2;
5609 dend2 = regend[regno];
5611 /* At end of register contents => success */
5612 if (d2 == dend2) break;
5614 /* If necessary, advance to next segment in data. */
5615 PREFETCH ();
5617 /* How many characters left in this segment to match. */
5618 dcnt = dend - d;
5620 /* Want how many consecutive characters we can match in
5621 one shot, so, if necessary, adjust the count. */
5622 if (dcnt > dend2 - d2)
5623 dcnt = dend2 - d2;
5625 /* Compare that many; failure if mismatch, else move
5626 past them. */
5627 if (RE_TRANSLATE_P (translate)
5628 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5629 : memcmp (d, d2, dcnt))
5631 d = dfail;
5632 goto fail;
5634 d += dcnt, d2 += dcnt;
5637 break;
5640 /* begline matches the empty string at the beginning of the string
5641 (unless `not_bol' is set in `bufp'), and after newlines. */
5642 case begline:
5643 DEBUG_PRINT ("EXECUTING begline.\n");
5645 if (AT_STRINGS_BEG (d))
5647 if (!bufp->not_bol) break;
5649 else
5651 unsigned c;
5652 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5653 if (c == '\n')
5654 break;
5656 /* In all other cases, we fail. */
5657 goto fail;
5660 /* endline is the dual of begline. */
5661 case endline:
5662 DEBUG_PRINT ("EXECUTING endline.\n");
5664 if (AT_STRINGS_END (d))
5666 if (!bufp->not_eol) break;
5668 else
5670 PREFETCH_NOLIMIT ();
5671 if (*d == '\n')
5672 break;
5674 goto fail;
5677 /* Match at the very beginning of the data. */
5678 case begbuf:
5679 DEBUG_PRINT ("EXECUTING begbuf.\n");
5680 if (AT_STRINGS_BEG (d))
5681 break;
5682 goto fail;
5685 /* Match at the very end of the data. */
5686 case endbuf:
5687 DEBUG_PRINT ("EXECUTING endbuf.\n");
5688 if (AT_STRINGS_END (d))
5689 break;
5690 goto fail;
5693 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5694 pushes NULL as the value for the string on the stack. Then
5695 `POP_FAILURE_POINT' will keep the current value for the
5696 string, instead of restoring it. To see why, consider
5697 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5698 then the . fails against the \n. But the next thing we want
5699 to do is match the \n against the \n; if we restored the
5700 string value, we would be back at the foo.
5702 Because this is used only in specific cases, we don't need to
5703 check all the things that `on_failure_jump' does, to make
5704 sure the right things get saved on the stack. Hence we don't
5705 share its code. The only reason to push anything on the
5706 stack at all is that otherwise we would have to change
5707 `anychar's code to do something besides goto fail in this
5708 case; that seems worse than this. */
5709 case on_failure_keep_string_jump:
5710 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5711 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5712 mcnt, p + mcnt);
5714 PUSH_FAILURE_POINT (p - 3, NULL);
5715 break;
5717 /* A nasty loop is introduced by the non-greedy *? and +?.
5718 With such loops, the stack only ever contains one failure point
5719 at a time, so that a plain on_failure_jump_loop kind of
5720 cycle detection cannot work. Worse yet, such a detection
5721 can not only fail to detect a cycle, but it can also wrongly
5722 detect a cycle (between different instantiations of the same
5723 loop).
5724 So the method used for those nasty loops is a little different:
5725 We use a special cycle-detection-stack-frame which is pushed
5726 when the on_failure_jump_nastyloop failure-point is *popped*.
5727 This special frame thus marks the beginning of one iteration
5728 through the loop and we can hence easily check right here
5729 whether something matched between the beginning and the end of
5730 the loop. */
5731 case on_failure_jump_nastyloop:
5732 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5733 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5734 mcnt, p + mcnt);
5736 assert ((re_opcode_t)p[-4] == no_op);
5738 int cycle = 0;
5739 CHECK_INFINITE_LOOP (p - 4, d);
5740 if (!cycle)
5741 /* If there's a cycle, just continue without pushing
5742 this failure point. The failure point is the "try again"
5743 option, which shouldn't be tried.
5744 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5745 PUSH_FAILURE_POINT (p - 3, d);
5747 break;
5749 /* Simple loop detecting on_failure_jump: just check on the
5750 failure stack if the same spot was already hit earlier. */
5751 case on_failure_jump_loop:
5752 on_failure:
5753 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5754 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5755 mcnt, p + mcnt);
5757 int cycle = 0;
5758 CHECK_INFINITE_LOOP (p - 3, d);
5759 if (cycle)
5760 /* If there's a cycle, get out of the loop, as if the matching
5761 had failed. We used to just `goto fail' here, but that was
5762 aborting the search a bit too early: we want to keep the
5763 empty-loop-match and keep matching after the loop.
5764 We want (x?)*y\1z to match both xxyz and xxyxz. */
5765 p += mcnt;
5766 else
5767 PUSH_FAILURE_POINT (p - 3, d);
5769 break;
5772 /* Uses of on_failure_jump:
5774 Each alternative starts with an on_failure_jump that points
5775 to the beginning of the next alternative. Each alternative
5776 except the last ends with a jump that in effect jumps past
5777 the rest of the alternatives. (They really jump to the
5778 ending jump of the following alternative, because tensioning
5779 these jumps is a hassle.)
5781 Repeats start with an on_failure_jump that points past both
5782 the repetition text and either the following jump or
5783 pop_failure_jump back to this on_failure_jump. */
5784 case on_failure_jump:
5785 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5786 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5787 mcnt, p + mcnt);
5789 PUSH_FAILURE_POINT (p -3, d);
5790 break;
5792 /* This operation is used for greedy *.
5793 Compare the beginning of the repeat with what in the
5794 pattern follows its end. If we can establish that there
5795 is nothing that they would both match, i.e., that we
5796 would have to backtrack because of (as in, e.g., `a*a')
5797 then we can use a non-backtracking loop based on
5798 on_failure_keep_string_jump instead of on_failure_jump. */
5799 case on_failure_jump_smart:
5800 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5801 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5802 mcnt, p + mcnt);
5804 re_char *p1 = p; /* Next operation. */
5805 /* Here, we discard `const', making re_match non-reentrant. */
5806 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5807 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5809 p -= 3; /* Reset so that we will re-execute the
5810 instruction once it's been changed. */
5812 EXTRACT_NUMBER (mcnt, p2 - 2);
5814 /* Ensure this is a indeed the trivial kind of loop
5815 we are expecting. */
5816 assert (skip_one_char (p1) == p2 - 3);
5817 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5818 DEBUG_STATEMENT (debug += 2);
5819 if (mutually_exclusive_p (bufp, p1, p2))
5821 /* Use a fast `on_failure_keep_string_jump' loop. */
5822 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5823 *p3 = (unsigned char) on_failure_keep_string_jump;
5824 STORE_NUMBER (p2 - 2, mcnt + 3);
5826 else
5828 /* Default to a safe `on_failure_jump' loop. */
5829 DEBUG_PRINT (" smart default => slow loop.\n");
5830 *p3 = (unsigned char) on_failure_jump;
5832 DEBUG_STATEMENT (debug -= 2);
5834 break;
5836 /* Unconditionally jump (without popping any failure points). */
5837 case jump:
5838 unconditional_jump:
5839 IMMEDIATE_QUIT_CHECK;
5840 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5841 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5842 p += mcnt; /* Do the jump. */
5843 DEBUG_PRINT ("(to %p).\n", p);
5844 break;
5847 /* Have to succeed matching what follows at least n times.
5848 After that, handle like `on_failure_jump'. */
5849 case succeed_n:
5850 /* Signedness doesn't matter since we only compare MCNT to 0. */
5851 EXTRACT_NUMBER (mcnt, p + 2);
5852 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5854 /* Originally, mcnt is how many times we HAVE to succeed. */
5855 if (mcnt != 0)
5857 /* Here, we discard `const', making re_match non-reentrant. */
5858 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5859 mcnt--;
5860 p += 4;
5861 PUSH_NUMBER (p2, mcnt);
5863 else
5864 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5865 goto on_failure;
5866 break;
5868 case jump_n:
5869 /* Signedness doesn't matter since we only compare MCNT to 0. */
5870 EXTRACT_NUMBER (mcnt, p + 2);
5871 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5873 /* Originally, this is how many times we CAN jump. */
5874 if (mcnt != 0)
5876 /* Here, we discard `const', making re_match non-reentrant. */
5877 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5878 mcnt--;
5879 PUSH_NUMBER (p2, mcnt);
5880 goto unconditional_jump;
5882 /* If don't have to jump any more, skip over the rest of command. */
5883 else
5884 p += 4;
5885 break;
5887 case set_number_at:
5889 unsigned char *p2; /* Location of the counter. */
5890 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5892 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5893 /* Here, we discard `const', making re_match non-reentrant. */
5894 p2 = (unsigned char*) p + mcnt;
5895 /* Signedness doesn't matter since we only copy MCNT's bits. */
5896 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5897 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5898 PUSH_NUMBER (p2, mcnt);
5899 break;
5902 case wordbound:
5903 case notwordbound:
5905 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5906 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5908 /* We SUCCEED (or FAIL) in one of the following cases: */
5910 /* Case 1: D is at the beginning or the end of string. */
5911 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5912 not = !not;
5913 else
5915 /* C1 is the character before D, S1 is the syntax of C1, C2
5916 is the character at D, and S2 is the syntax of C2. */
5917 re_wchar_t c1, c2;
5918 int s1, s2;
5919 int dummy;
5920 #ifdef emacs
5921 ssize_t offset = PTR_TO_OFFSET (d - 1);
5922 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5923 UPDATE_SYNTAX_TABLE_FAST (charpos);
5924 #endif
5925 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5926 s1 = SYNTAX (c1);
5927 #ifdef emacs
5928 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
5929 #endif
5930 PREFETCH_NOLIMIT ();
5931 GET_CHAR_AFTER (c2, d, dummy);
5932 s2 = SYNTAX (c2);
5934 if (/* Case 2: Only one of S1 and S2 is Sword. */
5935 ((s1 == Sword) != (s2 == Sword))
5936 /* Case 3: Both of S1 and S2 are Sword, and macro
5937 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5938 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5939 not = !not;
5941 if (not)
5942 break;
5943 else
5944 goto fail;
5947 case wordbeg:
5948 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5950 /* We FAIL in one of the following cases: */
5952 /* Case 1: D is at the end of string. */
5953 if (AT_STRINGS_END (d))
5954 goto fail;
5955 else
5957 /* C1 is the character before D, S1 is the syntax of C1, C2
5958 is the character at D, and S2 is the syntax of C2. */
5959 re_wchar_t c1, c2;
5960 int s1, s2;
5961 int dummy;
5962 #ifdef emacs
5963 ssize_t offset = PTR_TO_OFFSET (d);
5964 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5965 UPDATE_SYNTAX_TABLE_FAST (charpos);
5966 #endif
5967 PREFETCH ();
5968 GET_CHAR_AFTER (c2, d, dummy);
5969 s2 = SYNTAX (c2);
5971 /* Case 2: S2 is not Sword. */
5972 if (s2 != Sword)
5973 goto fail;
5975 /* Case 3: D is not at the beginning of string ... */
5976 if (!AT_STRINGS_BEG (d))
5978 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5979 #ifdef emacs
5980 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5981 #endif
5982 s1 = SYNTAX (c1);
5984 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5985 returns 0. */
5986 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5987 goto fail;
5990 break;
5992 case wordend:
5993 DEBUG_PRINT ("EXECUTING wordend.\n");
5995 /* We FAIL in one of the following cases: */
5997 /* Case 1: D is at the beginning of string. */
5998 if (AT_STRINGS_BEG (d))
5999 goto fail;
6000 else
6002 /* C1 is the character before D, S1 is the syntax of C1, C2
6003 is the character at D, and S2 is the syntax of C2. */
6004 re_wchar_t c1, c2;
6005 int s1, s2;
6006 int dummy;
6007 #ifdef emacs
6008 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6009 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6010 UPDATE_SYNTAX_TABLE_FAST (charpos);
6011 #endif
6012 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6013 s1 = SYNTAX (c1);
6015 /* Case 2: S1 is not Sword. */
6016 if (s1 != Sword)
6017 goto fail;
6019 /* Case 3: D is not at the end of string ... */
6020 if (!AT_STRINGS_END (d))
6022 PREFETCH_NOLIMIT ();
6023 GET_CHAR_AFTER (c2, d, dummy);
6024 #ifdef emacs
6025 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos);
6026 #endif
6027 s2 = SYNTAX (c2);
6029 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6030 returns 0. */
6031 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6032 goto fail;
6035 break;
6037 case symbeg:
6038 DEBUG_PRINT ("EXECUTING symbeg.\n");
6040 /* We FAIL in one of the following cases: */
6042 /* Case 1: D is at the end of string. */
6043 if (AT_STRINGS_END (d))
6044 goto fail;
6045 else
6047 /* C1 is the character before D, S1 is the syntax of C1, C2
6048 is the character at D, and S2 is the syntax of C2. */
6049 re_wchar_t c1, c2;
6050 int s1, s2;
6051 #ifdef emacs
6052 ssize_t offset = PTR_TO_OFFSET (d);
6053 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6054 UPDATE_SYNTAX_TABLE_FAST (charpos);
6055 #endif
6056 PREFETCH ();
6057 c2 = RE_STRING_CHAR (d, target_multibyte);
6058 s2 = SYNTAX (c2);
6060 /* Case 2: S2 is neither Sword nor Ssymbol. */
6061 if (s2 != Sword && s2 != Ssymbol)
6062 goto fail;
6064 /* Case 3: D is not at the beginning of string ... */
6065 if (!AT_STRINGS_BEG (d))
6067 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6068 #ifdef emacs
6069 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6070 #endif
6071 s1 = SYNTAX (c1);
6073 /* ... and S1 is Sword or Ssymbol. */
6074 if (s1 == Sword || s1 == Ssymbol)
6075 goto fail;
6078 break;
6080 case symend:
6081 DEBUG_PRINT ("EXECUTING symend.\n");
6083 /* We FAIL in one of the following cases: */
6085 /* Case 1: D is at the beginning of string. */
6086 if (AT_STRINGS_BEG (d))
6087 goto fail;
6088 else
6090 /* C1 is the character before D, S1 is the syntax of C1, C2
6091 is the character at D, and S2 is the syntax of C2. */
6092 re_wchar_t c1, c2;
6093 int s1, s2;
6094 #ifdef emacs
6095 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6096 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6097 UPDATE_SYNTAX_TABLE_FAST (charpos);
6098 #endif
6099 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6100 s1 = SYNTAX (c1);
6102 /* Case 2: S1 is neither Ssymbol nor Sword. */
6103 if (s1 != Sword && s1 != Ssymbol)
6104 goto fail;
6106 /* Case 3: D is not at the end of string ... */
6107 if (!AT_STRINGS_END (d))
6109 PREFETCH_NOLIMIT ();
6110 c2 = RE_STRING_CHAR (d, target_multibyte);
6111 #ifdef emacs
6112 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
6113 #endif
6114 s2 = SYNTAX (c2);
6116 /* ... and S2 is Sword or Ssymbol. */
6117 if (s2 == Sword || s2 == Ssymbol)
6118 goto fail;
6121 break;
6123 case syntaxspec:
6124 case notsyntaxspec:
6126 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6127 mcnt = *p++;
6128 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6129 mcnt);
6130 PREFETCH ();
6131 #ifdef emacs
6133 ssize_t offset = PTR_TO_OFFSET (d);
6134 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6135 UPDATE_SYNTAX_TABLE_FAST (pos1);
6137 #endif
6139 int len;
6140 re_wchar_t c;
6142 GET_CHAR_AFTER (c, d, len);
6143 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6144 goto fail;
6145 d += len;
6148 break;
6150 #ifdef emacs
6151 case at_dot:
6152 DEBUG_PRINT ("EXECUTING at_dot.\n");
6153 if (PTR_BYTE_POS (d) != PT_BYTE)
6154 goto fail;
6155 break;
6157 case categoryspec:
6158 case notcategoryspec:
6160 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6161 mcnt = *p++;
6162 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6163 not ? "not" : "", mcnt);
6164 PREFETCH ();
6167 int len;
6168 re_wchar_t c;
6169 GET_CHAR_AFTER (c, d, len);
6170 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6171 goto fail;
6172 d += len;
6175 break;
6177 #endif /* emacs */
6179 default:
6180 abort ();
6182 continue; /* Successfully executed one pattern command; keep going. */
6185 /* We goto here if a matching operation fails. */
6186 fail:
6187 IMMEDIATE_QUIT_CHECK;
6188 if (!FAIL_STACK_EMPTY ())
6190 re_char *str, *pat;
6191 /* A restart point is known. Restore to that state. */
6192 DEBUG_PRINT ("\nFAIL:\n");
6193 POP_FAILURE_POINT (str, pat);
6194 switch (*pat++)
6196 case on_failure_keep_string_jump:
6197 assert (str == NULL);
6198 goto continue_failure_jump;
6200 case on_failure_jump_nastyloop:
6201 assert ((re_opcode_t)pat[-2] == no_op);
6202 PUSH_FAILURE_POINT (pat - 2, str);
6203 /* Fallthrough */
6205 case on_failure_jump_loop:
6206 case on_failure_jump:
6207 case succeed_n:
6208 d = str;
6209 continue_failure_jump:
6210 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6211 p = pat + mcnt;
6212 break;
6214 case no_op:
6215 /* A special frame used for nastyloops. */
6216 goto fail;
6218 default:
6219 abort ();
6222 assert (p >= bufp->buffer && p <= pend);
6224 if (d >= string1 && d <= end1)
6225 dend = end_match_1;
6227 else
6228 break; /* Matching at this starting point really fails. */
6229 } /* for (;;) */
6231 if (best_regs_set)
6232 goto restore_best_regs;
6234 FREE_VARIABLES ();
6236 return -1; /* Failure to match. */
6239 /* Subroutine definitions for re_match_2. */
6241 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6242 bytes; nonzero otherwise. */
6244 static int
6245 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6246 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6248 register re_char *p1 = s1, *p2 = s2;
6249 re_char *p1_end = s1 + len;
6250 re_char *p2_end = s2 + len;
6252 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6253 different lengths, but relying on a single `len' would break this. -sm */
6254 while (p1 < p1_end && p2 < p2_end)
6256 int p1_charlen, p2_charlen;
6257 re_wchar_t p1_ch, p2_ch;
6259 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6260 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6262 if (RE_TRANSLATE (translate, p1_ch)
6263 != RE_TRANSLATE (translate, p2_ch))
6264 return 1;
6266 p1 += p1_charlen, p2 += p2_charlen;
6269 if (p1 != p1_end || p2 != p2_end)
6270 return 1;
6272 return 0;
6275 /* Entry points for GNU code. */
6277 /* re_compile_pattern is the GNU regular expression compiler: it
6278 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6279 Returns 0 if the pattern was valid, otherwise an error string.
6281 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6282 are set in BUFP on entry.
6284 We call regex_compile to do the actual compilation. */
6286 const char *
6287 re_compile_pattern (const char *pattern, size_t length,
6288 #ifdef emacs
6289 bool posix_backtracking, const char *whitespace_regexp,
6290 #endif
6291 struct re_pattern_buffer *bufp)
6293 reg_errcode_t ret;
6295 /* GNU code is written to assume at least RE_NREGS registers will be set
6296 (and at least one extra will be -1). */
6297 bufp->regs_allocated = REGS_UNALLOCATED;
6299 /* And GNU code determines whether or not to get register information
6300 by passing null for the REGS argument to re_match, etc., not by
6301 setting no_sub. */
6302 bufp->no_sub = 0;
6304 ret = regex_compile ((re_char*) pattern, length,
6305 #ifdef emacs
6306 posix_backtracking,
6307 whitespace_regexp,
6308 #else
6309 re_syntax_options,
6310 #endif
6311 bufp);
6313 if (!ret)
6314 return NULL;
6315 return gettext (re_error_msgid[(int) ret]);
6317 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6319 /* Entry points compatible with 4.2 BSD regex library. We don't define
6320 them unless specifically requested. */
6322 #if defined _REGEX_RE_COMP || defined _LIBC
6324 /* BSD has one and only one pattern buffer. */
6325 static struct re_pattern_buffer re_comp_buf;
6327 char *
6328 # ifdef _LIBC
6329 /* Make these definitions weak in libc, so POSIX programs can redefine
6330 these names if they don't use our functions, and still use
6331 regcomp/regexec below without link errors. */
6332 weak_function
6333 # endif
6334 re_comp (const char *s)
6336 reg_errcode_t ret;
6338 if (!s)
6340 if (!re_comp_buf.buffer)
6341 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6342 return (char *) gettext ("No previous regular expression");
6343 return 0;
6346 if (!re_comp_buf.buffer)
6348 re_comp_buf.buffer = malloc (200);
6349 if (re_comp_buf.buffer == NULL)
6350 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6351 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6352 re_comp_buf.allocated = 200;
6354 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6355 if (re_comp_buf.fastmap == NULL)
6356 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6357 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6360 /* Since `re_exec' always passes NULL for the `regs' argument, we
6361 don't need to initialize the pattern buffer fields which affect it. */
6363 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6365 if (!ret)
6366 return NULL;
6368 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6369 return (char *) gettext (re_error_msgid[(int) ret]);
6374 # ifdef _LIBC
6375 weak_function
6376 # endif
6377 re_exec (const char *s)
6379 const size_t len = strlen (s);
6380 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6382 #endif /* _REGEX_RE_COMP */
6384 /* POSIX.2 functions. Don't define these for Emacs. */
6386 #ifndef emacs
6388 /* regcomp takes a regular expression as a string and compiles it.
6390 PREG is a regex_t *. We do not expect any fields to be initialized,
6391 since POSIX says we shouldn't. Thus, we set
6393 `buffer' to the compiled pattern;
6394 `used' to the length of the compiled pattern;
6395 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6396 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6397 RE_SYNTAX_POSIX_BASIC;
6398 `fastmap' to an allocated space for the fastmap;
6399 `fastmap_accurate' to zero;
6400 `re_nsub' to the number of subexpressions in PATTERN.
6402 PATTERN is the address of the pattern string.
6404 CFLAGS is a series of bits which affect compilation.
6406 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6407 use POSIX basic syntax.
6409 If REG_NEWLINE is set, then . and [^...] don't match newline.
6410 Also, regexec will try a match beginning after every newline.
6412 If REG_ICASE is set, then we considers upper- and lowercase
6413 versions of letters to be equivalent when matching.
6415 If REG_NOSUB is set, then when PREG is passed to regexec, that
6416 routine will report only success or failure, and nothing about the
6417 registers.
6419 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6420 the return codes and their meanings.) */
6422 reg_errcode_t
6423 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6424 int cflags)
6426 reg_errcode_t ret;
6427 reg_syntax_t syntax
6428 = (cflags & REG_EXTENDED) ?
6429 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6431 /* regex_compile will allocate the space for the compiled pattern. */
6432 preg->buffer = 0;
6433 preg->allocated = 0;
6434 preg->used = 0;
6436 /* Try to allocate space for the fastmap. */
6437 preg->fastmap = malloc (1 << BYTEWIDTH);
6439 if (cflags & REG_ICASE)
6441 unsigned i;
6443 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6444 if (preg->translate == NULL)
6445 return (int) REG_ESPACE;
6447 /* Map uppercase characters to corresponding lowercase ones. */
6448 for (i = 0; i < CHAR_SET_SIZE; i++)
6449 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6451 else
6452 preg->translate = NULL;
6454 /* If REG_NEWLINE is set, newlines are treated differently. */
6455 if (cflags & REG_NEWLINE)
6456 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6457 syntax &= ~RE_DOT_NEWLINE;
6458 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6460 else
6461 syntax |= RE_NO_NEWLINE_ANCHOR;
6463 preg->no_sub = !!(cflags & REG_NOSUB);
6465 /* POSIX says a null character in the pattern terminates it, so we
6466 can use strlen here in compiling the pattern. */
6467 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6469 /* POSIX doesn't distinguish between an unmatched open-group and an
6470 unmatched close-group: both are REG_EPAREN. */
6471 if (ret == REG_ERPAREN)
6472 ret = REG_EPAREN;
6474 if (ret == REG_NOERROR && preg->fastmap)
6475 { /* Compute the fastmap now, since regexec cannot modify the pattern
6476 buffer. */
6477 re_compile_fastmap (preg);
6478 if (preg->can_be_null)
6479 { /* The fastmap can't be used anyway. */
6480 free (preg->fastmap);
6481 preg->fastmap = NULL;
6484 return ret;
6486 WEAK_ALIAS (__regcomp, regcomp)
6489 /* regexec searches for a given pattern, specified by PREG, in the
6490 string STRING.
6492 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6493 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6494 least NMATCH elements, and we set them to the offsets of the
6495 corresponding matched substrings.
6497 EFLAGS specifies `execution flags' which affect matching: if
6498 REG_NOTBOL is set, then ^ does not match at the beginning of the
6499 string; if REG_NOTEOL is set, then $ does not match at the end.
6501 We return 0 if we find a match and REG_NOMATCH if not. */
6503 reg_errcode_t
6504 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6505 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6507 regoff_t ret;
6508 struct re_registers regs;
6509 regex_t private_preg;
6510 size_t len = strlen (string);
6511 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6513 private_preg = *preg;
6515 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6516 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6518 /* The user has told us exactly how many registers to return
6519 information about, via `nmatch'. We have to pass that on to the
6520 matching routines. */
6521 private_preg.regs_allocated = REGS_FIXED;
6523 if (want_reg_info)
6525 regs.num_regs = nmatch;
6526 regs.start = TALLOC (nmatch * 2, regoff_t);
6527 if (regs.start == NULL)
6528 return REG_NOMATCH;
6529 regs.end = regs.start + nmatch;
6532 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6533 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6534 was a little bit longer but still only matching the real part.
6535 This works because the `endline' will check for a '\n' and will find a
6536 '\0', correctly deciding that this is not the end of a line.
6537 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6538 a convenient '\0' there. For all we know, the string could be preceded
6539 by '\n' which would throw things off. */
6541 /* Perform the searching operation. */
6542 ret = re_search (&private_preg, string, len,
6543 /* start: */ 0, /* range: */ len,
6544 want_reg_info ? &regs : 0);
6546 /* Copy the register information to the POSIX structure. */
6547 if (want_reg_info)
6549 if (ret >= 0)
6551 unsigned r;
6553 for (r = 0; r < nmatch; r++)
6555 pmatch[r].rm_so = regs.start[r];
6556 pmatch[r].rm_eo = regs.end[r];
6560 /* If we needed the temporary register info, free the space now. */
6561 free (regs.start);
6564 /* We want zero return to mean success, unlike `re_search'. */
6565 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6567 WEAK_ALIAS (__regexec, regexec)
6570 /* Returns a message corresponding to an error code, ERR_CODE, returned
6571 from either regcomp or regexec. We don't use PREG here.
6573 ERR_CODE was previously called ERRCODE, but that name causes an
6574 error with msvc8 compiler. */
6576 size_t
6577 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6579 const char *msg;
6580 size_t msg_size;
6582 if (err_code < 0
6583 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6584 /* Only error codes returned by the rest of the code should be passed
6585 to this routine. If we are given anything else, or if other regex
6586 code generates an invalid error code, then the program has a bug.
6587 Dump core so we can fix it. */
6588 abort ();
6590 msg = gettext (re_error_msgid[err_code]);
6592 msg_size = strlen (msg) + 1; /* Includes the null. */
6594 if (errbuf_size != 0)
6596 if (msg_size > errbuf_size)
6598 memcpy (errbuf, msg, errbuf_size - 1);
6599 errbuf[errbuf_size - 1] = 0;
6601 else
6602 strcpy (errbuf, msg);
6605 return msg_size;
6607 WEAK_ALIAS (__regerror, regerror)
6610 /* Free dynamically allocated space used by PREG. */
6612 void
6613 regfree (regex_t *preg)
6615 free (preg->buffer);
6616 preg->buffer = NULL;
6618 preg->allocated = 0;
6619 preg->used = 0;
6621 free (preg->fastmap);
6622 preg->fastmap = NULL;
6623 preg->fastmap_accurate = 0;
6625 free (preg->translate);
6626 preg->translate = NULL;
6628 WEAK_ALIAS (__regfree, regfree)
6630 #endif /* not emacs */