* composite.c (autocmp_chars): Don't reset point.
[emacs.git] / src / regex.c
blobd1b835621d97629fa1afac7b2328e84604668c9e
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-2011 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 USA. */
22 /* TODO:
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
26 need to modify the compiled regexp so that re_match can be reentrant.
27 - get rid of on_failure_jump_smart by doing the optimization in re_comp
28 rather than at run-time, so that re_match can be reentrant.
31 /* AIX requires this to be the first thing in the file. */
32 #if defined _AIX && !defined REGEX_MALLOC
33 #pragma alloca
34 #endif
36 #ifdef HAVE_CONFIG_H
37 # include <config.h>
38 #endif
40 #include <stddef.h>
42 #ifdef emacs
43 /* We need this for `regex.h', and perhaps for the Emacs include files. */
44 # include <sys/types.h>
45 #endif
47 /* Whether to use ISO C Amendment 1 wide char functions.
48 Those should not be used for Emacs since it uses its own. */
49 #if defined _LIBC
50 #define WIDE_CHAR_SUPPORT 1
51 #else
52 #define WIDE_CHAR_SUPPORT \
53 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
54 #endif
56 /* For platform which support the ISO C amendement 1 functionality we
57 support user defined character classes. */
58 #if WIDE_CHAR_SUPPORT
59 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
60 # include <wchar.h>
61 # include <wctype.h>
62 #endif
64 #ifdef _LIBC
65 /* We have to keep the namespace clean. */
66 # define regfree(preg) __regfree (preg)
67 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
68 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
69 # define regerror(err_code, preg, errbuf, errbuf_size) \
70 __regerror(err_code, preg, errbuf, errbuf_size)
71 # define re_set_registers(bu, re, nu, st, en) \
72 __re_set_registers (bu, re, nu, st, en)
73 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
74 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
75 # define re_match(bufp, string, size, pos, regs) \
76 __re_match (bufp, string, size, pos, regs)
77 # define re_search(bufp, string, size, startpos, range, regs) \
78 __re_search (bufp, string, size, startpos, range, regs)
79 # define re_compile_pattern(pattern, length, bufp) \
80 __re_compile_pattern (pattern, length, bufp)
81 # define re_set_syntax(syntax) __re_set_syntax (syntax)
82 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
83 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
84 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
86 /* Make sure we call libc's function even if the user overrides them. */
87 # define btowc __btowc
88 # define iswctype __iswctype
89 # define wctype __wctype
91 # define WEAK_ALIAS(a,b) weak_alias (a, b)
93 /* We are also using some library internals. */
94 # include <locale/localeinfo.h>
95 # include <locale/elem-hash.h>
96 # include <langinfo.h>
97 #else
98 # define WEAK_ALIAS(a,b)
99 #endif
101 /* This is for other GNU distributions with internationalized messages. */
102 #if HAVE_LIBINTL_H || defined _LIBC
103 # include <libintl.h>
104 #else
105 # define gettext(msgid) (msgid)
106 #endif
108 #ifndef gettext_noop
109 /* This define is so xgettext can find the internationalizable
110 strings. */
111 # define gettext_noop(String) String
112 #endif
114 /* The `emacs' switch turns on certain matching commands
115 that make sense only in Emacs. */
116 #ifdef emacs
118 # include <setjmp.h>
119 # include "lisp.h"
120 # include "buffer.h"
122 /* Make syntax table lookup grant data in gl_state. */
123 # define SYNTAX_ENTRY_VIA_PROPERTY
125 # include "syntax.h"
126 # include "character.h"
127 # include "category.h"
129 # ifdef malloc
130 # undef malloc
131 # endif
132 # define malloc xmalloc
133 # ifdef realloc
134 # undef realloc
135 # endif
136 # define realloc xrealloc
137 # ifdef free
138 # undef free
139 # endif
140 # define free xfree
142 /* Converts the pointer to the char to BEG-based offset from the start. */
143 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
144 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
146 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
147 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
148 # define RE_STRING_CHAR(p, multibyte) \
149 (multibyte ? (STRING_CHAR (p)) : (*(p)))
150 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
151 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
153 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
155 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
157 /* Set C a (possibly converted to multibyte) character before P. P
158 points into a string which is the virtual concatenation of STR1
159 (which ends at END1) or STR2 (which ends at END2). */
160 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
161 do { \
162 if (target_multibyte) \
164 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
165 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
166 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
167 c = STRING_CHAR (dtemp); \
169 else \
171 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
172 (c) = RE_CHAR_TO_MULTIBYTE (c); \
174 } while (0)
176 /* Set C a (possibly converted to multibyte) character at P, and set
177 LEN to the byte length of that character. */
178 # define GET_CHAR_AFTER(c, p, len) \
179 do { \
180 if (target_multibyte) \
181 (c) = STRING_CHAR_AND_LENGTH (p, len); \
182 else \
184 (c) = *p; \
185 len = 1; \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
188 } while (0)
190 #else /* not emacs */
192 /* If we are not linking with Emacs proper,
193 we can't use the relocating allocator
194 even if config.h says that we can. */
195 # undef REL_ALLOC
197 # include <unistd.h>
199 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
201 void *
202 xmalloc (size_t size)
204 register void *val;
205 val = (void *) malloc (size);
206 if (!val && size)
208 write (2, "virtual memory exhausted\n", 25);
209 exit (1);
211 return val;
214 void *
215 xrealloc (void *block, size_t size)
217 register void *val;
218 /* We must call malloc explicitly when BLOCK is 0, since some
219 reallocs don't do this. */
220 if (! block)
221 val = (void *) malloc (size);
222 else
223 val = (void *) realloc (block, size);
224 if (!val && size)
226 write (2, "virtual memory exhausted\n", 25);
227 exit (1);
229 return val;
232 # ifdef malloc
233 # undef malloc
234 # endif
235 # define malloc xmalloc
236 # ifdef realloc
237 # undef realloc
238 # endif
239 # define realloc xrealloc
241 # include <string.h>
243 /* Define the syntax stuff for \<, \>, etc. */
245 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
246 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
248 # define SWITCH_ENUM_CAST(x) (x)
250 /* Dummy macros for non-Emacs environments. */
251 # define CHAR_CHARSET(c) 0
252 # define CHARSET_LEADING_CODE_BASE(c) 0
253 # define MAX_MULTIBYTE_LENGTH 1
254 # define RE_MULTIBYTE_P(x) 0
255 # define RE_TARGET_MULTIBYTE_P(x) 0
256 # define WORD_BOUNDARY_P(c1, c2) (0)
257 # define CHAR_HEAD_P(p) (1)
258 # define SINGLE_BYTE_CHAR_P(c) (1)
259 # define SAME_CHARSET_P(c1, c2) (1)
260 # define BYTES_BY_CHAR_HEAD(p) (1)
261 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
262 # define STRING_CHAR(p) (*(p))
263 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
264 # define CHAR_STRING(c, s) (*(s) = (c), 1)
265 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
266 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
267 # define RE_CHAR_TO_MULTIBYTE(c) (c)
268 # define RE_CHAR_TO_UNIBYTE(c) (c)
269 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
270 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
271 # define GET_CHAR_AFTER(c, p, len) \
272 (c = *p, len = 1)
273 # define MAKE_CHAR(charset, c1, c2) (c1)
274 # define BYTE8_TO_CHAR(c) (c)
275 # define CHAR_BYTE8_P(c) (0)
276 # define CHAR_LEADING_CODE(c) (c)
278 #endif /* not emacs */
280 #ifndef RE_TRANSLATE
281 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
282 # define RE_TRANSLATE_P(TBL) (TBL)
283 #endif
285 /* Get the interface, including the syntax bits. */
286 #include "regex.h"
288 /* isalpha etc. are used for the character classes. */
289 #include <ctype.h>
291 #ifdef emacs
293 /* 1 if C is an ASCII character. */
294 # define IS_REAL_ASCII(c) ((c) < 0200)
296 /* 1 if C is a unibyte character. */
297 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
299 /* The Emacs definitions should not be directly affected by locales. */
301 /* In Emacs, these are only used for single-byte characters. */
302 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
303 # define ISCNTRL(c) ((c) < ' ')
304 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
305 || ((c) >= 'a' && (c) <= 'f') \
306 || ((c) >= 'A' && (c) <= 'F'))
308 /* This is only used for single-byte characters. */
309 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
311 /* The rest must handle multibyte characters. */
313 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
314 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
315 : 1)
317 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
318 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
319 : 1)
321 # define ISALNUM(c) (IS_REAL_ASCII (c) \
322 ? (((c) >= 'a' && (c) <= 'z') \
323 || ((c) >= 'A' && (c) <= 'Z') \
324 || ((c) >= '0' && (c) <= '9')) \
325 : SYNTAX (c) == Sword)
327 # define ISALPHA(c) (IS_REAL_ASCII (c) \
328 ? (((c) >= 'a' && (c) <= 'z') \
329 || ((c) >= 'A' && (c) <= 'Z')) \
330 : SYNTAX (c) == Sword)
332 # define ISLOWER(c) lowercasep (c)
334 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
335 ? ((c) > ' ' && (c) < 0177 \
336 && !(((c) >= 'a' && (c) <= 'z') \
337 || ((c) >= 'A' && (c) <= 'Z') \
338 || ((c) >= '0' && (c) <= '9'))) \
339 : SYNTAX (c) != Sword)
341 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
343 # define ISUPPER(c) uppercasep (c)
345 # define ISWORD(c) (SYNTAX (c) == Sword)
347 #else /* not emacs */
349 /* 1 if C is an ASCII character. */
350 # define IS_REAL_ASCII(c) ((c) < 0200)
352 /* This distinction is not meaningful, except in Emacs. */
353 # define ISUNIBYTE(c) 1
355 # ifdef isblank
356 # define ISBLANK(c) isblank (c)
357 # else
358 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
359 # endif
360 # ifdef isgraph
361 # define ISGRAPH(c) isgraph (c)
362 # else
363 # define ISGRAPH(c) (isprint (c) && !isspace (c))
364 # endif
366 /* Solaris defines ISPRINT so we must undefine it first. */
367 # undef ISPRINT
368 # define ISPRINT(c) isprint (c)
369 # define ISDIGIT(c) isdigit (c)
370 # define ISALNUM(c) isalnum (c)
371 # define ISALPHA(c) isalpha (c)
372 # define ISCNTRL(c) iscntrl (c)
373 # define ISLOWER(c) islower (c)
374 # define ISPUNCT(c) ispunct (c)
375 # define ISSPACE(c) isspace (c)
376 # define ISUPPER(c) isupper (c)
377 # define ISXDIGIT(c) isxdigit (c)
379 # define ISWORD(c) ISALPHA(c)
381 # ifdef _tolower
382 # define TOLOWER(c) _tolower(c)
383 # else
384 # define TOLOWER(c) tolower(c)
385 # endif
387 /* How many characters in the character set. */
388 # define CHAR_SET_SIZE 256
390 # ifdef SYNTAX_TABLE
392 extern char *re_syntax_table;
394 # else /* not SYNTAX_TABLE */
396 static char re_syntax_table[CHAR_SET_SIZE];
398 static void
399 init_syntax_once (void)
401 register int c;
402 static int done = 0;
404 if (done)
405 return;
407 memset (re_syntax_table, 0, sizeof re_syntax_table);
409 for (c = 0; c < CHAR_SET_SIZE; ++c)
410 if (ISALNUM (c))
411 re_syntax_table[c] = Sword;
413 re_syntax_table['_'] = Ssymbol;
415 done = 1;
418 # endif /* not SYNTAX_TABLE */
420 # define SYNTAX(c) re_syntax_table[(c)]
422 #endif /* not emacs */
424 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
425 since ours (we hope) works properly with all combinations of
426 machines, compilers, `char' and `unsigned char' argument types.
427 (Per Bothner suggested the basic approach.) */
428 #undef SIGN_EXTEND_CHAR
429 #if __STDC__
430 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
431 #else /* not __STDC__ */
432 /* As in Harbison and Steele. */
433 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
434 #endif
436 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
437 use `alloca' instead of `malloc'. This is because using malloc in
438 re_search* or re_match* could cause memory leaks when C-g is used in
439 Emacs; also, malloc is slower and causes storage fragmentation. On
440 the other hand, malloc is more portable, and easier to debug.
442 Because we sometimes use alloca, some routines have to be macros,
443 not functions -- `alloca'-allocated space disappears at the end of the
444 function it is called in. */
446 #ifdef REGEX_MALLOC
448 # define REGEX_ALLOCATE malloc
449 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
450 # define REGEX_FREE free
452 #else /* not REGEX_MALLOC */
454 /* Emacs already defines alloca, sometimes. */
455 # ifndef alloca
457 /* Make alloca work the best possible way. */
458 # ifdef __GNUC__
459 # define alloca __builtin_alloca
460 # else /* not __GNUC__ */
461 # ifdef HAVE_ALLOCA_H
462 # include <alloca.h>
463 # endif /* HAVE_ALLOCA_H */
464 # endif /* not __GNUC__ */
466 # endif /* not alloca */
468 # define REGEX_ALLOCATE alloca
470 /* Assumes a `char *destination' variable. */
471 # define REGEX_REALLOCATE(source, osize, nsize) \
472 (destination = (char *) alloca (nsize), \
473 memcpy (destination, source, osize))
475 /* No need to do anything to free, after alloca. */
476 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
478 #endif /* not REGEX_MALLOC */
480 /* Define how to allocate the failure stack. */
482 #if defined REL_ALLOC && defined REGEX_MALLOC
484 # define REGEX_ALLOCATE_STACK(size) \
485 r_alloc (&failure_stack_ptr, (size))
486 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
487 r_re_alloc (&failure_stack_ptr, (nsize))
488 # define REGEX_FREE_STACK(ptr) \
489 r_alloc_free (&failure_stack_ptr)
491 #else /* not using relocating allocator */
493 # ifdef REGEX_MALLOC
495 # define REGEX_ALLOCATE_STACK malloc
496 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
497 # define REGEX_FREE_STACK free
499 # else /* not REGEX_MALLOC */
501 # define REGEX_ALLOCATE_STACK alloca
503 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
504 REGEX_REALLOCATE (source, osize, nsize)
505 /* No need to explicitly free anything. */
506 # define REGEX_FREE_STACK(arg) ((void)0)
508 # endif /* not REGEX_MALLOC */
509 #endif /* not using relocating allocator */
512 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
513 `string1' or just past its end. This works if PTR is NULL, which is
514 a good thing. */
515 #define FIRST_STRING_P(ptr) \
516 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
518 /* (Re)Allocate N items of type T using malloc, or fail. */
519 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
520 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
521 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
523 #define BYTEWIDTH 8 /* In bits. */
525 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
527 #undef MAX
528 #undef MIN
529 #define MAX(a, b) ((a) > (b) ? (a) : (b))
530 #define MIN(a, b) ((a) < (b) ? (a) : (b))
532 /* Type of source-pattern and string chars. */
533 typedef const unsigned char re_char;
535 typedef char boolean;
536 #define false 0
537 #define true 1
539 static regoff_t re_match_2_internal _RE_ARGS ((struct re_pattern_buffer *bufp,
540 re_char *string1, size_t size1,
541 re_char *string2, size_t size2,
542 ssize_t pos,
543 struct re_registers *regs,
544 ssize_t stop));
546 /* These are the command codes that appear in compiled regular
547 expressions. Some opcodes are followed by argument bytes. A
548 command code can specify any interpretation whatsoever for its
549 arguments. Zero bytes may appear in the compiled regular expression. */
551 typedef enum
553 no_op = 0,
555 /* Succeed right away--no more backtracking. */
556 succeed,
558 /* Followed by one byte giving n, then by n literal bytes. */
559 exactn,
561 /* Matches any (more or less) character. */
562 anychar,
564 /* Matches any one char belonging to specified set. First
565 following byte is number of bitmap bytes. Then come bytes
566 for a bitmap saying which chars are in. Bits in each byte
567 are ordered low-bit-first. A character is in the set if its
568 bit is 1. A character too large to have a bit in the map is
569 automatically not in the set.
571 If the length byte has the 0x80 bit set, then that stuff
572 is followed by a range table:
573 2 bytes of flags for character sets (low 8 bits, high 8 bits)
574 See RANGE_TABLE_WORK_BITS below.
575 2 bytes, the number of pairs that follow (upto 32767)
576 pairs, each 2 multibyte characters,
577 each multibyte character represented as 3 bytes. */
578 charset,
580 /* Same parameters as charset, but match any character that is
581 not one of those specified. */
582 charset_not,
584 /* Start remembering the text that is matched, for storing in a
585 register. Followed by one byte with the register number, in
586 the range 0 to one less than the pattern buffer's re_nsub
587 field. */
588 start_memory,
590 /* Stop remembering the text that is matched and store it in a
591 memory register. Followed by one byte with the register
592 number, in the range 0 to one less than `re_nsub' in the
593 pattern buffer. */
594 stop_memory,
596 /* Match a duplicate of something remembered. Followed by one
597 byte containing the register number. */
598 duplicate,
600 /* Fail unless at beginning of line. */
601 begline,
603 /* Fail unless at end of line. */
604 endline,
606 /* Succeeds if at beginning of buffer (if emacs) or at beginning
607 of string to be matched (if not). */
608 begbuf,
610 /* Analogously, for end of buffer/string. */
611 endbuf,
613 /* Followed by two byte relative address to which to jump. */
614 jump,
616 /* Followed by two-byte relative address of place to resume at
617 in case of failure. */
618 on_failure_jump,
620 /* Like on_failure_jump, but pushes a placeholder instead of the
621 current string position when executed. */
622 on_failure_keep_string_jump,
624 /* Just like `on_failure_jump', except that it checks that we
625 don't get stuck in an infinite loop (matching an empty string
626 indefinitely). */
627 on_failure_jump_loop,
629 /* Just like `on_failure_jump_loop', except that it checks for
630 a different kind of loop (the kind that shows up with non-greedy
631 operators). This operation has to be immediately preceded
632 by a `no_op'. */
633 on_failure_jump_nastyloop,
635 /* A smart `on_failure_jump' used for greedy * and + operators.
636 It analyses the loop before which it is put and if the
637 loop does not require backtracking, it changes itself to
638 `on_failure_keep_string_jump' and short-circuits the loop,
639 else it just defaults to changing itself into `on_failure_jump'.
640 It assumes that it is pointing to just past a `jump'. */
641 on_failure_jump_smart,
643 /* Followed by two-byte relative address and two-byte number n.
644 After matching N times, jump to the address upon failure.
645 Does not work if N starts at 0: use on_failure_jump_loop
646 instead. */
647 succeed_n,
649 /* Followed by two-byte relative address, and two-byte number n.
650 Jump to the address N times, then fail. */
651 jump_n,
653 /* Set the following two-byte relative address to the
654 subsequent two-byte number. The address *includes* the two
655 bytes of number. */
656 set_number_at,
658 wordbeg, /* Succeeds if at word beginning. */
659 wordend, /* Succeeds if at word end. */
661 wordbound, /* Succeeds if at a word boundary. */
662 notwordbound, /* Succeeds if not at a word boundary. */
664 symbeg, /* Succeeds if at symbol beginning. */
665 symend, /* Succeeds if at symbol end. */
667 /* Matches any character whose syntax is specified. Followed by
668 a byte which contains a syntax code, e.g., Sword. */
669 syntaxspec,
671 /* Matches any character whose syntax is not that specified. */
672 notsyntaxspec
674 #ifdef emacs
675 ,before_dot, /* Succeeds if before point. */
676 at_dot, /* Succeeds if at point. */
677 after_dot, /* Succeeds if after point. */
679 /* Matches any character whose category-set contains the specified
680 category. The operator is followed by a byte which contains a
681 category code (mnemonic ASCII character). */
682 categoryspec,
684 /* Matches any character whose category-set does not contain the
685 specified category. The operator is followed by a byte which
686 contains the category code (mnemonic ASCII character). */
687 notcategoryspec
688 #endif /* emacs */
689 } re_opcode_t;
691 /* Common operations on the compiled pattern. */
693 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
695 #define STORE_NUMBER(destination, number) \
696 do { \
697 (destination)[0] = (number) & 0377; \
698 (destination)[1] = (number) >> 8; \
699 } while (0)
701 /* Same as STORE_NUMBER, except increment DESTINATION to
702 the byte after where the number is stored. Therefore, DESTINATION
703 must be an lvalue. */
705 #define STORE_NUMBER_AND_INCR(destination, number) \
706 do { \
707 STORE_NUMBER (destination, number); \
708 (destination) += 2; \
709 } while (0)
711 /* Put into DESTINATION a number stored in two contiguous bytes starting
712 at SOURCE. */
714 #define EXTRACT_NUMBER(destination, source) \
715 do { \
716 (destination) = *(source) & 0377; \
717 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
718 } while (0)
720 #ifdef DEBUG
721 static void extract_number _RE_ARGS ((int *dest, re_char *source));
722 static void
723 extract_number (dest, source)
724 int *dest;
725 re_char *source;
727 int temp = SIGN_EXTEND_CHAR (*(source + 1));
728 *dest = *source & 0377;
729 *dest += temp << 8;
732 # ifndef EXTRACT_MACROS /* To debug the macros. */
733 # undef EXTRACT_NUMBER
734 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
735 # endif /* not EXTRACT_MACROS */
737 #endif /* DEBUG */
739 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
740 SOURCE must be an lvalue. */
742 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
743 do { \
744 EXTRACT_NUMBER (destination, source); \
745 (source) += 2; \
746 } while (0)
748 #ifdef DEBUG
749 static void extract_number_and_incr _RE_ARGS ((int *destination,
750 re_char **source));
751 static void
752 extract_number_and_incr (destination, source)
753 int *destination;
754 re_char **source;
756 extract_number (destination, *source);
757 *source += 2;
760 # ifndef EXTRACT_MACROS
761 # undef EXTRACT_NUMBER_AND_INCR
762 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
763 extract_number_and_incr (&dest, &src)
764 # endif /* not EXTRACT_MACROS */
766 #endif /* DEBUG */
768 /* Store a multibyte character in three contiguous bytes starting
769 DESTINATION, and increment DESTINATION to the byte after where the
770 character is stored. Therefore, DESTINATION must be an lvalue. */
772 #define STORE_CHARACTER_AND_INCR(destination, character) \
773 do { \
774 (destination)[0] = (character) & 0377; \
775 (destination)[1] = ((character) >> 8) & 0377; \
776 (destination)[2] = (character) >> 16; \
777 (destination) += 3; \
778 } while (0)
780 /* Put into DESTINATION a character stored in three contiguous bytes
781 starting at SOURCE. */
783 #define EXTRACT_CHARACTER(destination, source) \
784 do { \
785 (destination) = ((source)[0] \
786 | ((source)[1] << 8) \
787 | ((source)[2] << 16)); \
788 } while (0)
791 /* Macros for charset. */
793 /* Size of bitmap of charset P in bytes. P is a start of charset,
794 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
795 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
797 /* Nonzero if charset P has range table. */
798 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
800 /* Return the address of range table of charset P. But not the start
801 of table itself, but the before where the number of ranges is
802 stored. `2 +' means to skip re_opcode_t and size of bitmap,
803 and the 2 bytes of flags at the start of the range table. */
804 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
806 /* Extract the bit flags that start a range table. */
807 #define CHARSET_RANGE_TABLE_BITS(p) \
808 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
809 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
811 /* Return the address of end of RANGE_TABLE. COUNT is number of
812 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
813 is start of range and end of range. `* 3' is size of each start
814 and end. */
815 #define CHARSET_RANGE_TABLE_END(range_table, count) \
816 ((range_table) + (count) * 2 * 3)
818 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
819 COUNT is number of ranges in RANGE_TABLE. */
820 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
821 do \
823 re_wchar_t range_start, range_end; \
824 re_char *rtp; \
825 re_char *range_table_end \
826 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
828 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
830 EXTRACT_CHARACTER (range_start, rtp); \
831 EXTRACT_CHARACTER (range_end, rtp + 3); \
833 if (range_start <= (c) && (c) <= range_end) \
835 (not) = !(not); \
836 break; \
840 while (0)
842 /* Test if C is in range table of CHARSET. The flag NOT is negated if
843 C is listed in it. */
844 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
845 do \
847 /* Number of ranges in range table. */ \
848 int count; \
849 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
851 EXTRACT_NUMBER_AND_INCR (count, range_table); \
852 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
854 while (0)
856 /* If DEBUG is defined, Regex prints many voluminous messages about what
857 it is doing (if the variable `debug' is nonzero). If linked with the
858 main program in `iregex.c', you can enter patterns and strings
859 interactively. And if linked with the main program in `main.c' and
860 the other test files, you can run the already-written tests. */
862 #ifdef DEBUG
864 /* We use standard I/O for debugging. */
865 # include <stdio.h>
867 /* It is useful to test things that ``must'' be true when debugging. */
868 # include <assert.h>
870 static int debug = -100000;
872 # define DEBUG_STATEMENT(e) e
873 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
874 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
875 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
876 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
877 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
878 if (debug > 0) print_partial_compiled_pattern (s, e)
879 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
880 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
883 /* Print the fastmap in human-readable form. */
885 void
886 print_fastmap (fastmap)
887 char *fastmap;
889 unsigned was_a_range = 0;
890 unsigned i = 0;
892 while (i < (1 << BYTEWIDTH))
894 if (fastmap[i++])
896 was_a_range = 0;
897 putchar (i - 1);
898 while (i < (1 << BYTEWIDTH) && fastmap[i])
900 was_a_range = 1;
901 i++;
903 if (was_a_range)
905 printf ("-");
906 putchar (i - 1);
910 putchar ('\n');
914 /* Print a compiled pattern string in human-readable form, starting at
915 the START pointer into it and ending just before the pointer END. */
917 void
918 print_partial_compiled_pattern (start, end)
919 re_char *start;
920 re_char *end;
922 int mcnt, mcnt2;
923 re_char *p = start;
924 re_char *pend = end;
926 if (start == NULL)
928 fprintf (stderr, "(null)\n");
929 return;
932 /* Loop over pattern commands. */
933 while (p < pend)
935 fprintf (stderr, "%d:\t", p - start);
937 switch ((re_opcode_t) *p++)
939 case no_op:
940 fprintf (stderr, "/no_op");
941 break;
943 case succeed:
944 fprintf (stderr, "/succeed");
945 break;
947 case exactn:
948 mcnt = *p++;
949 fprintf (stderr, "/exactn/%d", mcnt);
952 fprintf (stderr, "/%c", *p++);
954 while (--mcnt);
955 break;
957 case start_memory:
958 fprintf (stderr, "/start_memory/%d", *p++);
959 break;
961 case stop_memory:
962 fprintf (stderr, "/stop_memory/%d", *p++);
963 break;
965 case duplicate:
966 fprintf (stderr, "/duplicate/%d", *p++);
967 break;
969 case anychar:
970 fprintf (stderr, "/anychar");
971 break;
973 case charset:
974 case charset_not:
976 register int c, last = -100;
977 register int in_range = 0;
978 int length = CHARSET_BITMAP_SIZE (p - 1);
979 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
981 fprintf (stderr, "/charset [%s",
982 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
984 if (p + *p >= pend)
985 fprintf (stderr, " !extends past end of pattern! ");
987 for (c = 0; c < 256; c++)
988 if (c / 8 < length
989 && (p[1 + (c/8)] & (1 << (c % 8))))
991 /* Are we starting a range? */
992 if (last + 1 == c && ! in_range)
994 fprintf (stderr, "-");
995 in_range = 1;
997 /* Have we broken a range? */
998 else if (last + 1 != c && in_range)
1000 fprintf (stderr, "%c", last);
1001 in_range = 0;
1004 if (! in_range)
1005 fprintf (stderr, "%c", c);
1007 last = c;
1010 if (in_range)
1011 fprintf (stderr, "%c", last);
1013 fprintf (stderr, "]");
1015 p += 1 + length;
1017 if (has_range_table)
1019 int count;
1020 fprintf (stderr, "has-range-table");
1022 /* ??? Should print the range table; for now, just skip it. */
1023 p += 2; /* skip range table bits */
1024 EXTRACT_NUMBER_AND_INCR (count, p);
1025 p = CHARSET_RANGE_TABLE_END (p, count);
1028 break;
1030 case begline:
1031 fprintf (stderr, "/begline");
1032 break;
1034 case endline:
1035 fprintf (stderr, "/endline");
1036 break;
1038 case on_failure_jump:
1039 extract_number_and_incr (&mcnt, &p);
1040 fprintf (stderr, "/on_failure_jump to %d", p + mcnt - start);
1041 break;
1043 case on_failure_keep_string_jump:
1044 extract_number_and_incr (&mcnt, &p);
1045 fprintf (stderr, "/on_failure_keep_string_jump to %d", p + mcnt - start);
1046 break;
1048 case on_failure_jump_nastyloop:
1049 extract_number_and_incr (&mcnt, &p);
1050 fprintf (stderr, "/on_failure_jump_nastyloop to %d", p + mcnt - start);
1051 break;
1053 case on_failure_jump_loop:
1054 extract_number_and_incr (&mcnt, &p);
1055 fprintf (stderr, "/on_failure_jump_loop to %d", p + mcnt - start);
1056 break;
1058 case on_failure_jump_smart:
1059 extract_number_and_incr (&mcnt, &p);
1060 fprintf (stderr, "/on_failure_jump_smart to %d", p + mcnt - start);
1061 break;
1063 case jump:
1064 extract_number_and_incr (&mcnt, &p);
1065 fprintf (stderr, "/jump to %d", p + mcnt - start);
1066 break;
1068 case succeed_n:
1069 extract_number_and_incr (&mcnt, &p);
1070 extract_number_and_incr (&mcnt2, &p);
1071 fprintf (stderr, "/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1072 break;
1074 case jump_n:
1075 extract_number_and_incr (&mcnt, &p);
1076 extract_number_and_incr (&mcnt2, &p);
1077 fprintf (stderr, "/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1078 break;
1080 case set_number_at:
1081 extract_number_and_incr (&mcnt, &p);
1082 extract_number_and_incr (&mcnt2, &p);
1083 fprintf (stderr, "/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1084 break;
1086 case wordbound:
1087 fprintf (stderr, "/wordbound");
1088 break;
1090 case notwordbound:
1091 fprintf (stderr, "/notwordbound");
1092 break;
1094 case wordbeg:
1095 fprintf (stderr, "/wordbeg");
1096 break;
1098 case wordend:
1099 fprintf (stderr, "/wordend");
1100 break;
1102 case symbeg:
1103 fprintf (stderr, "/symbeg");
1104 break;
1106 case symend:
1107 fprintf (stderr, "/symend");
1108 break;
1110 case syntaxspec:
1111 fprintf (stderr, "/syntaxspec");
1112 mcnt = *p++;
1113 fprintf (stderr, "/%d", mcnt);
1114 break;
1116 case notsyntaxspec:
1117 fprintf (stderr, "/notsyntaxspec");
1118 mcnt = *p++;
1119 fprintf (stderr, "/%d", mcnt);
1120 break;
1122 # ifdef emacs
1123 case before_dot:
1124 fprintf (stderr, "/before_dot");
1125 break;
1127 case at_dot:
1128 fprintf (stderr, "/at_dot");
1129 break;
1131 case after_dot:
1132 fprintf (stderr, "/after_dot");
1133 break;
1135 case categoryspec:
1136 fprintf (stderr, "/categoryspec");
1137 mcnt = *p++;
1138 fprintf (stderr, "/%d", mcnt);
1139 break;
1141 case notcategoryspec:
1142 fprintf (stderr, "/notcategoryspec");
1143 mcnt = *p++;
1144 fprintf (stderr, "/%d", mcnt);
1145 break;
1146 # endif /* emacs */
1148 case begbuf:
1149 fprintf (stderr, "/begbuf");
1150 break;
1152 case endbuf:
1153 fprintf (stderr, "/endbuf");
1154 break;
1156 default:
1157 fprintf (stderr, "?%d", *(p-1));
1160 fprintf (stderr, "\n");
1163 fprintf (stderr, "%d:\tend of pattern.\n", p - start);
1167 void
1168 print_compiled_pattern (bufp)
1169 struct re_pattern_buffer *bufp;
1171 re_char *buffer = bufp->buffer;
1173 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1174 printf ("%ld bytes used/%ld bytes allocated.\n",
1175 bufp->used, bufp->allocated);
1177 if (bufp->fastmap_accurate && bufp->fastmap)
1179 printf ("fastmap: ");
1180 print_fastmap (bufp->fastmap);
1183 printf ("re_nsub: %d\t", bufp->re_nsub);
1184 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1185 printf ("can_be_null: %d\t", bufp->can_be_null);
1186 printf ("no_sub: %d\t", bufp->no_sub);
1187 printf ("not_bol: %d\t", bufp->not_bol);
1188 printf ("not_eol: %d\t", bufp->not_eol);
1189 printf ("syntax: %lx\n", bufp->syntax);
1190 fflush (stdout);
1191 /* Perhaps we should print the translate table? */
1195 void
1196 print_double_string (where, string1, size1, string2, size2)
1197 re_char *where;
1198 re_char *string1;
1199 re_char *string2;
1200 ssize_t size1;
1201 ssize_t size2;
1203 ssize_t this_char;
1205 if (where == NULL)
1206 printf ("(null)");
1207 else
1209 if (FIRST_STRING_P (where))
1211 for (this_char = where - string1; this_char < size1; this_char++)
1212 putchar (string1[this_char]);
1214 where = string2;
1217 for (this_char = where - string2; this_char < size2; this_char++)
1218 putchar (string2[this_char]);
1222 #else /* not DEBUG */
1224 # undef assert
1225 # define assert(e)
1227 # define DEBUG_STATEMENT(e)
1228 # define DEBUG_PRINT1(x)
1229 # define DEBUG_PRINT2(x1, x2)
1230 # define DEBUG_PRINT3(x1, x2, x3)
1231 # define DEBUG_PRINT4(x1, x2, x3, x4)
1232 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1233 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1235 #endif /* not DEBUG */
1237 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1238 #ifdef lint
1239 # define IF_LINT(Code) Code
1240 #else
1241 # define IF_LINT(Code) /* empty */
1242 #endif
1244 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1245 also be assigned to arbitrarily: each pattern buffer stores its own
1246 syntax, so it can be changed between regex compilations. */
1247 /* This has no initializer because initialized variables in Emacs
1248 become read-only after dumping. */
1249 reg_syntax_t re_syntax_options;
1252 /* Specify the precise syntax of regexps for compilation. This provides
1253 for compatibility for various utilities which historically have
1254 different, incompatible syntaxes.
1256 The argument SYNTAX is a bit mask comprised of the various bits
1257 defined in regex.h. We return the old syntax. */
1259 reg_syntax_t
1260 re_set_syntax (reg_syntax_t syntax)
1262 reg_syntax_t ret = re_syntax_options;
1264 re_syntax_options = syntax;
1265 return ret;
1267 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1269 /* Regexp to use to replace spaces, or NULL meaning don't. */
1270 static re_char *whitespace_regexp;
1272 void
1273 re_set_whitespace_regexp (const char *regexp)
1275 whitespace_regexp = (re_char *) regexp;
1277 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1279 /* This table gives an error message for each of the error codes listed
1280 in regex.h. Obviously the order here has to be same as there.
1281 POSIX doesn't require that we do anything for REG_NOERROR,
1282 but why not be nice? */
1284 static const char *re_error_msgid[] =
1286 gettext_noop ("Success"), /* REG_NOERROR */
1287 gettext_noop ("No match"), /* REG_NOMATCH */
1288 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1289 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1290 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1291 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1292 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1293 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1294 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1295 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1296 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1297 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1298 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1299 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1300 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1301 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1302 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1303 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1306 /* Avoiding alloca during matching, to placate r_alloc. */
1308 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1309 searching and matching functions should not call alloca. On some
1310 systems, alloca is implemented in terms of malloc, and if we're
1311 using the relocating allocator routines, then malloc could cause a
1312 relocation, which might (if the strings being searched are in the
1313 ralloc heap) shift the data out from underneath the regexp
1314 routines.
1316 Here's another reason to avoid allocation: Emacs
1317 processes input from X in a signal handler; processing X input may
1318 call malloc; if input arrives while a matching routine is calling
1319 malloc, then we're scrod. But Emacs can't just block input while
1320 calling matching routines; then we don't notice interrupts when
1321 they come in. So, Emacs blocks input around all regexp calls
1322 except the matching calls, which it leaves unprotected, in the
1323 faith that they will not malloc. */
1325 /* Normally, this is fine. */
1326 #define MATCH_MAY_ALLOCATE
1328 /* The match routines may not allocate if (1) they would do it with malloc
1329 and (2) it's not safe for them to use malloc.
1330 Note that if REL_ALLOC is defined, matching would not use malloc for the
1331 failure stack, but we would still use it for the register vectors;
1332 so REL_ALLOC should not affect this. */
1333 #if defined REGEX_MALLOC && defined emacs
1334 # undef MATCH_MAY_ALLOCATE
1335 #endif
1338 /* Failure stack declarations and macros; both re_compile_fastmap and
1339 re_match_2 use a failure stack. These have to be macros because of
1340 REGEX_ALLOCATE_STACK. */
1343 /* Approximate number of failure points for which to initially allocate space
1344 when matching. If this number is exceeded, we allocate more
1345 space, so it is not a hard limit. */
1346 #ifndef INIT_FAILURE_ALLOC
1347 # define INIT_FAILURE_ALLOC 20
1348 #endif
1350 /* Roughly the maximum number of failure points on the stack. Would be
1351 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1352 This is a variable only so users of regex can assign to it; we never
1353 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1354 before using it, so it should probably be a byte-count instead. */
1355 # if defined MATCH_MAY_ALLOCATE
1356 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1357 whose default stack limit is 2mb. In order for a larger
1358 value to work reliably, you have to try to make it accord
1359 with the process stack limit. */
1360 size_t re_max_failures = 40000;
1361 # else
1362 size_t re_max_failures = 4000;
1363 # endif
1365 union fail_stack_elt
1367 re_char *pointer;
1368 /* This should be the biggest `int' that's no bigger than a pointer. */
1369 long integer;
1372 typedef union fail_stack_elt fail_stack_elt_t;
1374 typedef struct
1376 fail_stack_elt_t *stack;
1377 size_t size;
1378 size_t avail; /* Offset of next open position. */
1379 size_t frame; /* Offset of the cur constructed frame. */
1380 } fail_stack_type;
1382 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1385 /* Define macros to initialize and free the failure stack.
1386 Do `return -2' if the alloc fails. */
1388 #ifdef MATCH_MAY_ALLOCATE
1389 # define INIT_FAIL_STACK() \
1390 do { \
1391 fail_stack.stack = (fail_stack_elt_t *) \
1392 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1393 * sizeof (fail_stack_elt_t)); \
1395 if (fail_stack.stack == NULL) \
1396 return -2; \
1398 fail_stack.size = INIT_FAILURE_ALLOC; \
1399 fail_stack.avail = 0; \
1400 fail_stack.frame = 0; \
1401 } while (0)
1402 #else
1403 # define INIT_FAIL_STACK() \
1404 do { \
1405 fail_stack.avail = 0; \
1406 fail_stack.frame = 0; \
1407 } while (0)
1409 # define RETALLOC_IF(addr, n, t) \
1410 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1411 #endif
1414 /* Double the size of FAIL_STACK, up to a limit
1415 which allows approximately `re_max_failures' items.
1417 Return 1 if succeeds, and 0 if either ran out of memory
1418 allocating space for it or it was already too large.
1420 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1422 /* Factor to increase the failure stack size by
1423 when we increase it.
1424 This used to be 2, but 2 was too wasteful
1425 because the old discarded stacks added up to as much space
1426 were as ultimate, maximum-size stack. */
1427 #define FAIL_STACK_GROWTH_FACTOR 4
1429 #define GROW_FAIL_STACK(fail_stack) \
1430 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1431 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1432 ? 0 \
1433 : ((fail_stack).stack \
1434 = (fail_stack_elt_t *) \
1435 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1436 (fail_stack).size * sizeof (fail_stack_elt_t), \
1437 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1438 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1439 * FAIL_STACK_GROWTH_FACTOR))), \
1441 (fail_stack).stack == NULL \
1442 ? 0 \
1443 : ((fail_stack).size \
1444 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1445 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1446 * FAIL_STACK_GROWTH_FACTOR)) \
1447 / sizeof (fail_stack_elt_t)), \
1448 1)))
1451 /* Push a pointer value onto the failure stack.
1452 Assumes the variable `fail_stack'. Probably should only
1453 be called from within `PUSH_FAILURE_POINT'. */
1454 #define PUSH_FAILURE_POINTER(item) \
1455 fail_stack.stack[fail_stack.avail++].pointer = (item)
1457 /* This pushes an integer-valued item onto the failure stack.
1458 Assumes the variable `fail_stack'. Probably should only
1459 be called from within `PUSH_FAILURE_POINT'. */
1460 #define PUSH_FAILURE_INT(item) \
1461 fail_stack.stack[fail_stack.avail++].integer = (item)
1463 /* These POP... operations complement the PUSH... operations.
1464 All assume that `fail_stack' is nonempty. */
1465 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1466 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1468 /* Individual items aside from the registers. */
1469 #define NUM_NONREG_ITEMS 3
1471 /* Used to examine the stack (to detect infinite loops). */
1472 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1473 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1474 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1475 #define TOP_FAILURE_HANDLE() fail_stack.frame
1478 #define ENSURE_FAIL_STACK(space) \
1479 while (REMAINING_AVAIL_SLOTS <= space) { \
1480 if (!GROW_FAIL_STACK (fail_stack)) \
1481 return -2; \
1482 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1483 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1486 /* Push register NUM onto the stack. */
1487 #define PUSH_FAILURE_REG(num) \
1488 do { \
1489 char *destination; \
1490 ENSURE_FAIL_STACK(3); \
1491 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1492 num, regstart[num], regend[num]); \
1493 PUSH_FAILURE_POINTER (regstart[num]); \
1494 PUSH_FAILURE_POINTER (regend[num]); \
1495 PUSH_FAILURE_INT (num); \
1496 } while (0)
1498 /* Change the counter's value to VAL, but make sure that it will
1499 be reset when backtracking. */
1500 #define PUSH_NUMBER(ptr,val) \
1501 do { \
1502 char *destination; \
1503 int c; \
1504 ENSURE_FAIL_STACK(3); \
1505 EXTRACT_NUMBER (c, ptr); \
1506 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1507 PUSH_FAILURE_INT (c); \
1508 PUSH_FAILURE_POINTER (ptr); \
1509 PUSH_FAILURE_INT (-1); \
1510 STORE_NUMBER (ptr, val); \
1511 } while (0)
1513 /* Pop a saved register off the stack. */
1514 #define POP_FAILURE_REG_OR_COUNT() \
1515 do { \
1516 long pfreg = POP_FAILURE_INT (); \
1517 if (pfreg == -1) \
1519 /* It's a counter. */ \
1520 /* Here, we discard `const', making re_match non-reentrant. */ \
1521 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1522 pfreg = POP_FAILURE_INT (); \
1523 STORE_NUMBER (ptr, pfreg); \
1524 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, pfreg); \
1526 else \
1528 regend[pfreg] = POP_FAILURE_POINTER (); \
1529 regstart[pfreg] = POP_FAILURE_POINTER (); \
1530 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1531 pfreg, regstart[pfreg], regend[pfreg]); \
1533 } while (0)
1535 /* Check that we are not stuck in an infinite loop. */
1536 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1537 do { \
1538 ssize_t failure = TOP_FAILURE_HANDLE (); \
1539 /* Check for infinite matching loops */ \
1540 while (failure > 0 \
1541 && (FAILURE_STR (failure) == string_place \
1542 || FAILURE_STR (failure) == NULL)) \
1544 assert (FAILURE_PAT (failure) >= bufp->buffer \
1545 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1546 if (FAILURE_PAT (failure) == pat_cur) \
1548 cycle = 1; \
1549 break; \
1551 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1552 failure = NEXT_FAILURE_HANDLE(failure); \
1554 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1555 } while (0)
1557 /* Push the information about the state we will need
1558 if we ever fail back to it.
1560 Requires variables fail_stack, regstart, regend and
1561 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1562 declared.
1564 Does `return FAILURE_CODE' if runs out of memory. */
1566 #define PUSH_FAILURE_POINT(pattern, string_place) \
1567 do { \
1568 char *destination; \
1569 /* Must be int, so when we don't save any registers, the arithmetic \
1570 of 0 + -1 isn't done as unsigned. */ \
1572 DEBUG_STATEMENT (nfailure_points_pushed++); \
1573 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1574 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1575 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1577 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1579 DEBUG_PRINT1 ("\n"); \
1581 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1582 PUSH_FAILURE_INT (fail_stack.frame); \
1584 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1585 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1586 DEBUG_PRINT1 ("'\n"); \
1587 PUSH_FAILURE_POINTER (string_place); \
1589 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1590 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1591 PUSH_FAILURE_POINTER (pattern); \
1593 /* Close the frame by moving the frame pointer past it. */ \
1594 fail_stack.frame = fail_stack.avail; \
1595 } while (0)
1597 /* Estimate the size of data pushed by a typical failure stack entry.
1598 An estimate is all we need, because all we use this for
1599 is to choose a limit for how big to make the failure stack. */
1600 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1601 #define TYPICAL_FAILURE_SIZE 20
1603 /* How many items can still be added to the stack without overflowing it. */
1604 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1607 /* Pops what PUSH_FAIL_STACK pushes.
1609 We restore into the parameters, all of which should be lvalues:
1610 STR -- the saved data position.
1611 PAT -- the saved pattern position.
1612 REGSTART, REGEND -- arrays of string positions.
1614 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1615 `pend', `string1', `size1', `string2', and `size2'. */
1617 #define POP_FAILURE_POINT(str, pat) \
1618 do { \
1619 assert (!FAIL_STACK_EMPTY ()); \
1621 /* Remove failure points and point to how many regs pushed. */ \
1622 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1623 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1624 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1626 /* Pop the saved registers. */ \
1627 while (fail_stack.frame < fail_stack.avail) \
1628 POP_FAILURE_REG_OR_COUNT (); \
1630 pat = POP_FAILURE_POINTER (); \
1631 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1632 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1634 /* If the saved string location is NULL, it came from an \
1635 on_failure_keep_string_jump opcode, and we want to throw away the \
1636 saved NULL, thus retaining our current position in the string. */ \
1637 str = POP_FAILURE_POINTER (); \
1638 DEBUG_PRINT2 (" Popping string %p: `", str); \
1639 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1640 DEBUG_PRINT1 ("'\n"); \
1642 fail_stack.frame = POP_FAILURE_INT (); \
1643 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1645 assert (fail_stack.avail >= 0); \
1646 assert (fail_stack.frame <= fail_stack.avail); \
1648 DEBUG_STATEMENT (nfailure_points_popped++); \
1649 } while (0) /* POP_FAILURE_POINT */
1653 /* Registers are set to a sentinel when they haven't yet matched. */
1654 #define REG_UNSET(e) ((e) == NULL)
1656 /* Subroutine declarations and macros for regex_compile. */
1658 static reg_errcode_t regex_compile _RE_ARGS ((re_char *pattern, size_t size,
1659 reg_syntax_t syntax,
1660 struct re_pattern_buffer *bufp));
1661 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1662 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1663 int arg1, int arg2));
1664 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1665 int arg, unsigned char *end));
1666 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1667 int arg1, int arg2, unsigned char *end));
1668 static boolean at_begline_loc_p _RE_ARGS ((re_char *pattern,
1669 re_char *p,
1670 reg_syntax_t syntax));
1671 static boolean at_endline_loc_p _RE_ARGS ((re_char *p,
1672 re_char *pend,
1673 reg_syntax_t syntax));
1674 static re_char *skip_one_char _RE_ARGS ((re_char *p));
1675 static int analyse_first _RE_ARGS ((re_char *p, re_char *pend,
1676 char *fastmap, const int multibyte));
1678 /* Fetch the next character in the uncompiled pattern, with no
1679 translation. */
1680 #define PATFETCH(c) \
1681 do { \
1682 int len; \
1683 if (p == pend) return REG_EEND; \
1684 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1685 p += len; \
1686 } while (0)
1689 /* If `translate' is non-null, return translate[D], else just D. We
1690 cast the subscript to translate because some data is declared as
1691 `char *', to avoid warnings when a string constant is passed. But
1692 when we use a character as a subscript we must make it unsigned. */
1693 #ifndef TRANSLATE
1694 # define TRANSLATE(d) \
1695 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1696 #endif
1699 /* Macros for outputting the compiled pattern into `buffer'. */
1701 /* If the buffer isn't allocated when it comes in, use this. */
1702 #define INIT_BUF_SIZE 32
1704 /* Make sure we have at least N more bytes of space in buffer. */
1705 #define GET_BUFFER_SPACE(n) \
1706 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1707 EXTEND_BUFFER ()
1709 /* Make sure we have one more byte of buffer space and then add C to it. */
1710 #define BUF_PUSH(c) \
1711 do { \
1712 GET_BUFFER_SPACE (1); \
1713 *b++ = (unsigned char) (c); \
1714 } while (0)
1717 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1718 #define BUF_PUSH_2(c1, c2) \
1719 do { \
1720 GET_BUFFER_SPACE (2); \
1721 *b++ = (unsigned char) (c1); \
1722 *b++ = (unsigned char) (c2); \
1723 } while (0)
1726 /* Store a jump with opcode OP at LOC to location TO. We store a
1727 relative address offset by the three bytes the jump itself occupies. */
1728 #define STORE_JUMP(op, loc, to) \
1729 store_op1 (op, loc, (to) - (loc) - 3)
1731 /* Likewise, for a two-argument jump. */
1732 #define STORE_JUMP2(op, loc, to, arg) \
1733 store_op2 (op, loc, (to) - (loc) - 3, arg)
1735 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1736 #define INSERT_JUMP(op, loc, to) \
1737 insert_op1 (op, loc, (to) - (loc) - 3, b)
1739 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1740 #define INSERT_JUMP2(op, loc, to, arg) \
1741 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1744 /* This is not an arbitrary limit: the arguments which represent offsets
1745 into the pattern are two bytes long. So if 2^15 bytes turns out to
1746 be too small, many things would have to change. */
1747 # define MAX_BUF_SIZE (1L << 15)
1749 #if 0 /* This is when we thought it could be 2^16 bytes. */
1750 /* Any other compiler which, like MSC, has allocation limit below 2^16
1751 bytes will have to use approach similar to what was done below for
1752 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1753 reallocating to 0 bytes. Such thing is not going to work too well.
1754 You have been warned!! */
1755 #if defined _MSC_VER && !defined WIN32
1756 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1757 # define MAX_BUF_SIZE 65500L
1758 #else
1759 # define MAX_BUF_SIZE (1L << 16)
1760 #endif
1761 #endif /* 0 */
1763 /* Extend the buffer by twice its current size via realloc and
1764 reset the pointers that pointed into the old block to point to the
1765 correct places in the new one. If extending the buffer results in it
1766 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1767 #if __BOUNDED_POINTERS__
1768 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1769 # define MOVE_BUFFER_POINTER(P) \
1770 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1771 SET_HIGH_BOUND (P), \
1772 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1773 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1774 else \
1776 SET_HIGH_BOUND (b); \
1777 SET_HIGH_BOUND (begalt); \
1778 if (fixup_alt_jump) \
1779 SET_HIGH_BOUND (fixup_alt_jump); \
1780 if (laststart) \
1781 SET_HIGH_BOUND (laststart); \
1782 if (pending_exact) \
1783 SET_HIGH_BOUND (pending_exact); \
1785 #else
1786 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1787 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1788 #endif
1789 #define EXTEND_BUFFER() \
1790 do { \
1791 unsigned char *old_buffer = bufp->buffer; \
1792 if (bufp->allocated == MAX_BUF_SIZE) \
1793 return REG_ESIZE; \
1794 bufp->allocated <<= 1; \
1795 if (bufp->allocated > MAX_BUF_SIZE) \
1796 bufp->allocated = MAX_BUF_SIZE; \
1797 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1798 if (bufp->buffer == NULL) \
1799 return REG_ESPACE; \
1800 /* If the buffer moved, move all the pointers into it. */ \
1801 if (old_buffer != bufp->buffer) \
1803 unsigned char *new_buffer = bufp->buffer; \
1804 MOVE_BUFFER_POINTER (b); \
1805 MOVE_BUFFER_POINTER (begalt); \
1806 if (fixup_alt_jump) \
1807 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1808 if (laststart) \
1809 MOVE_BUFFER_POINTER (laststart); \
1810 if (pending_exact) \
1811 MOVE_BUFFER_POINTER (pending_exact); \
1813 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1814 } while (0)
1817 /* Since we have one byte reserved for the register number argument to
1818 {start,stop}_memory, the maximum number of groups we can report
1819 things about is what fits in that byte. */
1820 #define MAX_REGNUM 255
1822 /* But patterns can have more than `MAX_REGNUM' registers. We just
1823 ignore the excess. */
1824 typedef int regnum_t;
1827 /* Macros for the compile stack. */
1829 /* Since offsets can go either forwards or backwards, this type needs to
1830 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1831 /* int may be not enough when sizeof(int) == 2. */
1832 typedef long pattern_offset_t;
1834 typedef struct
1836 pattern_offset_t begalt_offset;
1837 pattern_offset_t fixup_alt_jump;
1838 pattern_offset_t laststart_offset;
1839 regnum_t regnum;
1840 } compile_stack_elt_t;
1843 typedef struct
1845 compile_stack_elt_t *stack;
1846 size_t size;
1847 size_t avail; /* Offset of next open position. */
1848 } compile_stack_type;
1851 #define INIT_COMPILE_STACK_SIZE 32
1853 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1854 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1856 /* The next available element. */
1857 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1859 /* Explicit quit checking is only used on NTemacs and whenever we
1860 use polling to process input events. */
1861 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1862 extern int immediate_quit;
1863 # define IMMEDIATE_QUIT_CHECK \
1864 do { \
1865 if (immediate_quit) QUIT; \
1866 } while (0)
1867 #else
1868 # define IMMEDIATE_QUIT_CHECK ((void)0)
1869 #endif
1871 /* Structure to manage work area for range table. */
1872 struct range_table_work_area
1874 int *table; /* actual work area. */
1875 int allocated; /* allocated size for work area in bytes. */
1876 int used; /* actually used size in words. */
1877 int bits; /* flag to record character classes */
1880 /* Make sure that WORK_AREA can hold more N multibyte characters.
1881 This is used only in set_image_of_range and set_image_of_range_1.
1882 It expects WORK_AREA to be a pointer.
1883 If it can't get the space, it returns from the surrounding function. */
1885 #define EXTEND_RANGE_TABLE(work_area, n) \
1886 do { \
1887 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1889 extend_range_table_work_area (&work_area); \
1890 if ((work_area).table == 0) \
1891 return (REG_ESPACE); \
1893 } while (0)
1895 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1896 (work_area).bits |= (bit)
1898 /* Bits used to implement the multibyte-part of the various character classes
1899 such as [:alnum:] in a charset's range table. */
1900 #define BIT_WORD 0x1
1901 #define BIT_LOWER 0x2
1902 #define BIT_PUNCT 0x4
1903 #define BIT_SPACE 0x8
1904 #define BIT_UPPER 0x10
1905 #define BIT_MULTIBYTE 0x20
1907 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1908 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1909 do { \
1910 EXTEND_RANGE_TABLE ((work_area), 2); \
1911 (work_area).table[(work_area).used++] = (range_start); \
1912 (work_area).table[(work_area).used++] = (range_end); \
1913 } while (0)
1915 /* Free allocated memory for WORK_AREA. */
1916 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1917 do { \
1918 if ((work_area).table) \
1919 free ((work_area).table); \
1920 } while (0)
1922 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1923 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1924 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1925 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1928 /* Set the bit for character C in a list. */
1929 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1932 #ifdef emacs
1934 /* Store characters in the range FROM to TO in the bitmap at B (for
1935 ASCII and unibyte characters) and WORK_AREA (for multibyte
1936 characters) while translating them and paying attention to the
1937 continuity of translated characters.
1939 Implementation note: It is better to implement these fairly big
1940 macros by a function, but it's not that easy because macros called
1941 in this macro assume various local variables already declared. */
1943 /* Both FROM and TO are ASCII characters. */
1945 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1946 do { \
1947 int C0, C1; \
1949 for (C0 = (FROM); C0 <= (TO); C0++) \
1951 C1 = TRANSLATE (C0); \
1952 if (! ASCII_CHAR_P (C1)) \
1954 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1955 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1956 C1 = C0; \
1958 SET_LIST_BIT (C1); \
1960 } while (0)
1963 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1965 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1966 do { \
1967 int C0, C1, C2, I; \
1968 int USED = RANGE_TABLE_WORK_USED (work_area); \
1970 for (C0 = (FROM); C0 <= (TO); C0++) \
1972 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1973 if (CHAR_BYTE8_P (C1)) \
1974 SET_LIST_BIT (C0); \
1975 else \
1977 C2 = TRANSLATE (C1); \
1978 if (C2 == C1 \
1979 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1980 C1 = C0; \
1981 SET_LIST_BIT (C1); \
1982 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1984 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1985 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1987 if (C2 >= from - 1 && C2 <= to + 1) \
1989 if (C2 == from - 1) \
1990 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1991 else if (C2 == to + 1) \
1992 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1993 break; \
1996 if (I < USED) \
1997 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
2000 } while (0)
2003 /* Both FROM and TO are multibyte characters. */
2005 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2006 do { \
2007 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2009 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2010 for (C0 = (FROM); C0 <= (TO); C0++) \
2012 C1 = TRANSLATE (C0); \
2013 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2014 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2015 SET_LIST_BIT (C2); \
2016 if (C1 >= (FROM) && C1 <= (TO)) \
2017 continue; \
2018 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2020 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2021 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2023 if (C1 >= from - 1 && C1 <= to + 1) \
2025 if (C1 == from - 1) \
2026 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2027 else if (C1 == to + 1) \
2028 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2029 break; \
2032 if (I < USED) \
2033 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2035 } while (0)
2037 #endif /* emacs */
2039 /* Get the next unsigned number in the uncompiled pattern. */
2040 #define GET_UNSIGNED_NUMBER(num) \
2041 do { \
2042 if (p == pend) \
2043 FREE_STACK_RETURN (REG_EBRACE); \
2044 else \
2046 PATFETCH (c); \
2047 while ('0' <= c && c <= '9') \
2049 int prev; \
2050 if (num < 0) \
2051 num = 0; \
2052 prev = num; \
2053 num = num * 10 + c - '0'; \
2054 if (num / 10 != prev) \
2055 FREE_STACK_RETURN (REG_BADBR); \
2056 if (p == pend) \
2057 FREE_STACK_RETURN (REG_EBRACE); \
2058 PATFETCH (c); \
2061 } while (0)
2063 #if ! WIDE_CHAR_SUPPORT
2065 /* Map a string to the char class it names (if any). */
2066 re_wctype_t
2067 re_wctype (const re_char *str)
2069 const char *string = (const char *) str;
2070 if (STREQ (string, "alnum")) return RECC_ALNUM;
2071 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2072 else if (STREQ (string, "word")) return RECC_WORD;
2073 else if (STREQ (string, "ascii")) return RECC_ASCII;
2074 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2075 else if (STREQ (string, "graph")) return RECC_GRAPH;
2076 else if (STREQ (string, "lower")) return RECC_LOWER;
2077 else if (STREQ (string, "print")) return RECC_PRINT;
2078 else if (STREQ (string, "punct")) return RECC_PUNCT;
2079 else if (STREQ (string, "space")) return RECC_SPACE;
2080 else if (STREQ (string, "upper")) return RECC_UPPER;
2081 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2082 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2083 else if (STREQ (string, "digit")) return RECC_DIGIT;
2084 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2085 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2086 else if (STREQ (string, "blank")) return RECC_BLANK;
2087 else return 0;
2090 /* True if CH is in the char class CC. */
2091 boolean
2092 re_iswctype (int ch, re_wctype_t cc)
2094 switch (cc)
2096 case RECC_ALNUM: return ISALNUM (ch) != 0;
2097 case RECC_ALPHA: return ISALPHA (ch) != 0;
2098 case RECC_BLANK: return ISBLANK (ch) != 0;
2099 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2100 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2101 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2102 case RECC_LOWER: return ISLOWER (ch) != 0;
2103 case RECC_PRINT: return ISPRINT (ch) != 0;
2104 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2105 case RECC_SPACE: return ISSPACE (ch) != 0;
2106 case RECC_UPPER: return ISUPPER (ch) != 0;
2107 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2108 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2109 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2110 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2111 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2112 case RECC_WORD: return ISWORD (ch) != 0;
2113 case RECC_ERROR: return false;
2114 default:
2115 abort();
2119 /* Return a bit-pattern to use in the range-table bits to match multibyte
2120 chars of class CC. */
2121 static int
2122 re_wctype_to_bit (re_wctype_t cc)
2124 switch (cc)
2126 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2127 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2128 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2129 case RECC_LOWER: return BIT_LOWER;
2130 case RECC_UPPER: return BIT_UPPER;
2131 case RECC_PUNCT: return BIT_PUNCT;
2132 case RECC_SPACE: return BIT_SPACE;
2133 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2134 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2135 default:
2136 abort();
2139 #endif
2141 /* Filling in the work area of a range. */
2143 /* Actually extend the space in WORK_AREA. */
2145 static void
2146 extend_range_table_work_area (struct range_table_work_area *work_area)
2148 work_area->allocated += 16 * sizeof (int);
2149 if (work_area->table)
2150 work_area->table
2151 = (int *) realloc (work_area->table, work_area->allocated);
2152 else
2153 work_area->table
2154 = (int *) malloc (work_area->allocated);
2157 #if 0
2158 #ifdef emacs
2160 /* Carefully find the ranges of codes that are equivalent
2161 under case conversion to the range start..end when passed through
2162 TRANSLATE. Handle the case where non-letters can come in between
2163 two upper-case letters (which happens in Latin-1).
2164 Also handle the case of groups of more than 2 case-equivalent chars.
2166 The basic method is to look at consecutive characters and see
2167 if they can form a run that can be handled as one.
2169 Returns -1 if successful, REG_ESPACE if ran out of space. */
2171 static int
2172 set_image_of_range_1 (struct range_table_work_area *work_area,
2173 re_wchar_t start, re_wchar_t end,
2174 RE_TRANSLATE_TYPE translate)
2176 /* `one_case' indicates a character, or a run of characters,
2177 each of which is an isolate (no case-equivalents).
2178 This includes all ASCII non-letters.
2180 `two_case' indicates a character, or a run of characters,
2181 each of which has two case-equivalent forms.
2182 This includes all ASCII letters.
2184 `strange' indicates a character that has more than one
2185 case-equivalent. */
2187 enum case_type {one_case, two_case, strange};
2189 /* Describe the run that is in progress,
2190 which the next character can try to extend.
2191 If run_type is strange, that means there really is no run.
2192 If run_type is one_case, then run_start...run_end is the run.
2193 If run_type is two_case, then the run is run_start...run_end,
2194 and the case-equivalents end at run_eqv_end. */
2196 enum case_type run_type = strange;
2197 int run_start, run_end, run_eqv_end;
2199 Lisp_Object eqv_table;
2201 if (!RE_TRANSLATE_P (translate))
2203 EXTEND_RANGE_TABLE (work_area, 2);
2204 work_area->table[work_area->used++] = (start);
2205 work_area->table[work_area->used++] = (end);
2206 return -1;
2209 eqv_table = XCHAR_TABLE (translate)->extras[2];
2211 for (; start <= end; start++)
2213 enum case_type this_type;
2214 int eqv = RE_TRANSLATE (eqv_table, start);
2215 int minchar, maxchar;
2217 /* Classify this character */
2218 if (eqv == start)
2219 this_type = one_case;
2220 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2221 this_type = two_case;
2222 else
2223 this_type = strange;
2225 if (start < eqv)
2226 minchar = start, maxchar = eqv;
2227 else
2228 minchar = eqv, maxchar = start;
2230 /* Can this character extend the run in progress? */
2231 if (this_type == strange || this_type != run_type
2232 || !(minchar == run_end + 1
2233 && (run_type == two_case
2234 ? maxchar == run_eqv_end + 1 : 1)))
2236 /* No, end the run.
2237 Record each of its equivalent ranges. */
2238 if (run_type == one_case)
2240 EXTEND_RANGE_TABLE (work_area, 2);
2241 work_area->table[work_area->used++] = run_start;
2242 work_area->table[work_area->used++] = run_end;
2244 else if (run_type == two_case)
2246 EXTEND_RANGE_TABLE (work_area, 4);
2247 work_area->table[work_area->used++] = run_start;
2248 work_area->table[work_area->used++] = run_end;
2249 work_area->table[work_area->used++]
2250 = RE_TRANSLATE (eqv_table, run_start);
2251 work_area->table[work_area->used++]
2252 = RE_TRANSLATE (eqv_table, run_end);
2254 run_type = strange;
2257 if (this_type == strange)
2259 /* For a strange character, add each of its equivalents, one
2260 by one. Don't start a range. */
2263 EXTEND_RANGE_TABLE (work_area, 2);
2264 work_area->table[work_area->used++] = eqv;
2265 work_area->table[work_area->used++] = eqv;
2266 eqv = RE_TRANSLATE (eqv_table, eqv);
2268 while (eqv != start);
2271 /* Add this char to the run, or start a new run. */
2272 else if (run_type == strange)
2274 /* Initialize a new range. */
2275 run_type = this_type;
2276 run_start = start;
2277 run_end = start;
2278 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2280 else
2282 /* Extend a running range. */
2283 run_end = minchar;
2284 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2288 /* If a run is still in progress at the end, finish it now
2289 by recording its equivalent ranges. */
2290 if (run_type == one_case)
2292 EXTEND_RANGE_TABLE (work_area, 2);
2293 work_area->table[work_area->used++] = run_start;
2294 work_area->table[work_area->used++] = run_end;
2296 else if (run_type == two_case)
2298 EXTEND_RANGE_TABLE (work_area, 4);
2299 work_area->table[work_area->used++] = run_start;
2300 work_area->table[work_area->used++] = run_end;
2301 work_area->table[work_area->used++]
2302 = RE_TRANSLATE (eqv_table, run_start);
2303 work_area->table[work_area->used++]
2304 = RE_TRANSLATE (eqv_table, run_end);
2307 return -1;
2310 #endif /* emacs */
2312 /* Record the image of the range start..end when passed through
2313 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2314 and is not even necessarily contiguous.
2315 Normally we approximate it with the smallest contiguous range that contains
2316 all the chars we need. However, for Latin-1 we go to extra effort
2317 to do a better job.
2319 This function is not called for ASCII ranges.
2321 Returns -1 if successful, REG_ESPACE if ran out of space. */
2323 static int
2324 set_image_of_range (struct range_table_work_area *work_area,
2325 re_wchar_t start, re_wchar_t end,
2326 RE_TRANSLATE_TYPE translate)
2328 re_wchar_t cmin, cmax;
2330 #ifdef emacs
2331 /* For Latin-1 ranges, use set_image_of_range_1
2332 to get proper handling of ranges that include letters and nonletters.
2333 For a range that includes the whole of Latin-1, this is not necessary.
2334 For other character sets, we don't bother to get this right. */
2335 if (RE_TRANSLATE_P (translate) && start < 04400
2336 && !(start < 04200 && end >= 04377))
2338 int newend;
2339 int tem;
2340 newend = end;
2341 if (newend > 04377)
2342 newend = 04377;
2343 tem = set_image_of_range_1 (work_area, start, newend, translate);
2344 if (tem > 0)
2345 return tem;
2347 start = 04400;
2348 if (end < 04400)
2349 return -1;
2351 #endif
2353 EXTEND_RANGE_TABLE (work_area, 2);
2354 work_area->table[work_area->used++] = (start);
2355 work_area->table[work_area->used++] = (end);
2357 cmin = -1, cmax = -1;
2359 if (RE_TRANSLATE_P (translate))
2361 int ch;
2363 for (ch = start; ch <= end; ch++)
2365 re_wchar_t c = TRANSLATE (ch);
2366 if (! (start <= c && c <= end))
2368 if (cmin == -1)
2369 cmin = c, cmax = c;
2370 else
2372 cmin = MIN (cmin, c);
2373 cmax = MAX (cmax, c);
2378 if (cmin != -1)
2380 EXTEND_RANGE_TABLE (work_area, 2);
2381 work_area->table[work_area->used++] = (cmin);
2382 work_area->table[work_area->used++] = (cmax);
2386 return -1;
2388 #endif /* 0 */
2390 #ifndef MATCH_MAY_ALLOCATE
2392 /* If we cannot allocate large objects within re_match_2_internal,
2393 we make the fail stack and register vectors global.
2394 The fail stack, we grow to the maximum size when a regexp
2395 is compiled.
2396 The register vectors, we adjust in size each time we
2397 compile a regexp, according to the number of registers it needs. */
2399 static fail_stack_type fail_stack;
2401 /* Size with which the following vectors are currently allocated.
2402 That is so we can make them bigger as needed,
2403 but never make them smaller. */
2404 static int regs_allocated_size;
2406 static re_char ** regstart, ** regend;
2407 static re_char **best_regstart, **best_regend;
2409 /* Make the register vectors big enough for NUM_REGS registers,
2410 but don't make them smaller. */
2412 static
2413 regex_grow_registers (int num_regs)
2415 if (num_regs > regs_allocated_size)
2417 RETALLOC_IF (regstart, num_regs, re_char *);
2418 RETALLOC_IF (regend, num_regs, re_char *);
2419 RETALLOC_IF (best_regstart, num_regs, re_char *);
2420 RETALLOC_IF (best_regend, num_regs, re_char *);
2422 regs_allocated_size = num_regs;
2426 #endif /* not MATCH_MAY_ALLOCATE */
2428 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2429 compile_stack,
2430 regnum_t regnum));
2432 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2433 Returns one of error codes defined in `regex.h', or zero for success.
2435 Assumes the `allocated' (and perhaps `buffer') and `translate'
2436 fields are set in BUFP on entry.
2438 If it succeeds, results are put in BUFP (if it returns an error, the
2439 contents of BUFP are undefined):
2440 `buffer' is the compiled pattern;
2441 `syntax' is set to SYNTAX;
2442 `used' is set to the length of the compiled pattern;
2443 `fastmap_accurate' is zero;
2444 `re_nsub' is the number of subexpressions in PATTERN;
2445 `not_bol' and `not_eol' are zero;
2447 The `fastmap' field is neither examined nor set. */
2449 /* Insert the `jump' from the end of last alternative to "here".
2450 The space for the jump has already been allocated. */
2451 #define FIXUP_ALT_JUMP() \
2452 do { \
2453 if (fixup_alt_jump) \
2454 STORE_JUMP (jump, fixup_alt_jump, b); \
2455 } while (0)
2458 /* Return, freeing storage we allocated. */
2459 #define FREE_STACK_RETURN(value) \
2460 do { \
2461 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2462 free (compile_stack.stack); \
2463 return value; \
2464 } while (0)
2466 static reg_errcode_t
2467 regex_compile (const re_char *pattern, size_t size, reg_syntax_t syntax, struct re_pattern_buffer *bufp)
2469 /* We fetch characters from PATTERN here. */
2470 register re_wchar_t c, c1;
2472 /* Points to the end of the buffer, where we should append. */
2473 register unsigned char *b;
2475 /* Keeps track of unclosed groups. */
2476 compile_stack_type compile_stack;
2478 /* Points to the current (ending) position in the pattern. */
2479 #ifdef AIX
2480 /* `const' makes AIX compiler fail. */
2481 unsigned char *p = pattern;
2482 #else
2483 re_char *p = pattern;
2484 #endif
2485 re_char *pend = pattern + size;
2487 /* How to translate the characters in the pattern. */
2488 RE_TRANSLATE_TYPE translate = bufp->translate;
2490 /* Address of the count-byte of the most recently inserted `exactn'
2491 command. This makes it possible to tell if a new exact-match
2492 character can be added to that command or if the character requires
2493 a new `exactn' command. */
2494 unsigned char *pending_exact = 0;
2496 /* Address of start of the most recently finished expression.
2497 This tells, e.g., postfix * where to find the start of its
2498 operand. Reset at the beginning of groups and alternatives. */
2499 unsigned char *laststart = 0;
2501 /* Address of beginning of regexp, or inside of last group. */
2502 unsigned char *begalt;
2504 /* Place in the uncompiled pattern (i.e., the {) to
2505 which to go back if the interval is invalid. */
2506 re_char *beg_interval;
2508 /* Address of the place where a forward jump should go to the end of
2509 the containing expression. Each alternative of an `or' -- except the
2510 last -- ends with a forward jump of this sort. */
2511 unsigned char *fixup_alt_jump = 0;
2513 /* Work area for range table of charset. */
2514 struct range_table_work_area range_table_work;
2516 /* If the object matched can contain multibyte characters. */
2517 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2519 /* Nonzero if we have pushed down into a subpattern. */
2520 int in_subpattern = 0;
2522 /* These hold the values of p, pattern, and pend from the main
2523 pattern when we have pushed into a subpattern. */
2524 re_char *main_p IF_LINT (= NULL);
2525 re_char *main_pattern IF_LINT (= NULL);
2526 re_char *main_pend IF_LINT (= NULL);
2528 #ifdef DEBUG
2529 debug++;
2530 DEBUG_PRINT1 ("\nCompiling pattern: ");
2531 if (debug > 0)
2533 unsigned debug_count;
2535 for (debug_count = 0; debug_count < size; debug_count++)
2536 putchar (pattern[debug_count]);
2537 putchar ('\n');
2539 #endif /* DEBUG */
2541 /* Initialize the compile stack. */
2542 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2543 if (compile_stack.stack == NULL)
2544 return REG_ESPACE;
2546 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2547 compile_stack.avail = 0;
2549 range_table_work.table = 0;
2550 range_table_work.allocated = 0;
2552 /* Initialize the pattern buffer. */
2553 bufp->syntax = syntax;
2554 bufp->fastmap_accurate = 0;
2555 bufp->not_bol = bufp->not_eol = 0;
2556 bufp->used_syntax = 0;
2558 /* Set `used' to zero, so that if we return an error, the pattern
2559 printer (for debugging) will think there's no pattern. We reset it
2560 at the end. */
2561 bufp->used = 0;
2563 /* Always count groups, whether or not bufp->no_sub is set. */
2564 bufp->re_nsub = 0;
2566 #if !defined emacs && !defined SYNTAX_TABLE
2567 /* Initialize the syntax table. */
2568 init_syntax_once ();
2569 #endif
2571 if (bufp->allocated == 0)
2573 if (bufp->buffer)
2574 { /* If zero allocated, but buffer is non-null, try to realloc
2575 enough space. This loses if buffer's address is bogus, but
2576 that is the user's responsibility. */
2577 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2579 else
2580 { /* Caller did not allocate a buffer. Do it for them. */
2581 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2583 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2585 bufp->allocated = INIT_BUF_SIZE;
2588 begalt = b = bufp->buffer;
2590 /* Loop through the uncompiled pattern until we're at the end. */
2591 while (1)
2593 if (p == pend)
2595 /* If this is the end of an included regexp,
2596 pop back to the main regexp and try again. */
2597 if (in_subpattern)
2599 in_subpattern = 0;
2600 pattern = main_pattern;
2601 p = main_p;
2602 pend = main_pend;
2603 continue;
2605 /* If this is the end of the main regexp, we are done. */
2606 break;
2609 PATFETCH (c);
2611 switch (c)
2613 case ' ':
2615 re_char *p1 = p;
2617 /* If there's no special whitespace regexp, treat
2618 spaces normally. And don't try to do this recursively. */
2619 if (!whitespace_regexp || in_subpattern)
2620 goto normal_char;
2622 /* Peek past following spaces. */
2623 while (p1 != pend)
2625 if (*p1 != ' ')
2626 break;
2627 p1++;
2629 /* If the spaces are followed by a repetition op,
2630 treat them normally. */
2631 if (p1 != pend
2632 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2633 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2634 goto normal_char;
2636 /* Replace the spaces with the whitespace regexp. */
2637 in_subpattern = 1;
2638 main_p = p1;
2639 main_pend = pend;
2640 main_pattern = pattern;
2641 p = pattern = whitespace_regexp;
2642 pend = p + strlen ((const char *) p);
2643 break;
2646 case '^':
2648 if ( /* If at start of pattern, it's an operator. */
2649 p == pattern + 1
2650 /* If context independent, it's an operator. */
2651 || syntax & RE_CONTEXT_INDEP_ANCHORS
2652 /* Otherwise, depends on what's come before. */
2653 || at_begline_loc_p (pattern, p, syntax))
2654 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2655 else
2656 goto normal_char;
2658 break;
2661 case '$':
2663 if ( /* If at end of pattern, it's an operator. */
2664 p == pend
2665 /* If context independent, it's an operator. */
2666 || syntax & RE_CONTEXT_INDEP_ANCHORS
2667 /* Otherwise, depends on what's next. */
2668 || at_endline_loc_p (p, pend, syntax))
2669 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2670 else
2671 goto normal_char;
2673 break;
2676 case '+':
2677 case '?':
2678 if ((syntax & RE_BK_PLUS_QM)
2679 || (syntax & RE_LIMITED_OPS))
2680 goto normal_char;
2681 handle_plus:
2682 case '*':
2683 /* If there is no previous pattern... */
2684 if (!laststart)
2686 if (syntax & RE_CONTEXT_INVALID_OPS)
2687 FREE_STACK_RETURN (REG_BADRPT);
2688 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2689 goto normal_char;
2693 /* 1 means zero (many) matches is allowed. */
2694 boolean zero_times_ok = 0, many_times_ok = 0;
2695 boolean greedy = 1;
2697 /* If there is a sequence of repetition chars, collapse it
2698 down to just one (the right one). We can't combine
2699 interval operators with these because of, e.g., `a{2}*',
2700 which should only match an even number of `a's. */
2702 for (;;)
2704 if ((syntax & RE_FRUGAL)
2705 && c == '?' && (zero_times_ok || many_times_ok))
2706 greedy = 0;
2707 else
2709 zero_times_ok |= c != '+';
2710 many_times_ok |= c != '?';
2713 if (p == pend)
2714 break;
2715 else if (*p == '*'
2716 || (!(syntax & RE_BK_PLUS_QM)
2717 && (*p == '+' || *p == '?')))
2719 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2721 if (p+1 == pend)
2722 FREE_STACK_RETURN (REG_EESCAPE);
2723 if (p[1] == '+' || p[1] == '?')
2724 PATFETCH (c); /* Gobble up the backslash. */
2725 else
2726 break;
2728 else
2729 break;
2730 /* If we get here, we found another repeat character. */
2731 PATFETCH (c);
2734 /* Star, etc. applied to an empty pattern is equivalent
2735 to an empty pattern. */
2736 if (!laststart || laststart == b)
2737 break;
2739 /* Now we know whether or not zero matches is allowed
2740 and also whether or not two or more matches is allowed. */
2741 if (greedy)
2743 if (many_times_ok)
2745 boolean simple = skip_one_char (laststart) == b;
2746 size_t startoffset = 0;
2747 re_opcode_t ofj =
2748 /* Check if the loop can match the empty string. */
2749 (simple || !analyse_first (laststart, b, NULL, 0))
2750 ? on_failure_jump : on_failure_jump_loop;
2751 assert (skip_one_char (laststart) <= b);
2753 if (!zero_times_ok && simple)
2754 { /* Since simple * loops can be made faster by using
2755 on_failure_keep_string_jump, we turn simple P+
2756 into PP* if P is simple. */
2757 unsigned char *p1, *p2;
2758 startoffset = b - laststart;
2759 GET_BUFFER_SPACE (startoffset);
2760 p1 = b; p2 = laststart;
2761 while (p2 < p1)
2762 *b++ = *p2++;
2763 zero_times_ok = 1;
2766 GET_BUFFER_SPACE (6);
2767 if (!zero_times_ok)
2768 /* A + loop. */
2769 STORE_JUMP (ofj, b, b + 6);
2770 else
2771 /* Simple * loops can use on_failure_keep_string_jump
2772 depending on what follows. But since we don't know
2773 that yet, we leave the decision up to
2774 on_failure_jump_smart. */
2775 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2776 laststart + startoffset, b + 6);
2777 b += 3;
2778 STORE_JUMP (jump, b, laststart + startoffset);
2779 b += 3;
2781 else
2783 /* A simple ? pattern. */
2784 assert (zero_times_ok);
2785 GET_BUFFER_SPACE (3);
2786 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2787 b += 3;
2790 else /* not greedy */
2791 { /* I wish the greedy and non-greedy cases could be merged. */
2793 GET_BUFFER_SPACE (7); /* We might use less. */
2794 if (many_times_ok)
2796 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2798 /* The non-greedy multiple match looks like
2799 a repeat..until: we only need a conditional jump
2800 at the end of the loop. */
2801 if (emptyp) BUF_PUSH (no_op);
2802 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2803 : on_failure_jump, b, laststart);
2804 b += 3;
2805 if (zero_times_ok)
2807 /* The repeat...until naturally matches one or more.
2808 To also match zero times, we need to first jump to
2809 the end of the loop (its conditional jump). */
2810 INSERT_JUMP (jump, laststart, b);
2811 b += 3;
2814 else
2816 /* non-greedy a?? */
2817 INSERT_JUMP (jump, laststart, b + 3);
2818 b += 3;
2819 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2820 b += 3;
2824 pending_exact = 0;
2825 break;
2828 case '.':
2829 laststart = b;
2830 BUF_PUSH (anychar);
2831 break;
2834 case '[':
2836 re_char *p1;
2838 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2840 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2842 /* Ensure that we have enough space to push a charset: the
2843 opcode, the length count, and the bitset; 34 bytes in all. */
2844 GET_BUFFER_SPACE (34);
2846 laststart = b;
2848 /* We test `*p == '^' twice, instead of using an if
2849 statement, so we only need one BUF_PUSH. */
2850 BUF_PUSH (*p == '^' ? charset_not : charset);
2851 if (*p == '^')
2852 p++;
2854 /* Remember the first position in the bracket expression. */
2855 p1 = p;
2857 /* Push the number of bytes in the bitmap. */
2858 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2860 /* Clear the whole map. */
2861 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2863 /* charset_not matches newline according to a syntax bit. */
2864 if ((re_opcode_t) b[-2] == charset_not
2865 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2866 SET_LIST_BIT ('\n');
2868 /* Read in characters and ranges, setting map bits. */
2869 for (;;)
2871 boolean escaped_char = false;
2872 const unsigned char *p2 = p;
2873 re_wchar_t ch;
2875 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2877 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2878 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2879 So the translation is done later in a loop. Example:
2880 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2881 PATFETCH (c);
2883 /* \ might escape characters inside [...] and [^...]. */
2884 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2886 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2888 PATFETCH (c);
2889 escaped_char = true;
2891 else
2893 /* Could be the end of the bracket expression. If it's
2894 not (i.e., when the bracket expression is `[]' so
2895 far), the ']' character bit gets set way below. */
2896 if (c == ']' && p2 != p1)
2897 break;
2900 /* See if we're at the beginning of a possible character
2901 class. */
2903 if (!escaped_char &&
2904 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2906 /* Leave room for the null. */
2907 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2908 const unsigned char *class_beg;
2910 PATFETCH (c);
2911 c1 = 0;
2912 class_beg = p;
2914 /* If pattern is `[[:'. */
2915 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2917 for (;;)
2919 PATFETCH (c);
2920 if ((c == ':' && *p == ']') || p == pend)
2921 break;
2922 if (c1 < CHAR_CLASS_MAX_LENGTH)
2923 str[c1++] = c;
2924 else
2925 /* This is in any case an invalid class name. */
2926 str[0] = '\0';
2928 str[c1] = '\0';
2930 /* If isn't a word bracketed by `[:' and `:]':
2931 undo the ending character, the letters, and
2932 leave the leading `:' and `[' (but set bits for
2933 them). */
2934 if (c == ':' && *p == ']')
2936 re_wctype_t cc = re_wctype (str);
2938 if (cc == 0)
2939 FREE_STACK_RETURN (REG_ECTYPE);
2941 /* Throw away the ] at the end of the character
2942 class. */
2943 PATFETCH (c);
2945 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2947 #ifndef emacs
2948 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2949 if (re_iswctype (btowc (ch), cc))
2951 c = TRANSLATE (ch);
2952 if (c < (1 << BYTEWIDTH))
2953 SET_LIST_BIT (c);
2955 #else /* emacs */
2956 /* Most character classes in a multibyte match
2957 just set a flag. Exceptions are is_blank,
2958 is_digit, is_cntrl, and is_xdigit, since
2959 they can only match ASCII characters. We
2960 don't need to handle them for multibyte.
2961 They are distinguished by a negative wctype. */
2963 /* Setup the gl_state object to its buffer-defined
2964 value. This hardcodes the buffer-global
2965 syntax-table for ASCII chars, while the other chars
2966 will obey syntax-table properties. It's not ideal,
2967 but it's the way it's been done until now. */
2968 SETUP_BUFFER_SYNTAX_TABLE ();
2970 for (ch = 0; ch < 256; ++ch)
2972 c = RE_CHAR_TO_MULTIBYTE (ch);
2973 if (! CHAR_BYTE8_P (c)
2974 && re_iswctype (c, cc))
2976 SET_LIST_BIT (ch);
2977 c1 = TRANSLATE (c);
2978 if (c1 == c)
2979 continue;
2980 if (ASCII_CHAR_P (c1))
2981 SET_LIST_BIT (c1);
2982 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2983 SET_LIST_BIT (c1);
2986 SET_RANGE_TABLE_WORK_AREA_BIT
2987 (range_table_work, re_wctype_to_bit (cc));
2988 #endif /* emacs */
2989 /* In most cases the matching rule for char classes
2990 only uses the syntax table for multibyte chars,
2991 so that the content of the syntax-table it is not
2992 hardcoded in the range_table. SPACE and WORD are
2993 the two exceptions. */
2994 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2995 bufp->used_syntax = 1;
2997 /* Repeat the loop. */
2998 continue;
3000 else
3002 /* Go back to right after the "[:". */
3003 p = class_beg;
3004 SET_LIST_BIT ('[');
3006 /* Because the `:' may starts the range, we
3007 can't simply set bit and repeat the loop.
3008 Instead, just set it to C and handle below. */
3009 c = ':';
3013 if (p < pend && p[0] == '-' && p[1] != ']')
3016 /* Discard the `-'. */
3017 PATFETCH (c1);
3019 /* Fetch the character which ends the range. */
3020 PATFETCH (c1);
3021 #ifdef emacs
3022 if (CHAR_BYTE8_P (c1)
3023 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
3024 /* Treat the range from a multibyte character to
3025 raw-byte character as empty. */
3026 c = c1 + 1;
3027 #endif /* emacs */
3029 else
3030 /* Range from C to C. */
3031 c1 = c;
3033 if (c > c1)
3035 if (syntax & RE_NO_EMPTY_RANGES)
3036 FREE_STACK_RETURN (REG_ERANGEX);
3037 /* Else, repeat the loop. */
3039 else
3041 #ifndef emacs
3042 /* Set the range into bitmap */
3043 for (; c <= c1; c++)
3045 ch = TRANSLATE (c);
3046 if (ch < (1 << BYTEWIDTH))
3047 SET_LIST_BIT (ch);
3049 #else /* emacs */
3050 if (c < 128)
3052 ch = MIN (127, c1);
3053 SETUP_ASCII_RANGE (range_table_work, c, ch);
3054 c = ch + 1;
3055 if (CHAR_BYTE8_P (c1))
3056 c = BYTE8_TO_CHAR (128);
3058 if (c <= c1)
3060 if (CHAR_BYTE8_P (c))
3062 c = CHAR_TO_BYTE8 (c);
3063 c1 = CHAR_TO_BYTE8 (c1);
3064 for (; c <= c1; c++)
3065 SET_LIST_BIT (c);
3067 else if (multibyte)
3069 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
3071 else
3073 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
3076 #endif /* emacs */
3080 /* Discard any (non)matching list bytes that are all 0 at the
3081 end of the map. Decrease the map-length byte too. */
3082 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3083 b[-1]--;
3084 b += b[-1];
3086 /* Build real range table from work area. */
3087 if (RANGE_TABLE_WORK_USED (range_table_work)
3088 || RANGE_TABLE_WORK_BITS (range_table_work))
3090 int i;
3091 int used = RANGE_TABLE_WORK_USED (range_table_work);
3093 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3094 bytes for flags, two for COUNT, and three bytes for
3095 each character. */
3096 GET_BUFFER_SPACE (4 + used * 3);
3098 /* Indicate the existence of range table. */
3099 laststart[1] |= 0x80;
3101 /* Store the character class flag bits into the range table.
3102 If not in emacs, these flag bits are always 0. */
3103 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3104 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3106 STORE_NUMBER_AND_INCR (b, used / 2);
3107 for (i = 0; i < used; i++)
3108 STORE_CHARACTER_AND_INCR
3109 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3112 break;
3115 case '(':
3116 if (syntax & RE_NO_BK_PARENS)
3117 goto handle_open;
3118 else
3119 goto normal_char;
3122 case ')':
3123 if (syntax & RE_NO_BK_PARENS)
3124 goto handle_close;
3125 else
3126 goto normal_char;
3129 case '\n':
3130 if (syntax & RE_NEWLINE_ALT)
3131 goto handle_alt;
3132 else
3133 goto normal_char;
3136 case '|':
3137 if (syntax & RE_NO_BK_VBAR)
3138 goto handle_alt;
3139 else
3140 goto normal_char;
3143 case '{':
3144 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3145 goto handle_interval;
3146 else
3147 goto normal_char;
3150 case '\\':
3151 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3153 /* Do not translate the character after the \, so that we can
3154 distinguish, e.g., \B from \b, even if we normally would
3155 translate, e.g., B to b. */
3156 PATFETCH (c);
3158 switch (c)
3160 case '(':
3161 if (syntax & RE_NO_BK_PARENS)
3162 goto normal_backslash;
3164 handle_open:
3166 int shy = 0;
3167 regnum_t regnum = 0;
3168 if (p+1 < pend)
3170 /* Look for a special (?...) construct */
3171 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3173 PATFETCH (c); /* Gobble up the '?'. */
3174 while (!shy)
3176 PATFETCH (c);
3177 switch (c)
3179 case ':': shy = 1; break;
3180 case '0':
3181 /* An explicitly specified regnum must start
3182 with non-0. */
3183 if (regnum == 0)
3184 FREE_STACK_RETURN (REG_BADPAT);
3185 case '1': case '2': case '3': case '4':
3186 case '5': case '6': case '7': case '8': case '9':
3187 regnum = 10*regnum + (c - '0'); break;
3188 default:
3189 /* Only (?:...) is supported right now. */
3190 FREE_STACK_RETURN (REG_BADPAT);
3196 if (!shy)
3197 regnum = ++bufp->re_nsub;
3198 else if (regnum)
3199 { /* It's actually not shy, but explicitly numbered. */
3200 shy = 0;
3201 if (regnum > bufp->re_nsub)
3202 bufp->re_nsub = regnum;
3203 else if (regnum > bufp->re_nsub
3204 /* Ideally, we'd want to check that the specified
3205 group can't have matched (i.e. all subgroups
3206 using the same regnum are in other branches of
3207 OR patterns), but we don't currently keep track
3208 of enough info to do that easily. */
3209 || group_in_compile_stack (compile_stack, regnum))
3210 FREE_STACK_RETURN (REG_BADPAT);
3212 else
3213 /* It's really shy. */
3214 regnum = - bufp->re_nsub;
3216 if (COMPILE_STACK_FULL)
3218 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3219 compile_stack_elt_t);
3220 if (compile_stack.stack == NULL) return REG_ESPACE;
3222 compile_stack.size <<= 1;
3225 /* These are the values to restore when we hit end of this
3226 group. They are all relative offsets, so that if the
3227 whole pattern moves because of realloc, they will still
3228 be valid. */
3229 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3230 COMPILE_STACK_TOP.fixup_alt_jump
3231 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3232 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3233 COMPILE_STACK_TOP.regnum = regnum;
3235 /* Do not push a start_memory for groups beyond the last one
3236 we can represent in the compiled pattern. */
3237 if (regnum <= MAX_REGNUM && regnum > 0)
3238 BUF_PUSH_2 (start_memory, regnum);
3240 compile_stack.avail++;
3242 fixup_alt_jump = 0;
3243 laststart = 0;
3244 begalt = b;
3245 /* If we've reached MAX_REGNUM groups, then this open
3246 won't actually generate any code, so we'll have to
3247 clear pending_exact explicitly. */
3248 pending_exact = 0;
3249 break;
3252 case ')':
3253 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3255 if (COMPILE_STACK_EMPTY)
3257 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3258 goto normal_backslash;
3259 else
3260 FREE_STACK_RETURN (REG_ERPAREN);
3263 handle_close:
3264 FIXUP_ALT_JUMP ();
3266 /* See similar code for backslashed left paren above. */
3267 if (COMPILE_STACK_EMPTY)
3269 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3270 goto normal_char;
3271 else
3272 FREE_STACK_RETURN (REG_ERPAREN);
3275 /* Since we just checked for an empty stack above, this
3276 ``can't happen''. */
3277 assert (compile_stack.avail != 0);
3279 /* We don't just want to restore into `regnum', because
3280 later groups should continue to be numbered higher,
3281 as in `(ab)c(de)' -- the second group is #2. */
3282 regnum_t regnum;
3284 compile_stack.avail--;
3285 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3286 fixup_alt_jump
3287 = COMPILE_STACK_TOP.fixup_alt_jump
3288 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3289 : 0;
3290 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3291 regnum = COMPILE_STACK_TOP.regnum;
3292 /* If we've reached MAX_REGNUM groups, then this open
3293 won't actually generate any code, so we'll have to
3294 clear pending_exact explicitly. */
3295 pending_exact = 0;
3297 /* We're at the end of the group, so now we know how many
3298 groups were inside this one. */
3299 if (regnum <= MAX_REGNUM && regnum > 0)
3300 BUF_PUSH_2 (stop_memory, regnum);
3302 break;
3305 case '|': /* `\|'. */
3306 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3307 goto normal_backslash;
3308 handle_alt:
3309 if (syntax & RE_LIMITED_OPS)
3310 goto normal_char;
3312 /* Insert before the previous alternative a jump which
3313 jumps to this alternative if the former fails. */
3314 GET_BUFFER_SPACE (3);
3315 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3316 pending_exact = 0;
3317 b += 3;
3319 /* The alternative before this one has a jump after it
3320 which gets executed if it gets matched. Adjust that
3321 jump so it will jump to this alternative's analogous
3322 jump (put in below, which in turn will jump to the next
3323 (if any) alternative's such jump, etc.). The last such
3324 jump jumps to the correct final destination. A picture:
3325 _____ _____
3326 | | | |
3327 | v | v
3328 a | b | c
3330 If we are at `b', then fixup_alt_jump right now points to a
3331 three-byte space after `a'. We'll put in the jump, set
3332 fixup_alt_jump to right after `b', and leave behind three
3333 bytes which we'll fill in when we get to after `c'. */
3335 FIXUP_ALT_JUMP ();
3337 /* Mark and leave space for a jump after this alternative,
3338 to be filled in later either by next alternative or
3339 when know we're at the end of a series of alternatives. */
3340 fixup_alt_jump = b;
3341 GET_BUFFER_SPACE (3);
3342 b += 3;
3344 laststart = 0;
3345 begalt = b;
3346 break;
3349 case '{':
3350 /* If \{ is a literal. */
3351 if (!(syntax & RE_INTERVALS)
3352 /* If we're at `\{' and it's not the open-interval
3353 operator. */
3354 || (syntax & RE_NO_BK_BRACES))
3355 goto normal_backslash;
3357 handle_interval:
3359 /* If got here, then the syntax allows intervals. */
3361 /* At least (most) this many matches must be made. */
3362 int lower_bound = 0, upper_bound = -1;
3364 beg_interval = p;
3366 GET_UNSIGNED_NUMBER (lower_bound);
3368 if (c == ',')
3369 GET_UNSIGNED_NUMBER (upper_bound);
3370 else
3371 /* Interval such as `{1}' => match exactly once. */
3372 upper_bound = lower_bound;
3374 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3375 || (upper_bound >= 0 && lower_bound > upper_bound))
3376 FREE_STACK_RETURN (REG_BADBR);
3378 if (!(syntax & RE_NO_BK_BRACES))
3380 if (c != '\\')
3381 FREE_STACK_RETURN (REG_BADBR);
3382 if (p == pend)
3383 FREE_STACK_RETURN (REG_EESCAPE);
3384 PATFETCH (c);
3387 if (c != '}')
3388 FREE_STACK_RETURN (REG_BADBR);
3390 /* We just parsed a valid interval. */
3392 /* If it's invalid to have no preceding re. */
3393 if (!laststart)
3395 if (syntax & RE_CONTEXT_INVALID_OPS)
3396 FREE_STACK_RETURN (REG_BADRPT);
3397 else if (syntax & RE_CONTEXT_INDEP_OPS)
3398 laststart = b;
3399 else
3400 goto unfetch_interval;
3403 if (upper_bound == 0)
3404 /* If the upper bound is zero, just drop the sub pattern
3405 altogether. */
3406 b = laststart;
3407 else if (lower_bound == 1 && upper_bound == 1)
3408 /* Just match it once: nothing to do here. */
3411 /* Otherwise, we have a nontrivial interval. When
3412 we're all done, the pattern will look like:
3413 set_number_at <jump count> <upper bound>
3414 set_number_at <succeed_n count> <lower bound>
3415 succeed_n <after jump addr> <succeed_n count>
3416 <body of loop>
3417 jump_n <succeed_n addr> <jump count>
3418 (The upper bound and `jump_n' are omitted if
3419 `upper_bound' is 1, though.) */
3420 else
3421 { /* If the upper bound is > 1, we need to insert
3422 more at the end of the loop. */
3423 unsigned int nbytes = (upper_bound < 0 ? 3
3424 : upper_bound > 1 ? 5 : 0);
3425 unsigned int startoffset = 0;
3427 GET_BUFFER_SPACE (20); /* We might use less. */
3429 if (lower_bound == 0)
3431 /* A succeed_n that starts with 0 is really a
3432 a simple on_failure_jump_loop. */
3433 INSERT_JUMP (on_failure_jump_loop, laststart,
3434 b + 3 + nbytes);
3435 b += 3;
3437 else
3439 /* Initialize lower bound of the `succeed_n', even
3440 though it will be set during matching by its
3441 attendant `set_number_at' (inserted next),
3442 because `re_compile_fastmap' needs to know.
3443 Jump to the `jump_n' we might insert below. */
3444 INSERT_JUMP2 (succeed_n, laststart,
3445 b + 5 + nbytes,
3446 lower_bound);
3447 b += 5;
3449 /* Code to initialize the lower bound. Insert
3450 before the `succeed_n'. The `5' is the last two
3451 bytes of this `set_number_at', plus 3 bytes of
3452 the following `succeed_n'. */
3453 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3454 b += 5;
3455 startoffset += 5;
3458 if (upper_bound < 0)
3460 /* A negative upper bound stands for infinity,
3461 in which case it degenerates to a plain jump. */
3462 STORE_JUMP (jump, b, laststart + startoffset);
3463 b += 3;
3465 else if (upper_bound > 1)
3466 { /* More than one repetition is allowed, so
3467 append a backward jump to the `succeed_n'
3468 that starts this interval.
3470 When we've reached this during matching,
3471 we'll have matched the interval once, so
3472 jump back only `upper_bound - 1' times. */
3473 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3474 upper_bound - 1);
3475 b += 5;
3477 /* The location we want to set is the second
3478 parameter of the `jump_n'; that is `b-2' as
3479 an absolute address. `laststart' will be
3480 the `set_number_at' we're about to insert;
3481 `laststart+3' the number to set, the source
3482 for the relative address. But we are
3483 inserting into the middle of the pattern --
3484 so everything is getting moved up by 5.
3485 Conclusion: (b - 2) - (laststart + 3) + 5,
3486 i.e., b - laststart.
3488 We insert this at the beginning of the loop
3489 so that if we fail during matching, we'll
3490 reinitialize the bounds. */
3491 insert_op2 (set_number_at, laststart, b - laststart,
3492 upper_bound - 1, b);
3493 b += 5;
3496 pending_exact = 0;
3497 beg_interval = NULL;
3499 break;
3501 unfetch_interval:
3502 /* If an invalid interval, match the characters as literals. */
3503 assert (beg_interval);
3504 p = beg_interval;
3505 beg_interval = NULL;
3507 /* normal_char and normal_backslash need `c'. */
3508 c = '{';
3510 if (!(syntax & RE_NO_BK_BRACES))
3512 assert (p > pattern && p[-1] == '\\');
3513 goto normal_backslash;
3515 else
3516 goto normal_char;
3518 #ifdef emacs
3519 /* There is no way to specify the before_dot and after_dot
3520 operators. rms says this is ok. --karl */
3521 case '=':
3522 BUF_PUSH (at_dot);
3523 break;
3525 case 's':
3526 laststart = b;
3527 PATFETCH (c);
3528 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3529 break;
3531 case 'S':
3532 laststart = b;
3533 PATFETCH (c);
3534 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3535 break;
3537 case 'c':
3538 laststart = b;
3539 PATFETCH (c);
3540 BUF_PUSH_2 (categoryspec, c);
3541 break;
3543 case 'C':
3544 laststart = b;
3545 PATFETCH (c);
3546 BUF_PUSH_2 (notcategoryspec, c);
3547 break;
3548 #endif /* emacs */
3551 case 'w':
3552 if (syntax & RE_NO_GNU_OPS)
3553 goto normal_char;
3554 laststart = b;
3555 BUF_PUSH_2 (syntaxspec, Sword);
3556 break;
3559 case 'W':
3560 if (syntax & RE_NO_GNU_OPS)
3561 goto normal_char;
3562 laststart = b;
3563 BUF_PUSH_2 (notsyntaxspec, Sword);
3564 break;
3567 case '<':
3568 if (syntax & RE_NO_GNU_OPS)
3569 goto normal_char;
3570 BUF_PUSH (wordbeg);
3571 break;
3573 case '>':
3574 if (syntax & RE_NO_GNU_OPS)
3575 goto normal_char;
3576 BUF_PUSH (wordend);
3577 break;
3579 case '_':
3580 if (syntax & RE_NO_GNU_OPS)
3581 goto normal_char;
3582 laststart = b;
3583 PATFETCH (c);
3584 if (c == '<')
3585 BUF_PUSH (symbeg);
3586 else if (c == '>')
3587 BUF_PUSH (symend);
3588 else
3589 FREE_STACK_RETURN (REG_BADPAT);
3590 break;
3592 case 'b':
3593 if (syntax & RE_NO_GNU_OPS)
3594 goto normal_char;
3595 BUF_PUSH (wordbound);
3596 break;
3598 case 'B':
3599 if (syntax & RE_NO_GNU_OPS)
3600 goto normal_char;
3601 BUF_PUSH (notwordbound);
3602 break;
3604 case '`':
3605 if (syntax & RE_NO_GNU_OPS)
3606 goto normal_char;
3607 BUF_PUSH (begbuf);
3608 break;
3610 case '\'':
3611 if (syntax & RE_NO_GNU_OPS)
3612 goto normal_char;
3613 BUF_PUSH (endbuf);
3614 break;
3616 case '1': case '2': case '3': case '4': case '5':
3617 case '6': case '7': case '8': case '9':
3619 regnum_t reg;
3621 if (syntax & RE_NO_BK_REFS)
3622 goto normal_backslash;
3624 reg = c - '0';
3626 if (reg > bufp->re_nsub || reg < 1
3627 /* Can't back reference to a subexp before its end. */
3628 || group_in_compile_stack (compile_stack, reg))
3629 FREE_STACK_RETURN (REG_ESUBREG);
3631 laststart = b;
3632 BUF_PUSH_2 (duplicate, reg);
3634 break;
3637 case '+':
3638 case '?':
3639 if (syntax & RE_BK_PLUS_QM)
3640 goto handle_plus;
3641 else
3642 goto normal_backslash;
3644 default:
3645 normal_backslash:
3646 /* You might think it would be useful for \ to mean
3647 not to translate; but if we don't translate it
3648 it will never match anything. */
3649 goto normal_char;
3651 break;
3654 default:
3655 /* Expects the character in `c'. */
3656 normal_char:
3657 /* If no exactn currently being built. */
3658 if (!pending_exact
3660 /* If last exactn not at current position. */
3661 || pending_exact + *pending_exact + 1 != b
3663 /* We have only one byte following the exactn for the count. */
3664 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3666 /* If followed by a repetition operator. */
3667 || (p != pend && (*p == '*' || *p == '^'))
3668 || ((syntax & RE_BK_PLUS_QM)
3669 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3670 : p != pend && (*p == '+' || *p == '?'))
3671 || ((syntax & RE_INTERVALS)
3672 && ((syntax & RE_NO_BK_BRACES)
3673 ? p != pend && *p == '{'
3674 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3676 /* Start building a new exactn. */
3678 laststart = b;
3680 BUF_PUSH_2 (exactn, 0);
3681 pending_exact = b - 1;
3684 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3686 int len;
3688 if (multibyte)
3690 c = TRANSLATE (c);
3691 len = CHAR_STRING (c, b);
3692 b += len;
3694 else
3696 c1 = RE_CHAR_TO_MULTIBYTE (c);
3697 if (! CHAR_BYTE8_P (c1))
3699 re_wchar_t c2 = TRANSLATE (c1);
3701 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3702 c = c1;
3704 *b++ = c;
3705 len = 1;
3707 (*pending_exact) += len;
3710 break;
3711 } /* switch (c) */
3712 } /* while p != pend */
3715 /* Through the pattern now. */
3717 FIXUP_ALT_JUMP ();
3719 if (!COMPILE_STACK_EMPTY)
3720 FREE_STACK_RETURN (REG_EPAREN);
3722 /* If we don't want backtracking, force success
3723 the first time we reach the end of the compiled pattern. */
3724 if (syntax & RE_NO_POSIX_BACKTRACKING)
3725 BUF_PUSH (succeed);
3727 /* We have succeeded; set the length of the buffer. */
3728 bufp->used = b - bufp->buffer;
3730 #ifdef DEBUG
3731 if (debug > 0)
3733 re_compile_fastmap (bufp);
3734 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3735 print_compiled_pattern (bufp);
3737 debug--;
3738 #endif /* DEBUG */
3740 #ifndef MATCH_MAY_ALLOCATE
3741 /* Initialize the failure stack to the largest possible stack. This
3742 isn't necessary unless we're trying to avoid calling alloca in
3743 the search and match routines. */
3745 int num_regs = bufp->re_nsub + 1;
3747 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3749 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3751 if (! fail_stack.stack)
3752 fail_stack.stack
3753 = (fail_stack_elt_t *) malloc (fail_stack.size
3754 * sizeof (fail_stack_elt_t));
3755 else
3756 fail_stack.stack
3757 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3758 (fail_stack.size
3759 * sizeof (fail_stack_elt_t)));
3762 regex_grow_registers (num_regs);
3764 #endif /* not MATCH_MAY_ALLOCATE */
3766 FREE_STACK_RETURN (REG_NOERROR);
3767 } /* regex_compile */
3769 /* Subroutines for `regex_compile'. */
3771 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3773 static void
3774 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3776 *loc = (unsigned char) op;
3777 STORE_NUMBER (loc + 1, arg);
3781 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3783 static void
3784 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3786 *loc = (unsigned char) op;
3787 STORE_NUMBER (loc + 1, arg1);
3788 STORE_NUMBER (loc + 3, arg2);
3792 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3793 for OP followed by two-byte integer parameter ARG. */
3795 static void
3796 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3798 register unsigned char *pfrom = end;
3799 register unsigned char *pto = end + 3;
3801 while (pfrom != loc)
3802 *--pto = *--pfrom;
3804 store_op1 (op, loc, arg);
3808 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3810 static void
3811 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3813 register unsigned char *pfrom = end;
3814 register unsigned char *pto = end + 5;
3816 while (pfrom != loc)
3817 *--pto = *--pfrom;
3819 store_op2 (op, loc, arg1, arg2);
3823 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3824 after an alternative or a begin-subexpression. We assume there is at
3825 least one character before the ^. */
3827 static boolean
3828 at_begline_loc_p (const re_char *pattern, const re_char *p, reg_syntax_t syntax)
3830 re_char *prev = p - 2;
3831 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3833 return
3834 /* After a subexpression? */
3835 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3836 /* After an alternative? */
3837 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash))
3838 /* After a shy subexpression? */
3839 || ((syntax & RE_SHY_GROUPS) && prev - 2 >= pattern
3840 && prev[-1] == '?' && prev[-2] == '('
3841 && (syntax & RE_NO_BK_PARENS
3842 || (prev - 3 >= pattern && prev[-3] == '\\')));
3846 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3847 at least one character after the $, i.e., `P < PEND'. */
3849 static boolean
3850 at_endline_loc_p (const re_char *p, const re_char *pend, reg_syntax_t syntax)
3852 re_char *next = p;
3853 boolean next_backslash = *next == '\\';
3854 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3856 return
3857 /* Before a subexpression? */
3858 (syntax & RE_NO_BK_PARENS ? *next == ')'
3859 : next_backslash && next_next && *next_next == ')')
3860 /* Before an alternative? */
3861 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3862 : next_backslash && next_next && *next_next == '|');
3866 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3867 false if it's not. */
3869 static boolean
3870 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3872 ssize_t this_element;
3874 for (this_element = compile_stack.avail - 1;
3875 this_element >= 0;
3876 this_element--)
3877 if (compile_stack.stack[this_element].regnum == regnum)
3878 return true;
3880 return false;
3883 /* analyse_first.
3884 If fastmap is non-NULL, go through the pattern and fill fastmap
3885 with all the possible leading chars. If fastmap is NULL, don't
3886 bother filling it up (obviously) and only return whether the
3887 pattern could potentially match the empty string.
3889 Return 1 if p..pend might match the empty string.
3890 Return 0 if p..pend matches at least one char.
3891 Return -1 if fastmap was not updated accurately. */
3893 static int
3894 analyse_first (const re_char *p, const re_char *pend, char *fastmap, const int multibyte)
3896 int j, k;
3897 boolean not;
3899 /* If all elements for base leading-codes in fastmap is set, this
3900 flag is set true. */
3901 boolean match_any_multibyte_characters = false;
3903 assert (p);
3905 /* The loop below works as follows:
3906 - It has a working-list kept in the PATTERN_STACK and which basically
3907 starts by only containing a pointer to the first operation.
3908 - If the opcode we're looking at is a match against some set of
3909 chars, then we add those chars to the fastmap and go on to the
3910 next work element from the worklist (done via `break').
3911 - If the opcode is a control operator on the other hand, we either
3912 ignore it (if it's meaningless at this point, such as `start_memory')
3913 or execute it (if it's a jump). If the jump has several destinations
3914 (i.e. `on_failure_jump'), then we push the other destination onto the
3915 worklist.
3916 We guarantee termination by ignoring backward jumps (more or less),
3917 so that `p' is monotonically increasing. More to the point, we
3918 never set `p' (or push) anything `<= p1'. */
3920 while (p < pend)
3922 /* `p1' is used as a marker of how far back a `on_failure_jump'
3923 can go without being ignored. It is normally equal to `p'
3924 (which prevents any backward `on_failure_jump') except right
3925 after a plain `jump', to allow patterns such as:
3926 0: jump 10
3927 3..9: <body>
3928 10: on_failure_jump 3
3929 as used for the *? operator. */
3930 re_char *p1 = p;
3932 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3934 case succeed:
3935 return 1;
3937 case duplicate:
3938 /* If the first character has to match a backreference, that means
3939 that the group was empty (since it already matched). Since this
3940 is the only case that interests us here, we can assume that the
3941 backreference must match the empty string. */
3942 p++;
3943 continue;
3946 /* Following are the cases which match a character. These end
3947 with `break'. */
3949 case exactn:
3950 if (fastmap)
3952 /* If multibyte is nonzero, the first byte of each
3953 character is an ASCII or a leading code. Otherwise,
3954 each byte is a character. Thus, this works in both
3955 cases. */
3956 fastmap[p[1]] = 1;
3957 if (! multibyte)
3959 /* For the case of matching this unibyte regex
3960 against multibyte, we must set a leading code of
3961 the corresponding multibyte character. */
3962 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3964 fastmap[CHAR_LEADING_CODE (c)] = 1;
3967 break;
3970 case anychar:
3971 /* We could put all the chars except for \n (and maybe \0)
3972 but we don't bother since it is generally not worth it. */
3973 if (!fastmap) break;
3974 return -1;
3977 case charset_not:
3978 if (!fastmap) break;
3980 /* Chars beyond end of bitmap are possible matches. */
3981 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3982 j < (1 << BYTEWIDTH); j++)
3983 fastmap[j] = 1;
3986 /* Fallthrough */
3987 case charset:
3988 if (!fastmap) break;
3989 not = (re_opcode_t) *(p - 1) == charset_not;
3990 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3991 j >= 0; j--)
3992 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3993 fastmap[j] = 1;
3995 #ifdef emacs
3996 if (/* Any leading code can possibly start a character
3997 which doesn't match the specified set of characters. */
4000 /* If we can match a character class, we can match any
4001 multibyte characters. */
4002 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
4003 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
4006 if (match_any_multibyte_characters == false)
4008 for (j = MIN_MULTIBYTE_LEADING_CODE;
4009 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4010 fastmap[j] = 1;
4011 match_any_multibyte_characters = true;
4015 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
4016 && match_any_multibyte_characters == false)
4018 /* Set fastmap[I] to 1 where I is a leading code of each
4019 multibyte character in the range table. */
4020 int c, count;
4021 unsigned char lc1, lc2;
4023 /* Make P points the range table. `+ 2' is to skip flag
4024 bits for a character class. */
4025 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
4027 /* Extract the number of ranges in range table into COUNT. */
4028 EXTRACT_NUMBER_AND_INCR (count, p);
4029 for (; count > 0; count--, p += 3)
4031 /* Extract the start and end of each range. */
4032 EXTRACT_CHARACTER (c, p);
4033 lc1 = CHAR_LEADING_CODE (c);
4034 p += 3;
4035 EXTRACT_CHARACTER (c, p);
4036 lc2 = CHAR_LEADING_CODE (c);
4037 for (j = lc1; j <= lc2; j++)
4038 fastmap[j] = 1;
4041 #endif
4042 break;
4044 case syntaxspec:
4045 case notsyntaxspec:
4046 if (!fastmap) break;
4047 #ifndef emacs
4048 not = (re_opcode_t)p[-1] == notsyntaxspec;
4049 k = *p++;
4050 for (j = 0; j < (1 << BYTEWIDTH); j++)
4051 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
4052 fastmap[j] = 1;
4053 break;
4054 #else /* emacs */
4055 /* This match depends on text properties. These end with
4056 aborting optimizations. */
4057 return -1;
4059 case categoryspec:
4060 case notcategoryspec:
4061 if (!fastmap) break;
4062 not = (re_opcode_t)p[-1] == notcategoryspec;
4063 k = *p++;
4064 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4065 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4066 fastmap[j] = 1;
4068 /* Any leading code can possibly start a character which
4069 has or doesn't has the specified category. */
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;
4077 break;
4079 /* All cases after this match the empty string. These end with
4080 `continue'. */
4082 case before_dot:
4083 case at_dot:
4084 case after_dot:
4085 #endif /* !emacs */
4086 case no_op:
4087 case begline:
4088 case endline:
4089 case begbuf:
4090 case endbuf:
4091 case wordbound:
4092 case notwordbound:
4093 case wordbeg:
4094 case wordend:
4095 case symbeg:
4096 case symend:
4097 continue;
4100 case jump:
4101 EXTRACT_NUMBER_AND_INCR (j, p);
4102 if (j < 0)
4103 /* Backward jumps can only go back to code that we've already
4104 visited. `re_compile' should make sure this is true. */
4105 break;
4106 p += j;
4107 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4109 case on_failure_jump:
4110 case on_failure_keep_string_jump:
4111 case on_failure_jump_loop:
4112 case on_failure_jump_nastyloop:
4113 case on_failure_jump_smart:
4114 p++;
4115 break;
4116 default:
4117 continue;
4119 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4120 to jump back to "just after here". */
4121 /* Fallthrough */
4123 case on_failure_jump:
4124 case on_failure_keep_string_jump:
4125 case on_failure_jump_nastyloop:
4126 case on_failure_jump_loop:
4127 case on_failure_jump_smart:
4128 EXTRACT_NUMBER_AND_INCR (j, p);
4129 if (p + j <= p1)
4130 ; /* Backward jump to be ignored. */
4131 else
4132 { /* We have to look down both arms.
4133 We first go down the "straight" path so as to minimize
4134 stack usage when going through alternatives. */
4135 int r = analyse_first (p, pend, fastmap, multibyte);
4136 if (r) return r;
4137 p += j;
4139 continue;
4142 case jump_n:
4143 /* This code simply does not properly handle forward jump_n. */
4144 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4145 p += 4;
4146 /* jump_n can either jump or fall through. The (backward) jump
4147 case has already been handled, so we only need to look at the
4148 fallthrough case. */
4149 continue;
4151 case succeed_n:
4152 /* If N == 0, it should be an on_failure_jump_loop instead. */
4153 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4154 p += 4;
4155 /* We only care about one iteration of the loop, so we don't
4156 need to consider the case where this behaves like an
4157 on_failure_jump. */
4158 continue;
4161 case set_number_at:
4162 p += 4;
4163 continue;
4166 case start_memory:
4167 case stop_memory:
4168 p += 1;
4169 continue;
4172 default:
4173 abort (); /* We have listed all the cases. */
4174 } /* switch *p++ */
4176 /* Getting here means we have found the possible starting
4177 characters for one path of the pattern -- and that the empty
4178 string does not match. We need not follow this path further. */
4179 return 0;
4180 } /* while p */
4182 /* We reached the end without matching anything. */
4183 return 1;
4185 } /* analyse_first */
4187 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4188 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4189 characters can start a string that matches the pattern. This fastmap
4190 is used by re_search to skip quickly over impossible starting points.
4192 Character codes above (1 << BYTEWIDTH) are not represented in the
4193 fastmap, but the leading codes are represented. Thus, the fastmap
4194 indicates which character sets could start a match.
4196 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4197 area as BUFP->fastmap.
4199 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4200 the pattern buffer.
4202 Returns 0 if we succeed, -2 if an internal error. */
4205 re_compile_fastmap (struct re_pattern_buffer *bufp)
4207 char *fastmap = bufp->fastmap;
4208 int analysis;
4210 assert (fastmap && bufp->buffer);
4212 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4213 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4215 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
4216 fastmap, RE_MULTIBYTE_P (bufp));
4217 bufp->can_be_null = (analysis != 0);
4218 return 0;
4219 } /* re_compile_fastmap */
4221 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4222 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4223 this memory for recording register information. STARTS and ENDS
4224 must be allocated using the malloc library routine, and must each
4225 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4227 If NUM_REGS == 0, then subsequent matches should allocate their own
4228 register data.
4230 Unless this function is called, the first search or match using
4231 PATTERN_BUFFER will allocate its own register data, without
4232 freeing the old data. */
4234 void
4235 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4237 if (num_regs)
4239 bufp->regs_allocated = REGS_REALLOCATE;
4240 regs->num_regs = num_regs;
4241 regs->start = starts;
4242 regs->end = ends;
4244 else
4246 bufp->regs_allocated = REGS_UNALLOCATED;
4247 regs->num_regs = 0;
4248 regs->start = regs->end = (regoff_t *) 0;
4251 WEAK_ALIAS (__re_set_registers, re_set_registers)
4253 /* Searching routines. */
4255 /* Like re_search_2, below, but only one string is specified, and
4256 doesn't let you say where to stop matching. */
4258 regoff_t
4259 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4260 ssize_t startpos, ssize_t range, struct re_registers *regs)
4262 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4263 regs, size);
4265 WEAK_ALIAS (__re_search, re_search)
4267 /* Head address of virtual concatenation of string. */
4268 #define HEAD_ADDR_VSTRING(P) \
4269 (((P) >= size1 ? string2 : string1))
4271 /* Address of POS in the concatenation of virtual string. */
4272 #define POS_ADDR_VSTRING(POS) \
4273 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4275 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4276 virtual concatenation of STRING1 and STRING2, starting first at index
4277 STARTPOS, then at STARTPOS + 1, and so on.
4279 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4281 RANGE is how far to scan while trying to match. RANGE = 0 means try
4282 only at STARTPOS; in general, the last start tried is STARTPOS +
4283 RANGE.
4285 In REGS, return the indices of the virtual concatenation of STRING1
4286 and STRING2 that matched the entire BUFP->buffer and its contained
4287 subexpressions.
4289 Do not consider matching one past the index STOP in the virtual
4290 concatenation of STRING1 and STRING2.
4292 We return either the position in the strings at which the match was
4293 found, -1 if no match, or -2 if error (such as failure
4294 stack overflow). */
4296 regoff_t
4297 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4298 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4299 struct re_registers *regs, ssize_t stop)
4301 regoff_t val;
4302 re_char *string1 = (re_char*) str1;
4303 re_char *string2 = (re_char*) str2;
4304 register char *fastmap = bufp->fastmap;
4305 register RE_TRANSLATE_TYPE translate = bufp->translate;
4306 size_t total_size = size1 + size2;
4307 ssize_t endpos = startpos + range;
4308 boolean anchored_start;
4309 /* Nonzero if we are searching multibyte string. */
4310 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4312 /* Check for out-of-range STARTPOS. */
4313 if (startpos < 0 || startpos > total_size)
4314 return -1;
4316 /* Fix up RANGE if it might eventually take us outside
4317 the virtual concatenation of STRING1 and STRING2.
4318 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4319 if (endpos < 0)
4320 range = 0 - startpos;
4321 else if (endpos > total_size)
4322 range = total_size - startpos;
4324 /* If the search isn't to be a backwards one, don't waste time in a
4325 search for a pattern anchored at beginning of buffer. */
4326 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4328 if (startpos > 0)
4329 return -1;
4330 else
4331 range = 0;
4334 #ifdef emacs
4335 /* In a forward search for something that starts with \=.
4336 don't keep searching past point. */
4337 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4339 range = PT_BYTE - BEGV_BYTE - startpos;
4340 if (range < 0)
4341 return -1;
4343 #endif /* emacs */
4345 /* Update the fastmap now if not correct already. */
4346 if (fastmap && !bufp->fastmap_accurate)
4347 re_compile_fastmap (bufp);
4349 /* See whether the pattern is anchored. */
4350 anchored_start = (bufp->buffer[0] == begline);
4352 #ifdef emacs
4353 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4355 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4357 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4359 #endif
4361 /* Loop through the string, looking for a place to start matching. */
4362 for (;;)
4364 /* If the pattern is anchored,
4365 skip quickly past places we cannot match.
4366 We don't bother to treat startpos == 0 specially
4367 because that case doesn't repeat. */
4368 if (anchored_start && startpos > 0)
4370 if (! ((startpos <= size1 ? string1[startpos - 1]
4371 : string2[startpos - size1 - 1])
4372 == '\n'))
4373 goto advance;
4376 /* If a fastmap is supplied, skip quickly over characters that
4377 cannot be the start of a match. If the pattern can match the
4378 null string, however, we don't need to skip characters; we want
4379 the first null string. */
4380 if (fastmap && startpos < total_size && !bufp->can_be_null)
4382 register re_char *d;
4383 register re_wchar_t buf_ch;
4385 d = POS_ADDR_VSTRING (startpos);
4387 if (range > 0) /* Searching forwards. */
4389 register int lim = 0;
4390 ssize_t irange = range;
4392 if (startpos < size1 && startpos + range >= size1)
4393 lim = range - (size1 - startpos);
4395 /* Written out as an if-else to avoid testing `translate'
4396 inside the loop. */
4397 if (RE_TRANSLATE_P (translate))
4399 if (multibyte)
4400 while (range > lim)
4402 int buf_charlen;
4404 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4405 buf_ch = RE_TRANSLATE (translate, buf_ch);
4406 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4407 break;
4409 range -= buf_charlen;
4410 d += buf_charlen;
4412 else
4413 while (range > lim)
4415 register re_wchar_t ch, translated;
4417 buf_ch = *d;
4418 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4419 translated = RE_TRANSLATE (translate, ch);
4420 if (translated != ch
4421 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4422 buf_ch = ch;
4423 if (fastmap[buf_ch])
4424 break;
4425 d++;
4426 range--;
4429 else
4431 if (multibyte)
4432 while (range > lim)
4434 int buf_charlen;
4436 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4437 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4438 break;
4439 range -= buf_charlen;
4440 d += buf_charlen;
4442 else
4443 while (range > lim && !fastmap[*d])
4445 d++;
4446 range--;
4449 startpos += irange - range;
4451 else /* Searching backwards. */
4453 if (multibyte)
4455 buf_ch = STRING_CHAR (d);
4456 buf_ch = TRANSLATE (buf_ch);
4457 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4458 goto advance;
4460 else
4462 register re_wchar_t ch, translated;
4464 buf_ch = *d;
4465 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4466 translated = TRANSLATE (ch);
4467 if (translated != ch
4468 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4469 buf_ch = ch;
4470 if (! fastmap[TRANSLATE (buf_ch)])
4471 goto advance;
4476 /* If can't match the null string, and that's all we have left, fail. */
4477 if (range >= 0 && startpos == total_size && fastmap
4478 && !bufp->can_be_null)
4479 return -1;
4481 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4482 startpos, regs, stop);
4484 if (val >= 0)
4485 return startpos;
4487 if (val == -2)
4488 return -2;
4490 advance:
4491 if (!range)
4492 break;
4493 else if (range > 0)
4495 /* Update STARTPOS to the next character boundary. */
4496 if (multibyte)
4498 re_char *p = POS_ADDR_VSTRING (startpos);
4499 int len = BYTES_BY_CHAR_HEAD (*p);
4501 range -= len;
4502 if (range < 0)
4503 break;
4504 startpos += len;
4506 else
4508 range--;
4509 startpos++;
4512 else
4514 range++;
4515 startpos--;
4517 /* Update STARTPOS to the previous character boundary. */
4518 if (multibyte)
4520 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4521 re_char *p0 = p;
4522 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4524 /* Find the head of multibyte form. */
4525 PREV_CHAR_BOUNDARY (p, phead);
4526 range += p0 - 1 - p;
4527 if (range > 0)
4528 break;
4530 startpos -= p0 - 1 - p;
4534 return -1;
4535 } /* re_search_2 */
4536 WEAK_ALIAS (__re_search_2, re_search_2)
4538 /* Declarations and macros for re_match_2. */
4540 static int bcmp_translate _RE_ARGS((re_char *s1, re_char *s2,
4541 register ssize_t len,
4542 RE_TRANSLATE_TYPE translate,
4543 const int multibyte));
4545 /* This converts PTR, a pointer into one of the search strings `string1'
4546 and `string2' into an offset from the beginning of that string. */
4547 #define POINTER_TO_OFFSET(ptr) \
4548 (FIRST_STRING_P (ptr) \
4549 ? ((regoff_t) ((ptr) - string1)) \
4550 : ((regoff_t) ((ptr) - string2 + size1)))
4552 /* Call before fetching a character with *d. This switches over to
4553 string2 if necessary.
4554 Check re_match_2_internal for a discussion of why end_match_2 might
4555 not be within string2 (but be equal to end_match_1 instead). */
4556 #define PREFETCH() \
4557 while (d == dend) \
4559 /* End of string2 => fail. */ \
4560 if (dend == end_match_2) \
4561 goto fail; \
4562 /* End of string1 => advance to string2. */ \
4563 d = string2; \
4564 dend = end_match_2; \
4567 /* Call before fetching a char with *d if you already checked other limits.
4568 This is meant for use in lookahead operations like wordend, etc..
4569 where we might need to look at parts of the string that might be
4570 outside of the LIMITs (i.e past `stop'). */
4571 #define PREFETCH_NOLIMIT() \
4572 if (d == end1) \
4574 d = string2; \
4575 dend = end_match_2; \
4578 /* Test if at very beginning or at very end of the virtual concatenation
4579 of `string1' and `string2'. If only one string, it's `string2'. */
4580 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4581 #define AT_STRINGS_END(d) ((d) == end2)
4583 /* Disabled due to a compiler bug -- see comment at case wordbound */
4585 /* The comment at case wordbound is following one, but we don't use
4586 AT_WORD_BOUNDARY anymore to support multibyte form.
4588 The DEC Alpha C compiler 3.x generates incorrect code for the
4589 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4590 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4591 macro and introducing temporary variables works around the bug. */
4593 #if 0
4594 /* Test if D points to a character which is word-constituent. We have
4595 two special cases to check for: if past the end of string1, look at
4596 the first character in string2; and if before the beginning of
4597 string2, look at the last character in string1. */
4598 #define WORDCHAR_P(d) \
4599 (SYNTAX ((d) == end1 ? *string2 \
4600 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4601 == Sword)
4603 /* Test if the character before D and the one at D differ with respect
4604 to being word-constituent. */
4605 #define AT_WORD_BOUNDARY(d) \
4606 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4607 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4608 #endif
4610 /* Free everything we malloc. */
4611 #ifdef MATCH_MAY_ALLOCATE
4612 # define FREE_VAR(var) \
4613 do { \
4614 if (var) \
4616 REGEX_FREE (var); \
4617 var = NULL; \
4619 } while (0)
4620 # define FREE_VARIABLES() \
4621 do { \
4622 REGEX_FREE_STACK (fail_stack.stack); \
4623 FREE_VAR (regstart); \
4624 FREE_VAR (regend); \
4625 FREE_VAR (best_regstart); \
4626 FREE_VAR (best_regend); \
4627 } while (0)
4628 #else
4629 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4630 #endif /* not MATCH_MAY_ALLOCATE */
4633 /* Optimization routines. */
4635 /* If the operation is a match against one or more chars,
4636 return a pointer to the next operation, else return NULL. */
4637 static re_char *
4638 skip_one_char (const re_char *p)
4640 switch (SWITCH_ENUM_CAST (*p++))
4642 case anychar:
4643 break;
4645 case exactn:
4646 p += *p + 1;
4647 break;
4649 case charset_not:
4650 case charset:
4651 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4653 int mcnt;
4654 p = CHARSET_RANGE_TABLE (p - 1);
4655 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4656 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4658 else
4659 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4660 break;
4662 case syntaxspec:
4663 case notsyntaxspec:
4664 #ifdef emacs
4665 case categoryspec:
4666 case notcategoryspec:
4667 #endif /* emacs */
4668 p++;
4669 break;
4671 default:
4672 p = NULL;
4674 return p;
4678 /* Jump over non-matching operations. */
4679 static re_char *
4680 skip_noops (const re_char *p, const re_char *pend)
4682 int mcnt;
4683 while (p < pend)
4685 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4687 case start_memory:
4688 case stop_memory:
4689 p += 2; break;
4690 case no_op:
4691 p += 1; break;
4692 case jump:
4693 p += 1;
4694 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4695 p += mcnt;
4696 break;
4697 default:
4698 return p;
4701 assert (p == pend);
4702 return p;
4705 /* Non-zero if "p1 matches something" implies "p2 fails". */
4706 static int
4707 mutually_exclusive_p (struct re_pattern_buffer *bufp, const re_char *p1, const re_char *p2)
4709 re_opcode_t op2;
4710 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4711 unsigned char *pend = bufp->buffer + bufp->used;
4713 assert (p1 >= bufp->buffer && p1 < pend
4714 && p2 >= bufp->buffer && p2 <= pend);
4716 /* Skip over open/close-group commands.
4717 If what follows this loop is a ...+ construct,
4718 look at what begins its body, since we will have to
4719 match at least one of that. */
4720 p2 = skip_noops (p2, pend);
4721 /* The same skip can be done for p1, except that this function
4722 is only used in the case where p1 is a simple match operator. */
4723 /* p1 = skip_noops (p1, pend); */
4725 assert (p1 >= bufp->buffer && p1 < pend
4726 && p2 >= bufp->buffer && p2 <= pend);
4728 op2 = p2 == pend ? succeed : *p2;
4730 switch (SWITCH_ENUM_CAST (op2))
4732 case succeed:
4733 case endbuf:
4734 /* If we're at the end of the pattern, we can change. */
4735 if (skip_one_char (p1))
4737 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4738 return 1;
4740 break;
4742 case endline:
4743 case exactn:
4745 register re_wchar_t c
4746 = (re_opcode_t) *p2 == endline ? '\n'
4747 : RE_STRING_CHAR (p2 + 2, multibyte);
4749 if ((re_opcode_t) *p1 == exactn)
4751 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4753 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4754 return 1;
4758 else if ((re_opcode_t) *p1 == charset
4759 || (re_opcode_t) *p1 == charset_not)
4761 int not = (re_opcode_t) *p1 == charset_not;
4763 /* Test if C is listed in charset (or charset_not)
4764 at `p1'. */
4765 if (! multibyte || IS_REAL_ASCII (c))
4767 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4768 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4769 not = !not;
4771 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4772 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4774 /* `not' is equal to 1 if c would match, which means
4775 that we can't change to pop_failure_jump. */
4776 if (!not)
4778 DEBUG_PRINT1 (" No match => fast loop.\n");
4779 return 1;
4782 else if ((re_opcode_t) *p1 == anychar
4783 && c == '\n')
4785 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4786 return 1;
4789 break;
4791 case charset:
4793 if ((re_opcode_t) *p1 == exactn)
4794 /* Reuse the code above. */
4795 return mutually_exclusive_p (bufp, p2, p1);
4797 /* It is hard to list up all the character in charset
4798 P2 if it includes multibyte character. Give up in
4799 such case. */
4800 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4802 /* Now, we are sure that P2 has no range table.
4803 So, for the size of bitmap in P2, `p2[1]' is
4804 enough. But P1 may have range table, so the
4805 size of bitmap table of P1 is extracted by
4806 using macro `CHARSET_BITMAP_SIZE'.
4808 In a multibyte case, we know that all the character
4809 listed in P2 is ASCII. In a unibyte case, P1 has only a
4810 bitmap table. So, in both cases, it is enough to test
4811 only the bitmap table of P1. */
4813 if ((re_opcode_t) *p1 == charset)
4815 int idx;
4816 /* We win if the charset inside the loop
4817 has no overlap with the one after the loop. */
4818 for (idx = 0;
4819 (idx < (int) p2[1]
4820 && idx < CHARSET_BITMAP_SIZE (p1));
4821 idx++)
4822 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4823 break;
4825 if (idx == p2[1]
4826 || idx == CHARSET_BITMAP_SIZE (p1))
4828 DEBUG_PRINT1 (" No match => fast loop.\n");
4829 return 1;
4832 else if ((re_opcode_t) *p1 == charset_not)
4834 int idx;
4835 /* We win if the charset_not inside the loop lists
4836 every character listed in the charset after. */
4837 for (idx = 0; idx < (int) p2[1]; idx++)
4838 if (! (p2[2 + idx] == 0
4839 || (idx < CHARSET_BITMAP_SIZE (p1)
4840 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4841 break;
4843 if (idx == p2[1])
4845 DEBUG_PRINT1 (" No match => fast loop.\n");
4846 return 1;
4851 break;
4853 case charset_not:
4854 switch (SWITCH_ENUM_CAST (*p1))
4856 case exactn:
4857 case charset:
4858 /* Reuse the code above. */
4859 return mutually_exclusive_p (bufp, p2, p1);
4860 case charset_not:
4861 /* When we have two charset_not, it's very unlikely that
4862 they don't overlap. The union of the two sets of excluded
4863 chars should cover all possible chars, which, as a matter of
4864 fact, is virtually impossible in multibyte buffers. */
4865 break;
4867 break;
4869 case wordend:
4870 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4871 case symend:
4872 return ((re_opcode_t) *p1 == syntaxspec
4873 && (p1[1] == Ssymbol || p1[1] == Sword));
4874 case notsyntaxspec:
4875 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4877 case wordbeg:
4878 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4879 case symbeg:
4880 return ((re_opcode_t) *p1 == notsyntaxspec
4881 && (p1[1] == Ssymbol || p1[1] == Sword));
4882 case syntaxspec:
4883 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4885 case wordbound:
4886 return (((re_opcode_t) *p1 == notsyntaxspec
4887 || (re_opcode_t) *p1 == syntaxspec)
4888 && p1[1] == Sword);
4890 #ifdef emacs
4891 case categoryspec:
4892 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4893 case notcategoryspec:
4894 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4895 #endif /* emacs */
4897 default:
4901 /* Safe default. */
4902 return 0;
4906 /* Matching routines. */
4908 #ifndef emacs /* Emacs never uses this. */
4909 /* re_match is like re_match_2 except it takes only a single string. */
4911 regoff_t
4912 re_match (struct re_pattern_buffer *bufp, const char *string,
4913 size_t size, ssize_t pos, struct re_registers *regs)
4915 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4916 size, pos, regs, size);
4917 return result;
4919 WEAK_ALIAS (__re_match, re_match)
4920 #endif /* not emacs */
4922 #ifdef emacs
4923 /* In Emacs, this is the string or buffer in which we
4924 are matching. It is used for looking up syntax properties. */
4925 Lisp_Object re_match_object;
4926 #endif
4928 /* re_match_2 matches the compiled pattern in BUFP against the
4929 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4930 and SIZE2, respectively). We start matching at POS, and stop
4931 matching at STOP.
4933 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4934 store offsets for the substring each group matched in REGS. See the
4935 documentation for exactly how many groups we fill.
4937 We return -1 if no match, -2 if an internal error (such as the
4938 failure stack overflowing). Otherwise, we return the length of the
4939 matched substring. */
4941 regoff_t
4942 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4943 size_t size1, const char *string2, size_t size2, ssize_t pos,
4944 struct re_registers *regs, ssize_t stop)
4946 regoff_t result;
4948 #ifdef emacs
4949 ssize_t charpos;
4950 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4951 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4952 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4953 #endif
4955 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4956 (re_char*) string2, size2,
4957 pos, regs, stop);
4958 return result;
4960 WEAK_ALIAS (__re_match_2, re_match_2)
4963 /* This is a separate function so that we can force an alloca cleanup
4964 afterwards. */
4965 static regoff_t
4966 re_match_2_internal (struct re_pattern_buffer *bufp, const re_char *string1,
4967 size_t size1, const re_char *string2, size_t size2,
4968 ssize_t pos, struct re_registers *regs, ssize_t stop)
4970 /* General temporaries. */
4971 ssize_t mcnt;
4972 size_t reg;
4974 /* Just past the end of the corresponding string. */
4975 re_char *end1, *end2;
4977 /* Pointers into string1 and string2, just past the last characters in
4978 each to consider matching. */
4979 re_char *end_match_1, *end_match_2;
4981 /* Where we are in the data, and the end of the current string. */
4982 re_char *d, *dend;
4984 /* Used sometimes to remember where we were before starting matching
4985 an operator so that we can go back in case of failure. This "atomic"
4986 behavior of matching opcodes is indispensable to the correctness
4987 of the on_failure_keep_string_jump optimization. */
4988 re_char *dfail;
4990 /* Where we are in the pattern, and the end of the pattern. */
4991 re_char *p = bufp->buffer;
4992 re_char *pend = p + bufp->used;
4994 /* We use this to map every character in the string. */
4995 RE_TRANSLATE_TYPE translate = bufp->translate;
4997 /* Nonzero if BUFP is setup from a multibyte regex. */
4998 const boolean multibyte = RE_MULTIBYTE_P (bufp);
5000 /* Nonzero if STRING1/STRING2 are multibyte. */
5001 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
5003 /* Failure point stack. Each place that can handle a failure further
5004 down the line pushes a failure point on this stack. It consists of
5005 regstart, and regend for all registers corresponding to
5006 the subexpressions we're currently inside, plus the number of such
5007 registers, and, finally, two char *'s. The first char * is where
5008 to resume scanning the pattern; the second one is where to resume
5009 scanning the strings. */
5010 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5011 fail_stack_type fail_stack;
5012 #endif
5013 #ifdef DEBUG
5014 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5015 #endif
5017 #if defined REL_ALLOC && defined REGEX_MALLOC
5018 /* This holds the pointer to the failure stack, when
5019 it is allocated relocatably. */
5020 fail_stack_elt_t *failure_stack_ptr;
5021 #endif
5023 /* We fill all the registers internally, independent of what we
5024 return, for use in backreferences. The number here includes
5025 an element for register zero. */
5026 size_t num_regs = bufp->re_nsub + 1;
5028 /* Information on the contents of registers. These are pointers into
5029 the input strings; they record just what was matched (on this
5030 attempt) by a subexpression part of the pattern, that is, the
5031 regnum-th regstart pointer points to where in the pattern we began
5032 matching and the regnum-th regend points to right after where we
5033 stopped matching the regnum-th subexpression. (The zeroth register
5034 keeps track of what the whole pattern matches.) */
5035 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5036 re_char **regstart, **regend;
5037 #endif
5039 /* The following record the register info as found in the above
5040 variables when we find a match better than any we've seen before.
5041 This happens as we backtrack through the failure points, which in
5042 turn happens only if we have not yet matched the entire string. */
5043 unsigned best_regs_set = false;
5044 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5045 re_char **best_regstart, **best_regend;
5046 #endif
5048 /* Logically, this is `best_regend[0]'. But we don't want to have to
5049 allocate space for that if we're not allocating space for anything
5050 else (see below). Also, we never need info about register 0 for
5051 any of the other register vectors, and it seems rather a kludge to
5052 treat `best_regend' differently than the rest. So we keep track of
5053 the end of the best match so far in a separate variable. We
5054 initialize this to NULL so that when we backtrack the first time
5055 and need to test it, it's not garbage. */
5056 re_char *match_end = NULL;
5058 #ifdef DEBUG
5059 /* Counts the total number of registers pushed. */
5060 unsigned num_regs_pushed = 0;
5061 #endif
5063 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5065 INIT_FAIL_STACK ();
5067 #ifdef MATCH_MAY_ALLOCATE
5068 /* Do not bother to initialize all the register variables if there are
5069 no groups in the pattern, as it takes a fair amount of time. If
5070 there are groups, we include space for register 0 (the whole
5071 pattern), even though we never use it, since it simplifies the
5072 array indexing. We should fix this. */
5073 if (bufp->re_nsub)
5075 regstart = REGEX_TALLOC (num_regs, re_char *);
5076 regend = REGEX_TALLOC (num_regs, re_char *);
5077 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5078 best_regend = REGEX_TALLOC (num_regs, re_char *);
5080 if (!(regstart && regend && best_regstart && best_regend))
5082 FREE_VARIABLES ();
5083 return -2;
5086 else
5088 /* We must initialize all our variables to NULL, so that
5089 `FREE_VARIABLES' doesn't try to free them. */
5090 regstart = regend = best_regstart = best_regend = NULL;
5092 #endif /* MATCH_MAY_ALLOCATE */
5094 /* The starting position is bogus. */
5095 if (pos < 0 || pos > size1 + size2)
5097 FREE_VARIABLES ();
5098 return -1;
5101 /* Initialize subexpression text positions to -1 to mark ones that no
5102 start_memory/stop_memory has been seen for. Also initialize the
5103 register information struct. */
5104 for (reg = 1; reg < num_regs; reg++)
5105 regstart[reg] = regend[reg] = NULL;
5107 /* We move `string1' into `string2' if the latter's empty -- but not if
5108 `string1' is null. */
5109 if (size2 == 0 && string1 != NULL)
5111 string2 = string1;
5112 size2 = size1;
5113 string1 = 0;
5114 size1 = 0;
5116 end1 = string1 + size1;
5117 end2 = string2 + size2;
5119 /* `p' scans through the pattern as `d' scans through the data.
5120 `dend' is the end of the input string that `d' points within. `d'
5121 is advanced into the following input string whenever necessary, but
5122 this happens before fetching; therefore, at the beginning of the
5123 loop, `d' can be pointing at the end of a string, but it cannot
5124 equal `string2'. */
5125 if (pos >= size1)
5127 /* Only match within string2. */
5128 d = string2 + pos - size1;
5129 dend = end_match_2 = string2 + stop - size1;
5130 end_match_1 = end1; /* Just to give it a value. */
5132 else
5134 if (stop < size1)
5136 /* Only match within string1. */
5137 end_match_1 = string1 + stop;
5138 /* BEWARE!
5139 When we reach end_match_1, PREFETCH normally switches to string2.
5140 But in the present case, this means that just doing a PREFETCH
5141 makes us jump from `stop' to `gap' within the string.
5142 What we really want here is for the search to stop as
5143 soon as we hit end_match_1. That's why we set end_match_2
5144 to end_match_1 (since PREFETCH fails as soon as we hit
5145 end_match_2). */
5146 end_match_2 = end_match_1;
5148 else
5149 { /* It's important to use this code when stop == size so that
5150 moving `d' from end1 to string2 will not prevent the d == dend
5151 check from catching the end of string. */
5152 end_match_1 = end1;
5153 end_match_2 = string2 + stop - size1;
5155 d = string1 + pos;
5156 dend = end_match_1;
5159 DEBUG_PRINT1 ("The compiled pattern is: ");
5160 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5161 DEBUG_PRINT1 ("The string to match is: `");
5162 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5163 DEBUG_PRINT1 ("'\n");
5165 /* This loops over pattern commands. It exits by returning from the
5166 function if the match is complete, or it drops through if the match
5167 fails at this starting point in the input data. */
5168 for (;;)
5170 DEBUG_PRINT2 ("\n%p: ", p);
5172 if (p == pend)
5173 { /* End of pattern means we might have succeeded. */
5174 DEBUG_PRINT1 ("end of pattern ... ");
5176 /* If we haven't matched the entire string, and we want the
5177 longest match, try backtracking. */
5178 if (d != end_match_2)
5180 /* 1 if this match ends in the same string (string1 or string2)
5181 as the best previous match. */
5182 boolean same_str_p = (FIRST_STRING_P (match_end)
5183 == FIRST_STRING_P (d));
5184 /* 1 if this match is the best seen so far. */
5185 boolean best_match_p;
5187 /* AIX compiler got confused when this was combined
5188 with the previous declaration. */
5189 if (same_str_p)
5190 best_match_p = d > match_end;
5191 else
5192 best_match_p = !FIRST_STRING_P (d);
5194 DEBUG_PRINT1 ("backtracking.\n");
5196 if (!FAIL_STACK_EMPTY ())
5197 { /* More failure points to try. */
5199 /* If exceeds best match so far, save it. */
5200 if (!best_regs_set || best_match_p)
5202 best_regs_set = true;
5203 match_end = d;
5205 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5207 for (reg = 1; reg < num_regs; reg++)
5209 best_regstart[reg] = regstart[reg];
5210 best_regend[reg] = regend[reg];
5213 goto fail;
5216 /* If no failure points, don't restore garbage. And if
5217 last match is real best match, don't restore second
5218 best one. */
5219 else if (best_regs_set && !best_match_p)
5221 restore_best_regs:
5222 /* Restore best match. It may happen that `dend ==
5223 end_match_1' while the restored d is in string2.
5224 For example, the pattern `x.*y.*z' against the
5225 strings `x-' and `y-z-', if the two strings are
5226 not consecutive in memory. */
5227 DEBUG_PRINT1 ("Restoring best registers.\n");
5229 d = match_end;
5230 dend = ((d >= string1 && d <= end1)
5231 ? end_match_1 : end_match_2);
5233 for (reg = 1; reg < num_regs; reg++)
5235 regstart[reg] = best_regstart[reg];
5236 regend[reg] = best_regend[reg];
5239 } /* d != end_match_2 */
5241 succeed_label:
5242 DEBUG_PRINT1 ("Accepting match.\n");
5244 /* If caller wants register contents data back, do it. */
5245 if (regs && !bufp->no_sub)
5247 /* Have the register data arrays been allocated? */
5248 if (bufp->regs_allocated == REGS_UNALLOCATED)
5249 { /* No. So allocate them with malloc. We need one
5250 extra element beyond `num_regs' for the `-1' marker
5251 GNU code uses. */
5252 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5253 regs->start = TALLOC (regs->num_regs, regoff_t);
5254 regs->end = TALLOC (regs->num_regs, regoff_t);
5255 if (regs->start == NULL || regs->end == NULL)
5257 FREE_VARIABLES ();
5258 return -2;
5260 bufp->regs_allocated = REGS_REALLOCATE;
5262 else if (bufp->regs_allocated == REGS_REALLOCATE)
5263 { /* Yes. If we need more elements than were already
5264 allocated, reallocate them. If we need fewer, just
5265 leave it alone. */
5266 if (regs->num_regs < num_regs + 1)
5268 regs->num_regs = num_regs + 1;
5269 RETALLOC (regs->start, regs->num_regs, regoff_t);
5270 RETALLOC (regs->end, regs->num_regs, regoff_t);
5271 if (regs->start == NULL || regs->end == NULL)
5273 FREE_VARIABLES ();
5274 return -2;
5278 else
5280 /* These braces fend off a "empty body in an else-statement"
5281 warning under GCC when assert expands to nothing. */
5282 assert (bufp->regs_allocated == REGS_FIXED);
5285 /* Convert the pointer data in `regstart' and `regend' to
5286 indices. Register zero has to be set differently,
5287 since we haven't kept track of any info for it. */
5288 if (regs->num_regs > 0)
5290 regs->start[0] = pos;
5291 regs->end[0] = POINTER_TO_OFFSET (d);
5294 /* Go through the first `min (num_regs, regs->num_regs)'
5295 registers, since that is all we initialized. */
5296 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
5298 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5299 regs->start[reg] = regs->end[reg] = -1;
5300 else
5302 regs->start[reg]
5303 = (regoff_t) POINTER_TO_OFFSET (regstart[reg]);
5304 regs->end[reg]
5305 = (regoff_t) POINTER_TO_OFFSET (regend[reg]);
5309 /* If the regs structure we return has more elements than
5310 were in the pattern, set the extra elements to -1. If
5311 we (re)allocated the registers, this is the case,
5312 because we always allocate enough to have at least one
5313 -1 at the end. */
5314 for (reg = num_regs; reg < regs->num_regs; reg++)
5315 regs->start[reg] = regs->end[reg] = -1;
5316 } /* regs && !bufp->no_sub */
5318 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5319 nfailure_points_pushed, nfailure_points_popped,
5320 nfailure_points_pushed - nfailure_points_popped);
5321 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5323 mcnt = POINTER_TO_OFFSET (d) - pos;
5325 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5327 FREE_VARIABLES ();
5328 return mcnt;
5331 /* Otherwise match next pattern command. */
5332 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5334 /* Ignore these. Used to ignore the n of succeed_n's which
5335 currently have n == 0. */
5336 case no_op:
5337 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5338 break;
5340 case succeed:
5341 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5342 goto succeed_label;
5344 /* Match the next n pattern characters exactly. The following
5345 byte in the pattern defines n, and the n bytes after that
5346 are the characters to match. */
5347 case exactn:
5348 mcnt = *p++;
5349 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5351 /* Remember the start point to rollback upon failure. */
5352 dfail = d;
5354 #ifndef emacs
5355 /* This is written out as an if-else so we don't waste time
5356 testing `translate' inside the loop. */
5357 if (RE_TRANSLATE_P (translate))
5360 PREFETCH ();
5361 if (RE_TRANSLATE (translate, *d) != *p++)
5363 d = dfail;
5364 goto fail;
5366 d++;
5368 while (--mcnt);
5369 else
5372 PREFETCH ();
5373 if (*d++ != *p++)
5375 d = dfail;
5376 goto fail;
5379 while (--mcnt);
5380 #else /* emacs */
5381 /* The cost of testing `translate' is comparatively small. */
5382 if (target_multibyte)
5385 int pat_charlen, buf_charlen;
5386 int pat_ch, buf_ch;
5388 PREFETCH ();
5389 if (multibyte)
5390 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5391 else
5393 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5394 pat_charlen = 1;
5396 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5398 if (TRANSLATE (buf_ch) != pat_ch)
5400 d = dfail;
5401 goto fail;
5404 p += pat_charlen;
5405 d += buf_charlen;
5406 mcnt -= pat_charlen;
5408 while (mcnt > 0);
5409 else
5412 int pat_charlen;
5413 int pat_ch, buf_ch;
5415 PREFETCH ();
5416 if (multibyte)
5418 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5419 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5421 else
5423 pat_ch = *p;
5424 pat_charlen = 1;
5426 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5427 if (! CHAR_BYTE8_P (buf_ch))
5429 buf_ch = TRANSLATE (buf_ch);
5430 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5431 if (buf_ch < 0)
5432 buf_ch = *d;
5434 else
5435 buf_ch = *d;
5436 if (buf_ch != pat_ch)
5438 d = dfail;
5439 goto fail;
5441 p += pat_charlen;
5442 d++;
5444 while (--mcnt);
5445 #endif
5446 break;
5449 /* Match any character except possibly a newline or a null. */
5450 case anychar:
5452 int buf_charlen;
5453 re_wchar_t buf_ch;
5455 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5457 PREFETCH ();
5458 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5459 target_multibyte);
5460 buf_ch = TRANSLATE (buf_ch);
5462 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5463 && buf_ch == '\n')
5464 || ((bufp->syntax & RE_DOT_NOT_NULL)
5465 && buf_ch == '\000'))
5466 goto fail;
5468 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
5469 d += buf_charlen;
5471 break;
5474 case charset:
5475 case charset_not:
5477 register unsigned int c;
5478 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5479 int len;
5481 /* Start of actual range_table, or end of bitmap if there is no
5482 range table. */
5483 re_char *range_table IF_LINT (= NULL);
5485 /* Nonzero if there is a range table. */
5486 int range_table_exists;
5488 /* Number of ranges of range table. This is not included
5489 in the initial byte-length of the command. */
5490 int count = 0;
5492 /* Whether matching against a unibyte character. */
5493 boolean unibyte_char = false;
5495 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5497 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5499 if (range_table_exists)
5501 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5502 EXTRACT_NUMBER_AND_INCR (count, range_table);
5505 PREFETCH ();
5506 c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5507 if (target_multibyte)
5509 int c1;
5511 c = TRANSLATE (c);
5512 c1 = RE_CHAR_TO_UNIBYTE (c);
5513 if (c1 >= 0)
5515 unibyte_char = true;
5516 c = c1;
5519 else
5521 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5523 if (! CHAR_BYTE8_P (c1))
5525 c1 = TRANSLATE (c1);
5526 c1 = RE_CHAR_TO_UNIBYTE (c1);
5527 if (c1 >= 0)
5529 unibyte_char = true;
5530 c = c1;
5533 else
5534 unibyte_char = true;
5537 if (unibyte_char && c < (1 << BYTEWIDTH))
5538 { /* Lookup bitmap. */
5539 /* Cast to `unsigned' instead of `unsigned char' in
5540 case the bit list is a full 32 bytes long. */
5541 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5542 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5543 not = !not;
5545 #ifdef emacs
5546 else if (range_table_exists)
5548 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5550 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5551 | (class_bits & BIT_MULTIBYTE)
5552 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5553 | (class_bits & BIT_SPACE && ISSPACE (c))
5554 | (class_bits & BIT_UPPER && ISUPPER (c))
5555 | (class_bits & BIT_WORD && ISWORD (c)))
5556 not = !not;
5557 else
5558 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5560 #endif /* emacs */
5562 if (range_table_exists)
5563 p = CHARSET_RANGE_TABLE_END (range_table, count);
5564 else
5565 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5567 if (!not) goto fail;
5569 d += len;
5571 break;
5574 /* The beginning of a group is represented by start_memory.
5575 The argument is the register number. The text
5576 matched within the group is recorded (in the internal
5577 registers data structure) under the register number. */
5578 case start_memory:
5579 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5581 /* In case we need to undo this operation (via backtracking). */
5582 PUSH_FAILURE_REG ((unsigned int)*p);
5584 regstart[*p] = d;
5585 regend[*p] = NULL; /* probably unnecessary. -sm */
5586 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5588 /* Move past the register number and inner group count. */
5589 p += 1;
5590 break;
5593 /* The stop_memory opcode represents the end of a group. Its
5594 argument is the same as start_memory's: the register number. */
5595 case stop_memory:
5596 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5598 assert (!REG_UNSET (regstart[*p]));
5599 /* Strictly speaking, there should be code such as:
5601 assert (REG_UNSET (regend[*p]));
5602 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5604 But the only info to be pushed is regend[*p] and it is known to
5605 be UNSET, so there really isn't anything to push.
5606 Not pushing anything, on the other hand deprives us from the
5607 guarantee that regend[*p] is UNSET since undoing this operation
5608 will not reset its value properly. This is not important since
5609 the value will only be read on the next start_memory or at
5610 the very end and both events can only happen if this stop_memory
5611 is *not* undone. */
5613 regend[*p] = d;
5614 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5616 /* Move past the register number and the inner group count. */
5617 p += 1;
5618 break;
5621 /* \<digit> has been turned into a `duplicate' command which is
5622 followed by the numeric value of <digit> as the register number. */
5623 case duplicate:
5625 register re_char *d2, *dend2;
5626 int regno = *p++; /* Get which register to match against. */
5627 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5629 /* Can't back reference a group which we've never matched. */
5630 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5631 goto fail;
5633 /* Where in input to try to start matching. */
5634 d2 = regstart[regno];
5636 /* Remember the start point to rollback upon failure. */
5637 dfail = d;
5639 /* Where to stop matching; if both the place to start and
5640 the place to stop matching are in the same string, then
5641 set to the place to stop, otherwise, for now have to use
5642 the end of the first string. */
5644 dend2 = ((FIRST_STRING_P (regstart[regno])
5645 == FIRST_STRING_P (regend[regno]))
5646 ? regend[regno] : end_match_1);
5647 for (;;)
5649 /* If necessary, advance to next segment in register
5650 contents. */
5651 while (d2 == dend2)
5653 if (dend2 == end_match_2) break;
5654 if (dend2 == regend[regno]) break;
5656 /* End of string1 => advance to string2. */
5657 d2 = string2;
5658 dend2 = regend[regno];
5660 /* At end of register contents => success */
5661 if (d2 == dend2) break;
5663 /* If necessary, advance to next segment in data. */
5664 PREFETCH ();
5666 /* How many characters left in this segment to match. */
5667 mcnt = dend - d;
5669 /* Want how many consecutive characters we can match in
5670 one shot, so, if necessary, adjust the count. */
5671 if (mcnt > dend2 - d2)
5672 mcnt = dend2 - d2;
5674 /* Compare that many; failure if mismatch, else move
5675 past them. */
5676 if (RE_TRANSLATE_P (translate)
5677 ? bcmp_translate (d, d2, mcnt, translate, target_multibyte)
5678 : memcmp (d, d2, mcnt))
5680 d = dfail;
5681 goto fail;
5683 d += mcnt, d2 += mcnt;
5686 break;
5689 /* begline matches the empty string at the beginning of the string
5690 (unless `not_bol' is set in `bufp'), and after newlines. */
5691 case begline:
5692 DEBUG_PRINT1 ("EXECUTING begline.\n");
5694 if (AT_STRINGS_BEG (d))
5696 if (!bufp->not_bol) break;
5698 else
5700 unsigned c;
5701 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5702 if (c == '\n')
5703 break;
5705 /* In all other cases, we fail. */
5706 goto fail;
5709 /* endline is the dual of begline. */
5710 case endline:
5711 DEBUG_PRINT1 ("EXECUTING endline.\n");
5713 if (AT_STRINGS_END (d))
5715 if (!bufp->not_eol) break;
5717 else
5719 PREFETCH_NOLIMIT ();
5720 if (*d == '\n')
5721 break;
5723 goto fail;
5726 /* Match at the very beginning of the data. */
5727 case begbuf:
5728 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5729 if (AT_STRINGS_BEG (d))
5730 break;
5731 goto fail;
5734 /* Match at the very end of the data. */
5735 case endbuf:
5736 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5737 if (AT_STRINGS_END (d))
5738 break;
5739 goto fail;
5742 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5743 pushes NULL as the value for the string on the stack. Then
5744 `POP_FAILURE_POINT' will keep the current value for the
5745 string, instead of restoring it. To see why, consider
5746 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5747 then the . fails against the \n. But the next thing we want
5748 to do is match the \n against the \n; if we restored the
5749 string value, we would be back at the foo.
5751 Because this is used only in specific cases, we don't need to
5752 check all the things that `on_failure_jump' does, to make
5753 sure the right things get saved on the stack. Hence we don't
5754 share its code. The only reason to push anything on the
5755 stack at all is that otherwise we would have to change
5756 `anychar's code to do something besides goto fail in this
5757 case; that seems worse than this. */
5758 case on_failure_keep_string_jump:
5759 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5760 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5761 mcnt, p + mcnt);
5763 PUSH_FAILURE_POINT (p - 3, NULL);
5764 break;
5766 /* A nasty loop is introduced by the non-greedy *? and +?.
5767 With such loops, the stack only ever contains one failure point
5768 at a time, so that a plain on_failure_jump_loop kind of
5769 cycle detection cannot work. Worse yet, such a detection
5770 can not only fail to detect a cycle, but it can also wrongly
5771 detect a cycle (between different instantiations of the same
5772 loop).
5773 So the method used for those nasty loops is a little different:
5774 We use a special cycle-detection-stack-frame which is pushed
5775 when the on_failure_jump_nastyloop failure-point is *popped*.
5776 This special frame thus marks the beginning of one iteration
5777 through the loop and we can hence easily check right here
5778 whether something matched between the beginning and the end of
5779 the loop. */
5780 case on_failure_jump_nastyloop:
5781 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5782 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5783 mcnt, p + mcnt);
5785 assert ((re_opcode_t)p[-4] == no_op);
5787 int cycle = 0;
5788 CHECK_INFINITE_LOOP (p - 4, d);
5789 if (!cycle)
5790 /* If there's a cycle, just continue without pushing
5791 this failure point. The failure point is the "try again"
5792 option, which shouldn't be tried.
5793 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5794 PUSH_FAILURE_POINT (p - 3, d);
5796 break;
5798 /* Simple loop detecting on_failure_jump: just check on the
5799 failure stack if the same spot was already hit earlier. */
5800 case on_failure_jump_loop:
5801 on_failure:
5802 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5803 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5804 mcnt, p + mcnt);
5806 int cycle = 0;
5807 CHECK_INFINITE_LOOP (p - 3, d);
5808 if (cycle)
5809 /* If there's a cycle, get out of the loop, as if the matching
5810 had failed. We used to just `goto fail' here, but that was
5811 aborting the search a bit too early: we want to keep the
5812 empty-loop-match and keep matching after the loop.
5813 We want (x?)*y\1z to match both xxyz and xxyxz. */
5814 p += mcnt;
5815 else
5816 PUSH_FAILURE_POINT (p - 3, d);
5818 break;
5821 /* Uses of on_failure_jump:
5823 Each alternative starts with an on_failure_jump that points
5824 to the beginning of the next alternative. Each alternative
5825 except the last ends with a jump that in effect jumps past
5826 the rest of the alternatives. (They really jump to the
5827 ending jump of the following alternative, because tensioning
5828 these jumps is a hassle.)
5830 Repeats start with an on_failure_jump that points past both
5831 the repetition text and either the following jump or
5832 pop_failure_jump back to this on_failure_jump. */
5833 case on_failure_jump:
5834 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5835 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5836 mcnt, p + mcnt);
5838 PUSH_FAILURE_POINT (p -3, d);
5839 break;
5841 /* This operation is used for greedy *.
5842 Compare the beginning of the repeat with what in the
5843 pattern follows its end. If we can establish that there
5844 is nothing that they would both match, i.e., that we
5845 would have to backtrack because of (as in, e.g., `a*a')
5846 then we can use a non-backtracking loop based on
5847 on_failure_keep_string_jump instead of on_failure_jump. */
5848 case on_failure_jump_smart:
5849 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5850 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5851 mcnt, p + mcnt);
5853 re_char *p1 = p; /* Next operation. */
5854 /* Here, we discard `const', making re_match non-reentrant. */
5855 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5856 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5858 p -= 3; /* Reset so that we will re-execute the
5859 instruction once it's been changed. */
5861 EXTRACT_NUMBER (mcnt, p2 - 2);
5863 /* Ensure this is a indeed the trivial kind of loop
5864 we are expecting. */
5865 assert (skip_one_char (p1) == p2 - 3);
5866 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5867 DEBUG_STATEMENT (debug += 2);
5868 if (mutually_exclusive_p (bufp, p1, p2))
5870 /* Use a fast `on_failure_keep_string_jump' loop. */
5871 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5872 *p3 = (unsigned char) on_failure_keep_string_jump;
5873 STORE_NUMBER (p2 - 2, mcnt + 3);
5875 else
5877 /* Default to a safe `on_failure_jump' loop. */
5878 DEBUG_PRINT1 (" smart default => slow loop.\n");
5879 *p3 = (unsigned char) on_failure_jump;
5881 DEBUG_STATEMENT (debug -= 2);
5883 break;
5885 /* Unconditionally jump (without popping any failure points). */
5886 case jump:
5887 unconditional_jump:
5888 IMMEDIATE_QUIT_CHECK;
5889 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5890 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5891 p += mcnt; /* Do the jump. */
5892 DEBUG_PRINT2 ("(to %p).\n", p);
5893 break;
5896 /* Have to succeed matching what follows at least n times.
5897 After that, handle like `on_failure_jump'. */
5898 case succeed_n:
5899 /* Signedness doesn't matter since we only compare MCNT to 0. */
5900 EXTRACT_NUMBER (mcnt, p + 2);
5901 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5903 /* Originally, mcnt is how many times we HAVE to succeed. */
5904 if (mcnt != 0)
5906 /* Here, we discard `const', making re_match non-reentrant. */
5907 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5908 mcnt--;
5909 p += 4;
5910 PUSH_NUMBER (p2, mcnt);
5912 else
5913 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5914 goto on_failure;
5915 break;
5917 case jump_n:
5918 /* Signedness doesn't matter since we only compare MCNT to 0. */
5919 EXTRACT_NUMBER (mcnt, p + 2);
5920 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5922 /* Originally, this is how many times we CAN jump. */
5923 if (mcnt != 0)
5925 /* Here, we discard `const', making re_match non-reentrant. */
5926 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5927 mcnt--;
5928 PUSH_NUMBER (p2, mcnt);
5929 goto unconditional_jump;
5931 /* If don't have to jump any more, skip over the rest of command. */
5932 else
5933 p += 4;
5934 break;
5936 case set_number_at:
5938 unsigned char *p2; /* Location of the counter. */
5939 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5941 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5942 /* Here, we discard `const', making re_match non-reentrant. */
5943 p2 = (unsigned char*) p + mcnt;
5944 /* Signedness doesn't matter since we only copy MCNT's bits . */
5945 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5946 DEBUG_PRINT3 (" Setting %p to %d.\n", p2, mcnt);
5947 PUSH_NUMBER (p2, mcnt);
5948 break;
5951 case wordbound:
5952 case notwordbound:
5954 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5955 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5957 /* We SUCCEED (or FAIL) in one of the following cases: */
5959 /* Case 1: D is at the beginning or the end of string. */
5960 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5961 not = !not;
5962 else
5964 /* C1 is the character before D, S1 is the syntax of C1, C2
5965 is the character at D, and S2 is the syntax of C2. */
5966 re_wchar_t c1, c2;
5967 int s1, s2;
5968 int dummy;
5969 #ifdef emacs
5970 ssize_t offset = PTR_TO_OFFSET (d - 1);
5971 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5972 UPDATE_SYNTAX_TABLE (charpos);
5973 #endif
5974 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5975 s1 = SYNTAX (c1);
5976 #ifdef emacs
5977 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5978 #endif
5979 PREFETCH_NOLIMIT ();
5980 GET_CHAR_AFTER (c2, d, dummy);
5981 s2 = SYNTAX (c2);
5983 if (/* Case 2: Only one of S1 and S2 is Sword. */
5984 ((s1 == Sword) != (s2 == Sword))
5985 /* Case 3: Both of S1 and S2 are Sword, and macro
5986 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5987 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5988 not = !not;
5990 if (not)
5991 break;
5992 else
5993 goto fail;
5996 case wordbeg:
5997 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5999 /* We FAIL in one of the following cases: */
6001 /* Case 1: D is at the end of string. */
6002 if (AT_STRINGS_END (d))
6003 goto fail;
6004 else
6006 /* C1 is the character before D, S1 is the syntax of C1, C2
6007 is the character at D, and S2 is the syntax of C2. */
6008 re_wchar_t c1, c2;
6009 int s1, s2;
6010 int dummy;
6011 #ifdef emacs
6012 ssize_t offset = PTR_TO_OFFSET (d);
6013 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6014 UPDATE_SYNTAX_TABLE (charpos);
6015 #endif
6016 PREFETCH ();
6017 GET_CHAR_AFTER (c2, d, dummy);
6018 s2 = SYNTAX (c2);
6020 /* Case 2: S2 is not Sword. */
6021 if (s2 != Sword)
6022 goto fail;
6024 /* Case 3: D is not at the beginning of string ... */
6025 if (!AT_STRINGS_BEG (d))
6027 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6028 #ifdef emacs
6029 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6030 #endif
6031 s1 = SYNTAX (c1);
6033 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6034 returns 0. */
6035 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6036 goto fail;
6039 break;
6041 case wordend:
6042 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6044 /* We FAIL in one of the following cases: */
6046 /* Case 1: D is at the beginning of string. */
6047 if (AT_STRINGS_BEG (d))
6048 goto fail;
6049 else
6051 /* C1 is the character before D, S1 is the syntax of C1, C2
6052 is the character at D, and S2 is the syntax of C2. */
6053 re_wchar_t c1, c2;
6054 int s1, s2;
6055 int dummy;
6056 #ifdef emacs
6057 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6058 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6059 UPDATE_SYNTAX_TABLE (charpos);
6060 #endif
6061 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6062 s1 = SYNTAX (c1);
6064 /* Case 2: S1 is not Sword. */
6065 if (s1 != Sword)
6066 goto fail;
6068 /* Case 3: D is not at the end of string ... */
6069 if (!AT_STRINGS_END (d))
6071 PREFETCH_NOLIMIT ();
6072 GET_CHAR_AFTER (c2, d, dummy);
6073 #ifdef emacs
6074 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
6075 #endif
6076 s2 = SYNTAX (c2);
6078 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6079 returns 0. */
6080 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6081 goto fail;
6084 break;
6086 case symbeg:
6087 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6089 /* We FAIL in one of the following cases: */
6091 /* Case 1: D is at the end of string. */
6092 if (AT_STRINGS_END (d))
6093 goto fail;
6094 else
6096 /* C1 is the character before D, S1 is the syntax of C1, C2
6097 is the character at D, and S2 is the syntax of C2. */
6098 re_wchar_t c1, c2;
6099 int s1, s2;
6100 #ifdef emacs
6101 ssize_t offset = PTR_TO_OFFSET (d);
6102 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6103 UPDATE_SYNTAX_TABLE (charpos);
6104 #endif
6105 PREFETCH ();
6106 c2 = RE_STRING_CHAR (d, target_multibyte);
6107 s2 = SYNTAX (c2);
6109 /* Case 2: S2 is neither Sword nor Ssymbol. */
6110 if (s2 != Sword && s2 != Ssymbol)
6111 goto fail;
6113 /* Case 3: D is not at the beginning of string ... */
6114 if (!AT_STRINGS_BEG (d))
6116 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6117 #ifdef emacs
6118 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6119 #endif
6120 s1 = SYNTAX (c1);
6122 /* ... and S1 is Sword or Ssymbol. */
6123 if (s1 == Sword || s1 == Ssymbol)
6124 goto fail;
6127 break;
6129 case symend:
6130 DEBUG_PRINT1 ("EXECUTING symend.\n");
6132 /* We FAIL in one of the following cases: */
6134 /* Case 1: D is at the beginning of string. */
6135 if (AT_STRINGS_BEG (d))
6136 goto fail;
6137 else
6139 /* C1 is the character before D, S1 is the syntax of C1, C2
6140 is the character at D, and S2 is the syntax of C2. */
6141 re_wchar_t c1, c2;
6142 int s1, s2;
6143 #ifdef emacs
6144 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6145 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6146 UPDATE_SYNTAX_TABLE (charpos);
6147 #endif
6148 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6149 s1 = SYNTAX (c1);
6151 /* Case 2: S1 is neither Ssymbol nor Sword. */
6152 if (s1 != Sword && s1 != Ssymbol)
6153 goto fail;
6155 /* Case 3: D is not at the end of string ... */
6156 if (!AT_STRINGS_END (d))
6158 PREFETCH_NOLIMIT ();
6159 c2 = RE_STRING_CHAR (d, target_multibyte);
6160 #ifdef emacs
6161 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6162 #endif
6163 s2 = SYNTAX (c2);
6165 /* ... and S2 is Sword or Ssymbol. */
6166 if (s2 == Sword || s2 == Ssymbol)
6167 goto fail;
6170 break;
6172 case syntaxspec:
6173 case notsyntaxspec:
6175 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6176 mcnt = *p++;
6177 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
6178 PREFETCH ();
6179 #ifdef emacs
6181 ssize_t offset = PTR_TO_OFFSET (d);
6182 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6183 UPDATE_SYNTAX_TABLE (pos1);
6185 #endif
6187 int len;
6188 re_wchar_t c;
6190 GET_CHAR_AFTER (c, d, len);
6191 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6192 goto fail;
6193 d += len;
6196 break;
6198 #ifdef emacs
6199 case before_dot:
6200 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6201 if (PTR_BYTE_POS (d) >= PT_BYTE)
6202 goto fail;
6203 break;
6205 case at_dot:
6206 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6207 if (PTR_BYTE_POS (d) != PT_BYTE)
6208 goto fail;
6209 break;
6211 case after_dot:
6212 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6213 if (PTR_BYTE_POS (d) <= PT_BYTE)
6214 goto fail;
6215 break;
6217 case categoryspec:
6218 case notcategoryspec:
6220 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6221 mcnt = *p++;
6222 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n",
6223 not?"not":"", mcnt);
6224 PREFETCH ();
6227 int len;
6228 re_wchar_t c;
6229 GET_CHAR_AFTER (c, d, len);
6230 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6231 goto fail;
6232 d += len;
6235 break;
6237 #endif /* emacs */
6239 default:
6240 abort ();
6242 continue; /* Successfully executed one pattern command; keep going. */
6245 /* We goto here if a matching operation fails. */
6246 fail:
6247 IMMEDIATE_QUIT_CHECK;
6248 if (!FAIL_STACK_EMPTY ())
6250 re_char *str, *pat;
6251 /* A restart point is known. Restore to that state. */
6252 DEBUG_PRINT1 ("\nFAIL:\n");
6253 POP_FAILURE_POINT (str, pat);
6254 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
6256 case on_failure_keep_string_jump:
6257 assert (str == NULL);
6258 goto continue_failure_jump;
6260 case on_failure_jump_nastyloop:
6261 assert ((re_opcode_t)pat[-2] == no_op);
6262 PUSH_FAILURE_POINT (pat - 2, str);
6263 /* Fallthrough */
6265 case on_failure_jump_loop:
6266 case on_failure_jump:
6267 case succeed_n:
6268 d = str;
6269 continue_failure_jump:
6270 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6271 p = pat + mcnt;
6272 break;
6274 case no_op:
6275 /* A special frame used for nastyloops. */
6276 goto fail;
6278 default:
6279 abort();
6282 assert (p >= bufp->buffer && p <= pend);
6284 if (d >= string1 && d <= end1)
6285 dend = end_match_1;
6287 else
6288 break; /* Matching at this starting point really fails. */
6289 } /* for (;;) */
6291 if (best_regs_set)
6292 goto restore_best_regs;
6294 FREE_VARIABLES ();
6296 return -1; /* Failure to match. */
6297 } /* re_match_2 */
6299 /* Subroutine definitions for re_match_2. */
6301 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6302 bytes; nonzero otherwise. */
6304 static int
6305 bcmp_translate (const re_char *s1, const re_char *s2, register ssize_t len,
6306 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6308 register re_char *p1 = s1, *p2 = s2;
6309 re_char *p1_end = s1 + len;
6310 re_char *p2_end = s2 + len;
6312 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6313 different lengths, but relying on a single `len' would break this. -sm */
6314 while (p1 < p1_end && p2 < p2_end)
6316 int p1_charlen, p2_charlen;
6317 re_wchar_t p1_ch, p2_ch;
6319 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6320 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6322 if (RE_TRANSLATE (translate, p1_ch)
6323 != RE_TRANSLATE (translate, p2_ch))
6324 return 1;
6326 p1 += p1_charlen, p2 += p2_charlen;
6329 if (p1 != p1_end || p2 != p2_end)
6330 return 1;
6332 return 0;
6335 /* Entry points for GNU code. */
6337 /* re_compile_pattern is the GNU regular expression compiler: it
6338 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6339 Returns 0 if the pattern was valid, otherwise an error string.
6341 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6342 are set in BUFP on entry.
6344 We call regex_compile to do the actual compilation. */
6346 const char *
6347 re_compile_pattern (const char *pattern, size_t length,
6348 struct re_pattern_buffer *bufp)
6350 reg_errcode_t ret;
6352 /* GNU code is written to assume at least RE_NREGS registers will be set
6353 (and at least one extra will be -1). */
6354 bufp->regs_allocated = REGS_UNALLOCATED;
6356 /* And GNU code determines whether or not to get register information
6357 by passing null for the REGS argument to re_match, etc., not by
6358 setting no_sub. */
6359 bufp->no_sub = 0;
6361 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
6363 if (!ret)
6364 return NULL;
6365 return gettext (re_error_msgid[(int) ret]);
6367 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6369 /* Entry points compatible with 4.2 BSD regex library. We don't define
6370 them unless specifically requested. */
6372 #if defined _REGEX_RE_COMP || defined _LIBC
6374 /* BSD has one and only one pattern buffer. */
6375 static struct re_pattern_buffer re_comp_buf;
6377 char *
6378 # ifdef _LIBC
6379 /* Make these definitions weak in libc, so POSIX programs can redefine
6380 these names if they don't use our functions, and still use
6381 regcomp/regexec below without link errors. */
6382 weak_function
6383 # endif
6384 re_comp (const char *s)
6386 reg_errcode_t ret;
6388 if (!s)
6390 if (!re_comp_buf.buffer)
6391 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6392 return (char *) gettext ("No previous regular expression");
6393 return 0;
6396 if (!re_comp_buf.buffer)
6398 re_comp_buf.buffer = (unsigned char *) malloc (200);
6399 if (re_comp_buf.buffer == NULL)
6400 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6401 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6402 re_comp_buf.allocated = 200;
6404 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6405 if (re_comp_buf.fastmap == NULL)
6406 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6407 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6410 /* Since `re_exec' always passes NULL for the `regs' argument, we
6411 don't need to initialize the pattern buffer fields which affect it. */
6413 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6415 if (!ret)
6416 return NULL;
6418 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6419 return (char *) gettext (re_error_msgid[(int) ret]);
6424 # ifdef _LIBC
6425 weak_function
6426 # endif
6427 re_exec (const char *s)
6429 const size_t len = strlen (s);
6430 return
6431 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6433 #endif /* _REGEX_RE_COMP */
6435 /* POSIX.2 functions. Don't define these for Emacs. */
6437 #ifndef emacs
6439 /* regcomp takes a regular expression as a string and compiles it.
6441 PREG is a regex_t *. We do not expect any fields to be initialized,
6442 since POSIX says we shouldn't. Thus, we set
6444 `buffer' to the compiled pattern;
6445 `used' to the length of the compiled pattern;
6446 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6447 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6448 RE_SYNTAX_POSIX_BASIC;
6449 `fastmap' to an allocated space for the fastmap;
6450 `fastmap_accurate' to zero;
6451 `re_nsub' to the number of subexpressions in PATTERN.
6453 PATTERN is the address of the pattern string.
6455 CFLAGS is a series of bits which affect compilation.
6457 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6458 use POSIX basic syntax.
6460 If REG_NEWLINE is set, then . and [^...] don't match newline.
6461 Also, regexec will try a match beginning after every newline.
6463 If REG_ICASE is set, then we considers upper- and lowercase
6464 versions of letters to be equivalent when matching.
6466 If REG_NOSUB is set, then when PREG is passed to regexec, that
6467 routine will report only success or failure, and nothing about the
6468 registers.
6470 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6471 the return codes and their meanings.) */
6473 reg_errcode_t
6474 regcomp (regex_t *__restrict preg, const char *__restrict pattern,
6475 int cflags)
6477 reg_errcode_t ret;
6478 reg_syntax_t syntax
6479 = (cflags & REG_EXTENDED) ?
6480 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6482 /* regex_compile will allocate the space for the compiled pattern. */
6483 preg->buffer = 0;
6484 preg->allocated = 0;
6485 preg->used = 0;
6487 /* Try to allocate space for the fastmap. */
6488 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
6490 if (cflags & REG_ICASE)
6492 unsigned i;
6494 preg->translate
6495 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6496 * sizeof (*(RE_TRANSLATE_TYPE)0));
6497 if (preg->translate == NULL)
6498 return (int) REG_ESPACE;
6500 /* Map uppercase characters to corresponding lowercase ones. */
6501 for (i = 0; i < CHAR_SET_SIZE; i++)
6502 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6504 else
6505 preg->translate = NULL;
6507 /* If REG_NEWLINE is set, newlines are treated differently. */
6508 if (cflags & REG_NEWLINE)
6509 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6510 syntax &= ~RE_DOT_NEWLINE;
6511 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6513 else
6514 syntax |= RE_NO_NEWLINE_ANCHOR;
6516 preg->no_sub = !!(cflags & REG_NOSUB);
6518 /* POSIX says a null character in the pattern terminates it, so we
6519 can use strlen here in compiling the pattern. */
6520 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6522 /* POSIX doesn't distinguish between an unmatched open-group and an
6523 unmatched close-group: both are REG_EPAREN. */
6524 if (ret == REG_ERPAREN)
6525 ret = REG_EPAREN;
6527 if (ret == REG_NOERROR && preg->fastmap)
6528 { /* Compute the fastmap now, since regexec cannot modify the pattern
6529 buffer. */
6530 re_compile_fastmap (preg);
6531 if (preg->can_be_null)
6532 { /* The fastmap can't be used anyway. */
6533 free (preg->fastmap);
6534 preg->fastmap = NULL;
6537 return ret;
6539 WEAK_ALIAS (__regcomp, regcomp)
6542 /* regexec searches for a given pattern, specified by PREG, in the
6543 string STRING.
6545 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6546 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6547 least NMATCH elements, and we set them to the offsets of the
6548 corresponding matched substrings.
6550 EFLAGS specifies `execution flags' which affect matching: if
6551 REG_NOTBOL is set, then ^ does not match at the beginning of the
6552 string; if REG_NOTEOL is set, then $ does not match at the end.
6554 We return 0 if we find a match and REG_NOMATCH if not. */
6556 reg_errcode_t
6557 regexec (const regex_t *__restrict preg, const char *__restrict string,
6558 size_t nmatch, regmatch_t pmatch[__restrict_arr], int eflags)
6560 regoff_t ret;
6561 struct re_registers regs;
6562 regex_t private_preg;
6563 size_t len = strlen (string);
6564 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6566 private_preg = *preg;
6568 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6569 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6571 /* The user has told us exactly how many registers to return
6572 information about, via `nmatch'. We have to pass that on to the
6573 matching routines. */
6574 private_preg.regs_allocated = REGS_FIXED;
6576 if (want_reg_info)
6578 regs.num_regs = nmatch;
6579 regs.start = TALLOC (nmatch * 2, regoff_t);
6580 if (regs.start == NULL)
6581 return REG_NOMATCH;
6582 regs.end = regs.start + nmatch;
6585 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6586 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6587 was a little bit longer but still only matching the real part.
6588 This works because the `endline' will check for a '\n' and will find a
6589 '\0', correctly deciding that this is not the end of a line.
6590 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6591 a convenient '\0' there. For all we know, the string could be preceded
6592 by '\n' which would throw things off. */
6594 /* Perform the searching operation. */
6595 ret = re_search (&private_preg, string, len,
6596 /* start: */ 0, /* range: */ len,
6597 want_reg_info ? &regs : (struct re_registers *) 0);
6599 /* Copy the register information to the POSIX structure. */
6600 if (want_reg_info)
6602 if (ret >= 0)
6604 unsigned r;
6606 for (r = 0; r < nmatch; r++)
6608 pmatch[r].rm_so = regs.start[r];
6609 pmatch[r].rm_eo = regs.end[r];
6613 /* If we needed the temporary register info, free the space now. */
6614 free (regs.start);
6617 /* We want zero return to mean success, unlike `re_search'. */
6618 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6620 WEAK_ALIAS (__regexec, regexec)
6623 /* Returns a message corresponding to an error code, ERR_CODE, returned
6624 from either regcomp or regexec. We don't use PREG here.
6626 ERR_CODE was previously called ERRCODE, but that name causes an
6627 error with msvc8 compiler. */
6629 size_t
6630 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6632 const char *msg;
6633 size_t msg_size;
6635 if (err_code < 0
6636 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6637 /* Only error codes returned by the rest of the code should be passed
6638 to this routine. If we are given anything else, or if other regex
6639 code generates an invalid error code, then the program has a bug.
6640 Dump core so we can fix it. */
6641 abort ();
6643 msg = gettext (re_error_msgid[err_code]);
6645 msg_size = strlen (msg) + 1; /* Includes the null. */
6647 if (errbuf_size != 0)
6649 if (msg_size > errbuf_size)
6651 strncpy (errbuf, msg, errbuf_size - 1);
6652 errbuf[errbuf_size - 1] = 0;
6654 else
6655 strcpy (errbuf, msg);
6658 return msg_size;
6660 WEAK_ALIAS (__regerror, regerror)
6663 /* Free dynamically allocated space used by PREG. */
6665 void
6666 regfree (regex_t *preg)
6668 free (preg->buffer);
6669 preg->buffer = NULL;
6671 preg->allocated = 0;
6672 preg->used = 0;
6674 free (preg->fastmap);
6675 preg->fastmap = NULL;
6676 preg->fastmap_accurate = 0;
6678 free (preg->translate);
6679 preg->translate = NULL;
6681 WEAK_ALIAS (__regfree, regfree)
6683 #endif /* not emacs */