Add missing copyright years.
[emacs.git] / src / regex.c
blob6afbbb6d193e176aee828393877db635eb3bbb1d
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, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
6 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
7 Free Software Foundation, Inc.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
22 USA. */
24 /* TODO:
25 - structure the opcode space into opcode+flag.
26 - merge with glibc's regex.[ch].
27 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
28 need to modify the compiled regexp so that re_match can be reentrant.
29 - get rid of on_failure_jump_smart by doing the optimization in re_comp
30 rather than at run-time, so that re_match can be reentrant.
33 /* AIX requires this to be the first thing in the file. */
34 #if defined _AIX && !defined REGEX_MALLOC
35 #pragma alloca
36 #endif
38 #ifdef HAVE_CONFIG_H
39 # include <config.h>
40 #endif
42 #if defined STDC_HEADERS && !defined emacs
43 # include <stddef.h>
44 #else
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
47 #endif
49 /* Whether to use ISO C Amendment 1 wide char functions.
50 Those should not be used for Emacs since it uses its own. */
51 #if defined _LIBC
52 #define WIDE_CHAR_SUPPORT 1
53 #else
54 #define WIDE_CHAR_SUPPORT \
55 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
56 #endif
58 /* For platform which support the ISO C amendement 1 functionality we
59 support user defined character classes. */
60 #if WIDE_CHAR_SUPPORT
61 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
62 # include <wchar.h>
63 # include <wctype.h>
64 #endif
66 #ifdef _LIBC
67 /* We have to keep the namespace clean. */
68 # define regfree(preg) __regfree (preg)
69 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
70 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
71 # define regerror(err_code, preg, errbuf, errbuf_size) \
72 __regerror(err_code, preg, errbuf, errbuf_size)
73 # define re_set_registers(bu, re, nu, st, en) \
74 __re_set_registers (bu, re, nu, st, en)
75 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
76 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
77 # define re_match(bufp, string, size, pos, regs) \
78 __re_match (bufp, string, size, pos, regs)
79 # define re_search(bufp, string, size, startpos, range, regs) \
80 __re_search (bufp, string, size, startpos, range, regs)
81 # define re_compile_pattern(pattern, length, bufp) \
82 __re_compile_pattern (pattern, length, bufp)
83 # define re_set_syntax(syntax) __re_set_syntax (syntax)
84 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
85 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
86 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
88 /* Make sure we call libc's function even if the user overrides them. */
89 # define btowc __btowc
90 # define iswctype __iswctype
91 # define wctype __wctype
93 # define WEAK_ALIAS(a,b) weak_alias (a, b)
95 /* We are also using some library internals. */
96 # include <locale/localeinfo.h>
97 # include <locale/elem-hash.h>
98 # include <langinfo.h>
99 #else
100 # define WEAK_ALIAS(a,b)
101 #endif
103 /* This is for other GNU distributions with internationalized messages. */
104 #if HAVE_LIBINTL_H || defined _LIBC
105 # include <libintl.h>
106 #else
107 # define gettext(msgid) (msgid)
108 #endif
110 #ifndef gettext_noop
111 /* This define is so xgettext can find the internationalizable
112 strings. */
113 # define gettext_noop(String) String
114 #endif
116 /* The `emacs' switch turns on certain matching commands
117 that make sense only in Emacs. */
118 #ifdef emacs
120 # include <setjmp.h>
121 # include "lisp.h"
122 # include "buffer.h"
124 /* Make syntax table lookup grant data in gl_state. */
125 # define SYNTAX_ENTRY_VIA_PROPERTY
127 # include "syntax.h"
128 # include "character.h"
129 # include "category.h"
131 # ifdef malloc
132 # undef malloc
133 # endif
134 # define malloc xmalloc
135 # ifdef realloc
136 # undef realloc
137 # endif
138 # define realloc xrealloc
139 # ifdef free
140 # undef free
141 # endif
142 # define free xfree
144 /* Converts the pointer to the char to BEG-based offset from the start. */
145 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
146 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
148 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
149 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
150 # define RE_STRING_CHAR(p, multibyte) \
151 (multibyte ? (STRING_CHAR (p)) : (*(p)))
152 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
153 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
155 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
157 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
159 /* Set C a (possibly converted to multibyte) character before P. P
160 points into a string which is the virtual concatenation of STR1
161 (which ends at END1) or STR2 (which ends at END2). */
162 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
163 do { \
164 if (target_multibyte) \
166 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
167 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
168 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
169 c = STRING_CHAR (dtemp); \
171 else \
173 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
174 (c) = RE_CHAR_TO_MULTIBYTE (c); \
176 } while (0)
178 /* Set C a (possibly converted to multibyte) character at P, and set
179 LEN to the byte length of that character. */
180 # define GET_CHAR_AFTER(c, p, len) \
181 do { \
182 if (target_multibyte) \
183 (c) = STRING_CHAR_AND_LENGTH (p, len); \
184 else \
186 (c) = *p; \
187 len = 1; \
188 (c) = RE_CHAR_TO_MULTIBYTE (c); \
190 } while (0)
192 #else /* not emacs */
194 /* If we are not linking with Emacs proper,
195 we can't use the relocating allocator
196 even if config.h says that we can. */
197 # undef REL_ALLOC
199 # include <unistd.h>
201 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
203 void *
204 xmalloc (size_t size)
206 register void *val;
207 val = (void *) malloc (size);
208 if (!val && size)
210 write (2, "virtual memory exhausted\n", 25);
211 exit (1);
213 return val;
216 void *
217 xrealloc (void *block, size_t size)
219 register void *val;
220 /* We must call malloc explicitly when BLOCK is 0, since some
221 reallocs don't do this. */
222 if (! block)
223 val = (void *) malloc (size);
224 else
225 val = (void *) realloc (block, size);
226 if (!val && size)
228 write (2, "virtual memory exhausted\n", 25);
229 exit (1);
231 return val;
234 # ifdef malloc
235 # undef malloc
236 # endif
237 # define malloc xmalloc
238 # ifdef realloc
239 # undef realloc
240 # endif
241 # define realloc xrealloc
243 /* This is the normal way of making sure we have memcpy, memcmp and memset. */
244 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
245 # include <string.h>
246 # else
247 # include <strings.h>
248 # ifndef memcmp
249 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
250 # endif
251 # ifndef memcpy
252 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
253 # endif
254 # endif
256 /* Define the syntax stuff for \<, \>, etc. */
258 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
259 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
261 # define SWITCH_ENUM_CAST(x) (x)
263 /* Dummy macros for non-Emacs environments. */
264 # define CHAR_CHARSET(c) 0
265 # define CHARSET_LEADING_CODE_BASE(c) 0
266 # define MAX_MULTIBYTE_LENGTH 1
267 # define RE_MULTIBYTE_P(x) 0
268 # define RE_TARGET_MULTIBYTE_P(x) 0
269 # define WORD_BOUNDARY_P(c1, c2) (0)
270 # define CHAR_HEAD_P(p) (1)
271 # define SINGLE_BYTE_CHAR_P(c) (1)
272 # define SAME_CHARSET_P(c1, c2) (1)
273 # define BYTES_BY_CHAR_HEAD(p) (1)
274 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
275 # define STRING_CHAR(p) (*(p))
276 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
277 # define CHAR_STRING(c, s) (*(s) = (c), 1)
278 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
279 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
280 # define RE_CHAR_TO_MULTIBYTE(c) (c)
281 # define RE_CHAR_TO_UNIBYTE(c) (c)
282 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
283 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
284 # define GET_CHAR_AFTER(c, p, len) \
285 (c = *p, len = 1)
286 # define MAKE_CHAR(charset, c1, c2) (c1)
287 # define BYTE8_TO_CHAR(c) (c)
288 # define CHAR_BYTE8_P(c) (0)
289 # define CHAR_LEADING_CODE(c) (c)
291 #endif /* not emacs */
293 #ifndef RE_TRANSLATE
294 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
295 # define RE_TRANSLATE_P(TBL) (TBL)
296 #endif
298 /* Get the interface, including the syntax bits. */
299 #include "regex.h"
301 /* isalpha etc. are used for the character classes. */
302 #include <ctype.h>
304 #ifdef emacs
306 /* 1 if C is an ASCII character. */
307 # define IS_REAL_ASCII(c) ((c) < 0200)
309 /* 1 if C is a unibyte character. */
310 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
312 /* The Emacs definitions should not be directly affected by locales. */
314 /* In Emacs, these are only used for single-byte characters. */
315 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
316 # define ISCNTRL(c) ((c) < ' ')
317 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
318 || ((c) >= 'a' && (c) <= 'f') \
319 || ((c) >= 'A' && (c) <= 'F'))
321 /* This is only used for single-byte characters. */
322 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
324 /* The rest must handle multibyte characters. */
326 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
327 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
328 : 1)
330 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
331 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
332 : 1)
334 # define ISALNUM(c) (IS_REAL_ASCII (c) \
335 ? (((c) >= 'a' && (c) <= 'z') \
336 || ((c) >= 'A' && (c) <= 'Z') \
337 || ((c) >= '0' && (c) <= '9')) \
338 : SYNTAX (c) == Sword)
340 # define ISALPHA(c) (IS_REAL_ASCII (c) \
341 ? (((c) >= 'a' && (c) <= 'z') \
342 || ((c) >= 'A' && (c) <= 'Z')) \
343 : SYNTAX (c) == Sword)
345 # define ISLOWER(c) (LOWERCASEP (c))
347 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
348 ? ((c) > ' ' && (c) < 0177 \
349 && !(((c) >= 'a' && (c) <= 'z') \
350 || ((c) >= 'A' && (c) <= 'Z') \
351 || ((c) >= '0' && (c) <= '9'))) \
352 : SYNTAX (c) != Sword)
354 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
356 # define ISUPPER(c) (UPPERCASEP (c))
358 # define ISWORD(c) (SYNTAX (c) == Sword)
360 #else /* not emacs */
362 /* Jim Meyering writes:
364 "... Some ctype macros are valid only for character codes that
365 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
366 using /bin/cc or gcc but without giving an ansi option). So, all
367 ctype uses should be through macros like ISPRINT... If
368 STDC_HEADERS is defined, then autoconf has verified that the ctype
369 macros don't need to be guarded with references to isascii. ...
370 Defining isascii to 1 should let any compiler worth its salt
371 eliminate the && through constant folding."
372 Solaris defines some of these symbols so we must undefine them first. */
374 # undef ISASCII
375 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
376 # define ISASCII(c) 1
377 # else
378 # define ISASCII(c) isascii(c)
379 # endif
381 /* 1 if C is an ASCII character. */
382 # define IS_REAL_ASCII(c) ((c) < 0200)
384 /* This distinction is not meaningful, except in Emacs. */
385 # define ISUNIBYTE(c) 1
387 # ifdef isblank
388 # define ISBLANK(c) (ISASCII (c) && isblank (c))
389 # else
390 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
391 # endif
392 # ifdef isgraph
393 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
394 # else
395 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
396 # endif
398 # undef ISPRINT
399 # define ISPRINT(c) (ISASCII (c) && isprint (c))
400 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
401 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
402 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
403 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
404 # define ISLOWER(c) (ISASCII (c) && islower (c))
405 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
406 # define ISSPACE(c) (ISASCII (c) && isspace (c))
407 # define ISUPPER(c) (ISASCII (c) && isupper (c))
408 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
410 # define ISWORD(c) ISALPHA(c)
412 # ifdef _tolower
413 # define TOLOWER(c) _tolower(c)
414 # else
415 # define TOLOWER(c) tolower(c)
416 # endif
418 /* How many characters in the character set. */
419 # define CHAR_SET_SIZE 256
421 # ifdef SYNTAX_TABLE
423 extern char *re_syntax_table;
425 # else /* not SYNTAX_TABLE */
427 static char re_syntax_table[CHAR_SET_SIZE];
429 static void
430 init_syntax_once (void)
432 register int c;
433 static int done = 0;
435 if (done)
436 return;
438 memset (re_syntax_table, 0, sizeof re_syntax_table);
440 for (c = 0; c < CHAR_SET_SIZE; ++c)
441 if (ISALNUM (c))
442 re_syntax_table[c] = Sword;
444 re_syntax_table['_'] = Ssymbol;
446 done = 1;
449 # endif /* not SYNTAX_TABLE */
451 # define SYNTAX(c) re_syntax_table[(c)]
453 #endif /* not emacs */
455 #ifndef NULL
456 # define NULL (void *)0
457 #endif
459 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
460 since ours (we hope) works properly with all combinations of
461 machines, compilers, `char' and `unsigned char' argument types.
462 (Per Bothner suggested the basic approach.) */
463 #undef SIGN_EXTEND_CHAR
464 #if __STDC__
465 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
466 #else /* not __STDC__ */
467 /* As in Harbison and Steele. */
468 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
469 #endif
471 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
472 use `alloca' instead of `malloc'. This is because using malloc in
473 re_search* or re_match* could cause memory leaks when C-g is used in
474 Emacs; also, malloc is slower and causes storage fragmentation. On
475 the other hand, malloc is more portable, and easier to debug.
477 Because we sometimes use alloca, some routines have to be macros,
478 not functions -- `alloca'-allocated space disappears at the end of the
479 function it is called in. */
481 #ifdef REGEX_MALLOC
483 # define REGEX_ALLOCATE malloc
484 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
485 # define REGEX_FREE free
487 #else /* not REGEX_MALLOC */
489 /* Emacs already defines alloca, sometimes. */
490 # ifndef alloca
492 /* Make alloca work the best possible way. */
493 # ifdef __GNUC__
494 # define alloca __builtin_alloca
495 # else /* not __GNUC__ */
496 # ifdef HAVE_ALLOCA_H
497 # include <alloca.h>
498 # endif /* HAVE_ALLOCA_H */
499 # endif /* not __GNUC__ */
501 # endif /* not alloca */
503 # define REGEX_ALLOCATE alloca
505 /* Assumes a `char *destination' variable. */
506 # define REGEX_REALLOCATE(source, osize, nsize) \
507 (destination = (char *) alloca (nsize), \
508 memcpy (destination, source, osize))
510 /* No need to do anything to free, after alloca. */
511 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
513 #endif /* not REGEX_MALLOC */
515 /* Define how to allocate the failure stack. */
517 #if defined REL_ALLOC && defined REGEX_MALLOC
519 # define REGEX_ALLOCATE_STACK(size) \
520 r_alloc (&failure_stack_ptr, (size))
521 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
522 r_re_alloc (&failure_stack_ptr, (nsize))
523 # define REGEX_FREE_STACK(ptr) \
524 r_alloc_free (&failure_stack_ptr)
526 #else /* not using relocating allocator */
528 # ifdef REGEX_MALLOC
530 # define REGEX_ALLOCATE_STACK malloc
531 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
532 # define REGEX_FREE_STACK free
534 # else /* not REGEX_MALLOC */
536 # define REGEX_ALLOCATE_STACK alloca
538 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
539 REGEX_REALLOCATE (source, osize, nsize)
540 /* No need to explicitly free anything. */
541 # define REGEX_FREE_STACK(arg) ((void)0)
543 # endif /* not REGEX_MALLOC */
544 #endif /* not using relocating allocator */
547 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
548 `string1' or just past its end. This works if PTR is NULL, which is
549 a good thing. */
550 #define FIRST_STRING_P(ptr) \
551 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
553 /* (Re)Allocate N items of type T using malloc, or fail. */
554 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
555 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
556 #define RETALLOC_IF(addr, n, t) \
557 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
558 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
560 #define BYTEWIDTH 8 /* In bits. */
562 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
564 #undef MAX
565 #undef MIN
566 #define MAX(a, b) ((a) > (b) ? (a) : (b))
567 #define MIN(a, b) ((a) < (b) ? (a) : (b))
569 /* Type of source-pattern and string chars. */
570 typedef const unsigned char re_char;
572 typedef char boolean;
573 #define false 0
574 #define true 1
576 static int re_match_2_internal _RE_ARGS ((struct re_pattern_buffer *bufp,
577 re_char *string1, int size1,
578 re_char *string2, int size2,
579 int pos,
580 struct re_registers *regs,
581 int stop));
583 /* These are the command codes that appear in compiled regular
584 expressions. Some opcodes are followed by argument bytes. A
585 command code can specify any interpretation whatsoever for its
586 arguments. Zero bytes may appear in the compiled regular expression. */
588 typedef enum
590 no_op = 0,
592 /* Succeed right away--no more backtracking. */
593 succeed,
595 /* Followed by one byte giving n, then by n literal bytes. */
596 exactn,
598 /* Matches any (more or less) character. */
599 anychar,
601 /* Matches any one char belonging to specified set. First
602 following byte is number of bitmap bytes. Then come bytes
603 for a bitmap saying which chars are in. Bits in each byte
604 are ordered low-bit-first. A character is in the set if its
605 bit is 1. A character too large to have a bit in the map is
606 automatically not in the set.
608 If the length byte has the 0x80 bit set, then that stuff
609 is followed by a range table:
610 2 bytes of flags for character sets (low 8 bits, high 8 bits)
611 See RANGE_TABLE_WORK_BITS below.
612 2 bytes, the number of pairs that follow (upto 32767)
613 pairs, each 2 multibyte characters,
614 each multibyte character represented as 3 bytes. */
615 charset,
617 /* Same parameters as charset, but match any character that is
618 not one of those specified. */
619 charset_not,
621 /* Start remembering the text that is matched, for storing in a
622 register. Followed by one byte with the register number, in
623 the range 0 to one less than the pattern buffer's re_nsub
624 field. */
625 start_memory,
627 /* Stop remembering the text that is matched and store it in a
628 memory register. Followed by one byte with the register
629 number, in the range 0 to one less than `re_nsub' in the
630 pattern buffer. */
631 stop_memory,
633 /* Match a duplicate of something remembered. Followed by one
634 byte containing the register number. */
635 duplicate,
637 /* Fail unless at beginning of line. */
638 begline,
640 /* Fail unless at end of line. */
641 endline,
643 /* Succeeds if at beginning of buffer (if emacs) or at beginning
644 of string to be matched (if not). */
645 begbuf,
647 /* Analogously, for end of buffer/string. */
648 endbuf,
650 /* Followed by two byte relative address to which to jump. */
651 jump,
653 /* Followed by two-byte relative address of place to resume at
654 in case of failure. */
655 on_failure_jump,
657 /* Like on_failure_jump, but pushes a placeholder instead of the
658 current string position when executed. */
659 on_failure_keep_string_jump,
661 /* Just like `on_failure_jump', except that it checks that we
662 don't get stuck in an infinite loop (matching an empty string
663 indefinitely). */
664 on_failure_jump_loop,
666 /* Just like `on_failure_jump_loop', except that it checks for
667 a different kind of loop (the kind that shows up with non-greedy
668 operators). This operation has to be immediately preceded
669 by a `no_op'. */
670 on_failure_jump_nastyloop,
672 /* A smart `on_failure_jump' used for greedy * and + operators.
673 It analyses the loop before which it is put and if the
674 loop does not require backtracking, it changes itself to
675 `on_failure_keep_string_jump' and short-circuits the loop,
676 else it just defaults to changing itself into `on_failure_jump'.
677 It assumes that it is pointing to just past a `jump'. */
678 on_failure_jump_smart,
680 /* Followed by two-byte relative address and two-byte number n.
681 After matching N times, jump to the address upon failure.
682 Does not work if N starts at 0: use on_failure_jump_loop
683 instead. */
684 succeed_n,
686 /* Followed by two-byte relative address, and two-byte number n.
687 Jump to the address N times, then fail. */
688 jump_n,
690 /* Set the following two-byte relative address to the
691 subsequent two-byte number. The address *includes* the two
692 bytes of number. */
693 set_number_at,
695 wordbeg, /* Succeeds if at word beginning. */
696 wordend, /* Succeeds if at word end. */
698 wordbound, /* Succeeds if at a word boundary. */
699 notwordbound, /* Succeeds if not at a word boundary. */
701 symbeg, /* Succeeds if at symbol beginning. */
702 symend, /* Succeeds if at symbol end. */
704 /* Matches any character whose syntax is specified. Followed by
705 a byte which contains a syntax code, e.g., Sword. */
706 syntaxspec,
708 /* Matches any character whose syntax is not that specified. */
709 notsyntaxspec
711 #ifdef emacs
712 ,before_dot, /* Succeeds if before point. */
713 at_dot, /* Succeeds if at point. */
714 after_dot, /* Succeeds if after point. */
716 /* Matches any character whose category-set contains the specified
717 category. The operator is followed by a byte which contains a
718 category code (mnemonic ASCII character). */
719 categoryspec,
721 /* Matches any character whose category-set does not contain the
722 specified category. The operator is followed by a byte which
723 contains the category code (mnemonic ASCII character). */
724 notcategoryspec
725 #endif /* emacs */
726 } re_opcode_t;
728 /* Common operations on the compiled pattern. */
730 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
732 #define STORE_NUMBER(destination, number) \
733 do { \
734 (destination)[0] = (number) & 0377; \
735 (destination)[1] = (number) >> 8; \
736 } while (0)
738 /* Same as STORE_NUMBER, except increment DESTINATION to
739 the byte after where the number is stored. Therefore, DESTINATION
740 must be an lvalue. */
742 #define STORE_NUMBER_AND_INCR(destination, number) \
743 do { \
744 STORE_NUMBER (destination, number); \
745 (destination) += 2; \
746 } while (0)
748 /* Put into DESTINATION a number stored in two contiguous bytes starting
749 at SOURCE. */
751 #define EXTRACT_NUMBER(destination, source) \
752 do { \
753 (destination) = *(source) & 0377; \
754 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
755 } while (0)
757 #ifdef DEBUG
758 static void extract_number _RE_ARGS ((int *dest, re_char *source));
759 static void
760 extract_number (dest, source)
761 int *dest;
762 re_char *source;
764 int temp = SIGN_EXTEND_CHAR (*(source + 1));
765 *dest = *source & 0377;
766 *dest += temp << 8;
769 # ifndef EXTRACT_MACROS /* To debug the macros. */
770 # undef EXTRACT_NUMBER
771 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
772 # endif /* not EXTRACT_MACROS */
774 #endif /* DEBUG */
776 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
777 SOURCE must be an lvalue. */
779 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
780 do { \
781 EXTRACT_NUMBER (destination, source); \
782 (source) += 2; \
783 } while (0)
785 #ifdef DEBUG
786 static void extract_number_and_incr _RE_ARGS ((int *destination,
787 re_char **source));
788 static void
789 extract_number_and_incr (destination, source)
790 int *destination;
791 re_char **source;
793 extract_number (destination, *source);
794 *source += 2;
797 # ifndef EXTRACT_MACROS
798 # undef EXTRACT_NUMBER_AND_INCR
799 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
800 extract_number_and_incr (&dest, &src)
801 # endif /* not EXTRACT_MACROS */
803 #endif /* DEBUG */
805 /* Store a multibyte character in three contiguous bytes starting
806 DESTINATION, and increment DESTINATION to the byte after where the
807 character is stored. Therefore, DESTINATION must be an lvalue. */
809 #define STORE_CHARACTER_AND_INCR(destination, character) \
810 do { \
811 (destination)[0] = (character) & 0377; \
812 (destination)[1] = ((character) >> 8) & 0377; \
813 (destination)[2] = (character) >> 16; \
814 (destination) += 3; \
815 } while (0)
817 /* Put into DESTINATION a character stored in three contiguous bytes
818 starting at SOURCE. */
820 #define EXTRACT_CHARACTER(destination, source) \
821 do { \
822 (destination) = ((source)[0] \
823 | ((source)[1] << 8) \
824 | ((source)[2] << 16)); \
825 } while (0)
828 /* Macros for charset. */
830 /* Size of bitmap of charset P in bytes. P is a start of charset,
831 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
832 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
834 /* Nonzero if charset P has range table. */
835 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
837 /* Return the address of range table of charset P. But not the start
838 of table itself, but the before where the number of ranges is
839 stored. `2 +' means to skip re_opcode_t and size of bitmap,
840 and the 2 bytes of flags at the start of the range table. */
841 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
843 /* Extract the bit flags that start a range table. */
844 #define CHARSET_RANGE_TABLE_BITS(p) \
845 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
846 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
848 /* Test if C is listed in the bitmap of charset P. */
849 #define CHARSET_LOOKUP_BITMAP(p, c) \
850 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
851 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
853 /* Return the address of end of RANGE_TABLE. COUNT is number of
854 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
855 is start of range and end of range. `* 3' is size of each start
856 and end. */
857 #define CHARSET_RANGE_TABLE_END(range_table, count) \
858 ((range_table) + (count) * 2 * 3)
860 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
861 COUNT is number of ranges in RANGE_TABLE. */
862 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
863 do \
865 re_wchar_t range_start, range_end; \
866 re_char *p; \
867 re_char *range_table_end \
868 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
870 for (p = (range_table); p < range_table_end; p += 2 * 3) \
872 EXTRACT_CHARACTER (range_start, p); \
873 EXTRACT_CHARACTER (range_end, p + 3); \
875 if (range_start <= (c) && (c) <= range_end) \
877 (not) = !(not); \
878 break; \
882 while (0)
884 /* Test if C is in range table of CHARSET. The flag NOT is negated if
885 C is listed in it. */
886 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
887 do \
889 /* Number of ranges in range table. */ \
890 int count; \
891 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
893 EXTRACT_NUMBER_AND_INCR (count, range_table); \
894 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
896 while (0)
898 /* If DEBUG is defined, Regex prints many voluminous messages about what
899 it is doing (if the variable `debug' is nonzero). If linked with the
900 main program in `iregex.c', you can enter patterns and strings
901 interactively. And if linked with the main program in `main.c' and
902 the other test files, you can run the already-written tests. */
904 #ifdef DEBUG
906 /* We use standard I/O for debugging. */
907 # include <stdio.h>
909 /* It is useful to test things that ``must'' be true when debugging. */
910 # include <assert.h>
912 static int debug = -100000;
914 # define DEBUG_STATEMENT(e) e
915 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
916 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
917 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
918 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
919 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
920 if (debug > 0) print_partial_compiled_pattern (s, e)
921 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
922 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
925 /* Print the fastmap in human-readable form. */
927 void
928 print_fastmap (fastmap)
929 char *fastmap;
931 unsigned was_a_range = 0;
932 unsigned i = 0;
934 while (i < (1 << BYTEWIDTH))
936 if (fastmap[i++])
938 was_a_range = 0;
939 putchar (i - 1);
940 while (i < (1 << BYTEWIDTH) && fastmap[i])
942 was_a_range = 1;
943 i++;
945 if (was_a_range)
947 printf ("-");
948 putchar (i - 1);
952 putchar ('\n');
956 /* Print a compiled pattern string in human-readable form, starting at
957 the START pointer into it and ending just before the pointer END. */
959 void
960 print_partial_compiled_pattern (start, end)
961 re_char *start;
962 re_char *end;
964 int mcnt, mcnt2;
965 re_char *p = start;
966 re_char *pend = end;
968 if (start == NULL)
970 fprintf (stderr, "(null)\n");
971 return;
974 /* Loop over pattern commands. */
975 while (p < pend)
977 fprintf (stderr, "%d:\t", p - start);
979 switch ((re_opcode_t) *p++)
981 case no_op:
982 fprintf (stderr, "/no_op");
983 break;
985 case succeed:
986 fprintf (stderr, "/succeed");
987 break;
989 case exactn:
990 mcnt = *p++;
991 fprintf (stderr, "/exactn/%d", mcnt);
994 fprintf (stderr, "/%c", *p++);
996 while (--mcnt);
997 break;
999 case start_memory:
1000 fprintf (stderr, "/start_memory/%d", *p++);
1001 break;
1003 case stop_memory:
1004 fprintf (stderr, "/stop_memory/%d", *p++);
1005 break;
1007 case duplicate:
1008 fprintf (stderr, "/duplicate/%d", *p++);
1009 break;
1011 case anychar:
1012 fprintf (stderr, "/anychar");
1013 break;
1015 case charset:
1016 case charset_not:
1018 register int c, last = -100;
1019 register int in_range = 0;
1020 int length = CHARSET_BITMAP_SIZE (p - 1);
1021 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
1023 fprintf (stderr, "/charset [%s",
1024 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
1026 if (p + *p >= pend)
1027 fprintf (stderr, " !extends past end of pattern! ");
1029 for (c = 0; c < 256; c++)
1030 if (c / 8 < length
1031 && (p[1 + (c/8)] & (1 << (c % 8))))
1033 /* Are we starting a range? */
1034 if (last + 1 == c && ! in_range)
1036 fprintf (stderr, "-");
1037 in_range = 1;
1039 /* Have we broken a range? */
1040 else if (last + 1 != c && in_range)
1042 fprintf (stderr, "%c", last);
1043 in_range = 0;
1046 if (! in_range)
1047 fprintf (stderr, "%c", c);
1049 last = c;
1052 if (in_range)
1053 fprintf (stderr, "%c", last);
1055 fprintf (stderr, "]");
1057 p += 1 + length;
1059 if (has_range_table)
1061 int count;
1062 fprintf (stderr, "has-range-table");
1064 /* ??? Should print the range table; for now, just skip it. */
1065 p += 2; /* skip range table bits */
1066 EXTRACT_NUMBER_AND_INCR (count, p);
1067 p = CHARSET_RANGE_TABLE_END (p, count);
1070 break;
1072 case begline:
1073 fprintf (stderr, "/begline");
1074 break;
1076 case endline:
1077 fprintf (stderr, "/endline");
1078 break;
1080 case on_failure_jump:
1081 extract_number_and_incr (&mcnt, &p);
1082 fprintf (stderr, "/on_failure_jump to %d", p + mcnt - start);
1083 break;
1085 case on_failure_keep_string_jump:
1086 extract_number_and_incr (&mcnt, &p);
1087 fprintf (stderr, "/on_failure_keep_string_jump to %d", p + mcnt - start);
1088 break;
1090 case on_failure_jump_nastyloop:
1091 extract_number_and_incr (&mcnt, &p);
1092 fprintf (stderr, "/on_failure_jump_nastyloop to %d", p + mcnt - start);
1093 break;
1095 case on_failure_jump_loop:
1096 extract_number_and_incr (&mcnt, &p);
1097 fprintf (stderr, "/on_failure_jump_loop to %d", p + mcnt - start);
1098 break;
1100 case on_failure_jump_smart:
1101 extract_number_and_incr (&mcnt, &p);
1102 fprintf (stderr, "/on_failure_jump_smart to %d", p + mcnt - start);
1103 break;
1105 case jump:
1106 extract_number_and_incr (&mcnt, &p);
1107 fprintf (stderr, "/jump to %d", p + mcnt - start);
1108 break;
1110 case succeed_n:
1111 extract_number_and_incr (&mcnt, &p);
1112 extract_number_and_incr (&mcnt2, &p);
1113 fprintf (stderr, "/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1114 break;
1116 case jump_n:
1117 extract_number_and_incr (&mcnt, &p);
1118 extract_number_and_incr (&mcnt2, &p);
1119 fprintf (stderr, "/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1120 break;
1122 case set_number_at:
1123 extract_number_and_incr (&mcnt, &p);
1124 extract_number_and_incr (&mcnt2, &p);
1125 fprintf (stderr, "/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1126 break;
1128 case wordbound:
1129 fprintf (stderr, "/wordbound");
1130 break;
1132 case notwordbound:
1133 fprintf (stderr, "/notwordbound");
1134 break;
1136 case wordbeg:
1137 fprintf (stderr, "/wordbeg");
1138 break;
1140 case wordend:
1141 fprintf (stderr, "/wordend");
1142 break;
1144 case symbeg:
1145 fprintf (stderr, "/symbeg");
1146 break;
1148 case symend:
1149 fprintf (stderr, "/symend");
1150 break;
1152 case syntaxspec:
1153 fprintf (stderr, "/syntaxspec");
1154 mcnt = *p++;
1155 fprintf (stderr, "/%d", mcnt);
1156 break;
1158 case notsyntaxspec:
1159 fprintf (stderr, "/notsyntaxspec");
1160 mcnt = *p++;
1161 fprintf (stderr, "/%d", mcnt);
1162 break;
1164 # ifdef emacs
1165 case before_dot:
1166 fprintf (stderr, "/before_dot");
1167 break;
1169 case at_dot:
1170 fprintf (stderr, "/at_dot");
1171 break;
1173 case after_dot:
1174 fprintf (stderr, "/after_dot");
1175 break;
1177 case categoryspec:
1178 fprintf (stderr, "/categoryspec");
1179 mcnt = *p++;
1180 fprintf (stderr, "/%d", mcnt);
1181 break;
1183 case notcategoryspec:
1184 fprintf (stderr, "/notcategoryspec");
1185 mcnt = *p++;
1186 fprintf (stderr, "/%d", mcnt);
1187 break;
1188 # endif /* emacs */
1190 case begbuf:
1191 fprintf (stderr, "/begbuf");
1192 break;
1194 case endbuf:
1195 fprintf (stderr, "/endbuf");
1196 break;
1198 default:
1199 fprintf (stderr, "?%d", *(p-1));
1202 fprintf (stderr, "\n");
1205 fprintf (stderr, "%d:\tend of pattern.\n", p - start);
1209 void
1210 print_compiled_pattern (bufp)
1211 struct re_pattern_buffer *bufp;
1213 re_char *buffer = bufp->buffer;
1215 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1216 printf ("%ld bytes used/%ld bytes allocated.\n",
1217 bufp->used, bufp->allocated);
1219 if (bufp->fastmap_accurate && bufp->fastmap)
1221 printf ("fastmap: ");
1222 print_fastmap (bufp->fastmap);
1225 printf ("re_nsub: %d\t", bufp->re_nsub);
1226 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1227 printf ("can_be_null: %d\t", bufp->can_be_null);
1228 printf ("no_sub: %d\t", bufp->no_sub);
1229 printf ("not_bol: %d\t", bufp->not_bol);
1230 printf ("not_eol: %d\t", bufp->not_eol);
1231 printf ("syntax: %lx\n", bufp->syntax);
1232 fflush (stdout);
1233 /* Perhaps we should print the translate table? */
1237 void
1238 print_double_string (where, string1, size1, string2, size2)
1239 re_char *where;
1240 re_char *string1;
1241 re_char *string2;
1242 int size1;
1243 int size2;
1245 int this_char;
1247 if (where == NULL)
1248 printf ("(null)");
1249 else
1251 if (FIRST_STRING_P (where))
1253 for (this_char = where - string1; this_char < size1; this_char++)
1254 putchar (string1[this_char]);
1256 where = string2;
1259 for (this_char = where - string2; this_char < size2; this_char++)
1260 putchar (string2[this_char]);
1264 #else /* not DEBUG */
1266 # undef assert
1267 # define assert(e)
1269 # define DEBUG_STATEMENT(e)
1270 # define DEBUG_PRINT1(x)
1271 # define DEBUG_PRINT2(x1, x2)
1272 # define DEBUG_PRINT3(x1, x2, x3)
1273 # define DEBUG_PRINT4(x1, x2, x3, x4)
1274 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1275 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1277 #endif /* not DEBUG */
1279 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1280 also be assigned to arbitrarily: each pattern buffer stores its own
1281 syntax, so it can be changed between regex compilations. */
1282 /* This has no initializer because initialized variables in Emacs
1283 become read-only after dumping. */
1284 reg_syntax_t re_syntax_options;
1287 /* Specify the precise syntax of regexps for compilation. This provides
1288 for compatibility for various utilities which historically have
1289 different, incompatible syntaxes.
1291 The argument SYNTAX is a bit mask comprised of the various bits
1292 defined in regex.h. We return the old syntax. */
1294 reg_syntax_t
1295 re_set_syntax (reg_syntax_t syntax)
1297 reg_syntax_t ret = re_syntax_options;
1299 re_syntax_options = syntax;
1300 return ret;
1302 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1304 /* Regexp to use to replace spaces, or NULL meaning don't. */
1305 static re_char *whitespace_regexp;
1307 void
1308 re_set_whitespace_regexp (const char *regexp)
1310 whitespace_regexp = (re_char *) regexp;
1312 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1314 /* This table gives an error message for each of the error codes listed
1315 in regex.h. Obviously the order here has to be same as there.
1316 POSIX doesn't require that we do anything for REG_NOERROR,
1317 but why not be nice? */
1319 static const char *re_error_msgid[] =
1321 gettext_noop ("Success"), /* REG_NOERROR */
1322 gettext_noop ("No match"), /* REG_NOMATCH */
1323 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1324 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1325 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1326 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1327 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1328 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1329 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1330 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1331 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1332 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1333 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1334 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1335 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1336 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1337 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1338 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1341 /* Avoiding alloca during matching, to placate r_alloc. */
1343 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1344 searching and matching functions should not call alloca. On some
1345 systems, alloca is implemented in terms of malloc, and if we're
1346 using the relocating allocator routines, then malloc could cause a
1347 relocation, which might (if the strings being searched are in the
1348 ralloc heap) shift the data out from underneath the regexp
1349 routines.
1351 Here's another reason to avoid allocation: Emacs
1352 processes input from X in a signal handler; processing X input may
1353 call malloc; if input arrives while a matching routine is calling
1354 malloc, then we're scrod. But Emacs can't just block input while
1355 calling matching routines; then we don't notice interrupts when
1356 they come in. So, Emacs blocks input around all regexp calls
1357 except the matching calls, which it leaves unprotected, in the
1358 faith that they will not malloc. */
1360 /* Normally, this is fine. */
1361 #define MATCH_MAY_ALLOCATE
1363 /* The match routines may not allocate if (1) they would do it with malloc
1364 and (2) it's not safe for them to use malloc.
1365 Note that if REL_ALLOC is defined, matching would not use malloc for the
1366 failure stack, but we would still use it for the register vectors;
1367 so REL_ALLOC should not affect this. */
1368 #if defined REGEX_MALLOC && defined emacs
1369 # undef MATCH_MAY_ALLOCATE
1370 #endif
1373 /* Failure stack declarations and macros; both re_compile_fastmap and
1374 re_match_2 use a failure stack. These have to be macros because of
1375 REGEX_ALLOCATE_STACK. */
1378 /* Approximate number of failure points for which to initially allocate space
1379 when matching. If this number is exceeded, we allocate more
1380 space, so it is not a hard limit. */
1381 #ifndef INIT_FAILURE_ALLOC
1382 # define INIT_FAILURE_ALLOC 20
1383 #endif
1385 /* Roughly the maximum number of failure points on the stack. Would be
1386 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1387 This is a variable only so users of regex can assign to it; we never
1388 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1389 before using it, so it should probably be a byte-count instead. */
1390 # if defined MATCH_MAY_ALLOCATE
1391 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1392 whose default stack limit is 2mb. In order for a larger
1393 value to work reliably, you have to try to make it accord
1394 with the process stack limit. */
1395 size_t re_max_failures = 40000;
1396 # else
1397 size_t re_max_failures = 4000;
1398 # endif
1400 union fail_stack_elt
1402 re_char *pointer;
1403 /* This should be the biggest `int' that's no bigger than a pointer. */
1404 long integer;
1407 typedef union fail_stack_elt fail_stack_elt_t;
1409 typedef struct
1411 fail_stack_elt_t *stack;
1412 size_t size;
1413 size_t avail; /* Offset of next open position. */
1414 size_t frame; /* Offset of the cur constructed frame. */
1415 } fail_stack_type;
1417 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1418 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1421 /* Define macros to initialize and free the failure stack.
1422 Do `return -2' if the alloc fails. */
1424 #ifdef MATCH_MAY_ALLOCATE
1425 # define INIT_FAIL_STACK() \
1426 do { \
1427 fail_stack.stack = (fail_stack_elt_t *) \
1428 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1429 * sizeof (fail_stack_elt_t)); \
1431 if (fail_stack.stack == NULL) \
1432 return -2; \
1434 fail_stack.size = INIT_FAILURE_ALLOC; \
1435 fail_stack.avail = 0; \
1436 fail_stack.frame = 0; \
1437 } while (0)
1439 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1440 #else
1441 # define INIT_FAIL_STACK() \
1442 do { \
1443 fail_stack.avail = 0; \
1444 fail_stack.frame = 0; \
1445 } while (0)
1447 # define RESET_FAIL_STACK() ((void)0)
1448 #endif
1451 /* Double the size of FAIL_STACK, up to a limit
1452 which allows approximately `re_max_failures' items.
1454 Return 1 if succeeds, and 0 if either ran out of memory
1455 allocating space for it or it was already too large.
1457 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1459 /* Factor to increase the failure stack size by
1460 when we increase it.
1461 This used to be 2, but 2 was too wasteful
1462 because the old discarded stacks added up to as much space
1463 were as ultimate, maximum-size stack. */
1464 #define FAIL_STACK_GROWTH_FACTOR 4
1466 #define GROW_FAIL_STACK(fail_stack) \
1467 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1468 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1469 ? 0 \
1470 : ((fail_stack).stack \
1471 = (fail_stack_elt_t *) \
1472 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1473 (fail_stack).size * sizeof (fail_stack_elt_t), \
1474 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1475 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1476 * FAIL_STACK_GROWTH_FACTOR))), \
1478 (fail_stack).stack == NULL \
1479 ? 0 \
1480 : ((fail_stack).size \
1481 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1482 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1483 * FAIL_STACK_GROWTH_FACTOR)) \
1484 / sizeof (fail_stack_elt_t)), \
1485 1)))
1488 /* Push a pointer value onto the failure stack.
1489 Assumes the variable `fail_stack'. Probably should only
1490 be called from within `PUSH_FAILURE_POINT'. */
1491 #define PUSH_FAILURE_POINTER(item) \
1492 fail_stack.stack[fail_stack.avail++].pointer = (item)
1494 /* This pushes an integer-valued item onto the failure stack.
1495 Assumes the variable `fail_stack'. Probably should only
1496 be called from within `PUSH_FAILURE_POINT'. */
1497 #define PUSH_FAILURE_INT(item) \
1498 fail_stack.stack[fail_stack.avail++].integer = (item)
1500 /* Push a fail_stack_elt_t value onto the failure stack.
1501 Assumes the variable `fail_stack'. Probably should only
1502 be called from within `PUSH_FAILURE_POINT'. */
1503 #define PUSH_FAILURE_ELT(item) \
1504 fail_stack.stack[fail_stack.avail++] = (item)
1506 /* These three POP... operations complement the three PUSH... operations.
1507 All assume that `fail_stack' is nonempty. */
1508 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1509 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1510 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1512 /* Individual items aside from the registers. */
1513 #define NUM_NONREG_ITEMS 3
1515 /* Used to examine the stack (to detect infinite loops). */
1516 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1517 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1518 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1519 #define TOP_FAILURE_HANDLE() fail_stack.frame
1522 #define ENSURE_FAIL_STACK(space) \
1523 while (REMAINING_AVAIL_SLOTS <= space) { \
1524 if (!GROW_FAIL_STACK (fail_stack)) \
1525 return -2; \
1526 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1527 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1530 /* Push register NUM onto the stack. */
1531 #define PUSH_FAILURE_REG(num) \
1532 do { \
1533 char *destination; \
1534 ENSURE_FAIL_STACK(3); \
1535 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1536 num, regstart[num], regend[num]); \
1537 PUSH_FAILURE_POINTER (regstart[num]); \
1538 PUSH_FAILURE_POINTER (regend[num]); \
1539 PUSH_FAILURE_INT (num); \
1540 } while (0)
1542 /* Change the counter's value to VAL, but make sure that it will
1543 be reset when backtracking. */
1544 #define PUSH_NUMBER(ptr,val) \
1545 do { \
1546 char *destination; \
1547 int c; \
1548 ENSURE_FAIL_STACK(3); \
1549 EXTRACT_NUMBER (c, ptr); \
1550 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1551 PUSH_FAILURE_INT (c); \
1552 PUSH_FAILURE_POINTER (ptr); \
1553 PUSH_FAILURE_INT (-1); \
1554 STORE_NUMBER (ptr, val); \
1555 } while (0)
1557 /* Pop a saved register off the stack. */
1558 #define POP_FAILURE_REG_OR_COUNT() \
1559 do { \
1560 int reg = POP_FAILURE_INT (); \
1561 if (reg == -1) \
1563 /* It's a counter. */ \
1564 /* Here, we discard `const', making re_match non-reentrant. */ \
1565 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1566 reg = POP_FAILURE_INT (); \
1567 STORE_NUMBER (ptr, reg); \
1568 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1570 else \
1572 regend[reg] = POP_FAILURE_POINTER (); \
1573 regstart[reg] = POP_FAILURE_POINTER (); \
1574 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1575 reg, regstart[reg], regend[reg]); \
1577 } while (0)
1579 /* Check that we are not stuck in an infinite loop. */
1580 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1581 do { \
1582 int failure = TOP_FAILURE_HANDLE (); \
1583 /* Check for infinite matching loops */ \
1584 while (failure > 0 \
1585 && (FAILURE_STR (failure) == string_place \
1586 || FAILURE_STR (failure) == NULL)) \
1588 assert (FAILURE_PAT (failure) >= bufp->buffer \
1589 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1590 if (FAILURE_PAT (failure) == pat_cur) \
1592 cycle = 1; \
1593 break; \
1595 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1596 failure = NEXT_FAILURE_HANDLE(failure); \
1598 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1599 } while (0)
1601 /* Push the information about the state we will need
1602 if we ever fail back to it.
1604 Requires variables fail_stack, regstart, regend and
1605 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1606 declared.
1608 Does `return FAILURE_CODE' if runs out of memory. */
1610 #define PUSH_FAILURE_POINT(pattern, string_place) \
1611 do { \
1612 char *destination; \
1613 /* Must be int, so when we don't save any registers, the arithmetic \
1614 of 0 + -1 isn't done as unsigned. */ \
1616 DEBUG_STATEMENT (nfailure_points_pushed++); \
1617 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1618 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1619 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1621 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1623 DEBUG_PRINT1 ("\n"); \
1625 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1626 PUSH_FAILURE_INT (fail_stack.frame); \
1628 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1629 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1630 DEBUG_PRINT1 ("'\n"); \
1631 PUSH_FAILURE_POINTER (string_place); \
1633 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1634 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1635 PUSH_FAILURE_POINTER (pattern); \
1637 /* Close the frame by moving the frame pointer past it. */ \
1638 fail_stack.frame = fail_stack.avail; \
1639 } while (0)
1641 /* Estimate the size of data pushed by a typical failure stack entry.
1642 An estimate is all we need, because all we use this for
1643 is to choose a limit for how big to make the failure stack. */
1644 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1645 #define TYPICAL_FAILURE_SIZE 20
1647 /* How many items can still be added to the stack without overflowing it. */
1648 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1651 /* Pops what PUSH_FAIL_STACK pushes.
1653 We restore into the parameters, all of which should be lvalues:
1654 STR -- the saved data position.
1655 PAT -- the saved pattern position.
1656 REGSTART, REGEND -- arrays of string positions.
1658 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1659 `pend', `string1', `size1', `string2', and `size2'. */
1661 #define POP_FAILURE_POINT(str, pat) \
1662 do { \
1663 assert (!FAIL_STACK_EMPTY ()); \
1665 /* Remove failure points and point to how many regs pushed. */ \
1666 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1667 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1668 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1670 /* Pop the saved registers. */ \
1671 while (fail_stack.frame < fail_stack.avail) \
1672 POP_FAILURE_REG_OR_COUNT (); \
1674 pat = POP_FAILURE_POINTER (); \
1675 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1676 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1678 /* If the saved string location is NULL, it came from an \
1679 on_failure_keep_string_jump opcode, and we want to throw away the \
1680 saved NULL, thus retaining our current position in the string. */ \
1681 str = POP_FAILURE_POINTER (); \
1682 DEBUG_PRINT2 (" Popping string %p: `", str); \
1683 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1684 DEBUG_PRINT1 ("'\n"); \
1686 fail_stack.frame = POP_FAILURE_INT (); \
1687 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1689 assert (fail_stack.avail >= 0); \
1690 assert (fail_stack.frame <= fail_stack.avail); \
1692 DEBUG_STATEMENT (nfailure_points_popped++); \
1693 } while (0) /* POP_FAILURE_POINT */
1697 /* Registers are set to a sentinel when they haven't yet matched. */
1698 #define REG_UNSET(e) ((e) == NULL)
1700 /* Subroutine declarations and macros for regex_compile. */
1702 static reg_errcode_t regex_compile _RE_ARGS ((re_char *pattern, size_t size,
1703 reg_syntax_t syntax,
1704 struct re_pattern_buffer *bufp));
1705 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1706 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1707 int arg1, int arg2));
1708 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1709 int arg, unsigned char *end));
1710 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1711 int arg1, int arg2, unsigned char *end));
1712 static boolean at_begline_loc_p _RE_ARGS ((re_char *pattern,
1713 re_char *p,
1714 reg_syntax_t syntax));
1715 static boolean at_endline_loc_p _RE_ARGS ((re_char *p,
1716 re_char *pend,
1717 reg_syntax_t syntax));
1718 static re_char *skip_one_char _RE_ARGS ((re_char *p));
1719 static int analyse_first _RE_ARGS ((re_char *p, re_char *pend,
1720 char *fastmap, const int multibyte));
1722 /* Fetch the next character in the uncompiled pattern, with no
1723 translation. */
1724 #define PATFETCH(c) \
1725 do { \
1726 int len; \
1727 if (p == pend) return REG_EEND; \
1728 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1729 p += len; \
1730 } while (0)
1733 /* If `translate' is non-null, return translate[D], else just D. We
1734 cast the subscript to translate because some data is declared as
1735 `char *', to avoid warnings when a string constant is passed. But
1736 when we use a character as a subscript we must make it unsigned. */
1737 #ifndef TRANSLATE
1738 # define TRANSLATE(d) \
1739 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1740 #endif
1743 /* Macros for outputting the compiled pattern into `buffer'. */
1745 /* If the buffer isn't allocated when it comes in, use this. */
1746 #define INIT_BUF_SIZE 32
1748 /* Make sure we have at least N more bytes of space in buffer. */
1749 #define GET_BUFFER_SPACE(n) \
1750 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1751 EXTEND_BUFFER ()
1753 /* Make sure we have one more byte of buffer space and then add C to it. */
1754 #define BUF_PUSH(c) \
1755 do { \
1756 GET_BUFFER_SPACE (1); \
1757 *b++ = (unsigned char) (c); \
1758 } while (0)
1761 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1762 #define BUF_PUSH_2(c1, c2) \
1763 do { \
1764 GET_BUFFER_SPACE (2); \
1765 *b++ = (unsigned char) (c1); \
1766 *b++ = (unsigned char) (c2); \
1767 } while (0)
1770 /* As with BUF_PUSH_2, except for three bytes. */
1771 #define BUF_PUSH_3(c1, c2, c3) \
1772 do { \
1773 GET_BUFFER_SPACE (3); \
1774 *b++ = (unsigned char) (c1); \
1775 *b++ = (unsigned char) (c2); \
1776 *b++ = (unsigned char) (c3); \
1777 } while (0)
1780 /* Store a jump with opcode OP at LOC to location TO. We store a
1781 relative address offset by the three bytes the jump itself occupies. */
1782 #define STORE_JUMP(op, loc, to) \
1783 store_op1 (op, loc, (to) - (loc) - 3)
1785 /* Likewise, for a two-argument jump. */
1786 #define STORE_JUMP2(op, loc, to, arg) \
1787 store_op2 (op, loc, (to) - (loc) - 3, arg)
1789 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1790 #define INSERT_JUMP(op, loc, to) \
1791 insert_op1 (op, loc, (to) - (loc) - 3, b)
1793 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1794 #define INSERT_JUMP2(op, loc, to, arg) \
1795 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1798 /* This is not an arbitrary limit: the arguments which represent offsets
1799 into the pattern are two bytes long. So if 2^15 bytes turns out to
1800 be too small, many things would have to change. */
1801 # define MAX_BUF_SIZE (1L << 15)
1803 #if 0 /* This is when we thought it could be 2^16 bytes. */
1804 /* Any other compiler which, like MSC, has allocation limit below 2^16
1805 bytes will have to use approach similar to what was done below for
1806 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1807 reallocating to 0 bytes. Such thing is not going to work too well.
1808 You have been warned!! */
1809 #if defined _MSC_VER && !defined WIN32
1810 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1811 # define MAX_BUF_SIZE 65500L
1812 #else
1813 # define MAX_BUF_SIZE (1L << 16)
1814 #endif
1815 #endif /* 0 */
1817 /* Extend the buffer by twice its current size via realloc and
1818 reset the pointers that pointed into the old block to point to the
1819 correct places in the new one. If extending the buffer results in it
1820 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1821 #if __BOUNDED_POINTERS__
1822 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1823 # define MOVE_BUFFER_POINTER(P) \
1824 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1825 SET_HIGH_BOUND (P), \
1826 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1827 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1828 else \
1830 SET_HIGH_BOUND (b); \
1831 SET_HIGH_BOUND (begalt); \
1832 if (fixup_alt_jump) \
1833 SET_HIGH_BOUND (fixup_alt_jump); \
1834 if (laststart) \
1835 SET_HIGH_BOUND (laststart); \
1836 if (pending_exact) \
1837 SET_HIGH_BOUND (pending_exact); \
1839 #else
1840 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1841 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1842 #endif
1843 #define EXTEND_BUFFER() \
1844 do { \
1845 unsigned char *old_buffer = bufp->buffer; \
1846 if (bufp->allocated == MAX_BUF_SIZE) \
1847 return REG_ESIZE; \
1848 bufp->allocated <<= 1; \
1849 if (bufp->allocated > MAX_BUF_SIZE) \
1850 bufp->allocated = MAX_BUF_SIZE; \
1851 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1852 if (bufp->buffer == NULL) \
1853 return REG_ESPACE; \
1854 /* If the buffer moved, move all the pointers into it. */ \
1855 if (old_buffer != bufp->buffer) \
1857 unsigned char *new_buffer = bufp->buffer; \
1858 MOVE_BUFFER_POINTER (b); \
1859 MOVE_BUFFER_POINTER (begalt); \
1860 if (fixup_alt_jump) \
1861 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1862 if (laststart) \
1863 MOVE_BUFFER_POINTER (laststart); \
1864 if (pending_exact) \
1865 MOVE_BUFFER_POINTER (pending_exact); \
1867 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1868 } while (0)
1871 /* Since we have one byte reserved for the register number argument to
1872 {start,stop}_memory, the maximum number of groups we can report
1873 things about is what fits in that byte. */
1874 #define MAX_REGNUM 255
1876 /* But patterns can have more than `MAX_REGNUM' registers. We just
1877 ignore the excess. */
1878 typedef int regnum_t;
1881 /* Macros for the compile stack. */
1883 /* Since offsets can go either forwards or backwards, this type needs to
1884 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1885 /* int may be not enough when sizeof(int) == 2. */
1886 typedef long pattern_offset_t;
1888 typedef struct
1890 pattern_offset_t begalt_offset;
1891 pattern_offset_t fixup_alt_jump;
1892 pattern_offset_t laststart_offset;
1893 regnum_t regnum;
1894 } compile_stack_elt_t;
1897 typedef struct
1899 compile_stack_elt_t *stack;
1900 unsigned size;
1901 unsigned avail; /* Offset of next open position. */
1902 } compile_stack_type;
1905 #define INIT_COMPILE_STACK_SIZE 32
1907 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1908 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1910 /* The next available element. */
1911 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1913 /* Explicit quit checking is only used on NTemacs and whenever we
1914 use polling to process input events. */
1915 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1916 extern int immediate_quit;
1917 # define IMMEDIATE_QUIT_CHECK \
1918 do { \
1919 if (immediate_quit) QUIT; \
1920 } while (0)
1921 #else
1922 # define IMMEDIATE_QUIT_CHECK ((void)0)
1923 #endif
1925 /* Structure to manage work area for range table. */
1926 struct range_table_work_area
1928 int *table; /* actual work area. */
1929 int allocated; /* allocated size for work area in bytes. */
1930 int used; /* actually used size in words. */
1931 int bits; /* flag to record character classes */
1934 /* Make sure that WORK_AREA can hold more N multibyte characters.
1935 This is used only in set_image_of_range and set_image_of_range_1.
1936 It expects WORK_AREA to be a pointer.
1937 If it can't get the space, it returns from the surrounding function. */
1939 #define EXTEND_RANGE_TABLE(work_area, n) \
1940 do { \
1941 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1943 extend_range_table_work_area (&work_area); \
1944 if ((work_area).table == 0) \
1945 return (REG_ESPACE); \
1947 } while (0)
1949 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1950 (work_area).bits |= (bit)
1952 /* Bits used to implement the multibyte-part of the various character classes
1953 such as [:alnum:] in a charset's range table. */
1954 #define BIT_WORD 0x1
1955 #define BIT_LOWER 0x2
1956 #define BIT_PUNCT 0x4
1957 #define BIT_SPACE 0x8
1958 #define BIT_UPPER 0x10
1959 #define BIT_MULTIBYTE 0x20
1961 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1962 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1963 do { \
1964 EXTEND_RANGE_TABLE ((work_area), 2); \
1965 (work_area).table[(work_area).used++] = (range_start); \
1966 (work_area).table[(work_area).used++] = (range_end); \
1967 } while (0)
1969 /* Free allocated memory for WORK_AREA. */
1970 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1971 do { \
1972 if ((work_area).table) \
1973 free ((work_area).table); \
1974 } while (0)
1976 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1977 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1978 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1979 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1982 /* Set the bit for character C in a list. */
1983 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1986 #ifdef emacs
1988 /* Store characters in the range FROM to TO in the bitmap at B (for
1989 ASCII and unibyte characters) and WORK_AREA (for multibyte
1990 characters) while translating them and paying attention to the
1991 continuity of translated characters.
1993 Implementation note: It is better to implement these fairly big
1994 macros by a function, but it's not that easy because macros called
1995 in this macro assume various local variables already declared. */
1997 /* Both FROM and TO are ASCII characters. */
1999 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
2000 do { \
2001 int C0, C1; \
2003 for (C0 = (FROM); C0 <= (TO); C0++) \
2005 C1 = TRANSLATE (C0); \
2006 if (! ASCII_CHAR_P (C1)) \
2008 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2009 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
2010 C1 = C0; \
2012 SET_LIST_BIT (C1); \
2014 } while (0)
2017 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
2019 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
2020 do { \
2021 int C0, C1, C2, I; \
2022 int USED = RANGE_TABLE_WORK_USED (work_area); \
2024 for (C0 = (FROM); C0 <= (TO); C0++) \
2026 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
2027 if (CHAR_BYTE8_P (C1)) \
2028 SET_LIST_BIT (C0); \
2029 else \
2031 C2 = TRANSLATE (C1); \
2032 if (C2 == C1 \
2033 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
2034 C1 = C0; \
2035 SET_LIST_BIT (C1); \
2036 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2038 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2039 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2041 if (C2 >= from - 1 && C2 <= to + 1) \
2043 if (C2 == from - 1) \
2044 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2045 else if (C2 == to + 1) \
2046 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2047 break; \
2050 if (I < USED) \
2051 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
2054 } while (0)
2057 /* Both FROM and TO are multibyte characters. */
2059 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2060 do { \
2061 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2063 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2064 for (C0 = (FROM); C0 <= (TO); C0++) \
2066 C1 = TRANSLATE (C0); \
2067 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2068 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2069 SET_LIST_BIT (C2); \
2070 if (C1 >= (FROM) && C1 <= (TO)) \
2071 continue; \
2072 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2074 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2075 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2077 if (C1 >= from - 1 && C1 <= to + 1) \
2079 if (C1 == from - 1) \
2080 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2081 else if (C1 == to + 1) \
2082 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2083 break; \
2086 if (I < USED) \
2087 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2089 } while (0)
2091 #endif /* emacs */
2093 /* Get the next unsigned number in the uncompiled pattern. */
2094 #define GET_UNSIGNED_NUMBER(num) \
2095 do { \
2096 if (p == pend) \
2097 FREE_STACK_RETURN (REG_EBRACE); \
2098 else \
2100 PATFETCH (c); \
2101 while ('0' <= c && c <= '9') \
2103 int prev; \
2104 if (num < 0) \
2105 num = 0; \
2106 prev = num; \
2107 num = num * 10 + c - '0'; \
2108 if (num / 10 != prev) \
2109 FREE_STACK_RETURN (REG_BADBR); \
2110 if (p == pend) \
2111 FREE_STACK_RETURN (REG_EBRACE); \
2112 PATFETCH (c); \
2115 } while (0)
2117 #if ! WIDE_CHAR_SUPPORT
2119 /* Map a string to the char class it names (if any). */
2120 re_wctype_t
2121 re_wctype (const re_char *str)
2123 const char *string = str;
2124 if (STREQ (string, "alnum")) return RECC_ALNUM;
2125 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2126 else if (STREQ (string, "word")) return RECC_WORD;
2127 else if (STREQ (string, "ascii")) return RECC_ASCII;
2128 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2129 else if (STREQ (string, "graph")) return RECC_GRAPH;
2130 else if (STREQ (string, "lower")) return RECC_LOWER;
2131 else if (STREQ (string, "print")) return RECC_PRINT;
2132 else if (STREQ (string, "punct")) return RECC_PUNCT;
2133 else if (STREQ (string, "space")) return RECC_SPACE;
2134 else if (STREQ (string, "upper")) return RECC_UPPER;
2135 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2136 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2137 else if (STREQ (string, "digit")) return RECC_DIGIT;
2138 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2139 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2140 else if (STREQ (string, "blank")) return RECC_BLANK;
2141 else return 0;
2144 /* True if CH is in the char class CC. */
2145 boolean
2146 re_iswctype (int ch, re_wctype_t cc)
2148 switch (cc)
2150 case RECC_ALNUM: return ISALNUM (ch);
2151 case RECC_ALPHA: return ISALPHA (ch);
2152 case RECC_BLANK: return ISBLANK (ch);
2153 case RECC_CNTRL: return ISCNTRL (ch);
2154 case RECC_DIGIT: return ISDIGIT (ch);
2155 case RECC_GRAPH: return ISGRAPH (ch);
2156 case RECC_LOWER: return ISLOWER (ch);
2157 case RECC_PRINT: return ISPRINT (ch);
2158 case RECC_PUNCT: return ISPUNCT (ch);
2159 case RECC_SPACE: return ISSPACE (ch);
2160 case RECC_UPPER: return ISUPPER (ch);
2161 case RECC_XDIGIT: return ISXDIGIT (ch);
2162 case RECC_ASCII: return IS_REAL_ASCII (ch);
2163 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2164 case RECC_UNIBYTE: return ISUNIBYTE (ch);
2165 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2166 case RECC_WORD: return ISWORD (ch);
2167 case RECC_ERROR: return false;
2168 default:
2169 abort();
2173 /* Return a bit-pattern to use in the range-table bits to match multibyte
2174 chars of class CC. */
2175 static int
2176 re_wctype_to_bit (re_wctype_t cc)
2178 switch (cc)
2180 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2181 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2182 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2183 case RECC_LOWER: return BIT_LOWER;
2184 case RECC_UPPER: return BIT_UPPER;
2185 case RECC_PUNCT: return BIT_PUNCT;
2186 case RECC_SPACE: return BIT_SPACE;
2187 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2188 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2189 default:
2190 abort();
2193 #endif
2195 /* Filling in the work area of a range. */
2197 /* Actually extend the space in WORK_AREA. */
2199 static void
2200 extend_range_table_work_area (struct range_table_work_area *work_area)
2202 work_area->allocated += 16 * sizeof (int);
2203 if (work_area->table)
2204 work_area->table
2205 = (int *) realloc (work_area->table, work_area->allocated);
2206 else
2207 work_area->table
2208 = (int *) malloc (work_area->allocated);
2211 #if 0
2212 #ifdef emacs
2214 /* Carefully find the ranges of codes that are equivalent
2215 under case conversion to the range start..end when passed through
2216 TRANSLATE. Handle the case where non-letters can come in between
2217 two upper-case letters (which happens in Latin-1).
2218 Also handle the case of groups of more than 2 case-equivalent chars.
2220 The basic method is to look at consecutive characters and see
2221 if they can form a run that can be handled as one.
2223 Returns -1 if successful, REG_ESPACE if ran out of space. */
2225 static int
2226 set_image_of_range_1 (work_area, start, end, translate)
2227 RE_TRANSLATE_TYPE translate;
2228 struct range_table_work_area *work_area;
2229 re_wchar_t start, end;
2231 /* `one_case' indicates a character, or a run of characters,
2232 each of which is an isolate (no case-equivalents).
2233 This includes all ASCII non-letters.
2235 `two_case' indicates a character, or a run of characters,
2236 each of which has two case-equivalent forms.
2237 This includes all ASCII letters.
2239 `strange' indicates a character that has more than one
2240 case-equivalent. */
2242 enum case_type {one_case, two_case, strange};
2244 /* Describe the run that is in progress,
2245 which the next character can try to extend.
2246 If run_type is strange, that means there really is no run.
2247 If run_type is one_case, then run_start...run_end is the run.
2248 If run_type is two_case, then the run is run_start...run_end,
2249 and the case-equivalents end at run_eqv_end. */
2251 enum case_type run_type = strange;
2252 int run_start, run_end, run_eqv_end;
2254 Lisp_Object eqv_table;
2256 if (!RE_TRANSLATE_P (translate))
2258 EXTEND_RANGE_TABLE (work_area, 2);
2259 work_area->table[work_area->used++] = (start);
2260 work_area->table[work_area->used++] = (end);
2261 return -1;
2264 eqv_table = XCHAR_TABLE (translate)->extras[2];
2266 for (; start <= end; start++)
2268 enum case_type this_type;
2269 int eqv = RE_TRANSLATE (eqv_table, start);
2270 int minchar, maxchar;
2272 /* Classify this character */
2273 if (eqv == start)
2274 this_type = one_case;
2275 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2276 this_type = two_case;
2277 else
2278 this_type = strange;
2280 if (start < eqv)
2281 minchar = start, maxchar = eqv;
2282 else
2283 minchar = eqv, maxchar = start;
2285 /* Can this character extend the run in progress? */
2286 if (this_type == strange || this_type != run_type
2287 || !(minchar == run_end + 1
2288 && (run_type == two_case
2289 ? maxchar == run_eqv_end + 1 : 1)))
2291 /* No, end the run.
2292 Record each of its equivalent ranges. */
2293 if (run_type == one_case)
2295 EXTEND_RANGE_TABLE (work_area, 2);
2296 work_area->table[work_area->used++] = run_start;
2297 work_area->table[work_area->used++] = run_end;
2299 else if (run_type == two_case)
2301 EXTEND_RANGE_TABLE (work_area, 4);
2302 work_area->table[work_area->used++] = run_start;
2303 work_area->table[work_area->used++] = run_end;
2304 work_area->table[work_area->used++]
2305 = RE_TRANSLATE (eqv_table, run_start);
2306 work_area->table[work_area->used++]
2307 = RE_TRANSLATE (eqv_table, run_end);
2309 run_type = strange;
2312 if (this_type == strange)
2314 /* For a strange character, add each of its equivalents, one
2315 by one. Don't start a range. */
2318 EXTEND_RANGE_TABLE (work_area, 2);
2319 work_area->table[work_area->used++] = eqv;
2320 work_area->table[work_area->used++] = eqv;
2321 eqv = RE_TRANSLATE (eqv_table, eqv);
2323 while (eqv != start);
2326 /* Add this char to the run, or start a new run. */
2327 else if (run_type == strange)
2329 /* Initialize a new range. */
2330 run_type = this_type;
2331 run_start = start;
2332 run_end = start;
2333 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2335 else
2337 /* Extend a running range. */
2338 run_end = minchar;
2339 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2343 /* If a run is still in progress at the end, finish it now
2344 by recording its equivalent ranges. */
2345 if (run_type == one_case)
2347 EXTEND_RANGE_TABLE (work_area, 2);
2348 work_area->table[work_area->used++] = run_start;
2349 work_area->table[work_area->used++] = run_end;
2351 else if (run_type == two_case)
2353 EXTEND_RANGE_TABLE (work_area, 4);
2354 work_area->table[work_area->used++] = run_start;
2355 work_area->table[work_area->used++] = run_end;
2356 work_area->table[work_area->used++]
2357 = RE_TRANSLATE (eqv_table, run_start);
2358 work_area->table[work_area->used++]
2359 = RE_TRANSLATE (eqv_table, run_end);
2362 return -1;
2365 #endif /* emacs */
2367 /* Record the image of the range start..end when passed through
2368 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2369 and is not even necessarily contiguous.
2370 Normally we approximate it with the smallest contiguous range that contains
2371 all the chars we need. However, for Latin-1 we go to extra effort
2372 to do a better job.
2374 This function is not called for ASCII ranges.
2376 Returns -1 if successful, REG_ESPACE if ran out of space. */
2378 static int
2379 set_image_of_range (work_area, start, end, translate)
2380 RE_TRANSLATE_TYPE translate;
2381 struct range_table_work_area *work_area;
2382 re_wchar_t start, end;
2384 re_wchar_t cmin, cmax;
2386 #ifdef emacs
2387 /* For Latin-1 ranges, use set_image_of_range_1
2388 to get proper handling of ranges that include letters and nonletters.
2389 For a range that includes the whole of Latin-1, this is not necessary.
2390 For other character sets, we don't bother to get this right. */
2391 if (RE_TRANSLATE_P (translate) && start < 04400
2392 && !(start < 04200 && end >= 04377))
2394 int newend;
2395 int tem;
2396 newend = end;
2397 if (newend > 04377)
2398 newend = 04377;
2399 tem = set_image_of_range_1 (work_area, start, newend, translate);
2400 if (tem > 0)
2401 return tem;
2403 start = 04400;
2404 if (end < 04400)
2405 return -1;
2407 #endif
2409 EXTEND_RANGE_TABLE (work_area, 2);
2410 work_area->table[work_area->used++] = (start);
2411 work_area->table[work_area->used++] = (end);
2413 cmin = -1, cmax = -1;
2415 if (RE_TRANSLATE_P (translate))
2417 int ch;
2419 for (ch = start; ch <= end; ch++)
2421 re_wchar_t c = TRANSLATE (ch);
2422 if (! (start <= c && c <= end))
2424 if (cmin == -1)
2425 cmin = c, cmax = c;
2426 else
2428 cmin = MIN (cmin, c);
2429 cmax = MAX (cmax, c);
2434 if (cmin != -1)
2436 EXTEND_RANGE_TABLE (work_area, 2);
2437 work_area->table[work_area->used++] = (cmin);
2438 work_area->table[work_area->used++] = (cmax);
2442 return -1;
2444 #endif /* 0 */
2446 #ifndef MATCH_MAY_ALLOCATE
2448 /* If we cannot allocate large objects within re_match_2_internal,
2449 we make the fail stack and register vectors global.
2450 The fail stack, we grow to the maximum size when a regexp
2451 is compiled.
2452 The register vectors, we adjust in size each time we
2453 compile a regexp, according to the number of registers it needs. */
2455 static fail_stack_type fail_stack;
2457 /* Size with which the following vectors are currently allocated.
2458 That is so we can make them bigger as needed,
2459 but never make them smaller. */
2460 static int regs_allocated_size;
2462 static re_char ** regstart, ** regend;
2463 static re_char **best_regstart, **best_regend;
2465 /* Make the register vectors big enough for NUM_REGS registers,
2466 but don't make them smaller. */
2468 static
2469 regex_grow_registers (num_regs)
2470 int num_regs;
2472 if (num_regs > regs_allocated_size)
2474 RETALLOC_IF (regstart, num_regs, re_char *);
2475 RETALLOC_IF (regend, num_regs, re_char *);
2476 RETALLOC_IF (best_regstart, num_regs, re_char *);
2477 RETALLOC_IF (best_regend, num_regs, re_char *);
2479 regs_allocated_size = num_regs;
2483 #endif /* not MATCH_MAY_ALLOCATE */
2485 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2486 compile_stack,
2487 regnum_t regnum));
2489 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2490 Returns one of error codes defined in `regex.h', or zero for success.
2492 Assumes the `allocated' (and perhaps `buffer') and `translate'
2493 fields are set in BUFP on entry.
2495 If it succeeds, results are put in BUFP (if it returns an error, the
2496 contents of BUFP are undefined):
2497 `buffer' is the compiled pattern;
2498 `syntax' is set to SYNTAX;
2499 `used' is set to the length of the compiled pattern;
2500 `fastmap_accurate' is zero;
2501 `re_nsub' is the number of subexpressions in PATTERN;
2502 `not_bol' and `not_eol' are zero;
2504 The `fastmap' field is neither examined nor set. */
2506 /* Insert the `jump' from the end of last alternative to "here".
2507 The space for the jump has already been allocated. */
2508 #define FIXUP_ALT_JUMP() \
2509 do { \
2510 if (fixup_alt_jump) \
2511 STORE_JUMP (jump, fixup_alt_jump, b); \
2512 } while (0)
2515 /* Return, freeing storage we allocated. */
2516 #define FREE_STACK_RETURN(value) \
2517 do { \
2518 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2519 free (compile_stack.stack); \
2520 return value; \
2521 } while (0)
2523 static reg_errcode_t
2524 regex_compile (const re_char *pattern, size_t size, reg_syntax_t syntax, struct re_pattern_buffer *bufp)
2526 /* We fetch characters from PATTERN here. */
2527 register re_wchar_t c, c1;
2529 /* A random temporary spot in PATTERN. */
2530 re_char *p1;
2532 /* Points to the end of the buffer, where we should append. */
2533 register unsigned char *b;
2535 /* Keeps track of unclosed groups. */
2536 compile_stack_type compile_stack;
2538 /* Points to the current (ending) position in the pattern. */
2539 #ifdef AIX
2540 /* `const' makes AIX compiler fail. */
2541 unsigned char *p = pattern;
2542 #else
2543 re_char *p = pattern;
2544 #endif
2545 re_char *pend = pattern + size;
2547 /* How to translate the characters in the pattern. */
2548 RE_TRANSLATE_TYPE translate = bufp->translate;
2550 /* Address of the count-byte of the most recently inserted `exactn'
2551 command. This makes it possible to tell if a new exact-match
2552 character can be added to that command or if the character requires
2553 a new `exactn' command. */
2554 unsigned char *pending_exact = 0;
2556 /* Address of start of the most recently finished expression.
2557 This tells, e.g., postfix * where to find the start of its
2558 operand. Reset at the beginning of groups and alternatives. */
2559 unsigned char *laststart = 0;
2561 /* Address of beginning of regexp, or inside of last group. */
2562 unsigned char *begalt;
2564 /* Place in the uncompiled pattern (i.e., the {) to
2565 which to go back if the interval is invalid. */
2566 re_char *beg_interval;
2568 /* Address of the place where a forward jump should go to the end of
2569 the containing expression. Each alternative of an `or' -- except the
2570 last -- ends with a forward jump of this sort. */
2571 unsigned char *fixup_alt_jump = 0;
2573 /* Work area for range table of charset. */
2574 struct range_table_work_area range_table_work;
2576 /* If the object matched can contain multibyte characters. */
2577 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2579 /* If a target of matching can contain multibyte characters. */
2580 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
2582 /* Nonzero if we have pushed down into a subpattern. */
2583 int in_subpattern = 0;
2585 /* These hold the values of p, pattern, and pend from the main
2586 pattern when we have pushed into a subpattern. */
2587 re_char *main_p;
2588 re_char *main_pattern;
2589 re_char *main_pend;
2591 #ifdef DEBUG
2592 debug++;
2593 DEBUG_PRINT1 ("\nCompiling pattern: ");
2594 if (debug > 0)
2596 unsigned debug_count;
2598 for (debug_count = 0; debug_count < size; debug_count++)
2599 putchar (pattern[debug_count]);
2600 putchar ('\n');
2602 #endif /* DEBUG */
2604 /* Initialize the compile stack. */
2605 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2606 if (compile_stack.stack == NULL)
2607 return REG_ESPACE;
2609 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2610 compile_stack.avail = 0;
2612 range_table_work.table = 0;
2613 range_table_work.allocated = 0;
2615 /* Initialize the pattern buffer. */
2616 bufp->syntax = syntax;
2617 bufp->fastmap_accurate = 0;
2618 bufp->not_bol = bufp->not_eol = 0;
2619 bufp->used_syntax = 0;
2621 /* Set `used' to zero, so that if we return an error, the pattern
2622 printer (for debugging) will think there's no pattern. We reset it
2623 at the end. */
2624 bufp->used = 0;
2626 /* Always count groups, whether or not bufp->no_sub is set. */
2627 bufp->re_nsub = 0;
2629 #if !defined emacs && !defined SYNTAX_TABLE
2630 /* Initialize the syntax table. */
2631 init_syntax_once ();
2632 #endif
2634 if (bufp->allocated == 0)
2636 if (bufp->buffer)
2637 { /* If zero allocated, but buffer is non-null, try to realloc
2638 enough space. This loses if buffer's address is bogus, but
2639 that is the user's responsibility. */
2640 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2642 else
2643 { /* Caller did not allocate a buffer. Do it for them. */
2644 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2646 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2648 bufp->allocated = INIT_BUF_SIZE;
2651 begalt = b = bufp->buffer;
2653 /* Loop through the uncompiled pattern until we're at the end. */
2654 while (1)
2656 if (p == pend)
2658 /* If this is the end of an included regexp,
2659 pop back to the main regexp and try again. */
2660 if (in_subpattern)
2662 in_subpattern = 0;
2663 pattern = main_pattern;
2664 p = main_p;
2665 pend = main_pend;
2666 continue;
2668 /* If this is the end of the main regexp, we are done. */
2669 break;
2672 PATFETCH (c);
2674 switch (c)
2676 case ' ':
2678 re_char *p1 = p;
2680 /* If there's no special whitespace regexp, treat
2681 spaces normally. And don't try to do this recursively. */
2682 if (!whitespace_regexp || in_subpattern)
2683 goto normal_char;
2685 /* Peek past following spaces. */
2686 while (p1 != pend)
2688 if (*p1 != ' ')
2689 break;
2690 p1++;
2692 /* If the spaces are followed by a repetition op,
2693 treat them normally. */
2694 if (p1 != pend
2695 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2696 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2697 goto normal_char;
2699 /* Replace the spaces with the whitespace regexp. */
2700 in_subpattern = 1;
2701 main_p = p1;
2702 main_pend = pend;
2703 main_pattern = pattern;
2704 p = pattern = whitespace_regexp;
2705 pend = p + strlen (p);
2706 break;
2709 case '^':
2711 if ( /* If at start of pattern, it's an operator. */
2712 p == pattern + 1
2713 /* If context independent, it's an operator. */
2714 || syntax & RE_CONTEXT_INDEP_ANCHORS
2715 /* Otherwise, depends on what's come before. */
2716 || at_begline_loc_p (pattern, p, syntax))
2717 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2718 else
2719 goto normal_char;
2721 break;
2724 case '$':
2726 if ( /* If at end of pattern, it's an operator. */
2727 p == pend
2728 /* If context independent, it's an operator. */
2729 || syntax & RE_CONTEXT_INDEP_ANCHORS
2730 /* Otherwise, depends on what's next. */
2731 || at_endline_loc_p (p, pend, syntax))
2732 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2733 else
2734 goto normal_char;
2736 break;
2739 case '+':
2740 case '?':
2741 if ((syntax & RE_BK_PLUS_QM)
2742 || (syntax & RE_LIMITED_OPS))
2743 goto normal_char;
2744 handle_plus:
2745 case '*':
2746 /* If there is no previous pattern... */
2747 if (!laststart)
2749 if (syntax & RE_CONTEXT_INVALID_OPS)
2750 FREE_STACK_RETURN (REG_BADRPT);
2751 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2752 goto normal_char;
2756 /* 1 means zero (many) matches is allowed. */
2757 boolean zero_times_ok = 0, many_times_ok = 0;
2758 boolean greedy = 1;
2760 /* If there is a sequence of repetition chars, collapse it
2761 down to just one (the right one). We can't combine
2762 interval operators with these because of, e.g., `a{2}*',
2763 which should only match an even number of `a's. */
2765 for (;;)
2767 if ((syntax & RE_FRUGAL)
2768 && c == '?' && (zero_times_ok || many_times_ok))
2769 greedy = 0;
2770 else
2772 zero_times_ok |= c != '+';
2773 many_times_ok |= c != '?';
2776 if (p == pend)
2777 break;
2778 else if (*p == '*'
2779 || (!(syntax & RE_BK_PLUS_QM)
2780 && (*p == '+' || *p == '?')))
2782 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2784 if (p+1 == pend)
2785 FREE_STACK_RETURN (REG_EESCAPE);
2786 if (p[1] == '+' || p[1] == '?')
2787 PATFETCH (c); /* Gobble up the backslash. */
2788 else
2789 break;
2791 else
2792 break;
2793 /* If we get here, we found another repeat character. */
2794 PATFETCH (c);
2797 /* Star, etc. applied to an empty pattern is equivalent
2798 to an empty pattern. */
2799 if (!laststart || laststart == b)
2800 break;
2802 /* Now we know whether or not zero matches is allowed
2803 and also whether or not two or more matches is allowed. */
2804 if (greedy)
2806 if (many_times_ok)
2808 boolean simple = skip_one_char (laststart) == b;
2809 unsigned int startoffset = 0;
2810 re_opcode_t ofj =
2811 /* Check if the loop can match the empty string. */
2812 (simple || !analyse_first (laststart, b, NULL, 0))
2813 ? on_failure_jump : on_failure_jump_loop;
2814 assert (skip_one_char (laststart) <= b);
2816 if (!zero_times_ok && simple)
2817 { /* Since simple * loops can be made faster by using
2818 on_failure_keep_string_jump, we turn simple P+
2819 into PP* if P is simple. */
2820 unsigned char *p1, *p2;
2821 startoffset = b - laststart;
2822 GET_BUFFER_SPACE (startoffset);
2823 p1 = b; p2 = laststart;
2824 while (p2 < p1)
2825 *b++ = *p2++;
2826 zero_times_ok = 1;
2829 GET_BUFFER_SPACE (6);
2830 if (!zero_times_ok)
2831 /* A + loop. */
2832 STORE_JUMP (ofj, b, b + 6);
2833 else
2834 /* Simple * loops can use on_failure_keep_string_jump
2835 depending on what follows. But since we don't know
2836 that yet, we leave the decision up to
2837 on_failure_jump_smart. */
2838 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2839 laststart + startoffset, b + 6);
2840 b += 3;
2841 STORE_JUMP (jump, b, laststart + startoffset);
2842 b += 3;
2844 else
2846 /* A simple ? pattern. */
2847 assert (zero_times_ok);
2848 GET_BUFFER_SPACE (3);
2849 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2850 b += 3;
2853 else /* not greedy */
2854 { /* I wish the greedy and non-greedy cases could be merged. */
2856 GET_BUFFER_SPACE (7); /* We might use less. */
2857 if (many_times_ok)
2859 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2861 /* The non-greedy multiple match looks like
2862 a repeat..until: we only need a conditional jump
2863 at the end of the loop. */
2864 if (emptyp) BUF_PUSH (no_op);
2865 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2866 : on_failure_jump, b, laststart);
2867 b += 3;
2868 if (zero_times_ok)
2870 /* The repeat...until naturally matches one or more.
2871 To also match zero times, we need to first jump to
2872 the end of the loop (its conditional jump). */
2873 INSERT_JUMP (jump, laststart, b);
2874 b += 3;
2877 else
2879 /* non-greedy a?? */
2880 INSERT_JUMP (jump, laststart, b + 3);
2881 b += 3;
2882 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2883 b += 3;
2887 pending_exact = 0;
2888 break;
2891 case '.':
2892 laststart = b;
2893 BUF_PUSH (anychar);
2894 break;
2897 case '[':
2899 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2901 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2903 /* Ensure that we have enough space to push a charset: the
2904 opcode, the length count, and the bitset; 34 bytes in all. */
2905 GET_BUFFER_SPACE (34);
2907 laststart = b;
2909 /* We test `*p == '^' twice, instead of using an if
2910 statement, so we only need one BUF_PUSH. */
2911 BUF_PUSH (*p == '^' ? charset_not : charset);
2912 if (*p == '^')
2913 p++;
2915 /* Remember the first position in the bracket expression. */
2916 p1 = p;
2918 /* Push the number of bytes in the bitmap. */
2919 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2921 /* Clear the whole map. */
2922 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2924 /* charset_not matches newline according to a syntax bit. */
2925 if ((re_opcode_t) b[-2] == charset_not
2926 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2927 SET_LIST_BIT ('\n');
2929 /* Read in characters and ranges, setting map bits. */
2930 for (;;)
2932 boolean escaped_char = false;
2933 const unsigned char *p2 = p;
2934 re_wchar_t ch, c2;
2936 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2938 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2939 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2940 So the translation is done later in a loop. Example:
2941 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2942 PATFETCH (c);
2944 /* \ might escape characters inside [...] and [^...]. */
2945 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2947 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2949 PATFETCH (c);
2950 escaped_char = true;
2952 else
2954 /* Could be the end of the bracket expression. If it's
2955 not (i.e., when the bracket expression is `[]' so
2956 far), the ']' character bit gets set way below. */
2957 if (c == ']' && p2 != p1)
2958 break;
2961 /* See if we're at the beginning of a possible character
2962 class. */
2964 if (!escaped_char &&
2965 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2967 /* Leave room for the null. */
2968 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2969 const unsigned char *class_beg;
2971 PATFETCH (c);
2972 c1 = 0;
2973 class_beg = p;
2975 /* If pattern is `[[:'. */
2976 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2978 for (;;)
2980 PATFETCH (c);
2981 if ((c == ':' && *p == ']') || p == pend)
2982 break;
2983 if (c1 < CHAR_CLASS_MAX_LENGTH)
2984 str[c1++] = c;
2985 else
2986 /* This is in any case an invalid class name. */
2987 str[0] = '\0';
2989 str[c1] = '\0';
2991 /* If isn't a word bracketed by `[:' and `:]':
2992 undo the ending character, the letters, and
2993 leave the leading `:' and `[' (but set bits for
2994 them). */
2995 if (c == ':' && *p == ']')
2997 re_wctype_t cc;
2998 int limit;
3000 cc = re_wctype (str);
3002 if (cc == 0)
3003 FREE_STACK_RETURN (REG_ECTYPE);
3005 /* Throw away the ] at the end of the character
3006 class. */
3007 PATFETCH (c);
3009 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3011 #ifndef emacs
3012 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
3013 if (re_iswctype (btowc (ch), cc))
3015 c = TRANSLATE (ch);
3016 if (c < (1 << BYTEWIDTH))
3017 SET_LIST_BIT (c);
3019 #else /* emacs */
3020 /* Most character classes in a multibyte match
3021 just set a flag. Exceptions are is_blank,
3022 is_digit, is_cntrl, and is_xdigit, since
3023 they can only match ASCII characters. We
3024 don't need to handle them for multibyte.
3025 They are distinguished by a negative wctype. */
3027 /* Setup the gl_state object to its buffer-defined
3028 value. This hardcodes the buffer-global
3029 syntax-table for ASCII chars, while the other chars
3030 will obey syntax-table properties. It's not ideal,
3031 but it's the way it's been done until now. */
3032 SETUP_BUFFER_SYNTAX_TABLE ();
3034 for (ch = 0; ch < 256; ++ch)
3036 c = RE_CHAR_TO_MULTIBYTE (ch);
3037 if (! CHAR_BYTE8_P (c)
3038 && re_iswctype (c, cc))
3040 SET_LIST_BIT (ch);
3041 c1 = TRANSLATE (c);
3042 if (c1 == c)
3043 continue;
3044 if (ASCII_CHAR_P (c1))
3045 SET_LIST_BIT (c1);
3046 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
3047 SET_LIST_BIT (c1);
3050 SET_RANGE_TABLE_WORK_AREA_BIT
3051 (range_table_work, re_wctype_to_bit (cc));
3052 #endif /* emacs */
3053 /* In most cases the matching rule for char classes
3054 only uses the syntax table for multibyte chars,
3055 so that the content of the syntax-table it is not
3056 hardcoded in the range_table. SPACE and WORD are
3057 the two exceptions. */
3058 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
3059 bufp->used_syntax = 1;
3061 /* Repeat the loop. */
3062 continue;
3064 else
3066 /* Go back to right after the "[:". */
3067 p = class_beg;
3068 SET_LIST_BIT ('[');
3070 /* Because the `:' may starts the range, we
3071 can't simply set bit and repeat the loop.
3072 Instead, just set it to C and handle below. */
3073 c = ':';
3077 if (p < pend && p[0] == '-' && p[1] != ']')
3080 /* Discard the `-'. */
3081 PATFETCH (c1);
3083 /* Fetch the character which ends the range. */
3084 PATFETCH (c1);
3085 #ifdef emacs
3086 if (CHAR_BYTE8_P (c1)
3087 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
3088 /* Treat the range from a multibyte character to
3089 raw-byte character as empty. */
3090 c = c1 + 1;
3091 #endif /* emacs */
3093 else
3094 /* Range from C to C. */
3095 c1 = c;
3097 if (c > c1)
3099 if (syntax & RE_NO_EMPTY_RANGES)
3100 FREE_STACK_RETURN (REG_ERANGEX);
3101 /* Else, repeat the loop. */
3103 else
3105 #ifndef emacs
3106 /* Set the range into bitmap */
3107 for (; c <= c1; c++)
3109 ch = TRANSLATE (c);
3110 if (ch < (1 << BYTEWIDTH))
3111 SET_LIST_BIT (ch);
3113 #else /* emacs */
3114 if (c < 128)
3116 ch = MIN (127, c1);
3117 SETUP_ASCII_RANGE (range_table_work, c, ch);
3118 c = ch + 1;
3119 if (CHAR_BYTE8_P (c1))
3120 c = BYTE8_TO_CHAR (128);
3122 if (c <= c1)
3124 if (CHAR_BYTE8_P (c))
3126 c = CHAR_TO_BYTE8 (c);
3127 c1 = CHAR_TO_BYTE8 (c1);
3128 for (; c <= c1; c++)
3129 SET_LIST_BIT (c);
3131 else if (multibyte)
3133 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
3135 else
3137 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
3140 #endif /* emacs */
3144 /* Discard any (non)matching list bytes that are all 0 at the
3145 end of the map. Decrease the map-length byte too. */
3146 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3147 b[-1]--;
3148 b += b[-1];
3150 /* Build real range table from work area. */
3151 if (RANGE_TABLE_WORK_USED (range_table_work)
3152 || RANGE_TABLE_WORK_BITS (range_table_work))
3154 int i;
3155 int used = RANGE_TABLE_WORK_USED (range_table_work);
3157 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3158 bytes for flags, two for COUNT, and three bytes for
3159 each character. */
3160 GET_BUFFER_SPACE (4 + used * 3);
3162 /* Indicate the existence of range table. */
3163 laststart[1] |= 0x80;
3165 /* Store the character class flag bits into the range table.
3166 If not in emacs, these flag bits are always 0. */
3167 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3168 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3170 STORE_NUMBER_AND_INCR (b, used / 2);
3171 for (i = 0; i < used; i++)
3172 STORE_CHARACTER_AND_INCR
3173 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3176 break;
3179 case '(':
3180 if (syntax & RE_NO_BK_PARENS)
3181 goto handle_open;
3182 else
3183 goto normal_char;
3186 case ')':
3187 if (syntax & RE_NO_BK_PARENS)
3188 goto handle_close;
3189 else
3190 goto normal_char;
3193 case '\n':
3194 if (syntax & RE_NEWLINE_ALT)
3195 goto handle_alt;
3196 else
3197 goto normal_char;
3200 case '|':
3201 if (syntax & RE_NO_BK_VBAR)
3202 goto handle_alt;
3203 else
3204 goto normal_char;
3207 case '{':
3208 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3209 goto handle_interval;
3210 else
3211 goto normal_char;
3214 case '\\':
3215 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3217 /* Do not translate the character after the \, so that we can
3218 distinguish, e.g., \B from \b, even if we normally would
3219 translate, e.g., B to b. */
3220 PATFETCH (c);
3222 switch (c)
3224 case '(':
3225 if (syntax & RE_NO_BK_PARENS)
3226 goto normal_backslash;
3228 handle_open:
3230 int shy = 0;
3231 regnum_t regnum = 0;
3232 if (p+1 < pend)
3234 /* Look for a special (?...) construct */
3235 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3237 PATFETCH (c); /* Gobble up the '?'. */
3238 while (!shy)
3240 PATFETCH (c);
3241 switch (c)
3243 case ':': shy = 1; break;
3244 case '0':
3245 /* An explicitly specified regnum must start
3246 with non-0. */
3247 if (regnum == 0)
3248 FREE_STACK_RETURN (REG_BADPAT);
3249 case '1': case '2': case '3': case '4':
3250 case '5': case '6': case '7': case '8': case '9':
3251 regnum = 10*regnum + (c - '0'); break;
3252 default:
3253 /* Only (?:...) is supported right now. */
3254 FREE_STACK_RETURN (REG_BADPAT);
3260 if (!shy)
3261 regnum = ++bufp->re_nsub;
3262 else if (regnum)
3263 { /* It's actually not shy, but explicitly numbered. */
3264 shy = 0;
3265 if (regnum > bufp->re_nsub)
3266 bufp->re_nsub = regnum;
3267 else if (regnum > bufp->re_nsub
3268 /* Ideally, we'd want to check that the specified
3269 group can't have matched (i.e. all subgroups
3270 using the same regnum are in other branches of
3271 OR patterns), but we don't currently keep track
3272 of enough info to do that easily. */
3273 || group_in_compile_stack (compile_stack, regnum))
3274 FREE_STACK_RETURN (REG_BADPAT);
3276 else
3277 /* It's really shy. */
3278 regnum = - bufp->re_nsub;
3280 if (COMPILE_STACK_FULL)
3282 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3283 compile_stack_elt_t);
3284 if (compile_stack.stack == NULL) return REG_ESPACE;
3286 compile_stack.size <<= 1;
3289 /* These are the values to restore when we hit end of this
3290 group. They are all relative offsets, so that if the
3291 whole pattern moves because of realloc, they will still
3292 be valid. */
3293 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3294 COMPILE_STACK_TOP.fixup_alt_jump
3295 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3296 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3297 COMPILE_STACK_TOP.regnum = regnum;
3299 /* Do not push a start_memory for groups beyond the last one
3300 we can represent in the compiled pattern. */
3301 if (regnum <= MAX_REGNUM && regnum > 0)
3302 BUF_PUSH_2 (start_memory, regnum);
3304 compile_stack.avail++;
3306 fixup_alt_jump = 0;
3307 laststart = 0;
3308 begalt = b;
3309 /* If we've reached MAX_REGNUM groups, then this open
3310 won't actually generate any code, so we'll have to
3311 clear pending_exact explicitly. */
3312 pending_exact = 0;
3313 break;
3316 case ')':
3317 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3319 if (COMPILE_STACK_EMPTY)
3321 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3322 goto normal_backslash;
3323 else
3324 FREE_STACK_RETURN (REG_ERPAREN);
3327 handle_close:
3328 FIXUP_ALT_JUMP ();
3330 /* See similar code for backslashed left paren above. */
3331 if (COMPILE_STACK_EMPTY)
3333 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3334 goto normal_char;
3335 else
3336 FREE_STACK_RETURN (REG_ERPAREN);
3339 /* Since we just checked for an empty stack above, this
3340 ``can't happen''. */
3341 assert (compile_stack.avail != 0);
3343 /* We don't just want to restore into `regnum', because
3344 later groups should continue to be numbered higher,
3345 as in `(ab)c(de)' -- the second group is #2. */
3346 regnum_t regnum;
3348 compile_stack.avail--;
3349 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3350 fixup_alt_jump
3351 = COMPILE_STACK_TOP.fixup_alt_jump
3352 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3353 : 0;
3354 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3355 regnum = COMPILE_STACK_TOP.regnum;
3356 /* If we've reached MAX_REGNUM groups, then this open
3357 won't actually generate any code, so we'll have to
3358 clear pending_exact explicitly. */
3359 pending_exact = 0;
3361 /* We're at the end of the group, so now we know how many
3362 groups were inside this one. */
3363 if (regnum <= MAX_REGNUM && regnum > 0)
3364 BUF_PUSH_2 (stop_memory, regnum);
3366 break;
3369 case '|': /* `\|'. */
3370 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3371 goto normal_backslash;
3372 handle_alt:
3373 if (syntax & RE_LIMITED_OPS)
3374 goto normal_char;
3376 /* Insert before the previous alternative a jump which
3377 jumps to this alternative if the former fails. */
3378 GET_BUFFER_SPACE (3);
3379 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3380 pending_exact = 0;
3381 b += 3;
3383 /* The alternative before this one has a jump after it
3384 which gets executed if it gets matched. Adjust that
3385 jump so it will jump to this alternative's analogous
3386 jump (put in below, which in turn will jump to the next
3387 (if any) alternative's such jump, etc.). The last such
3388 jump jumps to the correct final destination. A picture:
3389 _____ _____
3390 | | | |
3391 | v | v
3392 a | b | c
3394 If we are at `b', then fixup_alt_jump right now points to a
3395 three-byte space after `a'. We'll put in the jump, set
3396 fixup_alt_jump to right after `b', and leave behind three
3397 bytes which we'll fill in when we get to after `c'. */
3399 FIXUP_ALT_JUMP ();
3401 /* Mark and leave space for a jump after this alternative,
3402 to be filled in later either by next alternative or
3403 when know we're at the end of a series of alternatives. */
3404 fixup_alt_jump = b;
3405 GET_BUFFER_SPACE (3);
3406 b += 3;
3408 laststart = 0;
3409 begalt = b;
3410 break;
3413 case '{':
3414 /* If \{ is a literal. */
3415 if (!(syntax & RE_INTERVALS)
3416 /* If we're at `\{' and it's not the open-interval
3417 operator. */
3418 || (syntax & RE_NO_BK_BRACES))
3419 goto normal_backslash;
3421 handle_interval:
3423 /* If got here, then the syntax allows intervals. */
3425 /* At least (most) this many matches must be made. */
3426 int lower_bound = 0, upper_bound = -1;
3428 beg_interval = p;
3430 GET_UNSIGNED_NUMBER (lower_bound);
3432 if (c == ',')
3433 GET_UNSIGNED_NUMBER (upper_bound);
3434 else
3435 /* Interval such as `{1}' => match exactly once. */
3436 upper_bound = lower_bound;
3438 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3439 || (upper_bound >= 0 && lower_bound > upper_bound))
3440 FREE_STACK_RETURN (REG_BADBR);
3442 if (!(syntax & RE_NO_BK_BRACES))
3444 if (c != '\\')
3445 FREE_STACK_RETURN (REG_BADBR);
3446 if (p == pend)
3447 FREE_STACK_RETURN (REG_EESCAPE);
3448 PATFETCH (c);
3451 if (c != '}')
3452 FREE_STACK_RETURN (REG_BADBR);
3454 /* We just parsed a valid interval. */
3456 /* If it's invalid to have no preceding re. */
3457 if (!laststart)
3459 if (syntax & RE_CONTEXT_INVALID_OPS)
3460 FREE_STACK_RETURN (REG_BADRPT);
3461 else if (syntax & RE_CONTEXT_INDEP_OPS)
3462 laststart = b;
3463 else
3464 goto unfetch_interval;
3467 if (upper_bound == 0)
3468 /* If the upper bound is zero, just drop the sub pattern
3469 altogether. */
3470 b = laststart;
3471 else if (lower_bound == 1 && upper_bound == 1)
3472 /* Just match it once: nothing to do here. */
3475 /* Otherwise, we have a nontrivial interval. When
3476 we're all done, the pattern will look like:
3477 set_number_at <jump count> <upper bound>
3478 set_number_at <succeed_n count> <lower bound>
3479 succeed_n <after jump addr> <succeed_n count>
3480 <body of loop>
3481 jump_n <succeed_n addr> <jump count>
3482 (The upper bound and `jump_n' are omitted if
3483 `upper_bound' is 1, though.) */
3484 else
3485 { /* If the upper bound is > 1, we need to insert
3486 more at the end of the loop. */
3487 unsigned int nbytes = (upper_bound < 0 ? 3
3488 : upper_bound > 1 ? 5 : 0);
3489 unsigned int startoffset = 0;
3491 GET_BUFFER_SPACE (20); /* We might use less. */
3493 if (lower_bound == 0)
3495 /* A succeed_n that starts with 0 is really a
3496 a simple on_failure_jump_loop. */
3497 INSERT_JUMP (on_failure_jump_loop, laststart,
3498 b + 3 + nbytes);
3499 b += 3;
3501 else
3503 /* Initialize lower bound of the `succeed_n', even
3504 though it will be set during matching by its
3505 attendant `set_number_at' (inserted next),
3506 because `re_compile_fastmap' needs to know.
3507 Jump to the `jump_n' we might insert below. */
3508 INSERT_JUMP2 (succeed_n, laststart,
3509 b + 5 + nbytes,
3510 lower_bound);
3511 b += 5;
3513 /* Code to initialize the lower bound. Insert
3514 before the `succeed_n'. The `5' is the last two
3515 bytes of this `set_number_at', plus 3 bytes of
3516 the following `succeed_n'. */
3517 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3518 b += 5;
3519 startoffset += 5;
3522 if (upper_bound < 0)
3524 /* A negative upper bound stands for infinity,
3525 in which case it degenerates to a plain jump. */
3526 STORE_JUMP (jump, b, laststart + startoffset);
3527 b += 3;
3529 else if (upper_bound > 1)
3530 { /* More than one repetition is allowed, so
3531 append a backward jump to the `succeed_n'
3532 that starts this interval.
3534 When we've reached this during matching,
3535 we'll have matched the interval once, so
3536 jump back only `upper_bound - 1' times. */
3537 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3538 upper_bound - 1);
3539 b += 5;
3541 /* The location we want to set is the second
3542 parameter of the `jump_n'; that is `b-2' as
3543 an absolute address. `laststart' will be
3544 the `set_number_at' we're about to insert;
3545 `laststart+3' the number to set, the source
3546 for the relative address. But we are
3547 inserting into the middle of the pattern --
3548 so everything is getting moved up by 5.
3549 Conclusion: (b - 2) - (laststart + 3) + 5,
3550 i.e., b - laststart.
3552 We insert this at the beginning of the loop
3553 so that if we fail during matching, we'll
3554 reinitialize the bounds. */
3555 insert_op2 (set_number_at, laststart, b - laststart,
3556 upper_bound - 1, b);
3557 b += 5;
3560 pending_exact = 0;
3561 beg_interval = NULL;
3563 break;
3565 unfetch_interval:
3566 /* If an invalid interval, match the characters as literals. */
3567 assert (beg_interval);
3568 p = beg_interval;
3569 beg_interval = NULL;
3571 /* normal_char and normal_backslash need `c'. */
3572 c = '{';
3574 if (!(syntax & RE_NO_BK_BRACES))
3576 assert (p > pattern && p[-1] == '\\');
3577 goto normal_backslash;
3579 else
3580 goto normal_char;
3582 #ifdef emacs
3583 /* There is no way to specify the before_dot and after_dot
3584 operators. rms says this is ok. --karl */
3585 case '=':
3586 BUF_PUSH (at_dot);
3587 break;
3589 case 's':
3590 laststart = b;
3591 PATFETCH (c);
3592 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3593 break;
3595 case 'S':
3596 laststart = b;
3597 PATFETCH (c);
3598 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3599 break;
3601 case 'c':
3602 laststart = b;
3603 PATFETCH (c);
3604 BUF_PUSH_2 (categoryspec, c);
3605 break;
3607 case 'C':
3608 laststart = b;
3609 PATFETCH (c);
3610 BUF_PUSH_2 (notcategoryspec, c);
3611 break;
3612 #endif /* emacs */
3615 case 'w':
3616 if (syntax & RE_NO_GNU_OPS)
3617 goto normal_char;
3618 laststart = b;
3619 BUF_PUSH_2 (syntaxspec, Sword);
3620 break;
3623 case 'W':
3624 if (syntax & RE_NO_GNU_OPS)
3625 goto normal_char;
3626 laststart = b;
3627 BUF_PUSH_2 (notsyntaxspec, Sword);
3628 break;
3631 case '<':
3632 if (syntax & RE_NO_GNU_OPS)
3633 goto normal_char;
3634 BUF_PUSH (wordbeg);
3635 break;
3637 case '>':
3638 if (syntax & RE_NO_GNU_OPS)
3639 goto normal_char;
3640 BUF_PUSH (wordend);
3641 break;
3643 case '_':
3644 if (syntax & RE_NO_GNU_OPS)
3645 goto normal_char;
3646 laststart = b;
3647 PATFETCH (c);
3648 if (c == '<')
3649 BUF_PUSH (symbeg);
3650 else if (c == '>')
3651 BUF_PUSH (symend);
3652 else
3653 FREE_STACK_RETURN (REG_BADPAT);
3654 break;
3656 case 'b':
3657 if (syntax & RE_NO_GNU_OPS)
3658 goto normal_char;
3659 BUF_PUSH (wordbound);
3660 break;
3662 case 'B':
3663 if (syntax & RE_NO_GNU_OPS)
3664 goto normal_char;
3665 BUF_PUSH (notwordbound);
3666 break;
3668 case '`':
3669 if (syntax & RE_NO_GNU_OPS)
3670 goto normal_char;
3671 BUF_PUSH (begbuf);
3672 break;
3674 case '\'':
3675 if (syntax & RE_NO_GNU_OPS)
3676 goto normal_char;
3677 BUF_PUSH (endbuf);
3678 break;
3680 case '1': case '2': case '3': case '4': case '5':
3681 case '6': case '7': case '8': case '9':
3683 regnum_t reg;
3685 if (syntax & RE_NO_BK_REFS)
3686 goto normal_backslash;
3688 reg = c - '0';
3690 if (reg > bufp->re_nsub || reg < 1
3691 /* Can't back reference to a subexp before its end. */
3692 || group_in_compile_stack (compile_stack, reg))
3693 FREE_STACK_RETURN (REG_ESUBREG);
3695 laststart = b;
3696 BUF_PUSH_2 (duplicate, reg);
3698 break;
3701 case '+':
3702 case '?':
3703 if (syntax & RE_BK_PLUS_QM)
3704 goto handle_plus;
3705 else
3706 goto normal_backslash;
3708 default:
3709 normal_backslash:
3710 /* You might think it would be useful for \ to mean
3711 not to translate; but if we don't translate it
3712 it will never match anything. */
3713 goto normal_char;
3715 break;
3718 default:
3719 /* Expects the character in `c'. */
3720 normal_char:
3721 /* If no exactn currently being built. */
3722 if (!pending_exact
3724 /* If last exactn not at current position. */
3725 || pending_exact + *pending_exact + 1 != b
3727 /* We have only one byte following the exactn for the count. */
3728 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3730 /* If followed by a repetition operator. */
3731 || (p != pend && (*p == '*' || *p == '^'))
3732 || ((syntax & RE_BK_PLUS_QM)
3733 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3734 : p != pend && (*p == '+' || *p == '?'))
3735 || ((syntax & RE_INTERVALS)
3736 && ((syntax & RE_NO_BK_BRACES)
3737 ? p != pend && *p == '{'
3738 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3740 /* Start building a new exactn. */
3742 laststart = b;
3744 BUF_PUSH_2 (exactn, 0);
3745 pending_exact = b - 1;
3748 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3750 int len;
3752 if (multibyte)
3754 c = TRANSLATE (c);
3755 len = CHAR_STRING (c, b);
3756 b += len;
3758 else
3760 c1 = RE_CHAR_TO_MULTIBYTE (c);
3761 if (! CHAR_BYTE8_P (c1))
3763 re_wchar_t c2 = TRANSLATE (c1);
3765 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3766 c = c1;
3768 *b++ = c;
3769 len = 1;
3771 (*pending_exact) += len;
3774 break;
3775 } /* switch (c) */
3776 } /* while p != pend */
3779 /* Through the pattern now. */
3781 FIXUP_ALT_JUMP ();
3783 if (!COMPILE_STACK_EMPTY)
3784 FREE_STACK_RETURN (REG_EPAREN);
3786 /* If we don't want backtracking, force success
3787 the first time we reach the end of the compiled pattern. */
3788 if (syntax & RE_NO_POSIX_BACKTRACKING)
3789 BUF_PUSH (succeed);
3791 /* We have succeeded; set the length of the buffer. */
3792 bufp->used = b - bufp->buffer;
3794 #ifdef DEBUG
3795 if (debug > 0)
3797 re_compile_fastmap (bufp);
3798 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3799 print_compiled_pattern (bufp);
3801 debug--;
3802 #endif /* DEBUG */
3804 #ifndef MATCH_MAY_ALLOCATE
3805 /* Initialize the failure stack to the largest possible stack. This
3806 isn't necessary unless we're trying to avoid calling alloca in
3807 the search and match routines. */
3809 int num_regs = bufp->re_nsub + 1;
3811 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3813 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3815 if (! fail_stack.stack)
3816 fail_stack.stack
3817 = (fail_stack_elt_t *) malloc (fail_stack.size
3818 * sizeof (fail_stack_elt_t));
3819 else
3820 fail_stack.stack
3821 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3822 (fail_stack.size
3823 * sizeof (fail_stack_elt_t)));
3826 regex_grow_registers (num_regs);
3828 #endif /* not MATCH_MAY_ALLOCATE */
3830 FREE_STACK_RETURN (REG_NOERROR);
3831 } /* regex_compile */
3833 /* Subroutines for `regex_compile'. */
3835 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3837 static void
3838 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3840 *loc = (unsigned char) op;
3841 STORE_NUMBER (loc + 1, arg);
3845 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3847 static void
3848 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3850 *loc = (unsigned char) op;
3851 STORE_NUMBER (loc + 1, arg1);
3852 STORE_NUMBER (loc + 3, arg2);
3856 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3857 for OP followed by two-byte integer parameter ARG. */
3859 static void
3860 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3862 register unsigned char *pfrom = end;
3863 register unsigned char *pto = end + 3;
3865 while (pfrom != loc)
3866 *--pto = *--pfrom;
3868 store_op1 (op, loc, arg);
3872 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3874 static void
3875 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3877 register unsigned char *pfrom = end;
3878 register unsigned char *pto = end + 5;
3880 while (pfrom != loc)
3881 *--pto = *--pfrom;
3883 store_op2 (op, loc, arg1, arg2);
3887 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3888 after an alternative or a begin-subexpression. We assume there is at
3889 least one character before the ^. */
3891 static boolean
3892 at_begline_loc_p (const re_char *pattern, const re_char *p, reg_syntax_t syntax)
3894 re_char *prev = p - 2;
3895 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3897 return
3898 /* After a subexpression? */
3899 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3900 /* After an alternative? */
3901 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash))
3902 /* After a shy subexpression? */
3903 || ((syntax & RE_SHY_GROUPS) && prev - 2 >= pattern
3904 && prev[-1] == '?' && prev[-2] == '('
3905 && (syntax & RE_NO_BK_PARENS
3906 || (prev - 3 >= pattern && prev[-3] == '\\')));
3910 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3911 at least one character after the $, i.e., `P < PEND'. */
3913 static boolean
3914 at_endline_loc_p (const re_char *p, const re_char *pend, reg_syntax_t syntax)
3916 re_char *next = p;
3917 boolean next_backslash = *next == '\\';
3918 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3920 return
3921 /* Before a subexpression? */
3922 (syntax & RE_NO_BK_PARENS ? *next == ')'
3923 : next_backslash && next_next && *next_next == ')')
3924 /* Before an alternative? */
3925 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3926 : next_backslash && next_next && *next_next == '|');
3930 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3931 false if it's not. */
3933 static boolean
3934 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3936 int this_element;
3938 for (this_element = compile_stack.avail - 1;
3939 this_element >= 0;
3940 this_element--)
3941 if (compile_stack.stack[this_element].regnum == regnum)
3942 return true;
3944 return false;
3947 /* analyse_first.
3948 If fastmap is non-NULL, go through the pattern and fill fastmap
3949 with all the possible leading chars. If fastmap is NULL, don't
3950 bother filling it up (obviously) and only return whether the
3951 pattern could potentially match the empty string.
3953 Return 1 if p..pend might match the empty string.
3954 Return 0 if p..pend matches at least one char.
3955 Return -1 if fastmap was not updated accurately. */
3957 static int
3958 analyse_first (const re_char *p, const re_char *pend, char *fastmap, const int multibyte)
3960 int j, k;
3961 boolean not;
3963 /* If all elements for base leading-codes in fastmap is set, this
3964 flag is set true. */
3965 boolean match_any_multibyte_characters = false;
3967 assert (p);
3969 /* The loop below works as follows:
3970 - It has a working-list kept in the PATTERN_STACK and which basically
3971 starts by only containing a pointer to the first operation.
3972 - If the opcode we're looking at is a match against some set of
3973 chars, then we add those chars to the fastmap and go on to the
3974 next work element from the worklist (done via `break').
3975 - If the opcode is a control operator on the other hand, we either
3976 ignore it (if it's meaningless at this point, such as `start_memory')
3977 or execute it (if it's a jump). If the jump has several destinations
3978 (i.e. `on_failure_jump'), then we push the other destination onto the
3979 worklist.
3980 We guarantee termination by ignoring backward jumps (more or less),
3981 so that `p' is monotonically increasing. More to the point, we
3982 never set `p' (or push) anything `<= p1'. */
3984 while (p < pend)
3986 /* `p1' is used as a marker of how far back a `on_failure_jump'
3987 can go without being ignored. It is normally equal to `p'
3988 (which prevents any backward `on_failure_jump') except right
3989 after a plain `jump', to allow patterns such as:
3990 0: jump 10
3991 3..9: <body>
3992 10: on_failure_jump 3
3993 as used for the *? operator. */
3994 re_char *p1 = p;
3996 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3998 case succeed:
3999 return 1;
4001 case duplicate:
4002 /* If the first character has to match a backreference, that means
4003 that the group was empty (since it already matched). Since this
4004 is the only case that interests us here, we can assume that the
4005 backreference must match the empty string. */
4006 p++;
4007 continue;
4010 /* Following are the cases which match a character. These end
4011 with `break'. */
4013 case exactn:
4014 if (fastmap)
4016 /* If multibyte is nonzero, the first byte of each
4017 character is an ASCII or a leading code. Otherwise,
4018 each byte is a character. Thus, this works in both
4019 cases. */
4020 fastmap[p[1]] = 1;
4021 if (! multibyte)
4023 /* For the case of matching this unibyte regex
4024 against multibyte, we must set a leading code of
4025 the corresponding multibyte character. */
4026 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
4028 fastmap[CHAR_LEADING_CODE (c)] = 1;
4031 break;
4034 case anychar:
4035 /* We could put all the chars except for \n (and maybe \0)
4036 but we don't bother since it is generally not worth it. */
4037 if (!fastmap) break;
4038 return -1;
4041 case charset_not:
4042 if (!fastmap) break;
4044 /* Chars beyond end of bitmap are possible matches. */
4045 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
4046 j < (1 << BYTEWIDTH); j++)
4047 fastmap[j] = 1;
4050 /* Fallthrough */
4051 case charset:
4052 if (!fastmap) break;
4053 not = (re_opcode_t) *(p - 1) == charset_not;
4054 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
4055 j >= 0; j--)
4056 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
4057 fastmap[j] = 1;
4059 #ifdef emacs
4060 if (/* Any leading code can possibly start a character
4061 which doesn't match the specified set of characters. */
4064 /* If we can match a character class, we can match any
4065 multibyte characters. */
4066 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
4067 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
4070 if (match_any_multibyte_characters == false)
4072 for (j = MIN_MULTIBYTE_LEADING_CODE;
4073 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4074 fastmap[j] = 1;
4075 match_any_multibyte_characters = true;
4079 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
4080 && match_any_multibyte_characters == false)
4082 /* Set fastmap[I] to 1 where I is a leading code of each
4083 multibyte character in the range table. */
4084 int c, count;
4085 unsigned char lc1, lc2;
4087 /* Make P points the range table. `+ 2' is to skip flag
4088 bits for a character class. */
4089 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
4091 /* Extract the number of ranges in range table into COUNT. */
4092 EXTRACT_NUMBER_AND_INCR (count, p);
4093 for (; count > 0; count--, p += 3)
4095 /* Extract the start and end of each range. */
4096 EXTRACT_CHARACTER (c, p);
4097 lc1 = CHAR_LEADING_CODE (c);
4098 p += 3;
4099 EXTRACT_CHARACTER (c, p);
4100 lc2 = CHAR_LEADING_CODE (c);
4101 for (j = lc1; j <= lc2; j++)
4102 fastmap[j] = 1;
4105 #endif
4106 break;
4108 case syntaxspec:
4109 case notsyntaxspec:
4110 if (!fastmap) break;
4111 #ifndef emacs
4112 not = (re_opcode_t)p[-1] == notsyntaxspec;
4113 k = *p++;
4114 for (j = 0; j < (1 << BYTEWIDTH); j++)
4115 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
4116 fastmap[j] = 1;
4117 break;
4118 #else /* emacs */
4119 /* This match depends on text properties. These end with
4120 aborting optimizations. */
4121 return -1;
4123 case categoryspec:
4124 case notcategoryspec:
4125 if (!fastmap) break;
4126 not = (re_opcode_t)p[-1] == notcategoryspec;
4127 k = *p++;
4128 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4129 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4130 fastmap[j] = 1;
4132 /* Any leading code can possibly start a character which
4133 has or doesn't has the specified category. */
4134 if (match_any_multibyte_characters == false)
4136 for (j = MIN_MULTIBYTE_LEADING_CODE;
4137 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4138 fastmap[j] = 1;
4139 match_any_multibyte_characters = true;
4141 break;
4143 /* All cases after this match the empty string. These end with
4144 `continue'. */
4146 case before_dot:
4147 case at_dot:
4148 case after_dot:
4149 #endif /* !emacs */
4150 case no_op:
4151 case begline:
4152 case endline:
4153 case begbuf:
4154 case endbuf:
4155 case wordbound:
4156 case notwordbound:
4157 case wordbeg:
4158 case wordend:
4159 case symbeg:
4160 case symend:
4161 continue;
4164 case jump:
4165 EXTRACT_NUMBER_AND_INCR (j, p);
4166 if (j < 0)
4167 /* Backward jumps can only go back to code that we've already
4168 visited. `re_compile' should make sure this is true. */
4169 break;
4170 p += j;
4171 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4173 case on_failure_jump:
4174 case on_failure_keep_string_jump:
4175 case on_failure_jump_loop:
4176 case on_failure_jump_nastyloop:
4177 case on_failure_jump_smart:
4178 p++;
4179 break;
4180 default:
4181 continue;
4183 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4184 to jump back to "just after here". */
4185 /* Fallthrough */
4187 case on_failure_jump:
4188 case on_failure_keep_string_jump:
4189 case on_failure_jump_nastyloop:
4190 case on_failure_jump_loop:
4191 case on_failure_jump_smart:
4192 EXTRACT_NUMBER_AND_INCR (j, p);
4193 if (p + j <= p1)
4194 ; /* Backward jump to be ignored. */
4195 else
4196 { /* We have to look down both arms.
4197 We first go down the "straight" path so as to minimize
4198 stack usage when going through alternatives. */
4199 int r = analyse_first (p, pend, fastmap, multibyte);
4200 if (r) return r;
4201 p += j;
4203 continue;
4206 case jump_n:
4207 /* This code simply does not properly handle forward jump_n. */
4208 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4209 p += 4;
4210 /* jump_n can either jump or fall through. The (backward) jump
4211 case has already been handled, so we only need to look at the
4212 fallthrough case. */
4213 continue;
4215 case succeed_n:
4216 /* If N == 0, it should be an on_failure_jump_loop instead. */
4217 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4218 p += 4;
4219 /* We only care about one iteration of the loop, so we don't
4220 need to consider the case where this behaves like an
4221 on_failure_jump. */
4222 continue;
4225 case set_number_at:
4226 p += 4;
4227 continue;
4230 case start_memory:
4231 case stop_memory:
4232 p += 1;
4233 continue;
4236 default:
4237 abort (); /* We have listed all the cases. */
4238 } /* switch *p++ */
4240 /* Getting here means we have found the possible starting
4241 characters for one path of the pattern -- and that the empty
4242 string does not match. We need not follow this path further. */
4243 return 0;
4244 } /* while p */
4246 /* We reached the end without matching anything. */
4247 return 1;
4249 } /* analyse_first */
4251 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4252 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4253 characters can start a string that matches the pattern. This fastmap
4254 is used by re_search to skip quickly over impossible starting points.
4256 Character codes above (1 << BYTEWIDTH) are not represented in the
4257 fastmap, but the leading codes are represented. Thus, the fastmap
4258 indicates which character sets could start a match.
4260 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4261 area as BUFP->fastmap.
4263 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4264 the pattern buffer.
4266 Returns 0 if we succeed, -2 if an internal error. */
4269 re_compile_fastmap (struct re_pattern_buffer *bufp)
4271 char *fastmap = bufp->fastmap;
4272 int analysis;
4274 assert (fastmap && bufp->buffer);
4276 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4277 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4279 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
4280 fastmap, RE_MULTIBYTE_P (bufp));
4281 bufp->can_be_null = (analysis != 0);
4282 return 0;
4283 } /* re_compile_fastmap */
4285 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4286 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4287 this memory for recording register information. STARTS and ENDS
4288 must be allocated using the malloc library routine, and must each
4289 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4291 If NUM_REGS == 0, then subsequent matches should allocate their own
4292 register data.
4294 Unless this function is called, the first search or match using
4295 PATTERN_BUFFER will allocate its own register data, without
4296 freeing the old data. */
4298 void
4299 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4301 if (num_regs)
4303 bufp->regs_allocated = REGS_REALLOCATE;
4304 regs->num_regs = num_regs;
4305 regs->start = starts;
4306 regs->end = ends;
4308 else
4310 bufp->regs_allocated = REGS_UNALLOCATED;
4311 regs->num_regs = 0;
4312 regs->start = regs->end = (regoff_t *) 0;
4315 WEAK_ALIAS (__re_set_registers, re_set_registers)
4317 /* Searching routines. */
4319 /* Like re_search_2, below, but only one string is specified, and
4320 doesn't let you say where to stop matching. */
4323 re_search (struct re_pattern_buffer *bufp, const char *string, int size, int startpos, int range, struct re_registers *regs)
4325 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4326 regs, size);
4328 WEAK_ALIAS (__re_search, re_search)
4330 /* Head address of virtual concatenation of string. */
4331 #define HEAD_ADDR_VSTRING(P) \
4332 (((P) >= size1 ? string2 : string1))
4334 /* End address of virtual concatenation of string. */
4335 #define STOP_ADDR_VSTRING(P) \
4336 (((P) >= size1 ? string2 + size2 : string1 + size1))
4338 /* Address of POS in the concatenation of virtual string. */
4339 #define POS_ADDR_VSTRING(POS) \
4340 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4342 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4343 virtual concatenation of STRING1 and STRING2, starting first at index
4344 STARTPOS, then at STARTPOS + 1, and so on.
4346 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4348 RANGE is how far to scan while trying to match. RANGE = 0 means try
4349 only at STARTPOS; in general, the last start tried is STARTPOS +
4350 RANGE.
4352 In REGS, return the indices of the virtual concatenation of STRING1
4353 and STRING2 that matched the entire BUFP->buffer and its contained
4354 subexpressions.
4356 Do not consider matching one past the index STOP in the virtual
4357 concatenation of STRING1 and STRING2.
4359 We return either the position in the strings at which the match was
4360 found, -1 if no match, or -2 if error (such as failure
4361 stack overflow). */
4364 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, int size1, const char *str2, int size2, int startpos, int range, struct re_registers *regs, int stop)
4366 int val;
4367 re_char *string1 = (re_char*) str1;
4368 re_char *string2 = (re_char*) str2;
4369 register char *fastmap = bufp->fastmap;
4370 register RE_TRANSLATE_TYPE translate = bufp->translate;
4371 int total_size = size1 + size2;
4372 int endpos = startpos + range;
4373 boolean anchored_start;
4374 /* Nonzero if we are searching multibyte string. */
4375 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4377 /* Check for out-of-range STARTPOS. */
4378 if (startpos < 0 || startpos > total_size)
4379 return -1;
4381 /* Fix up RANGE if it might eventually take us outside
4382 the virtual concatenation of STRING1 and STRING2.
4383 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4384 if (endpos < 0)
4385 range = 0 - startpos;
4386 else if (endpos > total_size)
4387 range = total_size - startpos;
4389 /* If the search isn't to be a backwards one, don't waste time in a
4390 search for a pattern anchored at beginning of buffer. */
4391 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4393 if (startpos > 0)
4394 return -1;
4395 else
4396 range = 0;
4399 #ifdef emacs
4400 /* In a forward search for something that starts with \=.
4401 don't keep searching past point. */
4402 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4404 range = PT_BYTE - BEGV_BYTE - startpos;
4405 if (range < 0)
4406 return -1;
4408 #endif /* emacs */
4410 /* Update the fastmap now if not correct already. */
4411 if (fastmap && !bufp->fastmap_accurate)
4412 re_compile_fastmap (bufp);
4414 /* See whether the pattern is anchored. */
4415 anchored_start = (bufp->buffer[0] == begline);
4417 #ifdef emacs
4418 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4420 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4422 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4424 #endif
4426 /* Loop through the string, looking for a place to start matching. */
4427 for (;;)
4429 /* If the pattern is anchored,
4430 skip quickly past places we cannot match.
4431 We don't bother to treat startpos == 0 specially
4432 because that case doesn't repeat. */
4433 if (anchored_start && startpos > 0)
4435 if (! ((startpos <= size1 ? string1[startpos - 1]
4436 : string2[startpos - size1 - 1])
4437 == '\n'))
4438 goto advance;
4441 /* If a fastmap is supplied, skip quickly over characters that
4442 cannot be the start of a match. If the pattern can match the
4443 null string, however, we don't need to skip characters; we want
4444 the first null string. */
4445 if (fastmap && startpos < total_size && !bufp->can_be_null)
4447 register re_char *d;
4448 register re_wchar_t buf_ch;
4450 d = POS_ADDR_VSTRING (startpos);
4452 if (range > 0) /* Searching forwards. */
4454 register int lim = 0;
4455 int irange = range;
4457 if (startpos < size1 && startpos + range >= size1)
4458 lim = range - (size1 - startpos);
4460 /* Written out as an if-else to avoid testing `translate'
4461 inside the loop. */
4462 if (RE_TRANSLATE_P (translate))
4464 if (multibyte)
4465 while (range > lim)
4467 int buf_charlen;
4469 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4470 buf_ch = RE_TRANSLATE (translate, buf_ch);
4471 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4472 break;
4474 range -= buf_charlen;
4475 d += buf_charlen;
4477 else
4478 while (range > lim)
4480 register re_wchar_t ch, translated;
4482 buf_ch = *d;
4483 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4484 translated = RE_TRANSLATE (translate, ch);
4485 if (translated != ch
4486 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4487 buf_ch = ch;
4488 if (fastmap[buf_ch])
4489 break;
4490 d++;
4491 range--;
4494 else
4496 if (multibyte)
4497 while (range > lim)
4499 int buf_charlen;
4501 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4502 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4503 break;
4504 range -= buf_charlen;
4505 d += buf_charlen;
4507 else
4508 while (range > lim && !fastmap[*d])
4510 d++;
4511 range--;
4514 startpos += irange - range;
4516 else /* Searching backwards. */
4518 if (multibyte)
4520 buf_ch = STRING_CHAR (d);
4521 buf_ch = TRANSLATE (buf_ch);
4522 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4523 goto advance;
4525 else
4527 register re_wchar_t ch, translated;
4529 buf_ch = *d;
4530 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4531 translated = TRANSLATE (ch);
4532 if (translated != ch
4533 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4534 buf_ch = ch;
4535 if (! fastmap[TRANSLATE (buf_ch)])
4536 goto advance;
4541 /* If can't match the null string, and that's all we have left, fail. */
4542 if (range >= 0 && startpos == total_size && fastmap
4543 && !bufp->can_be_null)
4544 return -1;
4546 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4547 startpos, regs, stop);
4549 if (val >= 0)
4550 return startpos;
4552 if (val == -2)
4553 return -2;
4555 advance:
4556 if (!range)
4557 break;
4558 else if (range > 0)
4560 /* Update STARTPOS to the next character boundary. */
4561 if (multibyte)
4563 re_char *p = POS_ADDR_VSTRING (startpos);
4564 re_char *pend = STOP_ADDR_VSTRING (startpos);
4565 int len = BYTES_BY_CHAR_HEAD (*p);
4567 range -= len;
4568 if (range < 0)
4569 break;
4570 startpos += len;
4572 else
4574 range--;
4575 startpos++;
4578 else
4580 range++;
4581 startpos--;
4583 /* Update STARTPOS to the previous character boundary. */
4584 if (multibyte)
4586 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4587 re_char *p0 = p;
4588 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4590 /* Find the head of multibyte form. */
4591 PREV_CHAR_BOUNDARY (p, phead);
4592 range += p0 - 1 - p;
4593 if (range > 0)
4594 break;
4596 startpos -= p0 - 1 - p;
4600 return -1;
4601 } /* re_search_2 */
4602 WEAK_ALIAS (__re_search_2, re_search_2)
4604 /* Declarations and macros for re_match_2. */
4606 static int bcmp_translate _RE_ARGS((re_char *s1, re_char *s2,
4607 register int len,
4608 RE_TRANSLATE_TYPE translate,
4609 const int multibyte));
4611 /* This converts PTR, a pointer into one of the search strings `string1'
4612 and `string2' into an offset from the beginning of that string. */
4613 #define POINTER_TO_OFFSET(ptr) \
4614 (FIRST_STRING_P (ptr) \
4615 ? ((regoff_t) ((ptr) - string1)) \
4616 : ((regoff_t) ((ptr) - string2 + size1)))
4618 /* Call before fetching a character with *d. This switches over to
4619 string2 if necessary.
4620 Check re_match_2_internal for a discussion of why end_match_2 might
4621 not be within string2 (but be equal to end_match_1 instead). */
4622 #define PREFETCH() \
4623 while (d == dend) \
4625 /* End of string2 => fail. */ \
4626 if (dend == end_match_2) \
4627 goto fail; \
4628 /* End of string1 => advance to string2. */ \
4629 d = string2; \
4630 dend = end_match_2; \
4633 /* Call before fetching a char with *d if you already checked other limits.
4634 This is meant for use in lookahead operations like wordend, etc..
4635 where we might need to look at parts of the string that might be
4636 outside of the LIMITs (i.e past `stop'). */
4637 #define PREFETCH_NOLIMIT() \
4638 if (d == end1) \
4640 d = string2; \
4641 dend = end_match_2; \
4644 /* Test if at very beginning or at very end of the virtual concatenation
4645 of `string1' and `string2'. If only one string, it's `string2'. */
4646 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4647 #define AT_STRINGS_END(d) ((d) == end2)
4650 /* Test if D points to a character which is word-constituent. We have
4651 two special cases to check for: if past the end of string1, look at
4652 the first character in string2; and if before the beginning of
4653 string2, look at the last character in string1. */
4654 #define WORDCHAR_P(d) \
4655 (SYNTAX ((d) == end1 ? *string2 \
4656 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4657 == Sword)
4659 /* Disabled due to a compiler bug -- see comment at case wordbound */
4661 /* The comment at case wordbound is following one, but we don't use
4662 AT_WORD_BOUNDARY anymore to support multibyte form.
4664 The DEC Alpha C compiler 3.x generates incorrect code for the
4665 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4666 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4667 macro and introducing temporary variables works around the bug. */
4669 #if 0
4670 /* Test if the character before D and the one at D differ with respect
4671 to being word-constituent. */
4672 #define AT_WORD_BOUNDARY(d) \
4673 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4674 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4675 #endif
4677 /* Free everything we malloc. */
4678 #ifdef MATCH_MAY_ALLOCATE
4679 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4680 # define FREE_VARIABLES() \
4681 do { \
4682 REGEX_FREE_STACK (fail_stack.stack); \
4683 FREE_VAR (regstart); \
4684 FREE_VAR (regend); \
4685 FREE_VAR (best_regstart); \
4686 FREE_VAR (best_regend); \
4687 } while (0)
4688 #else
4689 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4690 #endif /* not MATCH_MAY_ALLOCATE */
4693 /* Optimization routines. */
4695 /* If the operation is a match against one or more chars,
4696 return a pointer to the next operation, else return NULL. */
4697 static re_char *
4698 skip_one_char (const re_char *p)
4700 switch (SWITCH_ENUM_CAST (*p++))
4702 case anychar:
4703 break;
4705 case exactn:
4706 p += *p + 1;
4707 break;
4709 case charset_not:
4710 case charset:
4711 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4713 int mcnt;
4714 p = CHARSET_RANGE_TABLE (p - 1);
4715 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4716 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4718 else
4719 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4720 break;
4722 case syntaxspec:
4723 case notsyntaxspec:
4724 #ifdef emacs
4725 case categoryspec:
4726 case notcategoryspec:
4727 #endif /* emacs */
4728 p++;
4729 break;
4731 default:
4732 p = NULL;
4734 return p;
4738 /* Jump over non-matching operations. */
4739 static re_char *
4740 skip_noops (const re_char *p, const re_char *pend)
4742 int mcnt;
4743 while (p < pend)
4745 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4747 case start_memory:
4748 case stop_memory:
4749 p += 2; break;
4750 case no_op:
4751 p += 1; break;
4752 case jump:
4753 p += 1;
4754 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4755 p += mcnt;
4756 break;
4757 default:
4758 return p;
4761 assert (p == pend);
4762 return p;
4765 /* Non-zero if "p1 matches something" implies "p2 fails". */
4766 static int
4767 mutually_exclusive_p (struct re_pattern_buffer *bufp, const re_char *p1, const re_char *p2)
4769 re_opcode_t op2;
4770 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4771 unsigned char *pend = bufp->buffer + bufp->used;
4773 assert (p1 >= bufp->buffer && p1 < pend
4774 && p2 >= bufp->buffer && p2 <= pend);
4776 /* Skip over open/close-group commands.
4777 If what follows this loop is a ...+ construct,
4778 look at what begins its body, since we will have to
4779 match at least one of that. */
4780 p2 = skip_noops (p2, pend);
4781 /* The same skip can be done for p1, except that this function
4782 is only used in the case where p1 is a simple match operator. */
4783 /* p1 = skip_noops (p1, pend); */
4785 assert (p1 >= bufp->buffer && p1 < pend
4786 && p2 >= bufp->buffer && p2 <= pend);
4788 op2 = p2 == pend ? succeed : *p2;
4790 switch (SWITCH_ENUM_CAST (op2))
4792 case succeed:
4793 case endbuf:
4794 /* If we're at the end of the pattern, we can change. */
4795 if (skip_one_char (p1))
4797 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4798 return 1;
4800 break;
4802 case endline:
4803 case exactn:
4805 register re_wchar_t c
4806 = (re_opcode_t) *p2 == endline ? '\n'
4807 : RE_STRING_CHAR (p2 + 2, multibyte);
4809 if ((re_opcode_t) *p1 == exactn)
4811 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4813 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4814 return 1;
4818 else if ((re_opcode_t) *p1 == charset
4819 || (re_opcode_t) *p1 == charset_not)
4821 int not = (re_opcode_t) *p1 == charset_not;
4823 /* Test if C is listed in charset (or charset_not)
4824 at `p1'. */
4825 if (! multibyte || IS_REAL_ASCII (c))
4827 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4828 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4829 not = !not;
4831 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4832 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4834 /* `not' is equal to 1 if c would match, which means
4835 that we can't change to pop_failure_jump. */
4836 if (!not)
4838 DEBUG_PRINT1 (" No match => fast loop.\n");
4839 return 1;
4842 else if ((re_opcode_t) *p1 == anychar
4843 && c == '\n')
4845 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4846 return 1;
4849 break;
4851 case charset:
4853 if ((re_opcode_t) *p1 == exactn)
4854 /* Reuse the code above. */
4855 return mutually_exclusive_p (bufp, p2, p1);
4857 /* It is hard to list up all the character in charset
4858 P2 if it includes multibyte character. Give up in
4859 such case. */
4860 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4862 /* Now, we are sure that P2 has no range table.
4863 So, for the size of bitmap in P2, `p2[1]' is
4864 enough. But P1 may have range table, so the
4865 size of bitmap table of P1 is extracted by
4866 using macro `CHARSET_BITMAP_SIZE'.
4868 In a multibyte case, we know that all the character
4869 listed in P2 is ASCII. In a unibyte case, P1 has only a
4870 bitmap table. So, in both cases, it is enough to test
4871 only the bitmap table of P1. */
4873 if ((re_opcode_t) *p1 == charset)
4875 int idx;
4876 /* We win if the charset inside the loop
4877 has no overlap with the one after the loop. */
4878 for (idx = 0;
4879 (idx < (int) p2[1]
4880 && idx < CHARSET_BITMAP_SIZE (p1));
4881 idx++)
4882 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4883 break;
4885 if (idx == p2[1]
4886 || idx == CHARSET_BITMAP_SIZE (p1))
4888 DEBUG_PRINT1 (" No match => fast loop.\n");
4889 return 1;
4892 else if ((re_opcode_t) *p1 == charset_not)
4894 int idx;
4895 /* We win if the charset_not inside the loop lists
4896 every character listed in the charset after. */
4897 for (idx = 0; idx < (int) p2[1]; idx++)
4898 if (! (p2[2 + idx] == 0
4899 || (idx < CHARSET_BITMAP_SIZE (p1)
4900 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4901 break;
4903 if (idx == p2[1])
4905 DEBUG_PRINT1 (" No match => fast loop.\n");
4906 return 1;
4911 break;
4913 case charset_not:
4914 switch (SWITCH_ENUM_CAST (*p1))
4916 case exactn:
4917 case charset:
4918 /* Reuse the code above. */
4919 return mutually_exclusive_p (bufp, p2, p1);
4920 case charset_not:
4921 /* When we have two charset_not, it's very unlikely that
4922 they don't overlap. The union of the two sets of excluded
4923 chars should cover all possible chars, which, as a matter of
4924 fact, is virtually impossible in multibyte buffers. */
4925 break;
4927 break;
4929 case wordend:
4930 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4931 case symend:
4932 return ((re_opcode_t) *p1 == syntaxspec
4933 && (p1[1] == Ssymbol || p1[1] == Sword));
4934 case notsyntaxspec:
4935 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4937 case wordbeg:
4938 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4939 case symbeg:
4940 return ((re_opcode_t) *p1 == notsyntaxspec
4941 && (p1[1] == Ssymbol || p1[1] == Sword));
4942 case syntaxspec:
4943 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4945 case wordbound:
4946 return (((re_opcode_t) *p1 == notsyntaxspec
4947 || (re_opcode_t) *p1 == syntaxspec)
4948 && p1[1] == Sword);
4950 #ifdef emacs
4951 case categoryspec:
4952 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4953 case notcategoryspec:
4954 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4955 #endif /* emacs */
4957 default:
4961 /* Safe default. */
4962 return 0;
4966 /* Matching routines. */
4968 #ifndef emacs /* Emacs never uses this. */
4969 /* re_match is like re_match_2 except it takes only a single string. */
4972 re_match (struct re_pattern_buffer *bufp, const char *string,
4973 int size, int pos, struct re_registers *regs)
4975 int result = re_match_2_internal (bufp, NULL, 0, (re_char*) string, size,
4976 pos, regs, size);
4977 return result;
4979 WEAK_ALIAS (__re_match, re_match)
4980 #endif /* not emacs */
4982 #ifdef emacs
4983 /* In Emacs, this is the string or buffer in which we
4984 are matching. It is used for looking up syntax properties. */
4985 Lisp_Object re_match_object;
4986 #endif
4988 /* re_match_2 matches the compiled pattern in BUFP against the
4989 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4990 and SIZE2, respectively). We start matching at POS, and stop
4991 matching at STOP.
4993 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4994 store offsets for the substring each group matched in REGS. See the
4995 documentation for exactly how many groups we fill.
4997 We return -1 if no match, -2 if an internal error (such as the
4998 failure stack overflowing). Otherwise, we return the length of the
4999 matched substring. */
5002 re_match_2 (struct re_pattern_buffer *bufp, const char *string1, int size1, const char *string2, int size2, int pos, struct re_registers *regs, int stop)
5004 int result;
5006 #ifdef emacs
5007 int charpos;
5008 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
5009 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
5010 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
5011 #endif
5013 result = re_match_2_internal (bufp, (re_char*) string1, size1,
5014 (re_char*) string2, size2,
5015 pos, regs, stop);
5016 return result;
5018 WEAK_ALIAS (__re_match_2, re_match_2)
5021 /* This is a separate function so that we can force an alloca cleanup
5022 afterwards. */
5023 static int
5024 re_match_2_internal (struct re_pattern_buffer *bufp, const re_char *string1, int size1, const re_char *string2, int size2, int pos, struct re_registers *regs, int stop)
5026 /* General temporaries. */
5027 int mcnt;
5028 size_t reg;
5029 boolean not;
5031 /* Just past the end of the corresponding string. */
5032 re_char *end1, *end2;
5034 /* Pointers into string1 and string2, just past the last characters in
5035 each to consider matching. */
5036 re_char *end_match_1, *end_match_2;
5038 /* Where we are in the data, and the end of the current string. */
5039 re_char *d, *dend;
5041 /* Used sometimes to remember where we were before starting matching
5042 an operator so that we can go back in case of failure. This "atomic"
5043 behavior of matching opcodes is indispensable to the correctness
5044 of the on_failure_keep_string_jump optimization. */
5045 re_char *dfail;
5047 /* Where we are in the pattern, and the end of the pattern. */
5048 re_char *p = bufp->buffer;
5049 re_char *pend = p + bufp->used;
5051 /* We use this to map every character in the string. */
5052 RE_TRANSLATE_TYPE translate = bufp->translate;
5054 /* Nonzero if BUFP is setup from a multibyte regex. */
5055 const boolean multibyte = RE_MULTIBYTE_P (bufp);
5057 /* Nonzero if STRING1/STRING2 are multibyte. */
5058 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
5060 /* Failure point stack. Each place that can handle a failure further
5061 down the line pushes a failure point on this stack. It consists of
5062 regstart, and regend for all registers corresponding to
5063 the subexpressions we're currently inside, plus the number of such
5064 registers, and, finally, two char *'s. The first char * is where
5065 to resume scanning the pattern; the second one is where to resume
5066 scanning the strings. */
5067 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5068 fail_stack_type fail_stack;
5069 #endif
5070 #ifdef DEBUG
5071 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5072 #endif
5074 #if defined REL_ALLOC && defined REGEX_MALLOC
5075 /* This holds the pointer to the failure stack, when
5076 it is allocated relocatably. */
5077 fail_stack_elt_t *failure_stack_ptr;
5078 #endif
5080 /* We fill all the registers internally, independent of what we
5081 return, for use in backreferences. The number here includes
5082 an element for register zero. */
5083 size_t num_regs = bufp->re_nsub + 1;
5085 /* Information on the contents of registers. These are pointers into
5086 the input strings; they record just what was matched (on this
5087 attempt) by a subexpression part of the pattern, that is, the
5088 regnum-th regstart pointer points to where in the pattern we began
5089 matching and the regnum-th regend points to right after where we
5090 stopped matching the regnum-th subexpression. (The zeroth register
5091 keeps track of what the whole pattern matches.) */
5092 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5093 re_char **regstart, **regend;
5094 #endif
5096 /* The following record the register info as found in the above
5097 variables when we find a match better than any we've seen before.
5098 This happens as we backtrack through the failure points, which in
5099 turn happens only if we have not yet matched the entire string. */
5100 unsigned best_regs_set = false;
5101 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5102 re_char **best_regstart, **best_regend;
5103 #endif
5105 /* Logically, this is `best_regend[0]'. But we don't want to have to
5106 allocate space for that if we're not allocating space for anything
5107 else (see below). Also, we never need info about register 0 for
5108 any of the other register vectors, and it seems rather a kludge to
5109 treat `best_regend' differently than the rest. So we keep track of
5110 the end of the best match so far in a separate variable. We
5111 initialize this to NULL so that when we backtrack the first time
5112 and need to test it, it's not garbage. */
5113 re_char *match_end = NULL;
5115 #ifdef DEBUG
5116 /* Counts the total number of registers pushed. */
5117 unsigned num_regs_pushed = 0;
5118 #endif
5120 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5122 INIT_FAIL_STACK ();
5124 #ifdef MATCH_MAY_ALLOCATE
5125 /* Do not bother to initialize all the register variables if there are
5126 no groups in the pattern, as it takes a fair amount of time. If
5127 there are groups, we include space for register 0 (the whole
5128 pattern), even though we never use it, since it simplifies the
5129 array indexing. We should fix this. */
5130 if (bufp->re_nsub)
5132 regstart = REGEX_TALLOC (num_regs, re_char *);
5133 regend = REGEX_TALLOC (num_regs, re_char *);
5134 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5135 best_regend = REGEX_TALLOC (num_regs, re_char *);
5137 if (!(regstart && regend && best_regstart && best_regend))
5139 FREE_VARIABLES ();
5140 return -2;
5143 else
5145 /* We must initialize all our variables to NULL, so that
5146 `FREE_VARIABLES' doesn't try to free them. */
5147 regstart = regend = best_regstart = best_regend = NULL;
5149 #endif /* MATCH_MAY_ALLOCATE */
5151 /* The starting position is bogus. */
5152 if (pos < 0 || pos > size1 + size2)
5154 FREE_VARIABLES ();
5155 return -1;
5158 /* Initialize subexpression text positions to -1 to mark ones that no
5159 start_memory/stop_memory has been seen for. Also initialize the
5160 register information struct. */
5161 for (reg = 1; reg < num_regs; reg++)
5162 regstart[reg] = regend[reg] = NULL;
5164 /* We move `string1' into `string2' if the latter's empty -- but not if
5165 `string1' is null. */
5166 if (size2 == 0 && string1 != NULL)
5168 string2 = string1;
5169 size2 = size1;
5170 string1 = 0;
5171 size1 = 0;
5173 end1 = string1 + size1;
5174 end2 = string2 + size2;
5176 /* `p' scans through the pattern as `d' scans through the data.
5177 `dend' is the end of the input string that `d' points within. `d'
5178 is advanced into the following input string whenever necessary, but
5179 this happens before fetching; therefore, at the beginning of the
5180 loop, `d' can be pointing at the end of a string, but it cannot
5181 equal `string2'. */
5182 if (pos >= size1)
5184 /* Only match within string2. */
5185 d = string2 + pos - size1;
5186 dend = end_match_2 = string2 + stop - size1;
5187 end_match_1 = end1; /* Just to give it a value. */
5189 else
5191 if (stop < size1)
5193 /* Only match within string1. */
5194 end_match_1 = string1 + stop;
5195 /* BEWARE!
5196 When we reach end_match_1, PREFETCH normally switches to string2.
5197 But in the present case, this means that just doing a PREFETCH
5198 makes us jump from `stop' to `gap' within the string.
5199 What we really want here is for the search to stop as
5200 soon as we hit end_match_1. That's why we set end_match_2
5201 to end_match_1 (since PREFETCH fails as soon as we hit
5202 end_match_2). */
5203 end_match_2 = end_match_1;
5205 else
5206 { /* It's important to use this code when stop == size so that
5207 moving `d' from end1 to string2 will not prevent the d == dend
5208 check from catching the end of string. */
5209 end_match_1 = end1;
5210 end_match_2 = string2 + stop - size1;
5212 d = string1 + pos;
5213 dend = end_match_1;
5216 DEBUG_PRINT1 ("The compiled pattern is: ");
5217 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5218 DEBUG_PRINT1 ("The string to match is: `");
5219 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5220 DEBUG_PRINT1 ("'\n");
5222 /* This loops over pattern commands. It exits by returning from the
5223 function if the match is complete, or it drops through if the match
5224 fails at this starting point in the input data. */
5225 for (;;)
5227 DEBUG_PRINT2 ("\n%p: ", p);
5229 if (p == pend)
5230 { /* End of pattern means we might have succeeded. */
5231 DEBUG_PRINT1 ("end of pattern ... ");
5233 /* If we haven't matched the entire string, and we want the
5234 longest match, try backtracking. */
5235 if (d != end_match_2)
5237 /* 1 if this match ends in the same string (string1 or string2)
5238 as the best previous match. */
5239 boolean same_str_p = (FIRST_STRING_P (match_end)
5240 == FIRST_STRING_P (d));
5241 /* 1 if this match is the best seen so far. */
5242 boolean best_match_p;
5244 /* AIX compiler got confused when this was combined
5245 with the previous declaration. */
5246 if (same_str_p)
5247 best_match_p = d > match_end;
5248 else
5249 best_match_p = !FIRST_STRING_P (d);
5251 DEBUG_PRINT1 ("backtracking.\n");
5253 if (!FAIL_STACK_EMPTY ())
5254 { /* More failure points to try. */
5256 /* If exceeds best match so far, save it. */
5257 if (!best_regs_set || best_match_p)
5259 best_regs_set = true;
5260 match_end = d;
5262 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5264 for (reg = 1; reg < num_regs; reg++)
5266 best_regstart[reg] = regstart[reg];
5267 best_regend[reg] = regend[reg];
5270 goto fail;
5273 /* If no failure points, don't restore garbage. And if
5274 last match is real best match, don't restore second
5275 best one. */
5276 else if (best_regs_set && !best_match_p)
5278 restore_best_regs:
5279 /* Restore best match. It may happen that `dend ==
5280 end_match_1' while the restored d is in string2.
5281 For example, the pattern `x.*y.*z' against the
5282 strings `x-' and `y-z-', if the two strings are
5283 not consecutive in memory. */
5284 DEBUG_PRINT1 ("Restoring best registers.\n");
5286 d = match_end;
5287 dend = ((d >= string1 && d <= end1)
5288 ? end_match_1 : end_match_2);
5290 for (reg = 1; reg < num_regs; reg++)
5292 regstart[reg] = best_regstart[reg];
5293 regend[reg] = best_regend[reg];
5296 } /* d != end_match_2 */
5298 succeed_label:
5299 DEBUG_PRINT1 ("Accepting match.\n");
5301 /* If caller wants register contents data back, do it. */
5302 if (regs && !bufp->no_sub)
5304 /* Have the register data arrays been allocated? */
5305 if (bufp->regs_allocated == REGS_UNALLOCATED)
5306 { /* No. So allocate them with malloc. We need one
5307 extra element beyond `num_regs' for the `-1' marker
5308 GNU code uses. */
5309 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5310 regs->start = TALLOC (regs->num_regs, regoff_t);
5311 regs->end = TALLOC (regs->num_regs, regoff_t);
5312 if (regs->start == NULL || regs->end == NULL)
5314 FREE_VARIABLES ();
5315 return -2;
5317 bufp->regs_allocated = REGS_REALLOCATE;
5319 else if (bufp->regs_allocated == REGS_REALLOCATE)
5320 { /* Yes. If we need more elements than were already
5321 allocated, reallocate them. If we need fewer, just
5322 leave it alone. */
5323 if (regs->num_regs < num_regs + 1)
5325 regs->num_regs = num_regs + 1;
5326 RETALLOC (regs->start, regs->num_regs, regoff_t);
5327 RETALLOC (regs->end, regs->num_regs, regoff_t);
5328 if (regs->start == NULL || regs->end == NULL)
5330 FREE_VARIABLES ();
5331 return -2;
5335 else
5337 /* These braces fend off a "empty body in an else-statement"
5338 warning under GCC when assert expands to nothing. */
5339 assert (bufp->regs_allocated == REGS_FIXED);
5342 /* Convert the pointer data in `regstart' and `regend' to
5343 indices. Register zero has to be set differently,
5344 since we haven't kept track of any info for it. */
5345 if (regs->num_regs > 0)
5347 regs->start[0] = pos;
5348 regs->end[0] = POINTER_TO_OFFSET (d);
5351 /* Go through the first `min (num_regs, regs->num_regs)'
5352 registers, since that is all we initialized. */
5353 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
5355 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5356 regs->start[reg] = regs->end[reg] = -1;
5357 else
5359 regs->start[reg]
5360 = (regoff_t) POINTER_TO_OFFSET (regstart[reg]);
5361 regs->end[reg]
5362 = (regoff_t) POINTER_TO_OFFSET (regend[reg]);
5366 /* If the regs structure we return has more elements than
5367 were in the pattern, set the extra elements to -1. If
5368 we (re)allocated the registers, this is the case,
5369 because we always allocate enough to have at least one
5370 -1 at the end. */
5371 for (reg = num_regs; reg < regs->num_regs; reg++)
5372 regs->start[reg] = regs->end[reg] = -1;
5373 } /* regs && !bufp->no_sub */
5375 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5376 nfailure_points_pushed, nfailure_points_popped,
5377 nfailure_points_pushed - nfailure_points_popped);
5378 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5380 mcnt = POINTER_TO_OFFSET (d) - pos;
5382 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5384 FREE_VARIABLES ();
5385 return mcnt;
5388 /* Otherwise match next pattern command. */
5389 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5391 /* Ignore these. Used to ignore the n of succeed_n's which
5392 currently have n == 0. */
5393 case no_op:
5394 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5395 break;
5397 case succeed:
5398 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5399 goto succeed_label;
5401 /* Match the next n pattern characters exactly. The following
5402 byte in the pattern defines n, and the n bytes after that
5403 are the characters to match. */
5404 case exactn:
5405 mcnt = *p++;
5406 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5408 /* Remember the start point to rollback upon failure. */
5409 dfail = d;
5411 #ifndef emacs
5412 /* This is written out as an if-else so we don't waste time
5413 testing `translate' inside the loop. */
5414 if (RE_TRANSLATE_P (translate))
5417 PREFETCH ();
5418 if (RE_TRANSLATE (translate, *d) != *p++)
5420 d = dfail;
5421 goto fail;
5423 d++;
5425 while (--mcnt);
5426 else
5429 PREFETCH ();
5430 if (*d++ != *p++)
5432 d = dfail;
5433 goto fail;
5436 while (--mcnt);
5437 #else /* emacs */
5438 /* The cost of testing `translate' is comparatively small. */
5439 if (target_multibyte)
5442 int pat_charlen, buf_charlen;
5443 int pat_ch, buf_ch;
5445 PREFETCH ();
5446 if (multibyte)
5447 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5448 else
5450 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5451 pat_charlen = 1;
5453 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5455 if (TRANSLATE (buf_ch) != pat_ch)
5457 d = dfail;
5458 goto fail;
5461 p += pat_charlen;
5462 d += buf_charlen;
5463 mcnt -= pat_charlen;
5465 while (mcnt > 0);
5466 else
5469 int pat_charlen, buf_charlen;
5470 int pat_ch, buf_ch;
5472 PREFETCH ();
5473 if (multibyte)
5475 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5476 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5478 else
5480 pat_ch = *p;
5481 pat_charlen = 1;
5483 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5484 if (! CHAR_BYTE8_P (buf_ch))
5486 buf_ch = TRANSLATE (buf_ch);
5487 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5488 if (buf_ch < 0)
5489 buf_ch = *d;
5491 else
5492 buf_ch = *d;
5493 if (buf_ch != pat_ch)
5495 d = dfail;
5496 goto fail;
5498 p += pat_charlen;
5499 d++;
5501 while (--mcnt);
5502 #endif
5503 break;
5506 /* Match any character except possibly a newline or a null. */
5507 case anychar:
5509 int buf_charlen;
5510 re_wchar_t buf_ch;
5512 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5514 PREFETCH ();
5515 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5516 target_multibyte);
5517 buf_ch = TRANSLATE (buf_ch);
5519 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5520 && buf_ch == '\n')
5521 || ((bufp->syntax & RE_DOT_NOT_NULL)
5522 && buf_ch == '\000'))
5523 goto fail;
5525 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
5526 d += buf_charlen;
5528 break;
5531 case charset:
5532 case charset_not:
5534 register unsigned int c;
5535 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5536 int len;
5538 /* Start of actual range_table, or end of bitmap if there is no
5539 range table. */
5540 re_char *range_table;
5542 /* Nonzero if there is a range table. */
5543 int range_table_exists;
5545 /* Number of ranges of range table. This is not included
5546 in the initial byte-length of the command. */
5547 int count = 0;
5549 /* Whether matching against a unibyte character. */
5550 boolean unibyte_char = false;
5552 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5554 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5556 if (range_table_exists)
5558 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5559 EXTRACT_NUMBER_AND_INCR (count, range_table);
5562 PREFETCH ();
5563 c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5564 if (target_multibyte)
5566 int c1;
5568 c = TRANSLATE (c);
5569 c1 = RE_CHAR_TO_UNIBYTE (c);
5570 if (c1 >= 0)
5572 unibyte_char = true;
5573 c = c1;
5576 else
5578 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5580 if (! CHAR_BYTE8_P (c1))
5582 c1 = TRANSLATE (c1);
5583 c1 = RE_CHAR_TO_UNIBYTE (c1);
5584 if (c1 >= 0)
5586 unibyte_char = true;
5587 c = c1;
5590 else
5591 unibyte_char = true;
5594 if (unibyte_char && c < (1 << BYTEWIDTH))
5595 { /* Lookup bitmap. */
5596 /* Cast to `unsigned' instead of `unsigned char' in
5597 case the bit list is a full 32 bytes long. */
5598 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5599 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5600 not = !not;
5602 #ifdef emacs
5603 else if (range_table_exists)
5605 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5607 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5608 | (class_bits & BIT_MULTIBYTE)
5609 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5610 | (class_bits & BIT_SPACE && ISSPACE (c))
5611 | (class_bits & BIT_UPPER && ISUPPER (c))
5612 | (class_bits & BIT_WORD && ISWORD (c)))
5613 not = !not;
5614 else
5615 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5617 #endif /* emacs */
5619 if (range_table_exists)
5620 p = CHARSET_RANGE_TABLE_END (range_table, count);
5621 else
5622 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5624 if (!not) goto fail;
5626 d += len;
5627 break;
5631 /* The beginning of a group is represented by start_memory.
5632 The argument is the register number. The text
5633 matched within the group is recorded (in the internal
5634 registers data structure) under the register number. */
5635 case start_memory:
5636 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5638 /* In case we need to undo this operation (via backtracking). */
5639 PUSH_FAILURE_REG ((unsigned int)*p);
5641 regstart[*p] = d;
5642 regend[*p] = NULL; /* probably unnecessary. -sm */
5643 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5645 /* Move past the register number and inner group count. */
5646 p += 1;
5647 break;
5650 /* The stop_memory opcode represents the end of a group. Its
5651 argument is the same as start_memory's: the register number. */
5652 case stop_memory:
5653 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5655 assert (!REG_UNSET (regstart[*p]));
5656 /* Strictly speaking, there should be code such as:
5658 assert (REG_UNSET (regend[*p]));
5659 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5661 But the only info to be pushed is regend[*p] and it is known to
5662 be UNSET, so there really isn't anything to push.
5663 Not pushing anything, on the other hand deprives us from the
5664 guarantee that regend[*p] is UNSET since undoing this operation
5665 will not reset its value properly. This is not important since
5666 the value will only be read on the next start_memory or at
5667 the very end and both events can only happen if this stop_memory
5668 is *not* undone. */
5670 regend[*p] = d;
5671 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5673 /* Move past the register number and the inner group count. */
5674 p += 1;
5675 break;
5678 /* \<digit> has been turned into a `duplicate' command which is
5679 followed by the numeric value of <digit> as the register number. */
5680 case duplicate:
5682 register re_char *d2, *dend2;
5683 int regno = *p++; /* Get which register to match against. */
5684 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5686 /* Can't back reference a group which we've never matched. */
5687 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5688 goto fail;
5690 /* Where in input to try to start matching. */
5691 d2 = regstart[regno];
5693 /* Remember the start point to rollback upon failure. */
5694 dfail = d;
5696 /* Where to stop matching; if both the place to start and
5697 the place to stop matching are in the same string, then
5698 set to the place to stop, otherwise, for now have to use
5699 the end of the first string. */
5701 dend2 = ((FIRST_STRING_P (regstart[regno])
5702 == FIRST_STRING_P (regend[regno]))
5703 ? regend[regno] : end_match_1);
5704 for (;;)
5706 /* If necessary, advance to next segment in register
5707 contents. */
5708 while (d2 == dend2)
5710 if (dend2 == end_match_2) break;
5711 if (dend2 == regend[regno]) break;
5713 /* End of string1 => advance to string2. */
5714 d2 = string2;
5715 dend2 = regend[regno];
5717 /* At end of register contents => success */
5718 if (d2 == dend2) break;
5720 /* If necessary, advance to next segment in data. */
5721 PREFETCH ();
5723 /* How many characters left in this segment to match. */
5724 mcnt = dend - d;
5726 /* Want how many consecutive characters we can match in
5727 one shot, so, if necessary, adjust the count. */
5728 if (mcnt > dend2 - d2)
5729 mcnt = dend2 - d2;
5731 /* Compare that many; failure if mismatch, else move
5732 past them. */
5733 if (RE_TRANSLATE_P (translate)
5734 ? bcmp_translate (d, d2, mcnt, translate, target_multibyte)
5735 : memcmp (d, d2, mcnt))
5737 d = dfail;
5738 goto fail;
5740 d += mcnt, d2 += mcnt;
5743 break;
5746 /* begline matches the empty string at the beginning of the string
5747 (unless `not_bol' is set in `bufp'), and after newlines. */
5748 case begline:
5749 DEBUG_PRINT1 ("EXECUTING begline.\n");
5751 if (AT_STRINGS_BEG (d))
5753 if (!bufp->not_bol) break;
5755 else
5757 unsigned c;
5758 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5759 if (c == '\n')
5760 break;
5762 /* In all other cases, we fail. */
5763 goto fail;
5766 /* endline is the dual of begline. */
5767 case endline:
5768 DEBUG_PRINT1 ("EXECUTING endline.\n");
5770 if (AT_STRINGS_END (d))
5772 if (!bufp->not_eol) break;
5774 else
5776 PREFETCH_NOLIMIT ();
5777 if (*d == '\n')
5778 break;
5780 goto fail;
5783 /* Match at the very beginning of the data. */
5784 case begbuf:
5785 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5786 if (AT_STRINGS_BEG (d))
5787 break;
5788 goto fail;
5791 /* Match at the very end of the data. */
5792 case endbuf:
5793 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5794 if (AT_STRINGS_END (d))
5795 break;
5796 goto fail;
5799 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5800 pushes NULL as the value for the string on the stack. Then
5801 `POP_FAILURE_POINT' will keep the current value for the
5802 string, instead of restoring it. To see why, consider
5803 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5804 then the . fails against the \n. But the next thing we want
5805 to do is match the \n against the \n; if we restored the
5806 string value, we would be back at the foo.
5808 Because this is used only in specific cases, we don't need to
5809 check all the things that `on_failure_jump' does, to make
5810 sure the right things get saved on the stack. Hence we don't
5811 share its code. The only reason to push anything on the
5812 stack at all is that otherwise we would have to change
5813 `anychar's code to do something besides goto fail in this
5814 case; that seems worse than this. */
5815 case on_failure_keep_string_jump:
5816 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5817 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5818 mcnt, p + mcnt);
5820 PUSH_FAILURE_POINT (p - 3, NULL);
5821 break;
5823 /* A nasty loop is introduced by the non-greedy *? and +?.
5824 With such loops, the stack only ever contains one failure point
5825 at a time, so that a plain on_failure_jump_loop kind of
5826 cycle detection cannot work. Worse yet, such a detection
5827 can not only fail to detect a cycle, but it can also wrongly
5828 detect a cycle (between different instantiations of the same
5829 loop).
5830 So the method used for those nasty loops is a little different:
5831 We use a special cycle-detection-stack-frame which is pushed
5832 when the on_failure_jump_nastyloop failure-point is *popped*.
5833 This special frame thus marks the beginning of one iteration
5834 through the loop and we can hence easily check right here
5835 whether something matched between the beginning and the end of
5836 the loop. */
5837 case on_failure_jump_nastyloop:
5838 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5839 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5840 mcnt, p + mcnt);
5842 assert ((re_opcode_t)p[-4] == no_op);
5844 int cycle = 0;
5845 CHECK_INFINITE_LOOP (p - 4, d);
5846 if (!cycle)
5847 /* If there's a cycle, just continue without pushing
5848 this failure point. The failure point is the "try again"
5849 option, which shouldn't be tried.
5850 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5851 PUSH_FAILURE_POINT (p - 3, d);
5853 break;
5855 /* Simple loop detecting on_failure_jump: just check on the
5856 failure stack if the same spot was already hit earlier. */
5857 case on_failure_jump_loop:
5858 on_failure:
5859 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5860 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5861 mcnt, p + mcnt);
5863 int cycle = 0;
5864 CHECK_INFINITE_LOOP (p - 3, d);
5865 if (cycle)
5866 /* If there's a cycle, get out of the loop, as if the matching
5867 had failed. We used to just `goto fail' here, but that was
5868 aborting the search a bit too early: we want to keep the
5869 empty-loop-match and keep matching after the loop.
5870 We want (x?)*y\1z to match both xxyz and xxyxz. */
5871 p += mcnt;
5872 else
5873 PUSH_FAILURE_POINT (p - 3, d);
5875 break;
5878 /* Uses of on_failure_jump:
5880 Each alternative starts with an on_failure_jump that points
5881 to the beginning of the next alternative. Each alternative
5882 except the last ends with a jump that in effect jumps past
5883 the rest of the alternatives. (They really jump to the
5884 ending jump of the following alternative, because tensioning
5885 these jumps is a hassle.)
5887 Repeats start with an on_failure_jump that points past both
5888 the repetition text and either the following jump or
5889 pop_failure_jump back to this on_failure_jump. */
5890 case on_failure_jump:
5891 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5892 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5893 mcnt, p + mcnt);
5895 PUSH_FAILURE_POINT (p -3, d);
5896 break;
5898 /* This operation is used for greedy *.
5899 Compare the beginning of the repeat with what in the
5900 pattern follows its end. If we can establish that there
5901 is nothing that they would both match, i.e., that we
5902 would have to backtrack because of (as in, e.g., `a*a')
5903 then we can use a non-backtracking loop based on
5904 on_failure_keep_string_jump instead of on_failure_jump. */
5905 case on_failure_jump_smart:
5906 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5907 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5908 mcnt, p + mcnt);
5910 re_char *p1 = p; /* Next operation. */
5911 /* Here, we discard `const', making re_match non-reentrant. */
5912 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5913 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5915 p -= 3; /* Reset so that we will re-execute the
5916 instruction once it's been changed. */
5918 EXTRACT_NUMBER (mcnt, p2 - 2);
5920 /* Ensure this is a indeed the trivial kind of loop
5921 we are expecting. */
5922 assert (skip_one_char (p1) == p2 - 3);
5923 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5924 DEBUG_STATEMENT (debug += 2);
5925 if (mutually_exclusive_p (bufp, p1, p2))
5927 /* Use a fast `on_failure_keep_string_jump' loop. */
5928 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5929 *p3 = (unsigned char) on_failure_keep_string_jump;
5930 STORE_NUMBER (p2 - 2, mcnt + 3);
5932 else
5934 /* Default to a safe `on_failure_jump' loop. */
5935 DEBUG_PRINT1 (" smart default => slow loop.\n");
5936 *p3 = (unsigned char) on_failure_jump;
5938 DEBUG_STATEMENT (debug -= 2);
5940 break;
5942 /* Unconditionally jump (without popping any failure points). */
5943 case jump:
5944 unconditional_jump:
5945 IMMEDIATE_QUIT_CHECK;
5946 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5947 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5948 p += mcnt; /* Do the jump. */
5949 DEBUG_PRINT2 ("(to %p).\n", p);
5950 break;
5953 /* Have to succeed matching what follows at least n times.
5954 After that, handle like `on_failure_jump'. */
5955 case succeed_n:
5956 /* Signedness doesn't matter since we only compare MCNT to 0. */
5957 EXTRACT_NUMBER (mcnt, p + 2);
5958 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5960 /* Originally, mcnt is how many times we HAVE to succeed. */
5961 if (mcnt != 0)
5963 /* Here, we discard `const', making re_match non-reentrant. */
5964 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5965 mcnt--;
5966 p += 4;
5967 PUSH_NUMBER (p2, mcnt);
5969 else
5970 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5971 goto on_failure;
5972 break;
5974 case jump_n:
5975 /* Signedness doesn't matter since we only compare MCNT to 0. */
5976 EXTRACT_NUMBER (mcnt, p + 2);
5977 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5979 /* Originally, this is how many times we CAN jump. */
5980 if (mcnt != 0)
5982 /* Here, we discard `const', making re_match non-reentrant. */
5983 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5984 mcnt--;
5985 PUSH_NUMBER (p2, mcnt);
5986 goto unconditional_jump;
5988 /* If don't have to jump any more, skip over the rest of command. */
5989 else
5990 p += 4;
5991 break;
5993 case set_number_at:
5995 unsigned char *p2; /* Location of the counter. */
5996 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5998 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5999 /* Here, we discard `const', making re_match non-reentrant. */
6000 p2 = (unsigned char*) p + mcnt;
6001 /* Signedness doesn't matter since we only copy MCNT's bits . */
6002 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6003 DEBUG_PRINT3 (" Setting %p to %d.\n", p2, mcnt);
6004 PUSH_NUMBER (p2, mcnt);
6005 break;
6008 case wordbound:
6009 case notwordbound:
6010 not = (re_opcode_t) *(p - 1) == notwordbound;
6011 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
6013 /* We SUCCEED (or FAIL) in one of the following cases: */
6015 /* Case 1: D is at the beginning or the end of string. */
6016 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
6017 not = !not;
6018 else
6020 /* C1 is the character before D, S1 is the syntax of C1, C2
6021 is the character at D, and S2 is the syntax of C2. */
6022 re_wchar_t c1, c2;
6023 int s1, s2;
6024 int dummy;
6025 #ifdef emacs
6026 int offset = PTR_TO_OFFSET (d - 1);
6027 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6028 UPDATE_SYNTAX_TABLE (charpos);
6029 #endif
6030 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6031 s1 = SYNTAX (c1);
6032 #ifdef emacs
6033 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6034 #endif
6035 PREFETCH_NOLIMIT ();
6036 GET_CHAR_AFTER (c2, d, dummy);
6037 s2 = SYNTAX (c2);
6039 if (/* Case 2: Only one of S1 and S2 is Sword. */
6040 ((s1 == Sword) != (s2 == Sword))
6041 /* Case 3: Both of S1 and S2 are Sword, and macro
6042 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
6043 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
6044 not = !not;
6046 if (not)
6047 break;
6048 else
6049 goto fail;
6051 case wordbeg:
6052 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
6054 /* We FAIL in one of the following cases: */
6056 /* Case 1: D is at the end of string. */
6057 if (AT_STRINGS_END (d))
6058 goto fail;
6059 else
6061 /* C1 is the character before D, S1 is the syntax of C1, C2
6062 is the character at D, and S2 is the syntax of C2. */
6063 re_wchar_t c1, c2;
6064 int s1, s2;
6065 int dummy;
6066 #ifdef emacs
6067 int offset = PTR_TO_OFFSET (d);
6068 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6069 UPDATE_SYNTAX_TABLE (charpos);
6070 #endif
6071 PREFETCH ();
6072 GET_CHAR_AFTER (c2, d, dummy);
6073 s2 = SYNTAX (c2);
6075 /* Case 2: S2 is not Sword. */
6076 if (s2 != Sword)
6077 goto fail;
6079 /* Case 3: D is not at the beginning of string ... */
6080 if (!AT_STRINGS_BEG (d))
6082 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6083 #ifdef emacs
6084 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6085 #endif
6086 s1 = SYNTAX (c1);
6088 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6089 returns 0. */
6090 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6091 goto fail;
6094 break;
6096 case wordend:
6097 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6099 /* We FAIL in one of the following cases: */
6101 /* Case 1: D is at the beginning of string. */
6102 if (AT_STRINGS_BEG (d))
6103 goto fail;
6104 else
6106 /* C1 is the character before D, S1 is the syntax of C1, C2
6107 is the character at D, and S2 is the syntax of C2. */
6108 re_wchar_t c1, c2;
6109 int s1, s2;
6110 int dummy;
6111 #ifdef emacs
6112 int offset = PTR_TO_OFFSET (d) - 1;
6113 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6114 UPDATE_SYNTAX_TABLE (charpos);
6115 #endif
6116 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6117 s1 = SYNTAX (c1);
6119 /* Case 2: S1 is not Sword. */
6120 if (s1 != Sword)
6121 goto fail;
6123 /* Case 3: D is not at the end of string ... */
6124 if (!AT_STRINGS_END (d))
6126 PREFETCH_NOLIMIT ();
6127 GET_CHAR_AFTER (c2, d, dummy);
6128 #ifdef emacs
6129 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
6130 #endif
6131 s2 = SYNTAX (c2);
6133 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6134 returns 0. */
6135 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6136 goto fail;
6139 break;
6141 case symbeg:
6142 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6144 /* We FAIL in one of the following cases: */
6146 /* Case 1: D is at the end of string. */
6147 if (AT_STRINGS_END (d))
6148 goto fail;
6149 else
6151 /* C1 is the character before D, S1 is the syntax of C1, C2
6152 is the character at D, and S2 is the syntax of C2. */
6153 re_wchar_t c1, c2;
6154 int s1, s2;
6155 #ifdef emacs
6156 int offset = PTR_TO_OFFSET (d);
6157 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6158 UPDATE_SYNTAX_TABLE (charpos);
6159 #endif
6160 PREFETCH ();
6161 c2 = RE_STRING_CHAR (d, target_multibyte);
6162 s2 = SYNTAX (c2);
6164 /* Case 2: S2 is neither Sword nor Ssymbol. */
6165 if (s2 != Sword && s2 != Ssymbol)
6166 goto fail;
6168 /* Case 3: D is not at the beginning of string ... */
6169 if (!AT_STRINGS_BEG (d))
6171 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6172 #ifdef emacs
6173 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6174 #endif
6175 s1 = SYNTAX (c1);
6177 /* ... and S1 is Sword or Ssymbol. */
6178 if (s1 == Sword || s1 == Ssymbol)
6179 goto fail;
6182 break;
6184 case symend:
6185 DEBUG_PRINT1 ("EXECUTING symend.\n");
6187 /* We FAIL in one of the following cases: */
6189 /* Case 1: D is at the beginning of string. */
6190 if (AT_STRINGS_BEG (d))
6191 goto fail;
6192 else
6194 /* C1 is the character before D, S1 is the syntax of C1, C2
6195 is the character at D, and S2 is the syntax of C2. */
6196 re_wchar_t c1, c2;
6197 int s1, s2;
6198 #ifdef emacs
6199 int offset = PTR_TO_OFFSET (d) - 1;
6200 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6201 UPDATE_SYNTAX_TABLE (charpos);
6202 #endif
6203 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6204 s1 = SYNTAX (c1);
6206 /* Case 2: S1 is neither Ssymbol nor Sword. */
6207 if (s1 != Sword && s1 != Ssymbol)
6208 goto fail;
6210 /* Case 3: D is not at the end of string ... */
6211 if (!AT_STRINGS_END (d))
6213 PREFETCH_NOLIMIT ();
6214 c2 = RE_STRING_CHAR (d, target_multibyte);
6215 #ifdef emacs
6216 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6217 #endif
6218 s2 = SYNTAX (c2);
6220 /* ... and S2 is Sword or Ssymbol. */
6221 if (s2 == Sword || s2 == Ssymbol)
6222 goto fail;
6225 break;
6227 case syntaxspec:
6228 case notsyntaxspec:
6229 not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6230 mcnt = *p++;
6231 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
6232 PREFETCH ();
6233 #ifdef emacs
6235 int offset = PTR_TO_OFFSET (d);
6236 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6237 UPDATE_SYNTAX_TABLE (pos1);
6239 #endif
6241 int len;
6242 re_wchar_t c;
6244 GET_CHAR_AFTER (c, d, len);
6245 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6246 goto fail;
6247 d += len;
6249 break;
6251 #ifdef emacs
6252 case before_dot:
6253 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6254 if (PTR_BYTE_POS (d) >= PT_BYTE)
6255 goto fail;
6256 break;
6258 case at_dot:
6259 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6260 if (PTR_BYTE_POS (d) != PT_BYTE)
6261 goto fail;
6262 break;
6264 case after_dot:
6265 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6266 if (PTR_BYTE_POS (d) <= PT_BYTE)
6267 goto fail;
6268 break;
6270 case categoryspec:
6271 case notcategoryspec:
6272 not = (re_opcode_t) *(p - 1) == notcategoryspec;
6273 mcnt = *p++;
6274 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt);
6275 PREFETCH ();
6277 int len;
6278 re_wchar_t c;
6280 GET_CHAR_AFTER (c, d, len);
6281 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6282 goto fail;
6283 d += len;
6285 break;
6287 #endif /* emacs */
6289 default:
6290 abort ();
6292 continue; /* Successfully executed one pattern command; keep going. */
6295 /* We goto here if a matching operation fails. */
6296 fail:
6297 IMMEDIATE_QUIT_CHECK;
6298 if (!FAIL_STACK_EMPTY ())
6300 re_char *str, *pat;
6301 /* A restart point is known. Restore to that state. */
6302 DEBUG_PRINT1 ("\nFAIL:\n");
6303 POP_FAILURE_POINT (str, pat);
6304 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
6306 case on_failure_keep_string_jump:
6307 assert (str == NULL);
6308 goto continue_failure_jump;
6310 case on_failure_jump_nastyloop:
6311 assert ((re_opcode_t)pat[-2] == no_op);
6312 PUSH_FAILURE_POINT (pat - 2, str);
6313 /* Fallthrough */
6315 case on_failure_jump_loop:
6316 case on_failure_jump:
6317 case succeed_n:
6318 d = str;
6319 continue_failure_jump:
6320 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6321 p = pat + mcnt;
6322 break;
6324 case no_op:
6325 /* A special frame used for nastyloops. */
6326 goto fail;
6328 default:
6329 abort();
6332 assert (p >= bufp->buffer && p <= pend);
6334 if (d >= string1 && d <= end1)
6335 dend = end_match_1;
6337 else
6338 break; /* Matching at this starting point really fails. */
6339 } /* for (;;) */
6341 if (best_regs_set)
6342 goto restore_best_regs;
6344 FREE_VARIABLES ();
6346 return -1; /* Failure to match. */
6347 } /* re_match_2 */
6349 /* Subroutine definitions for re_match_2. */
6351 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6352 bytes; nonzero otherwise. */
6354 static int
6355 bcmp_translate (const re_char *s1, const re_char *s2, register int len,
6356 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6358 register re_char *p1 = s1, *p2 = s2;
6359 re_char *p1_end = s1 + len;
6360 re_char *p2_end = s2 + len;
6362 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6363 different lengths, but relying on a single `len' would break this. -sm */
6364 while (p1 < p1_end && p2 < p2_end)
6366 int p1_charlen, p2_charlen;
6367 re_wchar_t p1_ch, p2_ch;
6369 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6370 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6372 if (RE_TRANSLATE (translate, p1_ch)
6373 != RE_TRANSLATE (translate, p2_ch))
6374 return 1;
6376 p1 += p1_charlen, p2 += p2_charlen;
6379 if (p1 != p1_end || p2 != p2_end)
6380 return 1;
6382 return 0;
6385 /* Entry points for GNU code. */
6387 /* re_compile_pattern is the GNU regular expression compiler: it
6388 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6389 Returns 0 if the pattern was valid, otherwise an error string.
6391 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6392 are set in BUFP on entry.
6394 We call regex_compile to do the actual compilation. */
6396 const char *
6397 re_compile_pattern (const char *pattern, size_t length, struct re_pattern_buffer *bufp)
6399 reg_errcode_t ret;
6401 /* GNU code is written to assume at least RE_NREGS registers will be set
6402 (and at least one extra will be -1). */
6403 bufp->regs_allocated = REGS_UNALLOCATED;
6405 /* And GNU code determines whether or not to get register information
6406 by passing null for the REGS argument to re_match, etc., not by
6407 setting no_sub. */
6408 bufp->no_sub = 0;
6410 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
6412 if (!ret)
6413 return NULL;
6414 return gettext (re_error_msgid[(int) ret]);
6416 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6418 /* Entry points compatible with 4.2 BSD regex library. We don't define
6419 them unless specifically requested. */
6421 #if defined _REGEX_RE_COMP || defined _LIBC
6423 /* BSD has one and only one pattern buffer. */
6424 static struct re_pattern_buffer re_comp_buf;
6426 char *
6427 # ifdef _LIBC
6428 /* Make these definitions weak in libc, so POSIX programs can redefine
6429 these names if they don't use our functions, and still use
6430 regcomp/regexec below without link errors. */
6431 weak_function
6432 # endif
6433 re_comp (s)
6434 const char *s;
6436 reg_errcode_t ret;
6438 if (!s)
6440 if (!re_comp_buf.buffer)
6441 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6442 return (char *) gettext ("No previous regular expression");
6443 return 0;
6446 if (!re_comp_buf.buffer)
6448 re_comp_buf.buffer = (unsigned char *) malloc (200);
6449 if (re_comp_buf.buffer == NULL)
6450 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6451 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6452 re_comp_buf.allocated = 200;
6454 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6455 if (re_comp_buf.fastmap == NULL)
6456 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6457 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6460 /* Since `re_exec' always passes NULL for the `regs' argument, we
6461 don't need to initialize the pattern buffer fields which affect it. */
6463 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6465 if (!ret)
6466 return NULL;
6468 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6469 return (char *) gettext (re_error_msgid[(int) ret]);
6474 # ifdef _LIBC
6475 weak_function
6476 # endif
6477 re_exec (s)
6478 const char *s;
6480 const int len = strlen (s);
6481 return
6482 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6484 #endif /* _REGEX_RE_COMP */
6486 /* POSIX.2 functions. Don't define these for Emacs. */
6488 #ifndef emacs
6490 /* regcomp takes a regular expression as a string and compiles it.
6492 PREG is a regex_t *. We do not expect any fields to be initialized,
6493 since POSIX says we shouldn't. Thus, we set
6495 `buffer' to the compiled pattern;
6496 `used' to the length of the compiled pattern;
6497 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6498 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6499 RE_SYNTAX_POSIX_BASIC;
6500 `fastmap' to an allocated space for the fastmap;
6501 `fastmap_accurate' to zero;
6502 `re_nsub' to the number of subexpressions in PATTERN.
6504 PATTERN is the address of the pattern string.
6506 CFLAGS is a series of bits which affect compilation.
6508 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6509 use POSIX basic syntax.
6511 If REG_NEWLINE is set, then . and [^...] don't match newline.
6512 Also, regexec will try a match beginning after every newline.
6514 If REG_ICASE is set, then we considers upper- and lowercase
6515 versions of letters to be equivalent when matching.
6517 If REG_NOSUB is set, then when PREG is passed to regexec, that
6518 routine will report only success or failure, and nothing about the
6519 registers.
6521 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6522 the return codes and their meanings.) */
6525 regcomp (regex_t *__restrict preg, const char *__restrict pattern,
6526 int cflags)
6528 reg_errcode_t ret;
6529 reg_syntax_t syntax
6530 = (cflags & REG_EXTENDED) ?
6531 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6533 /* regex_compile will allocate the space for the compiled pattern. */
6534 preg->buffer = 0;
6535 preg->allocated = 0;
6536 preg->used = 0;
6538 /* Try to allocate space for the fastmap. */
6539 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
6541 if (cflags & REG_ICASE)
6543 unsigned i;
6545 preg->translate
6546 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6547 * sizeof (*(RE_TRANSLATE_TYPE)0));
6548 if (preg->translate == NULL)
6549 return (int) REG_ESPACE;
6551 /* Map uppercase characters to corresponding lowercase ones. */
6552 for (i = 0; i < CHAR_SET_SIZE; i++)
6553 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6555 else
6556 preg->translate = NULL;
6558 /* If REG_NEWLINE is set, newlines are treated differently. */
6559 if (cflags & REG_NEWLINE)
6560 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6561 syntax &= ~RE_DOT_NEWLINE;
6562 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6564 else
6565 syntax |= RE_NO_NEWLINE_ANCHOR;
6567 preg->no_sub = !!(cflags & REG_NOSUB);
6569 /* POSIX says a null character in the pattern terminates it, so we
6570 can use strlen here in compiling the pattern. */
6571 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6573 /* POSIX doesn't distinguish between an unmatched open-group and an
6574 unmatched close-group: both are REG_EPAREN. */
6575 if (ret == REG_ERPAREN)
6576 ret = REG_EPAREN;
6578 if (ret == REG_NOERROR && preg->fastmap)
6579 { /* Compute the fastmap now, since regexec cannot modify the pattern
6580 buffer. */
6581 re_compile_fastmap (preg);
6582 if (preg->can_be_null)
6583 { /* The fastmap can't be used anyway. */
6584 free (preg->fastmap);
6585 preg->fastmap = NULL;
6588 return (int) ret;
6590 WEAK_ALIAS (__regcomp, regcomp)
6593 /* regexec searches for a given pattern, specified by PREG, in the
6594 string STRING.
6596 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6597 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6598 least NMATCH elements, and we set them to the offsets of the
6599 corresponding matched substrings.
6601 EFLAGS specifies `execution flags' which affect matching: if
6602 REG_NOTBOL is set, then ^ does not match at the beginning of the
6603 string; if REG_NOTEOL is set, then $ does not match at the end.
6605 We return 0 if we find a match and REG_NOMATCH if not. */
6608 regexec (const regex_t *__restrict preg, const char *__restrict string,
6609 size_t nmatch, regmatch_t pmatch[__restrict_arr], int eflags)
6611 int ret;
6612 struct re_registers regs;
6613 regex_t private_preg;
6614 int len = strlen (string);
6615 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6617 private_preg = *preg;
6619 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6620 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6622 /* The user has told us exactly how many registers to return
6623 information about, via `nmatch'. We have to pass that on to the
6624 matching routines. */
6625 private_preg.regs_allocated = REGS_FIXED;
6627 if (want_reg_info)
6629 regs.num_regs = nmatch;
6630 regs.start = TALLOC (nmatch * 2, regoff_t);
6631 if (regs.start == NULL)
6632 return (int) REG_NOMATCH;
6633 regs.end = regs.start + nmatch;
6636 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6637 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6638 was a little bit longer but still only matching the real part.
6639 This works because the `endline' will check for a '\n' and will find a
6640 '\0', correctly deciding that this is not the end of a line.
6641 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6642 a convenient '\0' there. For all we know, the string could be preceded
6643 by '\n' which would throw things off. */
6645 /* Perform the searching operation. */
6646 ret = re_search (&private_preg, string, len,
6647 /* start: */ 0, /* range: */ len,
6648 want_reg_info ? &regs : (struct re_registers *) 0);
6650 /* Copy the register information to the POSIX structure. */
6651 if (want_reg_info)
6653 if (ret >= 0)
6655 unsigned r;
6657 for (r = 0; r < nmatch; r++)
6659 pmatch[r].rm_so = regs.start[r];
6660 pmatch[r].rm_eo = regs.end[r];
6664 /* If we needed the temporary register info, free the space now. */
6665 free (regs.start);
6668 /* We want zero return to mean success, unlike `re_search'. */
6669 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6671 WEAK_ALIAS (__regexec, regexec)
6674 /* Returns a message corresponding to an error code, ERR_CODE, returned
6675 from either regcomp or regexec. We don't use PREG here.
6677 ERR_CODE was previously called ERRCODE, but that name causes an
6678 error with msvc8 compiler. */
6680 size_t
6681 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6683 const char *msg;
6684 size_t msg_size;
6686 if (err_code < 0
6687 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6688 /* Only error codes returned by the rest of the code should be passed
6689 to this routine. If we are given anything else, or if other regex
6690 code generates an invalid error code, then the program has a bug.
6691 Dump core so we can fix it. */
6692 abort ();
6694 msg = gettext (re_error_msgid[err_code]);
6696 msg_size = strlen (msg) + 1; /* Includes the null. */
6698 if (errbuf_size != 0)
6700 if (msg_size > errbuf_size)
6702 strncpy (errbuf, msg, errbuf_size - 1);
6703 errbuf[errbuf_size - 1] = 0;
6705 else
6706 strcpy (errbuf, msg);
6709 return msg_size;
6711 WEAK_ALIAS (__regerror, regerror)
6714 /* Free dynamically allocated space used by PREG. */
6716 void
6717 regfree (regex_t *preg)
6719 free (preg->buffer);
6720 preg->buffer = NULL;
6722 preg->allocated = 0;
6723 preg->used = 0;
6725 free (preg->fastmap);
6726 preg->fastmap = NULL;
6727 preg->fastmap_accurate = 0;
6729 free (preg->translate);
6730 preg->translate = NULL;
6732 WEAK_ALIAS (__regfree, regfree)
6734 #endif /* not emacs */