Use 'header-line-highlight' face in proced and erc
[emacs.git] / src / regex.c
blob0dbb47309e486039f09b0623548cdb0e29845a52
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993-2017 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* TODO:
21 - structure the opcode space into opcode+flag.
22 - merge with glibc's regex.[ch].
23 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
24 need to modify the compiled regexp so that re_match can be reentrant.
25 - get rid of on_failure_jump_smart by doing the optimization in re_comp
26 rather than at run-time, so that re_match can be reentrant.
29 /* AIX requires this to be the first thing in the file. */
30 #if defined _AIX && !defined REGEX_MALLOC
31 #pragma alloca
32 #endif
34 /* Ignore some GCC warnings for now. This section should go away
35 once the Emacs and Gnulib regex code is merged. */
36 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__) || defined __clang__
37 # pragma GCC diagnostic ignored "-Wstrict-overflow"
38 # ifndef emacs
39 # pragma GCC diagnostic ignored "-Wunused-function"
40 # pragma GCC diagnostic ignored "-Wunused-macros"
41 # pragma GCC diagnostic ignored "-Wunused-result"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
43 # endif
44 #endif
46 #if 4 < __GNUC__ + (6 <= __GNUC_MINOR__) && ! defined __clang__
47 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
48 #endif
50 #include <config.h>
52 #include <stddef.h>
53 #include <stdlib.h>
55 #ifdef emacs
56 /* We need this for `regex.h', and perhaps for the Emacs include files. */
57 # include <sys/types.h>
58 #endif
60 /* Whether to use ISO C Amendment 1 wide char functions.
61 Those should not be used for Emacs since it uses its own. */
62 #if defined _LIBC
63 #define WIDE_CHAR_SUPPORT 1
64 #else
65 #define WIDE_CHAR_SUPPORT \
66 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
67 #endif
69 /* For platform which support the ISO C amendment 1 functionality we
70 support user defined character classes. */
71 #if WIDE_CHAR_SUPPORT
72 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
73 # include <wchar.h>
74 # include <wctype.h>
75 #endif
77 #ifdef _LIBC
78 /* We have to keep the namespace clean. */
79 # define regfree(preg) __regfree (preg)
80 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
81 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
82 # define regerror(err_code, preg, errbuf, errbuf_size) \
83 __regerror (err_code, preg, errbuf, errbuf_size)
84 # define re_set_registers(bu, re, nu, st, en) \
85 __re_set_registers (bu, re, nu, st, en)
86 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
87 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
88 # define re_match(bufp, string, size, pos, regs) \
89 __re_match (bufp, string, size, pos, regs)
90 # define re_search(bufp, string, size, startpos, range, regs) \
91 __re_search (bufp, string, size, startpos, range, regs)
92 # define re_compile_pattern(pattern, length, bufp) \
93 __re_compile_pattern (pattern, length, bufp)
94 # define re_set_syntax(syntax) __re_set_syntax (syntax)
95 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
96 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
97 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
99 /* Make sure we call libc's function even if the user overrides them. */
100 # define btowc __btowc
101 # define iswctype __iswctype
102 # define wctype __wctype
104 # define WEAK_ALIAS(a,b) weak_alias (a, b)
106 /* We are also using some library internals. */
107 # include <locale/localeinfo.h>
108 # include <locale/elem-hash.h>
109 # include <langinfo.h>
110 #else
111 # define WEAK_ALIAS(a,b)
112 #endif
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
117 #else
118 # define gettext(msgid) (msgid)
119 #endif
121 #ifndef gettext_noop
122 /* This define is so xgettext can find the internationalizable
123 strings. */
124 # define gettext_noop(String) String
125 #endif
127 /* The `emacs' switch turns on certain matching commands
128 that make sense only in Emacs. */
129 #ifdef emacs
131 # include "lisp.h"
132 # include "character.h"
133 # include "buffer.h"
135 # include "syntax.h"
136 # include "category.h"
138 /* Make syntax table lookup grant data in gl_state. */
139 # define SYNTAX(c) syntax_property (c, 1)
141 # ifdef malloc
142 # undef malloc
143 # endif
144 # define malloc xmalloc
145 # ifdef realloc
146 # undef realloc
147 # endif
148 # define realloc xrealloc
149 # ifdef free
150 # undef free
151 # endif
152 # define free xfree
154 /* Converts the pointer to the char to BEG-based offset from the start. */
155 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
156 /* Strings are 0-indexed, buffers are 1-indexed; we pun on the boolean
157 result to get the right base index. */
158 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
160 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
161 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
162 # define RE_STRING_CHAR(p, multibyte) \
163 (multibyte ? (STRING_CHAR (p)) : (*(p)))
164 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
165 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
167 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
169 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
171 /* Set C a (possibly converted to multibyte) character before P. P
172 points into a string which is the virtual concatenation of STR1
173 (which ends at END1) or STR2 (which ends at END2). */
174 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
175 do { \
176 if (target_multibyte) \
178 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
179 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
180 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
181 c = STRING_CHAR (dtemp); \
183 else \
185 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
188 } while (0)
190 /* Set C a (possibly converted to multibyte) character at P, and set
191 LEN to the byte length of that character. */
192 # define GET_CHAR_AFTER(c, p, len) \
193 do { \
194 if (target_multibyte) \
195 (c) = STRING_CHAR_AND_LENGTH (p, len); \
196 else \
198 (c) = *p; \
199 len = 1; \
200 (c) = RE_CHAR_TO_MULTIBYTE (c); \
202 } while (0)
204 #else /* not emacs */
206 /* If we are not linking with Emacs proper,
207 we can't use the relocating allocator
208 even if config.h says that we can. */
209 # undef REL_ALLOC
211 # include <unistd.h>
213 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
215 static void *
216 xmalloc (size_t size)
218 void *val = malloc (size);
219 if (!val && size)
221 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
222 exit (1);
224 return val;
227 static void *
228 xrealloc (void *block, size_t size)
230 void *val;
231 /* We must call malloc explicitly when BLOCK is 0, since some
232 reallocs don't do this. */
233 if (! block)
234 val = malloc (size);
235 else
236 val = realloc (block, size);
237 if (!val && size)
239 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
240 exit (1);
242 return val;
245 # ifdef malloc
246 # undef malloc
247 # endif
248 # define malloc xmalloc
249 # ifdef realloc
250 # undef realloc
251 # endif
252 # define realloc xrealloc
254 # include <stdbool.h>
255 # include <string.h>
257 /* Define the syntax stuff for \<, \>, etc. */
259 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
260 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
262 /* Dummy macros for non-Emacs environments. */
263 # define MAX_MULTIBYTE_LENGTH 1
264 # define RE_MULTIBYTE_P(x) 0
265 # define RE_TARGET_MULTIBYTE_P(x) 0
266 # define WORD_BOUNDARY_P(c1, c2) (0)
267 # define BYTES_BY_CHAR_HEAD(p) (1)
268 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
269 # define STRING_CHAR(p) (*(p))
270 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
271 # define CHAR_STRING(c, s) (*(s) = (c), 1)
272 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
273 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
274 # define RE_CHAR_TO_MULTIBYTE(c) (c)
275 # define RE_CHAR_TO_UNIBYTE(c) (c)
276 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
277 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
278 # define GET_CHAR_AFTER(c, p, len) \
279 (c = *p, len = 1)
280 # define CHAR_BYTE8_P(c) (0)
281 # define CHAR_LEADING_CODE(c) (c)
283 #endif /* not emacs */
285 #ifndef RE_TRANSLATE
286 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
287 # define RE_TRANSLATE_P(TBL) (TBL)
288 #endif
290 /* Get the interface, including the syntax bits. */
291 #include "regex.h"
293 /* isalpha etc. are used for the character classes. */
294 #include <ctype.h>
296 #ifdef emacs
298 /* 1 if C is an ASCII character. */
299 # define IS_REAL_ASCII(c) ((c) < 0200)
301 /* 1 if C is a unibyte character. */
302 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
304 /* The Emacs definitions should not be directly affected by locales. */
306 /* In Emacs, these are only used for single-byte characters. */
307 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
308 # define ISCNTRL(c) ((c) < ' ')
309 # define ISXDIGIT(c) (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 */
4043 case on_failure_jump:
4044 case on_failure_keep_string_jump:
4045 case on_failure_jump_nastyloop:
4046 case on_failure_jump_loop:
4047 case on_failure_jump_smart:
4048 EXTRACT_NUMBER_AND_INCR (j, p);
4049 if (p + j <= p1)
4050 ; /* Backward jump to be ignored. */
4051 else
4052 { /* We have to look down both arms.
4053 We first go down the "straight" path so as to minimize
4054 stack usage when going through alternatives. */
4055 int r = analyze_first (p, pend, fastmap, multibyte);
4056 if (r) return r;
4057 p += j;
4059 continue;
4062 case jump_n:
4063 /* This code simply does not properly handle forward jump_n. */
4064 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4065 p += 4;
4066 /* jump_n can either jump or fall through. The (backward) jump
4067 case has already been handled, so we only need to look at the
4068 fallthrough case. */
4069 continue;
4071 case succeed_n:
4072 /* If N == 0, it should be an on_failure_jump_loop instead. */
4073 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4074 p += 4;
4075 /* We only care about one iteration of the loop, so we don't
4076 need to consider the case where this behaves like an
4077 on_failure_jump. */
4078 continue;
4081 case set_number_at:
4082 p += 4;
4083 continue;
4086 case start_memory:
4087 case stop_memory:
4088 p += 1;
4089 continue;
4092 default:
4093 abort (); /* We have listed all the cases. */
4094 } /* switch *p++ */
4096 /* Getting here means we have found the possible starting
4097 characters for one path of the pattern -- and that the empty
4098 string does not match. We need not follow this path further. */
4099 return 0;
4100 } /* while p */
4102 /* We reached the end without matching anything. */
4103 return 1;
4105 } /* analyze_first */
4107 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4108 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4109 characters can start a string that matches the pattern. This fastmap
4110 is used by re_search to skip quickly over impossible starting points.
4112 Character codes above (1 << BYTEWIDTH) are not represented in the
4113 fastmap, but the leading codes are represented. Thus, the fastmap
4114 indicates which character sets could start a match.
4116 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4117 area as BUFP->fastmap.
4119 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4120 the pattern buffer.
4122 Returns 0 if we succeed, -2 if an internal error. */
4125 re_compile_fastmap (struct re_pattern_buffer *bufp)
4127 char *fastmap = bufp->fastmap;
4128 int analysis;
4130 assert (fastmap && bufp->buffer);
4132 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4133 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4135 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4136 fastmap, RE_MULTIBYTE_P (bufp));
4137 bufp->can_be_null = (analysis != 0);
4138 return 0;
4139 } /* re_compile_fastmap */
4141 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4142 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4143 this memory for recording register information. STARTS and ENDS
4144 must be allocated using the malloc library routine, and must each
4145 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4147 If NUM_REGS == 0, then subsequent matches should allocate their own
4148 register data.
4150 Unless this function is called, the first search or match using
4151 PATTERN_BUFFER will allocate its own register data, without
4152 freeing the old data. */
4154 void
4155 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4157 if (num_regs)
4159 bufp->regs_allocated = REGS_REALLOCATE;
4160 regs->num_regs = num_regs;
4161 regs->start = starts;
4162 regs->end = ends;
4164 else
4166 bufp->regs_allocated = REGS_UNALLOCATED;
4167 regs->num_regs = 0;
4168 regs->start = regs->end = 0;
4171 WEAK_ALIAS (__re_set_registers, re_set_registers)
4173 /* Searching routines. */
4175 /* Like re_search_2, below, but only one string is specified, and
4176 doesn't let you say where to stop matching. */
4178 regoff_t
4179 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4180 ssize_t startpos, ssize_t range, struct re_registers *regs)
4182 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4183 regs, size);
4185 WEAK_ALIAS (__re_search, re_search)
4187 /* Head address of virtual concatenation of string. */
4188 #define HEAD_ADDR_VSTRING(P) \
4189 (((P) >= size1 ? string2 : string1))
4191 /* Address of POS in the concatenation of virtual string. */
4192 #define POS_ADDR_VSTRING(POS) \
4193 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4195 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4196 virtual concatenation of STRING1 and STRING2, starting first at index
4197 STARTPOS, then at STARTPOS + 1, and so on.
4199 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4201 RANGE is how far to scan while trying to match. RANGE = 0 means try
4202 only at STARTPOS; in general, the last start tried is STARTPOS +
4203 RANGE.
4205 In REGS, return the indices of the virtual concatenation of STRING1
4206 and STRING2 that matched the entire BUFP->buffer and its contained
4207 subexpressions.
4209 Do not consider matching one past the index STOP in the virtual
4210 concatenation of STRING1 and STRING2.
4212 We return either the position in the strings at which the match was
4213 found, -1 if no match, or -2 if error (such as failure
4214 stack overflow). */
4216 regoff_t
4217 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4218 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4219 struct re_registers *regs, ssize_t stop)
4221 regoff_t val;
4222 re_char *string1 = (re_char *) str1;
4223 re_char *string2 = (re_char *) str2;
4224 register char *fastmap = bufp->fastmap;
4225 register RE_TRANSLATE_TYPE translate = bufp->translate;
4226 size_t total_size = size1 + size2;
4227 ssize_t endpos = startpos + range;
4228 boolean anchored_start;
4229 /* Nonzero if we are searching multibyte string. */
4230 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4232 /* Check for out-of-range STARTPOS. */
4233 if (startpos < 0 || startpos > total_size)
4234 return -1;
4236 /* Fix up RANGE if it might eventually take us outside
4237 the virtual concatenation of STRING1 and STRING2.
4238 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4239 if (endpos < 0)
4240 range = 0 - startpos;
4241 else if (endpos > total_size)
4242 range = total_size - startpos;
4244 /* If the search isn't to be a backwards one, don't waste time in a
4245 search for a pattern anchored at beginning of buffer. */
4246 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4248 if (startpos > 0)
4249 return -1;
4250 else
4251 range = 0;
4254 #ifdef emacs
4255 /* In a forward search for something that starts with \=.
4256 don't keep searching past point. */
4257 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4259 range = PT_BYTE - BEGV_BYTE - startpos;
4260 if (range < 0)
4261 return -1;
4263 #endif /* emacs */
4265 /* Update the fastmap now if not correct already. */
4266 if (fastmap && !bufp->fastmap_accurate)
4267 re_compile_fastmap (bufp);
4269 /* See whether the pattern is anchored. */
4270 anchored_start = (bufp->buffer[0] == begline);
4272 #ifdef emacs
4273 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4275 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4277 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4279 #endif
4281 /* Loop through the string, looking for a place to start matching. */
4282 for (;;)
4284 /* If the pattern is anchored,
4285 skip quickly past places we cannot match.
4286 We don't bother to treat startpos == 0 specially
4287 because that case doesn't repeat. */
4288 if (anchored_start && startpos > 0)
4290 if (! ((startpos <= size1 ? string1[startpos - 1]
4291 : string2[startpos - size1 - 1])
4292 == '\n'))
4293 goto advance;
4296 /* If a fastmap is supplied, skip quickly over characters that
4297 cannot be the start of a match. If the pattern can match the
4298 null string, however, we don't need to skip characters; we want
4299 the first null string. */
4300 if (fastmap && startpos < total_size && !bufp->can_be_null)
4302 register re_char *d;
4303 register re_wchar_t buf_ch;
4305 d = POS_ADDR_VSTRING (startpos);
4307 if (range > 0) /* Searching forwards. */
4309 ssize_t irange = range, lim = 0;
4311 if (startpos < size1 && startpos + range >= size1)
4312 lim = range - (size1 - startpos);
4314 /* Written out as an if-else to avoid testing `translate'
4315 inside the loop. */
4316 if (RE_TRANSLATE_P (translate))
4318 if (multibyte)
4319 while (range > lim)
4321 int buf_charlen;
4323 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4324 buf_ch = RE_TRANSLATE (translate, buf_ch);
4325 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4326 break;
4328 range -= buf_charlen;
4329 d += buf_charlen;
4331 else
4332 while (range > lim)
4334 register re_wchar_t ch, translated;
4336 buf_ch = *d;
4337 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4338 translated = RE_TRANSLATE (translate, ch);
4339 if (translated != ch
4340 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4341 buf_ch = ch;
4342 if (fastmap[buf_ch])
4343 break;
4344 d++;
4345 range--;
4348 else
4350 if (multibyte)
4351 while (range > lim)
4353 int buf_charlen;
4355 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4356 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4357 break;
4358 range -= buf_charlen;
4359 d += buf_charlen;
4361 else
4362 while (range > lim && !fastmap[*d])
4364 d++;
4365 range--;
4368 startpos += irange - range;
4370 else /* Searching backwards. */
4372 if (multibyte)
4374 buf_ch = STRING_CHAR (d);
4375 buf_ch = TRANSLATE (buf_ch);
4376 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4377 goto advance;
4379 else
4381 register re_wchar_t ch, translated;
4383 buf_ch = *d;
4384 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4385 translated = TRANSLATE (ch);
4386 if (translated != ch
4387 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4388 buf_ch = ch;
4389 if (! fastmap[TRANSLATE (buf_ch)])
4390 goto advance;
4395 /* If can't match the null string, and that's all we have left, fail. */
4396 if (range >= 0 && startpos == total_size && fastmap
4397 && !bufp->can_be_null)
4398 return -1;
4400 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4401 startpos, regs, stop);
4403 if (val >= 0)
4404 return startpos;
4406 if (val == -2)
4407 return -2;
4409 advance:
4410 if (!range)
4411 break;
4412 else if (range > 0)
4414 /* Update STARTPOS to the next character boundary. */
4415 if (multibyte)
4417 re_char *p = POS_ADDR_VSTRING (startpos);
4418 int len = BYTES_BY_CHAR_HEAD (*p);
4420 range -= len;
4421 if (range < 0)
4422 break;
4423 startpos += len;
4425 else
4427 range--;
4428 startpos++;
4431 else
4433 range++;
4434 startpos--;
4436 /* Update STARTPOS to the previous character boundary. */
4437 if (multibyte)
4439 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4440 re_char *p0 = p;
4441 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4443 /* Find the head of multibyte form. */
4444 PREV_CHAR_BOUNDARY (p, phead);
4445 range += p0 - 1 - p;
4446 if (range > 0)
4447 break;
4449 startpos -= p0 - 1 - p;
4453 return -1;
4454 } /* re_search_2 */
4455 WEAK_ALIAS (__re_search_2, re_search_2)
4457 /* Declarations and macros for re_match_2. */
4459 static int bcmp_translate (re_char *s1, re_char *s2,
4460 register ssize_t len,
4461 RE_TRANSLATE_TYPE translate,
4462 const int multibyte);
4464 /* This converts PTR, a pointer into one of the search strings `string1'
4465 and `string2' into an offset from the beginning of that string. */
4466 #define POINTER_TO_OFFSET(ptr) \
4467 (FIRST_STRING_P (ptr) \
4468 ? (ptr) - string1 \
4469 : (ptr) - string2 + (ptrdiff_t) size1)
4471 /* Call before fetching a character with *d. This switches over to
4472 string2 if necessary.
4473 Check re_match_2_internal for a discussion of why end_match_2 might
4474 not be within string2 (but be equal to end_match_1 instead). */
4475 #define PREFETCH() \
4476 while (d == dend) \
4478 /* End of string2 => fail. */ \
4479 if (dend == end_match_2) \
4480 goto fail; \
4481 /* End of string1 => advance to string2. */ \
4482 d = string2; \
4483 dend = end_match_2; \
4486 /* Call before fetching a char with *d if you already checked other limits.
4487 This is meant for use in lookahead operations like wordend, etc..
4488 where we might need to look at parts of the string that might be
4489 outside of the LIMITs (i.e past `stop'). */
4490 #define PREFETCH_NOLIMIT() \
4491 if (d == end1) \
4493 d = string2; \
4494 dend = end_match_2; \
4497 /* Test if at very beginning or at very end of the virtual concatenation
4498 of `string1' and `string2'. If only one string, it's `string2'. */
4499 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4500 #define AT_STRINGS_END(d) ((d) == end2)
4502 /* Disabled due to a compiler bug -- see comment at case wordbound */
4504 /* The comment at case wordbound is following one, but we don't use
4505 AT_WORD_BOUNDARY anymore to support multibyte form.
4507 The DEC Alpha C compiler 3.x generates incorrect code for the
4508 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4509 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4510 macro and introducing temporary variables works around the bug. */
4512 #if 0
4513 /* Test if D points to a character which is word-constituent. We have
4514 two special cases to check for: if past the end of string1, look at
4515 the first character in string2; and if before the beginning of
4516 string2, look at the last character in string1. */
4517 #define WORDCHAR_P(d) \
4518 (SYNTAX ((d) == end1 ? *string2 \
4519 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4520 == Sword)
4522 /* Test if the character before D and the one at D differ with respect
4523 to being word-constituent. */
4524 #define AT_WORD_BOUNDARY(d) \
4525 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4526 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4527 #endif
4529 /* Free everything we malloc. */
4530 #ifdef MATCH_MAY_ALLOCATE
4531 # define FREE_VAR(var) \
4532 do { \
4533 if (var) \
4535 REGEX_FREE (var); \
4536 var = NULL; \
4538 } while (0)
4539 # define FREE_VARIABLES() \
4540 do { \
4541 REGEX_FREE_STACK (fail_stack.stack); \
4542 FREE_VAR (regstart); \
4543 FREE_VAR (regend); \
4544 FREE_VAR (best_regstart); \
4545 FREE_VAR (best_regend); \
4546 REGEX_SAFE_FREE (); \
4547 } while (0)
4548 #else
4549 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4550 #endif /* not MATCH_MAY_ALLOCATE */
4553 /* Optimization routines. */
4555 /* If the operation is a match against one or more chars,
4556 return a pointer to the next operation, else return NULL. */
4557 static re_char *
4558 skip_one_char (const_re_char *p)
4560 switch (*p++)
4562 case anychar:
4563 break;
4565 case exactn:
4566 p += *p + 1;
4567 break;
4569 case charset_not:
4570 case charset:
4571 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4573 int mcnt;
4574 p = CHARSET_RANGE_TABLE (p - 1);
4575 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4576 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4578 else
4579 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4580 break;
4582 case syntaxspec:
4583 case notsyntaxspec:
4584 #ifdef emacs
4585 case categoryspec:
4586 case notcategoryspec:
4587 #endif /* emacs */
4588 p++;
4589 break;
4591 default:
4592 p = NULL;
4594 return p;
4598 /* Jump over non-matching operations. */
4599 static re_char *
4600 skip_noops (const_re_char *p, const_re_char *pend)
4602 int mcnt;
4603 while (p < pend)
4605 switch (*p)
4607 case start_memory:
4608 case stop_memory:
4609 p += 2; break;
4610 case no_op:
4611 p += 1; break;
4612 case jump:
4613 p += 1;
4614 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4615 p += mcnt;
4616 break;
4617 default:
4618 return p;
4621 assert (p == pend);
4622 return p;
4625 /* Test if C matches charset op. *PP points to the charset or charset_not
4626 opcode. When the function finishes, *PP will be advanced past that opcode.
4627 C is character to test (possibly after translations) and CORIG is original
4628 character (i.e. without any translations). UNIBYTE denotes whether c is
4629 unibyte or multibyte character. */
4630 static bool
4631 execute_charset (const_re_char **pp, unsigned c, unsigned corig, bool unibyte)
4633 re_char *p = *pp, *rtp = NULL;
4634 bool not = (re_opcode_t) *p == charset_not;
4636 if (CHARSET_RANGE_TABLE_EXISTS_P (p))
4638 int count;
4639 rtp = CHARSET_RANGE_TABLE (p);
4640 EXTRACT_NUMBER_AND_INCR (count, rtp);
4641 *pp = CHARSET_RANGE_TABLE_END ((rtp), (count));
4643 else
4644 *pp += 2 + CHARSET_BITMAP_SIZE (p);
4646 if (unibyte && c < (1 << BYTEWIDTH))
4647 { /* Lookup bitmap. */
4648 /* Cast to `unsigned' instead of `unsigned char' in
4649 case the bit list is a full 32 bytes long. */
4650 if (c < (unsigned) (CHARSET_BITMAP_SIZE (p) * BYTEWIDTH)
4651 && p[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4652 return !not;
4654 #ifdef emacs
4655 else if (rtp)
4657 int class_bits = CHARSET_RANGE_TABLE_BITS (p);
4658 re_wchar_t range_start, range_end;
4660 /* Sort tests by the most commonly used classes with some adjustment to which
4661 tests are easiest to perform. Take a look at comment in re_wctype_parse
4662 for table with frequencies of character class names. */
4664 if ((class_bits & BIT_MULTIBYTE) ||
4665 (class_bits & BIT_ALNUM && ISALNUM (c)) ||
4666 (class_bits & BIT_ALPHA && ISALPHA (c)) ||
4667 (class_bits & BIT_SPACE && ISSPACE (c)) ||
4668 (class_bits & BIT_BLANK && ISBLANK (c)) ||
4669 (class_bits & BIT_WORD && ISWORD (c)) ||
4670 ((class_bits & BIT_UPPER) &&
4671 (ISUPPER (c) || (corig != c &&
4672 c == downcase (corig) && ISLOWER (c)))) ||
4673 ((class_bits & BIT_LOWER) &&
4674 (ISLOWER (c) || (corig != c &&
4675 c == upcase (corig) && ISUPPER(c)))) ||
4676 (class_bits & BIT_PUNCT && ISPUNCT (c)) ||
4677 (class_bits & BIT_GRAPH && ISGRAPH (c)) ||
4678 (class_bits & BIT_PRINT && ISPRINT (c)))
4679 return !not;
4681 for (p = *pp; rtp < p; rtp += 2 * 3)
4683 EXTRACT_CHARACTER (range_start, rtp);
4684 EXTRACT_CHARACTER (range_end, rtp + 3);
4685 if (range_start <= c && c <= range_end)
4686 return !not;
4689 #endif /* emacs */
4690 return not;
4693 /* Non-zero if "p1 matches something" implies "p2 fails". */
4694 static int
4695 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4696 const_re_char *p2)
4698 re_opcode_t op2;
4699 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4700 unsigned char *pend = bufp->buffer + bufp->used;
4702 assert (p1 >= bufp->buffer && p1 < pend
4703 && p2 >= bufp->buffer && p2 <= pend);
4705 /* Skip over open/close-group commands.
4706 If what follows this loop is a ...+ construct,
4707 look at what begins its body, since we will have to
4708 match at least one of that. */
4709 p2 = skip_noops (p2, pend);
4710 /* The same skip can be done for p1, except that this function
4711 is only used in the case where p1 is a simple match operator. */
4712 /* p1 = skip_noops (p1, pend); */
4714 assert (p1 >= bufp->buffer && p1 < pend
4715 && p2 >= bufp->buffer && p2 <= pend);
4717 op2 = p2 == pend ? succeed : *p2;
4719 switch (op2)
4721 case succeed:
4722 case endbuf:
4723 /* If we're at the end of the pattern, we can change. */
4724 if (skip_one_char (p1))
4726 DEBUG_PRINT (" End of pattern: fast loop.\n");
4727 return 1;
4729 break;
4731 case endline:
4732 case exactn:
4734 register re_wchar_t c
4735 = (re_opcode_t) *p2 == endline ? '\n'
4736 : RE_STRING_CHAR (p2 + 2, multibyte);
4738 if ((re_opcode_t) *p1 == exactn)
4740 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4742 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4743 return 1;
4747 else if ((re_opcode_t) *p1 == charset
4748 || (re_opcode_t) *p1 == charset_not)
4750 if (!execute_charset (&p1, c, c, !multibyte || IS_REAL_ASCII (c)))
4752 DEBUG_PRINT (" No match => fast loop.\n");
4753 return 1;
4756 else if ((re_opcode_t) *p1 == anychar
4757 && c == '\n')
4759 DEBUG_PRINT (" . != \\n => fast loop.\n");
4760 return 1;
4763 break;
4765 case charset:
4767 if ((re_opcode_t) *p1 == exactn)
4768 /* Reuse the code above. */
4769 return mutually_exclusive_p (bufp, p2, p1);
4771 /* It is hard to list up all the character in charset
4772 P2 if it includes multibyte character. Give up in
4773 such case. */
4774 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4776 /* Now, we are sure that P2 has no range table.
4777 So, for the size of bitmap in P2, `p2[1]' is
4778 enough. But P1 may have range table, so the
4779 size of bitmap table of P1 is extracted by
4780 using macro `CHARSET_BITMAP_SIZE'.
4782 In a multibyte case, we know that all the character
4783 listed in P2 is ASCII. In a unibyte case, P1 has only a
4784 bitmap table. So, in both cases, it is enough to test
4785 only the bitmap table of P1. */
4787 if ((re_opcode_t) *p1 == charset)
4789 int idx;
4790 /* We win if the charset inside the loop
4791 has no overlap with the one after the loop. */
4792 for (idx = 0;
4793 (idx < (int) p2[1]
4794 && idx < CHARSET_BITMAP_SIZE (p1));
4795 idx++)
4796 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4797 break;
4799 if (idx == p2[1]
4800 || idx == CHARSET_BITMAP_SIZE (p1))
4802 DEBUG_PRINT (" No match => fast loop.\n");
4803 return 1;
4806 else if ((re_opcode_t) *p1 == charset_not)
4808 int idx;
4809 /* We win if the charset_not inside the loop lists
4810 every character listed in the charset after. */
4811 for (idx = 0; idx < (int) p2[1]; idx++)
4812 if (! (p2[2 + idx] == 0
4813 || (idx < CHARSET_BITMAP_SIZE (p1)
4814 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4815 break;
4817 if (idx == p2[1])
4819 DEBUG_PRINT (" No match => fast loop.\n");
4820 return 1;
4825 break;
4827 case charset_not:
4828 switch (*p1)
4830 case exactn:
4831 case charset:
4832 /* Reuse the code above. */
4833 return mutually_exclusive_p (bufp, p2, p1);
4834 case charset_not:
4835 /* When we have two charset_not, it's very unlikely that
4836 they don't overlap. The union of the two sets of excluded
4837 chars should cover all possible chars, which, as a matter of
4838 fact, is virtually impossible in multibyte buffers. */
4839 break;
4841 break;
4843 case wordend:
4844 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4845 case symend:
4846 return ((re_opcode_t) *p1 == syntaxspec
4847 && (p1[1] == Ssymbol || p1[1] == Sword));
4848 case notsyntaxspec:
4849 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4851 case wordbeg:
4852 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4853 case symbeg:
4854 return ((re_opcode_t) *p1 == notsyntaxspec
4855 && (p1[1] == Ssymbol || p1[1] == Sword));
4856 case syntaxspec:
4857 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4859 case wordbound:
4860 return (((re_opcode_t) *p1 == notsyntaxspec
4861 || (re_opcode_t) *p1 == syntaxspec)
4862 && p1[1] == Sword);
4864 #ifdef emacs
4865 case categoryspec:
4866 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4867 case notcategoryspec:
4868 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4869 #endif /* emacs */
4871 default:
4875 /* Safe default. */
4876 return 0;
4880 /* Matching routines. */
4882 #ifndef emacs /* Emacs never uses this. */
4883 /* re_match is like re_match_2 except it takes only a single string. */
4885 regoff_t
4886 re_match (struct re_pattern_buffer *bufp, const char *string,
4887 size_t size, ssize_t pos, struct re_registers *regs)
4889 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char *) string,
4890 size, pos, regs, size);
4891 return result;
4893 WEAK_ALIAS (__re_match, re_match)
4894 #endif /* not emacs */
4896 /* re_match_2 matches the compiled pattern in BUFP against the
4897 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4898 and SIZE2, respectively). We start matching at POS, and stop
4899 matching at STOP.
4901 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4902 store offsets for the substring each group matched in REGS. See the
4903 documentation for exactly how many groups we fill.
4905 We return -1 if no match, -2 if an internal error (such as the
4906 failure stack overflowing). Otherwise, we return the length of the
4907 matched substring. */
4909 regoff_t
4910 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4911 size_t size1, const char *string2, size_t size2, ssize_t pos,
4912 struct re_registers *regs, ssize_t stop)
4914 regoff_t result;
4916 #ifdef emacs
4917 ssize_t charpos;
4918 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4919 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4920 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4921 #endif
4923 result = re_match_2_internal (bufp, (re_char *) string1, size1,
4924 (re_char *) string2, size2,
4925 pos, regs, stop);
4926 return result;
4928 WEAK_ALIAS (__re_match_2, re_match_2)
4931 /* This is a separate function so that we can force an alloca cleanup
4932 afterwards. */
4933 static regoff_t
4934 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4935 size_t size1, const_re_char *string2, size_t size2,
4936 ssize_t pos, struct re_registers *regs, ssize_t stop)
4938 /* General temporaries. */
4939 int mcnt;
4940 size_t reg;
4942 /* Just past the end of the corresponding string. */
4943 re_char *end1, *end2;
4945 /* Pointers into string1 and string2, just past the last characters in
4946 each to consider matching. */
4947 re_char *end_match_1, *end_match_2;
4949 /* Where we are in the data, and the end of the current string. */
4950 re_char *d, *dend;
4952 /* Used sometimes to remember where we were before starting matching
4953 an operator so that we can go back in case of failure. This "atomic"
4954 behavior of matching opcodes is indispensable to the correctness
4955 of the on_failure_keep_string_jump optimization. */
4956 re_char *dfail;
4958 /* Where we are in the pattern, and the end of the pattern. */
4959 re_char *p = bufp->buffer;
4960 re_char *pend = p + bufp->used;
4962 /* We use this to map every character in the string. */
4963 RE_TRANSLATE_TYPE translate = bufp->translate;
4965 /* Nonzero if BUFP is setup from a multibyte regex. */
4966 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4968 /* Nonzero if STRING1/STRING2 are multibyte. */
4969 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4971 /* Failure point stack. Each place that can handle a failure further
4972 down the line pushes a failure point on this stack. It consists of
4973 regstart, and regend for all registers corresponding to
4974 the subexpressions we're currently inside, plus the number of such
4975 registers, and, finally, two char *'s. The first char * is where
4976 to resume scanning the pattern; the second one is where to resume
4977 scanning the strings. */
4978 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4979 fail_stack_type fail_stack;
4980 #endif
4981 #ifdef DEBUG_COMPILES_ARGUMENTS
4982 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4983 #endif
4985 #if defined REL_ALLOC && defined REGEX_MALLOC
4986 /* This holds the pointer to the failure stack, when
4987 it is allocated relocatably. */
4988 fail_stack_elt_t *failure_stack_ptr;
4989 #endif
4991 /* We fill all the registers internally, independent of what we
4992 return, for use in backreferences. The number here includes
4993 an element for register zero. */
4994 size_t num_regs = bufp->re_nsub + 1;
4996 /* Information on the contents of registers. These are pointers into
4997 the input strings; they record just what was matched (on this
4998 attempt) by a subexpression part of the pattern, that is, the
4999 regnum-th regstart pointer points to where in the pattern we began
5000 matching and the regnum-th regend points to right after where we
5001 stopped matching the regnum-th subexpression. (The zeroth register
5002 keeps track of what the whole pattern matches.) */
5003 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5004 re_char **regstart, **regend;
5005 #endif
5007 /* The following record the register info as found in the above
5008 variables when we find a match better than any we've seen before.
5009 This happens as we backtrack through the failure points, which in
5010 turn happens only if we have not yet matched the entire string. */
5011 unsigned best_regs_set = false;
5012 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5013 re_char **best_regstart, **best_regend;
5014 #endif
5016 /* Logically, this is `best_regend[0]'. But we don't want to have to
5017 allocate space for that if we're not allocating space for anything
5018 else (see below). Also, we never need info about register 0 for
5019 any of the other register vectors, and it seems rather a kludge to
5020 treat `best_regend' differently than the rest. So we keep track of
5021 the end of the best match so far in a separate variable. We
5022 initialize this to NULL so that when we backtrack the first time
5023 and need to test it, it's not garbage. */
5024 re_char *match_end = NULL;
5026 #ifdef DEBUG_COMPILES_ARGUMENTS
5027 /* Counts the total number of registers pushed. */
5028 unsigned num_regs_pushed = 0;
5029 #endif
5031 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5033 REGEX_USE_SAFE_ALLOCA;
5035 INIT_FAIL_STACK ();
5037 #ifdef MATCH_MAY_ALLOCATE
5038 /* Do not bother to initialize all the register variables if there are
5039 no groups in the pattern, as it takes a fair amount of time. If
5040 there are groups, we include space for register 0 (the whole
5041 pattern), even though we never use it, since it simplifies the
5042 array indexing. We should fix this. */
5043 if (bufp->re_nsub)
5045 regstart = REGEX_TALLOC (num_regs, re_char *);
5046 regend = REGEX_TALLOC (num_regs, re_char *);
5047 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5048 best_regend = REGEX_TALLOC (num_regs, re_char *);
5050 if (!(regstart && regend && best_regstart && best_regend))
5052 FREE_VARIABLES ();
5053 return -2;
5056 else
5058 /* We must initialize all our variables to NULL, so that
5059 `FREE_VARIABLES' doesn't try to free them. */
5060 regstart = regend = best_regstart = best_regend = NULL;
5062 #endif /* MATCH_MAY_ALLOCATE */
5064 /* The starting position is bogus. */
5065 if (pos < 0 || pos > size1 + size2)
5067 FREE_VARIABLES ();
5068 return -1;
5071 /* Initialize subexpression text positions to -1 to mark ones that no
5072 start_memory/stop_memory has been seen for. Also initialize the
5073 register information struct. */
5074 for (reg = 1; reg < num_regs; reg++)
5075 regstart[reg] = regend[reg] = NULL;
5077 /* We move `string1' into `string2' if the latter's empty -- but not if
5078 `string1' is null. */
5079 if (size2 == 0 && string1 != NULL)
5081 string2 = string1;
5082 size2 = size1;
5083 string1 = 0;
5084 size1 = 0;
5086 end1 = string1 + size1;
5087 end2 = string2 + size2;
5089 /* `p' scans through the pattern as `d' scans through the data.
5090 `dend' is the end of the input string that `d' points within. `d'
5091 is advanced into the following input string whenever necessary, but
5092 this happens before fetching; therefore, at the beginning of the
5093 loop, `d' can be pointing at the end of a string, but it cannot
5094 equal `string2'. */
5095 if (pos >= size1)
5097 /* Only match within string2. */
5098 d = string2 + pos - size1;
5099 dend = end_match_2 = string2 + stop - size1;
5100 end_match_1 = end1; /* Just to give it a value. */
5102 else
5104 if (stop < size1)
5106 /* Only match within string1. */
5107 end_match_1 = string1 + stop;
5108 /* BEWARE!
5109 When we reach end_match_1, PREFETCH normally switches to string2.
5110 But in the present case, this means that just doing a PREFETCH
5111 makes us jump from `stop' to `gap' within the string.
5112 What we really want here is for the search to stop as
5113 soon as we hit end_match_1. That's why we set end_match_2
5114 to end_match_1 (since PREFETCH fails as soon as we hit
5115 end_match_2). */
5116 end_match_2 = end_match_1;
5118 else
5119 { /* It's important to use this code when stop == size so that
5120 moving `d' from end1 to string2 will not prevent the d == dend
5121 check from catching the end of string. */
5122 end_match_1 = end1;
5123 end_match_2 = string2 + stop - size1;
5125 d = string1 + pos;
5126 dend = end_match_1;
5129 DEBUG_PRINT ("The compiled pattern is: ");
5130 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5131 DEBUG_PRINT ("The string to match is: \"");
5132 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5133 DEBUG_PRINT ("\"\n");
5135 /* This loops over pattern commands. It exits by returning from the
5136 function if the match is complete, or it drops through if the match
5137 fails at this starting point in the input data. */
5138 for (;;)
5140 DEBUG_PRINT ("\n%p: ", p);
5142 if (p == pend)
5144 /* End of pattern means we might have succeeded. */
5145 DEBUG_PRINT ("end of pattern ... ");
5147 /* If we haven't matched the entire string, and we want the
5148 longest match, try backtracking. */
5149 if (d != end_match_2)
5151 /* True if this match is the best seen so far. */
5152 bool best_match_p;
5155 /* True if this match ends in the same string (string1
5156 or string2) as the best previous match. */
5157 bool same_str_p = (FIRST_STRING_P (match_end)
5158 == FIRST_STRING_P (d));
5160 /* AIX compiler got confused when this was combined
5161 with the previous declaration. */
5162 if (same_str_p)
5163 best_match_p = d > match_end;
5164 else
5165 best_match_p = !FIRST_STRING_P (d);
5168 DEBUG_PRINT ("backtracking.\n");
5170 if (!FAIL_STACK_EMPTY ())
5171 { /* More failure points to try. */
5173 /* If exceeds best match so far, save it. */
5174 if (!best_regs_set || best_match_p)
5176 best_regs_set = true;
5177 match_end = d;
5179 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5181 for (reg = 1; reg < num_regs; reg++)
5183 best_regstart[reg] = regstart[reg];
5184 best_regend[reg] = regend[reg];
5187 goto fail;
5190 /* If no failure points, don't restore garbage. And if
5191 last match is real best match, don't restore second
5192 best one. */
5193 else if (best_regs_set && !best_match_p)
5195 restore_best_regs:
5196 /* Restore best match. It may happen that `dend ==
5197 end_match_1' while the restored d is in string2.
5198 For example, the pattern `x.*y.*z' against the
5199 strings `x-' and `y-z-', if the two strings are
5200 not consecutive in memory. */
5201 DEBUG_PRINT ("Restoring best registers.\n");
5203 d = match_end;
5204 dend = ((d >= string1 && d <= end1)
5205 ? end_match_1 : end_match_2);
5207 for (reg = 1; reg < num_regs; reg++)
5209 regstart[reg] = best_regstart[reg];
5210 regend[reg] = best_regend[reg];
5213 } /* d != end_match_2 */
5215 succeed_label:
5216 DEBUG_PRINT ("Accepting match.\n");
5218 /* If caller wants register contents data back, do it. */
5219 if (regs && !bufp->no_sub)
5221 /* Have the register data arrays been allocated? */
5222 if (bufp->regs_allocated == REGS_UNALLOCATED)
5223 { /* No. So allocate them with malloc. We need one
5224 extra element beyond `num_regs' for the `-1' marker
5225 GNU code uses. */
5226 regs->num_regs = max (RE_NREGS, num_regs + 1);
5227 regs->start = TALLOC (regs->num_regs, regoff_t);
5228 regs->end = TALLOC (regs->num_regs, regoff_t);
5229 if (regs->start == NULL || regs->end == NULL)
5231 FREE_VARIABLES ();
5232 return -2;
5234 bufp->regs_allocated = REGS_REALLOCATE;
5236 else if (bufp->regs_allocated == REGS_REALLOCATE)
5237 { /* Yes. If we need more elements than were already
5238 allocated, reallocate them. If we need fewer, just
5239 leave it alone. */
5240 if (regs->num_regs < num_regs + 1)
5242 regs->num_regs = num_regs + 1;
5243 RETALLOC (regs->start, regs->num_regs, regoff_t);
5244 RETALLOC (regs->end, regs->num_regs, regoff_t);
5245 if (regs->start == NULL || regs->end == NULL)
5247 FREE_VARIABLES ();
5248 return -2;
5252 else
5254 /* These braces fend off a "empty body in an else-statement"
5255 warning under GCC when assert expands to nothing. */
5256 assert (bufp->regs_allocated == REGS_FIXED);
5259 /* Convert the pointer data in `regstart' and `regend' to
5260 indices. Register zero has to be set differently,
5261 since we haven't kept track of any info for it. */
5262 if (regs->num_regs > 0)
5264 regs->start[0] = pos;
5265 regs->end[0] = POINTER_TO_OFFSET (d);
5268 /* Go through the first `min (num_regs, regs->num_regs)'
5269 registers, since that is all we initialized. */
5270 for (reg = 1; reg < min (num_regs, regs->num_regs); reg++)
5272 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5273 regs->start[reg] = regs->end[reg] = -1;
5274 else
5276 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5277 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5281 /* If the regs structure we return has more elements than
5282 were in the pattern, set the extra elements to -1. If
5283 we (re)allocated the registers, this is the case,
5284 because we always allocate enough to have at least one
5285 -1 at the end. */
5286 for (reg = num_regs; reg < regs->num_regs; reg++)
5287 regs->start[reg] = regs->end[reg] = -1;
5288 } /* regs && !bufp->no_sub */
5290 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5291 nfailure_points_pushed, nfailure_points_popped,
5292 nfailure_points_pushed - nfailure_points_popped);
5293 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5295 ptrdiff_t dcnt = POINTER_TO_OFFSET (d) - pos;
5297 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5299 FREE_VARIABLES ();
5300 return dcnt;
5303 /* Otherwise match next pattern command. */
5304 switch (*p++)
5306 /* Ignore these. Used to ignore the n of succeed_n's which
5307 currently have n == 0. */
5308 case no_op:
5309 DEBUG_PRINT ("EXECUTING no_op.\n");
5310 break;
5312 case succeed:
5313 DEBUG_PRINT ("EXECUTING succeed.\n");
5314 goto succeed_label;
5316 /* Match the next n pattern characters exactly. The following
5317 byte in the pattern defines n, and the n bytes after that
5318 are the characters to match. */
5319 case exactn:
5320 mcnt = *p++;
5321 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5323 /* Remember the start point to rollback upon failure. */
5324 dfail = d;
5326 #ifndef emacs
5327 /* This is written out as an if-else so we don't waste time
5328 testing `translate' inside the loop. */
5329 if (RE_TRANSLATE_P (translate))
5332 PREFETCH ();
5333 if (RE_TRANSLATE (translate, *d) != *p++)
5335 d = dfail;
5336 goto fail;
5338 d++;
5340 while (--mcnt);
5341 else
5344 PREFETCH ();
5345 if (*d++ != *p++)
5347 d = dfail;
5348 goto fail;
5351 while (--mcnt);
5352 #else /* emacs */
5353 /* The cost of testing `translate' is comparatively small. */
5354 if (target_multibyte)
5357 int pat_charlen, buf_charlen;
5358 int pat_ch, buf_ch;
5360 PREFETCH ();
5361 if (multibyte)
5362 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5363 else
5365 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5366 pat_charlen = 1;
5368 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5370 if (TRANSLATE (buf_ch) != pat_ch)
5372 d = dfail;
5373 goto fail;
5376 p += pat_charlen;
5377 d += buf_charlen;
5378 mcnt -= pat_charlen;
5380 while (mcnt > 0);
5381 else
5384 int pat_charlen;
5385 int pat_ch, buf_ch;
5387 PREFETCH ();
5388 if (multibyte)
5390 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5391 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5393 else
5395 pat_ch = *p;
5396 pat_charlen = 1;
5398 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5399 if (! CHAR_BYTE8_P (buf_ch))
5401 buf_ch = TRANSLATE (buf_ch);
5402 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5403 if (buf_ch < 0)
5404 buf_ch = *d;
5406 else
5407 buf_ch = *d;
5408 if (buf_ch != pat_ch)
5410 d = dfail;
5411 goto fail;
5413 p += pat_charlen;
5414 d++;
5416 while (--mcnt);
5417 #endif
5418 break;
5421 /* Match any character except possibly a newline or a null. */
5422 case anychar:
5424 int buf_charlen;
5425 re_wchar_t buf_ch;
5426 reg_syntax_t syntax;
5428 DEBUG_PRINT ("EXECUTING anychar.\n");
5430 PREFETCH ();
5431 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5432 target_multibyte);
5433 buf_ch = TRANSLATE (buf_ch);
5435 #ifdef emacs
5436 syntax = RE_SYNTAX_EMACS;
5437 #else
5438 syntax = bufp->syntax;
5439 #endif
5441 if ((!(syntax & RE_DOT_NEWLINE) && buf_ch == '\n')
5442 || ((syntax & RE_DOT_NOT_NULL) && buf_ch == '\000'))
5443 goto fail;
5445 DEBUG_PRINT (" Matched \"%d\".\n", *d);
5446 d += buf_charlen;
5448 break;
5451 case charset:
5452 case charset_not:
5454 register unsigned int c, corig;
5455 int len;
5457 /* Whether matching against a unibyte character. */
5458 boolean unibyte_char = false;
5460 DEBUG_PRINT ("EXECUTING charset%s.\n",
5461 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
5463 PREFETCH ();
5464 corig = c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5465 if (target_multibyte)
5467 int c1;
5469 c = TRANSLATE (c);
5470 c1 = RE_CHAR_TO_UNIBYTE (c);
5471 if (c1 >= 0)
5473 unibyte_char = true;
5474 c = c1;
5477 else
5479 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5481 if (! CHAR_BYTE8_P (c1))
5483 c1 = TRANSLATE (c1);
5484 c1 = RE_CHAR_TO_UNIBYTE (c1);
5485 if (c1 >= 0)
5487 unibyte_char = true;
5488 c = c1;
5491 else
5492 unibyte_char = true;
5495 p -= 1;
5496 if (!execute_charset (&p, c, corig, unibyte_char))
5497 goto fail;
5499 d += len;
5501 break;
5504 /* The beginning of a group is represented by start_memory.
5505 The argument is the register number. The text
5506 matched within the group is recorded (in the internal
5507 registers data structure) under the register number. */
5508 case start_memory:
5509 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5511 /* In case we need to undo this operation (via backtracking). */
5512 PUSH_FAILURE_REG (*p);
5514 regstart[*p] = d;
5515 regend[*p] = NULL; /* probably unnecessary. -sm */
5516 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5518 /* Move past the register number and inner group count. */
5519 p += 1;
5520 break;
5523 /* The stop_memory opcode represents the end of a group. Its
5524 argument is the same as start_memory's: the register number. */
5525 case stop_memory:
5526 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5528 assert (!REG_UNSET (regstart[*p]));
5529 /* Strictly speaking, there should be code such as:
5531 assert (REG_UNSET (regend[*p]));
5532 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5534 But the only info to be pushed is regend[*p] and it is known to
5535 be UNSET, so there really isn't anything to push.
5536 Not pushing anything, on the other hand deprives us from the
5537 guarantee that regend[*p] is UNSET since undoing this operation
5538 will not reset its value properly. This is not important since
5539 the value will only be read on the next start_memory or at
5540 the very end and both events can only happen if this stop_memory
5541 is *not* undone. */
5543 regend[*p] = d;
5544 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5546 /* Move past the register number and the inner group count. */
5547 p += 1;
5548 break;
5551 /* \<digit> has been turned into a `duplicate' command which is
5552 followed by the numeric value of <digit> as the register number. */
5553 case duplicate:
5555 register re_char *d2, *dend2;
5556 int regno = *p++; /* Get which register to match against. */
5557 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5559 /* Can't back reference a group which we've never matched. */
5560 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5561 goto fail;
5563 /* Where in input to try to start matching. */
5564 d2 = regstart[regno];
5566 /* Remember the start point to rollback upon failure. */
5567 dfail = d;
5569 /* Where to stop matching; if both the place to start and
5570 the place to stop matching are in the same string, then
5571 set to the place to stop, otherwise, for now have to use
5572 the end of the first string. */
5574 dend2 = ((FIRST_STRING_P (regstart[regno])
5575 == FIRST_STRING_P (regend[regno]))
5576 ? regend[regno] : end_match_1);
5577 for (;;)
5579 ptrdiff_t dcnt;
5581 /* If necessary, advance to next segment in register
5582 contents. */
5583 while (d2 == dend2)
5585 if (dend2 == end_match_2) break;
5586 if (dend2 == regend[regno]) break;
5588 /* End of string1 => advance to string2. */
5589 d2 = string2;
5590 dend2 = regend[regno];
5592 /* At end of register contents => success */
5593 if (d2 == dend2) break;
5595 /* If necessary, advance to next segment in data. */
5596 PREFETCH ();
5598 /* How many characters left in this segment to match. */
5599 dcnt = dend - d;
5601 /* Want how many consecutive characters we can match in
5602 one shot, so, if necessary, adjust the count. */
5603 if (dcnt > dend2 - d2)
5604 dcnt = dend2 - d2;
5606 /* Compare that many; failure if mismatch, else move
5607 past them. */
5608 if (RE_TRANSLATE_P (translate)
5609 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5610 : memcmp (d, d2, dcnt))
5612 d = dfail;
5613 goto fail;
5615 d += dcnt, d2 += dcnt;
5618 break;
5621 /* begline matches the empty string at the beginning of the string
5622 (unless `not_bol' is set in `bufp'), and after newlines. */
5623 case begline:
5624 DEBUG_PRINT ("EXECUTING begline.\n");
5626 if (AT_STRINGS_BEG (d))
5628 if (!bufp->not_bol) break;
5630 else
5632 unsigned c;
5633 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5634 if (c == '\n')
5635 break;
5637 /* In all other cases, we fail. */
5638 goto fail;
5641 /* endline is the dual of begline. */
5642 case endline:
5643 DEBUG_PRINT ("EXECUTING endline.\n");
5645 if (AT_STRINGS_END (d))
5647 if (!bufp->not_eol) break;
5649 else
5651 PREFETCH_NOLIMIT ();
5652 if (*d == '\n')
5653 break;
5655 goto fail;
5658 /* Match at the very beginning of the data. */
5659 case begbuf:
5660 DEBUG_PRINT ("EXECUTING begbuf.\n");
5661 if (AT_STRINGS_BEG (d))
5662 break;
5663 goto fail;
5666 /* Match at the very end of the data. */
5667 case endbuf:
5668 DEBUG_PRINT ("EXECUTING endbuf.\n");
5669 if (AT_STRINGS_END (d))
5670 break;
5671 goto fail;
5674 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5675 pushes NULL as the value for the string on the stack. Then
5676 `POP_FAILURE_POINT' will keep the current value for the
5677 string, instead of restoring it. To see why, consider
5678 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5679 then the . fails against the \n. But the next thing we want
5680 to do is match the \n against the \n; if we restored the
5681 string value, we would be back at the foo.
5683 Because this is used only in specific cases, we don't need to
5684 check all the things that `on_failure_jump' does, to make
5685 sure the right things get saved on the stack. Hence we don't
5686 share its code. The only reason to push anything on the
5687 stack at all is that otherwise we would have to change
5688 `anychar's code to do something besides goto fail in this
5689 case; that seems worse than this. */
5690 case on_failure_keep_string_jump:
5691 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5692 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5693 mcnt, p + mcnt);
5695 PUSH_FAILURE_POINT (p - 3, NULL);
5696 break;
5698 /* A nasty loop is introduced by the non-greedy *? and +?.
5699 With such loops, the stack only ever contains one failure point
5700 at a time, so that a plain on_failure_jump_loop kind of
5701 cycle detection cannot work. Worse yet, such a detection
5702 can not only fail to detect a cycle, but it can also wrongly
5703 detect a cycle (between different instantiations of the same
5704 loop).
5705 So the method used for those nasty loops is a little different:
5706 We use a special cycle-detection-stack-frame which is pushed
5707 when the on_failure_jump_nastyloop failure-point is *popped*.
5708 This special frame thus marks the beginning of one iteration
5709 through the loop and we can hence easily check right here
5710 whether something matched between the beginning and the end of
5711 the loop. */
5712 case on_failure_jump_nastyloop:
5713 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5714 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5715 mcnt, p + mcnt);
5717 assert ((re_opcode_t)p[-4] == no_op);
5719 int cycle = 0;
5720 CHECK_INFINITE_LOOP (p - 4, d);
5721 if (!cycle)
5722 /* If there's a cycle, just continue without pushing
5723 this failure point. The failure point is the "try again"
5724 option, which shouldn't be tried.
5725 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5726 PUSH_FAILURE_POINT (p - 3, d);
5728 break;
5730 /* Simple loop detecting on_failure_jump: just check on the
5731 failure stack if the same spot was already hit earlier. */
5732 case on_failure_jump_loop:
5733 on_failure:
5734 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5735 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5736 mcnt, p + mcnt);
5738 int cycle = 0;
5739 CHECK_INFINITE_LOOP (p - 3, d);
5740 if (cycle)
5741 /* If there's a cycle, get out of the loop, as if the matching
5742 had failed. We used to just `goto fail' here, but that was
5743 aborting the search a bit too early: we want to keep the
5744 empty-loop-match and keep matching after the loop.
5745 We want (x?)*y\1z to match both xxyz and xxyxz. */
5746 p += mcnt;
5747 else
5748 PUSH_FAILURE_POINT (p - 3, d);
5750 break;
5753 /* Uses of on_failure_jump:
5755 Each alternative starts with an on_failure_jump that points
5756 to the beginning of the next alternative. Each alternative
5757 except the last ends with a jump that in effect jumps past
5758 the rest of the alternatives. (They really jump to the
5759 ending jump of the following alternative, because tensioning
5760 these jumps is a hassle.)
5762 Repeats start with an on_failure_jump that points past both
5763 the repetition text and either the following jump or
5764 pop_failure_jump back to this on_failure_jump. */
5765 case on_failure_jump:
5766 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5767 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5768 mcnt, p + mcnt);
5770 PUSH_FAILURE_POINT (p -3, d);
5771 break;
5773 /* This operation is used for greedy *.
5774 Compare the beginning of the repeat with what in the
5775 pattern follows its end. If we can establish that there
5776 is nothing that they would both match, i.e., that we
5777 would have to backtrack because of (as in, e.g., `a*a')
5778 then we can use a non-backtracking loop based on
5779 on_failure_keep_string_jump instead of on_failure_jump. */
5780 case on_failure_jump_smart:
5781 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5782 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5783 mcnt, p + mcnt);
5785 re_char *p1 = p; /* Next operation. */
5786 /* Here, we discard `const', making re_match non-reentrant. */
5787 unsigned char *p2 = (unsigned char *) p + mcnt; /* Jump dest. */
5788 unsigned char *p3 = (unsigned char *) p - 3; /* opcode location. */
5790 p -= 3; /* Reset so that we will re-execute the
5791 instruction once it's been changed. */
5793 EXTRACT_NUMBER (mcnt, p2 - 2);
5795 /* Ensure this is a indeed the trivial kind of loop
5796 we are expecting. */
5797 assert (skip_one_char (p1) == p2 - 3);
5798 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5799 DEBUG_STATEMENT (debug += 2);
5800 if (mutually_exclusive_p (bufp, p1, p2))
5802 /* Use a fast `on_failure_keep_string_jump' loop. */
5803 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5804 *p3 = (unsigned char) on_failure_keep_string_jump;
5805 STORE_NUMBER (p2 - 2, mcnt + 3);
5807 else
5809 /* Default to a safe `on_failure_jump' loop. */
5810 DEBUG_PRINT (" smart default => slow loop.\n");
5811 *p3 = (unsigned char) on_failure_jump;
5813 DEBUG_STATEMENT (debug -= 2);
5815 break;
5817 /* Unconditionally jump (without popping any failure points). */
5818 case jump:
5819 unconditional_jump:
5820 maybe_quit ();
5821 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5822 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5823 p += mcnt; /* Do the jump. */
5824 DEBUG_PRINT ("(to %p).\n", p);
5825 break;
5828 /* Have to succeed matching what follows at least n times.
5829 After that, handle like `on_failure_jump'. */
5830 case succeed_n:
5831 /* Signedness doesn't matter since we only compare MCNT to 0. */
5832 EXTRACT_NUMBER (mcnt, p + 2);
5833 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5835 /* Originally, mcnt is how many times we HAVE to succeed. */
5836 if (mcnt != 0)
5838 /* Here, we discard `const', making re_match non-reentrant. */
5839 unsigned char *p2 = (unsigned char *) p + 2; /* counter loc. */
5840 mcnt--;
5841 p += 4;
5842 PUSH_NUMBER (p2, mcnt);
5844 else
5845 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5846 goto on_failure;
5847 break;
5849 case jump_n:
5850 /* Signedness doesn't matter since we only compare MCNT to 0. */
5851 EXTRACT_NUMBER (mcnt, p + 2);
5852 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5854 /* Originally, this is how many times we CAN jump. */
5855 if (mcnt != 0)
5857 /* Here, we discard `const', making re_match non-reentrant. */
5858 unsigned char *p2 = (unsigned char *) p + 2; /* counter loc. */
5859 mcnt--;
5860 PUSH_NUMBER (p2, mcnt);
5861 goto unconditional_jump;
5863 /* If don't have to jump any more, skip over the rest of command. */
5864 else
5865 p += 4;
5866 break;
5868 case set_number_at:
5870 unsigned char *p2; /* Location of the counter. */
5871 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5873 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5874 /* Here, we discard `const', making re_match non-reentrant. */
5875 p2 = (unsigned char *) p + mcnt;
5876 /* Signedness doesn't matter since we only copy MCNT's bits. */
5877 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5878 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5879 PUSH_NUMBER (p2, mcnt);
5880 break;
5883 case wordbound:
5884 case notwordbound:
5886 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5887 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5889 /* We SUCCEED (or FAIL) in one of the following cases: */
5891 /* Case 1: D is at the beginning or the end of string. */
5892 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5893 not = !not;
5894 else
5896 /* C1 is the character before D, S1 is the syntax of C1, C2
5897 is the character at D, and S2 is the syntax of C2. */
5898 re_wchar_t c1, c2;
5899 int s1, s2;
5900 int dummy;
5901 #ifdef emacs
5902 ssize_t offset = PTR_TO_OFFSET (d - 1);
5903 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5904 UPDATE_SYNTAX_TABLE_FAST (charpos);
5905 #endif
5906 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5907 s1 = SYNTAX (c1);
5908 #ifdef emacs
5909 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
5910 #endif
5911 PREFETCH_NOLIMIT ();
5912 GET_CHAR_AFTER (c2, d, dummy);
5913 s2 = SYNTAX (c2);
5915 if (/* Case 2: Only one of S1 and S2 is Sword. */
5916 ((s1 == Sword) != (s2 == Sword))
5917 /* Case 3: Both of S1 and S2 are Sword, and macro
5918 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5919 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5920 not = !not;
5922 if (not)
5923 break;
5924 else
5925 goto fail;
5928 case wordbeg:
5929 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5931 /* We FAIL in one of the following cases: */
5933 /* Case 1: D is at the end of string. */
5934 if (AT_STRINGS_END (d))
5935 goto fail;
5936 else
5938 /* C1 is the character before D, S1 is the syntax of C1, C2
5939 is the character at D, and S2 is the syntax of C2. */
5940 re_wchar_t c1, c2;
5941 int s1, s2;
5942 int dummy;
5943 #ifdef emacs
5944 ssize_t offset = PTR_TO_OFFSET (d);
5945 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5946 UPDATE_SYNTAX_TABLE_FAST (charpos);
5947 #endif
5948 PREFETCH ();
5949 GET_CHAR_AFTER (c2, d, dummy);
5950 s2 = SYNTAX (c2);
5952 /* Case 2: S2 is not Sword. */
5953 if (s2 != Sword)
5954 goto fail;
5956 /* Case 3: D is not at the beginning of string ... */
5957 if (!AT_STRINGS_BEG (d))
5959 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5960 #ifdef emacs
5961 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5962 #endif
5963 s1 = SYNTAX (c1);
5965 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5966 returns 0. */
5967 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5968 goto fail;
5971 break;
5973 case wordend:
5974 DEBUG_PRINT ("EXECUTING wordend.\n");
5976 /* We FAIL in one of the following cases: */
5978 /* Case 1: D is at the beginning of string. */
5979 if (AT_STRINGS_BEG (d))
5980 goto fail;
5981 else
5983 /* C1 is the character before D, S1 is the syntax of C1, C2
5984 is the character at D, and S2 is the syntax of C2. */
5985 re_wchar_t c1, c2;
5986 int s1, s2;
5987 int dummy;
5988 #ifdef emacs
5989 ssize_t offset = PTR_TO_OFFSET (d) - 1;
5990 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5991 UPDATE_SYNTAX_TABLE_FAST (charpos);
5992 #endif
5993 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5994 s1 = SYNTAX (c1);
5996 /* Case 2: S1 is not Sword. */
5997 if (s1 != Sword)
5998 goto fail;
6000 /* Case 3: D is not at the end of string ... */
6001 if (!AT_STRINGS_END (d))
6003 PREFETCH_NOLIMIT ();
6004 GET_CHAR_AFTER (c2, d, dummy);
6005 #ifdef emacs
6006 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos);
6007 #endif
6008 s2 = SYNTAX (c2);
6010 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6011 returns 0. */
6012 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6013 goto fail;
6016 break;
6018 case symbeg:
6019 DEBUG_PRINT ("EXECUTING symbeg.\n");
6021 /* We FAIL in one of the following cases: */
6023 /* Case 1: D is at the end of string. */
6024 if (AT_STRINGS_END (d))
6025 goto fail;
6026 else
6028 /* C1 is the character before D, S1 is the syntax of C1, C2
6029 is the character at D, and S2 is the syntax of C2. */
6030 re_wchar_t c1, c2;
6031 int s1, s2;
6032 #ifdef emacs
6033 ssize_t offset = PTR_TO_OFFSET (d);
6034 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6035 UPDATE_SYNTAX_TABLE_FAST (charpos);
6036 #endif
6037 PREFETCH ();
6038 c2 = RE_STRING_CHAR (d, target_multibyte);
6039 s2 = SYNTAX (c2);
6041 /* Case 2: S2 is neither Sword nor Ssymbol. */
6042 if (s2 != Sword && s2 != Ssymbol)
6043 goto fail;
6045 /* Case 3: D is not at the beginning of string ... */
6046 if (!AT_STRINGS_BEG (d))
6048 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6049 #ifdef emacs
6050 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6051 #endif
6052 s1 = SYNTAX (c1);
6054 /* ... and S1 is Sword or Ssymbol. */
6055 if (s1 == Sword || s1 == Ssymbol)
6056 goto fail;
6059 break;
6061 case symend:
6062 DEBUG_PRINT ("EXECUTING symend.\n");
6064 /* We FAIL in one of the following cases: */
6066 /* Case 1: D is at the beginning of string. */
6067 if (AT_STRINGS_BEG (d))
6068 goto fail;
6069 else
6071 /* C1 is the character before D, S1 is the syntax of C1, C2
6072 is the character at D, and S2 is the syntax of C2. */
6073 re_wchar_t c1, c2;
6074 int s1, s2;
6075 #ifdef emacs
6076 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6077 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6078 UPDATE_SYNTAX_TABLE_FAST (charpos);
6079 #endif
6080 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6081 s1 = SYNTAX (c1);
6083 /* Case 2: S1 is neither Ssymbol nor Sword. */
6084 if (s1 != Sword && s1 != Ssymbol)
6085 goto fail;
6087 /* Case 3: D is not at the end of string ... */
6088 if (!AT_STRINGS_END (d))
6090 PREFETCH_NOLIMIT ();
6091 c2 = RE_STRING_CHAR (d, target_multibyte);
6092 #ifdef emacs
6093 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
6094 #endif
6095 s2 = SYNTAX (c2);
6097 /* ... and S2 is Sword or Ssymbol. */
6098 if (s2 == Sword || s2 == Ssymbol)
6099 goto fail;
6102 break;
6104 case syntaxspec:
6105 case notsyntaxspec:
6107 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6108 mcnt = *p++;
6109 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6110 mcnt);
6111 PREFETCH ();
6112 #ifdef emacs
6114 ssize_t offset = PTR_TO_OFFSET (d);
6115 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6116 UPDATE_SYNTAX_TABLE_FAST (pos1);
6118 #endif
6120 int len;
6121 re_wchar_t c;
6123 GET_CHAR_AFTER (c, d, len);
6124 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6125 goto fail;
6126 d += len;
6129 break;
6131 #ifdef emacs
6132 case at_dot:
6133 DEBUG_PRINT ("EXECUTING at_dot.\n");
6134 if (PTR_BYTE_POS (d) != PT_BYTE)
6135 goto fail;
6136 break;
6138 case categoryspec:
6139 case notcategoryspec:
6141 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6142 mcnt = *p++;
6143 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6144 not ? "not" : "", mcnt);
6145 PREFETCH ();
6148 int len;
6149 re_wchar_t c;
6150 GET_CHAR_AFTER (c, d, len);
6151 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6152 goto fail;
6153 d += len;
6156 break;
6158 #endif /* emacs */
6160 default:
6161 abort ();
6163 continue; /* Successfully executed one pattern command; keep going. */
6166 /* We goto here if a matching operation fails. */
6167 fail:
6168 maybe_quit ();
6169 if (!FAIL_STACK_EMPTY ())
6171 re_char *str, *pat;
6172 /* A restart point is known. Restore to that state. */
6173 DEBUG_PRINT ("\nFAIL:\n");
6174 POP_FAILURE_POINT (str, pat);
6175 switch (*pat++)
6177 case on_failure_keep_string_jump:
6178 assert (str == NULL);
6179 goto continue_failure_jump;
6181 case on_failure_jump_nastyloop:
6182 assert ((re_opcode_t)pat[-2] == no_op);
6183 PUSH_FAILURE_POINT (pat - 2, str);
6184 FALLTHROUGH;
6185 case on_failure_jump_loop:
6186 case on_failure_jump:
6187 case succeed_n:
6188 d = str;
6189 continue_failure_jump:
6190 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6191 p = pat + mcnt;
6192 break;
6194 case no_op:
6195 /* A special frame used for nastyloops. */
6196 goto fail;
6198 default:
6199 abort ();
6202 assert (p >= bufp->buffer && p <= pend);
6204 if (d >= string1 && d <= end1)
6205 dend = end_match_1;
6207 else
6208 break; /* Matching at this starting point really fails. */
6209 } /* for (;;) */
6211 if (best_regs_set)
6212 goto restore_best_regs;
6214 FREE_VARIABLES ();
6216 return -1; /* Failure to match. */
6219 /* Subroutine definitions for re_match_2. */
6221 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6222 bytes; nonzero otherwise. */
6224 static int
6225 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6226 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6228 register re_char *p1 = s1, *p2 = s2;
6229 re_char *p1_end = s1 + len;
6230 re_char *p2_end = s2 + len;
6232 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6233 different lengths, but relying on a single `len' would break this. -sm */
6234 while (p1 < p1_end && p2 < p2_end)
6236 int p1_charlen, p2_charlen;
6237 re_wchar_t p1_ch, p2_ch;
6239 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6240 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6242 if (RE_TRANSLATE (translate, p1_ch)
6243 != RE_TRANSLATE (translate, p2_ch))
6244 return 1;
6246 p1 += p1_charlen, p2 += p2_charlen;
6249 if (p1 != p1_end || p2 != p2_end)
6250 return 1;
6252 return 0;
6255 /* Entry points for GNU code. */
6257 /* re_compile_pattern is the GNU regular expression compiler: it
6258 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6259 Returns 0 if the pattern was valid, otherwise an error string.
6261 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6262 are set in BUFP on entry.
6264 We call regex_compile to do the actual compilation. */
6266 const char *
6267 re_compile_pattern (const char *pattern, size_t length,
6268 #ifdef emacs
6269 bool posix_backtracking, const char *whitespace_regexp,
6270 #endif
6271 struct re_pattern_buffer *bufp)
6273 reg_errcode_t ret;
6275 /* GNU code is written to assume at least RE_NREGS registers will be set
6276 (and at least one extra will be -1). */
6277 bufp->regs_allocated = REGS_UNALLOCATED;
6279 /* And GNU code determines whether or not to get register information
6280 by passing null for the REGS argument to re_match, etc., not by
6281 setting no_sub. */
6282 bufp->no_sub = 0;
6284 ret = regex_compile ((re_char *) pattern, length,
6285 #ifdef emacs
6286 posix_backtracking,
6287 whitespace_regexp,
6288 #else
6289 re_syntax_options,
6290 #endif
6291 bufp);
6293 if (!ret)
6294 return NULL;
6295 return gettext (re_error_msgid[(int) ret]);
6297 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6299 /* Entry points compatible with 4.2 BSD regex library. We don't define
6300 them unless specifically requested. */
6302 #if defined _REGEX_RE_COMP || defined _LIBC
6304 /* BSD has one and only one pattern buffer. */
6305 static struct re_pattern_buffer re_comp_buf;
6307 char *
6308 # ifdef _LIBC
6309 /* Make these definitions weak in libc, so POSIX programs can redefine
6310 these names if they don't use our functions, and still use
6311 regcomp/regexec below without link errors. */
6312 weak_function
6313 # endif
6314 re_comp (const char *s)
6316 reg_errcode_t ret;
6318 if (!s)
6320 if (!re_comp_buf.buffer)
6321 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6322 return (char *) gettext ("No previous regular expression");
6323 return 0;
6326 if (!re_comp_buf.buffer)
6328 re_comp_buf.buffer = malloc (200);
6329 if (re_comp_buf.buffer == NULL)
6330 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6331 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6332 re_comp_buf.allocated = 200;
6334 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6335 if (re_comp_buf.fastmap == NULL)
6336 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6337 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6340 /* Since `re_exec' always passes NULL for the `regs' argument, we
6341 don't need to initialize the pattern buffer fields which affect it. */
6343 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6345 if (!ret)
6346 return NULL;
6348 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6349 return (char *) gettext (re_error_msgid[(int) ret]);
6354 # ifdef _LIBC
6355 weak_function
6356 # endif
6357 re_exec (const char *s)
6359 const size_t len = strlen (s);
6360 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6362 #endif /* _REGEX_RE_COMP */
6364 /* POSIX.2 functions. Don't define these for Emacs. */
6366 #ifndef emacs
6368 /* regcomp takes a regular expression as a string and compiles it.
6370 PREG is a regex_t *. We do not expect any fields to be initialized,
6371 since POSIX says we shouldn't. Thus, we set
6373 `buffer' to the compiled pattern;
6374 `used' to the length of the compiled pattern;
6375 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6376 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6377 RE_SYNTAX_POSIX_BASIC;
6378 `fastmap' to an allocated space for the fastmap;
6379 `fastmap_accurate' to zero;
6380 `re_nsub' to the number of subexpressions in PATTERN.
6382 PATTERN is the address of the pattern string.
6384 CFLAGS is a series of bits which affect compilation.
6386 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6387 use POSIX basic syntax.
6389 If REG_NEWLINE is set, then . and [^...] don't match newline.
6390 Also, regexec will try a match beginning after every newline.
6392 If REG_ICASE is set, then we considers upper- and lowercase
6393 versions of letters to be equivalent when matching.
6395 If REG_NOSUB is set, then when PREG is passed to regexec, that
6396 routine will report only success or failure, and nothing about the
6397 registers.
6399 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6400 the return codes and their meanings.) */
6402 reg_errcode_t
6403 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6404 int cflags)
6406 reg_errcode_t ret;
6407 reg_syntax_t syntax
6408 = (cflags & REG_EXTENDED) ?
6409 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6411 /* regex_compile will allocate the space for the compiled pattern. */
6412 preg->buffer = 0;
6413 preg->allocated = 0;
6414 preg->used = 0;
6416 /* Try to allocate space for the fastmap. */
6417 preg->fastmap = malloc (1 << BYTEWIDTH);
6419 if (cflags & REG_ICASE)
6421 unsigned i;
6423 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6424 if (preg->translate == NULL)
6425 return (int) REG_ESPACE;
6427 /* Map uppercase characters to corresponding lowercase ones. */
6428 for (i = 0; i < CHAR_SET_SIZE; i++)
6429 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6431 else
6432 preg->translate = NULL;
6434 /* If REG_NEWLINE is set, newlines are treated differently. */
6435 if (cflags & REG_NEWLINE)
6436 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6437 syntax &= ~RE_DOT_NEWLINE;
6438 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6440 else
6441 syntax |= RE_NO_NEWLINE_ANCHOR;
6443 preg->no_sub = !!(cflags & REG_NOSUB);
6445 /* POSIX says a null character in the pattern terminates it, so we
6446 can use strlen here in compiling the pattern. */
6447 ret = regex_compile ((re_char *) pattern, strlen (pattern), syntax, preg);
6449 /* POSIX doesn't distinguish between an unmatched open-group and an
6450 unmatched close-group: both are REG_EPAREN. */
6451 if (ret == REG_ERPAREN)
6452 ret = REG_EPAREN;
6454 if (ret == REG_NOERROR && preg->fastmap)
6455 { /* Compute the fastmap now, since regexec cannot modify the pattern
6456 buffer. */
6457 re_compile_fastmap (preg);
6458 if (preg->can_be_null)
6459 { /* The fastmap can't be used anyway. */
6460 free (preg->fastmap);
6461 preg->fastmap = NULL;
6464 return ret;
6466 WEAK_ALIAS (__regcomp, regcomp)
6469 /* regexec searches for a given pattern, specified by PREG, in the
6470 string STRING.
6472 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6473 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6474 least NMATCH elements, and we set them to the offsets of the
6475 corresponding matched substrings.
6477 EFLAGS specifies `execution flags' which affect matching: if
6478 REG_NOTBOL is set, then ^ does not match at the beginning of the
6479 string; if REG_NOTEOL is set, then $ does not match at the end.
6481 We return 0 if we find a match and REG_NOMATCH if not. */
6483 reg_errcode_t
6484 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6485 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6487 regoff_t ret;
6488 struct re_registers regs;
6489 regex_t private_preg;
6490 size_t len = strlen (string);
6491 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6493 private_preg = *preg;
6495 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6496 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6498 /* The user has told us exactly how many registers to return
6499 information about, via `nmatch'. We have to pass that on to the
6500 matching routines. */
6501 private_preg.regs_allocated = REGS_FIXED;
6503 if (want_reg_info)
6505 regs.num_regs = nmatch;
6506 regs.start = TALLOC (nmatch * 2, regoff_t);
6507 if (regs.start == NULL)
6508 return REG_NOMATCH;
6509 regs.end = regs.start + nmatch;
6512 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6513 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6514 was a little bit longer but still only matching the real part.
6515 This works because the `endline' will check for a '\n' and will find a
6516 '\0', correctly deciding that this is not the end of a line.
6517 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6518 a convenient '\0' there. For all we know, the string could be preceded
6519 by '\n' which would throw things off. */
6521 /* Perform the searching operation. */
6522 ret = re_search (&private_preg, string, len,
6523 /* start: */ 0, /* range: */ len,
6524 want_reg_info ? &regs : 0);
6526 /* Copy the register information to the POSIX structure. */
6527 if (want_reg_info)
6529 if (ret >= 0)
6531 unsigned r;
6533 for (r = 0; r < nmatch; r++)
6535 pmatch[r].rm_so = regs.start[r];
6536 pmatch[r].rm_eo = regs.end[r];
6540 /* If we needed the temporary register info, free the space now. */
6541 free (regs.start);
6544 /* We want zero return to mean success, unlike `re_search'. */
6545 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6547 WEAK_ALIAS (__regexec, regexec)
6550 /* Returns a message corresponding to an error code, ERR_CODE, returned
6551 from either regcomp or regexec. We don't use PREG here.
6553 ERR_CODE was previously called ERRCODE, but that name causes an
6554 error with msvc8 compiler. */
6556 size_t
6557 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6559 const char *msg;
6560 size_t msg_size;
6562 if (err_code < 0
6563 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6564 /* Only error codes returned by the rest of the code should be passed
6565 to this routine. If we are given anything else, or if other regex
6566 code generates an invalid error code, then the program has a bug.
6567 Dump core so we can fix it. */
6568 abort ();
6570 msg = gettext (re_error_msgid[err_code]);
6572 msg_size = strlen (msg) + 1; /* Includes the null. */
6574 if (errbuf_size != 0)
6576 if (msg_size > errbuf_size)
6578 memcpy (errbuf, msg, errbuf_size - 1);
6579 errbuf[errbuf_size - 1] = 0;
6581 else
6582 strcpy (errbuf, msg);
6585 return msg_size;
6587 WEAK_ALIAS (__regerror, regerror)
6590 /* Free dynamically allocated space used by PREG. */
6592 void
6593 regfree (regex_t *preg)
6595 free (preg->buffer);
6596 preg->buffer = NULL;
6598 preg->allocated = 0;
6599 preg->used = 0;
6601 free (preg->fastmap);
6602 preg->fastmap = NULL;
6603 preg->fastmap_accurate = 0;
6605 free (preg->translate);
6606 preg->translate = NULL;
6608 WEAK_ALIAS (__regfree, regfree)
6610 #endif /* not emacs */