gamegrid-add-score-with-update-game-score fix
[emacs.git] / src / regex.c
blob051a4fdc26b86895bcffe0db767e3e78564b059d
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-2013 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* TODO:
21 - structure the opcode space into opcode+flag.
22 - merge with glibc's regex.[ch].
23 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
24 need to modify the compiled regexp so that re_match can be reentrant.
25 - get rid of on_failure_jump_smart by doing the optimization in re_comp
26 rather than at run-time, so that re_match can be reentrant.
29 /* AIX requires this to be the first thing in the file. */
30 #if defined _AIX && !defined REGEX_MALLOC
31 #pragma alloca
32 #endif
34 /* Ignore some GCC warnings for now. This section should go away
35 once the Emacs and Gnulib regex code is merged. */
36 #if (__GNUC__ == 4 && 5 <= __GNUC_MINOR__) || 4 < __GNUC__
37 # pragma GCC diagnostic ignored "-Wstrict-overflow"
38 # ifndef emacs
39 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
40 # pragma GCC diagnostic ignored "-Wunused-function"
41 # pragma GCC diagnostic ignored "-Wunused-macros"
42 # pragma GCC diagnostic ignored "-Wunused-result"
43 # pragma GCC diagnostic ignored "-Wunused-variable"
44 # endif
45 #endif
47 #include <config.h>
49 #include <stddef.h>
51 #ifdef emacs
52 /* We need this for `regex.h', and perhaps for the Emacs include files. */
53 # include <sys/types.h>
54 #endif
56 /* Whether to use ISO C Amendment 1 wide char functions.
57 Those should not be used for Emacs since it uses its own. */
58 #if defined _LIBC
59 #define WIDE_CHAR_SUPPORT 1
60 #else
61 #define WIDE_CHAR_SUPPORT \
62 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
63 #endif
65 /* For platform which support the ISO C amendment 1 functionality we
66 support user defined character classes. */
67 #if WIDE_CHAR_SUPPORT
68 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
69 # include <wchar.h>
70 # include <wctype.h>
71 #endif
73 #ifdef _LIBC
74 /* We have to keep the namespace clean. */
75 # define regfree(preg) __regfree (preg)
76 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
77 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
78 # define regerror(err_code, preg, errbuf, errbuf_size) \
79 __regerror (err_code, preg, errbuf, errbuf_size)
80 # define re_set_registers(bu, re, nu, st, en) \
81 __re_set_registers (bu, re, nu, st, en)
82 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
83 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
84 # define re_match(bufp, string, size, pos, regs) \
85 __re_match (bufp, string, size, pos, regs)
86 # define re_search(bufp, string, size, startpos, range, regs) \
87 __re_search (bufp, string, size, startpos, range, regs)
88 # define re_compile_pattern(pattern, length, bufp) \
89 __re_compile_pattern (pattern, length, bufp)
90 # define re_set_syntax(syntax) __re_set_syntax (syntax)
91 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
92 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
93 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
95 /* Make sure we call libc's function even if the user overrides them. */
96 # define btowc __btowc
97 # define iswctype __iswctype
98 # define wctype __wctype
100 # define WEAK_ALIAS(a,b) weak_alias (a, b)
102 /* We are also using some library internals. */
103 # include <locale/localeinfo.h>
104 # include <locale/elem-hash.h>
105 # include <langinfo.h>
106 #else
107 # define WEAK_ALIAS(a,b)
108 #endif
110 /* This is for other GNU distributions with internationalized messages. */
111 #if HAVE_LIBINTL_H || defined _LIBC
112 # include <libintl.h>
113 #else
114 # define gettext(msgid) (msgid)
115 #endif
117 #ifndef gettext_noop
118 /* This define is so xgettext can find the internationalizable
119 strings. */
120 # define gettext_noop(String) String
121 #endif
123 /* The `emacs' switch turns on certain matching commands
124 that make sense only in Emacs. */
125 #ifdef emacs
127 # include "lisp.h"
128 # include "character.h"
129 # include "buffer.h"
131 /* Make syntax table lookup grant data in gl_state. */
132 # define SYNTAX_ENTRY_VIA_PROPERTY
134 # include "syntax.h"
135 # include "category.h"
137 # ifdef malloc
138 # undef malloc
139 # endif
140 # define malloc xmalloc
141 # ifdef realloc
142 # undef realloc
143 # endif
144 # define realloc xrealloc
145 # ifdef free
146 # undef free
147 # endif
148 # define free xfree
150 /* Converts the pointer to the char to BEG-based offset from the start. */
151 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
152 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
154 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
155 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
156 # define RE_STRING_CHAR(p, multibyte) \
157 (multibyte ? (STRING_CHAR (p)) : (*(p)))
158 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
159 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
161 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
163 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
165 /* Set C a (possibly converted to multibyte) character before P. P
166 points into a string which is the virtual concatenation of STR1
167 (which ends at END1) or STR2 (which ends at END2). */
168 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
169 do { \
170 if (target_multibyte) \
172 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
173 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
174 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
175 c = STRING_CHAR (dtemp); \
177 else \
179 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
180 (c) = RE_CHAR_TO_MULTIBYTE (c); \
182 } while (0)
184 /* Set C a (possibly converted to multibyte) character at P, and set
185 LEN to the byte length of that character. */
186 # define GET_CHAR_AFTER(c, p, len) \
187 do { \
188 if (target_multibyte) \
189 (c) = STRING_CHAR_AND_LENGTH (p, len); \
190 else \
192 (c) = *p; \
193 len = 1; \
194 (c) = RE_CHAR_TO_MULTIBYTE (c); \
196 } while (0)
198 #else /* not emacs */
200 /* If we are not linking with Emacs proper,
201 we can't use the relocating allocator
202 even if config.h says that we can. */
203 # undef REL_ALLOC
205 # include <unistd.h>
207 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
209 static void *
210 xmalloc (size_t size)
212 void *val = malloc (size);
213 if (!val && size)
215 write (2, "virtual memory exhausted\n", 25);
216 exit (1);
218 return val;
221 static void *
222 xrealloc (void *block, size_t size)
224 void *val;
225 /* We must call malloc explicitly when BLOCK is 0, since some
226 reallocs don't do this. */
227 if (! block)
228 val = malloc (size);
229 else
230 val = realloc (block, size);
231 if (!val && size)
233 write (2, "virtual memory exhausted\n", 25);
234 exit (1);
236 return val;
239 # ifdef malloc
240 # undef malloc
241 # endif
242 # define malloc xmalloc
243 # ifdef realloc
244 # undef realloc
245 # endif
246 # define realloc xrealloc
248 # include <stdbool.h>
249 # include <string.h>
251 /* Define the syntax stuff for \<, \>, etc. */
253 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
254 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
256 /* Dummy macros for non-Emacs environments. */
257 # define CHAR_CHARSET(c) 0
258 # define CHARSET_LEADING_CODE_BASE(c) 0
259 # define MAX_MULTIBYTE_LENGTH 1
260 # define RE_MULTIBYTE_P(x) 0
261 # define RE_TARGET_MULTIBYTE_P(x) 0
262 # define WORD_BOUNDARY_P(c1, c2) (0)
263 # define CHAR_HEAD_P(p) (1)
264 # define SINGLE_BYTE_CHAR_P(c) (1)
265 # define SAME_CHARSET_P(c1, c2) (1)
266 # define BYTES_BY_CHAR_HEAD(p) (1)
267 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
268 # define STRING_CHAR(p) (*(p))
269 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
270 # define CHAR_STRING(c, s) (*(s) = (c), 1)
271 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
272 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
273 # define RE_CHAR_TO_MULTIBYTE(c) (c)
274 # define RE_CHAR_TO_UNIBYTE(c) (c)
275 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
276 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
277 # define GET_CHAR_AFTER(c, p, len) \
278 (c = *p, len = 1)
279 # define MAKE_CHAR(charset, c1, c2) (c1)
280 # define BYTE8_TO_CHAR(c) (c)
281 # define CHAR_BYTE8_P(c) (0)
282 # define CHAR_LEADING_CODE(c) (c)
284 #endif /* not emacs */
286 #ifndef RE_TRANSLATE
287 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
288 # define RE_TRANSLATE_P(TBL) (TBL)
289 #endif
291 /* Get the interface, including the syntax bits. */
292 #include "regex.h"
294 /* isalpha etc. are used for the character classes. */
295 #include <ctype.h>
297 #ifdef emacs
299 /* 1 if C is an ASCII character. */
300 # define IS_REAL_ASCII(c) ((c) < 0200)
302 /* 1 if C is a unibyte character. */
303 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
305 /* The Emacs definitions should not be directly affected by locales. */
307 /* In Emacs, these are only used for single-byte characters. */
308 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
309 # define ISCNTRL(c) ((c) < ' ')
310 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
311 || ((c) >= 'a' && (c) <= 'f') \
312 || ((c) >= 'A' && (c) <= 'F'))
314 /* This is only used for single-byte characters. */
315 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
317 /* The rest must handle multibyte characters. */
319 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
320 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
321 : 1)
323 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
324 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
325 : 1)
327 # define ISALNUM(c) (IS_REAL_ASCII (c) \
328 ? (((c) >= 'a' && (c) <= 'z') \
329 || ((c) >= 'A' && (c) <= 'Z') \
330 || ((c) >= '0' && (c) <= '9')) \
331 : SYNTAX (c) == Sword)
333 # define ISALPHA(c) (IS_REAL_ASCII (c) \
334 ? (((c) >= 'a' && (c) <= 'z') \
335 || ((c) >= 'A' && (c) <= 'Z')) \
336 : SYNTAX (c) == Sword)
338 # define ISLOWER(c) lowercasep (c)
340 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
341 ? ((c) > ' ' && (c) < 0177 \
342 && !(((c) >= 'a' && (c) <= 'z') \
343 || ((c) >= 'A' && (c) <= 'Z') \
344 || ((c) >= '0' && (c) <= '9'))) \
345 : SYNTAX (c) != Sword)
347 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
349 # define ISUPPER(c) uppercasep (c)
351 # define ISWORD(c) (SYNTAX (c) == Sword)
353 #else /* not emacs */
355 /* 1 if C is an ASCII character. */
356 # define IS_REAL_ASCII(c) ((c) < 0200)
358 /* This distinction is not meaningful, except in Emacs. */
359 # define ISUNIBYTE(c) 1
361 # ifdef isblank
362 # define ISBLANK(c) isblank (c)
363 # else
364 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
365 # endif
366 # ifdef isgraph
367 # define ISGRAPH(c) isgraph (c)
368 # else
369 # define ISGRAPH(c) (isprint (c) && !isspace (c))
370 # endif
372 /* Solaris defines ISPRINT so we must undefine it first. */
373 # undef ISPRINT
374 # define ISPRINT(c) isprint (c)
375 # define ISDIGIT(c) isdigit (c)
376 # define ISALNUM(c) isalnum (c)
377 # define ISALPHA(c) isalpha (c)
378 # define ISCNTRL(c) iscntrl (c)
379 # define ISLOWER(c) islower (c)
380 # define ISPUNCT(c) ispunct (c)
381 # define ISSPACE(c) isspace (c)
382 # define ISUPPER(c) isupper (c)
383 # define ISXDIGIT(c) isxdigit (c)
385 # define ISWORD(c) ISALPHA (c)
387 # ifdef _tolower
388 # define TOLOWER(c) _tolower (c)
389 # else
390 # define TOLOWER(c) tolower (c)
391 # endif
393 /* How many characters in the character set. */
394 # define CHAR_SET_SIZE 256
396 # ifdef SYNTAX_TABLE
398 extern char *re_syntax_table;
400 # else /* not SYNTAX_TABLE */
402 static char re_syntax_table[CHAR_SET_SIZE];
404 static void
405 init_syntax_once (void)
407 register int c;
408 static int done = 0;
410 if (done)
411 return;
413 memset (re_syntax_table, 0, sizeof re_syntax_table);
415 for (c = 0; c < CHAR_SET_SIZE; ++c)
416 if (ISALNUM (c))
417 re_syntax_table[c] = Sword;
419 re_syntax_table['_'] = Ssymbol;
421 done = 1;
424 # endif /* not SYNTAX_TABLE */
426 # define SYNTAX(c) re_syntax_table[(c)]
428 #endif /* not emacs */
430 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
432 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
433 use `alloca' instead of `malloc'. This is because using malloc in
434 re_search* or re_match* could cause memory leaks when C-g is used in
435 Emacs; also, malloc is slower and causes storage fragmentation. On
436 the other hand, malloc is more portable, and easier to debug.
438 Because we sometimes use alloca, some routines have to be macros,
439 not functions -- `alloca'-allocated space disappears at the end of the
440 function it is called in. */
442 #ifdef REGEX_MALLOC
444 # define REGEX_ALLOCATE malloc
445 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
446 # define REGEX_FREE free
448 #else /* not REGEX_MALLOC */
450 /* Emacs already defines alloca, sometimes. */
451 # ifndef alloca
453 /* Make alloca work the best possible way. */
454 # ifdef __GNUC__
455 # define alloca __builtin_alloca
456 # else /* not __GNUC__ */
457 # ifdef HAVE_ALLOCA_H
458 # include <alloca.h>
459 # endif /* HAVE_ALLOCA_H */
460 # endif /* not __GNUC__ */
462 # endif /* not alloca */
464 # define REGEX_ALLOCATE alloca
466 /* Assumes a `char *destination' variable. */
467 # define REGEX_REALLOCATE(source, osize, nsize) \
468 (destination = (char *) alloca (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 /* Define how to allocate the failure stack. */
478 #if defined REL_ALLOC && defined REGEX_MALLOC
480 # define REGEX_ALLOCATE_STACK(size) \
481 r_alloc (&failure_stack_ptr, (size))
482 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
483 r_re_alloc (&failure_stack_ptr, (nsize))
484 # define REGEX_FREE_STACK(ptr) \
485 r_alloc_free (&failure_stack_ptr)
487 #else /* not using relocating allocator */
489 # ifdef REGEX_MALLOC
491 # define REGEX_ALLOCATE_STACK malloc
492 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
493 # define REGEX_FREE_STACK free
495 # else /* not REGEX_MALLOC */
497 # define REGEX_ALLOCATE_STACK alloca
499 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
500 REGEX_REALLOCATE (source, osize, nsize)
501 /* No need to explicitly free anything. */
502 # define REGEX_FREE_STACK(arg) ((void)0)
504 # endif /* not REGEX_MALLOC */
505 #endif /* not using relocating allocator */
508 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
509 `string1' or just past its end. This works if PTR is NULL, which is
510 a good thing. */
511 #define FIRST_STRING_P(ptr) \
512 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
514 /* (Re)Allocate N items of type T using malloc, or fail. */
515 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
516 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
517 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
519 #define BYTEWIDTH 8 /* In bits. */
521 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
523 #undef MAX
524 #undef MIN
525 #define MAX(a, b) ((a) > (b) ? (a) : (b))
526 #define MIN(a, b) ((a) < (b) ? (a) : (b))
528 /* Type of source-pattern and string chars. */
529 #ifdef _MSC_VER
530 typedef unsigned char re_char;
531 #else
532 typedef const unsigned char re_char;
533 #endif
535 typedef char boolean;
537 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
538 re_char *string1, size_t size1,
539 re_char *string2, size_t size2,
540 ssize_t pos,
541 struct re_registers *regs,
542 ssize_t stop);
544 /* These are the command codes that appear in compiled regular
545 expressions. Some opcodes are followed by argument bytes. A
546 command code can specify any interpretation whatsoever for its
547 arguments. Zero bytes may appear in the compiled regular expression. */
549 typedef enum
551 no_op = 0,
553 /* Succeed right away--no more backtracking. */
554 succeed,
556 /* Followed by one byte giving n, then by n literal bytes. */
557 exactn,
559 /* Matches any (more or less) character. */
560 anychar,
562 /* Matches any one char belonging to specified set. First
563 following byte is number of bitmap bytes. Then come bytes
564 for a bitmap saying which chars are in. Bits in each byte
565 are ordered low-bit-first. A character is in the set if its
566 bit is 1. A character too large to have a bit in the map is
567 automatically not in the set.
569 If the length byte has the 0x80 bit set, then that stuff
570 is followed by a range table:
571 2 bytes of flags for character sets (low 8 bits, high 8 bits)
572 See RANGE_TABLE_WORK_BITS below.
573 2 bytes, the number of pairs that follow (upto 32767)
574 pairs, each 2 multibyte characters,
575 each multibyte character represented as 3 bytes. */
576 charset,
578 /* Same parameters as charset, but match any character that is
579 not one of those specified. */
580 charset_not,
582 /* Start remembering the text that is matched, for storing in a
583 register. Followed by one byte with the register number, in
584 the range 0 to one less than the pattern buffer's re_nsub
585 field. */
586 start_memory,
588 /* Stop remembering the text that is matched and store it in a
589 memory register. Followed by one byte with the register
590 number, in the range 0 to one less than `re_nsub' in the
591 pattern buffer. */
592 stop_memory,
594 /* Match a duplicate of something remembered. Followed by one
595 byte containing the register number. */
596 duplicate,
598 /* Fail unless at beginning of line. */
599 begline,
601 /* Fail unless at end of line. */
602 endline,
604 /* Succeeds if at beginning of buffer (if emacs) or at beginning
605 of string to be matched (if not). */
606 begbuf,
608 /* Analogously, for end of buffer/string. */
609 endbuf,
611 /* Followed by two byte relative address to which to jump. */
612 jump,
614 /* Followed by two-byte relative address of place to resume at
615 in case of failure. */
616 on_failure_jump,
618 /* Like on_failure_jump, but pushes a placeholder instead of the
619 current string position when executed. */
620 on_failure_keep_string_jump,
622 /* Just like `on_failure_jump', except that it checks that we
623 don't get stuck in an infinite loop (matching an empty string
624 indefinitely). */
625 on_failure_jump_loop,
627 /* Just like `on_failure_jump_loop', except that it checks for
628 a different kind of loop (the kind that shows up with non-greedy
629 operators). This operation has to be immediately preceded
630 by a `no_op'. */
631 on_failure_jump_nastyloop,
633 /* A smart `on_failure_jump' used for greedy * and + operators.
634 It analyzes the loop before which it is put and if the
635 loop does not require backtracking, it changes itself to
636 `on_failure_keep_string_jump' and short-circuits the loop,
637 else it just defaults to changing itself into `on_failure_jump'.
638 It assumes that it is pointing to just past a `jump'. */
639 on_failure_jump_smart,
641 /* Followed by two-byte relative address and two-byte number n.
642 After matching N times, jump to the address upon failure.
643 Does not work if N starts at 0: use on_failure_jump_loop
644 instead. */
645 succeed_n,
647 /* Followed by two-byte relative address, and two-byte number n.
648 Jump to the address N times, then fail. */
649 jump_n,
651 /* Set the following two-byte relative address to the
652 subsequent two-byte number. The address *includes* the two
653 bytes of number. */
654 set_number_at,
656 wordbeg, /* Succeeds if at word beginning. */
657 wordend, /* Succeeds if at word end. */
659 wordbound, /* Succeeds if at a word boundary. */
660 notwordbound, /* Succeeds if not at a word boundary. */
662 symbeg, /* Succeeds if at symbol beginning. */
663 symend, /* Succeeds if at symbol end. */
665 /* Matches any character whose syntax is specified. Followed by
666 a byte which contains a syntax code, e.g., Sword. */
667 syntaxspec,
669 /* Matches any character whose syntax is not that specified. */
670 notsyntaxspec
672 #ifdef emacs
673 ,before_dot, /* Succeeds if before point. */
674 at_dot, /* Succeeds if at point. */
675 after_dot, /* Succeeds if after point. */
677 /* Matches any character whose category-set contains the specified
678 category. The operator is followed by a byte which contains a
679 category code (mnemonic ASCII character). */
680 categoryspec,
682 /* Matches any character whose category-set does not contain the
683 specified category. The operator is followed by a byte which
684 contains the category code (mnemonic ASCII character). */
685 notcategoryspec
686 #endif /* emacs */
687 } re_opcode_t;
689 /* Common operations on the compiled pattern. */
691 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
693 #define STORE_NUMBER(destination, number) \
694 do { \
695 (destination)[0] = (number) & 0377; \
696 (destination)[1] = (number) >> 8; \
697 } while (0)
699 /* Same as STORE_NUMBER, except increment DESTINATION to
700 the byte after where the number is stored. Therefore, DESTINATION
701 must be an lvalue. */
703 #define STORE_NUMBER_AND_INCR(destination, number) \
704 do { \
705 STORE_NUMBER (destination, number); \
706 (destination) += 2; \
707 } while (0)
709 /* Put into DESTINATION a number stored in two contiguous bytes starting
710 at SOURCE. */
712 #define EXTRACT_NUMBER(destination, source) \
713 do { \
714 (destination) = *(source) & 0377; \
715 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
716 } while (0)
718 #ifdef DEBUG
719 static void
720 extract_number (int *dest, re_char *source)
722 int temp = SIGN_EXTEND_CHAR (*(source + 1));
723 *dest = *source & 0377;
724 *dest += temp << 8;
727 # ifndef EXTRACT_MACROS /* To debug the macros. */
728 # undef EXTRACT_NUMBER
729 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
730 # endif /* not EXTRACT_MACROS */
732 #endif /* DEBUG */
734 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
735 SOURCE must be an lvalue. */
737 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
738 do { \
739 EXTRACT_NUMBER (destination, source); \
740 (source) += 2; \
741 } while (0)
743 #ifdef DEBUG
744 static void
745 extract_number_and_incr (int *destination, re_char **source)
747 extract_number (destination, *source);
748 *source += 2;
751 # ifndef EXTRACT_MACROS
752 # undef EXTRACT_NUMBER_AND_INCR
753 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
754 extract_number_and_incr (&dest, &src)
755 # endif /* not EXTRACT_MACROS */
757 #endif /* DEBUG */
759 /* Store a multibyte character in three contiguous bytes starting
760 DESTINATION, and increment DESTINATION to the byte after where the
761 character is stored. Therefore, DESTINATION must be an lvalue. */
763 #define STORE_CHARACTER_AND_INCR(destination, character) \
764 do { \
765 (destination)[0] = (character) & 0377; \
766 (destination)[1] = ((character) >> 8) & 0377; \
767 (destination)[2] = (character) >> 16; \
768 (destination) += 3; \
769 } while (0)
771 /* Put into DESTINATION a character stored in three contiguous bytes
772 starting at SOURCE. */
774 #define EXTRACT_CHARACTER(destination, source) \
775 do { \
776 (destination) = ((source)[0] \
777 | ((source)[1] << 8) \
778 | ((source)[2] << 16)); \
779 } while (0)
782 /* Macros for charset. */
784 /* Size of bitmap of charset P in bytes. P is a start of charset,
785 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
786 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
788 /* Nonzero if charset P has range table. */
789 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
791 /* Return the address of range table of charset P. But not the start
792 of table itself, but the before where the number of ranges is
793 stored. `2 +' means to skip re_opcode_t and size of bitmap,
794 and the 2 bytes of flags at the start of the range table. */
795 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
797 /* Extract the bit flags that start a range table. */
798 #define CHARSET_RANGE_TABLE_BITS(p) \
799 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
800 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
802 /* Return the address of end of RANGE_TABLE. COUNT is number of
803 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
804 is start of range and end of range. `* 3' is size of each start
805 and end. */
806 #define CHARSET_RANGE_TABLE_END(range_table, count) \
807 ((range_table) + (count) * 2 * 3)
809 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
810 COUNT is number of ranges in RANGE_TABLE. */
811 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
812 do \
814 re_wchar_t range_start, range_end; \
815 re_char *rtp; \
816 re_char *range_table_end \
817 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
819 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
821 EXTRACT_CHARACTER (range_start, rtp); \
822 EXTRACT_CHARACTER (range_end, rtp + 3); \
824 if (range_start <= (c) && (c) <= range_end) \
826 (not) = !(not); \
827 break; \
831 while (0)
833 /* Test if C is in range table of CHARSET. The flag NOT is negated if
834 C is listed in it. */
835 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
836 do \
838 /* Number of ranges in range table. */ \
839 int count; \
840 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
842 EXTRACT_NUMBER_AND_INCR (count, range_table); \
843 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
845 while (0)
847 /* If DEBUG is defined, Regex prints many voluminous messages about what
848 it is doing (if the variable `debug' is nonzero). If linked with the
849 main program in `iregex.c', you can enter patterns and strings
850 interactively. And if linked with the main program in `main.c' and
851 the other test files, you can run the already-written tests. */
853 #ifdef DEBUG
855 /* We use standard I/O for debugging. */
856 # include <stdio.h>
858 /* It is useful to test things that ``must'' be true when debugging. */
859 # include <assert.h>
861 static int debug = -100000;
863 # define DEBUG_STATEMENT(e) e
864 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
865 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
866 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
867 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
868 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
869 if (debug > 0) print_partial_compiled_pattern (s, e)
870 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
871 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
874 /* Print the fastmap in human-readable form. */
876 void
877 print_fastmap (fastmap)
878 char *fastmap;
880 unsigned was_a_range = 0;
881 unsigned i = 0;
883 while (i < (1 << BYTEWIDTH))
885 if (fastmap[i++])
887 was_a_range = 0;
888 putchar (i - 1);
889 while (i < (1 << BYTEWIDTH) && fastmap[i])
891 was_a_range = 1;
892 i++;
894 if (was_a_range)
896 printf ("-");
897 putchar (i - 1);
901 putchar ('\n');
905 /* Print a compiled pattern string in human-readable form, starting at
906 the START pointer into it and ending just before the pointer END. */
908 void
909 print_partial_compiled_pattern (start, end)
910 re_char *start;
911 re_char *end;
913 int mcnt, mcnt2;
914 re_char *p = start;
915 re_char *pend = end;
917 if (start == NULL)
919 fprintf (stderr, "(null)\n");
920 return;
923 /* Loop over pattern commands. */
924 while (p < pend)
926 fprintf (stderr, "%d:\t", p - start);
928 switch ((re_opcode_t) *p++)
930 case no_op:
931 fprintf (stderr, "/no_op");
932 break;
934 case succeed:
935 fprintf (stderr, "/succeed");
936 break;
938 case exactn:
939 mcnt = *p++;
940 fprintf (stderr, "/exactn/%d", mcnt);
943 fprintf (stderr, "/%c", *p++);
945 while (--mcnt);
946 break;
948 case start_memory:
949 fprintf (stderr, "/start_memory/%d", *p++);
950 break;
952 case stop_memory:
953 fprintf (stderr, "/stop_memory/%d", *p++);
954 break;
956 case duplicate:
957 fprintf (stderr, "/duplicate/%d", *p++);
958 break;
960 case anychar:
961 fprintf (stderr, "/anychar");
962 break;
964 case charset:
965 case charset_not:
967 register int c, last = -100;
968 register int in_range = 0;
969 int length = CHARSET_BITMAP_SIZE (p - 1);
970 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
972 fprintf (stderr, "/charset [%s",
973 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
975 if (p + *p >= pend)
976 fprintf (stderr, " !extends past end of pattern! ");
978 for (c = 0; c < 256; c++)
979 if (c / 8 < length
980 && (p[1 + (c/8)] & (1 << (c % 8))))
982 /* Are we starting a range? */
983 if (last + 1 == c && ! in_range)
985 fprintf (stderr, "-");
986 in_range = 1;
988 /* Have we broken a range? */
989 else if (last + 1 != c && in_range)
991 fprintf (stderr, "%c", last);
992 in_range = 0;
995 if (! in_range)
996 fprintf (stderr, "%c", c);
998 last = c;
1001 if (in_range)
1002 fprintf (stderr, "%c", last);
1004 fprintf (stderr, "]");
1006 p += 1 + length;
1008 if (has_range_table)
1010 int count;
1011 fprintf (stderr, "has-range-table");
1013 /* ??? Should print the range table; for now, just skip it. */
1014 p += 2; /* skip range table bits */
1015 EXTRACT_NUMBER_AND_INCR (count, p);
1016 p = CHARSET_RANGE_TABLE_END (p, count);
1019 break;
1021 case begline:
1022 fprintf (stderr, "/begline");
1023 break;
1025 case endline:
1026 fprintf (stderr, "/endline");
1027 break;
1029 case on_failure_jump:
1030 extract_number_and_incr (&mcnt, &p);
1031 fprintf (stderr, "/on_failure_jump to %d", p + mcnt - start);
1032 break;
1034 case on_failure_keep_string_jump:
1035 extract_number_and_incr (&mcnt, &p);
1036 fprintf (stderr, "/on_failure_keep_string_jump to %d", p + mcnt - start);
1037 break;
1039 case on_failure_jump_nastyloop:
1040 extract_number_and_incr (&mcnt, &p);
1041 fprintf (stderr, "/on_failure_jump_nastyloop to %d", p + mcnt - start);
1042 break;
1044 case on_failure_jump_loop:
1045 extract_number_and_incr (&mcnt, &p);
1046 fprintf (stderr, "/on_failure_jump_loop to %d", p + mcnt - start);
1047 break;
1049 case on_failure_jump_smart:
1050 extract_number_and_incr (&mcnt, &p);
1051 fprintf (stderr, "/on_failure_jump_smart to %d", p + mcnt - start);
1052 break;
1054 case jump:
1055 extract_number_and_incr (&mcnt, &p);
1056 fprintf (stderr, "/jump to %d", p + mcnt - start);
1057 break;
1059 case succeed_n:
1060 extract_number_and_incr (&mcnt, &p);
1061 extract_number_and_incr (&mcnt2, &p);
1062 fprintf (stderr, "/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1063 break;
1065 case jump_n:
1066 extract_number_and_incr (&mcnt, &p);
1067 extract_number_and_incr (&mcnt2, &p);
1068 fprintf (stderr, "/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1069 break;
1071 case set_number_at:
1072 extract_number_and_incr (&mcnt, &p);
1073 extract_number_and_incr (&mcnt2, &p);
1074 fprintf (stderr, "/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1075 break;
1077 case wordbound:
1078 fprintf (stderr, "/wordbound");
1079 break;
1081 case notwordbound:
1082 fprintf (stderr, "/notwordbound");
1083 break;
1085 case wordbeg:
1086 fprintf (stderr, "/wordbeg");
1087 break;
1089 case wordend:
1090 fprintf (stderr, "/wordend");
1091 break;
1093 case symbeg:
1094 fprintf (stderr, "/symbeg");
1095 break;
1097 case symend:
1098 fprintf (stderr, "/symend");
1099 break;
1101 case syntaxspec:
1102 fprintf (stderr, "/syntaxspec");
1103 mcnt = *p++;
1104 fprintf (stderr, "/%d", mcnt);
1105 break;
1107 case notsyntaxspec:
1108 fprintf (stderr, "/notsyntaxspec");
1109 mcnt = *p++;
1110 fprintf (stderr, "/%d", mcnt);
1111 break;
1113 # ifdef emacs
1114 case before_dot:
1115 fprintf (stderr, "/before_dot");
1116 break;
1118 case at_dot:
1119 fprintf (stderr, "/at_dot");
1120 break;
1122 case after_dot:
1123 fprintf (stderr, "/after_dot");
1124 break;
1126 case categoryspec:
1127 fprintf (stderr, "/categoryspec");
1128 mcnt = *p++;
1129 fprintf (stderr, "/%d", mcnt);
1130 break;
1132 case notcategoryspec:
1133 fprintf (stderr, "/notcategoryspec");
1134 mcnt = *p++;
1135 fprintf (stderr, "/%d", mcnt);
1136 break;
1137 # endif /* emacs */
1139 case begbuf:
1140 fprintf (stderr, "/begbuf");
1141 break;
1143 case endbuf:
1144 fprintf (stderr, "/endbuf");
1145 break;
1147 default:
1148 fprintf (stderr, "?%d", *(p-1));
1151 fprintf (stderr, "\n");
1154 fprintf (stderr, "%d:\tend of pattern.\n", p - start);
1158 void
1159 print_compiled_pattern (bufp)
1160 struct re_pattern_buffer *bufp;
1162 re_char *buffer = bufp->buffer;
1164 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1165 printf ("%ld bytes used/%ld bytes allocated.\n",
1166 bufp->used, bufp->allocated);
1168 if (bufp->fastmap_accurate && bufp->fastmap)
1170 printf ("fastmap: ");
1171 print_fastmap (bufp->fastmap);
1174 printf ("re_nsub: %d\t", bufp->re_nsub);
1175 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1176 printf ("can_be_null: %d\t", bufp->can_be_null);
1177 printf ("no_sub: %d\t", bufp->no_sub);
1178 printf ("not_bol: %d\t", bufp->not_bol);
1179 printf ("not_eol: %d\t", bufp->not_eol);
1180 printf ("syntax: %lx\n", bufp->syntax);
1181 fflush (stdout);
1182 /* Perhaps we should print the translate table? */
1186 void
1187 print_double_string (where, string1, size1, string2, size2)
1188 re_char *where;
1189 re_char *string1;
1190 re_char *string2;
1191 ssize_t size1;
1192 ssize_t size2;
1194 ssize_t this_char;
1196 if (where == NULL)
1197 printf ("(null)");
1198 else
1200 if (FIRST_STRING_P (where))
1202 for (this_char = where - string1; this_char < size1; this_char++)
1203 putchar (string1[this_char]);
1205 where = string2;
1208 for (this_char = where - string2; this_char < size2; this_char++)
1209 putchar (string2[this_char]);
1213 #else /* not DEBUG */
1215 # undef assert
1216 # define assert(e)
1218 # define DEBUG_STATEMENT(e)
1219 # define DEBUG_PRINT1(x)
1220 # define DEBUG_PRINT2(x1, x2)
1221 # define DEBUG_PRINT3(x1, x2, x3)
1222 # define DEBUG_PRINT4(x1, x2, x3, x4)
1223 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1224 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1226 #endif /* not DEBUG */
1228 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1229 #ifdef lint
1230 # define IF_LINT(Code) Code
1231 #else
1232 # define IF_LINT(Code) /* empty */
1233 #endif
1235 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1236 also be assigned to arbitrarily: each pattern buffer stores its own
1237 syntax, so it can be changed between regex compilations. */
1238 /* This has no initializer because initialized variables in Emacs
1239 become read-only after dumping. */
1240 reg_syntax_t re_syntax_options;
1243 /* Specify the precise syntax of regexps for compilation. This provides
1244 for compatibility for various utilities which historically have
1245 different, incompatible syntaxes.
1247 The argument SYNTAX is a bit mask comprised of the various bits
1248 defined in regex.h. We return the old syntax. */
1250 reg_syntax_t
1251 re_set_syntax (reg_syntax_t syntax)
1253 reg_syntax_t ret = re_syntax_options;
1255 re_syntax_options = syntax;
1256 return ret;
1258 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1260 /* Regexp to use to replace spaces, or NULL meaning don't. */
1261 static re_char *whitespace_regexp;
1263 void
1264 re_set_whitespace_regexp (const char *regexp)
1266 whitespace_regexp = (re_char *) regexp;
1268 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1270 /* This table gives an error message for each of the error codes listed
1271 in regex.h. Obviously the order here has to be same as there.
1272 POSIX doesn't require that we do anything for REG_NOERROR,
1273 but why not be nice? */
1275 static const char *re_error_msgid[] =
1277 gettext_noop ("Success"), /* REG_NOERROR */
1278 gettext_noop ("No match"), /* REG_NOMATCH */
1279 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1280 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1281 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1282 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1283 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1284 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1285 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1286 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1287 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1288 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1289 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1290 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1291 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1292 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1293 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1294 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1297 /* Avoiding alloca during matching, to placate r_alloc. */
1299 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1300 searching and matching functions should not call alloca. On some
1301 systems, alloca is implemented in terms of malloc, and if we're
1302 using the relocating allocator routines, then malloc could cause a
1303 relocation, which might (if the strings being searched are in the
1304 ralloc heap) shift the data out from underneath the regexp
1305 routines.
1307 Here's another reason to avoid allocation: Emacs
1308 processes input from X in a signal handler; processing X input may
1309 call malloc; if input arrives while a matching routine is calling
1310 malloc, then we're scrod. But Emacs can't just block input while
1311 calling matching routines; then we don't notice interrupts when
1312 they come in. So, Emacs blocks input around all regexp calls
1313 except the matching calls, which it leaves unprotected, in the
1314 faith that they will not malloc. */
1316 /* Normally, this is fine. */
1317 #define MATCH_MAY_ALLOCATE
1319 /* The match routines may not allocate if (1) they would do it with malloc
1320 and (2) it's not safe for them to use malloc.
1321 Note that if REL_ALLOC is defined, matching would not use malloc for the
1322 failure stack, but we would still use it for the register vectors;
1323 so REL_ALLOC should not affect this. */
1324 #if defined REGEX_MALLOC && defined emacs
1325 # undef MATCH_MAY_ALLOCATE
1326 #endif
1329 /* Failure stack declarations and macros; both re_compile_fastmap and
1330 re_match_2 use a failure stack. These have to be macros because of
1331 REGEX_ALLOCATE_STACK. */
1334 /* Approximate number of failure points for which to initially allocate space
1335 when matching. If this number is exceeded, we allocate more
1336 space, so it is not a hard limit. */
1337 #ifndef INIT_FAILURE_ALLOC
1338 # define INIT_FAILURE_ALLOC 20
1339 #endif
1341 /* Roughly the maximum number of failure points on the stack. Would be
1342 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1343 This is a variable only so users of regex can assign to it; we never
1344 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1345 before using it, so it should probably be a byte-count instead. */
1346 # if defined MATCH_MAY_ALLOCATE
1347 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1348 whose default stack limit is 2mb. In order for a larger
1349 value to work reliably, you have to try to make it accord
1350 with the process stack limit. */
1351 size_t re_max_failures = 40000;
1352 # else
1353 size_t re_max_failures = 4000;
1354 # endif
1356 union fail_stack_elt
1358 re_char *pointer;
1359 /* This should be the biggest `int' that's no bigger than a pointer. */
1360 long integer;
1363 typedef union fail_stack_elt fail_stack_elt_t;
1365 typedef struct
1367 fail_stack_elt_t *stack;
1368 size_t size;
1369 size_t avail; /* Offset of next open position. */
1370 size_t frame; /* Offset of the cur constructed frame. */
1371 } fail_stack_type;
1373 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1376 /* Define macros to initialize and free the failure stack.
1377 Do `return -2' if the alloc fails. */
1379 #ifdef MATCH_MAY_ALLOCATE
1380 # define INIT_FAIL_STACK() \
1381 do { \
1382 fail_stack.stack = \
1383 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1384 * sizeof (fail_stack_elt_t)); \
1386 if (fail_stack.stack == NULL) \
1387 return -2; \
1389 fail_stack.size = INIT_FAILURE_ALLOC; \
1390 fail_stack.avail = 0; \
1391 fail_stack.frame = 0; \
1392 } while (0)
1393 #else
1394 # define INIT_FAIL_STACK() \
1395 do { \
1396 fail_stack.avail = 0; \
1397 fail_stack.frame = 0; \
1398 } while (0)
1400 # define RETALLOC_IF(addr, n, t) \
1401 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1402 #endif
1405 /* Double the size of FAIL_STACK, up to a limit
1406 which allows approximately `re_max_failures' items.
1408 Return 1 if succeeds, and 0 if either ran out of memory
1409 allocating space for it or it was already too large.
1411 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1413 /* Factor to increase the failure stack size by
1414 when we increase it.
1415 This used to be 2, but 2 was too wasteful
1416 because the old discarded stacks added up to as much space
1417 were as ultimate, maximum-size stack. */
1418 #define FAIL_STACK_GROWTH_FACTOR 4
1420 #define GROW_FAIL_STACK(fail_stack) \
1421 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1422 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1423 ? 0 \
1424 : ((fail_stack).stack \
1425 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1426 (fail_stack).size * sizeof (fail_stack_elt_t), \
1427 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1428 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1429 * FAIL_STACK_GROWTH_FACTOR))), \
1431 (fail_stack).stack == NULL \
1432 ? 0 \
1433 : ((fail_stack).size \
1434 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1435 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1436 * FAIL_STACK_GROWTH_FACTOR)) \
1437 / sizeof (fail_stack_elt_t)), \
1438 1)))
1441 /* Push a pointer value onto the failure stack.
1442 Assumes the variable `fail_stack'. Probably should only
1443 be called from within `PUSH_FAILURE_POINT'. */
1444 #define PUSH_FAILURE_POINTER(item) \
1445 fail_stack.stack[fail_stack.avail++].pointer = (item)
1447 /* This pushes an integer-valued item onto the failure stack.
1448 Assumes the variable `fail_stack'. Probably should only
1449 be called from within `PUSH_FAILURE_POINT'. */
1450 #define PUSH_FAILURE_INT(item) \
1451 fail_stack.stack[fail_stack.avail++].integer = (item)
1453 /* These POP... operations complement the PUSH... operations.
1454 All assume that `fail_stack' is nonempty. */
1455 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1456 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1458 /* Individual items aside from the registers. */
1459 #define NUM_NONREG_ITEMS 3
1461 /* Used to examine the stack (to detect infinite loops). */
1462 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1463 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1464 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1465 #define TOP_FAILURE_HANDLE() fail_stack.frame
1468 #define ENSURE_FAIL_STACK(space) \
1469 while (REMAINING_AVAIL_SLOTS <= space) { \
1470 if (!GROW_FAIL_STACK (fail_stack)) \
1471 return -2; \
1472 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1473 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1476 /* Push register NUM onto the stack. */
1477 #define PUSH_FAILURE_REG(num) \
1478 do { \
1479 char *destination; \
1480 ENSURE_FAIL_STACK(3); \
1481 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1482 num, regstart[num], regend[num]); \
1483 PUSH_FAILURE_POINTER (regstart[num]); \
1484 PUSH_FAILURE_POINTER (regend[num]); \
1485 PUSH_FAILURE_INT (num); \
1486 } while (0)
1488 /* Change the counter's value to VAL, but make sure that it will
1489 be reset when backtracking. */
1490 #define PUSH_NUMBER(ptr,val) \
1491 do { \
1492 char *destination; \
1493 int c; \
1494 ENSURE_FAIL_STACK(3); \
1495 EXTRACT_NUMBER (c, ptr); \
1496 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1497 PUSH_FAILURE_INT (c); \
1498 PUSH_FAILURE_POINTER (ptr); \
1499 PUSH_FAILURE_INT (-1); \
1500 STORE_NUMBER (ptr, val); \
1501 } while (0)
1503 /* Pop a saved register off the stack. */
1504 #define POP_FAILURE_REG_OR_COUNT() \
1505 do { \
1506 long pfreg = POP_FAILURE_INT (); \
1507 if (pfreg == -1) \
1509 /* It's a counter. */ \
1510 /* Here, we discard `const', making re_match non-reentrant. */ \
1511 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1512 pfreg = POP_FAILURE_INT (); \
1513 STORE_NUMBER (ptr, pfreg); \
1514 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, pfreg); \
1516 else \
1518 regend[pfreg] = POP_FAILURE_POINTER (); \
1519 regstart[pfreg] = POP_FAILURE_POINTER (); \
1520 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1521 pfreg, regstart[pfreg], regend[pfreg]); \
1523 } while (0)
1525 /* Check that we are not stuck in an infinite loop. */
1526 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1527 do { \
1528 ssize_t failure = TOP_FAILURE_HANDLE (); \
1529 /* Check for infinite matching loops */ \
1530 while (failure > 0 \
1531 && (FAILURE_STR (failure) == string_place \
1532 || FAILURE_STR (failure) == NULL)) \
1534 assert (FAILURE_PAT (failure) >= bufp->buffer \
1535 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1536 if (FAILURE_PAT (failure) == pat_cur) \
1538 cycle = 1; \
1539 break; \
1541 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1542 failure = NEXT_FAILURE_HANDLE(failure); \
1544 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1545 } while (0)
1547 /* Push the information about the state we will need
1548 if we ever fail back to it.
1550 Requires variables fail_stack, regstart, regend and
1551 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1552 declared.
1554 Does `return FAILURE_CODE' if runs out of memory. */
1556 #define PUSH_FAILURE_POINT(pattern, string_place) \
1557 do { \
1558 char *destination; \
1559 /* Must be int, so when we don't save any registers, the arithmetic \
1560 of 0 + -1 isn't done as unsigned. */ \
1562 DEBUG_STATEMENT (nfailure_points_pushed++); \
1563 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1564 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1565 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1567 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1569 DEBUG_PRINT1 ("\n"); \
1571 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1572 PUSH_FAILURE_INT (fail_stack.frame); \
1574 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1575 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1576 DEBUG_PRINT1 ("'\n"); \
1577 PUSH_FAILURE_POINTER (string_place); \
1579 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1580 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1581 PUSH_FAILURE_POINTER (pattern); \
1583 /* Close the frame by moving the frame pointer past it. */ \
1584 fail_stack.frame = fail_stack.avail; \
1585 } while (0)
1587 /* Estimate the size of data pushed by a typical failure stack entry.
1588 An estimate is all we need, because all we use this for
1589 is to choose a limit for how big to make the failure stack. */
1590 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1591 #define TYPICAL_FAILURE_SIZE 20
1593 /* How many items can still be added to the stack without overflowing it. */
1594 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1597 /* Pops what PUSH_FAIL_STACK pushes.
1599 We restore into the parameters, all of which should be lvalues:
1600 STR -- the saved data position.
1601 PAT -- the saved pattern position.
1602 REGSTART, REGEND -- arrays of string positions.
1604 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1605 `pend', `string1', `size1', `string2', and `size2'. */
1607 #define POP_FAILURE_POINT(str, pat) \
1608 do { \
1609 assert (!FAIL_STACK_EMPTY ()); \
1611 /* Remove failure points and point to how many regs pushed. */ \
1612 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1613 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1614 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1616 /* Pop the saved registers. */ \
1617 while (fail_stack.frame < fail_stack.avail) \
1618 POP_FAILURE_REG_OR_COUNT (); \
1620 pat = POP_FAILURE_POINTER (); \
1621 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1622 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1624 /* If the saved string location is NULL, it came from an \
1625 on_failure_keep_string_jump opcode, and we want to throw away the \
1626 saved NULL, thus retaining our current position in the string. */ \
1627 str = POP_FAILURE_POINTER (); \
1628 DEBUG_PRINT2 (" Popping string %p: `", str); \
1629 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1630 DEBUG_PRINT1 ("'\n"); \
1632 fail_stack.frame = POP_FAILURE_INT (); \
1633 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1635 assert (fail_stack.avail >= 0); \
1636 assert (fail_stack.frame <= fail_stack.avail); \
1638 DEBUG_STATEMENT (nfailure_points_popped++); \
1639 } while (0) /* POP_FAILURE_POINT */
1643 /* Registers are set to a sentinel when they haven't yet matched. */
1644 #define REG_UNSET(e) ((e) == NULL)
1646 /* Subroutine declarations and macros for regex_compile. */
1648 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1649 reg_syntax_t syntax,
1650 struct re_pattern_buffer *bufp);
1651 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1652 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1653 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1654 int arg, unsigned char *end);
1655 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1656 int arg1, int arg2, unsigned char *end);
1657 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1658 reg_syntax_t syntax);
1659 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1660 reg_syntax_t syntax);
1661 static re_char *skip_one_char (re_char *p);
1662 static int analyse_first (re_char *p, re_char *pend,
1663 char *fastmap, const int multibyte);
1665 /* Fetch the next character in the uncompiled pattern, with no
1666 translation. */
1667 #define PATFETCH(c) \
1668 do { \
1669 int len; \
1670 if (p == pend) return REG_EEND; \
1671 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1672 p += len; \
1673 } while (0)
1676 /* If `translate' is non-null, return translate[D], else just D. We
1677 cast the subscript to translate because some data is declared as
1678 `char *', to avoid warnings when a string constant is passed. But
1679 when we use a character as a subscript we must make it unsigned. */
1680 #ifndef TRANSLATE
1681 # define TRANSLATE(d) \
1682 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1683 #endif
1686 /* Macros for outputting the compiled pattern into `buffer'. */
1688 /* If the buffer isn't allocated when it comes in, use this. */
1689 #define INIT_BUF_SIZE 32
1691 /* Make sure we have at least N more bytes of space in buffer. */
1692 #define GET_BUFFER_SPACE(n) \
1693 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1694 EXTEND_BUFFER ()
1696 /* Make sure we have one more byte of buffer space and then add C to it. */
1697 #define BUF_PUSH(c) \
1698 do { \
1699 GET_BUFFER_SPACE (1); \
1700 *b++ = (unsigned char) (c); \
1701 } while (0)
1704 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1705 #define BUF_PUSH_2(c1, c2) \
1706 do { \
1707 GET_BUFFER_SPACE (2); \
1708 *b++ = (unsigned char) (c1); \
1709 *b++ = (unsigned char) (c2); \
1710 } while (0)
1713 /* Store a jump with opcode OP at LOC to location TO. We store a
1714 relative address offset by the three bytes the jump itself occupies. */
1715 #define STORE_JUMP(op, loc, to) \
1716 store_op1 (op, loc, (to) - (loc) - 3)
1718 /* Likewise, for a two-argument jump. */
1719 #define STORE_JUMP2(op, loc, to, arg) \
1720 store_op2 (op, loc, (to) - (loc) - 3, arg)
1722 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1723 #define INSERT_JUMP(op, loc, to) \
1724 insert_op1 (op, loc, (to) - (loc) - 3, b)
1726 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1727 #define INSERT_JUMP2(op, loc, to, arg) \
1728 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1731 /* This is not an arbitrary limit: the arguments which represent offsets
1732 into the pattern are two bytes long. So if 2^15 bytes turns out to
1733 be too small, many things would have to change. */
1734 # define MAX_BUF_SIZE (1L << 15)
1736 /* Extend the buffer by twice its current size via realloc and
1737 reset the pointers that pointed into the old block to point to the
1738 correct places in the new one. If extending the buffer results in it
1739 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1740 #if __BOUNDED_POINTERS__
1741 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1742 # define MOVE_BUFFER_POINTER(P) \
1743 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1744 SET_HIGH_BOUND (P), \
1745 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1746 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1747 else \
1749 SET_HIGH_BOUND (b); \
1750 SET_HIGH_BOUND (begalt); \
1751 if (fixup_alt_jump) \
1752 SET_HIGH_BOUND (fixup_alt_jump); \
1753 if (laststart) \
1754 SET_HIGH_BOUND (laststart); \
1755 if (pending_exact) \
1756 SET_HIGH_BOUND (pending_exact); \
1758 #else
1759 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1760 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1761 #endif
1762 #define EXTEND_BUFFER() \
1763 do { \
1764 unsigned char *old_buffer = bufp->buffer; \
1765 if (bufp->allocated == MAX_BUF_SIZE) \
1766 return REG_ESIZE; \
1767 bufp->allocated <<= 1; \
1768 if (bufp->allocated > MAX_BUF_SIZE) \
1769 bufp->allocated = MAX_BUF_SIZE; \
1770 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1771 if (bufp->buffer == NULL) \
1772 return REG_ESPACE; \
1773 /* If the buffer moved, move all the pointers into it. */ \
1774 if (old_buffer != bufp->buffer) \
1776 unsigned char *new_buffer = bufp->buffer; \
1777 MOVE_BUFFER_POINTER (b); \
1778 MOVE_BUFFER_POINTER (begalt); \
1779 if (fixup_alt_jump) \
1780 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1781 if (laststart) \
1782 MOVE_BUFFER_POINTER (laststart); \
1783 if (pending_exact) \
1784 MOVE_BUFFER_POINTER (pending_exact); \
1786 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1787 } while (0)
1790 /* Since we have one byte reserved for the register number argument to
1791 {start,stop}_memory, the maximum number of groups we can report
1792 things about is what fits in that byte. */
1793 #define MAX_REGNUM 255
1795 /* But patterns can have more than `MAX_REGNUM' registers. We just
1796 ignore the excess. */
1797 typedef int regnum_t;
1800 /* Macros for the compile stack. */
1802 /* Since offsets can go either forwards or backwards, this type needs to
1803 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1804 /* int may be not enough when sizeof(int) == 2. */
1805 typedef long pattern_offset_t;
1807 typedef struct
1809 pattern_offset_t begalt_offset;
1810 pattern_offset_t fixup_alt_jump;
1811 pattern_offset_t laststart_offset;
1812 regnum_t regnum;
1813 } compile_stack_elt_t;
1816 typedef struct
1818 compile_stack_elt_t *stack;
1819 size_t size;
1820 size_t avail; /* Offset of next open position. */
1821 } compile_stack_type;
1824 #define INIT_COMPILE_STACK_SIZE 32
1826 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1827 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1829 /* The next available element. */
1830 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1832 /* Explicit quit checking is needed for Emacs, which uses polling to
1833 process input events. */
1834 #ifdef emacs
1835 # define IMMEDIATE_QUIT_CHECK \
1836 do { \
1837 if (immediate_quit) QUIT; \
1838 } while (0)
1839 #else
1840 # define IMMEDIATE_QUIT_CHECK ((void)0)
1841 #endif
1843 /* Structure to manage work area for range table. */
1844 struct range_table_work_area
1846 int *table; /* actual work area. */
1847 int allocated; /* allocated size for work area in bytes. */
1848 int used; /* actually used size in words. */
1849 int bits; /* flag to record character classes */
1852 /* Make sure that WORK_AREA can hold more N multibyte characters.
1853 This is used only in set_image_of_range and set_image_of_range_1.
1854 It expects WORK_AREA to be a pointer.
1855 If it can't get the space, it returns from the surrounding function. */
1857 #define EXTEND_RANGE_TABLE(work_area, n) \
1858 do { \
1859 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1861 extend_range_table_work_area (&work_area); \
1862 if ((work_area).table == 0) \
1863 return (REG_ESPACE); \
1865 } while (0)
1867 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1868 (work_area).bits |= (bit)
1870 /* Bits used to implement the multibyte-part of the various character classes
1871 such as [:alnum:] in a charset's range table. */
1872 #define BIT_WORD 0x1
1873 #define BIT_LOWER 0x2
1874 #define BIT_PUNCT 0x4
1875 #define BIT_SPACE 0x8
1876 #define BIT_UPPER 0x10
1877 #define BIT_MULTIBYTE 0x20
1879 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1880 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1881 do { \
1882 EXTEND_RANGE_TABLE ((work_area), 2); \
1883 (work_area).table[(work_area).used++] = (range_start); \
1884 (work_area).table[(work_area).used++] = (range_end); \
1885 } while (0)
1887 /* Free allocated memory for WORK_AREA. */
1888 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1889 do { \
1890 if ((work_area).table) \
1891 free ((work_area).table); \
1892 } while (0)
1894 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1895 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1896 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1897 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1900 /* Set the bit for character C in a list. */
1901 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1904 #ifdef emacs
1906 /* Store characters in the range FROM to TO in the bitmap at B (for
1907 ASCII and unibyte characters) and WORK_AREA (for multibyte
1908 characters) while translating them and paying attention to the
1909 continuity of translated characters.
1911 Implementation note: It is better to implement these fairly big
1912 macros by a function, but it's not that easy because macros called
1913 in this macro assume various local variables already declared. */
1915 /* Both FROM and TO are ASCII characters. */
1917 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1918 do { \
1919 int C0, C1; \
1921 for (C0 = (FROM); C0 <= (TO); C0++) \
1923 C1 = TRANSLATE (C0); \
1924 if (! ASCII_CHAR_P (C1)) \
1926 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1927 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1928 C1 = C0; \
1930 SET_LIST_BIT (C1); \
1932 } while (0)
1935 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1937 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1938 do { \
1939 int C0, C1, C2, I; \
1940 int USED = RANGE_TABLE_WORK_USED (work_area); \
1942 for (C0 = (FROM); C0 <= (TO); C0++) \
1944 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1945 if (CHAR_BYTE8_P (C1)) \
1946 SET_LIST_BIT (C0); \
1947 else \
1949 C2 = TRANSLATE (C1); \
1950 if (C2 == C1 \
1951 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1952 C1 = C0; \
1953 SET_LIST_BIT (C1); \
1954 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1956 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1957 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1959 if (C2 >= from - 1 && C2 <= to + 1) \
1961 if (C2 == from - 1) \
1962 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1963 else if (C2 == to + 1) \
1964 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1965 break; \
1968 if (I < USED) \
1969 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1972 } while (0)
1975 /* Both FROM and TO are multibyte characters. */
1977 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1978 do { \
1979 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1981 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1982 for (C0 = (FROM); C0 <= (TO); C0++) \
1984 C1 = TRANSLATE (C0); \
1985 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1986 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1987 SET_LIST_BIT (C2); \
1988 if (C1 >= (FROM) && C1 <= (TO)) \
1989 continue; \
1990 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1992 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1993 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1995 if (C1 >= from - 1 && C1 <= to + 1) \
1997 if (C1 == from - 1) \
1998 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1999 else if (C1 == to + 1) \
2000 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2001 break; \
2004 if (I < USED) \
2005 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2007 } while (0)
2009 #endif /* emacs */
2011 /* Get the next unsigned number in the uncompiled pattern. */
2012 #define GET_UNSIGNED_NUMBER(num) \
2013 do { \
2014 if (p == pend) \
2015 FREE_STACK_RETURN (REG_EBRACE); \
2016 else \
2018 PATFETCH (c); \
2019 while ('0' <= c && c <= '9') \
2021 int prev; \
2022 if (num < 0) \
2023 num = 0; \
2024 prev = num; \
2025 num = num * 10 + c - '0'; \
2026 if (num / 10 != prev) \
2027 FREE_STACK_RETURN (REG_BADBR); \
2028 if (p == pend) \
2029 FREE_STACK_RETURN (REG_EBRACE); \
2030 PATFETCH (c); \
2033 } while (0)
2035 #if ! WIDE_CHAR_SUPPORT
2037 /* Map a string to the char class it names (if any). */
2038 re_wctype_t
2039 re_wctype (const re_char *str)
2041 const char *string = (const char *) str;
2042 if (STREQ (string, "alnum")) return RECC_ALNUM;
2043 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2044 else if (STREQ (string, "word")) return RECC_WORD;
2045 else if (STREQ (string, "ascii")) return RECC_ASCII;
2046 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2047 else if (STREQ (string, "graph")) return RECC_GRAPH;
2048 else if (STREQ (string, "lower")) return RECC_LOWER;
2049 else if (STREQ (string, "print")) return RECC_PRINT;
2050 else if (STREQ (string, "punct")) return RECC_PUNCT;
2051 else if (STREQ (string, "space")) return RECC_SPACE;
2052 else if (STREQ (string, "upper")) return RECC_UPPER;
2053 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2054 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2055 else if (STREQ (string, "digit")) return RECC_DIGIT;
2056 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2057 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2058 else if (STREQ (string, "blank")) return RECC_BLANK;
2059 else return 0;
2062 /* True if CH is in the char class CC. */
2063 boolean
2064 re_iswctype (int ch, re_wctype_t cc)
2066 switch (cc)
2068 case RECC_ALNUM: return ISALNUM (ch) != 0;
2069 case RECC_ALPHA: return ISALPHA (ch) != 0;
2070 case RECC_BLANK: return ISBLANK (ch) != 0;
2071 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2072 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2073 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2074 case RECC_LOWER: return ISLOWER (ch) != 0;
2075 case RECC_PRINT: return ISPRINT (ch) != 0;
2076 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2077 case RECC_SPACE: return ISSPACE (ch) != 0;
2078 case RECC_UPPER: return ISUPPER (ch) != 0;
2079 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2080 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2081 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2082 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2083 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2084 case RECC_WORD: return ISWORD (ch) != 0;
2085 case RECC_ERROR: return false;
2086 default:
2087 abort ();
2091 /* Return a bit-pattern to use in the range-table bits to match multibyte
2092 chars of class CC. */
2093 static int
2094 re_wctype_to_bit (re_wctype_t cc)
2096 switch (cc)
2098 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2099 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2100 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2101 case RECC_LOWER: return BIT_LOWER;
2102 case RECC_UPPER: return BIT_UPPER;
2103 case RECC_PUNCT: return BIT_PUNCT;
2104 case RECC_SPACE: return BIT_SPACE;
2105 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2106 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2107 default:
2108 abort ();
2111 #endif
2113 /* Filling in the work area of a range. */
2115 /* Actually extend the space in WORK_AREA. */
2117 static void
2118 extend_range_table_work_area (struct range_table_work_area *work_area)
2120 work_area->allocated += 16 * sizeof (int);
2121 work_area->table = realloc (work_area->table, work_area->allocated);
2124 #if 0
2125 #ifdef emacs
2127 /* Carefully find the ranges of codes that are equivalent
2128 under case conversion to the range start..end when passed through
2129 TRANSLATE. Handle the case where non-letters can come in between
2130 two upper-case letters (which happens in Latin-1).
2131 Also handle the case of groups of more than 2 case-equivalent chars.
2133 The basic method is to look at consecutive characters and see
2134 if they can form a run that can be handled as one.
2136 Returns -1 if successful, REG_ESPACE if ran out of space. */
2138 static int
2139 set_image_of_range_1 (struct range_table_work_area *work_area,
2140 re_wchar_t start, re_wchar_t end,
2141 RE_TRANSLATE_TYPE translate)
2143 /* `one_case' indicates a character, or a run of characters,
2144 each of which is an isolate (no case-equivalents).
2145 This includes all ASCII non-letters.
2147 `two_case' indicates a character, or a run of characters,
2148 each of which has two case-equivalent forms.
2149 This includes all ASCII letters.
2151 `strange' indicates a character that has more than one
2152 case-equivalent. */
2154 enum case_type {one_case, two_case, strange};
2156 /* Describe the run that is in progress,
2157 which the next character can try to extend.
2158 If run_type is strange, that means there really is no run.
2159 If run_type is one_case, then run_start...run_end is the run.
2160 If run_type is two_case, then the run is run_start...run_end,
2161 and the case-equivalents end at run_eqv_end. */
2163 enum case_type run_type = strange;
2164 int run_start, run_end, run_eqv_end;
2166 Lisp_Object eqv_table;
2168 if (!RE_TRANSLATE_P (translate))
2170 EXTEND_RANGE_TABLE (work_area, 2);
2171 work_area->table[work_area->used++] = (start);
2172 work_area->table[work_area->used++] = (end);
2173 return -1;
2176 eqv_table = XCHAR_TABLE (translate)->extras[2];
2178 for (; start <= end; start++)
2180 enum case_type this_type;
2181 int eqv = RE_TRANSLATE (eqv_table, start);
2182 int minchar, maxchar;
2184 /* Classify this character */
2185 if (eqv == start)
2186 this_type = one_case;
2187 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2188 this_type = two_case;
2189 else
2190 this_type = strange;
2192 if (start < eqv)
2193 minchar = start, maxchar = eqv;
2194 else
2195 minchar = eqv, maxchar = start;
2197 /* Can this character extend the run in progress? */
2198 if (this_type == strange || this_type != run_type
2199 || !(minchar == run_end + 1
2200 && (run_type == two_case
2201 ? maxchar == run_eqv_end + 1 : 1)))
2203 /* No, end the run.
2204 Record each of its equivalent ranges. */
2205 if (run_type == one_case)
2207 EXTEND_RANGE_TABLE (work_area, 2);
2208 work_area->table[work_area->used++] = run_start;
2209 work_area->table[work_area->used++] = run_end;
2211 else if (run_type == two_case)
2213 EXTEND_RANGE_TABLE (work_area, 4);
2214 work_area->table[work_area->used++] = run_start;
2215 work_area->table[work_area->used++] = run_end;
2216 work_area->table[work_area->used++]
2217 = RE_TRANSLATE (eqv_table, run_start);
2218 work_area->table[work_area->used++]
2219 = RE_TRANSLATE (eqv_table, run_end);
2221 run_type = strange;
2224 if (this_type == strange)
2226 /* For a strange character, add each of its equivalents, one
2227 by one. Don't start a range. */
2230 EXTEND_RANGE_TABLE (work_area, 2);
2231 work_area->table[work_area->used++] = eqv;
2232 work_area->table[work_area->used++] = eqv;
2233 eqv = RE_TRANSLATE (eqv_table, eqv);
2235 while (eqv != start);
2238 /* Add this char to the run, or start a new run. */
2239 else if (run_type == strange)
2241 /* Initialize a new range. */
2242 run_type = this_type;
2243 run_start = start;
2244 run_end = start;
2245 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2247 else
2249 /* Extend a running range. */
2250 run_end = minchar;
2251 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2255 /* If a run is still in progress at the end, finish it now
2256 by recording its equivalent ranges. */
2257 if (run_type == one_case)
2259 EXTEND_RANGE_TABLE (work_area, 2);
2260 work_area->table[work_area->used++] = run_start;
2261 work_area->table[work_area->used++] = run_end;
2263 else if (run_type == two_case)
2265 EXTEND_RANGE_TABLE (work_area, 4);
2266 work_area->table[work_area->used++] = run_start;
2267 work_area->table[work_area->used++] = run_end;
2268 work_area->table[work_area->used++]
2269 = RE_TRANSLATE (eqv_table, run_start);
2270 work_area->table[work_area->used++]
2271 = RE_TRANSLATE (eqv_table, run_end);
2274 return -1;
2277 #endif /* emacs */
2279 /* Record the image of the range start..end when passed through
2280 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2281 and is not even necessarily contiguous.
2282 Normally we approximate it with the smallest contiguous range that contains
2283 all the chars we need. However, for Latin-1 we go to extra effort
2284 to do a better job.
2286 This function is not called for ASCII ranges.
2288 Returns -1 if successful, REG_ESPACE if ran out of space. */
2290 static int
2291 set_image_of_range (struct range_table_work_area *work_area,
2292 re_wchar_t start, re_wchar_t end,
2293 RE_TRANSLATE_TYPE translate)
2295 re_wchar_t cmin, cmax;
2297 #ifdef emacs
2298 /* For Latin-1 ranges, use set_image_of_range_1
2299 to get proper handling of ranges that include letters and nonletters.
2300 For a range that includes the whole of Latin-1, this is not necessary.
2301 For other character sets, we don't bother to get this right. */
2302 if (RE_TRANSLATE_P (translate) && start < 04400
2303 && !(start < 04200 && end >= 04377))
2305 int newend;
2306 int tem;
2307 newend = end;
2308 if (newend > 04377)
2309 newend = 04377;
2310 tem = set_image_of_range_1 (work_area, start, newend, translate);
2311 if (tem > 0)
2312 return tem;
2314 start = 04400;
2315 if (end < 04400)
2316 return -1;
2318 #endif
2320 EXTEND_RANGE_TABLE (work_area, 2);
2321 work_area->table[work_area->used++] = (start);
2322 work_area->table[work_area->used++] = (end);
2324 cmin = -1, cmax = -1;
2326 if (RE_TRANSLATE_P (translate))
2328 int ch;
2330 for (ch = start; ch <= end; ch++)
2332 re_wchar_t c = TRANSLATE (ch);
2333 if (! (start <= c && c <= end))
2335 if (cmin == -1)
2336 cmin = c, cmax = c;
2337 else
2339 cmin = MIN (cmin, c);
2340 cmax = MAX (cmax, c);
2345 if (cmin != -1)
2347 EXTEND_RANGE_TABLE (work_area, 2);
2348 work_area->table[work_area->used++] = (cmin);
2349 work_area->table[work_area->used++] = (cmax);
2353 return -1;
2355 #endif /* 0 */
2357 #ifndef MATCH_MAY_ALLOCATE
2359 /* If we cannot allocate large objects within re_match_2_internal,
2360 we make the fail stack and register vectors global.
2361 The fail stack, we grow to the maximum size when a regexp
2362 is compiled.
2363 The register vectors, we adjust in size each time we
2364 compile a regexp, according to the number of registers it needs. */
2366 static fail_stack_type fail_stack;
2368 /* Size with which the following vectors are currently allocated.
2369 That is so we can make them bigger as needed,
2370 but never make them smaller. */
2371 static int regs_allocated_size;
2373 static re_char ** regstart, ** regend;
2374 static re_char **best_regstart, **best_regend;
2376 /* Make the register vectors big enough for NUM_REGS registers,
2377 but don't make them smaller. */
2379 static
2380 regex_grow_registers (int num_regs)
2382 if (num_regs > regs_allocated_size)
2384 RETALLOC_IF (regstart, num_regs, re_char *);
2385 RETALLOC_IF (regend, num_regs, re_char *);
2386 RETALLOC_IF (best_regstart, num_regs, re_char *);
2387 RETALLOC_IF (best_regend, num_regs, re_char *);
2389 regs_allocated_size = num_regs;
2393 #endif /* not MATCH_MAY_ALLOCATE */
2395 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2396 regnum_t regnum);
2398 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2399 Returns one of error codes defined in `regex.h', or zero for success.
2401 Assumes the `allocated' (and perhaps `buffer') and `translate'
2402 fields are set in BUFP on entry.
2404 If it succeeds, results are put in BUFP (if it returns an error, the
2405 contents of BUFP are undefined):
2406 `buffer' is the compiled pattern;
2407 `syntax' is set to SYNTAX;
2408 `used' is set to the length of the compiled pattern;
2409 `fastmap_accurate' is zero;
2410 `re_nsub' is the number of subexpressions in PATTERN;
2411 `not_bol' and `not_eol' are zero;
2413 The `fastmap' field is neither examined nor set. */
2415 /* Insert the `jump' from the end of last alternative to "here".
2416 The space for the jump has already been allocated. */
2417 #define FIXUP_ALT_JUMP() \
2418 do { \
2419 if (fixup_alt_jump) \
2420 STORE_JUMP (jump, fixup_alt_jump, b); \
2421 } while (0)
2424 /* Return, freeing storage we allocated. */
2425 #define FREE_STACK_RETURN(value) \
2426 do { \
2427 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2428 free (compile_stack.stack); \
2429 return value; \
2430 } while (0)
2432 static reg_errcode_t
2433 regex_compile (const re_char *pattern, size_t size, reg_syntax_t syntax, struct re_pattern_buffer *bufp)
2435 /* We fetch characters from PATTERN here. */
2436 register re_wchar_t c, c1;
2438 /* Points to the end of the buffer, where we should append. */
2439 register unsigned char *b;
2441 /* Keeps track of unclosed groups. */
2442 compile_stack_type compile_stack;
2444 /* Points to the current (ending) position in the pattern. */
2445 #ifdef AIX
2446 /* `const' makes AIX compiler fail. */
2447 unsigned char *p = pattern;
2448 #else
2449 re_char *p = pattern;
2450 #endif
2451 re_char *pend = pattern + size;
2453 /* How to translate the characters in the pattern. */
2454 RE_TRANSLATE_TYPE translate = bufp->translate;
2456 /* Address of the count-byte of the most recently inserted `exactn'
2457 command. This makes it possible to tell if a new exact-match
2458 character can be added to that command or if the character requires
2459 a new `exactn' command. */
2460 unsigned char *pending_exact = 0;
2462 /* Address of start of the most recently finished expression.
2463 This tells, e.g., postfix * where to find the start of its
2464 operand. Reset at the beginning of groups and alternatives. */
2465 unsigned char *laststart = 0;
2467 /* Address of beginning of regexp, or inside of last group. */
2468 unsigned char *begalt;
2470 /* Place in the uncompiled pattern (i.e., the {) to
2471 which to go back if the interval is invalid. */
2472 re_char *beg_interval;
2474 /* Address of the place where a forward jump should go to the end of
2475 the containing expression. Each alternative of an `or' -- except the
2476 last -- ends with a forward jump of this sort. */
2477 unsigned char *fixup_alt_jump = 0;
2479 /* Work area for range table of charset. */
2480 struct range_table_work_area range_table_work;
2482 /* If the object matched can contain multibyte characters. */
2483 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2485 /* Nonzero if we have pushed down into a subpattern. */
2486 int in_subpattern = 0;
2488 /* These hold the values of p, pattern, and pend from the main
2489 pattern when we have pushed into a subpattern. */
2490 re_char *main_p IF_LINT (= NULL);
2491 re_char *main_pattern IF_LINT (= NULL);
2492 re_char *main_pend IF_LINT (= NULL);
2494 #ifdef DEBUG
2495 debug++;
2496 DEBUG_PRINT1 ("\nCompiling pattern: ");
2497 if (debug > 0)
2499 unsigned debug_count;
2501 for (debug_count = 0; debug_count < size; debug_count++)
2502 putchar (pattern[debug_count]);
2503 putchar ('\n');
2505 #endif /* DEBUG */
2507 /* Initialize the compile stack. */
2508 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2509 if (compile_stack.stack == NULL)
2510 return REG_ESPACE;
2512 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2513 compile_stack.avail = 0;
2515 range_table_work.table = 0;
2516 range_table_work.allocated = 0;
2518 /* Initialize the pattern buffer. */
2519 bufp->syntax = syntax;
2520 bufp->fastmap_accurate = 0;
2521 bufp->not_bol = bufp->not_eol = 0;
2522 bufp->used_syntax = 0;
2524 /* Set `used' to zero, so that if we return an error, the pattern
2525 printer (for debugging) will think there's no pattern. We reset it
2526 at the end. */
2527 bufp->used = 0;
2529 /* Always count groups, whether or not bufp->no_sub is set. */
2530 bufp->re_nsub = 0;
2532 #if !defined emacs && !defined SYNTAX_TABLE
2533 /* Initialize the syntax table. */
2534 init_syntax_once ();
2535 #endif
2537 if (bufp->allocated == 0)
2539 if (bufp->buffer)
2540 { /* If zero allocated, but buffer is non-null, try to realloc
2541 enough space. This loses if buffer's address is bogus, but
2542 that is the user's responsibility. */
2543 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2545 else
2546 { /* Caller did not allocate a buffer. Do it for them. */
2547 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2549 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2551 bufp->allocated = INIT_BUF_SIZE;
2554 begalt = b = bufp->buffer;
2556 /* Loop through the uncompiled pattern until we're at the end. */
2557 while (1)
2559 if (p == pend)
2561 /* If this is the end of an included regexp,
2562 pop back to the main regexp and try again. */
2563 if (in_subpattern)
2565 in_subpattern = 0;
2566 pattern = main_pattern;
2567 p = main_p;
2568 pend = main_pend;
2569 continue;
2571 /* If this is the end of the main regexp, we are done. */
2572 break;
2575 PATFETCH (c);
2577 switch (c)
2579 case ' ':
2581 re_char *p1 = p;
2583 /* If there's no special whitespace regexp, treat
2584 spaces normally. And don't try to do this recursively. */
2585 if (!whitespace_regexp || in_subpattern)
2586 goto normal_char;
2588 /* Peek past following spaces. */
2589 while (p1 != pend)
2591 if (*p1 != ' ')
2592 break;
2593 p1++;
2595 /* If the spaces are followed by a repetition op,
2596 treat them normally. */
2597 if (p1 != pend
2598 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2599 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2600 goto normal_char;
2602 /* Replace the spaces with the whitespace regexp. */
2603 in_subpattern = 1;
2604 main_p = p1;
2605 main_pend = pend;
2606 main_pattern = pattern;
2607 p = pattern = whitespace_regexp;
2608 pend = p + strlen ((const char *) p);
2609 break;
2612 case '^':
2614 if ( /* If at start of pattern, it's an operator. */
2615 p == pattern + 1
2616 /* If context independent, it's an operator. */
2617 || syntax & RE_CONTEXT_INDEP_ANCHORS
2618 /* Otherwise, depends on what's come before. */
2619 || at_begline_loc_p (pattern, p, syntax))
2620 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2621 else
2622 goto normal_char;
2624 break;
2627 case '$':
2629 if ( /* If at end of pattern, it's an operator. */
2630 p == pend
2631 /* If context independent, it's an operator. */
2632 || syntax & RE_CONTEXT_INDEP_ANCHORS
2633 /* Otherwise, depends on what's next. */
2634 || at_endline_loc_p (p, pend, syntax))
2635 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2636 else
2637 goto normal_char;
2639 break;
2642 case '+':
2643 case '?':
2644 if ((syntax & RE_BK_PLUS_QM)
2645 || (syntax & RE_LIMITED_OPS))
2646 goto normal_char;
2647 handle_plus:
2648 case '*':
2649 /* If there is no previous pattern... */
2650 if (!laststart)
2652 if (syntax & RE_CONTEXT_INVALID_OPS)
2653 FREE_STACK_RETURN (REG_BADRPT);
2654 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2655 goto normal_char;
2659 /* 1 means zero (many) matches is allowed. */
2660 boolean zero_times_ok = 0, many_times_ok = 0;
2661 boolean greedy = 1;
2663 /* If there is a sequence of repetition chars, collapse it
2664 down to just one (the right one). We can't combine
2665 interval operators with these because of, e.g., `a{2}*',
2666 which should only match an even number of `a's. */
2668 for (;;)
2670 if ((syntax & RE_FRUGAL)
2671 && c == '?' && (zero_times_ok || many_times_ok))
2672 greedy = 0;
2673 else
2675 zero_times_ok |= c != '+';
2676 many_times_ok |= c != '?';
2679 if (p == pend)
2680 break;
2681 else if (*p == '*'
2682 || (!(syntax & RE_BK_PLUS_QM)
2683 && (*p == '+' || *p == '?')))
2685 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2687 if (p+1 == pend)
2688 FREE_STACK_RETURN (REG_EESCAPE);
2689 if (p[1] == '+' || p[1] == '?')
2690 PATFETCH (c); /* Gobble up the backslash. */
2691 else
2692 break;
2694 else
2695 break;
2696 /* If we get here, we found another repeat character. */
2697 PATFETCH (c);
2700 /* Star, etc. applied to an empty pattern is equivalent
2701 to an empty pattern. */
2702 if (!laststart || laststart == b)
2703 break;
2705 /* Now we know whether or not zero matches is allowed
2706 and also whether or not two or more matches is allowed. */
2707 if (greedy)
2709 if (many_times_ok)
2711 boolean simple = skip_one_char (laststart) == b;
2712 size_t startoffset = 0;
2713 re_opcode_t ofj =
2714 /* Check if the loop can match the empty string. */
2715 (simple || !analyse_first (laststart, b, NULL, 0))
2716 ? on_failure_jump : on_failure_jump_loop;
2717 assert (skip_one_char (laststart) <= b);
2719 if (!zero_times_ok && simple)
2720 { /* Since simple * loops can be made faster by using
2721 on_failure_keep_string_jump, we turn simple P+
2722 into PP* if P is simple. */
2723 unsigned char *p1, *p2;
2724 startoffset = b - laststart;
2725 GET_BUFFER_SPACE (startoffset);
2726 p1 = b; p2 = laststart;
2727 while (p2 < p1)
2728 *b++ = *p2++;
2729 zero_times_ok = 1;
2732 GET_BUFFER_SPACE (6);
2733 if (!zero_times_ok)
2734 /* A + loop. */
2735 STORE_JUMP (ofj, b, b + 6);
2736 else
2737 /* Simple * loops can use on_failure_keep_string_jump
2738 depending on what follows. But since we don't know
2739 that yet, we leave the decision up to
2740 on_failure_jump_smart. */
2741 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2742 laststart + startoffset, b + 6);
2743 b += 3;
2744 STORE_JUMP (jump, b, laststart + startoffset);
2745 b += 3;
2747 else
2749 /* A simple ? pattern. */
2750 assert (zero_times_ok);
2751 GET_BUFFER_SPACE (3);
2752 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2753 b += 3;
2756 else /* not greedy */
2757 { /* I wish the greedy and non-greedy cases could be merged. */
2759 GET_BUFFER_SPACE (7); /* We might use less. */
2760 if (many_times_ok)
2762 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2764 /* The non-greedy multiple match looks like
2765 a repeat..until: we only need a conditional jump
2766 at the end of the loop. */
2767 if (emptyp) BUF_PUSH (no_op);
2768 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2769 : on_failure_jump, b, laststart);
2770 b += 3;
2771 if (zero_times_ok)
2773 /* The repeat...until naturally matches one or more.
2774 To also match zero times, we need to first jump to
2775 the end of the loop (its conditional jump). */
2776 INSERT_JUMP (jump, laststart, b);
2777 b += 3;
2780 else
2782 /* non-greedy a?? */
2783 INSERT_JUMP (jump, laststart, b + 3);
2784 b += 3;
2785 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2786 b += 3;
2790 pending_exact = 0;
2791 break;
2794 case '.':
2795 laststart = b;
2796 BUF_PUSH (anychar);
2797 break;
2800 case '[':
2802 re_char *p1;
2804 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2806 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2808 /* Ensure that we have enough space to push a charset: the
2809 opcode, the length count, and the bitset; 34 bytes in all. */
2810 GET_BUFFER_SPACE (34);
2812 laststart = b;
2814 /* We test `*p == '^' twice, instead of using an if
2815 statement, so we only need one BUF_PUSH. */
2816 BUF_PUSH (*p == '^' ? charset_not : charset);
2817 if (*p == '^')
2818 p++;
2820 /* Remember the first position in the bracket expression. */
2821 p1 = p;
2823 /* Push the number of bytes in the bitmap. */
2824 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2826 /* Clear the whole map. */
2827 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2829 /* charset_not matches newline according to a syntax bit. */
2830 if ((re_opcode_t) b[-2] == charset_not
2831 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2832 SET_LIST_BIT ('\n');
2834 /* Read in characters and ranges, setting map bits. */
2835 for (;;)
2837 boolean escaped_char = false;
2838 const unsigned char *p2 = p;
2839 re_wchar_t ch;
2841 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2843 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2844 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2845 So the translation is done later in a loop. Example:
2846 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2847 PATFETCH (c);
2849 /* \ might escape characters inside [...] and [^...]. */
2850 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2852 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2854 PATFETCH (c);
2855 escaped_char = true;
2857 else
2859 /* Could be the end of the bracket expression. If it's
2860 not (i.e., when the bracket expression is `[]' so
2861 far), the ']' character bit gets set way below. */
2862 if (c == ']' && p2 != p1)
2863 break;
2866 /* See if we're at the beginning of a possible character
2867 class. */
2869 if (!escaped_char &&
2870 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2872 /* Leave room for the null. */
2873 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2874 const unsigned char *class_beg;
2876 PATFETCH (c);
2877 c1 = 0;
2878 class_beg = p;
2880 /* If pattern is `[[:'. */
2881 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2883 for (;;)
2885 PATFETCH (c);
2886 if ((c == ':' && *p == ']') || p == pend)
2887 break;
2888 if (c1 < CHAR_CLASS_MAX_LENGTH)
2889 str[c1++] = c;
2890 else
2891 /* This is in any case an invalid class name. */
2892 str[0] = '\0';
2894 str[c1] = '\0';
2896 /* If isn't a word bracketed by `[:' and `:]':
2897 undo the ending character, the letters, and
2898 leave the leading `:' and `[' (but set bits for
2899 them). */
2900 if (c == ':' && *p == ']')
2902 re_wctype_t cc = re_wctype (str);
2904 if (cc == 0)
2905 FREE_STACK_RETURN (REG_ECTYPE);
2907 /* Throw away the ] at the end of the character
2908 class. */
2909 PATFETCH (c);
2911 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2913 #ifndef emacs
2914 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2915 if (re_iswctype (btowc (ch), cc))
2917 c = TRANSLATE (ch);
2918 if (c < (1 << BYTEWIDTH))
2919 SET_LIST_BIT (c);
2921 #else /* emacs */
2922 /* Most character classes in a multibyte match
2923 just set a flag. Exceptions are is_blank,
2924 is_digit, is_cntrl, and is_xdigit, since
2925 they can only match ASCII characters. We
2926 don't need to handle them for multibyte.
2927 They are distinguished by a negative wctype. */
2929 /* Setup the gl_state object to its buffer-defined
2930 value. This hardcodes the buffer-global
2931 syntax-table for ASCII chars, while the other chars
2932 will obey syntax-table properties. It's not ideal,
2933 but it's the way it's been done until now. */
2934 SETUP_BUFFER_SYNTAX_TABLE ();
2936 for (ch = 0; ch < 256; ++ch)
2938 c = RE_CHAR_TO_MULTIBYTE (ch);
2939 if (! CHAR_BYTE8_P (c)
2940 && re_iswctype (c, cc))
2942 SET_LIST_BIT (ch);
2943 c1 = TRANSLATE (c);
2944 if (c1 == c)
2945 continue;
2946 if (ASCII_CHAR_P (c1))
2947 SET_LIST_BIT (c1);
2948 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2949 SET_LIST_BIT (c1);
2952 SET_RANGE_TABLE_WORK_AREA_BIT
2953 (range_table_work, re_wctype_to_bit (cc));
2954 #endif /* emacs */
2955 /* In most cases the matching rule for char classes
2956 only uses the syntax table for multibyte chars,
2957 so that the content of the syntax-table it is not
2958 hardcoded in the range_table. SPACE and WORD are
2959 the two exceptions. */
2960 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2961 bufp->used_syntax = 1;
2963 /* Repeat the loop. */
2964 continue;
2966 else
2968 /* Go back to right after the "[:". */
2969 p = class_beg;
2970 SET_LIST_BIT ('[');
2972 /* Because the `:' may starts the range, we
2973 can't simply set bit and repeat the loop.
2974 Instead, just set it to C and handle below. */
2975 c = ':';
2979 if (p < pend && p[0] == '-' && p[1] != ']')
2982 /* Discard the `-'. */
2983 PATFETCH (c1);
2985 /* Fetch the character which ends the range. */
2986 PATFETCH (c1);
2987 #ifdef emacs
2988 if (CHAR_BYTE8_P (c1)
2989 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2990 /* Treat the range from a multibyte character to
2991 raw-byte character as empty. */
2992 c = c1 + 1;
2993 #endif /* emacs */
2995 else
2996 /* Range from C to C. */
2997 c1 = c;
2999 if (c > c1)
3001 if (syntax & RE_NO_EMPTY_RANGES)
3002 FREE_STACK_RETURN (REG_ERANGEX);
3003 /* Else, repeat the loop. */
3005 else
3007 #ifndef emacs
3008 /* Set the range into bitmap */
3009 for (; c <= c1; c++)
3011 ch = TRANSLATE (c);
3012 if (ch < (1 << BYTEWIDTH))
3013 SET_LIST_BIT (ch);
3015 #else /* emacs */
3016 if (c < 128)
3018 ch = MIN (127, c1);
3019 SETUP_ASCII_RANGE (range_table_work, c, ch);
3020 c = ch + 1;
3021 if (CHAR_BYTE8_P (c1))
3022 c = BYTE8_TO_CHAR (128);
3024 if (c <= c1)
3026 if (CHAR_BYTE8_P (c))
3028 c = CHAR_TO_BYTE8 (c);
3029 c1 = CHAR_TO_BYTE8 (c1);
3030 for (; c <= c1; c++)
3031 SET_LIST_BIT (c);
3033 else if (multibyte)
3035 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
3037 else
3039 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
3042 #endif /* emacs */
3046 /* Discard any (non)matching list bytes that are all 0 at the
3047 end of the map. Decrease the map-length byte too. */
3048 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3049 b[-1]--;
3050 b += b[-1];
3052 /* Build real range table from work area. */
3053 if (RANGE_TABLE_WORK_USED (range_table_work)
3054 || RANGE_TABLE_WORK_BITS (range_table_work))
3056 int i;
3057 int used = RANGE_TABLE_WORK_USED (range_table_work);
3059 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3060 bytes for flags, two for COUNT, and three bytes for
3061 each character. */
3062 GET_BUFFER_SPACE (4 + used * 3);
3064 /* Indicate the existence of range table. */
3065 laststart[1] |= 0x80;
3067 /* Store the character class flag bits into the range table.
3068 If not in emacs, these flag bits are always 0. */
3069 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3070 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3072 STORE_NUMBER_AND_INCR (b, used / 2);
3073 for (i = 0; i < used; i++)
3074 STORE_CHARACTER_AND_INCR
3075 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3078 break;
3081 case '(':
3082 if (syntax & RE_NO_BK_PARENS)
3083 goto handle_open;
3084 else
3085 goto normal_char;
3088 case ')':
3089 if (syntax & RE_NO_BK_PARENS)
3090 goto handle_close;
3091 else
3092 goto normal_char;
3095 case '\n':
3096 if (syntax & RE_NEWLINE_ALT)
3097 goto handle_alt;
3098 else
3099 goto normal_char;
3102 case '|':
3103 if (syntax & RE_NO_BK_VBAR)
3104 goto handle_alt;
3105 else
3106 goto normal_char;
3109 case '{':
3110 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3111 goto handle_interval;
3112 else
3113 goto normal_char;
3116 case '\\':
3117 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3119 /* Do not translate the character after the \, so that we can
3120 distinguish, e.g., \B from \b, even if we normally would
3121 translate, e.g., B to b. */
3122 PATFETCH (c);
3124 switch (c)
3126 case '(':
3127 if (syntax & RE_NO_BK_PARENS)
3128 goto normal_backslash;
3130 handle_open:
3132 int shy = 0;
3133 regnum_t regnum = 0;
3134 if (p+1 < pend)
3136 /* Look for a special (?...) construct */
3137 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3139 PATFETCH (c); /* Gobble up the '?'. */
3140 while (!shy)
3142 PATFETCH (c);
3143 switch (c)
3145 case ':': shy = 1; break;
3146 case '0':
3147 /* An explicitly specified regnum must start
3148 with non-0. */
3149 if (regnum == 0)
3150 FREE_STACK_RETURN (REG_BADPAT);
3151 case '1': case '2': case '3': case '4':
3152 case '5': case '6': case '7': case '8': case '9':
3153 regnum = 10*regnum + (c - '0'); break;
3154 default:
3155 /* Only (?:...) is supported right now. */
3156 FREE_STACK_RETURN (REG_BADPAT);
3162 if (!shy)
3163 regnum = ++bufp->re_nsub;
3164 else if (regnum)
3165 { /* It's actually not shy, but explicitly numbered. */
3166 shy = 0;
3167 if (regnum > bufp->re_nsub)
3168 bufp->re_nsub = regnum;
3169 else if (regnum > bufp->re_nsub
3170 /* Ideally, we'd want to check that the specified
3171 group can't have matched (i.e. all subgroups
3172 using the same regnum are in other branches of
3173 OR patterns), but we don't currently keep track
3174 of enough info to do that easily. */
3175 || group_in_compile_stack (compile_stack, regnum))
3176 FREE_STACK_RETURN (REG_BADPAT);
3178 else
3179 /* It's really shy. */
3180 regnum = - bufp->re_nsub;
3182 if (COMPILE_STACK_FULL)
3184 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3185 compile_stack_elt_t);
3186 if (compile_stack.stack == NULL) return REG_ESPACE;
3188 compile_stack.size <<= 1;
3191 /* These are the values to restore when we hit end of this
3192 group. They are all relative offsets, so that if the
3193 whole pattern moves because of realloc, they will still
3194 be valid. */
3195 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3196 COMPILE_STACK_TOP.fixup_alt_jump
3197 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3198 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3199 COMPILE_STACK_TOP.regnum = regnum;
3201 /* Do not push a start_memory for groups beyond the last one
3202 we can represent in the compiled pattern. */
3203 if (regnum <= MAX_REGNUM && regnum > 0)
3204 BUF_PUSH_2 (start_memory, regnum);
3206 compile_stack.avail++;
3208 fixup_alt_jump = 0;
3209 laststart = 0;
3210 begalt = b;
3211 /* If we've reached MAX_REGNUM groups, then this open
3212 won't actually generate any code, so we'll have to
3213 clear pending_exact explicitly. */
3214 pending_exact = 0;
3215 break;
3218 case ')':
3219 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3221 if (COMPILE_STACK_EMPTY)
3223 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3224 goto normal_backslash;
3225 else
3226 FREE_STACK_RETURN (REG_ERPAREN);
3229 handle_close:
3230 FIXUP_ALT_JUMP ();
3232 /* See similar code for backslashed left paren above. */
3233 if (COMPILE_STACK_EMPTY)
3235 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3236 goto normal_char;
3237 else
3238 FREE_STACK_RETURN (REG_ERPAREN);
3241 /* Since we just checked for an empty stack above, this
3242 ``can't happen''. */
3243 assert (compile_stack.avail != 0);
3245 /* We don't just want to restore into `regnum', because
3246 later groups should continue to be numbered higher,
3247 as in `(ab)c(de)' -- the second group is #2. */
3248 regnum_t regnum;
3250 compile_stack.avail--;
3251 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3252 fixup_alt_jump
3253 = COMPILE_STACK_TOP.fixup_alt_jump
3254 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3255 : 0;
3256 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3257 regnum = COMPILE_STACK_TOP.regnum;
3258 /* If we've reached MAX_REGNUM groups, then this open
3259 won't actually generate any code, so we'll have to
3260 clear pending_exact explicitly. */
3261 pending_exact = 0;
3263 /* We're at the end of the group, so now we know how many
3264 groups were inside this one. */
3265 if (regnum <= MAX_REGNUM && regnum > 0)
3266 BUF_PUSH_2 (stop_memory, regnum);
3268 break;
3271 case '|': /* `\|'. */
3272 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3273 goto normal_backslash;
3274 handle_alt:
3275 if (syntax & RE_LIMITED_OPS)
3276 goto normal_char;
3278 /* Insert before the previous alternative a jump which
3279 jumps to this alternative if the former fails. */
3280 GET_BUFFER_SPACE (3);
3281 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3282 pending_exact = 0;
3283 b += 3;
3285 /* The alternative before this one has a jump after it
3286 which gets executed if it gets matched. Adjust that
3287 jump so it will jump to this alternative's analogous
3288 jump (put in below, which in turn will jump to the next
3289 (if any) alternative's such jump, etc.). The last such
3290 jump jumps to the correct final destination. A picture:
3291 _____ _____
3292 | | | |
3293 | v | v
3294 a | b | c
3296 If we are at `b', then fixup_alt_jump right now points to a
3297 three-byte space after `a'. We'll put in the jump, set
3298 fixup_alt_jump to right after `b', and leave behind three
3299 bytes which we'll fill in when we get to after `c'. */
3301 FIXUP_ALT_JUMP ();
3303 /* Mark and leave space for a jump after this alternative,
3304 to be filled in later either by next alternative or
3305 when know we're at the end of a series of alternatives. */
3306 fixup_alt_jump = b;
3307 GET_BUFFER_SPACE (3);
3308 b += 3;
3310 laststart = 0;
3311 begalt = b;
3312 break;
3315 case '{':
3316 /* If \{ is a literal. */
3317 if (!(syntax & RE_INTERVALS)
3318 /* If we're at `\{' and it's not the open-interval
3319 operator. */
3320 || (syntax & RE_NO_BK_BRACES))
3321 goto normal_backslash;
3323 handle_interval:
3325 /* If got here, then the syntax allows intervals. */
3327 /* At least (most) this many matches must be made. */
3328 int lower_bound = 0, upper_bound = -1;
3330 beg_interval = p;
3332 GET_UNSIGNED_NUMBER (lower_bound);
3334 if (c == ',')
3335 GET_UNSIGNED_NUMBER (upper_bound);
3336 else
3337 /* Interval such as `{1}' => match exactly once. */
3338 upper_bound = lower_bound;
3340 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3341 || (upper_bound >= 0 && lower_bound > upper_bound))
3342 FREE_STACK_RETURN (REG_BADBR);
3344 if (!(syntax & RE_NO_BK_BRACES))
3346 if (c != '\\')
3347 FREE_STACK_RETURN (REG_BADBR);
3348 if (p == pend)
3349 FREE_STACK_RETURN (REG_EESCAPE);
3350 PATFETCH (c);
3353 if (c != '}')
3354 FREE_STACK_RETURN (REG_BADBR);
3356 /* We just parsed a valid interval. */
3358 /* If it's invalid to have no preceding re. */
3359 if (!laststart)
3361 if (syntax & RE_CONTEXT_INVALID_OPS)
3362 FREE_STACK_RETURN (REG_BADRPT);
3363 else if (syntax & RE_CONTEXT_INDEP_OPS)
3364 laststart = b;
3365 else
3366 goto unfetch_interval;
3369 if (upper_bound == 0)
3370 /* If the upper bound is zero, just drop the sub pattern
3371 altogether. */
3372 b = laststart;
3373 else if (lower_bound == 1 && upper_bound == 1)
3374 /* Just match it once: nothing to do here. */
3377 /* Otherwise, we have a nontrivial interval. When
3378 we're all done, the pattern will look like:
3379 set_number_at <jump count> <upper bound>
3380 set_number_at <succeed_n count> <lower bound>
3381 succeed_n <after jump addr> <succeed_n count>
3382 <body of loop>
3383 jump_n <succeed_n addr> <jump count>
3384 (The upper bound and `jump_n' are omitted if
3385 `upper_bound' is 1, though.) */
3386 else
3387 { /* If the upper bound is > 1, we need to insert
3388 more at the end of the loop. */
3389 unsigned int nbytes = (upper_bound < 0 ? 3
3390 : upper_bound > 1 ? 5 : 0);
3391 unsigned int startoffset = 0;
3393 GET_BUFFER_SPACE (20); /* We might use less. */
3395 if (lower_bound == 0)
3397 /* A succeed_n that starts with 0 is really a
3398 a simple on_failure_jump_loop. */
3399 INSERT_JUMP (on_failure_jump_loop, laststart,
3400 b + 3 + nbytes);
3401 b += 3;
3403 else
3405 /* Initialize lower bound of the `succeed_n', even
3406 though it will be set during matching by its
3407 attendant `set_number_at' (inserted next),
3408 because `re_compile_fastmap' needs to know.
3409 Jump to the `jump_n' we might insert below. */
3410 INSERT_JUMP2 (succeed_n, laststart,
3411 b + 5 + nbytes,
3412 lower_bound);
3413 b += 5;
3415 /* Code to initialize the lower bound. Insert
3416 before the `succeed_n'. The `5' is the last two
3417 bytes of this `set_number_at', plus 3 bytes of
3418 the following `succeed_n'. */
3419 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3420 b += 5;
3421 startoffset += 5;
3424 if (upper_bound < 0)
3426 /* A negative upper bound stands for infinity,
3427 in which case it degenerates to a plain jump. */
3428 STORE_JUMP (jump, b, laststart + startoffset);
3429 b += 3;
3431 else if (upper_bound > 1)
3432 { /* More than one repetition is allowed, so
3433 append a backward jump to the `succeed_n'
3434 that starts this interval.
3436 When we've reached this during matching,
3437 we'll have matched the interval once, so
3438 jump back only `upper_bound - 1' times. */
3439 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3440 upper_bound - 1);
3441 b += 5;
3443 /* The location we want to set is the second
3444 parameter of the `jump_n'; that is `b-2' as
3445 an absolute address. `laststart' will be
3446 the `set_number_at' we're about to insert;
3447 `laststart+3' the number to set, the source
3448 for the relative address. But we are
3449 inserting into the middle of the pattern --
3450 so everything is getting moved up by 5.
3451 Conclusion: (b - 2) - (laststart + 3) + 5,
3452 i.e., b - laststart.
3454 We insert this at the beginning of the loop
3455 so that if we fail during matching, we'll
3456 reinitialize the bounds. */
3457 insert_op2 (set_number_at, laststart, b - laststart,
3458 upper_bound - 1, b);
3459 b += 5;
3462 pending_exact = 0;
3463 beg_interval = NULL;
3465 break;
3467 unfetch_interval:
3468 /* If an invalid interval, match the characters as literals. */
3469 assert (beg_interval);
3470 p = beg_interval;
3471 beg_interval = NULL;
3473 /* normal_char and normal_backslash need `c'. */
3474 c = '{';
3476 if (!(syntax & RE_NO_BK_BRACES))
3478 assert (p > pattern && p[-1] == '\\');
3479 goto normal_backslash;
3481 else
3482 goto normal_char;
3484 #ifdef emacs
3485 /* There is no way to specify the before_dot and after_dot
3486 operators. rms says this is ok. --karl */
3487 case '=':
3488 BUF_PUSH (at_dot);
3489 break;
3491 case 's':
3492 laststart = b;
3493 PATFETCH (c);
3494 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3495 break;
3497 case 'S':
3498 laststart = b;
3499 PATFETCH (c);
3500 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3501 break;
3503 case 'c':
3504 laststart = b;
3505 PATFETCH (c);
3506 BUF_PUSH_2 (categoryspec, c);
3507 break;
3509 case 'C':
3510 laststart = b;
3511 PATFETCH (c);
3512 BUF_PUSH_2 (notcategoryspec, c);
3513 break;
3514 #endif /* emacs */
3517 case 'w':
3518 if (syntax & RE_NO_GNU_OPS)
3519 goto normal_char;
3520 laststart = b;
3521 BUF_PUSH_2 (syntaxspec, Sword);
3522 break;
3525 case 'W':
3526 if (syntax & RE_NO_GNU_OPS)
3527 goto normal_char;
3528 laststart = b;
3529 BUF_PUSH_2 (notsyntaxspec, Sword);
3530 break;
3533 case '<':
3534 if (syntax & RE_NO_GNU_OPS)
3535 goto normal_char;
3536 BUF_PUSH (wordbeg);
3537 break;
3539 case '>':
3540 if (syntax & RE_NO_GNU_OPS)
3541 goto normal_char;
3542 BUF_PUSH (wordend);
3543 break;
3545 case '_':
3546 if (syntax & RE_NO_GNU_OPS)
3547 goto normal_char;
3548 laststart = b;
3549 PATFETCH (c);
3550 if (c == '<')
3551 BUF_PUSH (symbeg);
3552 else if (c == '>')
3553 BUF_PUSH (symend);
3554 else
3555 FREE_STACK_RETURN (REG_BADPAT);
3556 break;
3558 case 'b':
3559 if (syntax & RE_NO_GNU_OPS)
3560 goto normal_char;
3561 BUF_PUSH (wordbound);
3562 break;
3564 case 'B':
3565 if (syntax & RE_NO_GNU_OPS)
3566 goto normal_char;
3567 BUF_PUSH (notwordbound);
3568 break;
3570 case '`':
3571 if (syntax & RE_NO_GNU_OPS)
3572 goto normal_char;
3573 BUF_PUSH (begbuf);
3574 break;
3576 case '\'':
3577 if (syntax & RE_NO_GNU_OPS)
3578 goto normal_char;
3579 BUF_PUSH (endbuf);
3580 break;
3582 case '1': case '2': case '3': case '4': case '5':
3583 case '6': case '7': case '8': case '9':
3585 regnum_t reg;
3587 if (syntax & RE_NO_BK_REFS)
3588 goto normal_backslash;
3590 reg = c - '0';
3592 if (reg > bufp->re_nsub || reg < 1
3593 /* Can't back reference to a subexp before its end. */
3594 || group_in_compile_stack (compile_stack, reg))
3595 FREE_STACK_RETURN (REG_ESUBREG);
3597 laststart = b;
3598 BUF_PUSH_2 (duplicate, reg);
3600 break;
3603 case '+':
3604 case '?':
3605 if (syntax & RE_BK_PLUS_QM)
3606 goto handle_plus;
3607 else
3608 goto normal_backslash;
3610 default:
3611 normal_backslash:
3612 /* You might think it would be useful for \ to mean
3613 not to translate; but if we don't translate it
3614 it will never match anything. */
3615 goto normal_char;
3617 break;
3620 default:
3621 /* Expects the character in `c'. */
3622 normal_char:
3623 /* If no exactn currently being built. */
3624 if (!pending_exact
3626 /* If last exactn not at current position. */
3627 || pending_exact + *pending_exact + 1 != b
3629 /* We have only one byte following the exactn for the count. */
3630 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3632 /* If followed by a repetition operator. */
3633 || (p != pend && (*p == '*' || *p == '^'))
3634 || ((syntax & RE_BK_PLUS_QM)
3635 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3636 : p != pend && (*p == '+' || *p == '?'))
3637 || ((syntax & RE_INTERVALS)
3638 && ((syntax & RE_NO_BK_BRACES)
3639 ? p != pend && *p == '{'
3640 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3642 /* Start building a new exactn. */
3644 laststart = b;
3646 BUF_PUSH_2 (exactn, 0);
3647 pending_exact = b - 1;
3650 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3652 int len;
3654 if (multibyte)
3656 c = TRANSLATE (c);
3657 len = CHAR_STRING (c, b);
3658 b += len;
3660 else
3662 c1 = RE_CHAR_TO_MULTIBYTE (c);
3663 if (! CHAR_BYTE8_P (c1))
3665 re_wchar_t c2 = TRANSLATE (c1);
3667 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3668 c = c1;
3670 *b++ = c;
3671 len = 1;
3673 (*pending_exact) += len;
3676 break;
3677 } /* switch (c) */
3678 } /* while p != pend */
3681 /* Through the pattern now. */
3683 FIXUP_ALT_JUMP ();
3685 if (!COMPILE_STACK_EMPTY)
3686 FREE_STACK_RETURN (REG_EPAREN);
3688 /* If we don't want backtracking, force success
3689 the first time we reach the end of the compiled pattern. */
3690 if (syntax & RE_NO_POSIX_BACKTRACKING)
3691 BUF_PUSH (succeed);
3693 /* We have succeeded; set the length of the buffer. */
3694 bufp->used = b - bufp->buffer;
3696 #ifdef DEBUG
3697 if (debug > 0)
3699 re_compile_fastmap (bufp);
3700 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3701 print_compiled_pattern (bufp);
3703 debug--;
3704 #endif /* DEBUG */
3706 #ifndef MATCH_MAY_ALLOCATE
3707 /* Initialize the failure stack to the largest possible stack. This
3708 isn't necessary unless we're trying to avoid calling alloca in
3709 the search and match routines. */
3711 int num_regs = bufp->re_nsub + 1;
3713 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3715 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3716 falk_stack.stack = realloc (fail_stack.stack,
3717 fail_stack.size * sizeof *falk_stack.stack);
3720 regex_grow_registers (num_regs);
3722 #endif /* not MATCH_MAY_ALLOCATE */
3724 FREE_STACK_RETURN (REG_NOERROR);
3725 } /* regex_compile */
3727 /* Subroutines for `regex_compile'. */
3729 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3731 static void
3732 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3734 *loc = (unsigned char) op;
3735 STORE_NUMBER (loc + 1, arg);
3739 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3741 static void
3742 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3744 *loc = (unsigned char) op;
3745 STORE_NUMBER (loc + 1, arg1);
3746 STORE_NUMBER (loc + 3, arg2);
3750 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3751 for OP followed by two-byte integer parameter ARG. */
3753 static void
3754 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3756 register unsigned char *pfrom = end;
3757 register unsigned char *pto = end + 3;
3759 while (pfrom != loc)
3760 *--pto = *--pfrom;
3762 store_op1 (op, loc, arg);
3766 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3768 static void
3769 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3771 register unsigned char *pfrom = end;
3772 register unsigned char *pto = end + 5;
3774 while (pfrom != loc)
3775 *--pto = *--pfrom;
3777 store_op2 (op, loc, arg1, arg2);
3781 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3782 after an alternative or a begin-subexpression. We assume there is at
3783 least one character before the ^. */
3785 static boolean
3786 at_begline_loc_p (const re_char *pattern, const re_char *p, reg_syntax_t syntax)
3788 re_char *prev = p - 2;
3789 boolean odd_backslashes;
3791 /* After a subexpression? */
3792 if (*prev == '(')
3793 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3795 /* After an alternative? */
3796 else if (*prev == '|')
3797 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3799 /* After a shy subexpression? */
3800 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3802 /* Skip over optional regnum. */
3803 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3804 --prev;
3806 if (!(prev - 2 >= pattern
3807 && prev[-1] == '?' && prev[-2] == '('))
3808 return false;
3809 prev -= 2;
3810 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3812 else
3813 return false;
3815 /* Count the number of preceding backslashes. */
3816 p = prev;
3817 while (prev - 1 >= pattern && prev[-1] == '\\')
3818 --prev;
3819 return (p - prev) & odd_backslashes;
3823 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3824 at least one character after the $, i.e., `P < PEND'. */
3826 static boolean
3827 at_endline_loc_p (const re_char *p, const re_char *pend, reg_syntax_t syntax)
3829 re_char *next = p;
3830 boolean next_backslash = *next == '\\';
3831 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3833 return
3834 /* Before a subexpression? */
3835 (syntax & RE_NO_BK_PARENS ? *next == ')'
3836 : next_backslash && next_next && *next_next == ')')
3837 /* Before an alternative? */
3838 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3839 : next_backslash && next_next && *next_next == '|');
3843 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3844 false if it's not. */
3846 static boolean
3847 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3849 ssize_t this_element;
3851 for (this_element = compile_stack.avail - 1;
3852 this_element >= 0;
3853 this_element--)
3854 if (compile_stack.stack[this_element].regnum == regnum)
3855 return true;
3857 return false;
3860 /* analyse_first.
3861 If fastmap is non-NULL, go through the pattern and fill fastmap
3862 with all the possible leading chars. If fastmap is NULL, don't
3863 bother filling it up (obviously) and only return whether the
3864 pattern could potentially match the empty string.
3866 Return 1 if p..pend might match the empty string.
3867 Return 0 if p..pend matches at least one char.
3868 Return -1 if fastmap was not updated accurately. */
3870 static int
3871 analyse_first (const re_char *p, const re_char *pend, char *fastmap, const int multibyte)
3873 int j, k;
3874 boolean not;
3876 /* If all elements for base leading-codes in fastmap is set, this
3877 flag is set true. */
3878 boolean match_any_multibyte_characters = false;
3880 assert (p);
3882 /* The loop below works as follows:
3883 - It has a working-list kept in the PATTERN_STACK and which basically
3884 starts by only containing a pointer to the first operation.
3885 - If the opcode we're looking at is a match against some set of
3886 chars, then we add those chars to the fastmap and go on to the
3887 next work element from the worklist (done via `break').
3888 - If the opcode is a control operator on the other hand, we either
3889 ignore it (if it's meaningless at this point, such as `start_memory')
3890 or execute it (if it's a jump). If the jump has several destinations
3891 (i.e. `on_failure_jump'), then we push the other destination onto the
3892 worklist.
3893 We guarantee termination by ignoring backward jumps (more or less),
3894 so that `p' is monotonically increasing. More to the point, we
3895 never set `p' (or push) anything `<= p1'. */
3897 while (p < pend)
3899 /* `p1' is used as a marker of how far back a `on_failure_jump'
3900 can go without being ignored. It is normally equal to `p'
3901 (which prevents any backward `on_failure_jump') except right
3902 after a plain `jump', to allow patterns such as:
3903 0: jump 10
3904 3..9: <body>
3905 10: on_failure_jump 3
3906 as used for the *? operator. */
3907 re_char *p1 = p;
3909 switch (*p++)
3911 case succeed:
3912 return 1;
3914 case duplicate:
3915 /* If the first character has to match a backreference, that means
3916 that the group was empty (since it already matched). Since this
3917 is the only case that interests us here, we can assume that the
3918 backreference must match the empty string. */
3919 p++;
3920 continue;
3923 /* Following are the cases which match a character. These end
3924 with `break'. */
3926 case exactn:
3927 if (fastmap)
3929 /* If multibyte is nonzero, the first byte of each
3930 character is an ASCII or a leading code. Otherwise,
3931 each byte is a character. Thus, this works in both
3932 cases. */
3933 fastmap[p[1]] = 1;
3934 if (! multibyte)
3936 /* For the case of matching this unibyte regex
3937 against multibyte, we must set a leading code of
3938 the corresponding multibyte character. */
3939 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3941 fastmap[CHAR_LEADING_CODE (c)] = 1;
3944 break;
3947 case anychar:
3948 /* We could put all the chars except for \n (and maybe \0)
3949 but we don't bother since it is generally not worth it. */
3950 if (!fastmap) break;
3951 return -1;
3954 case charset_not:
3955 if (!fastmap) break;
3957 /* Chars beyond end of bitmap are possible matches. */
3958 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3959 j < (1 << BYTEWIDTH); j++)
3960 fastmap[j] = 1;
3963 /* Fallthrough */
3964 case charset:
3965 if (!fastmap) break;
3966 not = (re_opcode_t) *(p - 1) == charset_not;
3967 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3968 j >= 0; j--)
3969 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3970 fastmap[j] = 1;
3972 #ifdef emacs
3973 if (/* Any leading code can possibly start a character
3974 which doesn't match the specified set of characters. */
3977 /* If we can match a character class, we can match any
3978 multibyte characters. */
3979 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3980 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3983 if (match_any_multibyte_characters == false)
3985 for (j = MIN_MULTIBYTE_LEADING_CODE;
3986 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3987 fastmap[j] = 1;
3988 match_any_multibyte_characters = true;
3992 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3993 && match_any_multibyte_characters == false)
3995 /* Set fastmap[I] to 1 where I is a leading code of each
3996 multibyte character in the range table. */
3997 int c, count;
3998 unsigned char lc1, lc2;
4000 /* Make P points the range table. `+ 2' is to skip flag
4001 bits for a character class. */
4002 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
4004 /* Extract the number of ranges in range table into COUNT. */
4005 EXTRACT_NUMBER_AND_INCR (count, p);
4006 for (; count > 0; count--, p += 3)
4008 /* Extract the start and end of each range. */
4009 EXTRACT_CHARACTER (c, p);
4010 lc1 = CHAR_LEADING_CODE (c);
4011 p += 3;
4012 EXTRACT_CHARACTER (c, p);
4013 lc2 = CHAR_LEADING_CODE (c);
4014 for (j = lc1; j <= lc2; j++)
4015 fastmap[j] = 1;
4018 #endif
4019 break;
4021 case syntaxspec:
4022 case notsyntaxspec:
4023 if (!fastmap) break;
4024 #ifndef emacs
4025 not = (re_opcode_t)p[-1] == notsyntaxspec;
4026 k = *p++;
4027 for (j = 0; j < (1 << BYTEWIDTH); j++)
4028 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
4029 fastmap[j] = 1;
4030 break;
4031 #else /* emacs */
4032 /* This match depends on text properties. These end with
4033 aborting optimizations. */
4034 return -1;
4036 case categoryspec:
4037 case notcategoryspec:
4038 if (!fastmap) break;
4039 not = (re_opcode_t)p[-1] == notcategoryspec;
4040 k = *p++;
4041 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4042 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4043 fastmap[j] = 1;
4045 /* Any leading code can possibly start a character which
4046 has or doesn't has the specified category. */
4047 if (match_any_multibyte_characters == false)
4049 for (j = MIN_MULTIBYTE_LEADING_CODE;
4050 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4051 fastmap[j] = 1;
4052 match_any_multibyte_characters = true;
4054 break;
4056 /* All cases after this match the empty string. These end with
4057 `continue'. */
4059 case before_dot:
4060 case at_dot:
4061 case after_dot:
4062 #endif /* !emacs */
4063 case no_op:
4064 case begline:
4065 case endline:
4066 case begbuf:
4067 case endbuf:
4068 case wordbound:
4069 case notwordbound:
4070 case wordbeg:
4071 case wordend:
4072 case symbeg:
4073 case symend:
4074 continue;
4077 case jump:
4078 EXTRACT_NUMBER_AND_INCR (j, p);
4079 if (j < 0)
4080 /* Backward jumps can only go back to code that we've already
4081 visited. `re_compile' should make sure this is true. */
4082 break;
4083 p += j;
4084 switch (*p)
4086 case on_failure_jump:
4087 case on_failure_keep_string_jump:
4088 case on_failure_jump_loop:
4089 case on_failure_jump_nastyloop:
4090 case on_failure_jump_smart:
4091 p++;
4092 break;
4093 default:
4094 continue;
4096 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4097 to jump back to "just after here". */
4098 /* Fallthrough */
4100 case on_failure_jump:
4101 case on_failure_keep_string_jump:
4102 case on_failure_jump_nastyloop:
4103 case on_failure_jump_loop:
4104 case on_failure_jump_smart:
4105 EXTRACT_NUMBER_AND_INCR (j, p);
4106 if (p + j <= p1)
4107 ; /* Backward jump to be ignored. */
4108 else
4109 { /* We have to look down both arms.
4110 We first go down the "straight" path so as to minimize
4111 stack usage when going through alternatives. */
4112 int r = analyse_first (p, pend, fastmap, multibyte);
4113 if (r) return r;
4114 p += j;
4116 continue;
4119 case jump_n:
4120 /* This code simply does not properly handle forward jump_n. */
4121 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4122 p += 4;
4123 /* jump_n can either jump or fall through. The (backward) jump
4124 case has already been handled, so we only need to look at the
4125 fallthrough case. */
4126 continue;
4128 case succeed_n:
4129 /* If N == 0, it should be an on_failure_jump_loop instead. */
4130 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4131 p += 4;
4132 /* We only care about one iteration of the loop, so we don't
4133 need to consider the case where this behaves like an
4134 on_failure_jump. */
4135 continue;
4138 case set_number_at:
4139 p += 4;
4140 continue;
4143 case start_memory:
4144 case stop_memory:
4145 p += 1;
4146 continue;
4149 default:
4150 abort (); /* We have listed all the cases. */
4151 } /* switch *p++ */
4153 /* Getting here means we have found the possible starting
4154 characters for one path of the pattern -- and that the empty
4155 string does not match. We need not follow this path further. */
4156 return 0;
4157 } /* while p */
4159 /* We reached the end without matching anything. */
4160 return 1;
4162 } /* analyse_first */
4164 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4165 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4166 characters can start a string that matches the pattern. This fastmap
4167 is used by re_search to skip quickly over impossible starting points.
4169 Character codes above (1 << BYTEWIDTH) are not represented in the
4170 fastmap, but the leading codes are represented. Thus, the fastmap
4171 indicates which character sets could start a match.
4173 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4174 area as BUFP->fastmap.
4176 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4177 the pattern buffer.
4179 Returns 0 if we succeed, -2 if an internal error. */
4182 re_compile_fastmap (struct re_pattern_buffer *bufp)
4184 char *fastmap = bufp->fastmap;
4185 int analysis;
4187 assert (fastmap && bufp->buffer);
4189 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4190 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4192 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
4193 fastmap, RE_MULTIBYTE_P (bufp));
4194 bufp->can_be_null = (analysis != 0);
4195 return 0;
4196 } /* re_compile_fastmap */
4198 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4199 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4200 this memory for recording register information. STARTS and ENDS
4201 must be allocated using the malloc library routine, and must each
4202 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4204 If NUM_REGS == 0, then subsequent matches should allocate their own
4205 register data.
4207 Unless this function is called, the first search or match using
4208 PATTERN_BUFFER will allocate its own register data, without
4209 freeing the old data. */
4211 void
4212 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4214 if (num_regs)
4216 bufp->regs_allocated = REGS_REALLOCATE;
4217 regs->num_regs = num_regs;
4218 regs->start = starts;
4219 regs->end = ends;
4221 else
4223 bufp->regs_allocated = REGS_UNALLOCATED;
4224 regs->num_regs = 0;
4225 regs->start = regs->end = (regoff_t *) 0;
4228 WEAK_ALIAS (__re_set_registers, re_set_registers)
4230 /* Searching routines. */
4232 /* Like re_search_2, below, but only one string is specified, and
4233 doesn't let you say where to stop matching. */
4235 regoff_t
4236 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4237 ssize_t startpos, ssize_t range, struct re_registers *regs)
4239 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4240 regs, size);
4242 WEAK_ALIAS (__re_search, re_search)
4244 /* Head address of virtual concatenation of string. */
4245 #define HEAD_ADDR_VSTRING(P) \
4246 (((P) >= size1 ? string2 : string1))
4248 /* Address of POS in the concatenation of virtual string. */
4249 #define POS_ADDR_VSTRING(POS) \
4250 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4252 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4253 virtual concatenation of STRING1 and STRING2, starting first at index
4254 STARTPOS, then at STARTPOS + 1, and so on.
4256 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4258 RANGE is how far to scan while trying to match. RANGE = 0 means try
4259 only at STARTPOS; in general, the last start tried is STARTPOS +
4260 RANGE.
4262 In REGS, return the indices of the virtual concatenation of STRING1
4263 and STRING2 that matched the entire BUFP->buffer and its contained
4264 subexpressions.
4266 Do not consider matching one past the index STOP in the virtual
4267 concatenation of STRING1 and STRING2.
4269 We return either the position in the strings at which the match was
4270 found, -1 if no match, or -2 if error (such as failure
4271 stack overflow). */
4273 regoff_t
4274 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4275 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4276 struct re_registers *regs, ssize_t stop)
4278 regoff_t val;
4279 re_char *string1 = (re_char*) str1;
4280 re_char *string2 = (re_char*) str2;
4281 register char *fastmap = bufp->fastmap;
4282 register RE_TRANSLATE_TYPE translate = bufp->translate;
4283 size_t total_size = size1 + size2;
4284 ssize_t endpos = startpos + range;
4285 boolean anchored_start;
4286 /* Nonzero if we are searching multibyte string. */
4287 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4289 /* Check for out-of-range STARTPOS. */
4290 if (startpos < 0 || startpos > total_size)
4291 return -1;
4293 /* Fix up RANGE if it might eventually take us outside
4294 the virtual concatenation of STRING1 and STRING2.
4295 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4296 if (endpos < 0)
4297 range = 0 - startpos;
4298 else if (endpos > total_size)
4299 range = total_size - startpos;
4301 /* If the search isn't to be a backwards one, don't waste time in a
4302 search for a pattern anchored at beginning of buffer. */
4303 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4305 if (startpos > 0)
4306 return -1;
4307 else
4308 range = 0;
4311 #ifdef emacs
4312 /* In a forward search for something that starts with \=.
4313 don't keep searching past point. */
4314 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4316 range = PT_BYTE - BEGV_BYTE - startpos;
4317 if (range < 0)
4318 return -1;
4320 #endif /* emacs */
4322 /* Update the fastmap now if not correct already. */
4323 if (fastmap && !bufp->fastmap_accurate)
4324 re_compile_fastmap (bufp);
4326 /* See whether the pattern is anchored. */
4327 anchored_start = (bufp->buffer[0] == begline);
4329 #ifdef emacs
4330 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4332 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4334 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4336 #endif
4338 /* Loop through the string, looking for a place to start matching. */
4339 for (;;)
4341 /* If the pattern is anchored,
4342 skip quickly past places we cannot match.
4343 We don't bother to treat startpos == 0 specially
4344 because that case doesn't repeat. */
4345 if (anchored_start && startpos > 0)
4347 if (! ((startpos <= size1 ? string1[startpos - 1]
4348 : string2[startpos - size1 - 1])
4349 == '\n'))
4350 goto advance;
4353 /* If a fastmap is supplied, skip quickly over characters that
4354 cannot be the start of a match. If the pattern can match the
4355 null string, however, we don't need to skip characters; we want
4356 the first null string. */
4357 if (fastmap && startpos < total_size && !bufp->can_be_null)
4359 register re_char *d;
4360 register re_wchar_t buf_ch;
4362 d = POS_ADDR_VSTRING (startpos);
4364 if (range > 0) /* Searching forwards. */
4366 register int lim = 0;
4367 ssize_t irange = range;
4369 if (startpos < size1 && startpos + range >= size1)
4370 lim = range - (size1 - startpos);
4372 /* Written out as an if-else to avoid testing `translate'
4373 inside the loop. */
4374 if (RE_TRANSLATE_P (translate))
4376 if (multibyte)
4377 while (range > lim)
4379 int buf_charlen;
4381 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4382 buf_ch = RE_TRANSLATE (translate, buf_ch);
4383 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4384 break;
4386 range -= buf_charlen;
4387 d += buf_charlen;
4389 else
4390 while (range > lim)
4392 register re_wchar_t ch, translated;
4394 buf_ch = *d;
4395 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4396 translated = RE_TRANSLATE (translate, ch);
4397 if (translated != ch
4398 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4399 buf_ch = ch;
4400 if (fastmap[buf_ch])
4401 break;
4402 d++;
4403 range--;
4406 else
4408 if (multibyte)
4409 while (range > lim)
4411 int buf_charlen;
4413 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4414 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4415 break;
4416 range -= buf_charlen;
4417 d += buf_charlen;
4419 else
4420 while (range > lim && !fastmap[*d])
4422 d++;
4423 range--;
4426 startpos += irange - range;
4428 else /* Searching backwards. */
4430 if (multibyte)
4432 buf_ch = STRING_CHAR (d);
4433 buf_ch = TRANSLATE (buf_ch);
4434 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4435 goto advance;
4437 else
4439 register re_wchar_t ch, translated;
4441 buf_ch = *d;
4442 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4443 translated = TRANSLATE (ch);
4444 if (translated != ch
4445 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4446 buf_ch = ch;
4447 if (! fastmap[TRANSLATE (buf_ch)])
4448 goto advance;
4453 /* If can't match the null string, and that's all we have left, fail. */
4454 if (range >= 0 && startpos == total_size && fastmap
4455 && !bufp->can_be_null)
4456 return -1;
4458 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4459 startpos, regs, stop);
4461 if (val >= 0)
4462 return startpos;
4464 if (val == -2)
4465 return -2;
4467 advance:
4468 if (!range)
4469 break;
4470 else if (range > 0)
4472 /* Update STARTPOS to the next character boundary. */
4473 if (multibyte)
4475 re_char *p = POS_ADDR_VSTRING (startpos);
4476 int len = BYTES_BY_CHAR_HEAD (*p);
4478 range -= len;
4479 if (range < 0)
4480 break;
4481 startpos += len;
4483 else
4485 range--;
4486 startpos++;
4489 else
4491 range++;
4492 startpos--;
4494 /* Update STARTPOS to the previous character boundary. */
4495 if (multibyte)
4497 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4498 re_char *p0 = p;
4499 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4501 /* Find the head of multibyte form. */
4502 PREV_CHAR_BOUNDARY (p, phead);
4503 range += p0 - 1 - p;
4504 if (range > 0)
4505 break;
4507 startpos -= p0 - 1 - p;
4511 return -1;
4512 } /* re_search_2 */
4513 WEAK_ALIAS (__re_search_2, re_search_2)
4515 /* Declarations and macros for re_match_2. */
4517 static int bcmp_translate (re_char *s1, re_char *s2,
4518 register ssize_t len,
4519 RE_TRANSLATE_TYPE translate,
4520 const int multibyte);
4522 /* This converts PTR, a pointer into one of the search strings `string1'
4523 and `string2' into an offset from the beginning of that string. */
4524 #define POINTER_TO_OFFSET(ptr) \
4525 (FIRST_STRING_P (ptr) \
4526 ? ((regoff_t) ((ptr) - string1)) \
4527 : ((regoff_t) ((ptr) - string2 + size1)))
4529 /* Call before fetching a character with *d. This switches over to
4530 string2 if necessary.
4531 Check re_match_2_internal for a discussion of why end_match_2 might
4532 not be within string2 (but be equal to end_match_1 instead). */
4533 #define PREFETCH() \
4534 while (d == dend) \
4536 /* End of string2 => fail. */ \
4537 if (dend == end_match_2) \
4538 goto fail; \
4539 /* End of string1 => advance to string2. */ \
4540 d = string2; \
4541 dend = end_match_2; \
4544 /* Call before fetching a char with *d if you already checked other limits.
4545 This is meant for use in lookahead operations like wordend, etc..
4546 where we might need to look at parts of the string that might be
4547 outside of the LIMITs (i.e past `stop'). */
4548 #define PREFETCH_NOLIMIT() \
4549 if (d == end1) \
4551 d = string2; \
4552 dend = end_match_2; \
4555 /* Test if at very beginning or at very end of the virtual concatenation
4556 of `string1' and `string2'. If only one string, it's `string2'. */
4557 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4558 #define AT_STRINGS_END(d) ((d) == end2)
4560 /* Disabled due to a compiler bug -- see comment at case wordbound */
4562 /* The comment at case wordbound is following one, but we don't use
4563 AT_WORD_BOUNDARY anymore to support multibyte form.
4565 The DEC Alpha C compiler 3.x generates incorrect code for the
4566 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4567 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4568 macro and introducing temporary variables works around the bug. */
4570 #if 0
4571 /* Test if D points to a character which is word-constituent. We have
4572 two special cases to check for: if past the end of string1, look at
4573 the first character in string2; and if before the beginning of
4574 string2, look at the last character in string1. */
4575 #define WORDCHAR_P(d) \
4576 (SYNTAX ((d) == end1 ? *string2 \
4577 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4578 == Sword)
4580 /* Test if the character before D and the one at D differ with respect
4581 to being word-constituent. */
4582 #define AT_WORD_BOUNDARY(d) \
4583 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4584 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4585 #endif
4587 /* Free everything we malloc. */
4588 #ifdef MATCH_MAY_ALLOCATE
4589 # define FREE_VAR(var) \
4590 do { \
4591 if (var) \
4593 REGEX_FREE (var); \
4594 var = NULL; \
4596 } while (0)
4597 # define FREE_VARIABLES() \
4598 do { \
4599 REGEX_FREE_STACK (fail_stack.stack); \
4600 FREE_VAR (regstart); \
4601 FREE_VAR (regend); \
4602 FREE_VAR (best_regstart); \
4603 FREE_VAR (best_regend); \
4604 } while (0)
4605 #else
4606 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4607 #endif /* not MATCH_MAY_ALLOCATE */
4610 /* Optimization routines. */
4612 /* If the operation is a match against one or more chars,
4613 return a pointer to the next operation, else return NULL. */
4614 static re_char *
4615 skip_one_char (const re_char *p)
4617 switch (*p++)
4619 case anychar:
4620 break;
4622 case exactn:
4623 p += *p + 1;
4624 break;
4626 case charset_not:
4627 case charset:
4628 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4630 int mcnt;
4631 p = CHARSET_RANGE_TABLE (p - 1);
4632 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4633 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4635 else
4636 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4637 break;
4639 case syntaxspec:
4640 case notsyntaxspec:
4641 #ifdef emacs
4642 case categoryspec:
4643 case notcategoryspec:
4644 #endif /* emacs */
4645 p++;
4646 break;
4648 default:
4649 p = NULL;
4651 return p;
4655 /* Jump over non-matching operations. */
4656 static re_char *
4657 skip_noops (const re_char *p, const re_char *pend)
4659 int mcnt;
4660 while (p < pend)
4662 switch (*p)
4664 case start_memory:
4665 case stop_memory:
4666 p += 2; break;
4667 case no_op:
4668 p += 1; break;
4669 case jump:
4670 p += 1;
4671 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4672 p += mcnt;
4673 break;
4674 default:
4675 return p;
4678 assert (p == pend);
4679 return p;
4682 /* Non-zero if "p1 matches something" implies "p2 fails". */
4683 static int
4684 mutually_exclusive_p (struct re_pattern_buffer *bufp, const re_char *p1, const re_char *p2)
4686 re_opcode_t op2;
4687 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4688 unsigned char *pend = bufp->buffer + bufp->used;
4690 assert (p1 >= bufp->buffer && p1 < pend
4691 && p2 >= bufp->buffer && p2 <= pend);
4693 /* Skip over open/close-group commands.
4694 If what follows this loop is a ...+ construct,
4695 look at what begins its body, since we will have to
4696 match at least one of that. */
4697 p2 = skip_noops (p2, pend);
4698 /* The same skip can be done for p1, except that this function
4699 is only used in the case where p1 is a simple match operator. */
4700 /* p1 = skip_noops (p1, pend); */
4702 assert (p1 >= bufp->buffer && p1 < pend
4703 && p2 >= bufp->buffer && p2 <= pend);
4705 op2 = p2 == pend ? succeed : *p2;
4707 switch (op2)
4709 case succeed:
4710 case endbuf:
4711 /* If we're at the end of the pattern, we can change. */
4712 if (skip_one_char (p1))
4714 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4715 return 1;
4717 break;
4719 case endline:
4720 case exactn:
4722 register re_wchar_t c
4723 = (re_opcode_t) *p2 == endline ? '\n'
4724 : RE_STRING_CHAR (p2 + 2, multibyte);
4726 if ((re_opcode_t) *p1 == exactn)
4728 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4730 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4731 return 1;
4735 else if ((re_opcode_t) *p1 == charset
4736 || (re_opcode_t) *p1 == charset_not)
4738 int not = (re_opcode_t) *p1 == charset_not;
4740 /* Test if C is listed in charset (or charset_not)
4741 at `p1'. */
4742 if (! multibyte || IS_REAL_ASCII (c))
4744 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4745 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4746 not = !not;
4748 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4749 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4751 /* `not' is equal to 1 if c would match, which means
4752 that we can't change to pop_failure_jump. */
4753 if (!not)
4755 DEBUG_PRINT1 (" No match => fast loop.\n");
4756 return 1;
4759 else if ((re_opcode_t) *p1 == anychar
4760 && c == '\n')
4762 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4763 return 1;
4766 break;
4768 case charset:
4770 if ((re_opcode_t) *p1 == exactn)
4771 /* Reuse the code above. */
4772 return mutually_exclusive_p (bufp, p2, p1);
4774 /* It is hard to list up all the character in charset
4775 P2 if it includes multibyte character. Give up in
4776 such case. */
4777 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4779 /* Now, we are sure that P2 has no range table.
4780 So, for the size of bitmap in P2, `p2[1]' is
4781 enough. But P1 may have range table, so the
4782 size of bitmap table of P1 is extracted by
4783 using macro `CHARSET_BITMAP_SIZE'.
4785 In a multibyte case, we know that all the character
4786 listed in P2 is ASCII. In a unibyte case, P1 has only a
4787 bitmap table. So, in both cases, it is enough to test
4788 only the bitmap table of P1. */
4790 if ((re_opcode_t) *p1 == charset)
4792 int idx;
4793 /* We win if the charset inside the loop
4794 has no overlap with the one after the loop. */
4795 for (idx = 0;
4796 (idx < (int) p2[1]
4797 && idx < CHARSET_BITMAP_SIZE (p1));
4798 idx++)
4799 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4800 break;
4802 if (idx == p2[1]
4803 || idx == CHARSET_BITMAP_SIZE (p1))
4805 DEBUG_PRINT1 (" No match => fast loop.\n");
4806 return 1;
4809 else if ((re_opcode_t) *p1 == charset_not)
4811 int idx;
4812 /* We win if the charset_not inside the loop lists
4813 every character listed in the charset after. */
4814 for (idx = 0; idx < (int) p2[1]; idx++)
4815 if (! (p2[2 + idx] == 0
4816 || (idx < CHARSET_BITMAP_SIZE (p1)
4817 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4818 break;
4820 if (idx == p2[1])
4822 DEBUG_PRINT1 (" No match => fast loop.\n");
4823 return 1;
4828 break;
4830 case charset_not:
4831 switch (*p1)
4833 case exactn:
4834 case charset:
4835 /* Reuse the code above. */
4836 return mutually_exclusive_p (bufp, p2, p1);
4837 case charset_not:
4838 /* When we have two charset_not, it's very unlikely that
4839 they don't overlap. The union of the two sets of excluded
4840 chars should cover all possible chars, which, as a matter of
4841 fact, is virtually impossible in multibyte buffers. */
4842 break;
4844 break;
4846 case wordend:
4847 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4848 case symend:
4849 return ((re_opcode_t) *p1 == syntaxspec
4850 && (p1[1] == Ssymbol || p1[1] == Sword));
4851 case notsyntaxspec:
4852 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4854 case wordbeg:
4855 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4856 case symbeg:
4857 return ((re_opcode_t) *p1 == notsyntaxspec
4858 && (p1[1] == Ssymbol || p1[1] == Sword));
4859 case syntaxspec:
4860 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4862 case wordbound:
4863 return (((re_opcode_t) *p1 == notsyntaxspec
4864 || (re_opcode_t) *p1 == syntaxspec)
4865 && p1[1] == Sword);
4867 #ifdef emacs
4868 case categoryspec:
4869 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4870 case notcategoryspec:
4871 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4872 #endif /* emacs */
4874 default:
4878 /* Safe default. */
4879 return 0;
4883 /* Matching routines. */
4885 #ifndef emacs /* Emacs never uses this. */
4886 /* re_match is like re_match_2 except it takes only a single string. */
4888 regoff_t
4889 re_match (struct re_pattern_buffer *bufp, const char *string,
4890 size_t size, ssize_t pos, struct re_registers *regs)
4892 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4893 size, pos, regs, size);
4894 return result;
4896 WEAK_ALIAS (__re_match, re_match)
4897 #endif /* not emacs */
4899 #ifdef emacs
4900 /* In Emacs, this is the string or buffer in which we
4901 are matching. It is used for looking up syntax properties. */
4902 Lisp_Object re_match_object;
4903 #endif
4905 /* re_match_2 matches the compiled pattern in BUFP against the
4906 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4907 and SIZE2, respectively). We start matching at POS, and stop
4908 matching at STOP.
4910 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4911 store offsets for the substring each group matched in REGS. See the
4912 documentation for exactly how many groups we fill.
4914 We return -1 if no match, -2 if an internal error (such as the
4915 failure stack overflowing). Otherwise, we return the length of the
4916 matched substring. */
4918 regoff_t
4919 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4920 size_t size1, const char *string2, size_t size2, ssize_t pos,
4921 struct re_registers *regs, ssize_t stop)
4923 regoff_t result;
4925 #ifdef emacs
4926 ssize_t charpos;
4927 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4928 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4929 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4930 #endif
4932 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4933 (re_char*) string2, size2,
4934 pos, regs, stop);
4935 return result;
4937 WEAK_ALIAS (__re_match_2, re_match_2)
4940 /* This is a separate function so that we can force an alloca cleanup
4941 afterwards. */
4942 static regoff_t
4943 re_match_2_internal (struct re_pattern_buffer *bufp, const re_char *string1,
4944 size_t size1, const re_char *string2, size_t size2,
4945 ssize_t pos, struct re_registers *regs, ssize_t stop)
4947 /* General temporaries. */
4948 ssize_t mcnt;
4949 size_t reg;
4951 /* Just past the end of the corresponding string. */
4952 re_char *end1, *end2;
4954 /* Pointers into string1 and string2, just past the last characters in
4955 each to consider matching. */
4956 re_char *end_match_1, *end_match_2;
4958 /* Where we are in the data, and the end of the current string. */
4959 re_char *d, *dend;
4961 /* Used sometimes to remember where we were before starting matching
4962 an operator so that we can go back in case of failure. This "atomic"
4963 behavior of matching opcodes is indispensable to the correctness
4964 of the on_failure_keep_string_jump optimization. */
4965 re_char *dfail;
4967 /* Where we are in the pattern, and the end of the pattern. */
4968 re_char *p = bufp->buffer;
4969 re_char *pend = p + bufp->used;
4971 /* We use this to map every character in the string. */
4972 RE_TRANSLATE_TYPE translate = bufp->translate;
4974 /* Nonzero if BUFP is setup from a multibyte regex. */
4975 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4977 /* Nonzero if STRING1/STRING2 are multibyte. */
4978 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4980 /* Failure point stack. Each place that can handle a failure further
4981 down the line pushes a failure point on this stack. It consists of
4982 regstart, and regend for all registers corresponding to
4983 the subexpressions we're currently inside, plus the number of such
4984 registers, and, finally, two char *'s. The first char * is where
4985 to resume scanning the pattern; the second one is where to resume
4986 scanning the strings. */
4987 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4988 fail_stack_type fail_stack;
4989 #endif
4990 #ifdef DEBUG
4991 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4992 #endif
4994 #if defined REL_ALLOC && defined REGEX_MALLOC
4995 /* This holds the pointer to the failure stack, when
4996 it is allocated relocatably. */
4997 fail_stack_elt_t *failure_stack_ptr;
4998 #endif
5000 /* We fill all the registers internally, independent of what we
5001 return, for use in backreferences. The number here includes
5002 an element for register zero. */
5003 size_t num_regs = bufp->re_nsub + 1;
5005 /* Information on the contents of registers. These are pointers into
5006 the input strings; they record just what was matched (on this
5007 attempt) by a subexpression part of the pattern, that is, the
5008 regnum-th regstart pointer points to where in the pattern we began
5009 matching and the regnum-th regend points to right after where we
5010 stopped matching the regnum-th subexpression. (The zeroth register
5011 keeps track of what the whole pattern matches.) */
5012 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5013 re_char **regstart, **regend;
5014 #endif
5016 /* The following record the register info as found in the above
5017 variables when we find a match better than any we've seen before.
5018 This happens as we backtrack through the failure points, which in
5019 turn happens only if we have not yet matched the entire string. */
5020 unsigned best_regs_set = false;
5021 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5022 re_char **best_regstart, **best_regend;
5023 #endif
5025 /* Logically, this is `best_regend[0]'. But we don't want to have to
5026 allocate space for that if we're not allocating space for anything
5027 else (see below). Also, we never need info about register 0 for
5028 any of the other register vectors, and it seems rather a kludge to
5029 treat `best_regend' differently than the rest. So we keep track of
5030 the end of the best match so far in a separate variable. We
5031 initialize this to NULL so that when we backtrack the first time
5032 and need to test it, it's not garbage. */
5033 re_char *match_end = NULL;
5035 #ifdef DEBUG
5036 /* Counts the total number of registers pushed. */
5037 unsigned num_regs_pushed = 0;
5038 #endif
5040 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5042 INIT_FAIL_STACK ();
5044 #ifdef MATCH_MAY_ALLOCATE
5045 /* Do not bother to initialize all the register variables if there are
5046 no groups in the pattern, as it takes a fair amount of time. If
5047 there are groups, we include space for register 0 (the whole
5048 pattern), even though we never use it, since it simplifies the
5049 array indexing. We should fix this. */
5050 if (bufp->re_nsub)
5052 regstart = REGEX_TALLOC (num_regs, re_char *);
5053 regend = REGEX_TALLOC (num_regs, re_char *);
5054 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5055 best_regend = REGEX_TALLOC (num_regs, re_char *);
5057 if (!(regstart && regend && best_regstart && best_regend))
5059 FREE_VARIABLES ();
5060 return -2;
5063 else
5065 /* We must initialize all our variables to NULL, so that
5066 `FREE_VARIABLES' doesn't try to free them. */
5067 regstart = regend = best_regstart = best_regend = NULL;
5069 #endif /* MATCH_MAY_ALLOCATE */
5071 /* The starting position is bogus. */
5072 if (pos < 0 || pos > size1 + size2)
5074 FREE_VARIABLES ();
5075 return -1;
5078 /* Initialize subexpression text positions to -1 to mark ones that no
5079 start_memory/stop_memory has been seen for. Also initialize the
5080 register information struct. */
5081 for (reg = 1; reg < num_regs; reg++)
5082 regstart[reg] = regend[reg] = NULL;
5084 /* We move `string1' into `string2' if the latter's empty -- but not if
5085 `string1' is null. */
5086 if (size2 == 0 && string1 != NULL)
5088 string2 = string1;
5089 size2 = size1;
5090 string1 = 0;
5091 size1 = 0;
5093 end1 = string1 + size1;
5094 end2 = string2 + size2;
5096 /* `p' scans through the pattern as `d' scans through the data.
5097 `dend' is the end of the input string that `d' points within. `d'
5098 is advanced into the following input string whenever necessary, but
5099 this happens before fetching; therefore, at the beginning of the
5100 loop, `d' can be pointing at the end of a string, but it cannot
5101 equal `string2'. */
5102 if (pos >= size1)
5104 /* Only match within string2. */
5105 d = string2 + pos - size1;
5106 dend = end_match_2 = string2 + stop - size1;
5107 end_match_1 = end1; /* Just to give it a value. */
5109 else
5111 if (stop < size1)
5113 /* Only match within string1. */
5114 end_match_1 = string1 + stop;
5115 /* BEWARE!
5116 When we reach end_match_1, PREFETCH normally switches to string2.
5117 But in the present case, this means that just doing a PREFETCH
5118 makes us jump from `stop' to `gap' within the string.
5119 What we really want here is for the search to stop as
5120 soon as we hit end_match_1. That's why we set end_match_2
5121 to end_match_1 (since PREFETCH fails as soon as we hit
5122 end_match_2). */
5123 end_match_2 = end_match_1;
5125 else
5126 { /* It's important to use this code when stop == size so that
5127 moving `d' from end1 to string2 will not prevent the d == dend
5128 check from catching the end of string. */
5129 end_match_1 = end1;
5130 end_match_2 = string2 + stop - size1;
5132 d = string1 + pos;
5133 dend = end_match_1;
5136 DEBUG_PRINT1 ("The compiled pattern is: ");
5137 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5138 DEBUG_PRINT1 ("The string to match is: `");
5139 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5140 DEBUG_PRINT1 ("'\n");
5142 /* This loops over pattern commands. It exits by returning from the
5143 function if the match is complete, or it drops through if the match
5144 fails at this starting point in the input data. */
5145 for (;;)
5147 DEBUG_PRINT2 ("\n%p: ", p);
5149 if (p == pend)
5150 { /* End of pattern means we might have succeeded. */
5151 DEBUG_PRINT1 ("end of pattern ... ");
5153 /* If we haven't matched the entire string, and we want the
5154 longest match, try backtracking. */
5155 if (d != end_match_2)
5157 /* 1 if this match ends in the same string (string1 or string2)
5158 as the best previous match. */
5159 boolean same_str_p = (FIRST_STRING_P (match_end)
5160 == FIRST_STRING_P (d));
5161 /* 1 if this match is the best seen so far. */
5162 boolean best_match_p;
5164 /* AIX compiler got confused when this was combined
5165 with the previous declaration. */
5166 if (same_str_p)
5167 best_match_p = d > match_end;
5168 else
5169 best_match_p = !FIRST_STRING_P (d);
5171 DEBUG_PRINT1 ("backtracking.\n");
5173 if (!FAIL_STACK_EMPTY ())
5174 { /* More failure points to try. */
5176 /* If exceeds best match so far, save it. */
5177 if (!best_regs_set || best_match_p)
5179 best_regs_set = true;
5180 match_end = d;
5182 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5184 for (reg = 1; reg < num_regs; reg++)
5186 best_regstart[reg] = regstart[reg];
5187 best_regend[reg] = regend[reg];
5190 goto fail;
5193 /* If no failure points, don't restore garbage. And if
5194 last match is real best match, don't restore second
5195 best one. */
5196 else if (best_regs_set && !best_match_p)
5198 restore_best_regs:
5199 /* Restore best match. It may happen that `dend ==
5200 end_match_1' while the restored d is in string2.
5201 For example, the pattern `x.*y.*z' against the
5202 strings `x-' and `y-z-', if the two strings are
5203 not consecutive in memory. */
5204 DEBUG_PRINT1 ("Restoring best registers.\n");
5206 d = match_end;
5207 dend = ((d >= string1 && d <= end1)
5208 ? end_match_1 : end_match_2);
5210 for (reg = 1; reg < num_regs; reg++)
5212 regstart[reg] = best_regstart[reg];
5213 regend[reg] = best_regend[reg];
5216 } /* d != end_match_2 */
5218 succeed_label:
5219 DEBUG_PRINT1 ("Accepting match.\n");
5221 /* If caller wants register contents data back, do it. */
5222 if (regs && !bufp->no_sub)
5224 /* Have the register data arrays been allocated? */
5225 if (bufp->regs_allocated == REGS_UNALLOCATED)
5226 { /* No. So allocate them with malloc. We need one
5227 extra element beyond `num_regs' for the `-1' marker
5228 GNU code uses. */
5229 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5230 regs->start = TALLOC (regs->num_regs, regoff_t);
5231 regs->end = TALLOC (regs->num_regs, regoff_t);
5232 if (regs->start == NULL || regs->end == NULL)
5234 FREE_VARIABLES ();
5235 return -2;
5237 bufp->regs_allocated = REGS_REALLOCATE;
5239 else if (bufp->regs_allocated == REGS_REALLOCATE)
5240 { /* Yes. If we need more elements than were already
5241 allocated, reallocate them. If we need fewer, just
5242 leave it alone. */
5243 if (regs->num_regs < num_regs + 1)
5245 regs->num_regs = num_regs + 1;
5246 RETALLOC (regs->start, regs->num_regs, regoff_t);
5247 RETALLOC (regs->end, regs->num_regs, regoff_t);
5248 if (regs->start == NULL || regs->end == NULL)
5250 FREE_VARIABLES ();
5251 return -2;
5255 else
5257 /* These braces fend off a "empty body in an else-statement"
5258 warning under GCC when assert expands to nothing. */
5259 assert (bufp->regs_allocated == REGS_FIXED);
5262 /* Convert the pointer data in `regstart' and `regend' to
5263 indices. Register zero has to be set differently,
5264 since we haven't kept track of any info for it. */
5265 if (regs->num_regs > 0)
5267 regs->start[0] = pos;
5268 regs->end[0] = POINTER_TO_OFFSET (d);
5271 /* Go through the first `min (num_regs, regs->num_regs)'
5272 registers, since that is all we initialized. */
5273 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
5275 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5276 regs->start[reg] = regs->end[reg] = -1;
5277 else
5279 regs->start[reg]
5280 = (regoff_t) POINTER_TO_OFFSET (regstart[reg]);
5281 regs->end[reg]
5282 = (regoff_t) POINTER_TO_OFFSET (regend[reg]);
5286 /* If the regs structure we return has more elements than
5287 were in the pattern, set the extra elements to -1. If
5288 we (re)allocated the registers, this is the case,
5289 because we always allocate enough to have at least one
5290 -1 at the end. */
5291 for (reg = num_regs; reg < regs->num_regs; reg++)
5292 regs->start[reg] = regs->end[reg] = -1;
5293 } /* regs && !bufp->no_sub */
5295 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5296 nfailure_points_pushed, nfailure_points_popped,
5297 nfailure_points_pushed - nfailure_points_popped);
5298 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5300 mcnt = POINTER_TO_OFFSET (d) - pos;
5302 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5304 FREE_VARIABLES ();
5305 return mcnt;
5308 /* Otherwise match next pattern command. */
5309 switch (*p++)
5311 /* Ignore these. Used to ignore the n of succeed_n's which
5312 currently have n == 0. */
5313 case no_op:
5314 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5315 break;
5317 case succeed:
5318 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5319 goto succeed_label;
5321 /* Match the next n pattern characters exactly. The following
5322 byte in the pattern defines n, and the n bytes after that
5323 are the characters to match. */
5324 case exactn:
5325 mcnt = *p++;
5326 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5328 /* Remember the start point to rollback upon failure. */
5329 dfail = d;
5331 #ifndef emacs
5332 /* This is written out as an if-else so we don't waste time
5333 testing `translate' inside the loop. */
5334 if (RE_TRANSLATE_P (translate))
5337 PREFETCH ();
5338 if (RE_TRANSLATE (translate, *d) != *p++)
5340 d = dfail;
5341 goto fail;
5343 d++;
5345 while (--mcnt);
5346 else
5349 PREFETCH ();
5350 if (*d++ != *p++)
5352 d = dfail;
5353 goto fail;
5356 while (--mcnt);
5357 #else /* emacs */
5358 /* The cost of testing `translate' is comparatively small. */
5359 if (target_multibyte)
5362 int pat_charlen, buf_charlen;
5363 int pat_ch, buf_ch;
5365 PREFETCH ();
5366 if (multibyte)
5367 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5368 else
5370 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5371 pat_charlen = 1;
5373 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5375 if (TRANSLATE (buf_ch) != pat_ch)
5377 d = dfail;
5378 goto fail;
5381 p += pat_charlen;
5382 d += buf_charlen;
5383 mcnt -= pat_charlen;
5385 while (mcnt > 0);
5386 else
5389 int pat_charlen;
5390 int pat_ch, buf_ch;
5392 PREFETCH ();
5393 if (multibyte)
5395 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5396 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5398 else
5400 pat_ch = *p;
5401 pat_charlen = 1;
5403 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5404 if (! CHAR_BYTE8_P (buf_ch))
5406 buf_ch = TRANSLATE (buf_ch);
5407 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5408 if (buf_ch < 0)
5409 buf_ch = *d;
5411 else
5412 buf_ch = *d;
5413 if (buf_ch != pat_ch)
5415 d = dfail;
5416 goto fail;
5418 p += pat_charlen;
5419 d++;
5421 while (--mcnt);
5422 #endif
5423 break;
5426 /* Match any character except possibly a newline or a null. */
5427 case anychar:
5429 int buf_charlen;
5430 re_wchar_t buf_ch;
5432 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5434 PREFETCH ();
5435 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5436 target_multibyte);
5437 buf_ch = TRANSLATE (buf_ch);
5439 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5440 && buf_ch == '\n')
5441 || ((bufp->syntax & RE_DOT_NOT_NULL)
5442 && buf_ch == '\000'))
5443 goto fail;
5445 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
5446 d += buf_charlen;
5448 break;
5451 case charset:
5452 case charset_not:
5454 register unsigned int c;
5455 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5456 int len;
5458 /* Start of actual range_table, or end of bitmap if there is no
5459 range table. */
5460 re_char *range_table IF_LINT (= NULL);
5462 /* Nonzero if there is a range table. */
5463 int range_table_exists;
5465 /* Number of ranges of range table. This is not included
5466 in the initial byte-length of the command. */
5467 int count = 0;
5469 /* Whether matching against a unibyte character. */
5470 boolean unibyte_char = false;
5472 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5474 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5476 if (range_table_exists)
5478 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5479 EXTRACT_NUMBER_AND_INCR (count, range_table);
5482 PREFETCH ();
5483 c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5484 if (target_multibyte)
5486 int c1;
5488 c = TRANSLATE (c);
5489 c1 = RE_CHAR_TO_UNIBYTE (c);
5490 if (c1 >= 0)
5492 unibyte_char = true;
5493 c = c1;
5496 else
5498 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5500 if (! CHAR_BYTE8_P (c1))
5502 c1 = TRANSLATE (c1);
5503 c1 = RE_CHAR_TO_UNIBYTE (c1);
5504 if (c1 >= 0)
5506 unibyte_char = true;
5507 c = c1;
5510 else
5511 unibyte_char = true;
5514 if (unibyte_char && c < (1 << BYTEWIDTH))
5515 { /* Lookup bitmap. */
5516 /* Cast to `unsigned' instead of `unsigned char' in
5517 case the bit list is a full 32 bytes long. */
5518 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5519 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5520 not = !not;
5522 #ifdef emacs
5523 else if (range_table_exists)
5525 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5527 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5528 | (class_bits & BIT_MULTIBYTE)
5529 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5530 | (class_bits & BIT_SPACE && ISSPACE (c))
5531 | (class_bits & BIT_UPPER && ISUPPER (c))
5532 | (class_bits & BIT_WORD && ISWORD (c)))
5533 not = !not;
5534 else
5535 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5537 #endif /* emacs */
5539 if (range_table_exists)
5540 p = CHARSET_RANGE_TABLE_END (range_table, count);
5541 else
5542 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5544 if (!not) goto fail;
5546 d += len;
5548 break;
5551 /* The beginning of a group is represented by start_memory.
5552 The argument is the register number. The text
5553 matched within the group is recorded (in the internal
5554 registers data structure) under the register number. */
5555 case start_memory:
5556 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5558 /* In case we need to undo this operation (via backtracking). */
5559 PUSH_FAILURE_REG ((unsigned int)*p);
5561 regstart[*p] = d;
5562 regend[*p] = NULL; /* probably unnecessary. -sm */
5563 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5565 /* Move past the register number and inner group count. */
5566 p += 1;
5567 break;
5570 /* The stop_memory opcode represents the end of a group. Its
5571 argument is the same as start_memory's: the register number. */
5572 case stop_memory:
5573 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5575 assert (!REG_UNSET (regstart[*p]));
5576 /* Strictly speaking, there should be code such as:
5578 assert (REG_UNSET (regend[*p]));
5579 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5581 But the only info to be pushed is regend[*p] and it is known to
5582 be UNSET, so there really isn't anything to push.
5583 Not pushing anything, on the other hand deprives us from the
5584 guarantee that regend[*p] is UNSET since undoing this operation
5585 will not reset its value properly. This is not important since
5586 the value will only be read on the next start_memory or at
5587 the very end and both events can only happen if this stop_memory
5588 is *not* undone. */
5590 regend[*p] = d;
5591 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5593 /* Move past the register number and the inner group count. */
5594 p += 1;
5595 break;
5598 /* \<digit> has been turned into a `duplicate' command which is
5599 followed by the numeric value of <digit> as the register number. */
5600 case duplicate:
5602 register re_char *d2, *dend2;
5603 int regno = *p++; /* Get which register to match against. */
5604 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5606 /* Can't back reference a group which we've never matched. */
5607 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5608 goto fail;
5610 /* Where in input to try to start matching. */
5611 d2 = regstart[regno];
5613 /* Remember the start point to rollback upon failure. */
5614 dfail = d;
5616 /* Where to stop matching; if both the place to start and
5617 the place to stop matching are in the same string, then
5618 set to the place to stop, otherwise, for now have to use
5619 the end of the first string. */
5621 dend2 = ((FIRST_STRING_P (regstart[regno])
5622 == FIRST_STRING_P (regend[regno]))
5623 ? regend[regno] : end_match_1);
5624 for (;;)
5626 /* If necessary, advance to next segment in register
5627 contents. */
5628 while (d2 == dend2)
5630 if (dend2 == end_match_2) break;
5631 if (dend2 == regend[regno]) break;
5633 /* End of string1 => advance to string2. */
5634 d2 = string2;
5635 dend2 = regend[regno];
5637 /* At end of register contents => success */
5638 if (d2 == dend2) break;
5640 /* If necessary, advance to next segment in data. */
5641 PREFETCH ();
5643 /* How many characters left in this segment to match. */
5644 mcnt = dend - d;
5646 /* Want how many consecutive characters we can match in
5647 one shot, so, if necessary, adjust the count. */
5648 if (mcnt > dend2 - d2)
5649 mcnt = dend2 - d2;
5651 /* Compare that many; failure if mismatch, else move
5652 past them. */
5653 if (RE_TRANSLATE_P (translate)
5654 ? bcmp_translate (d, d2, mcnt, translate, target_multibyte)
5655 : memcmp (d, d2, mcnt))
5657 d = dfail;
5658 goto fail;
5660 d += mcnt, d2 += mcnt;
5663 break;
5666 /* begline matches the empty string at the beginning of the string
5667 (unless `not_bol' is set in `bufp'), and after newlines. */
5668 case begline:
5669 DEBUG_PRINT1 ("EXECUTING begline.\n");
5671 if (AT_STRINGS_BEG (d))
5673 if (!bufp->not_bol) break;
5675 else
5677 unsigned c;
5678 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5679 if (c == '\n')
5680 break;
5682 /* In all other cases, we fail. */
5683 goto fail;
5686 /* endline is the dual of begline. */
5687 case endline:
5688 DEBUG_PRINT1 ("EXECUTING endline.\n");
5690 if (AT_STRINGS_END (d))
5692 if (!bufp->not_eol) break;
5694 else
5696 PREFETCH_NOLIMIT ();
5697 if (*d == '\n')
5698 break;
5700 goto fail;
5703 /* Match at the very beginning of the data. */
5704 case begbuf:
5705 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5706 if (AT_STRINGS_BEG (d))
5707 break;
5708 goto fail;
5711 /* Match at the very end of the data. */
5712 case endbuf:
5713 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5714 if (AT_STRINGS_END (d))
5715 break;
5716 goto fail;
5719 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5720 pushes NULL as the value for the string on the stack. Then
5721 `POP_FAILURE_POINT' will keep the current value for the
5722 string, instead of restoring it. To see why, consider
5723 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5724 then the . fails against the \n. But the next thing we want
5725 to do is match the \n against the \n; if we restored the
5726 string value, we would be back at the foo.
5728 Because this is used only in specific cases, we don't need to
5729 check all the things that `on_failure_jump' does, to make
5730 sure the right things get saved on the stack. Hence we don't
5731 share its code. The only reason to push anything on the
5732 stack at all is that otherwise we would have to change
5733 `anychar's code to do something besides goto fail in this
5734 case; that seems worse than this. */
5735 case on_failure_keep_string_jump:
5736 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5737 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5738 mcnt, p + mcnt);
5740 PUSH_FAILURE_POINT (p - 3, NULL);
5741 break;
5743 /* A nasty loop is introduced by the non-greedy *? and +?.
5744 With such loops, the stack only ever contains one failure point
5745 at a time, so that a plain on_failure_jump_loop kind of
5746 cycle detection cannot work. Worse yet, such a detection
5747 can not only fail to detect a cycle, but it can also wrongly
5748 detect a cycle (between different instantiations of the same
5749 loop).
5750 So the method used for those nasty loops is a little different:
5751 We use a special cycle-detection-stack-frame which is pushed
5752 when the on_failure_jump_nastyloop failure-point is *popped*.
5753 This special frame thus marks the beginning of one iteration
5754 through the loop and we can hence easily check right here
5755 whether something matched between the beginning and the end of
5756 the loop. */
5757 case on_failure_jump_nastyloop:
5758 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5759 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5760 mcnt, p + mcnt);
5762 assert ((re_opcode_t)p[-4] == no_op);
5764 int cycle = 0;
5765 CHECK_INFINITE_LOOP (p - 4, d);
5766 if (!cycle)
5767 /* If there's a cycle, just continue without pushing
5768 this failure point. The failure point is the "try again"
5769 option, which shouldn't be tried.
5770 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5771 PUSH_FAILURE_POINT (p - 3, d);
5773 break;
5775 /* Simple loop detecting on_failure_jump: just check on the
5776 failure stack if the same spot was already hit earlier. */
5777 case on_failure_jump_loop:
5778 on_failure:
5779 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5780 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5781 mcnt, p + mcnt);
5783 int cycle = 0;
5784 CHECK_INFINITE_LOOP (p - 3, d);
5785 if (cycle)
5786 /* If there's a cycle, get out of the loop, as if the matching
5787 had failed. We used to just `goto fail' here, but that was
5788 aborting the search a bit too early: we want to keep the
5789 empty-loop-match and keep matching after the loop.
5790 We want (x?)*y\1z to match both xxyz and xxyxz. */
5791 p += mcnt;
5792 else
5793 PUSH_FAILURE_POINT (p - 3, d);
5795 break;
5798 /* Uses of on_failure_jump:
5800 Each alternative starts with an on_failure_jump that points
5801 to the beginning of the next alternative. Each alternative
5802 except the last ends with a jump that in effect jumps past
5803 the rest of the alternatives. (They really jump to the
5804 ending jump of the following alternative, because tensioning
5805 these jumps is a hassle.)
5807 Repeats start with an on_failure_jump that points past both
5808 the repetition text and either the following jump or
5809 pop_failure_jump back to this on_failure_jump. */
5810 case on_failure_jump:
5811 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5812 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5813 mcnt, p + mcnt);
5815 PUSH_FAILURE_POINT (p -3, d);
5816 break;
5818 /* This operation is used for greedy *.
5819 Compare the beginning of the repeat with what in the
5820 pattern follows its end. If we can establish that there
5821 is nothing that they would both match, i.e., that we
5822 would have to backtrack because of (as in, e.g., `a*a')
5823 then we can use a non-backtracking loop based on
5824 on_failure_keep_string_jump instead of on_failure_jump. */
5825 case on_failure_jump_smart:
5826 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5827 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5828 mcnt, p + mcnt);
5830 re_char *p1 = p; /* Next operation. */
5831 /* Here, we discard `const', making re_match non-reentrant. */
5832 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5833 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5835 p -= 3; /* Reset so that we will re-execute the
5836 instruction once it's been changed. */
5838 EXTRACT_NUMBER (mcnt, p2 - 2);
5840 /* Ensure this is a indeed the trivial kind of loop
5841 we are expecting. */
5842 assert (skip_one_char (p1) == p2 - 3);
5843 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5844 DEBUG_STATEMENT (debug += 2);
5845 if (mutually_exclusive_p (bufp, p1, p2))
5847 /* Use a fast `on_failure_keep_string_jump' loop. */
5848 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5849 *p3 = (unsigned char) on_failure_keep_string_jump;
5850 STORE_NUMBER (p2 - 2, mcnt + 3);
5852 else
5854 /* Default to a safe `on_failure_jump' loop. */
5855 DEBUG_PRINT1 (" smart default => slow loop.\n");
5856 *p3 = (unsigned char) on_failure_jump;
5858 DEBUG_STATEMENT (debug -= 2);
5860 break;
5862 /* Unconditionally jump (without popping any failure points). */
5863 case jump:
5864 unconditional_jump:
5865 IMMEDIATE_QUIT_CHECK;
5866 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5867 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5868 p += mcnt; /* Do the jump. */
5869 DEBUG_PRINT2 ("(to %p).\n", p);
5870 break;
5873 /* Have to succeed matching what follows at least n times.
5874 After that, handle like `on_failure_jump'. */
5875 case succeed_n:
5876 /* Signedness doesn't matter since we only compare MCNT to 0. */
5877 EXTRACT_NUMBER (mcnt, p + 2);
5878 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5880 /* Originally, mcnt is how many times we HAVE to succeed. */
5881 if (mcnt != 0)
5883 /* Here, we discard `const', making re_match non-reentrant. */
5884 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5885 mcnt--;
5886 p += 4;
5887 PUSH_NUMBER (p2, mcnt);
5889 else
5890 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5891 goto on_failure;
5892 break;
5894 case jump_n:
5895 /* Signedness doesn't matter since we only compare MCNT to 0. */
5896 EXTRACT_NUMBER (mcnt, p + 2);
5897 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5899 /* Originally, this is how many times we CAN jump. */
5900 if (mcnt != 0)
5902 /* Here, we discard `const', making re_match non-reentrant. */
5903 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5904 mcnt--;
5905 PUSH_NUMBER (p2, mcnt);
5906 goto unconditional_jump;
5908 /* If don't have to jump any more, skip over the rest of command. */
5909 else
5910 p += 4;
5911 break;
5913 case set_number_at:
5915 unsigned char *p2; /* Location of the counter. */
5916 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5918 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5919 /* Here, we discard `const', making re_match non-reentrant. */
5920 p2 = (unsigned char*) p + mcnt;
5921 /* Signedness doesn't matter since we only copy MCNT's bits . */
5922 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5923 DEBUG_PRINT3 (" Setting %p to %d.\n", p2, mcnt);
5924 PUSH_NUMBER (p2, mcnt);
5925 break;
5928 case wordbound:
5929 case notwordbound:
5931 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5932 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5934 /* We SUCCEED (or FAIL) in one of the following cases: */
5936 /* Case 1: D is at the beginning or the end of string. */
5937 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5938 not = !not;
5939 else
5941 /* C1 is the character before D, S1 is the syntax of C1, C2
5942 is the character at D, and S2 is the syntax of C2. */
5943 re_wchar_t c1, c2;
5944 int s1, s2;
5945 int dummy;
5946 #ifdef emacs
5947 ssize_t offset = PTR_TO_OFFSET (d - 1);
5948 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5949 UPDATE_SYNTAX_TABLE (charpos);
5950 #endif
5951 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5952 s1 = SYNTAX (c1);
5953 #ifdef emacs
5954 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5955 #endif
5956 PREFETCH_NOLIMIT ();
5957 GET_CHAR_AFTER (c2, d, dummy);
5958 s2 = SYNTAX (c2);
5960 if (/* Case 2: Only one of S1 and S2 is Sword. */
5961 ((s1 == Sword) != (s2 == Sword))
5962 /* Case 3: Both of S1 and S2 are Sword, and macro
5963 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5964 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5965 not = !not;
5967 if (not)
5968 break;
5969 else
5970 goto fail;
5973 case wordbeg:
5974 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5976 /* We FAIL in one of the following cases: */
5978 /* Case 1: D is at the end of string. */
5979 if (AT_STRINGS_END (d))
5980 goto fail;
5981 else
5983 /* C1 is the character before D, S1 is the syntax of C1, C2
5984 is the character at D, and S2 is the syntax of C2. */
5985 re_wchar_t c1, c2;
5986 int s1, s2;
5987 int dummy;
5988 #ifdef emacs
5989 ssize_t offset = PTR_TO_OFFSET (d);
5990 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5991 UPDATE_SYNTAX_TABLE (charpos);
5992 #endif
5993 PREFETCH ();
5994 GET_CHAR_AFTER (c2, d, dummy);
5995 s2 = SYNTAX (c2);
5997 /* Case 2: S2 is not Sword. */
5998 if (s2 != Sword)
5999 goto fail;
6001 /* Case 3: D is not at the beginning of string ... */
6002 if (!AT_STRINGS_BEG (d))
6004 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6005 #ifdef emacs
6006 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6007 #endif
6008 s1 = SYNTAX (c1);
6010 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6011 returns 0. */
6012 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6013 goto fail;
6016 break;
6018 case wordend:
6019 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6021 /* We FAIL in one of the following cases: */
6023 /* Case 1: D is at the beginning of string. */
6024 if (AT_STRINGS_BEG (d))
6025 goto fail;
6026 else
6028 /* C1 is the character before D, S1 is the syntax of C1, C2
6029 is the character at D, and S2 is the syntax of C2. */
6030 re_wchar_t c1, c2;
6031 int s1, s2;
6032 int dummy;
6033 #ifdef emacs
6034 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6035 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6036 UPDATE_SYNTAX_TABLE (charpos);
6037 #endif
6038 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6039 s1 = SYNTAX (c1);
6041 /* Case 2: S1 is not Sword. */
6042 if (s1 != Sword)
6043 goto fail;
6045 /* Case 3: D is not at the end of string ... */
6046 if (!AT_STRINGS_END (d))
6048 PREFETCH_NOLIMIT ();
6049 GET_CHAR_AFTER (c2, d, dummy);
6050 #ifdef emacs
6051 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
6052 #endif
6053 s2 = SYNTAX (c2);
6055 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6056 returns 0. */
6057 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6058 goto fail;
6061 break;
6063 case symbeg:
6064 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6066 /* We FAIL in one of the following cases: */
6068 /* Case 1: D is at the end of string. */
6069 if (AT_STRINGS_END (d))
6070 goto fail;
6071 else
6073 /* C1 is the character before D, S1 is the syntax of C1, C2
6074 is the character at D, and S2 is the syntax of C2. */
6075 re_wchar_t c1, c2;
6076 int s1, s2;
6077 #ifdef emacs
6078 ssize_t offset = PTR_TO_OFFSET (d);
6079 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6080 UPDATE_SYNTAX_TABLE (charpos);
6081 #endif
6082 PREFETCH ();
6083 c2 = RE_STRING_CHAR (d, target_multibyte);
6084 s2 = SYNTAX (c2);
6086 /* Case 2: S2 is neither Sword nor Ssymbol. */
6087 if (s2 != Sword && s2 != Ssymbol)
6088 goto fail;
6090 /* Case 3: D is not at the beginning of string ... */
6091 if (!AT_STRINGS_BEG (d))
6093 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6094 #ifdef emacs
6095 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6096 #endif
6097 s1 = SYNTAX (c1);
6099 /* ... and S1 is Sword or Ssymbol. */
6100 if (s1 == Sword || s1 == Ssymbol)
6101 goto fail;
6104 break;
6106 case symend:
6107 DEBUG_PRINT1 ("EXECUTING symend.\n");
6109 /* We FAIL in one of the following cases: */
6111 /* Case 1: D is at the beginning of string. */
6112 if (AT_STRINGS_BEG (d))
6113 goto fail;
6114 else
6116 /* C1 is the character before D, S1 is the syntax of C1, C2
6117 is the character at D, and S2 is the syntax of C2. */
6118 re_wchar_t c1, c2;
6119 int s1, s2;
6120 #ifdef emacs
6121 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6122 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6123 UPDATE_SYNTAX_TABLE (charpos);
6124 #endif
6125 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6126 s1 = SYNTAX (c1);
6128 /* Case 2: S1 is neither Ssymbol nor Sword. */
6129 if (s1 != Sword && s1 != Ssymbol)
6130 goto fail;
6132 /* Case 3: D is not at the end of string ... */
6133 if (!AT_STRINGS_END (d))
6135 PREFETCH_NOLIMIT ();
6136 c2 = RE_STRING_CHAR (d, target_multibyte);
6137 #ifdef emacs
6138 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6139 #endif
6140 s2 = SYNTAX (c2);
6142 /* ... and S2 is Sword or Ssymbol. */
6143 if (s2 == Sword || s2 == Ssymbol)
6144 goto fail;
6147 break;
6149 case syntaxspec:
6150 case notsyntaxspec:
6152 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6153 mcnt = *p++;
6154 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
6155 PREFETCH ();
6156 #ifdef emacs
6158 ssize_t offset = PTR_TO_OFFSET (d);
6159 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6160 UPDATE_SYNTAX_TABLE (pos1);
6162 #endif
6164 int len;
6165 re_wchar_t c;
6167 GET_CHAR_AFTER (c, d, len);
6168 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6169 goto fail;
6170 d += len;
6173 break;
6175 #ifdef emacs
6176 case before_dot:
6177 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6178 if (PTR_BYTE_POS (d) >= PT_BYTE)
6179 goto fail;
6180 break;
6182 case at_dot:
6183 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6184 if (PTR_BYTE_POS (d) != PT_BYTE)
6185 goto fail;
6186 break;
6188 case after_dot:
6189 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6190 if (PTR_BYTE_POS (d) <= PT_BYTE)
6191 goto fail;
6192 break;
6194 case categoryspec:
6195 case notcategoryspec:
6197 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6198 mcnt = *p++;
6199 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n",
6200 not?"not":"", mcnt);
6201 PREFETCH ();
6204 int len;
6205 re_wchar_t c;
6206 GET_CHAR_AFTER (c, d, len);
6207 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6208 goto fail;
6209 d += len;
6212 break;
6214 #endif /* emacs */
6216 default:
6217 abort ();
6219 continue; /* Successfully executed one pattern command; keep going. */
6222 /* We goto here if a matching operation fails. */
6223 fail:
6224 IMMEDIATE_QUIT_CHECK;
6225 if (!FAIL_STACK_EMPTY ())
6227 re_char *str, *pat;
6228 /* A restart point is known. Restore to that state. */
6229 DEBUG_PRINT1 ("\nFAIL:\n");
6230 POP_FAILURE_POINT (str, pat);
6231 switch (*pat++)
6233 case on_failure_keep_string_jump:
6234 assert (str == NULL);
6235 goto continue_failure_jump;
6237 case on_failure_jump_nastyloop:
6238 assert ((re_opcode_t)pat[-2] == no_op);
6239 PUSH_FAILURE_POINT (pat - 2, str);
6240 /* Fallthrough */
6242 case on_failure_jump_loop:
6243 case on_failure_jump:
6244 case succeed_n:
6245 d = str;
6246 continue_failure_jump:
6247 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6248 p = pat + mcnt;
6249 break;
6251 case no_op:
6252 /* A special frame used for nastyloops. */
6253 goto fail;
6255 default:
6256 abort ();
6259 assert (p >= bufp->buffer && p <= pend);
6261 if (d >= string1 && d <= end1)
6262 dend = end_match_1;
6264 else
6265 break; /* Matching at this starting point really fails. */
6266 } /* for (;;) */
6268 if (best_regs_set)
6269 goto restore_best_regs;
6271 FREE_VARIABLES ();
6273 return -1; /* Failure to match. */
6274 } /* re_match_2 */
6276 /* Subroutine definitions for re_match_2. */
6278 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6279 bytes; nonzero otherwise. */
6281 static int
6282 bcmp_translate (const re_char *s1, const re_char *s2, register ssize_t len,
6283 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6285 register re_char *p1 = s1, *p2 = s2;
6286 re_char *p1_end = s1 + len;
6287 re_char *p2_end = s2 + len;
6289 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6290 different lengths, but relying on a single `len' would break this. -sm */
6291 while (p1 < p1_end && p2 < p2_end)
6293 int p1_charlen, p2_charlen;
6294 re_wchar_t p1_ch, p2_ch;
6296 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6297 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6299 if (RE_TRANSLATE (translate, p1_ch)
6300 != RE_TRANSLATE (translate, p2_ch))
6301 return 1;
6303 p1 += p1_charlen, p2 += p2_charlen;
6306 if (p1 != p1_end || p2 != p2_end)
6307 return 1;
6309 return 0;
6312 /* Entry points for GNU code. */
6314 /* re_compile_pattern is the GNU regular expression compiler: it
6315 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6316 Returns 0 if the pattern was valid, otherwise an error string.
6318 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6319 are set in BUFP on entry.
6321 We call regex_compile to do the actual compilation. */
6323 const char *
6324 re_compile_pattern (const char *pattern, size_t length,
6325 struct re_pattern_buffer *bufp)
6327 reg_errcode_t ret;
6329 /* GNU code is written to assume at least RE_NREGS registers will be set
6330 (and at least one extra will be -1). */
6331 bufp->regs_allocated = REGS_UNALLOCATED;
6333 /* And GNU code determines whether or not to get register information
6334 by passing null for the REGS argument to re_match, etc., not by
6335 setting no_sub. */
6336 bufp->no_sub = 0;
6338 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
6340 if (!ret)
6341 return NULL;
6342 return gettext (re_error_msgid[(int) ret]);
6344 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6346 /* Entry points compatible with 4.2 BSD regex library. We don't define
6347 them unless specifically requested. */
6349 #if defined _REGEX_RE_COMP || defined _LIBC
6351 /* BSD has one and only one pattern buffer. */
6352 static struct re_pattern_buffer re_comp_buf;
6354 char *
6355 # ifdef _LIBC
6356 /* Make these definitions weak in libc, so POSIX programs can redefine
6357 these names if they don't use our functions, and still use
6358 regcomp/regexec below without link errors. */
6359 weak_function
6360 # endif
6361 re_comp (const char *s)
6363 reg_errcode_t ret;
6365 if (!s)
6367 if (!re_comp_buf.buffer)
6368 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6369 return (char *) gettext ("No previous regular expression");
6370 return 0;
6373 if (!re_comp_buf.buffer)
6375 re_comp_buf.buffer = malloc (200);
6376 if (re_comp_buf.buffer == NULL)
6377 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6378 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6379 re_comp_buf.allocated = 200;
6381 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6382 if (re_comp_buf.fastmap == NULL)
6383 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6384 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6387 /* Since `re_exec' always passes NULL for the `regs' argument, we
6388 don't need to initialize the pattern buffer fields which affect it. */
6390 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6392 if (!ret)
6393 return NULL;
6395 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6396 return (char *) gettext (re_error_msgid[(int) ret]);
6401 # ifdef _LIBC
6402 weak_function
6403 # endif
6404 re_exec (const char *s)
6406 const size_t len = strlen (s);
6407 return
6408 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6410 #endif /* _REGEX_RE_COMP */
6412 /* POSIX.2 functions. Don't define these for Emacs. */
6414 #ifndef emacs
6416 /* regcomp takes a regular expression as a string and compiles it.
6418 PREG is a regex_t *. We do not expect any fields to be initialized,
6419 since POSIX says we shouldn't. Thus, we set
6421 `buffer' to the compiled pattern;
6422 `used' to the length of the compiled pattern;
6423 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6424 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6425 RE_SYNTAX_POSIX_BASIC;
6426 `fastmap' to an allocated space for the fastmap;
6427 `fastmap_accurate' to zero;
6428 `re_nsub' to the number of subexpressions in PATTERN.
6430 PATTERN is the address of the pattern string.
6432 CFLAGS is a series of bits which affect compilation.
6434 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6435 use POSIX basic syntax.
6437 If REG_NEWLINE is set, then . and [^...] don't match newline.
6438 Also, regexec will try a match beginning after every newline.
6440 If REG_ICASE is set, then we considers upper- and lowercase
6441 versions of letters to be equivalent when matching.
6443 If REG_NOSUB is set, then when PREG is passed to regexec, that
6444 routine will report only success or failure, and nothing about the
6445 registers.
6447 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6448 the return codes and their meanings.) */
6450 reg_errcode_t
6451 regcomp (regex_t *__restrict preg, const char *__restrict pattern,
6452 int cflags)
6454 reg_errcode_t ret;
6455 reg_syntax_t syntax
6456 = (cflags & REG_EXTENDED) ?
6457 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6459 /* regex_compile will allocate the space for the compiled pattern. */
6460 preg->buffer = 0;
6461 preg->allocated = 0;
6462 preg->used = 0;
6464 /* Try to allocate space for the fastmap. */
6465 preg->fastmap = malloc (1 << BYTEWIDTH);
6467 if (cflags & REG_ICASE)
6469 unsigned i;
6471 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6472 if (preg->translate == NULL)
6473 return (int) REG_ESPACE;
6475 /* Map uppercase characters to corresponding lowercase ones. */
6476 for (i = 0; i < CHAR_SET_SIZE; i++)
6477 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6479 else
6480 preg->translate = NULL;
6482 /* If REG_NEWLINE is set, newlines are treated differently. */
6483 if (cflags & REG_NEWLINE)
6484 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6485 syntax &= ~RE_DOT_NEWLINE;
6486 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6488 else
6489 syntax |= RE_NO_NEWLINE_ANCHOR;
6491 preg->no_sub = !!(cflags & REG_NOSUB);
6493 /* POSIX says a null character in the pattern terminates it, so we
6494 can use strlen here in compiling the pattern. */
6495 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6497 /* POSIX doesn't distinguish between an unmatched open-group and an
6498 unmatched close-group: both are REG_EPAREN. */
6499 if (ret == REG_ERPAREN)
6500 ret = REG_EPAREN;
6502 if (ret == REG_NOERROR && preg->fastmap)
6503 { /* Compute the fastmap now, since regexec cannot modify the pattern
6504 buffer. */
6505 re_compile_fastmap (preg);
6506 if (preg->can_be_null)
6507 { /* The fastmap can't be used anyway. */
6508 free (preg->fastmap);
6509 preg->fastmap = NULL;
6512 return ret;
6514 WEAK_ALIAS (__regcomp, regcomp)
6517 /* regexec searches for a given pattern, specified by PREG, in the
6518 string STRING.
6520 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6521 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6522 least NMATCH elements, and we set them to the offsets of the
6523 corresponding matched substrings.
6525 EFLAGS specifies `execution flags' which affect matching: if
6526 REG_NOTBOL is set, then ^ does not match at the beginning of the
6527 string; if REG_NOTEOL is set, then $ does not match at the end.
6529 We return 0 if we find a match and REG_NOMATCH if not. */
6531 reg_errcode_t
6532 regexec (const regex_t *__restrict preg, const char *__restrict string,
6533 size_t nmatch, regmatch_t pmatch[__restrict_arr], int eflags)
6535 regoff_t ret;
6536 struct re_registers regs;
6537 regex_t private_preg;
6538 size_t len = strlen (string);
6539 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6541 private_preg = *preg;
6543 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6544 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6546 /* The user has told us exactly how many registers to return
6547 information about, via `nmatch'. We have to pass that on to the
6548 matching routines. */
6549 private_preg.regs_allocated = REGS_FIXED;
6551 if (want_reg_info)
6553 regs.num_regs = nmatch;
6554 regs.start = TALLOC (nmatch * 2, regoff_t);
6555 if (regs.start == NULL)
6556 return REG_NOMATCH;
6557 regs.end = regs.start + nmatch;
6560 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6561 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6562 was a little bit longer but still only matching the real part.
6563 This works because the `endline' will check for a '\n' and will find a
6564 '\0', correctly deciding that this is not the end of a line.
6565 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6566 a convenient '\0' there. For all we know, the string could be preceded
6567 by '\n' which would throw things off. */
6569 /* Perform the searching operation. */
6570 ret = re_search (&private_preg, string, len,
6571 /* start: */ 0, /* range: */ len,
6572 want_reg_info ? &regs : (struct re_registers *) 0);
6574 /* Copy the register information to the POSIX structure. */
6575 if (want_reg_info)
6577 if (ret >= 0)
6579 unsigned r;
6581 for (r = 0; r < nmatch; r++)
6583 pmatch[r].rm_so = regs.start[r];
6584 pmatch[r].rm_eo = regs.end[r];
6588 /* If we needed the temporary register info, free the space now. */
6589 free (regs.start);
6592 /* We want zero return to mean success, unlike `re_search'. */
6593 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6595 WEAK_ALIAS (__regexec, regexec)
6598 /* Returns a message corresponding to an error code, ERR_CODE, returned
6599 from either regcomp or regexec. We don't use PREG here.
6601 ERR_CODE was previously called ERRCODE, but that name causes an
6602 error with msvc8 compiler. */
6604 size_t
6605 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6607 const char *msg;
6608 size_t msg_size;
6610 if (err_code < 0
6611 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6612 /* Only error codes returned by the rest of the code should be passed
6613 to this routine. If we are given anything else, or if other regex
6614 code generates an invalid error code, then the program has a bug.
6615 Dump core so we can fix it. */
6616 abort ();
6618 msg = gettext (re_error_msgid[err_code]);
6620 msg_size = strlen (msg) + 1; /* Includes the null. */
6622 if (errbuf_size != 0)
6624 if (msg_size > errbuf_size)
6626 memcpy (errbuf, msg, errbuf_size - 1);
6627 errbuf[errbuf_size - 1] = 0;
6629 else
6630 strcpy (errbuf, msg);
6633 return msg_size;
6635 WEAK_ALIAS (__regerror, regerror)
6638 /* Free dynamically allocated space used by PREG. */
6640 void
6641 regfree (regex_t *preg)
6643 free (preg->buffer);
6644 preg->buffer = NULL;
6646 preg->allocated = 0;
6647 preg->used = 0;
6649 free (preg->fastmap);
6650 preg->fastmap = NULL;
6651 preg->fastmap_accurate = 0;
6653 free (preg->translate);
6654 preg->translate = NULL;
6656 WEAK_ALIAS (__regfree, regfree)
6658 #endif /* not emacs */