Fix TTY colors breakage by 'clear-face-cache'
[emacs.git] / src / regex.c
blob4f9df68a9feb7cfb7d4e69ae67abe9b00399685d
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-2018 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 <https://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) (0 <= char_hexdigit (c))
311 /* The rest must handle multibyte characters. */
313 # define ISBLANK(c) (IS_REAL_ASCII (c) \
314 ? ((c) == ' ' || (c) == '\t') \
315 : blankp (c))
317 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
318 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0240) \
319 : graphicp (c))
321 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
322 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
323 : printablep (c))
325 # define ISALNUM(c) (IS_REAL_ASCII (c) \
326 ? (((c) >= 'a' && (c) <= 'z') \
327 || ((c) >= 'A' && (c) <= 'Z') \
328 || ((c) >= '0' && (c) <= '9')) \
329 : alphanumericp (c))
331 # define ISALPHA(c) (IS_REAL_ASCII (c) \
332 ? (((c) >= 'a' && (c) <= 'z') \
333 || ((c) >= 'A' && (c) <= 'Z')) \
334 : alphabeticp (c))
336 # define ISLOWER(c) lowercasep (c)
338 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
339 ? ((c) > ' ' && (c) < 0177 \
340 && !(((c) >= 'a' && (c) <= 'z') \
341 || ((c) >= 'A' && (c) <= 'Z') \
342 || ((c) >= '0' && (c) <= '9'))) \
343 : SYNTAX (c) != Sword)
345 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
347 # define ISUPPER(c) uppercasep (c)
349 # define ISWORD(c) (SYNTAX (c) == Sword)
351 #else /* not emacs */
353 /* 1 if C is an ASCII character. */
354 # define IS_REAL_ASCII(c) ((c) < 0200)
356 /* This distinction is not meaningful, except in Emacs. */
357 # define ISUNIBYTE(c) 1
359 # ifdef isblank
360 # define ISBLANK(c) isblank (c)
361 # else
362 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
363 # endif
364 # ifdef isgraph
365 # define ISGRAPH(c) isgraph (c)
366 # else
367 # define ISGRAPH(c) (isprint (c) && !isspace (c))
368 # endif
370 /* Solaris defines ISPRINT so we must undefine it first. */
371 # undef ISPRINT
372 # define ISPRINT(c) isprint (c)
373 # define ISDIGIT(c) isdigit (c)
374 # define ISALNUM(c) isalnum (c)
375 # define ISALPHA(c) isalpha (c)
376 # define ISCNTRL(c) iscntrl (c)
377 # define ISLOWER(c) islower (c)
378 # define ISPUNCT(c) ispunct (c)
379 # define ISSPACE(c) isspace (c)
380 # define ISUPPER(c) isupper (c)
381 # define ISXDIGIT(c) isxdigit (c)
383 # define ISWORD(c) ISALPHA (c)
385 # ifdef _tolower
386 # define TOLOWER(c) _tolower (c)
387 # else
388 # define TOLOWER(c) tolower (c)
389 # endif
391 /* How many characters in the character set. */
392 # define CHAR_SET_SIZE 256
394 # ifdef SYNTAX_TABLE
396 extern char *re_syntax_table;
398 # else /* not SYNTAX_TABLE */
400 static char re_syntax_table[CHAR_SET_SIZE];
402 static void
403 init_syntax_once (void)
405 register int c;
406 static int done = 0;
408 if (done)
409 return;
411 memset (re_syntax_table, 0, sizeof re_syntax_table);
413 for (c = 0; c < CHAR_SET_SIZE; ++c)
414 if (ISALNUM (c))
415 re_syntax_table[c] = Sword;
417 re_syntax_table['_'] = Ssymbol;
419 done = 1;
422 # endif /* not SYNTAX_TABLE */
424 # define SYNTAX(c) re_syntax_table[(c)]
426 #endif /* not emacs */
428 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
430 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
431 use `alloca' instead of `malloc'. This is because using malloc in
432 re_search* or re_match* could cause memory leaks when C-g is used
433 in Emacs (note that SAFE_ALLOCA could also call malloc, but does so
434 via `record_xmalloc' which uses `unwind_protect' to ensure the
435 memory is freed even in case of non-local exits); also, malloc is
436 slower and causes storage fragmentation. On the other hand, malloc
437 is more portable, and easier to debug.
439 Because we sometimes use alloca, some routines have to be macros,
440 not functions -- `alloca'-allocated space disappears at the end of the
441 function it is called in. */
443 #ifdef REGEX_MALLOC
445 # define REGEX_ALLOCATE malloc
446 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
447 # define REGEX_FREE free
449 #else /* not REGEX_MALLOC */
451 # ifdef emacs
452 /* This may be adjusted in main(), if the stack is successfully grown. */
453 ptrdiff_t emacs_re_safe_alloca = MAX_ALLOCA;
454 /* Like USE_SAFE_ALLOCA, but use emacs_re_safe_alloca. */
455 # define REGEX_USE_SAFE_ALLOCA \
456 ptrdiff_t sa_avail = emacs_re_safe_alloca; \
457 ptrdiff_t sa_count = SPECPDL_INDEX (); bool sa_must_free = false
459 # define REGEX_SAFE_FREE() SAFE_FREE ()
460 # define REGEX_ALLOCATE SAFE_ALLOCA
461 # else
462 # include <alloca.h>
463 # define REGEX_ALLOCATE alloca
464 # endif
466 /* Assumes a `char *destination' variable. */
467 # define REGEX_REALLOCATE(source, osize, nsize) \
468 (destination = REGEX_ALLOCATE (nsize), \
469 memcpy (destination, source, osize))
471 /* No need to do anything to free, after alloca. */
472 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
474 #endif /* not REGEX_MALLOC */
476 #ifndef REGEX_USE_SAFE_ALLOCA
477 # define REGEX_USE_SAFE_ALLOCA ((void) 0)
478 # define REGEX_SAFE_FREE() ((void) 0)
479 #endif
481 /* Define how to allocate the failure stack. */
483 #if defined REL_ALLOC && defined REGEX_MALLOC
485 # define REGEX_ALLOCATE_STACK(size) \
486 r_alloc (&failure_stack_ptr, (size))
487 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
488 r_re_alloc (&failure_stack_ptr, (nsize))
489 # define REGEX_FREE_STACK(ptr) \
490 r_alloc_free (&failure_stack_ptr)
492 #else /* not using relocating allocator */
494 # define REGEX_ALLOCATE_STACK(size) REGEX_ALLOCATE (size)
495 # define REGEX_REALLOCATE_STACK(source, o, n) REGEX_REALLOCATE (source, o, n)
496 # define REGEX_FREE_STACK(ptr) REGEX_FREE (ptr)
498 #endif /* not using relocating allocator */
501 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
502 `string1' or just past its end. This works if PTR is NULL, which is
503 a good thing. */
504 #define FIRST_STRING_P(ptr) \
505 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
507 /* (Re)Allocate N items of type T using malloc, or fail. */
508 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
509 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
510 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
512 #define BYTEWIDTH 8 /* In bits. */
514 #ifndef emacs
515 # undef max
516 # undef min
517 # define max(a, b) ((a) > (b) ? (a) : (b))
518 # define min(a, b) ((a) < (b) ? (a) : (b))
519 #endif
521 /* Type of source-pattern and string chars. */
522 #ifdef _MSC_VER
523 typedef unsigned char re_char;
524 typedef const re_char const_re_char;
525 #else
526 typedef const unsigned char re_char;
527 typedef re_char const_re_char;
528 #endif
530 typedef char boolean;
532 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
533 re_char *string1, size_t size1,
534 re_char *string2, size_t size2,
535 ssize_t pos,
536 struct re_registers *regs,
537 ssize_t stop);
539 /* These are the command codes that appear in compiled regular
540 expressions. Some opcodes are followed by argument bytes. A
541 command code can specify any interpretation whatsoever for its
542 arguments. Zero bytes may appear in the compiled regular expression. */
544 typedef enum
546 no_op = 0,
548 /* Succeed right away--no more backtracking. */
549 succeed,
551 /* Followed by one byte giving n, then by n literal bytes. */
552 exactn,
554 /* Matches any (more or less) character. */
555 anychar,
557 /* Matches any one char belonging to specified set. First
558 following byte is number of bitmap bytes. Then come bytes
559 for a bitmap saying which chars are in. Bits in each byte
560 are ordered low-bit-first. A character is in the set if its
561 bit is 1. A character too large to have a bit in the map is
562 automatically not in the set.
564 If the length byte has the 0x80 bit set, then that stuff
565 is followed by a range table:
566 2 bytes of flags for character sets (low 8 bits, high 8 bits)
567 See RANGE_TABLE_WORK_BITS below.
568 2 bytes, the number of pairs that follow (upto 32767)
569 pairs, each 2 multibyte characters,
570 each multibyte character represented as 3 bytes. */
571 charset,
573 /* Same parameters as charset, but match any character that is
574 not one of those specified. */
575 charset_not,
577 /* Start remembering the text that is matched, for storing in a
578 register. Followed by one byte with the register number, in
579 the range 0 to one less than the pattern buffer's re_nsub
580 field. */
581 start_memory,
583 /* Stop remembering the text that is matched and store it in a
584 memory register. Followed by one byte with the register
585 number, in the range 0 to one less than `re_nsub' in the
586 pattern buffer. */
587 stop_memory,
589 /* Match a duplicate of something remembered. Followed by one
590 byte containing the register number. */
591 duplicate,
593 /* Fail unless at beginning of line. */
594 begline,
596 /* Fail unless at end of line. */
597 endline,
599 /* Succeeds if at beginning of buffer (if emacs) or at beginning
600 of string to be matched (if not). */
601 begbuf,
603 /* Analogously, for end of buffer/string. */
604 endbuf,
606 /* Followed by two byte relative address to which to jump. */
607 jump,
609 /* Followed by two-byte relative address of place to resume at
610 in case of failure. */
611 on_failure_jump,
613 /* Like on_failure_jump, but pushes a placeholder instead of the
614 current string position when executed. */
615 on_failure_keep_string_jump,
617 /* Just like `on_failure_jump', except that it checks that we
618 don't get stuck in an infinite loop (matching an empty string
619 indefinitely). */
620 on_failure_jump_loop,
622 /* Just like `on_failure_jump_loop', except that it checks for
623 a different kind of loop (the kind that shows up with non-greedy
624 operators). This operation has to be immediately preceded
625 by a `no_op'. */
626 on_failure_jump_nastyloop,
628 /* A smart `on_failure_jump' used for greedy * and + operators.
629 It analyzes the loop before which it is put and if the
630 loop does not require backtracking, it changes itself to
631 `on_failure_keep_string_jump' and short-circuits the loop,
632 else it just defaults to changing itself into `on_failure_jump'.
633 It assumes that it is pointing to just past a `jump'. */
634 on_failure_jump_smart,
636 /* Followed by two-byte relative address and two-byte number n.
637 After matching N times, jump to the address upon failure.
638 Does not work if N starts at 0: use on_failure_jump_loop
639 instead. */
640 succeed_n,
642 /* Followed by two-byte relative address, and two-byte number n.
643 Jump to the address N times, then fail. */
644 jump_n,
646 /* Set the following two-byte relative address to the
647 subsequent two-byte number. The address *includes* the two
648 bytes of number. */
649 set_number_at,
651 wordbeg, /* Succeeds if at word beginning. */
652 wordend, /* Succeeds if at word end. */
654 wordbound, /* Succeeds if at a word boundary. */
655 notwordbound, /* Succeeds if not at a word boundary. */
657 symbeg, /* Succeeds if at symbol beginning. */
658 symend, /* Succeeds if at symbol end. */
660 /* Matches any character whose syntax is specified. Followed by
661 a byte which contains a syntax code, e.g., Sword. */
662 syntaxspec,
664 /* Matches any character whose syntax is not that specified. */
665 notsyntaxspec
667 #ifdef emacs
668 , at_dot, /* Succeeds if at point. */
670 /* Matches any character whose category-set contains the specified
671 category. The operator is followed by a byte which contains a
672 category code (mnemonic ASCII character). */
673 categoryspec,
675 /* Matches any character whose category-set does not contain the
676 specified category. The operator is followed by a byte which
677 contains the category code (mnemonic ASCII character). */
678 notcategoryspec
679 #endif /* emacs */
680 } re_opcode_t;
682 /* Common operations on the compiled pattern. */
684 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
686 #define STORE_NUMBER(destination, number) \
687 do { \
688 (destination)[0] = (number) & 0377; \
689 (destination)[1] = (number) >> 8; \
690 } while (0)
692 /* Same as STORE_NUMBER, except increment DESTINATION to
693 the byte after where the number is stored. Therefore, DESTINATION
694 must be an lvalue. */
696 #define STORE_NUMBER_AND_INCR(destination, number) \
697 do { \
698 STORE_NUMBER (destination, number); \
699 (destination) += 2; \
700 } while (0)
702 /* Put into DESTINATION a number stored in two contiguous bytes starting
703 at SOURCE. */
705 #define EXTRACT_NUMBER(destination, source) \
706 ((destination) = extract_number (source))
708 static int
709 extract_number (re_char *source)
711 unsigned leading_byte = SIGN_EXTEND_CHAR (source[1]);
712 return (leading_byte << 8) + source[0];
715 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
716 SOURCE must be an lvalue. */
718 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
719 ((destination) = extract_number_and_incr (&source))
721 static int
722 extract_number_and_incr (re_char **source)
724 int num = extract_number (*source);
725 *source += 2;
726 return num;
729 /* Store a multibyte character in three contiguous bytes starting
730 DESTINATION, and increment DESTINATION to the byte after where the
731 character is stored. Therefore, DESTINATION must be an lvalue. */
733 #define STORE_CHARACTER_AND_INCR(destination, character) \
734 do { \
735 (destination)[0] = (character) & 0377; \
736 (destination)[1] = ((character) >> 8) & 0377; \
737 (destination)[2] = (character) >> 16; \
738 (destination) += 3; \
739 } while (0)
741 /* Put into DESTINATION a character stored in three contiguous bytes
742 starting at SOURCE. */
744 #define EXTRACT_CHARACTER(destination, source) \
745 do { \
746 (destination) = ((source)[0] \
747 | ((source)[1] << 8) \
748 | ((source)[2] << 16)); \
749 } while (0)
752 /* Macros for charset. */
754 /* Size of bitmap of charset P in bytes. P is a start of charset,
755 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
756 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
758 /* Nonzero if charset P has range table. */
759 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
761 /* Return the address of range table of charset P. But not the start
762 of table itself, but the before where the number of ranges is
763 stored. `2 +' means to skip re_opcode_t and size of bitmap,
764 and the 2 bytes of flags at the start of the range table. */
765 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
767 #ifdef emacs
768 /* Extract the bit flags that start a range table. */
769 #define CHARSET_RANGE_TABLE_BITS(p) \
770 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
771 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
772 #endif
774 /* Return the address of end of RANGE_TABLE. COUNT is number of
775 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
776 is start of range and end of range. `* 3' is size of each start
777 and end. */
778 #define CHARSET_RANGE_TABLE_END(range_table, count) \
779 ((range_table) + (count) * 2 * 3)
781 /* If DEBUG is defined, Regex prints many voluminous messages about what
782 it is doing (if the variable `debug' is nonzero). If linked with the
783 main program in `iregex.c', you can enter patterns and strings
784 interactively. And if linked with the main program in `main.c' and
785 the other test files, you can run the already-written tests. */
787 #ifdef DEBUG
789 /* We use standard I/O for debugging. */
790 # include <stdio.h>
792 /* It is useful to test things that ``must'' be true when debugging. */
793 # include <assert.h>
795 static int debug = -100000;
797 # define DEBUG_STATEMENT(e) e
798 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
799 # define DEBUG_COMPILES_ARGUMENTS
800 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
801 if (debug > 0) print_partial_compiled_pattern (s, e)
802 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
803 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
806 /* Print the fastmap in human-readable form. */
808 static void
809 print_fastmap (char *fastmap)
811 unsigned was_a_range = 0;
812 unsigned i = 0;
814 while (i < (1 << BYTEWIDTH))
816 if (fastmap[i++])
818 was_a_range = 0;
819 putchar (i - 1);
820 while (i < (1 << BYTEWIDTH) && fastmap[i])
822 was_a_range = 1;
823 i++;
825 if (was_a_range)
827 printf ("-");
828 putchar (i - 1);
832 putchar ('\n');
836 /* Print a compiled pattern string in human-readable form, starting at
837 the START pointer into it and ending just before the pointer END. */
839 static void
840 print_partial_compiled_pattern (re_char *start, re_char *end)
842 int mcnt, mcnt2;
843 re_char *p = start;
844 re_char *pend = end;
846 if (start == NULL)
848 fprintf (stderr, "(null)\n");
849 return;
852 /* Loop over pattern commands. */
853 while (p < pend)
855 fprintf (stderr, "%td:\t", p - start);
857 switch ((re_opcode_t) *p++)
859 case no_op:
860 fprintf (stderr, "/no_op");
861 break;
863 case succeed:
864 fprintf (stderr, "/succeed");
865 break;
867 case exactn:
868 mcnt = *p++;
869 fprintf (stderr, "/exactn/%d", mcnt);
872 fprintf (stderr, "/%c", *p++);
874 while (--mcnt);
875 break;
877 case start_memory:
878 fprintf (stderr, "/start_memory/%d", *p++);
879 break;
881 case stop_memory:
882 fprintf (stderr, "/stop_memory/%d", *p++);
883 break;
885 case duplicate:
886 fprintf (stderr, "/duplicate/%d", *p++);
887 break;
889 case anychar:
890 fprintf (stderr, "/anychar");
891 break;
893 case charset:
894 case charset_not:
896 register int c, last = -100;
897 register int in_range = 0;
898 int length = CHARSET_BITMAP_SIZE (p - 1);
899 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
901 fprintf (stderr, "/charset [%s",
902 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
904 if (p + *p >= pend)
905 fprintf (stderr, " !extends past end of pattern! ");
907 for (c = 0; c < 256; c++)
908 if (c / 8 < length
909 && (p[1 + (c/8)] & (1 << (c % 8))))
911 /* Are we starting a range? */
912 if (last + 1 == c && ! in_range)
914 fprintf (stderr, "-");
915 in_range = 1;
917 /* Have we broken a range? */
918 else if (last + 1 != c && in_range)
920 fprintf (stderr, "%c", last);
921 in_range = 0;
924 if (! in_range)
925 fprintf (stderr, "%c", c);
927 last = c;
930 if (in_range)
931 fprintf (stderr, "%c", last);
933 fprintf (stderr, "]");
935 p += 1 + length;
937 if (has_range_table)
939 int count;
940 fprintf (stderr, "has-range-table");
942 /* ??? Should print the range table; for now, just skip it. */
943 p += 2; /* skip range table bits */
944 EXTRACT_NUMBER_AND_INCR (count, p);
945 p = CHARSET_RANGE_TABLE_END (p, count);
948 break;
950 case begline:
951 fprintf (stderr, "/begline");
952 break;
954 case endline:
955 fprintf (stderr, "/endline");
956 break;
958 case on_failure_jump:
959 EXTRACT_NUMBER_AND_INCR (mcnt, p);
960 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
961 break;
963 case on_failure_keep_string_jump:
964 EXTRACT_NUMBER_AND_INCR (mcnt, p);
965 fprintf (stderr, "/on_failure_keep_string_jump to %td",
966 p + mcnt - start);
967 break;
969 case on_failure_jump_nastyloop:
970 EXTRACT_NUMBER_AND_INCR (mcnt, p);
971 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
972 p + mcnt - start);
973 break;
975 case on_failure_jump_loop:
976 EXTRACT_NUMBER_AND_INCR (mcnt, p);
977 fprintf (stderr, "/on_failure_jump_loop to %td",
978 p + mcnt - start);
979 break;
981 case on_failure_jump_smart:
982 EXTRACT_NUMBER_AND_INCR (mcnt, p);
983 fprintf (stderr, "/on_failure_jump_smart to %td",
984 p + mcnt - start);
985 break;
987 case jump:
988 EXTRACT_NUMBER_AND_INCR (mcnt, p);
989 fprintf (stderr, "/jump to %td", p + mcnt - start);
990 break;
992 case succeed_n:
993 EXTRACT_NUMBER_AND_INCR (mcnt, p);
994 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
995 fprintf (stderr, "/succeed_n to %td, %d times",
996 p - 2 + mcnt - start, mcnt2);
997 break;
999 case jump_n:
1000 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1001 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1002 fprintf (stderr, "/jump_n to %td, %d times",
1003 p - 2 + mcnt - start, mcnt2);
1004 break;
1006 case set_number_at:
1007 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1008 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1009 fprintf (stderr, "/set_number_at location %td to %d",
1010 p - 2 + mcnt - start, mcnt2);
1011 break;
1013 case wordbound:
1014 fprintf (stderr, "/wordbound");
1015 break;
1017 case notwordbound:
1018 fprintf (stderr, "/notwordbound");
1019 break;
1021 case wordbeg:
1022 fprintf (stderr, "/wordbeg");
1023 break;
1025 case wordend:
1026 fprintf (stderr, "/wordend");
1027 break;
1029 case symbeg:
1030 fprintf (stderr, "/symbeg");
1031 break;
1033 case symend:
1034 fprintf (stderr, "/symend");
1035 break;
1037 case syntaxspec:
1038 fprintf (stderr, "/syntaxspec");
1039 mcnt = *p++;
1040 fprintf (stderr, "/%d", mcnt);
1041 break;
1043 case notsyntaxspec:
1044 fprintf (stderr, "/notsyntaxspec");
1045 mcnt = *p++;
1046 fprintf (stderr, "/%d", mcnt);
1047 break;
1049 # ifdef emacs
1050 case at_dot:
1051 fprintf (stderr, "/at_dot");
1052 break;
1054 case categoryspec:
1055 fprintf (stderr, "/categoryspec");
1056 mcnt = *p++;
1057 fprintf (stderr, "/%d", mcnt);
1058 break;
1060 case notcategoryspec:
1061 fprintf (stderr, "/notcategoryspec");
1062 mcnt = *p++;
1063 fprintf (stderr, "/%d", mcnt);
1064 break;
1065 # endif /* emacs */
1067 case begbuf:
1068 fprintf (stderr, "/begbuf");
1069 break;
1071 case endbuf:
1072 fprintf (stderr, "/endbuf");
1073 break;
1075 default:
1076 fprintf (stderr, "?%d", *(p-1));
1079 fprintf (stderr, "\n");
1082 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1086 static void
1087 print_compiled_pattern (struct re_pattern_buffer *bufp)
1089 re_char *buffer = bufp->buffer;
1091 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1092 printf ("%ld bytes used/%ld bytes allocated.\n",
1093 bufp->used, bufp->allocated);
1095 if (bufp->fastmap_accurate && bufp->fastmap)
1097 printf ("fastmap: ");
1098 print_fastmap (bufp->fastmap);
1101 printf ("re_nsub: %zu\t", bufp->re_nsub);
1102 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1103 printf ("can_be_null: %d\t", bufp->can_be_null);
1104 printf ("no_sub: %d\t", bufp->no_sub);
1105 printf ("not_bol: %d\t", bufp->not_bol);
1106 printf ("not_eol: %d\t", bufp->not_eol);
1107 #ifndef emacs
1108 printf ("syntax: %lx\n", bufp->syntax);
1109 #endif
1110 fflush (stdout);
1111 /* Perhaps we should print the translate table? */
1115 static void
1116 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1117 re_char *string2, ssize_t size2)
1119 ssize_t this_char;
1121 if (where == NULL)
1122 printf ("(null)");
1123 else
1125 if (FIRST_STRING_P (where))
1127 for (this_char = where - string1; this_char < size1; this_char++)
1128 putchar (string1[this_char]);
1130 where = string2;
1133 for (this_char = where - string2; this_char < size2; this_char++)
1134 putchar (string2[this_char]);
1138 #else /* not DEBUG */
1140 # undef assert
1141 # define assert(e)
1143 # define DEBUG_STATEMENT(e)
1144 # define DEBUG_PRINT(...)
1145 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1146 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1148 #endif /* not DEBUG */
1150 #ifndef emacs
1152 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1153 also be assigned to arbitrarily: each pattern buffer stores its own
1154 syntax, so it can be changed between regex compilations. */
1155 /* This has no initializer because initialized variables in Emacs
1156 become read-only after dumping. */
1157 reg_syntax_t re_syntax_options;
1160 /* Specify the precise syntax of regexps for compilation. This provides
1161 for compatibility for various utilities which historically have
1162 different, incompatible syntaxes.
1164 The argument SYNTAX is a bit mask comprised of the various bits
1165 defined in regex.h. We return the old syntax. */
1167 reg_syntax_t
1168 re_set_syntax (reg_syntax_t syntax)
1170 reg_syntax_t ret = re_syntax_options;
1172 re_syntax_options = syntax;
1173 return ret;
1175 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1177 #endif
1179 /* This table gives an error message for each of the error codes listed
1180 in regex.h. Obviously the order here has to be same as there.
1181 POSIX doesn't require that we do anything for REG_NOERROR,
1182 but why not be nice? */
1184 static const char *re_error_msgid[] =
1186 gettext_noop ("Success"), /* REG_NOERROR */
1187 gettext_noop ("No match"), /* REG_NOMATCH */
1188 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1189 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1190 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1191 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1192 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1193 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1194 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1195 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1196 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1197 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1198 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1199 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1200 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1201 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1202 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1203 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1206 /* Whether to allocate memory during matching. */
1208 /* Define MATCH_MAY_ALLOCATE to allow the searching and matching
1209 functions allocate memory for the failure stack and registers.
1210 Normally should be defined, because otherwise searching and
1211 matching routines will have much smaller memory resources at their
1212 disposal, and therefore might fail to handle complex regexps.
1213 Therefore undefine MATCH_MAY_ALLOCATE only in the following
1214 exceptional situations:
1216 . When running on a system where memory is at premium.
1217 . When alloca cannot be used at all, perhaps due to bugs in
1218 its implementation, or its being unavailable, or due to a
1219 very small stack size. This requires to define REGEX_MALLOC
1220 to use malloc instead, which in turn could lead to memory
1221 leaks if search is interrupted by a signal. (For these
1222 reasons, defining REGEX_MALLOC when building Emacs
1223 automatically undefines MATCH_MAY_ALLOCATE, but outside
1224 Emacs you may not care about memory leaks.) If you want to
1225 prevent the memory leaks, undefine MATCH_MAY_ALLOCATE.
1226 . When code that calls the searching and matching functions
1227 cannot allow memory allocation, for whatever reasons. */
1229 /* Normally, this is fine. */
1230 #define MATCH_MAY_ALLOCATE
1232 /* The match routines may not allocate if (1) they would do it with malloc
1233 and (2) it's not safe for them to use malloc.
1234 Note that if REL_ALLOC is defined, matching would not use malloc for the
1235 failure stack, but we would still use it for the register vectors;
1236 so REL_ALLOC should not affect this. */
1237 #if defined REGEX_MALLOC && defined emacs
1238 # undef MATCH_MAY_ALLOCATE
1239 #endif
1242 /* Failure stack declarations and macros; both re_compile_fastmap and
1243 re_match_2 use a failure stack. These have to be macros because of
1244 REGEX_ALLOCATE_STACK. */
1247 /* Approximate number of failure points for which to initially allocate space
1248 when matching. If this number is exceeded, we allocate more
1249 space, so it is not a hard limit. */
1250 #ifndef INIT_FAILURE_ALLOC
1251 # define INIT_FAILURE_ALLOC 20
1252 #endif
1254 /* Roughly the maximum number of failure points on the stack. Would be
1255 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1256 This is a variable only so users of regex can assign to it; we never
1257 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1258 before using it, so it should probably be a byte-count instead. */
1259 # if defined MATCH_MAY_ALLOCATE
1260 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1261 whose default stack limit is 2mb. In order for a larger
1262 value to work reliably, you have to try to make it accord
1263 with the process stack limit. */
1264 size_t emacs_re_max_failures = 40000;
1265 # else
1266 size_t emacs_re_max_failures = 4000;
1267 # endif
1269 union fail_stack_elt
1271 re_char *pointer;
1272 /* This should be the biggest `int' that's no bigger than a pointer. */
1273 long integer;
1276 typedef union fail_stack_elt fail_stack_elt_t;
1278 typedef struct
1280 fail_stack_elt_t *stack;
1281 size_t size;
1282 size_t avail; /* Offset of next open position. */
1283 size_t frame; /* Offset of the cur constructed frame. */
1284 } fail_stack_type;
1286 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1289 /* Define macros to initialize and free the failure stack.
1290 Do `return -2' if the alloc fails. */
1292 #ifdef MATCH_MAY_ALLOCATE
1293 # define INIT_FAIL_STACK() \
1294 do { \
1295 fail_stack.stack = \
1296 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1297 * sizeof (fail_stack_elt_t)); \
1299 if (fail_stack.stack == NULL) \
1300 return -2; \
1302 fail_stack.size = INIT_FAILURE_ALLOC; \
1303 fail_stack.avail = 0; \
1304 fail_stack.frame = 0; \
1305 } while (0)
1306 #else
1307 # define INIT_FAIL_STACK() \
1308 do { \
1309 fail_stack.avail = 0; \
1310 fail_stack.frame = 0; \
1311 } while (0)
1313 # define RETALLOC_IF(addr, n, t) \
1314 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1315 #endif
1318 /* Double the size of FAIL_STACK, up to a limit
1319 which allows approximately `emacs_re_max_failures' items.
1321 Return 1 if succeeds, and 0 if either ran out of memory
1322 allocating space for it or it was already too large.
1324 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1326 /* Factor to increase the failure stack size by
1327 when we increase it.
1328 This used to be 2, but 2 was too wasteful
1329 because the old discarded stacks added up to as much space
1330 were as ultimate, maximum-size stack. */
1331 #define FAIL_STACK_GROWTH_FACTOR 4
1333 #define GROW_FAIL_STACK(fail_stack) \
1334 (((fail_stack).size >= emacs_re_max_failures * TYPICAL_FAILURE_SIZE) \
1335 ? 0 \
1336 : ((fail_stack).stack \
1337 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1338 (fail_stack).size * sizeof (fail_stack_elt_t), \
1339 min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1340 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR)) \
1341 * sizeof (fail_stack_elt_t)), \
1343 (fail_stack).stack == NULL \
1344 ? 0 \
1345 : ((fail_stack).size \
1346 = (min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1347 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR))), \
1348 1)))
1351 /* Push a pointer value onto the failure stack.
1352 Assumes the variable `fail_stack'. Probably should only
1353 be called from within `PUSH_FAILURE_POINT'. */
1354 #define PUSH_FAILURE_POINTER(item) \
1355 fail_stack.stack[fail_stack.avail++].pointer = (item)
1357 /* This pushes an integer-valued item onto the failure stack.
1358 Assumes the variable `fail_stack'. Probably should only
1359 be called from within `PUSH_FAILURE_POINT'. */
1360 #define PUSH_FAILURE_INT(item) \
1361 fail_stack.stack[fail_stack.avail++].integer = (item)
1363 /* These POP... operations complement the PUSH... operations.
1364 All assume that `fail_stack' is nonempty. */
1365 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1366 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1368 /* Individual items aside from the registers. */
1369 #define NUM_NONREG_ITEMS 3
1371 /* Used to examine the stack (to detect infinite loops). */
1372 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1373 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1374 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1375 #define TOP_FAILURE_HANDLE() fail_stack.frame
1378 #define ENSURE_FAIL_STACK(space) \
1379 while (REMAINING_AVAIL_SLOTS <= space) { \
1380 if (!GROW_FAIL_STACK (fail_stack)) \
1381 return -2; \
1382 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1383 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1386 /* Push register NUM onto the stack. */
1387 #define PUSH_FAILURE_REG(num) \
1388 do { \
1389 char *destination; \
1390 long n = num; \
1391 ENSURE_FAIL_STACK(3); \
1392 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1393 n, regstart[n], regend[n]); \
1394 PUSH_FAILURE_POINTER (regstart[n]); \
1395 PUSH_FAILURE_POINTER (regend[n]); \
1396 PUSH_FAILURE_INT (n); \
1397 } while (0)
1399 /* Change the counter's value to VAL, but make sure that it will
1400 be reset when backtracking. */
1401 #define PUSH_NUMBER(ptr,val) \
1402 do { \
1403 char *destination; \
1404 int c; \
1405 ENSURE_FAIL_STACK(3); \
1406 EXTRACT_NUMBER (c, ptr); \
1407 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1408 PUSH_FAILURE_INT (c); \
1409 PUSH_FAILURE_POINTER (ptr); \
1410 PUSH_FAILURE_INT (-1); \
1411 STORE_NUMBER (ptr, val); \
1412 } while (0)
1414 /* Pop a saved register off the stack. */
1415 #define POP_FAILURE_REG_OR_COUNT() \
1416 do { \
1417 long pfreg = POP_FAILURE_INT (); \
1418 if (pfreg == -1) \
1420 /* It's a counter. */ \
1421 /* Here, we discard `const', making re_match non-reentrant. */ \
1422 unsigned char *ptr = (unsigned char *) POP_FAILURE_POINTER (); \
1423 pfreg = POP_FAILURE_INT (); \
1424 STORE_NUMBER (ptr, pfreg); \
1425 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1427 else \
1429 regend[pfreg] = POP_FAILURE_POINTER (); \
1430 regstart[pfreg] = POP_FAILURE_POINTER (); \
1431 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1432 pfreg, regstart[pfreg], regend[pfreg]); \
1434 } while (0)
1436 /* Check that we are not stuck in an infinite loop. */
1437 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1438 do { \
1439 ssize_t failure = TOP_FAILURE_HANDLE (); \
1440 /* Check for infinite matching loops */ \
1441 while (failure > 0 \
1442 && (FAILURE_STR (failure) == string_place \
1443 || FAILURE_STR (failure) == NULL)) \
1445 assert (FAILURE_PAT (failure) >= bufp->buffer \
1446 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1447 if (FAILURE_PAT (failure) == pat_cur) \
1449 cycle = 1; \
1450 break; \
1452 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1453 failure = NEXT_FAILURE_HANDLE(failure); \
1455 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1456 } while (0)
1458 /* Push the information about the state we will need
1459 if we ever fail back to it.
1461 Requires variables fail_stack, regstart, regend and
1462 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1463 declared.
1465 Does `return FAILURE_CODE' if runs out of memory. */
1467 #define PUSH_FAILURE_POINT(pattern, string_place) \
1468 do { \
1469 char *destination; \
1470 /* Must be int, so when we don't save any registers, the arithmetic \
1471 of 0 + -1 isn't done as unsigned. */ \
1473 DEBUG_STATEMENT (nfailure_points_pushed++); \
1474 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1475 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1476 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1478 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1480 DEBUG_PRINT ("\n"); \
1482 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1483 PUSH_FAILURE_INT (fail_stack.frame); \
1485 DEBUG_PRINT (" Push string %p: \"", string_place); \
1486 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1487 DEBUG_PRINT ("\"\n"); \
1488 PUSH_FAILURE_POINTER (string_place); \
1490 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1491 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1492 PUSH_FAILURE_POINTER (pattern); \
1494 /* Close the frame by moving the frame pointer past it. */ \
1495 fail_stack.frame = fail_stack.avail; \
1496 } while (0)
1498 /* Estimate the size of data pushed by a typical failure stack entry.
1499 An estimate is all we need, because all we use this for
1500 is to choose a limit for how big to make the failure stack. */
1501 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1502 #define TYPICAL_FAILURE_SIZE 20
1504 /* How many items can still be added to the stack without overflowing it. */
1505 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1508 /* Pops what PUSH_FAIL_STACK pushes.
1510 We restore into the parameters, all of which should be lvalues:
1511 STR -- the saved data position.
1512 PAT -- the saved pattern position.
1513 REGSTART, REGEND -- arrays of string positions.
1515 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1516 `pend', `string1', `size1', `string2', and `size2'. */
1518 #define POP_FAILURE_POINT(str, pat) \
1519 do { \
1520 assert (!FAIL_STACK_EMPTY ()); \
1522 /* Remove failure points and point to how many regs pushed. */ \
1523 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1524 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1525 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1527 /* Pop the saved registers. */ \
1528 while (fail_stack.frame < fail_stack.avail) \
1529 POP_FAILURE_REG_OR_COUNT (); \
1531 pat = POP_FAILURE_POINTER (); \
1532 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1533 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1535 /* If the saved string location is NULL, it came from an \
1536 on_failure_keep_string_jump opcode, and we want to throw away the \
1537 saved NULL, thus retaining our current position in the string. */ \
1538 str = POP_FAILURE_POINTER (); \
1539 DEBUG_PRINT (" Popping string %p: \"", str); \
1540 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1541 DEBUG_PRINT ("\"\n"); \
1543 fail_stack.frame = POP_FAILURE_INT (); \
1544 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1546 assert (fail_stack.avail >= 0); \
1547 assert (fail_stack.frame <= fail_stack.avail); \
1549 DEBUG_STATEMENT (nfailure_points_popped++); \
1550 } while (0) /* POP_FAILURE_POINT */
1554 /* Registers are set to a sentinel when they haven't yet matched. */
1555 #define REG_UNSET(e) ((e) == NULL)
1557 /* Subroutine declarations and macros for regex_compile. */
1559 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1560 #ifdef emacs
1561 bool posix_backtracking,
1562 const char *whitespace_regexp,
1563 #else
1564 reg_syntax_t syntax,
1565 #endif
1566 struct re_pattern_buffer *bufp);
1567 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1568 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1569 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1570 int arg, unsigned char *end);
1571 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1572 int arg1, int arg2, unsigned char *end);
1573 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1574 reg_syntax_t syntax);
1575 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1576 reg_syntax_t syntax);
1577 static re_char *skip_one_char (re_char *p);
1578 static int analyze_first (re_char *p, re_char *pend,
1579 char *fastmap, const int multibyte);
1581 /* Fetch the next character in the uncompiled pattern, with no
1582 translation. */
1583 #define PATFETCH(c) \
1584 do { \
1585 int len; \
1586 if (p == pend) return REG_EEND; \
1587 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1588 p += len; \
1589 } while (0)
1592 /* If `translate' is non-null, return translate[D], else just D. We
1593 cast the subscript to translate because some data is declared as
1594 `char *', to avoid warnings when a string constant is passed. But
1595 when we use a character as a subscript we must make it unsigned. */
1596 #ifndef TRANSLATE
1597 # define TRANSLATE(d) \
1598 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1599 #endif
1602 /* Macros for outputting the compiled pattern into `buffer'. */
1604 /* If the buffer isn't allocated when it comes in, use this. */
1605 #define INIT_BUF_SIZE 32
1607 /* Make sure we have at least N more bytes of space in buffer. */
1608 #define GET_BUFFER_SPACE(n) \
1609 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1610 EXTEND_BUFFER ()
1612 /* Make sure we have one more byte of buffer space and then add C to it. */
1613 #define BUF_PUSH(c) \
1614 do { \
1615 GET_BUFFER_SPACE (1); \
1616 *b++ = (unsigned char) (c); \
1617 } while (0)
1620 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1621 #define BUF_PUSH_2(c1, c2) \
1622 do { \
1623 GET_BUFFER_SPACE (2); \
1624 *b++ = (unsigned char) (c1); \
1625 *b++ = (unsigned char) (c2); \
1626 } while (0)
1629 /* Store a jump with opcode OP at LOC to location TO. We store a
1630 relative address offset by the three bytes the jump itself occupies. */
1631 #define STORE_JUMP(op, loc, to) \
1632 store_op1 (op, loc, (to) - (loc) - 3)
1634 /* Likewise, for a two-argument jump. */
1635 #define STORE_JUMP2(op, loc, to, arg) \
1636 store_op2 (op, loc, (to) - (loc) - 3, arg)
1638 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1639 #define INSERT_JUMP(op, loc, to) \
1640 insert_op1 (op, loc, (to) - (loc) - 3, b)
1642 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1643 #define INSERT_JUMP2(op, loc, to, arg) \
1644 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1647 /* This is not an arbitrary limit: the arguments which represent offsets
1648 into the pattern are two bytes long. So if 2^15 bytes turns out to
1649 be too small, many things would have to change. */
1650 # define MAX_BUF_SIZE (1L << 15)
1652 /* Extend the buffer by twice its current size via realloc and
1653 reset the pointers that pointed into the old block to point to the
1654 correct places in the new one. If extending the buffer results in it
1655 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1656 #define EXTEND_BUFFER() \
1657 do { \
1658 unsigned char *old_buffer = bufp->buffer; \
1659 if (bufp->allocated == MAX_BUF_SIZE) \
1660 return REG_ESIZE; \
1661 bufp->allocated <<= 1; \
1662 if (bufp->allocated > MAX_BUF_SIZE) \
1663 bufp->allocated = MAX_BUF_SIZE; \
1664 ptrdiff_t b_off = b - old_buffer; \
1665 ptrdiff_t begalt_off = begalt - old_buffer; \
1666 bool fixup_alt_jump_set = !!fixup_alt_jump; \
1667 bool laststart_set = !!laststart; \
1668 bool pending_exact_set = !!pending_exact; \
1669 ptrdiff_t fixup_alt_jump_off, laststart_off, pending_exact_off; \
1670 if (fixup_alt_jump_set) fixup_alt_jump_off = fixup_alt_jump - old_buffer; \
1671 if (laststart_set) laststart_off = laststart - old_buffer; \
1672 if (pending_exact_set) pending_exact_off = pending_exact - old_buffer; \
1673 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1674 if (bufp->buffer == NULL) \
1675 return REG_ESPACE; \
1676 unsigned char *new_buffer = bufp->buffer; \
1677 b = new_buffer + b_off; \
1678 begalt = new_buffer + begalt_off; \
1679 if (fixup_alt_jump_set) fixup_alt_jump = new_buffer + fixup_alt_jump_off; \
1680 if (laststart_set) laststart = new_buffer + laststart_off; \
1681 if (pending_exact_set) pending_exact = new_buffer + pending_exact_off; \
1682 } while (0)
1685 /* Since we have one byte reserved for the register number argument to
1686 {start,stop}_memory, the maximum number of groups we can report
1687 things about is what fits in that byte. */
1688 #define MAX_REGNUM 255
1690 /* But patterns can have more than `MAX_REGNUM' registers. We just
1691 ignore the excess. */
1692 typedef int regnum_t;
1695 /* Macros for the compile stack. */
1697 /* Since offsets can go either forwards or backwards, this type needs to
1698 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1699 /* int may be not enough when sizeof(int) == 2. */
1700 typedef long pattern_offset_t;
1702 typedef struct
1704 pattern_offset_t begalt_offset;
1705 pattern_offset_t fixup_alt_jump;
1706 pattern_offset_t laststart_offset;
1707 regnum_t regnum;
1708 } compile_stack_elt_t;
1711 typedef struct
1713 compile_stack_elt_t *stack;
1714 size_t size;
1715 size_t avail; /* Offset of next open position. */
1716 } compile_stack_type;
1719 #define INIT_COMPILE_STACK_SIZE 32
1721 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1722 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1724 /* The next available element. */
1725 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1727 /* Explicit quit checking is needed for Emacs, which uses polling to
1728 process input events. */
1729 #ifndef emacs
1730 static void maybe_quit (void) {}
1731 #endif
1733 /* Structure to manage work area for range table. */
1734 struct range_table_work_area
1736 int *table; /* actual work area. */
1737 int allocated; /* allocated size for work area in bytes. */
1738 int used; /* actually used size in words. */
1739 int bits; /* flag to record character classes */
1742 #ifdef emacs
1744 /* Make sure that WORK_AREA can hold more N multibyte characters.
1745 This is used only in set_image_of_range and set_image_of_range_1.
1746 It expects WORK_AREA to be a pointer.
1747 If it can't get the space, it returns from the surrounding function. */
1749 #define EXTEND_RANGE_TABLE(work_area, n) \
1750 do { \
1751 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1753 extend_range_table_work_area (&work_area); \
1754 if ((work_area).table == 0) \
1755 return (REG_ESPACE); \
1757 } while (0)
1759 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1760 (work_area).bits |= (bit)
1762 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1763 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1764 do { \
1765 EXTEND_RANGE_TABLE ((work_area), 2); \
1766 (work_area).table[(work_area).used++] = (range_start); \
1767 (work_area).table[(work_area).used++] = (range_end); \
1768 } while (0)
1770 #endif /* emacs */
1772 /* Free allocated memory for WORK_AREA. */
1773 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1774 do { \
1775 if ((work_area).table) \
1776 free ((work_area).table); \
1777 } while (0)
1779 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1780 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1781 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1782 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1784 /* Bits used to implement the multibyte-part of the various character classes
1785 such as [:alnum:] in a charset's range table. The code currently assumes
1786 that only the low 16 bits are used. */
1787 #define BIT_WORD 0x1
1788 #define BIT_LOWER 0x2
1789 #define BIT_PUNCT 0x4
1790 #define BIT_SPACE 0x8
1791 #define BIT_UPPER 0x10
1792 #define BIT_MULTIBYTE 0x20
1793 #define BIT_ALPHA 0x40
1794 #define BIT_ALNUM 0x80
1795 #define BIT_GRAPH 0x100
1796 #define BIT_PRINT 0x200
1797 #define BIT_BLANK 0x400
1800 /* Set the bit for character C in a list. */
1801 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1804 #ifdef emacs
1806 /* Store characters in the range FROM to TO in the bitmap at B (for
1807 ASCII and unibyte characters) and WORK_AREA (for multibyte
1808 characters) while translating them and paying attention to the
1809 continuity of translated characters.
1811 Implementation note: It is better to implement these fairly big
1812 macros by a function, but it's not that easy because macros called
1813 in this macro assume various local variables already declared. */
1815 /* Both FROM and TO are ASCII characters. */
1817 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1818 do { \
1819 int C0, C1; \
1821 for (C0 = (FROM); C0 <= (TO); C0++) \
1823 C1 = TRANSLATE (C0); \
1824 if (! ASCII_CHAR_P (C1)) \
1826 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1827 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1828 C1 = C0; \
1830 SET_LIST_BIT (C1); \
1832 } while (0)
1835 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1837 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1838 do { \
1839 int C0, C1, C2, I; \
1840 int USED = RANGE_TABLE_WORK_USED (work_area); \
1842 for (C0 = (FROM); C0 <= (TO); C0++) \
1844 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1845 if (CHAR_BYTE8_P (C1)) \
1846 SET_LIST_BIT (C0); \
1847 else \
1849 C2 = TRANSLATE (C1); \
1850 if (C2 == C1 \
1851 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1852 C1 = C0; \
1853 SET_LIST_BIT (C1); \
1854 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1856 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1857 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1859 if (C2 >= from - 1 && C2 <= to + 1) \
1861 if (C2 == from - 1) \
1862 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1863 else if (C2 == to + 1) \
1864 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1865 break; \
1868 if (I < USED) \
1869 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1872 } while (0)
1875 /* Both FROM and TO are multibyte characters. */
1877 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1878 do { \
1879 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1881 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1882 for (C0 = (FROM); C0 <= (TO); C0++) \
1884 C1 = TRANSLATE (C0); \
1885 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1886 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1887 SET_LIST_BIT (C2); \
1888 if (C1 >= (FROM) && C1 <= (TO)) \
1889 continue; \
1890 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1892 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1893 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1895 if (C1 >= from - 1 && C1 <= to + 1) \
1897 if (C1 == from - 1) \
1898 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1899 else if (C1 == to + 1) \
1900 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1901 break; \
1904 if (I < USED) \
1905 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1907 } while (0)
1909 #endif /* emacs */
1911 /* Get the next unsigned number in the uncompiled pattern. */
1912 #define GET_INTERVAL_COUNT(num) \
1913 do { \
1914 if (p == pend) \
1915 FREE_STACK_RETURN (REG_EBRACE); \
1916 else \
1918 PATFETCH (c); \
1919 while ('0' <= c && c <= '9') \
1921 if (num < 0) \
1922 num = 0; \
1923 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
1924 FREE_STACK_RETURN (REG_BADBR); \
1925 num = num * 10 + c - '0'; \
1926 if (p == pend) \
1927 FREE_STACK_RETURN (REG_EBRACE); \
1928 PATFETCH (c); \
1931 } while (0)
1933 #if ! WIDE_CHAR_SUPPORT
1935 /* Parse a character class, i.e. string such as "[:name:]". *strp
1936 points to the string to be parsed and limit is length, in bytes, of
1937 that string.
1939 If *strp point to a string that begins with "[:name:]", where name is
1940 a non-empty sequence of lower case letters, *strp will be advanced past the
1941 closing square bracket and RECC_* constant which maps to the name will be
1942 returned. If name is not a valid character class name zero, or RECC_ERROR,
1943 is returned.
1945 Otherwise, if *strp doesn't begin with "[:name:]", -1 is returned.
1947 The function can be used on ASCII and multibyte (UTF-8-encoded) strings.
1949 re_wctype_t
1950 re_wctype_parse (const unsigned char **strp, unsigned limit)
1952 const char *beg = (const char *)*strp, *it;
1954 if (limit < 4 || beg[0] != '[' || beg[1] != ':')
1955 return -1;
1957 beg += 2; /* skip opening "[:" */
1958 limit -= 3; /* opening "[:" and half of closing ":]"; --limit handles rest */
1959 for (it = beg; it[0] != ':' || it[1] != ']'; ++it)
1960 if (!--limit)
1961 return -1;
1963 *strp = (const unsigned char *)(it + 2);
1965 /* Sort tests in the length=five case by frequency the classes to minimize
1966 number of times we fail the comparison. The frequencies of character class
1967 names used in Emacs sources as of 2016-07-27:
1969 $ find \( -name \*.c -o -name \*.el \) -exec grep -h '\[:[a-z]*:]' {} + |
1970 sed 's/]/]\n/g' |grep -o '\[:[a-z]*:]' |sort |uniq -c |sort -nr
1971 213 [:alnum:]
1972 104 [:alpha:]
1973 62 [:space:]
1974 39 [:digit:]
1975 36 [:blank:]
1976 26 [:word:]
1977 26 [:upper:]
1978 21 [:lower:]
1979 10 [:xdigit:]
1980 10 [:punct:]
1981 10 [:ascii:]
1982 4 [:nonascii:]
1983 4 [:graph:]
1984 2 [:print:]
1985 2 [:cntrl:]
1986 1 [:ff:]
1988 If you update this list, consider also updating chain of or'ed conditions
1989 in execute_charset function.
1992 switch (it - beg) {
1993 case 4:
1994 if (!memcmp (beg, "word", 4)) return RECC_WORD;
1995 break;
1996 case 5:
1997 if (!memcmp (beg, "alnum", 5)) return RECC_ALNUM;
1998 if (!memcmp (beg, "alpha", 5)) return RECC_ALPHA;
1999 if (!memcmp (beg, "space", 5)) return RECC_SPACE;
2000 if (!memcmp (beg, "digit", 5)) return RECC_DIGIT;
2001 if (!memcmp (beg, "blank", 5)) return RECC_BLANK;
2002 if (!memcmp (beg, "upper", 5)) return RECC_UPPER;
2003 if (!memcmp (beg, "lower", 5)) return RECC_LOWER;
2004 if (!memcmp (beg, "punct", 5)) return RECC_PUNCT;
2005 if (!memcmp (beg, "ascii", 5)) return RECC_ASCII;
2006 if (!memcmp (beg, "graph", 5)) return RECC_GRAPH;
2007 if (!memcmp (beg, "print", 5)) return RECC_PRINT;
2008 if (!memcmp (beg, "cntrl", 5)) return RECC_CNTRL;
2009 break;
2010 case 6:
2011 if (!memcmp (beg, "xdigit", 6)) return RECC_XDIGIT;
2012 break;
2013 case 7:
2014 if (!memcmp (beg, "unibyte", 7)) return RECC_UNIBYTE;
2015 break;
2016 case 8:
2017 if (!memcmp (beg, "nonascii", 8)) return RECC_NONASCII;
2018 break;
2019 case 9:
2020 if (!memcmp (beg, "multibyte", 9)) return RECC_MULTIBYTE;
2021 break;
2024 return RECC_ERROR;
2027 /* True if CH is in the char class CC. */
2028 boolean
2029 re_iswctype (int ch, re_wctype_t cc)
2031 switch (cc)
2033 case RECC_ALNUM: return ISALNUM (ch) != 0;
2034 case RECC_ALPHA: return ISALPHA (ch) != 0;
2035 case RECC_BLANK: return ISBLANK (ch) != 0;
2036 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2037 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2038 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2039 case RECC_LOWER: return ISLOWER (ch) != 0;
2040 case RECC_PRINT: return ISPRINT (ch) != 0;
2041 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2042 case RECC_SPACE: return ISSPACE (ch) != 0;
2043 case RECC_UPPER: return ISUPPER (ch) != 0;
2044 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2045 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2046 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2047 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2048 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2049 case RECC_WORD: return ISWORD (ch) != 0;
2050 case RECC_ERROR: return false;
2051 default:
2052 abort ();
2056 /* Return a bit-pattern to use in the range-table bits to match multibyte
2057 chars of class CC. */
2058 static int
2059 re_wctype_to_bit (re_wctype_t cc)
2061 switch (cc)
2063 case RECC_NONASCII:
2064 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2065 case RECC_ALPHA: return BIT_ALPHA;
2066 case RECC_ALNUM: return BIT_ALNUM;
2067 case RECC_WORD: return BIT_WORD;
2068 case RECC_LOWER: return BIT_LOWER;
2069 case RECC_UPPER: return BIT_UPPER;
2070 case RECC_PUNCT: return BIT_PUNCT;
2071 case RECC_SPACE: return BIT_SPACE;
2072 case RECC_GRAPH: return BIT_GRAPH;
2073 case RECC_PRINT: return BIT_PRINT;
2074 case RECC_BLANK: return BIT_BLANK;
2075 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2076 case RECC_UNIBYTE: case RECC_ERROR: return 0;
2077 default:
2078 abort ();
2081 #endif
2083 /* Filling in the work area of a range. */
2085 /* Actually extend the space in WORK_AREA. */
2087 static void
2088 extend_range_table_work_area (struct range_table_work_area *work_area)
2090 work_area->allocated += 16 * sizeof (int);
2091 work_area->table = realloc (work_area->table, work_area->allocated);
2094 #if 0
2095 #ifdef emacs
2097 /* Carefully find the ranges of codes that are equivalent
2098 under case conversion to the range start..end when passed through
2099 TRANSLATE. Handle the case where non-letters can come in between
2100 two upper-case letters (which happens in Latin-1).
2101 Also handle the case of groups of more than 2 case-equivalent chars.
2103 The basic method is to look at consecutive characters and see
2104 if they can form a run that can be handled as one.
2106 Returns -1 if successful, REG_ESPACE if ran out of space. */
2108 static int
2109 set_image_of_range_1 (struct range_table_work_area *work_area,
2110 re_wchar_t start, re_wchar_t end,
2111 RE_TRANSLATE_TYPE translate)
2113 /* `one_case' indicates a character, or a run of characters,
2114 each of which is an isolate (no case-equivalents).
2115 This includes all ASCII non-letters.
2117 `two_case' indicates a character, or a run of characters,
2118 each of which has two case-equivalent forms.
2119 This includes all ASCII letters.
2121 `strange' indicates a character that has more than one
2122 case-equivalent. */
2124 enum case_type {one_case, two_case, strange};
2126 /* Describe the run that is in progress,
2127 which the next character can try to extend.
2128 If run_type is strange, that means there really is no run.
2129 If run_type is one_case, then run_start...run_end is the run.
2130 If run_type is two_case, then the run is run_start...run_end,
2131 and the case-equivalents end at run_eqv_end. */
2133 enum case_type run_type = strange;
2134 int run_start, run_end, run_eqv_end;
2136 Lisp_Object eqv_table;
2138 if (!RE_TRANSLATE_P (translate))
2140 EXTEND_RANGE_TABLE (work_area, 2);
2141 work_area->table[work_area->used++] = (start);
2142 work_area->table[work_area->used++] = (end);
2143 return -1;
2146 eqv_table = XCHAR_TABLE (translate)->extras[2];
2148 for (; start <= end; start++)
2150 enum case_type this_type;
2151 int eqv = RE_TRANSLATE (eqv_table, start);
2152 int minchar, maxchar;
2154 /* Classify this character */
2155 if (eqv == start)
2156 this_type = one_case;
2157 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2158 this_type = two_case;
2159 else
2160 this_type = strange;
2162 if (start < eqv)
2163 minchar = start, maxchar = eqv;
2164 else
2165 minchar = eqv, maxchar = start;
2167 /* Can this character extend the run in progress? */
2168 if (this_type == strange || this_type != run_type
2169 || !(minchar == run_end + 1
2170 && (run_type == two_case
2171 ? maxchar == run_eqv_end + 1 : 1)))
2173 /* No, end the run.
2174 Record each of its equivalent ranges. */
2175 if (run_type == one_case)
2177 EXTEND_RANGE_TABLE (work_area, 2);
2178 work_area->table[work_area->used++] = run_start;
2179 work_area->table[work_area->used++] = run_end;
2181 else if (run_type == two_case)
2183 EXTEND_RANGE_TABLE (work_area, 4);
2184 work_area->table[work_area->used++] = run_start;
2185 work_area->table[work_area->used++] = run_end;
2186 work_area->table[work_area->used++]
2187 = RE_TRANSLATE (eqv_table, run_start);
2188 work_area->table[work_area->used++]
2189 = RE_TRANSLATE (eqv_table, run_end);
2191 run_type = strange;
2194 if (this_type == strange)
2196 /* For a strange character, add each of its equivalents, one
2197 by one. Don't start a range. */
2200 EXTEND_RANGE_TABLE (work_area, 2);
2201 work_area->table[work_area->used++] = eqv;
2202 work_area->table[work_area->used++] = eqv;
2203 eqv = RE_TRANSLATE (eqv_table, eqv);
2205 while (eqv != start);
2208 /* Add this char to the run, or start a new run. */
2209 else if (run_type == strange)
2211 /* Initialize a new range. */
2212 run_type = this_type;
2213 run_start = start;
2214 run_end = start;
2215 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2217 else
2219 /* Extend a running range. */
2220 run_end = minchar;
2221 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2225 /* If a run is still in progress at the end, finish it now
2226 by recording its equivalent ranges. */
2227 if (run_type == one_case)
2229 EXTEND_RANGE_TABLE (work_area, 2);
2230 work_area->table[work_area->used++] = run_start;
2231 work_area->table[work_area->used++] = run_end;
2233 else if (run_type == two_case)
2235 EXTEND_RANGE_TABLE (work_area, 4);
2236 work_area->table[work_area->used++] = run_start;
2237 work_area->table[work_area->used++] = run_end;
2238 work_area->table[work_area->used++]
2239 = RE_TRANSLATE (eqv_table, run_start);
2240 work_area->table[work_area->used++]
2241 = RE_TRANSLATE (eqv_table, run_end);
2244 return -1;
2247 #endif /* emacs */
2249 /* Record the image of the range start..end when passed through
2250 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2251 and is not even necessarily contiguous.
2252 Normally we approximate it with the smallest contiguous range that contains
2253 all the chars we need. However, for Latin-1 we go to extra effort
2254 to do a better job.
2256 This function is not called for ASCII ranges.
2258 Returns -1 if successful, REG_ESPACE if ran out of space. */
2260 static int
2261 set_image_of_range (struct range_table_work_area *work_area,
2262 re_wchar_t start, re_wchar_t end,
2263 RE_TRANSLATE_TYPE translate)
2265 re_wchar_t cmin, cmax;
2267 #ifdef emacs
2268 /* For Latin-1 ranges, use set_image_of_range_1
2269 to get proper handling of ranges that include letters and nonletters.
2270 For a range that includes the whole of Latin-1, this is not necessary.
2271 For other character sets, we don't bother to get this right. */
2272 if (RE_TRANSLATE_P (translate) && start < 04400
2273 && !(start < 04200 && end >= 04377))
2275 int newend;
2276 int tem;
2277 newend = end;
2278 if (newend > 04377)
2279 newend = 04377;
2280 tem = set_image_of_range_1 (work_area, start, newend, translate);
2281 if (tem > 0)
2282 return tem;
2284 start = 04400;
2285 if (end < 04400)
2286 return -1;
2288 #endif
2290 EXTEND_RANGE_TABLE (work_area, 2);
2291 work_area->table[work_area->used++] = (start);
2292 work_area->table[work_area->used++] = (end);
2294 cmin = -1, cmax = -1;
2296 if (RE_TRANSLATE_P (translate))
2298 int ch;
2300 for (ch = start; ch <= end; ch++)
2302 re_wchar_t c = TRANSLATE (ch);
2303 if (! (start <= c && c <= end))
2305 if (cmin == -1)
2306 cmin = c, cmax = c;
2307 else
2309 cmin = min (cmin, c);
2310 cmax = max (cmax, c);
2315 if (cmin != -1)
2317 EXTEND_RANGE_TABLE (work_area, 2);
2318 work_area->table[work_area->used++] = (cmin);
2319 work_area->table[work_area->used++] = (cmax);
2323 return -1;
2325 #endif /* 0 */
2327 #ifndef MATCH_MAY_ALLOCATE
2329 /* If we cannot allocate large objects within re_match_2_internal,
2330 we make the fail stack and register vectors global.
2331 The fail stack, we grow to the maximum size when a regexp
2332 is compiled.
2333 The register vectors, we adjust in size each time we
2334 compile a regexp, according to the number of registers it needs. */
2336 static fail_stack_type fail_stack;
2338 /* Size with which the following vectors are currently allocated.
2339 That is so we can make them bigger as needed,
2340 but never make them smaller. */
2341 static int regs_allocated_size;
2343 static re_char ** regstart, ** regend;
2344 static re_char **best_regstart, **best_regend;
2346 /* Make the register vectors big enough for NUM_REGS registers,
2347 but don't make them smaller. */
2349 static
2350 regex_grow_registers (int num_regs)
2352 if (num_regs > regs_allocated_size)
2354 RETALLOC_IF (regstart, num_regs, re_char *);
2355 RETALLOC_IF (regend, num_regs, re_char *);
2356 RETALLOC_IF (best_regstart, num_regs, re_char *);
2357 RETALLOC_IF (best_regend, num_regs, re_char *);
2359 regs_allocated_size = num_regs;
2363 #endif /* not MATCH_MAY_ALLOCATE */
2365 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2366 regnum_t regnum);
2368 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2369 Returns one of error codes defined in `regex.h', or zero for success.
2371 If WHITESPACE_REGEXP is given (only #ifdef emacs), it is used instead of
2372 a space character in PATTERN.
2374 Assumes the `allocated' (and perhaps `buffer') and `translate'
2375 fields are set in BUFP on entry.
2377 If it succeeds, results are put in BUFP (if it returns an error, the
2378 contents of BUFP are undefined):
2379 `buffer' is the compiled pattern;
2380 `syntax' is set to SYNTAX;
2381 `used' is set to the length of the compiled pattern;
2382 `fastmap_accurate' is zero;
2383 `re_nsub' is the number of subexpressions in PATTERN;
2384 `not_bol' and `not_eol' are zero;
2386 The `fastmap' field is neither examined nor set. */
2388 /* Insert the `jump' from the end of last alternative to "here".
2389 The space for the jump has already been allocated. */
2390 #define FIXUP_ALT_JUMP() \
2391 do { \
2392 if (fixup_alt_jump) \
2393 STORE_JUMP (jump, fixup_alt_jump, b); \
2394 } while (0)
2397 /* Return, freeing storage we allocated. */
2398 #define FREE_STACK_RETURN(value) \
2399 do { \
2400 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2401 free (compile_stack.stack); \
2402 return value; \
2403 } while (0)
2405 static reg_errcode_t
2406 regex_compile (const_re_char *pattern, size_t size,
2407 #ifdef emacs
2408 # define syntax RE_SYNTAX_EMACS
2409 bool posix_backtracking,
2410 const char *whitespace_regexp,
2411 #else
2412 reg_syntax_t syntax,
2413 # define posix_backtracking (!(syntax & RE_NO_POSIX_BACKTRACKING))
2414 #endif
2415 struct re_pattern_buffer *bufp)
2417 /* We fetch characters from PATTERN here. */
2418 register re_wchar_t c, c1;
2420 /* Points to the end of the buffer, where we should append. */
2421 register unsigned char *b;
2423 /* Keeps track of unclosed groups. */
2424 compile_stack_type compile_stack;
2426 /* Points to the current (ending) position in the pattern. */
2427 #ifdef AIX
2428 /* `const' makes AIX compiler fail. */
2429 unsigned char *p = pattern;
2430 #else
2431 re_char *p = pattern;
2432 #endif
2433 re_char *pend = pattern + size;
2435 /* How to translate the characters in the pattern. */
2436 RE_TRANSLATE_TYPE translate = bufp->translate;
2438 /* Address of the count-byte of the most recently inserted `exactn'
2439 command. This makes it possible to tell if a new exact-match
2440 character can be added to that command or if the character requires
2441 a new `exactn' command. */
2442 unsigned char *pending_exact = 0;
2444 /* Address of start of the most recently finished expression.
2445 This tells, e.g., postfix * where to find the start of its
2446 operand. Reset at the beginning of groups and alternatives. */
2447 unsigned char *laststart = 0;
2449 /* Address of beginning of regexp, or inside of last group. */
2450 unsigned char *begalt;
2452 /* Place in the uncompiled pattern (i.e., the {) to
2453 which to go back if the interval is invalid. */
2454 re_char *beg_interval;
2456 /* Address of the place where a forward jump should go to the end of
2457 the containing expression. Each alternative of an `or' -- except the
2458 last -- ends with a forward jump of this sort. */
2459 unsigned char *fixup_alt_jump = 0;
2461 /* Work area for range table of charset. */
2462 struct range_table_work_area range_table_work;
2464 /* If the object matched can contain multibyte characters. */
2465 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2467 #ifdef emacs
2468 /* Nonzero if we have pushed down into a subpattern. */
2469 int in_subpattern = 0;
2471 /* These hold the values of p, pattern, and pend from the main
2472 pattern when we have pushed into a subpattern. */
2473 re_char *main_p;
2474 re_char *main_pattern;
2475 re_char *main_pend;
2476 #endif
2478 #ifdef DEBUG
2479 debug++;
2480 DEBUG_PRINT ("\nCompiling pattern: ");
2481 if (debug > 0)
2483 unsigned debug_count;
2485 for (debug_count = 0; debug_count < size; debug_count++)
2486 putchar (pattern[debug_count]);
2487 putchar ('\n');
2489 #endif /* DEBUG */
2491 /* Initialize the compile stack. */
2492 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2493 if (compile_stack.stack == NULL)
2494 return REG_ESPACE;
2496 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2497 compile_stack.avail = 0;
2499 range_table_work.table = 0;
2500 range_table_work.allocated = 0;
2502 /* Initialize the pattern buffer. */
2503 #ifndef emacs
2504 bufp->syntax = syntax;
2505 #endif
2506 bufp->fastmap_accurate = 0;
2507 bufp->not_bol = bufp->not_eol = 0;
2508 bufp->used_syntax = 0;
2510 /* Set `used' to zero, so that if we return an error, the pattern
2511 printer (for debugging) will think there's no pattern. We reset it
2512 at the end. */
2513 bufp->used = 0;
2515 /* Always count groups, whether or not bufp->no_sub is set. */
2516 bufp->re_nsub = 0;
2518 #if !defined emacs && !defined SYNTAX_TABLE
2519 /* Initialize the syntax table. */
2520 init_syntax_once ();
2521 #endif
2523 if (bufp->allocated == 0)
2525 if (bufp->buffer)
2526 { /* If zero allocated, but buffer is non-null, try to realloc
2527 enough space. This loses if buffer's address is bogus, but
2528 that is the user's responsibility. */
2529 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2531 else
2532 { /* Caller did not allocate a buffer. Do it for them. */
2533 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2535 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2537 bufp->allocated = INIT_BUF_SIZE;
2540 begalt = b = bufp->buffer;
2542 /* Loop through the uncompiled pattern until we're at the end. */
2543 while (1)
2545 if (p == pend)
2547 #ifdef emacs
2548 /* If this is the end of an included regexp,
2549 pop back to the main regexp and try again. */
2550 if (in_subpattern)
2552 in_subpattern = 0;
2553 pattern = main_pattern;
2554 p = main_p;
2555 pend = main_pend;
2556 continue;
2558 #endif
2559 /* If this is the end of the main regexp, we are done. */
2560 break;
2563 PATFETCH (c);
2565 switch (c)
2567 #ifdef emacs
2568 case ' ':
2570 re_char *p1 = p;
2572 /* If there's no special whitespace regexp, treat
2573 spaces normally. And don't try to do this recursively. */
2574 if (!whitespace_regexp || in_subpattern)
2575 goto normal_char;
2577 /* Peek past following spaces. */
2578 while (p1 != pend)
2580 if (*p1 != ' ')
2581 break;
2582 p1++;
2584 /* If the spaces are followed by a repetition op,
2585 treat them normally. */
2586 if (p1 != pend
2587 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2588 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2589 goto normal_char;
2591 /* Replace the spaces with the whitespace regexp. */
2592 in_subpattern = 1;
2593 main_p = p1;
2594 main_pend = pend;
2595 main_pattern = pattern;
2596 p = pattern = (re_char *) whitespace_regexp;
2597 pend = p + strlen (whitespace_regexp);
2598 break;
2600 #endif
2602 case '^':
2604 if ( /* If at start of pattern, it's an operator. */
2605 p == pattern + 1
2606 /* If context independent, it's an operator. */
2607 || syntax & RE_CONTEXT_INDEP_ANCHORS
2608 /* Otherwise, depends on what's come before. */
2609 || at_begline_loc_p (pattern, p, syntax))
2610 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2611 else
2612 goto normal_char;
2614 break;
2617 case '$':
2619 if ( /* If at end of pattern, it's an operator. */
2620 p == pend
2621 /* If context independent, it's an operator. */
2622 || syntax & RE_CONTEXT_INDEP_ANCHORS
2623 /* Otherwise, depends on what's next. */
2624 || at_endline_loc_p (p, pend, syntax))
2625 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2626 else
2627 goto normal_char;
2629 break;
2632 case '+':
2633 case '?':
2634 if ((syntax & RE_BK_PLUS_QM)
2635 || (syntax & RE_LIMITED_OPS))
2636 goto normal_char;
2637 FALLTHROUGH;
2638 case '*':
2639 handle_plus:
2640 /* If there is no previous pattern... */
2641 if (!laststart)
2643 if (syntax & RE_CONTEXT_INVALID_OPS)
2644 FREE_STACK_RETURN (REG_BADRPT);
2645 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2646 goto normal_char;
2650 /* 1 means zero (many) matches is allowed. */
2651 boolean zero_times_ok = 0, many_times_ok = 0;
2652 boolean greedy = 1;
2654 /* If there is a sequence of repetition chars, collapse it
2655 down to just one (the right one). We can't combine
2656 interval operators with these because of, e.g., `a{2}*',
2657 which should only match an even number of `a's. */
2659 for (;;)
2661 if ((syntax & RE_FRUGAL)
2662 && c == '?' && (zero_times_ok || many_times_ok))
2663 greedy = 0;
2664 else
2666 zero_times_ok |= c != '+';
2667 many_times_ok |= c != '?';
2670 if (p == pend)
2671 break;
2672 else if (*p == '*'
2673 || (!(syntax & RE_BK_PLUS_QM)
2674 && (*p == '+' || *p == '?')))
2676 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2678 if (p+1 == pend)
2679 FREE_STACK_RETURN (REG_EESCAPE);
2680 if (p[1] == '+' || p[1] == '?')
2681 PATFETCH (c); /* Gobble up the backslash. */
2682 else
2683 break;
2685 else
2686 break;
2687 /* If we get here, we found another repeat character. */
2688 PATFETCH (c);
2691 /* Star, etc. applied to an empty pattern is equivalent
2692 to an empty pattern. */
2693 if (!laststart || laststart == b)
2694 break;
2696 /* Now we know whether or not zero matches is allowed
2697 and also whether or not two or more matches is allowed. */
2698 if (greedy)
2700 if (many_times_ok)
2702 boolean simple = skip_one_char (laststart) == b;
2703 size_t startoffset = 0;
2704 re_opcode_t ofj =
2705 /* Check if the loop can match the empty string. */
2706 (simple || !analyze_first (laststart, b, NULL, 0))
2707 ? on_failure_jump : on_failure_jump_loop;
2708 assert (skip_one_char (laststart) <= b);
2710 if (!zero_times_ok && simple)
2711 { /* Since simple * loops can be made faster by using
2712 on_failure_keep_string_jump, we turn simple P+
2713 into PP* if P is simple. */
2714 unsigned char *p1, *p2;
2715 startoffset = b - laststart;
2716 GET_BUFFER_SPACE (startoffset);
2717 p1 = b; p2 = laststart;
2718 while (p2 < p1)
2719 *b++ = *p2++;
2720 zero_times_ok = 1;
2723 GET_BUFFER_SPACE (6);
2724 if (!zero_times_ok)
2725 /* A + loop. */
2726 STORE_JUMP (ofj, b, b + 6);
2727 else
2728 /* Simple * loops can use on_failure_keep_string_jump
2729 depending on what follows. But since we don't know
2730 that yet, we leave the decision up to
2731 on_failure_jump_smart. */
2732 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2733 laststart + startoffset, b + 6);
2734 b += 3;
2735 STORE_JUMP (jump, b, laststart + startoffset);
2736 b += 3;
2738 else
2740 /* A simple ? pattern. */
2741 assert (zero_times_ok);
2742 GET_BUFFER_SPACE (3);
2743 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2744 b += 3;
2747 else /* not greedy */
2748 { /* I wish the greedy and non-greedy cases could be merged. */
2750 GET_BUFFER_SPACE (7); /* We might use less. */
2751 if (many_times_ok)
2753 boolean emptyp = analyze_first (laststart, b, NULL, 0);
2755 /* The non-greedy multiple match looks like
2756 a repeat..until: we only need a conditional jump
2757 at the end of the loop. */
2758 if (emptyp) BUF_PUSH (no_op);
2759 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2760 : on_failure_jump, b, laststart);
2761 b += 3;
2762 if (zero_times_ok)
2764 /* The repeat...until naturally matches one or more.
2765 To also match zero times, we need to first jump to
2766 the end of the loop (its conditional jump). */
2767 INSERT_JUMP (jump, laststart, b);
2768 b += 3;
2771 else
2773 /* non-greedy a?? */
2774 INSERT_JUMP (jump, laststart, b + 3);
2775 b += 3;
2776 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2777 b += 3;
2781 pending_exact = 0;
2782 break;
2785 case '.':
2786 laststart = b;
2787 BUF_PUSH (anychar);
2788 break;
2791 case '[':
2793 re_char *p1;
2795 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2797 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2799 /* Ensure that we have enough space to push a charset: the
2800 opcode, the length count, and the bitset; 34 bytes in all. */
2801 GET_BUFFER_SPACE (34);
2803 laststart = b;
2805 /* We test `*p == '^' twice, instead of using an if
2806 statement, so we only need one BUF_PUSH. */
2807 BUF_PUSH (*p == '^' ? charset_not : charset);
2808 if (*p == '^')
2809 p++;
2811 /* Remember the first position in the bracket expression. */
2812 p1 = p;
2814 /* Push the number of bytes in the bitmap. */
2815 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2817 /* Clear the whole map. */
2818 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2820 /* charset_not matches newline according to a syntax bit. */
2821 if ((re_opcode_t) b[-2] == charset_not
2822 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2823 SET_LIST_BIT ('\n');
2825 /* Read in characters and ranges, setting map bits. */
2826 for (;;)
2828 boolean escaped_char = false;
2829 const unsigned char *p2 = p;
2830 re_wctype_t cc;
2831 re_wchar_t ch;
2833 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2835 /* See if we're at the beginning of a possible character
2836 class. */
2837 if (syntax & RE_CHAR_CLASSES &&
2838 (cc = re_wctype_parse(&p, pend - p)) != -1)
2840 if (cc == 0)
2841 FREE_STACK_RETURN (REG_ECTYPE);
2843 if (p == pend)
2844 FREE_STACK_RETURN (REG_EBRACK);
2846 #ifndef emacs
2847 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2848 if (re_iswctype (btowc (ch), cc))
2850 c = TRANSLATE (ch);
2851 if (c < (1 << BYTEWIDTH))
2852 SET_LIST_BIT (c);
2854 #else /* emacs */
2855 /* Most character classes in a multibyte match just set
2856 a flag. Exceptions are is_blank, is_digit, is_cntrl, and
2857 is_xdigit, since they can only match ASCII characters.
2858 We don't need to handle them for multibyte. */
2860 /* Setup the gl_state object to its buffer-defined value.
2861 This hardcodes the buffer-global syntax-table for ASCII
2862 chars, while the other chars will obey syntax-table
2863 properties. It's not ideal, but it's the way it's been
2864 done until now. */
2865 SETUP_BUFFER_SYNTAX_TABLE ();
2867 for (c = 0; c < 0x80; ++c)
2868 if (re_iswctype (c, cc))
2870 SET_LIST_BIT (c);
2871 c1 = TRANSLATE (c);
2872 if (c1 == c)
2873 continue;
2874 if (ASCII_CHAR_P (c1))
2875 SET_LIST_BIT (c1);
2876 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2877 SET_LIST_BIT (c1);
2879 SET_RANGE_TABLE_WORK_AREA_BIT
2880 (range_table_work, re_wctype_to_bit (cc));
2881 #endif /* emacs */
2882 /* In most cases the matching rule for char classes only
2883 uses the syntax table for multibyte chars, so that the
2884 content of the syntax-table is not hardcoded in the
2885 range_table. SPACE and WORD are the two exceptions. */
2886 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2887 bufp->used_syntax = 1;
2889 /* Repeat the loop. */
2890 continue;
2893 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2894 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2895 So the translation is done later in a loop. Example:
2896 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2897 PATFETCH (c);
2899 /* \ might escape characters inside [...] and [^...]. */
2900 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2902 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2904 PATFETCH (c);
2905 escaped_char = true;
2907 else
2909 /* Could be the end of the bracket expression. If it's
2910 not (i.e., when the bracket expression is `[]' so
2911 far), the ']' character bit gets set way below. */
2912 if (c == ']' && p2 != p1)
2913 break;
2916 if (p < pend && p[0] == '-' && p[1] != ']')
2919 /* Discard the `-'. */
2920 PATFETCH (c1);
2922 /* Fetch the character which ends the range. */
2923 PATFETCH (c1);
2924 #ifdef emacs
2925 if (CHAR_BYTE8_P (c1)
2926 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2927 /* Treat the range from a multibyte character to
2928 raw-byte character as empty. */
2929 c = c1 + 1;
2930 #endif /* emacs */
2932 else
2933 /* Range from C to C. */
2934 c1 = c;
2936 if (c > c1)
2938 if (syntax & RE_NO_EMPTY_RANGES)
2939 FREE_STACK_RETURN (REG_ERANGEX);
2940 /* Else, repeat the loop. */
2942 else
2944 #ifndef emacs
2945 /* Set the range into bitmap */
2946 for (; c <= c1; c++)
2948 ch = TRANSLATE (c);
2949 if (ch < (1 << BYTEWIDTH))
2950 SET_LIST_BIT (ch);
2952 #else /* emacs */
2953 if (c < 128)
2955 ch = min (127, c1);
2956 SETUP_ASCII_RANGE (range_table_work, c, ch);
2957 c = ch + 1;
2958 if (CHAR_BYTE8_P (c1))
2959 c = BYTE8_TO_CHAR (128);
2961 if (c <= c1)
2963 if (CHAR_BYTE8_P (c))
2965 c = CHAR_TO_BYTE8 (c);
2966 c1 = CHAR_TO_BYTE8 (c1);
2967 for (; c <= c1; c++)
2968 SET_LIST_BIT (c);
2970 else if (multibyte)
2972 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
2974 else
2976 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
2979 #endif /* emacs */
2983 /* Discard any (non)matching list bytes that are all 0 at the
2984 end of the map. Decrease the map-length byte too. */
2985 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2986 b[-1]--;
2987 b += b[-1];
2989 /* Build real range table from work area. */
2990 if (RANGE_TABLE_WORK_USED (range_table_work)
2991 || RANGE_TABLE_WORK_BITS (range_table_work))
2993 int i;
2994 int used = RANGE_TABLE_WORK_USED (range_table_work);
2996 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2997 bytes for flags, two for COUNT, and three bytes for
2998 each character. */
2999 GET_BUFFER_SPACE (4 + used * 3);
3001 /* Indicate the existence of range table. */
3002 laststart[1] |= 0x80;
3004 /* Store the character class flag bits into the range table.
3005 If not in emacs, these flag bits are always 0. */
3006 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3007 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3009 STORE_NUMBER_AND_INCR (b, used / 2);
3010 for (i = 0; i < used; i++)
3011 STORE_CHARACTER_AND_INCR
3012 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3015 break;
3018 case '(':
3019 if (syntax & RE_NO_BK_PARENS)
3020 goto handle_open;
3021 else
3022 goto normal_char;
3025 case ')':
3026 if (syntax & RE_NO_BK_PARENS)
3027 goto handle_close;
3028 else
3029 goto normal_char;
3032 case '\n':
3033 if (syntax & RE_NEWLINE_ALT)
3034 goto handle_alt;
3035 else
3036 goto normal_char;
3039 case '|':
3040 if (syntax & RE_NO_BK_VBAR)
3041 goto handle_alt;
3042 else
3043 goto normal_char;
3046 case '{':
3047 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3048 goto handle_interval;
3049 else
3050 goto normal_char;
3053 case '\\':
3054 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3056 /* Do not translate the character after the \, so that we can
3057 distinguish, e.g., \B from \b, even if we normally would
3058 translate, e.g., B to b. */
3059 PATFETCH (c);
3061 switch (c)
3063 case '(':
3064 if (syntax & RE_NO_BK_PARENS)
3065 goto normal_backslash;
3067 handle_open:
3069 int shy = 0;
3070 regnum_t regnum = 0;
3071 if (p+1 < pend)
3073 /* Look for a special (?...) construct */
3074 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3076 PATFETCH (c); /* Gobble up the '?'. */
3077 while (!shy)
3079 PATFETCH (c);
3080 switch (c)
3082 case ':': shy = 1; break;
3083 case '0':
3084 /* An explicitly specified regnum must start
3085 with non-0. */
3086 if (regnum == 0)
3087 FREE_STACK_RETURN (REG_BADPAT);
3088 FALLTHROUGH;
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;
3908 FALLTHROUGH;
3909 case charset:
3910 if (!fastmap) break;
3911 not = (re_opcode_t) *(p - 1) == charset_not;
3912 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3913 j >= 0; j--)
3914 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3915 fastmap[j] = 1;
3917 #ifdef emacs
3918 if (/* Any leading code can possibly start a character
3919 which doesn't match the specified set of characters. */
3922 /* If we can match a character class, we can match any
3923 multibyte characters. */
3924 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3925 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3928 if (match_any_multibyte_characters == false)
3930 for (j = MIN_MULTIBYTE_LEADING_CODE;
3931 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3932 fastmap[j] = 1;
3933 match_any_multibyte_characters = true;
3937 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3938 && match_any_multibyte_characters == false)
3940 /* Set fastmap[I] to 1 where I is a leading code of each
3941 multibyte character in the range table. */
3942 int c, count;
3943 unsigned char lc1, lc2;
3945 /* Make P points the range table. `+ 2' is to skip flag
3946 bits for a character class. */
3947 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3949 /* Extract the number of ranges in range table into COUNT. */
3950 EXTRACT_NUMBER_AND_INCR (count, p);
3951 for (; count > 0; count--, p += 3)
3953 /* Extract the start and end of each range. */
3954 EXTRACT_CHARACTER (c, p);
3955 lc1 = CHAR_LEADING_CODE (c);
3956 p += 3;
3957 EXTRACT_CHARACTER (c, p);
3958 lc2 = CHAR_LEADING_CODE (c);
3959 for (j = lc1; j <= lc2; j++)
3960 fastmap[j] = 1;
3963 #endif
3964 break;
3966 case syntaxspec:
3967 case notsyntaxspec:
3968 if (!fastmap) break;
3969 #ifndef emacs
3970 not = (re_opcode_t)p[-1] == notsyntaxspec;
3971 k = *p++;
3972 for (j = 0; j < (1 << BYTEWIDTH); j++)
3973 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3974 fastmap[j] = 1;
3975 break;
3976 #else /* emacs */
3977 /* This match depends on text properties. These end with
3978 aborting optimizations. */
3979 return -1;
3981 case categoryspec:
3982 case notcategoryspec:
3983 if (!fastmap) break;
3984 not = (re_opcode_t)p[-1] == notcategoryspec;
3985 k = *p++;
3986 for (j = (1 << BYTEWIDTH); j >= 0; j--)
3987 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3988 fastmap[j] = 1;
3990 /* Any leading code can possibly start a character which
3991 has or doesn't has the specified category. */
3992 if (match_any_multibyte_characters == false)
3994 for (j = MIN_MULTIBYTE_LEADING_CODE;
3995 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3996 fastmap[j] = 1;
3997 match_any_multibyte_characters = true;
3999 break;
4001 /* All cases after this match the empty string. These end with
4002 `continue'. */
4004 case at_dot:
4005 #endif /* !emacs */
4006 case no_op:
4007 case begline:
4008 case endline:
4009 case begbuf:
4010 case endbuf:
4011 case wordbound:
4012 case notwordbound:
4013 case wordbeg:
4014 case wordend:
4015 case symbeg:
4016 case symend:
4017 continue;
4020 case jump:
4021 EXTRACT_NUMBER_AND_INCR (j, p);
4022 if (j < 0)
4023 /* Backward jumps can only go back to code that we've already
4024 visited. `re_compile' should make sure this is true. */
4025 break;
4026 p += j;
4027 switch (*p)
4029 case on_failure_jump:
4030 case on_failure_keep_string_jump:
4031 case on_failure_jump_loop:
4032 case on_failure_jump_nastyloop:
4033 case on_failure_jump_smart:
4034 p++;
4035 break;
4036 default:
4037 continue;
4039 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4040 to jump back to "just after here". */
4041 FALLTHROUGH;
4042 case on_failure_jump:
4043 case on_failure_keep_string_jump:
4044 case on_failure_jump_nastyloop:
4045 case on_failure_jump_loop:
4046 case on_failure_jump_smart:
4047 EXTRACT_NUMBER_AND_INCR (j, p);
4048 if (p + j <= p1)
4049 ; /* Backward jump to be ignored. */
4050 else
4051 { /* We have to look down both arms.
4052 We first go down the "straight" path so as to minimize
4053 stack usage when going through alternatives. */
4054 int r = analyze_first (p, pend, fastmap, multibyte);
4055 if (r) return r;
4056 p += j;
4058 continue;
4061 case jump_n:
4062 /* This code simply does not properly handle forward jump_n. */
4063 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4064 p += 4;
4065 /* jump_n can either jump or fall through. The (backward) jump
4066 case has already been handled, so we only need to look at the
4067 fallthrough case. */
4068 continue;
4070 case succeed_n:
4071 /* If N == 0, it should be an on_failure_jump_loop instead. */
4072 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4073 p += 4;
4074 /* We only care about one iteration of the loop, so we don't
4075 need to consider the case where this behaves like an
4076 on_failure_jump. */
4077 continue;
4080 case set_number_at:
4081 p += 4;
4082 continue;
4085 case start_memory:
4086 case stop_memory:
4087 p += 1;
4088 continue;
4091 default:
4092 abort (); /* We have listed all the cases. */
4093 } /* switch *p++ */
4095 /* Getting here means we have found the possible starting
4096 characters for one path of the pattern -- and that the empty
4097 string does not match. We need not follow this path further. */
4098 return 0;
4099 } /* while p */
4101 /* We reached the end without matching anything. */
4102 return 1;
4104 } /* analyze_first */
4106 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4107 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4108 characters can start a string that matches the pattern. This fastmap
4109 is used by re_search to skip quickly over impossible starting points.
4111 Character codes above (1 << BYTEWIDTH) are not represented in the
4112 fastmap, but the leading codes are represented. Thus, the fastmap
4113 indicates which character sets could start a match.
4115 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4116 area as BUFP->fastmap.
4118 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4119 the pattern buffer.
4121 Returns 0 if we succeed, -2 if an internal error. */
4124 re_compile_fastmap (struct re_pattern_buffer *bufp)
4126 char *fastmap = bufp->fastmap;
4127 int analysis;
4129 assert (fastmap && bufp->buffer);
4131 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4132 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4134 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4135 fastmap, RE_MULTIBYTE_P (bufp));
4136 bufp->can_be_null = (analysis != 0);
4137 return 0;
4138 } /* re_compile_fastmap */
4140 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4141 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4142 this memory for recording register information. STARTS and ENDS
4143 must be allocated using the malloc library routine, and must each
4144 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4146 If NUM_REGS == 0, then subsequent matches should allocate their own
4147 register data.
4149 Unless this function is called, the first search or match using
4150 PATTERN_BUFFER will allocate its own register data, without
4151 freeing the old data. */
4153 void
4154 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4156 if (num_regs)
4158 bufp->regs_allocated = REGS_REALLOCATE;
4159 regs->num_regs = num_regs;
4160 regs->start = starts;
4161 regs->end = ends;
4163 else
4165 bufp->regs_allocated = REGS_UNALLOCATED;
4166 regs->num_regs = 0;
4167 regs->start = regs->end = 0;
4170 WEAK_ALIAS (__re_set_registers, re_set_registers)
4172 /* Searching routines. */
4174 /* Like re_search_2, below, but only one string is specified, and
4175 doesn't let you say where to stop matching. */
4177 regoff_t
4178 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4179 ssize_t startpos, ssize_t range, struct re_registers *regs)
4181 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4182 regs, size);
4184 WEAK_ALIAS (__re_search, re_search)
4186 /* Head address of virtual concatenation of string. */
4187 #define HEAD_ADDR_VSTRING(P) \
4188 (((P) >= size1 ? string2 : string1))
4190 /* Address of POS in the concatenation of virtual string. */
4191 #define POS_ADDR_VSTRING(POS) \
4192 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4194 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4195 virtual concatenation of STRING1 and STRING2, starting first at index
4196 STARTPOS, then at STARTPOS + 1, and so on.
4198 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4200 RANGE is how far to scan while trying to match. RANGE = 0 means try
4201 only at STARTPOS; in general, the last start tried is STARTPOS +
4202 RANGE.
4204 In REGS, return the indices of the virtual concatenation of STRING1
4205 and STRING2 that matched the entire BUFP->buffer and its contained
4206 subexpressions.
4208 Do not consider matching one past the index STOP in the virtual
4209 concatenation of STRING1 and STRING2.
4211 We return either the position in the strings at which the match was
4212 found, -1 if no match, or -2 if error (such as failure
4213 stack overflow). */
4215 regoff_t
4216 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4217 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4218 struct re_registers *regs, ssize_t stop)
4220 regoff_t val;
4221 re_char *string1 = (re_char *) str1;
4222 re_char *string2 = (re_char *) str2;
4223 register char *fastmap = bufp->fastmap;
4224 register RE_TRANSLATE_TYPE translate = bufp->translate;
4225 size_t total_size = size1 + size2;
4226 ssize_t endpos = startpos + range;
4227 boolean anchored_start;
4228 /* Nonzero if we are searching multibyte string. */
4229 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4231 /* Check for out-of-range STARTPOS. */
4232 if (startpos < 0 || startpos > total_size)
4233 return -1;
4235 /* Fix up RANGE if it might eventually take us outside
4236 the virtual concatenation of STRING1 and STRING2.
4237 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4238 if (endpos < 0)
4239 range = 0 - startpos;
4240 else if (endpos > total_size)
4241 range = total_size - startpos;
4243 /* If the search isn't to be a backwards one, don't waste time in a
4244 search for a pattern anchored at beginning of buffer. */
4245 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4247 if (startpos > 0)
4248 return -1;
4249 else
4250 range = 0;
4253 #ifdef emacs
4254 /* In a forward search for something that starts with \=.
4255 don't keep searching past point. */
4256 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4258 range = PT_BYTE - BEGV_BYTE - startpos;
4259 if (range < 0)
4260 return -1;
4262 #endif /* emacs */
4264 /* Update the fastmap now if not correct already. */
4265 if (fastmap && !bufp->fastmap_accurate)
4266 re_compile_fastmap (bufp);
4268 /* See whether the pattern is anchored. */
4269 anchored_start = (bufp->buffer[0] == begline);
4271 #ifdef emacs
4272 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4274 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4276 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4278 #endif
4280 /* Loop through the string, looking for a place to start matching. */
4281 for (;;)
4283 /* If the pattern is anchored,
4284 skip quickly past places we cannot match.
4285 We don't bother to treat startpos == 0 specially
4286 because that case doesn't repeat. */
4287 if (anchored_start && startpos > 0)
4289 if (! ((startpos <= size1 ? string1[startpos - 1]
4290 : string2[startpos - size1 - 1])
4291 == '\n'))
4292 goto advance;
4295 /* If a fastmap is supplied, skip quickly over characters that
4296 cannot be the start of a match. If the pattern can match the
4297 null string, however, we don't need to skip characters; we want
4298 the first null string. */
4299 if (fastmap && startpos < total_size && !bufp->can_be_null)
4301 register re_char *d;
4302 register re_wchar_t buf_ch;
4304 d = POS_ADDR_VSTRING (startpos);
4306 if (range > 0) /* Searching forwards. */
4308 ssize_t irange = range, lim = 0;
4310 if (startpos < size1 && startpos + range >= size1)
4311 lim = range - (size1 - startpos);
4313 /* Written out as an if-else to avoid testing `translate'
4314 inside the loop. */
4315 if (RE_TRANSLATE_P (translate))
4317 if (multibyte)
4318 while (range > lim)
4320 int buf_charlen;
4322 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4323 buf_ch = RE_TRANSLATE (translate, buf_ch);
4324 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4325 break;
4327 range -= buf_charlen;
4328 d += buf_charlen;
4330 else
4331 while (range > lim)
4333 register re_wchar_t ch, translated;
4335 buf_ch = *d;
4336 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4337 translated = RE_TRANSLATE (translate, ch);
4338 if (translated != ch
4339 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4340 buf_ch = ch;
4341 if (fastmap[buf_ch])
4342 break;
4343 d++;
4344 range--;
4347 else
4349 if (multibyte)
4350 while (range > lim)
4352 int buf_charlen;
4354 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4355 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4356 break;
4357 range -= buf_charlen;
4358 d += buf_charlen;
4360 else
4361 while (range > lim && !fastmap[*d])
4363 d++;
4364 range--;
4367 startpos += irange - range;
4369 else /* Searching backwards. */
4371 if (multibyte)
4373 buf_ch = STRING_CHAR (d);
4374 buf_ch = TRANSLATE (buf_ch);
4375 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4376 goto advance;
4378 else
4380 register re_wchar_t ch, translated;
4382 buf_ch = *d;
4383 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4384 translated = TRANSLATE (ch);
4385 if (translated != ch
4386 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4387 buf_ch = ch;
4388 if (! fastmap[TRANSLATE (buf_ch)])
4389 goto advance;
4394 /* If can't match the null string, and that's all we have left, fail. */
4395 if (range >= 0 && startpos == total_size && fastmap
4396 && !bufp->can_be_null)
4397 return -1;
4399 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4400 startpos, regs, stop);
4402 if (val >= 0)
4403 return startpos;
4405 if (val == -2)
4406 return -2;
4408 advance:
4409 if (!range)
4410 break;
4411 else if (range > 0)
4413 /* Update STARTPOS to the next character boundary. */
4414 if (multibyte)
4416 re_char *p = POS_ADDR_VSTRING (startpos);
4417 int len = BYTES_BY_CHAR_HEAD (*p);
4419 range -= len;
4420 if (range < 0)
4421 break;
4422 startpos += len;
4424 else
4426 range--;
4427 startpos++;
4430 else
4432 range++;
4433 startpos--;
4435 /* Update STARTPOS to the previous character boundary. */
4436 if (multibyte)
4438 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4439 re_char *p0 = p;
4440 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4442 /* Find the head of multibyte form. */
4443 PREV_CHAR_BOUNDARY (p, phead);
4444 range += p0 - 1 - p;
4445 if (range > 0)
4446 break;
4448 startpos -= p0 - 1 - p;
4452 return -1;
4453 } /* re_search_2 */
4454 WEAK_ALIAS (__re_search_2, re_search_2)
4456 /* Declarations and macros for re_match_2. */
4458 static int bcmp_translate (re_char *s1, re_char *s2,
4459 register ssize_t len,
4460 RE_TRANSLATE_TYPE translate,
4461 const int multibyte);
4463 /* This converts PTR, a pointer into one of the search strings `string1'
4464 and `string2' into an offset from the beginning of that string. */
4465 #define POINTER_TO_OFFSET(ptr) \
4466 (FIRST_STRING_P (ptr) \
4467 ? (ptr) - string1 \
4468 : (ptr) - string2 + (ptrdiff_t) size1)
4470 /* Call before fetching a character with *d. This switches over to
4471 string2 if necessary.
4472 Check re_match_2_internal for a discussion of why end_match_2 might
4473 not be within string2 (but be equal to end_match_1 instead). */
4474 #define PREFETCH() \
4475 while (d == dend) \
4477 /* End of string2 => fail. */ \
4478 if (dend == end_match_2) \
4479 goto fail; \
4480 /* End of string1 => advance to string2. */ \
4481 d = string2; \
4482 dend = end_match_2; \
4485 /* Call before fetching a char with *d if you already checked other limits.
4486 This is meant for use in lookahead operations like wordend, etc..
4487 where we might need to look at parts of the string that might be
4488 outside of the LIMITs (i.e past `stop'). */
4489 #define PREFETCH_NOLIMIT() \
4490 if (d == end1) \
4492 d = string2; \
4493 dend = end_match_2; \
4496 /* Test if at very beginning or at very end of the virtual concatenation
4497 of `string1' and `string2'. If only one string, it's `string2'. */
4498 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4499 #define AT_STRINGS_END(d) ((d) == end2)
4501 /* Disabled due to a compiler bug -- see comment at case wordbound */
4503 /* The comment at case wordbound is following one, but we don't use
4504 AT_WORD_BOUNDARY anymore to support multibyte form.
4506 The DEC Alpha C compiler 3.x generates incorrect code for the
4507 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4508 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4509 macro and introducing temporary variables works around the bug. */
4511 #if 0
4512 /* Test if D points to a character which is word-constituent. We have
4513 two special cases to check for: if past the end of string1, look at
4514 the first character in string2; and if before the beginning of
4515 string2, look at the last character in string1. */
4516 #define WORDCHAR_P(d) \
4517 (SYNTAX ((d) == end1 ? *string2 \
4518 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4519 == Sword)
4521 /* Test if the character before D and the one at D differ with respect
4522 to being word-constituent. */
4523 #define AT_WORD_BOUNDARY(d) \
4524 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4525 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4526 #endif
4528 /* Free everything we malloc. */
4529 #ifdef MATCH_MAY_ALLOCATE
4530 # define FREE_VAR(var) \
4531 do { \
4532 if (var) \
4534 REGEX_FREE (var); \
4535 var = NULL; \
4537 } while (0)
4538 # define FREE_VARIABLES() \
4539 do { \
4540 REGEX_FREE_STACK (fail_stack.stack); \
4541 FREE_VAR (regstart); \
4542 FREE_VAR (regend); \
4543 FREE_VAR (best_regstart); \
4544 FREE_VAR (best_regend); \
4545 REGEX_SAFE_FREE (); \
4546 } while (0)
4547 #else
4548 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4549 #endif /* not MATCH_MAY_ALLOCATE */
4552 /* Optimization routines. */
4554 /* If the operation is a match against one or more chars,
4555 return a pointer to the next operation, else return NULL. */
4556 static re_char *
4557 skip_one_char (const_re_char *p)
4559 switch (*p++)
4561 case anychar:
4562 break;
4564 case exactn:
4565 p += *p + 1;
4566 break;
4568 case charset_not:
4569 case charset:
4570 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4572 int mcnt;
4573 p = CHARSET_RANGE_TABLE (p - 1);
4574 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4575 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4577 else
4578 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4579 break;
4581 case syntaxspec:
4582 case notsyntaxspec:
4583 #ifdef emacs
4584 case categoryspec:
4585 case notcategoryspec:
4586 #endif /* emacs */
4587 p++;
4588 break;
4590 default:
4591 p = NULL;
4593 return p;
4597 /* Jump over non-matching operations. */
4598 static re_char *
4599 skip_noops (const_re_char *p, const_re_char *pend)
4601 int mcnt;
4602 while (p < pend)
4604 switch (*p)
4606 case start_memory:
4607 case stop_memory:
4608 p += 2; break;
4609 case no_op:
4610 p += 1; break;
4611 case jump:
4612 p += 1;
4613 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4614 p += mcnt;
4615 break;
4616 default:
4617 return p;
4620 assert (p == pend);
4621 return p;
4624 /* Test if C matches charset op. *PP points to the charset or charset_not
4625 opcode. When the function finishes, *PP will be advanced past that opcode.
4626 C is character to test (possibly after translations) and CORIG is original
4627 character (i.e. without any translations). UNIBYTE denotes whether c is
4628 unibyte or multibyte character. */
4629 static bool
4630 execute_charset (const_re_char **pp, unsigned c, unsigned corig, bool unibyte)
4632 re_char *p = *pp, *rtp = NULL;
4633 bool not = (re_opcode_t) *p == charset_not;
4635 if (CHARSET_RANGE_TABLE_EXISTS_P (p))
4637 int count;
4638 rtp = CHARSET_RANGE_TABLE (p);
4639 EXTRACT_NUMBER_AND_INCR (count, rtp);
4640 *pp = CHARSET_RANGE_TABLE_END ((rtp), (count));
4642 else
4643 *pp += 2 + CHARSET_BITMAP_SIZE (p);
4645 if (unibyte && c < (1 << BYTEWIDTH))
4646 { /* Lookup bitmap. */
4647 /* Cast to `unsigned' instead of `unsigned char' in
4648 case the bit list is a full 32 bytes long. */
4649 if (c < (unsigned) (CHARSET_BITMAP_SIZE (p) * BYTEWIDTH)
4650 && p[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4651 return !not;
4653 #ifdef emacs
4654 else if (rtp)
4656 int class_bits = CHARSET_RANGE_TABLE_BITS (p);
4657 re_wchar_t range_start, range_end;
4659 /* Sort tests by the most commonly used classes with some adjustment to which
4660 tests are easiest to perform. Take a look at comment in re_wctype_parse
4661 for table with frequencies of character class names. */
4663 if ((class_bits & BIT_MULTIBYTE) ||
4664 (class_bits & BIT_ALNUM && ISALNUM (c)) ||
4665 (class_bits & BIT_ALPHA && ISALPHA (c)) ||
4666 (class_bits & BIT_SPACE && ISSPACE (c)) ||
4667 (class_bits & BIT_BLANK && ISBLANK (c)) ||
4668 (class_bits & BIT_WORD && ISWORD (c)) ||
4669 ((class_bits & BIT_UPPER) &&
4670 (ISUPPER (c) || (corig != c &&
4671 c == downcase (corig) && ISLOWER (c)))) ||
4672 ((class_bits & BIT_LOWER) &&
4673 (ISLOWER (c) || (corig != c &&
4674 c == upcase (corig) && ISUPPER(c)))) ||
4675 (class_bits & BIT_PUNCT && ISPUNCT (c)) ||
4676 (class_bits & BIT_GRAPH && ISGRAPH (c)) ||
4677 (class_bits & BIT_PRINT && ISPRINT (c)))
4678 return !not;
4680 for (p = *pp; rtp < p; rtp += 2 * 3)
4682 EXTRACT_CHARACTER (range_start, rtp);
4683 EXTRACT_CHARACTER (range_end, rtp + 3);
4684 if (range_start <= c && c <= range_end)
4685 return !not;
4688 #endif /* emacs */
4689 return not;
4692 /* Non-zero if "p1 matches something" implies "p2 fails". */
4693 static int
4694 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4695 const_re_char *p2)
4697 re_opcode_t op2;
4698 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4699 unsigned char *pend = bufp->buffer + bufp->used;
4701 assert (p1 >= bufp->buffer && p1 < pend
4702 && p2 >= bufp->buffer && p2 <= pend);
4704 /* Skip over open/close-group commands.
4705 If what follows this loop is a ...+ construct,
4706 look at what begins its body, since we will have to
4707 match at least one of that. */
4708 p2 = skip_noops (p2, pend);
4709 /* The same skip can be done for p1, except that this function
4710 is only used in the case where p1 is a simple match operator. */
4711 /* p1 = skip_noops (p1, pend); */
4713 assert (p1 >= bufp->buffer && p1 < pend
4714 && p2 >= bufp->buffer && p2 <= pend);
4716 op2 = p2 == pend ? succeed : *p2;
4718 switch (op2)
4720 case succeed:
4721 case endbuf:
4722 /* If we're at the end of the pattern, we can change. */
4723 if (skip_one_char (p1))
4725 DEBUG_PRINT (" End of pattern: fast loop.\n");
4726 return 1;
4728 break;
4730 case endline:
4731 case exactn:
4733 register re_wchar_t c
4734 = (re_opcode_t) *p2 == endline ? '\n'
4735 : RE_STRING_CHAR (p2 + 2, multibyte);
4737 if ((re_opcode_t) *p1 == exactn)
4739 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4741 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4742 return 1;
4746 else if ((re_opcode_t) *p1 == charset
4747 || (re_opcode_t) *p1 == charset_not)
4749 if (!execute_charset (&p1, c, c, !multibyte || IS_REAL_ASCII (c)))
4751 DEBUG_PRINT (" No match => fast loop.\n");
4752 return 1;
4755 else if ((re_opcode_t) *p1 == anychar
4756 && c == '\n')
4758 DEBUG_PRINT (" . != \\n => fast loop.\n");
4759 return 1;
4762 break;
4764 case charset:
4766 if ((re_opcode_t) *p1 == exactn)
4767 /* Reuse the code above. */
4768 return mutually_exclusive_p (bufp, p2, p1);
4770 /* It is hard to list up all the character in charset
4771 P2 if it includes multibyte character. Give up in
4772 such case. */
4773 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4775 /* Now, we are sure that P2 has no range table.
4776 So, for the size of bitmap in P2, `p2[1]' is
4777 enough. But P1 may have range table, so the
4778 size of bitmap table of P1 is extracted by
4779 using macro `CHARSET_BITMAP_SIZE'.
4781 In a multibyte case, we know that all the character
4782 listed in P2 is ASCII. In a unibyte case, P1 has only a
4783 bitmap table. So, in both cases, it is enough to test
4784 only the bitmap table of P1. */
4786 if ((re_opcode_t) *p1 == charset)
4788 int idx;
4789 /* We win if the charset inside the loop
4790 has no overlap with the one after the loop. */
4791 for (idx = 0;
4792 (idx < (int) p2[1]
4793 && idx < CHARSET_BITMAP_SIZE (p1));
4794 idx++)
4795 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4796 break;
4798 if (idx == p2[1]
4799 || idx == CHARSET_BITMAP_SIZE (p1))
4801 DEBUG_PRINT (" No match => fast loop.\n");
4802 return 1;
4805 else if ((re_opcode_t) *p1 == charset_not)
4807 int idx;
4808 /* We win if the charset_not inside the loop lists
4809 every character listed in the charset after. */
4810 for (idx = 0; idx < (int) p2[1]; idx++)
4811 if (! (p2[2 + idx] == 0
4812 || (idx < CHARSET_BITMAP_SIZE (p1)
4813 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4814 break;
4816 if (idx == p2[1])
4818 DEBUG_PRINT (" No match => fast loop.\n");
4819 return 1;
4824 break;
4826 case charset_not:
4827 switch (*p1)
4829 case exactn:
4830 case charset:
4831 /* Reuse the code above. */
4832 return mutually_exclusive_p (bufp, p2, p1);
4833 case charset_not:
4834 /* When we have two charset_not, it's very unlikely that
4835 they don't overlap. The union of the two sets of excluded
4836 chars should cover all possible chars, which, as a matter of
4837 fact, is virtually impossible in multibyte buffers. */
4838 break;
4840 break;
4842 case wordend:
4843 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4844 case symend:
4845 return ((re_opcode_t) *p1 == syntaxspec
4846 && (p1[1] == Ssymbol || p1[1] == Sword));
4847 case notsyntaxspec:
4848 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4850 case wordbeg:
4851 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4852 case symbeg:
4853 return ((re_opcode_t) *p1 == notsyntaxspec
4854 && (p1[1] == Ssymbol || p1[1] == Sword));
4855 case syntaxspec:
4856 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4858 case wordbound:
4859 return (((re_opcode_t) *p1 == notsyntaxspec
4860 || (re_opcode_t) *p1 == syntaxspec)
4861 && p1[1] == Sword);
4863 #ifdef emacs
4864 case categoryspec:
4865 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4866 case notcategoryspec:
4867 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4868 #endif /* emacs */
4870 default:
4874 /* Safe default. */
4875 return 0;
4879 /* Matching routines. */
4881 #ifndef emacs /* Emacs never uses this. */
4882 /* re_match is like re_match_2 except it takes only a single string. */
4884 regoff_t
4885 re_match (struct re_pattern_buffer *bufp, const char *string,
4886 size_t size, ssize_t pos, struct re_registers *regs)
4888 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char *) string,
4889 size, pos, regs, size);
4890 return result;
4892 WEAK_ALIAS (__re_match, re_match)
4893 #endif /* not emacs */
4895 /* re_match_2 matches the compiled pattern in BUFP against the
4896 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4897 and SIZE2, respectively). We start matching at POS, and stop
4898 matching at STOP.
4900 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4901 store offsets for the substring each group matched in REGS. See the
4902 documentation for exactly how many groups we fill.
4904 We return -1 if no match, -2 if an internal error (such as the
4905 failure stack overflowing). Otherwise, we return the length of the
4906 matched substring. */
4908 regoff_t
4909 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4910 size_t size1, const char *string2, size_t size2, ssize_t pos,
4911 struct re_registers *regs, ssize_t stop)
4913 regoff_t result;
4915 #ifdef emacs
4916 ssize_t charpos;
4917 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4918 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4919 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4920 #endif
4922 result = re_match_2_internal (bufp, (re_char *) string1, size1,
4923 (re_char *) string2, size2,
4924 pos, regs, stop);
4925 return result;
4927 WEAK_ALIAS (__re_match_2, re_match_2)
4930 /* This is a separate function so that we can force an alloca cleanup
4931 afterwards. */
4932 static regoff_t
4933 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4934 size_t size1, const_re_char *string2, size_t size2,
4935 ssize_t pos, struct re_registers *regs, ssize_t stop)
4937 /* General temporaries. */
4938 int mcnt;
4939 size_t reg;
4941 /* Just past the end of the corresponding string. */
4942 re_char *end1, *end2;
4944 /* Pointers into string1 and string2, just past the last characters in
4945 each to consider matching. */
4946 re_char *end_match_1, *end_match_2;
4948 /* Where we are in the data, and the end of the current string. */
4949 re_char *d, *dend;
4951 /* Used sometimes to remember where we were before starting matching
4952 an operator so that we can go back in case of failure. This "atomic"
4953 behavior of matching opcodes is indispensable to the correctness
4954 of the on_failure_keep_string_jump optimization. */
4955 re_char *dfail;
4957 /* Where we are in the pattern, and the end of the pattern. */
4958 re_char *p = bufp->buffer;
4959 re_char *pend = p + bufp->used;
4961 /* We use this to map every character in the string. */
4962 RE_TRANSLATE_TYPE translate = bufp->translate;
4964 /* Nonzero if BUFP is setup from a multibyte regex. */
4965 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4967 /* Nonzero if STRING1/STRING2 are multibyte. */
4968 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4970 /* Failure point stack. Each place that can handle a failure further
4971 down the line pushes a failure point on this stack. It consists of
4972 regstart, and regend for all registers corresponding to
4973 the subexpressions we're currently inside, plus the number of such
4974 registers, and, finally, two char *'s. The first char * is where
4975 to resume scanning the pattern; the second one is where to resume
4976 scanning the strings. */
4977 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4978 fail_stack_type fail_stack;
4979 #endif
4980 #ifdef DEBUG_COMPILES_ARGUMENTS
4981 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4982 #endif
4984 #if defined REL_ALLOC && defined REGEX_MALLOC
4985 /* This holds the pointer to the failure stack, when
4986 it is allocated relocatably. */
4987 fail_stack_elt_t *failure_stack_ptr;
4988 #endif
4990 /* We fill all the registers internally, independent of what we
4991 return, for use in backreferences. The number here includes
4992 an element for register zero. */
4993 size_t num_regs = bufp->re_nsub + 1;
4995 /* Information on the contents of registers. These are pointers into
4996 the input strings; they record just what was matched (on this
4997 attempt) by a subexpression part of the pattern, that is, the
4998 regnum-th regstart pointer points to where in the pattern we began
4999 matching and the regnum-th regend points to right after where we
5000 stopped matching the regnum-th subexpression. (The zeroth register
5001 keeps track of what the whole pattern matches.) */
5002 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5003 re_char **regstart, **regend;
5004 #endif
5006 /* The following record the register info as found in the above
5007 variables when we find a match better than any we've seen before.
5008 This happens as we backtrack through the failure points, which in
5009 turn happens only if we have not yet matched the entire string. */
5010 unsigned best_regs_set = false;
5011 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5012 re_char **best_regstart, **best_regend;
5013 #endif
5015 /* Logically, this is `best_regend[0]'. But we don't want to have to
5016 allocate space for that if we're not allocating space for anything
5017 else (see below). Also, we never need info about register 0 for
5018 any of the other register vectors, and it seems rather a kludge to
5019 treat `best_regend' differently than the rest. So we keep track of
5020 the end of the best match so far in a separate variable. We
5021 initialize this to NULL so that when we backtrack the first time
5022 and need to test it, it's not garbage. */
5023 re_char *match_end = NULL;
5025 #ifdef DEBUG_COMPILES_ARGUMENTS
5026 /* Counts the total number of registers pushed. */
5027 unsigned num_regs_pushed = 0;
5028 #endif
5030 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5032 REGEX_USE_SAFE_ALLOCA;
5034 INIT_FAIL_STACK ();
5036 #ifdef MATCH_MAY_ALLOCATE
5037 /* Do not bother to initialize all the register variables if there are
5038 no groups in the pattern, as it takes a fair amount of time. If
5039 there are groups, we include space for register 0 (the whole
5040 pattern), even though we never use it, since it simplifies the
5041 array indexing. We should fix this. */
5042 if (bufp->re_nsub)
5044 regstart = REGEX_TALLOC (num_regs, re_char *);
5045 regend = REGEX_TALLOC (num_regs, re_char *);
5046 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5047 best_regend = REGEX_TALLOC (num_regs, re_char *);
5049 if (!(regstart && regend && best_regstart && best_regend))
5051 FREE_VARIABLES ();
5052 return -2;
5055 else
5057 /* We must initialize all our variables to NULL, so that
5058 `FREE_VARIABLES' doesn't try to free them. */
5059 regstart = regend = best_regstart = best_regend = NULL;
5061 #endif /* MATCH_MAY_ALLOCATE */
5063 /* The starting position is bogus. */
5064 if (pos < 0 || pos > size1 + size2)
5066 FREE_VARIABLES ();
5067 return -1;
5070 /* Initialize subexpression text positions to -1 to mark ones that no
5071 start_memory/stop_memory has been seen for. Also initialize the
5072 register information struct. */
5073 for (reg = 1; reg < num_regs; reg++)
5074 regstart[reg] = regend[reg] = NULL;
5076 /* We move `string1' into `string2' if the latter's empty -- but not if
5077 `string1' is null. */
5078 if (size2 == 0 && string1 != NULL)
5080 string2 = string1;
5081 size2 = size1;
5082 string1 = 0;
5083 size1 = 0;
5085 end1 = string1 + size1;
5086 end2 = string2 + size2;
5088 /* `p' scans through the pattern as `d' scans through the data.
5089 `dend' is the end of the input string that `d' points within. `d'
5090 is advanced into the following input string whenever necessary, but
5091 this happens before fetching; therefore, at the beginning of the
5092 loop, `d' can be pointing at the end of a string, but it cannot
5093 equal `string2'. */
5094 if (pos >= size1)
5096 /* Only match within string2. */
5097 d = string2 + pos - size1;
5098 dend = end_match_2 = string2 + stop - size1;
5099 end_match_1 = end1; /* Just to give it a value. */
5101 else
5103 if (stop < size1)
5105 /* Only match within string1. */
5106 end_match_1 = string1 + stop;
5107 /* BEWARE!
5108 When we reach end_match_1, PREFETCH normally switches to string2.
5109 But in the present case, this means that just doing a PREFETCH
5110 makes us jump from `stop' to `gap' within the string.
5111 What we really want here is for the search to stop as
5112 soon as we hit end_match_1. That's why we set end_match_2
5113 to end_match_1 (since PREFETCH fails as soon as we hit
5114 end_match_2). */
5115 end_match_2 = end_match_1;
5117 else
5118 { /* It's important to use this code when stop == size so that
5119 moving `d' from end1 to string2 will not prevent the d == dend
5120 check from catching the end of string. */
5121 end_match_1 = end1;
5122 end_match_2 = string2 + stop - size1;
5124 d = string1 + pos;
5125 dend = end_match_1;
5128 DEBUG_PRINT ("The compiled pattern is: ");
5129 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5130 DEBUG_PRINT ("The string to match is: \"");
5131 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5132 DEBUG_PRINT ("\"\n");
5134 /* This loops over pattern commands. It exits by returning from the
5135 function if the match is complete, or it drops through if the match
5136 fails at this starting point in the input data. */
5137 for (;;)
5139 DEBUG_PRINT ("\n%p: ", p);
5141 if (p == pend)
5143 /* End of pattern means we might have succeeded. */
5144 DEBUG_PRINT ("end of pattern ... ");
5146 /* If we haven't matched the entire string, and we want the
5147 longest match, try backtracking. */
5148 if (d != end_match_2)
5150 /* True if this match is the best seen so far. */
5151 bool best_match_p;
5154 /* True if this match ends in the same string (string1
5155 or string2) as the best previous match. */
5156 bool same_str_p = (FIRST_STRING_P (match_end)
5157 == FIRST_STRING_P (d));
5159 /* AIX compiler got confused when this was combined
5160 with the previous declaration. */
5161 if (same_str_p)
5162 best_match_p = d > match_end;
5163 else
5164 best_match_p = !FIRST_STRING_P (d);
5167 DEBUG_PRINT ("backtracking.\n");
5169 if (!FAIL_STACK_EMPTY ())
5170 { /* More failure points to try. */
5172 /* If exceeds best match so far, save it. */
5173 if (!best_regs_set || best_match_p)
5175 best_regs_set = true;
5176 match_end = d;
5178 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5180 for (reg = 1; reg < num_regs; reg++)
5182 best_regstart[reg] = regstart[reg];
5183 best_regend[reg] = regend[reg];
5186 goto fail;
5189 /* If no failure points, don't restore garbage. And if
5190 last match is real best match, don't restore second
5191 best one. */
5192 else if (best_regs_set && !best_match_p)
5194 restore_best_regs:
5195 /* Restore best match. It may happen that `dend ==
5196 end_match_1' while the restored d is in string2.
5197 For example, the pattern `x.*y.*z' against the
5198 strings `x-' and `y-z-', if the two strings are
5199 not consecutive in memory. */
5200 DEBUG_PRINT ("Restoring best registers.\n");
5202 d = match_end;
5203 dend = ((d >= string1 && d <= end1)
5204 ? end_match_1 : end_match_2);
5206 for (reg = 1; reg < num_regs; reg++)
5208 regstart[reg] = best_regstart[reg];
5209 regend[reg] = best_regend[reg];
5212 } /* d != end_match_2 */
5214 succeed_label:
5215 DEBUG_PRINT ("Accepting match.\n");
5217 /* If caller wants register contents data back, do it. */
5218 if (regs && !bufp->no_sub)
5220 /* Have the register data arrays been allocated? */
5221 if (bufp->regs_allocated == REGS_UNALLOCATED)
5222 { /* No. So allocate them with malloc. We need one
5223 extra element beyond `num_regs' for the `-1' marker
5224 GNU code uses. */
5225 regs->num_regs = max (RE_NREGS, num_regs + 1);
5226 regs->start = TALLOC (regs->num_regs, regoff_t);
5227 regs->end = TALLOC (regs->num_regs, regoff_t);
5228 if (regs->start == NULL || regs->end == NULL)
5230 FREE_VARIABLES ();
5231 return -2;
5233 bufp->regs_allocated = REGS_REALLOCATE;
5235 else if (bufp->regs_allocated == REGS_REALLOCATE)
5236 { /* Yes. If we need more elements than were already
5237 allocated, reallocate them. If we need fewer, just
5238 leave it alone. */
5239 if (regs->num_regs < num_regs + 1)
5241 regs->num_regs = num_regs + 1;
5242 RETALLOC (regs->start, regs->num_regs, regoff_t);
5243 RETALLOC (regs->end, regs->num_regs, regoff_t);
5244 if (regs->start == NULL || regs->end == NULL)
5246 FREE_VARIABLES ();
5247 return -2;
5251 else
5253 /* These braces fend off a "empty body in an else-statement"
5254 warning under GCC when assert expands to nothing. */
5255 assert (bufp->regs_allocated == REGS_FIXED);
5258 /* Convert the pointer data in `regstart' and `regend' to
5259 indices. Register zero has to be set differently,
5260 since we haven't kept track of any info for it. */
5261 if (regs->num_regs > 0)
5263 regs->start[0] = pos;
5264 regs->end[0] = POINTER_TO_OFFSET (d);
5267 /* Go through the first `min (num_regs, regs->num_regs)'
5268 registers, since that is all we initialized. */
5269 for (reg = 1; reg < min (num_regs, regs->num_regs); reg++)
5271 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5272 regs->start[reg] = regs->end[reg] = -1;
5273 else
5275 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5276 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5280 /* If the regs structure we return has more elements than
5281 were in the pattern, set the extra elements to -1. If
5282 we (re)allocated the registers, this is the case,
5283 because we always allocate enough to have at least one
5284 -1 at the end. */
5285 for (reg = num_regs; reg < regs->num_regs; reg++)
5286 regs->start[reg] = regs->end[reg] = -1;
5287 } /* regs && !bufp->no_sub */
5289 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5290 nfailure_points_pushed, nfailure_points_popped,
5291 nfailure_points_pushed - nfailure_points_popped);
5292 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5294 ptrdiff_t dcnt = POINTER_TO_OFFSET (d) - pos;
5296 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5298 FREE_VARIABLES ();
5299 return dcnt;
5302 /* Otherwise match next pattern command. */
5303 switch (*p++)
5305 /* Ignore these. Used to ignore the n of succeed_n's which
5306 currently have n == 0. */
5307 case no_op:
5308 DEBUG_PRINT ("EXECUTING no_op.\n");
5309 break;
5311 case succeed:
5312 DEBUG_PRINT ("EXECUTING succeed.\n");
5313 goto succeed_label;
5315 /* Match the next n pattern characters exactly. The following
5316 byte in the pattern defines n, and the n bytes after that
5317 are the characters to match. */
5318 case exactn:
5319 mcnt = *p++;
5320 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5322 /* Remember the start point to rollback upon failure. */
5323 dfail = d;
5325 #ifndef emacs
5326 /* This is written out as an if-else so we don't waste time
5327 testing `translate' inside the loop. */
5328 if (RE_TRANSLATE_P (translate))
5331 PREFETCH ();
5332 if (RE_TRANSLATE (translate, *d) != *p++)
5334 d = dfail;
5335 goto fail;
5337 d++;
5339 while (--mcnt);
5340 else
5343 PREFETCH ();
5344 if (*d++ != *p++)
5346 d = dfail;
5347 goto fail;
5350 while (--mcnt);
5351 #else /* emacs */
5352 /* The cost of testing `translate' is comparatively small. */
5353 if (target_multibyte)
5356 int pat_charlen, buf_charlen;
5357 int pat_ch, buf_ch;
5359 PREFETCH ();
5360 if (multibyte)
5361 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5362 else
5364 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5365 pat_charlen = 1;
5367 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5369 if (TRANSLATE (buf_ch) != pat_ch)
5371 d = dfail;
5372 goto fail;
5375 p += pat_charlen;
5376 d += buf_charlen;
5377 mcnt -= pat_charlen;
5379 while (mcnt > 0);
5380 else
5383 int pat_charlen;
5384 int pat_ch, buf_ch;
5386 PREFETCH ();
5387 if (multibyte)
5389 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5390 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5392 else
5394 pat_ch = *p;
5395 pat_charlen = 1;
5397 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5398 if (! CHAR_BYTE8_P (buf_ch))
5400 buf_ch = TRANSLATE (buf_ch);
5401 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5402 if (buf_ch < 0)
5403 buf_ch = *d;
5405 else
5406 buf_ch = *d;
5407 if (buf_ch != pat_ch)
5409 d = dfail;
5410 goto fail;
5412 p += pat_charlen;
5413 d++;
5415 while (--mcnt);
5416 #endif
5417 break;
5420 /* Match any character except possibly a newline or a null. */
5421 case anychar:
5423 int buf_charlen;
5424 re_wchar_t buf_ch;
5425 reg_syntax_t syntax;
5427 DEBUG_PRINT ("EXECUTING anychar.\n");
5429 PREFETCH ();
5430 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5431 target_multibyte);
5432 buf_ch = TRANSLATE (buf_ch);
5434 #ifdef emacs
5435 syntax = RE_SYNTAX_EMACS;
5436 #else
5437 syntax = bufp->syntax;
5438 #endif
5440 if ((!(syntax & RE_DOT_NEWLINE) && buf_ch == '\n')
5441 || ((syntax & RE_DOT_NOT_NULL) && buf_ch == '\000'))
5442 goto fail;
5444 DEBUG_PRINT (" Matched \"%d\".\n", *d);
5445 d += buf_charlen;
5447 break;
5450 case charset:
5451 case charset_not:
5453 register unsigned int c, corig;
5454 int len;
5456 /* Whether matching against a unibyte character. */
5457 boolean unibyte_char = false;
5459 DEBUG_PRINT ("EXECUTING charset%s.\n",
5460 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
5462 PREFETCH ();
5463 corig = c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5464 if (target_multibyte)
5466 int c1;
5468 c = TRANSLATE (c);
5469 c1 = RE_CHAR_TO_UNIBYTE (c);
5470 if (c1 >= 0)
5472 unibyte_char = true;
5473 c = c1;
5476 else
5478 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5480 if (! CHAR_BYTE8_P (c1))
5482 c1 = TRANSLATE (c1);
5483 c1 = RE_CHAR_TO_UNIBYTE (c1);
5484 if (c1 >= 0)
5486 unibyte_char = true;
5487 c = c1;
5490 else
5491 unibyte_char = true;
5494 p -= 1;
5495 if (!execute_charset (&p, c, corig, unibyte_char))
5496 goto fail;
5498 d += len;
5500 break;
5503 /* The beginning of a group is represented by start_memory.
5504 The argument is the register number. The text
5505 matched within the group is recorded (in the internal
5506 registers data structure) under the register number. */
5507 case start_memory:
5508 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5510 /* In case we need to undo this operation (via backtracking). */
5511 PUSH_FAILURE_REG (*p);
5513 regstart[*p] = d;
5514 regend[*p] = NULL; /* probably unnecessary. -sm */
5515 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5517 /* Move past the register number and inner group count. */
5518 p += 1;
5519 break;
5522 /* The stop_memory opcode represents the end of a group. Its
5523 argument is the same as start_memory's: the register number. */
5524 case stop_memory:
5525 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5527 assert (!REG_UNSET (regstart[*p]));
5528 /* Strictly speaking, there should be code such as:
5530 assert (REG_UNSET (regend[*p]));
5531 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5533 But the only info to be pushed is regend[*p] and it is known to
5534 be UNSET, so there really isn't anything to push.
5535 Not pushing anything, on the other hand deprives us from the
5536 guarantee that regend[*p] is UNSET since undoing this operation
5537 will not reset its value properly. This is not important since
5538 the value will only be read on the next start_memory or at
5539 the very end and both events can only happen if this stop_memory
5540 is *not* undone. */
5542 regend[*p] = d;
5543 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5545 /* Move past the register number and the inner group count. */
5546 p += 1;
5547 break;
5550 /* \<digit> has been turned into a `duplicate' command which is
5551 followed by the numeric value of <digit> as the register number. */
5552 case duplicate:
5554 register re_char *d2, *dend2;
5555 int regno = *p++; /* Get which register to match against. */
5556 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5558 /* Can't back reference a group which we've never matched. */
5559 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5560 goto fail;
5562 /* Where in input to try to start matching. */
5563 d2 = regstart[regno];
5565 /* Remember the start point to rollback upon failure. */
5566 dfail = d;
5568 /* Where to stop matching; if both the place to start and
5569 the place to stop matching are in the same string, then
5570 set to the place to stop, otherwise, for now have to use
5571 the end of the first string. */
5573 dend2 = ((FIRST_STRING_P (regstart[regno])
5574 == FIRST_STRING_P (regend[regno]))
5575 ? regend[regno] : end_match_1);
5576 for (;;)
5578 ptrdiff_t dcnt;
5580 /* If necessary, advance to next segment in register
5581 contents. */
5582 while (d2 == dend2)
5584 if (dend2 == end_match_2) break;
5585 if (dend2 == regend[regno]) break;
5587 /* End of string1 => advance to string2. */
5588 d2 = string2;
5589 dend2 = regend[regno];
5591 /* At end of register contents => success */
5592 if (d2 == dend2) break;
5594 /* If necessary, advance to next segment in data. */
5595 PREFETCH ();
5597 /* How many characters left in this segment to match. */
5598 dcnt = dend - d;
5600 /* Want how many consecutive characters we can match in
5601 one shot, so, if necessary, adjust the count. */
5602 if (dcnt > dend2 - d2)
5603 dcnt = dend2 - d2;
5605 /* Compare that many; failure if mismatch, else move
5606 past them. */
5607 if (RE_TRANSLATE_P (translate)
5608 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5609 : memcmp (d, d2, dcnt))
5611 d = dfail;
5612 goto fail;
5614 d += dcnt, d2 += dcnt;
5617 break;
5620 /* begline matches the empty string at the beginning of the string
5621 (unless `not_bol' is set in `bufp'), and after newlines. */
5622 case begline:
5623 DEBUG_PRINT ("EXECUTING begline.\n");
5625 if (AT_STRINGS_BEG (d))
5627 if (!bufp->not_bol) break;
5629 else
5631 unsigned c;
5632 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5633 if (c == '\n')
5634 break;
5636 /* In all other cases, we fail. */
5637 goto fail;
5640 /* endline is the dual of begline. */
5641 case endline:
5642 DEBUG_PRINT ("EXECUTING endline.\n");
5644 if (AT_STRINGS_END (d))
5646 if (!bufp->not_eol) break;
5648 else
5650 PREFETCH_NOLIMIT ();
5651 if (*d == '\n')
5652 break;
5654 goto fail;
5657 /* Match at the very beginning of the data. */
5658 case begbuf:
5659 DEBUG_PRINT ("EXECUTING begbuf.\n");
5660 if (AT_STRINGS_BEG (d))
5661 break;
5662 goto fail;
5665 /* Match at the very end of the data. */
5666 case endbuf:
5667 DEBUG_PRINT ("EXECUTING endbuf.\n");
5668 if (AT_STRINGS_END (d))
5669 break;
5670 goto fail;
5673 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5674 pushes NULL as the value for the string on the stack. Then
5675 `POP_FAILURE_POINT' will keep the current value for the
5676 string, instead of restoring it. To see why, consider
5677 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5678 then the . fails against the \n. But the next thing we want
5679 to do is match the \n against the \n; if we restored the
5680 string value, we would be back at the foo.
5682 Because this is used only in specific cases, we don't need to
5683 check all the things that `on_failure_jump' does, to make
5684 sure the right things get saved on the stack. Hence we don't
5685 share its code. The only reason to push anything on the
5686 stack at all is that otherwise we would have to change
5687 `anychar's code to do something besides goto fail in this
5688 case; that seems worse than this. */
5689 case on_failure_keep_string_jump:
5690 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5691 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5692 mcnt, p + mcnt);
5694 PUSH_FAILURE_POINT (p - 3, NULL);
5695 break;
5697 /* A nasty loop is introduced by the non-greedy *? and +?.
5698 With such loops, the stack only ever contains one failure point
5699 at a time, so that a plain on_failure_jump_loop kind of
5700 cycle detection cannot work. Worse yet, such a detection
5701 can not only fail to detect a cycle, but it can also wrongly
5702 detect a cycle (between different instantiations of the same
5703 loop).
5704 So the method used for those nasty loops is a little different:
5705 We use a special cycle-detection-stack-frame which is pushed
5706 when the on_failure_jump_nastyloop failure-point is *popped*.
5707 This special frame thus marks the beginning of one iteration
5708 through the loop and we can hence easily check right here
5709 whether something matched between the beginning and the end of
5710 the loop. */
5711 case on_failure_jump_nastyloop:
5712 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5713 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5714 mcnt, p + mcnt);
5716 assert ((re_opcode_t)p[-4] == no_op);
5718 int cycle = 0;
5719 CHECK_INFINITE_LOOP (p - 4, d);
5720 if (!cycle)
5721 /* If there's a cycle, just continue without pushing
5722 this failure point. The failure point is the "try again"
5723 option, which shouldn't be tried.
5724 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5725 PUSH_FAILURE_POINT (p - 3, d);
5727 break;
5729 /* Simple loop detecting on_failure_jump: just check on the
5730 failure stack if the same spot was already hit earlier. */
5731 case on_failure_jump_loop:
5732 on_failure:
5733 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5734 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5735 mcnt, p + mcnt);
5737 int cycle = 0;
5738 CHECK_INFINITE_LOOP (p - 3, d);
5739 if (cycle)
5740 /* If there's a cycle, get out of the loop, as if the matching
5741 had failed. We used to just `goto fail' here, but that was
5742 aborting the search a bit too early: we want to keep the
5743 empty-loop-match and keep matching after the loop.
5744 We want (x?)*y\1z to match both xxyz and xxyxz. */
5745 p += mcnt;
5746 else
5747 PUSH_FAILURE_POINT (p - 3, d);
5749 break;
5752 /* Uses of on_failure_jump:
5754 Each alternative starts with an on_failure_jump that points
5755 to the beginning of the next alternative. Each alternative
5756 except the last ends with a jump that in effect jumps past
5757 the rest of the alternatives. (They really jump to the
5758 ending jump of the following alternative, because tensioning
5759 these jumps is a hassle.)
5761 Repeats start with an on_failure_jump that points past both
5762 the repetition text and either the following jump or
5763 pop_failure_jump back to this on_failure_jump. */
5764 case on_failure_jump:
5765 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5766 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5767 mcnt, p + mcnt);
5769 PUSH_FAILURE_POINT (p -3, d);
5770 break;
5772 /* This operation is used for greedy *.
5773 Compare the beginning of the repeat with what in the
5774 pattern follows its end. If we can establish that there
5775 is nothing that they would both match, i.e., that we
5776 would have to backtrack because of (as in, e.g., `a*a')
5777 then we can use a non-backtracking loop based on
5778 on_failure_keep_string_jump instead of on_failure_jump. */
5779 case on_failure_jump_smart:
5780 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5781 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5782 mcnt, p + mcnt);
5784 re_char *p1 = p; /* Next operation. */
5785 /* Here, we discard `const', making re_match non-reentrant. */
5786 unsigned char *p2 = (unsigned char *) p + mcnt; /* Jump dest. */
5787 unsigned char *p3 = (unsigned char *) p - 3; /* opcode location. */
5789 p -= 3; /* Reset so that we will re-execute the
5790 instruction once it's been changed. */
5792 EXTRACT_NUMBER (mcnt, p2 - 2);
5794 /* Ensure this is indeed the trivial kind of loop
5795 we are expecting. */
5796 assert (skip_one_char (p1) == p2 - 3);
5797 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5798 DEBUG_STATEMENT (debug += 2);
5799 if (mutually_exclusive_p (bufp, p1, p2))
5801 /* Use a fast `on_failure_keep_string_jump' loop. */
5802 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5803 *p3 = (unsigned char) on_failure_keep_string_jump;
5804 STORE_NUMBER (p2 - 2, mcnt + 3);
5806 else
5808 /* Default to a safe `on_failure_jump' loop. */
5809 DEBUG_PRINT (" smart default => slow loop.\n");
5810 *p3 = (unsigned char) on_failure_jump;
5812 DEBUG_STATEMENT (debug -= 2);
5814 break;
5816 /* Unconditionally jump (without popping any failure points). */
5817 case jump:
5818 unconditional_jump:
5819 maybe_quit ();
5820 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5821 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5822 p += mcnt; /* Do the jump. */
5823 DEBUG_PRINT ("(to %p).\n", p);
5824 break;
5827 /* Have to succeed matching what follows at least n times.
5828 After that, handle like `on_failure_jump'. */
5829 case succeed_n:
5830 /* Signedness doesn't matter since we only compare MCNT to 0. */
5831 EXTRACT_NUMBER (mcnt, p + 2);
5832 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5834 /* Originally, mcnt is how many times we HAVE to succeed. */
5835 if (mcnt != 0)
5837 /* Here, we discard `const', making re_match non-reentrant. */
5838 unsigned char *p2 = (unsigned char *) p + 2; /* counter loc. */
5839 mcnt--;
5840 p += 4;
5841 PUSH_NUMBER (p2, mcnt);
5843 else
5844 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5845 goto on_failure;
5846 break;
5848 case jump_n:
5849 /* Signedness doesn't matter since we only compare MCNT to 0. */
5850 EXTRACT_NUMBER (mcnt, p + 2);
5851 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5853 /* Originally, this is how many times we CAN jump. */
5854 if (mcnt != 0)
5856 /* Here, we discard `const', making re_match non-reentrant. */
5857 unsigned char *p2 = (unsigned char *) p + 2; /* counter loc. */
5858 mcnt--;
5859 PUSH_NUMBER (p2, mcnt);
5860 goto unconditional_jump;
5862 /* If don't have to jump any more, skip over the rest of command. */
5863 else
5864 p += 4;
5865 break;
5867 case set_number_at:
5869 unsigned char *p2; /* Location of the counter. */
5870 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5872 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5873 /* Here, we discard `const', making re_match non-reentrant. */
5874 p2 = (unsigned char *) p + mcnt;
5875 /* Signedness doesn't matter since we only copy MCNT's bits. */
5876 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5877 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5878 PUSH_NUMBER (p2, mcnt);
5879 break;
5882 case wordbound:
5883 case notwordbound:
5885 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5886 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5888 /* We SUCCEED (or FAIL) in one of the following cases: */
5890 /* Case 1: D is at the beginning or the end of string. */
5891 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5892 not = !not;
5893 else
5895 /* C1 is the character before D, S1 is the syntax of C1, C2
5896 is the character at D, and S2 is the syntax of C2. */
5897 re_wchar_t c1, c2;
5898 int s1, s2;
5899 int dummy;
5900 #ifdef emacs
5901 ssize_t offset = PTR_TO_OFFSET (d - 1);
5902 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5903 UPDATE_SYNTAX_TABLE_FAST (charpos);
5904 #endif
5905 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5906 s1 = SYNTAX (c1);
5907 #ifdef emacs
5908 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
5909 #endif
5910 PREFETCH_NOLIMIT ();
5911 GET_CHAR_AFTER (c2, d, dummy);
5912 s2 = SYNTAX (c2);
5914 if (/* Case 2: Only one of S1 and S2 is Sword. */
5915 ((s1 == Sword) != (s2 == Sword))
5916 /* Case 3: Both of S1 and S2 are Sword, and macro
5917 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5918 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5919 not = !not;
5921 if (not)
5922 break;
5923 else
5924 goto fail;
5927 case wordbeg:
5928 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5930 /* We FAIL in one of the following cases: */
5932 /* Case 1: D is at the end of string. */
5933 if (AT_STRINGS_END (d))
5934 goto fail;
5935 else
5937 /* C1 is the character before D, S1 is the syntax of C1, C2
5938 is the character at D, and S2 is the syntax of C2. */
5939 re_wchar_t c1, c2;
5940 int s1, s2;
5941 int dummy;
5942 #ifdef emacs
5943 ssize_t offset = PTR_TO_OFFSET (d);
5944 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5945 UPDATE_SYNTAX_TABLE_FAST (charpos);
5946 #endif
5947 PREFETCH ();
5948 GET_CHAR_AFTER (c2, d, dummy);
5949 s2 = SYNTAX (c2);
5951 /* Case 2: S2 is not Sword. */
5952 if (s2 != Sword)
5953 goto fail;
5955 /* Case 3: D is not at the beginning of string ... */
5956 if (!AT_STRINGS_BEG (d))
5958 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5959 #ifdef emacs
5960 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5961 #endif
5962 s1 = SYNTAX (c1);
5964 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5965 returns 0. */
5966 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5967 goto fail;
5970 break;
5972 case wordend:
5973 DEBUG_PRINT ("EXECUTING wordend.\n");
5975 /* We FAIL in one of the following cases: */
5977 /* Case 1: D is at the beginning of string. */
5978 if (AT_STRINGS_BEG (d))
5979 goto fail;
5980 else
5982 /* C1 is the character before D, S1 is the syntax of C1, C2
5983 is the character at D, and S2 is the syntax of C2. */
5984 re_wchar_t c1, c2;
5985 int s1, s2;
5986 int dummy;
5987 #ifdef emacs
5988 ssize_t offset = PTR_TO_OFFSET (d) - 1;
5989 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5990 UPDATE_SYNTAX_TABLE_FAST (charpos);
5991 #endif
5992 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5993 s1 = SYNTAX (c1);
5995 /* Case 2: S1 is not Sword. */
5996 if (s1 != Sword)
5997 goto fail;
5999 /* Case 3: D is not at the end of string ... */
6000 if (!AT_STRINGS_END (d))
6002 PREFETCH_NOLIMIT ();
6003 GET_CHAR_AFTER (c2, d, dummy);
6004 #ifdef emacs
6005 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos);
6006 #endif
6007 s2 = SYNTAX (c2);
6009 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6010 returns 0. */
6011 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6012 goto fail;
6015 break;
6017 case symbeg:
6018 DEBUG_PRINT ("EXECUTING symbeg.\n");
6020 /* We FAIL in one of the following cases: */
6022 /* Case 1: D is at the end of string. */
6023 if (AT_STRINGS_END (d))
6024 goto fail;
6025 else
6027 /* C1 is the character before D, S1 is the syntax of C1, C2
6028 is the character at D, and S2 is the syntax of C2. */
6029 re_wchar_t c1, c2;
6030 int s1, s2;
6031 #ifdef emacs
6032 ssize_t offset = PTR_TO_OFFSET (d);
6033 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6034 UPDATE_SYNTAX_TABLE_FAST (charpos);
6035 #endif
6036 PREFETCH ();
6037 c2 = RE_STRING_CHAR (d, target_multibyte);
6038 s2 = SYNTAX (c2);
6040 /* Case 2: S2 is neither Sword nor Ssymbol. */
6041 if (s2 != Sword && s2 != Ssymbol)
6042 goto fail;
6044 /* Case 3: D is not at the beginning of string ... */
6045 if (!AT_STRINGS_BEG (d))
6047 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6048 #ifdef emacs
6049 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6050 #endif
6051 s1 = SYNTAX (c1);
6053 /* ... and S1 is Sword or Ssymbol. */
6054 if (s1 == Sword || s1 == Ssymbol)
6055 goto fail;
6058 break;
6060 case symend:
6061 DEBUG_PRINT ("EXECUTING symend.\n");
6063 /* We FAIL in one of the following cases: */
6065 /* Case 1: D is at the beginning of string. */
6066 if (AT_STRINGS_BEG (d))
6067 goto fail;
6068 else
6070 /* C1 is the character before D, S1 is the syntax of C1, C2
6071 is the character at D, and S2 is the syntax of C2. */
6072 re_wchar_t c1, c2;
6073 int s1, s2;
6074 #ifdef emacs
6075 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6076 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6077 UPDATE_SYNTAX_TABLE_FAST (charpos);
6078 #endif
6079 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6080 s1 = SYNTAX (c1);
6082 /* Case 2: S1 is neither Ssymbol nor Sword. */
6083 if (s1 != Sword && s1 != Ssymbol)
6084 goto fail;
6086 /* Case 3: D is not at the end of string ... */
6087 if (!AT_STRINGS_END (d))
6089 PREFETCH_NOLIMIT ();
6090 c2 = RE_STRING_CHAR (d, target_multibyte);
6091 #ifdef emacs
6092 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
6093 #endif
6094 s2 = SYNTAX (c2);
6096 /* ... and S2 is Sword or Ssymbol. */
6097 if (s2 == Sword || s2 == Ssymbol)
6098 goto fail;
6101 break;
6103 case syntaxspec:
6104 case notsyntaxspec:
6106 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6107 mcnt = *p++;
6108 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6109 mcnt);
6110 PREFETCH ();
6111 #ifdef emacs
6113 ssize_t offset = PTR_TO_OFFSET (d);
6114 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6115 UPDATE_SYNTAX_TABLE_FAST (pos1);
6117 #endif
6119 int len;
6120 re_wchar_t c;
6122 GET_CHAR_AFTER (c, d, len);
6123 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6124 goto fail;
6125 d += len;
6128 break;
6130 #ifdef emacs
6131 case at_dot:
6132 DEBUG_PRINT ("EXECUTING at_dot.\n");
6133 if (PTR_BYTE_POS (d) != PT_BYTE)
6134 goto fail;
6135 break;
6137 case categoryspec:
6138 case notcategoryspec:
6140 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6141 mcnt = *p++;
6142 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6143 not ? "not" : "", mcnt);
6144 PREFETCH ();
6147 int len;
6148 re_wchar_t c;
6149 GET_CHAR_AFTER (c, d, len);
6150 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6151 goto fail;
6152 d += len;
6155 break;
6157 #endif /* emacs */
6159 default:
6160 abort ();
6162 continue; /* Successfully executed one pattern command; keep going. */
6165 /* We goto here if a matching operation fails. */
6166 fail:
6167 maybe_quit ();
6168 if (!FAIL_STACK_EMPTY ())
6170 re_char *str, *pat;
6171 /* A restart point is known. Restore to that state. */
6172 DEBUG_PRINT ("\nFAIL:\n");
6173 POP_FAILURE_POINT (str, pat);
6174 switch (*pat++)
6176 case on_failure_keep_string_jump:
6177 assert (str == NULL);
6178 goto continue_failure_jump;
6180 case on_failure_jump_nastyloop:
6181 assert ((re_opcode_t)pat[-2] == no_op);
6182 PUSH_FAILURE_POINT (pat - 2, str);
6183 FALLTHROUGH;
6184 case on_failure_jump_loop:
6185 case on_failure_jump:
6186 case succeed_n:
6187 d = str;
6188 continue_failure_jump:
6189 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6190 p = pat + mcnt;
6191 break;
6193 case no_op:
6194 /* A special frame used for nastyloops. */
6195 goto fail;
6197 default:
6198 abort ();
6201 assert (p >= bufp->buffer && p <= pend);
6203 if (d >= string1 && d <= end1)
6204 dend = end_match_1;
6206 else
6207 break; /* Matching at this starting point really fails. */
6208 } /* for (;;) */
6210 if (best_regs_set)
6211 goto restore_best_regs;
6213 FREE_VARIABLES ();
6215 return -1; /* Failure to match. */
6218 /* Subroutine definitions for re_match_2. */
6220 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6221 bytes; nonzero otherwise. */
6223 static int
6224 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6225 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6227 register re_char *p1 = s1, *p2 = s2;
6228 re_char *p1_end = s1 + len;
6229 re_char *p2_end = s2 + len;
6231 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6232 different lengths, but relying on a single `len' would break this. -sm */
6233 while (p1 < p1_end && p2 < p2_end)
6235 int p1_charlen, p2_charlen;
6236 re_wchar_t p1_ch, p2_ch;
6238 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6239 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6241 if (RE_TRANSLATE (translate, p1_ch)
6242 != RE_TRANSLATE (translate, p2_ch))
6243 return 1;
6245 p1 += p1_charlen, p2 += p2_charlen;
6248 if (p1 != p1_end || p2 != p2_end)
6249 return 1;
6251 return 0;
6254 /* Entry points for GNU code. */
6256 /* re_compile_pattern is the GNU regular expression compiler: it
6257 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6258 Returns 0 if the pattern was valid, otherwise an error string.
6260 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6261 are set in BUFP on entry.
6263 We call regex_compile to do the actual compilation. */
6265 const char *
6266 re_compile_pattern (const char *pattern, size_t length,
6267 #ifdef emacs
6268 bool posix_backtracking, const char *whitespace_regexp,
6269 #endif
6270 struct re_pattern_buffer *bufp)
6272 reg_errcode_t ret;
6274 /* GNU code is written to assume at least RE_NREGS registers will be set
6275 (and at least one extra will be -1). */
6276 bufp->regs_allocated = REGS_UNALLOCATED;
6278 /* And GNU code determines whether or not to get register information
6279 by passing null for the REGS argument to re_match, etc., not by
6280 setting no_sub. */
6281 bufp->no_sub = 0;
6283 ret = regex_compile ((re_char *) pattern, length,
6284 #ifdef emacs
6285 posix_backtracking,
6286 whitespace_regexp,
6287 #else
6288 re_syntax_options,
6289 #endif
6290 bufp);
6292 if (!ret)
6293 return NULL;
6294 return gettext (re_error_msgid[(int) ret]);
6296 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6298 /* Entry points compatible with 4.2 BSD regex library. We don't define
6299 them unless specifically requested. */
6301 #if defined _REGEX_RE_COMP || defined _LIBC
6303 /* BSD has one and only one pattern buffer. */
6304 static struct re_pattern_buffer re_comp_buf;
6306 char *
6307 # ifdef _LIBC
6308 /* Make these definitions weak in libc, so POSIX programs can redefine
6309 these names if they don't use our functions, and still use
6310 regcomp/regexec below without link errors. */
6311 weak_function
6312 # endif
6313 re_comp (const char *s)
6315 reg_errcode_t ret;
6317 if (!s)
6319 if (!re_comp_buf.buffer)
6320 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6321 return (char *) gettext ("No previous regular expression");
6322 return 0;
6325 if (!re_comp_buf.buffer)
6327 re_comp_buf.buffer = malloc (200);
6328 if (re_comp_buf.buffer == NULL)
6329 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6330 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6331 re_comp_buf.allocated = 200;
6333 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6334 if (re_comp_buf.fastmap == NULL)
6335 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6336 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6339 /* Since `re_exec' always passes NULL for the `regs' argument, we
6340 don't need to initialize the pattern buffer fields which affect it. */
6342 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6344 if (!ret)
6345 return NULL;
6347 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6348 return (char *) gettext (re_error_msgid[(int) ret]);
6353 # ifdef _LIBC
6354 weak_function
6355 # endif
6356 re_exec (const char *s)
6358 const size_t len = strlen (s);
6359 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6361 #endif /* _REGEX_RE_COMP */
6363 /* POSIX.2 functions. Don't define these for Emacs. */
6365 #ifndef emacs
6367 /* regcomp takes a regular expression as a string and compiles it.
6369 PREG is a regex_t *. We do not expect any fields to be initialized,
6370 since POSIX says we shouldn't. Thus, we set
6372 `buffer' to the compiled pattern;
6373 `used' to the length of the compiled pattern;
6374 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6375 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6376 RE_SYNTAX_POSIX_BASIC;
6377 `fastmap' to an allocated space for the fastmap;
6378 `fastmap_accurate' to zero;
6379 `re_nsub' to the number of subexpressions in PATTERN.
6381 PATTERN is the address of the pattern string.
6383 CFLAGS is a series of bits which affect compilation.
6385 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6386 use POSIX basic syntax.
6388 If REG_NEWLINE is set, then . and [^...] don't match newline.
6389 Also, regexec will try a match beginning after every newline.
6391 If REG_ICASE is set, then we considers upper- and lowercase
6392 versions of letters to be equivalent when matching.
6394 If REG_NOSUB is set, then when PREG is passed to regexec, that
6395 routine will report only success or failure, and nothing about the
6396 registers.
6398 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6399 the return codes and their meanings.) */
6401 reg_errcode_t
6402 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6403 int cflags)
6405 reg_errcode_t ret;
6406 reg_syntax_t syntax
6407 = (cflags & REG_EXTENDED) ?
6408 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6410 /* regex_compile will allocate the space for the compiled pattern. */
6411 preg->buffer = 0;
6412 preg->allocated = 0;
6413 preg->used = 0;
6415 /* Try to allocate space for the fastmap. */
6416 preg->fastmap = malloc (1 << BYTEWIDTH);
6418 if (cflags & REG_ICASE)
6420 unsigned i;
6422 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6423 if (preg->translate == NULL)
6424 return (int) REG_ESPACE;
6426 /* Map uppercase characters to corresponding lowercase ones. */
6427 for (i = 0; i < CHAR_SET_SIZE; i++)
6428 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6430 else
6431 preg->translate = NULL;
6433 /* If REG_NEWLINE is set, newlines are treated differently. */
6434 if (cflags & REG_NEWLINE)
6435 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6436 syntax &= ~RE_DOT_NEWLINE;
6437 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6439 else
6440 syntax |= RE_NO_NEWLINE_ANCHOR;
6442 preg->no_sub = !!(cflags & REG_NOSUB);
6444 /* POSIX says a null character in the pattern terminates it, so we
6445 can use strlen here in compiling the pattern. */
6446 ret = regex_compile ((re_char *) pattern, strlen (pattern), syntax, preg);
6448 /* POSIX doesn't distinguish between an unmatched open-group and an
6449 unmatched close-group: both are REG_EPAREN. */
6450 if (ret == REG_ERPAREN)
6451 ret = REG_EPAREN;
6453 if (ret == REG_NOERROR && preg->fastmap)
6454 { /* Compute the fastmap now, since regexec cannot modify the pattern
6455 buffer. */
6456 re_compile_fastmap (preg);
6457 if (preg->can_be_null)
6458 { /* The fastmap can't be used anyway. */
6459 free (preg->fastmap);
6460 preg->fastmap = NULL;
6463 return ret;
6465 WEAK_ALIAS (__regcomp, regcomp)
6468 /* regexec searches for a given pattern, specified by PREG, in the
6469 string STRING.
6471 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6472 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6473 least NMATCH elements, and we set them to the offsets of the
6474 corresponding matched substrings.
6476 EFLAGS specifies `execution flags' which affect matching: if
6477 REG_NOTBOL is set, then ^ does not match at the beginning of the
6478 string; if REG_NOTEOL is set, then $ does not match at the end.
6480 We return 0 if we find a match and REG_NOMATCH if not. */
6482 reg_errcode_t
6483 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6484 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6486 regoff_t ret;
6487 struct re_registers regs;
6488 regex_t private_preg;
6489 size_t len = strlen (string);
6490 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6492 private_preg = *preg;
6494 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6495 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6497 /* The user has told us exactly how many registers to return
6498 information about, via `nmatch'. We have to pass that on to the
6499 matching routines. */
6500 private_preg.regs_allocated = REGS_FIXED;
6502 if (want_reg_info)
6504 regs.num_regs = nmatch;
6505 regs.start = TALLOC (nmatch * 2, regoff_t);
6506 if (regs.start == NULL)
6507 return REG_NOMATCH;
6508 regs.end = regs.start + nmatch;
6511 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6512 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6513 was a little bit longer but still only matching the real part.
6514 This works because the `endline' will check for a '\n' and will find a
6515 '\0', correctly deciding that this is not the end of a line.
6516 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6517 a convenient '\0' there. For all we know, the string could be preceded
6518 by '\n' which would throw things off. */
6520 /* Perform the searching operation. */
6521 ret = re_search (&private_preg, string, len,
6522 /* start: */ 0, /* range: */ len,
6523 want_reg_info ? &regs : 0);
6525 /* Copy the register information to the POSIX structure. */
6526 if (want_reg_info)
6528 if (ret >= 0)
6530 unsigned r;
6532 for (r = 0; r < nmatch; r++)
6534 pmatch[r].rm_so = regs.start[r];
6535 pmatch[r].rm_eo = regs.end[r];
6539 /* If we needed the temporary register info, free the space now. */
6540 free (regs.start);
6543 /* We want zero return to mean success, unlike `re_search'. */
6544 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6546 WEAK_ALIAS (__regexec, regexec)
6549 /* Returns a message corresponding to an error code, ERR_CODE, returned
6550 from either regcomp or regexec. We don't use PREG here.
6552 ERR_CODE was previously called ERRCODE, but that name causes an
6553 error with msvc8 compiler. */
6555 size_t
6556 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6558 const char *msg;
6559 size_t msg_size;
6561 if (err_code < 0
6562 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6563 /* Only error codes returned by the rest of the code should be passed
6564 to this routine. If we are given anything else, or if other regex
6565 code generates an invalid error code, then the program has a bug.
6566 Dump core so we can fix it. */
6567 abort ();
6569 msg = gettext (re_error_msgid[err_code]);
6571 msg_size = strlen (msg) + 1; /* Includes the null. */
6573 if (errbuf_size != 0)
6575 if (msg_size > errbuf_size)
6577 memcpy (errbuf, msg, errbuf_size - 1);
6578 errbuf[errbuf_size - 1] = 0;
6580 else
6581 strcpy (errbuf, msg);
6584 return msg_size;
6586 WEAK_ALIAS (__regerror, regerror)
6589 /* Free dynamically allocated space used by PREG. */
6591 void
6592 regfree (regex_t *preg)
6594 free (preg->buffer);
6595 preg->buffer = NULL;
6597 preg->allocated = 0;
6598 preg->used = 0;
6600 free (preg->fastmap);
6601 preg->fastmap = NULL;
6602 preg->fastmap_accurate = 0;
6604 free (preg->translate);
6605 preg->translate = NULL;
6607 WEAK_ALIAS (__regfree, regfree)
6609 #endif /* not emacs */