merge from trunk
[emacs.git] / src / regex.c
blob75661a27892b61de9882b1c11638414a06320f6d
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993-2013 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* TODO:
21 - structure the opcode space into opcode+flag.
22 - merge with glibc's regex.[ch].
23 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
24 need to modify the compiled regexp so that re_match can be reentrant.
25 - get rid of on_failure_jump_smart by doing the optimization in re_comp
26 rather than at run-time, so that re_match can be reentrant.
29 /* AIX requires this to be the first thing in the file. */
30 #if defined _AIX && !defined REGEX_MALLOC
31 #pragma alloca
32 #endif
34 /* Ignore some GCC warnings for now. This section should go away
35 once the Emacs and Gnulib regex code is merged. */
36 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__) || defined __clang__
37 # pragma GCC diagnostic ignored "-Wstrict-overflow"
38 # ifndef emacs
39 # pragma GCC diagnostic ignored "-Wunused-function"
40 # pragma GCC diagnostic ignored "-Wunused-macros"
41 # pragma GCC diagnostic ignored "-Wunused-result"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
43 # endif
44 #endif
46 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__) && ! defined __clang__
47 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
48 #endif
50 #include <config.h>
52 #include <stddef.h>
54 #ifdef emacs
55 /* We need this for `regex.h', and perhaps for the Emacs include files. */
56 # include <sys/types.h>
57 #endif
59 /* Whether to use ISO C Amendment 1 wide char functions.
60 Those should not be used for Emacs since it uses its own. */
61 #if defined _LIBC
62 #define WIDE_CHAR_SUPPORT 1
63 #else
64 #define WIDE_CHAR_SUPPORT \
65 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
66 #endif
68 /* For platform which support the ISO C amendment 1 functionality we
69 support user defined character classes. */
70 #if WIDE_CHAR_SUPPORT
71 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
72 # include <wchar.h>
73 # include <wctype.h>
74 #endif
76 #ifdef _LIBC
77 /* We have to keep the namespace clean. */
78 # define regfree(preg) __regfree (preg)
79 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
80 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
81 # define regerror(err_code, preg, errbuf, errbuf_size) \
82 __regerror (err_code, preg, errbuf, errbuf_size)
83 # define re_set_registers(bu, re, nu, st, en) \
84 __re_set_registers (bu, re, nu, st, en)
85 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
86 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
87 # define re_match(bufp, string, size, pos, regs) \
88 __re_match (bufp, string, size, pos, regs)
89 # define re_search(bufp, string, size, startpos, range, regs) \
90 __re_search (bufp, string, size, startpos, range, regs)
91 # define re_compile_pattern(pattern, length, bufp) \
92 __re_compile_pattern (pattern, length, bufp)
93 # define re_set_syntax(syntax) __re_set_syntax (syntax)
94 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
95 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
96 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
98 /* Make sure we call libc's function even if the user overrides them. */
99 # define btowc __btowc
100 # define iswctype __iswctype
101 # define wctype __wctype
103 # define WEAK_ALIAS(a,b) weak_alias (a, b)
105 /* We are also using some library internals. */
106 # include <locale/localeinfo.h>
107 # include <locale/elem-hash.h>
108 # include <langinfo.h>
109 #else
110 # define WEAK_ALIAS(a,b)
111 #endif
113 /* This is for other GNU distributions with internationalized messages. */
114 #if HAVE_LIBINTL_H || defined _LIBC
115 # include <libintl.h>
116 #else
117 # define gettext(msgid) (msgid)
118 #endif
120 #ifndef gettext_noop
121 /* This define is so xgettext can find the internationalizable
122 strings. */
123 # define gettext_noop(String) String
124 #endif
126 /* The `emacs' switch turns on certain matching commands
127 that make sense only in Emacs. */
128 #ifdef emacs
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 = 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 typedef const re_char const_re_char;
535 #else
536 typedef const unsigned char re_char;
537 typedef re_char const_re_char;
538 #endif
540 typedef char boolean;
542 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
543 re_char *string1, size_t size1,
544 re_char *string2, size_t size2,
545 ssize_t pos,
546 struct re_registers *regs,
547 ssize_t stop);
549 /* These are the command codes that appear in compiled regular
550 expressions. Some opcodes are followed by argument bytes. A
551 command code can specify any interpretation whatsoever for its
552 arguments. Zero bytes may appear in the compiled regular expression. */
554 typedef enum
556 no_op = 0,
558 /* Succeed right away--no more backtracking. */
559 succeed,
561 /* Followed by one byte giving n, then by n literal bytes. */
562 exactn,
564 /* Matches any (more or less) character. */
565 anychar,
567 /* Matches any one char belonging to specified set. First
568 following byte is number of bitmap bytes. Then come bytes
569 for a bitmap saying which chars are in. Bits in each byte
570 are ordered low-bit-first. A character is in the set if its
571 bit is 1. A character too large to have a bit in the map is
572 automatically not in the set.
574 If the length byte has the 0x80 bit set, then that stuff
575 is followed by a range table:
576 2 bytes of flags for character sets (low 8 bits, high 8 bits)
577 See RANGE_TABLE_WORK_BITS below.
578 2 bytes, the number of pairs that follow (upto 32767)
579 pairs, each 2 multibyte characters,
580 each multibyte character represented as 3 bytes. */
581 charset,
583 /* Same parameters as charset, but match any character that is
584 not one of those specified. */
585 charset_not,
587 /* Start remembering the text that is matched, for storing in a
588 register. Followed by one byte with the register number, in
589 the range 0 to one less than the pattern buffer's re_nsub
590 field. */
591 start_memory,
593 /* Stop remembering the text that is matched and store it in a
594 memory register. Followed by one byte with the register
595 number, in the range 0 to one less than `re_nsub' in the
596 pattern buffer. */
597 stop_memory,
599 /* Match a duplicate of something remembered. Followed by one
600 byte containing the register number. */
601 duplicate,
603 /* Fail unless at beginning of line. */
604 begline,
606 /* Fail unless at end of line. */
607 endline,
609 /* Succeeds if at beginning of buffer (if emacs) or at beginning
610 of string to be matched (if not). */
611 begbuf,
613 /* Analogously, for end of buffer/string. */
614 endbuf,
616 /* Followed by two byte relative address to which to jump. */
617 jump,
619 /* Followed by two-byte relative address of place to resume at
620 in case of failure. */
621 on_failure_jump,
623 /* Like on_failure_jump, but pushes a placeholder instead of the
624 current string position when executed. */
625 on_failure_keep_string_jump,
627 /* Just like `on_failure_jump', except that it checks that we
628 don't get stuck in an infinite loop (matching an empty string
629 indefinitely). */
630 on_failure_jump_loop,
632 /* Just like `on_failure_jump_loop', except that it checks for
633 a different kind of loop (the kind that shows up with non-greedy
634 operators). This operation has to be immediately preceded
635 by a `no_op'. */
636 on_failure_jump_nastyloop,
638 /* A smart `on_failure_jump' used for greedy * and + operators.
639 It analyzes the loop before which it is put and if the
640 loop does not require backtracking, it changes itself to
641 `on_failure_keep_string_jump' and short-circuits the loop,
642 else it just defaults to changing itself into `on_failure_jump'.
643 It assumes that it is pointing to just past a `jump'. */
644 on_failure_jump_smart,
646 /* Followed by two-byte relative address and two-byte number n.
647 After matching N times, jump to the address upon failure.
648 Does not work if N starts at 0: use on_failure_jump_loop
649 instead. */
650 succeed_n,
652 /* Followed by two-byte relative address, and two-byte number n.
653 Jump to the address N times, then fail. */
654 jump_n,
656 /* Set the following two-byte relative address to the
657 subsequent two-byte number. The address *includes* the two
658 bytes of number. */
659 set_number_at,
661 wordbeg, /* Succeeds if at word beginning. */
662 wordend, /* Succeeds if at word end. */
664 wordbound, /* Succeeds if at a word boundary. */
665 notwordbound, /* Succeeds if not at a word boundary. */
667 symbeg, /* Succeeds if at symbol beginning. */
668 symend, /* Succeeds if at symbol end. */
670 /* Matches any character whose syntax is specified. Followed by
671 a byte which contains a syntax code, e.g., Sword. */
672 syntaxspec,
674 /* Matches any character whose syntax is not that specified. */
675 notsyntaxspec
677 #ifdef emacs
678 ,before_dot, /* Succeeds if before point. */
679 at_dot, /* Succeeds if at point. */
680 after_dot, /* Succeeds if after point. */
682 /* Matches any character whose category-set contains the specified
683 category. The operator is followed by a byte which contains a
684 category code (mnemonic ASCII character). */
685 categoryspec,
687 /* Matches any character whose category-set does not contain the
688 specified category. The operator is followed by a byte which
689 contains the category code (mnemonic ASCII character). */
690 notcategoryspec
691 #endif /* emacs */
692 } re_opcode_t;
694 /* Common operations on the compiled pattern. */
696 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
698 #define STORE_NUMBER(destination, number) \
699 do { \
700 (destination)[0] = (number) & 0377; \
701 (destination)[1] = (number) >> 8; \
702 } while (0)
704 /* Same as STORE_NUMBER, except increment DESTINATION to
705 the byte after where the number is stored. Therefore, DESTINATION
706 must be an lvalue. */
708 #define STORE_NUMBER_AND_INCR(destination, number) \
709 do { \
710 STORE_NUMBER (destination, number); \
711 (destination) += 2; \
712 } while (0)
714 /* Put into DESTINATION a number stored in two contiguous bytes starting
715 at SOURCE. */
717 #define EXTRACT_NUMBER(destination, source) \
718 ((destination) = extract_number (source))
720 static int
721 extract_number (re_char *source)
723 return (SIGN_EXTEND_CHAR (source[1]) << 8) + source[0];
726 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
727 SOURCE must be an lvalue. */
729 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
730 ((destination) = extract_number_and_incr (&source))
732 static int
733 extract_number_and_incr (re_char **source)
735 int num = extract_number (*source);
736 *source += 2;
737 return num;
740 /* Store a multibyte character in three contiguous bytes starting
741 DESTINATION, and increment DESTINATION to the byte after where the
742 character is stored. Therefore, DESTINATION must be an lvalue. */
744 #define STORE_CHARACTER_AND_INCR(destination, character) \
745 do { \
746 (destination)[0] = (character) & 0377; \
747 (destination)[1] = ((character) >> 8) & 0377; \
748 (destination)[2] = (character) >> 16; \
749 (destination) += 3; \
750 } while (0)
752 /* Put into DESTINATION a character stored in three contiguous bytes
753 starting at SOURCE. */
755 #define EXTRACT_CHARACTER(destination, source) \
756 do { \
757 (destination) = ((source)[0] \
758 | ((source)[1] << 8) \
759 | ((source)[2] << 16)); \
760 } while (0)
763 /* Macros for charset. */
765 /* Size of bitmap of charset P in bytes. P is a start of charset,
766 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
767 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
769 /* Nonzero if charset P has range table. */
770 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
772 /* Return the address of range table of charset P. But not the start
773 of table itself, but the before where the number of ranges is
774 stored. `2 +' means to skip re_opcode_t and size of bitmap,
775 and the 2 bytes of flags at the start of the range table. */
776 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
778 /* Extract the bit flags that start a range table. */
779 #define CHARSET_RANGE_TABLE_BITS(p) \
780 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
781 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
783 /* Return the address of end of RANGE_TABLE. COUNT is number of
784 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
785 is start of range and end of range. `* 3' is size of each start
786 and end. */
787 #define CHARSET_RANGE_TABLE_END(range_table, count) \
788 ((range_table) + (count) * 2 * 3)
790 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
791 COUNT is number of ranges in RANGE_TABLE. */
792 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
793 do \
795 re_wchar_t range_start, range_end; \
796 re_char *rtp; \
797 re_char *range_table_end \
798 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
800 for (rtp = (range_table); rtp < range_table_end; rtp += 2 * 3) \
802 EXTRACT_CHARACTER (range_start, rtp); \
803 EXTRACT_CHARACTER (range_end, rtp + 3); \
805 if (range_start <= (c) && (c) <= range_end) \
807 (not) = !(not); \
808 break; \
812 while (0)
814 /* Test if C is in range table of CHARSET. The flag NOT is negated if
815 C is listed in it. */
816 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
817 do \
819 /* Number of ranges in range table. */ \
820 int count; \
821 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
823 EXTRACT_NUMBER_AND_INCR (count, range_table); \
824 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
826 while (0)
828 /* If DEBUG is defined, Regex prints many voluminous messages about what
829 it is doing (if the variable `debug' is nonzero). If linked with the
830 main program in `iregex.c', you can enter patterns and strings
831 interactively. And if linked with the main program in `main.c' and
832 the other test files, you can run the already-written tests. */
834 #ifdef DEBUG
836 /* We use standard I/O for debugging. */
837 # include <stdio.h>
839 /* It is useful to test things that ``must'' be true when debugging. */
840 # include <assert.h>
842 static int debug = -100000;
844 # define DEBUG_STATEMENT(e) e
845 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
846 # define DEBUG_COMPILES_ARGUMENTS
847 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
848 if (debug > 0) print_partial_compiled_pattern (s, e)
849 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
850 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
853 /* Print the fastmap in human-readable form. */
855 static void
856 print_fastmap (char *fastmap)
858 unsigned was_a_range = 0;
859 unsigned i = 0;
861 while (i < (1 << BYTEWIDTH))
863 if (fastmap[i++])
865 was_a_range = 0;
866 putchar (i - 1);
867 while (i < (1 << BYTEWIDTH) && fastmap[i])
869 was_a_range = 1;
870 i++;
872 if (was_a_range)
874 printf ("-");
875 putchar (i - 1);
879 putchar ('\n');
883 /* Print a compiled pattern string in human-readable form, starting at
884 the START pointer into it and ending just before the pointer END. */
886 static void
887 print_partial_compiled_pattern (re_char *start, re_char *end)
889 int mcnt, mcnt2;
890 re_char *p = start;
891 re_char *pend = end;
893 if (start == NULL)
895 fprintf (stderr, "(null)\n");
896 return;
899 /* Loop over pattern commands. */
900 while (p < pend)
902 fprintf (stderr, "%td:\t", p - start);
904 switch ((re_opcode_t) *p++)
906 case no_op:
907 fprintf (stderr, "/no_op");
908 break;
910 case succeed:
911 fprintf (stderr, "/succeed");
912 break;
914 case exactn:
915 mcnt = *p++;
916 fprintf (stderr, "/exactn/%d", mcnt);
919 fprintf (stderr, "/%c", *p++);
921 while (--mcnt);
922 break;
924 case start_memory:
925 fprintf (stderr, "/start_memory/%d", *p++);
926 break;
928 case stop_memory:
929 fprintf (stderr, "/stop_memory/%d", *p++);
930 break;
932 case duplicate:
933 fprintf (stderr, "/duplicate/%d", *p++);
934 break;
936 case anychar:
937 fprintf (stderr, "/anychar");
938 break;
940 case charset:
941 case charset_not:
943 register int c, last = -100;
944 register int in_range = 0;
945 int length = CHARSET_BITMAP_SIZE (p - 1);
946 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
948 fprintf (stderr, "/charset [%s",
949 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
951 if (p + *p >= pend)
952 fprintf (stderr, " !extends past end of pattern! ");
954 for (c = 0; c < 256; c++)
955 if (c / 8 < length
956 && (p[1 + (c/8)] & (1 << (c % 8))))
958 /* Are we starting a range? */
959 if (last + 1 == c && ! in_range)
961 fprintf (stderr, "-");
962 in_range = 1;
964 /* Have we broken a range? */
965 else if (last + 1 != c && in_range)
967 fprintf (stderr, "%c", last);
968 in_range = 0;
971 if (! in_range)
972 fprintf (stderr, "%c", c);
974 last = c;
977 if (in_range)
978 fprintf (stderr, "%c", last);
980 fprintf (stderr, "]");
982 p += 1 + length;
984 if (has_range_table)
986 int count;
987 fprintf (stderr, "has-range-table");
989 /* ??? Should print the range table; for now, just skip it. */
990 p += 2; /* skip range table bits */
991 EXTRACT_NUMBER_AND_INCR (count, p);
992 p = CHARSET_RANGE_TABLE_END (p, count);
995 break;
997 case begline:
998 fprintf (stderr, "/begline");
999 break;
1001 case endline:
1002 fprintf (stderr, "/endline");
1003 break;
1005 case on_failure_jump:
1006 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1007 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
1008 break;
1010 case on_failure_keep_string_jump:
1011 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1012 fprintf (stderr, "/on_failure_keep_string_jump to %td",
1013 p + mcnt - start);
1014 break;
1016 case on_failure_jump_nastyloop:
1017 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1018 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
1019 p + mcnt - start);
1020 break;
1022 case on_failure_jump_loop:
1023 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1024 fprintf (stderr, "/on_failure_jump_loop to %td",
1025 p + mcnt - start);
1026 break;
1028 case on_failure_jump_smart:
1029 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1030 fprintf (stderr, "/on_failure_jump_smart to %td",
1031 p + mcnt - start);
1032 break;
1034 case jump:
1035 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1036 fprintf (stderr, "/jump to %td", p + mcnt - start);
1037 break;
1039 case succeed_n:
1040 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1041 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1042 fprintf (stderr, "/succeed_n to %td, %d times",
1043 p - 2 + mcnt - start, mcnt2);
1044 break;
1046 case jump_n:
1047 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1048 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1049 fprintf (stderr, "/jump_n to %td, %d times",
1050 p - 2 + mcnt - start, mcnt2);
1051 break;
1053 case set_number_at:
1054 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1055 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1056 fprintf (stderr, "/set_number_at location %td to %d",
1057 p - 2 + mcnt - start, mcnt2);
1058 break;
1060 case wordbound:
1061 fprintf (stderr, "/wordbound");
1062 break;
1064 case notwordbound:
1065 fprintf (stderr, "/notwordbound");
1066 break;
1068 case wordbeg:
1069 fprintf (stderr, "/wordbeg");
1070 break;
1072 case wordend:
1073 fprintf (stderr, "/wordend");
1074 break;
1076 case symbeg:
1077 fprintf (stderr, "/symbeg");
1078 break;
1080 case symend:
1081 fprintf (stderr, "/symend");
1082 break;
1084 case syntaxspec:
1085 fprintf (stderr, "/syntaxspec");
1086 mcnt = *p++;
1087 fprintf (stderr, "/%d", mcnt);
1088 break;
1090 case notsyntaxspec:
1091 fprintf (stderr, "/notsyntaxspec");
1092 mcnt = *p++;
1093 fprintf (stderr, "/%d", mcnt);
1094 break;
1096 # ifdef emacs
1097 case before_dot:
1098 fprintf (stderr, "/before_dot");
1099 break;
1101 case at_dot:
1102 fprintf (stderr, "/at_dot");
1103 break;
1105 case after_dot:
1106 fprintf (stderr, "/after_dot");
1107 break;
1109 case categoryspec:
1110 fprintf (stderr, "/categoryspec");
1111 mcnt = *p++;
1112 fprintf (stderr, "/%d", mcnt);
1113 break;
1115 case notcategoryspec:
1116 fprintf (stderr, "/notcategoryspec");
1117 mcnt = *p++;
1118 fprintf (stderr, "/%d", mcnt);
1119 break;
1120 # endif /* emacs */
1122 case begbuf:
1123 fprintf (stderr, "/begbuf");
1124 break;
1126 case endbuf:
1127 fprintf (stderr, "/endbuf");
1128 break;
1130 default:
1131 fprintf (stderr, "?%d", *(p-1));
1134 fprintf (stderr, "\n");
1137 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1141 static void
1142 print_compiled_pattern (struct re_pattern_buffer *bufp)
1144 re_char *buffer = bufp->buffer;
1146 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1147 printf ("%ld bytes used/%ld bytes allocated.\n",
1148 bufp->used, bufp->allocated);
1150 if (bufp->fastmap_accurate && bufp->fastmap)
1152 printf ("fastmap: ");
1153 print_fastmap (bufp->fastmap);
1156 printf ("re_nsub: %zu\t", bufp->re_nsub);
1157 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1158 printf ("can_be_null: %d\t", bufp->can_be_null);
1159 printf ("no_sub: %d\t", bufp->no_sub);
1160 printf ("not_bol: %d\t", bufp->not_bol);
1161 printf ("not_eol: %d\t", bufp->not_eol);
1162 printf ("syntax: %lx\n", bufp->syntax);
1163 fflush (stdout);
1164 /* Perhaps we should print the translate table? */
1168 static void
1169 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1170 re_char *string2, ssize_t size2)
1172 ssize_t this_char;
1174 if (where == NULL)
1175 printf ("(null)");
1176 else
1178 if (FIRST_STRING_P (where))
1180 for (this_char = where - string1; this_char < size1; this_char++)
1181 putchar (string1[this_char]);
1183 where = string2;
1186 for (this_char = where - string2; this_char < size2; this_char++)
1187 putchar (string2[this_char]);
1191 #else /* not DEBUG */
1193 # undef assert
1194 # define assert(e)
1196 # define DEBUG_STATEMENT(e)
1197 # if __STDC_VERSION__ < 199901L
1198 # define DEBUG_COMPILES_ARGUMENTS
1199 # define DEBUG_PRINT /* 'DEBUG_PRINT (x, y)' discards X and Y. */ (void)
1200 # else
1201 # define DEBUG_PRINT(...)
1202 # endif
1203 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1204 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1206 #endif /* not DEBUG */
1208 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
1209 #ifdef lint
1210 # define IF_LINT(Code) Code
1211 #else
1212 # define IF_LINT(Code) /* empty */
1213 #endif
1215 #ifndef emacs
1216 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1217 also be assigned to arbitrarily: each pattern buffer stores its own
1218 syntax, so it can be changed between regex compilations. */
1219 /* This has no initializer because initialized variables in Emacs
1220 become read-only after dumping. */
1221 reg_syntax_t re_syntax_options;
1222 #endif
1225 /* Specify the precise syntax of regexps for compilation. This provides
1226 for compatibility for various utilities which historically have
1227 different, incompatible syntaxes.
1229 The argument SYNTAX is a bit mask comprised of the various bits
1230 defined in regex.h. We return the old syntax. */
1232 reg_syntax_t
1233 re_set_syntax (reg_syntax_t syntax)
1235 reg_syntax_t ret = re_syntax_options;
1237 re_syntax_options = syntax;
1238 return ret;
1240 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1242 #ifndef emacs
1243 /* Regexp to use to replace spaces, or NULL meaning don't. */
1244 static re_char *whitespace_regexp;
1245 #endif
1247 void
1248 re_set_whitespace_regexp (const char *regexp)
1250 whitespace_regexp = (re_char *) regexp;
1252 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1254 /* This table gives an error message for each of the error codes listed
1255 in regex.h. Obviously the order here has to be same as there.
1256 POSIX doesn't require that we do anything for REG_NOERROR,
1257 but why not be nice? */
1259 static const char *re_error_msgid[] =
1261 gettext_noop ("Success"), /* REG_NOERROR */
1262 gettext_noop ("No match"), /* REG_NOMATCH */
1263 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1264 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1265 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1266 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1267 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1268 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1269 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1270 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1271 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1272 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1273 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1274 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1275 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1276 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1277 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1278 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1281 /* Avoiding alloca during matching, to placate r_alloc. */
1283 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1284 searching and matching functions should not call alloca. On some
1285 systems, alloca is implemented in terms of malloc, and if we're
1286 using the relocating allocator routines, then malloc could cause a
1287 relocation, which might (if the strings being searched are in the
1288 ralloc heap) shift the data out from underneath the regexp
1289 routines.
1291 Here's another reason to avoid allocation: Emacs
1292 processes input from X in a signal handler; processing X input may
1293 call malloc; if input arrives while a matching routine is calling
1294 malloc, then we're scrod. But Emacs can't just block input while
1295 calling matching routines; then we don't notice interrupts when
1296 they come in. So, Emacs blocks input around all regexp calls
1297 except the matching calls, which it leaves unprotected, in the
1298 faith that they will not malloc. */
1300 /* Normally, this is fine. */
1301 #define MATCH_MAY_ALLOCATE
1303 /* The match routines may not allocate if (1) they would do it with malloc
1304 and (2) it's not safe for them to use malloc.
1305 Note that if REL_ALLOC is defined, matching would not use malloc for the
1306 failure stack, but we would still use it for the register vectors;
1307 so REL_ALLOC should not affect this. */
1308 #if defined REGEX_MALLOC && defined emacs
1309 # undef MATCH_MAY_ALLOCATE
1310 #endif
1313 /* Failure stack declarations and macros; both re_compile_fastmap and
1314 re_match_2 use a failure stack. These have to be macros because of
1315 REGEX_ALLOCATE_STACK. */
1318 /* Approximate number of failure points for which to initially allocate space
1319 when matching. If this number is exceeded, we allocate more
1320 space, so it is not a hard limit. */
1321 #ifndef INIT_FAILURE_ALLOC
1322 # define INIT_FAILURE_ALLOC 20
1323 #endif
1325 /* Roughly the maximum number of failure points on the stack. Would be
1326 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1327 This is a variable only so users of regex can assign to it; we never
1328 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1329 before using it, so it should probably be a byte-count instead. */
1330 # if defined MATCH_MAY_ALLOCATE
1331 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1332 whose default stack limit is 2mb. In order for a larger
1333 value to work reliably, you have to try to make it accord
1334 with the process stack limit. */
1335 size_t re_max_failures = 40000;
1336 # else
1337 size_t re_max_failures = 4000;
1338 # endif
1340 union fail_stack_elt
1342 re_char *pointer;
1343 /* This should be the biggest `int' that's no bigger than a pointer. */
1344 long integer;
1347 typedef union fail_stack_elt fail_stack_elt_t;
1349 typedef struct
1351 fail_stack_elt_t *stack;
1352 size_t size;
1353 size_t avail; /* Offset of next open position. */
1354 size_t frame; /* Offset of the cur constructed frame. */
1355 } fail_stack_type;
1357 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1360 /* Define macros to initialize and free the failure stack.
1361 Do `return -2' if the alloc fails. */
1363 #ifdef MATCH_MAY_ALLOCATE
1364 # define INIT_FAIL_STACK() \
1365 do { \
1366 fail_stack.stack = \
1367 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1368 * sizeof (fail_stack_elt_t)); \
1370 if (fail_stack.stack == NULL) \
1371 return -2; \
1373 fail_stack.size = INIT_FAILURE_ALLOC; \
1374 fail_stack.avail = 0; \
1375 fail_stack.frame = 0; \
1376 } while (0)
1377 #else
1378 # define INIT_FAIL_STACK() \
1379 do { \
1380 fail_stack.avail = 0; \
1381 fail_stack.frame = 0; \
1382 } while (0)
1384 # define RETALLOC_IF(addr, n, t) \
1385 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1386 #endif
1389 /* Double the size of FAIL_STACK, up to a limit
1390 which allows approximately `re_max_failures' items.
1392 Return 1 if succeeds, and 0 if either ran out of memory
1393 allocating space for it or it was already too large.
1395 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1397 /* Factor to increase the failure stack size by
1398 when we increase it.
1399 This used to be 2, but 2 was too wasteful
1400 because the old discarded stacks added up to as much space
1401 were as ultimate, maximum-size stack. */
1402 #define FAIL_STACK_GROWTH_FACTOR 4
1404 #define GROW_FAIL_STACK(fail_stack) \
1405 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1406 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1407 ? 0 \
1408 : ((fail_stack).stack \
1409 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1410 (fail_stack).size * sizeof (fail_stack_elt_t), \
1411 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1412 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1413 * FAIL_STACK_GROWTH_FACTOR))), \
1415 (fail_stack).stack == NULL \
1416 ? 0 \
1417 : ((fail_stack).size \
1418 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1419 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1420 * FAIL_STACK_GROWTH_FACTOR)) \
1421 / sizeof (fail_stack_elt_t)), \
1422 1)))
1425 /* Push a pointer value onto the failure stack.
1426 Assumes the variable `fail_stack'. Probably should only
1427 be called from within `PUSH_FAILURE_POINT'. */
1428 #define PUSH_FAILURE_POINTER(item) \
1429 fail_stack.stack[fail_stack.avail++].pointer = (item)
1431 /* This pushes an integer-valued item onto the failure stack.
1432 Assumes the variable `fail_stack'. Probably should only
1433 be called from within `PUSH_FAILURE_POINT'. */
1434 #define PUSH_FAILURE_INT(item) \
1435 fail_stack.stack[fail_stack.avail++].integer = (item)
1437 /* These POP... operations complement the PUSH... operations.
1438 All assume that `fail_stack' is nonempty. */
1439 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1440 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1442 /* Individual items aside from the registers. */
1443 #define NUM_NONREG_ITEMS 3
1445 /* Used to examine the stack (to detect infinite loops). */
1446 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1447 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1448 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1449 #define TOP_FAILURE_HANDLE() fail_stack.frame
1452 #define ENSURE_FAIL_STACK(space) \
1453 while (REMAINING_AVAIL_SLOTS <= space) { \
1454 if (!GROW_FAIL_STACK (fail_stack)) \
1455 return -2; \
1456 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1457 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1460 /* Push register NUM onto the stack. */
1461 #define PUSH_FAILURE_REG(num) \
1462 do { \
1463 char *destination; \
1464 long n = num; \
1465 ENSURE_FAIL_STACK(3); \
1466 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1467 n, regstart[n], regend[n]); \
1468 PUSH_FAILURE_POINTER (regstart[n]); \
1469 PUSH_FAILURE_POINTER (regend[n]); \
1470 PUSH_FAILURE_INT (n); \
1471 } while (0)
1473 /* Change the counter's value to VAL, but make sure that it will
1474 be reset when backtracking. */
1475 #define PUSH_NUMBER(ptr,val) \
1476 do { \
1477 char *destination; \
1478 int c; \
1479 ENSURE_FAIL_STACK(3); \
1480 EXTRACT_NUMBER (c, ptr); \
1481 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1482 PUSH_FAILURE_INT (c); \
1483 PUSH_FAILURE_POINTER (ptr); \
1484 PUSH_FAILURE_INT (-1); \
1485 STORE_NUMBER (ptr, val); \
1486 } while (0)
1488 /* Pop a saved register off the stack. */
1489 #define POP_FAILURE_REG_OR_COUNT() \
1490 do { \
1491 long pfreg = POP_FAILURE_INT (); \
1492 if (pfreg == -1) \
1494 /* It's a counter. */ \
1495 /* Here, we discard `const', making re_match non-reentrant. */ \
1496 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1497 pfreg = POP_FAILURE_INT (); \
1498 STORE_NUMBER (ptr, pfreg); \
1499 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1501 else \
1503 regend[pfreg] = POP_FAILURE_POINTER (); \
1504 regstart[pfreg] = POP_FAILURE_POINTER (); \
1505 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1506 pfreg, regstart[pfreg], regend[pfreg]); \
1508 } while (0)
1510 /* Check that we are not stuck in an infinite loop. */
1511 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1512 do { \
1513 ssize_t failure = TOP_FAILURE_HANDLE (); \
1514 /* Check for infinite matching loops */ \
1515 while (failure > 0 \
1516 && (FAILURE_STR (failure) == string_place \
1517 || FAILURE_STR (failure) == NULL)) \
1519 assert (FAILURE_PAT (failure) >= bufp->buffer \
1520 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1521 if (FAILURE_PAT (failure) == pat_cur) \
1523 cycle = 1; \
1524 break; \
1526 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1527 failure = NEXT_FAILURE_HANDLE(failure); \
1529 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1530 } while (0)
1532 /* Push the information about the state we will need
1533 if we ever fail back to it.
1535 Requires variables fail_stack, regstart, regend and
1536 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1537 declared.
1539 Does `return FAILURE_CODE' if runs out of memory. */
1541 #define PUSH_FAILURE_POINT(pattern, string_place) \
1542 do { \
1543 char *destination; \
1544 /* Must be int, so when we don't save any registers, the arithmetic \
1545 of 0 + -1 isn't done as unsigned. */ \
1547 DEBUG_STATEMENT (nfailure_points_pushed++); \
1548 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1549 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1550 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1552 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1554 DEBUG_PRINT ("\n"); \
1556 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1557 PUSH_FAILURE_INT (fail_stack.frame); \
1559 DEBUG_PRINT (" Push string %p: `", string_place); \
1560 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1561 DEBUG_PRINT ("'\n"); \
1562 PUSH_FAILURE_POINTER (string_place); \
1564 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1565 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1566 PUSH_FAILURE_POINTER (pattern); \
1568 /* Close the frame by moving the frame pointer past it. */ \
1569 fail_stack.frame = fail_stack.avail; \
1570 } while (0)
1572 /* Estimate the size of data pushed by a typical failure stack entry.
1573 An estimate is all we need, because all we use this for
1574 is to choose a limit for how big to make the failure stack. */
1575 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1576 #define TYPICAL_FAILURE_SIZE 20
1578 /* How many items can still be added to the stack without overflowing it. */
1579 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1582 /* Pops what PUSH_FAIL_STACK pushes.
1584 We restore into the parameters, all of which should be lvalues:
1585 STR -- the saved data position.
1586 PAT -- the saved pattern position.
1587 REGSTART, REGEND -- arrays of string positions.
1589 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1590 `pend', `string1', `size1', `string2', and `size2'. */
1592 #define POP_FAILURE_POINT(str, pat) \
1593 do { \
1594 assert (!FAIL_STACK_EMPTY ()); \
1596 /* Remove failure points and point to how many regs pushed. */ \
1597 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1598 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1599 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1601 /* Pop the saved registers. */ \
1602 while (fail_stack.frame < fail_stack.avail) \
1603 POP_FAILURE_REG_OR_COUNT (); \
1605 pat = POP_FAILURE_POINTER (); \
1606 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1607 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1609 /* If the saved string location is NULL, it came from an \
1610 on_failure_keep_string_jump opcode, and we want to throw away the \
1611 saved NULL, thus retaining our current position in the string. */ \
1612 str = POP_FAILURE_POINTER (); \
1613 DEBUG_PRINT (" Popping string %p: `", str); \
1614 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1615 DEBUG_PRINT ("'\n"); \
1617 fail_stack.frame = POP_FAILURE_INT (); \
1618 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1620 assert (fail_stack.avail >= 0); \
1621 assert (fail_stack.frame <= fail_stack.avail); \
1623 DEBUG_STATEMENT (nfailure_points_popped++); \
1624 } while (0) /* POP_FAILURE_POINT */
1628 /* Registers are set to a sentinel when they haven't yet matched. */
1629 #define REG_UNSET(e) ((e) == NULL)
1631 /* Subroutine declarations and macros for regex_compile. */
1633 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1634 reg_syntax_t syntax,
1635 struct re_pattern_buffer *bufp);
1636 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1637 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1638 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1639 int arg, unsigned char *end);
1640 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1641 int arg1, int arg2, unsigned char *end);
1642 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1643 reg_syntax_t syntax);
1644 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1645 reg_syntax_t syntax);
1646 static re_char *skip_one_char (re_char *p);
1647 static int analyse_first (re_char *p, re_char *pend,
1648 char *fastmap, const int multibyte);
1650 /* Fetch the next character in the uncompiled pattern, with no
1651 translation. */
1652 #define PATFETCH(c) \
1653 do { \
1654 int len; \
1655 if (p == pend) return REG_EEND; \
1656 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1657 p += len; \
1658 } while (0)
1661 /* If `translate' is non-null, return translate[D], else just D. We
1662 cast the subscript to translate because some data is declared as
1663 `char *', to avoid warnings when a string constant is passed. But
1664 when we use a character as a subscript we must make it unsigned. */
1665 #ifndef TRANSLATE
1666 # define TRANSLATE(d) \
1667 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1668 #endif
1671 /* Macros for outputting the compiled pattern into `buffer'. */
1673 /* If the buffer isn't allocated when it comes in, use this. */
1674 #define INIT_BUF_SIZE 32
1676 /* Make sure we have at least N more bytes of space in buffer. */
1677 #define GET_BUFFER_SPACE(n) \
1678 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1679 EXTEND_BUFFER ()
1681 /* Make sure we have one more byte of buffer space and then add C to it. */
1682 #define BUF_PUSH(c) \
1683 do { \
1684 GET_BUFFER_SPACE (1); \
1685 *b++ = (unsigned char) (c); \
1686 } while (0)
1689 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1690 #define BUF_PUSH_2(c1, c2) \
1691 do { \
1692 GET_BUFFER_SPACE (2); \
1693 *b++ = (unsigned char) (c1); \
1694 *b++ = (unsigned char) (c2); \
1695 } while (0)
1698 /* Store a jump with opcode OP at LOC to location TO. We store a
1699 relative address offset by the three bytes the jump itself occupies. */
1700 #define STORE_JUMP(op, loc, to) \
1701 store_op1 (op, loc, (to) - (loc) - 3)
1703 /* Likewise, for a two-argument jump. */
1704 #define STORE_JUMP2(op, loc, to, arg) \
1705 store_op2 (op, loc, (to) - (loc) - 3, arg)
1707 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1708 #define INSERT_JUMP(op, loc, to) \
1709 insert_op1 (op, loc, (to) - (loc) - 3, b)
1711 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1712 #define INSERT_JUMP2(op, loc, to, arg) \
1713 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1716 /* This is not an arbitrary limit: the arguments which represent offsets
1717 into the pattern are two bytes long. So if 2^15 bytes turns out to
1718 be too small, many things would have to change. */
1719 # define MAX_BUF_SIZE (1L << 15)
1721 /* Extend the buffer by twice its current size via realloc and
1722 reset the pointers that pointed into the old block to point to the
1723 correct places in the new one. If extending the buffer results in it
1724 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1725 #if __BOUNDED_POINTERS__
1726 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1727 # define MOVE_BUFFER_POINTER(P) \
1728 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1729 SET_HIGH_BOUND (P), \
1730 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1731 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1732 else \
1734 SET_HIGH_BOUND (b); \
1735 SET_HIGH_BOUND (begalt); \
1736 if (fixup_alt_jump) \
1737 SET_HIGH_BOUND (fixup_alt_jump); \
1738 if (laststart) \
1739 SET_HIGH_BOUND (laststart); \
1740 if (pending_exact) \
1741 SET_HIGH_BOUND (pending_exact); \
1743 #else
1744 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1745 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1746 #endif
1747 #define EXTEND_BUFFER() \
1748 do { \
1749 unsigned char *old_buffer = bufp->buffer; \
1750 if (bufp->allocated == MAX_BUF_SIZE) \
1751 return REG_ESIZE; \
1752 bufp->allocated <<= 1; \
1753 if (bufp->allocated > MAX_BUF_SIZE) \
1754 bufp->allocated = MAX_BUF_SIZE; \
1755 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1756 if (bufp->buffer == NULL) \
1757 return REG_ESPACE; \
1758 /* If the buffer moved, move all the pointers into it. */ \
1759 if (old_buffer != bufp->buffer) \
1761 unsigned char *new_buffer = bufp->buffer; \
1762 MOVE_BUFFER_POINTER (b); \
1763 MOVE_BUFFER_POINTER (begalt); \
1764 if (fixup_alt_jump) \
1765 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1766 if (laststart) \
1767 MOVE_BUFFER_POINTER (laststart); \
1768 if (pending_exact) \
1769 MOVE_BUFFER_POINTER (pending_exact); \
1771 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1772 } while (0)
1775 /* Since we have one byte reserved for the register number argument to
1776 {start,stop}_memory, the maximum number of groups we can report
1777 things about is what fits in that byte. */
1778 #define MAX_REGNUM 255
1780 /* But patterns can have more than `MAX_REGNUM' registers. We just
1781 ignore the excess. */
1782 typedef int regnum_t;
1785 /* Macros for the compile stack. */
1787 /* Since offsets can go either forwards or backwards, this type needs to
1788 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1789 /* int may be not enough when sizeof(int) == 2. */
1790 typedef long pattern_offset_t;
1792 typedef struct
1794 pattern_offset_t begalt_offset;
1795 pattern_offset_t fixup_alt_jump;
1796 pattern_offset_t laststart_offset;
1797 regnum_t regnum;
1798 } compile_stack_elt_t;
1801 typedef struct
1803 compile_stack_elt_t *stack;
1804 size_t size;
1805 size_t avail; /* Offset of next open position. */
1806 } compile_stack_type;
1809 #define INIT_COMPILE_STACK_SIZE 32
1811 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1812 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1814 /* The next available element. */
1815 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1817 /* Explicit quit checking is needed for Emacs, which uses polling to
1818 process input events. */
1819 #ifdef emacs
1820 # define IMMEDIATE_QUIT_CHECK \
1821 do { \
1822 if (immediate_quit) QUIT; \
1823 } while (0)
1824 #else
1825 # define IMMEDIATE_QUIT_CHECK ((void)0)
1826 #endif
1828 /* Structure to manage work area for range table. */
1829 struct range_table_work_area
1831 int *table; /* actual work area. */
1832 int allocated; /* allocated size for work area in bytes. */
1833 int used; /* actually used size in words. */
1834 int bits; /* flag to record character classes */
1837 /* Make sure that WORK_AREA can hold more N multibyte characters.
1838 This is used only in set_image_of_range and set_image_of_range_1.
1839 It expects WORK_AREA to be a pointer.
1840 If it can't get the space, it returns from the surrounding function. */
1842 #define EXTEND_RANGE_TABLE(work_area, n) \
1843 do { \
1844 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1846 extend_range_table_work_area (&work_area); \
1847 if ((work_area).table == 0) \
1848 return (REG_ESPACE); \
1850 } while (0)
1852 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1853 (work_area).bits |= (bit)
1855 /* Bits used to implement the multibyte-part of the various character classes
1856 such as [:alnum:] in a charset's range table. */
1857 #define BIT_WORD 0x1
1858 #define BIT_LOWER 0x2
1859 #define BIT_PUNCT 0x4
1860 #define BIT_SPACE 0x8
1861 #define BIT_UPPER 0x10
1862 #define BIT_MULTIBYTE 0x20
1864 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1865 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1866 do { \
1867 EXTEND_RANGE_TABLE ((work_area), 2); \
1868 (work_area).table[(work_area).used++] = (range_start); \
1869 (work_area).table[(work_area).used++] = (range_end); \
1870 } while (0)
1872 /* Free allocated memory for WORK_AREA. */
1873 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1874 do { \
1875 if ((work_area).table) \
1876 free ((work_area).table); \
1877 } while (0)
1879 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1880 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1881 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1882 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1885 /* Set the bit for character C in a list. */
1886 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1889 #ifdef emacs
1891 /* Store characters in the range FROM to TO in the bitmap at B (for
1892 ASCII and unibyte characters) and WORK_AREA (for multibyte
1893 characters) while translating them and paying attention to the
1894 continuity of translated characters.
1896 Implementation note: It is better to implement these fairly big
1897 macros by a function, but it's not that easy because macros called
1898 in this macro assume various local variables already declared. */
1900 /* Both FROM and TO are ASCII characters. */
1902 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1903 do { \
1904 int C0, C1; \
1906 for (C0 = (FROM); C0 <= (TO); C0++) \
1908 C1 = TRANSLATE (C0); \
1909 if (! ASCII_CHAR_P (C1)) \
1911 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1912 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1913 C1 = C0; \
1915 SET_LIST_BIT (C1); \
1917 } while (0)
1920 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1922 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1923 do { \
1924 int C0, C1, C2, I; \
1925 int USED = RANGE_TABLE_WORK_USED (work_area); \
1927 for (C0 = (FROM); C0 <= (TO); C0++) \
1929 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1930 if (CHAR_BYTE8_P (C1)) \
1931 SET_LIST_BIT (C0); \
1932 else \
1934 C2 = TRANSLATE (C1); \
1935 if (C2 == C1 \
1936 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1937 C1 = C0; \
1938 SET_LIST_BIT (C1); \
1939 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1941 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1942 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1944 if (C2 >= from - 1 && C2 <= to + 1) \
1946 if (C2 == from - 1) \
1947 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1948 else if (C2 == to + 1) \
1949 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1950 break; \
1953 if (I < USED) \
1954 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1957 } while (0)
1960 /* Both FROM and TO are multibyte characters. */
1962 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1963 do { \
1964 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1966 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1967 for (C0 = (FROM); C0 <= (TO); C0++) \
1969 C1 = TRANSLATE (C0); \
1970 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1971 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1972 SET_LIST_BIT (C2); \
1973 if (C1 >= (FROM) && C1 <= (TO)) \
1974 continue; \
1975 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1977 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1978 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1980 if (C1 >= from - 1 && C1 <= to + 1) \
1982 if (C1 == from - 1) \
1983 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1984 else if (C1 == to + 1) \
1985 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1986 break; \
1989 if (I < USED) \
1990 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1992 } while (0)
1994 #endif /* emacs */
1996 /* Get the next unsigned number in the uncompiled pattern. */
1997 #define GET_UNSIGNED_NUMBER(num) \
1998 do { \
1999 if (p == pend) \
2000 FREE_STACK_RETURN (REG_EBRACE); \
2001 else \
2003 PATFETCH (c); \
2004 while ('0' <= c && c <= '9') \
2006 int prev; \
2007 if (num < 0) \
2008 num = 0; \
2009 prev = num; \
2010 num = num * 10 + c - '0'; \
2011 if (num / 10 != prev) \
2012 FREE_STACK_RETURN (REG_BADBR); \
2013 if (p == pend) \
2014 FREE_STACK_RETURN (REG_EBRACE); \
2015 PATFETCH (c); \
2018 } while (0)
2020 #if ! WIDE_CHAR_SUPPORT
2022 /* Map a string to the char class it names (if any). */
2023 re_wctype_t
2024 re_wctype (const_re_char *str)
2026 const char *string = (const char *) str;
2027 if (STREQ (string, "alnum")) return RECC_ALNUM;
2028 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2029 else if (STREQ (string, "word")) return RECC_WORD;
2030 else if (STREQ (string, "ascii")) return RECC_ASCII;
2031 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2032 else if (STREQ (string, "graph")) return RECC_GRAPH;
2033 else if (STREQ (string, "lower")) return RECC_LOWER;
2034 else if (STREQ (string, "print")) return RECC_PRINT;
2035 else if (STREQ (string, "punct")) return RECC_PUNCT;
2036 else if (STREQ (string, "space")) return RECC_SPACE;
2037 else if (STREQ (string, "upper")) return RECC_UPPER;
2038 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2039 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2040 else if (STREQ (string, "digit")) return RECC_DIGIT;
2041 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2042 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2043 else if (STREQ (string, "blank")) return RECC_BLANK;
2044 else return 0;
2047 /* True if CH is in the char class CC. */
2048 boolean
2049 re_iswctype (int ch, re_wctype_t cc)
2051 switch (cc)
2053 case RECC_ALNUM: return ISALNUM (ch) != 0;
2054 case RECC_ALPHA: return ISALPHA (ch) != 0;
2055 case RECC_BLANK: return ISBLANK (ch) != 0;
2056 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2057 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2058 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2059 case RECC_LOWER: return ISLOWER (ch) != 0;
2060 case RECC_PRINT: return ISPRINT (ch) != 0;
2061 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2062 case RECC_SPACE: return ISSPACE (ch) != 0;
2063 case RECC_UPPER: return ISUPPER (ch) != 0;
2064 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2065 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2066 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2067 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2068 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2069 case RECC_WORD: return ISWORD (ch) != 0;
2070 case RECC_ERROR: return false;
2071 default:
2072 abort ();
2076 /* Return a bit-pattern to use in the range-table bits to match multibyte
2077 chars of class CC. */
2078 static int
2079 re_wctype_to_bit (re_wctype_t cc)
2081 switch (cc)
2083 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2084 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2085 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2086 case RECC_LOWER: return BIT_LOWER;
2087 case RECC_UPPER: return BIT_UPPER;
2088 case RECC_PUNCT: return BIT_PUNCT;
2089 case RECC_SPACE: return BIT_SPACE;
2090 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2091 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2092 default:
2093 abort ();
2096 #endif
2098 /* Filling in the work area of a range. */
2100 /* Actually extend the space in WORK_AREA. */
2102 static void
2103 extend_range_table_work_area (struct range_table_work_area *work_area)
2105 work_area->allocated += 16 * sizeof (int);
2106 work_area->table = realloc (work_area->table, work_area->allocated);
2109 #if 0
2110 #ifdef emacs
2112 /* Carefully find the ranges of codes that are equivalent
2113 under case conversion to the range start..end when passed through
2114 TRANSLATE. Handle the case where non-letters can come in between
2115 two upper-case letters (which happens in Latin-1).
2116 Also handle the case of groups of more than 2 case-equivalent chars.
2118 The basic method is to look at consecutive characters and see
2119 if they can form a run that can be handled as one.
2121 Returns -1 if successful, REG_ESPACE if ran out of space. */
2123 static int
2124 set_image_of_range_1 (struct range_table_work_area *work_area,
2125 re_wchar_t start, re_wchar_t end,
2126 RE_TRANSLATE_TYPE translate)
2128 /* `one_case' indicates a character, or a run of characters,
2129 each of which is an isolate (no case-equivalents).
2130 This includes all ASCII non-letters.
2132 `two_case' indicates a character, or a run of characters,
2133 each of which has two case-equivalent forms.
2134 This includes all ASCII letters.
2136 `strange' indicates a character that has more than one
2137 case-equivalent. */
2139 enum case_type {one_case, two_case, strange};
2141 /* Describe the run that is in progress,
2142 which the next character can try to extend.
2143 If run_type is strange, that means there really is no run.
2144 If run_type is one_case, then run_start...run_end is the run.
2145 If run_type is two_case, then the run is run_start...run_end,
2146 and the case-equivalents end at run_eqv_end. */
2148 enum case_type run_type = strange;
2149 int run_start, run_end, run_eqv_end;
2151 Lisp_Object eqv_table;
2153 if (!RE_TRANSLATE_P (translate))
2155 EXTEND_RANGE_TABLE (work_area, 2);
2156 work_area->table[work_area->used++] = (start);
2157 work_area->table[work_area->used++] = (end);
2158 return -1;
2161 eqv_table = XCHAR_TABLE (translate)->extras[2];
2163 for (; start <= end; start++)
2165 enum case_type this_type;
2166 int eqv = RE_TRANSLATE (eqv_table, start);
2167 int minchar, maxchar;
2169 /* Classify this character */
2170 if (eqv == start)
2171 this_type = one_case;
2172 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2173 this_type = two_case;
2174 else
2175 this_type = strange;
2177 if (start < eqv)
2178 minchar = start, maxchar = eqv;
2179 else
2180 minchar = eqv, maxchar = start;
2182 /* Can this character extend the run in progress? */
2183 if (this_type == strange || this_type != run_type
2184 || !(minchar == run_end + 1
2185 && (run_type == two_case
2186 ? maxchar == run_eqv_end + 1 : 1)))
2188 /* No, end the run.
2189 Record each of its equivalent ranges. */
2190 if (run_type == one_case)
2192 EXTEND_RANGE_TABLE (work_area, 2);
2193 work_area->table[work_area->used++] = run_start;
2194 work_area->table[work_area->used++] = run_end;
2196 else if (run_type == two_case)
2198 EXTEND_RANGE_TABLE (work_area, 4);
2199 work_area->table[work_area->used++] = run_start;
2200 work_area->table[work_area->used++] = run_end;
2201 work_area->table[work_area->used++]
2202 = RE_TRANSLATE (eqv_table, run_start);
2203 work_area->table[work_area->used++]
2204 = RE_TRANSLATE (eqv_table, run_end);
2206 run_type = strange;
2209 if (this_type == strange)
2211 /* For a strange character, add each of its equivalents, one
2212 by one. Don't start a range. */
2215 EXTEND_RANGE_TABLE (work_area, 2);
2216 work_area->table[work_area->used++] = eqv;
2217 work_area->table[work_area->used++] = eqv;
2218 eqv = RE_TRANSLATE (eqv_table, eqv);
2220 while (eqv != start);
2223 /* Add this char to the run, or start a new run. */
2224 else if (run_type == strange)
2226 /* Initialize a new range. */
2227 run_type = this_type;
2228 run_start = start;
2229 run_end = start;
2230 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2232 else
2234 /* Extend a running range. */
2235 run_end = minchar;
2236 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2240 /* If a run is still in progress at the end, finish it now
2241 by recording its equivalent ranges. */
2242 if (run_type == one_case)
2244 EXTEND_RANGE_TABLE (work_area, 2);
2245 work_area->table[work_area->used++] = run_start;
2246 work_area->table[work_area->used++] = run_end;
2248 else if (run_type == two_case)
2250 EXTEND_RANGE_TABLE (work_area, 4);
2251 work_area->table[work_area->used++] = run_start;
2252 work_area->table[work_area->used++] = run_end;
2253 work_area->table[work_area->used++]
2254 = RE_TRANSLATE (eqv_table, run_start);
2255 work_area->table[work_area->used++]
2256 = RE_TRANSLATE (eqv_table, run_end);
2259 return -1;
2262 #endif /* emacs */
2264 /* Record the image of the range start..end when passed through
2265 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2266 and is not even necessarily contiguous.
2267 Normally we approximate it with the smallest contiguous range that contains
2268 all the chars we need. However, for Latin-1 we go to extra effort
2269 to do a better job.
2271 This function is not called for ASCII ranges.
2273 Returns -1 if successful, REG_ESPACE if ran out of space. */
2275 static int
2276 set_image_of_range (struct range_table_work_area *work_area,
2277 re_wchar_t start, re_wchar_t end,
2278 RE_TRANSLATE_TYPE translate)
2280 re_wchar_t cmin, cmax;
2282 #ifdef emacs
2283 /* For Latin-1 ranges, use set_image_of_range_1
2284 to get proper handling of ranges that include letters and nonletters.
2285 For a range that includes the whole of Latin-1, this is not necessary.
2286 For other character sets, we don't bother to get this right. */
2287 if (RE_TRANSLATE_P (translate) && start < 04400
2288 && !(start < 04200 && end >= 04377))
2290 int newend;
2291 int tem;
2292 newend = end;
2293 if (newend > 04377)
2294 newend = 04377;
2295 tem = set_image_of_range_1 (work_area, start, newend, translate);
2296 if (tem > 0)
2297 return tem;
2299 start = 04400;
2300 if (end < 04400)
2301 return -1;
2303 #endif
2305 EXTEND_RANGE_TABLE (work_area, 2);
2306 work_area->table[work_area->used++] = (start);
2307 work_area->table[work_area->used++] = (end);
2309 cmin = -1, cmax = -1;
2311 if (RE_TRANSLATE_P (translate))
2313 int ch;
2315 for (ch = start; ch <= end; ch++)
2317 re_wchar_t c = TRANSLATE (ch);
2318 if (! (start <= c && c <= end))
2320 if (cmin == -1)
2321 cmin = c, cmax = c;
2322 else
2324 cmin = MIN (cmin, c);
2325 cmax = MAX (cmax, c);
2330 if (cmin != -1)
2332 EXTEND_RANGE_TABLE (work_area, 2);
2333 work_area->table[work_area->used++] = (cmin);
2334 work_area->table[work_area->used++] = (cmax);
2338 return -1;
2340 #endif /* 0 */
2342 #ifndef MATCH_MAY_ALLOCATE
2344 /* If we cannot allocate large objects within re_match_2_internal,
2345 we make the fail stack and register vectors global.
2346 The fail stack, we grow to the maximum size when a regexp
2347 is compiled.
2348 The register vectors, we adjust in size each time we
2349 compile a regexp, according to the number of registers it needs. */
2351 static fail_stack_type fail_stack;
2353 /* Size with which the following vectors are currently allocated.
2354 That is so we can make them bigger as needed,
2355 but never make them smaller. */
2356 static int regs_allocated_size;
2358 static re_char ** regstart, ** regend;
2359 static re_char **best_regstart, **best_regend;
2361 /* Make the register vectors big enough for NUM_REGS registers,
2362 but don't make them smaller. */
2364 static
2365 regex_grow_registers (int num_regs)
2367 if (num_regs > regs_allocated_size)
2369 RETALLOC_IF (regstart, num_regs, re_char *);
2370 RETALLOC_IF (regend, num_regs, re_char *);
2371 RETALLOC_IF (best_regstart, num_regs, re_char *);
2372 RETALLOC_IF (best_regend, num_regs, re_char *);
2374 regs_allocated_size = num_regs;
2378 #endif /* not MATCH_MAY_ALLOCATE */
2380 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2381 regnum_t regnum);
2383 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2384 Returns one of error codes defined in `regex.h', or zero for success.
2386 Assumes the `allocated' (and perhaps `buffer') and `translate'
2387 fields are set in BUFP on entry.
2389 If it succeeds, results are put in BUFP (if it returns an error, the
2390 contents of BUFP are undefined):
2391 `buffer' is the compiled pattern;
2392 `syntax' is set to SYNTAX;
2393 `used' is set to the length of the compiled pattern;
2394 `fastmap_accurate' is zero;
2395 `re_nsub' is the number of subexpressions in PATTERN;
2396 `not_bol' and `not_eol' are zero;
2398 The `fastmap' field is neither examined nor set. */
2400 /* Insert the `jump' from the end of last alternative to "here".
2401 The space for the jump has already been allocated. */
2402 #define FIXUP_ALT_JUMP() \
2403 do { \
2404 if (fixup_alt_jump) \
2405 STORE_JUMP (jump, fixup_alt_jump, b); \
2406 } while (0)
2409 /* Return, freeing storage we allocated. */
2410 #define FREE_STACK_RETURN(value) \
2411 do { \
2412 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2413 free (compile_stack.stack); \
2414 return value; \
2415 } while (0)
2417 static reg_errcode_t
2418 regex_compile (const_re_char *pattern, size_t size, reg_syntax_t syntax,
2419 struct re_pattern_buffer *bufp)
2421 /* We fetch characters from PATTERN here. */
2422 register re_wchar_t c, c1;
2424 /* Points to the end of the buffer, where we should append. */
2425 register unsigned char *b;
2427 /* Keeps track of unclosed groups. */
2428 compile_stack_type compile_stack;
2430 /* Points to the current (ending) position in the pattern. */
2431 #ifdef AIX
2432 /* `const' makes AIX compiler fail. */
2433 unsigned char *p = pattern;
2434 #else
2435 re_char *p = pattern;
2436 #endif
2437 re_char *pend = pattern + size;
2439 /* How to translate the characters in the pattern. */
2440 RE_TRANSLATE_TYPE translate = bufp->translate;
2442 /* Address of the count-byte of the most recently inserted `exactn'
2443 command. This makes it possible to tell if a new exact-match
2444 character can be added to that command or if the character requires
2445 a new `exactn' command. */
2446 unsigned char *pending_exact = 0;
2448 /* Address of start of the most recently finished expression.
2449 This tells, e.g., postfix * where to find the start of its
2450 operand. Reset at the beginning of groups and alternatives. */
2451 unsigned char *laststart = 0;
2453 /* Address of beginning of regexp, or inside of last group. */
2454 unsigned char *begalt;
2456 /* Place in the uncompiled pattern (i.e., the {) to
2457 which to go back if the interval is invalid. */
2458 re_char *beg_interval;
2460 /* Address of the place where a forward jump should go to the end of
2461 the containing expression. Each alternative of an `or' -- except the
2462 last -- ends with a forward jump of this sort. */
2463 unsigned char *fixup_alt_jump = 0;
2465 /* Work area for range table of charset. */
2466 struct range_table_work_area range_table_work;
2468 /* If the object matched can contain multibyte characters. */
2469 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2471 /* Nonzero if we have pushed down into a subpattern. */
2472 int in_subpattern = 0;
2474 /* These hold the values of p, pattern, and pend from the main
2475 pattern when we have pushed into a subpattern. */
2476 re_char *main_p IF_LINT (= NULL);
2477 re_char *main_pattern IF_LINT (= NULL);
2478 re_char *main_pend IF_LINT (= NULL);
2480 #ifdef DEBUG
2481 debug++;
2482 DEBUG_PRINT ("\nCompiling pattern: ");
2483 if (debug > 0)
2485 unsigned debug_count;
2487 for (debug_count = 0; debug_count < size; debug_count++)
2488 putchar (pattern[debug_count]);
2489 putchar ('\n');
2491 #endif /* DEBUG */
2493 /* Initialize the compile stack. */
2494 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2495 if (compile_stack.stack == NULL)
2496 return REG_ESPACE;
2498 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2499 compile_stack.avail = 0;
2501 range_table_work.table = 0;
2502 range_table_work.allocated = 0;
2504 /* Initialize the pattern buffer. */
2505 bufp->syntax = syntax;
2506 bufp->fastmap_accurate = 0;
2507 bufp->not_bol = bufp->not_eol = 0;
2508 bufp->used_syntax = 0;
2510 /* Set `used' to zero, so that if we return an error, the pattern
2511 printer (for debugging) will think there's no pattern. We reset it
2512 at the end. */
2513 bufp->used = 0;
2515 /* Always count groups, whether or not bufp->no_sub is set. */
2516 bufp->re_nsub = 0;
2518 #if !defined emacs && !defined SYNTAX_TABLE
2519 /* Initialize the syntax table. */
2520 init_syntax_once ();
2521 #endif
2523 if (bufp->allocated == 0)
2525 if (bufp->buffer)
2526 { /* If zero allocated, but buffer is non-null, try to realloc
2527 enough space. This loses if buffer's address is bogus, but
2528 that is the user's responsibility. */
2529 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2531 else
2532 { /* Caller did not allocate a buffer. Do it for them. */
2533 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2535 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2537 bufp->allocated = INIT_BUF_SIZE;
2540 begalt = b = bufp->buffer;
2542 /* Loop through the uncompiled pattern until we're at the end. */
2543 while (1)
2545 if (p == pend)
2547 /* If this is the end of an included regexp,
2548 pop back to the main regexp and try again. */
2549 if (in_subpattern)
2551 in_subpattern = 0;
2552 pattern = main_pattern;
2553 p = main_p;
2554 pend = main_pend;
2555 continue;
2557 /* If this is the end of the main regexp, we are done. */
2558 break;
2561 PATFETCH (c);
2563 switch (c)
2565 case ' ':
2567 re_char *p1 = p;
2569 /* If there's no special whitespace regexp, treat
2570 spaces normally. And don't try to do this recursively. */
2571 if (!whitespace_regexp || in_subpattern)
2572 goto normal_char;
2574 /* Peek past following spaces. */
2575 while (p1 != pend)
2577 if (*p1 != ' ')
2578 break;
2579 p1++;
2581 /* If the spaces are followed by a repetition op,
2582 treat them normally. */
2583 if (p1 != pend
2584 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2585 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2586 goto normal_char;
2588 /* Replace the spaces with the whitespace regexp. */
2589 in_subpattern = 1;
2590 main_p = p1;
2591 main_pend = pend;
2592 main_pattern = pattern;
2593 p = pattern = whitespace_regexp;
2594 pend = p + strlen ((const char *) p);
2595 break;
2598 case '^':
2600 if ( /* If at start of pattern, it's an operator. */
2601 p == pattern + 1
2602 /* If context independent, it's an operator. */
2603 || syntax & RE_CONTEXT_INDEP_ANCHORS
2604 /* Otherwise, depends on what's come before. */
2605 || at_begline_loc_p (pattern, p, syntax))
2606 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2607 else
2608 goto normal_char;
2610 break;
2613 case '$':
2615 if ( /* If at end of pattern, it's an operator. */
2616 p == pend
2617 /* If context independent, it's an operator. */
2618 || syntax & RE_CONTEXT_INDEP_ANCHORS
2619 /* Otherwise, depends on what's next. */
2620 || at_endline_loc_p (p, pend, syntax))
2621 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2622 else
2623 goto normal_char;
2625 break;
2628 case '+':
2629 case '?':
2630 if ((syntax & RE_BK_PLUS_QM)
2631 || (syntax & RE_LIMITED_OPS))
2632 goto normal_char;
2633 handle_plus:
2634 case '*':
2635 /* If there is no previous pattern... */
2636 if (!laststart)
2638 if (syntax & RE_CONTEXT_INVALID_OPS)
2639 FREE_STACK_RETURN (REG_BADRPT);
2640 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2641 goto normal_char;
2645 /* 1 means zero (many) matches is allowed. */
2646 boolean zero_times_ok = 0, many_times_ok = 0;
2647 boolean greedy = 1;
2649 /* If there is a sequence of repetition chars, collapse it
2650 down to just one (the right one). We can't combine
2651 interval operators with these because of, e.g., `a{2}*',
2652 which should only match an even number of `a's. */
2654 for (;;)
2656 if ((syntax & RE_FRUGAL)
2657 && c == '?' && (zero_times_ok || many_times_ok))
2658 greedy = 0;
2659 else
2661 zero_times_ok |= c != '+';
2662 many_times_ok |= c != '?';
2665 if (p == pend)
2666 break;
2667 else if (*p == '*'
2668 || (!(syntax & RE_BK_PLUS_QM)
2669 && (*p == '+' || *p == '?')))
2671 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2673 if (p+1 == pend)
2674 FREE_STACK_RETURN (REG_EESCAPE);
2675 if (p[1] == '+' || p[1] == '?')
2676 PATFETCH (c); /* Gobble up the backslash. */
2677 else
2678 break;
2680 else
2681 break;
2682 /* If we get here, we found another repeat character. */
2683 PATFETCH (c);
2686 /* Star, etc. applied to an empty pattern is equivalent
2687 to an empty pattern. */
2688 if (!laststart || laststart == b)
2689 break;
2691 /* Now we know whether or not zero matches is allowed
2692 and also whether or not two or more matches is allowed. */
2693 if (greedy)
2695 if (many_times_ok)
2697 boolean simple = skip_one_char (laststart) == b;
2698 size_t startoffset = 0;
2699 re_opcode_t ofj =
2700 /* Check if the loop can match the empty string. */
2701 (simple || !analyse_first (laststart, b, NULL, 0))
2702 ? on_failure_jump : on_failure_jump_loop;
2703 assert (skip_one_char (laststart) <= b);
2705 if (!zero_times_ok && simple)
2706 { /* Since simple * loops can be made faster by using
2707 on_failure_keep_string_jump, we turn simple P+
2708 into PP* if P is simple. */
2709 unsigned char *p1, *p2;
2710 startoffset = b - laststart;
2711 GET_BUFFER_SPACE (startoffset);
2712 p1 = b; p2 = laststart;
2713 while (p2 < p1)
2714 *b++ = *p2++;
2715 zero_times_ok = 1;
2718 GET_BUFFER_SPACE (6);
2719 if (!zero_times_ok)
2720 /* A + loop. */
2721 STORE_JUMP (ofj, b, b + 6);
2722 else
2723 /* Simple * loops can use on_failure_keep_string_jump
2724 depending on what follows. But since we don't know
2725 that yet, we leave the decision up to
2726 on_failure_jump_smart. */
2727 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2728 laststart + startoffset, b + 6);
2729 b += 3;
2730 STORE_JUMP (jump, b, laststart + startoffset);
2731 b += 3;
2733 else
2735 /* A simple ? pattern. */
2736 assert (zero_times_ok);
2737 GET_BUFFER_SPACE (3);
2738 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2739 b += 3;
2742 else /* not greedy */
2743 { /* I wish the greedy and non-greedy cases could be merged. */
2745 GET_BUFFER_SPACE (7); /* We might use less. */
2746 if (many_times_ok)
2748 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2750 /* The non-greedy multiple match looks like
2751 a repeat..until: we only need a conditional jump
2752 at the end of the loop. */
2753 if (emptyp) BUF_PUSH (no_op);
2754 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2755 : on_failure_jump, b, laststart);
2756 b += 3;
2757 if (zero_times_ok)
2759 /* The repeat...until naturally matches one or more.
2760 To also match zero times, we need to first jump to
2761 the end of the loop (its conditional jump). */
2762 INSERT_JUMP (jump, laststart, b);
2763 b += 3;
2766 else
2768 /* non-greedy a?? */
2769 INSERT_JUMP (jump, laststart, b + 3);
2770 b += 3;
2771 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2772 b += 3;
2776 pending_exact = 0;
2777 break;
2780 case '.':
2781 laststart = b;
2782 BUF_PUSH (anychar);
2783 break;
2786 case '[':
2788 re_char *p1;
2790 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2792 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2794 /* Ensure that we have enough space to push a charset: the
2795 opcode, the length count, and the bitset; 34 bytes in all. */
2796 GET_BUFFER_SPACE (34);
2798 laststart = b;
2800 /* We test `*p == '^' twice, instead of using an if
2801 statement, so we only need one BUF_PUSH. */
2802 BUF_PUSH (*p == '^' ? charset_not : charset);
2803 if (*p == '^')
2804 p++;
2806 /* Remember the first position in the bracket expression. */
2807 p1 = p;
2809 /* Push the number of bytes in the bitmap. */
2810 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2812 /* Clear the whole map. */
2813 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2815 /* charset_not matches newline according to a syntax bit. */
2816 if ((re_opcode_t) b[-2] == charset_not
2817 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2818 SET_LIST_BIT ('\n');
2820 /* Read in characters and ranges, setting map bits. */
2821 for (;;)
2823 boolean escaped_char = false;
2824 const unsigned char *p2 = p;
2825 re_wchar_t ch;
2827 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2829 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2830 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2831 So the translation is done later in a loop. Example:
2832 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2833 PATFETCH (c);
2835 /* \ might escape characters inside [...] and [^...]. */
2836 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2838 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2840 PATFETCH (c);
2841 escaped_char = true;
2843 else
2845 /* Could be the end of the bracket expression. If it's
2846 not (i.e., when the bracket expression is `[]' so
2847 far), the ']' character bit gets set way below. */
2848 if (c == ']' && p2 != p1)
2849 break;
2852 /* See if we're at the beginning of a possible character
2853 class. */
2855 if (!escaped_char &&
2856 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2858 /* Leave room for the null. */
2859 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2860 const unsigned char *class_beg;
2862 PATFETCH (c);
2863 c1 = 0;
2864 class_beg = p;
2866 /* If pattern is `[[:'. */
2867 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2869 for (;;)
2871 PATFETCH (c);
2872 if ((c == ':' && *p == ']') || p == pend)
2873 break;
2874 if (c1 < CHAR_CLASS_MAX_LENGTH)
2875 str[c1++] = c;
2876 else
2877 /* This is in any case an invalid class name. */
2878 str[0] = '\0';
2880 str[c1] = '\0';
2882 /* If isn't a word bracketed by `[:' and `:]':
2883 undo the ending character, the letters, and
2884 leave the leading `:' and `[' (but set bits for
2885 them). */
2886 if (c == ':' && *p == ']')
2888 re_wctype_t cc = re_wctype (str);
2890 if (cc == 0)
2891 FREE_STACK_RETURN (REG_ECTYPE);
2893 /* Throw away the ] at the end of the character
2894 class. */
2895 PATFETCH (c);
2897 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2899 #ifndef emacs
2900 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2901 if (re_iswctype (btowc (ch), cc))
2903 c = TRANSLATE (ch);
2904 if (c < (1 << BYTEWIDTH))
2905 SET_LIST_BIT (c);
2907 #else /* emacs */
2908 /* Most character classes in a multibyte match
2909 just set a flag. Exceptions are is_blank,
2910 is_digit, is_cntrl, and is_xdigit, since
2911 they can only match ASCII characters. We
2912 don't need to handle them for multibyte.
2913 They are distinguished by a negative wctype. */
2915 /* Setup the gl_state object to its buffer-defined
2916 value. This hardcodes the buffer-global
2917 syntax-table for ASCII chars, while the other chars
2918 will obey syntax-table properties. It's not ideal,
2919 but it's the way it's been done until now. */
2920 SETUP_BUFFER_SYNTAX_TABLE ();
2922 for (ch = 0; ch < 256; ++ch)
2924 c = RE_CHAR_TO_MULTIBYTE (ch);
2925 if (! CHAR_BYTE8_P (c)
2926 && re_iswctype (c, cc))
2928 SET_LIST_BIT (ch);
2929 c1 = TRANSLATE (c);
2930 if (c1 == c)
2931 continue;
2932 if (ASCII_CHAR_P (c1))
2933 SET_LIST_BIT (c1);
2934 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2935 SET_LIST_BIT (c1);
2938 SET_RANGE_TABLE_WORK_AREA_BIT
2939 (range_table_work, re_wctype_to_bit (cc));
2940 #endif /* emacs */
2941 /* In most cases the matching rule for char classes
2942 only uses the syntax table for multibyte chars,
2943 so that the content of the syntax-table it is not
2944 hardcoded in the range_table. SPACE and WORD are
2945 the two exceptions. */
2946 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2947 bufp->used_syntax = 1;
2949 /* Repeat the loop. */
2950 continue;
2952 else
2954 /* Go back to right after the "[:". */
2955 p = class_beg;
2956 SET_LIST_BIT ('[');
2958 /* Because the `:' may starts the range, we
2959 can't simply set bit and repeat the loop.
2960 Instead, just set it to C and handle below. */
2961 c = ':';
2965 if (p < pend && p[0] == '-' && p[1] != ']')
2968 /* Discard the `-'. */
2969 PATFETCH (c1);
2971 /* Fetch the character which ends the range. */
2972 PATFETCH (c1);
2973 #ifdef emacs
2974 if (CHAR_BYTE8_P (c1)
2975 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2976 /* Treat the range from a multibyte character to
2977 raw-byte character as empty. */
2978 c = c1 + 1;
2979 #endif /* emacs */
2981 else
2982 /* Range from C to C. */
2983 c1 = c;
2985 if (c > c1)
2987 if (syntax & RE_NO_EMPTY_RANGES)
2988 FREE_STACK_RETURN (REG_ERANGEX);
2989 /* Else, repeat the loop. */
2991 else
2993 #ifndef emacs
2994 /* Set the range into bitmap */
2995 for (; c <= c1; c++)
2997 ch = TRANSLATE (c);
2998 if (ch < (1 << BYTEWIDTH))
2999 SET_LIST_BIT (ch);
3001 #else /* emacs */
3002 if (c < 128)
3004 ch = MIN (127, c1);
3005 SETUP_ASCII_RANGE (range_table_work, c, ch);
3006 c = ch + 1;
3007 if (CHAR_BYTE8_P (c1))
3008 c = BYTE8_TO_CHAR (128);
3010 if (c <= c1)
3012 if (CHAR_BYTE8_P (c))
3014 c = CHAR_TO_BYTE8 (c);
3015 c1 = CHAR_TO_BYTE8 (c1);
3016 for (; c <= c1; c++)
3017 SET_LIST_BIT (c);
3019 else if (multibyte)
3021 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
3023 else
3025 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
3028 #endif /* emacs */
3032 /* Discard any (non)matching list bytes that are all 0 at the
3033 end of the map. Decrease the map-length byte too. */
3034 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3035 b[-1]--;
3036 b += b[-1];
3038 /* Build real range table from work area. */
3039 if (RANGE_TABLE_WORK_USED (range_table_work)
3040 || RANGE_TABLE_WORK_BITS (range_table_work))
3042 int i;
3043 int used = RANGE_TABLE_WORK_USED (range_table_work);
3045 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3046 bytes for flags, two for COUNT, and three bytes for
3047 each character. */
3048 GET_BUFFER_SPACE (4 + used * 3);
3050 /* Indicate the existence of range table. */
3051 laststart[1] |= 0x80;
3053 /* Store the character class flag bits into the range table.
3054 If not in emacs, these flag bits are always 0. */
3055 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3056 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3058 STORE_NUMBER_AND_INCR (b, used / 2);
3059 for (i = 0; i < used; i++)
3060 STORE_CHARACTER_AND_INCR
3061 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3064 break;
3067 case '(':
3068 if (syntax & RE_NO_BK_PARENS)
3069 goto handle_open;
3070 else
3071 goto normal_char;
3074 case ')':
3075 if (syntax & RE_NO_BK_PARENS)
3076 goto handle_close;
3077 else
3078 goto normal_char;
3081 case '\n':
3082 if (syntax & RE_NEWLINE_ALT)
3083 goto handle_alt;
3084 else
3085 goto normal_char;
3088 case '|':
3089 if (syntax & RE_NO_BK_VBAR)
3090 goto handle_alt;
3091 else
3092 goto normal_char;
3095 case '{':
3096 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3097 goto handle_interval;
3098 else
3099 goto normal_char;
3102 case '\\':
3103 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3105 /* Do not translate the character after the \, so that we can
3106 distinguish, e.g., \B from \b, even if we normally would
3107 translate, e.g., B to b. */
3108 PATFETCH (c);
3110 switch (c)
3112 case '(':
3113 if (syntax & RE_NO_BK_PARENS)
3114 goto normal_backslash;
3116 handle_open:
3118 int shy = 0;
3119 regnum_t regnum = 0;
3120 if (p+1 < pend)
3122 /* Look for a special (?...) construct */
3123 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3125 PATFETCH (c); /* Gobble up the '?'. */
3126 while (!shy)
3128 PATFETCH (c);
3129 switch (c)
3131 case ':': shy = 1; break;
3132 case '0':
3133 /* An explicitly specified regnum must start
3134 with non-0. */
3135 if (regnum == 0)
3136 FREE_STACK_RETURN (REG_BADPAT);
3137 case '1': case '2': case '3': case '4':
3138 case '5': case '6': case '7': case '8': case '9':
3139 regnum = 10*regnum + (c - '0'); break;
3140 default:
3141 /* Only (?:...) is supported right now. */
3142 FREE_STACK_RETURN (REG_BADPAT);
3148 if (!shy)
3149 regnum = ++bufp->re_nsub;
3150 else if (regnum)
3151 { /* It's actually not shy, but explicitly numbered. */
3152 shy = 0;
3153 if (regnum > bufp->re_nsub)
3154 bufp->re_nsub = regnum;
3155 else if (regnum > bufp->re_nsub
3156 /* Ideally, we'd want to check that the specified
3157 group can't have matched (i.e. all subgroups
3158 using the same regnum are in other branches of
3159 OR patterns), but we don't currently keep track
3160 of enough info to do that easily. */
3161 || group_in_compile_stack (compile_stack, regnum))
3162 FREE_STACK_RETURN (REG_BADPAT);
3164 else
3165 /* It's really shy. */
3166 regnum = - bufp->re_nsub;
3168 if (COMPILE_STACK_FULL)
3170 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3171 compile_stack_elt_t);
3172 if (compile_stack.stack == NULL) return REG_ESPACE;
3174 compile_stack.size <<= 1;
3177 /* These are the values to restore when we hit end of this
3178 group. They are all relative offsets, so that if the
3179 whole pattern moves because of realloc, they will still
3180 be valid. */
3181 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3182 COMPILE_STACK_TOP.fixup_alt_jump
3183 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3184 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3185 COMPILE_STACK_TOP.regnum = regnum;
3187 /* Do not push a start_memory for groups beyond the last one
3188 we can represent in the compiled pattern. */
3189 if (regnum <= MAX_REGNUM && regnum > 0)
3190 BUF_PUSH_2 (start_memory, regnum);
3192 compile_stack.avail++;
3194 fixup_alt_jump = 0;
3195 laststart = 0;
3196 begalt = b;
3197 /* If we've reached MAX_REGNUM groups, then this open
3198 won't actually generate any code, so we'll have to
3199 clear pending_exact explicitly. */
3200 pending_exact = 0;
3201 break;
3204 case ')':
3205 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3207 if (COMPILE_STACK_EMPTY)
3209 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3210 goto normal_backslash;
3211 else
3212 FREE_STACK_RETURN (REG_ERPAREN);
3215 handle_close:
3216 FIXUP_ALT_JUMP ();
3218 /* See similar code for backslashed left paren above. */
3219 if (COMPILE_STACK_EMPTY)
3221 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3222 goto normal_char;
3223 else
3224 FREE_STACK_RETURN (REG_ERPAREN);
3227 /* Since we just checked for an empty stack above, this
3228 ``can't happen''. */
3229 assert (compile_stack.avail != 0);
3231 /* We don't just want to restore into `regnum', because
3232 later groups should continue to be numbered higher,
3233 as in `(ab)c(de)' -- the second group is #2. */
3234 regnum_t regnum;
3236 compile_stack.avail--;
3237 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3238 fixup_alt_jump
3239 = COMPILE_STACK_TOP.fixup_alt_jump
3240 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3241 : 0;
3242 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3243 regnum = COMPILE_STACK_TOP.regnum;
3244 /* If we've reached MAX_REGNUM groups, then this open
3245 won't actually generate any code, so we'll have to
3246 clear pending_exact explicitly. */
3247 pending_exact = 0;
3249 /* We're at the end of the group, so now we know how many
3250 groups were inside this one. */
3251 if (regnum <= MAX_REGNUM && regnum > 0)
3252 BUF_PUSH_2 (stop_memory, regnum);
3254 break;
3257 case '|': /* `\|'. */
3258 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3259 goto normal_backslash;
3260 handle_alt:
3261 if (syntax & RE_LIMITED_OPS)
3262 goto normal_char;
3264 /* Insert before the previous alternative a jump which
3265 jumps to this alternative if the former fails. */
3266 GET_BUFFER_SPACE (3);
3267 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3268 pending_exact = 0;
3269 b += 3;
3271 /* The alternative before this one has a jump after it
3272 which gets executed if it gets matched. Adjust that
3273 jump so it will jump to this alternative's analogous
3274 jump (put in below, which in turn will jump to the next
3275 (if any) alternative's such jump, etc.). The last such
3276 jump jumps to the correct final destination. A picture:
3277 _____ _____
3278 | | | |
3279 | v | v
3280 a | b | c
3282 If we are at `b', then fixup_alt_jump right now points to a
3283 three-byte space after `a'. We'll put in the jump, set
3284 fixup_alt_jump to right after `b', and leave behind three
3285 bytes which we'll fill in when we get to after `c'. */
3287 FIXUP_ALT_JUMP ();
3289 /* Mark and leave space for a jump after this alternative,
3290 to be filled in later either by next alternative or
3291 when know we're at the end of a series of alternatives. */
3292 fixup_alt_jump = b;
3293 GET_BUFFER_SPACE (3);
3294 b += 3;
3296 laststart = 0;
3297 begalt = b;
3298 break;
3301 case '{':
3302 /* If \{ is a literal. */
3303 if (!(syntax & RE_INTERVALS)
3304 /* If we're at `\{' and it's not the open-interval
3305 operator. */
3306 || (syntax & RE_NO_BK_BRACES))
3307 goto normal_backslash;
3309 handle_interval:
3311 /* If got here, then the syntax allows intervals. */
3313 /* At least (most) this many matches must be made. */
3314 int lower_bound = 0, upper_bound = -1;
3316 beg_interval = p;
3318 GET_UNSIGNED_NUMBER (lower_bound);
3320 if (c == ',')
3321 GET_UNSIGNED_NUMBER (upper_bound);
3322 else
3323 /* Interval such as `{1}' => match exactly once. */
3324 upper_bound = lower_bound;
3326 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3327 || (upper_bound >= 0 && lower_bound > upper_bound))
3328 FREE_STACK_RETURN (REG_BADBR);
3330 if (!(syntax & RE_NO_BK_BRACES))
3332 if (c != '\\')
3333 FREE_STACK_RETURN (REG_BADBR);
3334 if (p == pend)
3335 FREE_STACK_RETURN (REG_EESCAPE);
3336 PATFETCH (c);
3339 if (c != '}')
3340 FREE_STACK_RETURN (REG_BADBR);
3342 /* We just parsed a valid interval. */
3344 /* If it's invalid to have no preceding re. */
3345 if (!laststart)
3347 if (syntax & RE_CONTEXT_INVALID_OPS)
3348 FREE_STACK_RETURN (REG_BADRPT);
3349 else if (syntax & RE_CONTEXT_INDEP_OPS)
3350 laststart = b;
3351 else
3352 goto unfetch_interval;
3355 if (upper_bound == 0)
3356 /* If the upper bound is zero, just drop the sub pattern
3357 altogether. */
3358 b = laststart;
3359 else if (lower_bound == 1 && upper_bound == 1)
3360 /* Just match it once: nothing to do here. */
3363 /* Otherwise, we have a nontrivial interval. When
3364 we're all done, the pattern will look like:
3365 set_number_at <jump count> <upper bound>
3366 set_number_at <succeed_n count> <lower bound>
3367 succeed_n <after jump addr> <succeed_n count>
3368 <body of loop>
3369 jump_n <succeed_n addr> <jump count>
3370 (The upper bound and `jump_n' are omitted if
3371 `upper_bound' is 1, though.) */
3372 else
3373 { /* If the upper bound is > 1, we need to insert
3374 more at the end of the loop. */
3375 unsigned int nbytes = (upper_bound < 0 ? 3
3376 : upper_bound > 1 ? 5 : 0);
3377 unsigned int startoffset = 0;
3379 GET_BUFFER_SPACE (20); /* We might use less. */
3381 if (lower_bound == 0)
3383 /* A succeed_n that starts with 0 is really a
3384 a simple on_failure_jump_loop. */
3385 INSERT_JUMP (on_failure_jump_loop, laststart,
3386 b + 3 + nbytes);
3387 b += 3;
3389 else
3391 /* Initialize lower bound of the `succeed_n', even
3392 though it will be set during matching by its
3393 attendant `set_number_at' (inserted next),
3394 because `re_compile_fastmap' needs to know.
3395 Jump to the `jump_n' we might insert below. */
3396 INSERT_JUMP2 (succeed_n, laststart,
3397 b + 5 + nbytes,
3398 lower_bound);
3399 b += 5;
3401 /* Code to initialize the lower bound. Insert
3402 before the `succeed_n'. The `5' is the last two
3403 bytes of this `set_number_at', plus 3 bytes of
3404 the following `succeed_n'. */
3405 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3406 b += 5;
3407 startoffset += 5;
3410 if (upper_bound < 0)
3412 /* A negative upper bound stands for infinity,
3413 in which case it degenerates to a plain jump. */
3414 STORE_JUMP (jump, b, laststart + startoffset);
3415 b += 3;
3417 else if (upper_bound > 1)
3418 { /* More than one repetition is allowed, so
3419 append a backward jump to the `succeed_n'
3420 that starts this interval.
3422 When we've reached this during matching,
3423 we'll have matched the interval once, so
3424 jump back only `upper_bound - 1' times. */
3425 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3426 upper_bound - 1);
3427 b += 5;
3429 /* The location we want to set is the second
3430 parameter of the `jump_n'; that is `b-2' as
3431 an absolute address. `laststart' will be
3432 the `set_number_at' we're about to insert;
3433 `laststart+3' the number to set, the source
3434 for the relative address. But we are
3435 inserting into the middle of the pattern --
3436 so everything is getting moved up by 5.
3437 Conclusion: (b - 2) - (laststart + 3) + 5,
3438 i.e., b - laststart.
3440 We insert this at the beginning of the loop
3441 so that if we fail during matching, we'll
3442 reinitialize the bounds. */
3443 insert_op2 (set_number_at, laststart, b - laststart,
3444 upper_bound - 1, b);
3445 b += 5;
3448 pending_exact = 0;
3449 beg_interval = NULL;
3451 break;
3453 unfetch_interval:
3454 /* If an invalid interval, match the characters as literals. */
3455 assert (beg_interval);
3456 p = beg_interval;
3457 beg_interval = NULL;
3459 /* normal_char and normal_backslash need `c'. */
3460 c = '{';
3462 if (!(syntax & RE_NO_BK_BRACES))
3464 assert (p > pattern && p[-1] == '\\');
3465 goto normal_backslash;
3467 else
3468 goto normal_char;
3470 #ifdef emacs
3471 /* There is no way to specify the before_dot and after_dot
3472 operators. rms says this is ok. --karl */
3473 case '=':
3474 laststart = b;
3475 BUF_PUSH (at_dot);
3476 break;
3478 case 's':
3479 laststart = b;
3480 PATFETCH (c);
3481 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3482 break;
3484 case 'S':
3485 laststart = b;
3486 PATFETCH (c);
3487 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3488 break;
3490 case 'c':
3491 laststart = b;
3492 PATFETCH (c);
3493 BUF_PUSH_2 (categoryspec, c);
3494 break;
3496 case 'C':
3497 laststart = b;
3498 PATFETCH (c);
3499 BUF_PUSH_2 (notcategoryspec, c);
3500 break;
3501 #endif /* emacs */
3504 case 'w':
3505 if (syntax & RE_NO_GNU_OPS)
3506 goto normal_char;
3507 laststart = b;
3508 BUF_PUSH_2 (syntaxspec, Sword);
3509 break;
3512 case 'W':
3513 if (syntax & RE_NO_GNU_OPS)
3514 goto normal_char;
3515 laststart = b;
3516 BUF_PUSH_2 (notsyntaxspec, Sword);
3517 break;
3520 case '<':
3521 if (syntax & RE_NO_GNU_OPS)
3522 goto normal_char;
3523 laststart = b;
3524 BUF_PUSH (wordbeg);
3525 break;
3527 case '>':
3528 if (syntax & RE_NO_GNU_OPS)
3529 goto normal_char;
3530 laststart = b;
3531 BUF_PUSH (wordend);
3532 break;
3534 case '_':
3535 if (syntax & RE_NO_GNU_OPS)
3536 goto normal_char;
3537 laststart = b;
3538 PATFETCH (c);
3539 if (c == '<')
3540 BUF_PUSH (symbeg);
3541 else if (c == '>')
3542 BUF_PUSH (symend);
3543 else
3544 FREE_STACK_RETURN (REG_BADPAT);
3545 break;
3547 case 'b':
3548 if (syntax & RE_NO_GNU_OPS)
3549 goto normal_char;
3550 BUF_PUSH (wordbound);
3551 break;
3553 case 'B':
3554 if (syntax & RE_NO_GNU_OPS)
3555 goto normal_char;
3556 BUF_PUSH (notwordbound);
3557 break;
3559 case '`':
3560 if (syntax & RE_NO_GNU_OPS)
3561 goto normal_char;
3562 BUF_PUSH (begbuf);
3563 break;
3565 case '\'':
3566 if (syntax & RE_NO_GNU_OPS)
3567 goto normal_char;
3568 BUF_PUSH (endbuf);
3569 break;
3571 case '1': case '2': case '3': case '4': case '5':
3572 case '6': case '7': case '8': case '9':
3574 regnum_t reg;
3576 if (syntax & RE_NO_BK_REFS)
3577 goto normal_backslash;
3579 reg = c - '0';
3581 if (reg > bufp->re_nsub || reg < 1
3582 /* Can't back reference to a subexp before its end. */
3583 || group_in_compile_stack (compile_stack, reg))
3584 FREE_STACK_RETURN (REG_ESUBREG);
3586 laststart = b;
3587 BUF_PUSH_2 (duplicate, reg);
3589 break;
3592 case '+':
3593 case '?':
3594 if (syntax & RE_BK_PLUS_QM)
3595 goto handle_plus;
3596 else
3597 goto normal_backslash;
3599 default:
3600 normal_backslash:
3601 /* You might think it would be useful for \ to mean
3602 not to translate; but if we don't translate it
3603 it will never match anything. */
3604 goto normal_char;
3606 break;
3609 default:
3610 /* Expects the character in `c'. */
3611 normal_char:
3612 /* If no exactn currently being built. */
3613 if (!pending_exact
3615 /* If last exactn not at current position. */
3616 || pending_exact + *pending_exact + 1 != b
3618 /* We have only one byte following the exactn for the count. */
3619 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3621 /* If followed by a repetition operator. */
3622 || (p != pend && (*p == '*' || *p == '^'))
3623 || ((syntax & RE_BK_PLUS_QM)
3624 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3625 : p != pend && (*p == '+' || *p == '?'))
3626 || ((syntax & RE_INTERVALS)
3627 && ((syntax & RE_NO_BK_BRACES)
3628 ? p != pend && *p == '{'
3629 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3631 /* Start building a new exactn. */
3633 laststart = b;
3635 BUF_PUSH_2 (exactn, 0);
3636 pending_exact = b - 1;
3639 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3641 int len;
3643 if (multibyte)
3645 c = TRANSLATE (c);
3646 len = CHAR_STRING (c, b);
3647 b += len;
3649 else
3651 c1 = RE_CHAR_TO_MULTIBYTE (c);
3652 if (! CHAR_BYTE8_P (c1))
3654 re_wchar_t c2 = TRANSLATE (c1);
3656 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3657 c = c1;
3659 *b++ = c;
3660 len = 1;
3662 (*pending_exact) += len;
3665 break;
3666 } /* switch (c) */
3667 } /* while p != pend */
3670 /* Through the pattern now. */
3672 FIXUP_ALT_JUMP ();
3674 if (!COMPILE_STACK_EMPTY)
3675 FREE_STACK_RETURN (REG_EPAREN);
3677 /* If we don't want backtracking, force success
3678 the first time we reach the end of the compiled pattern. */
3679 if (syntax & RE_NO_POSIX_BACKTRACKING)
3680 BUF_PUSH (succeed);
3682 /* We have succeeded; set the length of the buffer. */
3683 bufp->used = b - bufp->buffer;
3685 #ifdef DEBUG
3686 if (debug > 0)
3688 re_compile_fastmap (bufp);
3689 DEBUG_PRINT ("\nCompiled pattern: \n");
3690 print_compiled_pattern (bufp);
3692 debug--;
3693 #endif /* DEBUG */
3695 #ifndef MATCH_MAY_ALLOCATE
3696 /* Initialize the failure stack to the largest possible stack. This
3697 isn't necessary unless we're trying to avoid calling alloca in
3698 the search and match routines. */
3700 int num_regs = bufp->re_nsub + 1;
3702 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3704 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3705 falk_stack.stack = realloc (fail_stack.stack,
3706 fail_stack.size * sizeof *falk_stack.stack);
3709 regex_grow_registers (num_regs);
3711 #endif /* not MATCH_MAY_ALLOCATE */
3713 FREE_STACK_RETURN (REG_NOERROR);
3714 } /* regex_compile */
3716 /* Subroutines for `regex_compile'. */
3718 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3720 static void
3721 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3723 *loc = (unsigned char) op;
3724 STORE_NUMBER (loc + 1, arg);
3728 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3730 static void
3731 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3733 *loc = (unsigned char) op;
3734 STORE_NUMBER (loc + 1, arg1);
3735 STORE_NUMBER (loc + 3, arg2);
3739 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3740 for OP followed by two-byte integer parameter ARG. */
3742 static void
3743 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3745 register unsigned char *pfrom = end;
3746 register unsigned char *pto = end + 3;
3748 while (pfrom != loc)
3749 *--pto = *--pfrom;
3751 store_op1 (op, loc, arg);
3755 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3757 static void
3758 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3760 register unsigned char *pfrom = end;
3761 register unsigned char *pto = end + 5;
3763 while (pfrom != loc)
3764 *--pto = *--pfrom;
3766 store_op2 (op, loc, arg1, arg2);
3770 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3771 after an alternative or a begin-subexpression. We assume there is at
3772 least one character before the ^. */
3774 static boolean
3775 at_begline_loc_p (const_re_char *pattern, const_re_char *p, reg_syntax_t syntax)
3777 re_char *prev = p - 2;
3778 boolean odd_backslashes;
3780 /* After a subexpression? */
3781 if (*prev == '(')
3782 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3784 /* After an alternative? */
3785 else if (*prev == '|')
3786 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3788 /* After a shy subexpression? */
3789 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3791 /* Skip over optional regnum. */
3792 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3793 --prev;
3795 if (!(prev - 2 >= pattern
3796 && prev[-1] == '?' && prev[-2] == '('))
3797 return false;
3798 prev -= 2;
3799 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3801 else
3802 return false;
3804 /* Count the number of preceding backslashes. */
3805 p = prev;
3806 while (prev - 1 >= pattern && prev[-1] == '\\')
3807 --prev;
3808 return (p - prev) & odd_backslashes;
3812 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3813 at least one character after the $, i.e., `P < PEND'. */
3815 static boolean
3816 at_endline_loc_p (const_re_char *p, const_re_char *pend, reg_syntax_t syntax)
3818 re_char *next = p;
3819 boolean next_backslash = *next == '\\';
3820 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3822 return
3823 /* Before a subexpression? */
3824 (syntax & RE_NO_BK_PARENS ? *next == ')'
3825 : next_backslash && next_next && *next_next == ')')
3826 /* Before an alternative? */
3827 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3828 : next_backslash && next_next && *next_next == '|');
3832 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3833 false if it's not. */
3835 static boolean
3836 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3838 ssize_t this_element;
3840 for (this_element = compile_stack.avail - 1;
3841 this_element >= 0;
3842 this_element--)
3843 if (compile_stack.stack[this_element].regnum == regnum)
3844 return true;
3846 return false;
3849 /* analyse_first.
3850 If fastmap is non-NULL, go through the pattern and fill fastmap
3851 with all the possible leading chars. If fastmap is NULL, don't
3852 bother filling it up (obviously) and only return whether the
3853 pattern could potentially match the empty string.
3855 Return 1 if p..pend might match the empty string.
3856 Return 0 if p..pend matches at least one char.
3857 Return -1 if fastmap was not updated accurately. */
3859 static int
3860 analyse_first (const_re_char *p, const_re_char *pend, char *fastmap,
3861 const int multibyte)
3863 int j, k;
3864 boolean not;
3866 /* If all elements for base leading-codes in fastmap is set, this
3867 flag is set true. */
3868 boolean match_any_multibyte_characters = false;
3870 assert (p);
3872 /* The loop below works as follows:
3873 - It has a working-list kept in the PATTERN_STACK and which basically
3874 starts by only containing a pointer to the first operation.
3875 - If the opcode we're looking at is a match against some set of
3876 chars, then we add those chars to the fastmap and go on to the
3877 next work element from the worklist (done via `break').
3878 - If the opcode is a control operator on the other hand, we either
3879 ignore it (if it's meaningless at this point, such as `start_memory')
3880 or execute it (if it's a jump). If the jump has several destinations
3881 (i.e. `on_failure_jump'), then we push the other destination onto the
3882 worklist.
3883 We guarantee termination by ignoring backward jumps (more or less),
3884 so that `p' is monotonically increasing. More to the point, we
3885 never set `p' (or push) anything `<= p1'. */
3887 while (p < pend)
3889 /* `p1' is used as a marker of how far back a `on_failure_jump'
3890 can go without being ignored. It is normally equal to `p'
3891 (which prevents any backward `on_failure_jump') except right
3892 after a plain `jump', to allow patterns such as:
3893 0: jump 10
3894 3..9: <body>
3895 10: on_failure_jump 3
3896 as used for the *? operator. */
3897 re_char *p1 = p;
3899 switch (*p++)
3901 case succeed:
3902 return 1;
3904 case duplicate:
3905 /* If the first character has to match a backreference, that means
3906 that the group was empty (since it already matched). Since this
3907 is the only case that interests us here, we can assume that the
3908 backreference must match the empty string. */
3909 p++;
3910 continue;
3913 /* Following are the cases which match a character. These end
3914 with `break'. */
3916 case exactn:
3917 if (fastmap)
3919 /* If multibyte is nonzero, the first byte of each
3920 character is an ASCII or a leading code. Otherwise,
3921 each byte is a character. Thus, this works in both
3922 cases. */
3923 fastmap[p[1]] = 1;
3924 if (! multibyte)
3926 /* For the case of matching this unibyte regex
3927 against multibyte, we must set a leading code of
3928 the corresponding multibyte character. */
3929 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3931 fastmap[CHAR_LEADING_CODE (c)] = 1;
3934 break;
3937 case anychar:
3938 /* We could put all the chars except for \n (and maybe \0)
3939 but we don't bother since it is generally not worth it. */
3940 if (!fastmap) break;
3941 return -1;
3944 case charset_not:
3945 if (!fastmap) break;
3947 /* Chars beyond end of bitmap are possible matches. */
3948 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3949 j < (1 << BYTEWIDTH); j++)
3950 fastmap[j] = 1;
3953 /* Fallthrough */
3954 case charset:
3955 if (!fastmap) break;
3956 not = (re_opcode_t) *(p - 1) == charset_not;
3957 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3958 j >= 0; j--)
3959 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3960 fastmap[j] = 1;
3962 #ifdef emacs
3963 if (/* Any leading code can possibly start a character
3964 which doesn't match the specified set of characters. */
3967 /* If we can match a character class, we can match any
3968 multibyte characters. */
3969 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3970 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3973 if (match_any_multibyte_characters == false)
3975 for (j = MIN_MULTIBYTE_LEADING_CODE;
3976 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3977 fastmap[j] = 1;
3978 match_any_multibyte_characters = true;
3982 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3983 && match_any_multibyte_characters == false)
3985 /* Set fastmap[I] to 1 where I is a leading code of each
3986 multibyte character in the range table. */
3987 int c, count;
3988 unsigned char lc1, lc2;
3990 /* Make P points the range table. `+ 2' is to skip flag
3991 bits for a character class. */
3992 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3994 /* Extract the number of ranges in range table into COUNT. */
3995 EXTRACT_NUMBER_AND_INCR (count, p);
3996 for (; count > 0; count--, p += 3)
3998 /* Extract the start and end of each range. */
3999 EXTRACT_CHARACTER (c, p);
4000 lc1 = CHAR_LEADING_CODE (c);
4001 p += 3;
4002 EXTRACT_CHARACTER (c, p);
4003 lc2 = CHAR_LEADING_CODE (c);
4004 for (j = lc1; j <= lc2; j++)
4005 fastmap[j] = 1;
4008 #endif
4009 break;
4011 case syntaxspec:
4012 case notsyntaxspec:
4013 if (!fastmap) break;
4014 #ifndef emacs
4015 not = (re_opcode_t)p[-1] == notsyntaxspec;
4016 k = *p++;
4017 for (j = 0; j < (1 << BYTEWIDTH); j++)
4018 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
4019 fastmap[j] = 1;
4020 break;
4021 #else /* emacs */
4022 /* This match depends on text properties. These end with
4023 aborting optimizations. */
4024 return -1;
4026 case categoryspec:
4027 case notcategoryspec:
4028 if (!fastmap) break;
4029 not = (re_opcode_t)p[-1] == notcategoryspec;
4030 k = *p++;
4031 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4032 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4033 fastmap[j] = 1;
4035 /* Any leading code can possibly start a character which
4036 has or doesn't has the specified category. */
4037 if (match_any_multibyte_characters == false)
4039 for (j = MIN_MULTIBYTE_LEADING_CODE;
4040 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4041 fastmap[j] = 1;
4042 match_any_multibyte_characters = true;
4044 break;
4046 /* All cases after this match the empty string. These end with
4047 `continue'. */
4049 case before_dot:
4050 case at_dot:
4051 case after_dot:
4052 #endif /* !emacs */
4053 case no_op:
4054 case begline:
4055 case endline:
4056 case begbuf:
4057 case endbuf:
4058 case wordbound:
4059 case notwordbound:
4060 case wordbeg:
4061 case wordend:
4062 case symbeg:
4063 case symend:
4064 continue;
4067 case jump:
4068 EXTRACT_NUMBER_AND_INCR (j, p);
4069 if (j < 0)
4070 /* Backward jumps can only go back to code that we've already
4071 visited. `re_compile' should make sure this is true. */
4072 break;
4073 p += j;
4074 switch (*p)
4076 case on_failure_jump:
4077 case on_failure_keep_string_jump:
4078 case on_failure_jump_loop:
4079 case on_failure_jump_nastyloop:
4080 case on_failure_jump_smart:
4081 p++;
4082 break;
4083 default:
4084 continue;
4086 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4087 to jump back to "just after here". */
4088 /* Fallthrough */
4090 case on_failure_jump:
4091 case on_failure_keep_string_jump:
4092 case on_failure_jump_nastyloop:
4093 case on_failure_jump_loop:
4094 case on_failure_jump_smart:
4095 EXTRACT_NUMBER_AND_INCR (j, p);
4096 if (p + j <= p1)
4097 ; /* Backward jump to be ignored. */
4098 else
4099 { /* We have to look down both arms.
4100 We first go down the "straight" path so as to minimize
4101 stack usage when going through alternatives. */
4102 int r = analyse_first (p, pend, fastmap, multibyte);
4103 if (r) return r;
4104 p += j;
4106 continue;
4109 case jump_n:
4110 /* This code simply does not properly handle forward jump_n. */
4111 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4112 p += 4;
4113 /* jump_n can either jump or fall through. The (backward) jump
4114 case has already been handled, so we only need to look at the
4115 fallthrough case. */
4116 continue;
4118 case succeed_n:
4119 /* If N == 0, it should be an on_failure_jump_loop instead. */
4120 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4121 p += 4;
4122 /* We only care about one iteration of the loop, so we don't
4123 need to consider the case where this behaves like an
4124 on_failure_jump. */
4125 continue;
4128 case set_number_at:
4129 p += 4;
4130 continue;
4133 case start_memory:
4134 case stop_memory:
4135 p += 1;
4136 continue;
4139 default:
4140 abort (); /* We have listed all the cases. */
4141 } /* switch *p++ */
4143 /* Getting here means we have found the possible starting
4144 characters for one path of the pattern -- and that the empty
4145 string does not match. We need not follow this path further. */
4146 return 0;
4147 } /* while p */
4149 /* We reached the end without matching anything. */
4150 return 1;
4152 } /* analyse_first */
4154 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4155 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4156 characters can start a string that matches the pattern. This fastmap
4157 is used by re_search to skip quickly over impossible starting points.
4159 Character codes above (1 << BYTEWIDTH) are not represented in the
4160 fastmap, but the leading codes are represented. Thus, the fastmap
4161 indicates which character sets could start a match.
4163 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4164 area as BUFP->fastmap.
4166 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4167 the pattern buffer.
4169 Returns 0 if we succeed, -2 if an internal error. */
4172 re_compile_fastmap (struct re_pattern_buffer *bufp)
4174 char *fastmap = bufp->fastmap;
4175 int analysis;
4177 assert (fastmap && bufp->buffer);
4179 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4180 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4182 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
4183 fastmap, RE_MULTIBYTE_P (bufp));
4184 bufp->can_be_null = (analysis != 0);
4185 return 0;
4186 } /* re_compile_fastmap */
4188 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4189 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4190 this memory for recording register information. STARTS and ENDS
4191 must be allocated using the malloc library routine, and must each
4192 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4194 If NUM_REGS == 0, then subsequent matches should allocate their own
4195 register data.
4197 Unless this function is called, the first search or match using
4198 PATTERN_BUFFER will allocate its own register data, without
4199 freeing the old data. */
4201 void
4202 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4204 if (num_regs)
4206 bufp->regs_allocated = REGS_REALLOCATE;
4207 regs->num_regs = num_regs;
4208 regs->start = starts;
4209 regs->end = ends;
4211 else
4213 bufp->regs_allocated = REGS_UNALLOCATED;
4214 regs->num_regs = 0;
4215 regs->start = regs->end = 0;
4218 WEAK_ALIAS (__re_set_registers, re_set_registers)
4220 /* Searching routines. */
4222 /* Like re_search_2, below, but only one string is specified, and
4223 doesn't let you say where to stop matching. */
4225 regoff_t
4226 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4227 ssize_t startpos, ssize_t range, struct re_registers *regs)
4229 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4230 regs, size);
4232 WEAK_ALIAS (__re_search, re_search)
4234 /* Head address of virtual concatenation of string. */
4235 #define HEAD_ADDR_VSTRING(P) \
4236 (((P) >= size1 ? string2 : string1))
4238 /* Address of POS in the concatenation of virtual string. */
4239 #define POS_ADDR_VSTRING(POS) \
4240 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4242 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4243 virtual concatenation of STRING1 and STRING2, starting first at index
4244 STARTPOS, then at STARTPOS + 1, and so on.
4246 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4248 RANGE is how far to scan while trying to match. RANGE = 0 means try
4249 only at STARTPOS; in general, the last start tried is STARTPOS +
4250 RANGE.
4252 In REGS, return the indices of the virtual concatenation of STRING1
4253 and STRING2 that matched the entire BUFP->buffer and its contained
4254 subexpressions.
4256 Do not consider matching one past the index STOP in the virtual
4257 concatenation of STRING1 and STRING2.
4259 We return either the position in the strings at which the match was
4260 found, -1 if no match, or -2 if error (such as failure
4261 stack overflow). */
4263 regoff_t
4264 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4265 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4266 struct re_registers *regs, ssize_t stop)
4268 regoff_t val;
4269 re_char *string1 = (re_char*) str1;
4270 re_char *string2 = (re_char*) str2;
4271 register char *fastmap = bufp->fastmap;
4272 register RE_TRANSLATE_TYPE translate = bufp->translate;
4273 size_t total_size = size1 + size2;
4274 ssize_t endpos = startpos + range;
4275 boolean anchored_start;
4276 /* Nonzero if we are searching multibyte string. */
4277 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4279 /* Check for out-of-range STARTPOS. */
4280 if (startpos < 0 || startpos > total_size)
4281 return -1;
4283 /* Fix up RANGE if it might eventually take us outside
4284 the virtual concatenation of STRING1 and STRING2.
4285 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4286 if (endpos < 0)
4287 range = 0 - startpos;
4288 else if (endpos > total_size)
4289 range = total_size - startpos;
4291 /* If the search isn't to be a backwards one, don't waste time in a
4292 search for a pattern anchored at beginning of buffer. */
4293 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4295 if (startpos > 0)
4296 return -1;
4297 else
4298 range = 0;
4301 #ifdef emacs
4302 /* In a forward search for something that starts with \=.
4303 don't keep searching past point. */
4304 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4306 range = PT_BYTE - BEGV_BYTE - startpos;
4307 if (range < 0)
4308 return -1;
4310 #endif /* emacs */
4312 /* Update the fastmap now if not correct already. */
4313 if (fastmap && !bufp->fastmap_accurate)
4314 re_compile_fastmap (bufp);
4316 /* See whether the pattern is anchored. */
4317 anchored_start = (bufp->buffer[0] == begline);
4319 #ifdef emacs
4320 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4322 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4324 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4326 #endif
4328 /* Loop through the string, looking for a place to start matching. */
4329 for (;;)
4331 /* If the pattern is anchored,
4332 skip quickly past places we cannot match.
4333 We don't bother to treat startpos == 0 specially
4334 because that case doesn't repeat. */
4335 if (anchored_start && startpos > 0)
4337 if (! ((startpos <= size1 ? string1[startpos - 1]
4338 : string2[startpos - size1 - 1])
4339 == '\n'))
4340 goto advance;
4343 /* If a fastmap is supplied, skip quickly over characters that
4344 cannot be the start of a match. If the pattern can match the
4345 null string, however, we don't need to skip characters; we want
4346 the first null string. */
4347 if (fastmap && startpos < total_size && !bufp->can_be_null)
4349 register re_char *d;
4350 register re_wchar_t buf_ch;
4352 d = POS_ADDR_VSTRING (startpos);
4354 if (range > 0) /* Searching forwards. */
4356 register int lim = 0;
4357 ssize_t irange = range;
4359 if (startpos < size1 && startpos + range >= size1)
4360 lim = range - (size1 - startpos);
4362 /* Written out as an if-else to avoid testing `translate'
4363 inside the loop. */
4364 if (RE_TRANSLATE_P (translate))
4366 if (multibyte)
4367 while (range > lim)
4369 int buf_charlen;
4371 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4372 buf_ch = RE_TRANSLATE (translate, buf_ch);
4373 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4374 break;
4376 range -= buf_charlen;
4377 d += buf_charlen;
4379 else
4380 while (range > lim)
4382 register re_wchar_t ch, translated;
4384 buf_ch = *d;
4385 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4386 translated = RE_TRANSLATE (translate, ch);
4387 if (translated != ch
4388 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4389 buf_ch = ch;
4390 if (fastmap[buf_ch])
4391 break;
4392 d++;
4393 range--;
4396 else
4398 if (multibyte)
4399 while (range > lim)
4401 int buf_charlen;
4403 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4404 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4405 break;
4406 range -= buf_charlen;
4407 d += buf_charlen;
4409 else
4410 while (range > lim && !fastmap[*d])
4412 d++;
4413 range--;
4416 startpos += irange - range;
4418 else /* Searching backwards. */
4420 if (multibyte)
4422 buf_ch = STRING_CHAR (d);
4423 buf_ch = TRANSLATE (buf_ch);
4424 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4425 goto advance;
4427 else
4429 register re_wchar_t ch, translated;
4431 buf_ch = *d;
4432 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4433 translated = TRANSLATE (ch);
4434 if (translated != ch
4435 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4436 buf_ch = ch;
4437 if (! fastmap[TRANSLATE (buf_ch)])
4438 goto advance;
4443 /* If can't match the null string, and that's all we have left, fail. */
4444 if (range >= 0 && startpos == total_size && fastmap
4445 && !bufp->can_be_null)
4446 return -1;
4448 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4449 startpos, regs, stop);
4451 if (val >= 0)
4452 return startpos;
4454 if (val == -2)
4455 return -2;
4457 advance:
4458 if (!range)
4459 break;
4460 else if (range > 0)
4462 /* Update STARTPOS to the next character boundary. */
4463 if (multibyte)
4465 re_char *p = POS_ADDR_VSTRING (startpos);
4466 int len = BYTES_BY_CHAR_HEAD (*p);
4468 range -= len;
4469 if (range < 0)
4470 break;
4471 startpos += len;
4473 else
4475 range--;
4476 startpos++;
4479 else
4481 range++;
4482 startpos--;
4484 /* Update STARTPOS to the previous character boundary. */
4485 if (multibyte)
4487 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4488 re_char *p0 = p;
4489 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4491 /* Find the head of multibyte form. */
4492 PREV_CHAR_BOUNDARY (p, phead);
4493 range += p0 - 1 - p;
4494 if (range > 0)
4495 break;
4497 startpos -= p0 - 1 - p;
4501 return -1;
4502 } /* re_search_2 */
4503 WEAK_ALIAS (__re_search_2, re_search_2)
4505 /* Declarations and macros for re_match_2. */
4507 static int bcmp_translate (re_char *s1, re_char *s2,
4508 register ssize_t len,
4509 RE_TRANSLATE_TYPE translate,
4510 const int multibyte);
4512 /* This converts PTR, a pointer into one of the search strings `string1'
4513 and `string2' into an offset from the beginning of that string. */
4514 #define POINTER_TO_OFFSET(ptr) \
4515 (FIRST_STRING_P (ptr) \
4516 ? (ptr) - string1 \
4517 : (ptr) - string2 + (ptrdiff_t) size1)
4519 /* Call before fetching a character with *d. This switches over to
4520 string2 if necessary.
4521 Check re_match_2_internal for a discussion of why end_match_2 might
4522 not be within string2 (but be equal to end_match_1 instead). */
4523 #define PREFETCH() \
4524 while (d == dend) \
4526 /* End of string2 => fail. */ \
4527 if (dend == end_match_2) \
4528 goto fail; \
4529 /* End of string1 => advance to string2. */ \
4530 d = string2; \
4531 dend = end_match_2; \
4534 /* Call before fetching a char with *d if you already checked other limits.
4535 This is meant for use in lookahead operations like wordend, etc..
4536 where we might need to look at parts of the string that might be
4537 outside of the LIMITs (i.e past `stop'). */
4538 #define PREFETCH_NOLIMIT() \
4539 if (d == end1) \
4541 d = string2; \
4542 dend = end_match_2; \
4545 /* Test if at very beginning or at very end of the virtual concatenation
4546 of `string1' and `string2'. If only one string, it's `string2'. */
4547 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4548 #define AT_STRINGS_END(d) ((d) == end2)
4550 /* Disabled due to a compiler bug -- see comment at case wordbound */
4552 /* The comment at case wordbound is following one, but we don't use
4553 AT_WORD_BOUNDARY anymore to support multibyte form.
4555 The DEC Alpha C compiler 3.x generates incorrect code for the
4556 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4557 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4558 macro and introducing temporary variables works around the bug. */
4560 #if 0
4561 /* Test if D points to a character which is word-constituent. We have
4562 two special cases to check for: if past the end of string1, look at
4563 the first character in string2; and if before the beginning of
4564 string2, look at the last character in string1. */
4565 #define WORDCHAR_P(d) \
4566 (SYNTAX ((d) == end1 ? *string2 \
4567 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4568 == Sword)
4570 /* Test if the character before D and the one at D differ with respect
4571 to being word-constituent. */
4572 #define AT_WORD_BOUNDARY(d) \
4573 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4574 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4575 #endif
4577 /* Free everything we malloc. */
4578 #ifdef MATCH_MAY_ALLOCATE
4579 # define FREE_VAR(var) \
4580 do { \
4581 if (var) \
4583 REGEX_FREE (var); \
4584 var = NULL; \
4586 } while (0)
4587 # define FREE_VARIABLES() \
4588 do { \
4589 REGEX_FREE_STACK (fail_stack.stack); \
4590 FREE_VAR (regstart); \
4591 FREE_VAR (regend); \
4592 FREE_VAR (best_regstart); \
4593 FREE_VAR (best_regend); \
4594 } while (0)
4595 #else
4596 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4597 #endif /* not MATCH_MAY_ALLOCATE */
4600 /* Optimization routines. */
4602 /* If the operation is a match against one or more chars,
4603 return a pointer to the next operation, else return NULL. */
4604 static re_char *
4605 skip_one_char (const_re_char *p)
4607 switch (*p++)
4609 case anychar:
4610 break;
4612 case exactn:
4613 p += *p + 1;
4614 break;
4616 case charset_not:
4617 case charset:
4618 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4620 int mcnt;
4621 p = CHARSET_RANGE_TABLE (p - 1);
4622 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4623 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4625 else
4626 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4627 break;
4629 case syntaxspec:
4630 case notsyntaxspec:
4631 #ifdef emacs
4632 case categoryspec:
4633 case notcategoryspec:
4634 #endif /* emacs */
4635 p++;
4636 break;
4638 default:
4639 p = NULL;
4641 return p;
4645 /* Jump over non-matching operations. */
4646 static re_char *
4647 skip_noops (const_re_char *p, const_re_char *pend)
4649 int mcnt;
4650 while (p < pend)
4652 switch (*p)
4654 case start_memory:
4655 case stop_memory:
4656 p += 2; break;
4657 case no_op:
4658 p += 1; break;
4659 case jump:
4660 p += 1;
4661 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4662 p += mcnt;
4663 break;
4664 default:
4665 return p;
4668 assert (p == pend);
4669 return p;
4672 /* Non-zero if "p1 matches something" implies "p2 fails". */
4673 static int
4674 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4675 const_re_char *p2)
4677 re_opcode_t op2;
4678 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4679 unsigned char *pend = bufp->buffer + bufp->used;
4681 assert (p1 >= bufp->buffer && p1 < pend
4682 && p2 >= bufp->buffer && p2 <= pend);
4684 /* Skip over open/close-group commands.
4685 If what follows this loop is a ...+ construct,
4686 look at what begins its body, since we will have to
4687 match at least one of that. */
4688 p2 = skip_noops (p2, pend);
4689 /* The same skip can be done for p1, except that this function
4690 is only used in the case where p1 is a simple match operator. */
4691 /* p1 = skip_noops (p1, pend); */
4693 assert (p1 >= bufp->buffer && p1 < pend
4694 && p2 >= bufp->buffer && p2 <= pend);
4696 op2 = p2 == pend ? succeed : *p2;
4698 switch (op2)
4700 case succeed:
4701 case endbuf:
4702 /* If we're at the end of the pattern, we can change. */
4703 if (skip_one_char (p1))
4705 DEBUG_PRINT (" End of pattern: fast loop.\n");
4706 return 1;
4708 break;
4710 case endline:
4711 case exactn:
4713 register re_wchar_t c
4714 = (re_opcode_t) *p2 == endline ? '\n'
4715 : RE_STRING_CHAR (p2 + 2, multibyte);
4717 if ((re_opcode_t) *p1 == exactn)
4719 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4721 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4722 return 1;
4726 else if ((re_opcode_t) *p1 == charset
4727 || (re_opcode_t) *p1 == charset_not)
4729 int not = (re_opcode_t) *p1 == charset_not;
4731 /* Test if C is listed in charset (or charset_not)
4732 at `p1'. */
4733 if (! multibyte || IS_REAL_ASCII (c))
4735 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4736 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4737 not = !not;
4739 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4740 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4742 /* `not' is equal to 1 if c would match, which means
4743 that we can't change to pop_failure_jump. */
4744 if (!not)
4746 DEBUG_PRINT (" No match => fast loop.\n");
4747 return 1;
4750 else if ((re_opcode_t) *p1 == anychar
4751 && c == '\n')
4753 DEBUG_PRINT (" . != \\n => fast loop.\n");
4754 return 1;
4757 break;
4759 case charset:
4761 if ((re_opcode_t) *p1 == exactn)
4762 /* Reuse the code above. */
4763 return mutually_exclusive_p (bufp, p2, p1);
4765 /* It is hard to list up all the character in charset
4766 P2 if it includes multibyte character. Give up in
4767 such case. */
4768 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4770 /* Now, we are sure that P2 has no range table.
4771 So, for the size of bitmap in P2, `p2[1]' is
4772 enough. But P1 may have range table, so the
4773 size of bitmap table of P1 is extracted by
4774 using macro `CHARSET_BITMAP_SIZE'.
4776 In a multibyte case, we know that all the character
4777 listed in P2 is ASCII. In a unibyte case, P1 has only a
4778 bitmap table. So, in both cases, it is enough to test
4779 only the bitmap table of P1. */
4781 if ((re_opcode_t) *p1 == charset)
4783 int idx;
4784 /* We win if the charset inside the loop
4785 has no overlap with the one after the loop. */
4786 for (idx = 0;
4787 (idx < (int) p2[1]
4788 && idx < CHARSET_BITMAP_SIZE (p1));
4789 idx++)
4790 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4791 break;
4793 if (idx == p2[1]
4794 || idx == CHARSET_BITMAP_SIZE (p1))
4796 DEBUG_PRINT (" No match => fast loop.\n");
4797 return 1;
4800 else if ((re_opcode_t) *p1 == charset_not)
4802 int idx;
4803 /* We win if the charset_not inside the loop lists
4804 every character listed in the charset after. */
4805 for (idx = 0; idx < (int) p2[1]; idx++)
4806 if (! (p2[2 + idx] == 0
4807 || (idx < CHARSET_BITMAP_SIZE (p1)
4808 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4809 break;
4811 if (idx == p2[1])
4813 DEBUG_PRINT (" No match => fast loop.\n");
4814 return 1;
4819 break;
4821 case charset_not:
4822 switch (*p1)
4824 case exactn:
4825 case charset:
4826 /* Reuse the code above. */
4827 return mutually_exclusive_p (bufp, p2, p1);
4828 case charset_not:
4829 /* When we have two charset_not, it's very unlikely that
4830 they don't overlap. The union of the two sets of excluded
4831 chars should cover all possible chars, which, as a matter of
4832 fact, is virtually impossible in multibyte buffers. */
4833 break;
4835 break;
4837 case wordend:
4838 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4839 case symend:
4840 return ((re_opcode_t) *p1 == syntaxspec
4841 && (p1[1] == Ssymbol || p1[1] == Sword));
4842 case notsyntaxspec:
4843 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4845 case wordbeg:
4846 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4847 case symbeg:
4848 return ((re_opcode_t) *p1 == notsyntaxspec
4849 && (p1[1] == Ssymbol || p1[1] == Sword));
4850 case syntaxspec:
4851 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4853 case wordbound:
4854 return (((re_opcode_t) *p1 == notsyntaxspec
4855 || (re_opcode_t) *p1 == syntaxspec)
4856 && p1[1] == Sword);
4858 #ifdef emacs
4859 case categoryspec:
4860 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4861 case notcategoryspec:
4862 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4863 #endif /* emacs */
4865 default:
4869 /* Safe default. */
4870 return 0;
4874 /* Matching routines. */
4876 #ifndef emacs /* Emacs never uses this. */
4877 /* re_match is like re_match_2 except it takes only a single string. */
4879 regoff_t
4880 re_match (struct re_pattern_buffer *bufp, const char *string,
4881 size_t size, ssize_t pos, struct re_registers *regs)
4883 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4884 size, pos, regs, size);
4885 return result;
4887 WEAK_ALIAS (__re_match, re_match)
4888 #endif /* not emacs */
4890 /* re_match_2 matches the compiled pattern in BUFP against the
4891 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4892 and SIZE2, respectively). We start matching at POS, and stop
4893 matching at STOP.
4895 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4896 store offsets for the substring each group matched in REGS. See the
4897 documentation for exactly how many groups we fill.
4899 We return -1 if no match, -2 if an internal error (such as the
4900 failure stack overflowing). Otherwise, we return the length of the
4901 matched substring. */
4903 regoff_t
4904 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4905 size_t size1, const char *string2, size_t size2, ssize_t pos,
4906 struct re_registers *regs, ssize_t stop)
4908 regoff_t result;
4910 #ifdef emacs
4911 ssize_t charpos;
4912 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4913 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4914 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4915 #endif
4917 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4918 (re_char*) string2, size2,
4919 pos, regs, stop);
4920 return result;
4922 WEAK_ALIAS (__re_match_2, re_match_2)
4925 /* This is a separate function so that we can force an alloca cleanup
4926 afterwards. */
4927 static regoff_t
4928 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4929 size_t size1, const_re_char *string2, size_t size2,
4930 ssize_t pos, struct re_registers *regs, ssize_t stop)
4932 /* General temporaries. */
4933 int mcnt;
4934 size_t reg;
4936 /* Just past the end of the corresponding string. */
4937 re_char *end1, *end2;
4939 /* Pointers into string1 and string2, just past the last characters in
4940 each to consider matching. */
4941 re_char *end_match_1, *end_match_2;
4943 /* Where we are in the data, and the end of the current string. */
4944 re_char *d, *dend;
4946 /* Used sometimes to remember where we were before starting matching
4947 an operator so that we can go back in case of failure. This "atomic"
4948 behavior of matching opcodes is indispensable to the correctness
4949 of the on_failure_keep_string_jump optimization. */
4950 re_char *dfail;
4952 /* Where we are in the pattern, and the end of the pattern. */
4953 re_char *p = bufp->buffer;
4954 re_char *pend = p + bufp->used;
4956 /* We use this to map every character in the string. */
4957 RE_TRANSLATE_TYPE translate = bufp->translate;
4959 /* Nonzero if BUFP is setup from a multibyte regex. */
4960 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4962 /* Nonzero if STRING1/STRING2 are multibyte. */
4963 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4965 /* Failure point stack. Each place that can handle a failure further
4966 down the line pushes a failure point on this stack. It consists of
4967 regstart, and regend for all registers corresponding to
4968 the subexpressions we're currently inside, plus the number of such
4969 registers, and, finally, two char *'s. The first char * is where
4970 to resume scanning the pattern; the second one is where to resume
4971 scanning the strings. */
4972 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4973 fail_stack_type fail_stack;
4974 #endif
4975 #ifdef DEBUG_COMPILES_ARGUMENTS
4976 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4977 #endif
4979 #if defined REL_ALLOC && defined REGEX_MALLOC
4980 /* This holds the pointer to the failure stack, when
4981 it is allocated relocatably. */
4982 fail_stack_elt_t *failure_stack_ptr;
4983 #endif
4985 /* We fill all the registers internally, independent of what we
4986 return, for use in backreferences. The number here includes
4987 an element for register zero. */
4988 size_t num_regs = bufp->re_nsub + 1;
4990 /* Information on the contents of registers. These are pointers into
4991 the input strings; they record just what was matched (on this
4992 attempt) by a subexpression part of the pattern, that is, the
4993 regnum-th regstart pointer points to where in the pattern we began
4994 matching and the regnum-th regend points to right after where we
4995 stopped matching the regnum-th subexpression. (The zeroth register
4996 keeps track of what the whole pattern matches.) */
4997 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4998 re_char **regstart, **regend;
4999 #endif
5001 /* The following record the register info as found in the above
5002 variables when we find a match better than any we've seen before.
5003 This happens as we backtrack through the failure points, which in
5004 turn happens only if we have not yet matched the entire string. */
5005 unsigned best_regs_set = false;
5006 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5007 re_char **best_regstart, **best_regend;
5008 #endif
5010 /* Logically, this is `best_regend[0]'. But we don't want to have to
5011 allocate space for that if we're not allocating space for anything
5012 else (see below). Also, we never need info about register 0 for
5013 any of the other register vectors, and it seems rather a kludge to
5014 treat `best_regend' differently than the rest. So we keep track of
5015 the end of the best match so far in a separate variable. We
5016 initialize this to NULL so that when we backtrack the first time
5017 and need to test it, it's not garbage. */
5018 re_char *match_end = NULL;
5020 #ifdef DEBUG_COMPILES_ARGUMENTS
5021 /* Counts the total number of registers pushed. */
5022 unsigned num_regs_pushed = 0;
5023 #endif
5025 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5027 INIT_FAIL_STACK ();
5029 #ifdef MATCH_MAY_ALLOCATE
5030 /* Do not bother to initialize all the register variables if there are
5031 no groups in the pattern, as it takes a fair amount of time. If
5032 there are groups, we include space for register 0 (the whole
5033 pattern), even though we never use it, since it simplifies the
5034 array indexing. We should fix this. */
5035 if (bufp->re_nsub)
5037 regstart = REGEX_TALLOC (num_regs, re_char *);
5038 regend = REGEX_TALLOC (num_regs, re_char *);
5039 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5040 best_regend = REGEX_TALLOC (num_regs, re_char *);
5042 if (!(regstart && regend && best_regstart && best_regend))
5044 FREE_VARIABLES ();
5045 return -2;
5048 else
5050 /* We must initialize all our variables to NULL, so that
5051 `FREE_VARIABLES' doesn't try to free them. */
5052 regstart = regend = best_regstart = best_regend = NULL;
5054 #endif /* MATCH_MAY_ALLOCATE */
5056 /* The starting position is bogus. */
5057 if (pos < 0 || pos > size1 + size2)
5059 FREE_VARIABLES ();
5060 return -1;
5063 /* Initialize subexpression text positions to -1 to mark ones that no
5064 start_memory/stop_memory has been seen for. Also initialize the
5065 register information struct. */
5066 for (reg = 1; reg < num_regs; reg++)
5067 regstart[reg] = regend[reg] = NULL;
5069 /* We move `string1' into `string2' if the latter's empty -- but not if
5070 `string1' is null. */
5071 if (size2 == 0 && string1 != NULL)
5073 string2 = string1;
5074 size2 = size1;
5075 string1 = 0;
5076 size1 = 0;
5078 end1 = string1 + size1;
5079 end2 = string2 + size2;
5081 /* `p' scans through the pattern as `d' scans through the data.
5082 `dend' is the end of the input string that `d' points within. `d'
5083 is advanced into the following input string whenever necessary, but
5084 this happens before fetching; therefore, at the beginning of the
5085 loop, `d' can be pointing at the end of a string, but it cannot
5086 equal `string2'. */
5087 if (pos >= size1)
5089 /* Only match within string2. */
5090 d = string2 + pos - size1;
5091 dend = end_match_2 = string2 + stop - size1;
5092 end_match_1 = end1; /* Just to give it a value. */
5094 else
5096 if (stop < size1)
5098 /* Only match within string1. */
5099 end_match_1 = string1 + stop;
5100 /* BEWARE!
5101 When we reach end_match_1, PREFETCH normally switches to string2.
5102 But in the present case, this means that just doing a PREFETCH
5103 makes us jump from `stop' to `gap' within the string.
5104 What we really want here is for the search to stop as
5105 soon as we hit end_match_1. That's why we set end_match_2
5106 to end_match_1 (since PREFETCH fails as soon as we hit
5107 end_match_2). */
5108 end_match_2 = end_match_1;
5110 else
5111 { /* It's important to use this code when stop == size so that
5112 moving `d' from end1 to string2 will not prevent the d == dend
5113 check from catching the end of string. */
5114 end_match_1 = end1;
5115 end_match_2 = string2 + stop - size1;
5117 d = string1 + pos;
5118 dend = end_match_1;
5121 DEBUG_PRINT ("The compiled pattern is: ");
5122 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5123 DEBUG_PRINT ("The string to match is: `");
5124 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5125 DEBUG_PRINT ("'\n");
5127 /* This loops over pattern commands. It exits by returning from the
5128 function if the match is complete, or it drops through if the match
5129 fails at this starting point in the input data. */
5130 for (;;)
5132 DEBUG_PRINT ("\n%p: ", p);
5134 if (p == pend)
5136 ptrdiff_t dcnt;
5138 /* End of pattern means we might have succeeded. */
5139 DEBUG_PRINT ("end of pattern ... ");
5141 /* If we haven't matched the entire string, and we want the
5142 longest match, try backtracking. */
5143 if (d != end_match_2)
5145 /* 1 if this match ends in the same string (string1 or string2)
5146 as the best previous match. */
5147 boolean same_str_p = (FIRST_STRING_P (match_end)
5148 == FIRST_STRING_P (d));
5149 /* 1 if this match is the best seen so far. */
5150 boolean best_match_p;
5152 /* AIX compiler got confused when this was combined
5153 with the previous declaration. */
5154 if (same_str_p)
5155 best_match_p = d > match_end;
5156 else
5157 best_match_p = !FIRST_STRING_P (d);
5159 DEBUG_PRINT ("backtracking.\n");
5161 if (!FAIL_STACK_EMPTY ())
5162 { /* More failure points to try. */
5164 /* If exceeds best match so far, save it. */
5165 if (!best_regs_set || best_match_p)
5167 best_regs_set = true;
5168 match_end = d;
5170 DEBUG_PRINT ("\nSAVING match as best so far.\n");
5172 for (reg = 1; reg < num_regs; reg++)
5174 best_regstart[reg] = regstart[reg];
5175 best_regend[reg] = regend[reg];
5178 goto fail;
5181 /* If no failure points, don't restore garbage. And if
5182 last match is real best match, don't restore second
5183 best one. */
5184 else if (best_regs_set && !best_match_p)
5186 restore_best_regs:
5187 /* Restore best match. It may happen that `dend ==
5188 end_match_1' while the restored d is in string2.
5189 For example, the pattern `x.*y.*z' against the
5190 strings `x-' and `y-z-', if the two strings are
5191 not consecutive in memory. */
5192 DEBUG_PRINT ("Restoring best registers.\n");
5194 d = match_end;
5195 dend = ((d >= string1 && d <= end1)
5196 ? end_match_1 : end_match_2);
5198 for (reg = 1; reg < num_regs; reg++)
5200 regstart[reg] = best_regstart[reg];
5201 regend[reg] = best_regend[reg];
5204 } /* d != end_match_2 */
5206 succeed_label:
5207 DEBUG_PRINT ("Accepting match.\n");
5209 /* If caller wants register contents data back, do it. */
5210 if (regs && !bufp->no_sub)
5212 /* Have the register data arrays been allocated? */
5213 if (bufp->regs_allocated == REGS_UNALLOCATED)
5214 { /* No. So allocate them with malloc. We need one
5215 extra element beyond `num_regs' for the `-1' marker
5216 GNU code uses. */
5217 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5218 regs->start = TALLOC (regs->num_regs, regoff_t);
5219 regs->end = TALLOC (regs->num_regs, regoff_t);
5220 if (regs->start == NULL || regs->end == NULL)
5222 FREE_VARIABLES ();
5223 return -2;
5225 bufp->regs_allocated = REGS_REALLOCATE;
5227 else if (bufp->regs_allocated == REGS_REALLOCATE)
5228 { /* Yes. If we need more elements than were already
5229 allocated, reallocate them. If we need fewer, just
5230 leave it alone. */
5231 if (regs->num_regs < num_regs + 1)
5233 regs->num_regs = num_regs + 1;
5234 RETALLOC (regs->start, regs->num_regs, regoff_t);
5235 RETALLOC (regs->end, regs->num_regs, regoff_t);
5236 if (regs->start == NULL || regs->end == NULL)
5238 FREE_VARIABLES ();
5239 return -2;
5243 else
5245 /* These braces fend off a "empty body in an else-statement"
5246 warning under GCC when assert expands to nothing. */
5247 assert (bufp->regs_allocated == REGS_FIXED);
5250 /* Convert the pointer data in `regstart' and `regend' to
5251 indices. Register zero has to be set differently,
5252 since we haven't kept track of any info for it. */
5253 if (regs->num_regs > 0)
5255 regs->start[0] = pos;
5256 regs->end[0] = POINTER_TO_OFFSET (d);
5259 /* Go through the first `min (num_regs, regs->num_regs)'
5260 registers, since that is all we initialized. */
5261 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
5263 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5264 regs->start[reg] = regs->end[reg] = -1;
5265 else
5267 regs->start[reg] = POINTER_TO_OFFSET (regstart[reg]);
5268 regs->end[reg] = POINTER_TO_OFFSET (regend[reg]);
5272 /* If the regs structure we return has more elements than
5273 were in the pattern, set the extra elements to -1. If
5274 we (re)allocated the registers, this is the case,
5275 because we always allocate enough to have at least one
5276 -1 at the end. */
5277 for (reg = num_regs; reg < regs->num_regs; reg++)
5278 regs->start[reg] = regs->end[reg] = -1;
5279 } /* regs && !bufp->no_sub */
5281 DEBUG_PRINT ("%u failure points pushed, %u popped (%u remain).\n",
5282 nfailure_points_pushed, nfailure_points_popped,
5283 nfailure_points_pushed - nfailure_points_popped);
5284 DEBUG_PRINT ("%u registers pushed.\n", num_regs_pushed);
5286 dcnt = POINTER_TO_OFFSET (d) - pos;
5288 DEBUG_PRINT ("Returning %td from re_match_2.\n", dcnt);
5290 FREE_VARIABLES ();
5291 return dcnt;
5294 /* Otherwise match next pattern command. */
5295 switch (*p++)
5297 /* Ignore these. Used to ignore the n of succeed_n's which
5298 currently have n == 0. */
5299 case no_op:
5300 DEBUG_PRINT ("EXECUTING no_op.\n");
5301 break;
5303 case succeed:
5304 DEBUG_PRINT ("EXECUTING succeed.\n");
5305 goto succeed_label;
5307 /* Match the next n pattern characters exactly. The following
5308 byte in the pattern defines n, and the n bytes after that
5309 are the characters to match. */
5310 case exactn:
5311 mcnt = *p++;
5312 DEBUG_PRINT ("EXECUTING exactn %d.\n", mcnt);
5314 /* Remember the start point to rollback upon failure. */
5315 dfail = d;
5317 #ifndef emacs
5318 /* This is written out as an if-else so we don't waste time
5319 testing `translate' inside the loop. */
5320 if (RE_TRANSLATE_P (translate))
5323 PREFETCH ();
5324 if (RE_TRANSLATE (translate, *d) != *p++)
5326 d = dfail;
5327 goto fail;
5329 d++;
5331 while (--mcnt);
5332 else
5335 PREFETCH ();
5336 if (*d++ != *p++)
5338 d = dfail;
5339 goto fail;
5342 while (--mcnt);
5343 #else /* emacs */
5344 /* The cost of testing `translate' is comparatively small. */
5345 if (target_multibyte)
5348 int pat_charlen, buf_charlen;
5349 int pat_ch, buf_ch;
5351 PREFETCH ();
5352 if (multibyte)
5353 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5354 else
5356 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5357 pat_charlen = 1;
5359 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5361 if (TRANSLATE (buf_ch) != pat_ch)
5363 d = dfail;
5364 goto fail;
5367 p += pat_charlen;
5368 d += buf_charlen;
5369 mcnt -= pat_charlen;
5371 while (mcnt > 0);
5372 else
5375 int pat_charlen;
5376 int pat_ch, buf_ch;
5378 PREFETCH ();
5379 if (multibyte)
5381 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5382 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5384 else
5386 pat_ch = *p;
5387 pat_charlen = 1;
5389 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5390 if (! CHAR_BYTE8_P (buf_ch))
5392 buf_ch = TRANSLATE (buf_ch);
5393 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5394 if (buf_ch < 0)
5395 buf_ch = *d;
5397 else
5398 buf_ch = *d;
5399 if (buf_ch != pat_ch)
5401 d = dfail;
5402 goto fail;
5404 p += pat_charlen;
5405 d++;
5407 while (--mcnt);
5408 #endif
5409 break;
5412 /* Match any character except possibly a newline or a null. */
5413 case anychar:
5415 int buf_charlen;
5416 re_wchar_t buf_ch;
5418 DEBUG_PRINT ("EXECUTING anychar.\n");
5420 PREFETCH ();
5421 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5422 target_multibyte);
5423 buf_ch = TRANSLATE (buf_ch);
5425 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5426 && buf_ch == '\n')
5427 || ((bufp->syntax & RE_DOT_NOT_NULL)
5428 && buf_ch == '\000'))
5429 goto fail;
5431 DEBUG_PRINT (" Matched `%d'.\n", *d);
5432 d += buf_charlen;
5434 break;
5437 case charset:
5438 case charset_not:
5440 register unsigned int c;
5441 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5442 int len;
5444 /* Start of actual range_table, or end of bitmap if there is no
5445 range table. */
5446 re_char *range_table IF_LINT (= NULL);
5448 /* Nonzero if there is a range table. */
5449 int range_table_exists;
5451 /* Number of ranges of range table. This is not included
5452 in the initial byte-length of the command. */
5453 int count = 0;
5455 /* Whether matching against a unibyte character. */
5456 boolean unibyte_char = false;
5458 DEBUG_PRINT ("EXECUTING charset%s.\n", not ? "_not" : "");
5460 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5462 if (range_table_exists)
5464 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5465 EXTRACT_NUMBER_AND_INCR (count, range_table);
5468 PREFETCH ();
5469 c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5470 if (target_multibyte)
5472 int c1;
5474 c = TRANSLATE (c);
5475 c1 = RE_CHAR_TO_UNIBYTE (c);
5476 if (c1 >= 0)
5478 unibyte_char = true;
5479 c = c1;
5482 else
5484 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5486 if (! CHAR_BYTE8_P (c1))
5488 c1 = TRANSLATE (c1);
5489 c1 = RE_CHAR_TO_UNIBYTE (c1);
5490 if (c1 >= 0)
5492 unibyte_char = true;
5493 c = c1;
5496 else
5497 unibyte_char = true;
5500 if (unibyte_char && c < (1 << BYTEWIDTH))
5501 { /* Lookup bitmap. */
5502 /* Cast to `unsigned' instead of `unsigned char' in
5503 case the bit list is a full 32 bytes long. */
5504 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5505 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5506 not = !not;
5508 #ifdef emacs
5509 else if (range_table_exists)
5511 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5513 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5514 | (class_bits & BIT_MULTIBYTE)
5515 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5516 | (class_bits & BIT_SPACE && ISSPACE (c))
5517 | (class_bits & BIT_UPPER && ISUPPER (c))
5518 | (class_bits & BIT_WORD && ISWORD (c)))
5519 not = !not;
5520 else
5521 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5523 #endif /* emacs */
5525 if (range_table_exists)
5526 p = CHARSET_RANGE_TABLE_END (range_table, count);
5527 else
5528 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5530 if (!not) goto fail;
5532 d += len;
5534 break;
5537 /* The beginning of a group is represented by start_memory.
5538 The argument is the register number. The text
5539 matched within the group is recorded (in the internal
5540 registers data structure) under the register number. */
5541 case start_memory:
5542 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5544 /* In case we need to undo this operation (via backtracking). */
5545 PUSH_FAILURE_REG (*p);
5547 regstart[*p] = d;
5548 regend[*p] = NULL; /* probably unnecessary. -sm */
5549 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5551 /* Move past the register number and inner group count. */
5552 p += 1;
5553 break;
5556 /* The stop_memory opcode represents the end of a group. Its
5557 argument is the same as start_memory's: the register number. */
5558 case stop_memory:
5559 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5561 assert (!REG_UNSET (regstart[*p]));
5562 /* Strictly speaking, there should be code such as:
5564 assert (REG_UNSET (regend[*p]));
5565 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5567 But the only info to be pushed is regend[*p] and it is known to
5568 be UNSET, so there really isn't anything to push.
5569 Not pushing anything, on the other hand deprives us from the
5570 guarantee that regend[*p] is UNSET since undoing this operation
5571 will not reset its value properly. This is not important since
5572 the value will only be read on the next start_memory or at
5573 the very end and both events can only happen if this stop_memory
5574 is *not* undone. */
5576 regend[*p] = d;
5577 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5579 /* Move past the register number and the inner group count. */
5580 p += 1;
5581 break;
5584 /* \<digit> has been turned into a `duplicate' command which is
5585 followed by the numeric value of <digit> as the register number. */
5586 case duplicate:
5588 register re_char *d2, *dend2;
5589 int regno = *p++; /* Get which register to match against. */
5590 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5592 /* Can't back reference a group which we've never matched. */
5593 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5594 goto fail;
5596 /* Where in input to try to start matching. */
5597 d2 = regstart[regno];
5599 /* Remember the start point to rollback upon failure. */
5600 dfail = d;
5602 /* Where to stop matching; if both the place to start and
5603 the place to stop matching are in the same string, then
5604 set to the place to stop, otherwise, for now have to use
5605 the end of the first string. */
5607 dend2 = ((FIRST_STRING_P (regstart[regno])
5608 == FIRST_STRING_P (regend[regno]))
5609 ? regend[regno] : end_match_1);
5610 for (;;)
5612 ptrdiff_t dcnt;
5614 /* If necessary, advance to next segment in register
5615 contents. */
5616 while (d2 == dend2)
5618 if (dend2 == end_match_2) break;
5619 if (dend2 == regend[regno]) break;
5621 /* End of string1 => advance to string2. */
5622 d2 = string2;
5623 dend2 = regend[regno];
5625 /* At end of register contents => success */
5626 if (d2 == dend2) break;
5628 /* If necessary, advance to next segment in data. */
5629 PREFETCH ();
5631 /* How many characters left in this segment to match. */
5632 dcnt = dend - d;
5634 /* Want how many consecutive characters we can match in
5635 one shot, so, if necessary, adjust the count. */
5636 if (dcnt > dend2 - d2)
5637 dcnt = dend2 - d2;
5639 /* Compare that many; failure if mismatch, else move
5640 past them. */
5641 if (RE_TRANSLATE_P (translate)
5642 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5643 : memcmp (d, d2, dcnt))
5645 d = dfail;
5646 goto fail;
5648 d += dcnt, d2 += dcnt;
5651 break;
5654 /* begline matches the empty string at the beginning of the string
5655 (unless `not_bol' is set in `bufp'), and after newlines. */
5656 case begline:
5657 DEBUG_PRINT ("EXECUTING begline.\n");
5659 if (AT_STRINGS_BEG (d))
5661 if (!bufp->not_bol) break;
5663 else
5665 unsigned c;
5666 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5667 if (c == '\n')
5668 break;
5670 /* In all other cases, we fail. */
5671 goto fail;
5674 /* endline is the dual of begline. */
5675 case endline:
5676 DEBUG_PRINT ("EXECUTING endline.\n");
5678 if (AT_STRINGS_END (d))
5680 if (!bufp->not_eol) break;
5682 else
5684 PREFETCH_NOLIMIT ();
5685 if (*d == '\n')
5686 break;
5688 goto fail;
5691 /* Match at the very beginning of the data. */
5692 case begbuf:
5693 DEBUG_PRINT ("EXECUTING begbuf.\n");
5694 if (AT_STRINGS_BEG (d))
5695 break;
5696 goto fail;
5699 /* Match at the very end of the data. */
5700 case endbuf:
5701 DEBUG_PRINT ("EXECUTING endbuf.\n");
5702 if (AT_STRINGS_END (d))
5703 break;
5704 goto fail;
5707 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5708 pushes NULL as the value for the string on the stack. Then
5709 `POP_FAILURE_POINT' will keep the current value for the
5710 string, instead of restoring it. To see why, consider
5711 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5712 then the . fails against the \n. But the next thing we want
5713 to do is match the \n against the \n; if we restored the
5714 string value, we would be back at the foo.
5716 Because this is used only in specific cases, we don't need to
5717 check all the things that `on_failure_jump' does, to make
5718 sure the right things get saved on the stack. Hence we don't
5719 share its code. The only reason to push anything on the
5720 stack at all is that otherwise we would have to change
5721 `anychar's code to do something besides goto fail in this
5722 case; that seems worse than this. */
5723 case on_failure_keep_string_jump:
5724 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5725 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5726 mcnt, p + mcnt);
5728 PUSH_FAILURE_POINT (p - 3, NULL);
5729 break;
5731 /* A nasty loop is introduced by the non-greedy *? and +?.
5732 With such loops, the stack only ever contains one failure point
5733 at a time, so that a plain on_failure_jump_loop kind of
5734 cycle detection cannot work. Worse yet, such a detection
5735 can not only fail to detect a cycle, but it can also wrongly
5736 detect a cycle (between different instantiations of the same
5737 loop).
5738 So the method used for those nasty loops is a little different:
5739 We use a special cycle-detection-stack-frame which is pushed
5740 when the on_failure_jump_nastyloop failure-point is *popped*.
5741 This special frame thus marks the beginning of one iteration
5742 through the loop and we can hence easily check right here
5743 whether something matched between the beginning and the end of
5744 the loop. */
5745 case on_failure_jump_nastyloop:
5746 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5747 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5748 mcnt, p + mcnt);
5750 assert ((re_opcode_t)p[-4] == no_op);
5752 int cycle = 0;
5753 CHECK_INFINITE_LOOP (p - 4, d);
5754 if (!cycle)
5755 /* If there's a cycle, just continue without pushing
5756 this failure point. The failure point is the "try again"
5757 option, which shouldn't be tried.
5758 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5759 PUSH_FAILURE_POINT (p - 3, d);
5761 break;
5763 /* Simple loop detecting on_failure_jump: just check on the
5764 failure stack if the same spot was already hit earlier. */
5765 case on_failure_jump_loop:
5766 on_failure:
5767 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5768 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5769 mcnt, p + mcnt);
5771 int cycle = 0;
5772 CHECK_INFINITE_LOOP (p - 3, d);
5773 if (cycle)
5774 /* If there's a cycle, get out of the loop, as if the matching
5775 had failed. We used to just `goto fail' here, but that was
5776 aborting the search a bit too early: we want to keep the
5777 empty-loop-match and keep matching after the loop.
5778 We want (x?)*y\1z to match both xxyz and xxyxz. */
5779 p += mcnt;
5780 else
5781 PUSH_FAILURE_POINT (p - 3, d);
5783 break;
5786 /* Uses of on_failure_jump:
5788 Each alternative starts with an on_failure_jump that points
5789 to the beginning of the next alternative. Each alternative
5790 except the last ends with a jump that in effect jumps past
5791 the rest of the alternatives. (They really jump to the
5792 ending jump of the following alternative, because tensioning
5793 these jumps is a hassle.)
5795 Repeats start with an on_failure_jump that points past both
5796 the repetition text and either the following jump or
5797 pop_failure_jump back to this on_failure_jump. */
5798 case on_failure_jump:
5799 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5800 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5801 mcnt, p + mcnt);
5803 PUSH_FAILURE_POINT (p -3, d);
5804 break;
5806 /* This operation is used for greedy *.
5807 Compare the beginning of the repeat with what in the
5808 pattern follows its end. If we can establish that there
5809 is nothing that they would both match, i.e., that we
5810 would have to backtrack because of (as in, e.g., `a*a')
5811 then we can use a non-backtracking loop based on
5812 on_failure_keep_string_jump instead of on_failure_jump. */
5813 case on_failure_jump_smart:
5814 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5815 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5816 mcnt, p + mcnt);
5818 re_char *p1 = p; /* Next operation. */
5819 /* Here, we discard `const', making re_match non-reentrant. */
5820 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5821 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5823 p -= 3; /* Reset so that we will re-execute the
5824 instruction once it's been changed. */
5826 EXTRACT_NUMBER (mcnt, p2 - 2);
5828 /* Ensure this is a indeed the trivial kind of loop
5829 we are expecting. */
5830 assert (skip_one_char (p1) == p2 - 3);
5831 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5832 DEBUG_STATEMENT (debug += 2);
5833 if (mutually_exclusive_p (bufp, p1, p2))
5835 /* Use a fast `on_failure_keep_string_jump' loop. */
5836 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5837 *p3 = (unsigned char) on_failure_keep_string_jump;
5838 STORE_NUMBER (p2 - 2, mcnt + 3);
5840 else
5842 /* Default to a safe `on_failure_jump' loop. */
5843 DEBUG_PRINT (" smart default => slow loop.\n");
5844 *p3 = (unsigned char) on_failure_jump;
5846 DEBUG_STATEMENT (debug -= 2);
5848 break;
5850 /* Unconditionally jump (without popping any failure points). */
5851 case jump:
5852 unconditional_jump:
5853 IMMEDIATE_QUIT_CHECK;
5854 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5855 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5856 p += mcnt; /* Do the jump. */
5857 DEBUG_PRINT ("(to %p).\n", p);
5858 break;
5861 /* Have to succeed matching what follows at least n times.
5862 After that, handle like `on_failure_jump'. */
5863 case succeed_n:
5864 /* Signedness doesn't matter since we only compare MCNT to 0. */
5865 EXTRACT_NUMBER (mcnt, p + 2);
5866 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5868 /* Originally, mcnt is how many times we HAVE to succeed. */
5869 if (mcnt != 0)
5871 /* Here, we discard `const', making re_match non-reentrant. */
5872 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5873 mcnt--;
5874 p += 4;
5875 PUSH_NUMBER (p2, mcnt);
5877 else
5878 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5879 goto on_failure;
5880 break;
5882 case jump_n:
5883 /* Signedness doesn't matter since we only compare MCNT to 0. */
5884 EXTRACT_NUMBER (mcnt, p + 2);
5885 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5887 /* Originally, this is how many times we CAN jump. */
5888 if (mcnt != 0)
5890 /* Here, we discard `const', making re_match non-reentrant. */
5891 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5892 mcnt--;
5893 PUSH_NUMBER (p2, mcnt);
5894 goto unconditional_jump;
5896 /* If don't have to jump any more, skip over the rest of command. */
5897 else
5898 p += 4;
5899 break;
5901 case set_number_at:
5903 unsigned char *p2; /* Location of the counter. */
5904 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5906 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5907 /* Here, we discard `const', making re_match non-reentrant. */
5908 p2 = (unsigned char*) p + mcnt;
5909 /* Signedness doesn't matter since we only copy MCNT's bits . */
5910 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5911 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5912 PUSH_NUMBER (p2, mcnt);
5913 break;
5916 case wordbound:
5917 case notwordbound:
5919 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5920 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5922 /* We SUCCEED (or FAIL) in one of the following cases: */
5924 /* Case 1: D is at the beginning or the end of string. */
5925 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5926 not = !not;
5927 else
5929 /* C1 is the character before D, S1 is the syntax of C1, C2
5930 is the character at D, and S2 is the syntax of C2. */
5931 re_wchar_t c1, c2;
5932 int s1, s2;
5933 int dummy;
5934 #ifdef emacs
5935 ssize_t offset = PTR_TO_OFFSET (d - 1);
5936 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5937 UPDATE_SYNTAX_TABLE (charpos);
5938 #endif
5939 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5940 s1 = SYNTAX (c1);
5941 #ifdef emacs
5942 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5943 #endif
5944 PREFETCH_NOLIMIT ();
5945 GET_CHAR_AFTER (c2, d, dummy);
5946 s2 = SYNTAX (c2);
5948 if (/* Case 2: Only one of S1 and S2 is Sword. */
5949 ((s1 == Sword) != (s2 == Sword))
5950 /* Case 3: Both of S1 and S2 are Sword, and macro
5951 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5952 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5953 not = !not;
5955 if (not)
5956 break;
5957 else
5958 goto fail;
5961 case wordbeg:
5962 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5964 /* We FAIL in one of the following cases: */
5966 /* Case 1: D is at the end of string. */
5967 if (AT_STRINGS_END (d))
5968 goto fail;
5969 else
5971 /* C1 is the character before D, S1 is the syntax of C1, C2
5972 is the character at D, and S2 is the syntax of C2. */
5973 re_wchar_t c1, c2;
5974 int s1, s2;
5975 int dummy;
5976 #ifdef emacs
5977 ssize_t offset = PTR_TO_OFFSET (d);
5978 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5979 UPDATE_SYNTAX_TABLE (charpos);
5980 #endif
5981 PREFETCH ();
5982 GET_CHAR_AFTER (c2, d, dummy);
5983 s2 = SYNTAX (c2);
5985 /* Case 2: S2 is not Sword. */
5986 if (s2 != Sword)
5987 goto fail;
5989 /* Case 3: D is not at the beginning of string ... */
5990 if (!AT_STRINGS_BEG (d))
5992 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5993 #ifdef emacs
5994 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5995 #endif
5996 s1 = SYNTAX (c1);
5998 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5999 returns 0. */
6000 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6001 goto fail;
6004 break;
6006 case wordend:
6007 DEBUG_PRINT ("EXECUTING wordend.\n");
6009 /* We FAIL in one of the following cases: */
6011 /* Case 1: D is at the beginning of string. */
6012 if (AT_STRINGS_BEG (d))
6013 goto fail;
6014 else
6016 /* C1 is the character before D, S1 is the syntax of C1, C2
6017 is the character at D, and S2 is the syntax of C2. */
6018 re_wchar_t c1, c2;
6019 int s1, s2;
6020 int dummy;
6021 #ifdef emacs
6022 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6023 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6024 UPDATE_SYNTAX_TABLE (charpos);
6025 #endif
6026 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6027 s1 = SYNTAX (c1);
6029 /* Case 2: S1 is not Sword. */
6030 if (s1 != Sword)
6031 goto fail;
6033 /* Case 3: D is not at the end of string ... */
6034 if (!AT_STRINGS_END (d))
6036 PREFETCH_NOLIMIT ();
6037 GET_CHAR_AFTER (c2, d, dummy);
6038 #ifdef emacs
6039 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
6040 #endif
6041 s2 = SYNTAX (c2);
6043 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6044 returns 0. */
6045 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6046 goto fail;
6049 break;
6051 case symbeg:
6052 DEBUG_PRINT ("EXECUTING symbeg.\n");
6054 /* We FAIL in one of the following cases: */
6056 /* Case 1: D is at the end of string. */
6057 if (AT_STRINGS_END (d))
6058 goto fail;
6059 else
6061 /* C1 is the character before D, S1 is the syntax of C1, C2
6062 is the character at D, and S2 is the syntax of C2. */
6063 re_wchar_t c1, c2;
6064 int s1, s2;
6065 #ifdef emacs
6066 ssize_t offset = PTR_TO_OFFSET (d);
6067 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6068 UPDATE_SYNTAX_TABLE (charpos);
6069 #endif
6070 PREFETCH ();
6071 c2 = RE_STRING_CHAR (d, target_multibyte);
6072 s2 = SYNTAX (c2);
6074 /* Case 2: S2 is neither Sword nor Ssymbol. */
6075 if (s2 != Sword && s2 != Ssymbol)
6076 goto fail;
6078 /* Case 3: D is not at the beginning of string ... */
6079 if (!AT_STRINGS_BEG (d))
6081 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6082 #ifdef emacs
6083 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6084 #endif
6085 s1 = SYNTAX (c1);
6087 /* ... and S1 is Sword or Ssymbol. */
6088 if (s1 == Sword || s1 == Ssymbol)
6089 goto fail;
6092 break;
6094 case symend:
6095 DEBUG_PRINT ("EXECUTING symend.\n");
6097 /* We FAIL in one of the following cases: */
6099 /* Case 1: D is at the beginning of string. */
6100 if (AT_STRINGS_BEG (d))
6101 goto fail;
6102 else
6104 /* C1 is the character before D, S1 is the syntax of C1, C2
6105 is the character at D, and S2 is the syntax of C2. */
6106 re_wchar_t c1, c2;
6107 int s1, s2;
6108 #ifdef emacs
6109 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6110 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6111 UPDATE_SYNTAX_TABLE (charpos);
6112 #endif
6113 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6114 s1 = SYNTAX (c1);
6116 /* Case 2: S1 is neither Ssymbol nor Sword. */
6117 if (s1 != Sword && s1 != Ssymbol)
6118 goto fail;
6120 /* Case 3: D is not at the end of string ... */
6121 if (!AT_STRINGS_END (d))
6123 PREFETCH_NOLIMIT ();
6124 c2 = RE_STRING_CHAR (d, target_multibyte);
6125 #ifdef emacs
6126 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6127 #endif
6128 s2 = SYNTAX (c2);
6130 /* ... and S2 is Sword or Ssymbol. */
6131 if (s2 == Sword || s2 == Ssymbol)
6132 goto fail;
6135 break;
6137 case syntaxspec:
6138 case notsyntaxspec:
6140 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6141 mcnt = *p++;
6142 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6143 mcnt);
6144 PREFETCH ();
6145 #ifdef emacs
6147 ssize_t offset = PTR_TO_OFFSET (d);
6148 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6149 UPDATE_SYNTAX_TABLE (pos1);
6151 #endif
6153 int len;
6154 re_wchar_t c;
6156 GET_CHAR_AFTER (c, d, len);
6157 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6158 goto fail;
6159 d += len;
6162 break;
6164 #ifdef emacs
6165 case before_dot:
6166 DEBUG_PRINT ("EXECUTING before_dot.\n");
6167 if (PTR_BYTE_POS (d) >= PT_BYTE)
6168 goto fail;
6169 break;
6171 case at_dot:
6172 DEBUG_PRINT ("EXECUTING at_dot.\n");
6173 if (PTR_BYTE_POS (d) != PT_BYTE)
6174 goto fail;
6175 break;
6177 case after_dot:
6178 DEBUG_PRINT ("EXECUTING after_dot.\n");
6179 if (PTR_BYTE_POS (d) <= PT_BYTE)
6180 goto fail;
6181 break;
6183 case categoryspec:
6184 case notcategoryspec:
6186 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6187 mcnt = *p++;
6188 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6189 not ? "not" : "", mcnt);
6190 PREFETCH ();
6193 int len;
6194 re_wchar_t c;
6195 GET_CHAR_AFTER (c, d, len);
6196 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6197 goto fail;
6198 d += len;
6201 break;
6203 #endif /* emacs */
6205 default:
6206 abort ();
6208 continue; /* Successfully executed one pattern command; keep going. */
6211 /* We goto here if a matching operation fails. */
6212 fail:
6213 IMMEDIATE_QUIT_CHECK;
6214 if (!FAIL_STACK_EMPTY ())
6216 re_char *str, *pat;
6217 /* A restart point is known. Restore to that state. */
6218 DEBUG_PRINT ("\nFAIL:\n");
6219 POP_FAILURE_POINT (str, pat);
6220 switch (*pat++)
6222 case on_failure_keep_string_jump:
6223 assert (str == NULL);
6224 goto continue_failure_jump;
6226 case on_failure_jump_nastyloop:
6227 assert ((re_opcode_t)pat[-2] == no_op);
6228 PUSH_FAILURE_POINT (pat - 2, str);
6229 /* Fallthrough */
6231 case on_failure_jump_loop:
6232 case on_failure_jump:
6233 case succeed_n:
6234 d = str;
6235 continue_failure_jump:
6236 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6237 p = pat + mcnt;
6238 break;
6240 case no_op:
6241 /* A special frame used for nastyloops. */
6242 goto fail;
6244 default:
6245 abort ();
6248 assert (p >= bufp->buffer && p <= pend);
6250 if (d >= string1 && d <= end1)
6251 dend = end_match_1;
6253 else
6254 break; /* Matching at this starting point really fails. */
6255 } /* for (;;) */
6257 if (best_regs_set)
6258 goto restore_best_regs;
6260 FREE_VARIABLES ();
6262 return -1; /* Failure to match. */
6265 /* Subroutine definitions for re_match_2. */
6267 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6268 bytes; nonzero otherwise. */
6270 static int
6271 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6272 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6274 register re_char *p1 = s1, *p2 = s2;
6275 re_char *p1_end = s1 + len;
6276 re_char *p2_end = s2 + len;
6278 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6279 different lengths, but relying on a single `len' would break this. -sm */
6280 while (p1 < p1_end && p2 < p2_end)
6282 int p1_charlen, p2_charlen;
6283 re_wchar_t p1_ch, p2_ch;
6285 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6286 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6288 if (RE_TRANSLATE (translate, p1_ch)
6289 != RE_TRANSLATE (translate, p2_ch))
6290 return 1;
6292 p1 += p1_charlen, p2 += p2_charlen;
6295 if (p1 != p1_end || p2 != p2_end)
6296 return 1;
6298 return 0;
6301 /* Entry points for GNU code. */
6303 /* re_compile_pattern is the GNU regular expression compiler: it
6304 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6305 Returns 0 if the pattern was valid, otherwise an error string.
6307 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6308 are set in BUFP on entry.
6310 We call regex_compile to do the actual compilation. */
6312 const char *
6313 re_compile_pattern (const char *pattern, size_t length,
6314 struct re_pattern_buffer *bufp)
6316 reg_errcode_t ret;
6318 /* GNU code is written to assume at least RE_NREGS registers will be set
6319 (and at least one extra will be -1). */
6320 bufp->regs_allocated = REGS_UNALLOCATED;
6322 /* And GNU code determines whether or not to get register information
6323 by passing null for the REGS argument to re_match, etc., not by
6324 setting no_sub. */
6325 bufp->no_sub = 0;
6327 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
6329 if (!ret)
6330 return NULL;
6331 return gettext (re_error_msgid[(int) ret]);
6333 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6335 /* Entry points compatible with 4.2 BSD regex library. We don't define
6336 them unless specifically requested. */
6338 #if defined _REGEX_RE_COMP || defined _LIBC
6340 /* BSD has one and only one pattern buffer. */
6341 static struct re_pattern_buffer re_comp_buf;
6343 char *
6344 # ifdef _LIBC
6345 /* Make these definitions weak in libc, so POSIX programs can redefine
6346 these names if they don't use our functions, and still use
6347 regcomp/regexec below without link errors. */
6348 weak_function
6349 # endif
6350 re_comp (const char *s)
6352 reg_errcode_t ret;
6354 if (!s)
6356 if (!re_comp_buf.buffer)
6357 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6358 return (char *) gettext ("No previous regular expression");
6359 return 0;
6362 if (!re_comp_buf.buffer)
6364 re_comp_buf.buffer = malloc (200);
6365 if (re_comp_buf.buffer == NULL)
6366 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6367 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6368 re_comp_buf.allocated = 200;
6370 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6371 if (re_comp_buf.fastmap == NULL)
6372 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6373 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6376 /* Since `re_exec' always passes NULL for the `regs' argument, we
6377 don't need to initialize the pattern buffer fields which affect it. */
6379 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6381 if (!ret)
6382 return NULL;
6384 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6385 return (char *) gettext (re_error_msgid[(int) ret]);
6390 # ifdef _LIBC
6391 weak_function
6392 # endif
6393 re_exec (const char *s)
6395 const size_t len = strlen (s);
6396 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6398 #endif /* _REGEX_RE_COMP */
6400 /* POSIX.2 functions. Don't define these for Emacs. */
6402 #ifndef emacs
6404 /* regcomp takes a regular expression as a string and compiles it.
6406 PREG is a regex_t *. We do not expect any fields to be initialized,
6407 since POSIX says we shouldn't. Thus, we set
6409 `buffer' to the compiled pattern;
6410 `used' to the length of the compiled pattern;
6411 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6412 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6413 RE_SYNTAX_POSIX_BASIC;
6414 `fastmap' to an allocated space for the fastmap;
6415 `fastmap_accurate' to zero;
6416 `re_nsub' to the number of subexpressions in PATTERN.
6418 PATTERN is the address of the pattern string.
6420 CFLAGS is a series of bits which affect compilation.
6422 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6423 use POSIX basic syntax.
6425 If REG_NEWLINE is set, then . and [^...] don't match newline.
6426 Also, regexec will try a match beginning after every newline.
6428 If REG_ICASE is set, then we considers upper- and lowercase
6429 versions of letters to be equivalent when matching.
6431 If REG_NOSUB is set, then when PREG is passed to regexec, that
6432 routine will report only success or failure, and nothing about the
6433 registers.
6435 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6436 the return codes and their meanings.) */
6438 reg_errcode_t
6439 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6440 int cflags)
6442 reg_errcode_t ret;
6443 reg_syntax_t syntax
6444 = (cflags & REG_EXTENDED) ?
6445 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6447 /* regex_compile will allocate the space for the compiled pattern. */
6448 preg->buffer = 0;
6449 preg->allocated = 0;
6450 preg->used = 0;
6452 /* Try to allocate space for the fastmap. */
6453 preg->fastmap = malloc (1 << BYTEWIDTH);
6455 if (cflags & REG_ICASE)
6457 unsigned i;
6459 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6460 if (preg->translate == NULL)
6461 return (int) REG_ESPACE;
6463 /* Map uppercase characters to corresponding lowercase ones. */
6464 for (i = 0; i < CHAR_SET_SIZE; i++)
6465 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6467 else
6468 preg->translate = NULL;
6470 /* If REG_NEWLINE is set, newlines are treated differently. */
6471 if (cflags & REG_NEWLINE)
6472 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6473 syntax &= ~RE_DOT_NEWLINE;
6474 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6476 else
6477 syntax |= RE_NO_NEWLINE_ANCHOR;
6479 preg->no_sub = !!(cflags & REG_NOSUB);
6481 /* POSIX says a null character in the pattern terminates it, so we
6482 can use strlen here in compiling the pattern. */
6483 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6485 /* POSIX doesn't distinguish between an unmatched open-group and an
6486 unmatched close-group: both are REG_EPAREN. */
6487 if (ret == REG_ERPAREN)
6488 ret = REG_EPAREN;
6490 if (ret == REG_NOERROR && preg->fastmap)
6491 { /* Compute the fastmap now, since regexec cannot modify the pattern
6492 buffer. */
6493 re_compile_fastmap (preg);
6494 if (preg->can_be_null)
6495 { /* The fastmap can't be used anyway. */
6496 free (preg->fastmap);
6497 preg->fastmap = NULL;
6500 return ret;
6502 WEAK_ALIAS (__regcomp, regcomp)
6505 /* regexec searches for a given pattern, specified by PREG, in the
6506 string STRING.
6508 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6509 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6510 least NMATCH elements, and we set them to the offsets of the
6511 corresponding matched substrings.
6513 EFLAGS specifies `execution flags' which affect matching: if
6514 REG_NOTBOL is set, then ^ does not match at the beginning of the
6515 string; if REG_NOTEOL is set, then $ does not match at the end.
6517 We return 0 if we find a match and REG_NOMATCH if not. */
6519 reg_errcode_t
6520 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6521 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6523 regoff_t ret;
6524 struct re_registers regs;
6525 regex_t private_preg;
6526 size_t len = strlen (string);
6527 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6529 private_preg = *preg;
6531 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6532 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6534 /* The user has told us exactly how many registers to return
6535 information about, via `nmatch'. We have to pass that on to the
6536 matching routines. */
6537 private_preg.regs_allocated = REGS_FIXED;
6539 if (want_reg_info)
6541 regs.num_regs = nmatch;
6542 regs.start = TALLOC (nmatch * 2, regoff_t);
6543 if (regs.start == NULL)
6544 return REG_NOMATCH;
6545 regs.end = regs.start + nmatch;
6548 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6549 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6550 was a little bit longer but still only matching the real part.
6551 This works because the `endline' will check for a '\n' and will find a
6552 '\0', correctly deciding that this is not the end of a line.
6553 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6554 a convenient '\0' there. For all we know, the string could be preceded
6555 by '\n' which would throw things off. */
6557 /* Perform the searching operation. */
6558 ret = re_search (&private_preg, string, len,
6559 /* start: */ 0, /* range: */ len,
6560 want_reg_info ? &regs : 0);
6562 /* Copy the register information to the POSIX structure. */
6563 if (want_reg_info)
6565 if (ret >= 0)
6567 unsigned r;
6569 for (r = 0; r < nmatch; r++)
6571 pmatch[r].rm_so = regs.start[r];
6572 pmatch[r].rm_eo = regs.end[r];
6576 /* If we needed the temporary register info, free the space now. */
6577 free (regs.start);
6580 /* We want zero return to mean success, unlike `re_search'. */
6581 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6583 WEAK_ALIAS (__regexec, regexec)
6586 /* Returns a message corresponding to an error code, ERR_CODE, returned
6587 from either regcomp or regexec. We don't use PREG here.
6589 ERR_CODE was previously called ERRCODE, but that name causes an
6590 error with msvc8 compiler. */
6592 size_t
6593 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6595 const char *msg;
6596 size_t msg_size;
6598 if (err_code < 0
6599 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6600 /* Only error codes returned by the rest of the code should be passed
6601 to this routine. If we are given anything else, or if other regex
6602 code generates an invalid error code, then the program has a bug.
6603 Dump core so we can fix it. */
6604 abort ();
6606 msg = gettext (re_error_msgid[err_code]);
6608 msg_size = strlen (msg) + 1; /* Includes the null. */
6610 if (errbuf_size != 0)
6612 if (msg_size > errbuf_size)
6614 memcpy (errbuf, msg, errbuf_size - 1);
6615 errbuf[errbuf_size - 1] = 0;
6617 else
6618 strcpy (errbuf, msg);
6621 return msg_size;
6623 WEAK_ALIAS (__regerror, regerror)
6626 /* Free dynamically allocated space used by PREG. */
6628 void
6629 regfree (regex_t *preg)
6631 free (preg->buffer);
6632 preg->buffer = NULL;
6634 preg->allocated = 0;
6635 preg->used = 0;
6637 free (preg->fastmap);
6638 preg->fastmap = NULL;
6639 preg->fastmap_accurate = 0;
6641 free (preg->translate);
6642 preg->translate = NULL;
6644 WEAK_ALIAS (__regfree, regfree)
6646 #endif /* not emacs */