; Fix last commit in tramp.el
[emacs.git] / src / regex.c
bloba4e6441cce36e04c2509516d97e23591c4cce897
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993-2018 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <https://www.gnu.org/licenses/>. */
20 /* TODO:
21 - structure the opcode space into opcode+flag.
22 - merge with glibc's regex.[ch].
23 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
24 need to modify the compiled regexp so that re_match can be reentrant.
25 - get rid of on_failure_jump_smart by doing the optimization in re_comp
26 rather than at run-time, so that re_match can be reentrant.
29 /* AIX requires this to be the first thing in the file. */
30 #if defined _AIX && !defined REGEX_MALLOC
31 #pragma alloca
32 #endif
34 /* Ignore some GCC warnings for now. This section should go away
35 once the Emacs and Gnulib regex code is merged. */
36 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__) || defined __clang__
37 # pragma GCC diagnostic ignored "-Wstrict-overflow"
38 # ifndef emacs
39 # pragma GCC diagnostic ignored "-Wunused-function"
40 # pragma GCC diagnostic ignored "-Wunused-macros"
41 # pragma GCC diagnostic ignored "-Wunused-result"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
43 # endif
44 #endif
46 #if 4 < __GNUC__ + (6 <= __GNUC_MINOR__) && ! defined __clang__
47 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
48 #endif
50 #include <config.h>
52 #include <stddef.h>
53 #include <stdlib.h>
55 #ifdef emacs
56 /* We need this for `regex.h', and perhaps for the Emacs include files. */
57 # include <sys/types.h>
58 #endif
60 /* Whether to use ISO C Amendment 1 wide char functions.
61 Those should not be used for Emacs since it uses its own. */
62 #if defined _LIBC
63 #define WIDE_CHAR_SUPPORT 1
64 #else
65 #define WIDE_CHAR_SUPPORT \
66 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
67 #endif
69 /* For platform which support the ISO C amendment 1 functionality we
70 support user defined character classes. */
71 #if WIDE_CHAR_SUPPORT
72 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
73 # include <wchar.h>
74 # include <wctype.h>
75 #endif
77 #ifdef _LIBC
78 /* We have to keep the namespace clean. */
79 # define regfree(preg) __regfree (preg)
80 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
81 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
82 # define regerror(err_code, preg, errbuf, errbuf_size) \
83 __regerror (err_code, preg, errbuf, errbuf_size)
84 # define re_set_registers(bu, re, nu, st, en) \
85 __re_set_registers (bu, re, nu, st, en)
86 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
87 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
88 # define re_match(bufp, string, size, pos, regs) \
89 __re_match (bufp, string, size, pos, regs)
90 # define re_search(bufp, string, size, startpos, range, regs) \
91 __re_search (bufp, string, size, startpos, range, regs)
92 # define re_compile_pattern(pattern, length, bufp) \
93 __re_compile_pattern (pattern, length, bufp)
94 # define re_set_syntax(syntax) __re_set_syntax (syntax)
95 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
96 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
97 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
99 /* Make sure we call libc's function even if the user overrides them. */
100 # define btowc __btowc
101 # define iswctype __iswctype
102 # define wctype __wctype
104 # define WEAK_ALIAS(a,b) weak_alias (a, b)
106 /* We are also using some library internals. */
107 # include <locale/localeinfo.h>
108 # include <locale/elem-hash.h>
109 # include <langinfo.h>
110 #else
111 # define WEAK_ALIAS(a,b)
112 #endif
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
117 #else
118 # define gettext(msgid) (msgid)
119 #endif
121 #ifndef gettext_noop
122 /* This define is so xgettext can find the internationalizable
123 strings. */
124 # define gettext_noop(String) String
125 #endif
127 /* The `emacs' switch turns on certain matching commands
128 that make sense only in Emacs. */
129 #ifdef emacs
131 # include "lisp.h"
132 # include "character.h"
133 # include "buffer.h"
135 # include "syntax.h"
136 # include "category.h"
138 /* Make syntax table lookup grant data in gl_state. */
139 # define SYNTAX(c) syntax_property (c, 1)
141 # ifdef malloc
142 # undef malloc
143 # endif
144 # define malloc xmalloc
145 # ifdef realloc
146 # undef realloc
147 # endif
148 # define realloc xrealloc
149 # ifdef free
150 # undef free
151 # endif
152 # define free xfree
154 /* Converts the pointer to the char to BEG-based offset from the start. */
155 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
156 /* Strings are 0-indexed, buffers are 1-indexed; we pun on the boolean
157 result to get the right base index. */
158 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
160 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
161 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
162 # define RE_STRING_CHAR(p, multibyte) \
163 (multibyte ? (STRING_CHAR (p)) : (*(p)))
164 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
165 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
167 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
169 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
171 /* Set C a (possibly converted to multibyte) character before P. P
172 points into a string which is the virtual concatenation of STR1
173 (which ends at END1) or STR2 (which ends at END2). */
174 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
175 do { \
176 if (target_multibyte) \
178 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
179 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
180 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
181 c = STRING_CHAR (dtemp); \
183 else \
185 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
188 } while (0)
190 /* Set C a (possibly converted to multibyte) character at P, and set
191 LEN to the byte length of that character. */
192 # define GET_CHAR_AFTER(c, p, len) \
193 do { \
194 if (target_multibyte) \
195 (c) = STRING_CHAR_AND_LENGTH (p, len); \
196 else \
198 (c) = *p; \
199 len = 1; \
200 (c) = RE_CHAR_TO_MULTIBYTE (c); \
202 } while (0)
204 #else /* not emacs */
206 /* If we are not linking with Emacs proper,
207 we can't use the relocating allocator
208 even if config.h says that we can. */
209 # undef REL_ALLOC
211 # include <unistd.h>
213 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
215 static void *
216 xmalloc (size_t size)
218 void *val = malloc (size);
219 if (!val && size)
221 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
222 exit (1);
224 return val;
227 static void *
228 xrealloc (void *block, size_t size)
230 void *val;
231 /* We must call malloc explicitly when BLOCK is 0, since some
232 reallocs don't do this. */
233 if (! block)
234 val = malloc (size);
235 else
236 val = realloc (block, size);
237 if (!val && size)
239 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
240 exit (1);
242 return val;
245 # ifdef malloc
246 # undef malloc
247 # endif
248 # define malloc xmalloc
249 # ifdef realloc
250 # undef realloc
251 # endif
252 # define realloc xrealloc
254 # include <stdbool.h>
255 # include <string.h>
257 /* Define the syntax stuff for \<, \>, etc. */
259 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
260 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
262 /* Dummy macros for non-Emacs environments. */
263 # define MAX_MULTIBYTE_LENGTH 1
264 # define RE_MULTIBYTE_P(x) 0
265 # define RE_TARGET_MULTIBYTE_P(x) 0
266 # define WORD_BOUNDARY_P(c1, c2) (0)
267 # define BYTES_BY_CHAR_HEAD(p) (1)
268 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
269 # define STRING_CHAR(p) (*(p))
270 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
271 # define CHAR_STRING(c, s) (*(s) = (c), 1)
272 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
273 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
274 # define RE_CHAR_TO_MULTIBYTE(c) (c)
275 # define RE_CHAR_TO_UNIBYTE(c) (c)
276 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
277 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
278 # define GET_CHAR_AFTER(c, p, len) \
279 (c = *p, len = 1)
280 # define CHAR_BYTE8_P(c) (0)
281 # define CHAR_LEADING_CODE(c) (c)
283 #endif /* not emacs */
285 #ifndef RE_TRANSLATE
286 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
287 # define RE_TRANSLATE_P(TBL) (TBL)
288 #endif
290 /* Get the interface, including the syntax bits. */
291 #include "regex.h"
293 /* isalpha etc. are used for the character classes. */
294 #include <ctype.h>
296 #ifdef emacs
298 /* 1 if C is an ASCII character. */
299 # define IS_REAL_ASCII(c) ((c) < 0200)
301 /* 1 if C is a unibyte character. */
302 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
304 /* The Emacs definitions should not be directly affected by locales. */
306 /* In Emacs, these are only used for single-byte characters. */
307 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
308 # define ISCNTRL(c) ((c) < ' ')
309 # define ISXDIGIT(c) (0 <= char_hexdigit (c))
311 /* The rest must handle multibyte characters. */
313 # define ISBLANK(c) (IS_REAL_ASCII (c) \
314 ? ((c) == ' ' || (c) == '\t') \
315 : blankp (c))
317 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
318 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0240) \
319 : graphicp (c))
321 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
322 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
323 : printablep (c))
325 # define ISALNUM(c) (IS_REAL_ASCII (c) \
326 ? (((c) >= 'a' && (c) <= 'z') \
327 || ((c) >= 'A' && (c) <= 'Z') \
328 || ((c) >= '0' && (c) <= '9')) \
329 : alphanumericp (c))
331 # define ISALPHA(c) (IS_REAL_ASCII (c) \
332 ? (((c) >= 'a' && (c) <= 'z') \
333 || ((c) >= 'A' && (c) <= 'Z')) \
334 : alphabeticp (c))
336 # define ISLOWER(c) lowercasep (c)
338 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
339 ? ((c) > ' ' && (c) < 0177 \
340 && !(((c) >= 'a' && (c) <= 'z') \
341 || ((c) >= 'A' && (c) <= 'Z') \
342 || ((c) >= '0' && (c) <= '9'))) \
343 : SYNTAX (c) != Sword)
345 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
347 # define ISUPPER(c) uppercasep (c)
349 # define ISWORD(c) (SYNTAX (c) == Sword)
351 #else /* not emacs */
353 /* 1 if C is an ASCII character. */
354 # define IS_REAL_ASCII(c) ((c) < 0200)
356 /* This distinction is not meaningful, except in Emacs. */
357 # define ISUNIBYTE(c) 1
359 # ifdef isblank
360 # define ISBLANK(c) isblank (c)
361 # else
362 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
363 # endif
364 # ifdef isgraph
365 # define ISGRAPH(c) isgraph (c)
366 # else
367 # define ISGRAPH(c) (isprint (c) && !isspace (c))
368 # endif
370 /* Solaris defines ISPRINT so we must undefine it first. */
371 # undef ISPRINT
372 # define ISPRINT(c) isprint (c)
373 # define ISDIGIT(c) isdigit (c)
374 # define ISALNUM(c) isalnum (c)
375 # define ISALPHA(c) isalpha (c)
376 # define ISCNTRL(c) iscntrl (c)
377 # define ISLOWER(c) islower (c)
378 # define ISPUNCT(c) ispunct (c)
379 # define ISSPACE(c) isspace (c)
380 # define ISUPPER(c) isupper (c)
381 # define ISXDIGIT(c) isxdigit (c)
383 # define ISWORD(c) ISALPHA (c)
385 # ifdef _tolower
386 # define TOLOWER(c) _tolower (c)
387 # else
388 # define TOLOWER(c) tolower (c)
389 # endif
391 /* How many characters in the character set. */
392 # define CHAR_SET_SIZE 256
394 # ifdef SYNTAX_TABLE
396 extern char *re_syntax_table;
398 # else /* not SYNTAX_TABLE */
400 static char re_syntax_table[CHAR_SET_SIZE];
402 static void
403 init_syntax_once (void)
405 register int c;
406 static int done = 0;
408 if (done)
409 return;
411 memset (re_syntax_table, 0, sizeof re_syntax_table);
413 for (c = 0; c < CHAR_SET_SIZE; ++c)
414 if (ISALNUM (c))
415 re_syntax_table[c] = Sword;
417 re_syntax_table['_'] = Ssymbol;
419 done = 1;
422 # endif /* not SYNTAX_TABLE */
424 # define SYNTAX(c) re_syntax_table[(c)]
426 #endif /* not emacs */
428 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
430 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
431 use `alloca' instead of `malloc'. This is because using malloc in
432 re_search* or re_match* could cause memory leaks when C-g is used
433 in Emacs (note that SAFE_ALLOCA could also call malloc, but does so
434 via `record_xmalloc' which uses `unwind_protect' to ensure the
435 memory is freed even in case of non-local exits); also, malloc is
436 slower and causes storage fragmentation. On the other hand, malloc
437 is more portable, and easier to debug.
439 Because we sometimes use alloca, some routines have to be macros,
440 not functions -- `alloca'-allocated space disappears at the end of the
441 function it is called in. */
443 #ifdef REGEX_MALLOC
445 # define REGEX_ALLOCATE malloc
446 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
447 # define REGEX_FREE free
449 #else /* not REGEX_MALLOC */
451 # ifdef emacs
452 /* This may be adjusted in main(), if the stack is successfully grown. */
453 ptrdiff_t emacs_re_safe_alloca = MAX_ALLOCA;
454 /* Like USE_SAFE_ALLOCA, but use emacs_re_safe_alloca. */
455 # define REGEX_USE_SAFE_ALLOCA \
456 ptrdiff_t sa_avail = emacs_re_safe_alloca; \
457 ptrdiff_t sa_count = SPECPDL_INDEX (); bool sa_must_free = false
459 # define REGEX_SAFE_FREE() SAFE_FREE ()
460 # define REGEX_ALLOCATE SAFE_ALLOCA
461 # else
462 # include <alloca.h>
463 # define REGEX_ALLOCATE alloca
464 # endif
466 /* Assumes a `char *destination' variable. */
467 # define REGEX_REALLOCATE(source, osize, nsize) \
468 (destination = REGEX_ALLOCATE (nsize), \
469 memcpy (destination, source, osize))
471 /* No need to do anything to free, after alloca. */
472 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
474 #endif /* not REGEX_MALLOC */
476 #ifndef REGEX_USE_SAFE_ALLOCA
477 # define REGEX_USE_SAFE_ALLOCA ((void) 0)
478 # define REGEX_SAFE_FREE() ((void) 0)
479 #endif
481 /* Define how to allocate the failure stack. */
483 #if defined REL_ALLOC && defined REGEX_MALLOC
485 # define REGEX_ALLOCATE_STACK(size) \
486 r_alloc (&failure_stack_ptr, (size))
487 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
488 r_re_alloc (&failure_stack_ptr, (nsize))
489 # define REGEX_FREE_STACK(ptr) \
490 r_alloc_free (&failure_stack_ptr)
492 #else /* not using relocating allocator */
494 # define REGEX_ALLOCATE_STACK(size) REGEX_ALLOCATE (size)
495 # define REGEX_REALLOCATE_STACK(source, o, n) REGEX_REALLOCATE (source, o, n)
496 # define REGEX_FREE_STACK(ptr) REGEX_FREE (ptr)
498 #endif /* not using relocating allocator */
501 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
502 `string1' or just past its end. This works if PTR is NULL, which is
503 a good thing. */
504 #define FIRST_STRING_P(ptr) \
505 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
507 /* (Re)Allocate N items of type T using malloc, or fail. */
508 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
509 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
510 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
512 #define BYTEWIDTH 8 /* In bits. */
514 #ifndef emacs
515 # undef max
516 # undef min
517 # define max(a, b) ((a) > (b) ? (a) : (b))
518 # define min(a, b) ((a) < (b) ? (a) : (b))
519 #endif
521 /* Type of source-pattern and string chars. */
522 typedef const unsigned char re_char;
524 typedef char boolean;
526 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
527 re_char *string1, size_t size1,
528 re_char *string2, size_t size2,
529 ssize_t pos,
530 struct re_registers *regs,
531 ssize_t stop);
533 /* These are the command codes that appear in compiled regular
534 expressions. Some opcodes are followed by argument bytes. A
535 command code can specify any interpretation whatsoever for its
536 arguments. Zero bytes may appear in the compiled regular expression. */
538 typedef enum
540 no_op = 0,
542 /* Succeed right away--no more backtracking. */
543 succeed,
545 /* Followed by one byte giving n, then by n literal bytes. */
546 exactn,
548 /* Matches any (more or less) character. */
549 anychar,
551 /* Matches any one char belonging to specified set. First
552 following byte is number of bitmap bytes. Then come bytes
553 for a bitmap saying which chars are in. Bits in each byte
554 are ordered low-bit-first. A character is in the set if its
555 bit is 1. A character too large to have a bit in the map is
556 automatically not in the set.
558 If the length byte has the 0x80 bit set, then that stuff
559 is followed by a range table:
560 2 bytes of flags for character sets (low 8 bits, high 8 bits)
561 See RANGE_TABLE_WORK_BITS below.
562 2 bytes, the number of pairs that follow (upto 32767)
563 pairs, each 2 multibyte characters,
564 each multibyte character represented as 3 bytes. */
565 charset,
567 /* Same parameters as charset, but match any character that is
568 not one of those specified. */
569 charset_not,
571 /* Start remembering the text that is matched, for storing in a
572 register. Followed by one byte with the register number, in
573 the range 0 to one less than the pattern buffer's re_nsub
574 field. */
575 start_memory,
577 /* Stop remembering the text that is matched and store it in a
578 memory register. Followed by one byte with the register
579 number, in the range 0 to one less than `re_nsub' in the
580 pattern buffer. */
581 stop_memory,
583 /* Match a duplicate of something remembered. Followed by one
584 byte containing the register number. */
585 duplicate,
587 /* Fail unless at beginning of line. */
588 begline,
590 /* Fail unless at end of line. */
591 endline,
593 /* Succeeds if at beginning of buffer (if emacs) or at beginning
594 of string to be matched (if not). */
595 begbuf,
597 /* Analogously, for end of buffer/string. */
598 endbuf,
600 /* Followed by two byte relative address to which to jump. */
601 jump,
603 /* Followed by two-byte relative address of place to resume at
604 in case of failure. */
605 on_failure_jump,
607 /* Like on_failure_jump, but pushes a placeholder instead of the
608 current string position when executed. */
609 on_failure_keep_string_jump,
611 /* Just like `on_failure_jump', except that it checks that we
612 don't get stuck in an infinite loop (matching an empty string
613 indefinitely). */
614 on_failure_jump_loop,
616 /* Just like `on_failure_jump_loop', except that it checks for
617 a different kind of loop (the kind that shows up with non-greedy
618 operators). This operation has to be immediately preceded
619 by a `no_op'. */
620 on_failure_jump_nastyloop,
622 /* A smart `on_failure_jump' used for greedy * and + operators.
623 It analyzes the loop before which it is put and if the
624 loop does not require backtracking, it changes itself to
625 `on_failure_keep_string_jump' and short-circuits the loop,
626 else it just defaults to changing itself into `on_failure_jump'.
627 It assumes that it is pointing to just past a `jump'. */
628 on_failure_jump_smart,
630 /* Followed by two-byte relative address and two-byte number n.
631 After matching N times, jump to the address upon failure.
632 Does not work if N starts at 0: use on_failure_jump_loop
633 instead. */
634 succeed_n,
636 /* Followed by two-byte relative address, and two-byte number n.
637 Jump to the address N times, then fail. */
638 jump_n,
640 /* Set the following two-byte relative address to the
641 subsequent two-byte number. The address *includes* the two
642 bytes of number. */
643 set_number_at,
645 wordbeg, /* Succeeds if at word beginning. */
646 wordend, /* Succeeds if at word end. */
648 wordbound, /* Succeeds if at a word boundary. */
649 notwordbound, /* Succeeds if not at a word boundary. */
651 symbeg, /* Succeeds if at symbol beginning. */
652 symend, /* Succeeds if at symbol end. */
654 /* Matches any character whose syntax is specified. Followed by
655 a byte which contains a syntax code, e.g., Sword. */
656 syntaxspec,
658 /* Matches any character whose syntax is not that specified. */
659 notsyntaxspec
661 #ifdef emacs
662 , at_dot, /* Succeeds if at point. */
664 /* Matches any character whose category-set contains the specified
665 category. The operator is followed by a byte which contains a
666 category code (mnemonic ASCII character). */
667 categoryspec,
669 /* Matches any character whose category-set does not contain the
670 specified category. The operator is followed by a byte which
671 contains the category code (mnemonic ASCII character). */
672 notcategoryspec
673 #endif /* emacs */
674 } re_opcode_t;
676 /* Common operations on the compiled pattern. */
678 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
680 #define STORE_NUMBER(destination, number) \
681 do { \
682 (destination)[0] = (number) & 0377; \
683 (destination)[1] = (number) >> 8; \
684 } while (0)
686 /* Same as STORE_NUMBER, except increment DESTINATION to
687 the byte after where the number is stored. Therefore, DESTINATION
688 must be an lvalue. */
690 #define STORE_NUMBER_AND_INCR(destination, number) \
691 do { \
692 STORE_NUMBER (destination, number); \
693 (destination) += 2; \
694 } while (0)
696 /* Put into DESTINATION a number stored in two contiguous bytes starting
697 at SOURCE. */
699 #define EXTRACT_NUMBER(destination, source) \
700 ((destination) = extract_number (source))
702 static int
703 extract_number (re_char *source)
705 unsigned leading_byte = SIGN_EXTEND_CHAR (source[1]);
706 return (leading_byte << 8) + source[0];
709 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
710 SOURCE must be an lvalue. */
712 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
713 ((destination) = extract_number_and_incr (&source))
715 static int
716 extract_number_and_incr (re_char **source)
718 int num = extract_number (*source);
719 *source += 2;
720 return num;
723 /* Store a multibyte character in three contiguous bytes starting
724 DESTINATION, and increment DESTINATION to the byte after where the
725 character is stored. Therefore, DESTINATION must be an lvalue. */
727 #define STORE_CHARACTER_AND_INCR(destination, character) \
728 do { \
729 (destination)[0] = (character) & 0377; \
730 (destination)[1] = ((character) >> 8) & 0377; \
731 (destination)[2] = (character) >> 16; \
732 (destination) += 3; \
733 } while (0)
735 /* Put into DESTINATION a character stored in three contiguous bytes
736 starting at SOURCE. */
738 #define EXTRACT_CHARACTER(destination, source) \
739 do { \
740 (destination) = ((source)[0] \
741 | ((source)[1] << 8) \
742 | ((source)[2] << 16)); \
743 } while (0)
746 /* Macros for charset. */
748 /* Size of bitmap of charset P in bytes. P is a start of charset,
749 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
750 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
752 /* Nonzero if charset P has range table. */
753 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
755 /* Return the address of range table of charset P. But not the start
756 of table itself, but the before where the number of ranges is
757 stored. `2 +' means to skip re_opcode_t and size of bitmap,
758 and the 2 bytes of flags at the start of the range table. */
759 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
761 #ifdef emacs
762 /* Extract the bit flags that start a range table. */
763 #define CHARSET_RANGE_TABLE_BITS(p) \
764 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
765 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
766 #endif
768 /* Return the address of end of RANGE_TABLE. COUNT is number of
769 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
770 is start of range and end of range. `* 3' is size of each start
771 and end. */
772 #define CHARSET_RANGE_TABLE_END(range_table, count) \
773 ((range_table) + (count) * 2 * 3)
775 /* If DEBUG is defined, Regex prints many voluminous messages about what
776 it is doing (if the variable `debug' is nonzero). If linked with the
777 main program in `iregex.c', you can enter patterns and strings
778 interactively. And if linked with the main program in `main.c' and
779 the other test files, you can run the already-written tests. */
781 #ifdef DEBUG
783 /* We use standard I/O for debugging. */
784 # include <stdio.h>
786 /* It is useful to test things that ``must'' be true when debugging. */
787 # include <assert.h>
789 static int debug = -100000;
791 # define DEBUG_STATEMENT(e) e
792 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
793 # define DEBUG_COMPILES_ARGUMENTS
794 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
795 if (debug > 0) print_partial_compiled_pattern (s, e)
796 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
797 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
800 /* Print the fastmap in human-readable form. */
802 static void
803 print_fastmap (char *fastmap)
805 unsigned was_a_range = 0;
806 unsigned i = 0;
808 while (i < (1 << BYTEWIDTH))
810 if (fastmap[i++])
812 was_a_range = 0;
813 putchar (i - 1);
814 while (i < (1 << BYTEWIDTH) && fastmap[i])
816 was_a_range = 1;
817 i++;
819 if (was_a_range)
821 printf ("-");
822 putchar (i - 1);
826 putchar ('\n');
830 /* Print a compiled pattern string in human-readable form, starting at
831 the START pointer into it and ending just before the pointer END. */
833 static void
834 print_partial_compiled_pattern (re_char *start, re_char *end)
836 int mcnt, mcnt2;
837 re_char *p = start;
838 re_char *pend = end;
840 if (start == NULL)
842 fprintf (stderr, "(null)\n");
843 return;
846 /* Loop over pattern commands. */
847 while (p < pend)
849 fprintf (stderr, "%td:\t", p - start);
851 switch ((re_opcode_t) *p++)
853 case no_op:
854 fprintf (stderr, "/no_op");
855 break;
857 case succeed:
858 fprintf (stderr, "/succeed");
859 break;
861 case exactn:
862 mcnt = *p++;
863 fprintf (stderr, "/exactn/%d", mcnt);
866 fprintf (stderr, "/%c", *p++);
868 while (--mcnt);
869 break;
871 case start_memory:
872 fprintf (stderr, "/start_memory/%d", *p++);
873 break;
875 case stop_memory:
876 fprintf (stderr, "/stop_memory/%d", *p++);
877 break;
879 case duplicate:
880 fprintf (stderr, "/duplicate/%d", *p++);
881 break;
883 case anychar:
884 fprintf (stderr, "/anychar");
885 break;
887 case charset:
888 case charset_not:
890 register int c, last = -100;
891 register int in_range = 0;
892 int length = CHARSET_BITMAP_SIZE (p - 1);
893 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
895 fprintf (stderr, "/charset [%s",
896 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
898 if (p + *p >= pend)
899 fprintf (stderr, " !extends past end of pattern! ");
901 for (c = 0; c < 256; c++)
902 if (c / 8 < length
903 && (p[1 + (c/8)] & (1 << (c % 8))))
905 /* Are we starting a range? */
906 if (last + 1 == c && ! in_range)
908 fprintf (stderr, "-");
909 in_range = 1;
911 /* Have we broken a range? */
912 else if (last + 1 != c && in_range)
914 fprintf (stderr, "%c", last);
915 in_range = 0;
918 if (! in_range)
919 fprintf (stderr, "%c", c);
921 last = c;
924 if (in_range)
925 fprintf (stderr, "%c", last);
927 fprintf (stderr, "]");
929 p += 1 + length;
931 if (has_range_table)
933 int count;
934 fprintf (stderr, "has-range-table");
936 /* ??? Should print the range table; for now, just skip it. */
937 p += 2; /* skip range table bits */
938 EXTRACT_NUMBER_AND_INCR (count, p);
939 p = CHARSET_RANGE_TABLE_END (p, count);
942 break;
944 case begline:
945 fprintf (stderr, "/begline");
946 break;
948 case endline:
949 fprintf (stderr, "/endline");
950 break;
952 case on_failure_jump:
953 EXTRACT_NUMBER_AND_INCR (mcnt, p);
954 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
955 break;
957 case on_failure_keep_string_jump:
958 EXTRACT_NUMBER_AND_INCR (mcnt, p);
959 fprintf (stderr, "/on_failure_keep_string_jump to %td",
960 p + mcnt - start);
961 break;
963 case on_failure_jump_nastyloop:
964 EXTRACT_NUMBER_AND_INCR (mcnt, p);
965 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
966 p + mcnt - start);
967 break;
969 case on_failure_jump_loop:
970 EXTRACT_NUMBER_AND_INCR (mcnt, p);
971 fprintf (stderr, "/on_failure_jump_loop to %td",
972 p + mcnt - start);
973 break;
975 case on_failure_jump_smart:
976 EXTRACT_NUMBER_AND_INCR (mcnt, p);
977 fprintf (stderr, "/on_failure_jump_smart to %td",
978 p + mcnt - start);
979 break;
981 case jump:
982 EXTRACT_NUMBER_AND_INCR (mcnt, p);
983 fprintf (stderr, "/jump to %td", p + mcnt - start);
984 break;
986 case succeed_n:
987 EXTRACT_NUMBER_AND_INCR (mcnt, p);
988 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
989 fprintf (stderr, "/succeed_n to %td, %d times",
990 p - 2 + mcnt - start, mcnt2);
991 break;
993 case jump_n:
994 EXTRACT_NUMBER_AND_INCR (mcnt, p);
995 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
996 fprintf (stderr, "/jump_n to %td, %d times",
997 p - 2 + mcnt - start, mcnt2);
998 break;
1000 case set_number_at:
1001 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1002 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1003 fprintf (stderr, "/set_number_at location %td to %d",
1004 p - 2 + mcnt - start, mcnt2);
1005 break;
1007 case wordbound:
1008 fprintf (stderr, "/wordbound");
1009 break;
1011 case notwordbound:
1012 fprintf (stderr, "/notwordbound");
1013 break;
1015 case wordbeg:
1016 fprintf (stderr, "/wordbeg");
1017 break;
1019 case wordend:
1020 fprintf (stderr, "/wordend");
1021 break;
1023 case symbeg:
1024 fprintf (stderr, "/symbeg");
1025 break;
1027 case symend:
1028 fprintf (stderr, "/symend");
1029 break;
1031 case syntaxspec:
1032 fprintf (stderr, "/syntaxspec");
1033 mcnt = *p++;
1034 fprintf (stderr, "/%d", mcnt);
1035 break;
1037 case notsyntaxspec:
1038 fprintf (stderr, "/notsyntaxspec");
1039 mcnt = *p++;
1040 fprintf (stderr, "/%d", mcnt);
1041 break;
1043 # ifdef emacs
1044 case at_dot:
1045 fprintf (stderr, "/at_dot");
1046 break;
1048 case categoryspec:
1049 fprintf (stderr, "/categoryspec");
1050 mcnt = *p++;
1051 fprintf (stderr, "/%d", mcnt);
1052 break;
1054 case notcategoryspec:
1055 fprintf (stderr, "/notcategoryspec");
1056 mcnt = *p++;
1057 fprintf (stderr, "/%d", mcnt);
1058 break;
1059 # endif /* emacs */
1061 case begbuf:
1062 fprintf (stderr, "/begbuf");
1063 break;
1065 case endbuf:
1066 fprintf (stderr, "/endbuf");
1067 break;
1069 default:
1070 fprintf (stderr, "?%d", *(p-1));
1073 fprintf (stderr, "\n");
1076 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1080 static void
1081 print_compiled_pattern (struct re_pattern_buffer *bufp)
1083 re_char *buffer = bufp->buffer;
1085 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1086 printf ("%ld bytes used/%ld bytes allocated.\n",
1087 bufp->used, bufp->allocated);
1089 if (bufp->fastmap_accurate && bufp->fastmap)
1091 printf ("fastmap: ");
1092 print_fastmap (bufp->fastmap);
1095 printf ("re_nsub: %zu\t", bufp->re_nsub);
1096 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1097 printf ("can_be_null: %d\t", bufp->can_be_null);
1098 printf ("no_sub: %d\t", bufp->no_sub);
1099 printf ("not_bol: %d\t", bufp->not_bol);
1100 printf ("not_eol: %d\t", bufp->not_eol);
1101 #ifndef emacs
1102 printf ("syntax: %lx\n", bufp->syntax);
1103 #endif
1104 fflush (stdout);
1105 /* Perhaps we should print the translate table? */
1109 static void
1110 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1111 re_char *string2, ssize_t size2)
1113 ssize_t this_char;
1115 if (where == NULL)
1116 printf ("(null)");
1117 else
1119 if (FIRST_STRING_P (where))
1121 for (this_char = where - string1; this_char < size1; this_char++)
1122 putchar (string1[this_char]);
1124 where = string2;
1127 for (this_char = where - string2; this_char < size2; this_char++)
1128 putchar (string2[this_char]);
1132 #else /* not DEBUG */
1134 # undef assert
1135 # define assert(e)
1137 # define DEBUG_STATEMENT(e)
1138 # define DEBUG_PRINT(...)
1139 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1140 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1142 #endif /* not DEBUG */
1144 #ifndef emacs
1146 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1147 also be assigned to arbitrarily: each pattern buffer stores its own
1148 syntax, so it can be changed between regex compilations. */
1149 /* This has no initializer because initialized variables in Emacs
1150 become read-only after dumping. */
1151 reg_syntax_t re_syntax_options;
1154 /* Specify the precise syntax of regexps for compilation. This provides
1155 for compatibility for various utilities which historically have
1156 different, incompatible syntaxes.
1158 The argument SYNTAX is a bit mask comprised of the various bits
1159 defined in regex.h. We return the old syntax. */
1161 reg_syntax_t
1162 re_set_syntax (reg_syntax_t syntax)
1164 reg_syntax_t ret = re_syntax_options;
1166 re_syntax_options = syntax;
1167 return ret;
1169 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1171 #endif
1173 /* This table gives an error message for each of the error codes listed
1174 in regex.h. Obviously the order here has to be same as there.
1175 POSIX doesn't require that we do anything for REG_NOERROR,
1176 but why not be nice? */
1178 static const char *re_error_msgid[] =
1180 gettext_noop ("Success"), /* REG_NOERROR */
1181 gettext_noop ("No match"), /* REG_NOMATCH */
1182 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1183 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1184 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1185 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1186 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1187 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1188 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1189 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1190 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1191 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1192 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1193 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1194 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1195 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1196 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1197 gettext_noop ("Range striding over charsets"), /* REG_ERANGEX */
1198 gettext_noop ("Invalid content of \\{\\}, repetitions too big") /* REG_ESIZEBR */
1201 /* Whether to allocate memory during matching. */
1203 /* Define MATCH_MAY_ALLOCATE to allow the searching and matching
1204 functions allocate memory for the failure stack and registers.
1205 Normally should be defined, because otherwise searching and
1206 matching routines will have much smaller memory resources at their
1207 disposal, and therefore might fail to handle complex regexps.
1208 Therefore undefine MATCH_MAY_ALLOCATE only in the following
1209 exceptional situations:
1211 . When running on a system where memory is at premium.
1212 . When alloca cannot be used at all, perhaps due to bugs in
1213 its implementation, or its being unavailable, or due to a
1214 very small stack size. This requires to define REGEX_MALLOC
1215 to use malloc instead, which in turn could lead to memory
1216 leaks if search is interrupted by a signal. (For these
1217 reasons, defining REGEX_MALLOC when building Emacs
1218 automatically undefines MATCH_MAY_ALLOCATE, but outside
1219 Emacs you may not care about memory leaks.) If you want to
1220 prevent the memory leaks, undefine MATCH_MAY_ALLOCATE.
1221 . When code that calls the searching and matching functions
1222 cannot allow memory allocation, for whatever reasons. */
1224 /* Normally, this is fine. */
1225 #define MATCH_MAY_ALLOCATE
1227 /* The match routines may not allocate if (1) they would do it with malloc
1228 and (2) it's not safe for them to use malloc.
1229 Note that if REL_ALLOC is defined, matching would not use malloc for the
1230 failure stack, but we would still use it for the register vectors;
1231 so REL_ALLOC should not affect this. */
1232 #if defined REGEX_MALLOC && defined emacs
1233 # undef MATCH_MAY_ALLOCATE
1234 #endif
1237 /* Failure stack declarations and macros; both re_compile_fastmap and
1238 re_match_2 use a failure stack. These have to be macros because of
1239 REGEX_ALLOCATE_STACK. */
1242 /* Approximate number of failure points for which to initially allocate space
1243 when matching. If this number is exceeded, we allocate more
1244 space, so it is not a hard limit. */
1245 #ifndef INIT_FAILURE_ALLOC
1246 # define INIT_FAILURE_ALLOC 20
1247 #endif
1249 /* Roughly the maximum number of failure points on the stack. Would be
1250 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1251 This is a variable only so users of regex can assign to it; we never
1252 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1253 before using it, so it should probably be a byte-count instead. */
1254 # if defined MATCH_MAY_ALLOCATE
1255 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1256 whose default stack limit is 2mb. In order for a larger
1257 value to work reliably, you have to try to make it accord
1258 with the process stack limit. */
1259 size_t emacs_re_max_failures = 40000;
1260 # else
1261 size_t emacs_re_max_failures = 4000;
1262 # endif
1264 union fail_stack_elt
1266 re_char *pointer;
1267 /* This should be the biggest `int' that's no bigger than a pointer. */
1268 long integer;
1271 typedef union fail_stack_elt fail_stack_elt_t;
1273 typedef struct
1275 fail_stack_elt_t *stack;
1276 size_t size;
1277 size_t avail; /* Offset of next open position. */
1278 size_t frame; /* Offset of the cur constructed frame. */
1279 } fail_stack_type;
1281 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1284 /* Define macros to initialize and free the failure stack.
1285 Do `return -2' if the alloc fails. */
1287 #ifdef MATCH_MAY_ALLOCATE
1288 # define INIT_FAIL_STACK() \
1289 do { \
1290 fail_stack.stack = \
1291 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1292 * sizeof (fail_stack_elt_t)); \
1294 if (fail_stack.stack == NULL) \
1295 return -2; \
1297 fail_stack.size = INIT_FAILURE_ALLOC; \
1298 fail_stack.avail = 0; \
1299 fail_stack.frame = 0; \
1300 } while (0)
1301 #else
1302 # define INIT_FAIL_STACK() \
1303 do { \
1304 fail_stack.avail = 0; \
1305 fail_stack.frame = 0; \
1306 } while (0)
1308 # define RETALLOC_IF(addr, n, t) \
1309 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1310 #endif
1313 /* Double the size of FAIL_STACK, up to a limit
1314 which allows approximately `emacs_re_max_failures' items.
1316 Return 1 if succeeds, and 0 if either ran out of memory
1317 allocating space for it or it was already too large.
1319 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1321 /* Factor to increase the failure stack size by
1322 when we increase it.
1323 This used to be 2, but 2 was too wasteful
1324 because the old discarded stacks added up to as much space
1325 were as ultimate, maximum-size stack. */
1326 #define FAIL_STACK_GROWTH_FACTOR 4
1328 #define GROW_FAIL_STACK(fail_stack) \
1329 (((fail_stack).size >= emacs_re_max_failures * TYPICAL_FAILURE_SIZE) \
1330 ? 0 \
1331 : ((fail_stack).stack \
1332 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1333 (fail_stack).size * sizeof (fail_stack_elt_t), \
1334 min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1335 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR)) \
1336 * sizeof (fail_stack_elt_t)), \
1338 (fail_stack).stack == NULL \
1339 ? 0 \
1340 : ((fail_stack).size \
1341 = (min (emacs_re_max_failures * TYPICAL_FAILURE_SIZE, \
1342 ((fail_stack).size * FAIL_STACK_GROWTH_FACTOR))), \
1343 1)))
1346 /* Push a pointer value onto the failure stack.
1347 Assumes the variable `fail_stack'. Probably should only
1348 be called from within `PUSH_FAILURE_POINT'. */
1349 #define PUSH_FAILURE_POINTER(item) \
1350 fail_stack.stack[fail_stack.avail++].pointer = (item)
1352 /* This pushes an integer-valued item onto the failure stack.
1353 Assumes the variable `fail_stack'. Probably should only
1354 be called from within `PUSH_FAILURE_POINT'. */
1355 #define PUSH_FAILURE_INT(item) \
1356 fail_stack.stack[fail_stack.avail++].integer = (item)
1358 /* These POP... operations complement the PUSH... operations.
1359 All assume that `fail_stack' is nonempty. */
1360 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1361 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1363 /* Individual items aside from the registers. */
1364 #define NUM_NONREG_ITEMS 3
1366 /* Used to examine the stack (to detect infinite loops). */
1367 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1368 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1369 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1370 #define TOP_FAILURE_HANDLE() fail_stack.frame
1373 #define ENSURE_FAIL_STACK(space) \
1374 while (REMAINING_AVAIL_SLOTS <= space) { \
1375 if (!GROW_FAIL_STACK (fail_stack)) \
1376 return -2; \
1377 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1378 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1381 /* Push register NUM onto the stack. */
1382 #define PUSH_FAILURE_REG(num) \
1383 do { \
1384 char *destination; \
1385 long n = num; \
1386 ENSURE_FAIL_STACK(3); \
1387 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1388 n, regstart[n], regend[n]); \
1389 PUSH_FAILURE_POINTER (regstart[n]); \
1390 PUSH_FAILURE_POINTER (regend[n]); \
1391 PUSH_FAILURE_INT (n); \
1392 } while (0)
1394 /* Change the counter's value to VAL, but make sure that it will
1395 be reset when backtracking. */
1396 #define PUSH_NUMBER(ptr,val) \
1397 do { \
1398 char *destination; \
1399 int c; \
1400 ENSURE_FAIL_STACK(3); \
1401 EXTRACT_NUMBER (c, ptr); \
1402 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1403 PUSH_FAILURE_INT (c); \
1404 PUSH_FAILURE_POINTER (ptr); \
1405 PUSH_FAILURE_INT (-1); \
1406 STORE_NUMBER (ptr, val); \
1407 } while (0)
1409 /* Pop a saved register off the stack. */
1410 #define POP_FAILURE_REG_OR_COUNT() \
1411 do { \
1412 long pfreg = POP_FAILURE_INT (); \
1413 if (pfreg == -1) \
1415 /* It's a counter. */ \
1416 /* Here, we discard `const', making re_match non-reentrant. */ \
1417 unsigned char *ptr = (unsigned char *) POP_FAILURE_POINTER (); \
1418 pfreg = POP_FAILURE_INT (); \
1419 STORE_NUMBER (ptr, pfreg); \
1420 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1422 else \
1424 regend[pfreg] = POP_FAILURE_POINTER (); \
1425 regstart[pfreg] = POP_FAILURE_POINTER (); \
1426 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1427 pfreg, regstart[pfreg], regend[pfreg]); \
1429 } while (0)
1431 /* Check that we are not stuck in an infinite loop. */
1432 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1433 do { \
1434 ssize_t failure = TOP_FAILURE_HANDLE (); \
1435 /* Check for infinite matching loops */ \
1436 while (failure > 0 \
1437 && (FAILURE_STR (failure) == string_place \
1438 || FAILURE_STR (failure) == NULL)) \
1440 assert (FAILURE_PAT (failure) >= bufp->buffer \
1441 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1442 if (FAILURE_PAT (failure) == pat_cur) \
1444 cycle = 1; \
1445 break; \
1447 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1448 failure = NEXT_FAILURE_HANDLE(failure); \
1450 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1451 } while (0)
1453 /* Push the information about the state we will need
1454 if we ever fail back to it.
1456 Requires variables fail_stack, regstart, regend and
1457 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1458 declared.
1460 Does `return FAILURE_CODE' if runs out of memory. */
1462 #define PUSH_FAILURE_POINT(pattern, string_place) \
1463 do { \
1464 char *destination; \
1465 /* Must be int, so when we don't save any registers, the arithmetic \
1466 of 0 + -1 isn't done as unsigned. */ \
1468 DEBUG_STATEMENT (nfailure_points_pushed++); \
1469 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1470 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1471 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1473 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1475 DEBUG_PRINT ("\n"); \
1477 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1478 PUSH_FAILURE_INT (fail_stack.frame); \
1480 DEBUG_PRINT (" Push string %p: \"", string_place); \
1481 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1482 DEBUG_PRINT ("\"\n"); \
1483 PUSH_FAILURE_POINTER (string_place); \
1485 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1486 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1487 PUSH_FAILURE_POINTER (pattern); \
1489 /* Close the frame by moving the frame pointer past it. */ \
1490 fail_stack.frame = fail_stack.avail; \
1491 } while (0)
1493 /* Estimate the size of data pushed by a typical failure stack entry.
1494 An estimate is all we need, because all we use this for
1495 is to choose a limit for how big to make the failure stack. */
1496 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1497 #define TYPICAL_FAILURE_SIZE 20
1499 /* How many items can still be added to the stack without overflowing it. */
1500 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1503 /* Pops what PUSH_FAIL_STACK pushes.
1505 We restore into the parameters, all of which should be lvalues:
1506 STR -- the saved data position.
1507 PAT -- the saved pattern position.
1508 REGSTART, REGEND -- arrays of string positions.
1510 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1511 `pend', `string1', `size1', `string2', and `size2'. */
1513 #define POP_FAILURE_POINT(str, pat) \
1514 do { \
1515 assert (!FAIL_STACK_EMPTY ()); \
1517 /* Remove failure points and point to how many regs pushed. */ \
1518 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1519 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1520 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1522 /* Pop the saved registers. */ \
1523 while (fail_stack.frame < fail_stack.avail) \
1524 POP_FAILURE_REG_OR_COUNT (); \
1526 pat = POP_FAILURE_POINTER (); \
1527 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1528 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1530 /* If the saved string location is NULL, it came from an \
1531 on_failure_keep_string_jump opcode, and we want to throw away the \
1532 saved NULL, thus retaining our current position in the string. */ \
1533 str = POP_FAILURE_POINTER (); \
1534 DEBUG_PRINT (" Popping string %p: \"", str); \
1535 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1536 DEBUG_PRINT ("\"\n"); \
1538 fail_stack.frame = POP_FAILURE_INT (); \
1539 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1541 assert (fail_stack.avail >= 0); \
1542 assert (fail_stack.frame <= fail_stack.avail); \
1544 DEBUG_STATEMENT (nfailure_points_popped++); \
1545 } while (0) /* POP_FAILURE_POINT */
1549 /* Registers are set to a sentinel when they haven't yet matched. */
1550 #define REG_UNSET(e) ((e) == NULL)
1552 /* Subroutine declarations and macros for regex_compile. */
1554 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1555 #ifdef emacs
1556 bool posix_backtracking,
1557 const char *whitespace_regexp,
1558 #else
1559 reg_syntax_t syntax,
1560 #endif
1561 struct re_pattern_buffer *bufp);
1562 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1563 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1564 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1565 int arg, unsigned char *end);
1566 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1567 int arg1, int arg2, unsigned char *end);
1568 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1569 reg_syntax_t syntax);
1570 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1571 reg_syntax_t syntax);
1572 static re_char *skip_one_char (re_char *p);
1573 static int analyze_first (re_char *p, re_char *pend,
1574 char *fastmap, const int multibyte);
1576 /* Fetch the next character in the uncompiled pattern, with no
1577 translation. */
1578 #define PATFETCH(c) \
1579 do { \
1580 int len; \
1581 if (p == pend) return REG_EEND; \
1582 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1583 p += len; \
1584 } while (0)
1587 /* If `translate' is non-null, return translate[D], else just D. We
1588 cast the subscript to translate because some data is declared as
1589 `char *', to avoid warnings when a string constant is passed. But
1590 when we use a character as a subscript we must make it unsigned. */
1591 #ifndef TRANSLATE
1592 # define TRANSLATE(d) \
1593 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1594 #endif
1597 /* Macros for outputting the compiled pattern into `buffer'. */
1599 /* If the buffer isn't allocated when it comes in, use this. */
1600 #define INIT_BUF_SIZE 32
1602 /* Make sure we have at least N more bytes of space in buffer. */
1603 #define GET_BUFFER_SPACE(n) \
1604 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1605 EXTEND_BUFFER ()
1607 /* Make sure we have one more byte of buffer space and then add C to it. */
1608 #define BUF_PUSH(c) \
1609 do { \
1610 GET_BUFFER_SPACE (1); \
1611 *b++ = (unsigned char) (c); \
1612 } while (0)
1615 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1616 #define BUF_PUSH_2(c1, c2) \
1617 do { \
1618 GET_BUFFER_SPACE (2); \
1619 *b++ = (unsigned char) (c1); \
1620 *b++ = (unsigned char) (c2); \
1621 } while (0)
1624 /* Store a jump with opcode OP at LOC to location TO. We store a
1625 relative address offset by the three bytes the jump itself occupies. */
1626 #define STORE_JUMP(op, loc, to) \
1627 store_op1 (op, loc, (to) - (loc) - 3)
1629 /* Likewise, for a two-argument jump. */
1630 #define STORE_JUMP2(op, loc, to, arg) \
1631 store_op2 (op, loc, (to) - (loc) - 3, arg)
1633 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1634 #define INSERT_JUMP(op, loc, to) \
1635 insert_op1 (op, loc, (to) - (loc) - 3, b)
1637 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1638 #define INSERT_JUMP2(op, loc, to, arg) \
1639 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1642 /* This is not an arbitrary limit: the arguments which represent offsets
1643 into the pattern are two bytes long. So if 2^15 bytes turns out to
1644 be too small, many things would have to change. */
1645 # define MAX_BUF_SIZE (1L << 15)
1647 /* Extend the buffer by twice its current size via realloc and
1648 reset the pointers that pointed into the old block to point to the
1649 correct places in the new one. If extending the buffer results in it
1650 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1651 #define EXTEND_BUFFER() \
1652 do { \
1653 unsigned char *old_buffer = bufp->buffer; \
1654 if (bufp->allocated == MAX_BUF_SIZE) \
1655 return REG_ESIZE; \
1656 bufp->allocated <<= 1; \
1657 if (bufp->allocated > MAX_BUF_SIZE) \
1658 bufp->allocated = MAX_BUF_SIZE; \
1659 ptrdiff_t b_off = b - old_buffer; \
1660 ptrdiff_t begalt_off = begalt - old_buffer; \
1661 bool fixup_alt_jump_set = !!fixup_alt_jump; \
1662 bool laststart_set = !!laststart; \
1663 bool pending_exact_set = !!pending_exact; \
1664 ptrdiff_t fixup_alt_jump_off, laststart_off, pending_exact_off; \
1665 if (fixup_alt_jump_set) fixup_alt_jump_off = fixup_alt_jump - old_buffer; \
1666 if (laststart_set) laststart_off = laststart - old_buffer; \
1667 if (pending_exact_set) pending_exact_off = pending_exact - old_buffer; \
1668 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1669 if (bufp->buffer == NULL) \
1670 return REG_ESPACE; \
1671 unsigned char *new_buffer = bufp->buffer; \
1672 b = new_buffer + b_off; \
1673 begalt = new_buffer + begalt_off; \
1674 if (fixup_alt_jump_set) fixup_alt_jump = new_buffer + fixup_alt_jump_off; \
1675 if (laststart_set) laststart = new_buffer + laststart_off; \
1676 if (pending_exact_set) pending_exact = new_buffer + pending_exact_off; \
1677 } while (0)
1680 /* Since we have one byte reserved for the register number argument to
1681 {start,stop}_memory, the maximum number of groups we can report
1682 things about is what fits in that byte. */
1683 #define MAX_REGNUM 255
1685 /* But patterns can have more than `MAX_REGNUM' registers. We just
1686 ignore the excess. */
1687 typedef int regnum_t;
1690 /* Macros for the compile stack. */
1692 /* Since offsets can go either forwards or backwards, this type needs to
1693 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1694 /* int may be not enough when sizeof(int) == 2. */
1695 typedef long pattern_offset_t;
1697 typedef struct
1699 pattern_offset_t begalt_offset;
1700 pattern_offset_t fixup_alt_jump;
1701 pattern_offset_t laststart_offset;
1702 regnum_t regnum;
1703 } compile_stack_elt_t;
1706 typedef struct
1708 compile_stack_elt_t *stack;
1709 size_t size;
1710 size_t avail; /* Offset of next open position. */
1711 } compile_stack_type;
1714 #define INIT_COMPILE_STACK_SIZE 32
1716 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1717 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1719 /* The next available element. */
1720 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1722 /* Explicit quit checking is needed for Emacs, which uses polling to
1723 process input events. */
1724 #ifndef emacs
1725 static void maybe_quit (void) {}
1726 #endif
1728 /* Structure to manage work area for range table. */
1729 struct range_table_work_area
1731 int *table; /* actual work area. */
1732 int allocated; /* allocated size for work area in bytes. */
1733 int used; /* actually used size in words. */
1734 int bits; /* flag to record character classes */
1737 #ifdef emacs
1739 /* Make sure that WORK_AREA can hold more N multibyte characters.
1740 This is used only in set_image_of_range and set_image_of_range_1.
1741 It expects WORK_AREA to be a pointer.
1742 If it can't get the space, it returns from the surrounding function. */
1744 #define EXTEND_RANGE_TABLE(work_area, n) \
1745 do { \
1746 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1748 extend_range_table_work_area (&work_area); \
1749 if ((work_area).table == 0) \
1750 return (REG_ESPACE); \
1752 } while (0)
1754 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1755 (work_area).bits |= (bit)
1757 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1758 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1759 do { \
1760 EXTEND_RANGE_TABLE ((work_area), 2); \
1761 (work_area).table[(work_area).used++] = (range_start); \
1762 (work_area).table[(work_area).used++] = (range_end); \
1763 } while (0)
1765 #endif /* emacs */
1767 /* Free allocated memory for WORK_AREA. */
1768 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1769 do { \
1770 if ((work_area).table) \
1771 free ((work_area).table); \
1772 } while (0)
1774 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1775 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1776 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1777 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1779 /* Bits used to implement the multibyte-part of the various character classes
1780 such as [:alnum:] in a charset's range table. The code currently assumes
1781 that only the low 16 bits are used. */
1782 #define BIT_WORD 0x1
1783 #define BIT_LOWER 0x2
1784 #define BIT_PUNCT 0x4
1785 #define BIT_SPACE 0x8
1786 #define BIT_UPPER 0x10
1787 #define BIT_MULTIBYTE 0x20
1788 #define BIT_ALPHA 0x40
1789 #define BIT_ALNUM 0x80
1790 #define BIT_GRAPH 0x100
1791 #define BIT_PRINT 0x200
1792 #define BIT_BLANK 0x400
1795 /* Set the bit for character C in a list. */
1796 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1799 #ifdef emacs
1801 /* Store characters in the range FROM to TO in the bitmap at B (for
1802 ASCII and unibyte characters) and WORK_AREA (for multibyte
1803 characters) while translating them and paying attention to the
1804 continuity of translated characters.
1806 Implementation note: It is better to implement these fairly big
1807 macros by a function, but it's not that easy because macros called
1808 in this macro assume various local variables already declared. */
1810 /* Both FROM and TO are ASCII characters. */
1812 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1813 do { \
1814 int C0, C1; \
1816 for (C0 = (FROM); C0 <= (TO); C0++) \
1818 C1 = TRANSLATE (C0); \
1819 if (! ASCII_CHAR_P (C1)) \
1821 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1822 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1823 C1 = C0; \
1825 SET_LIST_BIT (C1); \
1827 } while (0)
1830 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1832 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1833 do { \
1834 int C0, C1, C2, I; \
1835 int USED = RANGE_TABLE_WORK_USED (work_area); \
1837 for (C0 = (FROM); C0 <= (TO); C0++) \
1839 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1840 if (CHAR_BYTE8_P (C1)) \
1841 SET_LIST_BIT (C0); \
1842 else \
1844 C2 = TRANSLATE (C1); \
1845 if (C2 == C1 \
1846 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1847 C1 = C0; \
1848 SET_LIST_BIT (C1); \
1849 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1851 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1852 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1854 if (C2 >= from - 1 && C2 <= to + 1) \
1856 if (C2 == from - 1) \
1857 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1858 else if (C2 == to + 1) \
1859 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1860 break; \
1863 if (I < USED) \
1864 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1867 } while (0)
1870 /* Both FROM and TO are multibyte characters. */
1872 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1873 do { \
1874 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1876 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1877 for (C0 = (FROM); C0 <= (TO); C0++) \
1879 C1 = TRANSLATE (C0); \
1880 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1881 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1882 SET_LIST_BIT (C2); \
1883 if (C1 >= (FROM) && C1 <= (TO)) \
1884 continue; \
1885 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1887 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1888 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1890 if (C1 >= from - 1 && C1 <= to + 1) \
1892 if (C1 == from - 1) \
1893 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1894 else if (C1 == to + 1) \
1895 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1896 break; \
1899 if (I < USED) \
1900 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1902 } while (0)
1904 #endif /* emacs */
1906 /* Get the next unsigned number in the uncompiled pattern. */
1907 #define GET_INTERVAL_COUNT(num) \
1908 do { \
1909 if (p == pend) \
1910 FREE_STACK_RETURN (REG_EBRACE); \
1911 else \
1913 PATFETCH (c); \
1914 while ('0' <= c && c <= '9') \
1916 if (num < 0) \
1917 num = 0; \
1918 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
1919 FREE_STACK_RETURN (REG_ESIZEBR); \
1920 num = num * 10 + c - '0'; \
1921 if (p == pend) \
1922 FREE_STACK_RETURN (REG_EBRACE); \
1923 PATFETCH (c); \
1926 } while (0)
1928 #if ! WIDE_CHAR_SUPPORT
1930 /* Parse a character class, i.e. string such as "[:name:]". *strp
1931 points to the string to be parsed and limit is length, in bytes, of
1932 that string.
1934 If *strp point to a string that begins with "[:name:]", where name is
1935 a non-empty sequence of lower case letters, *strp will be advanced past the
1936 closing square bracket and RECC_* constant which maps to the name will be
1937 returned. If name is not a valid character class name zero, or RECC_ERROR,
1938 is returned.
1940 Otherwise, if *strp doesn't begin with "[:name:]", -1 is returned.
1942 The function can be used on ASCII and multibyte (UTF-8-encoded) strings.
1944 re_wctype_t
1945 re_wctype_parse (const unsigned char **strp, unsigned limit)
1947 const char *beg = (const char *)*strp, *it;
1949 if (limit < 4 || beg[0] != '[' || beg[1] != ':')
1950 return -1;
1952 beg += 2; /* skip opening "[:" */
1953 limit -= 3; /* opening "[:" and half of closing ":]"; --limit handles rest */
1954 for (it = beg; it[0] != ':' || it[1] != ']'; ++it)
1955 if (!--limit)
1956 return -1;
1958 *strp = (const unsigned char *)(it + 2);
1960 /* Sort tests in the length=five case by frequency the classes to minimize
1961 number of times we fail the comparison. The frequencies of character class
1962 names used in Emacs sources as of 2016-07-27:
1964 $ find \( -name \*.c -o -name \*.el \) -exec grep -h '\[:[a-z]*:]' {} + |
1965 sed 's/]/]\n/g' |grep -o '\[:[a-z]*:]' |sort |uniq -c |sort -nr
1966 213 [:alnum:]
1967 104 [:alpha:]
1968 62 [:space:]
1969 39 [:digit:]
1970 36 [:blank:]
1971 26 [:word:]
1972 26 [:upper:]
1973 21 [:lower:]
1974 10 [:xdigit:]
1975 10 [:punct:]
1976 10 [:ascii:]
1977 4 [:nonascii:]
1978 4 [:graph:]
1979 2 [:print:]
1980 2 [:cntrl:]
1981 1 [:ff:]
1983 If you update this list, consider also updating chain of or'ed conditions
1984 in execute_charset function.
1987 switch (it - beg) {
1988 case 4:
1989 if (!memcmp (beg, "word", 4)) return RECC_WORD;
1990 break;
1991 case 5:
1992 if (!memcmp (beg, "alnum", 5)) return RECC_ALNUM;
1993 if (!memcmp (beg, "alpha", 5)) return RECC_ALPHA;
1994 if (!memcmp (beg, "space", 5)) return RECC_SPACE;
1995 if (!memcmp (beg, "digit", 5)) return RECC_DIGIT;
1996 if (!memcmp (beg, "blank", 5)) return RECC_BLANK;
1997 if (!memcmp (beg, "upper", 5)) return RECC_UPPER;
1998 if (!memcmp (beg, "lower", 5)) return RECC_LOWER;
1999 if (!memcmp (beg, "punct", 5)) return RECC_PUNCT;
2000 if (!memcmp (beg, "ascii", 5)) return RECC_ASCII;
2001 if (!memcmp (beg, "graph", 5)) return RECC_GRAPH;
2002 if (!memcmp (beg, "print", 5)) return RECC_PRINT;
2003 if (!memcmp (beg, "cntrl", 5)) return RECC_CNTRL;
2004 break;
2005 case 6:
2006 if (!memcmp (beg, "xdigit", 6)) return RECC_XDIGIT;
2007 break;
2008 case 7:
2009 if (!memcmp (beg, "unibyte", 7)) return RECC_UNIBYTE;
2010 break;
2011 case 8:
2012 if (!memcmp (beg, "nonascii", 8)) return RECC_NONASCII;
2013 break;
2014 case 9:
2015 if (!memcmp (beg, "multibyte", 9)) return RECC_MULTIBYTE;
2016 break;
2019 return RECC_ERROR;
2022 /* True if CH is in the char class CC. */
2023 boolean
2024 re_iswctype (int ch, re_wctype_t cc)
2026 switch (cc)
2028 case RECC_ALNUM: return ISALNUM (ch) != 0;
2029 case RECC_ALPHA: return ISALPHA (ch) != 0;
2030 case RECC_BLANK: return ISBLANK (ch) != 0;
2031 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2032 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2033 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2034 case RECC_LOWER: return ISLOWER (ch) != 0;
2035 case RECC_PRINT: return ISPRINT (ch) != 0;
2036 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2037 case RECC_SPACE: return ISSPACE (ch) != 0;
2038 case RECC_UPPER: return ISUPPER (ch) != 0;
2039 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2040 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2041 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2042 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2043 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2044 case RECC_WORD: return ISWORD (ch) != 0;
2045 case RECC_ERROR: return false;
2046 default:
2047 abort ();
2051 /* Return a bit-pattern to use in the range-table bits to match multibyte
2052 chars of class CC. */
2053 static int
2054 re_wctype_to_bit (re_wctype_t cc)
2056 switch (cc)
2058 case RECC_NONASCII:
2059 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2060 case RECC_ALPHA: return BIT_ALPHA;
2061 case RECC_ALNUM: return BIT_ALNUM;
2062 case RECC_WORD: return BIT_WORD;
2063 case RECC_LOWER: return BIT_LOWER;
2064 case RECC_UPPER: return BIT_UPPER;
2065 case RECC_PUNCT: return BIT_PUNCT;
2066 case RECC_SPACE: return BIT_SPACE;
2067 case RECC_GRAPH: return BIT_GRAPH;
2068 case RECC_PRINT: return BIT_PRINT;
2069 case RECC_BLANK: return BIT_BLANK;
2070 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2071 case RECC_UNIBYTE: case RECC_ERROR: return 0;
2072 default:
2073 abort ();
2076 #endif
2078 /* Filling in the work area of a range. */
2080 /* Actually extend the space in WORK_AREA. */
2082 static void
2083 extend_range_table_work_area (struct range_table_work_area *work_area)
2085 work_area->allocated += 16 * sizeof (int);
2086 work_area->table = realloc (work_area->table, work_area->allocated);
2089 #if 0
2090 #ifdef emacs
2092 /* Carefully find the ranges of codes that are equivalent
2093 under case conversion to the range start..end when passed through
2094 TRANSLATE. Handle the case where non-letters can come in between
2095 two upper-case letters (which happens in Latin-1).
2096 Also handle the case of groups of more than 2 case-equivalent chars.
2098 The basic method is to look at consecutive characters and see
2099 if they can form a run that can be handled as one.
2101 Returns -1 if successful, REG_ESPACE if ran out of space. */
2103 static int
2104 set_image_of_range_1 (struct range_table_work_area *work_area,
2105 re_wchar_t start, re_wchar_t end,
2106 RE_TRANSLATE_TYPE translate)
2108 /* `one_case' indicates a character, or a run of characters,
2109 each of which is an isolate (no case-equivalents).
2110 This includes all ASCII non-letters.
2112 `two_case' indicates a character, or a run of characters,
2113 each of which has two case-equivalent forms.
2114 This includes all ASCII letters.
2116 `strange' indicates a character that has more than one
2117 case-equivalent. */
2119 enum case_type {one_case, two_case, strange};
2121 /* Describe the run that is in progress,
2122 which the next character can try to extend.
2123 If run_type is strange, that means there really is no run.
2124 If run_type is one_case, then run_start...run_end is the run.
2125 If run_type is two_case, then the run is run_start...run_end,
2126 and the case-equivalents end at run_eqv_end. */
2128 enum case_type run_type = strange;
2129 int run_start, run_end, run_eqv_end;
2131 Lisp_Object eqv_table;
2133 if (!RE_TRANSLATE_P (translate))
2135 EXTEND_RANGE_TABLE (work_area, 2);
2136 work_area->table[work_area->used++] = (start);
2137 work_area->table[work_area->used++] = (end);
2138 return -1;
2141 eqv_table = XCHAR_TABLE (translate)->extras[2];
2143 for (; start <= end; start++)
2145 enum case_type this_type;
2146 int eqv = RE_TRANSLATE (eqv_table, start);
2147 int minchar, maxchar;
2149 /* Classify this character */
2150 if (eqv == start)
2151 this_type = one_case;
2152 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2153 this_type = two_case;
2154 else
2155 this_type = strange;
2157 if (start < eqv)
2158 minchar = start, maxchar = eqv;
2159 else
2160 minchar = eqv, maxchar = start;
2162 /* Can this character extend the run in progress? */
2163 if (this_type == strange || this_type != run_type
2164 || !(minchar == run_end + 1
2165 && (run_type == two_case
2166 ? maxchar == run_eqv_end + 1 : 1)))
2168 /* No, end the run.
2169 Record each of its equivalent ranges. */
2170 if (run_type == one_case)
2172 EXTEND_RANGE_TABLE (work_area, 2);
2173 work_area->table[work_area->used++] = run_start;
2174 work_area->table[work_area->used++] = run_end;
2176 else if (run_type == two_case)
2178 EXTEND_RANGE_TABLE (work_area, 4);
2179 work_area->table[work_area->used++] = run_start;
2180 work_area->table[work_area->used++] = run_end;
2181 work_area->table[work_area->used++]
2182 = RE_TRANSLATE (eqv_table, run_start);
2183 work_area->table[work_area->used++]
2184 = RE_TRANSLATE (eqv_table, run_end);
2186 run_type = strange;
2189 if (this_type == strange)
2191 /* For a strange character, add each of its equivalents, one
2192 by one. Don't start a range. */
2195 EXTEND_RANGE_TABLE (work_area, 2);
2196 work_area->table[work_area->used++] = eqv;
2197 work_area->table[work_area->used++] = eqv;
2198 eqv = RE_TRANSLATE (eqv_table, eqv);
2200 while (eqv != start);
2203 /* Add this char to the run, or start a new run. */
2204 else if (run_type == strange)
2206 /* Initialize a new range. */
2207 run_type = this_type;
2208 run_start = start;
2209 run_end = start;
2210 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2212 else
2214 /* Extend a running range. */
2215 run_end = minchar;
2216 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2220 /* If a run is still in progress at the end, finish it now
2221 by recording its equivalent ranges. */
2222 if (run_type == one_case)
2224 EXTEND_RANGE_TABLE (work_area, 2);
2225 work_area->table[work_area->used++] = run_start;
2226 work_area->table[work_area->used++] = run_end;
2228 else if (run_type == two_case)
2230 EXTEND_RANGE_TABLE (work_area, 4);
2231 work_area->table[work_area->used++] = run_start;
2232 work_area->table[work_area->used++] = run_end;
2233 work_area->table[work_area->used++]
2234 = RE_TRANSLATE (eqv_table, run_start);
2235 work_area->table[work_area->used++]
2236 = RE_TRANSLATE (eqv_table, run_end);
2239 return -1;
2242 #endif /* emacs */
2244 /* Record the image of the range start..end when passed through
2245 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2246 and is not even necessarily contiguous.
2247 Normally we approximate it with the smallest contiguous range that contains
2248 all the chars we need. However, for Latin-1 we go to extra effort
2249 to do a better job.
2251 This function is not called for ASCII ranges.
2253 Returns -1 if successful, REG_ESPACE if ran out of space. */
2255 static int
2256 set_image_of_range (struct range_table_work_area *work_area,
2257 re_wchar_t start, re_wchar_t end,
2258 RE_TRANSLATE_TYPE translate)
2260 re_wchar_t cmin, cmax;
2262 #ifdef emacs
2263 /* For Latin-1 ranges, use set_image_of_range_1
2264 to get proper handling of ranges that include letters and nonletters.
2265 For a range that includes the whole of Latin-1, this is not necessary.
2266 For other character sets, we don't bother to get this right. */
2267 if (RE_TRANSLATE_P (translate) && start < 04400
2268 && !(start < 04200 && end >= 04377))
2270 int newend;
2271 int tem;
2272 newend = end;
2273 if (newend > 04377)
2274 newend = 04377;
2275 tem = set_image_of_range_1 (work_area, start, newend, translate);
2276 if (tem > 0)
2277 return tem;
2279 start = 04400;
2280 if (end < 04400)
2281 return -1;
2283 #endif
2285 EXTEND_RANGE_TABLE (work_area, 2);
2286 work_area->table[work_area->used++] = (start);
2287 work_area->table[work_area->used++] = (end);
2289 cmin = -1, cmax = -1;
2291 if (RE_TRANSLATE_P (translate))
2293 int ch;
2295 for (ch = start; ch <= end; ch++)
2297 re_wchar_t c = TRANSLATE (ch);
2298 if (! (start <= c && c <= end))
2300 if (cmin == -1)
2301 cmin = c, cmax = c;
2302 else
2304 cmin = min (cmin, c);
2305 cmax = max (cmax, c);
2310 if (cmin != -1)
2312 EXTEND_RANGE_TABLE (work_area, 2);
2313 work_area->table[work_area->used++] = (cmin);
2314 work_area->table[work_area->used++] = (cmax);
2318 return -1;
2320 #endif /* 0 */
2322 #ifndef MATCH_MAY_ALLOCATE
2324 /* If we cannot allocate large objects within re_match_2_internal,
2325 we make the fail stack and register vectors global.
2326 The fail stack, we grow to the maximum size when a regexp
2327 is compiled.
2328 The register vectors, we adjust in size each time we
2329 compile a regexp, according to the number of registers it needs. */
2331 static fail_stack_type fail_stack;
2333 /* Size with which the following vectors are currently allocated.
2334 That is so we can make them bigger as needed,
2335 but never make them smaller. */
2336 static int regs_allocated_size;
2338 static re_char ** regstart, ** regend;
2339 static re_char **best_regstart, **best_regend;
2341 /* Make the register vectors big enough for NUM_REGS registers,
2342 but don't make them smaller. */
2344 static
2345 regex_grow_registers (int num_regs)
2347 if (num_regs > regs_allocated_size)
2349 RETALLOC_IF (regstart, num_regs, re_char *);
2350 RETALLOC_IF (regend, num_regs, re_char *);
2351 RETALLOC_IF (best_regstart, num_regs, re_char *);
2352 RETALLOC_IF (best_regend, num_regs, re_char *);
2354 regs_allocated_size = num_regs;
2358 #endif /* not MATCH_MAY_ALLOCATE */
2360 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2361 regnum_t regnum);
2363 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2364 Returns one of error codes defined in `regex.h', or zero for success.
2366 If WHITESPACE_REGEXP is given (only #ifdef emacs), it is used instead of
2367 a space character in PATTERN.
2369 Assumes the `allocated' (and perhaps `buffer') and `translate'
2370 fields are set in BUFP on entry.
2372 If it succeeds, results are put in BUFP (if it returns an error, the
2373 contents of BUFP are undefined):
2374 `buffer' is the compiled pattern;
2375 `syntax' is set to SYNTAX;
2376 `used' is set to the length of the compiled pattern;
2377 `fastmap_accurate' is zero;
2378 `re_nsub' is the number of subexpressions in PATTERN;
2379 `not_bol' and `not_eol' are zero;
2381 The `fastmap' field is neither examined nor set. */
2383 /* Insert the `jump' from the end of last alternative to "here".
2384 The space for the jump has already been allocated. */
2385 #define FIXUP_ALT_JUMP() \
2386 do { \
2387 if (fixup_alt_jump) \
2388 STORE_JUMP (jump, fixup_alt_jump, b); \
2389 } while (0)
2392 /* Return, freeing storage we allocated. */
2393 #define FREE_STACK_RETURN(value) \
2394 do { \
2395 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2396 free (compile_stack.stack); \
2397 return value; \
2398 } while (0)
2400 static reg_errcode_t
2401 regex_compile (re_char *pattern, size_t size,
2402 #ifdef emacs
2403 # define syntax RE_SYNTAX_EMACS
2404 bool posix_backtracking,
2405 const char *whitespace_regexp,
2406 #else
2407 reg_syntax_t syntax,
2408 # define posix_backtracking (!(syntax & RE_NO_POSIX_BACKTRACKING))
2409 #endif
2410 struct re_pattern_buffer *bufp)
2412 /* We fetch characters from PATTERN here. */
2413 register re_wchar_t c, c1;
2415 /* Points to the end of the buffer, where we should append. */
2416 register unsigned char *b;
2418 /* Keeps track of unclosed groups. */
2419 compile_stack_type compile_stack;
2421 /* Points to the current (ending) position in the pattern. */
2422 #ifdef AIX
2423 /* `const' makes AIX compiler fail. */
2424 unsigned char *p = pattern;
2425 #else
2426 re_char *p = pattern;
2427 #endif
2428 re_char *pend = pattern + size;
2430 /* How to translate the characters in the pattern. */
2431 RE_TRANSLATE_TYPE translate = bufp->translate;
2433 /* Address of the count-byte of the most recently inserted `exactn'
2434 command. This makes it possible to tell if a new exact-match
2435 character can be added to that command or if the character requires
2436 a new `exactn' command. */
2437 unsigned char *pending_exact = 0;
2439 /* Address of start of the most recently finished expression.
2440 This tells, e.g., postfix * where to find the start of its
2441 operand. Reset at the beginning of groups and alternatives. */
2442 unsigned char *laststart = 0;
2444 /* Address of beginning of regexp, or inside of last group. */
2445 unsigned char *begalt;
2447 /* Place in the uncompiled pattern (i.e., the {) to
2448 which to go back if the interval is invalid. */
2449 re_char *beg_interval;
2451 /* Address of the place where a forward jump should go to the end of
2452 the containing expression. Each alternative of an `or' -- except the
2453 last -- ends with a forward jump of this sort. */
2454 unsigned char *fixup_alt_jump = 0;
2456 /* Work area for range table of charset. */
2457 struct range_table_work_area range_table_work;
2459 /* If the object matched can contain multibyte characters. */
2460 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2462 #ifdef emacs
2463 /* Nonzero if we have pushed down into a subpattern. */
2464 int in_subpattern = 0;
2466 /* These hold the values of p, pattern, and pend from the main
2467 pattern when we have pushed into a subpattern. */
2468 re_char *main_p;
2469 re_char *main_pattern;
2470 re_char *main_pend;
2471 #endif
2473 #ifdef DEBUG
2474 debug++;
2475 DEBUG_PRINT ("\nCompiling pattern: ");
2476 if (debug > 0)
2478 unsigned debug_count;
2480 for (debug_count = 0; debug_count < size; debug_count++)
2481 putchar (pattern[debug_count]);
2482 putchar ('\n');
2484 #endif /* DEBUG */
2486 /* Initialize the compile stack. */
2487 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2488 if (compile_stack.stack == NULL)
2489 return REG_ESPACE;
2491 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2492 compile_stack.avail = 0;
2494 range_table_work.table = 0;
2495 range_table_work.allocated = 0;
2497 /* Initialize the pattern buffer. */
2498 #ifndef emacs
2499 bufp->syntax = syntax;
2500 #endif
2501 bufp->fastmap_accurate = 0;
2502 bufp->not_bol = bufp->not_eol = 0;
2503 bufp->used_syntax = 0;
2505 /* Set `used' to zero, so that if we return an error, the pattern
2506 printer (for debugging) will think there's no pattern. We reset it
2507 at the end. */
2508 bufp->used = 0;
2510 /* Always count groups, whether or not bufp->no_sub is set. */
2511 bufp->re_nsub = 0;
2513 #if !defined emacs && !defined SYNTAX_TABLE
2514 /* Initialize the syntax table. */
2515 init_syntax_once ();
2516 #endif
2518 if (bufp->allocated == 0)
2520 if (bufp->buffer)
2521 { /* If zero allocated, but buffer is non-null, try to realloc
2522 enough space. This loses if buffer's address is bogus, but
2523 that is the user's responsibility. */
2524 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2526 else
2527 { /* Caller did not allocate a buffer. Do it for them. */
2528 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2530 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2532 bufp->allocated = INIT_BUF_SIZE;
2535 begalt = b = bufp->buffer;
2537 /* Loop through the uncompiled pattern until we're at the end. */
2538 while (1)
2540 if (p == pend)
2542 #ifdef emacs
2543 /* If this is the end of an included regexp,
2544 pop back to the main regexp and try again. */
2545 if (in_subpattern)
2547 in_subpattern = 0;
2548 pattern = main_pattern;
2549 p = main_p;
2550 pend = main_pend;
2551 continue;
2553 #endif
2554 /* If this is the end of the main regexp, we are done. */
2555 break;
2558 PATFETCH (c);
2560 switch (c)
2562 #ifdef emacs
2563 case ' ':
2565 re_char *p1 = p;
2567 /* If there's no special whitespace regexp, treat
2568 spaces normally. And don't try to do this recursively. */
2569 if (!whitespace_regexp || in_subpattern)
2570 goto normal_char;
2572 /* Peek past following spaces. */
2573 while (p1 != pend)
2575 if (*p1 != ' ')
2576 break;
2577 p1++;
2579 /* If the spaces are followed by a repetition op,
2580 treat them normally. */
2581 if (p1 != pend
2582 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2583 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2584 goto normal_char;
2586 /* Replace the spaces with the whitespace regexp. */
2587 in_subpattern = 1;
2588 main_p = p1;
2589 main_pend = pend;
2590 main_pattern = pattern;
2591 p = pattern = (re_char *) whitespace_regexp;
2592 pend = p + strlen (whitespace_regexp);
2593 break;
2595 #endif
2597 case '^':
2599 if ( /* If at start of pattern, it's an operator. */
2600 p == pattern + 1
2601 /* If context independent, it's an operator. */
2602 || syntax & RE_CONTEXT_INDEP_ANCHORS
2603 /* Otherwise, depends on what's come before. */
2604 || at_begline_loc_p (pattern, p, syntax))
2605 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2606 else
2607 goto normal_char;
2609 break;
2612 case '$':
2614 if ( /* If at end of pattern, it's an operator. */
2615 p == pend
2616 /* If context independent, it's an operator. */
2617 || syntax & RE_CONTEXT_INDEP_ANCHORS
2618 /* Otherwise, depends on what's next. */
2619 || at_endline_loc_p (p, pend, syntax))
2620 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2621 else
2622 goto normal_char;
2624 break;
2627 case '+':
2628 case '?':
2629 if ((syntax & RE_BK_PLUS_QM)
2630 || (syntax & RE_LIMITED_OPS))
2631 goto normal_char;
2632 FALLTHROUGH;
2633 case '*':
2634 handle_plus:
2635 /* If there is no previous pattern... */
2636 if (!laststart)
2638 if (syntax & RE_CONTEXT_INVALID_OPS)
2639 FREE_STACK_RETURN (REG_BADRPT);
2640 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2641 goto normal_char;
2645 /* 1 means zero (many) matches is allowed. */
2646 boolean zero_times_ok = 0, many_times_ok = 0;
2647 boolean greedy = 1;
2649 /* If there is a sequence of repetition chars, collapse it
2650 down to just one (the right one). We can't combine
2651 interval operators with these because of, e.g., `a{2}*',
2652 which should only match an even number of `a's. */
2654 for (;;)
2656 if ((syntax & RE_FRUGAL)
2657 && c == '?' && (zero_times_ok || many_times_ok))
2658 greedy = 0;
2659 else
2661 zero_times_ok |= c != '+';
2662 many_times_ok |= c != '?';
2665 if (p == pend)
2666 break;
2667 else if (*p == '*'
2668 || (!(syntax & RE_BK_PLUS_QM)
2669 && (*p == '+' || *p == '?')))
2671 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2673 if (p+1 == pend)
2674 FREE_STACK_RETURN (REG_EESCAPE);
2675 if (p[1] == '+' || p[1] == '?')
2676 PATFETCH (c); /* Gobble up the backslash. */
2677 else
2678 break;
2680 else
2681 break;
2682 /* If we get here, we found another repeat character. */
2683 PATFETCH (c);
2686 /* Star, etc. applied to an empty pattern is equivalent
2687 to an empty pattern. */
2688 if (!laststart || laststart == b)
2689 break;
2691 /* Now we know whether or not zero matches is allowed
2692 and also whether or not two or more matches is allowed. */
2693 if (greedy)
2695 if (many_times_ok)
2697 boolean simple = skip_one_char (laststart) == b;
2698 size_t startoffset = 0;
2699 re_opcode_t ofj =
2700 /* Check if the loop can match the empty string. */
2701 (simple || !analyze_first (laststart, b, NULL, 0))
2702 ? on_failure_jump : on_failure_jump_loop;
2703 assert (skip_one_char (laststart) <= b);
2705 if (!zero_times_ok && simple)
2706 { /* Since simple * loops can be made faster by using
2707 on_failure_keep_string_jump, we turn simple P+
2708 into PP* if P is simple. */
2709 unsigned char *p1, *p2;
2710 startoffset = b - laststart;
2711 GET_BUFFER_SPACE (startoffset);
2712 p1 = b; p2 = laststart;
2713 while (p2 < p1)
2714 *b++ = *p2++;
2715 zero_times_ok = 1;
2718 GET_BUFFER_SPACE (6);
2719 if (!zero_times_ok)
2720 /* A + loop. */
2721 STORE_JUMP (ofj, b, b + 6);
2722 else
2723 /* Simple * loops can use on_failure_keep_string_jump
2724 depending on what follows. But since we don't know
2725 that yet, we leave the decision up to
2726 on_failure_jump_smart. */
2727 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2728 laststart + startoffset, b + 6);
2729 b += 3;
2730 STORE_JUMP (jump, b, laststart + startoffset);
2731 b += 3;
2733 else
2735 /* A simple ? pattern. */
2736 assert (zero_times_ok);
2737 GET_BUFFER_SPACE (3);
2738 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2739 b += 3;
2742 else /* not greedy */
2743 { /* I wish the greedy and non-greedy cases could be merged. */
2745 GET_BUFFER_SPACE (7); /* We might use less. */
2746 if (many_times_ok)
2748 boolean emptyp = analyze_first (laststart, b, NULL, 0);
2750 /* The non-greedy multiple match looks like
2751 a repeat..until: we only need a conditional jump
2752 at the end of the loop. */
2753 if (emptyp) BUF_PUSH (no_op);
2754 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2755 : on_failure_jump, b, laststart);
2756 b += 3;
2757 if (zero_times_ok)
2759 /* The repeat...until naturally matches one or more.
2760 To also match zero times, we need to first jump to
2761 the end of the loop (its conditional jump). */
2762 INSERT_JUMP (jump, laststart, b);
2763 b += 3;
2766 else
2768 /* non-greedy a?? */
2769 INSERT_JUMP (jump, laststart, b + 3);
2770 b += 3;
2771 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2772 b += 3;
2776 pending_exact = 0;
2777 break;
2780 case '.':
2781 laststart = b;
2782 BUF_PUSH (anychar);
2783 break;
2786 case '[':
2788 re_char *p1;
2790 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2792 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2794 /* Ensure that we have enough space to push a charset: the
2795 opcode, the length count, and the bitset; 34 bytes in all. */
2796 GET_BUFFER_SPACE (34);
2798 laststart = b;
2800 /* We test `*p == '^' twice, instead of using an if
2801 statement, so we only need one BUF_PUSH. */
2802 BUF_PUSH (*p == '^' ? charset_not : charset);
2803 if (*p == '^')
2804 p++;
2806 /* Remember the first position in the bracket expression. */
2807 p1 = p;
2809 /* Push the number of bytes in the bitmap. */
2810 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2812 /* Clear the whole map. */
2813 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2815 /* charset_not matches newline according to a syntax bit. */
2816 if ((re_opcode_t) b[-2] == charset_not
2817 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2818 SET_LIST_BIT ('\n');
2820 /* Read in characters and ranges, setting map bits. */
2821 for (;;)
2823 boolean escaped_char = false;
2824 const unsigned char *p2 = p;
2825 re_wctype_t cc;
2826 re_wchar_t ch;
2828 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2830 /* See if we're at the beginning of a possible character
2831 class. */
2832 if (syntax & RE_CHAR_CLASSES &&
2833 (cc = re_wctype_parse(&p, pend - p)) != -1)
2835 if (cc == 0)
2836 FREE_STACK_RETURN (REG_ECTYPE);
2838 if (p == pend)
2839 FREE_STACK_RETURN (REG_EBRACK);
2841 #ifndef emacs
2842 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2843 if (re_iswctype (btowc (ch), cc))
2845 c = TRANSLATE (ch);
2846 if (c < (1 << BYTEWIDTH))
2847 SET_LIST_BIT (c);
2849 #else /* emacs */
2850 /* Most character classes in a multibyte match just set
2851 a flag. Exceptions are is_blank, is_digit, is_cntrl, and
2852 is_xdigit, since they can only match ASCII characters.
2853 We don't need to handle them for multibyte. */
2855 /* Setup the gl_state object to its buffer-defined value.
2856 This hardcodes the buffer-global syntax-table for ASCII
2857 chars, while the other chars will obey syntax-table
2858 properties. It's not ideal, but it's the way it's been
2859 done until now. */
2860 SETUP_BUFFER_SYNTAX_TABLE ();
2862 for (c = 0; c < 0x80; ++c)
2863 if (re_iswctype (c, cc))
2865 SET_LIST_BIT (c);
2866 c1 = TRANSLATE (c);
2867 if (c1 == c)
2868 continue;
2869 if (ASCII_CHAR_P (c1))
2870 SET_LIST_BIT (c1);
2871 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2872 SET_LIST_BIT (c1);
2874 SET_RANGE_TABLE_WORK_AREA_BIT
2875 (range_table_work, re_wctype_to_bit (cc));
2876 #endif /* emacs */
2877 /* In most cases the matching rule for char classes only
2878 uses the syntax table for multibyte chars, so that the
2879 content of the syntax-table is not hardcoded in the
2880 range_table. SPACE and WORD are the two exceptions. */
2881 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2882 bufp->used_syntax = 1;
2884 /* Repeat the loop. */
2885 continue;
2888 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2889 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2890 So the translation is done later in a loop. Example:
2891 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2892 PATFETCH (c);
2894 /* \ might escape characters inside [...] and [^...]. */
2895 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2897 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2899 PATFETCH (c);
2900 escaped_char = true;
2902 else
2904 /* Could be the end of the bracket expression. If it's
2905 not (i.e., when the bracket expression is `[]' so
2906 far), the ']' character bit gets set way below. */
2907 if (c == ']' && p2 != p1)
2908 break;
2911 if (p < pend && p[0] == '-' && p[1] != ']')
2914 /* Discard the `-'. */
2915 PATFETCH (c1);
2917 /* Fetch the character which ends the range. */
2918 PATFETCH (c1);
2919 #ifdef emacs
2920 if (CHAR_BYTE8_P (c1)
2921 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2922 /* Treat the range from a multibyte character to
2923 raw-byte character as empty. */
2924 c = c1 + 1;
2925 #endif /* emacs */
2927 else
2928 /* Range from C to C. */
2929 c1 = c;
2931 if (c > c1)
2933 if (syntax & RE_NO_EMPTY_RANGES)
2934 FREE_STACK_RETURN (REG_ERANGEX);
2935 /* Else, repeat the loop. */
2937 else
2939 #ifndef emacs
2940 /* Set the range into bitmap */
2941 for (; c <= c1; c++)
2943 ch = TRANSLATE (c);
2944 if (ch < (1 << BYTEWIDTH))
2945 SET_LIST_BIT (ch);
2947 #else /* emacs */
2948 if (c < 128)
2950 ch = min (127, c1);
2951 SETUP_ASCII_RANGE (range_table_work, c, ch);
2952 c = ch + 1;
2953 if (CHAR_BYTE8_P (c1))
2954 c = BYTE8_TO_CHAR (128);
2956 if (c <= c1)
2958 if (CHAR_BYTE8_P (c))
2960 c = CHAR_TO_BYTE8 (c);
2961 c1 = CHAR_TO_BYTE8 (c1);
2962 for (; c <= c1; c++)
2963 SET_LIST_BIT (c);
2965 else if (multibyte)
2967 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
2969 else
2971 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
2974 #endif /* emacs */
2978 /* Discard any (non)matching list bytes that are all 0 at the
2979 end of the map. Decrease the map-length byte too. */
2980 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2981 b[-1]--;
2982 b += b[-1];
2984 /* Build real range table from work area. */
2985 if (RANGE_TABLE_WORK_USED (range_table_work)
2986 || RANGE_TABLE_WORK_BITS (range_table_work))
2988 int i;
2989 int used = RANGE_TABLE_WORK_USED (range_table_work);
2991 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2992 bytes for flags, two for COUNT, and three bytes for
2993 each character. */
2994 GET_BUFFER_SPACE (4 + used * 3);
2996 /* Indicate the existence of range table. */
2997 laststart[1] |= 0x80;
2999 /* Store the character class flag bits into the range table.
3000 If not in emacs, these flag bits are always 0. */
3001 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3002 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3004 STORE_NUMBER_AND_INCR (b, used / 2);
3005 for (i = 0; i < used; i++)
3006 STORE_CHARACTER_AND_INCR
3007 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3010 break;
3013 case '(':
3014 if (syntax & RE_NO_BK_PARENS)
3015 goto handle_open;
3016 else
3017 goto normal_char;
3020 case ')':
3021 if (syntax & RE_NO_BK_PARENS)
3022 goto handle_close;
3023 else
3024 goto normal_char;
3027 case '\n':
3028 if (syntax & RE_NEWLINE_ALT)
3029 goto handle_alt;
3030 else
3031 goto normal_char;
3034 case '|':
3035 if (syntax & RE_NO_BK_VBAR)
3036 goto handle_alt;
3037 else
3038 goto normal_char;
3041 case '{':
3042 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3043 goto handle_interval;
3044 else
3045 goto normal_char;
3048 case '\\':
3049 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3051 /* Do not translate the character after the \, so that we can
3052 distinguish, e.g., \B from \b, even if we normally would
3053 translate, e.g., B to b. */
3054 PATFETCH (c);
3056 switch (c)
3058 case '(':
3059 if (syntax & RE_NO_BK_PARENS)
3060 goto normal_backslash;
3062 handle_open:
3064 int shy = 0;
3065 regnum_t regnum = 0;
3066 if (p+1 < pend)
3068 /* Look for a special (?...) construct */
3069 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3071 PATFETCH (c); /* Gobble up the '?'. */
3072 while (!shy)
3074 PATFETCH (c);
3075 switch (c)
3077 case ':': shy = 1; break;
3078 case '0':
3079 /* An explicitly specified regnum must start
3080 with non-0. */
3081 if (regnum == 0)
3082 FREE_STACK_RETURN (REG_BADPAT);
3083 FALLTHROUGH;
3084 case '1': case '2': case '3': case '4':
3085 case '5': case '6': case '7': case '8': case '9':
3086 regnum = 10*regnum + (c - '0'); break;
3087 default:
3088 /* Only (?:...) is supported right now. */
3089 FREE_STACK_RETURN (REG_BADPAT);
3095 if (!shy)
3096 regnum = ++bufp->re_nsub;
3097 else if (regnum)
3098 { /* It's actually not shy, but explicitly numbered. */
3099 shy = 0;
3100 if (regnum > bufp->re_nsub)
3101 bufp->re_nsub = regnum;
3102 else if (regnum > bufp->re_nsub
3103 /* Ideally, we'd want to check that the specified
3104 group can't have matched (i.e. all subgroups
3105 using the same regnum are in other branches of
3106 OR patterns), but we don't currently keep track
3107 of enough info to do that easily. */
3108 || group_in_compile_stack (compile_stack, regnum))
3109 FREE_STACK_RETURN (REG_BADPAT);
3111 else
3112 /* It's really shy. */
3113 regnum = - bufp->re_nsub;
3115 if (COMPILE_STACK_FULL)
3117 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3118 compile_stack_elt_t);
3119 if (compile_stack.stack == NULL) return REG_ESPACE;
3121 compile_stack.size <<= 1;
3124 /* These are the values to restore when we hit end of this
3125 group. They are all relative offsets, so that if the
3126 whole pattern moves because of realloc, they will still
3127 be valid. */
3128 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3129 COMPILE_STACK_TOP.fixup_alt_jump
3130 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3131 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3132 COMPILE_STACK_TOP.regnum = regnum;
3134 /* Do not push a start_memory for groups beyond the last one
3135 we can represent in the compiled pattern. */
3136 if (regnum <= MAX_REGNUM && regnum > 0)
3137 BUF_PUSH_2 (start_memory, regnum);
3139 compile_stack.avail++;
3141 fixup_alt_jump = 0;
3142 laststart = 0;
3143 begalt = b;
3144 /* If we've reached MAX_REGNUM groups, then this open
3145 won't actually generate any code, so we'll have to
3146 clear pending_exact explicitly. */
3147 pending_exact = 0;
3148 break;
3151 case ')':
3152 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3154 if (COMPILE_STACK_EMPTY)
3156 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3157 goto normal_backslash;
3158 else
3159 FREE_STACK_RETURN (REG_ERPAREN);
3162 handle_close:
3163 FIXUP_ALT_JUMP ();
3165 /* See similar code for backslashed left paren above. */
3166 if (COMPILE_STACK_EMPTY)
3168 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3169 goto normal_char;
3170 else
3171 FREE_STACK_RETURN (REG_ERPAREN);
3174 /* Since we just checked for an empty stack above, this
3175 ``can't happen''. */
3176 assert (compile_stack.avail != 0);
3178 /* We don't just want to restore into `regnum', because
3179 later groups should continue to be numbered higher,
3180 as in `(ab)c(de)' -- the second group is #2. */
3181 regnum_t regnum;
3183 compile_stack.avail--;
3184 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3185 fixup_alt_jump
3186 = COMPILE_STACK_TOP.fixup_alt_jump
3187 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3188 : 0;
3189 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3190 regnum = COMPILE_STACK_TOP.regnum;
3191 /* If we've reached MAX_REGNUM groups, then this open
3192 won't actually generate any code, so we'll have to
3193 clear pending_exact explicitly. */
3194 pending_exact = 0;
3196 /* We're at the end of the group, so now we know how many
3197 groups were inside this one. */
3198 if (regnum <= MAX_REGNUM && regnum > 0)
3199 BUF_PUSH_2 (stop_memory, regnum);
3201 break;
3204 case '|': /* `\|'. */
3205 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3206 goto normal_backslash;
3207 handle_alt:
3208 if (syntax & RE_LIMITED_OPS)
3209 goto normal_char;
3211 /* Insert before the previous alternative a jump which
3212 jumps to this alternative if the former fails. */
3213 GET_BUFFER_SPACE (3);
3214 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3215 pending_exact = 0;
3216 b += 3;
3218 /* The alternative before this one has a jump after it
3219 which gets executed if it gets matched. Adjust that
3220 jump so it will jump to this alternative's analogous
3221 jump (put in below, which in turn will jump to the next
3222 (if any) alternative's such jump, etc.). The last such
3223 jump jumps to the correct final destination. A picture:
3224 _____ _____
3225 | | | |
3226 | v | v
3227 a | b | c
3229 If we are at `b', then fixup_alt_jump right now points to a
3230 three-byte space after `a'. We'll put in the jump, set
3231 fixup_alt_jump to right after `b', and leave behind three
3232 bytes which we'll fill in when we get to after `c'. */
3234 FIXUP_ALT_JUMP ();
3236 /* Mark and leave space for a jump after this alternative,
3237 to be filled in later either by next alternative or
3238 when know we're at the end of a series of alternatives. */
3239 fixup_alt_jump = b;
3240 GET_BUFFER_SPACE (3);
3241 b += 3;
3243 laststart = 0;
3244 begalt = b;
3245 break;
3248 case '{':
3249 /* If \{ is a literal. */
3250 if (!(syntax & RE_INTERVALS)
3251 /* If we're at `\{' and it's not the open-interval
3252 operator. */
3253 || (syntax & RE_NO_BK_BRACES))
3254 goto normal_backslash;
3256 handle_interval:
3258 /* If got here, then the syntax allows intervals. */
3260 /* At least (most) this many matches must be made. */
3261 int lower_bound = 0, upper_bound = -1;
3263 beg_interval = p;
3265 GET_INTERVAL_COUNT (lower_bound);
3267 if (c == ',')
3268 GET_INTERVAL_COUNT (upper_bound);
3269 else
3270 /* Interval such as `{1}' => match exactly once. */
3271 upper_bound = lower_bound;
3273 if (lower_bound < 0
3274 || (0 <= upper_bound && upper_bound < lower_bound))
3275 FREE_STACK_RETURN (REG_BADBR);
3277 if (!(syntax & RE_NO_BK_BRACES))
3279 if (c != '\\')
3280 FREE_STACK_RETURN (REG_BADBR);
3281 if (p == pend)
3282 FREE_STACK_RETURN (REG_EESCAPE);
3283 PATFETCH (c);
3286 if (c != '}')
3287 FREE_STACK_RETURN (REG_BADBR);
3289 /* We just parsed a valid interval. */
3291 /* If it's invalid to have no preceding re. */
3292 if (!laststart)
3294 if (syntax & RE_CONTEXT_INVALID_OPS)
3295 FREE_STACK_RETURN (REG_BADRPT);
3296 else if (syntax & RE_CONTEXT_INDEP_OPS)
3297 laststart = b;
3298 else
3299 goto unfetch_interval;
3302 if (upper_bound == 0)
3303 /* If the upper bound is zero, just drop the sub pattern
3304 altogether. */
3305 b = laststart;
3306 else if (lower_bound == 1 && upper_bound == 1)
3307 /* Just match it once: nothing to do here. */
3310 /* Otherwise, we have a nontrivial interval. When
3311 we're all done, the pattern will look like:
3312 set_number_at <jump count> <upper bound>
3313 set_number_at <succeed_n count> <lower bound>
3314 succeed_n <after jump addr> <succeed_n count>
3315 <body of loop>
3316 jump_n <succeed_n addr> <jump count>
3317 (The upper bound and `jump_n' are omitted if
3318 `upper_bound' is 1, though.) */
3319 else
3320 { /* If the upper bound is > 1, we need to insert
3321 more at the end of the loop. */
3322 unsigned int nbytes = (upper_bound < 0 ? 3
3323 : upper_bound > 1 ? 5 : 0);
3324 unsigned int startoffset = 0;
3326 GET_BUFFER_SPACE (20); /* We might use less. */
3328 if (lower_bound == 0)
3330 /* A succeed_n that starts with 0 is really a
3331 a simple on_failure_jump_loop. */
3332 INSERT_JUMP (on_failure_jump_loop, laststart,
3333 b + 3 + nbytes);
3334 b += 3;
3336 else
3338 /* Initialize lower bound of the `succeed_n', even
3339 though it will be set during matching by its
3340 attendant `set_number_at' (inserted next),
3341 because `re_compile_fastmap' needs to know.
3342 Jump to the `jump_n' we might insert below. */
3343 INSERT_JUMP2 (succeed_n, laststart,
3344 b + 5 + nbytes,
3345 lower_bound);
3346 b += 5;
3348 /* Code to initialize the lower bound. Insert
3349 before the `succeed_n'. The `5' is the last two
3350 bytes of this `set_number_at', plus 3 bytes of
3351 the following `succeed_n'. */
3352 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3353 b += 5;
3354 startoffset += 5;
3357 if (upper_bound < 0)
3359 /* A negative upper bound stands for infinity,
3360 in which case it degenerates to a plain jump. */
3361 STORE_JUMP (jump, b, laststart + startoffset);
3362 b += 3;
3364 else if (upper_bound > 1)
3365 { /* More than one repetition is allowed, so
3366 append a backward jump to the `succeed_n'
3367 that starts this interval.
3369 When we've reached this during matching,
3370 we'll have matched the interval once, so
3371 jump back only `upper_bound - 1' times. */
3372 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3373 upper_bound - 1);
3374 b += 5;
3376 /* The location we want to set is the second
3377 parameter of the `jump_n'; that is `b-2' as
3378 an absolute address. `laststart' will be
3379 the `set_number_at' we're about to insert;
3380 `laststart+3' the number to set, the source
3381 for the relative address. But we are
3382 inserting into the middle of the pattern --
3383 so everything is getting moved up by 5.
3384 Conclusion: (b - 2) - (laststart + 3) + 5,
3385 i.e., b - laststart.
3387 We insert this at the beginning of the loop
3388 so that if we fail during matching, we'll
3389 reinitialize the bounds. */
3390 insert_op2 (set_number_at, laststart, b - laststart,
3391 upper_bound - 1, b);
3392 b += 5;
3395 pending_exact = 0;
3396 beg_interval = NULL;
3398 break;
3400 unfetch_interval:
3401 /* If an invalid interval, match the characters as literals. */
3402 assert (beg_interval);
3403 p = beg_interval;
3404 beg_interval = NULL;
3406 /* normal_char and normal_backslash need `c'. */
3407 c = '{';
3409 if (!(syntax & RE_NO_BK_BRACES))
3411 assert (p > pattern && p[-1] == '\\');
3412 goto normal_backslash;
3414 else
3415 goto normal_char;
3417 #ifdef emacs
3418 case '=':
3419 laststart = b;
3420 BUF_PUSH (at_dot);
3421 break;
3423 case 's':
3424 laststart = b;
3425 PATFETCH (c);
3426 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3427 break;
3429 case 'S':
3430 laststart = b;
3431 PATFETCH (c);
3432 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3433 break;
3435 case 'c':
3436 laststart = b;
3437 PATFETCH (c);
3438 BUF_PUSH_2 (categoryspec, c);
3439 break;
3441 case 'C':
3442 laststart = b;
3443 PATFETCH (c);
3444 BUF_PUSH_2 (notcategoryspec, c);
3445 break;
3446 #endif /* emacs */
3449 case 'w':
3450 if (syntax & RE_NO_GNU_OPS)
3451 goto normal_char;
3452 laststart = b;
3453 BUF_PUSH_2 (syntaxspec, Sword);
3454 break;
3457 case 'W':
3458 if (syntax & RE_NO_GNU_OPS)
3459 goto normal_char;
3460 laststart = b;
3461 BUF_PUSH_2 (notsyntaxspec, Sword);
3462 break;
3465 case '<':
3466 if (syntax & RE_NO_GNU_OPS)
3467 goto normal_char;
3468 laststart = b;
3469 BUF_PUSH (wordbeg);
3470 break;
3472 case '>':
3473 if (syntax & RE_NO_GNU_OPS)
3474 goto normal_char;
3475 laststart = b;
3476 BUF_PUSH (wordend);
3477 break;
3479 case '_':
3480 if (syntax & RE_NO_GNU_OPS)
3481 goto normal_char;
3482 laststart = b;
3483 PATFETCH (c);
3484 if (c == '<')
3485 BUF_PUSH (symbeg);
3486 else if (c == '>')
3487 BUF_PUSH (symend);
3488 else
3489 FREE_STACK_RETURN (REG_BADPAT);
3490 break;
3492 case 'b':
3493 if (syntax & RE_NO_GNU_OPS)
3494 goto normal_char;
3495 BUF_PUSH (wordbound);
3496 break;
3498 case 'B':
3499 if (syntax & RE_NO_GNU_OPS)
3500 goto normal_char;
3501 BUF_PUSH (notwordbound);
3502 break;
3504 case '`':
3505 if (syntax & RE_NO_GNU_OPS)
3506 goto normal_char;
3507 BUF_PUSH (begbuf);
3508 break;
3510 case '\'':
3511 if (syntax & RE_NO_GNU_OPS)
3512 goto normal_char;
3513 BUF_PUSH (endbuf);
3514 break;
3516 case '1': case '2': case '3': case '4': case '5':
3517 case '6': case '7': case '8': case '9':
3519 regnum_t reg;
3521 if (syntax & RE_NO_BK_REFS)
3522 goto normal_backslash;
3524 reg = c - '0';
3526 if (reg > bufp->re_nsub || reg < 1
3527 /* Can't back reference to a subexp before its end. */
3528 || group_in_compile_stack (compile_stack, reg))
3529 FREE_STACK_RETURN (REG_ESUBREG);
3531 laststart = b;
3532 BUF_PUSH_2 (duplicate, reg);
3534 break;
3537 case '+':
3538 case '?':
3539 if (syntax & RE_BK_PLUS_QM)
3540 goto handle_plus;
3541 else
3542 goto normal_backslash;
3544 default:
3545 normal_backslash:
3546 /* You might think it would be useful for \ to mean
3547 not to translate; but if we don't translate it
3548 it will never match anything. */
3549 goto normal_char;
3551 break;
3554 default:
3555 /* Expects the character in `c'. */
3556 normal_char:
3557 /* If no exactn currently being built. */
3558 if (!pending_exact
3560 /* If last exactn not at current position. */
3561 || pending_exact + *pending_exact + 1 != b
3563 /* We have only one byte following the exactn for the count. */
3564 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3566 /* If followed by a repetition operator. */
3567 || (p != pend && (*p == '*' || *p == '^'))
3568 || ((syntax & RE_BK_PLUS_QM)
3569 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3570 : p != pend && (*p == '+' || *p == '?'))
3571 || ((syntax & RE_INTERVALS)
3572 && ((syntax & RE_NO_BK_BRACES)
3573 ? p != pend && *p == '{'
3574 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3576 /* Start building a new exactn. */
3578 laststart = b;
3580 BUF_PUSH_2 (exactn, 0);
3581 pending_exact = b - 1;
3584 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3586 int len;
3588 if (multibyte)
3590 c = TRANSLATE (c);
3591 len = CHAR_STRING (c, b);
3592 b += len;
3594 else
3596 c1 = RE_CHAR_TO_MULTIBYTE (c);
3597 if (! CHAR_BYTE8_P (c1))
3599 re_wchar_t c2 = TRANSLATE (c1);
3601 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3602 c = c1;
3604 *b++ = c;
3605 len = 1;
3607 (*pending_exact) += len;
3610 break;
3611 } /* switch (c) */
3612 } /* while p != pend */
3615 /* Through the pattern now. */
3617 FIXUP_ALT_JUMP ();
3619 if (!COMPILE_STACK_EMPTY)
3620 FREE_STACK_RETURN (REG_EPAREN);
3622 /* If we don't want backtracking, force success
3623 the first time we reach the end of the compiled pattern. */
3624 if (!posix_backtracking)
3625 BUF_PUSH (succeed);
3627 /* We have succeeded; set the length of the buffer. */
3628 bufp->used = b - bufp->buffer;
3630 #ifdef DEBUG
3631 if (debug > 0)
3633 re_compile_fastmap (bufp);
3634 DEBUG_PRINT ("\nCompiled pattern: \n");
3635 print_compiled_pattern (bufp);
3637 debug--;
3638 #endif /* DEBUG */
3640 #ifndef MATCH_MAY_ALLOCATE
3641 /* Initialize the failure stack to the largest possible stack. This
3642 isn't necessary unless we're trying to avoid calling alloca in
3643 the search and match routines. */
3645 int num_regs = bufp->re_nsub + 1;
3647 if (fail_stack.size < emacs_re_max_failures * TYPICAL_FAILURE_SIZE)
3649 fail_stack.size = emacs_re_max_failures * TYPICAL_FAILURE_SIZE;
3650 falk_stack.stack = realloc (fail_stack.stack,
3651 fail_stack.size * sizeof *falk_stack.stack);
3654 regex_grow_registers (num_regs);
3656 #endif /* not MATCH_MAY_ALLOCATE */
3658 FREE_STACK_RETURN (REG_NOERROR);
3660 #ifdef emacs
3661 # undef syntax
3662 #else
3663 # undef posix_backtracking
3664 #endif
3665 } /* regex_compile */
3667 /* Subroutines for `regex_compile'. */
3669 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3671 static void
3672 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3674 *loc = (unsigned char) op;
3675 STORE_NUMBER (loc + 1, arg);
3679 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3681 static void
3682 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3684 *loc = (unsigned char) op;
3685 STORE_NUMBER (loc + 1, arg1);
3686 STORE_NUMBER (loc + 3, arg2);
3690 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3691 for OP followed by two-byte integer parameter ARG. */
3693 static void
3694 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3696 register unsigned char *pfrom = end;
3697 register unsigned char *pto = end + 3;
3699 while (pfrom != loc)
3700 *--pto = *--pfrom;
3702 store_op1 (op, loc, arg);
3706 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3708 static void
3709 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3711 register unsigned char *pfrom = end;
3712 register unsigned char *pto = end + 5;
3714 while (pfrom != loc)
3715 *--pto = *--pfrom;
3717 store_op2 (op, loc, arg1, arg2);
3721 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3722 after an alternative or a begin-subexpression. We assume there is at
3723 least one character before the ^. */
3725 static boolean
3726 at_begline_loc_p (re_char *pattern, re_char *p, reg_syntax_t syntax)
3728 re_char *prev = p - 2;
3729 boolean odd_backslashes;
3731 /* After a subexpression? */
3732 if (*prev == '(')
3733 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3735 /* After an alternative? */
3736 else if (*prev == '|')
3737 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3739 /* After a shy subexpression? */
3740 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3742 /* Skip over optional regnum. */
3743 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3744 --prev;
3746 if (!(prev - 2 >= pattern
3747 && prev[-1] == '?' && prev[-2] == '('))
3748 return false;
3749 prev -= 2;
3750 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3752 else
3753 return false;
3755 /* Count the number of preceding backslashes. */
3756 p = prev;
3757 while (prev - 1 >= pattern && prev[-1] == '\\')
3758 --prev;
3759 return (p - prev) & odd_backslashes;
3763 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3764 at least one character after the $, i.e., `P < PEND'. */
3766 static boolean
3767 at_endline_loc_p (re_char *p, re_char *pend, reg_syntax_t syntax)
3769 re_char *next = p;
3770 boolean next_backslash = *next == '\\';
3771 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3773 return
3774 /* Before a subexpression? */
3775 (syntax & RE_NO_BK_PARENS ? *next == ')'
3776 : next_backslash && next_next && *next_next == ')')
3777 /* Before an alternative? */
3778 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3779 : next_backslash && next_next && *next_next == '|');
3783 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3784 false if it's not. */
3786 static boolean
3787 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3789 ssize_t this_element;
3791 for (this_element = compile_stack.avail - 1;
3792 this_element >= 0;
3793 this_element--)
3794 if (compile_stack.stack[this_element].regnum == regnum)
3795 return true;
3797 return false;
3800 /* analyze_first.
3801 If fastmap is non-NULL, go through the pattern and fill fastmap
3802 with all the possible leading chars. If fastmap is NULL, don't
3803 bother filling it up (obviously) and only return whether the
3804 pattern could potentially match the empty string.
3806 Return 1 if p..pend might match the empty string.
3807 Return 0 if p..pend matches at least one char.
3808 Return -1 if fastmap was not updated accurately. */
3810 static int
3811 analyze_first (re_char *p, re_char *pend, char *fastmap,
3812 const int multibyte)
3814 int j, k;
3815 boolean not;
3817 /* If all elements for base leading-codes in fastmap is set, this
3818 flag is set true. */
3819 boolean match_any_multibyte_characters = false;
3821 assert (p);
3823 /* The loop below works as follows:
3824 - It has a working-list kept in the PATTERN_STACK and which basically
3825 starts by only containing a pointer to the first operation.
3826 - If the opcode we're looking at is a match against some set of
3827 chars, then we add those chars to the fastmap and go on to the
3828 next work element from the worklist (done via `break').
3829 - If the opcode is a control operator on the other hand, we either
3830 ignore it (if it's meaningless at this point, such as `start_memory')
3831 or execute it (if it's a jump). If the jump has several destinations
3832 (i.e. `on_failure_jump'), then we push the other destination onto the
3833 worklist.
3834 We guarantee termination by ignoring backward jumps (more or less),
3835 so that `p' is monotonically increasing. More to the point, we
3836 never set `p' (or push) anything `<= p1'. */
3838 while (p < pend)
3840 /* `p1' is used as a marker of how far back a `on_failure_jump'
3841 can go without being ignored. It is normally equal to `p'
3842 (which prevents any backward `on_failure_jump') except right
3843 after a plain `jump', to allow patterns such as:
3844 0: jump 10
3845 3..9: <body>
3846 10: on_failure_jump 3
3847 as used for the *? operator. */
3848 re_char *p1 = p;
3850 switch (*p++)
3852 case succeed:
3853 return 1;
3855 case duplicate:
3856 /* If the first character has to match a backreference, that means
3857 that the group was empty (since it already matched). Since this
3858 is the only case that interests us here, we can assume that the
3859 backreference must match the empty string. */
3860 p++;
3861 continue;
3864 /* Following are the cases which match a character. These end
3865 with `break'. */
3867 case exactn:
3868 if (fastmap)
3870 /* If multibyte is nonzero, the first byte of each
3871 character is an ASCII or a leading code. Otherwise,
3872 each byte is a character. Thus, this works in both
3873 cases. */
3874 fastmap[p[1]] = 1;
3875 if (! multibyte)
3877 /* For the case of matching this unibyte regex
3878 against multibyte, we must set a leading code of
3879 the corresponding multibyte character. */
3880 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3882 fastmap[CHAR_LEADING_CODE (c)] = 1;
3885 break;
3888 case anychar:
3889 /* We could put all the chars except for \n (and maybe \0)
3890 but we don't bother since it is generally not worth it. */
3891 if (!fastmap) break;
3892 return -1;
3895 case charset_not:
3896 if (!fastmap) break;
3898 /* Chars beyond end of bitmap are possible matches. */
3899 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3900 j < (1 << BYTEWIDTH); j++)
3901 fastmap[j] = 1;
3903 FALLTHROUGH;
3904 case charset:
3905 if (!fastmap) break;
3906 not = (re_opcode_t) *(p - 1) == charset_not;
3907 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3908 j >= 0; j--)
3909 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3910 fastmap[j] = 1;
3912 #ifdef emacs
3913 if (/* Any leading code can possibly start a character
3914 which doesn't match the specified set of characters. */
3917 /* If we can match a character class, we can match any
3918 multibyte characters. */
3919 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3920 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3923 if (match_any_multibyte_characters == false)
3925 for (j = MIN_MULTIBYTE_LEADING_CODE;
3926 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3927 fastmap[j] = 1;
3928 match_any_multibyte_characters = true;
3932 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3933 && match_any_multibyte_characters == false)
3935 /* Set fastmap[I] to 1 where I is a leading code of each
3936 multibyte character in the range table. */
3937 int c, count;
3938 unsigned char lc1, lc2;
3940 /* Make P points the range table. `+ 2' is to skip flag
3941 bits for a character class. */
3942 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3944 /* Extract the number of ranges in range table into COUNT. */
3945 EXTRACT_NUMBER_AND_INCR (count, p);
3946 for (; count > 0; count--, p += 3)
3948 /* Extract the start and end of each range. */
3949 EXTRACT_CHARACTER (c, p);
3950 lc1 = CHAR_LEADING_CODE (c);
3951 p += 3;
3952 EXTRACT_CHARACTER (c, p);
3953 lc2 = CHAR_LEADING_CODE (c);
3954 for (j = lc1; j <= lc2; j++)
3955 fastmap[j] = 1;
3958 #endif
3959 break;
3961 case syntaxspec:
3962 case notsyntaxspec:
3963 if (!fastmap) break;
3964 #ifndef emacs
3965 not = (re_opcode_t)p[-1] == notsyntaxspec;
3966 k = *p++;
3967 for (j = 0; j < (1 << BYTEWIDTH); j++)
3968 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3969 fastmap[j] = 1;
3970 break;
3971 #else /* emacs */
3972 /* This match depends on text properties. These end with
3973 aborting optimizations. */
3974 return -1;
3976 case categoryspec:
3977 case notcategoryspec:
3978 if (!fastmap) break;
3979 not = (re_opcode_t)p[-1] == notcategoryspec;
3980 k = *p++;
3981 for (j = (1 << BYTEWIDTH); j >= 0; j--)
3982 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3983 fastmap[j] = 1;
3985 /* Any leading code can possibly start a character which
3986 has or doesn't has the specified category. */
3987 if (match_any_multibyte_characters == false)
3989 for (j = MIN_MULTIBYTE_LEADING_CODE;
3990 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3991 fastmap[j] = 1;
3992 match_any_multibyte_characters = true;
3994 break;
3996 /* All cases after this match the empty string. These end with
3997 `continue'. */
3999 case at_dot:
4000 #endif /* !emacs */
4001 case no_op:
4002 case begline:
4003 case endline:
4004 case begbuf:
4005 case endbuf:
4006 case wordbound:
4007 case notwordbound:
4008 case wordbeg:
4009 case wordend:
4010 case symbeg:
4011 case symend:
4012 continue;
4015 case jump:
4016 EXTRACT_NUMBER_AND_INCR (j, p);
4017 if (j < 0)
4018 /* Backward jumps can only go back to code that we've already
4019 visited. `re_compile' should make sure this is true. */
4020 break;
4021 p += j;
4022 switch (*p)
4024 case on_failure_jump:
4025 case on_failure_keep_string_jump:
4026 case on_failure_jump_loop:
4027 case on_failure_jump_nastyloop:
4028 case on_failure_jump_smart:
4029 p++;
4030 break;
4031 default:
4032 continue;
4034 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4035 to jump back to "just after here". */
4036 /* Fallthrough */
4038 case on_failure_jump:
4039 case on_failure_keep_string_jump:
4040 case on_failure_jump_nastyloop:
4041 case on_failure_jump_loop:
4042 case on_failure_jump_smart:
4043 EXTRACT_NUMBER_AND_INCR (j, p);
4044 if (p + j <= p1)
4045 ; /* Backward jump to be ignored. */
4046 else
4047 { /* We have to look down both arms.
4048 We first go down the "straight" path so as to minimize
4049 stack usage when going through alternatives. */
4050 int r = analyze_first (p, pend, fastmap, multibyte);
4051 if (r) return r;
4052 p += j;
4054 continue;
4057 case jump_n:
4058 /* This code simply does not properly handle forward jump_n. */
4059 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4060 p += 4;
4061 /* jump_n can either jump or fall through. The (backward) jump
4062 case has already been handled, so we only need to look at the
4063 fallthrough case. */
4064 continue;
4066 case succeed_n:
4067 /* If N == 0, it should be an on_failure_jump_loop instead. */
4068 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4069 p += 4;
4070 /* We only care about one iteration of the loop, so we don't
4071 need to consider the case where this behaves like an
4072 on_failure_jump. */
4073 continue;
4076 case set_number_at:
4077 p += 4;
4078 continue;
4081 case start_memory:
4082 case stop_memory:
4083 p += 1;
4084 continue;
4087 default:
4088 abort (); /* We have listed all the cases. */
4089 } /* switch *p++ */
4091 /* Getting here means we have found the possible starting
4092 characters for one path of the pattern -- and that the empty
4093 string does not match. We need not follow this path further. */
4094 return 0;
4095 } /* while p */
4097 /* We reached the end without matching anything. */
4098 return 1;
4100 } /* analyze_first */
4102 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4103 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4104 characters can start a string that matches the pattern. This fastmap
4105 is used by re_search to skip quickly over impossible starting points.
4107 Character codes above (1 << BYTEWIDTH) are not represented in the
4108 fastmap, but the leading codes are represented. Thus, the fastmap
4109 indicates which character sets could start a match.
4111 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4112 area as BUFP->fastmap.
4114 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4115 the pattern buffer.
4117 Returns 0 if we succeed, -2 if an internal error. */
4120 re_compile_fastmap (struct re_pattern_buffer *bufp)
4122 char *fastmap = bufp->fastmap;
4123 int analysis;
4125 assert (fastmap && bufp->buffer);
4127 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4128 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4130 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4131 fastmap, RE_MULTIBYTE_P (bufp));
4132 bufp->can_be_null = (analysis != 0);
4133 return 0;
4134 } /* re_compile_fastmap */
4136 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4137 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4138 this memory for recording register information. STARTS and ENDS
4139 must be allocated using the malloc library routine, and must each
4140 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4142 If NUM_REGS == 0, then subsequent matches should allocate their own
4143 register data.
4145 Unless this function is called, the first search or match using
4146 PATTERN_BUFFER will allocate its own register data, without
4147 freeing the old data. */
4149 void
4150 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4152 if (num_regs)
4154 bufp->regs_allocated = REGS_REALLOCATE;
4155 regs->num_regs = num_regs;
4156 regs->start = starts;
4157 regs->end = ends;
4159 else
4161 bufp->regs_allocated = REGS_UNALLOCATED;
4162 regs->num_regs = 0;
4163 regs->start = regs->end = 0;
4166 WEAK_ALIAS (__re_set_registers, re_set_registers)
4168 /* Searching routines. */
4170 /* Like re_search_2, below, but only one string is specified, and
4171 doesn't let you say where to stop matching. */
4173 regoff_t
4174 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4175 ssize_t startpos, ssize_t range, struct re_registers *regs)
4177 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4178 regs, size);
4180 WEAK_ALIAS (__re_search, re_search)
4182 /* Head address of virtual concatenation of string. */
4183 #define HEAD_ADDR_VSTRING(P) \
4184 (((P) >= size1 ? string2 : string1))
4186 /* Address of POS in the concatenation of virtual string. */
4187 #define POS_ADDR_VSTRING(POS) \
4188 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4190 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4191 virtual concatenation of STRING1 and STRING2, starting first at index
4192 STARTPOS, then at STARTPOS + 1, and so on.
4194 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4196 RANGE is how far to scan while trying to match. RANGE = 0 means try
4197 only at STARTPOS; in general, the last start tried is STARTPOS +
4198 RANGE.
4200 In REGS, return the indices of the virtual concatenation of STRING1
4201 and STRING2 that matched the entire BUFP->buffer and its contained
4202 subexpressions.
4204 Do not consider matching one past the index STOP in the virtual
4205 concatenation of STRING1 and STRING2.
4207 We return either the position in the strings at which the match was
4208 found, -1 if no match, or -2 if error (such as failure
4209 stack overflow). */
4211 regoff_t
4212 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4213 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4214 struct re_registers *regs, ssize_t stop)
4216 regoff_t val;
4217 re_char *string1 = (re_char *) str1;
4218 re_char *string2 = (re_char *) str2;
4219 register char *fastmap = bufp->fastmap;
4220 register RE_TRANSLATE_TYPE translate = bufp->translate;
4221 size_t total_size = size1 + size2;
4222 ssize_t endpos = startpos + range;
4223 boolean anchored_start;
4224 /* Nonzero if we are searching multibyte string. */
4225 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4227 /* Check for out-of-range STARTPOS. */
4228 if (startpos < 0 || startpos > total_size)
4229 return -1;
4231 /* Fix up RANGE if it might eventually take us outside
4232 the virtual concatenation of STRING1 and STRING2.
4233 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4234 if (endpos < 0)
4235 range = 0 - startpos;
4236 else if (endpos > total_size)
4237 range = total_size - startpos;
4239 /* If the search isn't to be a backwards one, don't waste time in a
4240 search for a pattern anchored at beginning of buffer. */
4241 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4243 if (startpos > 0)
4244 return -1;
4245 else
4246 range = 0;
4249 #ifdef emacs
4250 /* In a forward search for something that starts with \=.
4251 don't keep searching past point. */
4252 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4254 range = PT_BYTE - BEGV_BYTE - startpos;
4255 if (range < 0)
4256 return -1;
4258 #endif /* emacs */
4260 /* Update the fastmap now if not correct already. */
4261 if (fastmap && !bufp->fastmap_accurate)
4262 re_compile_fastmap (bufp);
4264 /* See whether the pattern is anchored. */
4265 anchored_start = (bufp->buffer[0] == begline);
4267 #ifdef emacs
4268 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4270 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4272 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4274 #endif
4276 /* Loop through the string, looking for a place to start matching. */
4277 for (;;)
4279 /* If the pattern is anchored,
4280 skip quickly past places we cannot match.
4281 We don't bother to treat startpos == 0 specially
4282 because that case doesn't repeat. */
4283 if (anchored_start && startpos > 0)
4285 if (! ((startpos <= size1 ? string1[startpos - 1]
4286 : string2[startpos - size1 - 1])
4287 == '\n'))
4288 goto advance;
4291 /* If a fastmap is supplied, skip quickly over characters that
4292 cannot be the start of a match. If the pattern can match the
4293 null string, however, we don't need to skip characters; we want
4294 the first null string. */
4295 if (fastmap && startpos < total_size && !bufp->can_be_null)
4297 register re_char *d;
4298 register re_wchar_t buf_ch;
4300 d = POS_ADDR_VSTRING (startpos);
4302 if (range > 0) /* Searching forwards. */
4304 ssize_t irange = range, lim = 0;
4306 if (startpos < size1 && startpos + range >= size1)
4307 lim = range - (size1 - startpos);
4309 /* Written out as an if-else to avoid testing `translate'
4310 inside the loop. */
4311 if (RE_TRANSLATE_P (translate))
4313 if (multibyte)
4314 while (range > lim)
4316 int buf_charlen;
4318 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4319 buf_ch = RE_TRANSLATE (translate, buf_ch);
4320 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4321 break;
4323 range -= buf_charlen;
4324 d += buf_charlen;
4326 else
4327 while (range > lim)
4329 register re_wchar_t ch, translated;
4331 buf_ch = *d;
4332 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4333 translated = RE_TRANSLATE (translate, ch);
4334 if (translated != ch
4335 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4336 buf_ch = ch;
4337 if (fastmap[buf_ch])
4338 break;
4339 d++;
4340 range--;
4343 else
4345 if (multibyte)
4346 while (range > lim)
4348 int buf_charlen;
4350 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4351 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4352 break;
4353 range -= buf_charlen;
4354 d += buf_charlen;
4356 else
4357 while (range > lim && !fastmap[*d])
4359 d++;
4360 range--;
4363 startpos += irange - range;
4365 else /* Searching backwards. */
4367 if (multibyte)
4369 buf_ch = STRING_CHAR (d);
4370 buf_ch = TRANSLATE (buf_ch);
4371 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4372 goto advance;
4374 else
4376 register re_wchar_t ch, translated;
4378 buf_ch = *d;
4379 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4380 translated = TRANSLATE (ch);
4381 if (translated != ch
4382 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4383 buf_ch = ch;
4384 if (! fastmap[TRANSLATE (buf_ch)])
4385 goto advance;
4390 /* If can't match the null string, and that's all we have left, fail. */
4391 if (range >= 0 && startpos == total_size && fastmap
4392 && !bufp->can_be_null)
4393 return -1;
4395 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4396 startpos, regs, stop);
4398 if (val >= 0)
4399 return startpos;
4401 if (val == -2)
4402 return -2;
4404 advance:
4405 if (!range)
4406 break;
4407 else if (range > 0)
4409 /* Update STARTPOS to the next character boundary. */
4410 if (multibyte)
4412 re_char *p = POS_ADDR_VSTRING (startpos);
4413 int len = BYTES_BY_CHAR_HEAD (*p);
4415 range -= len;
4416 if (range < 0)
4417 break;
4418 startpos += len;
4420 else
4422 range--;
4423 startpos++;
4426 else
4428 range++;
4429 startpos--;
4431 /* Update STARTPOS to the previous character boundary. */
4432 if (multibyte)
4434 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4435 re_char *p0 = p;
4436 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4438 /* Find the head of multibyte form. */
4439 PREV_CHAR_BOUNDARY (p, phead);
4440 range += p0 - 1 - p;
4441 if (range > 0)
4442 break;
4444 startpos -= p0 - 1 - p;
4448 return -1;
4449 } /* re_search_2 */
4450 WEAK_ALIAS (__re_search_2, re_search_2)
4452 /* Declarations and macros for re_match_2. */
4454 static int bcmp_translate (re_char *s1, re_char *s2,
4455 register ssize_t len,
4456 RE_TRANSLATE_TYPE translate,
4457 const int multibyte);
4459 /* This converts PTR, a pointer into one of the search strings `string1'
4460 and `string2' into an offset from the beginning of that string. */
4461 #define POINTER_TO_OFFSET(ptr) \
4462 (FIRST_STRING_P (ptr) \
4463 ? (ptr) - string1 \
4464 : (ptr) - string2 + (ptrdiff_t) size1)
4466 /* Call before fetching a character with *d. This switches over to
4467 string2 if necessary.
4468 Check re_match_2_internal for a discussion of why end_match_2 might
4469 not be within string2 (but be equal to end_match_1 instead). */
4470 #define PREFETCH() \
4471 while (d == dend) \
4473 /* End of string2 => fail. */ \
4474 if (dend == end_match_2) \
4475 goto fail; \
4476 /* End of string1 => advance to string2. */ \
4477 d = string2; \
4478 dend = end_match_2; \
4481 /* Call before fetching a char with *d if you already checked other limits.
4482 This is meant for use in lookahead operations like wordend, etc..
4483 where we might need to look at parts of the string that might be
4484 outside of the LIMITs (i.e past `stop'). */
4485 #define PREFETCH_NOLIMIT() \
4486 if (d == end1) \
4488 d = string2; \
4489 dend = end_match_2; \
4492 /* Test if at very beginning or at very end of the virtual concatenation
4493 of `string1' and `string2'. If only one string, it's `string2'. */
4494 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4495 #define AT_STRINGS_END(d) ((d) == end2)
4497 /* Disabled due to a compiler bug -- see comment at case wordbound */
4499 /* The comment at case wordbound is following one, but we don't use
4500 AT_WORD_BOUNDARY anymore to support multibyte form.
4502 The DEC Alpha C compiler 3.x generates incorrect code for the
4503 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4504 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4505 macro and introducing temporary variables works around the bug. */
4507 #if 0
4508 /* Test if D points to a character which is word-constituent. We have
4509 two special cases to check for: if past the end of string1, look at
4510 the first character in string2; and if before the beginning of
4511 string2, look at the last character in string1. */
4512 #define WORDCHAR_P(d) \
4513 (SYNTAX ((d) == end1 ? *string2 \
4514 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4515 == Sword)
4517 /* Test if the character before D and the one at D differ with respect
4518 to being word-constituent. */
4519 #define AT_WORD_BOUNDARY(d) \
4520 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4521 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4522 #endif
4524 /* Free everything we malloc. */
4525 #ifdef MATCH_MAY_ALLOCATE
4526 # define FREE_VAR(var) \
4527 do { \
4528 if (var) \
4530 REGEX_FREE (var); \
4531 var = NULL; \
4533 } while (0)
4534 # define FREE_VARIABLES() \
4535 do { \
4536 REGEX_FREE_STACK (fail_stack.stack); \
4537 FREE_VAR (regstart); \
4538 FREE_VAR (regend); \
4539 FREE_VAR (best_regstart); \
4540 FREE_VAR (best_regend); \
4541 REGEX_SAFE_FREE (); \
4542 } while (0)
4543 #else
4544 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4545 #endif /* not MATCH_MAY_ALLOCATE */
4548 /* Optimization routines. */
4550 /* If the operation is a match against one or more chars,
4551 return a pointer to the next operation, else return NULL. */
4552 static re_char *
4553 skip_one_char (re_char *p)
4555 switch (*p++)
4557 case anychar:
4558 break;
4560 case exactn:
4561 p += *p + 1;
4562 break;
4564 case charset_not:
4565 case charset:
4566 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4568 int mcnt;
4569 p = CHARSET_RANGE_TABLE (p - 1);
4570 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4571 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4573 else
4574 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4575 break;
4577 case syntaxspec:
4578 case notsyntaxspec:
4579 #ifdef emacs
4580 case categoryspec:
4581 case notcategoryspec:
4582 #endif /* emacs */
4583 p++;
4584 break;
4586 default:
4587 p = NULL;
4589 return p;
4593 /* Jump over non-matching operations. */
4594 static re_char *
4595 skip_noops (re_char *p, re_char *pend)
4597 int mcnt;
4598 while (p < pend)
4600 switch (*p)
4602 case start_memory:
4603 case stop_memory:
4604 p += 2; break;
4605 case no_op:
4606 p += 1; break;
4607 case jump:
4608 p += 1;
4609 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4610 p += mcnt;
4611 break;
4612 default:
4613 return p;
4616 assert (p == pend);
4617 return p;
4620 /* Test if C matches charset op. *PP points to the charset or charset_not
4621 opcode. When the function finishes, *PP will be advanced past that opcode.
4622 C is character to test (possibly after translations) and CORIG is original
4623 character (i.e. without any translations). UNIBYTE denotes whether c is
4624 unibyte or multibyte character. */
4625 static bool
4626 execute_charset (re_char **pp, unsigned c, unsigned corig, bool unibyte)
4628 re_char *p = *pp, *rtp = NULL;
4629 bool not = (re_opcode_t) *p == charset_not;
4631 if (CHARSET_RANGE_TABLE_EXISTS_P (p))
4633 int count;
4634 rtp = CHARSET_RANGE_TABLE (p);
4635 EXTRACT_NUMBER_AND_INCR (count, rtp);
4636 *pp = CHARSET_RANGE_TABLE_END ((rtp), (count));
4638 else
4639 *pp += 2 + CHARSET_BITMAP_SIZE (p);
4641 if (unibyte && c < (1 << BYTEWIDTH))
4642 { /* Lookup bitmap. */
4643 /* Cast to `unsigned' instead of `unsigned char' in
4644 case the bit list is a full 32 bytes long. */
4645 if (c < (unsigned) (CHARSET_BITMAP_SIZE (p) * BYTEWIDTH)
4646 && p[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4647 return !not;
4649 #ifdef emacs
4650 else if (rtp)
4652 int class_bits = CHARSET_RANGE_TABLE_BITS (p);
4653 re_wchar_t range_start, range_end;
4655 /* Sort tests by the most commonly used classes with some adjustment to which
4656 tests are easiest to perform. Take a look at comment in re_wctype_parse
4657 for table with frequencies of character class names. */
4659 if ((class_bits & BIT_MULTIBYTE) ||
4660 (class_bits & BIT_ALNUM && ISALNUM (c)) ||
4661 (class_bits & BIT_ALPHA && ISALPHA (c)) ||
4662 (class_bits & BIT_SPACE && ISSPACE (c)) ||
4663 (class_bits & BIT_BLANK && ISBLANK (c)) ||
4664 (class_bits & BIT_WORD && ISWORD (c)) ||
4665 ((class_bits & BIT_UPPER) &&
4666 (ISUPPER (c) || (corig != c &&
4667 c == downcase (corig) && ISLOWER (c)))) ||
4668 ((class_bits & BIT_LOWER) &&
4669 (ISLOWER (c) || (corig != c &&
4670 c == upcase (corig) && ISUPPER(c)))) ||
4671 (class_bits & BIT_PUNCT && ISPUNCT (c)) ||
4672 (class_bits & BIT_GRAPH && ISGRAPH (c)) ||
4673 (class_bits & BIT_PRINT && ISPRINT (c)))
4674 return !not;
4676 for (p = *pp; rtp < p; rtp += 2 * 3)
4678 EXTRACT_CHARACTER (range_start, rtp);
4679 EXTRACT_CHARACTER (range_end, rtp + 3);
4680 if (range_start <= c && c <= range_end)
4681 return !not;
4684 #endif /* emacs */
4685 return not;
4688 /* Non-zero if "p1 matches something" implies "p2 fails". */
4689 static int
4690 mutually_exclusive_p (struct re_pattern_buffer *bufp, re_char *p1,
4691 re_char *p2)
4693 re_opcode_t op2;
4694 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4695 unsigned char *pend = bufp->buffer + bufp->used;
4697 assert (p1 >= bufp->buffer && p1 < pend
4698 && p2 >= bufp->buffer && p2 <= pend);
4700 /* Skip over open/close-group commands.
4701 If what follows this loop is a ...+ construct,
4702 look at what begins its body, since we will have to
4703 match at least one of that. */
4704 p2 = skip_noops (p2, pend);
4705 /* The same skip can be done for p1, except that this function
4706 is only used in the case where p1 is a simple match operator. */
4707 /* p1 = skip_noops (p1, pend); */
4709 assert (p1 >= bufp->buffer && p1 < pend
4710 && p2 >= bufp->buffer && p2 <= pend);
4712 op2 = p2 == pend ? succeed : *p2;
4714 switch (op2)
4716 case succeed:
4717 case endbuf:
4718 /* If we're at the end of the pattern, we can change. */
4719 if (skip_one_char (p1))
4721 DEBUG_PRINT (" End of pattern: fast loop.\n");
4722 return 1;
4724 break;
4726 case endline:
4727 case exactn:
4729 register re_wchar_t c
4730 = (re_opcode_t) *p2 == endline ? '\n'
4731 : RE_STRING_CHAR (p2 + 2, multibyte);
4733 if ((re_opcode_t) *p1 == exactn)
4735 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4737 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4738 return 1;
4742 else if ((re_opcode_t) *p1 == charset
4743 || (re_opcode_t) *p1 == charset_not)
4745 if (!execute_charset (&p1, c, c, !multibyte || IS_REAL_ASCII (c)))
4747 DEBUG_PRINT (" No match => fast loop.\n");
4748 return 1;
4751 else if ((re_opcode_t) *p1 == anychar
4752 && c == '\n')
4754 DEBUG_PRINT (" . != \\n => fast loop.\n");
4755 return 1;
4758 break;
4760 case charset:
4762 if ((re_opcode_t) *p1 == exactn)
4763 /* Reuse the code above. */
4764 return mutually_exclusive_p (bufp, p2, p1);
4766 /* It is hard to list up all the character in charset
4767 P2 if it includes multibyte character. Give up in
4768 such case. */
4769 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4771 /* Now, we are sure that P2 has no range table.
4772 So, for the size of bitmap in P2, `p2[1]' is
4773 enough. But P1 may have range table, so the
4774 size of bitmap table of P1 is extracted by
4775 using macro `CHARSET_BITMAP_SIZE'.
4777 In a multibyte case, we know that all the character
4778 listed in P2 is ASCII. In a unibyte case, P1 has only a
4779 bitmap table. So, in both cases, it is enough to test
4780 only the bitmap table of P1. */
4782 if ((re_opcode_t) *p1 == charset)
4784 int idx;
4785 /* We win if the charset inside the loop
4786 has no overlap with the one after the loop. */
4787 for (idx = 0;
4788 (idx < (int) p2[1]
4789 && idx < CHARSET_BITMAP_SIZE (p1));
4790 idx++)
4791 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4792 break;
4794 if (idx == p2[1]
4795 || idx == CHARSET_BITMAP_SIZE (p1))
4797 DEBUG_PRINT (" No match => fast loop.\n");
4798 return 1;
4801 else if ((re_opcode_t) *p1 == charset_not)
4803 int idx;
4804 /* We win if the charset_not inside the loop lists
4805 every character listed in the charset after. */
4806 for (idx = 0; idx < (int) p2[1]; idx++)
4807 if (! (p2[2 + idx] == 0
4808 || (idx < CHARSET_BITMAP_SIZE (p1)
4809 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4810 break;
4812 if (idx == p2[1])
4814 DEBUG_PRINT (" No match => fast loop.\n");
4815 return 1;
4820 break;
4822 case charset_not:
4823 switch (*p1)
4825 case exactn:
4826 case charset:
4827 /* Reuse the code above. */
4828 return mutually_exclusive_p (bufp, p2, p1);
4829 case charset_not:
4830 /* When we have two charset_not, it's very unlikely that
4831 they don't overlap. The union of the two sets of excluded
4832 chars should cover all possible chars, which, as a matter of
4833 fact, is virtually impossible in multibyte buffers. */
4834 break;
4836 break;
4838 case wordend:
4839 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4840 case symend:
4841 return ((re_opcode_t) *p1 == syntaxspec
4842 && (p1[1] == Ssymbol || p1[1] == Sword));
4843 case notsyntaxspec:
4844 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4846 case wordbeg:
4847 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4848 case symbeg:
4849 return ((re_opcode_t) *p1 == notsyntaxspec
4850 && (p1[1] == Ssymbol || p1[1] == Sword));
4851 case syntaxspec:
4852 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4854 case wordbound:
4855 return (((re_opcode_t) *p1 == notsyntaxspec
4856 || (re_opcode_t) *p1 == syntaxspec)
4857 && p1[1] == Sword);
4859 #ifdef emacs
4860 case categoryspec:
4861 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4862 case notcategoryspec:
4863 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4864 #endif /* emacs */
4866 default:
4870 /* Safe default. */
4871 return 0;
4875 /* Matching routines. */
4877 #ifndef emacs /* Emacs never uses this. */
4878 /* re_match is like re_match_2 except it takes only a single string. */
4880 regoff_t
4881 re_match (struct re_pattern_buffer *bufp, const char *string,
4882 size_t size, ssize_t pos, struct re_registers *regs)
4884 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char *) string,
4885 size, pos, regs, size);
4886 return result;
4888 WEAK_ALIAS (__re_match, re_match)
4889 #endif /* not emacs */
4891 /* re_match_2 matches the compiled pattern in BUFP against the
4892 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4893 and SIZE2, respectively). We start matching at POS, and stop
4894 matching at STOP.
4896 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4897 store offsets for the substring each group matched in REGS. See the
4898 documentation for exactly how many groups we fill.
4900 We return -1 if no match, -2 if an internal error (such as the
4901 failure stack overflowing). Otherwise, we return the length of the
4902 matched substring. */
4904 regoff_t
4905 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4906 size_t size1, const char *string2, size_t size2, ssize_t pos,
4907 struct re_registers *regs, ssize_t stop)
4909 regoff_t result;
4911 #ifdef emacs
4912 ssize_t charpos;
4913 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4914 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4915 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4916 #endif
4918 result = re_match_2_internal (bufp, (re_char *) string1, size1,
4919 (re_char *) string2, size2,
4920 pos, regs, stop);
4921 return result;
4923 WEAK_ALIAS (__re_match_2, re_match_2)
4926 /* This is a separate function so that we can force an alloca cleanup
4927 afterwards. */
4928 static regoff_t
4929 re_match_2_internal (struct re_pattern_buffer *bufp, re_char *string1,
4930 size_t size1, re_char *string2, size_t size2,
4931 ssize_t pos, struct re_registers *regs, ssize_t stop)
4933 /* General temporaries. */
4934 int mcnt;
4935 size_t reg;
4937 /* Just past the end of the corresponding string. */
4938 re_char *end1, *end2;
4940 /* Pointers into string1 and string2, just past the last characters in
4941 each to consider matching. */
4942 re_char *end_match_1, *end_match_2;
4944 /* Where we are in the data, and the end of the current string. */
4945 re_char *d, *dend;
4947 /* Used sometimes to remember where we were before starting matching
4948 an operator so that we can go back in case of failure. This "atomic"
4949 behavior of matching opcodes is indispensable to the correctness
4950 of the on_failure_keep_string_jump optimization. */
4951 re_char *dfail;
4953 /* Where we are in the pattern, and the end of the pattern. */
4954 re_char *p = bufp->buffer;
4955 re_char *pend = p + bufp->used;
4957 /* We use this to map every character in the string. */
4958 RE_TRANSLATE_TYPE translate = bufp->translate;
4960 /* Nonzero if BUFP is setup from a multibyte regex. */
4961 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4963 /* Nonzero if STRING1/STRING2 are multibyte. */
4964 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4966 /* Failure point stack. Each place that can handle a failure further
4967 down the line pushes a failure point on this stack. It consists of
4968 regstart, and regend for all registers corresponding to
4969 the subexpressions we're currently inside, plus the number of such
4970 registers, and, finally, two char *'s. The first char * is where
4971 to resume scanning the pattern; the second one is where to resume
4972 scanning the strings. */
4973 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4974 fail_stack_type fail_stack;
4975 #endif
4976 #ifdef DEBUG_COMPILES_ARGUMENTS
4977 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4978 #endif
4980 #if defined REL_ALLOC && defined REGEX_MALLOC
4981 /* This holds the pointer to the failure stack, when
4982 it is allocated relocatably. */
4983 fail_stack_elt_t *failure_stack_ptr;
4984 #endif
4986 /* We fill all the registers internally, independent of what we
4987 return, for use in backreferences. The number here includes
4988 an element for register zero. */
4989 size_t num_regs = bufp->re_nsub + 1;
4991 /* Information on the contents of registers. These are pointers into
4992 the input strings; they record just what was matched (on this
4993 attempt) by a subexpression part of the pattern, that is, the
4994 regnum-th regstart pointer points to where in the pattern we began
4995 matching and the regnum-th regend points to right after where we
4996 stopped matching the regnum-th subexpression. (The zeroth register
4997 keeps track of what the whole pattern matches.) */
4998 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4999 re_char **regstart, **regend;
5000 #endif
5002 /* The following record the register info as found in the above
5003 variables when we find a match better than any we've seen before.
5004 This happens as we backtrack through the failure points, which in
5005 turn happens only if we have not yet matched the entire string. */
5006 unsigned best_regs_set = false;
5007 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5008 re_char **best_regstart, **best_regend;
5009 #endif
5011 /* Logically, this is `best_regend[0]'. But we don't want to have to
5012 allocate space for that if we're not allocating space for anything
5013 else (see below). Also, we never need info about register 0 for
5014 any of the other register vectors, and it seems rather a kludge to
5015 treat `best_regend' differently than the rest. So we keep track of
5016 the end of the best match so far in a separate variable. We
5017 initialize this to NULL so that when we backtrack the first time
5018 and need to test it, it's not garbage. */
5019 re_char *match_end = NULL;
5021 #ifdef DEBUG_COMPILES_ARGUMENTS
5022 /* Counts the total number of registers pushed. */
5023 unsigned num_regs_pushed = 0;
5024 #endif
5026 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5028 REGEX_USE_SAFE_ALLOCA;
5030 INIT_FAIL_STACK ();
5032 #ifdef MATCH_MAY_ALLOCATE
5033 /* Do not bother to initialize all the register variables if there are
5034 no groups in the pattern, as it takes a fair amount of time. If
5035 there are groups, we include space for register 0 (the whole
5036 pattern), even though we never use it, since it simplifies the
5037 array indexing. We should fix this. */
5038 if (bufp->re_nsub)
5040 regstart = REGEX_TALLOC (num_regs, re_char *);
5041 regend = REGEX_TALLOC (num_regs, re_char *);
5042 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5043 best_regend = REGEX_TALLOC (num_regs, re_char *);
5045 if (!(regstart && regend && best_regstart && best_regend))
5047 FREE_VARIABLES ();
5048 return -2;
5051 else
5053 /* We must initialize all our variables to NULL, so that
5054 `FREE_VARIABLES' doesn't try to free them. */
5055 regstart = regend = best_regstart = best_regend = NULL;
5057 #endif /* MATCH_MAY_ALLOCATE */
5059 /* The starting position is bogus. */
5060 if (pos < 0 || pos > size1 + size2)
5062 FREE_VARIABLES ();
5063 return -1;
5066 /* Initialize subexpression text positions to -1 to mark ones that no
5067 start_memory/stop_memory has been seen for. Also initialize the
5068 register information struct. */
5069 for (reg = 1; reg < num_regs; reg++)
5070 regstart[reg] = regend[reg] = NULL;
5072 /* We move `string1' into `string2' if the latter's empty -- but not if
5073 `string1' is null. */
5074 if (size2 == 0 && string1 != NULL)
5076 string2 = string1;
5077 size2 = size1;
5078 string1 = 0;
5079 size1 = 0;
5081 end1 = string1 + size1;
5082 end2 = string2 + size2;
5084 /* `p' scans through the pattern as `d' scans through the data.
5085 `dend' is the end of the input string that `d' points within. `d'
5086 is advanced into the following input string whenever necessary, but
5087 this happens before fetching; therefore, at the beginning of the
5088 loop, `d' can be pointing at the end of a string, but it cannot
5089 equal `string2'. */
5090 if (pos >= size1)
5092 /* Only match within string2. */
5093 d = string2 + pos - size1;
5094 dend = end_match_2 = string2 + stop - size1;
5095 end_match_1 = end1; /* Just to give it a value. */
5097 else
5099 if (stop < size1)
5101 /* Only match within string1. */
5102 end_match_1 = string1 + stop;
5103 /* BEWARE!
5104 When we reach end_match_1, PREFETCH normally switches to string2.
5105 But in the present case, this means that just doing a PREFETCH
5106 makes us jump from `stop' to `gap' within the string.
5107 What we really want here is for the search to stop as
5108 soon as we hit end_match_1. That's why we set end_match_2
5109 to end_match_1 (since PREFETCH fails as soon as we hit
5110 end_match_2). */
5111 end_match_2 = end_match_1;
5113 else
5114 { /* It's important to use this code when stop == size so that
5115 moving `d' from end1 to string2 will not prevent the d == dend
5116 check from catching the end of string. */
5117 end_match_1 = end1;
5118 end_match_2 = string2 + stop - size1;
5120 d = string1 + pos;
5121 dend = end_match_1;
5124 DEBUG_PRINT ("The compiled pattern is: ");
5125 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5126 DEBUG_PRINT ("The string to match is: \"");
5127 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5128 DEBUG_PRINT ("\"\n");
5130 /* This loops over pattern commands. It exits by returning from the
5131 function if the match is complete, or it drops through if the match
5132 fails at this starting point in the input data. */
5133 for (;;)
5135 DEBUG_PRINT ("\n%p: ", p);
5137 if (p == pend)
5139 /* End of pattern means we might have succeeded. */
5140 DEBUG_PRINT ("end of pattern ... ");
5142 /* If we haven't matched the entire string, and we want the
5143 longest match, try backtracking. */
5144 if (d != end_match_2)
5146 /* True if this match is the best seen so far. */
5147 bool best_match_p;
5150 /* True if this match ends in the same string (string1
5151 or string2) as the best previous match. */
5152 bool same_str_p = (FIRST_STRING_P (match_end)
5153 == FIRST_STRING_P (d));
5155 /* AIX compiler got confused when this was combined
5156 with the previous declaration. */
5157 if (same_str_p)
5158 best_match_p = d > match_end;
5159 else
5160 best_match_p = !FIRST_STRING_P (d);
5163 DEBUG_PRINT ("backtracking.\n");
5165 if (!FAIL_STACK_EMPTY ())
5166 { /* More failure points to try. */
5168 /* If exceeds best match so far, save it. */
5169 if (!best_regs_set || best_match_p)
5171 best_regs_set = true;
5172 match_end = d;
5174 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5176 for (reg = 1; reg < num_regs; reg++)
5178 best_regstart[reg] = regstart[reg];
5179 best_regend[reg] = regend[reg];
5182 goto fail;
5185 /* If no failure points, don't restore garbage. And if
5186 last match is real best match, don't restore second
5187 best one. */
5188 else if (best_regs_set && !best_match_p)
5190 restore_best_regs:
5191 /* Restore best match. It may happen that `dend ==
5192 end_match_1' while the restored d is in string2.
5193 For example, the pattern `x.*y.*z' against the
5194 strings `x-' and `y-z-', if the two strings are
5195 not consecutive in memory. */
5196 DEBUG_PRINT ("Restoring best registers.\n");
5198 d = match_end;
5199 dend = ((d >= string1 && d <= end1)
5200 ? end_match_1 : end_match_2);
5202 for (reg = 1; reg < num_regs; reg++)
5204 regstart[reg] = best_regstart[reg];
5205 regend[reg] = best_regend[reg];
5208 } /* d != end_match_2 */
5210 succeed_label:
5211 DEBUG_PRINT ("Accepting match.\n");
5213 /* If caller wants register contents data back, do it. */
5214 if (regs && !bufp->no_sub)
5216 /* Have the register data arrays been allocated? */
5217 if (bufp->regs_allocated == REGS_UNALLOCATED)
5218 { /* No. So allocate them with malloc. We need one
5219 extra element beyond `num_regs' for the `-1' marker
5220 GNU code uses. */
5221 regs->num_regs = max (RE_NREGS, num_regs + 1);
5222 regs->start = TALLOC (regs->num_regs, regoff_t);
5223 regs->end = TALLOC (regs->num_regs, regoff_t);
5224 if (regs->start == NULL || regs->end == NULL)
5226 FREE_VARIABLES ();
5227 return -2;
5229 bufp->regs_allocated = REGS_REALLOCATE;
5231 else if (bufp->regs_allocated == REGS_REALLOCATE)
5232 { /* Yes. If we need more elements than were already
5233 allocated, reallocate them. If we need fewer, just
5234 leave it alone. */
5235 if (regs->num_regs < num_regs + 1)
5237 regs->num_regs = num_regs + 1;
5238 RETALLOC (regs->start, regs->num_regs, regoff_t);
5239 RETALLOC (regs->end, regs->num_regs, regoff_t);
5240 if (regs->start == NULL || regs->end == NULL)
5242 FREE_VARIABLES ();
5243 return -2;
5247 else
5249 /* These braces fend off a "empty body in an else-statement"
5250 warning under GCC when assert expands to nothing. */
5251 assert (bufp->regs_allocated == REGS_FIXED);
5254 /* Convert the pointer data in `regstart' and `regend' to
5255 indices. Register zero has to be set differently,
5256 since we haven't kept track of any info for it. */
5257 if (regs->num_regs > 0)
5259 regs->start[0] = pos;
5260 regs->end[0] = POINTER_TO_OFFSET (d);
5263 /* Go through the first `min (num_regs, regs->num_regs)'
5264 registers, since that is all we initialized. */
5265 for (reg = 1; reg < min (num_regs, regs->num_regs); reg++)
5267 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5268 regs->start[reg] = regs->end[reg] = -1;
5269 else
5271 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5272 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5276 /* If the regs structure we return has more elements than
5277 were in the pattern, set the extra elements to -1. If
5278 we (re)allocated the registers, this is the case,
5279 because we always allocate enough to have at least one
5280 -1 at the end. */
5281 for (reg = num_regs; reg < regs->num_regs; reg++)
5282 regs->start[reg] = regs->end[reg] = -1;
5283 } /* regs && !bufp->no_sub */
5285 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5286 nfailure_points_pushed, nfailure_points_popped,
5287 nfailure_points_pushed - nfailure_points_popped);
5288 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5290 ptrdiff_t dcnt = POINTER_TO_OFFSET (d) - pos;
5292 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5294 FREE_VARIABLES ();
5295 return dcnt;
5298 /* Otherwise match next pattern command. */
5299 switch (*p++)
5301 /* Ignore these. Used to ignore the n of succeed_n's which
5302 currently have n == 0. */
5303 case no_op:
5304 DEBUG_PRINT ("EXECUTING no_op.\n");
5305 break;
5307 case succeed:
5308 DEBUG_PRINT ("EXECUTING succeed.\n");
5309 goto succeed_label;
5311 /* Match the next n pattern characters exactly. The following
5312 byte in the pattern defines n, and the n bytes after that
5313 are the characters to match. */
5314 case exactn:
5315 mcnt = *p++;
5316 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5318 /* Remember the start point to rollback upon failure. */
5319 dfail = d;
5321 #ifndef emacs
5322 /* This is written out as an if-else so we don't waste time
5323 testing `translate' inside the loop. */
5324 if (RE_TRANSLATE_P (translate))
5327 PREFETCH ();
5328 if (RE_TRANSLATE (translate, *d) != *p++)
5330 d = dfail;
5331 goto fail;
5333 d++;
5335 while (--mcnt);
5336 else
5339 PREFETCH ();
5340 if (*d++ != *p++)
5342 d = dfail;
5343 goto fail;
5346 while (--mcnt);
5347 #else /* emacs */
5348 /* The cost of testing `translate' is comparatively small. */
5349 if (target_multibyte)
5352 int pat_charlen, buf_charlen;
5353 int pat_ch, buf_ch;
5355 PREFETCH ();
5356 if (multibyte)
5357 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5358 else
5360 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5361 pat_charlen = 1;
5363 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5365 if (TRANSLATE (buf_ch) != pat_ch)
5367 d = dfail;
5368 goto fail;
5371 p += pat_charlen;
5372 d += buf_charlen;
5373 mcnt -= pat_charlen;
5375 while (mcnt > 0);
5376 else
5379 int pat_charlen;
5380 int pat_ch, buf_ch;
5382 PREFETCH ();
5383 if (multibyte)
5385 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5386 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5388 else
5390 pat_ch = *p;
5391 pat_charlen = 1;
5393 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5394 if (! CHAR_BYTE8_P (buf_ch))
5396 buf_ch = TRANSLATE (buf_ch);
5397 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5398 if (buf_ch < 0)
5399 buf_ch = *d;
5401 else
5402 buf_ch = *d;
5403 if (buf_ch != pat_ch)
5405 d = dfail;
5406 goto fail;
5408 p += pat_charlen;
5409 d++;
5411 while (--mcnt);
5412 #endif
5413 break;
5416 /* Match any character except possibly a newline or a null. */
5417 case anychar:
5419 int buf_charlen;
5420 re_wchar_t buf_ch;
5421 reg_syntax_t syntax;
5423 DEBUG_PRINT ("EXECUTING anychar.\n");
5425 PREFETCH ();
5426 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5427 target_multibyte);
5428 buf_ch = TRANSLATE (buf_ch);
5430 #ifdef emacs
5431 syntax = RE_SYNTAX_EMACS;
5432 #else
5433 syntax = bufp->syntax;
5434 #endif
5436 if ((!(syntax & RE_DOT_NEWLINE) && buf_ch == '\n')
5437 || ((syntax & RE_DOT_NOT_NULL) && buf_ch == '\000'))
5438 goto fail;
5440 DEBUG_PRINT (" Matched \"%d\".\n", *d);
5441 d += buf_charlen;
5443 break;
5446 case charset:
5447 case charset_not:
5449 register unsigned int c, corig;
5450 int len;
5452 /* Whether matching against a unibyte character. */
5453 boolean unibyte_char = false;
5455 DEBUG_PRINT ("EXECUTING charset%s.\n",
5456 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
5458 PREFETCH ();
5459 corig = c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5460 if (target_multibyte)
5462 int c1;
5464 c = TRANSLATE (c);
5465 c1 = RE_CHAR_TO_UNIBYTE (c);
5466 if (c1 >= 0)
5468 unibyte_char = true;
5469 c = c1;
5472 else
5474 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5476 if (! CHAR_BYTE8_P (c1))
5478 c1 = TRANSLATE (c1);
5479 c1 = RE_CHAR_TO_UNIBYTE (c1);
5480 if (c1 >= 0)
5482 unibyte_char = true;
5483 c = c1;
5486 else
5487 unibyte_char = true;
5490 p -= 1;
5491 if (!execute_charset (&p, c, corig, unibyte_char))
5492 goto fail;
5494 d += len;
5496 break;
5499 /* The beginning of a group is represented by start_memory.
5500 The argument is the register number. The text
5501 matched within the group is recorded (in the internal
5502 registers data structure) under the register number. */
5503 case start_memory:
5504 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5506 /* In case we need to undo this operation (via backtracking). */
5507 PUSH_FAILURE_REG (*p);
5509 regstart[*p] = d;
5510 regend[*p] = NULL; /* probably unnecessary. -sm */
5511 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5513 /* Move past the register number and inner group count. */
5514 p += 1;
5515 break;
5518 /* The stop_memory opcode represents the end of a group. Its
5519 argument is the same as start_memory's: the register number. */
5520 case stop_memory:
5521 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5523 assert (!REG_UNSET (regstart[*p]));
5524 /* Strictly speaking, there should be code such as:
5526 assert (REG_UNSET (regend[*p]));
5527 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5529 But the only info to be pushed is regend[*p] and it is known to
5530 be UNSET, so there really isn't anything to push.
5531 Not pushing anything, on the other hand deprives us from the
5532 guarantee that regend[*p] is UNSET since undoing this operation
5533 will not reset its value properly. This is not important since
5534 the value will only be read on the next start_memory or at
5535 the very end and both events can only happen if this stop_memory
5536 is *not* undone. */
5538 regend[*p] = d;
5539 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5541 /* Move past the register number and the inner group count. */
5542 p += 1;
5543 break;
5546 /* \<digit> has been turned into a `duplicate' command which is
5547 followed by the numeric value of <digit> as the register number. */
5548 case duplicate:
5550 register re_char *d2, *dend2;
5551 int regno = *p++; /* Get which register to match against. */
5552 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5554 /* Can't back reference a group which we've never matched. */
5555 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5556 goto fail;
5558 /* Where in input to try to start matching. */
5559 d2 = regstart[regno];
5561 /* Remember the start point to rollback upon failure. */
5562 dfail = d;
5564 /* Where to stop matching; if both the place to start and
5565 the place to stop matching are in the same string, then
5566 set to the place to stop, otherwise, for now have to use
5567 the end of the first string. */
5569 dend2 = ((FIRST_STRING_P (regstart[regno])
5570 == FIRST_STRING_P (regend[regno]))
5571 ? regend[regno] : end_match_1);
5572 for (;;)
5574 ptrdiff_t dcnt;
5576 /* If necessary, advance to next segment in register
5577 contents. */
5578 while (d2 == dend2)
5580 if (dend2 == end_match_2) break;
5581 if (dend2 == regend[regno]) break;
5583 /* End of string1 => advance to string2. */
5584 d2 = string2;
5585 dend2 = regend[regno];
5587 /* At end of register contents => success */
5588 if (d2 == dend2) break;
5590 /* If necessary, advance to next segment in data. */
5591 PREFETCH ();
5593 /* How many characters left in this segment to match. */
5594 dcnt = dend - d;
5596 /* Want how many consecutive characters we can match in
5597 one shot, so, if necessary, adjust the count. */
5598 if (dcnt > dend2 - d2)
5599 dcnt = dend2 - d2;
5601 /* Compare that many; failure if mismatch, else move
5602 past them. */
5603 if (RE_TRANSLATE_P (translate)
5604 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5605 : memcmp (d, d2, dcnt))
5607 d = dfail;
5608 goto fail;
5610 d += dcnt, d2 += dcnt;
5613 break;
5616 /* begline matches the empty string at the beginning of the string
5617 (unless `not_bol' is set in `bufp'), and after newlines. */
5618 case begline:
5619 DEBUG_PRINT ("EXECUTING begline.\n");
5621 if (AT_STRINGS_BEG (d))
5623 if (!bufp->not_bol) break;
5625 else
5627 unsigned c;
5628 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5629 if (c == '\n')
5630 break;
5632 /* In all other cases, we fail. */
5633 goto fail;
5636 /* endline is the dual of begline. */
5637 case endline:
5638 DEBUG_PRINT ("EXECUTING endline.\n");
5640 if (AT_STRINGS_END (d))
5642 if (!bufp->not_eol) break;
5644 else
5646 PREFETCH_NOLIMIT ();
5647 if (*d == '\n')
5648 break;
5650 goto fail;
5653 /* Match at the very beginning of the data. */
5654 case begbuf:
5655 DEBUG_PRINT ("EXECUTING begbuf.\n");
5656 if (AT_STRINGS_BEG (d))
5657 break;
5658 goto fail;
5661 /* Match at the very end of the data. */
5662 case endbuf:
5663 DEBUG_PRINT ("EXECUTING endbuf.\n");
5664 if (AT_STRINGS_END (d))
5665 break;
5666 goto fail;
5669 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5670 pushes NULL as the value for the string on the stack. Then
5671 `POP_FAILURE_POINT' will keep the current value for the
5672 string, instead of restoring it. To see why, consider
5673 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5674 then the . fails against the \n. But the next thing we want
5675 to do is match the \n against the \n; if we restored the
5676 string value, we would be back at the foo.
5678 Because this is used only in specific cases, we don't need to
5679 check all the things that `on_failure_jump' does, to make
5680 sure the right things get saved on the stack. Hence we don't
5681 share its code. The only reason to push anything on the
5682 stack at all is that otherwise we would have to change
5683 `anychar's code to do something besides goto fail in this
5684 case; that seems worse than this. */
5685 case on_failure_keep_string_jump:
5686 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5687 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5688 mcnt, p + mcnt);
5690 PUSH_FAILURE_POINT (p - 3, NULL);
5691 break;
5693 /* A nasty loop is introduced by the non-greedy *? and +?.
5694 With such loops, the stack only ever contains one failure point
5695 at a time, so that a plain on_failure_jump_loop kind of
5696 cycle detection cannot work. Worse yet, such a detection
5697 can not only fail to detect a cycle, but it can also wrongly
5698 detect a cycle (between different instantiations of the same
5699 loop).
5700 So the method used for those nasty loops is a little different:
5701 We use a special cycle-detection-stack-frame which is pushed
5702 when the on_failure_jump_nastyloop failure-point is *popped*.
5703 This special frame thus marks the beginning of one iteration
5704 through the loop and we can hence easily check right here
5705 whether something matched between the beginning and the end of
5706 the loop. */
5707 case on_failure_jump_nastyloop:
5708 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5709 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5710 mcnt, p + mcnt);
5712 assert ((re_opcode_t)p[-4] == no_op);
5714 int cycle = 0;
5715 CHECK_INFINITE_LOOP (p - 4, d);
5716 if (!cycle)
5717 /* If there's a cycle, just continue without pushing
5718 this failure point. The failure point is the "try again"
5719 option, which shouldn't be tried.
5720 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5721 PUSH_FAILURE_POINT (p - 3, d);
5723 break;
5725 /* Simple loop detecting on_failure_jump: just check on the
5726 failure stack if the same spot was already hit earlier. */
5727 case on_failure_jump_loop:
5728 on_failure:
5729 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5730 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5731 mcnt, p + mcnt);
5733 int cycle = 0;
5734 CHECK_INFINITE_LOOP (p - 3, d);
5735 if (cycle)
5736 /* If there's a cycle, get out of the loop, as if the matching
5737 had failed. We used to just `goto fail' here, but that was
5738 aborting the search a bit too early: we want to keep the
5739 empty-loop-match and keep matching after the loop.
5740 We want (x?)*y\1z to match both xxyz and xxyxz. */
5741 p += mcnt;
5742 else
5743 PUSH_FAILURE_POINT (p - 3, d);
5745 break;
5748 /* Uses of on_failure_jump:
5750 Each alternative starts with an on_failure_jump that points
5751 to the beginning of the next alternative. Each alternative
5752 except the last ends with a jump that in effect jumps past
5753 the rest of the alternatives. (They really jump to the
5754 ending jump of the following alternative, because tensioning
5755 these jumps is a hassle.)
5757 Repeats start with an on_failure_jump that points past both
5758 the repetition text and either the following jump or
5759 pop_failure_jump back to this on_failure_jump. */
5760 case on_failure_jump:
5761 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5762 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5763 mcnt, p + mcnt);
5765 PUSH_FAILURE_POINT (p -3, d);
5766 break;
5768 /* This operation is used for greedy *.
5769 Compare the beginning of the repeat with what in the
5770 pattern follows its end. If we can establish that there
5771 is nothing that they would both match, i.e., that we
5772 would have to backtrack because of (as in, e.g., `a*a')
5773 then we can use a non-backtracking loop based on
5774 on_failure_keep_string_jump instead of on_failure_jump. */
5775 case on_failure_jump_smart:
5776 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5777 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5778 mcnt, p + mcnt);
5780 re_char *p1 = p; /* Next operation. */
5781 /* Here, we discard `const', making re_match non-reentrant. */
5782 unsigned char *p2 = (unsigned char *) p + mcnt; /* Jump dest. */
5783 unsigned char *p3 = (unsigned char *) p - 3; /* opcode location. */
5785 p -= 3; /* Reset so that we will re-execute the
5786 instruction once it's been changed. */
5788 EXTRACT_NUMBER (mcnt, p2 - 2);
5790 /* Ensure this is indeed the trivial kind of loop
5791 we are expecting. */
5792 assert (skip_one_char (p1) == p2 - 3);
5793 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5794 DEBUG_STATEMENT (debug += 2);
5795 if (mutually_exclusive_p (bufp, p1, p2))
5797 /* Use a fast `on_failure_keep_string_jump' loop. */
5798 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5799 *p3 = (unsigned char) on_failure_keep_string_jump;
5800 STORE_NUMBER (p2 - 2, mcnt + 3);
5802 else
5804 /* Default to a safe `on_failure_jump' loop. */
5805 DEBUG_PRINT (" smart default => slow loop.\n");
5806 *p3 = (unsigned char) on_failure_jump;
5808 DEBUG_STATEMENT (debug -= 2);
5810 break;
5812 /* Unconditionally jump (without popping any failure points). */
5813 case jump:
5814 unconditional_jump:
5815 maybe_quit ();
5816 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5817 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5818 p += mcnt; /* Do the jump. */
5819 DEBUG_PRINT ("(to %p).\n", p);
5820 break;
5823 /* Have to succeed matching what follows at least n times.
5824 After that, handle like `on_failure_jump'. */
5825 case succeed_n:
5826 /* Signedness doesn't matter since we only compare MCNT to 0. */
5827 EXTRACT_NUMBER (mcnt, p + 2);
5828 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5830 /* Originally, mcnt is how many times we HAVE to succeed. */
5831 if (mcnt != 0)
5833 /* Here, we discard `const', making re_match non-reentrant. */
5834 unsigned char *p2 = (unsigned char *) p + 2; /* counter loc. */
5835 mcnt--;
5836 p += 4;
5837 PUSH_NUMBER (p2, mcnt);
5839 else
5840 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5841 goto on_failure;
5842 break;
5844 case jump_n:
5845 /* Signedness doesn't matter since we only compare MCNT to 0. */
5846 EXTRACT_NUMBER (mcnt, p + 2);
5847 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5849 /* Originally, this is how many times we CAN jump. */
5850 if (mcnt != 0)
5852 /* Here, we discard `const', making re_match non-reentrant. */
5853 unsigned char *p2 = (unsigned char *) p + 2; /* counter loc. */
5854 mcnt--;
5855 PUSH_NUMBER (p2, mcnt);
5856 goto unconditional_jump;
5858 /* If don't have to jump any more, skip over the rest of command. */
5859 else
5860 p += 4;
5861 break;
5863 case set_number_at:
5865 unsigned char *p2; /* Location of the counter. */
5866 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5868 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5869 /* Here, we discard `const', making re_match non-reentrant. */
5870 p2 = (unsigned char *) p + mcnt;
5871 /* Signedness doesn't matter since we only copy MCNT's bits. */
5872 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5873 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5874 PUSH_NUMBER (p2, mcnt);
5875 break;
5878 case wordbound:
5879 case notwordbound:
5881 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5882 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5884 /* We SUCCEED (or FAIL) in one of the following cases: */
5886 /* Case 1: D is at the beginning or the end of string. */
5887 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5888 not = !not;
5889 else
5891 /* C1 is the character before D, S1 is the syntax of C1, C2
5892 is the character at D, and S2 is the syntax of C2. */
5893 re_wchar_t c1, c2;
5894 int s1, s2;
5895 int dummy;
5896 #ifdef emacs
5897 ssize_t offset = PTR_TO_OFFSET (d - 1);
5898 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5899 UPDATE_SYNTAX_TABLE_FAST (charpos);
5900 #endif
5901 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5902 s1 = SYNTAX (c1);
5903 #ifdef emacs
5904 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
5905 #endif
5906 PREFETCH_NOLIMIT ();
5907 GET_CHAR_AFTER (c2, d, dummy);
5908 s2 = SYNTAX (c2);
5910 if (/* Case 2: Only one of S1 and S2 is Sword. */
5911 ((s1 == Sword) != (s2 == Sword))
5912 /* Case 3: Both of S1 and S2 are Sword, and macro
5913 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5914 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5915 not = !not;
5917 if (not)
5918 break;
5919 else
5920 goto fail;
5923 case wordbeg:
5924 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5926 /* We FAIL in one of the following cases: */
5928 /* Case 1: D is at the end of string. */
5929 if (AT_STRINGS_END (d))
5930 goto fail;
5931 else
5933 /* C1 is the character before D, S1 is the syntax of C1, C2
5934 is the character at D, and S2 is the syntax of C2. */
5935 re_wchar_t c1, c2;
5936 int s1, s2;
5937 int dummy;
5938 #ifdef emacs
5939 ssize_t offset = PTR_TO_OFFSET (d);
5940 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5941 UPDATE_SYNTAX_TABLE_FAST (charpos);
5942 #endif
5943 PREFETCH ();
5944 GET_CHAR_AFTER (c2, d, dummy);
5945 s2 = SYNTAX (c2);
5947 /* Case 2: S2 is not Sword. */
5948 if (s2 != Sword)
5949 goto fail;
5951 /* Case 3: D is not at the beginning of string ... */
5952 if (!AT_STRINGS_BEG (d))
5954 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5955 #ifdef emacs
5956 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5957 #endif
5958 s1 = SYNTAX (c1);
5960 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5961 returns 0. */
5962 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5963 goto fail;
5966 break;
5968 case wordend:
5969 DEBUG_PRINT ("EXECUTING wordend.\n");
5971 /* We FAIL in one of the following cases: */
5973 /* Case 1: D is at the beginning of string. */
5974 if (AT_STRINGS_BEG (d))
5975 goto fail;
5976 else
5978 /* C1 is the character before D, S1 is the syntax of C1, C2
5979 is the character at D, and S2 is the syntax of C2. */
5980 re_wchar_t c1, c2;
5981 int s1, s2;
5982 int dummy;
5983 #ifdef emacs
5984 ssize_t offset = PTR_TO_OFFSET (d) - 1;
5985 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5986 UPDATE_SYNTAX_TABLE_FAST (charpos);
5987 #endif
5988 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5989 s1 = SYNTAX (c1);
5991 /* Case 2: S1 is not Sword. */
5992 if (s1 != Sword)
5993 goto fail;
5995 /* Case 3: D is not at the end of string ... */
5996 if (!AT_STRINGS_END (d))
5998 PREFETCH_NOLIMIT ();
5999 GET_CHAR_AFTER (c2, d, dummy);
6000 #ifdef emacs
6001 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos);
6002 #endif
6003 s2 = SYNTAX (c2);
6005 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6006 returns 0. */
6007 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6008 goto fail;
6011 break;
6013 case symbeg:
6014 DEBUG_PRINT ("EXECUTING symbeg.\n");
6016 /* We FAIL in one of the following cases: */
6018 /* Case 1: D is at the end of string. */
6019 if (AT_STRINGS_END (d))
6020 goto fail;
6021 else
6023 /* C1 is the character before D, S1 is the syntax of C1, C2
6024 is the character at D, and S2 is the syntax of C2. */
6025 re_wchar_t c1, c2;
6026 int s1, s2;
6027 #ifdef emacs
6028 ssize_t offset = PTR_TO_OFFSET (d);
6029 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6030 UPDATE_SYNTAX_TABLE_FAST (charpos);
6031 #endif
6032 PREFETCH ();
6033 c2 = RE_STRING_CHAR (d, target_multibyte);
6034 s2 = SYNTAX (c2);
6036 /* Case 2: S2 is neither Sword nor Ssymbol. */
6037 if (s2 != Sword && s2 != Ssymbol)
6038 goto fail;
6040 /* Case 3: D is not at the beginning of string ... */
6041 if (!AT_STRINGS_BEG (d))
6043 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6044 #ifdef emacs
6045 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6046 #endif
6047 s1 = SYNTAX (c1);
6049 /* ... and S1 is Sword or Ssymbol. */
6050 if (s1 == Sword || s1 == Ssymbol)
6051 goto fail;
6054 break;
6056 case symend:
6057 DEBUG_PRINT ("EXECUTING symend.\n");
6059 /* We FAIL in one of the following cases: */
6061 /* Case 1: D is at the beginning of string. */
6062 if (AT_STRINGS_BEG (d))
6063 goto fail;
6064 else
6066 /* C1 is the character before D, S1 is the syntax of C1, C2
6067 is the character at D, and S2 is the syntax of C2. */
6068 re_wchar_t c1, c2;
6069 int s1, s2;
6070 #ifdef emacs
6071 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6072 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6073 UPDATE_SYNTAX_TABLE_FAST (charpos);
6074 #endif
6075 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6076 s1 = SYNTAX (c1);
6078 /* Case 2: S1 is neither Ssymbol nor Sword. */
6079 if (s1 != Sword && s1 != Ssymbol)
6080 goto fail;
6082 /* Case 3: D is not at the end of string ... */
6083 if (!AT_STRINGS_END (d))
6085 PREFETCH_NOLIMIT ();
6086 c2 = RE_STRING_CHAR (d, target_multibyte);
6087 #ifdef emacs
6088 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
6089 #endif
6090 s2 = SYNTAX (c2);
6092 /* ... and S2 is Sword or Ssymbol. */
6093 if (s2 == Sword || s2 == Ssymbol)
6094 goto fail;
6097 break;
6099 case syntaxspec:
6100 case notsyntaxspec:
6102 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6103 mcnt = *p++;
6104 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6105 mcnt);
6106 PREFETCH ();
6107 #ifdef emacs
6109 ssize_t offset = PTR_TO_OFFSET (d);
6110 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6111 UPDATE_SYNTAX_TABLE_FAST (pos1);
6113 #endif
6115 int len;
6116 re_wchar_t c;
6118 GET_CHAR_AFTER (c, d, len);
6119 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6120 goto fail;
6121 d += len;
6124 break;
6126 #ifdef emacs
6127 case at_dot:
6128 DEBUG_PRINT ("EXECUTING at_dot.\n");
6129 if (PTR_BYTE_POS (d) != PT_BYTE)
6130 goto fail;
6131 break;
6133 case categoryspec:
6134 case notcategoryspec:
6136 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6137 mcnt = *p++;
6138 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6139 not ? "not" : "", mcnt);
6140 PREFETCH ();
6143 int len;
6144 re_wchar_t c;
6145 GET_CHAR_AFTER (c, d, len);
6146 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6147 goto fail;
6148 d += len;
6151 break;
6153 #endif /* emacs */
6155 default:
6156 abort ();
6158 continue; /* Successfully executed one pattern command; keep going. */
6161 /* We goto here if a matching operation fails. */
6162 fail:
6163 maybe_quit ();
6164 if (!FAIL_STACK_EMPTY ())
6166 re_char *str, *pat;
6167 /* A restart point is known. Restore to that state. */
6168 DEBUG_PRINT ("\nFAIL:\n");
6169 POP_FAILURE_POINT (str, pat);
6170 switch (*pat++)
6172 case on_failure_keep_string_jump:
6173 assert (str == NULL);
6174 goto continue_failure_jump;
6176 case on_failure_jump_nastyloop:
6177 assert ((re_opcode_t)pat[-2] == no_op);
6178 PUSH_FAILURE_POINT (pat - 2, str);
6179 FALLTHROUGH;
6180 case on_failure_jump_loop:
6181 case on_failure_jump:
6182 case succeed_n:
6183 d = str;
6184 continue_failure_jump:
6185 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6186 p = pat + mcnt;
6187 break;
6189 case no_op:
6190 /* A special frame used for nastyloops. */
6191 goto fail;
6193 default:
6194 abort ();
6197 assert (p >= bufp->buffer && p <= pend);
6199 if (d >= string1 && d <= end1)
6200 dend = end_match_1;
6202 else
6203 break; /* Matching at this starting point really fails. */
6204 } /* for (;;) */
6206 if (best_regs_set)
6207 goto restore_best_regs;
6209 FREE_VARIABLES ();
6211 return -1; /* Failure to match. */
6214 /* Subroutine definitions for re_match_2. */
6216 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6217 bytes; nonzero otherwise. */
6219 static int
6220 bcmp_translate (re_char *s1, re_char *s2, ssize_t len,
6221 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6223 re_char *p1 = s1, *p2 = s2;
6224 re_char *p1_end = s1 + len;
6225 re_char *p2_end = s2 + len;
6227 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6228 different lengths, but relying on a single `len' would break this. -sm */
6229 while (p1 < p1_end && p2 < p2_end)
6231 int p1_charlen, p2_charlen;
6232 re_wchar_t p1_ch, p2_ch;
6234 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6235 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6237 if (RE_TRANSLATE (translate, p1_ch)
6238 != RE_TRANSLATE (translate, p2_ch))
6239 return 1;
6241 p1 += p1_charlen, p2 += p2_charlen;
6244 if (p1 != p1_end || p2 != p2_end)
6245 return 1;
6247 return 0;
6250 /* Entry points for GNU code. */
6252 /* re_compile_pattern is the GNU regular expression compiler: it
6253 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6254 Returns 0 if the pattern was valid, otherwise an error string.
6256 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6257 are set in BUFP on entry.
6259 We call regex_compile to do the actual compilation. */
6261 const char *
6262 re_compile_pattern (const char *pattern, size_t length,
6263 #ifdef emacs
6264 bool posix_backtracking, const char *whitespace_regexp,
6265 #endif
6266 struct re_pattern_buffer *bufp)
6268 reg_errcode_t ret;
6270 /* GNU code is written to assume at least RE_NREGS registers will be set
6271 (and at least one extra will be -1). */
6272 bufp->regs_allocated = REGS_UNALLOCATED;
6274 /* And GNU code determines whether or not to get register information
6275 by passing null for the REGS argument to re_match, etc., not by
6276 setting no_sub. */
6277 bufp->no_sub = 0;
6279 ret = regex_compile ((re_char *) pattern, length,
6280 #ifdef emacs
6281 posix_backtracking,
6282 whitespace_regexp,
6283 #else
6284 re_syntax_options,
6285 #endif
6286 bufp);
6288 if (!ret)
6289 return NULL;
6290 return gettext (re_error_msgid[(int) ret]);
6292 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6294 /* Entry points compatible with 4.2 BSD regex library. We don't define
6295 them unless specifically requested. */
6297 #if defined _REGEX_RE_COMP || defined _LIBC
6299 /* BSD has one and only one pattern buffer. */
6300 static struct re_pattern_buffer re_comp_buf;
6302 char *
6303 # ifdef _LIBC
6304 /* Make these definitions weak in libc, so POSIX programs can redefine
6305 these names if they don't use our functions, and still use
6306 regcomp/regexec below without link errors. */
6307 weak_function
6308 # endif
6309 re_comp (const char *s)
6311 reg_errcode_t ret;
6313 if (!s)
6315 if (!re_comp_buf.buffer)
6316 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6317 return (char *) gettext ("No previous regular expression");
6318 return 0;
6321 if (!re_comp_buf.buffer)
6323 re_comp_buf.buffer = malloc (200);
6324 if (re_comp_buf.buffer == NULL)
6325 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6326 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6327 re_comp_buf.allocated = 200;
6329 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6330 if (re_comp_buf.fastmap == NULL)
6331 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6332 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6335 /* Since `re_exec' always passes NULL for the `regs' argument, we
6336 don't need to initialize the pattern buffer fields which affect it. */
6338 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6340 if (!ret)
6341 return NULL;
6343 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6344 return (char *) gettext (re_error_msgid[(int) ret]);
6349 # ifdef _LIBC
6350 weak_function
6351 # endif
6352 re_exec (const char *s)
6354 const size_t len = strlen (s);
6355 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6357 #endif /* _REGEX_RE_COMP */
6359 /* POSIX.2 functions. Don't define these for Emacs. */
6361 #ifndef emacs
6363 /* regcomp takes a regular expression as a string and compiles it.
6365 PREG is a regex_t *. We do not expect any fields to be initialized,
6366 since POSIX says we shouldn't. Thus, we set
6368 `buffer' to the compiled pattern;
6369 `used' to the length of the compiled pattern;
6370 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6371 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6372 RE_SYNTAX_POSIX_BASIC;
6373 `fastmap' to an allocated space for the fastmap;
6374 `fastmap_accurate' to zero;
6375 `re_nsub' to the number of subexpressions in PATTERN.
6377 PATTERN is the address of the pattern string.
6379 CFLAGS is a series of bits which affect compilation.
6381 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6382 use POSIX basic syntax.
6384 If REG_NEWLINE is set, then . and [^...] don't match newline.
6385 Also, regexec will try a match beginning after every newline.
6387 If REG_ICASE is set, then we considers upper- and lowercase
6388 versions of letters to be equivalent when matching.
6390 If REG_NOSUB is set, then when PREG is passed to regexec, that
6391 routine will report only success or failure, and nothing about the
6392 registers.
6394 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6395 the return codes and their meanings.) */
6397 reg_errcode_t
6398 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6399 int cflags)
6401 reg_errcode_t ret;
6402 reg_syntax_t syntax
6403 = (cflags & REG_EXTENDED) ?
6404 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6406 /* regex_compile will allocate the space for the compiled pattern. */
6407 preg->buffer = 0;
6408 preg->allocated = 0;
6409 preg->used = 0;
6411 /* Try to allocate space for the fastmap. */
6412 preg->fastmap = malloc (1 << BYTEWIDTH);
6414 if (cflags & REG_ICASE)
6416 unsigned i;
6418 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6419 if (preg->translate == NULL)
6420 return (int) REG_ESPACE;
6422 /* Map uppercase characters to corresponding lowercase ones. */
6423 for (i = 0; i < CHAR_SET_SIZE; i++)
6424 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6426 else
6427 preg->translate = NULL;
6429 /* If REG_NEWLINE is set, newlines are treated differently. */
6430 if (cflags & REG_NEWLINE)
6431 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6432 syntax &= ~RE_DOT_NEWLINE;
6433 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6435 else
6436 syntax |= RE_NO_NEWLINE_ANCHOR;
6438 preg->no_sub = !!(cflags & REG_NOSUB);
6440 /* POSIX says a null character in the pattern terminates it, so we
6441 can use strlen here in compiling the pattern. */
6442 ret = regex_compile ((re_char *) pattern, strlen (pattern), syntax, preg);
6444 /* POSIX doesn't distinguish between an unmatched open-group and an
6445 unmatched close-group: both are REG_EPAREN. */
6446 if (ret == REG_ERPAREN)
6447 ret = REG_EPAREN;
6449 if (ret == REG_NOERROR && preg->fastmap)
6450 { /* Compute the fastmap now, since regexec cannot modify the pattern
6451 buffer. */
6452 re_compile_fastmap (preg);
6453 if (preg->can_be_null)
6454 { /* The fastmap can't be used anyway. */
6455 free (preg->fastmap);
6456 preg->fastmap = NULL;
6459 return ret;
6461 WEAK_ALIAS (__regcomp, regcomp)
6464 /* regexec searches for a given pattern, specified by PREG, in the
6465 string STRING.
6467 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6468 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6469 least NMATCH elements, and we set them to the offsets of the
6470 corresponding matched substrings.
6472 EFLAGS specifies `execution flags' which affect matching: if
6473 REG_NOTBOL is set, then ^ does not match at the beginning of the
6474 string; if REG_NOTEOL is set, then $ does not match at the end.
6476 We return 0 if we find a match and REG_NOMATCH if not. */
6478 reg_errcode_t
6479 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6480 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6482 regoff_t ret;
6483 struct re_registers regs;
6484 regex_t private_preg;
6485 size_t len = strlen (string);
6486 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6488 private_preg = *preg;
6490 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6491 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6493 /* The user has told us exactly how many registers to return
6494 information about, via `nmatch'. We have to pass that on to the
6495 matching routines. */
6496 private_preg.regs_allocated = REGS_FIXED;
6498 if (want_reg_info)
6500 regs.num_regs = nmatch;
6501 regs.start = TALLOC (nmatch * 2, regoff_t);
6502 if (regs.start == NULL)
6503 return REG_NOMATCH;
6504 regs.end = regs.start + nmatch;
6507 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6508 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6509 was a little bit longer but still only matching the real part.
6510 This works because the `endline' will check for a '\n' and will find a
6511 '\0', correctly deciding that this is not the end of a line.
6512 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6513 a convenient '\0' there. For all we know, the string could be preceded
6514 by '\n' which would throw things off. */
6516 /* Perform the searching operation. */
6517 ret = re_search (&private_preg, string, len,
6518 /* start: */ 0, /* range: */ len,
6519 want_reg_info ? &regs : 0);
6521 /* Copy the register information to the POSIX structure. */
6522 if (want_reg_info)
6524 if (ret >= 0)
6526 unsigned r;
6528 for (r = 0; r < nmatch; r++)
6530 pmatch[r].rm_so = regs.start[r];
6531 pmatch[r].rm_eo = regs.end[r];
6535 /* If we needed the temporary register info, free the space now. */
6536 free (regs.start);
6539 /* We want zero return to mean success, unlike `re_search'. */
6540 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6542 WEAK_ALIAS (__regexec, regexec)
6545 /* Returns a message corresponding to an error code, ERR_CODE, returned
6546 from either regcomp or regexec. We don't use PREG here.
6548 ERR_CODE was previously called ERRCODE, but that name causes an
6549 error with msvc8 compiler. */
6551 size_t
6552 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6554 const char *msg;
6555 size_t msg_size;
6557 if (err_code < 0
6558 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6559 /* Only error codes returned by the rest of the code should be passed
6560 to this routine. If we are given anything else, or if other regex
6561 code generates an invalid error code, then the program has a bug.
6562 Dump core so we can fix it. */
6563 abort ();
6565 msg = gettext (re_error_msgid[err_code]);
6567 msg_size = strlen (msg) + 1; /* Includes the null. */
6569 if (errbuf_size != 0)
6571 if (msg_size > errbuf_size)
6573 memcpy (errbuf, msg, errbuf_size - 1);
6574 errbuf[errbuf_size - 1] = 0;
6576 else
6577 strcpy (errbuf, msg);
6580 return msg_size;
6582 WEAK_ALIAS (__regerror, regerror)
6585 /* Free dynamically allocated space used by PREG. */
6587 void
6588 regfree (regex_t *preg)
6590 free (preg->buffer);
6591 preg->buffer = NULL;
6593 preg->allocated = 0;
6594 preg->used = 0;
6596 free (preg->fastmap);
6597 preg->fastmap = NULL;
6598 preg->fastmap_accurate = 0;
6600 free (preg->translate);
6601 preg->translate = NULL;
6603 WEAK_ALIAS (__regfree, regfree)
6605 #endif /* not emacs */