Minimize spurious diffs from master.
[emacs.git] / src / regex.c
blobe7231d3882bb7b0b00ff8a75f83ddb1781a60d45
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-2016 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__ + (6 <= __GNUC_MINOR__) && ! defined __clang__
47 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
48 #endif
50 #include <config.h>
52 #include <stddef.h>
53 #include <stdlib.h>
55 #ifdef emacs
56 /* We need this for `regex.h', and perhaps for the Emacs include files. */
57 # include <sys/types.h>
58 #endif
60 /* Whether to use ISO C Amendment 1 wide char functions.
61 Those should not be used for Emacs since it uses its own. */
62 #if defined _LIBC
63 #define WIDE_CHAR_SUPPORT 1
64 #else
65 #define WIDE_CHAR_SUPPORT \
66 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
67 #endif
69 /* For platform which support the ISO C amendment 1 functionality we
70 support user defined character classes. */
71 #if WIDE_CHAR_SUPPORT
72 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
73 # include <wchar.h>
74 # include <wctype.h>
75 #endif
77 #ifdef _LIBC
78 /* We have to keep the namespace clean. */
79 # define regfree(preg) __regfree (preg)
80 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
81 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
82 # define regerror(err_code, preg, errbuf, errbuf_size) \
83 __regerror (err_code, preg, errbuf, errbuf_size)
84 # define re_set_registers(bu, re, nu, st, en) \
85 __re_set_registers (bu, re, nu, st, en)
86 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
87 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
88 # define re_match(bufp, string, size, pos, regs) \
89 __re_match (bufp, string, size, pos, regs)
90 # define re_search(bufp, string, size, startpos, range, regs) \
91 __re_search (bufp, string, size, startpos, range, regs)
92 # define re_compile_pattern(pattern, length, bufp) \
93 __re_compile_pattern (pattern, length, bufp)
94 # define re_set_syntax(syntax) __re_set_syntax (syntax)
95 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
96 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
97 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
99 /* Make sure we call libc's function even if the user overrides them. */
100 # define btowc __btowc
101 # define iswctype __iswctype
102 # define wctype __wctype
104 # define WEAK_ALIAS(a,b) weak_alias (a, b)
106 /* We are also using some library internals. */
107 # include <locale/localeinfo.h>
108 # include <locale/elem-hash.h>
109 # include <langinfo.h>
110 #else
111 # define WEAK_ALIAS(a,b)
112 #endif
114 /* This is for other GNU distributions with internationalized messages. */
115 #if HAVE_LIBINTL_H || defined _LIBC
116 # include <libintl.h>
117 #else
118 # define gettext(msgid) (msgid)
119 #endif
121 #ifndef gettext_noop
122 /* This define is so xgettext can find the internationalizable
123 strings. */
124 # define gettext_noop(String) String
125 #endif
127 /* The `emacs' switch turns on certain matching commands
128 that make sense only in Emacs. */
129 #ifdef emacs
131 # include "lisp.h"
132 # include "character.h"
133 # include "buffer.h"
135 # include "syntax.h"
136 # include "category.h"
138 /* Make syntax table lookup grant data in gl_state. */
139 # define SYNTAX(c) syntax_property (c, 1)
141 # ifdef malloc
142 # undef malloc
143 # endif
144 # define malloc xmalloc
145 # ifdef realloc
146 # undef realloc
147 # endif
148 # define realloc xrealloc
149 # ifdef free
150 # undef free
151 # endif
152 # define free xfree
154 /* Converts the pointer to the char to BEG-based offset from the start. */
155 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
156 /* Strings are 0-indexed, buffers are 1-indexed; we pun on the boolean
157 result to get the right base index. */
158 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
160 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
161 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
162 # define RE_STRING_CHAR(p, multibyte) \
163 (multibyte ? (STRING_CHAR (p)) : (*(p)))
164 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
165 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
167 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
169 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
171 /* Set C a (possibly converted to multibyte) character before P. P
172 points into a string which is the virtual concatenation of STR1
173 (which ends at END1) or STR2 (which ends at END2). */
174 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
175 do { \
176 if (target_multibyte) \
178 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
179 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
180 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
181 c = STRING_CHAR (dtemp); \
183 else \
185 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
186 (c) = RE_CHAR_TO_MULTIBYTE (c); \
188 } while (0)
190 /* Set C a (possibly converted to multibyte) character at P, and set
191 LEN to the byte length of that character. */
192 # define GET_CHAR_AFTER(c, p, len) \
193 do { \
194 if (target_multibyte) \
195 (c) = STRING_CHAR_AND_LENGTH (p, len); \
196 else \
198 (c) = *p; \
199 len = 1; \
200 (c) = RE_CHAR_TO_MULTIBYTE (c); \
202 } while (0)
204 #else /* not emacs */
206 /* If we are not linking with Emacs proper,
207 we can't use the relocating allocator
208 even if config.h says that we can. */
209 # undef REL_ALLOC
211 # include <unistd.h>
213 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
215 static void *
216 xmalloc (size_t size)
218 void *val = malloc (size);
219 if (!val && size)
221 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
222 exit (1);
224 return val;
227 static void *
228 xrealloc (void *block, size_t size)
230 void *val;
231 /* We must call malloc explicitly when BLOCK is 0, since some
232 reallocs don't do this. */
233 if (! block)
234 val = malloc (size);
235 else
236 val = realloc (block, size);
237 if (!val && size)
239 write (STDERR_FILENO, "virtual memory exhausted\n", 25);
240 exit (1);
242 return val;
245 # ifdef malloc
246 # undef malloc
247 # endif
248 # define malloc xmalloc
249 # ifdef realloc
250 # undef realloc
251 # endif
252 # define realloc xrealloc
254 # include <stdbool.h>
255 # include <string.h>
257 /* Define the syntax stuff for \<, \>, etc. */
259 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
260 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
262 /* Dummy macros for non-Emacs environments. */
263 # define MAX_MULTIBYTE_LENGTH 1
264 # define RE_MULTIBYTE_P(x) 0
265 # define RE_TARGET_MULTIBYTE_P(x) 0
266 # define WORD_BOUNDARY_P(c1, c2) (0)
267 # define BYTES_BY_CHAR_HEAD(p) (1)
268 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
269 # define STRING_CHAR(p) (*(p))
270 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
271 # define CHAR_STRING(c, s) (*(s) = (c), 1)
272 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
273 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
274 # define RE_CHAR_TO_MULTIBYTE(c) (c)
275 # define RE_CHAR_TO_UNIBYTE(c) (c)
276 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
277 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
278 # define GET_CHAR_AFTER(c, p, len) \
279 (c = *p, len = 1)
280 # define CHAR_BYTE8_P(c) (0)
281 # define CHAR_LEADING_CODE(c) (c)
283 #endif /* not emacs */
285 #ifndef RE_TRANSLATE
286 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
287 # define RE_TRANSLATE_P(TBL) (TBL)
288 #endif
290 /* Get the interface, including the syntax bits. */
291 #include "regex.h"
293 /* isalpha etc. are used for the character classes. */
294 #include <ctype.h>
296 #ifdef emacs
298 /* 1 if C is an ASCII character. */
299 # define IS_REAL_ASCII(c) ((c) < 0200)
301 /* 1 if C is a unibyte character. */
302 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
304 /* The Emacs definitions should not be directly affected by locales. */
306 /* In Emacs, these are only used for single-byte characters. */
307 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
308 # define ISCNTRL(c) ((c) < ' ')
309 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
310 || ((c) >= 'a' && (c) <= 'f') \
311 || ((c) >= 'A' && (c) <= 'F'))
313 /* This is only used for single-byte characters. */
314 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
316 /* The rest must handle multibyte characters. */
318 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
319 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0240) \
320 : graphicp (c))
322 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
323 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
324 : printablep (c))
326 # define ISALNUM(c) (IS_REAL_ASCII (c) \
327 ? (((c) >= 'a' && (c) <= 'z') \
328 || ((c) >= 'A' && (c) <= 'Z') \
329 || ((c) >= '0' && (c) <= '9')) \
330 : alphanumericp (c))
332 # define ISALPHA(c) (IS_REAL_ASCII (c) \
333 ? (((c) >= 'a' && (c) <= 'z') \
334 || ((c) >= 'A' && (c) <= 'Z')) \
335 : alphabeticp (c))
337 # define ISLOWER(c) lowercasep (c)
339 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
340 ? ((c) > ' ' && (c) < 0177 \
341 && !(((c) >= 'a' && (c) <= 'z') \
342 || ((c) >= 'A' && (c) <= 'Z') \
343 || ((c) >= '0' && (c) <= '9'))) \
344 : SYNTAX (c) != Sword)
346 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
348 # define ISUPPER(c) uppercasep (c)
350 # define ISWORD(c) (SYNTAX (c) == Sword)
352 #else /* not emacs */
354 /* 1 if C is an ASCII character. */
355 # define IS_REAL_ASCII(c) ((c) < 0200)
357 /* This distinction is not meaningful, except in Emacs. */
358 # define ISUNIBYTE(c) 1
360 # ifdef isblank
361 # define ISBLANK(c) isblank (c)
362 # else
363 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
364 # endif
365 # ifdef isgraph
366 # define ISGRAPH(c) isgraph (c)
367 # else
368 # define ISGRAPH(c) (isprint (c) && !isspace (c))
369 # endif
371 /* Solaris defines ISPRINT so we must undefine it first. */
372 # undef ISPRINT
373 # define ISPRINT(c) isprint (c)
374 # define ISDIGIT(c) isdigit (c)
375 # define ISALNUM(c) isalnum (c)
376 # define ISALPHA(c) isalpha (c)
377 # define ISCNTRL(c) iscntrl (c)
378 # define ISLOWER(c) islower (c)
379 # define ISPUNCT(c) ispunct (c)
380 # define ISSPACE(c) isspace (c)
381 # define ISUPPER(c) isupper (c)
382 # define ISXDIGIT(c) isxdigit (c)
384 # define ISWORD(c) ISALPHA (c)
386 # ifdef _tolower
387 # define TOLOWER(c) _tolower (c)
388 # else
389 # define TOLOWER(c) tolower (c)
390 # endif
392 /* How many characters in the character set. */
393 # define CHAR_SET_SIZE 256
395 # ifdef SYNTAX_TABLE
397 extern char *re_syntax_table;
399 # else /* not SYNTAX_TABLE */
401 static char re_syntax_table[CHAR_SET_SIZE];
403 static void
404 init_syntax_once (void)
406 register int c;
407 static int done = 0;
409 if (done)
410 return;
412 memset (re_syntax_table, 0, sizeof re_syntax_table);
414 for (c = 0; c < CHAR_SET_SIZE; ++c)
415 if (ISALNUM (c))
416 re_syntax_table[c] = Sword;
418 re_syntax_table['_'] = Ssymbol;
420 done = 1;
423 # endif /* not SYNTAX_TABLE */
425 # define SYNTAX(c) re_syntax_table[(c)]
427 #endif /* not emacs */
429 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
431 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
432 use `alloca' instead of `malloc'. This is because using malloc in
433 re_search* or re_match* could cause memory leaks when C-g is used in
434 Emacs; also, malloc is slower and causes storage fragmentation. On
435 the other hand, malloc is more portable, and easier to debug.
437 Because we sometimes use alloca, some routines have to be macros,
438 not functions -- `alloca'-allocated space disappears at the end of the
439 function it is called in. */
441 #ifdef REGEX_MALLOC
443 # define REGEX_ALLOCATE malloc
444 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
445 # define REGEX_FREE free
447 #else /* not REGEX_MALLOC */
449 # ifdef emacs
450 # define REGEX_USE_SAFE_ALLOCA USE_SAFE_ALLOCA
451 # define REGEX_SAFE_FREE() SAFE_FREE ()
452 # define REGEX_ALLOCATE SAFE_ALLOCA
453 # else
454 # include <alloca.h>
455 # define REGEX_ALLOCATE alloca
456 # endif
458 /* Assumes a `char *destination' variable. */
459 # define REGEX_REALLOCATE(source, osize, nsize) \
460 (destination = REGEX_ALLOCATE (nsize), \
461 memcpy (destination, source, osize))
463 /* No need to do anything to free, after alloca. */
464 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
466 #endif /* not REGEX_MALLOC */
468 #ifndef REGEX_USE_SAFE_ALLOCA
469 # define REGEX_USE_SAFE_ALLOCA ((void) 0)
470 # define REGEX_SAFE_FREE() ((void) 0)
471 #endif
473 /* Define how to allocate the failure stack. */
475 #if defined REL_ALLOC && defined REGEX_MALLOC
477 # define REGEX_ALLOCATE_STACK(size) \
478 r_alloc (&failure_stack_ptr, (size))
479 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
480 r_re_alloc (&failure_stack_ptr, (nsize))
481 # define REGEX_FREE_STACK(ptr) \
482 r_alloc_free (&failure_stack_ptr)
484 #else /* not using relocating allocator */
486 # define REGEX_ALLOCATE_STACK(size) REGEX_ALLOCATE (size)
487 # define REGEX_REALLOCATE_STACK(source, o, n) REGEX_REALLOCATE (source, o, n)
488 # define REGEX_FREE_STACK(ptr) REGEX_FREE (ptr)
490 #endif /* not using relocating allocator */
493 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
494 `string1' or just past its end. This works if PTR is NULL, which is
495 a good thing. */
496 #define FIRST_STRING_P(ptr) \
497 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
499 /* (Re)Allocate N items of type T using malloc, or fail. */
500 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
501 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
502 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
504 #define BYTEWIDTH 8 /* In bits. */
506 #ifndef emacs
507 # undef max
508 # undef min
509 # define max(a, b) ((a) > (b) ? (a) : (b))
510 # define min(a, b) ((a) < (b) ? (a) : (b))
511 #endif
513 /* Type of source-pattern and string chars. */
514 #ifdef _MSC_VER
515 typedef unsigned char re_char;
516 typedef const re_char const_re_char;
517 #else
518 typedef const unsigned char re_char;
519 typedef re_char const_re_char;
520 #endif
522 typedef char boolean;
524 static regoff_t re_match_2_internal (struct re_pattern_buffer *bufp,
525 re_char *string1, size_t size1,
526 re_char *string2, size_t size2,
527 ssize_t pos,
528 struct re_registers *regs,
529 ssize_t stop);
531 /* These are the command codes that appear in compiled regular
532 expressions. Some opcodes are followed by argument bytes. A
533 command code can specify any interpretation whatsoever for its
534 arguments. Zero bytes may appear in the compiled regular expression. */
536 typedef enum
538 no_op = 0,
540 /* Succeed right away--no more backtracking. */
541 succeed,
543 /* Followed by one byte giving n, then by n literal bytes. */
544 exactn,
546 /* Matches any (more or less) character. */
547 anychar,
549 /* Matches any one char belonging to specified set. First
550 following byte is number of bitmap bytes. Then come bytes
551 for a bitmap saying which chars are in. Bits in each byte
552 are ordered low-bit-first. A character is in the set if its
553 bit is 1. A character too large to have a bit in the map is
554 automatically not in the set.
556 If the length byte has the 0x80 bit set, then that stuff
557 is followed by a range table:
558 2 bytes of flags for character sets (low 8 bits, high 8 bits)
559 See RANGE_TABLE_WORK_BITS below.
560 2 bytes, the number of pairs that follow (upto 32767)
561 pairs, each 2 multibyte characters,
562 each multibyte character represented as 3 bytes. */
563 charset,
565 /* Same parameters as charset, but match any character that is
566 not one of those specified. */
567 charset_not,
569 /* Start remembering the text that is matched, for storing in a
570 register. Followed by one byte with the register number, in
571 the range 0 to one less than the pattern buffer's re_nsub
572 field. */
573 start_memory,
575 /* Stop remembering the text that is matched and store it in a
576 memory register. Followed by one byte with the register
577 number, in the range 0 to one less than `re_nsub' in the
578 pattern buffer. */
579 stop_memory,
581 /* Match a duplicate of something remembered. Followed by one
582 byte containing the register number. */
583 duplicate,
585 /* Fail unless at beginning of line. */
586 begline,
588 /* Fail unless at end of line. */
589 endline,
591 /* Succeeds if at beginning of buffer (if emacs) or at beginning
592 of string to be matched (if not). */
593 begbuf,
595 /* Analogously, for end of buffer/string. */
596 endbuf,
598 /* Followed by two byte relative address to which to jump. */
599 jump,
601 /* Followed by two-byte relative address of place to resume at
602 in case of failure. */
603 on_failure_jump,
605 /* Like on_failure_jump, but pushes a placeholder instead of the
606 current string position when executed. */
607 on_failure_keep_string_jump,
609 /* Just like `on_failure_jump', except that it checks that we
610 don't get stuck in an infinite loop (matching an empty string
611 indefinitely). */
612 on_failure_jump_loop,
614 /* Just like `on_failure_jump_loop', except that it checks for
615 a different kind of loop (the kind that shows up with non-greedy
616 operators). This operation has to be immediately preceded
617 by a `no_op'. */
618 on_failure_jump_nastyloop,
620 /* A smart `on_failure_jump' used for greedy * and + operators.
621 It analyzes the loop before which it is put and if the
622 loop does not require backtracking, it changes itself to
623 `on_failure_keep_string_jump' and short-circuits the loop,
624 else it just defaults to changing itself into `on_failure_jump'.
625 It assumes that it is pointing to just past a `jump'. */
626 on_failure_jump_smart,
628 /* Followed by two-byte relative address and two-byte number n.
629 After matching N times, jump to the address upon failure.
630 Does not work if N starts at 0: use on_failure_jump_loop
631 instead. */
632 succeed_n,
634 /* Followed by two-byte relative address, and two-byte number n.
635 Jump to the address N times, then fail. */
636 jump_n,
638 /* Set the following two-byte relative address to the
639 subsequent two-byte number. The address *includes* the two
640 bytes of number. */
641 set_number_at,
643 wordbeg, /* Succeeds if at word beginning. */
644 wordend, /* Succeeds if at word end. */
646 wordbound, /* Succeeds if at a word boundary. */
647 notwordbound, /* Succeeds if not at a word boundary. */
649 symbeg, /* Succeeds if at symbol beginning. */
650 symend, /* Succeeds if at symbol end. */
652 /* Matches any character whose syntax is specified. Followed by
653 a byte which contains a syntax code, e.g., Sword. */
654 syntaxspec,
656 /* Matches any character whose syntax is not that specified. */
657 notsyntaxspec
659 #ifdef emacs
660 , at_dot, /* Succeeds if at point. */
662 /* Matches any character whose category-set contains the specified
663 category. The operator is followed by a byte which contains a
664 category code (mnemonic ASCII character). */
665 categoryspec,
667 /* Matches any character whose category-set does not contain the
668 specified category. The operator is followed by a byte which
669 contains the category code (mnemonic ASCII character). */
670 notcategoryspec
671 #endif /* emacs */
672 } re_opcode_t;
674 /* Common operations on the compiled pattern. */
676 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
678 #define STORE_NUMBER(destination, number) \
679 do { \
680 (destination)[0] = (number) & 0377; \
681 (destination)[1] = (number) >> 8; \
682 } while (0)
684 /* Same as STORE_NUMBER, except increment DESTINATION to
685 the byte after where the number is stored. Therefore, DESTINATION
686 must be an lvalue. */
688 #define STORE_NUMBER_AND_INCR(destination, number) \
689 do { \
690 STORE_NUMBER (destination, number); \
691 (destination) += 2; \
692 } while (0)
694 /* Put into DESTINATION a number stored in two contiguous bytes starting
695 at SOURCE. */
697 #define EXTRACT_NUMBER(destination, source) \
698 ((destination) = extract_number (source))
700 static int
701 extract_number (re_char *source)
703 unsigned leading_byte = SIGN_EXTEND_CHAR (source[1]);
704 return (leading_byte << 8) + source[0];
707 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
708 SOURCE must be an lvalue. */
710 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
711 ((destination) = extract_number_and_incr (&source))
713 static int
714 extract_number_and_incr (re_char **source)
716 int num = extract_number (*source);
717 *source += 2;
718 return num;
721 /* Store a multibyte character in three contiguous bytes starting
722 DESTINATION, and increment DESTINATION to the byte after where the
723 character is stored. Therefore, DESTINATION must be an lvalue. */
725 #define STORE_CHARACTER_AND_INCR(destination, character) \
726 do { \
727 (destination)[0] = (character) & 0377; \
728 (destination)[1] = ((character) >> 8) & 0377; \
729 (destination)[2] = (character) >> 16; \
730 (destination) += 3; \
731 } while (0)
733 /* Put into DESTINATION a character stored in three contiguous bytes
734 starting at SOURCE. */
736 #define EXTRACT_CHARACTER(destination, source) \
737 do { \
738 (destination) = ((source)[0] \
739 | ((source)[1] << 8) \
740 | ((source)[2] << 16)); \
741 } while (0)
744 /* Macros for charset. */
746 /* Size of bitmap of charset P in bytes. P is a start of charset,
747 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
748 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
750 /* Nonzero if charset P has range table. */
751 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
753 /* Return the address of range table of charset P. But not the start
754 of table itself, but the before where the number of ranges is
755 stored. `2 +' means to skip re_opcode_t and size of bitmap,
756 and the 2 bytes of flags at the start of the range table. */
757 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
759 #ifdef emacs
760 /* Extract the bit flags that start a range table. */
761 #define CHARSET_RANGE_TABLE_BITS(p) \
762 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
763 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
764 #endif
766 /* Return the address of end of RANGE_TABLE. COUNT is number of
767 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
768 is start of range and end of range. `* 3' is size of each start
769 and end. */
770 #define CHARSET_RANGE_TABLE_END(range_table, count) \
771 ((range_table) + (count) * 2 * 3)
773 /* If DEBUG is defined, Regex prints many voluminous messages about what
774 it is doing (if the variable `debug' is nonzero). If linked with the
775 main program in `iregex.c', you can enter patterns and strings
776 interactively. And if linked with the main program in `main.c' and
777 the other test files, you can run the already-written tests. */
779 #ifdef DEBUG
781 /* We use standard I/O for debugging. */
782 # include <stdio.h>
784 /* It is useful to test things that ``must'' be true when debugging. */
785 # include <assert.h>
787 static int debug = -100000;
789 # define DEBUG_STATEMENT(e) e
790 # define DEBUG_PRINT(...) if (debug > 0) printf (__VA_ARGS__)
791 # define DEBUG_COMPILES_ARGUMENTS
792 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
793 if (debug > 0) print_partial_compiled_pattern (s, e)
794 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
795 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
798 /* Print the fastmap in human-readable form. */
800 static void
801 print_fastmap (char *fastmap)
803 unsigned was_a_range = 0;
804 unsigned i = 0;
806 while (i < (1 << BYTEWIDTH))
808 if (fastmap[i++])
810 was_a_range = 0;
811 putchar (i - 1);
812 while (i < (1 << BYTEWIDTH) && fastmap[i])
814 was_a_range = 1;
815 i++;
817 if (was_a_range)
819 printf ("-");
820 putchar (i - 1);
824 putchar ('\n');
828 /* Print a compiled pattern string in human-readable form, starting at
829 the START pointer into it and ending just before the pointer END. */
831 static void
832 print_partial_compiled_pattern (re_char *start, re_char *end)
834 int mcnt, mcnt2;
835 re_char *p = start;
836 re_char *pend = end;
838 if (start == NULL)
840 fprintf (stderr, "(null)\n");
841 return;
844 /* Loop over pattern commands. */
845 while (p < pend)
847 fprintf (stderr, "%td:\t", p - start);
849 switch ((re_opcode_t) *p++)
851 case no_op:
852 fprintf (stderr, "/no_op");
853 break;
855 case succeed:
856 fprintf (stderr, "/succeed");
857 break;
859 case exactn:
860 mcnt = *p++;
861 fprintf (stderr, "/exactn/%d", mcnt);
864 fprintf (stderr, "/%c", *p++);
866 while (--mcnt);
867 break;
869 case start_memory:
870 fprintf (stderr, "/start_memory/%d", *p++);
871 break;
873 case stop_memory:
874 fprintf (stderr, "/stop_memory/%d", *p++);
875 break;
877 case duplicate:
878 fprintf (stderr, "/duplicate/%d", *p++);
879 break;
881 case anychar:
882 fprintf (stderr, "/anychar");
883 break;
885 case charset:
886 case charset_not:
888 register int c, last = -100;
889 register int in_range = 0;
890 int length = CHARSET_BITMAP_SIZE (p - 1);
891 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
893 fprintf (stderr, "/charset [%s",
894 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
896 if (p + *p >= pend)
897 fprintf (stderr, " !extends past end of pattern! ");
899 for (c = 0; c < 256; c++)
900 if (c / 8 < length
901 && (p[1 + (c/8)] & (1 << (c % 8))))
903 /* Are we starting a range? */
904 if (last + 1 == c && ! in_range)
906 fprintf (stderr, "-");
907 in_range = 1;
909 /* Have we broken a range? */
910 else if (last + 1 != c && in_range)
912 fprintf (stderr, "%c", last);
913 in_range = 0;
916 if (! in_range)
917 fprintf (stderr, "%c", c);
919 last = c;
922 if (in_range)
923 fprintf (stderr, "%c", last);
925 fprintf (stderr, "]");
927 p += 1 + length;
929 if (has_range_table)
931 int count;
932 fprintf (stderr, "has-range-table");
934 /* ??? Should print the range table; for now, just skip it. */
935 p += 2; /* skip range table bits */
936 EXTRACT_NUMBER_AND_INCR (count, p);
937 p = CHARSET_RANGE_TABLE_END (p, count);
940 break;
942 case begline:
943 fprintf (stderr, "/begline");
944 break;
946 case endline:
947 fprintf (stderr, "/endline");
948 break;
950 case on_failure_jump:
951 EXTRACT_NUMBER_AND_INCR (mcnt, p);
952 fprintf (stderr, "/on_failure_jump to %td", p + mcnt - start);
953 break;
955 case on_failure_keep_string_jump:
956 EXTRACT_NUMBER_AND_INCR (mcnt, p);
957 fprintf (stderr, "/on_failure_keep_string_jump to %td",
958 p + mcnt - start);
959 break;
961 case on_failure_jump_nastyloop:
962 EXTRACT_NUMBER_AND_INCR (mcnt, p);
963 fprintf (stderr, "/on_failure_jump_nastyloop to %td",
964 p + mcnt - start);
965 break;
967 case on_failure_jump_loop:
968 EXTRACT_NUMBER_AND_INCR (mcnt, p);
969 fprintf (stderr, "/on_failure_jump_loop to %td",
970 p + mcnt - start);
971 break;
973 case on_failure_jump_smart:
974 EXTRACT_NUMBER_AND_INCR (mcnt, p);
975 fprintf (stderr, "/on_failure_jump_smart to %td",
976 p + mcnt - start);
977 break;
979 case jump:
980 EXTRACT_NUMBER_AND_INCR (mcnt, p);
981 fprintf (stderr, "/jump to %td", p + mcnt - start);
982 break;
984 case succeed_n:
985 EXTRACT_NUMBER_AND_INCR (mcnt, p);
986 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
987 fprintf (stderr, "/succeed_n to %td, %d times",
988 p - 2 + mcnt - start, mcnt2);
989 break;
991 case jump_n:
992 EXTRACT_NUMBER_AND_INCR (mcnt, p);
993 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
994 fprintf (stderr, "/jump_n to %td, %d times",
995 p - 2 + mcnt - start, mcnt2);
996 break;
998 case set_number_at:
999 EXTRACT_NUMBER_AND_INCR (mcnt, p);
1000 EXTRACT_NUMBER_AND_INCR (mcnt2, p);
1001 fprintf (stderr, "/set_number_at location %td to %d",
1002 p - 2 + mcnt - start, mcnt2);
1003 break;
1005 case wordbound:
1006 fprintf (stderr, "/wordbound");
1007 break;
1009 case notwordbound:
1010 fprintf (stderr, "/notwordbound");
1011 break;
1013 case wordbeg:
1014 fprintf (stderr, "/wordbeg");
1015 break;
1017 case wordend:
1018 fprintf (stderr, "/wordend");
1019 break;
1021 case symbeg:
1022 fprintf (stderr, "/symbeg");
1023 break;
1025 case symend:
1026 fprintf (stderr, "/symend");
1027 break;
1029 case syntaxspec:
1030 fprintf (stderr, "/syntaxspec");
1031 mcnt = *p++;
1032 fprintf (stderr, "/%d", mcnt);
1033 break;
1035 case notsyntaxspec:
1036 fprintf (stderr, "/notsyntaxspec");
1037 mcnt = *p++;
1038 fprintf (stderr, "/%d", mcnt);
1039 break;
1041 # ifdef emacs
1042 case at_dot:
1043 fprintf (stderr, "/at_dot");
1044 break;
1046 case categoryspec:
1047 fprintf (stderr, "/categoryspec");
1048 mcnt = *p++;
1049 fprintf (stderr, "/%d", mcnt);
1050 break;
1052 case notcategoryspec:
1053 fprintf (stderr, "/notcategoryspec");
1054 mcnt = *p++;
1055 fprintf (stderr, "/%d", mcnt);
1056 break;
1057 # endif /* emacs */
1059 case begbuf:
1060 fprintf (stderr, "/begbuf");
1061 break;
1063 case endbuf:
1064 fprintf (stderr, "/endbuf");
1065 break;
1067 default:
1068 fprintf (stderr, "?%d", *(p-1));
1071 fprintf (stderr, "\n");
1074 fprintf (stderr, "%td:\tend of pattern.\n", p - start);
1078 static void
1079 print_compiled_pattern (struct re_pattern_buffer *bufp)
1081 re_char *buffer = bufp->buffer;
1083 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1084 printf ("%ld bytes used/%ld bytes allocated.\n",
1085 bufp->used, bufp->allocated);
1087 if (bufp->fastmap_accurate && bufp->fastmap)
1089 printf ("fastmap: ");
1090 print_fastmap (bufp->fastmap);
1093 printf ("re_nsub: %zu\t", bufp->re_nsub);
1094 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1095 printf ("can_be_null: %d\t", bufp->can_be_null);
1096 printf ("no_sub: %d\t", bufp->no_sub);
1097 printf ("not_bol: %d\t", bufp->not_bol);
1098 printf ("not_eol: %d\t", bufp->not_eol);
1099 #ifndef emacs
1100 printf ("syntax: %lx\n", bufp->syntax);
1101 #endif
1102 fflush (stdout);
1103 /* Perhaps we should print the translate table? */
1107 static void
1108 print_double_string (re_char *where, re_char *string1, ssize_t size1,
1109 re_char *string2, ssize_t size2)
1111 ssize_t this_char;
1113 if (where == NULL)
1114 printf ("(null)");
1115 else
1117 if (FIRST_STRING_P (where))
1119 for (this_char = where - string1; this_char < size1; this_char++)
1120 putchar (string1[this_char]);
1122 where = string2;
1125 for (this_char = where - string2; this_char < size2; this_char++)
1126 putchar (string2[this_char]);
1130 #else /* not DEBUG */
1132 # undef assert
1133 # define assert(e)
1135 # define DEBUG_STATEMENT(e)
1136 # define DEBUG_PRINT(...)
1137 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1138 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1140 #endif /* not DEBUG */
1142 #ifndef emacs
1143 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1144 also be assigned to arbitrarily: each pattern buffer stores its own
1145 syntax, so it can be changed between regex compilations. */
1146 /* This has no initializer because initialized variables in Emacs
1147 become read-only after dumping. */
1148 reg_syntax_t re_syntax_options;
1151 /* Specify the precise syntax of regexps for compilation. This provides
1152 for compatibility for various utilities which historically have
1153 different, incompatible syntaxes.
1155 The argument SYNTAX is a bit mask comprised of the various bits
1156 defined in regex.h. We return the old syntax. */
1158 reg_syntax_t
1159 re_set_syntax (reg_syntax_t syntax)
1161 reg_syntax_t ret = re_syntax_options;
1163 re_syntax_options = syntax;
1164 return ret;
1166 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1168 #endif
1170 /* This table gives an error message for each of the error codes listed
1171 in regex.h. Obviously the order here has to be same as there.
1172 POSIX doesn't require that we do anything for REG_NOERROR,
1173 but why not be nice? */
1175 static const char *re_error_msgid[] =
1177 gettext_noop ("Success"), /* REG_NOERROR */
1178 gettext_noop ("No match"), /* REG_NOMATCH */
1179 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1180 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1181 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1182 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1183 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1184 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1185 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1186 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1187 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1188 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1189 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1190 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1191 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1192 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1193 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1194 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1197 /* Avoiding alloca during matching, to placate r_alloc. */
1199 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1200 searching and matching functions should not call alloca. On some
1201 systems, alloca is implemented in terms of malloc, and if we're
1202 using the relocating allocator routines, then malloc could cause a
1203 relocation, which might (if the strings being searched are in the
1204 ralloc heap) shift the data out from underneath the regexp
1205 routines.
1207 Here's another reason to avoid allocation: Emacs
1208 processes input from X in a signal handler; processing X input may
1209 call malloc; if input arrives while a matching routine is calling
1210 malloc, then we're scrod. But Emacs can't just block input while
1211 calling matching routines; then we don't notice interrupts when
1212 they come in. So, Emacs blocks input around all regexp calls
1213 except the matching calls, which it leaves unprotected, in the
1214 faith that they will not malloc. */
1216 /* Normally, this is fine. */
1217 #define MATCH_MAY_ALLOCATE
1219 /* The match routines may not allocate if (1) they would do it with malloc
1220 and (2) it's not safe for them to use malloc.
1221 Note that if REL_ALLOC is defined, matching would not use malloc for the
1222 failure stack, but we would still use it for the register vectors;
1223 so REL_ALLOC should not affect this. */
1224 #if defined REGEX_MALLOC && defined emacs
1225 # undef MATCH_MAY_ALLOCATE
1226 #endif
1229 /* Failure stack declarations and macros; both re_compile_fastmap and
1230 re_match_2 use a failure stack. These have to be macros because of
1231 REGEX_ALLOCATE_STACK. */
1234 /* Approximate number of failure points for which to initially allocate space
1235 when matching. If this number is exceeded, we allocate more
1236 space, so it is not a hard limit. */
1237 #ifndef INIT_FAILURE_ALLOC
1238 # define INIT_FAILURE_ALLOC 20
1239 #endif
1241 /* Roughly the maximum number of failure points on the stack. Would be
1242 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1243 This is a variable only so users of regex can assign to it; we never
1244 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1245 before using it, so it should probably be a byte-count instead. */
1246 # if defined MATCH_MAY_ALLOCATE
1247 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1248 whose default stack limit is 2mb. In order for a larger
1249 value to work reliably, you have to try to make it accord
1250 with the process stack limit. */
1251 size_t re_max_failures = 40000;
1252 # else
1253 size_t re_max_failures = 4000;
1254 # endif
1256 union fail_stack_elt
1258 re_char *pointer;
1259 /* This should be the biggest `int' that's no bigger than a pointer. */
1260 long integer;
1263 typedef union fail_stack_elt fail_stack_elt_t;
1265 typedef struct
1267 fail_stack_elt_t *stack;
1268 size_t size;
1269 size_t avail; /* Offset of next open position. */
1270 size_t frame; /* Offset of the cur constructed frame. */
1271 } fail_stack_type;
1273 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1276 /* Define macros to initialize and free the failure stack.
1277 Do `return -2' if the alloc fails. */
1279 #ifdef MATCH_MAY_ALLOCATE
1280 # define INIT_FAIL_STACK() \
1281 do { \
1282 fail_stack.stack = \
1283 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1284 * sizeof (fail_stack_elt_t)); \
1286 if (fail_stack.stack == NULL) \
1287 return -2; \
1289 fail_stack.size = INIT_FAILURE_ALLOC; \
1290 fail_stack.avail = 0; \
1291 fail_stack.frame = 0; \
1292 } while (0)
1293 #else
1294 # define INIT_FAIL_STACK() \
1295 do { \
1296 fail_stack.avail = 0; \
1297 fail_stack.frame = 0; \
1298 } while (0)
1300 # define RETALLOC_IF(addr, n, t) \
1301 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
1302 #endif
1305 /* Double the size of FAIL_STACK, up to a limit
1306 which allows approximately `re_max_failures' items.
1308 Return 1 if succeeds, and 0 if either ran out of memory
1309 allocating space for it or it was already too large.
1311 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1313 /* Factor to increase the failure stack size by
1314 when we increase it.
1315 This used to be 2, but 2 was too wasteful
1316 because the old discarded stacks added up to as much space
1317 were as ultimate, maximum-size stack. */
1318 #define FAIL_STACK_GROWTH_FACTOR 4
1320 #define GROW_FAIL_STACK(fail_stack) \
1321 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1322 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1323 ? 0 \
1324 : ((fail_stack).stack \
1325 = REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1326 (fail_stack).size * sizeof (fail_stack_elt_t), \
1327 min (re_max_failures * TYPICAL_FAILURE_SIZE, \
1328 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1329 * FAIL_STACK_GROWTH_FACTOR))), \
1331 (fail_stack).stack == NULL \
1332 ? 0 \
1333 : ((fail_stack).size \
1334 = (min (re_max_failures * TYPICAL_FAILURE_SIZE, \
1335 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1336 * FAIL_STACK_GROWTH_FACTOR)) \
1337 / sizeof (fail_stack_elt_t)), \
1338 1)))
1341 /* Push a pointer value onto the failure stack.
1342 Assumes the variable `fail_stack'. Probably should only
1343 be called from within `PUSH_FAILURE_POINT'. */
1344 #define PUSH_FAILURE_POINTER(item) \
1345 fail_stack.stack[fail_stack.avail++].pointer = (item)
1347 /* This pushes an integer-valued item onto the failure stack.
1348 Assumes the variable `fail_stack'. Probably should only
1349 be called from within `PUSH_FAILURE_POINT'. */
1350 #define PUSH_FAILURE_INT(item) \
1351 fail_stack.stack[fail_stack.avail++].integer = (item)
1353 /* These POP... operations complement the PUSH... operations.
1354 All assume that `fail_stack' is nonempty. */
1355 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1356 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1358 /* Individual items aside from the registers. */
1359 #define NUM_NONREG_ITEMS 3
1361 /* Used to examine the stack (to detect infinite loops). */
1362 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1363 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1364 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1365 #define TOP_FAILURE_HANDLE() fail_stack.frame
1368 #define ENSURE_FAIL_STACK(space) \
1369 while (REMAINING_AVAIL_SLOTS <= space) { \
1370 if (!GROW_FAIL_STACK (fail_stack)) \
1371 return -2; \
1372 DEBUG_PRINT ("\n Doubled stack; size now: %zd\n", (fail_stack).size);\
1373 DEBUG_PRINT (" slots available: %zd\n", REMAINING_AVAIL_SLOTS);\
1376 /* Push register NUM onto the stack. */
1377 #define PUSH_FAILURE_REG(num) \
1378 do { \
1379 char *destination; \
1380 long n = num; \
1381 ENSURE_FAIL_STACK(3); \
1382 DEBUG_PRINT (" Push reg %ld (spanning %p -> %p)\n", \
1383 n, regstart[n], regend[n]); \
1384 PUSH_FAILURE_POINTER (regstart[n]); \
1385 PUSH_FAILURE_POINTER (regend[n]); \
1386 PUSH_FAILURE_INT (n); \
1387 } while (0)
1389 /* Change the counter's value to VAL, but make sure that it will
1390 be reset when backtracking. */
1391 #define PUSH_NUMBER(ptr,val) \
1392 do { \
1393 char *destination; \
1394 int c; \
1395 ENSURE_FAIL_STACK(3); \
1396 EXTRACT_NUMBER (c, ptr); \
1397 DEBUG_PRINT (" Push number %p = %d -> %d\n", ptr, c, val); \
1398 PUSH_FAILURE_INT (c); \
1399 PUSH_FAILURE_POINTER (ptr); \
1400 PUSH_FAILURE_INT (-1); \
1401 STORE_NUMBER (ptr, val); \
1402 } while (0)
1404 /* Pop a saved register off the stack. */
1405 #define POP_FAILURE_REG_OR_COUNT() \
1406 do { \
1407 long pfreg = POP_FAILURE_INT (); \
1408 if (pfreg == -1) \
1410 /* It's a counter. */ \
1411 /* Here, we discard `const', making re_match non-reentrant. */ \
1412 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1413 pfreg = POP_FAILURE_INT (); \
1414 STORE_NUMBER (ptr, pfreg); \
1415 DEBUG_PRINT (" Pop counter %p = %ld\n", ptr, pfreg); \
1417 else \
1419 regend[pfreg] = POP_FAILURE_POINTER (); \
1420 regstart[pfreg] = POP_FAILURE_POINTER (); \
1421 DEBUG_PRINT (" Pop reg %ld (spanning %p -> %p)\n", \
1422 pfreg, regstart[pfreg], regend[pfreg]); \
1424 } while (0)
1426 /* Check that we are not stuck in an infinite loop. */
1427 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1428 do { \
1429 ssize_t failure = TOP_FAILURE_HANDLE (); \
1430 /* Check for infinite matching loops */ \
1431 while (failure > 0 \
1432 && (FAILURE_STR (failure) == string_place \
1433 || FAILURE_STR (failure) == NULL)) \
1435 assert (FAILURE_PAT (failure) >= bufp->buffer \
1436 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1437 if (FAILURE_PAT (failure) == pat_cur) \
1439 cycle = 1; \
1440 break; \
1442 DEBUG_PRINT (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1443 failure = NEXT_FAILURE_HANDLE(failure); \
1445 DEBUG_PRINT (" Other string: %p\n", FAILURE_STR (failure)); \
1446 } while (0)
1448 /* Push the information about the state we will need
1449 if we ever fail back to it.
1451 Requires variables fail_stack, regstart, regend and
1452 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1453 declared.
1455 Does `return FAILURE_CODE' if runs out of memory. */
1457 #define PUSH_FAILURE_POINT(pattern, string_place) \
1458 do { \
1459 char *destination; \
1460 /* Must be int, so when we don't save any registers, the arithmetic \
1461 of 0 + -1 isn't done as unsigned. */ \
1463 DEBUG_STATEMENT (nfailure_points_pushed++); \
1464 DEBUG_PRINT ("\nPUSH_FAILURE_POINT:\n"); \
1465 DEBUG_PRINT (" Before push, next avail: %zd\n", (fail_stack).avail); \
1466 DEBUG_PRINT (" size: %zd\n", (fail_stack).size);\
1468 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1470 DEBUG_PRINT ("\n"); \
1472 DEBUG_PRINT (" Push frame index: %zd\n", fail_stack.frame); \
1473 PUSH_FAILURE_INT (fail_stack.frame); \
1475 DEBUG_PRINT (" Push string %p: \"", string_place); \
1476 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1477 DEBUG_PRINT ("\"\n"); \
1478 PUSH_FAILURE_POINTER (string_place); \
1480 DEBUG_PRINT (" Push pattern %p: ", pattern); \
1481 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1482 PUSH_FAILURE_POINTER (pattern); \
1484 /* Close the frame by moving the frame pointer past it. */ \
1485 fail_stack.frame = fail_stack.avail; \
1486 } while (0)
1488 /* Estimate the size of data pushed by a typical failure stack entry.
1489 An estimate is all we need, because all we use this for
1490 is to choose a limit for how big to make the failure stack. */
1491 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1492 #define TYPICAL_FAILURE_SIZE 20
1494 /* How many items can still be added to the stack without overflowing it. */
1495 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1498 /* Pops what PUSH_FAIL_STACK pushes.
1500 We restore into the parameters, all of which should be lvalues:
1501 STR -- the saved data position.
1502 PAT -- the saved pattern position.
1503 REGSTART, REGEND -- arrays of string positions.
1505 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1506 `pend', `string1', `size1', `string2', and `size2'. */
1508 #define POP_FAILURE_POINT(str, pat) \
1509 do { \
1510 assert (!FAIL_STACK_EMPTY ()); \
1512 /* Remove failure points and point to how many regs pushed. */ \
1513 DEBUG_PRINT ("POP_FAILURE_POINT:\n"); \
1514 DEBUG_PRINT (" Before pop, next avail: %zd\n", fail_stack.avail); \
1515 DEBUG_PRINT (" size: %zd\n", fail_stack.size); \
1517 /* Pop the saved registers. */ \
1518 while (fail_stack.frame < fail_stack.avail) \
1519 POP_FAILURE_REG_OR_COUNT (); \
1521 pat = POP_FAILURE_POINTER (); \
1522 DEBUG_PRINT (" Popping pattern %p: ", pat); \
1523 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1525 /* If the saved string location is NULL, it came from an \
1526 on_failure_keep_string_jump opcode, and we want to throw away the \
1527 saved NULL, thus retaining our current position in the string. */ \
1528 str = POP_FAILURE_POINTER (); \
1529 DEBUG_PRINT (" Popping string %p: \"", str); \
1530 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1531 DEBUG_PRINT ("\"\n"); \
1533 fail_stack.frame = POP_FAILURE_INT (); \
1534 DEBUG_PRINT (" Popping frame index: %zd\n", fail_stack.frame); \
1536 assert (fail_stack.avail >= 0); \
1537 assert (fail_stack.frame <= fail_stack.avail); \
1539 DEBUG_STATEMENT (nfailure_points_popped++); \
1540 } while (0) /* POP_FAILURE_POINT */
1544 /* Registers are set to a sentinel when they haven't yet matched. */
1545 #define REG_UNSET(e) ((e) == NULL)
1547 /* Subroutine declarations and macros for regex_compile. */
1549 static reg_errcode_t regex_compile (re_char *pattern, size_t size,
1550 #ifdef emacs
1551 bool posix_backtracking,
1552 const char *whitespace_regexp,
1553 #else
1554 reg_syntax_t syntax,
1555 #endif
1556 struct re_pattern_buffer *bufp);
1557 static void store_op1 (re_opcode_t op, unsigned char *loc, int arg);
1558 static void store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
1559 static void insert_op1 (re_opcode_t op, unsigned char *loc,
1560 int arg, unsigned char *end);
1561 static void insert_op2 (re_opcode_t op, unsigned char *loc,
1562 int arg1, int arg2, unsigned char *end);
1563 static boolean at_begline_loc_p (re_char *pattern, re_char *p,
1564 reg_syntax_t syntax);
1565 static boolean at_endline_loc_p (re_char *p, re_char *pend,
1566 reg_syntax_t syntax);
1567 static re_char *skip_one_char (re_char *p);
1568 static int analyze_first (re_char *p, re_char *pend,
1569 char *fastmap, const int multibyte);
1571 /* Fetch the next character in the uncompiled pattern, with no
1572 translation. */
1573 #define PATFETCH(c) \
1574 do { \
1575 int len; \
1576 if (p == pend) return REG_EEND; \
1577 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1578 p += len; \
1579 } while (0)
1582 /* If `translate' is non-null, return translate[D], else just D. We
1583 cast the subscript to translate because some data is declared as
1584 `char *', to avoid warnings when a string constant is passed. But
1585 when we use a character as a subscript we must make it unsigned. */
1586 #ifndef TRANSLATE
1587 # define TRANSLATE(d) \
1588 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1589 #endif
1592 /* Macros for outputting the compiled pattern into `buffer'. */
1594 /* If the buffer isn't allocated when it comes in, use this. */
1595 #define INIT_BUF_SIZE 32
1597 /* Make sure we have at least N more bytes of space in buffer. */
1598 #define GET_BUFFER_SPACE(n) \
1599 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1600 EXTEND_BUFFER ()
1602 /* Make sure we have one more byte of buffer space and then add C to it. */
1603 #define BUF_PUSH(c) \
1604 do { \
1605 GET_BUFFER_SPACE (1); \
1606 *b++ = (unsigned char) (c); \
1607 } while (0)
1610 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1611 #define BUF_PUSH_2(c1, c2) \
1612 do { \
1613 GET_BUFFER_SPACE (2); \
1614 *b++ = (unsigned char) (c1); \
1615 *b++ = (unsigned char) (c2); \
1616 } while (0)
1619 /* Store a jump with opcode OP at LOC to location TO. We store a
1620 relative address offset by the three bytes the jump itself occupies. */
1621 #define STORE_JUMP(op, loc, to) \
1622 store_op1 (op, loc, (to) - (loc) - 3)
1624 /* Likewise, for a two-argument jump. */
1625 #define STORE_JUMP2(op, loc, to, arg) \
1626 store_op2 (op, loc, (to) - (loc) - 3, arg)
1628 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1629 #define INSERT_JUMP(op, loc, to) \
1630 insert_op1 (op, loc, (to) - (loc) - 3, b)
1632 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1633 #define INSERT_JUMP2(op, loc, to, arg) \
1634 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1637 /* This is not an arbitrary limit: the arguments which represent offsets
1638 into the pattern are two bytes long. So if 2^15 bytes turns out to
1639 be too small, many things would have to change. */
1640 # define MAX_BUF_SIZE (1L << 15)
1642 /* Extend the buffer by twice its current size via realloc and
1643 reset the pointers that pointed into the old block to point to the
1644 correct places in the new one. If extending the buffer results in it
1645 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1646 #define EXTEND_BUFFER() \
1647 do { \
1648 unsigned char *old_buffer = bufp->buffer; \
1649 if (bufp->allocated == MAX_BUF_SIZE) \
1650 return REG_ESIZE; \
1651 bufp->allocated <<= 1; \
1652 if (bufp->allocated > MAX_BUF_SIZE) \
1653 bufp->allocated = MAX_BUF_SIZE; \
1654 ptrdiff_t b_off = b - old_buffer; \
1655 ptrdiff_t begalt_off = begalt - old_buffer; \
1656 bool fixup_alt_jump_set = !!fixup_alt_jump; \
1657 bool laststart_set = !!laststart; \
1658 bool pending_exact_set = !!pending_exact; \
1659 ptrdiff_t fixup_alt_jump_off, laststart_off, pending_exact_off; \
1660 if (fixup_alt_jump_set) fixup_alt_jump_off = fixup_alt_jump - old_buffer; \
1661 if (laststart_set) laststart_off = laststart - old_buffer; \
1662 if (pending_exact_set) pending_exact_off = pending_exact - old_buffer; \
1663 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1664 if (bufp->buffer == NULL) \
1665 return REG_ESPACE; \
1666 unsigned char *new_buffer = bufp->buffer; \
1667 b = new_buffer + b_off; \
1668 begalt = new_buffer + begalt_off; \
1669 if (fixup_alt_jump_set) fixup_alt_jump = new_buffer + fixup_alt_jump_off; \
1670 if (laststart_set) laststart = new_buffer + laststart_off; \
1671 if (pending_exact_set) pending_exact = new_buffer + pending_exact_off; \
1672 } while (0)
1675 /* Since we have one byte reserved for the register number argument to
1676 {start,stop}_memory, the maximum number of groups we can report
1677 things about is what fits in that byte. */
1678 #define MAX_REGNUM 255
1680 /* But patterns can have more than `MAX_REGNUM' registers. We just
1681 ignore the excess. */
1682 typedef int regnum_t;
1685 /* Macros for the compile stack. */
1687 /* Since offsets can go either forwards or backwards, this type needs to
1688 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1689 /* int may be not enough when sizeof(int) == 2. */
1690 typedef long pattern_offset_t;
1692 typedef struct
1694 pattern_offset_t begalt_offset;
1695 pattern_offset_t fixup_alt_jump;
1696 pattern_offset_t laststart_offset;
1697 regnum_t regnum;
1698 } compile_stack_elt_t;
1701 typedef struct
1703 compile_stack_elt_t *stack;
1704 size_t size;
1705 size_t avail; /* Offset of next open position. */
1706 } compile_stack_type;
1709 #define INIT_COMPILE_STACK_SIZE 32
1711 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1712 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1714 /* The next available element. */
1715 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1717 /* Explicit quit checking is needed for Emacs, which uses polling to
1718 process input events. */
1719 #ifdef emacs
1720 # define IMMEDIATE_QUIT_CHECK \
1721 do { \
1722 if (immediate_quit) QUIT; \
1723 } while (0)
1724 #else
1725 # define IMMEDIATE_QUIT_CHECK ((void)0)
1726 #endif
1728 /* Structure to manage work area for range table. */
1729 struct range_table_work_area
1731 int *table; /* actual work area. */
1732 int allocated; /* allocated size for work area in bytes. */
1733 int used; /* actually used size in words. */
1734 int bits; /* flag to record character classes */
1737 #ifdef emacs
1739 /* Make sure that WORK_AREA can hold more N multibyte characters.
1740 This is used only in set_image_of_range and set_image_of_range_1.
1741 It expects WORK_AREA to be a pointer.
1742 If it can't get the space, it returns from the surrounding function. */
1744 #define EXTEND_RANGE_TABLE(work_area, n) \
1745 do { \
1746 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1748 extend_range_table_work_area (&work_area); \
1749 if ((work_area).table == 0) \
1750 return (REG_ESPACE); \
1752 } while (0)
1754 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1755 (work_area).bits |= (bit)
1757 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1758 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1759 do { \
1760 EXTEND_RANGE_TABLE ((work_area), 2); \
1761 (work_area).table[(work_area).used++] = (range_start); \
1762 (work_area).table[(work_area).used++] = (range_end); \
1763 } while (0)
1765 #endif /* emacs */
1767 /* Free allocated memory for WORK_AREA. */
1768 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1769 do { \
1770 if ((work_area).table) \
1771 free ((work_area).table); \
1772 } while (0)
1774 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1775 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1776 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1777 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1779 /* Bits used to implement the multibyte-part of the various character classes
1780 such as [:alnum:] in a charset's range table. The code currently assumes
1781 that only the low 16 bits are used. */
1782 #define BIT_WORD 0x1
1783 #define BIT_LOWER 0x2
1784 #define BIT_PUNCT 0x4
1785 #define BIT_SPACE 0x8
1786 #define BIT_UPPER 0x10
1787 #define BIT_MULTIBYTE 0x20
1788 #define BIT_ALPHA 0x40
1789 #define BIT_ALNUM 0x80
1790 #define BIT_GRAPH 0x100
1791 #define BIT_PRINT 0x200
1794 /* Set the bit for character C in a list. */
1795 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1798 #ifdef emacs
1800 /* Store characters in the range FROM to TO in the bitmap at B (for
1801 ASCII and unibyte characters) and WORK_AREA (for multibyte
1802 characters) while translating them and paying attention to the
1803 continuity of translated characters.
1805 Implementation note: It is better to implement these fairly big
1806 macros by a function, but it's not that easy because macros called
1807 in this macro assume various local variables already declared. */
1809 /* Both FROM and TO are ASCII characters. */
1811 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
1812 do { \
1813 int C0, C1; \
1815 for (C0 = (FROM); C0 <= (TO); C0++) \
1817 C1 = TRANSLATE (C0); \
1818 if (! ASCII_CHAR_P (C1)) \
1820 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1821 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
1822 C1 = C0; \
1824 SET_LIST_BIT (C1); \
1826 } while (0)
1829 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
1831 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
1832 do { \
1833 int C0, C1, C2, I; \
1834 int USED = RANGE_TABLE_WORK_USED (work_area); \
1836 for (C0 = (FROM); C0 <= (TO); C0++) \
1838 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
1839 if (CHAR_BYTE8_P (C1)) \
1840 SET_LIST_BIT (C0); \
1841 else \
1843 C2 = TRANSLATE (C1); \
1844 if (C2 == C1 \
1845 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
1846 C1 = C0; \
1847 SET_LIST_BIT (C1); \
1848 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1850 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1851 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1853 if (C2 >= from - 1 && C2 <= to + 1) \
1855 if (C2 == from - 1) \
1856 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1857 else if (C2 == to + 1) \
1858 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1859 break; \
1862 if (I < USED) \
1863 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
1866 } while (0)
1869 /* Both FROM and TO are multibyte characters. */
1871 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
1872 do { \
1873 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
1875 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
1876 for (C0 = (FROM); C0 <= (TO); C0++) \
1878 C1 = TRANSLATE (C0); \
1879 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
1880 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
1881 SET_LIST_BIT (C2); \
1882 if (C1 >= (FROM) && C1 <= (TO)) \
1883 continue; \
1884 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
1886 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
1887 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
1889 if (C1 >= from - 1 && C1 <= to + 1) \
1891 if (C1 == from - 1) \
1892 RANGE_TABLE_WORK_ELT (work_area, I)--; \
1893 else if (C1 == to + 1) \
1894 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
1895 break; \
1898 if (I < USED) \
1899 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
1901 } while (0)
1903 #endif /* emacs */
1905 /* Get the next unsigned number in the uncompiled pattern. */
1906 #define GET_INTERVAL_COUNT(num) \
1907 do { \
1908 if (p == pend) \
1909 FREE_STACK_RETURN (REG_EBRACE); \
1910 else \
1912 PATFETCH (c); \
1913 while ('0' <= c && c <= '9') \
1915 if (num < 0) \
1916 num = 0; \
1917 if (RE_DUP_MAX / 10 - (RE_DUP_MAX % 10 < c - '0') < num) \
1918 FREE_STACK_RETURN (REG_BADBR); \
1919 num = num * 10 + c - '0'; \
1920 if (p == pend) \
1921 FREE_STACK_RETURN (REG_EBRACE); \
1922 PATFETCH (c); \
1925 } while (0)
1927 #if ! WIDE_CHAR_SUPPORT
1929 /* Parse a character class, i.e. string such as "[:name:]". *strp
1930 points to the string to be parsed and limit is length, in bytes, of
1931 that string.
1933 If *strp point to a string that begins with "[:name:]", where name is
1934 a non-empty sequence of lower case letters, *strp will be advanced past the
1935 closing square bracket and RECC_* constant which maps to the name will be
1936 returned. If name is not a valid character class name zero, or RECC_ERROR,
1937 is returned.
1939 Otherwise, if *strp doesn’t begin with "[:name:]", -1 is returned.
1941 The function can be used on ASCII and multibyte (UTF-8-encoded) strings.
1943 re_wctype_t
1944 re_wctype_parse (const unsigned char **strp, unsigned limit)
1946 const char *beg = (const char *)*strp, *it;
1948 if (limit < 4 || beg[0] != '[' || beg[1] != ':')
1949 return -1;
1951 beg += 2; /* skip opening ‘[:’ */
1952 limit -= 3; /* opening ‘[:’ and half of closing ‘:]’; --limit handles rest */
1953 for (it = beg; it[0] != ':' || it[1] != ']'; ++it)
1954 if (!--limit)
1955 return -1;
1957 *strp = (const unsigned char *)(it + 2);
1959 /* Sort tests in the length=five case by frequency the classes to minimize
1960 number of times we fail the comparison. The frequencies of character class
1961 names used in Emacs sources as of 2016-07-27:
1963 $ find \( -name \*.c -o -name \*.el \) -exec grep -h '\[:[a-z]*:]' {} + |
1964 sed 's/]/]\n/g' |grep -o '\[:[a-z]*:]' |sort |uniq -c |sort -nr
1965 213 [:alnum:]
1966 104 [:alpha:]
1967 62 [:space:]
1968 39 [:digit:]
1969 36 [:blank:]
1970 26 [:word:]
1971 26 [:upper:]
1972 21 [:lower:]
1973 10 [:xdigit:]
1974 10 [:punct:]
1975 10 [:ascii:]
1976 4 [:nonascii:]
1977 4 [:graph:]
1978 2 [:print:]
1979 2 [:cntrl:]
1980 1 [:ff:]
1982 If you update this list, consider also updating chain of or’ed conditions
1983 in execute_charset function.
1986 switch (it - beg) {
1987 case 4:
1988 if (!memcmp (beg, "word", 4)) return RECC_WORD;
1989 break;
1990 case 5:
1991 if (!memcmp (beg, "alnum", 5)) return RECC_ALNUM;
1992 if (!memcmp (beg, "alpha", 5)) return RECC_ALPHA;
1993 if (!memcmp (beg, "space", 5)) return RECC_SPACE;
1994 if (!memcmp (beg, "digit", 5)) return RECC_DIGIT;
1995 if (!memcmp (beg, "blank", 5)) return RECC_BLANK;
1996 if (!memcmp (beg, "upper", 5)) return RECC_UPPER;
1997 if (!memcmp (beg, "lower", 5)) return RECC_LOWER;
1998 if (!memcmp (beg, "punct", 5)) return RECC_PUNCT;
1999 if (!memcmp (beg, "ascii", 5)) return RECC_ASCII;
2000 if (!memcmp (beg, "graph", 5)) return RECC_GRAPH;
2001 if (!memcmp (beg, "print", 5)) return RECC_PRINT;
2002 if (!memcmp (beg, "cntrl", 5)) return RECC_CNTRL;
2003 break;
2004 case 6:
2005 if (!memcmp (beg, "xdigit", 6)) return RECC_XDIGIT;
2006 break;
2007 case 7:
2008 if (!memcmp (beg, "unibyte", 7)) return RECC_UNIBYTE;
2009 break;
2010 case 8:
2011 if (!memcmp (beg, "nonascii", 8)) return RECC_NONASCII;
2012 break;
2013 case 9:
2014 if (!memcmp (beg, "multibyte", 9)) return RECC_MULTIBYTE;
2015 break;
2018 return RECC_ERROR;
2021 /* True if CH is in the char class CC. */
2022 boolean
2023 re_iswctype (int ch, re_wctype_t cc)
2025 switch (cc)
2027 case RECC_ALNUM: return ISALNUM (ch) != 0;
2028 case RECC_ALPHA: return ISALPHA (ch) != 0;
2029 case RECC_BLANK: return ISBLANK (ch) != 0;
2030 case RECC_CNTRL: return ISCNTRL (ch) != 0;
2031 case RECC_DIGIT: return ISDIGIT (ch) != 0;
2032 case RECC_GRAPH: return ISGRAPH (ch) != 0;
2033 case RECC_LOWER: return ISLOWER (ch) != 0;
2034 case RECC_PRINT: return ISPRINT (ch) != 0;
2035 case RECC_PUNCT: return ISPUNCT (ch) != 0;
2036 case RECC_SPACE: return ISSPACE (ch) != 0;
2037 case RECC_UPPER: return ISUPPER (ch) != 0;
2038 case RECC_XDIGIT: return ISXDIGIT (ch) != 0;
2039 case RECC_ASCII: return IS_REAL_ASCII (ch) != 0;
2040 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2041 case RECC_UNIBYTE: return ISUNIBYTE (ch) != 0;
2042 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2043 case RECC_WORD: return ISWORD (ch) != 0;
2044 case RECC_ERROR: return false;
2045 default:
2046 abort ();
2050 /* Return a bit-pattern to use in the range-table bits to match multibyte
2051 chars of class CC. */
2052 static int
2053 re_wctype_to_bit (re_wctype_t cc)
2055 switch (cc)
2057 case RECC_NONASCII:
2058 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2059 case RECC_ALPHA: return BIT_ALPHA;
2060 case RECC_ALNUM: return BIT_ALNUM;
2061 case RECC_WORD: return BIT_WORD;
2062 case RECC_LOWER: return BIT_LOWER;
2063 case RECC_UPPER: return BIT_UPPER;
2064 case RECC_PUNCT: return BIT_PUNCT;
2065 case RECC_SPACE: return BIT_SPACE;
2066 case RECC_GRAPH: return BIT_GRAPH;
2067 case RECC_PRINT: return BIT_PRINT;
2068 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2069 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2070 default:
2071 abort ();
2074 #endif
2076 /* Filling in the work area of a range. */
2078 /* Actually extend the space in WORK_AREA. */
2080 static void
2081 extend_range_table_work_area (struct range_table_work_area *work_area)
2083 work_area->allocated += 16 * sizeof (int);
2084 work_area->table = realloc (work_area->table, work_area->allocated);
2087 #if 0
2088 #ifdef emacs
2090 /* Carefully find the ranges of codes that are equivalent
2091 under case conversion to the range start..end when passed through
2092 TRANSLATE. Handle the case where non-letters can come in between
2093 two upper-case letters (which happens in Latin-1).
2094 Also handle the case of groups of more than 2 case-equivalent chars.
2096 The basic method is to look at consecutive characters and see
2097 if they can form a run that can be handled as one.
2099 Returns -1 if successful, REG_ESPACE if ran out of space. */
2101 static int
2102 set_image_of_range_1 (struct range_table_work_area *work_area,
2103 re_wchar_t start, re_wchar_t end,
2104 RE_TRANSLATE_TYPE translate)
2106 /* `one_case' indicates a character, or a run of characters,
2107 each of which is an isolate (no case-equivalents).
2108 This includes all ASCII non-letters.
2110 `two_case' indicates a character, or a run of characters,
2111 each of which has two case-equivalent forms.
2112 This includes all ASCII letters.
2114 `strange' indicates a character that has more than one
2115 case-equivalent. */
2117 enum case_type {one_case, two_case, strange};
2119 /* Describe the run that is in progress,
2120 which the next character can try to extend.
2121 If run_type is strange, that means there really is no run.
2122 If run_type is one_case, then run_start...run_end is the run.
2123 If run_type is two_case, then the run is run_start...run_end,
2124 and the case-equivalents end at run_eqv_end. */
2126 enum case_type run_type = strange;
2127 int run_start, run_end, run_eqv_end;
2129 Lisp_Object eqv_table;
2131 if (!RE_TRANSLATE_P (translate))
2133 EXTEND_RANGE_TABLE (work_area, 2);
2134 work_area->table[work_area->used++] = (start);
2135 work_area->table[work_area->used++] = (end);
2136 return -1;
2139 eqv_table = XCHAR_TABLE (translate)->extras[2];
2141 for (; start <= end; start++)
2143 enum case_type this_type;
2144 int eqv = RE_TRANSLATE (eqv_table, start);
2145 int minchar, maxchar;
2147 /* Classify this character */
2148 if (eqv == start)
2149 this_type = one_case;
2150 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2151 this_type = two_case;
2152 else
2153 this_type = strange;
2155 if (start < eqv)
2156 minchar = start, maxchar = eqv;
2157 else
2158 minchar = eqv, maxchar = start;
2160 /* Can this character extend the run in progress? */
2161 if (this_type == strange || this_type != run_type
2162 || !(minchar == run_end + 1
2163 && (run_type == two_case
2164 ? maxchar == run_eqv_end + 1 : 1)))
2166 /* No, end the run.
2167 Record each of its equivalent ranges. */
2168 if (run_type == one_case)
2170 EXTEND_RANGE_TABLE (work_area, 2);
2171 work_area->table[work_area->used++] = run_start;
2172 work_area->table[work_area->used++] = run_end;
2174 else if (run_type == two_case)
2176 EXTEND_RANGE_TABLE (work_area, 4);
2177 work_area->table[work_area->used++] = run_start;
2178 work_area->table[work_area->used++] = run_end;
2179 work_area->table[work_area->used++]
2180 = RE_TRANSLATE (eqv_table, run_start);
2181 work_area->table[work_area->used++]
2182 = RE_TRANSLATE (eqv_table, run_end);
2184 run_type = strange;
2187 if (this_type == strange)
2189 /* For a strange character, add each of its equivalents, one
2190 by one. Don't start a range. */
2193 EXTEND_RANGE_TABLE (work_area, 2);
2194 work_area->table[work_area->used++] = eqv;
2195 work_area->table[work_area->used++] = eqv;
2196 eqv = RE_TRANSLATE (eqv_table, eqv);
2198 while (eqv != start);
2201 /* Add this char to the run, or start a new run. */
2202 else if (run_type == strange)
2204 /* Initialize a new range. */
2205 run_type = this_type;
2206 run_start = start;
2207 run_end = start;
2208 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2210 else
2212 /* Extend a running range. */
2213 run_end = minchar;
2214 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2218 /* If a run is still in progress at the end, finish it now
2219 by recording its equivalent ranges. */
2220 if (run_type == one_case)
2222 EXTEND_RANGE_TABLE (work_area, 2);
2223 work_area->table[work_area->used++] = run_start;
2224 work_area->table[work_area->used++] = run_end;
2226 else if (run_type == two_case)
2228 EXTEND_RANGE_TABLE (work_area, 4);
2229 work_area->table[work_area->used++] = run_start;
2230 work_area->table[work_area->used++] = run_end;
2231 work_area->table[work_area->used++]
2232 = RE_TRANSLATE (eqv_table, run_start);
2233 work_area->table[work_area->used++]
2234 = RE_TRANSLATE (eqv_table, run_end);
2237 return -1;
2240 #endif /* emacs */
2242 /* Record the image of the range start..end when passed through
2243 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2244 and is not even necessarily contiguous.
2245 Normally we approximate it with the smallest contiguous range that contains
2246 all the chars we need. However, for Latin-1 we go to extra effort
2247 to do a better job.
2249 This function is not called for ASCII ranges.
2251 Returns -1 if successful, REG_ESPACE if ran out of space. */
2253 static int
2254 set_image_of_range (struct range_table_work_area *work_area,
2255 re_wchar_t start, re_wchar_t end,
2256 RE_TRANSLATE_TYPE translate)
2258 re_wchar_t cmin, cmax;
2260 #ifdef emacs
2261 /* For Latin-1 ranges, use set_image_of_range_1
2262 to get proper handling of ranges that include letters and nonletters.
2263 For a range that includes the whole of Latin-1, this is not necessary.
2264 For other character sets, we don't bother to get this right. */
2265 if (RE_TRANSLATE_P (translate) && start < 04400
2266 && !(start < 04200 && end >= 04377))
2268 int newend;
2269 int tem;
2270 newend = end;
2271 if (newend > 04377)
2272 newend = 04377;
2273 tem = set_image_of_range_1 (work_area, start, newend, translate);
2274 if (tem > 0)
2275 return tem;
2277 start = 04400;
2278 if (end < 04400)
2279 return -1;
2281 #endif
2283 EXTEND_RANGE_TABLE (work_area, 2);
2284 work_area->table[work_area->used++] = (start);
2285 work_area->table[work_area->used++] = (end);
2287 cmin = -1, cmax = -1;
2289 if (RE_TRANSLATE_P (translate))
2291 int ch;
2293 for (ch = start; ch <= end; ch++)
2295 re_wchar_t c = TRANSLATE (ch);
2296 if (! (start <= c && c <= end))
2298 if (cmin == -1)
2299 cmin = c, cmax = c;
2300 else
2302 cmin = min (cmin, c);
2303 cmax = max (cmax, c);
2308 if (cmin != -1)
2310 EXTEND_RANGE_TABLE (work_area, 2);
2311 work_area->table[work_area->used++] = (cmin);
2312 work_area->table[work_area->used++] = (cmax);
2316 return -1;
2318 #endif /* 0 */
2320 #ifndef MATCH_MAY_ALLOCATE
2322 /* If we cannot allocate large objects within re_match_2_internal,
2323 we make the fail stack and register vectors global.
2324 The fail stack, we grow to the maximum size when a regexp
2325 is compiled.
2326 The register vectors, we adjust in size each time we
2327 compile a regexp, according to the number of registers it needs. */
2329 static fail_stack_type fail_stack;
2331 /* Size with which the following vectors are currently allocated.
2332 That is so we can make them bigger as needed,
2333 but never make them smaller. */
2334 static int regs_allocated_size;
2336 static re_char ** regstart, ** regend;
2337 static re_char **best_regstart, **best_regend;
2339 /* Make the register vectors big enough for NUM_REGS registers,
2340 but don't make them smaller. */
2342 static
2343 regex_grow_registers (int num_regs)
2345 if (num_regs > regs_allocated_size)
2347 RETALLOC_IF (regstart, num_regs, re_char *);
2348 RETALLOC_IF (regend, num_regs, re_char *);
2349 RETALLOC_IF (best_regstart, num_regs, re_char *);
2350 RETALLOC_IF (best_regend, num_regs, re_char *);
2352 regs_allocated_size = num_regs;
2356 #endif /* not MATCH_MAY_ALLOCATE */
2358 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2359 regnum_t regnum);
2361 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2362 Returns one of error codes defined in `regex.h', or zero for success.
2364 If WHITESPACE_REGEXP is given (only #ifdef emacs), it is used instead of
2365 a space character in PATTERN.
2367 Assumes the `allocated' (and perhaps `buffer') and `translate'
2368 fields are set in BUFP on entry.
2370 If it succeeds, results are put in BUFP (if it returns an error, the
2371 contents of BUFP are undefined):
2372 `buffer' is the compiled pattern;
2373 `syntax' is set to SYNTAX;
2374 `used' is set to the length of the compiled pattern;
2375 `fastmap_accurate' is zero;
2376 `re_nsub' is the number of subexpressions in PATTERN;
2377 `not_bol' and `not_eol' are zero;
2379 The `fastmap' field is neither examined nor set. */
2381 /* Insert the `jump' from the end of last alternative to "here".
2382 The space for the jump has already been allocated. */
2383 #define FIXUP_ALT_JUMP() \
2384 do { \
2385 if (fixup_alt_jump) \
2386 STORE_JUMP (jump, fixup_alt_jump, b); \
2387 } while (0)
2390 /* Return, freeing storage we allocated. */
2391 #define FREE_STACK_RETURN(value) \
2392 do { \
2393 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2394 free (compile_stack.stack); \
2395 return value; \
2396 } while (0)
2398 static reg_errcode_t
2399 regex_compile (const_re_char *pattern, size_t size,
2400 #ifdef emacs
2401 # define syntax RE_SYNTAX_EMACS
2402 bool posix_backtracking,
2403 const char *whitespace_regexp,
2404 #else
2405 reg_syntax_t syntax,
2406 # define posix_backtracking (!(syntax & RE_NO_POSIX_BACKTRACKING))
2407 #endif
2408 struct re_pattern_buffer *bufp)
2410 /* We fetch characters from PATTERN here. */
2411 register re_wchar_t c, c1;
2413 /* Points to the end of the buffer, where we should append. */
2414 register unsigned char *b;
2416 /* Keeps track of unclosed groups. */
2417 compile_stack_type compile_stack;
2419 /* Points to the current (ending) position in the pattern. */
2420 #ifdef AIX
2421 /* `const' makes AIX compiler fail. */
2422 unsigned char *p = pattern;
2423 #else
2424 re_char *p = pattern;
2425 #endif
2426 re_char *pend = pattern + size;
2428 /* How to translate the characters in the pattern. */
2429 RE_TRANSLATE_TYPE translate = bufp->translate;
2431 /* Address of the count-byte of the most recently inserted `exactn'
2432 command. This makes it possible to tell if a new exact-match
2433 character can be added to that command or if the character requires
2434 a new `exactn' command. */
2435 unsigned char *pending_exact = 0;
2437 /* Address of start of the most recently finished expression.
2438 This tells, e.g., postfix * where to find the start of its
2439 operand. Reset at the beginning of groups and alternatives. */
2440 unsigned char *laststart = 0;
2442 /* Address of beginning of regexp, or inside of last group. */
2443 unsigned char *begalt;
2445 /* Place in the uncompiled pattern (i.e., the {) to
2446 which to go back if the interval is invalid. */
2447 re_char *beg_interval;
2449 /* Address of the place where a forward jump should go to the end of
2450 the containing expression. Each alternative of an `or' -- except the
2451 last -- ends with a forward jump of this sort. */
2452 unsigned char *fixup_alt_jump = 0;
2454 /* Work area for range table of charset. */
2455 struct range_table_work_area range_table_work;
2457 /* If the object matched can contain multibyte characters. */
2458 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2460 #ifdef emacs
2461 /* Nonzero if we have pushed down into a subpattern. */
2462 int in_subpattern = 0;
2464 /* These hold the values of p, pattern, and pend from the main
2465 pattern when we have pushed into a subpattern. */
2466 re_char *main_p;
2467 re_char *main_pattern;
2468 re_char *main_pend;
2469 #endif
2471 #ifdef DEBUG
2472 debug++;
2473 DEBUG_PRINT ("\nCompiling pattern: ");
2474 if (debug > 0)
2476 unsigned debug_count;
2478 for (debug_count = 0; debug_count < size; debug_count++)
2479 putchar (pattern[debug_count]);
2480 putchar ('\n');
2482 #endif /* DEBUG */
2484 /* Initialize the compile stack. */
2485 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2486 if (compile_stack.stack == NULL)
2487 return REG_ESPACE;
2489 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2490 compile_stack.avail = 0;
2492 range_table_work.table = 0;
2493 range_table_work.allocated = 0;
2495 /* Initialize the pattern buffer. */
2496 #ifndef emacs
2497 bufp->syntax = syntax;
2498 #endif
2499 bufp->fastmap_accurate = 0;
2500 bufp->not_bol = bufp->not_eol = 0;
2501 bufp->used_syntax = 0;
2503 /* Set `used' to zero, so that if we return an error, the pattern
2504 printer (for debugging) will think there's no pattern. We reset it
2505 at the end. */
2506 bufp->used = 0;
2508 /* Always count groups, whether or not bufp->no_sub is set. */
2509 bufp->re_nsub = 0;
2511 #if !defined emacs && !defined SYNTAX_TABLE
2512 /* Initialize the syntax table. */
2513 init_syntax_once ();
2514 #endif
2516 if (bufp->allocated == 0)
2518 if (bufp->buffer)
2519 { /* If zero allocated, but buffer is non-null, try to realloc
2520 enough space. This loses if buffer's address is bogus, but
2521 that is the user's responsibility. */
2522 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2524 else
2525 { /* Caller did not allocate a buffer. Do it for them. */
2526 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2528 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2530 bufp->allocated = INIT_BUF_SIZE;
2533 begalt = b = bufp->buffer;
2535 /* Loop through the uncompiled pattern until we're at the end. */
2536 while (1)
2538 if (p == pend)
2540 #ifdef emacs
2541 /* If this is the end of an included regexp,
2542 pop back to the main regexp and try again. */
2543 if (in_subpattern)
2545 in_subpattern = 0;
2546 pattern = main_pattern;
2547 p = main_p;
2548 pend = main_pend;
2549 continue;
2551 #endif
2552 /* If this is the end of the main regexp, we are done. */
2553 break;
2556 PATFETCH (c);
2558 switch (c)
2560 #ifdef emacs
2561 case ' ':
2563 re_char *p1 = p;
2565 /* If there's no special whitespace regexp, treat
2566 spaces normally. And don't try to do this recursively. */
2567 if (!whitespace_regexp || in_subpattern)
2568 goto normal_char;
2570 /* Peek past following spaces. */
2571 while (p1 != pend)
2573 if (*p1 != ' ')
2574 break;
2575 p1++;
2577 /* If the spaces are followed by a repetition op,
2578 treat them normally. */
2579 if (p1 != pend
2580 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2581 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2582 goto normal_char;
2584 /* Replace the spaces with the whitespace regexp. */
2585 in_subpattern = 1;
2586 main_p = p1;
2587 main_pend = pend;
2588 main_pattern = pattern;
2589 p = pattern = (re_char *) whitespace_regexp;
2590 pend = p + strlen (whitespace_regexp);
2591 break;
2593 #endif
2595 case '^':
2597 if ( /* If at start of pattern, it's an operator. */
2598 p == pattern + 1
2599 /* If context independent, it's an operator. */
2600 || syntax & RE_CONTEXT_INDEP_ANCHORS
2601 /* Otherwise, depends on what's come before. */
2602 || at_begline_loc_p (pattern, p, syntax))
2603 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2604 else
2605 goto normal_char;
2607 break;
2610 case '$':
2612 if ( /* If at end of pattern, it's an operator. */
2613 p == pend
2614 /* If context independent, it's an operator. */
2615 || syntax & RE_CONTEXT_INDEP_ANCHORS
2616 /* Otherwise, depends on what's next. */
2617 || at_endline_loc_p (p, pend, syntax))
2618 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2619 else
2620 goto normal_char;
2622 break;
2625 case '+':
2626 case '?':
2627 if ((syntax & RE_BK_PLUS_QM)
2628 || (syntax & RE_LIMITED_OPS))
2629 goto normal_char;
2630 handle_plus:
2631 case '*':
2632 /* If there is no previous pattern... */
2633 if (!laststart)
2635 if (syntax & RE_CONTEXT_INVALID_OPS)
2636 FREE_STACK_RETURN (REG_BADRPT);
2637 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2638 goto normal_char;
2642 /* 1 means zero (many) matches is allowed. */
2643 boolean zero_times_ok = 0, many_times_ok = 0;
2644 boolean greedy = 1;
2646 /* If there is a sequence of repetition chars, collapse it
2647 down to just one (the right one). We can't combine
2648 interval operators with these because of, e.g., `a{2}*',
2649 which should only match an even number of `a's. */
2651 for (;;)
2653 if ((syntax & RE_FRUGAL)
2654 && c == '?' && (zero_times_ok || many_times_ok))
2655 greedy = 0;
2656 else
2658 zero_times_ok |= c != '+';
2659 many_times_ok |= c != '?';
2662 if (p == pend)
2663 break;
2664 else if (*p == '*'
2665 || (!(syntax & RE_BK_PLUS_QM)
2666 && (*p == '+' || *p == '?')))
2668 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2670 if (p+1 == pend)
2671 FREE_STACK_RETURN (REG_EESCAPE);
2672 if (p[1] == '+' || p[1] == '?')
2673 PATFETCH (c); /* Gobble up the backslash. */
2674 else
2675 break;
2677 else
2678 break;
2679 /* If we get here, we found another repeat character. */
2680 PATFETCH (c);
2683 /* Star, etc. applied to an empty pattern is equivalent
2684 to an empty pattern. */
2685 if (!laststart || laststart == b)
2686 break;
2688 /* Now we know whether or not zero matches is allowed
2689 and also whether or not two or more matches is allowed. */
2690 if (greedy)
2692 if (many_times_ok)
2694 boolean simple = skip_one_char (laststart) == b;
2695 size_t startoffset = 0;
2696 re_opcode_t ofj =
2697 /* Check if the loop can match the empty string. */
2698 (simple || !analyze_first (laststart, b, NULL, 0))
2699 ? on_failure_jump : on_failure_jump_loop;
2700 assert (skip_one_char (laststart) <= b);
2702 if (!zero_times_ok && simple)
2703 { /* Since simple * loops can be made faster by using
2704 on_failure_keep_string_jump, we turn simple P+
2705 into PP* if P is simple. */
2706 unsigned char *p1, *p2;
2707 startoffset = b - laststart;
2708 GET_BUFFER_SPACE (startoffset);
2709 p1 = b; p2 = laststart;
2710 while (p2 < p1)
2711 *b++ = *p2++;
2712 zero_times_ok = 1;
2715 GET_BUFFER_SPACE (6);
2716 if (!zero_times_ok)
2717 /* A + loop. */
2718 STORE_JUMP (ofj, b, b + 6);
2719 else
2720 /* Simple * loops can use on_failure_keep_string_jump
2721 depending on what follows. But since we don't know
2722 that yet, we leave the decision up to
2723 on_failure_jump_smart. */
2724 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2725 laststart + startoffset, b + 6);
2726 b += 3;
2727 STORE_JUMP (jump, b, laststart + startoffset);
2728 b += 3;
2730 else
2732 /* A simple ? pattern. */
2733 assert (zero_times_ok);
2734 GET_BUFFER_SPACE (3);
2735 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2736 b += 3;
2739 else /* not greedy */
2740 { /* I wish the greedy and non-greedy cases could be merged. */
2742 GET_BUFFER_SPACE (7); /* We might use less. */
2743 if (many_times_ok)
2745 boolean emptyp = analyze_first (laststart, b, NULL, 0);
2747 /* The non-greedy multiple match looks like
2748 a repeat..until: we only need a conditional jump
2749 at the end of the loop. */
2750 if (emptyp) BUF_PUSH (no_op);
2751 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2752 : on_failure_jump, b, laststart);
2753 b += 3;
2754 if (zero_times_ok)
2756 /* The repeat...until naturally matches one or more.
2757 To also match zero times, we need to first jump to
2758 the end of the loop (its conditional jump). */
2759 INSERT_JUMP (jump, laststart, b);
2760 b += 3;
2763 else
2765 /* non-greedy a?? */
2766 INSERT_JUMP (jump, laststart, b + 3);
2767 b += 3;
2768 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2769 b += 3;
2773 pending_exact = 0;
2774 break;
2777 case '.':
2778 laststart = b;
2779 BUF_PUSH (anychar);
2780 break;
2783 case '[':
2785 re_char *p1;
2787 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2789 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2791 /* Ensure that we have enough space to push a charset: the
2792 opcode, the length count, and the bitset; 34 bytes in all. */
2793 GET_BUFFER_SPACE (34);
2795 laststart = b;
2797 /* We test `*p == '^' twice, instead of using an if
2798 statement, so we only need one BUF_PUSH. */
2799 BUF_PUSH (*p == '^' ? charset_not : charset);
2800 if (*p == '^')
2801 p++;
2803 /* Remember the first position in the bracket expression. */
2804 p1 = p;
2806 /* Push the number of bytes in the bitmap. */
2807 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2809 /* Clear the whole map. */
2810 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2812 /* charset_not matches newline according to a syntax bit. */
2813 if ((re_opcode_t) b[-2] == charset_not
2814 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2815 SET_LIST_BIT ('\n');
2817 /* Read in characters and ranges, setting map bits. */
2818 for (;;)
2820 boolean escaped_char = false;
2821 const unsigned char *p2 = p;
2822 re_wctype_t cc;
2823 re_wchar_t ch;
2825 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2827 /* See if we're at the beginning of a possible character
2828 class. */
2829 if (syntax & RE_CHAR_CLASSES &&
2830 (cc = re_wctype_parse(&p, pend - p)) != -1)
2832 if (cc == 0)
2833 FREE_STACK_RETURN (REG_ECTYPE);
2835 if (p == pend)
2836 FREE_STACK_RETURN (REG_EBRACK);
2838 #ifndef emacs
2839 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
2840 if (re_iswctype (btowc (ch), cc))
2842 c = TRANSLATE (ch);
2843 if (c < (1 << BYTEWIDTH))
2844 SET_LIST_BIT (c);
2846 #else /* emacs */
2847 /* Most character classes in a multibyte match just set
2848 a flag. Exceptions are is_blank, is_digit, is_cntrl, and
2849 is_xdigit, since they can only match ASCII characters.
2850 We don't need to handle them for multibyte. */
2852 /* Setup the gl_state object to its buffer-defined value.
2853 This hardcodes the buffer-global syntax-table for ASCII
2854 chars, while the other chars will obey syntax-table
2855 properties. It's not ideal, but it's the way it's been
2856 done until now. */
2857 SETUP_BUFFER_SYNTAX_TABLE ();
2859 for (c = 0; c < 0x80; ++c)
2860 if (re_iswctype (c, cc))
2862 SET_LIST_BIT (c);
2863 c1 = TRANSLATE (c);
2864 if (c1 == c)
2865 continue;
2866 if (ASCII_CHAR_P (c1))
2867 SET_LIST_BIT (c1);
2868 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
2869 SET_LIST_BIT (c1);
2871 SET_RANGE_TABLE_WORK_AREA_BIT
2872 (range_table_work, re_wctype_to_bit (cc));
2873 #endif /* emacs */
2874 /* In most cases the matching rule for char classes only
2875 uses the syntax table for multibyte chars, so that the
2876 content of the syntax-table is not hardcoded in the
2877 range_table. SPACE and WORD are the two exceptions. */
2878 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
2879 bufp->used_syntax = 1;
2881 /* Repeat the loop. */
2882 continue;
2885 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2886 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2887 So the translation is done later in a loop. Example:
2888 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2889 PATFETCH (c);
2891 /* \ might escape characters inside [...] and [^...]. */
2892 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2894 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2896 PATFETCH (c);
2897 escaped_char = true;
2899 else
2901 /* Could be the end of the bracket expression. If it's
2902 not (i.e., when the bracket expression is `[]' so
2903 far), the ']' character bit gets set way below. */
2904 if (c == ']' && p2 != p1)
2905 break;
2908 if (p < pend && p[0] == '-' && p[1] != ']')
2911 /* Discard the `-'. */
2912 PATFETCH (c1);
2914 /* Fetch the character which ends the range. */
2915 PATFETCH (c1);
2916 #ifdef emacs
2917 if (CHAR_BYTE8_P (c1)
2918 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
2919 /* Treat the range from a multibyte character to
2920 raw-byte character as empty. */
2921 c = c1 + 1;
2922 #endif /* emacs */
2924 else
2925 /* Range from C to C. */
2926 c1 = c;
2928 if (c > c1)
2930 if (syntax & RE_NO_EMPTY_RANGES)
2931 FREE_STACK_RETURN (REG_ERANGEX);
2932 /* Else, repeat the loop. */
2934 else
2936 #ifndef emacs
2937 /* Set the range into bitmap */
2938 for (; c <= c1; c++)
2940 ch = TRANSLATE (c);
2941 if (ch < (1 << BYTEWIDTH))
2942 SET_LIST_BIT (ch);
2944 #else /* emacs */
2945 if (c < 128)
2947 ch = min (127, c1);
2948 SETUP_ASCII_RANGE (range_table_work, c, ch);
2949 c = ch + 1;
2950 if (CHAR_BYTE8_P (c1))
2951 c = BYTE8_TO_CHAR (128);
2953 if (c <= c1)
2955 if (CHAR_BYTE8_P (c))
2957 c = CHAR_TO_BYTE8 (c);
2958 c1 = CHAR_TO_BYTE8 (c1);
2959 for (; c <= c1; c++)
2960 SET_LIST_BIT (c);
2962 else if (multibyte)
2964 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
2966 else
2968 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
2971 #endif /* emacs */
2975 /* Discard any (non)matching list bytes that are all 0 at the
2976 end of the map. Decrease the map-length byte too. */
2977 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2978 b[-1]--;
2979 b += b[-1];
2981 /* Build real range table from work area. */
2982 if (RANGE_TABLE_WORK_USED (range_table_work)
2983 || RANGE_TABLE_WORK_BITS (range_table_work))
2985 int i;
2986 int used = RANGE_TABLE_WORK_USED (range_table_work);
2988 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2989 bytes for flags, two for COUNT, and three bytes for
2990 each character. */
2991 GET_BUFFER_SPACE (4 + used * 3);
2993 /* Indicate the existence of range table. */
2994 laststart[1] |= 0x80;
2996 /* Store the character class flag bits into the range table.
2997 If not in emacs, these flag bits are always 0. */
2998 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
2999 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3001 STORE_NUMBER_AND_INCR (b, used / 2);
3002 for (i = 0; i < used; i++)
3003 STORE_CHARACTER_AND_INCR
3004 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3007 break;
3010 case '(':
3011 if (syntax & RE_NO_BK_PARENS)
3012 goto handle_open;
3013 else
3014 goto normal_char;
3017 case ')':
3018 if (syntax & RE_NO_BK_PARENS)
3019 goto handle_close;
3020 else
3021 goto normal_char;
3024 case '\n':
3025 if (syntax & RE_NEWLINE_ALT)
3026 goto handle_alt;
3027 else
3028 goto normal_char;
3031 case '|':
3032 if (syntax & RE_NO_BK_VBAR)
3033 goto handle_alt;
3034 else
3035 goto normal_char;
3038 case '{':
3039 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3040 goto handle_interval;
3041 else
3042 goto normal_char;
3045 case '\\':
3046 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3048 /* Do not translate the character after the \, so that we can
3049 distinguish, e.g., \B from \b, even if we normally would
3050 translate, e.g., B to b. */
3051 PATFETCH (c);
3053 switch (c)
3055 case '(':
3056 if (syntax & RE_NO_BK_PARENS)
3057 goto normal_backslash;
3059 handle_open:
3061 int shy = 0;
3062 regnum_t regnum = 0;
3063 if (p+1 < pend)
3065 /* Look for a special (?...) construct */
3066 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3068 PATFETCH (c); /* Gobble up the '?'. */
3069 while (!shy)
3071 PATFETCH (c);
3072 switch (c)
3074 case ':': shy = 1; break;
3075 case '0':
3076 /* An explicitly specified regnum must start
3077 with non-0. */
3078 if (regnum == 0)
3079 FREE_STACK_RETURN (REG_BADPAT);
3080 case '1': case '2': case '3': case '4':
3081 case '5': case '6': case '7': case '8': case '9':
3082 regnum = 10*regnum + (c - '0'); break;
3083 default:
3084 /* Only (?:...) is supported right now. */
3085 FREE_STACK_RETURN (REG_BADPAT);
3091 if (!shy)
3092 regnum = ++bufp->re_nsub;
3093 else if (regnum)
3094 { /* It's actually not shy, but explicitly numbered. */
3095 shy = 0;
3096 if (regnum > bufp->re_nsub)
3097 bufp->re_nsub = regnum;
3098 else if (regnum > bufp->re_nsub
3099 /* Ideally, we'd want to check that the specified
3100 group can't have matched (i.e. all subgroups
3101 using the same regnum are in other branches of
3102 OR patterns), but we don't currently keep track
3103 of enough info to do that easily. */
3104 || group_in_compile_stack (compile_stack, regnum))
3105 FREE_STACK_RETURN (REG_BADPAT);
3107 else
3108 /* It's really shy. */
3109 regnum = - bufp->re_nsub;
3111 if (COMPILE_STACK_FULL)
3113 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3114 compile_stack_elt_t);
3115 if (compile_stack.stack == NULL) return REG_ESPACE;
3117 compile_stack.size <<= 1;
3120 /* These are the values to restore when we hit end of this
3121 group. They are all relative offsets, so that if the
3122 whole pattern moves because of realloc, they will still
3123 be valid. */
3124 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3125 COMPILE_STACK_TOP.fixup_alt_jump
3126 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3127 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3128 COMPILE_STACK_TOP.regnum = regnum;
3130 /* Do not push a start_memory for groups beyond the last one
3131 we can represent in the compiled pattern. */
3132 if (regnum <= MAX_REGNUM && regnum > 0)
3133 BUF_PUSH_2 (start_memory, regnum);
3135 compile_stack.avail++;
3137 fixup_alt_jump = 0;
3138 laststart = 0;
3139 begalt = b;
3140 /* If we've reached MAX_REGNUM groups, then this open
3141 won't actually generate any code, so we'll have to
3142 clear pending_exact explicitly. */
3143 pending_exact = 0;
3144 break;
3147 case ')':
3148 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3150 if (COMPILE_STACK_EMPTY)
3152 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3153 goto normal_backslash;
3154 else
3155 FREE_STACK_RETURN (REG_ERPAREN);
3158 handle_close:
3159 FIXUP_ALT_JUMP ();
3161 /* See similar code for backslashed left paren above. */
3162 if (COMPILE_STACK_EMPTY)
3164 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3165 goto normal_char;
3166 else
3167 FREE_STACK_RETURN (REG_ERPAREN);
3170 /* Since we just checked for an empty stack above, this
3171 ``can't happen''. */
3172 assert (compile_stack.avail != 0);
3174 /* We don't just want to restore into `regnum', because
3175 later groups should continue to be numbered higher,
3176 as in `(ab)c(de)' -- the second group is #2. */
3177 regnum_t regnum;
3179 compile_stack.avail--;
3180 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3181 fixup_alt_jump
3182 = COMPILE_STACK_TOP.fixup_alt_jump
3183 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3184 : 0;
3185 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3186 regnum = COMPILE_STACK_TOP.regnum;
3187 /* If we've reached MAX_REGNUM groups, then this open
3188 won't actually generate any code, so we'll have to
3189 clear pending_exact explicitly. */
3190 pending_exact = 0;
3192 /* We're at the end of the group, so now we know how many
3193 groups were inside this one. */
3194 if (regnum <= MAX_REGNUM && regnum > 0)
3195 BUF_PUSH_2 (stop_memory, regnum);
3197 break;
3200 case '|': /* `\|'. */
3201 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3202 goto normal_backslash;
3203 handle_alt:
3204 if (syntax & RE_LIMITED_OPS)
3205 goto normal_char;
3207 /* Insert before the previous alternative a jump which
3208 jumps to this alternative if the former fails. */
3209 GET_BUFFER_SPACE (3);
3210 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3211 pending_exact = 0;
3212 b += 3;
3214 /* The alternative before this one has a jump after it
3215 which gets executed if it gets matched. Adjust that
3216 jump so it will jump to this alternative's analogous
3217 jump (put in below, which in turn will jump to the next
3218 (if any) alternative's such jump, etc.). The last such
3219 jump jumps to the correct final destination. A picture:
3220 _____ _____
3221 | | | |
3222 | v | v
3223 a | b | c
3225 If we are at `b', then fixup_alt_jump right now points to a
3226 three-byte space after `a'. We'll put in the jump, set
3227 fixup_alt_jump to right after `b', and leave behind three
3228 bytes which we'll fill in when we get to after `c'. */
3230 FIXUP_ALT_JUMP ();
3232 /* Mark and leave space for a jump after this alternative,
3233 to be filled in later either by next alternative or
3234 when know we're at the end of a series of alternatives. */
3235 fixup_alt_jump = b;
3236 GET_BUFFER_SPACE (3);
3237 b += 3;
3239 laststart = 0;
3240 begalt = b;
3241 break;
3244 case '{':
3245 /* If \{ is a literal. */
3246 if (!(syntax & RE_INTERVALS)
3247 /* If we're at `\{' and it's not the open-interval
3248 operator. */
3249 || (syntax & RE_NO_BK_BRACES))
3250 goto normal_backslash;
3252 handle_interval:
3254 /* If got here, then the syntax allows intervals. */
3256 /* At least (most) this many matches must be made. */
3257 int lower_bound = 0, upper_bound = -1;
3259 beg_interval = p;
3261 GET_INTERVAL_COUNT (lower_bound);
3263 if (c == ',')
3264 GET_INTERVAL_COUNT (upper_bound);
3265 else
3266 /* Interval such as `{1}' => match exactly once. */
3267 upper_bound = lower_bound;
3269 if (lower_bound < 0
3270 || (0 <= upper_bound && upper_bound < lower_bound))
3271 FREE_STACK_RETURN (REG_BADBR);
3273 if (!(syntax & RE_NO_BK_BRACES))
3275 if (c != '\\')
3276 FREE_STACK_RETURN (REG_BADBR);
3277 if (p == pend)
3278 FREE_STACK_RETURN (REG_EESCAPE);
3279 PATFETCH (c);
3282 if (c != '}')
3283 FREE_STACK_RETURN (REG_BADBR);
3285 /* We just parsed a valid interval. */
3287 /* If it's invalid to have no preceding re. */
3288 if (!laststart)
3290 if (syntax & RE_CONTEXT_INVALID_OPS)
3291 FREE_STACK_RETURN (REG_BADRPT);
3292 else if (syntax & RE_CONTEXT_INDEP_OPS)
3293 laststart = b;
3294 else
3295 goto unfetch_interval;
3298 if (upper_bound == 0)
3299 /* If the upper bound is zero, just drop the sub pattern
3300 altogether. */
3301 b = laststart;
3302 else if (lower_bound == 1 && upper_bound == 1)
3303 /* Just match it once: nothing to do here. */
3306 /* Otherwise, we have a nontrivial interval. When
3307 we're all done, the pattern will look like:
3308 set_number_at <jump count> <upper bound>
3309 set_number_at <succeed_n count> <lower bound>
3310 succeed_n <after jump addr> <succeed_n count>
3311 <body of loop>
3312 jump_n <succeed_n addr> <jump count>
3313 (The upper bound and `jump_n' are omitted if
3314 `upper_bound' is 1, though.) */
3315 else
3316 { /* If the upper bound is > 1, we need to insert
3317 more at the end of the loop. */
3318 unsigned int nbytes = (upper_bound < 0 ? 3
3319 : upper_bound > 1 ? 5 : 0);
3320 unsigned int startoffset = 0;
3322 GET_BUFFER_SPACE (20); /* We might use less. */
3324 if (lower_bound == 0)
3326 /* A succeed_n that starts with 0 is really a
3327 a simple on_failure_jump_loop. */
3328 INSERT_JUMP (on_failure_jump_loop, laststart,
3329 b + 3 + nbytes);
3330 b += 3;
3332 else
3334 /* Initialize lower bound of the `succeed_n', even
3335 though it will be set during matching by its
3336 attendant `set_number_at' (inserted next),
3337 because `re_compile_fastmap' needs to know.
3338 Jump to the `jump_n' we might insert below. */
3339 INSERT_JUMP2 (succeed_n, laststart,
3340 b + 5 + nbytes,
3341 lower_bound);
3342 b += 5;
3344 /* Code to initialize the lower bound. Insert
3345 before the `succeed_n'. The `5' is the last two
3346 bytes of this `set_number_at', plus 3 bytes of
3347 the following `succeed_n'. */
3348 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3349 b += 5;
3350 startoffset += 5;
3353 if (upper_bound < 0)
3355 /* A negative upper bound stands for infinity,
3356 in which case it degenerates to a plain jump. */
3357 STORE_JUMP (jump, b, laststart + startoffset);
3358 b += 3;
3360 else if (upper_bound > 1)
3361 { /* More than one repetition is allowed, so
3362 append a backward jump to the `succeed_n'
3363 that starts this interval.
3365 When we've reached this during matching,
3366 we'll have matched the interval once, so
3367 jump back only `upper_bound - 1' times. */
3368 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3369 upper_bound - 1);
3370 b += 5;
3372 /* The location we want to set is the second
3373 parameter of the `jump_n'; that is `b-2' as
3374 an absolute address. `laststart' will be
3375 the `set_number_at' we're about to insert;
3376 `laststart+3' the number to set, the source
3377 for the relative address. But we are
3378 inserting into the middle of the pattern --
3379 so everything is getting moved up by 5.
3380 Conclusion: (b - 2) - (laststart + 3) + 5,
3381 i.e., b - laststart.
3383 We insert this at the beginning of the loop
3384 so that if we fail during matching, we'll
3385 reinitialize the bounds. */
3386 insert_op2 (set_number_at, laststart, b - laststart,
3387 upper_bound - 1, b);
3388 b += 5;
3391 pending_exact = 0;
3392 beg_interval = NULL;
3394 break;
3396 unfetch_interval:
3397 /* If an invalid interval, match the characters as literals. */
3398 assert (beg_interval);
3399 p = beg_interval;
3400 beg_interval = NULL;
3402 /* normal_char and normal_backslash need `c'. */
3403 c = '{';
3405 if (!(syntax & RE_NO_BK_BRACES))
3407 assert (p > pattern && p[-1] == '\\');
3408 goto normal_backslash;
3410 else
3411 goto normal_char;
3413 #ifdef emacs
3414 case '=':
3415 laststart = b;
3416 BUF_PUSH (at_dot);
3417 break;
3419 case 's':
3420 laststart = b;
3421 PATFETCH (c);
3422 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3423 break;
3425 case 'S':
3426 laststart = b;
3427 PATFETCH (c);
3428 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3429 break;
3431 case 'c':
3432 laststart = b;
3433 PATFETCH (c);
3434 BUF_PUSH_2 (categoryspec, c);
3435 break;
3437 case 'C':
3438 laststart = b;
3439 PATFETCH (c);
3440 BUF_PUSH_2 (notcategoryspec, c);
3441 break;
3442 #endif /* emacs */
3445 case 'w':
3446 if (syntax & RE_NO_GNU_OPS)
3447 goto normal_char;
3448 laststart = b;
3449 BUF_PUSH_2 (syntaxspec, Sword);
3450 break;
3453 case 'W':
3454 if (syntax & RE_NO_GNU_OPS)
3455 goto normal_char;
3456 laststart = b;
3457 BUF_PUSH_2 (notsyntaxspec, Sword);
3458 break;
3461 case '<':
3462 if (syntax & RE_NO_GNU_OPS)
3463 goto normal_char;
3464 laststart = b;
3465 BUF_PUSH (wordbeg);
3466 break;
3468 case '>':
3469 if (syntax & RE_NO_GNU_OPS)
3470 goto normal_char;
3471 laststart = b;
3472 BUF_PUSH (wordend);
3473 break;
3475 case '_':
3476 if (syntax & RE_NO_GNU_OPS)
3477 goto normal_char;
3478 laststart = b;
3479 PATFETCH (c);
3480 if (c == '<')
3481 BUF_PUSH (symbeg);
3482 else if (c == '>')
3483 BUF_PUSH (symend);
3484 else
3485 FREE_STACK_RETURN (REG_BADPAT);
3486 break;
3488 case 'b':
3489 if (syntax & RE_NO_GNU_OPS)
3490 goto normal_char;
3491 BUF_PUSH (wordbound);
3492 break;
3494 case 'B':
3495 if (syntax & RE_NO_GNU_OPS)
3496 goto normal_char;
3497 BUF_PUSH (notwordbound);
3498 break;
3500 case '`':
3501 if (syntax & RE_NO_GNU_OPS)
3502 goto normal_char;
3503 BUF_PUSH (begbuf);
3504 break;
3506 case '\'':
3507 if (syntax & RE_NO_GNU_OPS)
3508 goto normal_char;
3509 BUF_PUSH (endbuf);
3510 break;
3512 case '1': case '2': case '3': case '4': case '5':
3513 case '6': case '7': case '8': case '9':
3515 regnum_t reg;
3517 if (syntax & RE_NO_BK_REFS)
3518 goto normal_backslash;
3520 reg = c - '0';
3522 if (reg > bufp->re_nsub || reg < 1
3523 /* Can't back reference to a subexp before its end. */
3524 || group_in_compile_stack (compile_stack, reg))
3525 FREE_STACK_RETURN (REG_ESUBREG);
3527 laststart = b;
3528 BUF_PUSH_2 (duplicate, reg);
3530 break;
3533 case '+':
3534 case '?':
3535 if (syntax & RE_BK_PLUS_QM)
3536 goto handle_plus;
3537 else
3538 goto normal_backslash;
3540 default:
3541 normal_backslash:
3542 /* You might think it would be useful for \ to mean
3543 not to translate; but if we don't translate it
3544 it will never match anything. */
3545 goto normal_char;
3547 break;
3550 default:
3551 /* Expects the character in `c'. */
3552 normal_char:
3553 /* If no exactn currently being built. */
3554 if (!pending_exact
3556 /* If last exactn not at current position. */
3557 || pending_exact + *pending_exact + 1 != b
3559 /* We have only one byte following the exactn for the count. */
3560 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3562 /* If followed by a repetition operator. */
3563 || (p != pend && (*p == '*' || *p == '^'))
3564 || ((syntax & RE_BK_PLUS_QM)
3565 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3566 : p != pend && (*p == '+' || *p == '?'))
3567 || ((syntax & RE_INTERVALS)
3568 && ((syntax & RE_NO_BK_BRACES)
3569 ? p != pend && *p == '{'
3570 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3572 /* Start building a new exactn. */
3574 laststart = b;
3576 BUF_PUSH_2 (exactn, 0);
3577 pending_exact = b - 1;
3580 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3582 int len;
3584 if (multibyte)
3586 c = TRANSLATE (c);
3587 len = CHAR_STRING (c, b);
3588 b += len;
3590 else
3592 c1 = RE_CHAR_TO_MULTIBYTE (c);
3593 if (! CHAR_BYTE8_P (c1))
3595 re_wchar_t c2 = TRANSLATE (c1);
3597 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3598 c = c1;
3600 *b++ = c;
3601 len = 1;
3603 (*pending_exact) += len;
3606 break;
3607 } /* switch (c) */
3608 } /* while p != pend */
3611 /* Through the pattern now. */
3613 FIXUP_ALT_JUMP ();
3615 if (!COMPILE_STACK_EMPTY)
3616 FREE_STACK_RETURN (REG_EPAREN);
3618 /* If we don't want backtracking, force success
3619 the first time we reach the end of the compiled pattern. */
3620 if (!posix_backtracking)
3621 BUF_PUSH (succeed);
3623 /* We have succeeded; set the length of the buffer. */
3624 bufp->used = b - bufp->buffer;
3626 #ifdef DEBUG
3627 if (debug > 0)
3629 re_compile_fastmap (bufp);
3630 DEBUG_PRINT ("\nCompiled pattern: \n");
3631 print_compiled_pattern (bufp);
3633 debug--;
3634 #endif /* DEBUG */
3636 #ifndef MATCH_MAY_ALLOCATE
3637 /* Initialize the failure stack to the largest possible stack. This
3638 isn't necessary unless we're trying to avoid calling alloca in
3639 the search and match routines. */
3641 int num_regs = bufp->re_nsub + 1;
3643 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3645 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3646 falk_stack.stack = realloc (fail_stack.stack,
3647 fail_stack.size * sizeof *falk_stack.stack);
3650 regex_grow_registers (num_regs);
3652 #endif /* not MATCH_MAY_ALLOCATE */
3654 FREE_STACK_RETURN (REG_NOERROR);
3656 #ifdef emacs
3657 # undef syntax
3658 #else
3659 # undef posix_backtracking
3660 #endif
3661 } /* regex_compile */
3663 /* Subroutines for `regex_compile'. */
3665 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3667 static void
3668 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3670 *loc = (unsigned char) op;
3671 STORE_NUMBER (loc + 1, arg);
3675 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3677 static void
3678 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3680 *loc = (unsigned char) op;
3681 STORE_NUMBER (loc + 1, arg1);
3682 STORE_NUMBER (loc + 3, arg2);
3686 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3687 for OP followed by two-byte integer parameter ARG. */
3689 static void
3690 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3692 register unsigned char *pfrom = end;
3693 register unsigned char *pto = end + 3;
3695 while (pfrom != loc)
3696 *--pto = *--pfrom;
3698 store_op1 (op, loc, arg);
3702 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3704 static void
3705 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3707 register unsigned char *pfrom = end;
3708 register unsigned char *pto = end + 5;
3710 while (pfrom != loc)
3711 *--pto = *--pfrom;
3713 store_op2 (op, loc, arg1, arg2);
3717 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3718 after an alternative or a begin-subexpression. We assume there is at
3719 least one character before the ^. */
3721 static boolean
3722 at_begline_loc_p (const_re_char *pattern, const_re_char *p, reg_syntax_t syntax)
3724 re_char *prev = p - 2;
3725 boolean odd_backslashes;
3727 /* After a subexpression? */
3728 if (*prev == '(')
3729 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3731 /* After an alternative? */
3732 else if (*prev == '|')
3733 odd_backslashes = (syntax & RE_NO_BK_VBAR) == 0;
3735 /* After a shy subexpression? */
3736 else if (*prev == ':' && (syntax & RE_SHY_GROUPS))
3738 /* Skip over optional regnum. */
3739 while (prev - 1 >= pattern && prev[-1] >= '0' && prev[-1] <= '9')
3740 --prev;
3742 if (!(prev - 2 >= pattern
3743 && prev[-1] == '?' && prev[-2] == '('))
3744 return false;
3745 prev -= 2;
3746 odd_backslashes = (syntax & RE_NO_BK_PARENS) == 0;
3748 else
3749 return false;
3751 /* Count the number of preceding backslashes. */
3752 p = prev;
3753 while (prev - 1 >= pattern && prev[-1] == '\\')
3754 --prev;
3755 return (p - prev) & odd_backslashes;
3759 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3760 at least one character after the $, i.e., `P < PEND'. */
3762 static boolean
3763 at_endline_loc_p (const_re_char *p, const_re_char *pend, reg_syntax_t syntax)
3765 re_char *next = p;
3766 boolean next_backslash = *next == '\\';
3767 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3769 return
3770 /* Before a subexpression? */
3771 (syntax & RE_NO_BK_PARENS ? *next == ')'
3772 : next_backslash && next_next && *next_next == ')')
3773 /* Before an alternative? */
3774 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3775 : next_backslash && next_next && *next_next == '|');
3779 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3780 false if it's not. */
3782 static boolean
3783 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3785 ssize_t this_element;
3787 for (this_element = compile_stack.avail - 1;
3788 this_element >= 0;
3789 this_element--)
3790 if (compile_stack.stack[this_element].regnum == regnum)
3791 return true;
3793 return false;
3796 /* analyze_first.
3797 If fastmap is non-NULL, go through the pattern and fill fastmap
3798 with all the possible leading chars. If fastmap is NULL, don't
3799 bother filling it up (obviously) and only return whether the
3800 pattern could potentially match the empty string.
3802 Return 1 if p..pend might match the empty string.
3803 Return 0 if p..pend matches at least one char.
3804 Return -1 if fastmap was not updated accurately. */
3806 static int
3807 analyze_first (const_re_char *p, const_re_char *pend, char *fastmap,
3808 const int multibyte)
3810 int j, k;
3811 boolean not;
3813 /* If all elements for base leading-codes in fastmap is set, this
3814 flag is set true. */
3815 boolean match_any_multibyte_characters = false;
3817 assert (p);
3819 /* The loop below works as follows:
3820 - It has a working-list kept in the PATTERN_STACK and which basically
3821 starts by only containing a pointer to the first operation.
3822 - If the opcode we're looking at is a match against some set of
3823 chars, then we add those chars to the fastmap and go on to the
3824 next work element from the worklist (done via `break').
3825 - If the opcode is a control operator on the other hand, we either
3826 ignore it (if it's meaningless at this point, such as `start_memory')
3827 or execute it (if it's a jump). If the jump has several destinations
3828 (i.e. `on_failure_jump'), then we push the other destination onto the
3829 worklist.
3830 We guarantee termination by ignoring backward jumps (more or less),
3831 so that `p' is monotonically increasing. More to the point, we
3832 never set `p' (or push) anything `<= p1'. */
3834 while (p < pend)
3836 /* `p1' is used as a marker of how far back a `on_failure_jump'
3837 can go without being ignored. It is normally equal to `p'
3838 (which prevents any backward `on_failure_jump') except right
3839 after a plain `jump', to allow patterns such as:
3840 0: jump 10
3841 3..9: <body>
3842 10: on_failure_jump 3
3843 as used for the *? operator. */
3844 re_char *p1 = p;
3846 switch (*p++)
3848 case succeed:
3849 return 1;
3851 case duplicate:
3852 /* If the first character has to match a backreference, that means
3853 that the group was empty (since it already matched). Since this
3854 is the only case that interests us here, we can assume that the
3855 backreference must match the empty string. */
3856 p++;
3857 continue;
3860 /* Following are the cases which match a character. These end
3861 with `break'. */
3863 case exactn:
3864 if (fastmap)
3866 /* If multibyte is nonzero, the first byte of each
3867 character is an ASCII or a leading code. Otherwise,
3868 each byte is a character. Thus, this works in both
3869 cases. */
3870 fastmap[p[1]] = 1;
3871 if (! multibyte)
3873 /* For the case of matching this unibyte regex
3874 against multibyte, we must set a leading code of
3875 the corresponding multibyte character. */
3876 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
3878 fastmap[CHAR_LEADING_CODE (c)] = 1;
3881 break;
3884 case anychar:
3885 /* We could put all the chars except for \n (and maybe \0)
3886 but we don't bother since it is generally not worth it. */
3887 if (!fastmap) break;
3888 return -1;
3891 case charset_not:
3892 if (!fastmap) break;
3894 /* Chars beyond end of bitmap are possible matches. */
3895 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3896 j < (1 << BYTEWIDTH); j++)
3897 fastmap[j] = 1;
3900 /* Fallthrough */
3901 case charset:
3902 if (!fastmap) break;
3903 not = (re_opcode_t) *(p - 1) == charset_not;
3904 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3905 j >= 0; j--)
3906 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3907 fastmap[j] = 1;
3909 #ifdef emacs
3910 if (/* Any leading code can possibly start a character
3911 which doesn't match the specified set of characters. */
3914 /* If we can match a character class, we can match any
3915 multibyte characters. */
3916 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3917 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3920 if (match_any_multibyte_characters == false)
3922 for (j = MIN_MULTIBYTE_LEADING_CODE;
3923 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3924 fastmap[j] = 1;
3925 match_any_multibyte_characters = true;
3929 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3930 && match_any_multibyte_characters == false)
3932 /* Set fastmap[I] to 1 where I is a leading code of each
3933 multibyte character in the range table. */
3934 int c, count;
3935 unsigned char lc1, lc2;
3937 /* Make P points the range table. `+ 2' is to skip flag
3938 bits for a character class. */
3939 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3941 /* Extract the number of ranges in range table into COUNT. */
3942 EXTRACT_NUMBER_AND_INCR (count, p);
3943 for (; count > 0; count--, p += 3)
3945 /* Extract the start and end of each range. */
3946 EXTRACT_CHARACTER (c, p);
3947 lc1 = CHAR_LEADING_CODE (c);
3948 p += 3;
3949 EXTRACT_CHARACTER (c, p);
3950 lc2 = CHAR_LEADING_CODE (c);
3951 for (j = lc1; j <= lc2; j++)
3952 fastmap[j] = 1;
3955 #endif
3956 break;
3958 case syntaxspec:
3959 case notsyntaxspec:
3960 if (!fastmap) break;
3961 #ifndef emacs
3962 not = (re_opcode_t)p[-1] == notsyntaxspec;
3963 k = *p++;
3964 for (j = 0; j < (1 << BYTEWIDTH); j++)
3965 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3966 fastmap[j] = 1;
3967 break;
3968 #else /* emacs */
3969 /* This match depends on text properties. These end with
3970 aborting optimizations. */
3971 return -1;
3973 case categoryspec:
3974 case notcategoryspec:
3975 if (!fastmap) break;
3976 not = (re_opcode_t)p[-1] == notcategoryspec;
3977 k = *p++;
3978 for (j = (1 << BYTEWIDTH); j >= 0; j--)
3979 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3980 fastmap[j] = 1;
3982 /* Any leading code can possibly start a character which
3983 has or doesn't has the specified category. */
3984 if (match_any_multibyte_characters == false)
3986 for (j = MIN_MULTIBYTE_LEADING_CODE;
3987 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
3988 fastmap[j] = 1;
3989 match_any_multibyte_characters = true;
3991 break;
3993 /* All cases after this match the empty string. These end with
3994 `continue'. */
3996 case at_dot:
3997 #endif /* !emacs */
3998 case no_op:
3999 case begline:
4000 case endline:
4001 case begbuf:
4002 case endbuf:
4003 case wordbound:
4004 case notwordbound:
4005 case wordbeg:
4006 case wordend:
4007 case symbeg:
4008 case symend:
4009 continue;
4012 case jump:
4013 EXTRACT_NUMBER_AND_INCR (j, p);
4014 if (j < 0)
4015 /* Backward jumps can only go back to code that we've already
4016 visited. `re_compile' should make sure this is true. */
4017 break;
4018 p += j;
4019 switch (*p)
4021 case on_failure_jump:
4022 case on_failure_keep_string_jump:
4023 case on_failure_jump_loop:
4024 case on_failure_jump_nastyloop:
4025 case on_failure_jump_smart:
4026 p++;
4027 break;
4028 default:
4029 continue;
4031 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4032 to jump back to "just after here". */
4033 /* Fallthrough */
4035 case on_failure_jump:
4036 case on_failure_keep_string_jump:
4037 case on_failure_jump_nastyloop:
4038 case on_failure_jump_loop:
4039 case on_failure_jump_smart:
4040 EXTRACT_NUMBER_AND_INCR (j, p);
4041 if (p + j <= p1)
4042 ; /* Backward jump to be ignored. */
4043 else
4044 { /* We have to look down both arms.
4045 We first go down the "straight" path so as to minimize
4046 stack usage when going through alternatives. */
4047 int r = analyze_first (p, pend, fastmap, multibyte);
4048 if (r) return r;
4049 p += j;
4051 continue;
4054 case jump_n:
4055 /* This code simply does not properly handle forward jump_n. */
4056 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4057 p += 4;
4058 /* jump_n can either jump or fall through. The (backward) jump
4059 case has already been handled, so we only need to look at the
4060 fallthrough case. */
4061 continue;
4063 case succeed_n:
4064 /* If N == 0, it should be an on_failure_jump_loop instead. */
4065 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4066 p += 4;
4067 /* We only care about one iteration of the loop, so we don't
4068 need to consider the case where this behaves like an
4069 on_failure_jump. */
4070 continue;
4073 case set_number_at:
4074 p += 4;
4075 continue;
4078 case start_memory:
4079 case stop_memory:
4080 p += 1;
4081 continue;
4084 default:
4085 abort (); /* We have listed all the cases. */
4086 } /* switch *p++ */
4088 /* Getting here means we have found the possible starting
4089 characters for one path of the pattern -- and that the empty
4090 string does not match. We need not follow this path further. */
4091 return 0;
4092 } /* while p */
4094 /* We reached the end without matching anything. */
4095 return 1;
4097 } /* analyze_first */
4099 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4100 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4101 characters can start a string that matches the pattern. This fastmap
4102 is used by re_search to skip quickly over impossible starting points.
4104 Character codes above (1 << BYTEWIDTH) are not represented in the
4105 fastmap, but the leading codes are represented. Thus, the fastmap
4106 indicates which character sets could start a match.
4108 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4109 area as BUFP->fastmap.
4111 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4112 the pattern buffer.
4114 Returns 0 if we succeed, -2 if an internal error. */
4117 re_compile_fastmap (struct re_pattern_buffer *bufp)
4119 char *fastmap = bufp->fastmap;
4120 int analysis;
4122 assert (fastmap && bufp->buffer);
4124 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4125 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4127 analysis = analyze_first (bufp->buffer, bufp->buffer + bufp->used,
4128 fastmap, RE_MULTIBYTE_P (bufp));
4129 bufp->can_be_null = (analysis != 0);
4130 return 0;
4131 } /* re_compile_fastmap */
4133 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4134 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4135 this memory for recording register information. STARTS and ENDS
4136 must be allocated using the malloc library routine, and must each
4137 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4139 If NUM_REGS == 0, then subsequent matches should allocate their own
4140 register data.
4142 Unless this function is called, the first search or match using
4143 PATTERN_BUFFER will allocate its own register data, without
4144 freeing the old data. */
4146 void
4147 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4149 if (num_regs)
4151 bufp->regs_allocated = REGS_REALLOCATE;
4152 regs->num_regs = num_regs;
4153 regs->start = starts;
4154 regs->end = ends;
4156 else
4158 bufp->regs_allocated = REGS_UNALLOCATED;
4159 regs->num_regs = 0;
4160 regs->start = regs->end = 0;
4163 WEAK_ALIAS (__re_set_registers, re_set_registers)
4165 /* Searching routines. */
4167 /* Like re_search_2, below, but only one string is specified, and
4168 doesn't let you say where to stop matching. */
4170 regoff_t
4171 re_search (struct re_pattern_buffer *bufp, const char *string, size_t size,
4172 ssize_t startpos, ssize_t range, struct re_registers *regs)
4174 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4175 regs, size);
4177 WEAK_ALIAS (__re_search, re_search)
4179 /* Head address of virtual concatenation of string. */
4180 #define HEAD_ADDR_VSTRING(P) \
4181 (((P) >= size1 ? string2 : string1))
4183 /* Address of POS in the concatenation of virtual string. */
4184 #define POS_ADDR_VSTRING(POS) \
4185 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4187 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4188 virtual concatenation of STRING1 and STRING2, starting first at index
4189 STARTPOS, then at STARTPOS + 1, and so on.
4191 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4193 RANGE is how far to scan while trying to match. RANGE = 0 means try
4194 only at STARTPOS; in general, the last start tried is STARTPOS +
4195 RANGE.
4197 In REGS, return the indices of the virtual concatenation of STRING1
4198 and STRING2 that matched the entire BUFP->buffer and its contained
4199 subexpressions.
4201 Do not consider matching one past the index STOP in the virtual
4202 concatenation of STRING1 and STRING2.
4204 We return either the position in the strings at which the match was
4205 found, -1 if no match, or -2 if error (such as failure
4206 stack overflow). */
4208 regoff_t
4209 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, size_t size1,
4210 const char *str2, size_t size2, ssize_t startpos, ssize_t range,
4211 struct re_registers *regs, ssize_t stop)
4213 regoff_t val;
4214 re_char *string1 = (re_char*) str1;
4215 re_char *string2 = (re_char*) str2;
4216 register char *fastmap = bufp->fastmap;
4217 register RE_TRANSLATE_TYPE translate = bufp->translate;
4218 size_t total_size = size1 + size2;
4219 ssize_t endpos = startpos + range;
4220 boolean anchored_start;
4221 /* Nonzero if we are searching multibyte string. */
4222 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4224 /* Check for out-of-range STARTPOS. */
4225 if (startpos < 0 || startpos > total_size)
4226 return -1;
4228 /* Fix up RANGE if it might eventually take us outside
4229 the virtual concatenation of STRING1 and STRING2.
4230 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4231 if (endpos < 0)
4232 range = 0 - startpos;
4233 else if (endpos > total_size)
4234 range = total_size - startpos;
4236 /* If the search isn't to be a backwards one, don't waste time in a
4237 search for a pattern anchored at beginning of buffer. */
4238 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4240 if (startpos > 0)
4241 return -1;
4242 else
4243 range = 0;
4246 #ifdef emacs
4247 /* In a forward search for something that starts with \=.
4248 don't keep searching past point. */
4249 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4251 range = PT_BYTE - BEGV_BYTE - startpos;
4252 if (range < 0)
4253 return -1;
4255 #endif /* emacs */
4257 /* Update the fastmap now if not correct already. */
4258 if (fastmap && !bufp->fastmap_accurate)
4259 re_compile_fastmap (bufp);
4261 /* See whether the pattern is anchored. */
4262 anchored_start = (bufp->buffer[0] == begline);
4264 #ifdef emacs
4265 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4267 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4269 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4271 #endif
4273 /* Loop through the string, looking for a place to start matching. */
4274 for (;;)
4276 /* If the pattern is anchored,
4277 skip quickly past places we cannot match.
4278 We don't bother to treat startpos == 0 specially
4279 because that case doesn't repeat. */
4280 if (anchored_start && startpos > 0)
4282 if (! ((startpos <= size1 ? string1[startpos - 1]
4283 : string2[startpos - size1 - 1])
4284 == '\n'))
4285 goto advance;
4288 /* If a fastmap is supplied, skip quickly over characters that
4289 cannot be the start of a match. If the pattern can match the
4290 null string, however, we don't need to skip characters; we want
4291 the first null string. */
4292 if (fastmap && startpos < total_size && !bufp->can_be_null)
4294 register re_char *d;
4295 register re_wchar_t buf_ch;
4297 d = POS_ADDR_VSTRING (startpos);
4299 if (range > 0) /* Searching forwards. */
4301 ssize_t irange = range, lim = 0;
4303 if (startpos < size1 && startpos + range >= size1)
4304 lim = range - (size1 - startpos);
4306 /* Written out as an if-else to avoid testing `translate'
4307 inside the loop. */
4308 if (RE_TRANSLATE_P (translate))
4310 if (multibyte)
4311 while (range > lim)
4313 int buf_charlen;
4315 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4316 buf_ch = RE_TRANSLATE (translate, buf_ch);
4317 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4318 break;
4320 range -= buf_charlen;
4321 d += buf_charlen;
4323 else
4324 while (range > lim)
4326 register re_wchar_t ch, translated;
4328 buf_ch = *d;
4329 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4330 translated = RE_TRANSLATE (translate, ch);
4331 if (translated != ch
4332 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4333 buf_ch = ch;
4334 if (fastmap[buf_ch])
4335 break;
4336 d++;
4337 range--;
4340 else
4342 if (multibyte)
4343 while (range > lim)
4345 int buf_charlen;
4347 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4348 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4349 break;
4350 range -= buf_charlen;
4351 d += buf_charlen;
4353 else
4354 while (range > lim && !fastmap[*d])
4356 d++;
4357 range--;
4360 startpos += irange - range;
4362 else /* Searching backwards. */
4364 if (multibyte)
4366 buf_ch = STRING_CHAR (d);
4367 buf_ch = TRANSLATE (buf_ch);
4368 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4369 goto advance;
4371 else
4373 register re_wchar_t ch, translated;
4375 buf_ch = *d;
4376 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4377 translated = TRANSLATE (ch);
4378 if (translated != ch
4379 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4380 buf_ch = ch;
4381 if (! fastmap[TRANSLATE (buf_ch)])
4382 goto advance;
4387 /* If can't match the null string, and that's all we have left, fail. */
4388 if (range >= 0 && startpos == total_size && fastmap
4389 && !bufp->can_be_null)
4390 return -1;
4392 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4393 startpos, regs, stop);
4395 if (val >= 0)
4396 return startpos;
4398 if (val == -2)
4399 return -2;
4401 advance:
4402 if (!range)
4403 break;
4404 else if (range > 0)
4406 /* Update STARTPOS to the next character boundary. */
4407 if (multibyte)
4409 re_char *p = POS_ADDR_VSTRING (startpos);
4410 int len = BYTES_BY_CHAR_HEAD (*p);
4412 range -= len;
4413 if (range < 0)
4414 break;
4415 startpos += len;
4417 else
4419 range--;
4420 startpos++;
4423 else
4425 range++;
4426 startpos--;
4428 /* Update STARTPOS to the previous character boundary. */
4429 if (multibyte)
4431 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4432 re_char *p0 = p;
4433 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4435 /* Find the head of multibyte form. */
4436 PREV_CHAR_BOUNDARY (p, phead);
4437 range += p0 - 1 - p;
4438 if (range > 0)
4439 break;
4441 startpos -= p0 - 1 - p;
4445 return -1;
4446 } /* re_search_2 */
4447 WEAK_ALIAS (__re_search_2, re_search_2)
4449 /* Declarations and macros for re_match_2. */
4451 static int bcmp_translate (re_char *s1, re_char *s2,
4452 register ssize_t len,
4453 RE_TRANSLATE_TYPE translate,
4454 const int multibyte);
4456 /* This converts PTR, a pointer into one of the search strings `string1'
4457 and `string2' into an offset from the beginning of that string. */
4458 #define POINTER_TO_OFFSET(ptr) \
4459 (FIRST_STRING_P (ptr) \
4460 ? (ptr) - string1 \
4461 : (ptr) - string2 + (ptrdiff_t) size1)
4463 /* Call before fetching a character with *d. This switches over to
4464 string2 if necessary.
4465 Check re_match_2_internal for a discussion of why end_match_2 might
4466 not be within string2 (but be equal to end_match_1 instead). */
4467 #define PREFETCH() \
4468 while (d == dend) \
4470 /* End of string2 => fail. */ \
4471 if (dend == end_match_2) \
4472 goto fail; \
4473 /* End of string1 => advance to string2. */ \
4474 d = string2; \
4475 dend = end_match_2; \
4478 /* Call before fetching a char with *d if you already checked other limits.
4479 This is meant for use in lookahead operations like wordend, etc..
4480 where we might need to look at parts of the string that might be
4481 outside of the LIMITs (i.e past `stop'). */
4482 #define PREFETCH_NOLIMIT() \
4483 if (d == end1) \
4485 d = string2; \
4486 dend = end_match_2; \
4489 /* Test if at very beginning or at very end of the virtual concatenation
4490 of `string1' and `string2'. If only one string, it's `string2'. */
4491 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4492 #define AT_STRINGS_END(d) ((d) == end2)
4494 /* Disabled due to a compiler bug -- see comment at case wordbound */
4496 /* The comment at case wordbound is following one, but we don't use
4497 AT_WORD_BOUNDARY anymore to support multibyte form.
4499 The DEC Alpha C compiler 3.x generates incorrect code for the
4500 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4501 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4502 macro and introducing temporary variables works around the bug. */
4504 #if 0
4505 /* Test if D points to a character which is word-constituent. We have
4506 two special cases to check for: if past the end of string1, look at
4507 the first character in string2; and if before the beginning of
4508 string2, look at the last character in string1. */
4509 #define WORDCHAR_P(d) \
4510 (SYNTAX ((d) == end1 ? *string2 \
4511 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4512 == Sword)
4514 /* Test if the character before D and the one at D differ with respect
4515 to being word-constituent. */
4516 #define AT_WORD_BOUNDARY(d) \
4517 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4518 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4519 #endif
4521 /* Free everything we malloc. */
4522 #ifdef MATCH_MAY_ALLOCATE
4523 # define FREE_VAR(var) \
4524 do { \
4525 if (var) \
4527 REGEX_FREE (var); \
4528 var = NULL; \
4530 } while (0)
4531 # define FREE_VARIABLES() \
4532 do { \
4533 REGEX_FREE_STACK (fail_stack.stack); \
4534 FREE_VAR (regstart); \
4535 FREE_VAR (regend); \
4536 FREE_VAR (best_regstart); \
4537 FREE_VAR (best_regend); \
4538 REGEX_SAFE_FREE (); \
4539 } while (0)
4540 #else
4541 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4542 #endif /* not MATCH_MAY_ALLOCATE */
4545 /* Optimization routines. */
4547 /* If the operation is a match against one or more chars,
4548 return a pointer to the next operation, else return NULL. */
4549 static re_char *
4550 skip_one_char (const_re_char *p)
4552 switch (*p++)
4554 case anychar:
4555 break;
4557 case exactn:
4558 p += *p + 1;
4559 break;
4561 case charset_not:
4562 case charset:
4563 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4565 int mcnt;
4566 p = CHARSET_RANGE_TABLE (p - 1);
4567 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4568 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4570 else
4571 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4572 break;
4574 case syntaxspec:
4575 case notsyntaxspec:
4576 #ifdef emacs
4577 case categoryspec:
4578 case notcategoryspec:
4579 #endif /* emacs */
4580 p++;
4581 break;
4583 default:
4584 p = NULL;
4586 return p;
4590 /* Jump over non-matching operations. */
4591 static re_char *
4592 skip_noops (const_re_char *p, const_re_char *pend)
4594 int mcnt;
4595 while (p < pend)
4597 switch (*p)
4599 case start_memory:
4600 case stop_memory:
4601 p += 2; break;
4602 case no_op:
4603 p += 1; break;
4604 case jump:
4605 p += 1;
4606 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4607 p += mcnt;
4608 break;
4609 default:
4610 return p;
4613 assert (p == pend);
4614 return p;
4617 /* Test if C matches charset op. *PP points to the charset or charset_not
4618 opcode. When the function finishes, *PP will be advanced past that opcode.
4619 C is character to test (possibly after translations) and CORIG is original
4620 character (i.e. without any translations). UNIBYTE denotes whether c is
4621 unibyte or multibyte character. */
4622 static bool
4623 execute_charset (const_re_char **pp, unsigned c, unsigned corig, bool unibyte)
4625 re_char *p = *pp, *rtp = NULL;
4626 bool not = (re_opcode_t) *p == charset_not;
4628 if (CHARSET_RANGE_TABLE_EXISTS_P (p))
4630 int count;
4631 rtp = CHARSET_RANGE_TABLE (p);
4632 EXTRACT_NUMBER_AND_INCR (count, rtp);
4633 *pp = CHARSET_RANGE_TABLE_END ((rtp), (count));
4635 else
4636 *pp += 2 + CHARSET_BITMAP_SIZE (p);
4638 if (unibyte && c < (1 << BYTEWIDTH))
4639 { /* Lookup bitmap. */
4640 /* Cast to `unsigned' instead of `unsigned char' in
4641 case the bit list is a full 32 bytes long. */
4642 if (c < (unsigned) (CHARSET_BITMAP_SIZE (p) * BYTEWIDTH)
4643 && p[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4644 return !not;
4646 #ifdef emacs
4647 else if (rtp)
4649 int class_bits = CHARSET_RANGE_TABLE_BITS (p);
4650 re_wchar_t range_start, range_end;
4652 /* Sort tests by the most commonly used classes with some adjustment to which
4653 tests are easiest to perform. Take a look at comment in re_wctype_parse
4654 for table with frequencies of character class names. */
4656 if ((class_bits & BIT_MULTIBYTE) ||
4657 (class_bits & BIT_ALNUM && ISALNUM (c)) ||
4658 (class_bits & BIT_ALPHA && ISALPHA (c)) ||
4659 (class_bits & BIT_SPACE && ISSPACE (c)) ||
4660 (class_bits & BIT_WORD && ISWORD (c)) ||
4661 ((class_bits & BIT_UPPER) &&
4662 (ISUPPER (c) || (corig != c &&
4663 c == downcase (corig) && ISLOWER (c)))) ||
4664 ((class_bits & BIT_LOWER) &&
4665 (ISLOWER (c) || (corig != c &&
4666 c == upcase (corig) && ISUPPER(c)))) ||
4667 (class_bits & BIT_PUNCT && ISPUNCT (c)) ||
4668 (class_bits & BIT_GRAPH && ISGRAPH (c)) ||
4669 (class_bits & BIT_PRINT && ISPRINT (c)))
4670 return !not;
4672 for (p = *pp; rtp < p; rtp += 2 * 3)
4674 EXTRACT_CHARACTER (range_start, rtp);
4675 EXTRACT_CHARACTER (range_end, rtp + 3);
4676 if (range_start <= c && c <= range_end)
4677 return !not;
4680 #endif /* emacs */
4681 return not;
4684 /* Non-zero if "p1 matches something" implies "p2 fails". */
4685 static int
4686 mutually_exclusive_p (struct re_pattern_buffer *bufp, const_re_char *p1,
4687 const_re_char *p2)
4689 re_opcode_t op2;
4690 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4691 unsigned char *pend = bufp->buffer + bufp->used;
4693 assert (p1 >= bufp->buffer && p1 < pend
4694 && p2 >= bufp->buffer && p2 <= pend);
4696 /* Skip over open/close-group commands.
4697 If what follows this loop is a ...+ construct,
4698 look at what begins its body, since we will have to
4699 match at least one of that. */
4700 p2 = skip_noops (p2, pend);
4701 /* The same skip can be done for p1, except that this function
4702 is only used in the case where p1 is a simple match operator. */
4703 /* p1 = skip_noops (p1, pend); */
4705 assert (p1 >= bufp->buffer && p1 < pend
4706 && p2 >= bufp->buffer && p2 <= pend);
4708 op2 = p2 == pend ? succeed : *p2;
4710 switch (op2)
4712 case succeed:
4713 case endbuf:
4714 /* If we're at the end of the pattern, we can change. */
4715 if (skip_one_char (p1))
4717 DEBUG_PRINT (" End of pattern: fast loop.\n");
4718 return 1;
4720 break;
4722 case endline:
4723 case exactn:
4725 register re_wchar_t c
4726 = (re_opcode_t) *p2 == endline ? '\n'
4727 : RE_STRING_CHAR (p2 + 2, multibyte);
4729 if ((re_opcode_t) *p1 == exactn)
4731 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4733 DEBUG_PRINT (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4734 return 1;
4738 else if ((re_opcode_t) *p1 == charset
4739 || (re_opcode_t) *p1 == charset_not)
4741 if (!execute_charset (&p1, c, c, !multibyte || IS_REAL_ASCII (c)))
4743 DEBUG_PRINT (" No match => fast loop.\n");
4744 return 1;
4747 else if ((re_opcode_t) *p1 == anychar
4748 && c == '\n')
4750 DEBUG_PRINT (" . != \\n => fast loop.\n");
4751 return 1;
4754 break;
4756 case charset:
4758 if ((re_opcode_t) *p1 == exactn)
4759 /* Reuse the code above. */
4760 return mutually_exclusive_p (bufp, p2, p1);
4762 /* It is hard to list up all the character in charset
4763 P2 if it includes multibyte character. Give up in
4764 such case. */
4765 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4767 /* Now, we are sure that P2 has no range table.
4768 So, for the size of bitmap in P2, `p2[1]' is
4769 enough. But P1 may have range table, so the
4770 size of bitmap table of P1 is extracted by
4771 using macro `CHARSET_BITMAP_SIZE'.
4773 In a multibyte case, we know that all the character
4774 listed in P2 is ASCII. In a unibyte case, P1 has only a
4775 bitmap table. So, in both cases, it is enough to test
4776 only the bitmap table of P1. */
4778 if ((re_opcode_t) *p1 == charset)
4780 int idx;
4781 /* We win if the charset inside the loop
4782 has no overlap with the one after the loop. */
4783 for (idx = 0;
4784 (idx < (int) p2[1]
4785 && idx < CHARSET_BITMAP_SIZE (p1));
4786 idx++)
4787 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4788 break;
4790 if (idx == p2[1]
4791 || idx == CHARSET_BITMAP_SIZE (p1))
4793 DEBUG_PRINT (" No match => fast loop.\n");
4794 return 1;
4797 else if ((re_opcode_t) *p1 == charset_not)
4799 int idx;
4800 /* We win if the charset_not inside the loop lists
4801 every character listed in the charset after. */
4802 for (idx = 0; idx < (int) p2[1]; idx++)
4803 if (! (p2[2 + idx] == 0
4804 || (idx < CHARSET_BITMAP_SIZE (p1)
4805 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4806 break;
4808 if (idx == p2[1])
4810 DEBUG_PRINT (" No match => fast loop.\n");
4811 return 1;
4816 break;
4818 case charset_not:
4819 switch (*p1)
4821 case exactn:
4822 case charset:
4823 /* Reuse the code above. */
4824 return mutually_exclusive_p (bufp, p2, p1);
4825 case charset_not:
4826 /* When we have two charset_not, it's very unlikely that
4827 they don't overlap. The union of the two sets of excluded
4828 chars should cover all possible chars, which, as a matter of
4829 fact, is virtually impossible in multibyte buffers. */
4830 break;
4832 break;
4834 case wordend:
4835 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4836 case symend:
4837 return ((re_opcode_t) *p1 == syntaxspec
4838 && (p1[1] == Ssymbol || p1[1] == Sword));
4839 case notsyntaxspec:
4840 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4842 case wordbeg:
4843 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4844 case symbeg:
4845 return ((re_opcode_t) *p1 == notsyntaxspec
4846 && (p1[1] == Ssymbol || p1[1] == Sword));
4847 case syntaxspec:
4848 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4850 case wordbound:
4851 return (((re_opcode_t) *p1 == notsyntaxspec
4852 || (re_opcode_t) *p1 == syntaxspec)
4853 && p1[1] == Sword);
4855 #ifdef emacs
4856 case categoryspec:
4857 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4858 case notcategoryspec:
4859 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4860 #endif /* emacs */
4862 default:
4866 /* Safe default. */
4867 return 0;
4871 /* Matching routines. */
4873 #ifndef emacs /* Emacs never uses this. */
4874 /* re_match is like re_match_2 except it takes only a single string. */
4876 regoff_t
4877 re_match (struct re_pattern_buffer *bufp, const char *string,
4878 size_t size, ssize_t pos, struct re_registers *regs)
4880 regoff_t result = re_match_2_internal (bufp, NULL, 0, (re_char*) string,
4881 size, pos, regs, size);
4882 return result;
4884 WEAK_ALIAS (__re_match, re_match)
4885 #endif /* not emacs */
4887 /* re_match_2 matches the compiled pattern in BUFP against the
4888 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4889 and SIZE2, respectively). We start matching at POS, and stop
4890 matching at STOP.
4892 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4893 store offsets for the substring each group matched in REGS. See the
4894 documentation for exactly how many groups we fill.
4896 We return -1 if no match, -2 if an internal error (such as the
4897 failure stack overflowing). Otherwise, we return the length of the
4898 matched substring. */
4900 regoff_t
4901 re_match_2 (struct re_pattern_buffer *bufp, const char *string1,
4902 size_t size1, const char *string2, size_t size2, ssize_t pos,
4903 struct re_registers *regs, ssize_t stop)
4905 regoff_t result;
4907 #ifdef emacs
4908 ssize_t charpos;
4909 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4910 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4911 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4912 #endif
4914 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4915 (re_char*) string2, size2,
4916 pos, regs, stop);
4917 return result;
4919 WEAK_ALIAS (__re_match_2, re_match_2)
4922 /* This is a separate function so that we can force an alloca cleanup
4923 afterwards. */
4924 static regoff_t
4925 re_match_2_internal (struct re_pattern_buffer *bufp, const_re_char *string1,
4926 size_t size1, const_re_char *string2, size_t size2,
4927 ssize_t pos, struct re_registers *regs, ssize_t stop)
4929 /* General temporaries. */
4930 int mcnt;
4931 size_t reg;
4933 /* Just past the end of the corresponding string. */
4934 re_char *end1, *end2;
4936 /* Pointers into string1 and string2, just past the last characters in
4937 each to consider matching. */
4938 re_char *end_match_1, *end_match_2;
4940 /* Where we are in the data, and the end of the current string. */
4941 re_char *d, *dend;
4943 /* Used sometimes to remember where we were before starting matching
4944 an operator so that we can go back in case of failure. This "atomic"
4945 behavior of matching opcodes is indispensable to the correctness
4946 of the on_failure_keep_string_jump optimization. */
4947 re_char *dfail;
4949 /* Where we are in the pattern, and the end of the pattern. */
4950 re_char *p = bufp->buffer;
4951 re_char *pend = p + bufp->used;
4953 /* We use this to map every character in the string. */
4954 RE_TRANSLATE_TYPE translate = bufp->translate;
4956 /* Nonzero if BUFP is setup from a multibyte regex. */
4957 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4959 /* Nonzero if STRING1/STRING2 are multibyte. */
4960 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4962 /* Failure point stack. Each place that can handle a failure further
4963 down the line pushes a failure point on this stack. It consists of
4964 regstart, and regend for all registers corresponding to
4965 the subexpressions we're currently inside, plus the number of such
4966 registers, and, finally, two char *'s. The first char * is where
4967 to resume scanning the pattern; the second one is where to resume
4968 scanning the strings. */
4969 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4970 fail_stack_type fail_stack;
4971 #endif
4972 #ifdef DEBUG_COMPILES_ARGUMENTS
4973 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4974 #endif
4976 #if defined REL_ALLOC && defined REGEX_MALLOC
4977 /* This holds the pointer to the failure stack, when
4978 it is allocated relocatably. */
4979 fail_stack_elt_t *failure_stack_ptr;
4980 #endif
4982 /* We fill all the registers internally, independent of what we
4983 return, for use in backreferences. The number here includes
4984 an element for register zero. */
4985 size_t num_regs = bufp->re_nsub + 1;
4987 /* Information on the contents of registers. These are pointers into
4988 the input strings; they record just what was matched (on this
4989 attempt) by a subexpression part of the pattern, that is, the
4990 regnum-th regstart pointer points to where in the pattern we began
4991 matching and the regnum-th regend points to right after where we
4992 stopped matching the regnum-th subexpression. (The zeroth register
4993 keeps track of what the whole pattern matches.) */
4994 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4995 re_char **regstart, **regend;
4996 #endif
4998 /* The following record the register info as found in the above
4999 variables when we find a match better than any we've seen before.
5000 This happens as we backtrack through the failure points, which in
5001 turn happens only if we have not yet matched the entire string. */
5002 unsigned best_regs_set = false;
5003 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5004 re_char **best_regstart, **best_regend;
5005 #endif
5007 /* Logically, this is `best_regend[0]'. But we don't want to have to
5008 allocate space for that if we're not allocating space for anything
5009 else (see below). Also, we never need info about register 0 for
5010 any of the other register vectors, and it seems rather a kludge to
5011 treat `best_regend' differently than the rest. So we keep track of
5012 the end of the best match so far in a separate variable. We
5013 initialize this to NULL so that when we backtrack the first time
5014 and need to test it, it's not garbage. */
5015 re_char *match_end = NULL;
5017 #ifdef DEBUG_COMPILES_ARGUMENTS
5018 /* Counts the total number of registers pushed. */
5019 unsigned num_regs_pushed = 0;
5020 #endif
5022 DEBUG_PRINT ("\n\nEntering re_match_2.\n");
5024 REGEX_USE_SAFE_ALLOCA;
5026 INIT_FAIL_STACK ();
5028 #ifdef MATCH_MAY_ALLOCATE
5029 /* Do not bother to initialize all the register variables if there are
5030 no groups in the pattern, as it takes a fair amount of time. If
5031 there are groups, we include space for register 0 (the whole
5032 pattern), even though we never use it, since it simplifies the
5033 array indexing. We should fix this. */
5034 if (bufp->re_nsub)
5036 regstart = REGEX_TALLOC (num_regs, re_char *);
5037 regend = REGEX_TALLOC (num_regs, re_char *);
5038 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5039 best_regend = REGEX_TALLOC (num_regs, re_char *);
5041 if (!(regstart && regend && best_regstart && best_regend))
5043 FREE_VARIABLES ();
5044 return -2;
5047 else
5049 /* We must initialize all our variables to NULL, so that
5050 `FREE_VARIABLES' doesn't try to free them. */
5051 regstart = regend = best_regstart = best_regend = NULL;
5053 #endif /* MATCH_MAY_ALLOCATE */
5055 /* The starting position is bogus. */
5056 if (pos < 0 || pos > size1 + size2)
5058 FREE_VARIABLES ();
5059 return -1;
5062 /* Initialize subexpression text positions to -1 to mark ones that no
5063 start_memory/stop_memory has been seen for. Also initialize the
5064 register information struct. */
5065 for (reg = 1; reg < num_regs; reg++)
5066 regstart[reg] = regend[reg] = NULL;
5068 /* We move `string1' into `string2' if the latter's empty -- but not if
5069 `string1' is null. */
5070 if (size2 == 0 && string1 != NULL)
5072 string2 = string1;
5073 size2 = size1;
5074 string1 = 0;
5075 size1 = 0;
5077 end1 = string1 + size1;
5078 end2 = string2 + size2;
5080 /* `p' scans through the pattern as `d' scans through the data.
5081 `dend' is the end of the input string that `d' points within. `d'
5082 is advanced into the following input string whenever necessary, but
5083 this happens before fetching; therefore, at the beginning of the
5084 loop, `d' can be pointing at the end of a string, but it cannot
5085 equal `string2'. */
5086 if (pos >= size1)
5088 /* Only match within string2. */
5089 d = string2 + pos - size1;
5090 dend = end_match_2 = string2 + stop - size1;
5091 end_match_1 = end1; /* Just to give it a value. */
5093 else
5095 if (stop < size1)
5097 /* Only match within string1. */
5098 end_match_1 = string1 + stop;
5099 /* BEWARE!
5100 When we reach end_match_1, PREFETCH normally switches to string2.
5101 But in the present case, this means that just doing a PREFETCH
5102 makes us jump from `stop' to `gap' within the string.
5103 What we really want here is for the search to stop as
5104 soon as we hit end_match_1. That's why we set end_match_2
5105 to end_match_1 (since PREFETCH fails as soon as we hit
5106 end_match_2). */
5107 end_match_2 = end_match_1;
5109 else
5110 { /* It's important to use this code when stop == size so that
5111 moving `d' from end1 to string2 will not prevent the d == dend
5112 check from catching the end of string. */
5113 end_match_1 = end1;
5114 end_match_2 = string2 + stop - size1;
5116 d = string1 + pos;
5117 dend = end_match_1;
5120 DEBUG_PRINT ("The compiled pattern is: ");
5121 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5122 DEBUG_PRINT ("The string to match is: \"");
5123 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5124 DEBUG_PRINT ("\"\n");
5126 /* This loops over pattern commands. It exits by returning from the
5127 function if the match is complete, or it drops through if the match
5128 fails at this starting point in the input data. */
5129 for (;;)
5131 DEBUG_PRINT ("\n%p: ", p);
5133 if (p == pend)
5135 /* End of pattern means we might have succeeded. */
5136 DEBUG_PRINT ("end of pattern ... ");
5138 /* If we haven't matched the entire string, and we want the
5139 longest match, try backtracking. */
5140 if (d != end_match_2)
5142 /* True if this match is the best seen so far. */
5143 bool best_match_p;
5146 /* True if this match ends in the same string (string1
5147 or string2) as the best previous match. */
5148 bool same_str_p = (FIRST_STRING_P (match_end)
5149 == FIRST_STRING_P (d));
5151 /* AIX compiler got confused when this was combined
5152 with the previous declaration. */
5153 if (same_str_p)
5154 best_match_p = d > match_end;
5155 else
5156 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 ptrdiff_t 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;
5417 reg_syntax_t syntax;
5419 DEBUG_PRINT ("EXECUTING anychar.\n");
5421 PREFETCH ();
5422 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5423 target_multibyte);
5424 buf_ch = TRANSLATE (buf_ch);
5426 #ifdef emacs
5427 syntax = RE_SYNTAX_EMACS;
5428 #else
5429 syntax = bufp->syntax;
5430 #endif
5432 if ((!(syntax & RE_DOT_NEWLINE) && buf_ch == '\n')
5433 || ((syntax & RE_DOT_NOT_NULL) && buf_ch == '\000'))
5434 goto fail;
5436 DEBUG_PRINT (" Matched \"%d\".\n", *d);
5437 d += buf_charlen;
5439 break;
5442 case charset:
5443 case charset_not:
5445 register unsigned int c, corig;
5446 int len;
5448 /* Whether matching against a unibyte character. */
5449 boolean unibyte_char = false;
5451 DEBUG_PRINT ("EXECUTING charset%s.\n",
5452 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
5454 PREFETCH ();
5455 corig = c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5456 if (target_multibyte)
5458 int c1;
5460 c = TRANSLATE (c);
5461 c1 = RE_CHAR_TO_UNIBYTE (c);
5462 if (c1 >= 0)
5464 unibyte_char = true;
5465 c = c1;
5468 else
5470 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5472 if (! CHAR_BYTE8_P (c1))
5474 c1 = TRANSLATE (c1);
5475 c1 = RE_CHAR_TO_UNIBYTE (c1);
5476 if (c1 >= 0)
5478 unibyte_char = true;
5479 c = c1;
5482 else
5483 unibyte_char = true;
5486 p -= 1;
5487 if (!execute_charset (&p, c, corig, unibyte_char))
5488 goto fail;
5490 d += len;
5492 break;
5495 /* The beginning of a group is represented by start_memory.
5496 The argument is the register number. The text
5497 matched within the group is recorded (in the internal
5498 registers data structure) under the register number. */
5499 case start_memory:
5500 DEBUG_PRINT ("EXECUTING start_memory %d:\n", *p);
5502 /* In case we need to undo this operation (via backtracking). */
5503 PUSH_FAILURE_REG (*p);
5505 regstart[*p] = d;
5506 regend[*p] = NULL; /* probably unnecessary. -sm */
5507 DEBUG_PRINT (" regstart: %td\n", POINTER_TO_OFFSET (regstart[*p]));
5509 /* Move past the register number and inner group count. */
5510 p += 1;
5511 break;
5514 /* The stop_memory opcode represents the end of a group. Its
5515 argument is the same as start_memory's: the register number. */
5516 case stop_memory:
5517 DEBUG_PRINT ("EXECUTING stop_memory %d:\n", *p);
5519 assert (!REG_UNSET (regstart[*p]));
5520 /* Strictly speaking, there should be code such as:
5522 assert (REG_UNSET (regend[*p]));
5523 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5525 But the only info to be pushed is regend[*p] and it is known to
5526 be UNSET, so there really isn't anything to push.
5527 Not pushing anything, on the other hand deprives us from the
5528 guarantee that regend[*p] is UNSET since undoing this operation
5529 will not reset its value properly. This is not important since
5530 the value will only be read on the next start_memory or at
5531 the very end and both events can only happen if this stop_memory
5532 is *not* undone. */
5534 regend[*p] = d;
5535 DEBUG_PRINT (" regend: %td\n", POINTER_TO_OFFSET (regend[*p]));
5537 /* Move past the register number and the inner group count. */
5538 p += 1;
5539 break;
5542 /* \<digit> has been turned into a `duplicate' command which is
5543 followed by the numeric value of <digit> as the register number. */
5544 case duplicate:
5546 register re_char *d2, *dend2;
5547 int regno = *p++; /* Get which register to match against. */
5548 DEBUG_PRINT ("EXECUTING duplicate %d.\n", regno);
5550 /* Can't back reference a group which we've never matched. */
5551 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5552 goto fail;
5554 /* Where in input to try to start matching. */
5555 d2 = regstart[regno];
5557 /* Remember the start point to rollback upon failure. */
5558 dfail = d;
5560 /* Where to stop matching; if both the place to start and
5561 the place to stop matching are in the same string, then
5562 set to the place to stop, otherwise, for now have to use
5563 the end of the first string. */
5565 dend2 = ((FIRST_STRING_P (regstart[regno])
5566 == FIRST_STRING_P (regend[regno]))
5567 ? regend[regno] : end_match_1);
5568 for (;;)
5570 ptrdiff_t dcnt;
5572 /* If necessary, advance to next segment in register
5573 contents. */
5574 while (d2 == dend2)
5576 if (dend2 == end_match_2) break;
5577 if (dend2 == regend[regno]) break;
5579 /* End of string1 => advance to string2. */
5580 d2 = string2;
5581 dend2 = regend[regno];
5583 /* At end of register contents => success */
5584 if (d2 == dend2) break;
5586 /* If necessary, advance to next segment in data. */
5587 PREFETCH ();
5589 /* How many characters left in this segment to match. */
5590 dcnt = dend - d;
5592 /* Want how many consecutive characters we can match in
5593 one shot, so, if necessary, adjust the count. */
5594 if (dcnt > dend2 - d2)
5595 dcnt = dend2 - d2;
5597 /* Compare that many; failure if mismatch, else move
5598 past them. */
5599 if (RE_TRANSLATE_P (translate)
5600 ? bcmp_translate (d, d2, dcnt, translate, target_multibyte)
5601 : memcmp (d, d2, dcnt))
5603 d = dfail;
5604 goto fail;
5606 d += dcnt, d2 += dcnt;
5609 break;
5612 /* begline matches the empty string at the beginning of the string
5613 (unless `not_bol' is set in `bufp'), and after newlines. */
5614 case begline:
5615 DEBUG_PRINT ("EXECUTING begline.\n");
5617 if (AT_STRINGS_BEG (d))
5619 if (!bufp->not_bol) break;
5621 else
5623 unsigned c;
5624 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5625 if (c == '\n')
5626 break;
5628 /* In all other cases, we fail. */
5629 goto fail;
5632 /* endline is the dual of begline. */
5633 case endline:
5634 DEBUG_PRINT ("EXECUTING endline.\n");
5636 if (AT_STRINGS_END (d))
5638 if (!bufp->not_eol) break;
5640 else
5642 PREFETCH_NOLIMIT ();
5643 if (*d == '\n')
5644 break;
5646 goto fail;
5649 /* Match at the very beginning of the data. */
5650 case begbuf:
5651 DEBUG_PRINT ("EXECUTING begbuf.\n");
5652 if (AT_STRINGS_BEG (d))
5653 break;
5654 goto fail;
5657 /* Match at the very end of the data. */
5658 case endbuf:
5659 DEBUG_PRINT ("EXECUTING endbuf.\n");
5660 if (AT_STRINGS_END (d))
5661 break;
5662 goto fail;
5665 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5666 pushes NULL as the value for the string on the stack. Then
5667 `POP_FAILURE_POINT' will keep the current value for the
5668 string, instead of restoring it. To see why, consider
5669 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5670 then the . fails against the \n. But the next thing we want
5671 to do is match the \n against the \n; if we restored the
5672 string value, we would be back at the foo.
5674 Because this is used only in specific cases, we don't need to
5675 check all the things that `on_failure_jump' does, to make
5676 sure the right things get saved on the stack. Hence we don't
5677 share its code. The only reason to push anything on the
5678 stack at all is that otherwise we would have to change
5679 `anychar's code to do something besides goto fail in this
5680 case; that seems worse than this. */
5681 case on_failure_keep_string_jump:
5682 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5683 DEBUG_PRINT ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5684 mcnt, p + mcnt);
5686 PUSH_FAILURE_POINT (p - 3, NULL);
5687 break;
5689 /* A nasty loop is introduced by the non-greedy *? and +?.
5690 With such loops, the stack only ever contains one failure point
5691 at a time, so that a plain on_failure_jump_loop kind of
5692 cycle detection cannot work. Worse yet, such a detection
5693 can not only fail to detect a cycle, but it can also wrongly
5694 detect a cycle (between different instantiations of the same
5695 loop).
5696 So the method used for those nasty loops is a little different:
5697 We use a special cycle-detection-stack-frame which is pushed
5698 when the on_failure_jump_nastyloop failure-point is *popped*.
5699 This special frame thus marks the beginning of one iteration
5700 through the loop and we can hence easily check right here
5701 whether something matched between the beginning and the end of
5702 the loop. */
5703 case on_failure_jump_nastyloop:
5704 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5705 DEBUG_PRINT ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5706 mcnt, p + mcnt);
5708 assert ((re_opcode_t)p[-4] == no_op);
5710 int cycle = 0;
5711 CHECK_INFINITE_LOOP (p - 4, d);
5712 if (!cycle)
5713 /* If there's a cycle, just continue without pushing
5714 this failure point. The failure point is the "try again"
5715 option, which shouldn't be tried.
5716 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5717 PUSH_FAILURE_POINT (p - 3, d);
5719 break;
5721 /* Simple loop detecting on_failure_jump: just check on the
5722 failure stack if the same spot was already hit earlier. */
5723 case on_failure_jump_loop:
5724 on_failure:
5725 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5726 DEBUG_PRINT ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5727 mcnt, p + mcnt);
5729 int cycle = 0;
5730 CHECK_INFINITE_LOOP (p - 3, d);
5731 if (cycle)
5732 /* If there's a cycle, get out of the loop, as if the matching
5733 had failed. We used to just `goto fail' here, but that was
5734 aborting the search a bit too early: we want to keep the
5735 empty-loop-match and keep matching after the loop.
5736 We want (x?)*y\1z to match both xxyz and xxyxz. */
5737 p += mcnt;
5738 else
5739 PUSH_FAILURE_POINT (p - 3, d);
5741 break;
5744 /* Uses of on_failure_jump:
5746 Each alternative starts with an on_failure_jump that points
5747 to the beginning of the next alternative. Each alternative
5748 except the last ends with a jump that in effect jumps past
5749 the rest of the alternatives. (They really jump to the
5750 ending jump of the following alternative, because tensioning
5751 these jumps is a hassle.)
5753 Repeats start with an on_failure_jump that points past both
5754 the repetition text and either the following jump or
5755 pop_failure_jump back to this on_failure_jump. */
5756 case on_failure_jump:
5757 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5758 DEBUG_PRINT ("EXECUTING on_failure_jump %d (to %p):\n",
5759 mcnt, p + mcnt);
5761 PUSH_FAILURE_POINT (p -3, d);
5762 break;
5764 /* This operation is used for greedy *.
5765 Compare the beginning of the repeat with what in the
5766 pattern follows its end. If we can establish that there
5767 is nothing that they would both match, i.e., that we
5768 would have to backtrack because of (as in, e.g., `a*a')
5769 then we can use a non-backtracking loop based on
5770 on_failure_keep_string_jump instead of on_failure_jump. */
5771 case on_failure_jump_smart:
5772 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5773 DEBUG_PRINT ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5774 mcnt, p + mcnt);
5776 re_char *p1 = p; /* Next operation. */
5777 /* Here, we discard `const', making re_match non-reentrant. */
5778 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5779 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5781 p -= 3; /* Reset so that we will re-execute the
5782 instruction once it's been changed. */
5784 EXTRACT_NUMBER (mcnt, p2 - 2);
5786 /* Ensure this is a indeed the trivial kind of loop
5787 we are expecting. */
5788 assert (skip_one_char (p1) == p2 - 3);
5789 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5790 DEBUG_STATEMENT (debug += 2);
5791 if (mutually_exclusive_p (bufp, p1, p2))
5793 /* Use a fast `on_failure_keep_string_jump' loop. */
5794 DEBUG_PRINT (" smart exclusive => fast loop.\n");
5795 *p3 = (unsigned char) on_failure_keep_string_jump;
5796 STORE_NUMBER (p2 - 2, mcnt + 3);
5798 else
5800 /* Default to a safe `on_failure_jump' loop. */
5801 DEBUG_PRINT (" smart default => slow loop.\n");
5802 *p3 = (unsigned char) on_failure_jump;
5804 DEBUG_STATEMENT (debug -= 2);
5806 break;
5808 /* Unconditionally jump (without popping any failure points). */
5809 case jump:
5810 unconditional_jump:
5811 IMMEDIATE_QUIT_CHECK;
5812 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5813 DEBUG_PRINT ("EXECUTING jump %d ", mcnt);
5814 p += mcnt; /* Do the jump. */
5815 DEBUG_PRINT ("(to %p).\n", p);
5816 break;
5819 /* Have to succeed matching what follows at least n times.
5820 After that, handle like `on_failure_jump'. */
5821 case succeed_n:
5822 /* Signedness doesn't matter since we only compare MCNT to 0. */
5823 EXTRACT_NUMBER (mcnt, p + 2);
5824 DEBUG_PRINT ("EXECUTING succeed_n %d.\n", mcnt);
5826 /* Originally, mcnt is how many times we HAVE to succeed. */
5827 if (mcnt != 0)
5829 /* Here, we discard `const', making re_match non-reentrant. */
5830 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5831 mcnt--;
5832 p += 4;
5833 PUSH_NUMBER (p2, mcnt);
5835 else
5836 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5837 goto on_failure;
5838 break;
5840 case jump_n:
5841 /* Signedness doesn't matter since we only compare MCNT to 0. */
5842 EXTRACT_NUMBER (mcnt, p + 2);
5843 DEBUG_PRINT ("EXECUTING jump_n %d.\n", mcnt);
5845 /* Originally, this is how many times we CAN jump. */
5846 if (mcnt != 0)
5848 /* Here, we discard `const', making re_match non-reentrant. */
5849 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5850 mcnt--;
5851 PUSH_NUMBER (p2, mcnt);
5852 goto unconditional_jump;
5854 /* If don't have to jump any more, skip over the rest of command. */
5855 else
5856 p += 4;
5857 break;
5859 case set_number_at:
5861 unsigned char *p2; /* Location of the counter. */
5862 DEBUG_PRINT ("EXECUTING set_number_at.\n");
5864 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5865 /* Here, we discard `const', making re_match non-reentrant. */
5866 p2 = (unsigned char*) p + mcnt;
5867 /* Signedness doesn't matter since we only copy MCNT's bits. */
5868 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5869 DEBUG_PRINT (" Setting %p to %d.\n", p2, mcnt);
5870 PUSH_NUMBER (p2, mcnt);
5871 break;
5874 case wordbound:
5875 case notwordbound:
5877 boolean not = (re_opcode_t) *(p - 1) == notwordbound;
5878 DEBUG_PRINT ("EXECUTING %swordbound.\n", not ? "not" : "");
5880 /* We SUCCEED (or FAIL) in one of the following cases: */
5882 /* Case 1: D is at the beginning or the end of string. */
5883 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5884 not = !not;
5885 else
5887 /* C1 is the character before D, S1 is the syntax of C1, C2
5888 is the character at D, and S2 is the syntax of C2. */
5889 re_wchar_t c1, c2;
5890 int s1, s2;
5891 int dummy;
5892 #ifdef emacs
5893 ssize_t offset = PTR_TO_OFFSET (d - 1);
5894 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5895 UPDATE_SYNTAX_TABLE_FAST (charpos);
5896 #endif
5897 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5898 s1 = SYNTAX (c1);
5899 #ifdef emacs
5900 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
5901 #endif
5902 PREFETCH_NOLIMIT ();
5903 GET_CHAR_AFTER (c2, d, dummy);
5904 s2 = SYNTAX (c2);
5906 if (/* Case 2: Only one of S1 and S2 is Sword. */
5907 ((s1 == Sword) != (s2 == Sword))
5908 /* Case 3: Both of S1 and S2 are Sword, and macro
5909 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5910 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5911 not = !not;
5913 if (not)
5914 break;
5915 else
5916 goto fail;
5919 case wordbeg:
5920 DEBUG_PRINT ("EXECUTING wordbeg.\n");
5922 /* We FAIL in one of the following cases: */
5924 /* Case 1: D is at the end of string. */
5925 if (AT_STRINGS_END (d))
5926 goto fail;
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);
5936 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5937 UPDATE_SYNTAX_TABLE_FAST (charpos);
5938 #endif
5939 PREFETCH ();
5940 GET_CHAR_AFTER (c2, d, dummy);
5941 s2 = SYNTAX (c2);
5943 /* Case 2: S2 is not Sword. */
5944 if (s2 != Sword)
5945 goto fail;
5947 /* Case 3: D is not at the beginning of string ... */
5948 if (!AT_STRINGS_BEG (d))
5950 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5951 #ifdef emacs
5952 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5953 #endif
5954 s1 = SYNTAX (c1);
5956 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5957 returns 0. */
5958 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5959 goto fail;
5962 break;
5964 case wordend:
5965 DEBUG_PRINT ("EXECUTING wordend.\n");
5967 /* We FAIL in one of the following cases: */
5969 /* Case 1: D is at the beginning of string. */
5970 if (AT_STRINGS_BEG (d))
5971 goto fail;
5972 else
5974 /* C1 is the character before D, S1 is the syntax of C1, C2
5975 is the character at D, and S2 is the syntax of C2. */
5976 re_wchar_t c1, c2;
5977 int s1, s2;
5978 int dummy;
5979 #ifdef emacs
5980 ssize_t offset = PTR_TO_OFFSET (d) - 1;
5981 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5982 UPDATE_SYNTAX_TABLE_FAST (charpos);
5983 #endif
5984 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5985 s1 = SYNTAX (c1);
5987 /* Case 2: S1 is not Sword. */
5988 if (s1 != Sword)
5989 goto fail;
5991 /* Case 3: D is not at the end of string ... */
5992 if (!AT_STRINGS_END (d))
5994 PREFETCH_NOLIMIT ();
5995 GET_CHAR_AFTER (c2, d, dummy);
5996 #ifdef emacs
5997 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos);
5998 #endif
5999 s2 = SYNTAX (c2);
6001 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6002 returns 0. */
6003 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6004 goto fail;
6007 break;
6009 case symbeg:
6010 DEBUG_PRINT ("EXECUTING symbeg.\n");
6012 /* We FAIL in one of the following cases: */
6014 /* Case 1: D is at the end of string. */
6015 if (AT_STRINGS_END (d))
6016 goto fail;
6017 else
6019 /* C1 is the character before D, S1 is the syntax of C1, C2
6020 is the character at D, and S2 is the syntax of C2. */
6021 re_wchar_t c1, c2;
6022 int s1, s2;
6023 #ifdef emacs
6024 ssize_t offset = PTR_TO_OFFSET (d);
6025 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6026 UPDATE_SYNTAX_TABLE_FAST (charpos);
6027 #endif
6028 PREFETCH ();
6029 c2 = RE_STRING_CHAR (d, target_multibyte);
6030 s2 = SYNTAX (c2);
6032 /* Case 2: S2 is neither Sword nor Ssymbol. */
6033 if (s2 != Sword && s2 != Ssymbol)
6034 goto fail;
6036 /* Case 3: D is not at the beginning of string ... */
6037 if (!AT_STRINGS_BEG (d))
6039 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6040 #ifdef emacs
6041 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6042 #endif
6043 s1 = SYNTAX (c1);
6045 /* ... and S1 is Sword or Ssymbol. */
6046 if (s1 == Sword || s1 == Ssymbol)
6047 goto fail;
6050 break;
6052 case symend:
6053 DEBUG_PRINT ("EXECUTING symend.\n");
6055 /* We FAIL in one of the following cases: */
6057 /* Case 1: D is at the beginning of string. */
6058 if (AT_STRINGS_BEG (d))
6059 goto fail;
6060 else
6062 /* C1 is the character before D, S1 is the syntax of C1, C2
6063 is the character at D, and S2 is the syntax of C2. */
6064 re_wchar_t c1, c2;
6065 int s1, s2;
6066 #ifdef emacs
6067 ssize_t offset = PTR_TO_OFFSET (d) - 1;
6068 ssize_t charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6069 UPDATE_SYNTAX_TABLE_FAST (charpos);
6070 #endif
6071 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6072 s1 = SYNTAX (c1);
6074 /* Case 2: S1 is neither Ssymbol nor Sword. */
6075 if (s1 != Sword && s1 != Ssymbol)
6076 goto fail;
6078 /* Case 3: D is not at the end of string ... */
6079 if (!AT_STRINGS_END (d))
6081 PREFETCH_NOLIMIT ();
6082 c2 = RE_STRING_CHAR (d, target_multibyte);
6083 #ifdef emacs
6084 UPDATE_SYNTAX_TABLE_FORWARD_FAST (charpos + 1);
6085 #endif
6086 s2 = SYNTAX (c2);
6088 /* ... and S2 is Sword or Ssymbol. */
6089 if (s2 == Sword || s2 == Ssymbol)
6090 goto fail;
6093 break;
6095 case syntaxspec:
6096 case notsyntaxspec:
6098 boolean not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6099 mcnt = *p++;
6100 DEBUG_PRINT ("EXECUTING %ssyntaxspec %d.\n", not ? "not" : "",
6101 mcnt);
6102 PREFETCH ();
6103 #ifdef emacs
6105 ssize_t offset = PTR_TO_OFFSET (d);
6106 ssize_t pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6107 UPDATE_SYNTAX_TABLE_FAST (pos1);
6109 #endif
6111 int len;
6112 re_wchar_t c;
6114 GET_CHAR_AFTER (c, d, len);
6115 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6116 goto fail;
6117 d += len;
6120 break;
6122 #ifdef emacs
6123 case at_dot:
6124 DEBUG_PRINT ("EXECUTING at_dot.\n");
6125 if (PTR_BYTE_POS (d) != PT_BYTE)
6126 goto fail;
6127 break;
6129 case categoryspec:
6130 case notcategoryspec:
6132 boolean not = (re_opcode_t) *(p - 1) == notcategoryspec;
6133 mcnt = *p++;
6134 DEBUG_PRINT ("EXECUTING %scategoryspec %d.\n",
6135 not ? "not" : "", mcnt);
6136 PREFETCH ();
6139 int len;
6140 re_wchar_t c;
6141 GET_CHAR_AFTER (c, d, len);
6142 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6143 goto fail;
6144 d += len;
6147 break;
6149 #endif /* emacs */
6151 default:
6152 abort ();
6154 continue; /* Successfully executed one pattern command; keep going. */
6157 /* We goto here if a matching operation fails. */
6158 fail:
6159 IMMEDIATE_QUIT_CHECK;
6160 if (!FAIL_STACK_EMPTY ())
6162 re_char *str, *pat;
6163 /* A restart point is known. Restore to that state. */
6164 DEBUG_PRINT ("\nFAIL:\n");
6165 POP_FAILURE_POINT (str, pat);
6166 switch (*pat++)
6168 case on_failure_keep_string_jump:
6169 assert (str == NULL);
6170 goto continue_failure_jump;
6172 case on_failure_jump_nastyloop:
6173 assert ((re_opcode_t)pat[-2] == no_op);
6174 PUSH_FAILURE_POINT (pat - 2, str);
6175 /* Fallthrough */
6177 case on_failure_jump_loop:
6178 case on_failure_jump:
6179 case succeed_n:
6180 d = str;
6181 continue_failure_jump:
6182 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6183 p = pat + mcnt;
6184 break;
6186 case no_op:
6187 /* A special frame used for nastyloops. */
6188 goto fail;
6190 default:
6191 abort ();
6194 assert (p >= bufp->buffer && p <= pend);
6196 if (d >= string1 && d <= end1)
6197 dend = end_match_1;
6199 else
6200 break; /* Matching at this starting point really fails. */
6201 } /* for (;;) */
6203 if (best_regs_set)
6204 goto restore_best_regs;
6206 FREE_VARIABLES ();
6208 return -1; /* Failure to match. */
6211 /* Subroutine definitions for re_match_2. */
6213 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6214 bytes; nonzero otherwise. */
6216 static int
6217 bcmp_translate (const_re_char *s1, const_re_char *s2, register ssize_t len,
6218 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6220 register re_char *p1 = s1, *p2 = s2;
6221 re_char *p1_end = s1 + len;
6222 re_char *p2_end = s2 + len;
6224 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6225 different lengths, but relying on a single `len' would break this. -sm */
6226 while (p1 < p1_end && p2 < p2_end)
6228 int p1_charlen, p2_charlen;
6229 re_wchar_t p1_ch, p2_ch;
6231 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6232 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6234 if (RE_TRANSLATE (translate, p1_ch)
6235 != RE_TRANSLATE (translate, p2_ch))
6236 return 1;
6238 p1 += p1_charlen, p2 += p2_charlen;
6241 if (p1 != p1_end || p2 != p2_end)
6242 return 1;
6244 return 0;
6247 /* Entry points for GNU code. */
6249 /* re_compile_pattern is the GNU regular expression compiler: it
6250 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6251 Returns 0 if the pattern was valid, otherwise an error string.
6253 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6254 are set in BUFP on entry.
6256 We call regex_compile to do the actual compilation. */
6258 const char *
6259 re_compile_pattern (const char *pattern, size_t length,
6260 #ifdef emacs
6261 bool posix_backtracking, const char *whitespace_regexp,
6262 #endif
6263 struct re_pattern_buffer *bufp)
6265 reg_errcode_t ret;
6267 /* GNU code is written to assume at least RE_NREGS registers will be set
6268 (and at least one extra will be -1). */
6269 bufp->regs_allocated = REGS_UNALLOCATED;
6271 /* And GNU code determines whether or not to get register information
6272 by passing null for the REGS argument to re_match, etc., not by
6273 setting no_sub. */
6274 bufp->no_sub = 0;
6276 ret = regex_compile ((re_char*) pattern, length,
6277 #ifdef emacs
6278 posix_backtracking,
6279 whitespace_regexp,
6280 #else
6281 re_syntax_options,
6282 #endif
6283 bufp);
6285 if (!ret)
6286 return NULL;
6287 return gettext (re_error_msgid[(int) ret]);
6289 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6291 /* Entry points compatible with 4.2 BSD regex library. We don't define
6292 them unless specifically requested. */
6294 #if defined _REGEX_RE_COMP || defined _LIBC
6296 /* BSD has one and only one pattern buffer. */
6297 static struct re_pattern_buffer re_comp_buf;
6299 char *
6300 # ifdef _LIBC
6301 /* Make these definitions weak in libc, so POSIX programs can redefine
6302 these names if they don't use our functions, and still use
6303 regcomp/regexec below without link errors. */
6304 weak_function
6305 # endif
6306 re_comp (const char *s)
6308 reg_errcode_t ret;
6310 if (!s)
6312 if (!re_comp_buf.buffer)
6313 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6314 return (char *) gettext ("No previous regular expression");
6315 return 0;
6318 if (!re_comp_buf.buffer)
6320 re_comp_buf.buffer = malloc (200);
6321 if (re_comp_buf.buffer == NULL)
6322 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6323 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6324 re_comp_buf.allocated = 200;
6326 re_comp_buf.fastmap = malloc (1 << BYTEWIDTH);
6327 if (re_comp_buf.fastmap == NULL)
6328 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6329 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6332 /* Since `re_exec' always passes NULL for the `regs' argument, we
6333 don't need to initialize the pattern buffer fields which affect it. */
6335 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6337 if (!ret)
6338 return NULL;
6340 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6341 return (char *) gettext (re_error_msgid[(int) ret]);
6346 # ifdef _LIBC
6347 weak_function
6348 # endif
6349 re_exec (const char *s)
6351 const size_t len = strlen (s);
6352 return re_search (&re_comp_buf, s, len, 0, len, 0) >= 0;
6354 #endif /* _REGEX_RE_COMP */
6356 /* POSIX.2 functions. Don't define these for Emacs. */
6358 #ifndef emacs
6360 /* regcomp takes a regular expression as a string and compiles it.
6362 PREG is a regex_t *. We do not expect any fields to be initialized,
6363 since POSIX says we shouldn't. Thus, we set
6365 `buffer' to the compiled pattern;
6366 `used' to the length of the compiled pattern;
6367 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6368 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6369 RE_SYNTAX_POSIX_BASIC;
6370 `fastmap' to an allocated space for the fastmap;
6371 `fastmap_accurate' to zero;
6372 `re_nsub' to the number of subexpressions in PATTERN.
6374 PATTERN is the address of the pattern string.
6376 CFLAGS is a series of bits which affect compilation.
6378 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6379 use POSIX basic syntax.
6381 If REG_NEWLINE is set, then . and [^...] don't match newline.
6382 Also, regexec will try a match beginning after every newline.
6384 If REG_ICASE is set, then we considers upper- and lowercase
6385 versions of letters to be equivalent when matching.
6387 If REG_NOSUB is set, then when PREG is passed to regexec, that
6388 routine will report only success or failure, and nothing about the
6389 registers.
6391 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6392 the return codes and their meanings.) */
6394 reg_errcode_t
6395 regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern,
6396 int cflags)
6398 reg_errcode_t ret;
6399 reg_syntax_t syntax
6400 = (cflags & REG_EXTENDED) ?
6401 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6403 /* regex_compile will allocate the space for the compiled pattern. */
6404 preg->buffer = 0;
6405 preg->allocated = 0;
6406 preg->used = 0;
6408 /* Try to allocate space for the fastmap. */
6409 preg->fastmap = malloc (1 << BYTEWIDTH);
6411 if (cflags & REG_ICASE)
6413 unsigned i;
6415 preg->translate = malloc (CHAR_SET_SIZE * sizeof *preg->translate);
6416 if (preg->translate == NULL)
6417 return (int) REG_ESPACE;
6419 /* Map uppercase characters to corresponding lowercase ones. */
6420 for (i = 0; i < CHAR_SET_SIZE; i++)
6421 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6423 else
6424 preg->translate = NULL;
6426 /* If REG_NEWLINE is set, newlines are treated differently. */
6427 if (cflags & REG_NEWLINE)
6428 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6429 syntax &= ~RE_DOT_NEWLINE;
6430 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6432 else
6433 syntax |= RE_NO_NEWLINE_ANCHOR;
6435 preg->no_sub = !!(cflags & REG_NOSUB);
6437 /* POSIX says a null character in the pattern terminates it, so we
6438 can use strlen here in compiling the pattern. */
6439 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6441 /* POSIX doesn't distinguish between an unmatched open-group and an
6442 unmatched close-group: both are REG_EPAREN. */
6443 if (ret == REG_ERPAREN)
6444 ret = REG_EPAREN;
6446 if (ret == REG_NOERROR && preg->fastmap)
6447 { /* Compute the fastmap now, since regexec cannot modify the pattern
6448 buffer. */
6449 re_compile_fastmap (preg);
6450 if (preg->can_be_null)
6451 { /* The fastmap can't be used anyway. */
6452 free (preg->fastmap);
6453 preg->fastmap = NULL;
6456 return ret;
6458 WEAK_ALIAS (__regcomp, regcomp)
6461 /* regexec searches for a given pattern, specified by PREG, in the
6462 string STRING.
6464 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6465 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6466 least NMATCH elements, and we set them to the offsets of the
6467 corresponding matched substrings.
6469 EFLAGS specifies `execution flags' which affect matching: if
6470 REG_NOTBOL is set, then ^ does not match at the beginning of the
6471 string; if REG_NOTEOL is set, then $ does not match at the end.
6473 We return 0 if we find a match and REG_NOMATCH if not. */
6475 reg_errcode_t
6476 regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
6477 size_t nmatch, regmatch_t pmatch[_Restrict_arr_], int eflags)
6479 regoff_t ret;
6480 struct re_registers regs;
6481 regex_t private_preg;
6482 size_t len = strlen (string);
6483 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6485 private_preg = *preg;
6487 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6488 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6490 /* The user has told us exactly how many registers to return
6491 information about, via `nmatch'. We have to pass that on to the
6492 matching routines. */
6493 private_preg.regs_allocated = REGS_FIXED;
6495 if (want_reg_info)
6497 regs.num_regs = nmatch;
6498 regs.start = TALLOC (nmatch * 2, regoff_t);
6499 if (regs.start == NULL)
6500 return REG_NOMATCH;
6501 regs.end = regs.start + nmatch;
6504 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6505 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6506 was a little bit longer but still only matching the real part.
6507 This works because the `endline' will check for a '\n' and will find a
6508 '\0', correctly deciding that this is not the end of a line.
6509 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6510 a convenient '\0' there. For all we know, the string could be preceded
6511 by '\n' which would throw things off. */
6513 /* Perform the searching operation. */
6514 ret = re_search (&private_preg, string, len,
6515 /* start: */ 0, /* range: */ len,
6516 want_reg_info ? &regs : 0);
6518 /* Copy the register information to the POSIX structure. */
6519 if (want_reg_info)
6521 if (ret >= 0)
6523 unsigned r;
6525 for (r = 0; r < nmatch; r++)
6527 pmatch[r].rm_so = regs.start[r];
6528 pmatch[r].rm_eo = regs.end[r];
6532 /* If we needed the temporary register info, free the space now. */
6533 free (regs.start);
6536 /* We want zero return to mean success, unlike `re_search'. */
6537 return ret >= 0 ? REG_NOERROR : REG_NOMATCH;
6539 WEAK_ALIAS (__regexec, regexec)
6542 /* Returns a message corresponding to an error code, ERR_CODE, returned
6543 from either regcomp or regexec. We don't use PREG here.
6545 ERR_CODE was previously called ERRCODE, but that name causes an
6546 error with msvc8 compiler. */
6548 size_t
6549 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6551 const char *msg;
6552 size_t msg_size;
6554 if (err_code < 0
6555 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6556 /* Only error codes returned by the rest of the code should be passed
6557 to this routine. If we are given anything else, or if other regex
6558 code generates an invalid error code, then the program has a bug.
6559 Dump core so we can fix it. */
6560 abort ();
6562 msg = gettext (re_error_msgid[err_code]);
6564 msg_size = strlen (msg) + 1; /* Includes the null. */
6566 if (errbuf_size != 0)
6568 if (msg_size > errbuf_size)
6570 memcpy (errbuf, msg, errbuf_size - 1);
6571 errbuf[errbuf_size - 1] = 0;
6573 else
6574 strcpy (errbuf, msg);
6577 return msg_size;
6579 WEAK_ALIAS (__regerror, regerror)
6582 /* Free dynamically allocated space used by PREG. */
6584 void
6585 regfree (regex_t *preg)
6587 free (preg->buffer);
6588 preg->buffer = NULL;
6590 preg->allocated = 0;
6591 preg->used = 0;
6593 free (preg->fastmap);
6594 preg->fastmap = NULL;
6595 preg->fastmap_accurate = 0;
6597 free (preg->translate);
6598 preg->translate = NULL;
6600 WEAK_ALIAS (__regfree, regfree)
6602 #endif /* not emacs */