Fix display of mouse-highlight produced by overlapping overlays
[emacs.git] / src / regex.c
blob8e38a920cdb1615d8ca9c7018f1afd242fc8e39f
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993-2017 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* TODO:
21 - structure the opcode space into opcode+flag.
22 - merge with glibc's regex.[ch].
23 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
24 need to modify the compiled regexp so that re_match can be reentrant.
25 - get rid of on_failure_jump_smart by doing the optimization in re_comp
26 rather than at run-time, so that re_match can be reentrant.
29 /* AIX requires this to be the first thing in the file. */
30 #if defined _AIX && !defined REGEX_MALLOC
31 #pragma alloca
32 #endif
34 /* Ignore some GCC warnings for now. This section should go away
35 once the Emacs and Gnulib regex code is merged. */
36 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__) || defined __clang__
37 # pragma GCC diagnostic ignored "-Wstrict-overflow"
38 # ifndef emacs
39 # pragma GCC diagnostic ignored "-Wunused-function"
40 # pragma GCC diagnostic ignored "-Wunused-macros"
41 # pragma GCC diagnostic ignored "-Wunused-result"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
43 # endif
44 #endif
46 #if 4 < __GNUC__ + (6 <= __GNUC_MINOR__) && ! defined __clang__
47 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
48 #endif
50 #include <config.h>
52 #include <stddef.h>
53 #include <stdlib.h>
55 #ifdef emacs
56 /* We need this for `regex.h', and perhaps for the Emacs include files. */
57 # include <sys/types.h>
58 #endif
60 /* Whether to use ISO C Amendment 1 wide char functions.
61 Those should not be used for Emacs since it uses its own. */
62 #if defined _LIBC
63 #define WIDE_CHAR_SUPPORT 1
64 #else
65 #define WIDE_CHAR_SUPPORT \
66 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
67 #endif
69 /* For platform which support the ISO C amendment 1 functionality we
70 support user defined character classes. */
71 #if WIDE_CHAR_SUPPORT
72 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
73 # include <wchar.h>
74 # include <wctype.h>
75 #endif
77 #ifdef _LIBC
78 /* We have to keep the namespace clean. */
79 # define regfree(preg) __regfree (preg)
80 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
81 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
82 # define regerror(err_code, preg, errbuf, errbuf_size) \
83 __regerror (err_code, preg, errbuf, errbuf_size)
84 # define re_set_registers(bu, re, nu, st, en) \
85 __re_set_registers (bu, re, nu, st, en)
86 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
87 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
88 # define re_match(bufp, string, size, pos, regs) \
89 __re_match (bufp, string, size, pos, regs)
90 # define re_search(bufp, string, size, startpos, range, regs) \
91 __re_search (bufp, string, size, startpos, range, regs)
92 # define re_compile_pattern(pattern, length, bufp) \
93 __re_compile_pattern (pattern, length, bufp)
94 # define re_set_syntax(syntax) __re_set_syntax (syntax)
95 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
96 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
97 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
99 /* Make sure we call libc's function even if the user overrides them. */
100 # define btowc __btowc
101 # define iswctype __iswctype
102 # define wctype __wctype
104 # define WEAK_ALIAS(a,b) weak_alias (a, b)
106 /* We are also using some library internals. */
107 # include <locale/localeinfo.h>
108 # include <locale/elem-hash.h>
109 # include <langinfo.h>
110 #else
111 # define WEAK_ALIAS(a,b)
112 #endif
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
117 #else
118 # define gettext(msgid) (msgid)
119 #endif
121 #ifndef gettext_noop
122 /* This define is so xgettext can find the internationalizable
123 strings. */
124 # define gettext_noop(String) String
125 #endif
127 /* The `emacs' switch turns on certain matching commands
128 that make sense only in Emacs. */
129 #ifdef emacs
131 # include "lisp.h"
132 # include "character.h"
133 # include "buffer.h"
135 # include "syntax.h"
136 # include "category.h"
138 /* Make syntax table lookup grant data in gl_state. */
139 # define SYNTAX(c) syntax_property (c, 1)
141 # ifdef malloc
142 # undef malloc
143 # endif
144 # define malloc xmalloc
145 # ifdef realloc
146 # undef realloc
147 # endif
148 # define realloc xrealloc
149 # ifdef free
150 # undef free
151 # endif
152 # define free xfree
154 /* Converts the pointer to the char to BEG-based offset from the start. */
155 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
156 /* Strings are 0-indexed, buffers are 1-indexed; we pun on the boolean
157 result to get the right base index. */
158 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
160 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
161 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
162 # define RE_STRING_CHAR(p, multibyte) \
163 (multibyte ? (STRING_CHAR (p)) : (*(p)))
164 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
165 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
167 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
169 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
171 /* Set C a (possibly converted to multibyte) character before P. P
172 points into a string which is the virtual concatenation of STR1
173 (which ends at END1) or STR2 (which ends at END2). */
174 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
175 do { \
176 if (target_multibyte) \
178 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
179 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
180 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
181 c = STRING_CHAR (dtemp); \
183 else \
185 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
188 } while (0)
190 /* Set C a (possibly converted to multibyte) character at P, and set
191 LEN to the byte length of that character. */
192 # define GET_CHAR_AFTER(c, p, len) \
193 do { \
194 if (target_multibyte) \
195 (c) = STRING_CHAR_AND_LENGTH (p, len); \
196 else \
198 (c) = *p; \
199 len = 1; \
200 (c) = RE_CHAR_TO_MULTIBYTE (c); \
202 } while (0)
204 #else /* not emacs */
206 /* If we are not linking with Emacs proper,
207 we can't use the relocating allocator
208 even if config.h says that we can. */
209 # undef REL_ALLOC
211 # include <unistd.h>
213 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
215 static void *
216 xmalloc (size_t size)
218 void *val = malloc (size);
219 if (!val && size)
221 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
222 exit (1);
224 return val;
227 static void *
228 xrealloc (void *block, size_t size)
230 void *val;
231 /* We must call malloc explicitly when BLOCK is 0, since some
232 reallocs don't do this. */
233 if (! block)
234 val = malloc (size);
235 else
236 val = realloc (block, size);
237 if (!val && size)
239 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
240 exit (1);
242 return val;
245 # ifdef malloc
246 # undef malloc
247 # endif
248 # define malloc xmalloc
249 # ifdef realloc
250 # undef realloc
251 # endif
252 # define realloc xrealloc
254 # include <stdbool.h>
255 # include <string.h>
257 /* Define the syntax stuff for \<, \>, etc. */
259 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
260 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
262 /* Dummy macros for non-Emacs environments. */
263 # define MAX_MULTIBYTE_LENGTH 1
264 # define RE_MULTIBYTE_P(x) 0
265 # define RE_TARGET_MULTIBYTE_P(x) 0
266 # define WORD_BOUNDARY_P(c1, c2) (0)
267 # define BYTES_BY_CHAR_HEAD(p) (1)
268 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
269 # define STRING_CHAR(p) (*(p))
270 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
271 # define CHAR_STRING(c, s) (*(s) = (c), 1)
272 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
273 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
274 # define RE_CHAR_TO_MULTIBYTE(c) (c)
275 # define RE_CHAR_TO_UNIBYTE(c) (c)
276 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
277 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
278 # define GET_CHAR_AFTER(c, p, len) \
279 (c = *p, len = 1)
280 # define CHAR_BYTE8_P(c) (0)
281 # define CHAR_LEADING_CODE(c) (c)
283 #endif /* not emacs */
285 #ifndef RE_TRANSLATE
286 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
287 # define RE_TRANSLATE_P(TBL) (TBL)
288 #endif
290 /* Get the interface, including the syntax bits. */
291 #include "regex.h"
293 /* isalpha etc. are used for the character classes. */
294 #include <ctype.h>
296 #ifdef emacs
298 /* 1 if C is an ASCII character. */
299 # define IS_REAL_ASCII(c) ((c) < 0200)
301 /* 1 if C is a unibyte character. */
302 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
304 /* The Emacs definitions should not be directly affected by locales. */
306 /* In Emacs, these are only used for single-byte characters. */
307 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
308 # define ISCNTRL(c) ((c) < ' ')
309 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
310 || ((c) >= 'a' && (c) <= 'f') \
311 || ((c) >= 'A' && (c) <= 'F'))
313 /* The rest must handle multibyte characters. */
315 # define ISBLANK(c) (IS_REAL_ASCII (c) \
316 ? ((c) == ' ' || (c) == '\t') \
317 : blankp (c))
319 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
320 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0240) \
321 : graphicp (c))
323 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
324 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
325 : printablep (c))
327 # define ISALNUM(c) (IS_REAL_ASCII (c) \
328 ? (((c) >= 'a' && (c) <= 'z') \
329 || ((c) >= 'A' && (c) <= 'Z') \
330 || ((c) >= '0' && (c) <= '9')) \
331 : alphanumericp (c))
333 # define ISALPHA(c) (IS_REAL_ASCII (c) \
334 ? (((c) >= 'a' && (c) <= 'z') \
335 || ((c) >= 'A' && (c) <= 'Z')) \
336 : alphabeticp (c))
338 # define ISLOWER(c) lowercasep (c)
340 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
341 ? ((c) > ' ' && (c) < 0177 \
342 && !(((c) >= 'a' && (c) <= 'z') \
343 || ((c) >= 'A' && (c) <= 'Z') \
344 || ((c) >= '0' && (c) <= '9'))) \
345 : SYNTAX (c) != Sword)
347 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
349 # define ISUPPER(c) uppercasep (c)
351 # define ISWORD(c) (SYNTAX (c) == Sword)
353 #else /* not emacs */
355 /* 1 if C is an ASCII character. */
356 # define IS_REAL_ASCII(c) ((c) < 0200)
358 /* This distinction is not meaningful, except in Emacs. */
359 # define ISUNIBYTE(c) 1
361 # ifdef isblank
362 # define ISBLANK(c) isblank (c)
363 # else
364 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
365 # endif
366 # ifdef isgraph
367 # define ISGRAPH(c) isgraph (c)
368 # else
369 # define ISGRAPH(c) (isprint (c) && !isspace (c))
370 # endif
372 /* Solaris defines ISPRINT so we must undefine it first. */
373 # undef ISPRINT
374 # define ISPRINT(c) isprint (c)
375 # define ISDIGIT(c) isdigit (c)
376 # define ISALNUM(c) isalnum (c)
377 # define ISALPHA(c) isalpha (c)
378 # define ISCNTRL(c) iscntrl (c)
379 # define ISLOWER(c) islower (c)
380 # define ISPUNCT(c) ispunct (c)
381 # define ISSPACE(c) isspace (c)
382 # define ISUPPER(c) isupper (c)
383 # define ISXDIGIT(c) isxdigit (c)
385 # define ISWORD(c) ISALPHA (c)
387 # ifdef _tolower
388 # define TOLOWER(c) _tolower (c)
389 # else
390 # define TOLOWER(c) tolower (c)
391 # endif
393 /* How many characters in the character set. */
394 # define CHAR_SET_SIZE 256
396 # ifdef SYNTAX_TABLE
398 extern char *re_syntax_table;
400 # else /* not SYNTAX_TABLE */
402 static char re_syntax_table[CHAR_SET_SIZE];
404 static void
405 init_syntax_once (void)
407 register int c;
408 static int done = 0;
410 if (done)
411 return;
413 memset (re_syntax_table, 0, sizeof re_syntax_table);
415 for (c = 0; c < CHAR_SET_SIZE; ++c)
416 if (ISALNUM (c))
417 re_syntax_table[c] = Sword;
419 re_syntax_table['_'] = Ssymbol;
421 done = 1;
424 # endif /* not SYNTAX_TABLE */
426 # define SYNTAX(c) re_syntax_table[(c)]
428 #endif /* not emacs */
430 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
432 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
433 use `alloca' instead of `malloc'. This is because using malloc in
434 re_search* or re_match* could cause memory leaks when C-g is used
435 in Emacs (note that SAFE_ALLOCA could also call malloc, but does so
436 via `record_xmalloc' which uses `unwind_protect' to ensure the
437 memory is freed even in case of non-local exits); also, malloc is
438 slower and causes storage fragmentation. On the other hand, malloc
439 is more portable, and easier to debug.
441 Because we sometimes use alloca, some routines have to be macros,
442 not functions -- `alloca'-allocated space disappears at the end of the
443 function it is called in. */
445 #ifdef REGEX_MALLOC
447 # define REGEX_ALLOCATE malloc
448 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
449 # define REGEX_FREE free
451 #else /* not REGEX_MALLOC */
453 # ifdef emacs
454 /* This may be adjusted in main(), if the stack is successfully grown. */
455 ptrdiff_t emacs_re_safe_alloca = MAX_ALLOCA;
456 /* Like USE_SAFE_ALLOCA, but use emacs_re_safe_alloca. */
457 # define REGEX_USE_SAFE_ALLOCA \
458 ptrdiff_t sa_avail = emacs_re_safe_alloca; \
459 ptrdiff_t sa_count = SPECPDL_INDEX (); bool sa_must_free = false
461 # define REGEX_SAFE_FREE() SAFE_FREE ()
462 # define REGEX_ALLOCATE SAFE_ALLOCA
463 # else
464 # include <alloca.h>
465 # define REGEX_ALLOCATE alloca
466 # endif
468 /* Assumes a `char *destination' variable. */
469 # define REGEX_REALLOCATE(source, osize, nsize) \
470 (destination = REGEX_ALLOCATE (nsize), \
471 memcpy (destination, source, osize))
473 /* No need to do anything to free, after alloca. */
474 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
476 #endif /* not REGEX_MALLOC */
478 #ifndef REGEX_USE_SAFE_ALLOCA
479 # define REGEX_USE_SAFE_ALLOCA ((void) 0)
480 # define REGEX_SAFE_FREE() ((void) 0)
481 #endif
483 /* Define how to allocate the failure stack. */
485 #if defined REL_ALLOC && defined REGEX_MALLOC
487 # define REGEX_ALLOCATE_STACK(size) \
488 r_alloc (&failure_stack_ptr, (size))
489 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
490 r_re_alloc (&failure_stack_ptr, (nsize))
491 # define REGEX_FREE_STACK(ptr) \
492 r_alloc_free (&failure_stack_ptr)
494 #else /* not using relocating allocator */
496 # define REGEX_ALLOCATE_STACK(size) REGEX_ALLOCATE (size)
497 # define REGEX_REALLOCATE_STACK(source, o, n) REGEX_REALLOCATE (source, o, n)
498 # define REGEX_FREE_STACK(ptr) REGEX_FREE (ptr)
500 #endif /* not using relocating allocator */
503 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
504 `string1' or just past its end. This works if PTR is NULL, which is
505 a good thing. */
506 #define FIRST_STRING_P(ptr) \
507 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
509 /* (Re)Allocate N items of type T using malloc, or fail. */
510 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
511 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
512 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
514 #define BYTEWIDTH 8 /* In bits. */
516 #ifndef emacs
517 # undef max
518 # undef min
519 # define max(a, b) ((a) > (b) ? (a) : (b))
520 # define min(a, b) ((a) < (b) ? (a) : (b))
521 #endif
523 /* Type of source-pattern and string chars. */
524 #ifdef _MSC_VER
525 typedef unsigned char re_char;
526 typedef const re_char const_re_char;
527 #else
528 typedef const unsigned char re_char;
529 typedef re_char const_re_char;
530 #endif
532 typedef char boolean;
534 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
535 re_char *string1, size_t size1,
536 re_char *string2, size_t size2,
537 ssize_t pos,
538 struct re_registers *regs,
539 ssize_t stop);
541 /* These are the command codes that appear in compiled regular
542 expressions. Some opcodes are followed by argument bytes. A
543 command code can specify any interpretation whatsoever for its
544 arguments. Zero bytes may appear in the compiled regular expression. */
546 typedef enum
548 no_op = 0,
550 /* Succeed right away--no more backtracking. */
551 succeed,
553 /* Followed by one byte giving n, then by n literal bytes. */
554 exactn,
556 /* Matches any (more or less) character. */
557 anychar,
559 /* Matches any one char belonging to specified set. First
560 following byte is number of bitmap bytes. Then come bytes
561 for a bitmap saying which chars are in. Bits in each byte
562 are ordered low-bit-first. A character is in the set if its
563 bit is 1. A character too large to have a bit in the map is
564 automatically not in the set.
566 If the length byte has the 0x80 bit set, then that stuff
567 is followed by a range table:
568 2 bytes of flags for character sets (low 8 bits, high 8 bits)
569 See RANGE_TABLE_WORK_BITS below.
570 2 bytes, the number of pairs that follow (upto 32767)
571 pairs, each 2 multibyte characters,
572 each multibyte character represented as 3 bytes. */
573 charset,
575 /* Same parameters as charset, but match any character that is
576 not one of those specified. */
577 charset_not,
579 /* Start remembering the text that is matched, for storing in a
580 register. Followed by one byte with the register number, in
581 the range 0 to one less than the pattern buffer's re_nsub
582 field. */
583 start_memory,
585 /* Stop remembering the text that is matched and store it in a
586 memory register. Followed by one byte with the register
587 number, in the range 0 to one less than `re_nsub' in the
588 pattern buffer. */
589 stop_memory,
591 /* Match a duplicate of something remembered. Followed by one
592 byte containing the register number. */
593 duplicate,
595 /* Fail unless at beginning of line. */
596 begline,
598 /* Fail unless at end of line. */
599 endline,
601 /* Succeeds if at beginning of buffer (if emacs) or at beginning
602 of string to be matched (if not). */
603 begbuf,
605 /* Analogously, for end of buffer/string. */
606 endbuf,
608 /* Followed by two byte relative address to which to jump. */
609 jump,
611 /* Followed by two-byte relative address of place to resume at
612 in case of failure. */
613 on_failure_jump,
615 /* Like on_failure_jump, but pushes a placeholder instead of the
616 current string position when executed. */
617 on_failure_keep_string_jump,
619 /* Just like `on_failure_jump', except that it checks that we
620 don't get stuck in an infinite loop (matching an empty string
621 indefinitely). */
622 on_failure_jump_loop,
624 /* Just like `on_failure_jump_loop', except that it checks for
625 a different kind of loop (the kind that shows up with non-greedy
626 operators). This operation has to be immediately preceded
627 by a `no_op'. */
628 on_failure_jump_nastyloop,
630 /* A smart `on_failure_jump' used for greedy * and + operators.
631 It analyzes the loop before which it is put and if the
632 loop does not require backtracking, it changes itself to
633 `on_failure_keep_string_jump' and short-circuits the loop,
634 else it just defaults to changing itself into `on_failure_jump'.
635 It assumes that it is pointing to just past a `jump'. */
636 on_failure_jump_smart,
638 /* Followed by two-byte relative address and two-byte number n.
639 After matching N times, jump to the address upon failure.
640 Does not work if N starts at 0: use on_failure_jump_loop
641 instead. */
642 succeed_n,
644 /* Followed by two-byte relative address, and two-byte number n.
645 Jump to the address N times, then fail. */
646 jump_n,
648 /* Set the following two-byte relative address to the
649 subsequent two-byte number. The address *includes* the two
650 bytes of number. */
651 set_number_at,
653 wordbeg, /* Succeeds if at word beginning. */
654 wordend, /* Succeeds if at word end. */
656 wordbound, /* Succeeds if at a word boundary. */
657 notwordbound, /* Succeeds if not at a word boundary. */
659 symbeg, /* Succeeds if at symbol beginning. */
660 symend, /* Succeeds if at symbol end. */
662 /* Matches any character whose syntax is specified. Followed by
663 a byte which contains a syntax code, e.g., Sword. */
664 syntaxspec,
666 /* Matches any character whose syntax is not that specified. */
667 notsyntaxspec
669 #ifdef emacs
670 , at_dot, /* Succeeds if at point. */
672 /* Matches any character whose category-set contains the specified
673 category. The operator is followed by a byte which contains a
674 category code (mnemonic ASCII character). */
675 categoryspec,
677 /* Matches any character whose category-set does not contain the
678 specified category. The operator is followed by a byte which
679 contains the category code (mnemonic ASCII character). */
680 notcategoryspec
681 #endif /* emacs */
682 } re_opcode_t;
684 /* Common operations on the compiled pattern. */
686 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
688 #define STORE_NUMBER(destination, number) \
689 do { \
690 (destination)[0] = (number) & 0377; \
691 (destination)[1] = (number) >> 8; \
692 } while (0)
694 /* Same as STORE_NUMBER, except increment DESTINATION to
695 the byte after where the number is stored. Therefore, DESTINATION
696 must be an lvalue. */
698 #define STORE_NUMBER_AND_INCR(destination, number) \
699 do { \
700 STORE_NUMBER (destination, number); \
701 (destination) += 2; \
702 } while (0)
704 /* Put into DESTINATION a number stored in two contiguous bytes starting
705 at SOURCE. */
707 #define EXTRACT_NUMBER(destination, source) \
708 ((destination) = extract_number (source))
710 static int
711 extract_number (re_char *source)
713 unsigned leading_byte = SIGN_EXTEND_CHAR (source[1]);
714 return (leading_byte << 8) + source[0];
717 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
718 SOURCE must be an lvalue. */
720 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
721 ((destination) = extract_number_and_incr (&source))
723 static int
724 extract_number_and_incr (re_char **source)
726 int num = extract_number (*source);
727 *source += 2;
728 return num;
731 /* Store a multibyte character in three contiguous bytes starting
732 DESTINATION, and increment DESTINATION to the byte after where the
733 character is stored. Therefore, DESTINATION must be an lvalue. */
735 #define STORE_CHARACTER_AND_INCR(destination, character) \
736 do { \
737 (destination)[0] = (character) & 0377; \
738 (destination)[1] = ((character) >> 8) & 0377; \
739 (destination)[2] = (character) >> 16; \
740 (destination) += 3; \
741 } while (0)
743 /* Put into DESTINATION a character stored in three contiguous bytes
744 starting at SOURCE. */
746 #define EXTRACT_CHARACTER(destination, source) \
747 do { \
748 (destination) = ((source)[0] \
749 | ((source)[1] << 8) \
750 | ((source)[2] << 16)); \
751 } while (0)
754 /* Macros for charset. */
756 /* Size of bitmap of charset P in bytes. P is a start of charset,
757 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
758 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
760 /* Nonzero if charset P has range table. */
761 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
763 /* Return the address of range table of charset P. But not the start
764 of table itself, but the before where the number of ranges is
765 stored. `2 +' means to skip re_opcode_t and size of bitmap,
766 and the 2 bytes of flags at the start of the range table. */
767 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
769 #ifdef emacs
770 /* Extract the bit flags that start a range table. */
771 #define CHARSET_RANGE_TABLE_BITS(p) \
772 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
773 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
774 #endif
776 /* Return the address of end of RANGE_TABLE. COUNT is number of
777 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
778 is start of range and end of range. `* 3' is size of each start
779 and end. */
780 #define CHARSET_RANGE_TABLE_END(range_table, count) \
781 ((range_table) + (count) * 2 * 3)
783 /* If DEBUG is defined, Regex prints many voluminous messages about what
784 it is doing (if the variable `debug' is nonzero). If linked with the
785 main program in `iregex.c', you can enter patterns and strings
786 interactively. And if linked with the main program in `main.c' and
787 the other test files, you can run the already-written tests. */
789 #ifdef DEBUG
791 /* We use standard I/O for debugging. */
792 # include <stdio.h>
794 /* It is useful to test things that ``must'' be true when debugging. */
795 # include <assert.h>
797 static int debug = -100000;
799 # define DEBUG_STATEMENT(e) e
800 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
801 # define DEBUG_COMPILES_ARGUMENTS
802 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
803 if (debug > 0) print_partial_compiled_pattern (s, e)
804 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
805 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
808 /* Print the fastmap in human-readable form. */
810 static void
811 print_fastmap (char *fastmap)
813 unsigned was_a_range = 0;
814 unsigned i = 0;
816 while (i < (1 << BYTEWIDTH))
818 if (fastmap[i++])
820 was_a_range = 0;
821 putchar (i - 1);
822 while (i < (1 << BYTEWIDTH) && fastmap[i])
824 was_a_range = 1;
825 i++;
827 if (was_a_range)
829 printf ("-");
830 putchar (i - 1);
834 putchar ('\n');
838 /* Print a compiled pattern string in human-readable form, starting at
839 the START pointer into it and ending just before the pointer END. */
841 static void
842 print_partial_compiled_pattern (re_char *start, re_char *end)
844 int mcnt, mcnt2;
845 re_char *p = start;
846 re_char *pend = end;
848 if (start == NULL)
850 fprintf (stderr, "(null)\n");
851 return;
854 /* Loop over pattern commands. */
855 while (p < pend)
857 fprintf (stderr, "%td:\t", p - start);
859 switch ((re_opcode_t) *p++)
861 case no_op:
862 fprintf (stderr, "/no_op");
863 break;
865 case succeed:
866 fprintf (stderr, "/succeed");
867 break;
869 case exactn:
870 mcnt = *p++;
871 fprintf (stderr, "/exactn/%d", mcnt);
874 fprintf (stderr, "/%c", *p++);
876 while (--mcnt);
877 break;
879 case start_memory:
880 fprintf (stderr, "/start_memory/%d", *p++);
881 break;
883 case stop_memory:
884 fprintf (stderr, "/stop_memory/%d", *p++);
885 break;
887 case duplicate:
888 fprintf (stderr, "/duplicate/%d", *p++);
889 break;
891 case anychar:
892 fprintf (stderr, "/anychar");
893 break;
895 case charset:
896 case charset_not:
898 register int c, last = -100;
899 register int in_range = 0;
900 int length = CHARSET_BITMAP_SIZE (p - 1);
901 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
903 fprintf (stderr, "/charset [%s",
904 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
906 if (p + *p >= pend)
907 fprintf (stderr, " !extends past end of pattern! ");
909 for (c = 0; c < 256; c++)
910 if (c / 8 < length
911 && (p[1 + (c/8)] & (1 << (c % 8))))
913 /* Are we starting a range? */
914 if (last + 1 == c && ! in_range)
916 fprintf (stderr, "-");
917 in_range = 1;
919 /* Have we broken a range? */
920 else if (last + 1 != c && in_range)
922 fprintf (stderr, "%c", last);
923 in_range = 0;
926 if (! in_range)
927 fprintf (stderr, "%c", c);
929 last = c;
932 if (in_range)
933 fprintf (stderr, "%c", last);
935 fprintf (stderr, "]");
937 p += 1 + length;
939 if (has_range_table)
941 int count;
942 fprintf (stderr, "has-range-table");
944 /* ??? Should print the range table; for now, just skip it. */
945 p += 2; /* skip range table bits */
946 EXTRACT_NUMBER_AND_INCR (count, p);
947 p = CHARSET_RANGE_TABLE_END (p, count);
950 break;
952 case begline:
953 fprintf (stderr, "/begline");
954 break;
956 case endline:
957 fprintf (stderr, "/endline");
958 break;
960 case on_failure_jump:
961 EXTRACT_NUMBER_AND_INCR (mcnt, p);
962 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
963 break;
965 case on_failure_keep_string_jump:
966 EXTRACT_NUMBER_AND_INCR (mcnt, p);
967 fprintf (stderr, "/on_failure_keep_string_jump to %td",
968 p + mcnt - start);
969 break;
971 case on_failure_jump_nastyloop:
972 EXTRACT_NUMBER_AND_INCR (mcnt, p);
973 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
974 p + mcnt - start);
975 break;
977 case on_failure_jump_loop:
978 EXTRACT_NUMBER_AND_INCR (mcnt, p);
979 fprintf (stderr, "/on_failure_jump_loop to %td",
980 p + mcnt - start);
981 break;
983 case on_failure_jump_smart:
984 EXTRACT_NUMBER_AND_INCR (mcnt, p);
985 fprintf (stderr, "/on_failure_jump_smart to %td",
986 p + mcnt - start);
987 break;
989 case jump:
990 EXTRACT_NUMBER_AND_INCR (mcnt, p);
991 fprintf (stderr, "/jump to %td", p + mcnt - start);
992 break;
994 case succeed_n:
995 EXTRACT_NUMBER_AND_INCR (mcnt, p);
996 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
997 fprintf (stderr, "/succeed_n to %td, %d times",
998 p - 2 + mcnt - start, mcnt2);
999 break;
1001 case jump_n:
1002 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1003 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1004 fprintf (stderr, "/jump_n to %td, %d times",
1005 p - 2 + mcnt - start, mcnt2);
1006 break;
1008 case set_number_at:
1009 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1010 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1011 fprintf (stderr, "/set_number_at location %td to %d",
1012 p - 2 + mcnt - start, mcnt2);
1013 break;
1015 case wordbound:
1016 fprintf (stderr, "/wordbound");
1017 break;
1019 case notwordbound:
1020 fprintf (stderr, "/notwordbound");
1021 break;
1023 case wordbeg:
1024 fprintf (stderr, "/wordbeg");
1025 break;
1027 case wordend:
1028 fprintf (stderr, "/wordend");
1029 break;
1031 case symbeg:
1032 fprintf (stderr, "/symbeg");
1033 break;
1035 case symend:
1036 fprintf (stderr, "/symend");
1037 break;
1039 case syntaxspec:
1040 fprintf (stderr, "/syntaxspec");
1041 mcnt = *p++;
1042 fprintf (stderr, "/%d", mcnt);
1043 break;
1045 case notsyntaxspec:
1046 fprintf (stderr, "/notsyntaxspec");
1047 mcnt = *p++;
1048 fprintf (stderr, "/%d", mcnt);
1049 break;
1051 # ifdef emacs
1052 case at_dot:
1053 fprintf (stderr, "/at_dot");
1054 break;
1056 case categoryspec:
1057 fprintf (stderr, "/categoryspec");
1058 mcnt = *p++;
1059 fprintf (stderr, "/%d", mcnt);
1060 break;
1062 case notcategoryspec:
1063 fprintf (stderr, "/notcategoryspec");
1064 mcnt = *p++;
1065 fprintf (stderr, "/%d", mcnt);
1066 break;
1067 # endif /* emacs */
1069 case begbuf:
1070 fprintf (stderr, "/begbuf");
1071 break;
1073 case endbuf:
1074 fprintf (stderr, "/endbuf");
1075 break;
1077 default:
1078 fprintf (stderr, "?%d", *(p-1));
1081 fprintf (stderr, "\n");
1084 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1088 static void
1089 print_compiled_pattern (struct re_pattern_buffer *bufp)
1091 re_char *buffer = bufp->buffer;
1093 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1094 printf ("%ld bytes used/%ld bytes allocated.\n",
1095 bufp->used, bufp->allocated);
1097 if (bufp->fastmap_accurate && bufp->fastmap)
1099 printf ("fastmap: ");
1100 print_fastmap (bufp->fastmap);
1103 printf ("re_nsub: %zu\t", bufp->re_nsub);
1104 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1105 printf ("can_be_null: %d\t", bufp->can_be_null);
1106 printf ("no_sub: %d\t", bufp->no_sub);
1107 printf ("not_bol: %d\t", bufp->not_bol);
1108 printf ("not_eol: %d\t", bufp->not_eol);
1109 #ifndef emacs
1110 printf ("syntax: %lx\n", bufp->syntax);
1111 #endif
1112 fflush (stdout);
1113 /* Perhaps we should print the translate table? */
1117 static void
1118 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1119 re_char *string2, ssize_t size2)
1121 ssize_t this_char;
1123 if (where == NULL)
1124 printf ("(null)");
1125 else
1127 if (FIRST_STRING_P (where))
1129 for (this_char = where - string1; this_char < size1; this_char++)
1130 putchar (string1[this_char]);
1132 where = string2;
1135 for (this_char = where - string2; this_char < size2; this_char++)
1136 putchar (string2[this_char]);
1140 #else /* not DEBUG */
1142 # undef assert
1143 # define assert(e)
1145 # define DEBUG_STATEMENT(e)
1146 # define DEBUG_PRINT(...)
1147 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1148 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1150 #endif /* not DEBUG */
1152 #ifndef emacs
1154 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1155 also be assigned to arbitrarily: each pattern buffer stores its own
1156 syntax, so it can be changed between regex compilations. */
1157 /* This has no initializer because initialized variables in Emacs
1158 become read-only after dumping. */
1159 reg_syntax_t re_syntax_options;
1162 /* Specify the precise syntax of regexps for compilation. This provides
1163 for compatibility for various utilities which historically have
1164 different, incompatible syntaxes.
1166 The argument SYNTAX is a bit mask comprised of the various bits
1167 defined in regex.h. We return the old syntax. */
1169 reg_syntax_t
1170 re_set_syntax (reg_syntax_t syntax)
1172 reg_syntax_t ret = re_syntax_options;
1174 re_syntax_options = syntax;
1175 return ret;
1177 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1179 #endif
1181 /* This table gives an error message for each of the error codes listed
1182 in regex.h. Obviously the order here has to be same as there.
1183 POSIX doesn't require that we do anything for REG_NOERROR,
1184 but why not be nice? */
1186 static const char *re_error_msgid[] =
1188 gettext_noop ("Success"), /* REG_NOERROR */
1189 gettext_noop ("No match"), /* REG_NOMATCH */
1190 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1191 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1192 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1193 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1194 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1195 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1196 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1197 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1198 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1199 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1200 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1201 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1202 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1203 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1204 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1205 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1208 /* Whether to allocate memory during matching. */
1210 /* Define MATCH_MAY_ALLOCATE to allow the searching and matching
1211 functions allocate memory for the failure stack and registers.
1212 Normally should be defined, because otherwise searching and
1213 matching routines will have much smaller memory resources at their
1214 disposal, and therefore might fail to handle complex regexps.
1215 Therefore undefine MATCH_MAY_ALLOCATE only in the following
1216 exceptional situations:
1218 . When running on a system where memory is at premium.
1219 . When alloca cannot be used at all, perhaps due to bugs in
1220 its implementation, or its being unavailable, or due to a
1221 very small stack size. This requires to define REGEX_MALLOC
1222 to use malloc instead, which in turn could lead to memory
1223 leaks if search is interrupted by a signal. (For these
1224 reasons, defining REGEX_MALLOC when building Emacs
1225 automatically undefines MATCH_MAY_ALLOCATE, but outside
1226 Emacs you may not care about memory leaks.) If you want to
1227 prevent the memory leaks, undefine MATCH_MAY_ALLOCATE.
1228 . When code that calls the searching and matching functions
1229 cannot allow memory allocation, for whatever reasons. */
1231 /* Normally, this is fine. */
1232 #define MATCH_MAY_ALLOCATE
1234 /* The match routines may not allocate if (1) they would do it with malloc
1235 and (2) it's not safe for them to use malloc.
1236 Note that if REL_ALLOC is defined, matching would not use malloc for the
1237 failure stack, but we would still use it for the register vectors;
1238 so REL_ALLOC should not affect this. */
1239 #if defined REGEX_MALLOC && defined emacs
1240 # undef MATCH_MAY_ALLOCATE
1241 #endif
1244 /* Failure stack declarations and macros; both re_compile_fastmap and
1245 re_match_2 use a failure stack. These have to be macros because of
1246 REGEX_ALLOCATE_STACK. */
1249 /* Approximate number of failure points for which to initially allocate space
1250 when matching. If this number is exceeded, we allocate more
1251 space, so it is not a hard limit. */
1252 #ifndef INIT_FAILURE_ALLOC
1253 # define INIT_FAILURE_ALLOC 20
1254 #endif
1256 /* Roughly the maximum number of failure points on the stack. Would be
1257 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1258 This is a variable only so users of regex can assign to it; we never
1259 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1260 before using it, so it should probably be a byte-count instead. */
1261 # if defined MATCH_MAY_ALLOCATE
1262 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1263 whose default stack limit is 2mb. In order for a larger
1264 value to work reliably, you have to try to make it accord
1265 with the process stack limit. */
1266 size_t emacs_re_max_failures = 40000;
1267 # else
1268 size_t emacs_re_max_failures = 4000;
1269 # endif
1271 union fail_stack_elt
1273 re_char *pointer;
1274 /* This should be the biggest `int' that's no bigger than a pointer. */
1275 long integer;
1278 typedef union fail_stack_elt fail_stack_elt_t;
1280 typedef struct
1282 fail_stack_elt_t *stack;
1283 size_t size;
1284 size_t avail; /* Offset of next open position. */
1285 size_t frame; /* Offset of the cur constructed frame. */
1286 } fail_stack_type;
1288 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1291 /* Define macros to initialize and free the failure stack.
1292 Do `return -2' if the alloc fails. */
1294 #ifdef MATCH_MAY_ALLOCATE
1295 # define INIT_FAIL_STACK() \
1296 do { \
1297 fail_stack.stack = \
1298 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1299 * sizeof (fail_stack_elt_t)); \
1301 if (fail_stack.stack == NULL) \
1302 return -2; \
1304 fail_stack.size = INIT_FAILURE_ALLOC; \
1305 fail_stack.avail = 0; \
1306 fail_stack.frame = 0; \
1307 } while (0)
1308 #else
1309 # define INIT_FAIL_STACK() \
1310 do { \
1311 fail_stack.avail = 0; \
1312 fail_stack.frame = 0; \
1313 } while (0)
1315 # define RETALLOC_IF(addr, n, t) \
1316 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1317 #endif
1320 /* Double the size of FAIL_STACK, up to a limit
1321 which allows approximately `emacs_re_max_failures' items.
1323 Return 1 if succeeds, and 0 if either ran out of memory
1324 allocating space for it or it was already too large.
1326 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1328 /* Factor to increase the failure stack size by
1329 when we increase it.
1330 This used to be 2, but 2 was too wasteful
1331 because the old discarded stacks added up to as much space
1332 were as ultimate, maximum-size stack. */
1333 #define FAIL_STACK_GROWTH_FACTOR 4
1335 #define GROW_FAIL_STACK(fail_stack) \
1336 (((fail_stack).size >= emacs_re_max_failures * TYPICAL_FAILURE_SIZE) \
1337 ? 0 \
1338 : ((fail_stack).stack \
1339 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1340 (fail_stack).size * sizeof (fail_stack_elt_t), \
1341 min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1342 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR)) \
1343 * sizeof (fail_stack_elt_t)), \
1345 (fail_stack).stack == NULL \
1346 ? 0 \
1347 : ((fail_stack).size \
1348 = (min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1349 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR))), \
1350 1)))
1353 /* Push a pointer value onto the failure stack.
1354 Assumes the variable `fail_stack'. Probably should only
1355 be called from within `PUSH_FAILURE_POINT'. */
1356 #define PUSH_FAILURE_POINTER(item) \
1357 fail_stack.stack[fail_stack.avail++].pointer = (item)
1359 /* This pushes an integer-valued item onto the failure stack.
1360 Assumes the variable `fail_stack'. Probably should only
1361 be called from within `PUSH_FAILURE_POINT'. */
1362 #define PUSH_FAILURE_INT(item) \
1363 fail_stack.stack[fail_stack.avail++].integer = (item)
1365 /* These POP... operations complement the PUSH... operations.
1366 All assume that `fail_stack' is nonempty. */
1367 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1368 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1370 /* Individual items aside from the registers. */
1371 #define NUM_NONREG_ITEMS 3
1373 /* Used to examine the stack (to detect infinite loops). */
1374 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1375 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1376 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1377 #define TOP_FAILURE_HANDLE() fail_stack.frame
1380 #define ENSURE_FAIL_STACK(space) \
1381 while (REMAINING_AVAIL_SLOTS <= space) { \
1382 if (!GROW_FAIL_STACK (fail_stack)) \
1383 return -2; \
1384 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1385 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1388 /* Push register NUM onto the stack. */
1389 #define PUSH_FAILURE_REG(num) \
1390 do { \
1391 char *destination; \
1392 long n = num; \
1393 ENSURE_FAIL_STACK(3); \
1394 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1395 n, regstart[n], regend[n]); \
1396 PUSH_FAILURE_POINTER (regstart[n]); \
1397 PUSH_FAILURE_POINTER (regend[n]); \
1398 PUSH_FAILURE_INT (n); \
1399 } while (0)
1401 /* Change the counter's value to VAL, but make sure that it will
1402 be reset when backtracking. */
1403 #define PUSH_NUMBER(ptr,val) \
1404 do { \
1405 char *destination; \
1406 int c; \
1407 ENSURE_FAIL_STACK(3); \
1408 EXTRACT_NUMBER (c, ptr); \
1409 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1410 PUSH_FAILURE_INT (c); \
1411 PUSH_FAILURE_POINTER (ptr); \
1412 PUSH_FAILURE_INT (-1); \
1413 STORE_NUMBER (ptr, val); \
1414 } while (0)
1416 /* Pop a saved register off the stack. */
1417 #define POP_FAILURE_REG_OR_COUNT() \
1418 do { \
1419 long pfreg = POP_FAILURE_INT (); \
1420 if (pfreg == -1) \
1422 /* It's a counter. */ \
1423 /* Here, we discard `const', making re_match non-reentrant. */ \
1424 unsigned char *ptr = (unsigned char *) POP_FAILURE_POINTER (); \
1425 pfreg = POP_FAILURE_INT (); \
1426 STORE_NUMBER (ptr, pfreg); \
1427 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1429 else \
1431 regend[pfreg] = POP_FAILURE_POINTER (); \
1432 regstart[pfreg] = POP_FAILURE_POINTER (); \
1433 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1434 pfreg, regstart[pfreg], regend[pfreg]); \
1436 } while (0)
1438 /* Check that we are not stuck in an infinite loop. */
1439 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1440 do { \
1441 ssize_t failure = TOP_FAILURE_HANDLE (); \
1442 /* Check for infinite matching loops */ \
1443 while (failure > 0 \
1444 && (FAILURE_STR (failure) == string_place \
1445 || FAILURE_STR (failure) == NULL)) \
1447 assert (FAILURE_PAT (failure) >= bufp->buffer \
1448 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1449 if (FAILURE_PAT (failure) == pat_cur) \
1451 cycle = 1; \
1452 break; \
1454 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1455 failure = NEXT_FAILURE_HANDLE(failure); \
1457 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1458 } while (0)
1460 /* Push the information about the state we will need
1461 if we ever fail back to it.
1463 Requires variables fail_stack, regstart, regend and
1464 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1465 declared.
1467 Does `return FAILURE_CODE' if runs out of memory. */
1469 #define PUSH_FAILURE_POINT(pattern, string_place) \
1470 do { \
1471 char *destination; \
1472 /* Must be int, so when we don't save any registers, the arithmetic \
1473 of 0 + -1 isn't done as unsigned. */ \
1475 DEBUG_STATEMENT (nfailure_points_pushed++); \
1476 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1477 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1478 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1480 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1482 DEBUG_PRINT ("\n"); \
1484 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1485 PUSH_FAILURE_INT (fail_stack.frame); \
1487 DEBUG_PRINT (" Push string %p: \"", string_place); \
1488 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1489 DEBUG_PRINT ("\"\n"); \
1490 PUSH_FAILURE_POINTER (string_place); \
1492 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1493 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1494 PUSH_FAILURE_POINTER (pattern); \
1496 /* Close the frame by moving the frame pointer past it. */ \
1497 fail_stack.frame = fail_stack.avail; \
1498 } while (0)
1500 /* Estimate the size of data pushed by a typical failure stack entry.
1501 An estimate is all we need, because all we use this for
1502 is to choose a limit for how big to make the failure stack. */
1503 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1504 #define TYPICAL_FAILURE_SIZE 20
1506 /* How many items can still be added to the stack without overflowing it. */
1507 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1510 /* Pops what PUSH_FAIL_STACK pushes.
1512 We restore into the parameters, all of which should be lvalues:
1513 STR -- the saved data position.
1514 PAT -- the saved pattern position.
1515 REGSTART, REGEND -- arrays of string positions.
1517 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1518 `pend', `string1', `size1', `string2', and `size2'. */
1520 #define POP_FAILURE_POINT(str, pat) \
1521 do { \
1522 assert (!FAIL_STACK_EMPTY ()); \
1524 /* Remove failure points and point to how many regs pushed. */ \
1525 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1526 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1527 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1529 /* Pop the saved registers. */ \
1530 while (fail_stack.frame < fail_stack.avail) \
1531 POP_FAILURE_REG_OR_COUNT (); \
1533 pat = POP_FAILURE_POINTER (); \
1534 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1535 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1537 /* If the saved string location is NULL, it came from an \
1538 on_failure_keep_string_jump opcode, and we want to throw away the \
1539 saved NULL, thus retaining our current position in the string. */ \
1540 str = POP_FAILURE_POINTER (); \
1541 DEBUG_PRINT (" Popping string %p: \"", str); \
1542 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1543 DEBUG_PRINT ("\"\n"); \
1545 fail_stack.frame = POP_FAILURE_INT (); \
1546 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1548 assert (fail_stack.avail >= 0); \
1549 assert (fail_stack.frame <= fail_stack.avail); \
1551 DEBUG_STATEMENT (nfailure_points_popped++); \
1552 } while (0) /* POP_FAILURE_POINT */
1556 /* Registers are set to a sentinel when they haven't yet matched. */
1557 #define REG_UNSET(e) ((e) == NULL)
1559 /* Subroutine declarations and macros for regex_compile. */
1561 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1562 #ifdef emacs
1563 bool posix_backtracking,
1564 const char *whitespace_regexp,
1565 #else
1566 reg_syntax_t syntax,
1567 #endif
1568 struct re_pattern_buffer *bufp);
1569 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1570 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1571 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1572 int arg, unsigned char *end);
1573 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1574 int arg1, int arg2, unsigned char *end);
1575 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1576 reg_syntax_t syntax);
1577 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1578 reg_syntax_t syntax);
1579 static re_char *skip_one_char (re_char *p);
1580 static int analyze_first (re_char *p, re_char *pend,
1581 char *fastmap, const int multibyte);
1583 /* Fetch the next character in the uncompiled pattern, with no
1584 translation. */
1585 #define PATFETCH(c) \
1586 do { \
1587 int len; \
1588 if (p == pend) return REG_EEND; \
1589 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1590 p += len; \
1591 } while (0)
1594 /* If `translate' is non-null, return translate[D], else just D. We
1595 cast the subscript to translate because some data is declared as
1596 `char *', to avoid warnings when a string constant is passed. But
1597 when we use a character as a subscript we must make it unsigned. */
1598 #ifndef TRANSLATE
1599 # define TRANSLATE(d) \
1600 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1601 #endif
1604 /* Macros for outputting the compiled pattern into `buffer'. */
1606 /* If the buffer isn't allocated when it comes in, use this. */
1607 #define INIT_BUF_SIZE 32
1609 /* Make sure we have at least N more bytes of space in buffer. */
1610 #define GET_BUFFER_SPACE(n) \
1611 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1612 EXTEND_BUFFER ()
1614 /* Make sure we have one more byte of buffer space and then add C to it. */
1615 #define BUF_PUSH(c) \
1616 do { \
1617 GET_BUFFER_SPACE (1); \
1618 *b++ = (unsigned char) (c); \
1619 } while (0)
1622 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1623 #define BUF_PUSH_2(c1, c2) \
1624 do { \
1625 GET_BUFFER_SPACE (2); \
1626 *b++ = (unsigned char) (c1); \
1627 *b++ = (unsigned char) (c2); \
1628 } while (0)
1631 /* Store a jump with opcode OP at LOC to location TO. We store a
1632 relative address offset by the three bytes the jump itself occupies. */
1633 #define STORE_JUMP(op, loc, to) \
1634 store_op1 (op, loc, (to) - (loc) - 3)
1636 /* Likewise, for a two-argument jump. */
1637 #define STORE_JUMP2(op, loc, to, arg) \
1638 store_op2 (op, loc, (to) - (loc) - 3, arg)
1640 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1641 #define INSERT_JUMP(op, loc, to) \
1642 insert_op1 (op, loc, (to) - (loc) - 3, b)
1644 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1645 #define INSERT_JUMP2(op, loc, to, arg) \
1646 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1649 /* This is not an arbitrary limit: the arguments which represent offsets
1650 into the pattern are two bytes long. So if 2^15 bytes turns out to
1651 be too small, many things would have to change. */
1652 # define MAX_BUF_SIZE (1L << 15)
1654 /* Extend the buffer by twice its current size via realloc and
1655 reset the pointers that pointed into the old block to point to the
1656 correct places in the new one. If extending the buffer results in it
1657 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1658 #define EXTEND_BUFFER() \
1659 do { \
1660 unsigned char *old_buffer = bufp->buffer; \
1661 if (bufp->allocated == MAX_BUF_SIZE) \
1662 return REG_ESIZE; \
1663 bufp->allocated <<= 1; \
1664 if (bufp->allocated > MAX_BUF_SIZE) \
1665 bufp->allocated = MAX_BUF_SIZE; \
1666 ptrdiff_t b_off = b - old_buffer; \
1667 ptrdiff_t begalt_off = begalt - old_buffer; \
1668 bool fixup_alt_jump_set = !!fixup_alt_jump; \
1669 bool laststart_set = !!laststart; \
1670 bool pending_exact_set = !!pending_exact; \
1671 ptrdiff_t fixup_alt_jump_off, laststart_off, pending_exact_off; \
1672 if (fixup_alt_jump_set) fixup_alt_jump_off = fixup_alt_jump - old_buffer; \
1673 if (laststart_set) laststart_off = laststart - old_buffer; \
1674 if (pending_exact_set) pending_exact_off = pending_exact - old_buffer; \
1675 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1676 if (bufp->buffer == NULL) \
1677 return REG_ESPACE; \
1678 unsigned char *new_buffer = bufp->buffer; \
1679 b = new_buffer + b_off; \
1680 begalt = new_buffer + begalt_off; \
1681 if (fixup_alt_jump_set) fixup_alt_jump = new_buffer + fixup_alt_jump_off; \
1682 if (laststart_set) laststart = new_buffer + laststart_off; \
1683 if (pending_exact_set) pending_exact = new_buffer + pending_exact_off; \
1684 } while (0)
1687 /* Since we have one byte reserved for the register number argument to
1688 {start,stop}_memory, the maximum number of groups we can report
1689 things about is what fits in that byte. */
1690 #define MAX_REGNUM 255
1692 /* But patterns can have more than `MAX_REGNUM' registers. We just
1693 ignore the excess. */
1694 typedef int regnum_t;
1697 /* Macros for the compile stack. */
1699 /* Since offsets can go either forwards or backwards, this type needs to
1700 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1701 /* int may be not enough when sizeof(int) == 2. */
1702 typedef long pattern_offset_t;
1704 typedef struct
1706 pattern_offset_t begalt_offset;
1707 pattern_offset_t fixup_alt_jump;
1708 pattern_offset_t laststart_offset;
1709 regnum_t regnum;
1710 } compile_stack_elt_t;
1713 typedef struct
1715 compile_stack_elt_t *stack;
1716 size_t size;
1717 size_t avail; /* Offset of next open position. */
1718 } compile_stack_type;
1721 #define INIT_COMPILE_STACK_SIZE 32
1723 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1724 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1726 /* The next available element. */
1727 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1729 /* Explicit quit checking is needed for Emacs, which uses polling to
1730 process input events. */
1731 #ifndef emacs
1732 static void maybe_quit (void) {}
1733 #endif
1735 /* Structure to manage work area for range table. */
1736 struct range_table_work_area
1738 int *table; /* actual work area. */
1739 int allocated; /* allocated size for work area in bytes. */
1740 int used; /* actually used size in words. */
1741 int bits; /* flag to record character classes */
1744 #ifdef emacs
1746 /* Make sure that WORK_AREA can hold more N multibyte characters.
1747 This is used only in set_image_of_range and set_image_of_range_1.
1748 It expects WORK_AREA to be a pointer.
1749 If it can't get the space, it returns from the surrounding function. */
1751 #define EXTEND_RANGE_TABLE(work_area, n) \
1752 do { \
1753 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1755 extend_range_table_work_area (&work_area); \
1756 if ((work_area).table == 0) \
1757 return (REG_ESPACE); \
1759 } while (0)
1761 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1762 (work_area).bits |= (bit)
1764 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1765 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1766 do { \
1767 EXTEND_RANGE_TABLE ((work_area), 2); \
1768 (work_area).table[(work_area).used++] = (range_start); \
1769 (work_area).table[(work_area).used++] = (range_end); \
1770 } while (0)
1772 #endif /* emacs */
1774 /* Free allocated memory for WORK_AREA. */
1775 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1776 do { \
1777 if ((work_area).table) \
1778 free ((work_area).table); \
1779 } while (0)
1781 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1782 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1783 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1784 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1786 /* Bits used to implement the multibyte-part of the various character classes
1787 such as [:alnum:] in a charset's range table. The code currently assumes
1788 that only the low 16 bits are used. */
1789 #define BIT_WORD 0x1
1790 #define BIT_LOWER 0x2
1791 #define BIT_PUNCT 0x4
1792 #define BIT_SPACE 0x8
1793 #define BIT_UPPER 0x10
1794 #define BIT_MULTIBYTE 0x20
1795 #define BIT_ALPHA 0x40
1796 #define BIT_ALNUM 0x80
1797 #define BIT_GRAPH 0x100
1798 #define BIT_PRINT 0x200
1799 #define BIT_BLANK 0x400
1802 /* Set the bit for character C in a list. */
1803 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1806 #ifdef emacs
1808 /* Store characters in the range FROM to TO in the bitmap at B (for
1809 ASCII and unibyte characters) and WORK_AREA (for multibyte
1810 characters) while translating them and paying attention to the
1811 continuity of translated characters.
1813 Implementation note: It is better to implement these fairly big
1814 macros by a function, but it's not that easy because macros called
1815 in this macro assume various local variables already declared. */
1817 /* Both FROM and TO are ASCII characters. */
1819 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1820 do { \
1821 int C0, C1; \
1823 for (C0 = (FROM); C0 <= (TO); C0++) \
1825 C1 = TRANSLATE (C0); \
1826 if (! ASCII_CHAR_P (C1)) \
1828 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1829 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1830 C1 = C0; \
1832 SET_LIST_BIT (C1); \
1834 } while (0)
1837 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1839 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1840 do { \
1841 int C0, C1, C2, I; \
1842 int USED = RANGE_TABLE_WORK_USED (work_area); \
1844 for (C0 = (FROM); C0 <= (TO); C0++) \
1846 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1847 if (CHAR_BYTE8_P (C1)) \
1848 SET_LIST_BIT (C0); \
1849 else \
1851 C2 = TRANSLATE (C1); \
1852 if (C2 == C1 \
1853 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1854 C1 = C0; \
1855 SET_LIST_BIT (C1); \
1856 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1858 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1859 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1861 if (C2 >= from - 1 && C2 <= to + 1) \
1863 if (C2 == from - 1) \
1864 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1865 else if (C2 == to + 1) \
1866 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1867 break; \
1870 if (I < USED) \
1871 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1874 } while (0)
1877 /* Both FROM and TO are multibyte characters. */
1879 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1880 do { \
1881 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1883 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1884 for (C0 = (FROM); C0 <= (TO); C0++) \
1886 C1 = TRANSLATE (C0); \
1887 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1888 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1889 SET_LIST_BIT (C2); \
1890 if (C1 >= (FROM) && C1 <= (TO)) \
1891 continue; \
1892 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1894 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1895 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1897 if (C1 >= from - 1 && C1 <= to + 1) \
1899 if (C1 == from - 1) \
1900 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1901 else if (C1 == to + 1) \
1902 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1903 break; \
1906 if (I < USED) \
1907 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1909 } while (0)
1911 #endif /* emacs */
1913 /* Get the next unsigned number in the uncompiled pattern. */
1914 #define GET_INTERVAL_COUNT(num) \
1915 do { \
1916 if (p == pend) \
1917 FREE_STACK_RETURN (REG_EBRACE); \
1918 else \
1920 PATFETCH (c); \
1921 while ('0' <= c && c <= '9') \
1923 if (num < 0) \
1924 num = 0; \
1925 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
1926 FREE_STACK_RETURN (REG_BADBR); \
1927 num = num * 10 + c - '0'; \
1928 if (p == pend) \
1929 FREE_STACK_RETURN (REG_EBRACE); \
1930 PATFETCH (c); \
1933 } while (0)
1935 #if ! WIDE_CHAR_SUPPORT
1937 /* Parse a character class, i.e. string such as "[:name:]". *strp
1938 points to the string to be parsed and limit is length, in bytes, of
1939 that string.
1941 If *strp point to a string that begins with "[:name:]", where name is
1942 a non-empty sequence of lower case letters, *strp will be advanced past the
1943 closing square bracket and RECC_* constant which maps to the name will be
1944 returned. If name is not a valid character class name zero, or RECC_ERROR,
1945 is returned.
1947 Otherwise, if *strp doesn’t begin with "[:name:]", -1 is returned.
1949 The function can be used on ASCII and multibyte (UTF-8-encoded) strings.
1951 re_wctype_t
1952 re_wctype_parse (const unsigned char **strp, unsigned limit)
1954 const char *beg = (const char *)*strp, *it;
1956 if (limit < 4 || beg[0] != '[' || beg[1] != ':')
1957 return -1;
1959 beg += 2; /* skip opening ‘[:’ */
1960 limit -= 3; /* opening ‘[:’ and half of closing ‘:]’; --limit handles rest */
1961 for (it = beg; it[0] != ':' || it[1] != ']'; ++it)
1962 if (!--limit)
1963 return -1;
1965 *strp = (const unsigned char *)(it + 2);
1967 /* Sort tests in the length=five case by frequency the classes to minimize
1968 number of times we fail the comparison. The frequencies of character class
1969 names used in Emacs sources as of 2016-07-27:
1971 $ find \( -name \*.c -o -name \*.el \) -exec grep -h '\[:[a-z]*:]' {} + |
1972 sed 's/]/]\n/g' |grep -o '\[:[a-z]*:]' |sort |uniq -c |sort -nr
1973 213 [:alnum:]
1974 104 [:alpha:]
1975 62 [:space:]
1976 39 [:digit:]
1977 36 [:blank:]
1978 26 [:word:]
1979 26 [:upper:]
1980 21 [:lower:]
1981 10 [:xdigit:]
1982 10 [:punct:]
1983 10 [:ascii:]
1984 4 [:nonascii:]
1985 4 [:graph:]
1986 2 [:print:]
1987 2 [:cntrl:]
1988 1 [:ff:]
1990 If you update this list, consider also updating chain of or’ed conditions
1991 in execute_charset function.
1994 switch (it - beg) {
1995 case 4:
1996 if (!memcmp (beg, "word", 4)) return RECC_WORD;
1997 break;
1998 case 5:
1999 if (!memcmp (beg, "alnum", 5)) return RECC_ALNUM;
2000 if (!memcmp (beg, "alpha", 5)) return RECC_ALPHA;
2001 if (!memcmp (beg, "space", 5)) return RECC_SPACE;
2002 if (!memcmp (beg, "digit", 5)) return RECC_DIGIT;
2003 if (!memcmp (beg, "blank", 5)) return RECC_BLANK;
2004 if (!memcmp (beg, "upper", 5)) return RECC_UPPER;
2005 if (!memcmp (beg, "lower", 5)) return RECC_LOWER;
2006 if (!memcmp (beg, "punct", 5)) return RECC_PUNCT;
2007 if (!memcmp (beg, "ascii", 5)) return RECC_ASCII;
2008 if (!memcmp (beg, "graph", 5)) return RECC_GRAPH;
2009 if (!memcmp (beg, "print", 5)) return RECC_PRINT;
2010 if (!memcmp (beg, "cntrl", 5)) return RECC_CNTRL;
2011 break;
2012 case 6:
2013 if (!memcmp (beg, "xdigit", 6)) return RECC_XDIGIT;
2014 break;
2015 case 7:
2016 if (!memcmp (beg, "unibyte", 7)) return RECC_UNIBYTE;
2017 break;
2018 case 8:
2019 if (!memcmp (beg, "nonascii", 8)) return RECC_NONASCII;
2020 break;
2021 case 9:
2022 if (!memcmp (beg, "multibyte", 9)) return RECC_MULTIBYTE;
2023 break;
2026 return RECC_ERROR;
2029 /* True if CH is in the char class CC. */
2030 boolean
2031 re_iswctype (int ch, re_wctype_t cc)
2033 switch (cc)
2035 case RECC_ALNUM: return ISALNUM (ch) != 0;
2036 case RECC_ALPHA: return ISALPHA (ch) != 0;
2037 case RECC_BLANK: return ISBLANK (ch) != 0;
2038 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2039 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2040 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2041 case RECC_LOWER: return ISLOWER (ch) != 0;
2042 case RECC_PRINT: return ISPRINT (ch) != 0;
2043 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2044 case RECC_SPACE: return ISSPACE (ch) != 0;
2045 case RECC_UPPER: return ISUPPER (ch) != 0;
2046 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2047 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2048 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2049 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2050 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2051 case RECC_WORD: return ISWORD (ch) != 0;
2052 case RECC_ERROR: return false;
2053 default:
2054 abort ();
2058 /* Return a bit-pattern to use in the range-table bits to match multibyte
2059 chars of class CC. */
2060 static int
2061 re_wctype_to_bit (re_wctype_t cc)
2063 switch (cc)
2065 case RECC_NONASCII:
2066 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2067 case RECC_ALPHA: return BIT_ALPHA;
2068 case RECC_ALNUM: return BIT_ALNUM;
2069 case RECC_WORD: return BIT_WORD;
2070 case RECC_LOWER: return BIT_LOWER;
2071 case RECC_UPPER: return BIT_UPPER;
2072 case RECC_PUNCT: return BIT_PUNCT;
2073 case RECC_SPACE: return BIT_SPACE;
2074 case RECC_GRAPH: return BIT_GRAPH;
2075 case RECC_PRINT: return BIT_PRINT;
2076 case RECC_BLANK: return BIT_BLANK;
2077 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2078 case RECC_UNIBYTE: case RECC_ERROR: return 0;
2079 default:
2080 abort ();
2083 #endif
2085 /* Filling in the work area of a range. */
2087 /* Actually extend the space in WORK_AREA. */
2089 static void
2090 extend_range_table_work_area (struct range_table_work_area *work_area)
2092 work_area->allocated += 16 * sizeof (int);
2093 work_area->table = realloc (work_area->table, work_area->allocated);
2096 #if 0
2097 #ifdef emacs
2099 /* Carefully find the ranges of codes that are equivalent
2100 under case conversion to the range start..end when passed through
2101 TRANSLATE. Handle the case where non-letters can come in between
2102 two upper-case letters (which happens in Latin-1).
2103 Also handle the case of groups of more than 2 case-equivalent chars.
2105 The basic method is to look at consecutive characters and see
2106 if they can form a run that can be handled as one.
2108 Returns -1 if successful, REG_ESPACE if ran out of space. */
2110 static int
2111 set_image_of_range_1 (struct range_table_work_area *work_area,
2112 re_wchar_t start, re_wchar_t end,
2113 RE_TRANSLATE_TYPE translate)
2115 /* `one_case' indicates a character, or a run of characters,
2116 each of which is an isolate (no case-equivalents).
2117 This includes all ASCII non-letters.
2119 `two_case' indicates a character, or a run of characters,
2120 each of which has two case-equivalent forms.
2121 This includes all ASCII letters.
2123 `strange' indicates a character that has more than one
2124 case-equivalent. */
2126 enum case_type {one_case, two_case, strange};
2128 /* Describe the run that is in progress,
2129 which the next character can try to extend.
2130 If run_type is strange, that means there really is no run.
2131 If run_type is one_case, then run_start...run_end is the run.
2132 If run_type is two_case, then the run is run_start...run_end,
2133 and the case-equivalents end at run_eqv_end. */
2135 enum case_type run_type = strange;
2136 int run_start, run_end, run_eqv_end;
2138 Lisp_Object eqv_table;
2140 if (!RE_TRANSLATE_P (translate))
2142 EXTEND_RANGE_TABLE (work_area, 2);
2143 work_area->table[work_area->used++] = (start);
2144 work_area->table[work_area->used++] = (end);
2145 return -1;
2148 eqv_table = XCHAR_TABLE (translate)->extras[2];
2150 for (; start <= end; start++)
2152 enum case_type this_type;
2153 int eqv = RE_TRANSLATE (eqv_table, start);
2154 int minchar, maxchar;
2156 /* Classify this character */
2157 if (eqv == start)
2158 this_type = one_case;
2159 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2160 this_type = two_case;
2161 else
2162 this_type = strange;
2164 if (start < eqv)
2165 minchar = start, maxchar = eqv;
2166 else
2167 minchar = eqv, maxchar = start;
2169 /* Can this character extend the run in progress? */
2170 if (this_type == strange || this_type != run_type
2171 || !(minchar == run_end + 1
2172 && (run_type == two_case
2173 ? maxchar == run_eqv_end + 1 : 1)))
2175 /* No, end the run.
2176 Record each of its equivalent ranges. */
2177 if (run_type == one_case)
2179 EXTEND_RANGE_TABLE (work_area, 2);
2180 work_area->table[work_area->used++] = run_start;
2181 work_area->table[work_area->used++] = run_end;
2183 else if (run_type == two_case)
2185 EXTEND_RANGE_TABLE (work_area, 4);
2186 work_area->table[work_area->used++] = run_start;
2187 work_area->table[work_area->used++] = run_end;
2188 work_area->table[work_area->used++]
2189 = RE_TRANSLATE (eqv_table, run_start);
2190 work_area->table[work_area->used++]
2191 = RE_TRANSLATE (eqv_table, run_end);
2193 run_type = strange;
2196 if (this_type == strange)
2198 /* For a strange character, add each of its equivalents, one
2199 by one. Don't start a range. */
2202 EXTEND_RANGE_TABLE (work_area, 2);
2203 work_area->table[work_area->used++] = eqv;
2204 work_area->table[work_area->used++] = eqv;
2205 eqv = RE_TRANSLATE (eqv_table, eqv);
2207 while (eqv != start);
2210 /* Add this char to the run, or start a new run. */
2211 else if (run_type == strange)
2213 /* Initialize a new range. */
2214 run_type = this_type;
2215 run_start = start;
2216 run_end = start;
2217 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2219 else
2221 /* Extend a running range. */
2222 run_end = minchar;
2223 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2227 /* If a run is still in progress at the end, finish it now
2228 by recording its equivalent ranges. */
2229 if (run_type == one_case)
2231 EXTEND_RANGE_TABLE (work_area, 2);
2232 work_area->table[work_area->used++] = run_start;
2233 work_area->table[work_area->used++] = run_end;
2235 else if (run_type == two_case)
2237 EXTEND_RANGE_TABLE (work_area, 4);
2238 work_area->table[work_area->used++] = run_start;
2239 work_area->table[work_area->used++] = run_end;
2240 work_area->table[work_area->used++]
2241 = RE_TRANSLATE (eqv_table, run_start);
2242 work_area->table[work_area->used++]
2243 = RE_TRANSLATE (eqv_table, run_end);
2246 return -1;
2249 #endif /* emacs */
2251 /* Record the image of the range start..end when passed through
2252 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2253 and is not even necessarily contiguous.
2254 Normally we approximate it with the smallest contiguous range that contains
2255 all the chars we need. However, for Latin-1 we go to extra effort
2256 to do a better job.
2258 This function is not called for ASCII ranges.
2260 Returns -1 if successful, REG_ESPACE if ran out of space. */
2262 static int
2263 set_image_of_range (struct range_table_work_area *work_area,
2264 re_wchar_t start, re_wchar_t end,
2265 RE_TRANSLATE_TYPE translate)
2267 re_wchar_t cmin, cmax;
2269 #ifdef emacs
2270 /* For Latin-1 ranges, use set_image_of_range_1
2271 to get proper handling of ranges that include letters and nonletters.
2272 For a range that includes the whole of Latin-1, this is not necessary.
2273 For other character sets, we don't bother to get this right. */
2274 if (RE_TRANSLATE_P (translate) && start < 04400
2275 && !(start < 04200 && end >= 04377))
2277 int newend;
2278 int tem;
2279 newend = end;
2280 if (newend > 04377)
2281 newend = 04377;
2282 tem = set_image_of_range_1 (work_area, start, newend, translate);
2283 if (tem > 0)
2284 return tem;
2286 start = 04400;
2287 if (end < 04400)
2288 return -1;
2290 #endif
2292 EXTEND_RANGE_TABLE (work_area, 2);
2293 work_area->table[work_area->used++] = (start);
2294 work_area->table[work_area->used++] = (end);
2296 cmin = -1, cmax = -1;
2298 if (RE_TRANSLATE_P (translate))
2300 int ch;
2302 for (ch = start; ch <= end; ch++)
2304 re_wchar_t c = TRANSLATE (ch);
2305 if (! (start <= c && c <= end))
2307 if (cmin == -1)
2308 cmin = c, cmax = c;
2309 else
2311 cmin = min (cmin, c);
2312 cmax = max (cmax, c);
2317 if (cmin != -1)
2319 EXTEND_RANGE_TABLE (work_area, 2);
2320 work_area->table[work_area->used++] = (cmin);
2321 work_area->table[work_area->used++] = (cmax);
2325 return -1;
2327 #endif /* 0 */
2329 #ifndef MATCH_MAY_ALLOCATE
2331 /* If we cannot allocate large objects within re_match_2_internal,
2332 we make the fail stack and register vectors global.
2333 The fail stack, we grow to the maximum size when a regexp
2334 is compiled.
2335 The register vectors, we adjust in size each time we
2336 compile a regexp, according to the number of registers it needs. */
2338 static fail_stack_type fail_stack;
2340 /* Size with which the following vectors are currently allocated.
2341 That is so we can make them bigger as needed,
2342 but never make them smaller. */
2343 static int regs_allocated_size;
2345 static re_char ** regstart, ** regend;
2346 static re_char **best_regstart, **best_regend;
2348 /* Make the register vectors big enough for NUM_REGS registers,
2349 but don't make them smaller. */
2351 static
2352 regex_grow_registers (int num_regs)
2354 if (num_regs > regs_allocated_size)
2356 RETALLOC_IF (regstart, num_regs, re_char *);
2357 RETALLOC_IF (regend, num_regs, re_char *);
2358 RETALLOC_IF (best_regstart, num_regs, re_char *);
2359 RETALLOC_IF (best_regend, num_regs, re_char *);
2361 regs_allocated_size = num_regs;
2365 #endif /* not MATCH_MAY_ALLOCATE */
2367 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2368 regnum_t regnum);
2370 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2371 Returns one of error codes defined in `regex.h', or zero for success.
2373 If WHITESPACE_REGEXP is given (only #ifdef emacs), it is used instead of
2374 a space character in PATTERN.
2376 Assumes the `allocated' (and perhaps `buffer') and `translate'
2377 fields are set in BUFP on entry.
2379 If it succeeds, results are put in BUFP (if it returns an error, the
2380 contents of BUFP are undefined):
2381 `buffer' is the compiled pattern;
2382 `syntax' is set to SYNTAX;
2383 `used' is set to the length of the compiled pattern;
2384 `fastmap_accurate' is zero;
2385 `re_nsub' is the number of subexpressions in PATTERN;
2386 `not_bol' and `not_eol' are zero;
2388 The `fastmap' field is neither examined nor set. */
2390 /* Insert the `jump' from the end of last alternative to "here".
2391 The space for the jump has already been allocated. */
2392 #define FIXUP_ALT_JUMP() \
2393 do { \
2394 if (fixup_alt_jump) \
2395 STORE_JUMP (jump, fixup_alt_jump, b); \
2396 } while (0)
2399 /* Return, freeing storage we allocated. */
2400 #define FREE_STACK_RETURN(value) \
2401 do { \
2402 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2403 free (compile_stack.stack); \
2404 return value; \
2405 } while (0)
2407 static reg_errcode_t
2408 regex_compile (const_re_char *pattern, size_t size,
2409 #ifdef emacs
2410 # define syntax RE_SYNTAX_EMACS
2411 bool posix_backtracking,
2412 const char *whitespace_regexp,
2413 #else
2414 reg_syntax_t syntax,
2415 # define posix_backtracking (!(syntax & RE_NO_POSIX_BACKTRACKING))
2416 #endif
2417 struct re_pattern_buffer *bufp)
2419 /* We fetch characters from PATTERN here. */
2420 register re_wchar_t c, c1;
2422 /* Points to the end of the buffer, where we should append. */
2423 register unsigned char *b;
2425 /* Keeps track of unclosed groups. */
2426 compile_stack_type compile_stack;
2428 /* Points to the current (ending) position in the pattern. */
2429 #ifdef AIX
2430 /* `const' makes AIX compiler fail. */
2431 unsigned char *p = pattern;
2432 #else
2433 re_char *p = pattern;
2434 #endif
2435 re_char *pend = pattern + size;
2437 /* How to translate the characters in the pattern. */
2438 RE_TRANSLATE_TYPE translate = bufp->translate;
2440 /* Address of the count-byte of the most recently inserted `exactn'
2441 command. This makes it possible to tell if a new exact-match
2442 character can be added to that command or if the character requires
2443 a new `exactn' command. */
2444 unsigned char *pending_exact = 0;
2446 /* Address of start of the most recently finished expression.
2447 This tells, e.g., postfix * where to find the start of its
2448 operand. Reset at the beginning of groups and alternatives. */
2449 unsigned char *laststart = 0;
2451 /* Address of beginning of regexp, or inside of last group. */
2452 unsigned char *begalt;
2454 /* Place in the uncompiled pattern (i.e., the {) to
2455 which to go back if the interval is invalid. */
2456 re_char *beg_interval;
2458 /* Address of the place where a forward jump should go to the end of
2459 the containing expression. Each alternative of an `or' -- except the
2460 last -- ends with a forward jump of this sort. */
2461 unsigned char *fixup_alt_jump = 0;
2463 /* Work area for range table of charset. */
2464 struct range_table_work_area range_table_work;
2466 /* If the object matched can contain multibyte characters. */
2467 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2469 #ifdef emacs
2470 /* Nonzero if we have pushed down into a subpattern. */
2471 int in_subpattern = 0;
2473 /* These hold the values of p, pattern, and pend from the main
2474 pattern when we have pushed into a subpattern. */
2475 re_char *main_p;
2476 re_char *main_pattern;
2477 re_char *main_pend;
2478 #endif
2480 #ifdef DEBUG
2481 debug++;
2482 DEBUG_PRINT ("\nCompiling pattern: ");
2483 if (debug > 0)
2485 unsigned debug_count;
2487 for (debug_count = 0; debug_count < size; debug_count++)
2488 putchar (pattern[debug_count]);
2489 putchar ('\n');
2491 #endif /* DEBUG */
2493 /* Initialize the compile stack. */
2494 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2495 if (compile_stack.stack == NULL)
2496 return REG_ESPACE;
2498 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2499 compile_stack.avail = 0;
2501 range_table_work.table = 0;
2502 range_table_work.allocated = 0;
2504 /* Initialize the pattern buffer. */
2505 #ifndef emacs
2506 bufp->syntax = syntax;
2507 #endif
2508 bufp->fastmap_accurate = 0;
2509 bufp->not_bol = bufp->not_eol = 0;
2510 bufp->used_syntax = 0;
2512 /* Set `used' to zero, so that if we return an error, the pattern
2513 printer (for debugging) will think there's no pattern. We reset it
2514 at the end. */
2515 bufp->used = 0;
2517 /* Always count groups, whether or not bufp->no_sub is set. */
2518 bufp->re_nsub = 0;
2520 #if !defined emacs && !defined SYNTAX_TABLE
2521 /* Initialize the syntax table. */
2522 init_syntax_once ();
2523 #endif
2525 if (bufp->allocated == 0)
2527 if (bufp->buffer)
2528 { /* If zero allocated, but buffer is non-null, try to realloc
2529 enough space. This loses if buffer's address is bogus, but
2530 that is the user's responsibility. */
2531 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2533 else
2534 { /* Caller did not allocate a buffer. Do it for them. */
2535 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2537 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2539 bufp->allocated = INIT_BUF_SIZE;
2542 begalt = b = bufp->buffer;
2544 /* Loop through the uncompiled pattern until we're at the end. */
2545 while (1)
2547 if (p == pend)
2549 #ifdef emacs
2550 /* If this is the end of an included regexp,
2551 pop back to the main regexp and try again. */
2552 if (in_subpattern)
2554 in_subpattern = 0;
2555 pattern = main_pattern;
2556 p = main_p;
2557 pend = main_pend;
2558 continue;
2560 #endif
2561 /* If this is the end of the main regexp, we are done. */
2562 break;
2565 PATFETCH (c);
2567 switch (c)
2569 #ifdef emacs
2570 case ' ':
2572 re_char *p1 = p;
2574 /* If there's no special whitespace regexp, treat
2575 spaces normally. And don't try to do this recursively. */
2576 if (!whitespace_regexp || in_subpattern)
2577 goto normal_char;
2579 /* Peek past following spaces. */
2580 while (p1 != pend)
2582 if (*p1 != ' ')
2583 break;
2584 p1++;
2586 /* If the spaces are followed by a repetition op,
2587 treat them normally. */
2588 if (p1 != pend
2589 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2590 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2591 goto normal_char;
2593 /* Replace the spaces with the whitespace regexp. */
2594 in_subpattern = 1;
2595 main_p = p1;
2596 main_pend = pend;
2597 main_pattern = pattern;
2598 p = pattern = (re_char *) whitespace_regexp;
2599 pend = p + strlen (whitespace_regexp);
2600 break;
2602 #endif
2604 case '^':
2606 if ( /* If at start of pattern, it's an operator. */
2607 p == pattern + 1
2608 /* If context independent, it's an operator. */
2609 || syntax & RE_CONTEXT_INDEP_ANCHORS
2610 /* Otherwise, depends on what's come before. */
2611 || at_begline_loc_p (pattern, p, syntax))
2612 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2613 else
2614 goto normal_char;
2616 break;
2619 case '$':
2621 if ( /* If at end of pattern, it's an operator. */
2622 p == pend
2623 /* If context independent, it's an operator. */
2624 || syntax & RE_CONTEXT_INDEP_ANCHORS
2625 /* Otherwise, depends on what's next. */
2626 || at_endline_loc_p (p, pend, syntax))
2627 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2628 else
2629 goto normal_char;
2631 break;
2634 case '+':
2635 case '?':
2636 if ((syntax & RE_BK_PLUS_QM)
2637 || (syntax & RE_LIMITED_OPS))
2638 goto normal_char;
2639 handle_plus:
2640 case '*':
2641 /* If there is no previous pattern... */
2642 if (!laststart)
2644 if (syntax & RE_CONTEXT_INVALID_OPS)
2645 FREE_STACK_RETURN (REG_BADRPT);
2646 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2647 goto normal_char;
2651 /* 1 means zero (many) matches is allowed. */
2652 boolean zero_times_ok = 0, many_times_ok = 0;
2653 boolean greedy = 1;
2655 /* If there is a sequence of repetition chars, collapse it
2656 down to just one (the right one). We can't combine
2657 interval operators with these because of, e.g., `a{2}*',
2658 which should only match an even number of `a's. */
2660 for (;;)
2662 if ((syntax & RE_FRUGAL)
2663 && c == '?' && (zero_times_ok || many_times_ok))
2664 greedy = 0;
2665 else
2667 zero_times_ok |= c != '+';
2668 many_times_ok |= c != '?';
2671 if (p == pend)
2672 break;
2673 else if (*p == '*'
2674 || (!(syntax & RE_BK_PLUS_QM)
2675 && (*p == '+' || *p == '?')))
2677 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2679 if (p+1 == pend)
2680 FREE_STACK_RETURN (REG_EESCAPE);
2681 if (p[1] == '+' || p[1] == '?')
2682 PATFETCH (c); /* Gobble up the backslash. */
2683 else
2684 break;
2686 else
2687 break;
2688 /* If we get here, we found another repeat character. */
2689 PATFETCH (c);
2692 /* Star, etc. applied to an empty pattern is equivalent
2693 to an empty pattern. */
2694 if (!laststart || laststart == b)
2695 break;
2697 /* Now we know whether or not zero matches is allowed
2698 and also whether or not two or more matches is allowed. */
2699 if (greedy)
2701 if (many_times_ok)
2703 boolean simple = skip_one_char (laststart) == b;
2704 size_t startoffset = 0;
2705 re_opcode_t ofj =
2706 /* Check if the loop can match the empty string. */
2707 (simple || !analyze_first (laststart, b, NULL, 0))
2708 ? on_failure_jump : on_failure_jump_loop;
2709 assert (skip_one_char (laststart) <= b);
2711 if (!zero_times_ok && simple)
2712 { /* Since simple * loops can be made faster by using
2713 on_failure_keep_string_jump, we turn simple P+
2714 into PP* if P is simple. */
2715 unsigned char *p1, *p2;
2716 startoffset = b - laststart;
2717 GET_BUFFER_SPACE (startoffset);
2718 p1 = b; p2 = laststart;
2719 while (p2 < p1)
2720 *b++ = *p2++;
2721 zero_times_ok = 1;
2724 GET_BUFFER_SPACE (6);
2725 if (!zero_times_ok)
2726 /* A + loop. */
2727 STORE_JUMP (ofj, b, b + 6);
2728 else
2729 /* Simple * loops can use on_failure_keep_string_jump
2730 depending on what follows. But since we don't know
2731 that yet, we leave the decision up to
2732 on_failure_jump_smart. */
2733 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2734 laststart + startoffset, b + 6);
2735 b += 3;
2736 STORE_JUMP (jump, b, laststart + startoffset);
2737 b += 3;
2739 else
2741 /* A simple ? pattern. */
2742 assert (zero_times_ok);
2743 GET_BUFFER_SPACE (3);
2744 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2745 b += 3;
2748 else /* not greedy */
2749 { /* I wish the greedy and non-greedy cases could be merged. */
2751 GET_BUFFER_SPACE (7); /* We might use less. */
2752 if (many_times_ok)
2754 boolean emptyp = analyze_first (laststart, b, NULL, 0);
2756 /* The non-greedy multiple match looks like
2757 a repeat..until: we only need a conditional jump
2758 at the end of the loop. */
2759 if (emptyp) BUF_PUSH (no_op);
2760 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2761 : on_failure_jump, b, laststart);
2762 b += 3;
2763 if (zero_times_ok)
2765 /* The repeat...until naturally matches one or more.
2766 To also match zero times, we need to first jump to
2767 the end of the loop (its conditional jump). */
2768 INSERT_JUMP (jump, laststart, b);
2769 b += 3;
2772 else
2774 /* non-greedy a?? */
2775 INSERT_JUMP (jump, laststart, b + 3);
2776 b += 3;
2777 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2778 b += 3;
2782 pending_exact = 0;
2783 break;
2786 case '.':
2787 laststart = b;
2788 BUF_PUSH (anychar);
2789 break;
2792 case '[':
2794 re_char *p1;
2796 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2798 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2800 /* Ensure that we have enough space to push a charset: the
2801 opcode, the length count, and the bitset; 34 bytes in all. */
2802 GET_BUFFER_SPACE (34);
2804 laststart = b;
2806 /* We test `*p == '^' twice, instead of using an if
2807 statement, so we only need one BUF_PUSH. */
2808 BUF_PUSH (*p == '^' ? charset_not : charset);
2809 if (*p == '^')
2810 p++;
2812 /* Remember the first position in the bracket expression. */
2813 p1 = p;
2815 /* Push the number of bytes in the bitmap. */
2816 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2818 /* Clear the whole map. */
2819 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2821 /* charset_not matches newline according to a syntax bit. */
2822 if ((re_opcode_t) b[-2] == charset_not
2823 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2824 SET_LIST_BIT ('\n');
2826 /* Read in characters and ranges, setting map bits. */
2827 for (;;)
2829 boolean escaped_char = false;
2830 const unsigned char *p2 = p;
2831 re_wctype_t cc;
2832 re_wchar_t ch;
2834 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2836 /* See if we're at the beginning of a possible character
2837 class. */
2838 if (syntax & RE_CHAR_CLASSES &&
2839 (cc = re_wctype_parse(&p, pend - p)) != -1)
2841 if (cc == 0)
2842 FREE_STACK_RETURN (REG_ECTYPE);
2844 if (p == pend)
2845 FREE_STACK_RETURN (REG_EBRACK);
2847 #ifndef emacs
2848 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2849 if (re_iswctype (btowc (ch), cc))
2851 c = TRANSLATE (ch);
2852 if (c < (1 << BYTEWIDTH))
2853 SET_LIST_BIT (c);
2855 #else /* emacs */
2856 /* Most character classes in a multibyte match just set
2857 a flag. Exceptions are is_blank, is_digit, is_cntrl, and
2858 is_xdigit, since they can only match ASCII characters.
2859 We don't need to handle them for multibyte. */
2861 /* Setup the gl_state object to its buffer-defined value.
2862 This hardcodes the buffer-global syntax-table for ASCII
2863 chars, while the other chars will obey syntax-table
2864 properties. It's not ideal, but it's the way it's been
2865 done until now. */
2866 SETUP_BUFFER_SYNTAX_TABLE ();
2868 for (c = 0; c < 0x80; ++c)
2869 if (re_iswctype (c, cc))
2871 SET_LIST_BIT (c);
2872 c1 = TRANSLATE (c);
2873 if (c1 == c)
2874 continue;
2875 if (ASCII_CHAR_P (c1))
2876 SET_LIST_BIT (c1);
2877 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2878 SET_LIST_BIT (c1);
2880 SET_RANGE_TABLE_WORK_AREA_BIT
2881 (range_table_work, re_wctype_to_bit (cc));
2882 #endif /* emacs */
2883 /* In most cases the matching rule for char classes only
2884 uses the syntax table for multibyte chars, so that the
2885 content of the syntax-table is not hardcoded in the
2886 range_table. SPACE and WORD are the two exceptions. */
2887 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2888 bufp->used_syntax = 1;
2890 /* Repeat the loop. */
2891 continue;
2894 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2895 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2896 So the translation is done later in a loop. Example:
2897 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2898 PATFETCH (c);
2900 /* \ might escape characters inside [...] and [^...]. */
2901 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2903 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2905 PATFETCH (c);
2906 escaped_char = true;
2908 else
2910 /* Could be the end of the bracket expression. If it's
2911 not (i.e., when the bracket expression is `[]' so
2912 far), the ']' character bit gets set way below. */
2913 if (c == ']' && p2 != p1)
2914 break;
2917 if (p < pend && p[0] == '-' && p[1] != ']')
2920 /* Discard the `-'. */
2921 PATFETCH (c1);
2923 /* Fetch the character which ends the range. */
2924 PATFETCH (c1);
2925 #ifdef emacs
2926 if (CHAR_BYTE8_P (c1)
2927 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2928 /* Treat the range from a multibyte character to
2929 raw-byte character as empty. */
2930 c = c1 + 1;
2931 #endif /* emacs */
2933 else
2934 /* Range from C to C. */
2935 c1 = c;
2937 if (c > c1)
2939 if (syntax & RE_NO_EMPTY_RANGES)
2940 FREE_STACK_RETURN (REG_ERANGEX);
2941 /* Else, repeat the loop. */
2943 else
2945 #ifndef emacs
2946 /* Set the range into bitmap */
2947 for (; c <= c1; c++)
2949 ch = TRANSLATE (c);
2950 if (ch < (1 << BYTEWIDTH))
2951 SET_LIST_BIT (ch);
2953 #else /* emacs */
2954 if (c < 128)
2956 ch = min (127, c1);
2957 SETUP_ASCII_RANGE (range_table_work, c, ch);
2958 c = ch + 1;
2959 if (CHAR_BYTE8_P (c1))
2960 c = BYTE8_TO_CHAR (128);
2962 if (c <= c1)
2964 if (CHAR_BYTE8_P (c))
2966 c = CHAR_TO_BYTE8 (c);
2967 c1 = CHAR_TO_BYTE8 (c1);
2968 for (; c <= c1; c++)
2969 SET_LIST_BIT (c);
2971 else if (multibyte)
2973 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
2975 else
2977 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
2980 #endif /* emacs */
2984 /* Discard any (non)matching list bytes that are all 0 at the
2985 end of the map. Decrease the map-length byte too. */
2986 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2987 b[-1]--;
2988 b += b[-1];
2990 /* Build real range table from work area. */
2991 if (RANGE_TABLE_WORK_USED (range_table_work)
2992 || RANGE_TABLE_WORK_BITS (range_table_work))
2994 int i;
2995 int used = RANGE_TABLE_WORK_USED (range_table_work);
2997 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2998 bytes for flags, two for COUNT, and three bytes for
2999 each character. */
3000 GET_BUFFER_SPACE (4 + used * 3);
3002 /* Indicate the existence of range table. */
3003 laststart[1] |= 0x80;
3005 /* Store the character class flag bits into the range table.
3006 If not in emacs, these flag bits are always 0. */
3007 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3008 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3010 STORE_NUMBER_AND_INCR (b, used / 2);
3011 for (i = 0; i < used; i++)
3012 STORE_CHARACTER_AND_INCR
3013 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3016 break;
3019 case '(':
3020 if (syntax & RE_NO_BK_PARENS)
3021 goto handle_open;
3022 else
3023 goto normal_char;
3026 case ')':
3027 if (syntax & RE_NO_BK_PARENS)
3028 goto handle_close;
3029 else
3030 goto normal_char;
3033 case '\n':
3034 if (syntax & RE_NEWLINE_ALT)
3035 goto handle_alt;
3036 else
3037 goto normal_char;
3040 case '|':
3041 if (syntax & RE_NO_BK_VBAR)
3042 goto handle_alt;
3043 else
3044 goto normal_char;
3047 case '{':
3048 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3049 goto handle_interval;
3050 else
3051 goto normal_char;
3054 case '\\':
3055 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3057 /* Do not translate the character after the \, so that we can
3058 distinguish, e.g., \B from \b, even if we normally would
3059 translate, e.g., B to b. */
3060 PATFETCH (c);
3062 switch (c)
3064 case '(':
3065 if (syntax & RE_NO_BK_PARENS)
3066 goto normal_backslash;
3068 handle_open:
3070 int shy = 0;
3071 regnum_t regnum = 0;
3072 if (p+1 < pend)
3074 /* Look for a special (?...) construct */
3075 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3077 PATFETCH (c); /* Gobble up the '?'. */
3078 while (!shy)
3080 PATFETCH (c);
3081 switch (c)
3083 case ':': shy = 1; break;
3084 case '0':
3085 /* An explicitly specified regnum must start
3086 with non-0. */
3087 if (regnum == 0)
3088 FREE_STACK_RETURN (REG_BADPAT);
3089 case '1': case '2': case '3': case '4':
3090 case '5': case '6': case '7': case '8': case '9':
3091 regnum = 10*regnum + (c - '0'); break;
3092 default:
3093 /* Only (?:...) is supported right now. */
3094 FREE_STACK_RETURN (REG_BADPAT);
3100 if (!shy)
3101 regnum = ++bufp->re_nsub;
3102 else if (regnum)
3103 { /* It's actually not shy, but explicitly numbered. */
3104 shy = 0;
3105 if (regnum > bufp->re_nsub)
3106 bufp->re_nsub = regnum;
3107 else if (regnum > bufp->re_nsub
3108 /* Ideally, we'd want to check that the specified
3109 group can't have matched (i.e. all subgroups
3110 using the same regnum are in other branches of
3111 OR patterns), but we don't currently keep track
3112 of enough info to do that easily. */
3113 || group_in_compile_stack (compile_stack, regnum))
3114 FREE_STACK_RETURN (REG_BADPAT);
3116 else
3117 /* It's really shy. */
3118 regnum = - bufp->re_nsub;
3120 if (COMPILE_STACK_FULL)
3122 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3123 compile_stack_elt_t);
3124 if (compile_stack.stack == NULL) return REG_ESPACE;
3126 compile_stack.size <<= 1;
3129 /* These are the values to restore when we hit end of this
3130 group. They are all relative offsets, so that if the
3131 whole pattern moves because of realloc, they will still
3132 be valid. */
3133 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3134 COMPILE_STACK_TOP.fixup_alt_jump
3135 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3136 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3137 COMPILE_STACK_TOP.regnum = regnum;
3139 /* Do not push a start_memory for groups beyond the last one
3140 we can represent in the compiled pattern. */
3141 if (regnum <= MAX_REGNUM && regnum > 0)
3142 BUF_PUSH_2 (start_memory, regnum);
3144 compile_stack.avail++;
3146 fixup_alt_jump = 0;
3147 laststart = 0;
3148 begalt = b;
3149 /* If we've reached MAX_REGNUM groups, then this open
3150 won't actually generate any code, so we'll have to
3151 clear pending_exact explicitly. */
3152 pending_exact = 0;
3153 break;
3156 case ')':
3157 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3159 if (COMPILE_STACK_EMPTY)
3161 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3162 goto normal_backslash;
3163 else
3164 FREE_STACK_RETURN (REG_ERPAREN);
3167 handle_close:
3168 FIXUP_ALT_JUMP ();
3170 /* See similar code for backslashed left paren above. */
3171 if (COMPILE_STACK_EMPTY)
3173 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3174 goto normal_char;
3175 else
3176 FREE_STACK_RETURN (REG_ERPAREN);
3179 /* Since we just checked for an empty stack above, this
3180 ``can't happen''. */
3181 assert (compile_stack.avail != 0);
3183 /* We don't just want to restore into `regnum', because
3184 later groups should continue to be numbered higher,
3185 as in `(ab)c(de)' -- the second group is #2. */
3186 regnum_t regnum;
3188 compile_stack.avail--;
3189 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3190 fixup_alt_jump
3191 = COMPILE_STACK_TOP.fixup_alt_jump
3192 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3193 : 0;
3194 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3195 regnum = COMPILE_STACK_TOP.regnum;
3196 /* If we've reached MAX_REGNUM groups, then this open
3197 won't actually generate any code, so we'll have to
3198 clear pending_exact explicitly. */
3199 pending_exact = 0;
3201 /* We're at the end of the group, so now we know how many
3202 groups were inside this one. */
3203 if (regnum <= MAX_REGNUM && regnum > 0)
3204 BUF_PUSH_2 (stop_memory, regnum);
3206 break;
3209 case '|': /* `\|'. */
3210 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3211 goto normal_backslash;
3212 handle_alt:
3213 if (syntax & RE_LIMITED_OPS)
3214 goto normal_char;
3216 /* Insert before the previous alternative a jump which
3217 jumps to this alternative if the former fails. */
3218 GET_BUFFER_SPACE (3);
3219 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3220 pending_exact = 0;
3221 b += 3;
3223 /* The alternative before this one has a jump after it
3224 which gets executed if it gets matched. Adjust that
3225 jump so it will jump to this alternative's analogous
3226 jump (put in below, which in turn will jump to the next
3227 (if any) alternative's such jump, etc.). The last such
3228 jump jumps to the correct final destination. A picture:
3229 _____ _____
3230 | | | |
3231 | v | v
3232 a | b | c
3234 If we are at `b', then fixup_alt_jump right now points to a
3235 three-byte space after `a'. We'll put in the jump, set
3236 fixup_alt_jump to right after `b', and leave behind three
3237 bytes which we'll fill in when we get to after `c'. */
3239 FIXUP_ALT_JUMP ();
3241 /* Mark and leave space for a jump after this alternative,
3242 to be filled in later either by next alternative or
3243 when know we're at the end of a series of alternatives. */
3244 fixup_alt_jump = b;
3245 GET_BUFFER_SPACE (3);
3246 b += 3;
3248 laststart = 0;
3249 begalt = b;
3250 break;
3253 case '{':
3254 /* If \{ is a literal. */
3255 if (!(syntax & RE_INTERVALS)
3256 /* If we're at `\{' and it's not the open-interval
3257 operator. */
3258 || (syntax & RE_NO_BK_BRACES))
3259 goto normal_backslash;
3261 handle_interval:
3263 /* If got here, then the syntax allows intervals. */
3265 /* At least (most) this many matches must be made. */
3266 int lower_bound = 0, upper_bound = -1;
3268 beg_interval = p;
3270 GET_INTERVAL_COUNT (lower_bound);
3272 if (c == ',')
3273 GET_INTERVAL_COUNT (upper_bound);
3274 else
3275 /* Interval such as `{1}' => match exactly once. */
3276 upper_bound = lower_bound;
3278 if (lower_bound < 0
3279 || (0 <= upper_bound && upper_bound < lower_bound))
3280 FREE_STACK_RETURN (REG_BADBR);
3282 if (!(syntax & RE_NO_BK_BRACES))
3284 if (c != '\\')
3285 FREE_STACK_RETURN (REG_BADBR);
3286 if (p == pend)
3287 FREE_STACK_RETURN (REG_EESCAPE);
3288 PATFETCH (c);
3291 if (c != '}')
3292 FREE_STACK_RETURN (REG_BADBR);
3294 /* We just parsed a valid interval. */
3296 /* If it's invalid to have no preceding re. */
3297 if (!laststart)
3299 if (syntax & RE_CONTEXT_INVALID_OPS)
3300 FREE_STACK_RETURN (REG_BADRPT);
3301 else if (syntax & RE_CONTEXT_INDEP_OPS)
3302 laststart = b;
3303 else
3304 goto unfetch_interval;
3307 if (upper_bound == 0)
3308 /* If the upper bound is zero, just drop the sub pattern
3309 altogether. */
3310 b = laststart;
3311 else if (lower_bound == 1 && upper_bound == 1)
3312 /* Just match it once: nothing to do here. */
3315 /* Otherwise, we have a nontrivial interval. When
3316 we're all done, the pattern will look like:
3317 set_number_at <jump count> <upper bound>
3318 set_number_at <succeed_n count> <lower bound>
3319 succeed_n <after jump addr> <succeed_n count>
3320 <body of loop>
3321 jump_n <succeed_n addr> <jump count>
3322 (The upper bound and `jump_n' are omitted if
3323 `upper_bound' is 1, though.) */
3324 else
3325 { /* If the upper bound is > 1, we need to insert
3326 more at the end of the loop. */
3327 unsigned int nbytes = (upper_bound < 0 ? 3
3328 : upper_bound > 1 ? 5 : 0);
3329 unsigned int startoffset = 0;
3331 GET_BUFFER_SPACE (20); /* We might use less. */
3333 if (lower_bound == 0)
3335 /* A succeed_n that starts with 0 is really a
3336 a simple on_failure_jump_loop. */
3337 INSERT_JUMP (on_failure_jump_loop, laststart,
3338 b + 3 + nbytes);
3339 b += 3;
3341 else
3343 /* Initialize lower bound of the `succeed_n', even
3344 though it will be set during matching by its
3345 attendant `set_number_at' (inserted next),
3346 because `re_compile_fastmap' needs to know.
3347 Jump to the `jump_n' we might insert below. */
3348 INSERT_JUMP2 (succeed_n, laststart,
3349 b + 5 + nbytes,
3350 lower_bound);
3351 b += 5;
3353 /* Code to initialize the lower bound. Insert
3354 before the `succeed_n'. The `5' is the last two
3355 bytes of this `set_number_at', plus 3 bytes of
3356 the following `succeed_n'. */
3357 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3358 b += 5;
3359 startoffset += 5;
3362 if (upper_bound < 0)
3364 /* A negative upper bound stands for infinity,
3365 in which case it degenerates to a plain jump. */
3366 STORE_JUMP (jump, b, laststart + startoffset);
3367 b += 3;
3369 else if (upper_bound > 1)
3370 { /* More than one repetition is allowed, so
3371 append a backward jump to the `succeed_n'
3372 that starts this interval.
3374 When we've reached this during matching,
3375 we'll have matched the interval once, so
3376 jump back only `upper_bound - 1' times. */
3377 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3378 upper_bound - 1);
3379 b += 5;
3381 /* The location we want to set is the second
3382 parameter of the `jump_n'; that is `b-2' as
3383 an absolute address. `laststart' will be
3384 the `set_number_at' we're about to insert;
3385 `laststart+3' the number to set, the source
3386 for the relative address. But we are
3387 inserting into the middle of the pattern --
3388 so everything is getting moved up by 5.
3389 Conclusion: (b - 2) - (laststart + 3) + 5,
3390 i.e., b - laststart.
3392 We insert this at the beginning of the loop
3393 so that if we fail during matching, we'll
3394 reinitialize the bounds. */
3395 insert_op2 (set_number_at, laststart, b - laststart,
3396 upper_bound - 1, b);
3397 b += 5;
3400 pending_exact = 0;
3401 beg_interval = NULL;
3403 break;
3405 unfetch_interval:
3406 /* If an invalid interval, match the characters as literals. */
3407 assert (beg_interval);
3408 p = beg_interval;
3409 beg_interval = NULL;
3411 /* normal_char and normal_backslash need `c'. */
3412 c = '{';
3414 if (!(syntax & RE_NO_BK_BRACES))
3416 assert (p > pattern && p[-1] == '\\');
3417 goto normal_backslash;
3419 else
3420 goto normal_char;
3422 #ifdef emacs
3423 case '=':
3424 laststart = b;
3425 BUF_PUSH (at_dot);
3426 break;
3428 case 's':
3429 laststart = b;
3430 PATFETCH (c);
3431 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3432 break;
3434 case 'S':
3435 laststart = b;
3436 PATFETCH (c);
3437 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3438 break;
3440 case 'c':
3441 laststart = b;
3442 PATFETCH (c);
3443 BUF_PUSH_2 (categoryspec, c);
3444 break;
3446 case 'C':
3447 laststart = b;
3448 PATFETCH (c);
3449 BUF_PUSH_2 (notcategoryspec, c);
3450 break;
3451 #endif /* emacs */
3454 case 'w':
3455 if (syntax & RE_NO_GNU_OPS)
3456 goto normal_char;
3457 laststart = b;
3458 BUF_PUSH_2 (syntaxspec, Sword);
3459 break;
3462 case 'W':
3463 if (syntax & RE_NO_GNU_OPS)
3464 goto normal_char;
3465 laststart = b;
3466 BUF_PUSH_2 (notsyntaxspec, Sword);
3467 break;
3470 case '<':
3471 if (syntax & RE_NO_GNU_OPS)
3472 goto normal_char;
3473 laststart = b;
3474 BUF_PUSH (wordbeg);
3475 break;
3477 case '>':
3478 if (syntax & RE_NO_GNU_OPS)
3479 goto normal_char;
3480 laststart = b;
3481 BUF_PUSH (wordend);
3482 break;
3484 case '_':
3485 if (syntax & RE_NO_GNU_OPS)
3486 goto normal_char;
3487 laststart = b;
3488 PATFETCH (c);
3489 if (c == '<')
3490 BUF_PUSH (symbeg);
3491 else if (c == '>')
3492 BUF_PUSH (symend);
3493 else
3494 FREE_STACK_RETURN (REG_BADPAT);
3495 break;
3497 case 'b':
3498 if (syntax & RE_NO_GNU_OPS)
3499 goto normal_char;
3500 BUF_PUSH (wordbound);
3501 break;
3503 case 'B':
3504 if (syntax & RE_NO_GNU_OPS)
3505 goto normal_char;
3506 BUF_PUSH (notwordbound);
3507 break;
3509 case '`':
3510 if (syntax & RE_NO_GNU_OPS)
3511 goto normal_char;
3512 BUF_PUSH (begbuf);
3513 break;
3515 case '\'':
3516 if (syntax & RE_NO_GNU_OPS)
3517 goto normal_char;
3518 BUF_PUSH (endbuf);
3519 break;
3521 case '1': case '2': case '3': case '4': case '5':
3522 case '6': case '7': case '8': case '9':
3524 regnum_t reg;
3526 if (syntax & RE_NO_BK_REFS)
3527 goto normal_backslash;
3529 reg = c - '0';
3531 if (reg > bufp->re_nsub || reg < 1
3532 /* Can't back reference to a subexp before its end. */
3533 || group_in_compile_stack (compile_stack, reg))
3534 FREE_STACK_RETURN (REG_ESUBREG);
3536 laststart = b;
3537 BUF_PUSH_2 (duplicate, reg);
3539 break;
3542 case '+':
3543 case '?':
3544 if (syntax & RE_BK_PLUS_QM)
3545 goto handle_plus;
3546 else
3547 goto normal_backslash;
3549 default:
3550 normal_backslash:
3551 /* You might think it would be useful for \ to mean
3552 not to translate; but if we don't translate it
3553 it will never match anything. */
3554 goto normal_char;
3556 break;
3559 default:
3560 /* Expects the character in `c'. */
3561 normal_char:
3562 /* If no exactn currently being built. */
3563 if (!pending_exact
3565 /* If last exactn not at current position. */
3566 || pending_exact + *pending_exact + 1 != b
3568 /* We have only one byte following the exactn for the count. */
3569 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3571 /* If followed by a repetition operator. */
3572 || (p != pend && (*p == '*' || *p == '^'))
3573 || ((syntax & RE_BK_PLUS_QM)
3574 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3575 : p != pend && (*p == '+' || *p == '?'))
3576 || ((syntax & RE_INTERVALS)
3577 && ((syntax & RE_NO_BK_BRACES)
3578 ? p != pend && *p == '{'
3579 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3581 /* Start building a new exactn. */
3583 laststart = b;
3585 BUF_PUSH_2 (exactn, 0);
3586 pending_exact = b - 1;
3589 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3591 int len;
3593 if (multibyte)
3595 c = TRANSLATE (c);
3596 len = CHAR_STRING (c, b);
3597 b += len;
3599 else
3601 c1 = RE_CHAR_TO_MULTIBYTE (c);
3602 if (! CHAR_BYTE8_P (c1))
3604 re_wchar_t c2 = TRANSLATE (c1);
3606 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3607 c = c1;
3609 *b++ = c;
3610 len = 1;
3612 (*pending_exact) += len;
3615 break;
3616 } /* switch (c) */
3617 } /* while p != pend */
3620 /* Through the pattern now. */
3622 FIXUP_ALT_JUMP ();
3624 if (!COMPILE_STACK_EMPTY)
3625 FREE_STACK_RETURN (REG_EPAREN);
3627 /* If we don't want backtracking, force success
3628 the first time we reach the end of the compiled pattern. */
3629 if (!posix_backtracking)
3630 BUF_PUSH (succeed);
3632 /* We have succeeded; set the length of the buffer. */
3633 bufp->used = b - bufp->buffer;
3635 #ifdef DEBUG
3636 if (debug > 0)
3638 re_compile_fastmap (bufp);
3639 DEBUG_PRINT ("\nCompiled pattern: \n");
3640 print_compiled_pattern (bufp);
3642 debug--;
3643 #endif /* DEBUG */
3645 #ifndef MATCH_MAY_ALLOCATE
3646 /* Initialize the failure stack to the largest possible stack. This
3647 isn't necessary unless we're trying to avoid calling alloca in
3648 the search and match routines. */
3650 int num_regs = bufp->re_nsub + 1;
3652 if (fail_stack.size < emacs_re_max_failures * TYPICAL_FAILURE_SIZE)
3654 fail_stack.size = emacs_re_max_failures * TYPICAL_FAILURE_SIZE;
3655 falk_stack.stack = realloc (fail_stack.stack,
3656 fail_stack.size * sizeof *falk_stack.stack);
3659 regex_grow_registers (num_regs);
3661 #endif /* not MATCH_MAY_ALLOCATE */
3663 FREE_STACK_RETURN (REG_NOERROR);
3665 #ifdef emacs
3666 # undef syntax
3667 #else
3668 # undef posix_backtracking
3669 #endif
3670 } /* regex_compile */
3672 /* Subroutines for `regex_compile'. */
3674 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3676 static void
3677 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3679 *loc = (unsigned char) op;
3680 STORE_NUMBER (loc + 1, arg);
3684 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3686 static void
3687 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3689 *loc = (unsigned char) op;
3690 STORE_NUMBER (loc + 1, arg1);
3691 STORE_NUMBER (loc + 3, arg2);
3695 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3696 for OP followed by two-byte integer parameter ARG. */
3698 static void
3699 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3701 register unsigned char *pfrom = end;
3702 register unsigned char *pto = end + 3;
3704 while (pfrom != loc)
3705 *--pto = *--pfrom;
3707 store_op1 (op, loc, arg);
3711 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3713 static void
3714 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3716 register unsigned char *pfrom = end;
3717 register unsigned char *pto = end + 5;
3719 while (pfrom != loc)
3720 *--pto = *--pfrom;
3722 store_op2 (op, loc, arg1, arg2);
3726 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3727 after an alternative or a begin-subexpression. We assume there is at
3728 least one character before the ^. */
3730 static boolean
3731 at_begline_loc_p (const_re_char *pattern, const_re_char *p, reg_syntax_t syntax)
3733 re_char *prev = p - 2;
3734 boolean odd_backslashes;
3736 /* After a subexpression? */
3737 if (*prev == '(')
3738 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3740 /* After an alternative? */
3741 else if (*prev == '|')
3742 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3744 /* After a shy subexpression? */
3745 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3747 /* Skip over optional regnum. */
3748 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3749 --prev;
3751 if (!(prev - 2 >= pattern
3752 && prev[-1] == '?' && prev[-2] == '('))
3753 return false;
3754 prev -= 2;
3755 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3757 else
3758 return false;
3760 /* Count the number of preceding backslashes. */
3761 p = prev;
3762 while (prev - 1 >= pattern && prev[-1] == '\\')
3763 --prev;
3764 return (p - prev) & odd_backslashes;
3768 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3769 at least one character after the $, i.e., `P < PEND'. */
3771 static boolean
3772 at_endline_loc_p (const_re_char *p, const_re_char *pend, reg_syntax_t syntax)
3774 re_char *next = p;
3775 boolean next_backslash = *next == '\\';
3776 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3778 return
3779 /* Before a subexpression? */
3780 (syntax & RE_NO_BK_PARENS ? *next == ')'
3781 : next_backslash && next_next && *next_next == ')')
3782 /* Before an alternative? */
3783 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3784 : next_backslash && next_next && *next_next == '|');
3788 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3789 false if it's not. */
3791 static boolean
3792 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3794 ssize_t this_element;
3796 for (this_element = compile_stack.avail - 1;
3797 this_element >= 0;
3798 this_element--)
3799 if (compile_stack.stack[this_element].regnum == regnum)
3800 return true;
3802 return false;
3805 /* analyze_first.
3806 If fastmap is non-NULL, go through the pattern and fill fastmap
3807 with all the possible leading chars. If fastmap is NULL, don't
3808 bother filling it up (obviously) and only return whether the
3809 pattern could potentially match the empty string.
3811 Return 1 if p..pend might match the empty string.
3812 Return 0 if p..pend matches at least one char.
3813 Return -1 if fastmap was not updated accurately. */
3815 static int
3816 analyze_first (const_re_char *p, const_re_char *pend, char *fastmap,
3817 const int multibyte)
3819 int j, k;
3820 boolean not;
3822 /* If all elements for base leading-codes in fastmap is set, this
3823 flag is set true. */
3824 boolean match_any_multibyte_characters = false;
3826 assert (p);
3828 /* The loop below works as follows:
3829 - It has a working-list kept in the PATTERN_STACK and which basically
3830 starts by only containing a pointer to the first operation.
3831 - If the opcode we're looking at is a match against some set of
3832 chars, then we add those chars to the fastmap and go on to the
3833 next work element from the worklist (done via `break').
3834 - If the opcode is a control operator on the other hand, we either
3835 ignore it (if it's meaningless at this point, such as `start_memory')
3836 or execute it (if it's a jump). If the jump has several destinations
3837 (i.e. `on_failure_jump'), then we push the other destination onto the
3838 worklist.
3839 We guarantee termination by ignoring backward jumps (more or less),
3840 so that `p' is monotonically increasing. More to the point, we
3841 never set `p' (or push) anything `<= p1'. */
3843 while (p < pend)
3845 /* `p1' is used as a marker of how far back a `on_failure_jump'
3846 can go without being ignored. It is normally equal to `p'
3847 (which prevents any backward `on_failure_jump') except right
3848 after a plain `jump', to allow patterns such as:
3849 0: jump 10
3850 3..9: <body>
3851 10: on_failure_jump 3
3852 as used for the *? operator. */
3853 re_char *p1 = p;
3855 switch (*p++)
3857 case succeed:
3858 return 1;
3860 case duplicate:
3861 /* If the first character has to match a backreference, that means
3862 that the group was empty (since it already matched). Since this
3863 is the only case that interests us here, we can assume that the
3864 backreference must match the empty string. */
3865 p++;
3866 continue;
3869 /* Following are the cases which match a character. These end
3870 with `break'. */
3872 case exactn:
3873 if (fastmap)
3875 /* If multibyte is nonzero, the first byte of each
3876 character is an ASCII or a leading code. Otherwise,
3877 each byte is a character. Thus, this works in both
3878 cases. */
3879 fastmap[p[1]] = 1;
3880 if (! multibyte)
3882 /* For the case of matching this unibyte regex
3883 against multibyte, we must set a leading code of
3884 the corresponding multibyte character. */
3885 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3887 fastmap[CHAR_LEADING_CODE (c)] = 1;
3890 break;
3893 case anychar:
3894 /* We could put all the chars except for \n (and maybe \0)
3895 but we don't bother since it is generally not worth it. */
3896 if (!fastmap) break;
3897 return -1;
3900 case charset_not:
3901 if (!fastmap) break;
3903 /* Chars beyond end of bitmap are possible matches. */
3904 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3905 j < (1 << BYTEWIDTH); j++)
3906 fastmap[j] = 1;
3909 /* Fallthrough */
3910 case charset:
3911 if (!fastmap) break;
3912 not = (re_opcode_t) *(p - 1) == charset_not;
3913 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3914 j >= 0; j--)
3915 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3916 fastmap[j] = 1;
3918 #ifdef emacs
3919 if (/* Any leading code can possibly start a character
3920 which doesn't match the specified set of characters. */
3923 /* If we can match a character class, we can match any
3924 multibyte characters. */
3925 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3926 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3929 if (match_any_multibyte_characters == false)
3931 for (j = MIN_MULTIBYTE_LEADING_CODE;
3932 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3933 fastmap[j] = 1;
3934 match_any_multibyte_characters = true;
3938 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3939 && match_any_multibyte_characters == false)
3941 /* Set fastmap[I] to 1 where I is a leading code of each
3942 multibyte character in the range table. */
3943 int c, count;
3944 unsigned char lc1, lc2;
3946 /* Make P points the range table. `+ 2' is to skip flag
3947 bits for a character class. */
3948 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3950 /* Extract the number of ranges in range table into COUNT. */
3951 EXTRACT_NUMBER_AND_INCR (count, p);
3952 for (; count > 0; count--, p += 3)
3954 /* Extract the start and end of each range. */
3955 EXTRACT_CHARACTER (c, p);
3956 lc1 = CHAR_LEADING_CODE (c);
3957 p += 3;
3958 EXTRACT_CHARACTER (c, p);
3959 lc2 = CHAR_LEADING_CODE (c);
3960 for (j = lc1; j <= lc2; j++)
3961 fastmap[j] = 1;
3964 #endif
3965 break;
3967 case syntaxspec:
3968 case notsyntaxspec:
3969 if (!fastmap) break;
3970 #ifndef emacs
3971 not = (re_opcode_t)p[-1] == notsyntaxspec;
3972 k = *p++;
3973 for (j = 0; j < (1 << BYTEWIDTH); j++)
3974 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3975 fastmap[j] = 1;
3976 break;
3977 #else /* emacs */
3978 /* This match depends on text properties. These end with
3979 aborting optimizations. */
3980 return -1;
3982 case categoryspec:
3983 case notcategoryspec:
3984 if (!fastmap) break;
3985 not = (re_opcode_t)p[-1] == notcategoryspec;
3986 k = *p++;
3987 for (j = (1 << BYTEWIDTH); j >= 0; j--)
3988 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3989 fastmap[j] = 1;
3991 /* Any leading code can possibly start a character which
3992 has or doesn't has the specified category. */
3993 if (match_any_multibyte_characters == false)
3995 for (j = MIN_MULTIBYTE_LEADING_CODE;
3996 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3997 fastmap[j] = 1;
3998 match_any_multibyte_characters = true;
4000 break;
4002 /* All cases after this match the empty string. These end with
4003 `continue'. */
4005 case at_dot:
4006 #endif /* !emacs */
4007 case no_op:
4008 case begline:
4009 case endline:
4010 case begbuf:
4011 case endbuf:
4012 case wordbound:
4013 case notwordbound:
4014 case wordbeg:
4015 case wordend:
4016 case symbeg:
4017 case symend:
4018 continue;
4021 case jump:
4022 EXTRACT_NUMBER_AND_INCR (j, p);
4023 if (j < 0)
4024 /* Backward jumps can only go back to code that we've already
4025 visited. `re_compile' should make sure this is true. */
4026 break;
4027 p += j;
4028 switch (*p)
4030 case on_failure_jump:
4031 case on_failure_keep_string_jump:
4032 case on_failure_jump_loop:
4033 case on_failure_jump_nastyloop:
4034 case on_failure_jump_smart:
4035 p++;
4036 break;
4037 default:
4038 continue;
4040 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4041 to jump back to "just after here". */
4042 /* Fallthrough */
4044 case on_failure_jump:
4045 case on_failure_keep_string_jump:
4046 case on_failure_jump_nastyloop:
4047 case on_failure_jump_loop:
4048 case on_failure_jump_smart:
4049 EXTRACT_NUMBER_AND_INCR (j, p);
4050 if (p + j <= p1)
4051 ; /* Backward jump to be ignored. */
4052 else
4053 { /* We have to look down both arms.
4054 We first go down the "straight" path so as to minimize
4055 stack usage when going through alternatives. */
4056 int r = analyze_first (p, pend, fastmap, multibyte);
4057 if (r) return r;
4058 p += j;
4060 continue;
4063 case jump_n:
4064 /* This code simply does not properly handle forward jump_n. */
4065 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4066 p += 4;
4067 /* jump_n can either jump or fall through. The (backward) jump
4068 case has already been handled, so we only need to look at the
4069 fallthrough case. */
4070 continue;
4072 case succeed_n:
4073 /* If N == 0, it should be an on_failure_jump_loop instead. */
4074 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4075 p += 4;
4076 /* We only care about one iteration of the loop, so we don't
4077 need to consider the case where this behaves like an
4078 on_failure_jump. */
4079 continue;
4082 case set_number_at:
4083 p += 4;
4084 continue;
4087 case start_memory:
4088 case stop_memory:
4089 p += 1;
4090 continue;
4093 default:
4094 abort (); /* We have listed all the cases. */
4095 } /* switch *p++ */
4097 /* Getting here means we have found the possible starting
4098 characters for one path of the pattern -- and that the empty
4099 string does not match. We need not follow this path further. */
4100 return 0;
4101 } /* while p */
4103 /* We reached the end without matching anything. */
4104 return 1;
4106 } /* analyze_first */
4108 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4109 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4110 characters can start a string that matches the pattern. This fastmap
4111 is used by re_search to skip quickly over impossible starting points.
4113 Character codes above (1 << BYTEWIDTH) are not represented in the
4114 fastmap, but the leading codes are represented. Thus, the fastmap
4115 indicates which character sets could start a match.
4117 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4118 area as BUFP->fastmap.
4120 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4121 the pattern buffer.
4123 Returns 0 if we succeed, -2 if an internal error. */
4126 re_compile_fastmap (struct re_pattern_buffer *bufp)
4128 char *fastmap = bufp->fastmap;
4129 int analysis;
4131 assert (fastmap && bufp->buffer);
4133 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4134 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4136 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4137 fastmap, RE_MULTIBYTE_P (bufp));
4138 bufp->can_be_null = (analysis != 0);
4139 return 0;
4140 } /* re_compile_fastmap */
4142 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4143 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4144 this memory for recording register information. STARTS and ENDS
4145 must be allocated using the malloc library routine, and must each
4146 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4148 If NUM_REGS == 0, then subsequent matches should allocate their own
4149 register data.
4151 Unless this function is called, the first search or match using
4152 PATTERN_BUFFER will allocate its own register data, without
4153 freeing the old data. */
4155 void
4156 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4158 if (num_regs)
4160 bufp->regs_allocated = REGS_REALLOCATE;
4161 regs->num_regs = num_regs;
4162 regs->start = starts;
4163 regs->end = ends;
4165 else
4167 bufp->regs_allocated = REGS_UNALLOCATED;
4168 regs->num_regs = 0;
4169 regs->start = regs->end = 0;
4172 WEAK_ALIAS (__re_set_registers, re_set_registers)
4174 /* Searching routines. */
4176 /* Like re_search_2, below, but only one string is specified, and
4177 doesn't let you say where to stop matching. */
4179 regoff_t
4180 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4181 ssize_t startpos, ssize_t range, struct re_registers *regs)
4183 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4184 regs, size);
4186 WEAK_ALIAS (__re_search, re_search)
4188 /* Head address of virtual concatenation of string. */
4189 #define HEAD_ADDR_VSTRING(P) \
4190 (((P) >= size1 ? string2 : string1))
4192 /* Address of POS in the concatenation of virtual string. */
4193 #define POS_ADDR_VSTRING(POS) \
4194 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4196 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4197 virtual concatenation of STRING1 and STRING2, starting first at index
4198 STARTPOS, then at STARTPOS + 1, and so on.
4200 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4202 RANGE is how far to scan while trying to match. RANGE = 0 means try
4203 only at STARTPOS; in general, the last start tried is STARTPOS +
4204 RANGE.
4206 In REGS, return the indices of the virtual concatenation of STRING1
4207 and STRING2 that matched the entire BUFP->buffer and its contained
4208 subexpressions.
4210 Do not consider matching one past the index STOP in the virtual
4211 concatenation of STRING1 and STRING2.
4213 We return either the position in the strings at which the match was
4214 found, -1 if no match, or -2 if error (such as failure
4215 stack overflow). */
4217 regoff_t
4218 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4219 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4220 struct re_registers *regs, ssize_t stop)
4222 regoff_t val;
4223 re_char *string1 = (re_char *) str1;
4224 re_char *string2 = (re_char *) str2;
4225 register char *fastmap = bufp->fastmap;
4226 register RE_TRANSLATE_TYPE translate = bufp->translate;
4227 size_t total_size = size1 + size2;
4228 ssize_t endpos = startpos + range;
4229 boolean anchored_start;
4230 /* Nonzero if we are searching multibyte string. */
4231 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4233 /* Check for out-of-range STARTPOS. */
4234 if (startpos < 0 || startpos > total_size)
4235 return -1;
4237 /* Fix up RANGE if it might eventually take us outside
4238 the virtual concatenation of STRING1 and STRING2.
4239 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4240 if (endpos < 0)
4241 range = 0 - startpos;
4242 else if (endpos > total_size)
4243 range = total_size - startpos;
4245 /* If the search isn't to be a backwards one, don't waste time in a
4246 search for a pattern anchored at beginning of buffer. */
4247 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4249 if (startpos > 0)
4250 return -1;
4251 else
4252 range = 0;
4255 #ifdef emacs
4256 /* In a forward search for something that starts with \=.
4257 don't keep searching past point. */
4258 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4260 range = PT_BYTE - BEGV_BYTE - startpos;
4261 if (range < 0)
4262 return -1;
4264 #endif /* emacs */
4266 /* Update the fastmap now if not correct already. */
4267 if (fastmap && !bufp->fastmap_accurate)
4268 re_compile_fastmap (bufp);
4270 /* See whether the pattern is anchored. */
4271 anchored_start = (bufp->buffer[0] == begline);
4273 #ifdef emacs
4274 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4276 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4278 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4280 #endif
4282 /* Loop through the string, looking for a place to start matching. */
4283 for (;;)
4285 /* If the pattern is anchored,
4286 skip quickly past places we cannot match.
4287 We don't bother to treat startpos == 0 specially
4288 because that case doesn't repeat. */
4289 if (anchored_start && startpos > 0)
4291 if (! ((startpos <= size1 ? string1[startpos - 1]
4292 : string2[startpos - size1 - 1])
4293 == '\n'))
4294 goto advance;
4297 /* If a fastmap is supplied, skip quickly over characters that
4298 cannot be the start of a match. If the pattern can match the
4299 null string, however, we don't need to skip characters; we want
4300 the first null string. */
4301 if (fastmap && startpos < total_size && !bufp->can_be_null)
4303 register re_char *d;
4304 register re_wchar_t buf_ch;
4306 d = POS_ADDR_VSTRING (startpos);
4308 if (range > 0) /* Searching forwards. */
4310 ssize_t irange = range, lim = 0;
4312 if (startpos < size1 && startpos + range >= size1)
4313 lim = range - (size1 - startpos);
4315 /* Written out as an if-else to avoid testing `translate'
4316 inside the loop. */
4317 if (RE_TRANSLATE_P (translate))
4319 if (multibyte)
4320 while (range > lim)
4322 int buf_charlen;
4324 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4325 buf_ch = RE_TRANSLATE (translate, buf_ch);
4326 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4327 break;
4329 range -= buf_charlen;
4330 d += buf_charlen;
4332 else
4333 while (range > lim)
4335 register re_wchar_t ch, translated;
4337 buf_ch = *d;
4338 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4339 translated = RE_TRANSLATE (translate, ch);
4340 if (translated != ch
4341 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4342 buf_ch = ch;
4343 if (fastmap[buf_ch])
4344 break;
4345 d++;
4346 range--;
4349 else
4351 if (multibyte)
4352 while (range > lim)
4354 int buf_charlen;
4356 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4357 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4358 break;
4359 range -= buf_charlen;
4360 d += buf_charlen;
4362 else
4363 while (range > lim && !fastmap[*d])
4365 d++;
4366 range--;
4369 startpos += irange - range;
4371 else /* Searching backwards. */
4373 if (multibyte)
4375 buf_ch = STRING_CHAR (d);
4376 buf_ch = TRANSLATE (buf_ch);
4377 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4378 goto advance;
4380 else
4382 register re_wchar_t ch, translated;
4384 buf_ch = *d;
4385 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4386 translated = TRANSLATE (ch);
4387 if (translated != ch
4388 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4389 buf_ch = ch;
4390 if (! fastmap[TRANSLATE (buf_ch)])
4391 goto advance;
4396 /* If can't match the null string, and that's all we have left, fail. */
4397 if (range >= 0 && startpos == total_size && fastmap
4398 && !bufp->can_be_null)
4399 return -1;
4401 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4402 startpos, regs, stop);
4404 if (val >= 0)
4405 return startpos;
4407 if (val == -2)
4408 return -2;
4410 advance:
4411 if (!range)
4412 break;
4413 else if (range > 0)
4415 /* Update STARTPOS to the next character boundary. */
4416 if (multibyte)
4418 re_char *p = POS_ADDR_VSTRING (startpos);
4419 int len = BYTES_BY_CHAR_HEAD (*p);
4421 range -= len;
4422 if (range < 0)
4423 break;
4424 startpos += len;
4426 else
4428 range--;
4429 startpos++;
4432 else
4434 range++;
4435 startpos--;
4437 /* Update STARTPOS to the previous character boundary. */
4438 if (multibyte)
4440 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4441 re_char *p0 = p;
4442 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4444 /* Find the head of multibyte form. */
4445 PREV_CHAR_BOUNDARY (p, phead);
4446 range += p0 - 1 - p;
4447 if (range > 0)
4448 break;
4450 startpos -= p0 - 1 - p;
4454 return -1;
4455 } /* re_search_2 */
4456 WEAK_ALIAS (__re_search_2, re_search_2)
4458 /* Declarations and macros for re_match_2. */
4460 static int bcmp_translate (re_char *s1, re_char *s2,
4461 register ssize_t len,
4462 RE_TRANSLATE_TYPE translate,
4463 const int multibyte);
4465 /* This converts PTR, a pointer into one of the search strings `string1'
4466 and `string2' into an offset from the beginning of that string. */
4467 #define POINTER_TO_OFFSET(ptr) \
4468 (FIRST_STRING_P (ptr) \
4469 ? (ptr) - string1 \
4470 : (ptr) - string2 + (ptrdiff_t) size1)
4472 /* Call before fetching a character with *d. This switches over to
4473 string2 if necessary.
4474 Check re_match_2_internal for a discussion of why end_match_2 might
4475 not be within string2 (but be equal to end_match_1 instead). */
4476 #define PREFETCH() \
4477 while (d == dend) \
4479 /* End of string2 => fail. */ \
4480 if (dend == end_match_2) \
4481 goto fail; \
4482 /* End of string1 => advance to string2. */ \
4483 d = string2; \
4484 dend = end_match_2; \
4487 /* Call before fetching a char with *d if you already checked other limits.
4488 This is meant for use in lookahead operations like wordend, etc..
4489 where we might need to look at parts of the string that might be
4490 outside of the LIMITs (i.e past `stop'). */
4491 #define PREFETCH_NOLIMIT() \
4492 if (d == end1) \
4494 d = string2; \
4495 dend = end_match_2; \
4498 /* Test if at very beginning or at very end of the virtual concatenation
4499 of `string1' and `string2'. If only one string, it's `string2'. */
4500 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4501 #define AT_STRINGS_END(d) ((d) == end2)
4503 /* Disabled due to a compiler bug -- see comment at case wordbound */
4505 /* The comment at case wordbound is following one, but we don't use
4506 AT_WORD_BOUNDARY anymore to support multibyte form.
4508 The DEC Alpha C compiler 3.x generates incorrect code for the
4509 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4510 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4511 macro and introducing temporary variables works around the bug. */
4513 #if 0
4514 /* Test if D points to a character which is word-constituent. We have
4515 two special cases to check for: if past the end of string1, look at
4516 the first character in string2; and if before the beginning of
4517 string2, look at the last character in string1. */
4518 #define WORDCHAR_P(d) \
4519 (SYNTAX ((d) == end1 ? *string2 \
4520 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4521 == Sword)
4523 /* Test if the character before D and the one at D differ with respect
4524 to being word-constituent. */
4525 #define AT_WORD_BOUNDARY(d) \
4526 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4527 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4528 #endif
4530 /* Free everything we malloc. */
4531 #ifdef MATCH_MAY_ALLOCATE
4532 # define FREE_VAR(var) \
4533 do { \
4534 if (var) \
4536 REGEX_FREE (var); \
4537 var = NULL; \
4539 } while (0)
4540 # define FREE_VARIABLES() \
4541 do { \
4542 REGEX_FREE_STACK (fail_stack.stack); \
4543 FREE_VAR (regstart); \
4544 FREE_VAR (regend); \
4545 FREE_VAR (best_regstart); \
4546 FREE_VAR (best_regend); \
4547 REGEX_SAFE_FREE (); \
4548 } while (0)
4549 #else
4550 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4551 #endif /* not MATCH_MAY_ALLOCATE */
4554 /* Optimization routines. */
4556 /* If the operation is a match against one or more chars,
4557 return a pointer to the next operation, else return NULL. */
4558 static re_char *
4559 skip_one_char (const_re_char *p)
4561 switch (*p++)
4563 case anychar:
4564 break;
4566 case exactn:
4567 p += *p + 1;
4568 break;
4570 case charset_not:
4571 case charset:
4572 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4574 int mcnt;
4575 p = CHARSET_RANGE_TABLE (p - 1);
4576 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4577 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4579 else
4580 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4581 break;
4583 case syntaxspec:
4584 case notsyntaxspec:
4585 #ifdef emacs
4586 case categoryspec:
4587 case notcategoryspec:
4588 #endif /* emacs */
4589 p++;
4590 break;
4592 default:
4593 p = NULL;
4595 return p;
4599 /* Jump over non-matching operations. */
4600 static re_char *
4601 skip_noops (const_re_char *p, const_re_char *pend)
4603 int mcnt;
4604 while (p < pend)
4606 switch (*p)
4608 case start_memory:
4609 case stop_memory:
4610 p += 2; break;
4611 case no_op:
4612 p += 1; break;
4613 case jump:
4614 p += 1;
4615 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4616 p += mcnt;
4617 break;
4618 default:
4619 return p;
4622 assert (p == pend);
4623 return p;
4626 /* Test if C matches charset op. *PP points to the charset or charset_not
4627 opcode. When the function finishes, *PP will be advanced past that opcode.
4628 C is character to test (possibly after translations) and CORIG is original
4629 character (i.e. without any translations). UNIBYTE denotes whether c is
4630 unibyte or multibyte character. */
4631 static bool
4632 execute_charset (const_re_char **pp, unsigned c, unsigned corig, bool unibyte)
4634 re_char *p = *pp, *rtp = NULL;
4635 bool not = (re_opcode_t) *p == charset_not;
4637 if (CHARSET_RANGE_TABLE_EXISTS_P (p))
4639 int count;
4640 rtp = CHARSET_RANGE_TABLE (p);
4641 EXTRACT_NUMBER_AND_INCR (count, rtp);
4642 *pp = CHARSET_RANGE_TABLE_END ((rtp), (count));
4644 else
4645 *pp += 2 + CHARSET_BITMAP_SIZE (p);
4647 if (unibyte && c < (1 << BYTEWIDTH))
4648 { /* Lookup bitmap. */
4649 /* Cast to `unsigned' instead of `unsigned char' in
4650 case the bit list is a full 32 bytes long. */
4651 if (c < (unsigned) (CHARSET_BITMAP_SIZE (p) * BYTEWIDTH)
4652 && p[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4653 return !not;
4655 #ifdef emacs
4656 else if (rtp)
4658 int class_bits = CHARSET_RANGE_TABLE_BITS (p);
4659 re_wchar_t range_start, range_end;
4661 /* Sort tests by the most commonly used classes with some adjustment to which
4662 tests are easiest to perform. Take a look at comment in re_wctype_parse
4663 for table with frequencies of character class names. */
4665 if ((class_bits & BIT_MULTIBYTE) ||
4666 (class_bits & BIT_ALNUM && ISALNUM (c)) ||
4667 (class_bits & BIT_ALPHA && ISALPHA (c)) ||
4668 (class_bits & BIT_SPACE && ISSPACE (c)) ||
4669 (class_bits & BIT_BLANK && ISBLANK (c)) ||
4670 (class_bits & BIT_WORD && ISWORD (c)) ||
4671 ((class_bits & BIT_UPPER) &&
4672 (ISUPPER (c) || (corig != c &&
4673 c == downcase (corig) && ISLOWER (c)))) ||
4674 ((class_bits & BIT_LOWER) &&
4675 (ISLOWER (c) || (corig != c &&
4676 c == upcase (corig) && ISUPPER(c)))) ||
4677 (class_bits & BIT_PUNCT && ISPUNCT (c)) ||
4678 (class_bits & BIT_GRAPH && ISGRAPH (c)) ||
4679 (class_bits & BIT_PRINT && ISPRINT (c)))
4680 return !not;
4682 for (p = *pp; rtp < p; rtp += 2 * 3)
4684 EXTRACT_CHARACTER (range_start, rtp);
4685 EXTRACT_CHARACTER (range_end, rtp + 3);
4686 if (range_start <= c && c <= range_end)
4687 return !not;
4690 #endif /* emacs */
4691 return not;
4694 /* Non-zero if "p1 matches something" implies "p2 fails". */
4695 static int
4696 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4697 const_re_char *p2)
4699 re_opcode_t op2;
4700 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4701 unsigned char *pend = bufp->buffer + bufp->used;
4703 assert (p1 >= bufp->buffer && p1 < pend
4704 && p2 >= bufp->buffer && p2 <= pend);
4706 /* Skip over open/close-group commands.
4707 If what follows this loop is a ...+ construct,
4708 look at what begins its body, since we will have to
4709 match at least one of that. */
4710 p2 = skip_noops (p2, pend);
4711 /* The same skip can be done for p1, except that this function
4712 is only used in the case where p1 is a simple match operator. */
4713 /* p1 = skip_noops (p1, pend); */
4715 assert (p1 >= bufp->buffer && p1 < pend
4716 && p2 >= bufp->buffer && p2 <= pend);
4718 op2 = p2 == pend ? succeed : *p2;
4720 switch (op2)
4722 case succeed:
4723 case endbuf:
4724 /* If we're at the end of the pattern, we can change. */
4725 if (skip_one_char (p1))
4727 DEBUG_PRINT (" End of pattern: fast loop.\n");
4728 return 1;
4730 break;
4732 case endline:
4733 case exactn:
4735 register re_wchar_t c
4736 = (re_opcode_t) *p2 == endline ? '\n'
4737 : RE_STRING_CHAR (p2 + 2, multibyte);
4739 if ((re_opcode_t) *p1 == exactn)
4741 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4743 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4744 return 1;
4748 else if ((re_opcode_t) *p1 == charset
4749 || (re_opcode_t) *p1 == charset_not)
4751 if (!execute_charset (&p1, c, c, !multibyte || IS_REAL_ASCII (c)))
4753 DEBUG_PRINT (" No match => fast loop.\n");
4754 return 1;
4757 else if ((re_opcode_t) *p1 == anychar
4758 && c == '\n')
4760 DEBUG_PRINT (" . != \\n => fast loop.\n");
4761 return 1;
4764 break;
4766 case charset:
4768 if ((re_opcode_t) *p1 == exactn)
4769 /* Reuse the code above. */
4770 return mutually_exclusive_p (bufp, p2, p1);
4772 /* It is hard to list up all the character in charset
4773 P2 if it includes multibyte character. Give up in
4774 such case. */
4775 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4777 /* Now, we are sure that P2 has no range table.
4778 So, for the size of bitmap in P2, `p2[1]' is
4779 enough. But P1 may have range table, so the
4780 size of bitmap table of P1 is extracted by
4781 using macro `CHARSET_BITMAP_SIZE'.
4783 In a multibyte case, we know that all the character
4784 listed in P2 is ASCII. In a unibyte case, P1 has only a
4785 bitmap table. So, in both cases, it is enough to test
4786 only the bitmap table of P1. */
4788 if ((re_opcode_t) *p1 == charset)
4790 int idx;
4791 /* We win if the charset inside the loop
4792 has no overlap with the one after the loop. */
4793 for (idx = 0;
4794 (idx < (int) p2[1]
4795 && idx < CHARSET_BITMAP_SIZE (p1));
4796 idx++)
4797 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4798 break;
4800 if (idx == p2[1]
4801 || idx == CHARSET_BITMAP_SIZE (p1))
4803 DEBUG_PRINT (" No match => fast loop.\n");
4804 return 1;
4807 else if ((re_opcode_t) *p1 == charset_not)
4809 int idx;
4810 /* We win if the charset_not inside the loop lists
4811 every character listed in the charset after. */
4812 for (idx = 0; idx < (int) p2[1]; idx++)
4813 if (! (p2[2 + idx] == 0
4814 || (idx < CHARSET_BITMAP_SIZE (p1)
4815 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4816 break;
4818 if (idx == p2[1])
4820 DEBUG_PRINT (" No match => fast loop.\n");
4821 return 1;
4826 break;
4828 case charset_not:
4829 switch (*p1)
4831 case exactn:
4832 case charset:
4833 /* Reuse the code above. */
4834 return mutually_exclusive_p (bufp, p2, p1);
4835 case charset_not:
4836 /* When we have two charset_not, it's very unlikely that
4837 they don't overlap. The union of the two sets of excluded
4838 chars should cover all possible chars, which, as a matter of
4839 fact, is virtually impossible in multibyte buffers. */
4840 break;
4842 break;
4844 case wordend:
4845 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4846 case symend:
4847 return ((re_opcode_t) *p1 == syntaxspec
4848 && (p1[1] == Ssymbol || p1[1] == Sword));
4849 case notsyntaxspec:
4850 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4852 case wordbeg:
4853 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4854 case symbeg:
4855 return ((re_opcode_t) *p1 == notsyntaxspec
4856 && (p1[1] == Ssymbol || p1[1] == Sword));
4857 case syntaxspec:
4858 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4860 case wordbound:
4861 return (((re_opcode_t) *p1 == notsyntaxspec
4862 || (re_opcode_t) *p1 == syntaxspec)
4863 && p1[1] == Sword);
4865 #ifdef emacs
4866 case categoryspec:
4867 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4868 case notcategoryspec:
4869 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4870 #endif /* emacs */
4872 default:
4876 /* Safe default. */
4877 return 0;
4881 /* Matching routines. */
4883 #ifndef emacs /* Emacs never uses this. */
4884 /* re_match is like re_match_2 except it takes only a single string. */
4886 regoff_t
4887 re_match (struct re_pattern_buffer *bufp, const char *string,
4888 size_t size, ssize_t pos, struct re_registers *regs)
4890 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char *) string,
4891 size, pos, regs, size);
4892 return result;
4894 WEAK_ALIAS (__re_match, re_match)
4895 #endif /* not emacs */
4897 /* re_match_2 matches the compiled pattern in BUFP against the
4898 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4899 and SIZE2, respectively). We start matching at POS, and stop
4900 matching at STOP.
4902 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4903 store offsets for the substring each group matched in REGS. See the
4904 documentation for exactly how many groups we fill.
4906 We return -1 if no match, -2 if an internal error (such as the
4907 failure stack overflowing). Otherwise, we return the length of the
4908 matched substring. */
4910 regoff_t
4911 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4912 size_t size1, const char *string2, size_t size2, ssize_t pos,
4913 struct re_registers *regs, ssize_t stop)
4915 regoff_t result;
4917 #ifdef emacs
4918 ssize_t charpos;
4919 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4920 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4921 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4922 #endif
4924 result = re_match_2_internal (bufp, (re_char *) string1, size1,
4925 (re_char *) string2, size2,
4926 pos, regs, stop);
4927 return result;
4929 WEAK_ALIAS (__re_match_2, re_match_2)
4932 /* This is a separate function so that we can force an alloca cleanup
4933 afterwards. */
4934 static regoff_t
4935 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4936 size_t size1, const_re_char *string2, size_t size2,
4937 ssize_t pos, struct re_registers *regs, ssize_t stop)
4939 /* General temporaries. */
4940 int mcnt;
4941 size_t reg;
4943 /* Just past the end of the corresponding string. */
4944 re_char *end1, *end2;
4946 /* Pointers into string1 and string2, just past the last characters in
4947 each to consider matching. */
4948 re_char *end_match_1, *end_match_2;
4950 /* Where we are in the data, and the end of the current string. */
4951 re_char *d, *dend;
4953 /* Used sometimes to remember where we were before starting matching
4954 an operator so that we can go back in case of failure. This "atomic"
4955 behavior of matching opcodes is indispensable to the correctness
4956 of the on_failure_keep_string_jump optimization. */
4957 re_char *dfail;
4959 /* Where we are in the pattern, and the end of the pattern. */
4960 re_char *p = bufp->buffer;
4961 re_char *pend = p + bufp->used;
4963 /* We use this to map every character in the string. */
4964 RE_TRANSLATE_TYPE translate = bufp->translate;
4966 /* Nonzero if BUFP is setup from a multibyte regex. */
4967 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4969 /* Nonzero if STRING1/STRING2 are multibyte. */
4970 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4972 /* Failure point stack. Each place that can handle a failure further
4973 down the line pushes a failure point on this stack. It consists of
4974 regstart, and regend for all registers corresponding to
4975 the subexpressions we're currently inside, plus the number of such
4976 registers, and, finally, two char *'s. The first char * is where
4977 to resume scanning the pattern; the second one is where to resume
4978 scanning the strings. */
4979 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4980 fail_stack_type fail_stack;
4981 #endif
4982 #ifdef DEBUG_COMPILES_ARGUMENTS
4983 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4984 #endif
4986 #if defined REL_ALLOC && defined REGEX_MALLOC
4987 /* This holds the pointer to the failure stack, when
4988 it is allocated relocatably. */
4989 fail_stack_elt_t *failure_stack_ptr;
4990 #endif
4992 /* We fill all the registers internally, independent of what we
4993 return, for use in backreferences. The number here includes
4994 an element for register zero. */
4995 size_t num_regs = bufp->re_nsub + 1;
4997 /* Information on the contents of registers. These are pointers into
4998 the input strings; they record just what was matched (on this
4999 attempt) by a subexpression part of the pattern, that is, the
5000 regnum-th regstart pointer points to where in the pattern we began
5001 matching and the regnum-th regend points to right after where we
5002 stopped matching the regnum-th subexpression. (The zeroth register
5003 keeps track of what the whole pattern matches.) */
5004 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5005 re_char **regstart, **regend;
5006 #endif
5008 /* The following record the register info as found in the above
5009 variables when we find a match better than any we've seen before.
5010 This happens as we backtrack through the failure points, which in
5011 turn happens only if we have not yet matched the entire string. */
5012 unsigned best_regs_set = false;
5013 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5014 re_char **best_regstart, **best_regend;
5015 #endif
5017 /* Logically, this is `best_regend[0]'. But we don't want to have to
5018 allocate space for that if we're not allocating space for anything
5019 else (see below). Also, we never need info about register 0 for
5020 any of the other register vectors, and it seems rather a kludge to
5021 treat `best_regend' differently than the rest. So we keep track of
5022 the end of the best match so far in a separate variable. We
5023 initialize this to NULL so that when we backtrack the first time
5024 and need to test it, it's not garbage. */
5025 re_char *match_end = NULL;
5027 #ifdef DEBUG_COMPILES_ARGUMENTS
5028 /* Counts the total number of registers pushed. */
5029 unsigned num_regs_pushed = 0;
5030 #endif
5032 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5034 REGEX_USE_SAFE_ALLOCA;
5036 INIT_FAIL_STACK ();
5038 #ifdef MATCH_MAY_ALLOCATE
5039 /* Do not bother to initialize all the register variables if there are
5040 no groups in the pattern, as it takes a fair amount of time. If
5041 there are groups, we include space for register 0 (the whole
5042 pattern), even though we never use it, since it simplifies the
5043 array indexing. We should fix this. */
5044 if (bufp->re_nsub)
5046 regstart = REGEX_TALLOC (num_regs, re_char *);
5047 regend = REGEX_TALLOC (num_regs, re_char *);
5048 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5049 best_regend = REGEX_TALLOC (num_regs, re_char *);
5051 if (!(regstart && regend && best_regstart && best_regend))
5053 FREE_VARIABLES ();
5054 return -2;
5057 else
5059 /* We must initialize all our variables to NULL, so that
5060 `FREE_VARIABLES' doesn't try to free them. */
5061 regstart = regend = best_regstart = best_regend = NULL;
5063 #endif /* MATCH_MAY_ALLOCATE */
5065 /* The starting position is bogus. */
5066 if (pos < 0 || pos > size1 + size2)
5068 FREE_VARIABLES ();
5069 return -1;
5072 /* Initialize subexpression text positions to -1 to mark ones that no
5073 start_memory/stop_memory has been seen for. Also initialize the
5074 register information struct. */
5075 for (reg = 1; reg < num_regs; reg++)
5076 regstart[reg] = regend[reg] = NULL;
5078 /* We move `string1' into `string2' if the latter's empty -- but not if
5079 `string1' is null. */
5080 if (size2 == 0 && string1 != NULL)
5082 string2 = string1;
5083 size2 = size1;
5084 string1 = 0;
5085 size1 = 0;
5087 end1 = string1 + size1;
5088 end2 = string2 + size2;
5090 /* `p' scans through the pattern as `d' scans through the data.
5091 `dend' is the end of the input string that `d' points within. `d'
5092 is advanced into the following input string whenever necessary, but
5093 this happens before fetching; therefore, at the beginning of the
5094 loop, `d' can be pointing at the end of a string, but it cannot
5095 equal `string2'. */
5096 if (pos >= size1)
5098 /* Only match within string2. */
5099 d = string2 + pos - size1;
5100 dend = end_match_2 = string2 + stop - size1;
5101 end_match_1 = end1; /* Just to give it a value. */
5103 else
5105 if (stop < size1)
5107 /* Only match within string1. */
5108 end_match_1 = string1 + stop;
5109 /* BEWARE!
5110 When we reach end_match_1, PREFETCH normally switches to string2.
5111 But in the present case, this means that just doing a PREFETCH
5112 makes us jump from `stop' to `gap' within the string.
5113 What we really want here is for the search to stop as
5114 soon as we hit end_match_1. That's why we set end_match_2
5115 to end_match_1 (since PREFETCH fails as soon as we hit
5116 end_match_2). */
5117 end_match_2 = end_match_1;
5119 else
5120 { /* It's important to use this code when stop == size so that
5121 moving `d' from end1 to string2 will not prevent the d == dend
5122 check from catching the end of string. */
5123 end_match_1 = end1;
5124 end_match_2 = string2 + stop - size1;
5126 d = string1 + pos;
5127 dend = end_match_1;
5130 DEBUG_PRINT ("The compiled pattern is: ");
5131 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5132 DEBUG_PRINT ("The string to match is: \"");
5133 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5134 DEBUG_PRINT ("\"\n");
5136 /* This loops over pattern commands. It exits by returning from the
5137 function if the match is complete, or it drops through if the match
5138 fails at this starting point in the input data. */
5139 for (;;)
5141 DEBUG_PRINT ("\n%p: ", p);
5143 if (p == pend)
5145 /* End of pattern means we might have succeeded. */
5146 DEBUG_PRINT ("end of pattern ... ");
5148 /* If we haven't matched the entire string, and we want the
5149 longest match, try backtracking. */
5150 if (d != end_match_2)
5152 /* True if this match is the best seen so far. */
5153 bool best_match_p;
5156 /* True if this match ends in the same string (string1
5157 or string2) as the best previous match. */
5158 bool same_str_p = (FIRST_STRING_P (match_end)
5159 == FIRST_STRING_P (d));
5161 /* AIX compiler got confused when this was combined
5162 with the previous declaration. */
5163 if (same_str_p)
5164 best_match_p = d > match_end;
5165 else
5166 best_match_p = !FIRST_STRING_P (d);
5169 DEBUG_PRINT ("backtracking.\n");
5171 if (!FAIL_STACK_EMPTY ())
5172 { /* More failure points to try. */
5174 /* If exceeds best match so far, save it. */
5175 if (!best_regs_set || best_match_p)
5177 best_regs_set = true;
5178 match_end = d;
5180 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5182 for (reg = 1; reg < num_regs; reg++)
5184 best_regstart[reg] = regstart[reg];
5185 best_regend[reg] = regend[reg];
5188 goto fail;
5191 /* If no failure points, don't restore garbage. And if
5192 last match is real best match, don't restore second
5193 best one. */
5194 else if (best_regs_set && !best_match_p)
5196 restore_best_regs:
5197 /* Restore best match. It may happen that `dend ==
5198 end_match_1' while the restored d is in string2.
5199 For example, the pattern `x.*y.*z' against the
5200 strings `x-' and `y-z-', if the two strings are
5201 not consecutive in memory. */
5202 DEBUG_PRINT ("Restoring best registers.\n");
5204 d = match_end;
5205 dend = ((d >= string1 && d <= end1)
5206 ? end_match_1 : end_match_2);
5208 for (reg = 1; reg < num_regs; reg++)
5210 regstart[reg] = best_regstart[reg];
5211 regend[reg] = best_regend[reg];
5214 } /* d != end_match_2 */
5216 succeed_label:
5217 DEBUG_PRINT ("Accepting match.\n");
5219 /* If caller wants register contents data back, do it. */
5220 if (regs && !bufp->no_sub)
5222 /* Have the register data arrays been allocated? */
5223 if (bufp->regs_allocated == REGS_UNALLOCATED)
5224 { /* No. So allocate them with malloc. We need one
5225 extra element beyond `num_regs' for the `-1' marker
5226 GNU code uses. */
5227 regs->num_regs = max (RE_NREGS, num_regs + 1);
5228 regs->start = TALLOC (regs->num_regs, regoff_t);
5229 regs->end = TALLOC (regs->num_regs, regoff_t);
5230 if (regs->start == NULL || regs->end == NULL)
5232 FREE_VARIABLES ();
5233 return -2;
5235 bufp->regs_allocated = REGS_REALLOCATE;
5237 else if (bufp->regs_allocated == REGS_REALLOCATE)
5238 { /* Yes. If we need more elements than were already
5239 allocated, reallocate them. If we need fewer, just
5240 leave it alone. */
5241 if (regs->num_regs < num_regs + 1)
5243 regs->num_regs = num_regs + 1;
5244 RETALLOC (regs->start, regs->num_regs, regoff_t);
5245 RETALLOC (regs->end, regs->num_regs, regoff_t);
5246 if (regs->start == NULL || regs->end == NULL)
5248 FREE_VARIABLES ();
5249 return -2;
5253 else
5255 /* These braces fend off a "empty body in an else-statement"
5256 warning under GCC when assert expands to nothing. */
5257 assert (bufp->regs_allocated == REGS_FIXED);
5260 /* Convert the pointer data in `regstart' and `regend' to
5261 indices. Register zero has to be set differently,
5262 since we haven't kept track of any info for it. */
5263 if (regs->num_regs > 0)
5265 regs->start[0] = pos;
5266 regs->end[0] = POINTER_TO_OFFSET (d);
5269 /* Go through the first `min (num_regs, regs->num_regs)'
5270 registers, since that is all we initialized. */
5271 for (reg = 1; reg < min (num_regs, regs->num_regs); reg++)
5273 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5274 regs->start[reg] = regs->end[reg] = -1;
5275 else
5277 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5278 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5282 /* If the regs structure we return has more elements than
5283 were in the pattern, set the extra elements to -1. If
5284 we (re)allocated the registers, this is the case,
5285 because we always allocate enough to have at least one
5286 -1 at the end. */
5287 for (reg = num_regs; reg < regs->num_regs; reg++)
5288 regs->start[reg] = regs->end[reg] = -1;
5289 } /* regs && !bufp->no_sub */
5291 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5292 nfailure_points_pushed, nfailure_points_popped,
5293 nfailure_points_pushed - nfailure_points_popped);
5294 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5296 ptrdiff_t dcnt = POINTER_TO_OFFSET (d) - pos;
5298 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5300 FREE_VARIABLES ();
5301 return dcnt;
5304 /* Otherwise match next pattern command. */
5305 switch (*p++)
5307 /* Ignore these. Used to ignore the n of succeed_n's which
5308 currently have n == 0. */
5309 case no_op:
5310 DEBUG_PRINT ("EXECUTING no_op.\n");
5311 break;
5313 case succeed:
5314 DEBUG_PRINT ("EXECUTING succeed.\n");
5315 goto succeed_label;
5317 /* Match the next n pattern characters exactly. The following
5318 byte in the pattern defines n, and the n bytes after that
5319 are the characters to match. */
5320 case exactn:
5321 mcnt = *p++;
5322 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5324 /* Remember the start point to rollback upon failure. */
5325 dfail = d;
5327 #ifndef emacs
5328 /* This is written out as an if-else so we don't waste time
5329 testing `translate' inside the loop. */
5330 if (RE_TRANSLATE_P (translate))
5333 PREFETCH ();
5334 if (RE_TRANSLATE (translate, *d) != *p++)
5336 d = dfail;
5337 goto fail;
5339 d++;
5341 while (--mcnt);
5342 else
5345 PREFETCH ();
5346 if (*d++ != *p++)
5348 d = dfail;
5349 goto fail;
5352 while (--mcnt);
5353 #else /* emacs */
5354 /* The cost of testing `translate' is comparatively small. */
5355 if (target_multibyte)
5358 int pat_charlen, buf_charlen;
5359 int pat_ch, buf_ch;
5361 PREFETCH ();
5362 if (multibyte)
5363 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5364 else
5366 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5367 pat_charlen = 1;
5369 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5371 if (TRANSLATE (buf_ch) != pat_ch)
5373 d = dfail;
5374 goto fail;
5377 p += pat_charlen;
5378 d += buf_charlen;
5379 mcnt -= pat_charlen;
5381 while (mcnt > 0);
5382 else
5385 int pat_charlen;
5386 int pat_ch, buf_ch;
5388 PREFETCH ();
5389 if (multibyte)
5391 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5392 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5394 else
5396 pat_ch = *p;
5397 pat_charlen = 1;
5399 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5400 if (! CHAR_BYTE8_P (buf_ch))
5402 buf_ch = TRANSLATE (buf_ch);
5403 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5404 if (buf_ch < 0)
5405 buf_ch = *d;
5407 else
5408 buf_ch = *d;
5409 if (buf_ch != pat_ch)
5411 d = dfail;
5412 goto fail;
5414 p += pat_charlen;
5415 d++;
5417 while (--mcnt);
5418 #endif
5419 break;
5422 /* Match any character except possibly a newline or a null. */
5423 case anychar:
5425 int buf_charlen;
5426 re_wchar_t buf_ch;
5427 reg_syntax_t syntax;
5429 DEBUG_PRINT ("EXECUTING anychar.\n");
5431 PREFETCH ();
5432 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5433 target_multibyte);
5434 buf_ch = TRANSLATE (buf_ch);
5436 #ifdef emacs
5437 syntax = RE_SYNTAX_EMACS;
5438 #else
5439 syntax = bufp->syntax;
5440 #endif
5442 if ((!(syntax & RE_DOT_NEWLINE) && buf_ch == '\n')
5443 || ((syntax & RE_DOT_NOT_NULL) && buf_ch == '\000'))
5444 goto fail;
5446 DEBUG_PRINT (" Matched \"%d\".\n", *d);
5447 d += buf_charlen;
5449 break;
5452 case charset:
5453 case charset_not:
5455 register unsigned int c, corig;
5456 int len;
5458 /* Whether matching against a unibyte character. */
5459 boolean unibyte_char = false;
5461 DEBUG_PRINT ("EXECUTING charset%s.\n",
5462 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
5464 PREFETCH ();
5465 corig = c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5466 if (target_multibyte)
5468 int c1;
5470 c = TRANSLATE (c);
5471 c1 = RE_CHAR_TO_UNIBYTE (c);
5472 if (c1 >= 0)
5474 unibyte_char = true;
5475 c = c1;
5478 else
5480 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5482 if (! CHAR_BYTE8_P (c1))
5484 c1 = TRANSLATE (c1);
5485 c1 = RE_CHAR_TO_UNIBYTE (c1);
5486 if (c1 >= 0)
5488 unibyte_char = true;
5489 c = c1;
5492 else
5493 unibyte_char = true;
5496 p -= 1;
5497 if (!execute_charset (&p, c, corig, unibyte_char))
5498 goto fail;
5500 d += len;
5502 break;
5505 /* The beginning of a group is represented by start_memory.
5506 The argument is the register number. The text
5507 matched within the group is recorded (in the internal
5508 registers data structure) under the register number. */
5509 case start_memory:
5510 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5512 /* In case we need to undo this operation (via backtracking). */
5513 PUSH_FAILURE_REG (*p);
5515 regstart[*p] = d;
5516 regend[*p] = NULL; /* probably unnecessary. -sm */
5517 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5519 /* Move past the register number and inner group count. */
5520 p += 1;
5521 break;
5524 /* The stop_memory opcode represents the end of a group. Its
5525 argument is the same as start_memory's: the register number. */
5526 case stop_memory:
5527 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5529 assert (!REG_UNSET (regstart[*p]));
5530 /* Strictly speaking, there should be code such as:
5532 assert (REG_UNSET (regend[*p]));
5533 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5535 But the only info to be pushed is regend[*p] and it is known to
5536 be UNSET, so there really isn't anything to push.
5537 Not pushing anything, on the other hand deprives us from the
5538 guarantee that regend[*p] is UNSET since undoing this operation
5539 will not reset its value properly. This is not important since
5540 the value will only be read on the next start_memory or at
5541 the very end and both events can only happen if this stop_memory
5542 is *not* undone. */
5544 regend[*p] = d;
5545 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5547 /* Move past the register number and the inner group count. */
5548 p += 1;
5549 break;
5552 /* \<digit> has been turned into a `duplicate' command which is
5553 followed by the numeric value of <digit> as the register number. */
5554 case duplicate:
5556 register re_char *d2, *dend2;
5557 int regno = *p++; /* Get which register to match against. */
5558 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5560 /* Can't back reference a group which we've never matched. */
5561 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5562 goto fail;
5564 /* Where in input to try to start matching. */
5565 d2 = regstart[regno];
5567 /* Remember the start point to rollback upon failure. */
5568 dfail = d;
5570 /* Where to stop matching; if both the place to start and
5571 the place to stop matching are in the same string, then
5572 set to the place to stop, otherwise, for now have to use
5573 the end of the first string. */
5575 dend2 = ((FIRST_STRING_P (regstart[regno])
5576 == FIRST_STRING_P (regend[regno]))
5577 ? regend[regno] : end_match_1);
5578 for (;;)
5580 ptrdiff_t dcnt;
5582 /* If necessary, advance to next segment in register
5583 contents. */
5584 while (d2 == dend2)
5586 if (dend2 == end_match_2) break;
5587 if (dend2 == regend[regno]) break;
5589 /* End of string1 => advance to string2. */
5590 d2 = string2;
5591 dend2 = regend[regno];
5593 /* At end of register contents => success */
5594 if (d2 == dend2) break;
5596 /* If necessary, advance to next segment in data. */
5597 PREFETCH ();
5599 /* How many characters left in this segment to match. */
5600 dcnt = dend - d;
5602 /* Want how many consecutive characters we can match in
5603 one shot, so, if necessary, adjust the count. */
5604 if (dcnt > dend2 - d2)
5605 dcnt = dend2 - d2;
5607 /* Compare that many; failure if mismatch, else move
5608 past them. */
5609 if (RE_TRANSLATE_P (translate)
5610 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5611 : memcmp (d, d2, dcnt))
5613 d = dfail;
5614 goto fail;
5616 d += dcnt, d2 += dcnt;
5619 break;
5622 /* begline matches the empty string at the beginning of the string
5623 (unless `not_bol' is set in `bufp'), and after newlines. */
5624 case begline:
5625 DEBUG_PRINT ("EXECUTING begline.\n");
5627 if (AT_STRINGS_BEG (d))
5629 if (!bufp->not_bol) break;
5631 else
5633 unsigned c;
5634 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5635 if (c == '\n')
5636 break;
5638 /* In all other cases, we fail. */
5639 goto fail;
5642 /* endline is the dual of begline. */
5643 case endline:
5644 DEBUG_PRINT ("EXECUTING endline.\n");
5646 if (AT_STRINGS_END (d))
5648 if (!bufp->not_eol) break;
5650 else
5652 PREFETCH_NOLIMIT ();
5653 if (*d == '\n')
5654 break;
5656 goto fail;
5659 /* Match at the very beginning of the data. */
5660 case begbuf:
5661 DEBUG_PRINT ("EXECUTING begbuf.\n");
5662 if (AT_STRINGS_BEG (d))
5663 break;
5664 goto fail;
5667 /* Match at the very end of the data. */
5668 case endbuf:
5669 DEBUG_PRINT ("EXECUTING endbuf.\n");
5670 if (AT_STRINGS_END (d))
5671 break;
5672 goto fail;
5675 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5676 pushes NULL as the value for the string on the stack. Then
5677 `POP_FAILURE_POINT' will keep the current value for the
5678 string, instead of restoring it. To see why, consider
5679 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5680 then the . fails against the \n. But the next thing we want
5681 to do is match the \n against the \n; if we restored the
5682 string value, we would be back at the foo.
5684 Because this is used only in specific cases, we don't need to
5685 check all the things that `on_failure_jump' does, to make
5686 sure the right things get saved on the stack. Hence we don't
5687 share its code. The only reason to push anything on the
5688 stack at all is that otherwise we would have to change
5689 `anychar's code to do something besides goto fail in this
5690 case; that seems worse than this. */
5691 case on_failure_keep_string_jump:
5692 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5693 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5694 mcnt, p + mcnt);
5696 PUSH_FAILURE_POINT (p - 3, NULL);
5697 break;
5699 /* A nasty loop is introduced by the non-greedy *? and +?.
5700 With such loops, the stack only ever contains one failure point
5701 at a time, so that a plain on_failure_jump_loop kind of
5702 cycle detection cannot work. Worse yet, such a detection
5703 can not only fail to detect a cycle, but it can also wrongly
5704 detect a cycle (between different instantiations of the same
5705 loop).
5706 So the method used for those nasty loops is a little different:
5707 We use a special cycle-detection-stack-frame which is pushed
5708 when the on_failure_jump_nastyloop failure-point is *popped*.
5709 This special frame thus marks the beginning of one iteration
5710 through the loop and we can hence easily check right here
5711 whether something matched between the beginning and the end of
5712 the loop. */
5713 case on_failure_jump_nastyloop:
5714 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5715 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5716 mcnt, p + mcnt);
5718 assert ((re_opcode_t)p[-4] == no_op);
5720 int cycle = 0;
5721 CHECK_INFINITE_LOOP (p - 4, d);
5722 if (!cycle)
5723 /* If there's a cycle, just continue without pushing
5724 this failure point. The failure point is the "try again"
5725 option, which shouldn't be tried.
5726 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5727 PUSH_FAILURE_POINT (p - 3, d);
5729 break;
5731 /* Simple loop detecting on_failure_jump: just check on the
5732 failure stack if the same spot was already hit earlier. */
5733 case on_failure_jump_loop:
5734 on_failure:
5735 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5736 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5737 mcnt, p + mcnt);
5739 int cycle = 0;
5740 CHECK_INFINITE_LOOP (p - 3, d);
5741 if (cycle)
5742 /* If there's a cycle, get out of the loop, as if the matching
5743 had failed. We used to just `goto fail' here, but that was
5744 aborting the search a bit too early: we want to keep the
5745 empty-loop-match and keep matching after the loop.
5746 We want (x?)*y\1z to match both xxyz and xxyxz. */
5747 p += mcnt;
5748 else
5749 PUSH_FAILURE_POINT (p - 3, d);
5751 break;
5754 /* Uses of on_failure_jump:
5756 Each alternative starts with an on_failure_jump that points
5757 to the beginning of the next alternative. Each alternative
5758 except the last ends with a jump that in effect jumps past
5759 the rest of the alternatives. (They really jump to the
5760 ending jump of the following alternative, because tensioning
5761 these jumps is a hassle.)
5763 Repeats start with an on_failure_jump that points past both
5764 the repetition text and either the following jump or
5765 pop_failure_jump back to this on_failure_jump. */
5766 case on_failure_jump:
5767 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5768 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5769 mcnt, p + mcnt);
5771 PUSH_FAILURE_POINT (p -3, d);
5772 break;
5774 /* This operation is used for greedy *.
5775 Compare the beginning of the repeat with what in the
5776 pattern follows its end. If we can establish that there
5777 is nothing that they would both match, i.e., that we
5778 would have to backtrack because of (as in, e.g., `a*a')
5779 then we can use a non-backtracking loop based on
5780 on_failure_keep_string_jump instead of on_failure_jump. */
5781 case on_failure_jump_smart:
5782 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5783 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5784 mcnt, p + mcnt);
5786 re_char *p1 = p; /* Next operation. */
5787 /* Here, we discard `const', making re_match non-reentrant. */
5788 unsigned char *p2 = (unsigned char *) p + mcnt; /* Jump dest. */
5789 unsigned char *p3 = (unsigned char *) p - 3; /* opcode location. */
5791 p -= 3; /* Reset so that we will re-execute the
5792 instruction once it's been changed. */
5794 EXTRACT_NUMBER (mcnt, p2 - 2);
5796 /* Ensure this is a indeed the trivial kind of loop
5797 we are expecting. */
5798 assert (skip_one_char (p1) == p2 - 3);
5799 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5800 DEBUG_STATEMENT (debug += 2);
5801 if (mutually_exclusive_p (bufp, p1, p2))
5803 /* Use a fast `on_failure_keep_string_jump' loop. */
5804 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5805 *p3 = (unsigned char) on_failure_keep_string_jump;
5806 STORE_NUMBER (p2 - 2, mcnt + 3);
5808 else
5810 /* Default to a safe `on_failure_jump' loop. */
5811 DEBUG_PRINT (" smart default => slow loop.\n");
5812 *p3 = (unsigned char) on_failure_jump;
5814 DEBUG_STATEMENT (debug -= 2);
5816 break;
5818 /* Unconditionally jump (without popping any failure points). */
5819 case jump:
5820 unconditional_jump:
5821 maybe_quit ();
5822 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5823 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5824 p += mcnt; /* Do the jump. */
5825 DEBUG_PRINT ("(to %p).\n", p);
5826 break;
5829 /* Have to succeed matching what follows at least n times.
5830 After that, handle like `on_failure_jump'. */
5831 case succeed_n:
5832 /* Signedness doesn't matter since we only compare MCNT to 0. */
5833 EXTRACT_NUMBER (mcnt, p + 2);
5834 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5836 /* Originally, mcnt is how many times we HAVE to succeed. */
5837 if (mcnt != 0)
5839 /* Here, we discard `const', making re_match non-reentrant. */
5840 unsigned char *p2 = (unsigned char *) p + 2; /* counter loc. */
5841 mcnt--;
5842 p += 4;
5843 PUSH_NUMBER (p2, mcnt);
5845 else
5846 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5847 goto on_failure;
5848 break;
5850 case jump_n:
5851 /* Signedness doesn't matter since we only compare MCNT to 0. */
5852 EXTRACT_NUMBER (mcnt, p + 2);
5853 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5855 /* Originally, this is how many times we CAN jump. */
5856 if (mcnt != 0)
5858 /* Here, we discard `const', making re_match non-reentrant. */
5859 unsigned char *p2 = (unsigned char *) p + 2; /* counter loc. */
5860 mcnt--;
5861 PUSH_NUMBER (p2, mcnt);
5862 goto unconditional_jump;
5864 /* If don't have to jump any more, skip over the rest of command. */
5865 else
5866 p += 4;
5867 break;
5869 case set_number_at:
5871 unsigned char *p2; /* Location of the counter. */
5872 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5874 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5875 /* Here, we discard `const', making re_match non-reentrant. */
5876 p2 = (unsigned char *) p + mcnt;
5877 /* Signedness doesn't matter since we only copy MCNT's bits. */
5878 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5879 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5880 PUSH_NUMBER (p2, mcnt);
5881 break;
5884 case wordbound:
5885 case notwordbound:
5887 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5888 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5890 /* We SUCCEED (or FAIL) in one of the following cases: */
5892 /* Case 1: D is at the beginning or the end of string. */
5893 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5894 not = !not;
5895 else
5897 /* C1 is the character before D, S1 is the syntax of C1, C2
5898 is the character at D, and S2 is the syntax of C2. */
5899 re_wchar_t c1, c2;
5900 int s1, s2;
5901 int dummy;
5902 #ifdef emacs
5903 ssize_t offset = PTR_TO_OFFSET (d - 1);
5904 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5905 UPDATE_SYNTAX_TABLE_FAST (charpos);
5906 #endif
5907 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5908 s1 = SYNTAX (c1);
5909 #ifdef emacs
5910 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
5911 #endif
5912 PREFETCH_NOLIMIT ();
5913 GET_CHAR_AFTER (c2, d, dummy);
5914 s2 = SYNTAX (c2);
5916 if (/* Case 2: Only one of S1 and S2 is Sword. */
5917 ((s1 == Sword) != (s2 == Sword))
5918 /* Case 3: Both of S1 and S2 are Sword, and macro
5919 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5920 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5921 not = !not;
5923 if (not)
5924 break;
5925 else
5926 goto fail;
5929 case wordbeg:
5930 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5932 /* We FAIL in one of the following cases: */
5934 /* Case 1: D is at the end of string. */
5935 if (AT_STRINGS_END (d))
5936 goto fail;
5937 else
5939 /* C1 is the character before D, S1 is the syntax of C1, C2
5940 is the character at D, and S2 is the syntax of C2. */
5941 re_wchar_t c1, c2;
5942 int s1, s2;
5943 int dummy;
5944 #ifdef emacs
5945 ssize_t offset = PTR_TO_OFFSET (d);
5946 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5947 UPDATE_SYNTAX_TABLE_FAST (charpos);
5948 #endif
5949 PREFETCH ();
5950 GET_CHAR_AFTER (c2, d, dummy);
5951 s2 = SYNTAX (c2);
5953 /* Case 2: S2 is not Sword. */
5954 if (s2 != Sword)
5955 goto fail;
5957 /* Case 3: D is not at the beginning of string ... */
5958 if (!AT_STRINGS_BEG (d))
5960 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5961 #ifdef emacs
5962 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5963 #endif
5964 s1 = SYNTAX (c1);
5966 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5967 returns 0. */
5968 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5969 goto fail;
5972 break;
5974 case wordend:
5975 DEBUG_PRINT ("EXECUTING wordend.\n");
5977 /* We FAIL in one of the following cases: */
5979 /* Case 1: D is at the beginning of string. */
5980 if (AT_STRINGS_BEG (d))
5981 goto fail;
5982 else
5984 /* C1 is the character before D, S1 is the syntax of C1, C2
5985 is the character at D, and S2 is the syntax of C2. */
5986 re_wchar_t c1, c2;
5987 int s1, s2;
5988 int dummy;
5989 #ifdef emacs
5990 ssize_t offset = PTR_TO_OFFSET (d) - 1;
5991 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5992 UPDATE_SYNTAX_TABLE_FAST (charpos);
5993 #endif
5994 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5995 s1 = SYNTAX (c1);
5997 /* Case 2: S1 is not Sword. */
5998 if (s1 != Sword)
5999 goto fail;
6001 /* Case 3: D is not at the end of string ... */
6002 if (!AT_STRINGS_END (d))
6004 PREFETCH_NOLIMIT ();
6005 GET_CHAR_AFTER (c2, d, dummy);
6006 #ifdef emacs
6007 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos);
6008 #endif
6009 s2 = SYNTAX (c2);
6011 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6012 returns 0. */
6013 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6014 goto fail;
6017 break;
6019 case symbeg:
6020 DEBUG_PRINT ("EXECUTING symbeg.\n");
6022 /* We FAIL in one of the following cases: */
6024 /* Case 1: D is at the end of string. */
6025 if (AT_STRINGS_END (d))
6026 goto fail;
6027 else
6029 /* C1 is the character before D, S1 is the syntax of C1, C2
6030 is the character at D, and S2 is the syntax of C2. */
6031 re_wchar_t c1, c2;
6032 int s1, s2;
6033 #ifdef emacs
6034 ssize_t offset = PTR_TO_OFFSET (d);
6035 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6036 UPDATE_SYNTAX_TABLE_FAST (charpos);
6037 #endif
6038 PREFETCH ();
6039 c2 = RE_STRING_CHAR (d, target_multibyte);
6040 s2 = SYNTAX (c2);
6042 /* Case 2: S2 is neither Sword nor Ssymbol. */
6043 if (s2 != Sword && s2 != Ssymbol)
6044 goto fail;
6046 /* Case 3: D is not at the beginning of string ... */
6047 if (!AT_STRINGS_BEG (d))
6049 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6050 #ifdef emacs
6051 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6052 #endif
6053 s1 = SYNTAX (c1);
6055 /* ... and S1 is Sword or Ssymbol. */
6056 if (s1 == Sword || s1 == Ssymbol)
6057 goto fail;
6060 break;
6062 case symend:
6063 DEBUG_PRINT ("EXECUTING symend.\n");
6065 /* We FAIL in one of the following cases: */
6067 /* Case 1: D is at the beginning of string. */
6068 if (AT_STRINGS_BEG (d))
6069 goto fail;
6070 else
6072 /* C1 is the character before D, S1 is the syntax of C1, C2
6073 is the character at D, and S2 is the syntax of C2. */
6074 re_wchar_t c1, c2;
6075 int s1, s2;
6076 #ifdef emacs
6077 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6078 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6079 UPDATE_SYNTAX_TABLE_FAST (charpos);
6080 #endif
6081 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6082 s1 = SYNTAX (c1);
6084 /* Case 2: S1 is neither Ssymbol nor Sword. */
6085 if (s1 != Sword && s1 != Ssymbol)
6086 goto fail;
6088 /* Case 3: D is not at the end of string ... */
6089 if (!AT_STRINGS_END (d))
6091 PREFETCH_NOLIMIT ();
6092 c2 = RE_STRING_CHAR (d, target_multibyte);
6093 #ifdef emacs
6094 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
6095 #endif
6096 s2 = SYNTAX (c2);
6098 /* ... and S2 is Sword or Ssymbol. */
6099 if (s2 == Sword || s2 == Ssymbol)
6100 goto fail;
6103 break;
6105 case syntaxspec:
6106 case notsyntaxspec:
6108 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6109 mcnt = *p++;
6110 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6111 mcnt);
6112 PREFETCH ();
6113 #ifdef emacs
6115 ssize_t offset = PTR_TO_OFFSET (d);
6116 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6117 UPDATE_SYNTAX_TABLE_FAST (pos1);
6119 #endif
6121 int len;
6122 re_wchar_t c;
6124 GET_CHAR_AFTER (c, d, len);
6125 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6126 goto fail;
6127 d += len;
6130 break;
6132 #ifdef emacs
6133 case at_dot:
6134 DEBUG_PRINT ("EXECUTING at_dot.\n");
6135 if (PTR_BYTE_POS (d) != PT_BYTE)
6136 goto fail;
6137 break;
6139 case categoryspec:
6140 case notcategoryspec:
6142 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6143 mcnt = *p++;
6144 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6145 not ? "not" : "", mcnt);
6146 PREFETCH ();
6149 int len;
6150 re_wchar_t c;
6151 GET_CHAR_AFTER (c, d, len);
6152 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6153 goto fail;
6154 d += len;
6157 break;
6159 #endif /* emacs */
6161 default:
6162 abort ();
6164 continue; /* Successfully executed one pattern command; keep going. */
6167 /* We goto here if a matching operation fails. */
6168 fail:
6169 maybe_quit ();
6170 if (!FAIL_STACK_EMPTY ())
6172 re_char *str, *pat;
6173 /* A restart point is known. Restore to that state. */
6174 DEBUG_PRINT ("\nFAIL:\n");
6175 POP_FAILURE_POINT (str, pat);
6176 switch (*pat++)
6178 case on_failure_keep_string_jump:
6179 assert (str == NULL);
6180 goto continue_failure_jump;
6182 case on_failure_jump_nastyloop:
6183 assert ((re_opcode_t)pat[-2] == no_op);
6184 PUSH_FAILURE_POINT (pat - 2, str);
6185 /* Fallthrough */
6187 case on_failure_jump_loop:
6188 case on_failure_jump:
6189 case succeed_n:
6190 d = str;
6191 continue_failure_jump:
6192 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6193 p = pat + mcnt;
6194 break;
6196 case no_op:
6197 /* A special frame used for nastyloops. */
6198 goto fail;
6200 default:
6201 abort ();
6204 assert (p >= bufp->buffer && p <= pend);
6206 if (d >= string1 && d <= end1)
6207 dend = end_match_1;
6209 else
6210 break; /* Matching at this starting point really fails. */
6211 } /* for (;;) */
6213 if (best_regs_set)
6214 goto restore_best_regs;
6216 FREE_VARIABLES ();
6218 return -1; /* Failure to match. */
6221 /* Subroutine definitions for re_match_2. */
6223 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6224 bytes; nonzero otherwise. */
6226 static int
6227 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6228 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6230 register re_char *p1 = s1, *p2 = s2;
6231 re_char *p1_end = s1 + len;
6232 re_char *p2_end = s2 + len;
6234 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6235 different lengths, but relying on a single `len' would break this. -sm */
6236 while (p1 < p1_end && p2 < p2_end)
6238 int p1_charlen, p2_charlen;
6239 re_wchar_t p1_ch, p2_ch;
6241 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6242 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6244 if (RE_TRANSLATE (translate, p1_ch)
6245 != RE_TRANSLATE (translate, p2_ch))
6246 return 1;
6248 p1 += p1_charlen, p2 += p2_charlen;
6251 if (p1 != p1_end || p2 != p2_end)
6252 return 1;
6254 return 0;
6257 /* Entry points for GNU code. */
6259 /* re_compile_pattern is the GNU regular expression compiler: it
6260 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6261 Returns 0 if the pattern was valid, otherwise an error string.
6263 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6264 are set in BUFP on entry.
6266 We call regex_compile to do the actual compilation. */
6268 const char *
6269 re_compile_pattern (const char *pattern, size_t length,
6270 #ifdef emacs
6271 bool posix_backtracking, const char *whitespace_regexp,
6272 #endif
6273 struct re_pattern_buffer *bufp)
6275 reg_errcode_t ret;
6277 /* GNU code is written to assume at least RE_NREGS registers will be set
6278 (and at least one extra will be -1). */
6279 bufp->regs_allocated = REGS_UNALLOCATED;
6281 /* And GNU code determines whether or not to get register information
6282 by passing null for the REGS argument to re_match, etc., not by
6283 setting no_sub. */
6284 bufp->no_sub = 0;
6286 ret = regex_compile ((re_char *) pattern, length,
6287 #ifdef emacs
6288 posix_backtracking,
6289 whitespace_regexp,
6290 #else
6291 re_syntax_options,
6292 #endif
6293 bufp);
6295 if (!ret)
6296 return NULL;
6297 return gettext (re_error_msgid[(int) ret]);
6299 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6301 /* Entry points compatible with 4.2 BSD regex library. We don't define
6302 them unless specifically requested. */
6304 #if defined _REGEX_RE_COMP || defined _LIBC
6306 /* BSD has one and only one pattern buffer. */
6307 static struct re_pattern_buffer re_comp_buf;
6309 char *
6310 # ifdef _LIBC
6311 /* Make these definitions weak in libc, so POSIX programs can redefine
6312 these names if they don't use our functions, and still use
6313 regcomp/regexec below without link errors. */
6314 weak_function
6315 # endif
6316 re_comp (const char *s)
6318 reg_errcode_t ret;
6320 if (!s)
6322 if (!re_comp_buf.buffer)
6323 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6324 return (char *) gettext ("No previous regular expression");
6325 return 0;
6328 if (!re_comp_buf.buffer)
6330 re_comp_buf.buffer = malloc (200);
6331 if (re_comp_buf.buffer == NULL)
6332 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6333 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6334 re_comp_buf.allocated = 200;
6336 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6337 if (re_comp_buf.fastmap == NULL)
6338 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6339 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6342 /* Since `re_exec' always passes NULL for the `regs' argument, we
6343 don't need to initialize the pattern buffer fields which affect it. */
6345 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6347 if (!ret)
6348 return NULL;
6350 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6351 return (char *) gettext (re_error_msgid[(int) ret]);
6356 # ifdef _LIBC
6357 weak_function
6358 # endif
6359 re_exec (const char *s)
6361 const size_t len = strlen (s);
6362 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6364 #endif /* _REGEX_RE_COMP */
6366 /* POSIX.2 functions. Don't define these for Emacs. */
6368 #ifndef emacs
6370 /* regcomp takes a regular expression as a string and compiles it.
6372 PREG is a regex_t *. We do not expect any fields to be initialized,
6373 since POSIX says we shouldn't. Thus, we set
6375 `buffer' to the compiled pattern;
6376 `used' to the length of the compiled pattern;
6377 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6378 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6379 RE_SYNTAX_POSIX_BASIC;
6380 `fastmap' to an allocated space for the fastmap;
6381 `fastmap_accurate' to zero;
6382 `re_nsub' to the number of subexpressions in PATTERN.
6384 PATTERN is the address of the pattern string.
6386 CFLAGS is a series of bits which affect compilation.
6388 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6389 use POSIX basic syntax.
6391 If REG_NEWLINE is set, then . and [^...] don't match newline.
6392 Also, regexec will try a match beginning after every newline.
6394 If REG_ICASE is set, then we considers upper- and lowercase
6395 versions of letters to be equivalent when matching.
6397 If REG_NOSUB is set, then when PREG is passed to regexec, that
6398 routine will report only success or failure, and nothing about the
6399 registers.
6401 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6402 the return codes and their meanings.) */
6404 reg_errcode_t
6405 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6406 int cflags)
6408 reg_errcode_t ret;
6409 reg_syntax_t syntax
6410 = (cflags & REG_EXTENDED) ?
6411 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6413 /* regex_compile will allocate the space for the compiled pattern. */
6414 preg->buffer = 0;
6415 preg->allocated = 0;
6416 preg->used = 0;
6418 /* Try to allocate space for the fastmap. */
6419 preg->fastmap = malloc (1 << BYTEWIDTH);
6421 if (cflags & REG_ICASE)
6423 unsigned i;
6425 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6426 if (preg->translate == NULL)
6427 return (int) REG_ESPACE;
6429 /* Map uppercase characters to corresponding lowercase ones. */
6430 for (i = 0; i < CHAR_SET_SIZE; i++)
6431 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6433 else
6434 preg->translate = NULL;
6436 /* If REG_NEWLINE is set, newlines are treated differently. */
6437 if (cflags & REG_NEWLINE)
6438 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6439 syntax &= ~RE_DOT_NEWLINE;
6440 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6442 else
6443 syntax |= RE_NO_NEWLINE_ANCHOR;
6445 preg->no_sub = !!(cflags & REG_NOSUB);
6447 /* POSIX says a null character in the pattern terminates it, so we
6448 can use strlen here in compiling the pattern. */
6449 ret = regex_compile ((re_char *) pattern, strlen (pattern), syntax, preg);
6451 /* POSIX doesn't distinguish between an unmatched open-group and an
6452 unmatched close-group: both are REG_EPAREN. */
6453 if (ret == REG_ERPAREN)
6454 ret = REG_EPAREN;
6456 if (ret == REG_NOERROR && preg->fastmap)
6457 { /* Compute the fastmap now, since regexec cannot modify the pattern
6458 buffer. */
6459 re_compile_fastmap (preg);
6460 if (preg->can_be_null)
6461 { /* The fastmap can't be used anyway. */
6462 free (preg->fastmap);
6463 preg->fastmap = NULL;
6466 return ret;
6468 WEAK_ALIAS (__regcomp, regcomp)
6471 /* regexec searches for a given pattern, specified by PREG, in the
6472 string STRING.
6474 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6475 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6476 least NMATCH elements, and we set them to the offsets of the
6477 corresponding matched substrings.
6479 EFLAGS specifies `execution flags' which affect matching: if
6480 REG_NOTBOL is set, then ^ does not match at the beginning of the
6481 string; if REG_NOTEOL is set, then $ does not match at the end.
6483 We return 0 if we find a match and REG_NOMATCH if not. */
6485 reg_errcode_t
6486 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6487 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6489 regoff_t ret;
6490 struct re_registers regs;
6491 regex_t private_preg;
6492 size_t len = strlen (string);
6493 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6495 private_preg = *preg;
6497 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6498 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6500 /* The user has told us exactly how many registers to return
6501 information about, via `nmatch'. We have to pass that on to the
6502 matching routines. */
6503 private_preg.regs_allocated = REGS_FIXED;
6505 if (want_reg_info)
6507 regs.num_regs = nmatch;
6508 regs.start = TALLOC (nmatch * 2, regoff_t);
6509 if (regs.start == NULL)
6510 return REG_NOMATCH;
6511 regs.end = regs.start + nmatch;
6514 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6515 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6516 was a little bit longer but still only matching the real part.
6517 This works because the `endline' will check for a '\n' and will find a
6518 '\0', correctly deciding that this is not the end of a line.
6519 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6520 a convenient '\0' there. For all we know, the string could be preceded
6521 by '\n' which would throw things off. */
6523 /* Perform the searching operation. */
6524 ret = re_search (&private_preg, string, len,
6525 /* start: */ 0, /* range: */ len,
6526 want_reg_info ? &regs : 0);
6528 /* Copy the register information to the POSIX structure. */
6529 if (want_reg_info)
6531 if (ret >= 0)
6533 unsigned r;
6535 for (r = 0; r < nmatch; r++)
6537 pmatch[r].rm_so = regs.start[r];
6538 pmatch[r].rm_eo = regs.end[r];
6542 /* If we needed the temporary register info, free the space now. */
6543 free (regs.start);
6546 /* We want zero return to mean success, unlike `re_search'. */
6547 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6549 WEAK_ALIAS (__regexec, regexec)
6552 /* Returns a message corresponding to an error code, ERR_CODE, returned
6553 from either regcomp or regexec. We don't use PREG here.
6555 ERR_CODE was previously called ERRCODE, but that name causes an
6556 error with msvc8 compiler. */
6558 size_t
6559 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6561 const char *msg;
6562 size_t msg_size;
6564 if (err_code < 0
6565 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6566 /* Only error codes returned by the rest of the code should be passed
6567 to this routine. If we are given anything else, or if other regex
6568 code generates an invalid error code, then the program has a bug.
6569 Dump core so we can fix it. */
6570 abort ();
6572 msg = gettext (re_error_msgid[err_code]);
6574 msg_size = strlen (msg) + 1; /* Includes the null. */
6576 if (errbuf_size != 0)
6578 if (msg_size > errbuf_size)
6580 memcpy (errbuf, msg, errbuf_size - 1);
6581 errbuf[errbuf_size - 1] = 0;
6583 else
6584 strcpy (errbuf, msg);
6587 return msg_size;
6589 WEAK_ALIAS (__regerror, regerror)
6592 /* Free dynamically allocated space used by PREG. */
6594 void
6595 regfree (regex_t *preg)
6597 free (preg->buffer);
6598 preg->buffer = NULL;
6600 preg->allocated = 0;
6601 preg->used = 0;
6603 free (preg->fastmap);
6604 preg->fastmap = NULL;
6605 preg->fastmap_accurate = 0;
6607 free (preg->translate);
6608 preg->translate = NULL;
6610 WEAK_ALIAS (__regfree, regfree)
6612 #endif /* not emacs */