add test case for I/O switching
[emacs.git] / src / regex.c
blobb995538e30dd5bdf99b56cbc77727c65fb6b4ef8
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-2012 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 /* Ignore some GCC warnings for now. This section should go away
37 once the Emacs and Gnulib regex code is merged. */
38 #if (__GNUC__ == 4 && 5 <= __GNUC_MINOR__) || 4 < __GNUC__
39 # pragma GCC diagnostic ignored "-Wstrict-overflow"
40 # ifndef emacs
41 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
42 # pragma GCC diagnostic ignored "-Wunused-function"
43 # pragma GCC diagnostic ignored "-Wunused-macros"
44 # pragma GCC diagnostic ignored "-Wunused-result"
45 # pragma GCC diagnostic ignored "-Wunused-variable"
46 # endif
47 #endif
49 #include <config.h>
51 #include <stddef.h>
53 #ifdef emacs
54 /* We need this for `regex.h', and perhaps for the Emacs include files. */
55 # include <sys/types.h>
56 #endif
58 /* Whether to use ISO C Amendment 1 wide char functions.
59 Those should not be used for Emacs since it uses its own. */
60 #if defined _LIBC
61 #define WIDE_CHAR_SUPPORT 1
62 #else
63 #define WIDE_CHAR_SUPPORT \
64 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
65 #endif
67 /* For platform which support the ISO C amendment 1 functionality we
68 support user defined character classes. */
69 #if WIDE_CHAR_SUPPORT
70 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
71 # include <wchar.h>
72 # include <wctype.h>
73 #endif
75 #ifdef _LIBC
76 /* We have to keep the namespace clean. */
77 # define regfree(preg) __regfree (preg)
78 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
79 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
80 # define regerror(err_code, preg, errbuf, errbuf_size) \
81 __regerror (err_code, preg, errbuf, errbuf_size)
82 # define re_set_registers(bu, re, nu, st, en) \
83 __re_set_registers (bu, re, nu, st, en)
84 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
85 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
86 # define re_match(bufp, string, size, pos, regs) \
87 __re_match (bufp, string, size, pos, regs)
88 # define re_search(bufp, string, size, startpos, range, regs) \
89 __re_search (bufp, string, size, startpos, range, regs)
90 # define re_compile_pattern(pattern, length, bufp) \
91 __re_compile_pattern (pattern, length, bufp)
92 # define re_set_syntax(syntax) __re_set_syntax (syntax)
93 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
94 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
95 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
97 /* Make sure we call libc's function even if the user overrides them. */
98 # define btowc __btowc
99 # define iswctype __iswctype
100 # define wctype __wctype
102 # define WEAK_ALIAS(a,b) weak_alias (a, b)
104 /* We are also using some library internals. */
105 # include <locale/localeinfo.h>
106 # include <locale/elem-hash.h>
107 # include <langinfo.h>
108 #else
109 # define WEAK_ALIAS(a,b)
110 #endif
112 /* This is for other GNU distributions with internationalized messages. */
113 #if HAVE_LIBINTL_H || defined _LIBC
114 # include <libintl.h>
115 #else
116 # define gettext(msgid) (msgid)
117 #endif
119 #ifndef gettext_noop
120 /* This define is so xgettext can find the internationalizable
121 strings. */
122 # define gettext_noop(String) String
123 #endif
125 /* The `emacs' switch turns on certain matching commands
126 that make sense only in Emacs. */
127 #ifdef emacs
129 # include <setjmp.h>
130 # include "lisp.h"
131 # include "character.h"
132 # include "buffer.h"
134 /* Make syntax table lookup grant data in gl_state. */
135 # define SYNTAX_ENTRY_VIA_PROPERTY
137 # include "syntax.h"
138 # include "category.h"
140 # ifdef malloc
141 # undef malloc
142 # endif
143 # define malloc xmalloc
144 # ifdef realloc
145 # undef realloc
146 # endif
147 # define realloc xrealloc
148 # ifdef free
149 # undef free
150 # endif
151 # define free xfree
153 /* Converts the pointer to the char to BEG-based offset from the start. */
154 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
155 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
157 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
158 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
159 # define RE_STRING_CHAR(p, multibyte) \
160 (multibyte ? (STRING_CHAR (p)) : (*(p)))
161 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
162 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
164 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
166 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
168 /* Set C a (possibly converted to multibyte) character before P. P
169 points into a string which is the virtual concatenation of STR1
170 (which ends at END1) or STR2 (which ends at END2). */
171 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
172 do { \
173 if (target_multibyte) \
175 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
176 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
177 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
178 c = STRING_CHAR (dtemp); \
180 else \
182 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
183 (c) = RE_CHAR_TO_MULTIBYTE (c); \
185 } while (0)
187 /* Set C a (possibly converted to multibyte) character at P, and set
188 LEN to the byte length of that character. */
189 # define GET_CHAR_AFTER(c, p, len) \
190 do { \
191 if (target_multibyte) \
192 (c) = STRING_CHAR_AND_LENGTH (p, len); \
193 else \
195 (c) = *p; \
196 len = 1; \
197 (c) = RE_CHAR_TO_MULTIBYTE (c); \
199 } while (0)
201 #else /* not emacs */
203 /* If we are not linking with Emacs proper,
204 we can't use the relocating allocator
205 even if config.h says that we can. */
206 # undef REL_ALLOC
208 # include <unistd.h>
210 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
212 static void *
213 xmalloc (size_t size)
215 void *val = malloc (size);
216 if (!val && size)
218 write (2, "virtual memory exhausted\n", 25);
219 exit (1);
221 return val;
224 static void *
225 xrealloc (void *block, size_t size)
227 void *val;
228 /* We must call malloc explicitly when BLOCK is 0, since some
229 reallocs don't do this. */
230 if (! block)
231 val = malloc (size);
232 else
233 val = realloc (block, size);
234 if (!val && size)
236 write (2, "virtual memory exhausted\n", 25);
237 exit (1);
239 return val;
242 # ifdef malloc
243 # undef malloc
244 # endif
245 # define malloc xmalloc
246 # ifdef realloc
247 # undef realloc
248 # endif
249 # define realloc xrealloc
251 # include <stdbool.h>
252 # include <string.h>
254 /* Define the syntax stuff for \<, \>, etc. */
256 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
257 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
259 /* Dummy macros for non-Emacs environments. */
260 # define CHAR_CHARSET(c) 0
261 # define CHARSET_LEADING_CODE_BASE(c) 0
262 # define MAX_MULTIBYTE_LENGTH 1
263 # define RE_MULTIBYTE_P(x) 0
264 # define RE_TARGET_MULTIBYTE_P(x) 0
265 # define WORD_BOUNDARY_P(c1, c2) (0)
266 # define CHAR_HEAD_P(p) (1)
267 # define SINGLE_BYTE_CHAR_P(c) (1)
268 # define SAME_CHARSET_P(c1, c2) (1)
269 # define BYTES_BY_CHAR_HEAD(p) (1)
270 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
271 # define STRING_CHAR(p) (*(p))
272 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
273 # define CHAR_STRING(c, s) (*(s) = (c), 1)
274 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
275 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
276 # define RE_CHAR_TO_MULTIBYTE(c) (c)
277 # define RE_CHAR_TO_UNIBYTE(c) (c)
278 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
279 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
280 # define GET_CHAR_AFTER(c, p, len) \
281 (c = *p, len = 1)
282 # define MAKE_CHAR(charset, c1, c2) (c1)
283 # define BYTE8_TO_CHAR(c) (c)
284 # define CHAR_BYTE8_P(c) (0)
285 # define CHAR_LEADING_CODE(c) (c)
287 #endif /* not emacs */
289 #ifndef RE_TRANSLATE
290 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
291 # define RE_TRANSLATE_P(TBL) (TBL)
292 #endif
294 /* Get the interface, including the syntax bits. */
295 #include "regex.h"
297 /* isalpha etc. are used for the character classes. */
298 #include <ctype.h>
300 #ifdef emacs
302 /* 1 if C is an ASCII character. */
303 # define IS_REAL_ASCII(c) ((c) < 0200)
305 /* 1 if C is a unibyte character. */
306 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
308 /* The Emacs definitions should not be directly affected by locales. */
310 /* In Emacs, these are only used for single-byte characters. */
311 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
312 # define ISCNTRL(c) ((c) < ' ')
313 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
314 || ((c) >= 'a' && (c) <= 'f') \
315 || ((c) >= 'A' && (c) <= 'F'))
317 /* This is only used for single-byte characters. */
318 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
320 /* The rest must handle multibyte characters. */
322 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
323 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
324 : 1)
326 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
327 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
328 : 1)
330 # define ISALNUM(c) (IS_REAL_ASCII (c) \
331 ? (((c) >= 'a' && (c) <= 'z') \
332 || ((c) >= 'A' && (c) <= 'Z') \
333 || ((c) >= '0' && (c) <= '9')) \
334 : SYNTAX (c) == Sword)
336 # define ISALPHA(c) (IS_REAL_ASCII (c) \
337 ? (((c) >= 'a' && (c) <= 'z') \
338 || ((c) >= 'A' && (c) <= 'Z')) \
339 : SYNTAX (c) == Sword)
341 # define ISLOWER(c) lowercasep (c)
343 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
344 ? ((c) > ' ' && (c) < 0177 \
345 && !(((c) >= 'a' && (c) <= 'z') \
346 || ((c) >= 'A' && (c) <= 'Z') \
347 || ((c) >= '0' && (c) <= '9'))) \
348 : SYNTAX (c) != Sword)
350 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
352 # define ISUPPER(c) uppercasep (c)
354 # define ISWORD(c) (SYNTAX (c) == Sword)
356 #else /* not emacs */
358 /* 1 if C is an ASCII character. */
359 # define IS_REAL_ASCII(c) ((c) < 0200)
361 /* This distinction is not meaningful, except in Emacs. */
362 # define ISUNIBYTE(c) 1
364 # ifdef isblank
365 # define ISBLANK(c) isblank (c)
366 # else
367 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
368 # endif
369 # ifdef isgraph
370 # define ISGRAPH(c) isgraph (c)
371 # else
372 # define ISGRAPH(c) (isprint (c) && !isspace (c))
373 # endif
375 /* Solaris defines ISPRINT so we must undefine it first. */
376 # undef ISPRINT
377 # define ISPRINT(c) isprint (c)
378 # define ISDIGIT(c) isdigit (c)
379 # define ISALNUM(c) isalnum (c)
380 # define ISALPHA(c) isalpha (c)
381 # define ISCNTRL(c) iscntrl (c)
382 # define ISLOWER(c) islower (c)
383 # define ISPUNCT(c) ispunct (c)
384 # define ISSPACE(c) isspace (c)
385 # define ISUPPER(c) isupper (c)
386 # define ISXDIGIT(c) isxdigit (c)
388 # define ISWORD(c) ISALPHA (c)
390 # ifdef _tolower
391 # define TOLOWER(c) _tolower (c)
392 # else
393 # define TOLOWER(c) tolower (c)
394 # endif
396 /* How many characters in the character set. */
397 # define CHAR_SET_SIZE 256
399 # ifdef SYNTAX_TABLE
401 extern char *re_syntax_table;
403 # else /* not SYNTAX_TABLE */
405 static char re_syntax_table[CHAR_SET_SIZE];
407 static void
408 init_syntax_once (void)
410 register int c;
411 static int done = 0;
413 if (done)
414 return;
416 memset (re_syntax_table, 0, sizeof re_syntax_table);
418 for (c = 0; c < CHAR_SET_SIZE; ++c)
419 if (ISALNUM (c))
420 re_syntax_table[c] = Sword;
422 re_syntax_table['_'] = Ssymbol;
424 done = 1;
427 # endif /* not SYNTAX_TABLE */
429 # define SYNTAX(c) re_syntax_table[(c)]
431 #endif /* not emacs */
433 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
435 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
436 use `alloca' instead of `malloc'. This is because using malloc in
437 re_search* or re_match* could cause memory leaks when C-g is used in
438 Emacs; also, malloc is slower and causes storage fragmentation. On
439 the other hand, malloc is more portable, and easier to debug.
441 Because we sometimes use alloca, some routines have to be macros,
442 not functions -- `alloca'-allocated space disappears at the end of the
443 function it is called in. */
445 #ifdef REGEX_MALLOC
447 # define REGEX_ALLOCATE malloc
448 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
449 # define REGEX_FREE free
451 #else /* not REGEX_MALLOC */
453 /* Emacs already defines alloca, sometimes. */
454 # ifndef alloca
456 /* Make alloca work the best possible way. */
457 # ifdef __GNUC__
458 # define alloca __builtin_alloca
459 # else /* not __GNUC__ */
460 # ifdef HAVE_ALLOCA_H
461 # include <alloca.h>
462 # endif /* HAVE_ALLOCA_H */
463 # endif /* not __GNUC__ */
465 # endif /* not alloca */
467 # define REGEX_ALLOCATE alloca
469 /* Assumes a `char *destination' variable. */
470 # define REGEX_REALLOCATE(source, osize, nsize) \
471 (destination = (char *) alloca (nsize), \
472 memcpy (destination, source, osize))
474 /* No need to do anything to free, after alloca. */
475 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
477 #endif /* not REGEX_MALLOC */
479 /* Define how to allocate the failure stack. */
481 #if defined REL_ALLOC && defined REGEX_MALLOC
483 # define REGEX_ALLOCATE_STACK(size) \
484 r_alloc (&failure_stack_ptr, (size))
485 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
486 r_re_alloc (&failure_stack_ptr, (nsize))
487 # define REGEX_FREE_STACK(ptr) \
488 r_alloc_free (&failure_stack_ptr)
490 #else /* not using relocating allocator */
492 # ifdef REGEX_MALLOC
494 # define REGEX_ALLOCATE_STACK malloc
495 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
496 # define REGEX_FREE_STACK free
498 # else /* not REGEX_MALLOC */
500 # define REGEX_ALLOCATE_STACK alloca
502 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
503 REGEX_REALLOCATE (source, osize, nsize)
504 /* No need to explicitly free anything. */
505 # define REGEX_FREE_STACK(arg) ((void)0)
507 # endif /* not REGEX_MALLOC */
508 #endif /* not using relocating allocator */
511 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
512 `string1' or just past its end. This works if PTR is NULL, which is
513 a good thing. */
514 #define FIRST_STRING_P(ptr) \
515 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
517 /* (Re)Allocate N items of type T using malloc, or fail. */
518 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
519 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
520 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
522 #define BYTEWIDTH 8 /* In bits. */
524 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
526 #undef MAX
527 #undef MIN
528 #define MAX(a, b) ((a) > (b) ? (a) : (b))
529 #define MIN(a, b) ((a) < (b) ? (a) : (b))
531 /* Type of source-pattern and string chars. */
532 #ifdef _MSC_VER
533 typedef unsigned char re_char;
534 #else
535 typedef const unsigned char re_char;
536 #endif
538 typedef char boolean;
540 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
541 re_char *string1, size_t size1,
542 re_char *string2, size_t size2,
543 ssize_t pos,
544 struct re_registers *regs,
545 ssize_t stop);
547 /* These are the command codes that appear in compiled regular
548 expressions. Some opcodes are followed by argument bytes. A
549 command code can specify any interpretation whatsoever for its
550 arguments. Zero bytes may appear in the compiled regular expression. */
552 typedef enum
554 no_op = 0,
556 /* Succeed right away--no more backtracking. */
557 succeed,
559 /* Followed by one byte giving n, then by n literal bytes. */
560 exactn,
562 /* Matches any (more or less) character. */
563 anychar,
565 /* Matches any one char belonging to specified set. First
566 following byte is number of bitmap bytes. Then come bytes
567 for a bitmap saying which chars are in. Bits in each byte
568 are ordered low-bit-first. A character is in the set if its
569 bit is 1. A character too large to have a bit in the map is
570 automatically not in the set.
572 If the length byte has the 0x80 bit set, then that stuff
573 is followed by a range table:
574 2 bytes of flags for character sets (low 8 bits, high 8 bits)
575 See RANGE_TABLE_WORK_BITS below.
576 2 bytes, the number of pairs that follow (upto 32767)
577 pairs, each 2 multibyte characters,
578 each multibyte character represented as 3 bytes. */
579 charset,
581 /* Same parameters as charset, but match any character that is
582 not one of those specified. */
583 charset_not,
585 /* Start remembering the text that is matched, for storing in a
586 register. Followed by one byte with the register number, in
587 the range 0 to one less than the pattern buffer's re_nsub
588 field. */
589 start_memory,
591 /* Stop remembering the text that is matched and store it in a
592 memory register. Followed by one byte with the register
593 number, in the range 0 to one less than `re_nsub' in the
594 pattern buffer. */
595 stop_memory,
597 /* Match a duplicate of something remembered. Followed by one
598 byte containing the register number. */
599 duplicate,
601 /* Fail unless at beginning of line. */
602 begline,
604 /* Fail unless at end of line. */
605 endline,
607 /* Succeeds if at beginning of buffer (if emacs) or at beginning
608 of string to be matched (if not). */
609 begbuf,
611 /* Analogously, for end of buffer/string. */
612 endbuf,
614 /* Followed by two byte relative address to which to jump. */
615 jump,
617 /* Followed by two-byte relative address of place to resume at
618 in case of failure. */
619 on_failure_jump,
621 /* Like on_failure_jump, but pushes a placeholder instead of the
622 current string position when executed. */
623 on_failure_keep_string_jump,
625 /* Just like `on_failure_jump', except that it checks that we
626 don't get stuck in an infinite loop (matching an empty string
627 indefinitely). */
628 on_failure_jump_loop,
630 /* Just like `on_failure_jump_loop', except that it checks for
631 a different kind of loop (the kind that shows up with non-greedy
632 operators). This operation has to be immediately preceded
633 by a `no_op'. */
634 on_failure_jump_nastyloop,
636 /* A smart `on_failure_jump' used for greedy * and + operators.
637 It analyzes the loop before which it is put and if the
638 loop does not require backtracking, it changes itself to
639 `on_failure_keep_string_jump' and short-circuits the loop,
640 else it just defaults to changing itself into `on_failure_jump'.
641 It assumes that it is pointing to just past a `jump'. */
642 on_failure_jump_smart,
644 /* Followed by two-byte relative address and two-byte number n.
645 After matching N times, jump to the address upon failure.
646 Does not work if N starts at 0: use on_failure_jump_loop
647 instead. */
648 succeed_n,
650 /* Followed by two-byte relative address, and two-byte number n.
651 Jump to the address N times, then fail. */
652 jump_n,
654 /* Set the following two-byte relative address to the
655 subsequent two-byte number. The address *includes* the two
656 bytes of number. */
657 set_number_at,
659 wordbeg, /* Succeeds if at word beginning. */
660 wordend, /* Succeeds if at word end. */
662 wordbound, /* Succeeds if at a word boundary. */
663 notwordbound, /* Succeeds if not at a word boundary. */
665 symbeg, /* Succeeds if at symbol beginning. */
666 symend, /* Succeeds if at symbol end. */
668 /* Matches any character whose syntax is specified. Followed by
669 a byte which contains a syntax code, e.g., Sword. */
670 syntaxspec,
672 /* Matches any character whose syntax is not that specified. */
673 notsyntaxspec
675 #ifdef emacs
676 ,before_dot, /* Succeeds if before point. */
677 at_dot, /* Succeeds if at point. */
678 after_dot, /* Succeeds if after point. */
680 /* Matches any character whose category-set contains the specified
681 category. The operator is followed by a byte which contains a
682 category code (mnemonic ASCII character). */
683 categoryspec,
685 /* Matches any character whose category-set does not contain the
686 specified category. The operator is followed by a byte which
687 contains the category code (mnemonic ASCII character). */
688 notcategoryspec
689 #endif /* emacs */
690 } re_opcode_t;
692 /* Common operations on the compiled pattern. */
694 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
696 #define STORE_NUMBER(destination, number) \
697 do { \
698 (destination)[0] = (number) & 0377; \
699 (destination)[1] = (number) >> 8; \
700 } while (0)
702 /* Same as STORE_NUMBER, except increment DESTINATION to
703 the byte after where the number is stored. Therefore, DESTINATION
704 must be an lvalue. */
706 #define STORE_NUMBER_AND_INCR(destination, number) \
707 do { \
708 STORE_NUMBER (destination, number); \
709 (destination) += 2; \
710 } while (0)
712 /* Put into DESTINATION a number stored in two contiguous bytes starting
713 at SOURCE. */
715 #define EXTRACT_NUMBER(destination, source) \
716 do { \
717 (destination) = *(source) & 0377; \
718 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
719 } while (0)
721 #ifdef DEBUG
722 static void
723 extract_number (int *dest, re_char *source)
725 int temp = SIGN_EXTEND_CHAR (*(source + 1));
726 *dest = *source & 0377;
727 *dest += temp << 8;
730 # ifndef EXTRACT_MACROS /* To debug the macros. */
731 # undef EXTRACT_NUMBER
732 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
733 # endif /* not EXTRACT_MACROS */
735 #endif /* DEBUG */
737 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
738 SOURCE must be an lvalue. */
740 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
741 do { \
742 EXTRACT_NUMBER (destination, source); \
743 (source) += 2; \
744 } while (0)
746 #ifdef DEBUG
747 static void
748 extract_number_and_incr (int *destination, re_char **source)
750 extract_number (destination, *source);
751 *source += 2;
754 # ifndef EXTRACT_MACROS
755 # undef EXTRACT_NUMBER_AND_INCR
756 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
757 extract_number_and_incr (&dest, &src)
758 # endif /* not EXTRACT_MACROS */
760 #endif /* DEBUG */
762 /* Store a multibyte character in three contiguous bytes starting
763 DESTINATION, and increment DESTINATION to the byte after where the
764 character is stored. Therefore, DESTINATION must be an lvalue. */
766 #define STORE_CHARACTER_AND_INCR(destination, character) \
767 do { \
768 (destination)[0] = (character) & 0377; \
769 (destination)[1] = ((character) >> 8) & 0377; \
770 (destination)[2] = (character) >> 16; \
771 (destination) += 3; \
772 } while (0)
774 /* Put into DESTINATION a character stored in three contiguous bytes
775 starting at SOURCE. */
777 #define EXTRACT_CHARACTER(destination, source) \
778 do { \
779 (destination) = ((source)[0] \
780 | ((source)[1] << 8) \
781 | ((source)[2] << 16)); \
782 } while (0)
785 /* Macros for charset. */
787 /* Size of bitmap of charset P in bytes. P is a start of charset,
788 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
789 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
791 /* Nonzero if charset P has range table. */
792 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
794 /* Return the address of range table of charset P. But not the start
795 of table itself, but the before where the number of ranges is
796 stored. `2 +' means to skip re_opcode_t and size of bitmap,
797 and the 2 bytes of flags at the start of the range table. */
798 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
800 /* Extract the bit flags that start a range table. */
801 #define CHARSET_RANGE_TABLE_BITS(p) \
802 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
803 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
805 /* Return the address of end of RANGE_TABLE. COUNT is number of
806 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
807 is start of range and end of range. `* 3' is size of each start
808 and end. */
809 #define CHARSET_RANGE_TABLE_END(range_table, count) \
810 ((range_table) + (count) * 2 * 3)
812 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
813 COUNT is number of ranges in RANGE_TABLE. */
814 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
815 do \
817 re_wchar_t range_start, range_end; \
818 re_char *rtp; \
819 re_char *range_table_end \
820 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
822 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
824 EXTRACT_CHARACTER (range_start, rtp); \
825 EXTRACT_CHARACTER (range_end, rtp + 3); \
827 if (range_start <= (c) && (c) <= range_end) \
829 (not) = !(not); \
830 break; \
834 while (0)
836 /* Test if C is in range table of CHARSET. The flag NOT is negated if
837 C is listed in it. */
838 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
839 do \
841 /* Number of ranges in range table. */ \
842 int count; \
843 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
845 EXTRACT_NUMBER_AND_INCR (count, range_table); \
846 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
848 while (0)
850 /* If DEBUG is defined, Regex prints many voluminous messages about what
851 it is doing (if the variable `debug' is nonzero). If linked with the
852 main program in `iregex.c', you can enter patterns and strings
853 interactively. And if linked with the main program in `main.c' and
854 the other test files, you can run the already-written tests. */
856 #ifdef DEBUG
858 /* We use standard I/O for debugging. */
859 # include <stdio.h>
861 /* It is useful to test things that ``must'' be true when debugging. */
862 # include <assert.h>
864 static int debug = -100000;
866 # define DEBUG_STATEMENT(e) e
867 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
868 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
869 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
870 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
871 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
872 if (debug > 0) print_partial_compiled_pattern (s, e)
873 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
874 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
877 /* Print the fastmap in human-readable form. */
879 void
880 print_fastmap (fastmap)
881 char *fastmap;
883 unsigned was_a_range = 0;
884 unsigned i = 0;
886 while (i < (1 << BYTEWIDTH))
888 if (fastmap[i++])
890 was_a_range = 0;
891 putchar (i - 1);
892 while (i < (1 << BYTEWIDTH) && fastmap[i])
894 was_a_range = 1;
895 i++;
897 if (was_a_range)
899 printf ("-");
900 putchar (i - 1);
904 putchar ('\n');
908 /* Print a compiled pattern string in human-readable form, starting at
909 the START pointer into it and ending just before the pointer END. */
911 void
912 print_partial_compiled_pattern (start, end)
913 re_char *start;
914 re_char *end;
916 int mcnt, mcnt2;
917 re_char *p = start;
918 re_char *pend = end;
920 if (start == NULL)
922 fprintf (stderr, "(null)\n");
923 return;
926 /* Loop over pattern commands. */
927 while (p < pend)
929 fprintf (stderr, "%d:\t", p - start);
931 switch ((re_opcode_t) *p++)
933 case no_op:
934 fprintf (stderr, "/no_op");
935 break;
937 case succeed:
938 fprintf (stderr, "/succeed");
939 break;
941 case exactn:
942 mcnt = *p++;
943 fprintf (stderr, "/exactn/%d", mcnt);
946 fprintf (stderr, "/%c", *p++);
948 while (--mcnt);
949 break;
951 case start_memory:
952 fprintf (stderr, "/start_memory/%d", *p++);
953 break;
955 case stop_memory:
956 fprintf (stderr, "/stop_memory/%d", *p++);
957 break;
959 case duplicate:
960 fprintf (stderr, "/duplicate/%d", *p++);
961 break;
963 case anychar:
964 fprintf (stderr, "/anychar");
965 break;
967 case charset:
968 case charset_not:
970 register int c, last = -100;
971 register int in_range = 0;
972 int length = CHARSET_BITMAP_SIZE (p - 1);
973 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
975 fprintf (stderr, "/charset [%s",
976 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
978 if (p + *p >= pend)
979 fprintf (stderr, " !extends past end of pattern! ");
981 for (c = 0; c < 256; c++)
982 if (c / 8 < length
983 && (p[1 + (c/8)] & (1 << (c % 8))))
985 /* Are we starting a range? */
986 if (last + 1 == c && ! in_range)
988 fprintf (stderr, "-");
989 in_range = 1;
991 /* Have we broken a range? */
992 else if (last + 1 != c && in_range)
994 fprintf (stderr, "%c", last);
995 in_range = 0;
998 if (! in_range)
999 fprintf (stderr, "%c", c);
1001 last = c;
1004 if (in_range)
1005 fprintf (stderr, "%c", last);
1007 fprintf (stderr, "]");
1009 p += 1 + length;
1011 if (has_range_table)
1013 int count;
1014 fprintf (stderr, "has-range-table");
1016 /* ??? Should print the range table; for now, just skip it. */
1017 p += 2; /* skip range table bits */
1018 EXTRACT_NUMBER_AND_INCR (count, p);
1019 p = CHARSET_RANGE_TABLE_END (p, count);
1022 break;
1024 case begline:
1025 fprintf (stderr, "/begline");
1026 break;
1028 case endline:
1029 fprintf (stderr, "/endline");
1030 break;
1032 case on_failure_jump:
1033 extract_number_and_incr (&mcnt, &p);
1034 fprintf (stderr, "/on_failure_jump to %d", p + mcnt - start);
1035 break;
1037 case on_failure_keep_string_jump:
1038 extract_number_and_incr (&mcnt, &p);
1039 fprintf (stderr, "/on_failure_keep_string_jump to %d", p + mcnt - start);
1040 break;
1042 case on_failure_jump_nastyloop:
1043 extract_number_and_incr (&mcnt, &p);
1044 fprintf (stderr, "/on_failure_jump_nastyloop to %d", p + mcnt - start);
1045 break;
1047 case on_failure_jump_loop:
1048 extract_number_and_incr (&mcnt, &p);
1049 fprintf (stderr, "/on_failure_jump_loop to %d", p + mcnt - start);
1050 break;
1052 case on_failure_jump_smart:
1053 extract_number_and_incr (&mcnt, &p);
1054 fprintf (stderr, "/on_failure_jump_smart to %d", p + mcnt - start);
1055 break;
1057 case jump:
1058 extract_number_and_incr (&mcnt, &p);
1059 fprintf (stderr, "/jump to %d", p + mcnt - start);
1060 break;
1062 case succeed_n:
1063 extract_number_and_incr (&mcnt, &p);
1064 extract_number_and_incr (&mcnt2, &p);
1065 fprintf (stderr, "/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1066 break;
1068 case jump_n:
1069 extract_number_and_incr (&mcnt, &p);
1070 extract_number_and_incr (&mcnt2, &p);
1071 fprintf (stderr, "/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1072 break;
1074 case set_number_at:
1075 extract_number_and_incr (&mcnt, &p);
1076 extract_number_and_incr (&mcnt2, &p);
1077 fprintf (stderr, "/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1078 break;
1080 case wordbound:
1081 fprintf (stderr, "/wordbound");
1082 break;
1084 case notwordbound:
1085 fprintf (stderr, "/notwordbound");
1086 break;
1088 case wordbeg:
1089 fprintf (stderr, "/wordbeg");
1090 break;
1092 case wordend:
1093 fprintf (stderr, "/wordend");
1094 break;
1096 case symbeg:
1097 fprintf (stderr, "/symbeg");
1098 break;
1100 case symend:
1101 fprintf (stderr, "/symend");
1102 break;
1104 case syntaxspec:
1105 fprintf (stderr, "/syntaxspec");
1106 mcnt = *p++;
1107 fprintf (stderr, "/%d", mcnt);
1108 break;
1110 case notsyntaxspec:
1111 fprintf (stderr, "/notsyntaxspec");
1112 mcnt = *p++;
1113 fprintf (stderr, "/%d", mcnt);
1114 break;
1116 # ifdef emacs
1117 case before_dot:
1118 fprintf (stderr, "/before_dot");
1119 break;
1121 case at_dot:
1122 fprintf (stderr, "/at_dot");
1123 break;
1125 case after_dot:
1126 fprintf (stderr, "/after_dot");
1127 break;
1129 case categoryspec:
1130 fprintf (stderr, "/categoryspec");
1131 mcnt = *p++;
1132 fprintf (stderr, "/%d", mcnt);
1133 break;
1135 case notcategoryspec:
1136 fprintf (stderr, "/notcategoryspec");
1137 mcnt = *p++;
1138 fprintf (stderr, "/%d", mcnt);
1139 break;
1140 # endif /* emacs */
1142 case begbuf:
1143 fprintf (stderr, "/begbuf");
1144 break;
1146 case endbuf:
1147 fprintf (stderr, "/endbuf");
1148 break;
1150 default:
1151 fprintf (stderr, "?%d", *(p-1));
1154 fprintf (stderr, "\n");
1157 fprintf (stderr, "%d:\tend of pattern.\n", p - start);
1161 void
1162 print_compiled_pattern (bufp)
1163 struct re_pattern_buffer *bufp;
1165 re_char *buffer = bufp->buffer;
1167 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1168 printf ("%ld bytes used/%ld bytes allocated.\n",
1169 bufp->used, bufp->allocated);
1171 if (bufp->fastmap_accurate && bufp->fastmap)
1173 printf ("fastmap: ");
1174 print_fastmap (bufp->fastmap);
1177 printf ("re_nsub: %d\t", bufp->re_nsub);
1178 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1179 printf ("can_be_null: %d\t", bufp->can_be_null);
1180 printf ("no_sub: %d\t", bufp->no_sub);
1181 printf ("not_bol: %d\t", bufp->not_bol);
1182 printf ("not_eol: %d\t", bufp->not_eol);
1183 printf ("syntax: %lx\n", bufp->syntax);
1184 fflush (stdout);
1185 /* Perhaps we should print the translate table? */
1189 void
1190 print_double_string (where, string1, size1, string2, size2)
1191 re_char *where;
1192 re_char *string1;
1193 re_char *string2;
1194 ssize_t size1;
1195 ssize_t size2;
1197 ssize_t this_char;
1199 if (where == NULL)
1200 printf ("(null)");
1201 else
1203 if (FIRST_STRING_P (where))
1205 for (this_char = where - string1; this_char < size1; this_char++)
1206 putchar (string1[this_char]);
1208 where = string2;
1211 for (this_char = where - string2; this_char < size2; this_char++)
1212 putchar (string2[this_char]);
1216 #else /* not DEBUG */
1218 # undef assert
1219 # define assert(e)
1221 # define DEBUG_STATEMENT(e)
1222 # define DEBUG_PRINT1(x)
1223 # define DEBUG_PRINT2(x1, x2)
1224 # define DEBUG_PRINT3(x1, x2, x3)
1225 # define DEBUG_PRINT4(x1, x2, x3, x4)
1226 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1227 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1229 #endif /* not DEBUG */
1231 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1232 #ifdef lint
1233 # define IF_LINT(Code) Code
1234 #else
1235 # define IF_LINT(Code) /* empty */
1236 #endif
1238 #ifndef emacs
1239 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1240 also be assigned to arbitrarily: each pattern buffer stores its own
1241 syntax, so it can be changed between regex compilations. */
1242 /* This has no initializer because initialized variables in Emacs
1243 become read-only after dumping. */
1244 reg_syntax_t re_syntax_options;
1245 #endif
1248 /* Specify the precise syntax of regexps for compilation. This provides
1249 for compatibility for various utilities which historically have
1250 different, incompatible syntaxes.
1252 The argument SYNTAX is a bit mask comprised of the various bits
1253 defined in regex.h. We return the old syntax. */
1255 reg_syntax_t
1256 re_set_syntax (reg_syntax_t syntax)
1258 reg_syntax_t ret = re_syntax_options;
1260 re_syntax_options = syntax;
1261 return ret;
1263 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1265 #ifndef emacs
1266 /* Regexp to use to replace spaces, or NULL meaning don't. */
1267 static re_char *whitespace_regexp;
1268 #endif
1270 void
1271 re_set_whitespace_regexp (const char *regexp)
1273 whitespace_regexp = (re_char *) regexp;
1275 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1277 /* This table gives an error message for each of the error codes listed
1278 in regex.h. Obviously the order here has to be same as there.
1279 POSIX doesn't require that we do anything for REG_NOERROR,
1280 but why not be nice? */
1282 static const char *re_error_msgid[] =
1284 gettext_noop ("Success"), /* REG_NOERROR */
1285 gettext_noop ("No match"), /* REG_NOMATCH */
1286 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1287 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1288 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1289 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1290 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1291 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1292 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1293 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1294 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1295 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1296 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1297 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1298 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1299 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1300 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1301 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1304 /* Avoiding alloca during matching, to placate r_alloc. */
1306 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1307 searching and matching functions should not call alloca. On some
1308 systems, alloca is implemented in terms of malloc, and if we're
1309 using the relocating allocator routines, then malloc could cause a
1310 relocation, which might (if the strings being searched are in the
1311 ralloc heap) shift the data out from underneath the regexp
1312 routines.
1314 Here's another reason to avoid allocation: Emacs
1315 processes input from X in a signal handler; processing X input may
1316 call malloc; if input arrives while a matching routine is calling
1317 malloc, then we're scrod. But Emacs can't just block input while
1318 calling matching routines; then we don't notice interrupts when
1319 they come in. So, Emacs blocks input around all regexp calls
1320 except the matching calls, which it leaves unprotected, in the
1321 faith that they will not malloc. */
1323 /* Normally, this is fine. */
1324 #define MATCH_MAY_ALLOCATE
1326 /* The match routines may not allocate if (1) they would do it with malloc
1327 and (2) it's not safe for them to use malloc.
1328 Note that if REL_ALLOC is defined, matching would not use malloc for the
1329 failure stack, but we would still use it for the register vectors;
1330 so REL_ALLOC should not affect this. */
1331 #if defined REGEX_MALLOC && defined emacs
1332 # undef MATCH_MAY_ALLOCATE
1333 #endif
1336 /* Failure stack declarations and macros; both re_compile_fastmap and
1337 re_match_2 use a failure stack. These have to be macros because of
1338 REGEX_ALLOCATE_STACK. */
1341 /* Approximate number of failure points for which to initially allocate space
1342 when matching. If this number is exceeded, we allocate more
1343 space, so it is not a hard limit. */
1344 #ifndef INIT_FAILURE_ALLOC
1345 # define INIT_FAILURE_ALLOC 20
1346 #endif
1348 /* Roughly the maximum number of failure points on the stack. Would be
1349 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1350 This is a variable only so users of regex can assign to it; we never
1351 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1352 before using it, so it should probably be a byte-count instead. */
1353 # if defined MATCH_MAY_ALLOCATE
1354 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1355 whose default stack limit is 2mb. In order for a larger
1356 value to work reliably, you have to try to make it accord
1357 with the process stack limit. */
1358 size_t re_max_failures = 40000;
1359 # else
1360 size_t re_max_failures = 4000;
1361 # endif
1363 union fail_stack_elt
1365 re_char *pointer;
1366 /* This should be the biggest `int' that's no bigger than a pointer. */
1367 long integer;
1370 typedef union fail_stack_elt fail_stack_elt_t;
1372 typedef struct
1374 fail_stack_elt_t *stack;
1375 size_t size;
1376 size_t avail; /* Offset of next open position. */
1377 size_t frame; /* Offset of the cur constructed frame. */
1378 } fail_stack_type;
1380 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1383 /* Define macros to initialize and free the failure stack.
1384 Do `return -2' if the alloc fails. */
1386 #ifdef MATCH_MAY_ALLOCATE
1387 # define INIT_FAIL_STACK() \
1388 do { \
1389 fail_stack.stack = \
1390 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1391 * sizeof (fail_stack_elt_t)); \
1393 if (fail_stack.stack == NULL) \
1394 return -2; \
1396 fail_stack.size = INIT_FAILURE_ALLOC; \
1397 fail_stack.avail = 0; \
1398 fail_stack.frame = 0; \
1399 } while (0)
1400 #else
1401 # define INIT_FAIL_STACK() \
1402 do { \
1403 fail_stack.avail = 0; \
1404 fail_stack.frame = 0; \
1405 } while (0)
1407 # define RETALLOC_IF(addr, n, t) \
1408 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1409 #endif
1412 /* Double the size of FAIL_STACK, up to a limit
1413 which allows approximately `re_max_failures' items.
1415 Return 1 if succeeds, and 0 if either ran out of memory
1416 allocating space for it or it was already too large.
1418 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1420 /* Factor to increase the failure stack size by
1421 when we increase it.
1422 This used to be 2, but 2 was too wasteful
1423 because the old discarded stacks added up to as much space
1424 were as ultimate, maximum-size stack. */
1425 #define FAIL_STACK_GROWTH_FACTOR 4
1427 #define GROW_FAIL_STACK(fail_stack) \
1428 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1429 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1430 ? 0 \
1431 : ((fail_stack).stack \
1432 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1433 (fail_stack).size * sizeof (fail_stack_elt_t), \
1434 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1435 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1436 * FAIL_STACK_GROWTH_FACTOR))), \
1438 (fail_stack).stack == NULL \
1439 ? 0 \
1440 : ((fail_stack).size \
1441 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1442 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1443 * FAIL_STACK_GROWTH_FACTOR)) \
1444 / sizeof (fail_stack_elt_t)), \
1445 1)))
1448 /* Push a pointer value onto the failure stack.
1449 Assumes the variable `fail_stack'. Probably should only
1450 be called from within `PUSH_FAILURE_POINT'. */
1451 #define PUSH_FAILURE_POINTER(item) \
1452 fail_stack.stack[fail_stack.avail++].pointer = (item)
1454 /* This pushes an integer-valued item onto the failure stack.
1455 Assumes the variable `fail_stack'. Probably should only
1456 be called from within `PUSH_FAILURE_POINT'. */
1457 #define PUSH_FAILURE_INT(item) \
1458 fail_stack.stack[fail_stack.avail++].integer = (item)
1460 /* These POP... operations complement the PUSH... operations.
1461 All assume that `fail_stack' is nonempty. */
1462 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1463 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1465 /* Individual items aside from the registers. */
1466 #define NUM_NONREG_ITEMS 3
1468 /* Used to examine the stack (to detect infinite loops). */
1469 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1470 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1471 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1472 #define TOP_FAILURE_HANDLE() fail_stack.frame
1475 #define ENSURE_FAIL_STACK(space) \
1476 while (REMAINING_AVAIL_SLOTS <= space) { \
1477 if (!GROW_FAIL_STACK (fail_stack)) \
1478 return -2; \
1479 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1480 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1483 /* Push register NUM onto the stack. */
1484 #define PUSH_FAILURE_REG(num) \
1485 do { \
1486 char *destination; \
1487 ENSURE_FAIL_STACK(3); \
1488 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1489 num, regstart[num], regend[num]); \
1490 PUSH_FAILURE_POINTER (regstart[num]); \
1491 PUSH_FAILURE_POINTER (regend[num]); \
1492 PUSH_FAILURE_INT (num); \
1493 } while (0)
1495 /* Change the counter's value to VAL, but make sure that it will
1496 be reset when backtracking. */
1497 #define PUSH_NUMBER(ptr,val) \
1498 do { \
1499 char *destination; \
1500 int c; \
1501 ENSURE_FAIL_STACK(3); \
1502 EXTRACT_NUMBER (c, ptr); \
1503 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1504 PUSH_FAILURE_INT (c); \
1505 PUSH_FAILURE_POINTER (ptr); \
1506 PUSH_FAILURE_INT (-1); \
1507 STORE_NUMBER (ptr, val); \
1508 } while (0)
1510 /* Pop a saved register off the stack. */
1511 #define POP_FAILURE_REG_OR_COUNT() \
1512 do { \
1513 long pfreg = POP_FAILURE_INT (); \
1514 if (pfreg == -1) \
1516 /* It's a counter. */ \
1517 /* Here, we discard `const', making re_match non-reentrant. */ \
1518 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1519 pfreg = POP_FAILURE_INT (); \
1520 STORE_NUMBER (ptr, pfreg); \
1521 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, pfreg); \
1523 else \
1525 regend[pfreg] = POP_FAILURE_POINTER (); \
1526 regstart[pfreg] = POP_FAILURE_POINTER (); \
1527 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1528 pfreg, regstart[pfreg], regend[pfreg]); \
1530 } while (0)
1532 /* Check that we are not stuck in an infinite loop. */
1533 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1534 do { \
1535 ssize_t failure = TOP_FAILURE_HANDLE (); \
1536 /* Check for infinite matching loops */ \
1537 while (failure > 0 \
1538 && (FAILURE_STR (failure) == string_place \
1539 || FAILURE_STR (failure) == NULL)) \
1541 assert (FAILURE_PAT (failure) >= bufp->buffer \
1542 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1543 if (FAILURE_PAT (failure) == pat_cur) \
1545 cycle = 1; \
1546 break; \
1548 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1549 failure = NEXT_FAILURE_HANDLE(failure); \
1551 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1552 } while (0)
1554 /* Push the information about the state we will need
1555 if we ever fail back to it.
1557 Requires variables fail_stack, regstart, regend and
1558 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1559 declared.
1561 Does `return FAILURE_CODE' if runs out of memory. */
1563 #define PUSH_FAILURE_POINT(pattern, string_place) \
1564 do { \
1565 char *destination; \
1566 /* Must be int, so when we don't save any registers, the arithmetic \
1567 of 0 + -1 isn't done as unsigned. */ \
1569 DEBUG_STATEMENT (nfailure_points_pushed++); \
1570 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1571 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1572 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1574 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1576 DEBUG_PRINT1 ("\n"); \
1578 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1579 PUSH_FAILURE_INT (fail_stack.frame); \
1581 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1582 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1583 DEBUG_PRINT1 ("'\n"); \
1584 PUSH_FAILURE_POINTER (string_place); \
1586 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1587 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1588 PUSH_FAILURE_POINTER (pattern); \
1590 /* Close the frame by moving the frame pointer past it. */ \
1591 fail_stack.frame = fail_stack.avail; \
1592 } while (0)
1594 /* Estimate the size of data pushed by a typical failure stack entry.
1595 An estimate is all we need, because all we use this for
1596 is to choose a limit for how big to make the failure stack. */
1597 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1598 #define TYPICAL_FAILURE_SIZE 20
1600 /* How many items can still be added to the stack without overflowing it. */
1601 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1604 /* Pops what PUSH_FAIL_STACK pushes.
1606 We restore into the parameters, all of which should be lvalues:
1607 STR -- the saved data position.
1608 PAT -- the saved pattern position.
1609 REGSTART, REGEND -- arrays of string positions.
1611 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1612 `pend', `string1', `size1', `string2', and `size2'. */
1614 #define POP_FAILURE_POINT(str, pat) \
1615 do { \
1616 assert (!FAIL_STACK_EMPTY ()); \
1618 /* Remove failure points and point to how many regs pushed. */ \
1619 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1620 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1621 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1623 /* Pop the saved registers. */ \
1624 while (fail_stack.frame < fail_stack.avail) \
1625 POP_FAILURE_REG_OR_COUNT (); \
1627 pat = POP_FAILURE_POINTER (); \
1628 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1629 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1631 /* If the saved string location is NULL, it came from an \
1632 on_failure_keep_string_jump opcode, and we want to throw away the \
1633 saved NULL, thus retaining our current position in the string. */ \
1634 str = POP_FAILURE_POINTER (); \
1635 DEBUG_PRINT2 (" Popping string %p: `", str); \
1636 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1637 DEBUG_PRINT1 ("'\n"); \
1639 fail_stack.frame = POP_FAILURE_INT (); \
1640 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1642 assert (fail_stack.avail >= 0); \
1643 assert (fail_stack.frame <= fail_stack.avail); \
1645 DEBUG_STATEMENT (nfailure_points_popped++); \
1646 } while (0) /* POP_FAILURE_POINT */
1650 /* Registers are set to a sentinel when they haven't yet matched. */
1651 #define REG_UNSET(e) ((e) == NULL)
1653 /* Subroutine declarations and macros for regex_compile. */
1655 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1656 reg_syntax_t syntax,
1657 struct re_pattern_buffer *bufp);
1658 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1659 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1660 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1661 int arg, unsigned char *end);
1662 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1663 int arg1, int arg2, unsigned char *end);
1664 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1665 reg_syntax_t syntax);
1666 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1667 reg_syntax_t syntax);
1668 static re_char *skip_one_char (re_char *p);
1669 static int analyse_first (re_char *p, re_char *pend,
1670 char *fastmap, const int multibyte);
1672 /* Fetch the next character in the uncompiled pattern, with no
1673 translation. */
1674 #define PATFETCH(c) \
1675 do { \
1676 int len; \
1677 if (p == pend) return REG_EEND; \
1678 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1679 p += len; \
1680 } while (0)
1683 /* If `translate' is non-null, return translate[D], else just D. We
1684 cast the subscript to translate because some data is declared as
1685 `char *', to avoid warnings when a string constant is passed. But
1686 when we use a character as a subscript we must make it unsigned. */
1687 #ifndef TRANSLATE
1688 # define TRANSLATE(d) \
1689 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1690 #endif
1693 /* Macros for outputting the compiled pattern into `buffer'. */
1695 /* If the buffer isn't allocated when it comes in, use this. */
1696 #define INIT_BUF_SIZE 32
1698 /* Make sure we have at least N more bytes of space in buffer. */
1699 #define GET_BUFFER_SPACE(n) \
1700 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1701 EXTEND_BUFFER ()
1703 /* Make sure we have one more byte of buffer space and then add C to it. */
1704 #define BUF_PUSH(c) \
1705 do { \
1706 GET_BUFFER_SPACE (1); \
1707 *b++ = (unsigned char) (c); \
1708 } while (0)
1711 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1712 #define BUF_PUSH_2(c1, c2) \
1713 do { \
1714 GET_BUFFER_SPACE (2); \
1715 *b++ = (unsigned char) (c1); \
1716 *b++ = (unsigned char) (c2); \
1717 } while (0)
1720 /* Store a jump with opcode OP at LOC to location TO. We store a
1721 relative address offset by the three bytes the jump itself occupies. */
1722 #define STORE_JUMP(op, loc, to) \
1723 store_op1 (op, loc, (to) - (loc) - 3)
1725 /* Likewise, for a two-argument jump. */
1726 #define STORE_JUMP2(op, loc, to, arg) \
1727 store_op2 (op, loc, (to) - (loc) - 3, arg)
1729 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1730 #define INSERT_JUMP(op, loc, to) \
1731 insert_op1 (op, loc, (to) - (loc) - 3, b)
1733 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1734 #define INSERT_JUMP2(op, loc, to, arg) \
1735 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1738 /* This is not an arbitrary limit: the arguments which represent offsets
1739 into the pattern are two bytes long. So if 2^15 bytes turns out to
1740 be too small, many things would have to change. */
1741 # define MAX_BUF_SIZE (1L << 15)
1743 /* Extend the buffer by twice its current size via realloc and
1744 reset the pointers that pointed into the old block to point to the
1745 correct places in the new one. If extending the buffer results in it
1746 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1747 #if __BOUNDED_POINTERS__
1748 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1749 # define MOVE_BUFFER_POINTER(P) \
1750 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1751 SET_HIGH_BOUND (P), \
1752 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1753 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1754 else \
1756 SET_HIGH_BOUND (b); \
1757 SET_HIGH_BOUND (begalt); \
1758 if (fixup_alt_jump) \
1759 SET_HIGH_BOUND (fixup_alt_jump); \
1760 if (laststart) \
1761 SET_HIGH_BOUND (laststart); \
1762 if (pending_exact) \
1763 SET_HIGH_BOUND (pending_exact); \
1765 #else
1766 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1767 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1768 #endif
1769 #define EXTEND_BUFFER() \
1770 do { \
1771 unsigned char *old_buffer = bufp->buffer; \
1772 if (bufp->allocated == MAX_BUF_SIZE) \
1773 return REG_ESIZE; \
1774 bufp->allocated <<= 1; \
1775 if (bufp->allocated > MAX_BUF_SIZE) \
1776 bufp->allocated = MAX_BUF_SIZE; \
1777 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1778 if (bufp->buffer == NULL) \
1779 return REG_ESPACE; \
1780 /* If the buffer moved, move all the pointers into it. */ \
1781 if (old_buffer != bufp->buffer) \
1783 unsigned char *new_buffer = bufp->buffer; \
1784 MOVE_BUFFER_POINTER (b); \
1785 MOVE_BUFFER_POINTER (begalt); \
1786 if (fixup_alt_jump) \
1787 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1788 if (laststart) \
1789 MOVE_BUFFER_POINTER (laststart); \
1790 if (pending_exact) \
1791 MOVE_BUFFER_POINTER (pending_exact); \
1793 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1794 } while (0)
1797 /* Since we have one byte reserved for the register number argument to
1798 {start,stop}_memory, the maximum number of groups we can report
1799 things about is what fits in that byte. */
1800 #define MAX_REGNUM 255
1802 /* But patterns can have more than `MAX_REGNUM' registers. We just
1803 ignore the excess. */
1804 typedef int regnum_t;
1807 /* Macros for the compile stack. */
1809 /* Since offsets can go either forwards or backwards, this type needs to
1810 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1811 /* int may be not enough when sizeof(int) == 2. */
1812 typedef long pattern_offset_t;
1814 typedef struct
1816 pattern_offset_t begalt_offset;
1817 pattern_offset_t fixup_alt_jump;
1818 pattern_offset_t laststart_offset;
1819 regnum_t regnum;
1820 } compile_stack_elt_t;
1823 typedef struct
1825 compile_stack_elt_t *stack;
1826 size_t size;
1827 size_t avail; /* Offset of next open position. */
1828 } compile_stack_type;
1831 #define INIT_COMPILE_STACK_SIZE 32
1833 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1834 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1836 /* The next available element. */
1837 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1839 /* Explicit quit checking is only used on NTemacs and whenever we
1840 use polling to process input events. */
1841 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1842 extern int immediate_quit;
1843 # define IMMEDIATE_QUIT_CHECK \
1844 do { \
1845 if (immediate_quit) QUIT; \
1846 } while (0)
1847 #else
1848 # define IMMEDIATE_QUIT_CHECK ((void)0)
1849 #endif
1851 /* Structure to manage work area for range table. */
1852 struct range_table_work_area
1854 int *table; /* actual work area. */
1855 int allocated; /* allocated size for work area in bytes. */
1856 int used; /* actually used size in words. */
1857 int bits; /* flag to record character classes */
1860 /* Make sure that WORK_AREA can hold more N multibyte characters.
1861 This is used only in set_image_of_range and set_image_of_range_1.
1862 It expects WORK_AREA to be a pointer.
1863 If it can't get the space, it returns from the surrounding function. */
1865 #define EXTEND_RANGE_TABLE(work_area, n) \
1866 do { \
1867 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1869 extend_range_table_work_area (&work_area); \
1870 if ((work_area).table == 0) \
1871 return (REG_ESPACE); \
1873 } while (0)
1875 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1876 (work_area).bits |= (bit)
1878 /* Bits used to implement the multibyte-part of the various character classes
1879 such as [:alnum:] in a charset's range table. */
1880 #define BIT_WORD 0x1
1881 #define BIT_LOWER 0x2
1882 #define BIT_PUNCT 0x4
1883 #define BIT_SPACE 0x8
1884 #define BIT_UPPER 0x10
1885 #define BIT_MULTIBYTE 0x20
1887 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1888 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1889 do { \
1890 EXTEND_RANGE_TABLE ((work_area), 2); \
1891 (work_area).table[(work_area).used++] = (range_start); \
1892 (work_area).table[(work_area).used++] = (range_end); \
1893 } while (0)
1895 /* Free allocated memory for WORK_AREA. */
1896 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1897 do { \
1898 if ((work_area).table) \
1899 free ((work_area).table); \
1900 } while (0)
1902 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1903 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1904 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1905 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1908 /* Set the bit for character C in a list. */
1909 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1912 #ifdef emacs
1914 /* Store characters in the range FROM to TO in the bitmap at B (for
1915 ASCII and unibyte characters) and WORK_AREA (for multibyte
1916 characters) while translating them and paying attention to the
1917 continuity of translated characters.
1919 Implementation note: It is better to implement these fairly big
1920 macros by a function, but it's not that easy because macros called
1921 in this macro assume various local variables already declared. */
1923 /* Both FROM and TO are ASCII characters. */
1925 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1926 do { \
1927 int C0, C1; \
1929 for (C0 = (FROM); C0 <= (TO); C0++) \
1931 C1 = TRANSLATE (C0); \
1932 if (! ASCII_CHAR_P (C1)) \
1934 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1935 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1936 C1 = C0; \
1938 SET_LIST_BIT (C1); \
1940 } while (0)
1943 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1945 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1946 do { \
1947 int C0, C1, C2, I; \
1948 int USED = RANGE_TABLE_WORK_USED (work_area); \
1950 for (C0 = (FROM); C0 <= (TO); C0++) \
1952 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1953 if (CHAR_BYTE8_P (C1)) \
1954 SET_LIST_BIT (C0); \
1955 else \
1957 C2 = TRANSLATE (C1); \
1958 if (C2 == C1 \
1959 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1960 C1 = C0; \
1961 SET_LIST_BIT (C1); \
1962 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1964 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1965 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1967 if (C2 >= from - 1 && C2 <= to + 1) \
1969 if (C2 == from - 1) \
1970 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1971 else if (C2 == to + 1) \
1972 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1973 break; \
1976 if (I < USED) \
1977 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1980 } while (0)
1983 /* Both FROM and TO are multibyte characters. */
1985 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1986 do { \
1987 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1989 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1990 for (C0 = (FROM); C0 <= (TO); C0++) \
1992 C1 = TRANSLATE (C0); \
1993 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1994 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1995 SET_LIST_BIT (C2); \
1996 if (C1 >= (FROM) && C1 <= (TO)) \
1997 continue; \
1998 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2000 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2001 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2003 if (C1 >= from - 1 && C1 <= to + 1) \
2005 if (C1 == from - 1) \
2006 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2007 else if (C1 == to + 1) \
2008 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2009 break; \
2012 if (I < USED) \
2013 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2015 } while (0)
2017 #endif /* emacs */
2019 /* Get the next unsigned number in the uncompiled pattern. */
2020 #define GET_UNSIGNED_NUMBER(num) \
2021 do { \
2022 if (p == pend) \
2023 FREE_STACK_RETURN (REG_EBRACE); \
2024 else \
2026 PATFETCH (c); \
2027 while ('0' <= c && c <= '9') \
2029 int prev; \
2030 if (num < 0) \
2031 num = 0; \
2032 prev = num; \
2033 num = num * 10 + c - '0'; \
2034 if (num / 10 != prev) \
2035 FREE_STACK_RETURN (REG_BADBR); \
2036 if (p == pend) \
2037 FREE_STACK_RETURN (REG_EBRACE); \
2038 PATFETCH (c); \
2041 } while (0)
2043 #if ! WIDE_CHAR_SUPPORT
2045 /* Map a string to the char class it names (if any). */
2046 re_wctype_t
2047 re_wctype (const re_char *str)
2049 const char *string = (const char *) str;
2050 if (STREQ (string, "alnum")) return RECC_ALNUM;
2051 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2052 else if (STREQ (string, "word")) return RECC_WORD;
2053 else if (STREQ (string, "ascii")) return RECC_ASCII;
2054 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2055 else if (STREQ (string, "graph")) return RECC_GRAPH;
2056 else if (STREQ (string, "lower")) return RECC_LOWER;
2057 else if (STREQ (string, "print")) return RECC_PRINT;
2058 else if (STREQ (string, "punct")) return RECC_PUNCT;
2059 else if (STREQ (string, "space")) return RECC_SPACE;
2060 else if (STREQ (string, "upper")) return RECC_UPPER;
2061 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2062 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2063 else if (STREQ (string, "digit")) return RECC_DIGIT;
2064 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2065 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2066 else if (STREQ (string, "blank")) return RECC_BLANK;
2067 else return 0;
2070 /* True if CH is in the char class CC. */
2071 boolean
2072 re_iswctype (int ch, re_wctype_t cc)
2074 switch (cc)
2076 case RECC_ALNUM: return ISALNUM (ch) != 0;
2077 case RECC_ALPHA: return ISALPHA (ch) != 0;
2078 case RECC_BLANK: return ISBLANK (ch) != 0;
2079 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2080 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2081 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2082 case RECC_LOWER: return ISLOWER (ch) != 0;
2083 case RECC_PRINT: return ISPRINT (ch) != 0;
2084 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2085 case RECC_SPACE: return ISSPACE (ch) != 0;
2086 case RECC_UPPER: return ISUPPER (ch) != 0;
2087 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2088 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2089 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2090 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2091 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2092 case RECC_WORD: return ISWORD (ch) != 0;
2093 case RECC_ERROR: return false;
2094 default:
2095 abort ();
2099 /* Return a bit-pattern to use in the range-table bits to match multibyte
2100 chars of class CC. */
2101 static int
2102 re_wctype_to_bit (re_wctype_t cc)
2104 switch (cc)
2106 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2107 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2108 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2109 case RECC_LOWER: return BIT_LOWER;
2110 case RECC_UPPER: return BIT_UPPER;
2111 case RECC_PUNCT: return BIT_PUNCT;
2112 case RECC_SPACE: return BIT_SPACE;
2113 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2114 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2115 default:
2116 abort ();
2119 #endif
2121 /* Filling in the work area of a range. */
2123 /* Actually extend the space in WORK_AREA. */
2125 static void
2126 extend_range_table_work_area (struct range_table_work_area *work_area)
2128 work_area->allocated += 16 * sizeof (int);
2129 work_area->table = realloc (work_area->table, work_area->allocated);
2132 #if 0
2133 #ifdef emacs
2135 /* Carefully find the ranges of codes that are equivalent
2136 under case conversion to the range start..end when passed through
2137 TRANSLATE. Handle the case where non-letters can come in between
2138 two upper-case letters (which happens in Latin-1).
2139 Also handle the case of groups of more than 2 case-equivalent chars.
2141 The basic method is to look at consecutive characters and see
2142 if they can form a run that can be handled as one.
2144 Returns -1 if successful, REG_ESPACE if ran out of space. */
2146 static int
2147 set_image_of_range_1 (struct range_table_work_area *work_area,
2148 re_wchar_t start, re_wchar_t end,
2149 RE_TRANSLATE_TYPE translate)
2151 /* `one_case' indicates a character, or a run of characters,
2152 each of which is an isolate (no case-equivalents).
2153 This includes all ASCII non-letters.
2155 `two_case' indicates a character, or a run of characters,
2156 each of which has two case-equivalent forms.
2157 This includes all ASCII letters.
2159 `strange' indicates a character that has more than one
2160 case-equivalent. */
2162 enum case_type {one_case, two_case, strange};
2164 /* Describe the run that is in progress,
2165 which the next character can try to extend.
2166 If run_type is strange, that means there really is no run.
2167 If run_type is one_case, then run_start...run_end is the run.
2168 If run_type is two_case, then the run is run_start...run_end,
2169 and the case-equivalents end at run_eqv_end. */
2171 enum case_type run_type = strange;
2172 int run_start, run_end, run_eqv_end;
2174 Lisp_Object eqv_table;
2176 if (!RE_TRANSLATE_P (translate))
2178 EXTEND_RANGE_TABLE (work_area, 2);
2179 work_area->table[work_area->used++] = (start);
2180 work_area->table[work_area->used++] = (end);
2181 return -1;
2184 eqv_table = XCHAR_TABLE (translate)->extras[2];
2186 for (; start <= end; start++)
2188 enum case_type this_type;
2189 int eqv = RE_TRANSLATE (eqv_table, start);
2190 int minchar, maxchar;
2192 /* Classify this character */
2193 if (eqv == start)
2194 this_type = one_case;
2195 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2196 this_type = two_case;
2197 else
2198 this_type = strange;
2200 if (start < eqv)
2201 minchar = start, maxchar = eqv;
2202 else
2203 minchar = eqv, maxchar = start;
2205 /* Can this character extend the run in progress? */
2206 if (this_type == strange || this_type != run_type
2207 || !(minchar == run_end + 1
2208 && (run_type == two_case
2209 ? maxchar == run_eqv_end + 1 : 1)))
2211 /* No, end the run.
2212 Record each of its equivalent ranges. */
2213 if (run_type == one_case)
2215 EXTEND_RANGE_TABLE (work_area, 2);
2216 work_area->table[work_area->used++] = run_start;
2217 work_area->table[work_area->used++] = run_end;
2219 else if (run_type == two_case)
2221 EXTEND_RANGE_TABLE (work_area, 4);
2222 work_area->table[work_area->used++] = run_start;
2223 work_area->table[work_area->used++] = run_end;
2224 work_area->table[work_area->used++]
2225 = RE_TRANSLATE (eqv_table, run_start);
2226 work_area->table[work_area->used++]
2227 = RE_TRANSLATE (eqv_table, run_end);
2229 run_type = strange;
2232 if (this_type == strange)
2234 /* For a strange character, add each of its equivalents, one
2235 by one. Don't start a range. */
2238 EXTEND_RANGE_TABLE (work_area, 2);
2239 work_area->table[work_area->used++] = eqv;
2240 work_area->table[work_area->used++] = eqv;
2241 eqv = RE_TRANSLATE (eqv_table, eqv);
2243 while (eqv != start);
2246 /* Add this char to the run, or start a new run. */
2247 else if (run_type == strange)
2249 /* Initialize a new range. */
2250 run_type = this_type;
2251 run_start = start;
2252 run_end = start;
2253 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2255 else
2257 /* Extend a running range. */
2258 run_end = minchar;
2259 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2263 /* If a run is still in progress at the end, finish it now
2264 by recording its equivalent ranges. */
2265 if (run_type == one_case)
2267 EXTEND_RANGE_TABLE (work_area, 2);
2268 work_area->table[work_area->used++] = run_start;
2269 work_area->table[work_area->used++] = run_end;
2271 else if (run_type == two_case)
2273 EXTEND_RANGE_TABLE (work_area, 4);
2274 work_area->table[work_area->used++] = run_start;
2275 work_area->table[work_area->used++] = run_end;
2276 work_area->table[work_area->used++]
2277 = RE_TRANSLATE (eqv_table, run_start);
2278 work_area->table[work_area->used++]
2279 = RE_TRANSLATE (eqv_table, run_end);
2282 return -1;
2285 #endif /* emacs */
2287 /* Record the image of the range start..end when passed through
2288 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2289 and is not even necessarily contiguous.
2290 Normally we approximate it with the smallest contiguous range that contains
2291 all the chars we need. However, for Latin-1 we go to extra effort
2292 to do a better job.
2294 This function is not called for ASCII ranges.
2296 Returns -1 if successful, REG_ESPACE if ran out of space. */
2298 static int
2299 set_image_of_range (struct range_table_work_area *work_area,
2300 re_wchar_t start, re_wchar_t end,
2301 RE_TRANSLATE_TYPE translate)
2303 re_wchar_t cmin, cmax;
2305 #ifdef emacs
2306 /* For Latin-1 ranges, use set_image_of_range_1
2307 to get proper handling of ranges that include letters and nonletters.
2308 For a range that includes the whole of Latin-1, this is not necessary.
2309 For other character sets, we don't bother to get this right. */
2310 if (RE_TRANSLATE_P (translate) && start < 04400
2311 && !(start < 04200 && end >= 04377))
2313 int newend;
2314 int tem;
2315 newend = end;
2316 if (newend > 04377)
2317 newend = 04377;
2318 tem = set_image_of_range_1 (work_area, start, newend, translate);
2319 if (tem > 0)
2320 return tem;
2322 start = 04400;
2323 if (end < 04400)
2324 return -1;
2326 #endif
2328 EXTEND_RANGE_TABLE (work_area, 2);
2329 work_area->table[work_area->used++] = (start);
2330 work_area->table[work_area->used++] = (end);
2332 cmin = -1, cmax = -1;
2334 if (RE_TRANSLATE_P (translate))
2336 int ch;
2338 for (ch = start; ch <= end; ch++)
2340 re_wchar_t c = TRANSLATE (ch);
2341 if (! (start <= c && c <= end))
2343 if (cmin == -1)
2344 cmin = c, cmax = c;
2345 else
2347 cmin = MIN (cmin, c);
2348 cmax = MAX (cmax, c);
2353 if (cmin != -1)
2355 EXTEND_RANGE_TABLE (work_area, 2);
2356 work_area->table[work_area->used++] = (cmin);
2357 work_area->table[work_area->used++] = (cmax);
2361 return -1;
2363 #endif /* 0 */
2365 #ifndef MATCH_MAY_ALLOCATE
2367 /* If we cannot allocate large objects within re_match_2_internal,
2368 we make the fail stack and register vectors global.
2369 The fail stack, we grow to the maximum size when a regexp
2370 is compiled.
2371 The register vectors, we adjust in size each time we
2372 compile a regexp, according to the number of registers it needs. */
2374 static fail_stack_type fail_stack;
2376 /* Size with which the following vectors are currently allocated.
2377 That is so we can make them bigger as needed,
2378 but never make them smaller. */
2379 static int regs_allocated_size;
2381 static re_char ** regstart, ** regend;
2382 static re_char **best_regstart, **best_regend;
2384 /* Make the register vectors big enough for NUM_REGS registers,
2385 but don't make them smaller. */
2387 static
2388 regex_grow_registers (int num_regs)
2390 if (num_regs > regs_allocated_size)
2392 RETALLOC_IF (regstart, num_regs, re_char *);
2393 RETALLOC_IF (regend, num_regs, re_char *);
2394 RETALLOC_IF (best_regstart, num_regs, re_char *);
2395 RETALLOC_IF (best_regend, num_regs, re_char *);
2397 regs_allocated_size = num_regs;
2401 #endif /* not MATCH_MAY_ALLOCATE */
2403 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2404 regnum_t regnum);
2406 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2407 Returns one of error codes defined in `regex.h', or zero for success.
2409 Assumes the `allocated' (and perhaps `buffer') and `translate'
2410 fields are set in BUFP on entry.
2412 If it succeeds, results are put in BUFP (if it returns an error, the
2413 contents of BUFP are undefined):
2414 `buffer' is the compiled pattern;
2415 `syntax' is set to SYNTAX;
2416 `used' is set to the length of the compiled pattern;
2417 `fastmap_accurate' is zero;
2418 `re_nsub' is the number of subexpressions in PATTERN;
2419 `not_bol' and `not_eol' are zero;
2421 The `fastmap' field is neither examined nor set. */
2423 /* Insert the `jump' from the end of last alternative to "here".
2424 The space for the jump has already been allocated. */
2425 #define FIXUP_ALT_JUMP() \
2426 do { \
2427 if (fixup_alt_jump) \
2428 STORE_JUMP (jump, fixup_alt_jump, b); \
2429 } while (0)
2432 /* Return, freeing storage we allocated. */
2433 #define FREE_STACK_RETURN(value) \
2434 do { \
2435 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2436 free (compile_stack.stack); \
2437 return value; \
2438 } while (0)
2440 static reg_errcode_t
2441 regex_compile (const re_char *pattern, size_t size, reg_syntax_t syntax, struct re_pattern_buffer *bufp)
2443 /* We fetch characters from PATTERN here. */
2444 register re_wchar_t c, c1;
2446 /* Points to the end of the buffer, where we should append. */
2447 register unsigned char *b;
2449 /* Keeps track of unclosed groups. */
2450 compile_stack_type compile_stack;
2452 /* Points to the current (ending) position in the pattern. */
2453 #ifdef AIX
2454 /* `const' makes AIX compiler fail. */
2455 unsigned char *p = pattern;
2456 #else
2457 re_char *p = pattern;
2458 #endif
2459 re_char *pend = pattern + size;
2461 /* How to translate the characters in the pattern. */
2462 RE_TRANSLATE_TYPE translate = bufp->translate;
2464 /* Address of the count-byte of the most recently inserted `exactn'
2465 command. This makes it possible to tell if a new exact-match
2466 character can be added to that command or if the character requires
2467 a new `exactn' command. */
2468 unsigned char *pending_exact = 0;
2470 /* Address of start of the most recently finished expression.
2471 This tells, e.g., postfix * where to find the start of its
2472 operand. Reset at the beginning of groups and alternatives. */
2473 unsigned char *laststart = 0;
2475 /* Address of beginning of regexp, or inside of last group. */
2476 unsigned char *begalt;
2478 /* Place in the uncompiled pattern (i.e., the {) to
2479 which to go back if the interval is invalid. */
2480 re_char *beg_interval;
2482 /* Address of the place where a forward jump should go to the end of
2483 the containing expression. Each alternative of an `or' -- except the
2484 last -- ends with a forward jump of this sort. */
2485 unsigned char *fixup_alt_jump = 0;
2487 /* Work area for range table of charset. */
2488 struct range_table_work_area range_table_work;
2490 /* If the object matched can contain multibyte characters. */
2491 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2493 /* Nonzero if we have pushed down into a subpattern. */
2494 int in_subpattern = 0;
2496 /* These hold the values of p, pattern, and pend from the main
2497 pattern when we have pushed into a subpattern. */
2498 re_char *main_p IF_LINT (= NULL);
2499 re_char *main_pattern IF_LINT (= NULL);
2500 re_char *main_pend IF_LINT (= NULL);
2502 #ifdef DEBUG
2503 debug++;
2504 DEBUG_PRINT1 ("\nCompiling pattern: ");
2505 if (debug > 0)
2507 unsigned debug_count;
2509 for (debug_count = 0; debug_count < size; debug_count++)
2510 putchar (pattern[debug_count]);
2511 putchar ('\n');
2513 #endif /* DEBUG */
2515 /* Initialize the compile stack. */
2516 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2517 if (compile_stack.stack == NULL)
2518 return REG_ESPACE;
2520 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2521 compile_stack.avail = 0;
2523 range_table_work.table = 0;
2524 range_table_work.allocated = 0;
2526 /* Initialize the pattern buffer. */
2527 bufp->syntax = syntax;
2528 bufp->fastmap_accurate = 0;
2529 bufp->not_bol = bufp->not_eol = 0;
2530 bufp->used_syntax = 0;
2532 /* Set `used' to zero, so that if we return an error, the pattern
2533 printer (for debugging) will think there's no pattern. We reset it
2534 at the end. */
2535 bufp->used = 0;
2537 /* Always count groups, whether or not bufp->no_sub is set. */
2538 bufp->re_nsub = 0;
2540 #if !defined emacs && !defined SYNTAX_TABLE
2541 /* Initialize the syntax table. */
2542 init_syntax_once ();
2543 #endif
2545 if (bufp->allocated == 0)
2547 if (bufp->buffer)
2548 { /* If zero allocated, but buffer is non-null, try to realloc
2549 enough space. This loses if buffer's address is bogus, but
2550 that is the user's responsibility. */
2551 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2553 else
2554 { /* Caller did not allocate a buffer. Do it for them. */
2555 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2557 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2559 bufp->allocated = INIT_BUF_SIZE;
2562 begalt = b = bufp->buffer;
2564 /* Loop through the uncompiled pattern until we're at the end. */
2565 while (1)
2567 if (p == pend)
2569 /* If this is the end of an included regexp,
2570 pop back to the main regexp and try again. */
2571 if (in_subpattern)
2573 in_subpattern = 0;
2574 pattern = main_pattern;
2575 p = main_p;
2576 pend = main_pend;
2577 continue;
2579 /* If this is the end of the main regexp, we are done. */
2580 break;
2583 PATFETCH (c);
2585 switch (c)
2587 case ' ':
2589 re_char *p1 = p;
2591 /* If there's no special whitespace regexp, treat
2592 spaces normally. And don't try to do this recursively. */
2593 if (!whitespace_regexp || in_subpattern)
2594 goto normal_char;
2596 /* Peek past following spaces. */
2597 while (p1 != pend)
2599 if (*p1 != ' ')
2600 break;
2601 p1++;
2603 /* If the spaces are followed by a repetition op,
2604 treat them normally. */
2605 if (p1 != pend
2606 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2607 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2608 goto normal_char;
2610 /* Replace the spaces with the whitespace regexp. */
2611 in_subpattern = 1;
2612 main_p = p1;
2613 main_pend = pend;
2614 main_pattern = pattern;
2615 p = pattern = whitespace_regexp;
2616 pend = p + strlen ((const char *) p);
2617 break;
2620 case '^':
2622 if ( /* If at start of pattern, it's an operator. */
2623 p == pattern + 1
2624 /* If context independent, it's an operator. */
2625 || syntax & RE_CONTEXT_INDEP_ANCHORS
2626 /* Otherwise, depends on what's come before. */
2627 || at_begline_loc_p (pattern, p, syntax))
2628 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2629 else
2630 goto normal_char;
2632 break;
2635 case '$':
2637 if ( /* If at end of pattern, it's an operator. */
2638 p == pend
2639 /* If context independent, it's an operator. */
2640 || syntax & RE_CONTEXT_INDEP_ANCHORS
2641 /* Otherwise, depends on what's next. */
2642 || at_endline_loc_p (p, pend, syntax))
2643 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2644 else
2645 goto normal_char;
2647 break;
2650 case '+':
2651 case '?':
2652 if ((syntax & RE_BK_PLUS_QM)
2653 || (syntax & RE_LIMITED_OPS))
2654 goto normal_char;
2655 handle_plus:
2656 case '*':
2657 /* If there is no previous pattern... */
2658 if (!laststart)
2660 if (syntax & RE_CONTEXT_INVALID_OPS)
2661 FREE_STACK_RETURN (REG_BADRPT);
2662 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2663 goto normal_char;
2667 /* 1 means zero (many) matches is allowed. */
2668 boolean zero_times_ok = 0, many_times_ok = 0;
2669 boolean greedy = 1;
2671 /* If there is a sequence of repetition chars, collapse it
2672 down to just one (the right one). We can't combine
2673 interval operators with these because of, e.g., `a{2}*',
2674 which should only match an even number of `a's. */
2676 for (;;)
2678 if ((syntax & RE_FRUGAL)
2679 && c == '?' && (zero_times_ok || many_times_ok))
2680 greedy = 0;
2681 else
2683 zero_times_ok |= c != '+';
2684 many_times_ok |= c != '?';
2687 if (p == pend)
2688 break;
2689 else if (*p == '*'
2690 || (!(syntax & RE_BK_PLUS_QM)
2691 && (*p == '+' || *p == '?')))
2693 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2695 if (p+1 == pend)
2696 FREE_STACK_RETURN (REG_EESCAPE);
2697 if (p[1] == '+' || p[1] == '?')
2698 PATFETCH (c); /* Gobble up the backslash. */
2699 else
2700 break;
2702 else
2703 break;
2704 /* If we get here, we found another repeat character. */
2705 PATFETCH (c);
2708 /* Star, etc. applied to an empty pattern is equivalent
2709 to an empty pattern. */
2710 if (!laststart || laststart == b)
2711 break;
2713 /* Now we know whether or not zero matches is allowed
2714 and also whether or not two or more matches is allowed. */
2715 if (greedy)
2717 if (many_times_ok)
2719 boolean simple = skip_one_char (laststart) == b;
2720 size_t startoffset = 0;
2721 re_opcode_t ofj =
2722 /* Check if the loop can match the empty string. */
2723 (simple || !analyse_first (laststart, b, NULL, 0))
2724 ? on_failure_jump : on_failure_jump_loop;
2725 assert (skip_one_char (laststart) <= b);
2727 if (!zero_times_ok && simple)
2728 { /* Since simple * loops can be made faster by using
2729 on_failure_keep_string_jump, we turn simple P+
2730 into PP* if P is simple. */
2731 unsigned char *p1, *p2;
2732 startoffset = b - laststart;
2733 GET_BUFFER_SPACE (startoffset);
2734 p1 = b; p2 = laststart;
2735 while (p2 < p1)
2736 *b++ = *p2++;
2737 zero_times_ok = 1;
2740 GET_BUFFER_SPACE (6);
2741 if (!zero_times_ok)
2742 /* A + loop. */
2743 STORE_JUMP (ofj, b, b + 6);
2744 else
2745 /* Simple * loops can use on_failure_keep_string_jump
2746 depending on what follows. But since we don't know
2747 that yet, we leave the decision up to
2748 on_failure_jump_smart. */
2749 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2750 laststart + startoffset, b + 6);
2751 b += 3;
2752 STORE_JUMP (jump, b, laststart + startoffset);
2753 b += 3;
2755 else
2757 /* A simple ? pattern. */
2758 assert (zero_times_ok);
2759 GET_BUFFER_SPACE (3);
2760 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2761 b += 3;
2764 else /* not greedy */
2765 { /* I wish the greedy and non-greedy cases could be merged. */
2767 GET_BUFFER_SPACE (7); /* We might use less. */
2768 if (many_times_ok)
2770 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2772 /* The non-greedy multiple match looks like
2773 a repeat..until: we only need a conditional jump
2774 at the end of the loop. */
2775 if (emptyp) BUF_PUSH (no_op);
2776 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2777 : on_failure_jump, b, laststart);
2778 b += 3;
2779 if (zero_times_ok)
2781 /* The repeat...until naturally matches one or more.
2782 To also match zero times, we need to first jump to
2783 the end of the loop (its conditional jump). */
2784 INSERT_JUMP (jump, laststart, b);
2785 b += 3;
2788 else
2790 /* non-greedy a?? */
2791 INSERT_JUMP (jump, laststart, b + 3);
2792 b += 3;
2793 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2794 b += 3;
2798 pending_exact = 0;
2799 break;
2802 case '.':
2803 laststart = b;
2804 BUF_PUSH (anychar);
2805 break;
2808 case '[':
2810 re_char *p1;
2812 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2814 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2816 /* Ensure that we have enough space to push a charset: the
2817 opcode, the length count, and the bitset; 34 bytes in all. */
2818 GET_BUFFER_SPACE (34);
2820 laststart = b;
2822 /* We test `*p == '^' twice, instead of using an if
2823 statement, so we only need one BUF_PUSH. */
2824 BUF_PUSH (*p == '^' ? charset_not : charset);
2825 if (*p == '^')
2826 p++;
2828 /* Remember the first position in the bracket expression. */
2829 p1 = p;
2831 /* Push the number of bytes in the bitmap. */
2832 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2834 /* Clear the whole map. */
2835 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2837 /* charset_not matches newline according to a syntax bit. */
2838 if ((re_opcode_t) b[-2] == charset_not
2839 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2840 SET_LIST_BIT ('\n');
2842 /* Read in characters and ranges, setting map bits. */
2843 for (;;)
2845 boolean escaped_char = false;
2846 const unsigned char *p2 = p;
2847 re_wchar_t ch;
2849 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2851 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2852 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2853 So the translation is done later in a loop. Example:
2854 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2855 PATFETCH (c);
2857 /* \ might escape characters inside [...] and [^...]. */
2858 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2860 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2862 PATFETCH (c);
2863 escaped_char = true;
2865 else
2867 /* Could be the end of the bracket expression. If it's
2868 not (i.e., when the bracket expression is `[]' so
2869 far), the ']' character bit gets set way below. */
2870 if (c == ']' && p2 != p1)
2871 break;
2874 /* See if we're at the beginning of a possible character
2875 class. */
2877 if (!escaped_char &&
2878 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2880 /* Leave room for the null. */
2881 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2882 const unsigned char *class_beg;
2884 PATFETCH (c);
2885 c1 = 0;
2886 class_beg = p;
2888 /* If pattern is `[[:'. */
2889 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2891 for (;;)
2893 PATFETCH (c);
2894 if ((c == ':' && *p == ']') || p == pend)
2895 break;
2896 if (c1 < CHAR_CLASS_MAX_LENGTH)
2897 str[c1++] = c;
2898 else
2899 /* This is in any case an invalid class name. */
2900 str[0] = '\0';
2902 str[c1] = '\0';
2904 /* If isn't a word bracketed by `[:' and `:]':
2905 undo the ending character, the letters, and
2906 leave the leading `:' and `[' (but set bits for
2907 them). */
2908 if (c == ':' && *p == ']')
2910 re_wctype_t cc = re_wctype (str);
2912 if (cc == 0)
2913 FREE_STACK_RETURN (REG_ECTYPE);
2915 /* Throw away the ] at the end of the character
2916 class. */
2917 PATFETCH (c);
2919 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2921 #ifndef emacs
2922 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2923 if (re_iswctype (btowc (ch), cc))
2925 c = TRANSLATE (ch);
2926 if (c < (1 << BYTEWIDTH))
2927 SET_LIST_BIT (c);
2929 #else /* emacs */
2930 /* Most character classes in a multibyte match
2931 just set a flag. Exceptions are is_blank,
2932 is_digit, is_cntrl, and is_xdigit, since
2933 they can only match ASCII characters. We
2934 don't need to handle them for multibyte.
2935 They are distinguished by a negative wctype. */
2937 /* Setup the gl_state object to its buffer-defined
2938 value. This hardcodes the buffer-global
2939 syntax-table for ASCII chars, while the other chars
2940 will obey syntax-table properties. It's not ideal,
2941 but it's the way it's been done until now. */
2942 SETUP_BUFFER_SYNTAX_TABLE ();
2944 for (ch = 0; ch < 256; ++ch)
2946 c = RE_CHAR_TO_MULTIBYTE (ch);
2947 if (! CHAR_BYTE8_P (c)
2948 && re_iswctype (c, cc))
2950 SET_LIST_BIT (ch);
2951 c1 = TRANSLATE (c);
2952 if (c1 == c)
2953 continue;
2954 if (ASCII_CHAR_P (c1))
2955 SET_LIST_BIT (c1);
2956 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2957 SET_LIST_BIT (c1);
2960 SET_RANGE_TABLE_WORK_AREA_BIT
2961 (range_table_work, re_wctype_to_bit (cc));
2962 #endif /* emacs */
2963 /* In most cases the matching rule for char classes
2964 only uses the syntax table for multibyte chars,
2965 so that the content of the syntax-table it is not
2966 hardcoded in the range_table. SPACE and WORD are
2967 the two exceptions. */
2968 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2969 bufp->used_syntax = 1;
2971 /* Repeat the loop. */
2972 continue;
2974 else
2976 /* Go back to right after the "[:". */
2977 p = class_beg;
2978 SET_LIST_BIT ('[');
2980 /* Because the `:' may starts the range, we
2981 can't simply set bit and repeat the loop.
2982 Instead, just set it to C and handle below. */
2983 c = ':';
2987 if (p < pend && p[0] == '-' && p[1] != ']')
2990 /* Discard the `-'. */
2991 PATFETCH (c1);
2993 /* Fetch the character which ends the range. */
2994 PATFETCH (c1);
2995 #ifdef emacs
2996 if (CHAR_BYTE8_P (c1)
2997 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2998 /* Treat the range from a multibyte character to
2999 raw-byte character as empty. */
3000 c = c1 + 1;
3001 #endif /* emacs */
3003 else
3004 /* Range from C to C. */
3005 c1 = c;
3007 if (c > c1)
3009 if (syntax & RE_NO_EMPTY_RANGES)
3010 FREE_STACK_RETURN (REG_ERANGEX);
3011 /* Else, repeat the loop. */
3013 else
3015 #ifndef emacs
3016 /* Set the range into bitmap */
3017 for (; c <= c1; c++)
3019 ch = TRANSLATE (c);
3020 if (ch < (1 << BYTEWIDTH))
3021 SET_LIST_BIT (ch);
3023 #else /* emacs */
3024 if (c < 128)
3026 ch = MIN (127, c1);
3027 SETUP_ASCII_RANGE (range_table_work, c, ch);
3028 c = ch + 1;
3029 if (CHAR_BYTE8_P (c1))
3030 c = BYTE8_TO_CHAR (128);
3032 if (c <= c1)
3034 if (CHAR_BYTE8_P (c))
3036 c = CHAR_TO_BYTE8 (c);
3037 c1 = CHAR_TO_BYTE8 (c1);
3038 for (; c <= c1; c++)
3039 SET_LIST_BIT (c);
3041 else if (multibyte)
3043 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
3045 else
3047 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
3050 #endif /* emacs */
3054 /* Discard any (non)matching list bytes that are all 0 at the
3055 end of the map. Decrease the map-length byte too. */
3056 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3057 b[-1]--;
3058 b += b[-1];
3060 /* Build real range table from work area. */
3061 if (RANGE_TABLE_WORK_USED (range_table_work)
3062 || RANGE_TABLE_WORK_BITS (range_table_work))
3064 int i;
3065 int used = RANGE_TABLE_WORK_USED (range_table_work);
3067 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3068 bytes for flags, two for COUNT, and three bytes for
3069 each character. */
3070 GET_BUFFER_SPACE (4 + used * 3);
3072 /* Indicate the existence of range table. */
3073 laststart[1] |= 0x80;
3075 /* Store the character class flag bits into the range table.
3076 If not in emacs, these flag bits are always 0. */
3077 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3078 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3080 STORE_NUMBER_AND_INCR (b, used / 2);
3081 for (i = 0; i < used; i++)
3082 STORE_CHARACTER_AND_INCR
3083 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3086 break;
3089 case '(':
3090 if (syntax & RE_NO_BK_PARENS)
3091 goto handle_open;
3092 else
3093 goto normal_char;
3096 case ')':
3097 if (syntax & RE_NO_BK_PARENS)
3098 goto handle_close;
3099 else
3100 goto normal_char;
3103 case '\n':
3104 if (syntax & RE_NEWLINE_ALT)
3105 goto handle_alt;
3106 else
3107 goto normal_char;
3110 case '|':
3111 if (syntax & RE_NO_BK_VBAR)
3112 goto handle_alt;
3113 else
3114 goto normal_char;
3117 case '{':
3118 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3119 goto handle_interval;
3120 else
3121 goto normal_char;
3124 case '\\':
3125 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3127 /* Do not translate the character after the \, so that we can
3128 distinguish, e.g., \B from \b, even if we normally would
3129 translate, e.g., B to b. */
3130 PATFETCH (c);
3132 switch (c)
3134 case '(':
3135 if (syntax & RE_NO_BK_PARENS)
3136 goto normal_backslash;
3138 handle_open:
3140 int shy = 0;
3141 regnum_t regnum = 0;
3142 if (p+1 < pend)
3144 /* Look for a special (?...) construct */
3145 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3147 PATFETCH (c); /* Gobble up the '?'. */
3148 while (!shy)
3150 PATFETCH (c);
3151 switch (c)
3153 case ':': shy = 1; break;
3154 case '0':
3155 /* An explicitly specified regnum must start
3156 with non-0. */
3157 if (regnum == 0)
3158 FREE_STACK_RETURN (REG_BADPAT);
3159 case '1': case '2': case '3': case '4':
3160 case '5': case '6': case '7': case '8': case '9':
3161 regnum = 10*regnum + (c - '0'); break;
3162 default:
3163 /* Only (?:...) is supported right now. */
3164 FREE_STACK_RETURN (REG_BADPAT);
3170 if (!shy)
3171 regnum = ++bufp->re_nsub;
3172 else if (regnum)
3173 { /* It's actually not shy, but explicitly numbered. */
3174 shy = 0;
3175 if (regnum > bufp->re_nsub)
3176 bufp->re_nsub = regnum;
3177 else if (regnum > bufp->re_nsub
3178 /* Ideally, we'd want to check that the specified
3179 group can't have matched (i.e. all subgroups
3180 using the same regnum are in other branches of
3181 OR patterns), but we don't currently keep track
3182 of enough info to do that easily. */
3183 || group_in_compile_stack (compile_stack, regnum))
3184 FREE_STACK_RETURN (REG_BADPAT);
3186 else
3187 /* It's really shy. */
3188 regnum = - bufp->re_nsub;
3190 if (COMPILE_STACK_FULL)
3192 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3193 compile_stack_elt_t);
3194 if (compile_stack.stack == NULL) return REG_ESPACE;
3196 compile_stack.size <<= 1;
3199 /* These are the values to restore when we hit end of this
3200 group. They are all relative offsets, so that if the
3201 whole pattern moves because of realloc, they will still
3202 be valid. */
3203 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3204 COMPILE_STACK_TOP.fixup_alt_jump
3205 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3206 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3207 COMPILE_STACK_TOP.regnum = regnum;
3209 /* Do not push a start_memory for groups beyond the last one
3210 we can represent in the compiled pattern. */
3211 if (regnum <= MAX_REGNUM && regnum > 0)
3212 BUF_PUSH_2 (start_memory, regnum);
3214 compile_stack.avail++;
3216 fixup_alt_jump = 0;
3217 laststart = 0;
3218 begalt = b;
3219 /* If we've reached MAX_REGNUM groups, then this open
3220 won't actually generate any code, so we'll have to
3221 clear pending_exact explicitly. */
3222 pending_exact = 0;
3223 break;
3226 case ')':
3227 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3229 if (COMPILE_STACK_EMPTY)
3231 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3232 goto normal_backslash;
3233 else
3234 FREE_STACK_RETURN (REG_ERPAREN);
3237 handle_close:
3238 FIXUP_ALT_JUMP ();
3240 /* See similar code for backslashed left paren above. */
3241 if (COMPILE_STACK_EMPTY)
3243 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3244 goto normal_char;
3245 else
3246 FREE_STACK_RETURN (REG_ERPAREN);
3249 /* Since we just checked for an empty stack above, this
3250 ``can't happen''. */
3251 assert (compile_stack.avail != 0);
3253 /* We don't just want to restore into `regnum', because
3254 later groups should continue to be numbered higher,
3255 as in `(ab)c(de)' -- the second group is #2. */
3256 regnum_t regnum;
3258 compile_stack.avail--;
3259 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3260 fixup_alt_jump
3261 = COMPILE_STACK_TOP.fixup_alt_jump
3262 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3263 : 0;
3264 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3265 regnum = COMPILE_STACK_TOP.regnum;
3266 /* If we've reached MAX_REGNUM groups, then this open
3267 won't actually generate any code, so we'll have to
3268 clear pending_exact explicitly. */
3269 pending_exact = 0;
3271 /* We're at the end of the group, so now we know how many
3272 groups were inside this one. */
3273 if (regnum <= MAX_REGNUM && regnum > 0)
3274 BUF_PUSH_2 (stop_memory, regnum);
3276 break;
3279 case '|': /* `\|'. */
3280 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3281 goto normal_backslash;
3282 handle_alt:
3283 if (syntax & RE_LIMITED_OPS)
3284 goto normal_char;
3286 /* Insert before the previous alternative a jump which
3287 jumps to this alternative if the former fails. */
3288 GET_BUFFER_SPACE (3);
3289 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3290 pending_exact = 0;
3291 b += 3;
3293 /* The alternative before this one has a jump after it
3294 which gets executed if it gets matched. Adjust that
3295 jump so it will jump to this alternative's analogous
3296 jump (put in below, which in turn will jump to the next
3297 (if any) alternative's such jump, etc.). The last such
3298 jump jumps to the correct final destination. A picture:
3299 _____ _____
3300 | | | |
3301 | v | v
3302 a | b | c
3304 If we are at `b', then fixup_alt_jump right now points to a
3305 three-byte space after `a'. We'll put in the jump, set
3306 fixup_alt_jump to right after `b', and leave behind three
3307 bytes which we'll fill in when we get to after `c'. */
3309 FIXUP_ALT_JUMP ();
3311 /* Mark and leave space for a jump after this alternative,
3312 to be filled in later either by next alternative or
3313 when know we're at the end of a series of alternatives. */
3314 fixup_alt_jump = b;
3315 GET_BUFFER_SPACE (3);
3316 b += 3;
3318 laststart = 0;
3319 begalt = b;
3320 break;
3323 case '{':
3324 /* If \{ is a literal. */
3325 if (!(syntax & RE_INTERVALS)
3326 /* If we're at `\{' and it's not the open-interval
3327 operator. */
3328 || (syntax & RE_NO_BK_BRACES))
3329 goto normal_backslash;
3331 handle_interval:
3333 /* If got here, then the syntax allows intervals. */
3335 /* At least (most) this many matches must be made. */
3336 int lower_bound = 0, upper_bound = -1;
3338 beg_interval = p;
3340 GET_UNSIGNED_NUMBER (lower_bound);
3342 if (c == ',')
3343 GET_UNSIGNED_NUMBER (upper_bound);
3344 else
3345 /* Interval such as `{1}' => match exactly once. */
3346 upper_bound = lower_bound;
3348 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3349 || (upper_bound >= 0 && lower_bound > upper_bound))
3350 FREE_STACK_RETURN (REG_BADBR);
3352 if (!(syntax & RE_NO_BK_BRACES))
3354 if (c != '\\')
3355 FREE_STACK_RETURN (REG_BADBR);
3356 if (p == pend)
3357 FREE_STACK_RETURN (REG_EESCAPE);
3358 PATFETCH (c);
3361 if (c != '}')
3362 FREE_STACK_RETURN (REG_BADBR);
3364 /* We just parsed a valid interval. */
3366 /* If it's invalid to have no preceding re. */
3367 if (!laststart)
3369 if (syntax & RE_CONTEXT_INVALID_OPS)
3370 FREE_STACK_RETURN (REG_BADRPT);
3371 else if (syntax & RE_CONTEXT_INDEP_OPS)
3372 laststart = b;
3373 else
3374 goto unfetch_interval;
3377 if (upper_bound == 0)
3378 /* If the upper bound is zero, just drop the sub pattern
3379 altogether. */
3380 b = laststart;
3381 else if (lower_bound == 1 && upper_bound == 1)
3382 /* Just match it once: nothing to do here. */
3385 /* Otherwise, we have a nontrivial interval. When
3386 we're all done, the pattern will look like:
3387 set_number_at <jump count> <upper bound>
3388 set_number_at <succeed_n count> <lower bound>
3389 succeed_n <after jump addr> <succeed_n count>
3390 <body of loop>
3391 jump_n <succeed_n addr> <jump count>
3392 (The upper bound and `jump_n' are omitted if
3393 `upper_bound' is 1, though.) */
3394 else
3395 { /* If the upper bound is > 1, we need to insert
3396 more at the end of the loop. */
3397 unsigned int nbytes = (upper_bound < 0 ? 3
3398 : upper_bound > 1 ? 5 : 0);
3399 unsigned int startoffset = 0;
3401 GET_BUFFER_SPACE (20); /* We might use less. */
3403 if (lower_bound == 0)
3405 /* A succeed_n that starts with 0 is really a
3406 a simple on_failure_jump_loop. */
3407 INSERT_JUMP (on_failure_jump_loop, laststart,
3408 b + 3 + nbytes);
3409 b += 3;
3411 else
3413 /* Initialize lower bound of the `succeed_n', even
3414 though it will be set during matching by its
3415 attendant `set_number_at' (inserted next),
3416 because `re_compile_fastmap' needs to know.
3417 Jump to the `jump_n' we might insert below. */
3418 INSERT_JUMP2 (succeed_n, laststart,
3419 b + 5 + nbytes,
3420 lower_bound);
3421 b += 5;
3423 /* Code to initialize the lower bound. Insert
3424 before the `succeed_n'. The `5' is the last two
3425 bytes of this `set_number_at', plus 3 bytes of
3426 the following `succeed_n'. */
3427 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3428 b += 5;
3429 startoffset += 5;
3432 if (upper_bound < 0)
3434 /* A negative upper bound stands for infinity,
3435 in which case it degenerates to a plain jump. */
3436 STORE_JUMP (jump, b, laststart + startoffset);
3437 b += 3;
3439 else if (upper_bound > 1)
3440 { /* More than one repetition is allowed, so
3441 append a backward jump to the `succeed_n'
3442 that starts this interval.
3444 When we've reached this during matching,
3445 we'll have matched the interval once, so
3446 jump back only `upper_bound - 1' times. */
3447 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3448 upper_bound - 1);
3449 b += 5;
3451 /* The location we want to set is the second
3452 parameter of the `jump_n'; that is `b-2' as
3453 an absolute address. `laststart' will be
3454 the `set_number_at' we're about to insert;
3455 `laststart+3' the number to set, the source
3456 for the relative address. But we are
3457 inserting into the middle of the pattern --
3458 so everything is getting moved up by 5.
3459 Conclusion: (b - 2) - (laststart + 3) + 5,
3460 i.e., b - laststart.
3462 We insert this at the beginning of the loop
3463 so that if we fail during matching, we'll
3464 reinitialize the bounds. */
3465 insert_op2 (set_number_at, laststart, b - laststart,
3466 upper_bound - 1, b);
3467 b += 5;
3470 pending_exact = 0;
3471 beg_interval = NULL;
3473 break;
3475 unfetch_interval:
3476 /* If an invalid interval, match the characters as literals. */
3477 assert (beg_interval);
3478 p = beg_interval;
3479 beg_interval = NULL;
3481 /* normal_char and normal_backslash need `c'. */
3482 c = '{';
3484 if (!(syntax & RE_NO_BK_BRACES))
3486 assert (p > pattern && p[-1] == '\\');
3487 goto normal_backslash;
3489 else
3490 goto normal_char;
3492 #ifdef emacs
3493 /* There is no way to specify the before_dot and after_dot
3494 operators. rms says this is ok. --karl */
3495 case '=':
3496 BUF_PUSH (at_dot);
3497 break;
3499 case 's':
3500 laststart = b;
3501 PATFETCH (c);
3502 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3503 break;
3505 case 'S':
3506 laststart = b;
3507 PATFETCH (c);
3508 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3509 break;
3511 case 'c':
3512 laststart = b;
3513 PATFETCH (c);
3514 BUF_PUSH_2 (categoryspec, c);
3515 break;
3517 case 'C':
3518 laststart = b;
3519 PATFETCH (c);
3520 BUF_PUSH_2 (notcategoryspec, c);
3521 break;
3522 #endif /* emacs */
3525 case 'w':
3526 if (syntax & RE_NO_GNU_OPS)
3527 goto normal_char;
3528 laststart = b;
3529 BUF_PUSH_2 (syntaxspec, Sword);
3530 break;
3533 case 'W':
3534 if (syntax & RE_NO_GNU_OPS)
3535 goto normal_char;
3536 laststart = b;
3537 BUF_PUSH_2 (notsyntaxspec, Sword);
3538 break;
3541 case '<':
3542 if (syntax & RE_NO_GNU_OPS)
3543 goto normal_char;
3544 BUF_PUSH (wordbeg);
3545 break;
3547 case '>':
3548 if (syntax & RE_NO_GNU_OPS)
3549 goto normal_char;
3550 BUF_PUSH (wordend);
3551 break;
3553 case '_':
3554 if (syntax & RE_NO_GNU_OPS)
3555 goto normal_char;
3556 laststart = b;
3557 PATFETCH (c);
3558 if (c == '<')
3559 BUF_PUSH (symbeg);
3560 else if (c == '>')
3561 BUF_PUSH (symend);
3562 else
3563 FREE_STACK_RETURN (REG_BADPAT);
3564 break;
3566 case 'b':
3567 if (syntax & RE_NO_GNU_OPS)
3568 goto normal_char;
3569 BUF_PUSH (wordbound);
3570 break;
3572 case 'B':
3573 if (syntax & RE_NO_GNU_OPS)
3574 goto normal_char;
3575 BUF_PUSH (notwordbound);
3576 break;
3578 case '`':
3579 if (syntax & RE_NO_GNU_OPS)
3580 goto normal_char;
3581 BUF_PUSH (begbuf);
3582 break;
3584 case '\'':
3585 if (syntax & RE_NO_GNU_OPS)
3586 goto normal_char;
3587 BUF_PUSH (endbuf);
3588 break;
3590 case '1': case '2': case '3': case '4': case '5':
3591 case '6': case '7': case '8': case '9':
3593 regnum_t reg;
3595 if (syntax & RE_NO_BK_REFS)
3596 goto normal_backslash;
3598 reg = c - '0';
3600 if (reg > bufp->re_nsub || reg < 1
3601 /* Can't back reference to a subexp before its end. */
3602 || group_in_compile_stack (compile_stack, reg))
3603 FREE_STACK_RETURN (REG_ESUBREG);
3605 laststart = b;
3606 BUF_PUSH_2 (duplicate, reg);
3608 break;
3611 case '+':
3612 case '?':
3613 if (syntax & RE_BK_PLUS_QM)
3614 goto handle_plus;
3615 else
3616 goto normal_backslash;
3618 default:
3619 normal_backslash:
3620 /* You might think it would be useful for \ to mean
3621 not to translate; but if we don't translate it
3622 it will never match anything. */
3623 goto normal_char;
3625 break;
3628 default:
3629 /* Expects the character in `c'. */
3630 normal_char:
3631 /* If no exactn currently being built. */
3632 if (!pending_exact
3634 /* If last exactn not at current position. */
3635 || pending_exact + *pending_exact + 1 != b
3637 /* We have only one byte following the exactn for the count. */
3638 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3640 /* If followed by a repetition operator. */
3641 || (p != pend && (*p == '*' || *p == '^'))
3642 || ((syntax & RE_BK_PLUS_QM)
3643 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3644 : p != pend && (*p == '+' || *p == '?'))
3645 || ((syntax & RE_INTERVALS)
3646 && ((syntax & RE_NO_BK_BRACES)
3647 ? p != pend && *p == '{'
3648 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3650 /* Start building a new exactn. */
3652 laststart = b;
3654 BUF_PUSH_2 (exactn, 0);
3655 pending_exact = b - 1;
3658 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3660 int len;
3662 if (multibyte)
3664 c = TRANSLATE (c);
3665 len = CHAR_STRING (c, b);
3666 b += len;
3668 else
3670 c1 = RE_CHAR_TO_MULTIBYTE (c);
3671 if (! CHAR_BYTE8_P (c1))
3673 re_wchar_t c2 = TRANSLATE (c1);
3675 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3676 c = c1;
3678 *b++ = c;
3679 len = 1;
3681 (*pending_exact) += len;
3684 break;
3685 } /* switch (c) */
3686 } /* while p != pend */
3689 /* Through the pattern now. */
3691 FIXUP_ALT_JUMP ();
3693 if (!COMPILE_STACK_EMPTY)
3694 FREE_STACK_RETURN (REG_EPAREN);
3696 /* If we don't want backtracking, force success
3697 the first time we reach the end of the compiled pattern. */
3698 if (syntax & RE_NO_POSIX_BACKTRACKING)
3699 BUF_PUSH (succeed);
3701 /* We have succeeded; set the length of the buffer. */
3702 bufp->used = b - bufp->buffer;
3704 #ifdef DEBUG
3705 if (debug > 0)
3707 re_compile_fastmap (bufp);
3708 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3709 print_compiled_pattern (bufp);
3711 debug--;
3712 #endif /* DEBUG */
3714 #ifndef MATCH_MAY_ALLOCATE
3715 /* Initialize the failure stack to the largest possible stack. This
3716 isn't necessary unless we're trying to avoid calling alloca in
3717 the search and match routines. */
3719 int num_regs = bufp->re_nsub + 1;
3721 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3723 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3724 falk_stack.stack = realloc (fail_stack.stack,
3725 fail_stack.size * sizeof *falk_stack.stack);
3728 regex_grow_registers (num_regs);
3730 #endif /* not MATCH_MAY_ALLOCATE */
3732 FREE_STACK_RETURN (REG_NOERROR);
3733 } /* regex_compile */
3735 /* Subroutines for `regex_compile'. */
3737 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3739 static void
3740 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3742 *loc = (unsigned char) op;
3743 STORE_NUMBER (loc + 1, arg);
3747 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3749 static void
3750 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3752 *loc = (unsigned char) op;
3753 STORE_NUMBER (loc + 1, arg1);
3754 STORE_NUMBER (loc + 3, arg2);
3758 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3759 for OP followed by two-byte integer parameter ARG. */
3761 static void
3762 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3764 register unsigned char *pfrom = end;
3765 register unsigned char *pto = end + 3;
3767 while (pfrom != loc)
3768 *--pto = *--pfrom;
3770 store_op1 (op, loc, arg);
3774 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3776 static void
3777 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3779 register unsigned char *pfrom = end;
3780 register unsigned char *pto = end + 5;
3782 while (pfrom != loc)
3783 *--pto = *--pfrom;
3785 store_op2 (op, loc, arg1, arg2);
3789 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3790 after an alternative or a begin-subexpression. We assume there is at
3791 least one character before the ^. */
3793 static boolean
3794 at_begline_loc_p (const re_char *pattern, const re_char *p, reg_syntax_t syntax)
3796 re_char *prev = p - 2;
3797 boolean odd_backslashes;
3799 /* After a subexpression? */
3800 if (*prev == '(')
3801 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3803 /* After an alternative? */
3804 else if (*prev == '|')
3805 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3807 /* After a shy subexpression? */
3808 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3810 /* Skip over optional regnum. */
3811 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3812 --prev;
3814 if (!(prev - 2 >= pattern
3815 && prev[-1] == '?' && prev[-2] == '('))
3816 return false;
3817 prev -= 2;
3818 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3820 else
3821 return false;
3823 /* Count the number of preceding backslashes. */
3824 p = prev;
3825 while (prev - 1 >= pattern && prev[-1] == '\\')
3826 --prev;
3827 return (p - prev) & odd_backslashes;
3831 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3832 at least one character after the $, i.e., `P < PEND'. */
3834 static boolean
3835 at_endline_loc_p (const re_char *p, const re_char *pend, reg_syntax_t syntax)
3837 re_char *next = p;
3838 boolean next_backslash = *next == '\\';
3839 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3841 return
3842 /* Before a subexpression? */
3843 (syntax & RE_NO_BK_PARENS ? *next == ')'
3844 : next_backslash && next_next && *next_next == ')')
3845 /* Before an alternative? */
3846 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3847 : next_backslash && next_next && *next_next == '|');
3851 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3852 false if it's not. */
3854 static boolean
3855 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3857 ssize_t this_element;
3859 for (this_element = compile_stack.avail - 1;
3860 this_element >= 0;
3861 this_element--)
3862 if (compile_stack.stack[this_element].regnum == regnum)
3863 return true;
3865 return false;
3868 /* analyse_first.
3869 If fastmap is non-NULL, go through the pattern and fill fastmap
3870 with all the possible leading chars. If fastmap is NULL, don't
3871 bother filling it up (obviously) and only return whether the
3872 pattern could potentially match the empty string.
3874 Return 1 if p..pend might match the empty string.
3875 Return 0 if p..pend matches at least one char.
3876 Return -1 if fastmap was not updated accurately. */
3878 static int
3879 analyse_first (const re_char *p, const re_char *pend, char *fastmap, const int multibyte)
3881 int j, k;
3882 boolean not;
3884 /* If all elements for base leading-codes in fastmap is set, this
3885 flag is set true. */
3886 boolean match_any_multibyte_characters = false;
3888 assert (p);
3890 /* The loop below works as follows:
3891 - It has a working-list kept in the PATTERN_STACK and which basically
3892 starts by only containing a pointer to the first operation.
3893 - If the opcode we're looking at is a match against some set of
3894 chars, then we add those chars to the fastmap and go on to the
3895 next work element from the worklist (done via `break').
3896 - If the opcode is a control operator on the other hand, we either
3897 ignore it (if it's meaningless at this point, such as `start_memory')
3898 or execute it (if it's a jump). If the jump has several destinations
3899 (i.e. `on_failure_jump'), then we push the other destination onto the
3900 worklist.
3901 We guarantee termination by ignoring backward jumps (more or less),
3902 so that `p' is monotonically increasing. More to the point, we
3903 never set `p' (or push) anything `<= p1'. */
3905 while (p < pend)
3907 /* `p1' is used as a marker of how far back a `on_failure_jump'
3908 can go without being ignored. It is normally equal to `p'
3909 (which prevents any backward `on_failure_jump') except right
3910 after a plain `jump', to allow patterns such as:
3911 0: jump 10
3912 3..9: <body>
3913 10: on_failure_jump 3
3914 as used for the *? operator. */
3915 re_char *p1 = p;
3917 switch (*p++)
3919 case succeed:
3920 return 1;
3922 case duplicate:
3923 /* If the first character has to match a backreference, that means
3924 that the group was empty (since it already matched). Since this
3925 is the only case that interests us here, we can assume that the
3926 backreference must match the empty string. */
3927 p++;
3928 continue;
3931 /* Following are the cases which match a character. These end
3932 with `break'. */
3934 case exactn:
3935 if (fastmap)
3937 /* If multibyte is nonzero, the first byte of each
3938 character is an ASCII or a leading code. Otherwise,
3939 each byte is a character. Thus, this works in both
3940 cases. */
3941 fastmap[p[1]] = 1;
3942 if (! multibyte)
3944 /* For the case of matching this unibyte regex
3945 against multibyte, we must set a leading code of
3946 the corresponding multibyte character. */
3947 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3949 fastmap[CHAR_LEADING_CODE (c)] = 1;
3952 break;
3955 case anychar:
3956 /* We could put all the chars except for \n (and maybe \0)
3957 but we don't bother since it is generally not worth it. */
3958 if (!fastmap) break;
3959 return -1;
3962 case charset_not:
3963 if (!fastmap) break;
3965 /* Chars beyond end of bitmap are possible matches. */
3966 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3967 j < (1 << BYTEWIDTH); j++)
3968 fastmap[j] = 1;
3971 /* Fallthrough */
3972 case charset:
3973 if (!fastmap) break;
3974 not = (re_opcode_t) *(p - 1) == charset_not;
3975 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3976 j >= 0; j--)
3977 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3978 fastmap[j] = 1;
3980 #ifdef emacs
3981 if (/* Any leading code can possibly start a character
3982 which doesn't match the specified set of characters. */
3985 /* If we can match a character class, we can match any
3986 multibyte characters. */
3987 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3988 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3991 if (match_any_multibyte_characters == false)
3993 for (j = MIN_MULTIBYTE_LEADING_CODE;
3994 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3995 fastmap[j] = 1;
3996 match_any_multibyte_characters = true;
4000 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
4001 && match_any_multibyte_characters == false)
4003 /* Set fastmap[I] to 1 where I is a leading code of each
4004 multibyte character in the range table. */
4005 int c, count;
4006 unsigned char lc1, lc2;
4008 /* Make P points the range table. `+ 2' is to skip flag
4009 bits for a character class. */
4010 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
4012 /* Extract the number of ranges in range table into COUNT. */
4013 EXTRACT_NUMBER_AND_INCR (count, p);
4014 for (; count > 0; count--, p += 3)
4016 /* Extract the start and end of each range. */
4017 EXTRACT_CHARACTER (c, p);
4018 lc1 = CHAR_LEADING_CODE (c);
4019 p += 3;
4020 EXTRACT_CHARACTER (c, p);
4021 lc2 = CHAR_LEADING_CODE (c);
4022 for (j = lc1; j <= lc2; j++)
4023 fastmap[j] = 1;
4026 #endif
4027 break;
4029 case syntaxspec:
4030 case notsyntaxspec:
4031 if (!fastmap) break;
4032 #ifndef emacs
4033 not = (re_opcode_t)p[-1] == notsyntaxspec;
4034 k = *p++;
4035 for (j = 0; j < (1 << BYTEWIDTH); j++)
4036 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
4037 fastmap[j] = 1;
4038 break;
4039 #else /* emacs */
4040 /* This match depends on text properties. These end with
4041 aborting optimizations. */
4042 return -1;
4044 case categoryspec:
4045 case notcategoryspec:
4046 if (!fastmap) break;
4047 not = (re_opcode_t)p[-1] == notcategoryspec;
4048 k = *p++;
4049 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4050 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4051 fastmap[j] = 1;
4053 /* Any leading code can possibly start a character which
4054 has or doesn't has the specified category. */
4055 if (match_any_multibyte_characters == false)
4057 for (j = MIN_MULTIBYTE_LEADING_CODE;
4058 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4059 fastmap[j] = 1;
4060 match_any_multibyte_characters = true;
4062 break;
4064 /* All cases after this match the empty string. These end with
4065 `continue'. */
4067 case before_dot:
4068 case at_dot:
4069 case after_dot:
4070 #endif /* !emacs */
4071 case no_op:
4072 case begline:
4073 case endline:
4074 case begbuf:
4075 case endbuf:
4076 case wordbound:
4077 case notwordbound:
4078 case wordbeg:
4079 case wordend:
4080 case symbeg:
4081 case symend:
4082 continue;
4085 case jump:
4086 EXTRACT_NUMBER_AND_INCR (j, p);
4087 if (j < 0)
4088 /* Backward jumps can only go back to code that we've already
4089 visited. `re_compile' should make sure this is true. */
4090 break;
4091 p += j;
4092 switch (*p)
4094 case on_failure_jump:
4095 case on_failure_keep_string_jump:
4096 case on_failure_jump_loop:
4097 case on_failure_jump_nastyloop:
4098 case on_failure_jump_smart:
4099 p++;
4100 break;
4101 default:
4102 continue;
4104 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4105 to jump back to "just after here". */
4106 /* Fallthrough */
4108 case on_failure_jump:
4109 case on_failure_keep_string_jump:
4110 case on_failure_jump_nastyloop:
4111 case on_failure_jump_loop:
4112 case on_failure_jump_smart:
4113 EXTRACT_NUMBER_AND_INCR (j, p);
4114 if (p + j <= p1)
4115 ; /* Backward jump to be ignored. */
4116 else
4117 { /* We have to look down both arms.
4118 We first go down the "straight" path so as to minimize
4119 stack usage when going through alternatives. */
4120 int r = analyse_first (p, pend, fastmap, multibyte);
4121 if (r) return r;
4122 p += j;
4124 continue;
4127 case jump_n:
4128 /* This code simply does not properly handle forward jump_n. */
4129 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4130 p += 4;
4131 /* jump_n can either jump or fall through. The (backward) jump
4132 case has already been handled, so we only need to look at the
4133 fallthrough case. */
4134 continue;
4136 case succeed_n:
4137 /* If N == 0, it should be an on_failure_jump_loop instead. */
4138 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4139 p += 4;
4140 /* We only care about one iteration of the loop, so we don't
4141 need to consider the case where this behaves like an
4142 on_failure_jump. */
4143 continue;
4146 case set_number_at:
4147 p += 4;
4148 continue;
4151 case start_memory:
4152 case stop_memory:
4153 p += 1;
4154 continue;
4157 default:
4158 abort (); /* We have listed all the cases. */
4159 } /* switch *p++ */
4161 /* Getting here means we have found the possible starting
4162 characters for one path of the pattern -- and that the empty
4163 string does not match. We need not follow this path further. */
4164 return 0;
4165 } /* while p */
4167 /* We reached the end without matching anything. */
4168 return 1;
4170 } /* analyse_first */
4172 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4173 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4174 characters can start a string that matches the pattern. This fastmap
4175 is used by re_search to skip quickly over impossible starting points.
4177 Character codes above (1 << BYTEWIDTH) are not represented in the
4178 fastmap, but the leading codes are represented. Thus, the fastmap
4179 indicates which character sets could start a match.
4181 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4182 area as BUFP->fastmap.
4184 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4185 the pattern buffer.
4187 Returns 0 if we succeed, -2 if an internal error. */
4190 re_compile_fastmap (struct re_pattern_buffer *bufp)
4192 char *fastmap = bufp->fastmap;
4193 int analysis;
4195 assert (fastmap && bufp->buffer);
4197 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4198 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4200 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
4201 fastmap, RE_MULTIBYTE_P (bufp));
4202 bufp->can_be_null = (analysis != 0);
4203 return 0;
4204 } /* re_compile_fastmap */
4206 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4207 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4208 this memory for recording register information. STARTS and ENDS
4209 must be allocated using the malloc library routine, and must each
4210 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4212 If NUM_REGS == 0, then subsequent matches should allocate their own
4213 register data.
4215 Unless this function is called, the first search or match using
4216 PATTERN_BUFFER will allocate its own register data, without
4217 freeing the old data. */
4219 void
4220 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4222 if (num_regs)
4224 bufp->regs_allocated = REGS_REALLOCATE;
4225 regs->num_regs = num_regs;
4226 regs->start = starts;
4227 regs->end = ends;
4229 else
4231 bufp->regs_allocated = REGS_UNALLOCATED;
4232 regs->num_regs = 0;
4233 regs->start = regs->end = (regoff_t *) 0;
4236 WEAK_ALIAS (__re_set_registers, re_set_registers)
4238 /* Searching routines. */
4240 /* Like re_search_2, below, but only one string is specified, and
4241 doesn't let you say where to stop matching. */
4243 regoff_t
4244 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4245 ssize_t startpos, ssize_t range, struct re_registers *regs)
4247 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4248 regs, size);
4250 WEAK_ALIAS (__re_search, re_search)
4252 /* Head address of virtual concatenation of string. */
4253 #define HEAD_ADDR_VSTRING(P) \
4254 (((P) >= size1 ? string2 : string1))
4256 /* Address of POS in the concatenation of virtual string. */
4257 #define POS_ADDR_VSTRING(POS) \
4258 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4260 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4261 virtual concatenation of STRING1 and STRING2, starting first at index
4262 STARTPOS, then at STARTPOS + 1, and so on.
4264 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4266 RANGE is how far to scan while trying to match. RANGE = 0 means try
4267 only at STARTPOS; in general, the last start tried is STARTPOS +
4268 RANGE.
4270 In REGS, return the indices of the virtual concatenation of STRING1
4271 and STRING2 that matched the entire BUFP->buffer and its contained
4272 subexpressions.
4274 Do not consider matching one past the index STOP in the virtual
4275 concatenation of STRING1 and STRING2.
4277 We return either the position in the strings at which the match was
4278 found, -1 if no match, or -2 if error (such as failure
4279 stack overflow). */
4281 regoff_t
4282 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4283 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4284 struct re_registers *regs, ssize_t stop)
4286 regoff_t val;
4287 re_char *string1 = (re_char*) str1;
4288 re_char *string2 = (re_char*) str2;
4289 register char *fastmap = bufp->fastmap;
4290 register RE_TRANSLATE_TYPE translate = bufp->translate;
4291 size_t total_size = size1 + size2;
4292 ssize_t endpos = startpos + range;
4293 boolean anchored_start;
4294 /* Nonzero if we are searching multibyte string. */
4295 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4297 /* Check for out-of-range STARTPOS. */
4298 if (startpos < 0 || startpos > total_size)
4299 return -1;
4301 /* Fix up RANGE if it might eventually take us outside
4302 the virtual concatenation of STRING1 and STRING2.
4303 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4304 if (endpos < 0)
4305 range = 0 - startpos;
4306 else if (endpos > total_size)
4307 range = total_size - startpos;
4309 /* If the search isn't to be a backwards one, don't waste time in a
4310 search for a pattern anchored at beginning of buffer. */
4311 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4313 if (startpos > 0)
4314 return -1;
4315 else
4316 range = 0;
4319 #ifdef emacs
4320 /* In a forward search for something that starts with \=.
4321 don't keep searching past point. */
4322 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4324 range = PT_BYTE - BEGV_BYTE - startpos;
4325 if (range < 0)
4326 return -1;
4328 #endif /* emacs */
4330 /* Update the fastmap now if not correct already. */
4331 if (fastmap && !bufp->fastmap_accurate)
4332 re_compile_fastmap (bufp);
4334 /* See whether the pattern is anchored. */
4335 anchored_start = (bufp->buffer[0] == begline);
4337 #ifdef emacs
4338 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4340 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4342 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4344 #endif
4346 /* Loop through the string, looking for a place to start matching. */
4347 for (;;)
4349 /* If the pattern is anchored,
4350 skip quickly past places we cannot match.
4351 We don't bother to treat startpos == 0 specially
4352 because that case doesn't repeat. */
4353 if (anchored_start && startpos > 0)
4355 if (! ((startpos <= size1 ? string1[startpos - 1]
4356 : string2[startpos - size1 - 1])
4357 == '\n'))
4358 goto advance;
4361 /* If a fastmap is supplied, skip quickly over characters that
4362 cannot be the start of a match. If the pattern can match the
4363 null string, however, we don't need to skip characters; we want
4364 the first null string. */
4365 if (fastmap && startpos < total_size && !bufp->can_be_null)
4367 register re_char *d;
4368 register re_wchar_t buf_ch;
4370 d = POS_ADDR_VSTRING (startpos);
4372 if (range > 0) /* Searching forwards. */
4374 register int lim = 0;
4375 ssize_t irange = range;
4377 if (startpos < size1 && startpos + range >= size1)
4378 lim = range - (size1 - startpos);
4380 /* Written out as an if-else to avoid testing `translate'
4381 inside the loop. */
4382 if (RE_TRANSLATE_P (translate))
4384 if (multibyte)
4385 while (range > lim)
4387 int buf_charlen;
4389 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4390 buf_ch = RE_TRANSLATE (translate, buf_ch);
4391 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4392 break;
4394 range -= buf_charlen;
4395 d += buf_charlen;
4397 else
4398 while (range > lim)
4400 register re_wchar_t ch, translated;
4402 buf_ch = *d;
4403 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4404 translated = RE_TRANSLATE (translate, ch);
4405 if (translated != ch
4406 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4407 buf_ch = ch;
4408 if (fastmap[buf_ch])
4409 break;
4410 d++;
4411 range--;
4414 else
4416 if (multibyte)
4417 while (range > lim)
4419 int buf_charlen;
4421 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4422 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4423 break;
4424 range -= buf_charlen;
4425 d += buf_charlen;
4427 else
4428 while (range > lim && !fastmap[*d])
4430 d++;
4431 range--;
4434 startpos += irange - range;
4436 else /* Searching backwards. */
4438 if (multibyte)
4440 buf_ch = STRING_CHAR (d);
4441 buf_ch = TRANSLATE (buf_ch);
4442 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4443 goto advance;
4445 else
4447 register re_wchar_t ch, translated;
4449 buf_ch = *d;
4450 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4451 translated = TRANSLATE (ch);
4452 if (translated != ch
4453 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4454 buf_ch = ch;
4455 if (! fastmap[TRANSLATE (buf_ch)])
4456 goto advance;
4461 /* If can't match the null string, and that's all we have left, fail. */
4462 if (range >= 0 && startpos == total_size && fastmap
4463 && !bufp->can_be_null)
4464 return -1;
4466 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4467 startpos, regs, stop);
4469 if (val >= 0)
4470 return startpos;
4472 if (val == -2)
4473 return -2;
4475 advance:
4476 if (!range)
4477 break;
4478 else if (range > 0)
4480 /* Update STARTPOS to the next character boundary. */
4481 if (multibyte)
4483 re_char *p = POS_ADDR_VSTRING (startpos);
4484 int len = BYTES_BY_CHAR_HEAD (*p);
4486 range -= len;
4487 if (range < 0)
4488 break;
4489 startpos += len;
4491 else
4493 range--;
4494 startpos++;
4497 else
4499 range++;
4500 startpos--;
4502 /* Update STARTPOS to the previous character boundary. */
4503 if (multibyte)
4505 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4506 re_char *p0 = p;
4507 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4509 /* Find the head of multibyte form. */
4510 PREV_CHAR_BOUNDARY (p, phead);
4511 range += p0 - 1 - p;
4512 if (range > 0)
4513 break;
4515 startpos -= p0 - 1 - p;
4519 return -1;
4520 } /* re_search_2 */
4521 WEAK_ALIAS (__re_search_2, re_search_2)
4523 /* Declarations and macros for re_match_2. */
4525 static int bcmp_translate (re_char *s1, re_char *s2,
4526 register ssize_t len,
4527 RE_TRANSLATE_TYPE translate,
4528 const int multibyte);
4530 /* This converts PTR, a pointer into one of the search strings `string1'
4531 and `string2' into an offset from the beginning of that string. */
4532 #define POINTER_TO_OFFSET(ptr) \
4533 (FIRST_STRING_P (ptr) \
4534 ? ((regoff_t) ((ptr) - string1)) \
4535 : ((regoff_t) ((ptr) - string2 + size1)))
4537 /* Call before fetching a character with *d. This switches over to
4538 string2 if necessary.
4539 Check re_match_2_internal for a discussion of why end_match_2 might
4540 not be within string2 (but be equal to end_match_1 instead). */
4541 #define PREFETCH() \
4542 while (d == dend) \
4544 /* End of string2 => fail. */ \
4545 if (dend == end_match_2) \
4546 goto fail; \
4547 /* End of string1 => advance to string2. */ \
4548 d = string2; \
4549 dend = end_match_2; \
4552 /* Call before fetching a char with *d if you already checked other limits.
4553 This is meant for use in lookahead operations like wordend, etc..
4554 where we might need to look at parts of the string that might be
4555 outside of the LIMITs (i.e past `stop'). */
4556 #define PREFETCH_NOLIMIT() \
4557 if (d == end1) \
4559 d = string2; \
4560 dend = end_match_2; \
4563 /* Test if at very beginning or at very end of the virtual concatenation
4564 of `string1' and `string2'. If only one string, it's `string2'. */
4565 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4566 #define AT_STRINGS_END(d) ((d) == end2)
4568 /* Disabled due to a compiler bug -- see comment at case wordbound */
4570 /* The comment at case wordbound is following one, but we don't use
4571 AT_WORD_BOUNDARY anymore to support multibyte form.
4573 The DEC Alpha C compiler 3.x generates incorrect code for the
4574 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4575 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4576 macro and introducing temporary variables works around the bug. */
4578 #if 0
4579 /* Test if D points to a character which is word-constituent. We have
4580 two special cases to check for: if past the end of string1, look at
4581 the first character in string2; and if before the beginning of
4582 string2, look at the last character in string1. */
4583 #define WORDCHAR_P(d) \
4584 (SYNTAX ((d) == end1 ? *string2 \
4585 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4586 == Sword)
4588 /* Test if the character before D and the one at D differ with respect
4589 to being word-constituent. */
4590 #define AT_WORD_BOUNDARY(d) \
4591 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4592 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4593 #endif
4595 /* Free everything we malloc. */
4596 #ifdef MATCH_MAY_ALLOCATE
4597 # define FREE_VAR(var) \
4598 do { \
4599 if (var) \
4601 REGEX_FREE (var); \
4602 var = NULL; \
4604 } while (0)
4605 # define FREE_VARIABLES() \
4606 do { \
4607 REGEX_FREE_STACK (fail_stack.stack); \
4608 FREE_VAR (regstart); \
4609 FREE_VAR (regend); \
4610 FREE_VAR (best_regstart); \
4611 FREE_VAR (best_regend); \
4612 } while (0)
4613 #else
4614 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4615 #endif /* not MATCH_MAY_ALLOCATE */
4618 /* Optimization routines. */
4620 /* If the operation is a match against one or more chars,
4621 return a pointer to the next operation, else return NULL. */
4622 static re_char *
4623 skip_one_char (const re_char *p)
4625 switch (*p++)
4627 case anychar:
4628 break;
4630 case exactn:
4631 p += *p + 1;
4632 break;
4634 case charset_not:
4635 case charset:
4636 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4638 int mcnt;
4639 p = CHARSET_RANGE_TABLE (p - 1);
4640 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4641 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4643 else
4644 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4645 break;
4647 case syntaxspec:
4648 case notsyntaxspec:
4649 #ifdef emacs
4650 case categoryspec:
4651 case notcategoryspec:
4652 #endif /* emacs */
4653 p++;
4654 break;
4656 default:
4657 p = NULL;
4659 return p;
4663 /* Jump over non-matching operations. */
4664 static re_char *
4665 skip_noops (const re_char *p, const re_char *pend)
4667 int mcnt;
4668 while (p < pend)
4670 switch (*p)
4672 case start_memory:
4673 case stop_memory:
4674 p += 2; break;
4675 case no_op:
4676 p += 1; break;
4677 case jump:
4678 p += 1;
4679 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4680 p += mcnt;
4681 break;
4682 default:
4683 return p;
4686 assert (p == pend);
4687 return p;
4690 /* Non-zero if "p1 matches something" implies "p2 fails". */
4691 static int
4692 mutually_exclusive_p (struct re_pattern_buffer *bufp, const re_char *p1, const re_char *p2)
4694 re_opcode_t op2;
4695 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4696 unsigned char *pend = bufp->buffer + bufp->used;
4698 assert (p1 >= bufp->buffer && p1 < pend
4699 && p2 >= bufp->buffer && p2 <= pend);
4701 /* Skip over open/close-group commands.
4702 If what follows this loop is a ...+ construct,
4703 look at what begins its body, since we will have to
4704 match at least one of that. */
4705 p2 = skip_noops (p2, pend);
4706 /* The same skip can be done for p1, except that this function
4707 is only used in the case where p1 is a simple match operator. */
4708 /* p1 = skip_noops (p1, pend); */
4710 assert (p1 >= bufp->buffer && p1 < pend
4711 && p2 >= bufp->buffer && p2 <= pend);
4713 op2 = p2 == pend ? succeed : *p2;
4715 switch (op2)
4717 case succeed:
4718 case endbuf:
4719 /* If we're at the end of the pattern, we can change. */
4720 if (skip_one_char (p1))
4722 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4723 return 1;
4725 break;
4727 case endline:
4728 case exactn:
4730 register re_wchar_t c
4731 = (re_opcode_t) *p2 == endline ? '\n'
4732 : RE_STRING_CHAR (p2 + 2, multibyte);
4734 if ((re_opcode_t) *p1 == exactn)
4736 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4738 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4739 return 1;
4743 else if ((re_opcode_t) *p1 == charset
4744 || (re_opcode_t) *p1 == charset_not)
4746 int not = (re_opcode_t) *p1 == charset_not;
4748 /* Test if C is listed in charset (or charset_not)
4749 at `p1'. */
4750 if (! multibyte || IS_REAL_ASCII (c))
4752 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4753 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4754 not = !not;
4756 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4757 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4759 /* `not' is equal to 1 if c would match, which means
4760 that we can't change to pop_failure_jump. */
4761 if (!not)
4763 DEBUG_PRINT1 (" No match => fast loop.\n");
4764 return 1;
4767 else if ((re_opcode_t) *p1 == anychar
4768 && c == '\n')
4770 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4771 return 1;
4774 break;
4776 case charset:
4778 if ((re_opcode_t) *p1 == exactn)
4779 /* Reuse the code above. */
4780 return mutually_exclusive_p (bufp, p2, p1);
4782 /* It is hard to list up all the character in charset
4783 P2 if it includes multibyte character. Give up in
4784 such case. */
4785 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4787 /* Now, we are sure that P2 has no range table.
4788 So, for the size of bitmap in P2, `p2[1]' is
4789 enough. But P1 may have range table, so the
4790 size of bitmap table of P1 is extracted by
4791 using macro `CHARSET_BITMAP_SIZE'.
4793 In a multibyte case, we know that all the character
4794 listed in P2 is ASCII. In a unibyte case, P1 has only a
4795 bitmap table. So, in both cases, it is enough to test
4796 only the bitmap table of P1. */
4798 if ((re_opcode_t) *p1 == charset)
4800 int idx;
4801 /* We win if the charset inside the loop
4802 has no overlap with the one after the loop. */
4803 for (idx = 0;
4804 (idx < (int) p2[1]
4805 && idx < CHARSET_BITMAP_SIZE (p1));
4806 idx++)
4807 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4808 break;
4810 if (idx == p2[1]
4811 || idx == CHARSET_BITMAP_SIZE (p1))
4813 DEBUG_PRINT1 (" No match => fast loop.\n");
4814 return 1;
4817 else if ((re_opcode_t) *p1 == charset_not)
4819 int idx;
4820 /* We win if the charset_not inside the loop lists
4821 every character listed in the charset after. */
4822 for (idx = 0; idx < (int) p2[1]; idx++)
4823 if (! (p2[2 + idx] == 0
4824 || (idx < CHARSET_BITMAP_SIZE (p1)
4825 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4826 break;
4828 if (idx == p2[1])
4830 DEBUG_PRINT1 (" No match => fast loop.\n");
4831 return 1;
4836 break;
4838 case charset_not:
4839 switch (*p1)
4841 case exactn:
4842 case charset:
4843 /* Reuse the code above. */
4844 return mutually_exclusive_p (bufp, p2, p1);
4845 case charset_not:
4846 /* When we have two charset_not, it's very unlikely that
4847 they don't overlap. The union of the two sets of excluded
4848 chars should cover all possible chars, which, as a matter of
4849 fact, is virtually impossible in multibyte buffers. */
4850 break;
4852 break;
4854 case wordend:
4855 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4856 case symend:
4857 return ((re_opcode_t) *p1 == syntaxspec
4858 && (p1[1] == Ssymbol || p1[1] == Sword));
4859 case notsyntaxspec:
4860 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4862 case wordbeg:
4863 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4864 case symbeg:
4865 return ((re_opcode_t) *p1 == notsyntaxspec
4866 && (p1[1] == Ssymbol || p1[1] == Sword));
4867 case syntaxspec:
4868 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4870 case wordbound:
4871 return (((re_opcode_t) *p1 == notsyntaxspec
4872 || (re_opcode_t) *p1 == syntaxspec)
4873 && p1[1] == Sword);
4875 #ifdef emacs
4876 case categoryspec:
4877 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4878 case notcategoryspec:
4879 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4880 #endif /* emacs */
4882 default:
4886 /* Safe default. */
4887 return 0;
4891 /* Matching routines. */
4893 #ifndef emacs /* Emacs never uses this. */
4894 /* re_match is like re_match_2 except it takes only a single string. */
4896 regoff_t
4897 re_match (struct re_pattern_buffer *bufp, const char *string,
4898 size_t size, ssize_t pos, struct re_registers *regs)
4900 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4901 size, pos, regs, size);
4902 return result;
4904 WEAK_ALIAS (__re_match, re_match)
4905 #endif /* not emacs */
4907 /* re_match_2 matches the compiled pattern in BUFP against the
4908 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4909 and SIZE2, respectively). We start matching at POS, and stop
4910 matching at STOP.
4912 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4913 store offsets for the substring each group matched in REGS. See the
4914 documentation for exactly how many groups we fill.
4916 We return -1 if no match, -2 if an internal error (such as the
4917 failure stack overflowing). Otherwise, we return the length of the
4918 matched substring. */
4920 regoff_t
4921 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4922 size_t size1, const char *string2, size_t size2, ssize_t pos,
4923 struct re_registers *regs, ssize_t stop)
4925 regoff_t result;
4927 #ifdef emacs
4928 ssize_t charpos;
4929 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4930 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4931 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4932 #endif
4934 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4935 (re_char*) string2, size2,
4936 pos, regs, stop);
4937 return result;
4939 WEAK_ALIAS (__re_match_2, re_match_2)
4942 /* This is a separate function so that we can force an alloca cleanup
4943 afterwards. */
4944 static regoff_t
4945 re_match_2_internal (struct re_pattern_buffer *bufp, const re_char *string1,
4946 size_t size1, const re_char *string2, size_t size2,
4947 ssize_t pos, struct re_registers *regs, ssize_t stop)
4949 /* General temporaries. */
4950 ssize_t mcnt;
4951 size_t reg;
4953 /* Just past the end of the corresponding string. */
4954 re_char *end1, *end2;
4956 /* Pointers into string1 and string2, just past the last characters in
4957 each to consider matching. */
4958 re_char *end_match_1, *end_match_2;
4960 /* Where we are in the data, and the end of the current string. */
4961 re_char *d, *dend;
4963 /* Used sometimes to remember where we were before starting matching
4964 an operator so that we can go back in case of failure. This "atomic"
4965 behavior of matching opcodes is indispensable to the correctness
4966 of the on_failure_keep_string_jump optimization. */
4967 re_char *dfail;
4969 /* Where we are in the pattern, and the end of the pattern. */
4970 re_char *p = bufp->buffer;
4971 re_char *pend = p + bufp->used;
4973 /* We use this to map every character in the string. */
4974 RE_TRANSLATE_TYPE translate = bufp->translate;
4976 /* Nonzero if BUFP is setup from a multibyte regex. */
4977 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4979 /* Nonzero if STRING1/STRING2 are multibyte. */
4980 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4982 /* Failure point stack. Each place that can handle a failure further
4983 down the line pushes a failure point on this stack. It consists of
4984 regstart, and regend for all registers corresponding to
4985 the subexpressions we're currently inside, plus the number of such
4986 registers, and, finally, two char *'s. The first char * is where
4987 to resume scanning the pattern; the second one is where to resume
4988 scanning the strings. */
4989 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4990 fail_stack_type fail_stack;
4991 #endif
4992 #ifdef DEBUG
4993 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4994 #endif
4996 #if defined REL_ALLOC && defined REGEX_MALLOC
4997 /* This holds the pointer to the failure stack, when
4998 it is allocated relocatably. */
4999 fail_stack_elt_t *failure_stack_ptr;
5000 #endif
5002 /* We fill all the registers internally, independent of what we
5003 return, for use in backreferences. The number here includes
5004 an element for register zero. */
5005 size_t num_regs = bufp->re_nsub + 1;
5007 /* Information on the contents of registers. These are pointers into
5008 the input strings; they record just what was matched (on this
5009 attempt) by a subexpression part of the pattern, that is, the
5010 regnum-th regstart pointer points to where in the pattern we began
5011 matching and the regnum-th regend points to right after where we
5012 stopped matching the regnum-th subexpression. (The zeroth register
5013 keeps track of what the whole pattern matches.) */
5014 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5015 re_char **regstart, **regend;
5016 #endif
5018 /* The following record the register info as found in the above
5019 variables when we find a match better than any we've seen before.
5020 This happens as we backtrack through the failure points, which in
5021 turn happens only if we have not yet matched the entire string. */
5022 unsigned best_regs_set = false;
5023 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5024 re_char **best_regstart, **best_regend;
5025 #endif
5027 /* Logically, this is `best_regend[0]'. But we don't want to have to
5028 allocate space for that if we're not allocating space for anything
5029 else (see below). Also, we never need info about register 0 for
5030 any of the other register vectors, and it seems rather a kludge to
5031 treat `best_regend' differently than the rest. So we keep track of
5032 the end of the best match so far in a separate variable. We
5033 initialize this to NULL so that when we backtrack the first time
5034 and need to test it, it's not garbage. */
5035 re_char *match_end = NULL;
5037 #ifdef DEBUG
5038 /* Counts the total number of registers pushed. */
5039 unsigned num_regs_pushed = 0;
5040 #endif
5042 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5044 INIT_FAIL_STACK ();
5046 #ifdef MATCH_MAY_ALLOCATE
5047 /* Do not bother to initialize all the register variables if there are
5048 no groups in the pattern, as it takes a fair amount of time. If
5049 there are groups, we include space for register 0 (the whole
5050 pattern), even though we never use it, since it simplifies the
5051 array indexing. We should fix this. */
5052 if (bufp->re_nsub)
5054 regstart = REGEX_TALLOC (num_regs, re_char *);
5055 regend = REGEX_TALLOC (num_regs, re_char *);
5056 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5057 best_regend = REGEX_TALLOC (num_regs, re_char *);
5059 if (!(regstart && regend && best_regstart && best_regend))
5061 FREE_VARIABLES ();
5062 return -2;
5065 else
5067 /* We must initialize all our variables to NULL, so that
5068 `FREE_VARIABLES' doesn't try to free them. */
5069 regstart = regend = best_regstart = best_regend = NULL;
5071 #endif /* MATCH_MAY_ALLOCATE */
5073 /* The starting position is bogus. */
5074 if (pos < 0 || pos > size1 + size2)
5076 FREE_VARIABLES ();
5077 return -1;
5080 /* Initialize subexpression text positions to -1 to mark ones that no
5081 start_memory/stop_memory has been seen for. Also initialize the
5082 register information struct. */
5083 for (reg = 1; reg < num_regs; reg++)
5084 regstart[reg] = regend[reg] = NULL;
5086 /* We move `string1' into `string2' if the latter's empty -- but not if
5087 `string1' is null. */
5088 if (size2 == 0 && string1 != NULL)
5090 string2 = string1;
5091 size2 = size1;
5092 string1 = 0;
5093 size1 = 0;
5095 end1 = string1 + size1;
5096 end2 = string2 + size2;
5098 /* `p' scans through the pattern as `d' scans through the data.
5099 `dend' is the end of the input string that `d' points within. `d'
5100 is advanced into the following input string whenever necessary, but
5101 this happens before fetching; therefore, at the beginning of the
5102 loop, `d' can be pointing at the end of a string, but it cannot
5103 equal `string2'. */
5104 if (pos >= size1)
5106 /* Only match within string2. */
5107 d = string2 + pos - size1;
5108 dend = end_match_2 = string2 + stop - size1;
5109 end_match_1 = end1; /* Just to give it a value. */
5111 else
5113 if (stop < size1)
5115 /* Only match within string1. */
5116 end_match_1 = string1 + stop;
5117 /* BEWARE!
5118 When we reach end_match_1, PREFETCH normally switches to string2.
5119 But in the present case, this means that just doing a PREFETCH
5120 makes us jump from `stop' to `gap' within the string.
5121 What we really want here is for the search to stop as
5122 soon as we hit end_match_1. That's why we set end_match_2
5123 to end_match_1 (since PREFETCH fails as soon as we hit
5124 end_match_2). */
5125 end_match_2 = end_match_1;
5127 else
5128 { /* It's important to use this code when stop == size so that
5129 moving `d' from end1 to string2 will not prevent the d == dend
5130 check from catching the end of string. */
5131 end_match_1 = end1;
5132 end_match_2 = string2 + stop - size1;
5134 d = string1 + pos;
5135 dend = end_match_1;
5138 DEBUG_PRINT1 ("The compiled pattern is: ");
5139 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5140 DEBUG_PRINT1 ("The string to match is: `");
5141 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5142 DEBUG_PRINT1 ("'\n");
5144 /* This loops over pattern commands. It exits by returning from the
5145 function if the match is complete, or it drops through if the match
5146 fails at this starting point in the input data. */
5147 for (;;)
5149 DEBUG_PRINT2 ("\n%p: ", p);
5151 if (p == pend)
5152 { /* End of pattern means we might have succeeded. */
5153 DEBUG_PRINT1 ("end of pattern ... ");
5155 /* If we haven't matched the entire string, and we want the
5156 longest match, try backtracking. */
5157 if (d != end_match_2)
5159 /* 1 if this match ends in the same string (string1 or string2)
5160 as the best previous match. */
5161 boolean same_str_p = (FIRST_STRING_P (match_end)
5162 == FIRST_STRING_P (d));
5163 /* 1 if this match is the best seen so far. */
5164 boolean best_match_p;
5166 /* AIX compiler got confused when this was combined
5167 with the previous declaration. */
5168 if (same_str_p)
5169 best_match_p = d > match_end;
5170 else
5171 best_match_p = !FIRST_STRING_P (d);
5173 DEBUG_PRINT1 ("backtracking.\n");
5175 if (!FAIL_STACK_EMPTY ())
5176 { /* More failure points to try. */
5178 /* If exceeds best match so far, save it. */
5179 if (!best_regs_set || best_match_p)
5181 best_regs_set = true;
5182 match_end = d;
5184 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5186 for (reg = 1; reg < num_regs; reg++)
5188 best_regstart[reg] = regstart[reg];
5189 best_regend[reg] = regend[reg];
5192 goto fail;
5195 /* If no failure points, don't restore garbage. And if
5196 last match is real best match, don't restore second
5197 best one. */
5198 else if (best_regs_set && !best_match_p)
5200 restore_best_regs:
5201 /* Restore best match. It may happen that `dend ==
5202 end_match_1' while the restored d is in string2.
5203 For example, the pattern `x.*y.*z' against the
5204 strings `x-' and `y-z-', if the two strings are
5205 not consecutive in memory. */
5206 DEBUG_PRINT1 ("Restoring best registers.\n");
5208 d = match_end;
5209 dend = ((d >= string1 && d <= end1)
5210 ? end_match_1 : end_match_2);
5212 for (reg = 1; reg < num_regs; reg++)
5214 regstart[reg] = best_regstart[reg];
5215 regend[reg] = best_regend[reg];
5218 } /* d != end_match_2 */
5220 succeed_label:
5221 DEBUG_PRINT1 ("Accepting match.\n");
5223 /* If caller wants register contents data back, do it. */
5224 if (regs && !bufp->no_sub)
5226 /* Have the register data arrays been allocated? */
5227 if (bufp->regs_allocated == REGS_UNALLOCATED)
5228 { /* No. So allocate them with malloc. We need one
5229 extra element beyond `num_regs' for the `-1' marker
5230 GNU code uses. */
5231 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5232 regs->start = TALLOC (regs->num_regs, regoff_t);
5233 regs->end = TALLOC (regs->num_regs, regoff_t);
5234 if (regs->start == NULL || regs->end == NULL)
5236 FREE_VARIABLES ();
5237 return -2;
5239 bufp->regs_allocated = REGS_REALLOCATE;
5241 else if (bufp->regs_allocated == REGS_REALLOCATE)
5242 { /* Yes. If we need more elements than were already
5243 allocated, reallocate them. If we need fewer, just
5244 leave it alone. */
5245 if (regs->num_regs < num_regs + 1)
5247 regs->num_regs = num_regs + 1;
5248 RETALLOC (regs->start, regs->num_regs, regoff_t);
5249 RETALLOC (regs->end, regs->num_regs, regoff_t);
5250 if (regs->start == NULL || regs->end == NULL)
5252 FREE_VARIABLES ();
5253 return -2;
5257 else
5259 /* These braces fend off a "empty body in an else-statement"
5260 warning under GCC when assert expands to nothing. */
5261 assert (bufp->regs_allocated == REGS_FIXED);
5264 /* Convert the pointer data in `regstart' and `regend' to
5265 indices. Register zero has to be set differently,
5266 since we haven't kept track of any info for it. */
5267 if (regs->num_regs > 0)
5269 regs->start[0] = pos;
5270 regs->end[0] = POINTER_TO_OFFSET (d);
5273 /* Go through the first `min (num_regs, regs->num_regs)'
5274 registers, since that is all we initialized. */
5275 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
5277 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5278 regs->start[reg] = regs->end[reg] = -1;
5279 else
5281 regs->start[reg]
5282 = (regoff_t) POINTER_TO_OFFSET (regstart[reg]);
5283 regs->end[reg]
5284 = (regoff_t) POINTER_TO_OFFSET (regend[reg]);
5288 /* If the regs structure we return has more elements than
5289 were in the pattern, set the extra elements to -1. If
5290 we (re)allocated the registers, this is the case,
5291 because we always allocate enough to have at least one
5292 -1 at the end. */
5293 for (reg = num_regs; reg < regs->num_regs; reg++)
5294 regs->start[reg] = regs->end[reg] = -1;
5295 } /* regs && !bufp->no_sub */
5297 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5298 nfailure_points_pushed, nfailure_points_popped,
5299 nfailure_points_pushed - nfailure_points_popped);
5300 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5302 mcnt = POINTER_TO_OFFSET (d) - pos;
5304 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5306 FREE_VARIABLES ();
5307 return mcnt;
5310 /* Otherwise match next pattern command. */
5311 switch (*p++)
5313 /* Ignore these. Used to ignore the n of succeed_n's which
5314 currently have n == 0. */
5315 case no_op:
5316 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5317 break;
5319 case succeed:
5320 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5321 goto succeed_label;
5323 /* Match the next n pattern characters exactly. The following
5324 byte in the pattern defines n, and the n bytes after that
5325 are the characters to match. */
5326 case exactn:
5327 mcnt = *p++;
5328 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5330 /* Remember the start point to rollback upon failure. */
5331 dfail = d;
5333 #ifndef emacs
5334 /* This is written out as an if-else so we don't waste time
5335 testing `translate' inside the loop. */
5336 if (RE_TRANSLATE_P (translate))
5339 PREFETCH ();
5340 if (RE_TRANSLATE (translate, *d) != *p++)
5342 d = dfail;
5343 goto fail;
5345 d++;
5347 while (--mcnt);
5348 else
5351 PREFETCH ();
5352 if (*d++ != *p++)
5354 d = dfail;
5355 goto fail;
5358 while (--mcnt);
5359 #else /* emacs */
5360 /* The cost of testing `translate' is comparatively small. */
5361 if (target_multibyte)
5364 int pat_charlen, buf_charlen;
5365 int pat_ch, buf_ch;
5367 PREFETCH ();
5368 if (multibyte)
5369 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5370 else
5372 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5373 pat_charlen = 1;
5375 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5377 if (TRANSLATE (buf_ch) != pat_ch)
5379 d = dfail;
5380 goto fail;
5383 p += pat_charlen;
5384 d += buf_charlen;
5385 mcnt -= pat_charlen;
5387 while (mcnt > 0);
5388 else
5391 int pat_charlen;
5392 int pat_ch, buf_ch;
5394 PREFETCH ();
5395 if (multibyte)
5397 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5398 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5400 else
5402 pat_ch = *p;
5403 pat_charlen = 1;
5405 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5406 if (! CHAR_BYTE8_P (buf_ch))
5408 buf_ch = TRANSLATE (buf_ch);
5409 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5410 if (buf_ch < 0)
5411 buf_ch = *d;
5413 else
5414 buf_ch = *d;
5415 if (buf_ch != pat_ch)
5417 d = dfail;
5418 goto fail;
5420 p += pat_charlen;
5421 d++;
5423 while (--mcnt);
5424 #endif
5425 break;
5428 /* Match any character except possibly a newline or a null. */
5429 case anychar:
5431 int buf_charlen;
5432 re_wchar_t buf_ch;
5434 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5436 PREFETCH ();
5437 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5438 target_multibyte);
5439 buf_ch = TRANSLATE (buf_ch);
5441 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5442 && buf_ch == '\n')
5443 || ((bufp->syntax & RE_DOT_NOT_NULL)
5444 && buf_ch == '\000'))
5445 goto fail;
5447 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
5448 d += buf_charlen;
5450 break;
5453 case charset:
5454 case charset_not:
5456 register unsigned int c;
5457 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5458 int len;
5460 /* Start of actual range_table, or end of bitmap if there is no
5461 range table. */
5462 re_char *range_table IF_LINT (= NULL);
5464 /* Nonzero if there is a range table. */
5465 int range_table_exists;
5467 /* Number of ranges of range table. This is not included
5468 in the initial byte-length of the command. */
5469 int count = 0;
5471 /* Whether matching against a unibyte character. */
5472 boolean unibyte_char = false;
5474 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5476 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5478 if (range_table_exists)
5480 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5481 EXTRACT_NUMBER_AND_INCR (count, range_table);
5484 PREFETCH ();
5485 c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5486 if (target_multibyte)
5488 int c1;
5490 c = TRANSLATE (c);
5491 c1 = RE_CHAR_TO_UNIBYTE (c);
5492 if (c1 >= 0)
5494 unibyte_char = true;
5495 c = c1;
5498 else
5500 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5502 if (! CHAR_BYTE8_P (c1))
5504 c1 = TRANSLATE (c1);
5505 c1 = RE_CHAR_TO_UNIBYTE (c1);
5506 if (c1 >= 0)
5508 unibyte_char = true;
5509 c = c1;
5512 else
5513 unibyte_char = true;
5516 if (unibyte_char && c < (1 << BYTEWIDTH))
5517 { /* Lookup bitmap. */
5518 /* Cast to `unsigned' instead of `unsigned char' in
5519 case the bit list is a full 32 bytes long. */
5520 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5521 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5522 not = !not;
5524 #ifdef emacs
5525 else if (range_table_exists)
5527 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5529 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5530 | (class_bits & BIT_MULTIBYTE)
5531 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5532 | (class_bits & BIT_SPACE && ISSPACE (c))
5533 | (class_bits & BIT_UPPER && ISUPPER (c))
5534 | (class_bits & BIT_WORD && ISWORD (c)))
5535 not = !not;
5536 else
5537 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5539 #endif /* emacs */
5541 if (range_table_exists)
5542 p = CHARSET_RANGE_TABLE_END (range_table, count);
5543 else
5544 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5546 if (!not) goto fail;
5548 d += len;
5550 break;
5553 /* The beginning of a group is represented by start_memory.
5554 The argument is the register number. The text
5555 matched within the group is recorded (in the internal
5556 registers data structure) under the register number. */
5557 case start_memory:
5558 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5560 /* In case we need to undo this operation (via backtracking). */
5561 PUSH_FAILURE_REG ((unsigned int)*p);
5563 regstart[*p] = d;
5564 regend[*p] = NULL; /* probably unnecessary. -sm */
5565 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5567 /* Move past the register number and inner group count. */
5568 p += 1;
5569 break;
5572 /* The stop_memory opcode represents the end of a group. Its
5573 argument is the same as start_memory's: the register number. */
5574 case stop_memory:
5575 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5577 assert (!REG_UNSET (regstart[*p]));
5578 /* Strictly speaking, there should be code such as:
5580 assert (REG_UNSET (regend[*p]));
5581 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5583 But the only info to be pushed is regend[*p] and it is known to
5584 be UNSET, so there really isn't anything to push.
5585 Not pushing anything, on the other hand deprives us from the
5586 guarantee that regend[*p] is UNSET since undoing this operation
5587 will not reset its value properly. This is not important since
5588 the value will only be read on the next start_memory or at
5589 the very end and both events can only happen if this stop_memory
5590 is *not* undone. */
5592 regend[*p] = d;
5593 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5595 /* Move past the register number and the inner group count. */
5596 p += 1;
5597 break;
5600 /* \<digit> has been turned into a `duplicate' command which is
5601 followed by the numeric value of <digit> as the register number. */
5602 case duplicate:
5604 register re_char *d2, *dend2;
5605 int regno = *p++; /* Get which register to match against. */
5606 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5608 /* Can't back reference a group which we've never matched. */
5609 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5610 goto fail;
5612 /* Where in input to try to start matching. */
5613 d2 = regstart[regno];
5615 /* Remember the start point to rollback upon failure. */
5616 dfail = d;
5618 /* Where to stop matching; if both the place to start and
5619 the place to stop matching are in the same string, then
5620 set to the place to stop, otherwise, for now have to use
5621 the end of the first string. */
5623 dend2 = ((FIRST_STRING_P (regstart[regno])
5624 == FIRST_STRING_P (regend[regno]))
5625 ? regend[regno] : end_match_1);
5626 for (;;)
5628 /* If necessary, advance to next segment in register
5629 contents. */
5630 while (d2 == dend2)
5632 if (dend2 == end_match_2) break;
5633 if (dend2 == regend[regno]) break;
5635 /* End of string1 => advance to string2. */
5636 d2 = string2;
5637 dend2 = regend[regno];
5639 /* At end of register contents => success */
5640 if (d2 == dend2) break;
5642 /* If necessary, advance to next segment in data. */
5643 PREFETCH ();
5645 /* How many characters left in this segment to match. */
5646 mcnt = dend - d;
5648 /* Want how many consecutive characters we can match in
5649 one shot, so, if necessary, adjust the count. */
5650 if (mcnt > dend2 - d2)
5651 mcnt = dend2 - d2;
5653 /* Compare that many; failure if mismatch, else move
5654 past them. */
5655 if (RE_TRANSLATE_P (translate)
5656 ? bcmp_translate (d, d2, mcnt, translate, target_multibyte)
5657 : memcmp (d, d2, mcnt))
5659 d = dfail;
5660 goto fail;
5662 d += mcnt, d2 += mcnt;
5665 break;
5668 /* begline matches the empty string at the beginning of the string
5669 (unless `not_bol' is set in `bufp'), and after newlines. */
5670 case begline:
5671 DEBUG_PRINT1 ("EXECUTING begline.\n");
5673 if (AT_STRINGS_BEG (d))
5675 if (!bufp->not_bol) break;
5677 else
5679 unsigned c;
5680 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5681 if (c == '\n')
5682 break;
5684 /* In all other cases, we fail. */
5685 goto fail;
5688 /* endline is the dual of begline. */
5689 case endline:
5690 DEBUG_PRINT1 ("EXECUTING endline.\n");
5692 if (AT_STRINGS_END (d))
5694 if (!bufp->not_eol) break;
5696 else
5698 PREFETCH_NOLIMIT ();
5699 if (*d == '\n')
5700 break;
5702 goto fail;
5705 /* Match at the very beginning of the data. */
5706 case begbuf:
5707 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5708 if (AT_STRINGS_BEG (d))
5709 break;
5710 goto fail;
5713 /* Match at the very end of the data. */
5714 case endbuf:
5715 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5716 if (AT_STRINGS_END (d))
5717 break;
5718 goto fail;
5721 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5722 pushes NULL as the value for the string on the stack. Then
5723 `POP_FAILURE_POINT' will keep the current value for the
5724 string, instead of restoring it. To see why, consider
5725 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5726 then the . fails against the \n. But the next thing we want
5727 to do is match the \n against the \n; if we restored the
5728 string value, we would be back at the foo.
5730 Because this is used only in specific cases, we don't need to
5731 check all the things that `on_failure_jump' does, to make
5732 sure the right things get saved on the stack. Hence we don't
5733 share its code. The only reason to push anything on the
5734 stack at all is that otherwise we would have to change
5735 `anychar's code to do something besides goto fail in this
5736 case; that seems worse than this. */
5737 case on_failure_keep_string_jump:
5738 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5739 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5740 mcnt, p + mcnt);
5742 PUSH_FAILURE_POINT (p - 3, NULL);
5743 break;
5745 /* A nasty loop is introduced by the non-greedy *? and +?.
5746 With such loops, the stack only ever contains one failure point
5747 at a time, so that a plain on_failure_jump_loop kind of
5748 cycle detection cannot work. Worse yet, such a detection
5749 can not only fail to detect a cycle, but it can also wrongly
5750 detect a cycle (between different instantiations of the same
5751 loop).
5752 So the method used for those nasty loops is a little different:
5753 We use a special cycle-detection-stack-frame which is pushed
5754 when the on_failure_jump_nastyloop failure-point is *popped*.
5755 This special frame thus marks the beginning of one iteration
5756 through the loop and we can hence easily check right here
5757 whether something matched between the beginning and the end of
5758 the loop. */
5759 case on_failure_jump_nastyloop:
5760 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5761 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5762 mcnt, p + mcnt);
5764 assert ((re_opcode_t)p[-4] == no_op);
5766 int cycle = 0;
5767 CHECK_INFINITE_LOOP (p - 4, d);
5768 if (!cycle)
5769 /* If there's a cycle, just continue without pushing
5770 this failure point. The failure point is the "try again"
5771 option, which shouldn't be tried.
5772 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5773 PUSH_FAILURE_POINT (p - 3, d);
5775 break;
5777 /* Simple loop detecting on_failure_jump: just check on the
5778 failure stack if the same spot was already hit earlier. */
5779 case on_failure_jump_loop:
5780 on_failure:
5781 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5782 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5783 mcnt, p + mcnt);
5785 int cycle = 0;
5786 CHECK_INFINITE_LOOP (p - 3, d);
5787 if (cycle)
5788 /* If there's a cycle, get out of the loop, as if the matching
5789 had failed. We used to just `goto fail' here, but that was
5790 aborting the search a bit too early: we want to keep the
5791 empty-loop-match and keep matching after the loop.
5792 We want (x?)*y\1z to match both xxyz and xxyxz. */
5793 p += mcnt;
5794 else
5795 PUSH_FAILURE_POINT (p - 3, d);
5797 break;
5800 /* Uses of on_failure_jump:
5802 Each alternative starts with an on_failure_jump that points
5803 to the beginning of the next alternative. Each alternative
5804 except the last ends with a jump that in effect jumps past
5805 the rest of the alternatives. (They really jump to the
5806 ending jump of the following alternative, because tensioning
5807 these jumps is a hassle.)
5809 Repeats start with an on_failure_jump that points past both
5810 the repetition text and either the following jump or
5811 pop_failure_jump back to this on_failure_jump. */
5812 case on_failure_jump:
5813 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5814 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5815 mcnt, p + mcnt);
5817 PUSH_FAILURE_POINT (p -3, d);
5818 break;
5820 /* This operation is used for greedy *.
5821 Compare the beginning of the repeat with what in the
5822 pattern follows its end. If we can establish that there
5823 is nothing that they would both match, i.e., that we
5824 would have to backtrack because of (as in, e.g., `a*a')
5825 then we can use a non-backtracking loop based on
5826 on_failure_keep_string_jump instead of on_failure_jump. */
5827 case on_failure_jump_smart:
5828 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5829 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5830 mcnt, p + mcnt);
5832 re_char *p1 = p; /* Next operation. */
5833 /* Here, we discard `const', making re_match non-reentrant. */
5834 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5835 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5837 p -= 3; /* Reset so that we will re-execute the
5838 instruction once it's been changed. */
5840 EXTRACT_NUMBER (mcnt, p2 - 2);
5842 /* Ensure this is a indeed the trivial kind of loop
5843 we are expecting. */
5844 assert (skip_one_char (p1) == p2 - 3);
5845 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5846 DEBUG_STATEMENT (debug += 2);
5847 if (mutually_exclusive_p (bufp, p1, p2))
5849 /* Use a fast `on_failure_keep_string_jump' loop. */
5850 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5851 *p3 = (unsigned char) on_failure_keep_string_jump;
5852 STORE_NUMBER (p2 - 2, mcnt + 3);
5854 else
5856 /* Default to a safe `on_failure_jump' loop. */
5857 DEBUG_PRINT1 (" smart default => slow loop.\n");
5858 *p3 = (unsigned char) on_failure_jump;
5860 DEBUG_STATEMENT (debug -= 2);
5862 break;
5864 /* Unconditionally jump (without popping any failure points). */
5865 case jump:
5866 unconditional_jump:
5867 IMMEDIATE_QUIT_CHECK;
5868 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5869 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5870 p += mcnt; /* Do the jump. */
5871 DEBUG_PRINT2 ("(to %p).\n", p);
5872 break;
5875 /* Have to succeed matching what follows at least n times.
5876 After that, handle like `on_failure_jump'. */
5877 case succeed_n:
5878 /* Signedness doesn't matter since we only compare MCNT to 0. */
5879 EXTRACT_NUMBER (mcnt, p + 2);
5880 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5882 /* Originally, mcnt is how many times we HAVE to succeed. */
5883 if (mcnt != 0)
5885 /* Here, we discard `const', making re_match non-reentrant. */
5886 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5887 mcnt--;
5888 p += 4;
5889 PUSH_NUMBER (p2, mcnt);
5891 else
5892 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5893 goto on_failure;
5894 break;
5896 case jump_n:
5897 /* Signedness doesn't matter since we only compare MCNT to 0. */
5898 EXTRACT_NUMBER (mcnt, p + 2);
5899 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5901 /* Originally, this is how many times we CAN jump. */
5902 if (mcnt != 0)
5904 /* Here, we discard `const', making re_match non-reentrant. */
5905 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5906 mcnt--;
5907 PUSH_NUMBER (p2, mcnt);
5908 goto unconditional_jump;
5910 /* If don't have to jump any more, skip over the rest of command. */
5911 else
5912 p += 4;
5913 break;
5915 case set_number_at:
5917 unsigned char *p2; /* Location of the counter. */
5918 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5920 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5921 /* Here, we discard `const', making re_match non-reentrant. */
5922 p2 = (unsigned char*) p + mcnt;
5923 /* Signedness doesn't matter since we only copy MCNT's bits . */
5924 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5925 DEBUG_PRINT3 (" Setting %p to %d.\n", p2, mcnt);
5926 PUSH_NUMBER (p2, mcnt);
5927 break;
5930 case wordbound:
5931 case notwordbound:
5933 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5934 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5936 /* We SUCCEED (or FAIL) in one of the following cases: */
5938 /* Case 1: D is at the beginning or the end of string. */
5939 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5940 not = !not;
5941 else
5943 /* C1 is the character before D, S1 is the syntax of C1, C2
5944 is the character at D, and S2 is the syntax of C2. */
5945 re_wchar_t c1, c2;
5946 int s1, s2;
5947 int dummy;
5948 #ifdef emacs
5949 ssize_t offset = PTR_TO_OFFSET (d - 1);
5950 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5951 UPDATE_SYNTAX_TABLE (charpos);
5952 #endif
5953 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5954 s1 = SYNTAX (c1);
5955 #ifdef emacs
5956 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5957 #endif
5958 PREFETCH_NOLIMIT ();
5959 GET_CHAR_AFTER (c2, d, dummy);
5960 s2 = SYNTAX (c2);
5962 if (/* Case 2: Only one of S1 and S2 is Sword. */
5963 ((s1 == Sword) != (s2 == Sword))
5964 /* Case 3: Both of S1 and S2 are Sword, and macro
5965 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5966 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5967 not = !not;
5969 if (not)
5970 break;
5971 else
5972 goto fail;
5975 case wordbeg:
5976 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5978 /* We FAIL in one of the following cases: */
5980 /* Case 1: D is at the end of string. */
5981 if (AT_STRINGS_END (d))
5982 goto fail;
5983 else
5985 /* C1 is the character before D, S1 is the syntax of C1, C2
5986 is the character at D, and S2 is the syntax of C2. */
5987 re_wchar_t c1, c2;
5988 int s1, s2;
5989 int dummy;
5990 #ifdef emacs
5991 ssize_t offset = PTR_TO_OFFSET (d);
5992 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5993 UPDATE_SYNTAX_TABLE (charpos);
5994 #endif
5995 PREFETCH ();
5996 GET_CHAR_AFTER (c2, d, dummy);
5997 s2 = SYNTAX (c2);
5999 /* Case 2: S2 is not Sword. */
6000 if (s2 != Sword)
6001 goto fail;
6003 /* Case 3: D is not at the beginning of string ... */
6004 if (!AT_STRINGS_BEG (d))
6006 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6007 #ifdef emacs
6008 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6009 #endif
6010 s1 = SYNTAX (c1);
6012 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6013 returns 0. */
6014 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6015 goto fail;
6018 break;
6020 case wordend:
6021 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6023 /* We FAIL in one of the following cases: */
6025 /* Case 1: D is at the beginning of string. */
6026 if (AT_STRINGS_BEG (d))
6027 goto fail;
6028 else
6030 /* C1 is the character before D, S1 is the syntax of C1, C2
6031 is the character at D, and S2 is the syntax of C2. */
6032 re_wchar_t c1, c2;
6033 int s1, s2;
6034 int dummy;
6035 #ifdef emacs
6036 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6037 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6038 UPDATE_SYNTAX_TABLE (charpos);
6039 #endif
6040 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6041 s1 = SYNTAX (c1);
6043 /* Case 2: S1 is not Sword. */
6044 if (s1 != Sword)
6045 goto fail;
6047 /* Case 3: D is not at the end of string ... */
6048 if (!AT_STRINGS_END (d))
6050 PREFETCH_NOLIMIT ();
6051 GET_CHAR_AFTER (c2, d, dummy);
6052 #ifdef emacs
6053 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
6054 #endif
6055 s2 = SYNTAX (c2);
6057 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6058 returns 0. */
6059 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6060 goto fail;
6063 break;
6065 case symbeg:
6066 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6068 /* We FAIL in one of the following cases: */
6070 /* Case 1: D is at the end of string. */
6071 if (AT_STRINGS_END (d))
6072 goto fail;
6073 else
6075 /* C1 is the character before D, S1 is the syntax of C1, C2
6076 is the character at D, and S2 is the syntax of C2. */
6077 re_wchar_t c1, c2;
6078 int s1, s2;
6079 #ifdef emacs
6080 ssize_t offset = PTR_TO_OFFSET (d);
6081 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6082 UPDATE_SYNTAX_TABLE (charpos);
6083 #endif
6084 PREFETCH ();
6085 c2 = RE_STRING_CHAR (d, target_multibyte);
6086 s2 = SYNTAX (c2);
6088 /* Case 2: S2 is neither Sword nor Ssymbol. */
6089 if (s2 != Sword && s2 != Ssymbol)
6090 goto fail;
6092 /* Case 3: D is not at the beginning of string ... */
6093 if (!AT_STRINGS_BEG (d))
6095 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6096 #ifdef emacs
6097 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6098 #endif
6099 s1 = SYNTAX (c1);
6101 /* ... and S1 is Sword or Ssymbol. */
6102 if (s1 == Sword || s1 == Ssymbol)
6103 goto fail;
6106 break;
6108 case symend:
6109 DEBUG_PRINT1 ("EXECUTING symend.\n");
6111 /* We FAIL in one of the following cases: */
6113 /* Case 1: D is at the beginning of string. */
6114 if (AT_STRINGS_BEG (d))
6115 goto fail;
6116 else
6118 /* C1 is the character before D, S1 is the syntax of C1, C2
6119 is the character at D, and S2 is the syntax of C2. */
6120 re_wchar_t c1, c2;
6121 int s1, s2;
6122 #ifdef emacs
6123 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6124 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6125 UPDATE_SYNTAX_TABLE (charpos);
6126 #endif
6127 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6128 s1 = SYNTAX (c1);
6130 /* Case 2: S1 is neither Ssymbol nor Sword. */
6131 if (s1 != Sword && s1 != Ssymbol)
6132 goto fail;
6134 /* Case 3: D is not at the end of string ... */
6135 if (!AT_STRINGS_END (d))
6137 PREFETCH_NOLIMIT ();
6138 c2 = RE_STRING_CHAR (d, target_multibyte);
6139 #ifdef emacs
6140 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6141 #endif
6142 s2 = SYNTAX (c2);
6144 /* ... and S2 is Sword or Ssymbol. */
6145 if (s2 == Sword || s2 == Ssymbol)
6146 goto fail;
6149 break;
6151 case syntaxspec:
6152 case notsyntaxspec:
6154 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6155 mcnt = *p++;
6156 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
6157 PREFETCH ();
6158 #ifdef emacs
6160 ssize_t offset = PTR_TO_OFFSET (d);
6161 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6162 UPDATE_SYNTAX_TABLE (pos1);
6164 #endif
6166 int len;
6167 re_wchar_t c;
6169 GET_CHAR_AFTER (c, d, len);
6170 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6171 goto fail;
6172 d += len;
6175 break;
6177 #ifdef emacs
6178 case before_dot:
6179 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6180 if (PTR_BYTE_POS (d) >= PT_BYTE)
6181 goto fail;
6182 break;
6184 case at_dot:
6185 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6186 if (PTR_BYTE_POS (d) != PT_BYTE)
6187 goto fail;
6188 break;
6190 case after_dot:
6191 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6192 if (PTR_BYTE_POS (d) <= PT_BYTE)
6193 goto fail;
6194 break;
6196 case categoryspec:
6197 case notcategoryspec:
6199 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6200 mcnt = *p++;
6201 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n",
6202 not?"not":"", mcnt);
6203 PREFETCH ();
6206 int len;
6207 re_wchar_t c;
6208 GET_CHAR_AFTER (c, d, len);
6209 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6210 goto fail;
6211 d += len;
6214 break;
6216 #endif /* emacs */
6218 default:
6219 abort ();
6221 continue; /* Successfully executed one pattern command; keep going. */
6224 /* We goto here if a matching operation fails. */
6225 fail:
6226 IMMEDIATE_QUIT_CHECK;
6227 if (!FAIL_STACK_EMPTY ())
6229 re_char *str, *pat;
6230 /* A restart point is known. Restore to that state. */
6231 DEBUG_PRINT1 ("\nFAIL:\n");
6232 POP_FAILURE_POINT (str, pat);
6233 switch (*pat++)
6235 case on_failure_keep_string_jump:
6236 assert (str == NULL);
6237 goto continue_failure_jump;
6239 case on_failure_jump_nastyloop:
6240 assert ((re_opcode_t)pat[-2] == no_op);
6241 PUSH_FAILURE_POINT (pat - 2, str);
6242 /* Fallthrough */
6244 case on_failure_jump_loop:
6245 case on_failure_jump:
6246 case succeed_n:
6247 d = str;
6248 continue_failure_jump:
6249 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6250 p = pat + mcnt;
6251 break;
6253 case no_op:
6254 /* A special frame used for nastyloops. */
6255 goto fail;
6257 default:
6258 abort ();
6261 assert (p >= bufp->buffer && p <= pend);
6263 if (d >= string1 && d <= end1)
6264 dend = end_match_1;
6266 else
6267 break; /* Matching at this starting point really fails. */
6268 } /* for (;;) */
6270 if (best_regs_set)
6271 goto restore_best_regs;
6273 FREE_VARIABLES ();
6275 return -1; /* Failure to match. */
6276 } /* re_match_2 */
6278 /* Subroutine definitions for re_match_2. */
6280 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6281 bytes; nonzero otherwise. */
6283 static int
6284 bcmp_translate (const re_char *s1, const re_char *s2, register ssize_t len,
6285 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6287 register re_char *p1 = s1, *p2 = s2;
6288 re_char *p1_end = s1 + len;
6289 re_char *p2_end = s2 + len;
6291 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6292 different lengths, but relying on a single `len' would break this. -sm */
6293 while (p1 < p1_end && p2 < p2_end)
6295 int p1_charlen, p2_charlen;
6296 re_wchar_t p1_ch, p2_ch;
6298 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6299 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6301 if (RE_TRANSLATE (translate, p1_ch)
6302 != RE_TRANSLATE (translate, p2_ch))
6303 return 1;
6305 p1 += p1_charlen, p2 += p2_charlen;
6308 if (p1 != p1_end || p2 != p2_end)
6309 return 1;
6311 return 0;
6314 /* Entry points for GNU code. */
6316 /* re_compile_pattern is the GNU regular expression compiler: it
6317 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6318 Returns 0 if the pattern was valid, otherwise an error string.
6320 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6321 are set in BUFP on entry.
6323 We call regex_compile to do the actual compilation. */
6325 const char *
6326 re_compile_pattern (const char *pattern, size_t length,
6327 struct re_pattern_buffer *bufp)
6329 reg_errcode_t ret;
6331 /* GNU code is written to assume at least RE_NREGS registers will be set
6332 (and at least one extra will be -1). */
6333 bufp->regs_allocated = REGS_UNALLOCATED;
6335 /* And GNU code determines whether or not to get register information
6336 by passing null for the REGS argument to re_match, etc., not by
6337 setting no_sub. */
6338 bufp->no_sub = 0;
6340 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
6342 if (!ret)
6343 return NULL;
6344 return gettext (re_error_msgid[(int) ret]);
6346 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6348 /* Entry points compatible with 4.2 BSD regex library. We don't define
6349 them unless specifically requested. */
6351 #if defined _REGEX_RE_COMP || defined _LIBC
6353 /* BSD has one and only one pattern buffer. */
6354 static struct re_pattern_buffer re_comp_buf;
6356 char *
6357 # ifdef _LIBC
6358 /* Make these definitions weak in libc, so POSIX programs can redefine
6359 these names if they don't use our functions, and still use
6360 regcomp/regexec below without link errors. */
6361 weak_function
6362 # endif
6363 re_comp (const char *s)
6365 reg_errcode_t ret;
6367 if (!s)
6369 if (!re_comp_buf.buffer)
6370 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6371 return (char *) gettext ("No previous regular expression");
6372 return 0;
6375 if (!re_comp_buf.buffer)
6377 re_comp_buf.buffer = malloc (200);
6378 if (re_comp_buf.buffer == NULL)
6379 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6380 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6381 re_comp_buf.allocated = 200;
6383 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6384 if (re_comp_buf.fastmap == NULL)
6385 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6386 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6389 /* Since `re_exec' always passes NULL for the `regs' argument, we
6390 don't need to initialize the pattern buffer fields which affect it. */
6392 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6394 if (!ret)
6395 return NULL;
6397 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6398 return (char *) gettext (re_error_msgid[(int) ret]);
6403 # ifdef _LIBC
6404 weak_function
6405 # endif
6406 re_exec (const char *s)
6408 const size_t len = strlen (s);
6409 return
6410 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6412 #endif /* _REGEX_RE_COMP */
6414 /* POSIX.2 functions. Don't define these for Emacs. */
6416 #ifndef emacs
6418 /* regcomp takes a regular expression as a string and compiles it.
6420 PREG is a regex_t *. We do not expect any fields to be initialized,
6421 since POSIX says we shouldn't. Thus, we set
6423 `buffer' to the compiled pattern;
6424 `used' to the length of the compiled pattern;
6425 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6426 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6427 RE_SYNTAX_POSIX_BASIC;
6428 `fastmap' to an allocated space for the fastmap;
6429 `fastmap_accurate' to zero;
6430 `re_nsub' to the number of subexpressions in PATTERN.
6432 PATTERN is the address of the pattern string.
6434 CFLAGS is a series of bits which affect compilation.
6436 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6437 use POSIX basic syntax.
6439 If REG_NEWLINE is set, then . and [^...] don't match newline.
6440 Also, regexec will try a match beginning after every newline.
6442 If REG_ICASE is set, then we considers upper- and lowercase
6443 versions of letters to be equivalent when matching.
6445 If REG_NOSUB is set, then when PREG is passed to regexec, that
6446 routine will report only success or failure, and nothing about the
6447 registers.
6449 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6450 the return codes and their meanings.) */
6452 reg_errcode_t
6453 regcomp (regex_t *__restrict preg, const char *__restrict pattern,
6454 int cflags)
6456 reg_errcode_t ret;
6457 reg_syntax_t syntax
6458 = (cflags & REG_EXTENDED) ?
6459 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6461 /* regex_compile will allocate the space for the compiled pattern. */
6462 preg->buffer = 0;
6463 preg->allocated = 0;
6464 preg->used = 0;
6466 /* Try to allocate space for the fastmap. */
6467 preg->fastmap = malloc (1 << BYTEWIDTH);
6469 if (cflags & REG_ICASE)
6471 unsigned i;
6473 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6474 if (preg->translate == NULL)
6475 return (int) REG_ESPACE;
6477 /* Map uppercase characters to corresponding lowercase ones. */
6478 for (i = 0; i < CHAR_SET_SIZE; i++)
6479 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6481 else
6482 preg->translate = NULL;
6484 /* If REG_NEWLINE is set, newlines are treated differently. */
6485 if (cflags & REG_NEWLINE)
6486 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6487 syntax &= ~RE_DOT_NEWLINE;
6488 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6490 else
6491 syntax |= RE_NO_NEWLINE_ANCHOR;
6493 preg->no_sub = !!(cflags & REG_NOSUB);
6495 /* POSIX says a null character in the pattern terminates it, so we
6496 can use strlen here in compiling the pattern. */
6497 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6499 /* POSIX doesn't distinguish between an unmatched open-group and an
6500 unmatched close-group: both are REG_EPAREN. */
6501 if (ret == REG_ERPAREN)
6502 ret = REG_EPAREN;
6504 if (ret == REG_NOERROR && preg->fastmap)
6505 { /* Compute the fastmap now, since regexec cannot modify the pattern
6506 buffer. */
6507 re_compile_fastmap (preg);
6508 if (preg->can_be_null)
6509 { /* The fastmap can't be used anyway. */
6510 free (preg->fastmap);
6511 preg->fastmap = NULL;
6514 return ret;
6516 WEAK_ALIAS (__regcomp, regcomp)
6519 /* regexec searches for a given pattern, specified by PREG, in the
6520 string STRING.
6522 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6523 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6524 least NMATCH elements, and we set them to the offsets of the
6525 corresponding matched substrings.
6527 EFLAGS specifies `execution flags' which affect matching: if
6528 REG_NOTBOL is set, then ^ does not match at the beginning of the
6529 string; if REG_NOTEOL is set, then $ does not match at the end.
6531 We return 0 if we find a match and REG_NOMATCH if not. */
6533 reg_errcode_t
6534 regexec (const regex_t *__restrict preg, const char *__restrict string,
6535 size_t nmatch, regmatch_t pmatch[__restrict_arr], int eflags)
6537 regoff_t ret;
6538 struct re_registers regs;
6539 regex_t private_preg;
6540 size_t len = strlen (string);
6541 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6543 private_preg = *preg;
6545 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6546 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6548 /* The user has told us exactly how many registers to return
6549 information about, via `nmatch'. We have to pass that on to the
6550 matching routines. */
6551 private_preg.regs_allocated = REGS_FIXED;
6553 if (want_reg_info)
6555 regs.num_regs = nmatch;
6556 regs.start = TALLOC (nmatch * 2, regoff_t);
6557 if (regs.start == NULL)
6558 return REG_NOMATCH;
6559 regs.end = regs.start + nmatch;
6562 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6563 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6564 was a little bit longer but still only matching the real part.
6565 This works because the `endline' will check for a '\n' and will find a
6566 '\0', correctly deciding that this is not the end of a line.
6567 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6568 a convenient '\0' there. For all we know, the string could be preceded
6569 by '\n' which would throw things off. */
6571 /* Perform the searching operation. */
6572 ret = re_search (&private_preg, string, len,
6573 /* start: */ 0, /* range: */ len,
6574 want_reg_info ? &regs : (struct re_registers *) 0);
6576 /* Copy the register information to the POSIX structure. */
6577 if (want_reg_info)
6579 if (ret >= 0)
6581 unsigned r;
6583 for (r = 0; r < nmatch; r++)
6585 pmatch[r].rm_so = regs.start[r];
6586 pmatch[r].rm_eo = regs.end[r];
6590 /* If we needed the temporary register info, free the space now. */
6591 free (regs.start);
6594 /* We want zero return to mean success, unlike `re_search'. */
6595 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6597 WEAK_ALIAS (__regexec, regexec)
6600 /* Returns a message corresponding to an error code, ERR_CODE, returned
6601 from either regcomp or regexec. We don't use PREG here.
6603 ERR_CODE was previously called ERRCODE, but that name causes an
6604 error with msvc8 compiler. */
6606 size_t
6607 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6609 const char *msg;
6610 size_t msg_size;
6612 if (err_code < 0
6613 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6614 /* Only error codes returned by the rest of the code should be passed
6615 to this routine. If we are given anything else, or if other regex
6616 code generates an invalid error code, then the program has a bug.
6617 Dump core so we can fix it. */
6618 abort ();
6620 msg = gettext (re_error_msgid[err_code]);
6622 msg_size = strlen (msg) + 1; /* Includes the null. */
6624 if (errbuf_size != 0)
6626 if (msg_size > errbuf_size)
6628 memcpy (errbuf, msg, errbuf_size - 1);
6629 errbuf[errbuf_size - 1] = 0;
6631 else
6632 strcpy (errbuf, msg);
6635 return msg_size;
6637 WEAK_ALIAS (__regerror, regerror)
6640 /* Free dynamically allocated space used by PREG. */
6642 void
6643 regfree (regex_t *preg)
6645 free (preg->buffer);
6646 preg->buffer = NULL;
6648 preg->allocated = 0;
6649 preg->used = 0;
6651 free (preg->fastmap);
6652 preg->fastmap = NULL;
6653 preg->fastmap_accurate = 0;
6655 free (preg->translate);
6656 preg->translate = NULL;
6658 WEAK_ALIAS (__regfree, regfree)
6660 #endif /* not emacs */