soc/intel/xeon_sp: Align resources to 4K
[coreboot2.git] / util / kconfig / regex.c
blobbde5f8244382e36966a58d1c5711bc0affb1c4f3
1 /* Extended regular expression matching and search library,
2 version 0.12.
3 (Implements POSIX draft P10003.2/D11.2, except for
4 internationalization features.)
6 Copyright (C) 1993 Free Software Foundation, Inc.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
24 #pragma alloca
25 #endif
27 #ifndef _GNU_SOURCE
28 #define _GNU_SOURCE
29 #endif
31 /* We need this for `regex.h', and perhaps for the Emacs include files. */
32 #include <sys/types.h>
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
38 /* The `emacs' switch turns on certain matching commands
39 that make sense only in Emacs. */
40 #ifdef emacs
42 #include "lisp.h"
43 #include "buffer.h"
44 #include "syntax.h"
46 /* Emacs uses `NULL' as a predicate. */
47 #undef NULL
49 #else /* not emacs */
51 /* We used to test for `BSTRING' here, but only GCC and Emacs define
52 `BSTRING', as far as I know, and neither of them use this code. */
53 #if HAVE_STRING_H || STDC_HEADERS
54 #include <string.h>
55 #ifndef bcmp
56 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
57 #endif
58 #ifndef bcopy
59 #define bcopy(s, d, n) memcpy ((d), (s), (n))
60 #endif
61 #ifndef bzero
62 #define bzero(s, n) memset ((s), 0, (n))
63 #endif
64 #else
65 #include <strings.h>
66 #endif
68 #ifdef STDC_HEADERS
69 #include <stdlib.h>
70 #else
71 char *malloc ();
72 char *realloc ();
73 #endif
76 /* Define the syntax stuff for \<, \>, etc. */
78 /* This must be nonzero for the wordchar and notwordchar pattern
79 commands in re_match_2. */
80 #ifndef Sword
81 #define Sword 1
82 #endif
84 #ifdef SYNTAX_TABLE
86 extern char *re_syntax_table;
88 #else /* not SYNTAX_TABLE */
90 /* How many characters in the character set. */
91 #define CHAR_SET_SIZE 256
93 static char re_syntax_table[CHAR_SET_SIZE];
95 static void
96 init_syntax_once ()
98 register int c;
99 static int done = 0;
101 if (done)
102 return;
104 bzero (re_syntax_table, sizeof re_syntax_table);
106 for (c = 'a'; c <= 'z'; c++)
107 re_syntax_table[c] = Sword;
109 for (c = 'A'; c <= 'Z'; c++)
110 re_syntax_table[c] = Sword;
112 for (c = '0'; c <= '9'; c++)
113 re_syntax_table[c] = Sword;
115 re_syntax_table['_'] = Sword;
117 done = 1;
120 #endif /* not SYNTAX_TABLE */
122 #define SYNTAX(c) re_syntax_table[c]
124 #endif /* not emacs */
126 /* Get the interface, including the syntax bits. */
127 #include "regex.h"
129 /* isalpha etc. are used for the character classes. */
130 #include <ctype.h>
132 #ifndef isascii
133 #define isascii(c) 1
134 #endif
136 #ifdef isblank
137 #define ISBLANK(c) (isascii (c) && isblank (c))
138 #else
139 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
140 #endif
141 #ifdef isgraph
142 #define ISGRAPH(c) (isascii (c) && isgraph (c))
143 #else
144 #define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c))
145 #endif
147 #define ISPRINT(c) (isascii (c) && isprint (c))
148 #define ISDIGIT(c) (isascii (c) && isdigit (c))
149 #define ISALNUM(c) (isascii (c) && isalnum (c))
150 #define ISALPHA(c) (isascii (c) && isalpha (c))
151 #define ISCNTRL(c) (isascii (c) && iscntrl (c))
152 #define ISLOWER(c) (isascii (c) && islower (c))
153 #define ISPUNCT(c) (isascii (c) && ispunct (c))
154 #define ISSPACE(c) (isascii (c) && isspace (c))
155 #define ISUPPER(c) (isascii (c) && isupper (c))
156 #define ISXDIGIT(c) (isascii (c) && isxdigit (c))
158 #ifndef NULL
159 #define NULL 0
160 #endif
162 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
163 since ours (we hope) works properly with all combinations of
164 machines, compilers, `char' and `unsigned char' argument types.
165 (Per Bothner suggested the basic approach.) */
166 #undef SIGN_EXTEND_CHAR
167 #if __STDC__
168 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
169 #else /* not __STDC__ */
170 /* As in Harbison and Steele. */
171 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
172 #endif
174 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
175 use `alloca' instead of `malloc'. This is because using malloc in
176 re_search* or re_match* could cause memory leaks when C-g is used in
177 Emacs; also, malloc is slower and causes storage fragmentation. On
178 the other hand, malloc is more portable, and easier to debug.
180 Because we sometimes use alloca, some routines have to be macros,
181 not functions -- `alloca'-allocated space disappears at the end of the
182 function it is called in. */
184 #ifdef REGEX_MALLOC
186 #define REGEX_ALLOCATE malloc
187 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
189 #else /* not REGEX_MALLOC */
191 /* Emacs already defines alloca, sometimes. */
192 #ifndef alloca
194 /* Make alloca work the best possible way. */
195 #ifdef __GNUC__
196 #define alloca __builtin_alloca
197 #else /* not __GNUC__ */
198 #if HAVE_ALLOCA_H
199 #include <alloca.h>
200 #else /* not __GNUC__ or HAVE_ALLOCA_H */
201 #ifndef _AIX /* Already did AIX, up at the top. */
202 char *alloca ();
203 #endif /* not _AIX */
204 #endif /* not HAVE_ALLOCA_H */
205 #endif /* not __GNUC__ */
207 #endif /* not alloca */
209 #define REGEX_ALLOCATE alloca
211 /* Assumes a `char *destination' variable. */
212 #define REGEX_REALLOCATE(source, osize, nsize) \
213 (destination = (char *) alloca (nsize), \
214 bcopy (source, destination, osize), \
215 destination)
217 #endif /* not REGEX_MALLOC */
220 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
221 `string1' or just past its end. This works if PTR is NULL, which is
222 a good thing. */
223 #define FIRST_STRING_P(ptr) \
224 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
226 /* (Re)Allocate N items of type T using malloc, or fail. */
227 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
228 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
229 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
231 #define BYTEWIDTH 8 /* In bits. */
233 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
235 #define MAX(a, b) ((a) > (b) ? (a) : (b))
236 #define MIN(a, b) ((a) < (b) ? (a) : (b))
238 typedef char boolean;
239 #define false 0
240 #define true 1
242 /* These are the command codes that appear in compiled regular
243 expressions. Some opcodes are followed by argument bytes. A
244 command code can specify any interpretation whatsoever for its
245 arguments. Zero bytes may appear in the compiled regular expression.
247 The value of `exactn' is needed in search.c (search_buffer) in Emacs.
248 So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
249 `exactn' we use here must also be 1. */
251 typedef enum
253 no_op = 0,
255 /* Followed by one byte giving n, then by n literal bytes. */
256 exactn = 1,
258 /* Matches any (more or less) character. */
259 anychar,
261 /* Matches any one char belonging to specified set. First
262 following byte is number of bitmap bytes. Then come bytes
263 for a bitmap saying which chars are in. Bits in each byte
264 are ordered low-bit-first. A character is in the set if its
265 bit is 1. A character too large to have a bit in the map is
266 automatically not in the set. */
267 charset,
269 /* Same parameters as charset, but match any character that is
270 not one of those specified. */
271 charset_not,
273 /* Start remembering the text that is matched, for storing in a
274 register. Followed by one byte with the register number, in
275 the range 0 to one less than the pattern buffer's re_nsub
276 field. Then followed by one byte with the number of groups
277 inner to this one. (This last has to be part of the
278 start_memory only because we need it in the on_failure_jump
279 of re_match_2.) */
280 start_memory,
282 /* Stop remembering the text that is matched and store it in a
283 memory register. Followed by one byte with the register
284 number, in the range 0 to one less than `re_nsub' in the
285 pattern buffer, and one byte with the number of inner groups,
286 just like `start_memory'. (We need the number of inner
287 groups here because we don't have any easy way of finding the
288 corresponding start_memory when we're at a stop_memory.) */
289 stop_memory,
291 /* Match a duplicate of something remembered. Followed by one
292 byte containing the register number. */
293 duplicate,
295 /* Fail unless at beginning of line. */
296 begline,
298 /* Fail unless at end of line. */
299 endline,
301 /* Succeeds if at beginning of buffer (if emacs) or at beginning
302 of string to be matched (if not). */
303 begbuf,
305 /* Analogously, for end of buffer/string. */
306 endbuf,
308 /* Followed by two byte relative address to which to jump. */
309 jump,
311 /* Same as jump, but marks the end of an alternative. */
312 jump_past_alt,
314 /* Followed by two-byte relative address of place to resume at
315 in case of failure. */
316 on_failure_jump,
318 /* Like on_failure_jump, but pushes a placeholder instead of the
319 current string position when executed. */
320 on_failure_keep_string_jump,
322 /* Throw away latest failure point and then jump to following
323 two-byte relative address. */
324 pop_failure_jump,
326 /* Change to pop_failure_jump if know won't have to backtrack to
327 match; otherwise change to jump. This is used to jump
328 back to the beginning of a repeat. If what follows this jump
329 clearly won't match what the repeat does, such that we can be
330 sure that there is no use backtracking out of repetitions
331 already matched, then we change it to a pop_failure_jump.
332 Followed by two-byte address. */
333 maybe_pop_jump,
335 /* Jump to following two-byte address, and push a dummy failure
336 point. This failure point will be thrown away if an attempt
337 is made to use it for a failure. A `+' construct makes this
338 before the first repeat. Also used as an intermediary kind
339 of jump when compiling an alternative. */
340 dummy_failure_jump,
342 /* Push a dummy failure point and continue. Used at the end of
343 alternatives. */
344 push_dummy_failure,
346 /* Followed by two-byte relative address and two-byte number n.
347 After matching N times, jump to the address upon failure. */
348 succeed_n,
350 /* Followed by two-byte relative address, and two-byte number n.
351 Jump to the address N times, then fail. */
352 jump_n,
354 /* Set the following two-byte relative address to the
355 subsequent two-byte number. The address *includes* the two
356 bytes of number. */
357 set_number_at,
359 wordchar, /* Matches any word-constituent character. */
360 notwordchar, /* Matches any char that is not a word-constituent. */
362 wordbeg, /* Succeeds if at word beginning. */
363 wordend, /* Succeeds if at word end. */
365 wordbound, /* Succeeds if at a word boundary. */
366 notwordbound /* Succeeds if not at a word boundary. */
368 #ifdef emacs
369 ,before_dot, /* Succeeds if before point. */
370 at_dot, /* Succeeds if at point. */
371 after_dot, /* Succeeds if after point. */
373 /* Matches any character whose syntax is specified. Followed by
374 a byte which contains a syntax code, e.g., Sword. */
375 syntaxspec,
377 /* Matches any character whose syntax is not that specified. */
378 notsyntaxspec
379 #endif /* emacs */
380 } re_opcode_t;
382 /* Common operations on the compiled pattern. */
384 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
386 #define STORE_NUMBER(destination, number) \
387 do { \
388 (destination)[0] = (number) & 0377; \
389 (destination)[1] = (number) >> 8; \
390 } while (0)
392 /* Same as STORE_NUMBER, except increment DESTINATION to
393 the byte after where the number is stored. Therefore, DESTINATION
394 must be an lvalue. */
396 #define STORE_NUMBER_AND_INCR(destination, number) \
397 do { \
398 STORE_NUMBER (destination, number); \
399 (destination) += 2; \
400 } while (0)
402 /* Put into DESTINATION a number stored in two contiguous bytes starting
403 at SOURCE. */
405 #define EXTRACT_NUMBER(destination, source) \
406 do { \
407 (destination) = *(source) & 0377; \
408 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
409 } while (0)
411 #ifdef DEBUG
412 static void
413 extract_number (dest, source)
414 int *dest;
415 unsigned char *source;
417 int temp = SIGN_EXTEND_CHAR (*(source + 1));
418 *dest = *source & 0377;
419 *dest += temp << 8;
422 #ifndef EXTRACT_MACROS /* To debug the macros. */
423 #undef EXTRACT_NUMBER
424 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
425 #endif /* not EXTRACT_MACROS */
427 #endif /* DEBUG */
429 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
430 SOURCE must be an lvalue. */
432 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
433 do { \
434 EXTRACT_NUMBER (destination, source); \
435 (source) += 2; \
436 } while (0)
438 #ifdef DEBUG
439 static void
440 extract_number_and_incr (destination, source)
441 int *destination;
442 unsigned char **source;
444 extract_number (destination, *source);
445 *source += 2;
448 #ifndef EXTRACT_MACROS
449 #undef EXTRACT_NUMBER_AND_INCR
450 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
451 extract_number_and_incr (&dest, &src)
452 #endif /* not EXTRACT_MACROS */
454 #endif /* DEBUG */
456 /* If DEBUG is defined, Regex prints many voluminous messages about what
457 it is doing (if the variable `debug' is nonzero). If linked with the
458 main program in `iregex.c', you can enter patterns and strings
459 interactively. And if linked with the main program in `main.c' and
460 the other test files, you can run the already-written tests. */
462 #ifdef DEBUG
464 /* We use standard I/O for debugging. */
465 #include <stdio.h>
467 /* It is useful to test things that ``must'' be true when debugging. */
468 #include <assert.h>
470 static int debug = 0;
472 #define DEBUG_STATEMENT(e) e
473 #define DEBUG_PRINT1(x) if (debug) printf (x)
474 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
475 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
476 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
477 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
478 if (debug) print_partial_compiled_pattern (s, e)
479 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
480 if (debug) print_double_string (w, s1, sz1, s2, sz2)
483 extern void printchar ();
485 /* Print the fastmap in human-readable form. */
487 void
488 print_fastmap (fastmap)
489 char *fastmap;
491 unsigned was_a_range = 0;
492 unsigned i = 0;
494 while (i < (1 << BYTEWIDTH))
496 if (fastmap[i++])
498 was_a_range = 0;
499 printchar (i - 1);
500 while (i < (1 << BYTEWIDTH) && fastmap[i])
502 was_a_range = 1;
503 i++;
505 if (was_a_range)
507 printf ("-");
508 printchar (i - 1);
512 putchar ('\n');
516 /* Print a compiled pattern string in human-readable form, starting at
517 the START pointer into it and ending just before the pointer END. */
519 void
520 print_partial_compiled_pattern (start, end)
521 unsigned char *start;
522 unsigned char *end;
524 int mcnt, mcnt2;
525 unsigned char *p = start;
526 unsigned char *pend = end;
528 if (start == NULL)
530 printf ("(null)\n");
531 return;
534 /* Loop over pattern commands. */
535 while (p < pend)
537 switch ((re_opcode_t) *p++)
539 case no_op:
540 printf ("/no_op");
541 break;
543 case exactn:
544 mcnt = *p++;
545 printf ("/exactn/%d", mcnt);
548 putchar ('/');
549 printchar (*p++);
551 while (--mcnt);
552 break;
554 case start_memory:
555 mcnt = *p++;
556 printf ("/start_memory/%d/%d", mcnt, *p++);
557 break;
559 case stop_memory:
560 mcnt = *p++;
561 printf ("/stop_memory/%d/%d", mcnt, *p++);
562 break;
564 case duplicate:
565 printf ("/duplicate/%d", *p++);
566 break;
568 case anychar:
569 printf ("/anychar");
570 break;
572 case charset:
573 case charset_not:
575 register int c;
577 printf ("/charset%s",
578 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
580 assert (p + *p < pend);
582 for (c = 0; c < *p; c++)
584 unsigned bit;
585 unsigned char map_byte = p[1 + c];
587 putchar ('/');
589 for (bit = 0; bit < BYTEWIDTH; bit++)
590 if (map_byte & (1 << bit))
591 printchar (c * BYTEWIDTH + bit);
593 p += 1 + *p;
594 break;
597 case begline:
598 printf ("/begline");
599 break;
601 case endline:
602 printf ("/endline");
603 break;
605 case on_failure_jump:
606 extract_number_and_incr (&mcnt, &p);
607 printf ("/on_failure_jump/0/%d", mcnt);
608 break;
610 case on_failure_keep_string_jump:
611 extract_number_and_incr (&mcnt, &p);
612 printf ("/on_failure_keep_string_jump/0/%d", mcnt);
613 break;
615 case dummy_failure_jump:
616 extract_number_and_incr (&mcnt, &p);
617 printf ("/dummy_failure_jump/0/%d", mcnt);
618 break;
620 case push_dummy_failure:
621 printf ("/push_dummy_failure");
622 break;
624 case maybe_pop_jump:
625 extract_number_and_incr (&mcnt, &p);
626 printf ("/maybe_pop_jump/0/%d", mcnt);
627 break;
629 case pop_failure_jump:
630 extract_number_and_incr (&mcnt, &p);
631 printf ("/pop_failure_jump/0/%d", mcnt);
632 break;
634 case jump_past_alt:
635 extract_number_and_incr (&mcnt, &p);
636 printf ("/jump_past_alt/0/%d", mcnt);
637 break;
639 case jump:
640 extract_number_and_incr (&mcnt, &p);
641 printf ("/jump/0/%d", mcnt);
642 break;
644 case succeed_n:
645 extract_number_and_incr (&mcnt, &p);
646 extract_number_and_incr (&mcnt2, &p);
647 printf ("/succeed_n/0/%d/0/%d", mcnt, mcnt2);
648 break;
650 case jump_n:
651 extract_number_and_incr (&mcnt, &p);
652 extract_number_and_incr (&mcnt2, &p);
653 printf ("/jump_n/0/%d/0/%d", mcnt, mcnt2);
654 break;
656 case set_number_at:
657 extract_number_and_incr (&mcnt, &p);
658 extract_number_and_incr (&mcnt2, &p);
659 printf ("/set_number_at/0/%d/0/%d", mcnt, mcnt2);
660 break;
662 case wordbound:
663 printf ("/wordbound");
664 break;
666 case notwordbound:
667 printf ("/notwordbound");
668 break;
670 case wordbeg:
671 printf ("/wordbeg");
672 break;
674 case wordend:
675 printf ("/wordend");
677 #ifdef emacs
678 case before_dot:
679 printf ("/before_dot");
680 break;
682 case at_dot:
683 printf ("/at_dot");
684 break;
686 case after_dot:
687 printf ("/after_dot");
688 break;
690 case syntaxspec:
691 printf ("/syntaxspec");
692 mcnt = *p++;
693 printf ("/%d", mcnt);
694 break;
696 case notsyntaxspec:
697 printf ("/notsyntaxspec");
698 mcnt = *p++;
699 printf ("/%d", mcnt);
700 break;
701 #endif /* emacs */
703 case wordchar:
704 printf ("/wordchar");
705 break;
707 case notwordchar:
708 printf ("/notwordchar");
709 break;
711 case begbuf:
712 printf ("/begbuf");
713 break;
715 case endbuf:
716 printf ("/endbuf");
717 break;
719 default:
720 printf ("?%d", *(p-1));
723 printf ("/\n");
727 void
728 print_compiled_pattern (bufp)
729 struct re_pattern_buffer *bufp;
731 unsigned char *buffer = bufp->buffer;
733 print_partial_compiled_pattern (buffer, buffer + bufp->used);
734 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
736 if (bufp->fastmap_accurate && bufp->fastmap)
738 printf ("fastmap: ");
739 print_fastmap (bufp->fastmap);
742 printf ("re_nsub: %d\t", bufp->re_nsub);
743 printf ("regs_alloc: %d\t", bufp->regs_allocated);
744 printf ("can_be_null: %d\t", bufp->can_be_null);
745 printf ("newline_anchor: %d\n", bufp->newline_anchor);
746 printf ("no_sub: %d\t", bufp->no_sub);
747 printf ("not_bol: %d\t", bufp->not_bol);
748 printf ("not_eol: %d\t", bufp->not_eol);
749 printf ("syntax: %d\n", bufp->syntax);
750 /* Perhaps we should print the translate table? */
754 void
755 print_double_string (where, string1, size1, string2, size2)
756 const char *where;
757 const char *string1;
758 const char *string2;
759 int size1;
760 int size2;
762 unsigned this_char;
764 if (where == NULL)
765 printf ("(null)");
766 else
768 if (FIRST_STRING_P (where))
770 for (this_char = where - string1; this_char < size1; this_char++)
771 printchar (string1[this_char]);
773 where = string2;
776 for (this_char = where - string2; this_char < size2; this_char++)
777 printchar (string2[this_char]);
781 #else /* not DEBUG */
783 #undef assert
784 #define assert(e)
786 #define DEBUG_STATEMENT(e)
787 #define DEBUG_PRINT1(x)
788 #define DEBUG_PRINT2(x1, x2)
789 #define DEBUG_PRINT3(x1, x2, x3)
790 #define DEBUG_PRINT4(x1, x2, x3, x4)
791 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
792 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
794 #endif /* not DEBUG */
796 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
797 also be assigned to arbitrarily: each pattern buffer stores its own
798 syntax, so it can be changed between regex compilations. */
799 reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
802 /* Specify the precise syntax of regexps for compilation. This provides
803 for compatibility for various utilities which historically have
804 different, incompatible syntaxes.
806 The argument SYNTAX is a bit mask comprised of the various bits
807 defined in regex.h. We return the old syntax. */
809 reg_syntax_t
810 re_set_syntax (syntax)
811 reg_syntax_t syntax;
813 reg_syntax_t ret = re_syntax_options;
815 re_syntax_options = syntax;
816 return ret;
819 /* This table gives an error message for each of the error codes listed
820 in regex.h. Obviously the order here has to be same as there. */
822 static const char *re_error_msg[] =
823 { NULL, /* REG_NOERROR */
824 "No match", /* REG_NOMATCH */
825 "Invalid regular expression", /* REG_BADPAT */
826 "Invalid collation character", /* REG_ECOLLATE */
827 "Invalid character class name", /* REG_ECTYPE */
828 "Trailing backslash", /* REG_EESCAPE */
829 "Invalid back reference", /* REG_ESUBREG */
830 "Unmatched [ or [^", /* REG_EBRACK */
831 "Unmatched ( or \\(", /* REG_EPAREN */
832 "Unmatched \\{", /* REG_EBRACE */
833 "Invalid content of \\{\\}", /* REG_BADBR */
834 "Invalid range end", /* REG_ERANGE */
835 "Memory exhausted", /* REG_ESPACE */
836 "Invalid preceding regular expression", /* REG_BADRPT */
837 "Premature end of regular expression", /* REG_EEND */
838 "Regular expression too big", /* REG_ESIZE */
839 "Unmatched ) or \\)", /* REG_ERPAREN */
842 /* Subroutine declarations and macros for regex_compile. */
844 static void store_op1 (), store_op2 ();
845 static void insert_op1 (), insert_op2 ();
846 static boolean at_begline_loc_p (), at_endline_loc_p ();
847 static boolean group_in_compile_stack ();
848 static reg_errcode_t compile_range ();
850 /* Fetch the next character in the uncompiled pattern---translating it
851 if necessary. Also cast from a signed character in the constant
852 string passed to us by the user to an unsigned char that we can use
853 as an array index (in, e.g., `translate'). */
854 #define PATFETCH(c) \
855 do {if (p == pend) return REG_EEND; \
856 c = (unsigned char) *p++; \
857 if (translate) c = translate[c]; \
858 } while (0)
860 /* Fetch the next character in the uncompiled pattern, with no
861 translation. */
862 #define PATFETCH_RAW(c) \
863 do {if (p == pend) return REG_EEND; \
864 c = (unsigned char) *p++; \
865 } while (0)
867 /* Go backwards one character in the pattern. */
868 #define PATUNFETCH p--
871 /* If `translate' is non-null, return translate[D], else just D. We
872 cast the subscript to translate because some data is declared as
873 `char *', to avoid warnings when a string constant is passed. But
874 when we use a character as a subscript we must make it unsigned. */
875 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
878 /* Macros for outputting the compiled pattern into `buffer'. */
880 /* If the buffer isn't allocated when it comes in, use this. */
881 #define INIT_BUF_SIZE 32
883 /* Make sure we have at least N more bytes of space in buffer. */
884 #define GET_BUFFER_SPACE(n) \
885 while (b - bufp->buffer + (n) > bufp->allocated) \
886 EXTEND_BUFFER ()
888 /* Make sure we have one more byte of buffer space and then add C to it. */
889 #define BUF_PUSH(c) \
890 do { \
891 GET_BUFFER_SPACE (1); \
892 *b++ = (unsigned char) (c); \
893 } while (0)
896 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
897 #define BUF_PUSH_2(c1, c2) \
898 do { \
899 GET_BUFFER_SPACE (2); \
900 *b++ = (unsigned char) (c1); \
901 *b++ = (unsigned char) (c2); \
902 } while (0)
905 /* As with BUF_PUSH_2, except for three bytes. */
906 #define BUF_PUSH_3(c1, c2, c3) \
907 do { \
908 GET_BUFFER_SPACE (3); \
909 *b++ = (unsigned char) (c1); \
910 *b++ = (unsigned char) (c2); \
911 *b++ = (unsigned char) (c3); \
912 } while (0)
915 /* Store a jump with opcode OP at LOC to location TO. We store a
916 relative address offset by the three bytes the jump itself occupies. */
917 #define STORE_JUMP(op, loc, to) \
918 store_op1 (op, loc, (to) - (loc) - 3)
920 /* Likewise, for a two-argument jump. */
921 #define STORE_JUMP2(op, loc, to, arg) \
922 store_op2 (op, loc, (to) - (loc) - 3, arg)
924 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
925 #define INSERT_JUMP(op, loc, to) \
926 insert_op1 (op, loc, (to) - (loc) - 3, b)
928 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
929 #define INSERT_JUMP2(op, loc, to, arg) \
930 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
933 /* This is not an arbitrary limit: the arguments which represent offsets
934 into the pattern are two bytes long. So if 2^16 bytes turns out to
935 be too small, many things would have to change. */
936 #define MAX_BUF_SIZE (1L << 16)
939 /* Extend the buffer by twice its current size via realloc and
940 reset the pointers that pointed into the old block to point to the
941 correct places in the new one. If extending the buffer results in it
942 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
943 #define EXTEND_BUFFER() \
944 do { \
945 unsigned char *old_buffer = bufp->buffer; \
946 if (bufp->allocated == MAX_BUF_SIZE) \
947 return REG_ESIZE; \
948 bufp->allocated <<= 1; \
949 if (bufp->allocated > MAX_BUF_SIZE) \
950 bufp->allocated = MAX_BUF_SIZE; \
951 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
952 if (bufp->buffer == NULL) \
953 return REG_ESPACE; \
954 /* If the buffer moved, move all the pointers into it. */ \
955 if (old_buffer != bufp->buffer) \
957 b = (b - old_buffer) + bufp->buffer; \
958 begalt = (begalt - old_buffer) + bufp->buffer; \
959 if (fixup_alt_jump) \
960 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
961 if (laststart) \
962 laststart = (laststart - old_buffer) + bufp->buffer; \
963 if (pending_exact) \
964 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
966 } while (0)
969 /* Since we have one byte reserved for the register number argument to
970 {start,stop}_memory, the maximum number of groups we can report
971 things about is what fits in that byte. */
972 #define MAX_REGNUM 255
974 /* But patterns can have more than `MAX_REGNUM' registers. We just
975 ignore the excess. */
976 typedef unsigned regnum_t;
979 /* Macros for the compile stack. */
981 /* Since offsets can go either forwards or backwards, this type needs to
982 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
983 typedef int pattern_offset_t;
985 typedef struct
987 pattern_offset_t begalt_offset;
988 pattern_offset_t fixup_alt_jump;
989 pattern_offset_t inner_group_offset;
990 pattern_offset_t laststart_offset;
991 regnum_t regnum;
992 } compile_stack_elt_t;
995 typedef struct
997 compile_stack_elt_t *stack;
998 unsigned size;
999 unsigned avail; /* Offset of next open position. */
1000 } compile_stack_type;
1003 #define INIT_COMPILE_STACK_SIZE 32
1005 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1006 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1008 /* The next available element. */
1009 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1012 /* Set the bit for character C in a list. */
1013 #define SET_LIST_BIT(c) \
1014 (b[((unsigned char) (c)) / BYTEWIDTH] \
1015 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1018 /* Get the next unsigned number in the uncompiled pattern. */
1019 #define GET_UNSIGNED_NUMBER(num) \
1020 { if (p != pend) \
1022 PATFETCH (c); \
1023 while (ISDIGIT (c)) \
1025 if (num < 0) \
1026 num = 0; \
1027 num = num * 10 + c - '0'; \
1028 if (p == pend) \
1029 break; \
1030 PATFETCH (c); \
1035 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1037 #define IS_CHAR_CLASS(string) \
1038 (STREQ (string, "alpha") || STREQ (string, "upper") \
1039 || STREQ (string, "lower") || STREQ (string, "digit") \
1040 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1041 || STREQ (string, "space") || STREQ (string, "print") \
1042 || STREQ (string, "punct") || STREQ (string, "graph") \
1043 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1045 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1046 Returns one of error codes defined in `regex.h', or zero for success.
1048 Assumes the `allocated' (and perhaps `buffer') and `translate'
1049 fields are set in BUFP on entry.
1051 If it succeeds, results are put in BUFP (if it returns an error, the
1052 contents of BUFP are undefined):
1053 `buffer' is the compiled pattern;
1054 `syntax' is set to SYNTAX;
1055 `used' is set to the length of the compiled pattern;
1056 `fastmap_accurate' is zero;
1057 `re_nsub' is the number of subexpressions in PATTERN;
1058 `not_bol' and `not_eol' are zero;
1060 The `fastmap' and `newline_anchor' fields are neither
1061 examined nor set. */
1063 static reg_errcode_t
1064 regex_compile (pattern, size, syntax, bufp)
1065 const char *pattern;
1066 int size;
1067 reg_syntax_t syntax;
1068 struct re_pattern_buffer *bufp;
1070 /* We fetch characters from PATTERN here. Even though PATTERN is
1071 `char *' (i.e., signed), we declare these variables as unsigned, so
1072 they can be reliably used as array indices. */
1073 register unsigned char c, c1;
1075 /* A random tempory spot in PATTERN. */
1076 const char *p1;
1078 /* Points to the end of the buffer, where we should append. */
1079 register unsigned char *b;
1081 /* Keeps track of unclosed groups. */
1082 compile_stack_type compile_stack;
1084 /* Points to the current (ending) position in the pattern. */
1085 const char *p = pattern;
1086 const char *pend = pattern + size;
1088 /* How to translate the characters in the pattern. */
1089 char *translate = bufp->translate;
1091 /* Address of the count-byte of the most recently inserted `exactn'
1092 command. This makes it possible to tell if a new exact-match
1093 character can be added to that command or if the character requires
1094 a new `exactn' command. */
1095 unsigned char *pending_exact = NULL;
1097 /* Address of start of the most recently finished expression.
1098 This tells, e.g., postfix * where to find the start of its
1099 operand. Reset at the beginning of groups and alternatives. */
1100 unsigned char *laststart = NULL;
1102 /* Address of beginning of regexp, or inside of last group. */
1103 unsigned char *begalt;
1105 /* Place in the uncompiled pattern (i.e., the {) to
1106 which to go back if the interval is invalid. */
1107 const char *beg_interval;
1109 /* Address of the place where a forward jump should go to the end of
1110 the containing expression. Each alternative of an `or' -- except the
1111 last -- ends with a forward jump of this sort. */
1112 unsigned char *fixup_alt_jump = NULL;
1114 /* Counts open-groups as they are encountered. Remembered for the
1115 matching close-group on the compile stack, so the same register
1116 number is put in the stop_memory as the start_memory. */
1117 regnum_t regnum = 0;
1119 #ifdef DEBUG
1120 DEBUG_PRINT1 ("\nCompiling pattern: ");
1121 if (debug)
1123 unsigned debug_count;
1125 for (debug_count = 0; debug_count < size; debug_count++)
1126 printchar (pattern[debug_count]);
1127 putchar ('\n');
1129 #endif /* DEBUG */
1131 /* Initialize the compile stack. */
1132 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1133 if (compile_stack.stack == NULL)
1134 return REG_ESPACE;
1136 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1137 compile_stack.avail = 0;
1139 /* Initialize the pattern buffer. */
1140 bufp->syntax = syntax;
1141 bufp->fastmap_accurate = 0;
1142 bufp->not_bol = bufp->not_eol = 0;
1144 /* Set `used' to zero, so that if we return an error, the pattern
1145 printer (for debugging) will think there's no pattern. We reset it
1146 at the end. */
1147 bufp->used = 0;
1149 /* Always count groups, whether or not bufp->no_sub is set. */
1150 bufp->re_nsub = 0;
1152 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1153 /* Initialize the syntax table. */
1154 init_syntax_once ();
1155 #endif
1157 if (bufp->allocated == 0)
1159 if (bufp->buffer)
1160 { /* If zero allocated, but buffer is non-null, try to realloc
1161 enough space. This loses if buffer's address is bogus, but
1162 that is the user's responsibility. */
1163 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1165 else
1166 { /* Caller did not allocate a buffer. Do it for them. */
1167 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1169 if (!bufp->buffer) return REG_ESPACE;
1171 bufp->allocated = INIT_BUF_SIZE;
1174 begalt = b = bufp->buffer;
1176 /* Loop through the uncompiled pattern until we're at the end. */
1177 while (p != pend)
1179 PATFETCH (c);
1181 switch (c)
1183 case '^':
1185 if ( /* If at start of pattern, it's an operator. */
1186 p == pattern + 1
1187 /* If context independent, it's an operator. */
1188 || syntax & RE_CONTEXT_INDEP_ANCHORS
1189 /* Otherwise, depends on what's come before. */
1190 || at_begline_loc_p (pattern, p, syntax))
1191 BUF_PUSH (begline);
1192 else
1193 goto normal_char;
1195 break;
1198 case '$':
1200 if ( /* If at end of pattern, it's an operator. */
1201 p == pend
1202 /* If context independent, it's an operator. */
1203 || syntax & RE_CONTEXT_INDEP_ANCHORS
1204 /* Otherwise, depends on what's next. */
1205 || at_endline_loc_p (p, pend, syntax))
1206 BUF_PUSH (endline);
1207 else
1208 goto normal_char;
1210 break;
1213 case '+':
1214 case '?':
1215 if ((syntax & RE_BK_PLUS_QM)
1216 || (syntax & RE_LIMITED_OPS))
1217 goto normal_char;
1218 handle_plus:
1219 case '*':
1220 /* If there is no previous pattern... */
1221 if (!laststart)
1223 if (syntax & RE_CONTEXT_INVALID_OPS)
1224 return REG_BADRPT;
1225 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1226 goto normal_char;
1230 /* Are we optimizing this jump? */
1231 boolean keep_string_p = false;
1233 /* 1 means zero (many) matches is allowed. */
1234 char zero_times_ok = 0, many_times_ok = 0;
1236 /* If there is a sequence of repetition chars, collapse it
1237 down to just one (the right one). We can't combine
1238 interval operators with these because of, e.g., `a{2}*',
1239 which should only match an even number of `a's. */
1241 for (;;)
1243 zero_times_ok |= c != '+';
1244 many_times_ok |= c != '?';
1246 if (p == pend)
1247 break;
1249 PATFETCH (c);
1251 if (c == '*'
1252 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1255 else if (syntax & RE_BK_PLUS_QM && c == '\\')
1257 if (p == pend) return REG_EESCAPE;
1259 PATFETCH (c1);
1260 if (!(c1 == '+' || c1 == '?'))
1262 PATUNFETCH;
1263 PATUNFETCH;
1264 break;
1267 c = c1;
1269 else
1271 PATUNFETCH;
1272 break;
1275 /* If we get here, we found another repeat character. */
1278 /* Star, etc. applied to an empty pattern is equivalent
1279 to an empty pattern. */
1280 if (!laststart)
1281 break;
1283 /* Now we know whether or not zero matches is allowed
1284 and also whether or not two or more matches is allowed. */
1285 if (many_times_ok)
1286 { /* More than one repetition is allowed, so put in at the
1287 end a backward relative jump from `b' to before the next
1288 jump we're going to put in below (which jumps from
1289 laststart to after this jump).
1291 But if we are at the `*' in the exact sequence `.*\n',
1292 insert an unconditional jump backwards to the .,
1293 instead of the beginning of the loop. This way we only
1294 push a failure point once, instead of every time
1295 through the loop. */
1296 assert (p - 1 > pattern);
1298 /* Allocate the space for the jump. */
1299 GET_BUFFER_SPACE (3);
1301 /* We know we are not at the first character of the pattern,
1302 because laststart was nonzero. And we've already
1303 incremented `p', by the way, to be the character after
1304 the `*'. Do we have to do something analogous here
1305 for null bytes, because of RE_DOT_NOT_NULL? */
1306 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1307 && zero_times_ok
1308 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1309 && !(syntax & RE_DOT_NEWLINE))
1310 { /* We have .*\n. */
1311 STORE_JUMP (jump, b, laststart);
1312 keep_string_p = true;
1314 else
1315 /* Anything else. */
1316 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1318 /* We've added more stuff to the buffer. */
1319 b += 3;
1322 /* On failure, jump from laststart to b + 3, which will be the
1323 end of the buffer after this jump is inserted. */
1324 GET_BUFFER_SPACE (3);
1325 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1326 : on_failure_jump,
1327 laststart, b + 3);
1328 pending_exact = 0;
1329 b += 3;
1331 if (!zero_times_ok)
1333 /* At least one repetition is required, so insert a
1334 `dummy_failure_jump' before the initial
1335 `on_failure_jump' instruction of the loop. This
1336 effects a skip over that instruction the first time
1337 we hit that loop. */
1338 GET_BUFFER_SPACE (3);
1339 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1340 b += 3;
1343 break;
1346 case '.':
1347 laststart = b;
1348 BUF_PUSH (anychar);
1349 break;
1352 case '[':
1354 boolean had_char_class = false;
1356 if (p == pend) return REG_EBRACK;
1358 /* Ensure that we have enough space to push a charset: the
1359 opcode, the length count, and the bitset; 34 bytes in all. */
1360 GET_BUFFER_SPACE (34);
1362 laststart = b;
1364 /* We test `*p == '^' twice, instead of using an if
1365 statement, so we only need one BUF_PUSH. */
1366 BUF_PUSH (*p == '^' ? charset_not : charset);
1367 if (*p == '^')
1368 p++;
1370 /* Remember the first position in the bracket expression. */
1371 p1 = p;
1373 /* Push the number of bytes in the bitmap. */
1374 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1376 /* Clear the whole map. */
1377 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1379 /* charset_not matches newline according to a syntax bit. */
1380 if ((re_opcode_t) b[-2] == charset_not
1381 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1382 SET_LIST_BIT ('\n');
1384 /* Read in characters and ranges, setting map bits. */
1385 for (;;)
1387 if (p == pend) return REG_EBRACK;
1389 PATFETCH (c);
1391 /* \ might escape characters inside [...] and [^...]. */
1392 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1394 if (p == pend) return REG_EESCAPE;
1396 PATFETCH (c1);
1397 SET_LIST_BIT (c1);
1398 continue;
1401 /* Could be the end of the bracket expression. If it's
1402 not (i.e., when the bracket expression is `[]' so
1403 far), the ']' character bit gets set way below. */
1404 if (c == ']' && p != p1 + 1)
1405 break;
1407 /* Look ahead to see if it's a range when the last thing
1408 was a character class. */
1409 if (had_char_class && c == '-' && *p != ']')
1410 return REG_ERANGE;
1412 /* Look ahead to see if it's a range when the last thing
1413 was a character: if this is a hyphen not at the
1414 beginning or the end of a list, then it's the range
1415 operator. */
1416 if (c == '-'
1417 && !(p - 2 >= pattern && p[-2] == '[')
1418 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1419 && *p != ']')
1421 reg_errcode_t ret
1422 = compile_range (&p, pend, translate, syntax, b);
1423 if (ret != REG_NOERROR) return ret;
1426 else if (p[0] == '-' && p[1] != ']')
1427 { /* This handles ranges made up of characters only. */
1428 reg_errcode_t ret;
1430 /* Move past the `-'. */
1431 PATFETCH (c1);
1433 ret = compile_range (&p, pend, translate, syntax, b);
1434 if (ret != REG_NOERROR) return ret;
1437 /* See if we're at the beginning of a possible character
1438 class. */
1440 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
1441 { /* Leave room for the null. */
1442 char str[CHAR_CLASS_MAX_LENGTH + 1];
1444 PATFETCH (c);
1445 c1 = 0;
1447 /* If pattern is `[[:'. */
1448 if (p == pend) return REG_EBRACK;
1450 for (;;)
1452 PATFETCH (c);
1453 if (c == ':' || c == ']' || p == pend
1454 || c1 == CHAR_CLASS_MAX_LENGTH)
1455 break;
1456 str[c1++] = c;
1458 str[c1] = '\0';
1460 /* If isn't a word bracketed by `[:' and:`]':
1461 undo the ending character, the letters, and leave
1462 the leading `:' and `[' (but set bits for them). */
1463 if (c == ':' && *p == ']')
1465 int ch;
1466 boolean is_alnum = STREQ (str, "alnum");
1467 boolean is_alpha = STREQ (str, "alpha");
1468 boolean is_blank = STREQ (str, "blank");
1469 boolean is_cntrl = STREQ (str, "cntrl");
1470 boolean is_digit = STREQ (str, "digit");
1471 boolean is_graph = STREQ (str, "graph");
1472 boolean is_lower = STREQ (str, "lower");
1473 boolean is_print = STREQ (str, "print");
1474 boolean is_punct = STREQ (str, "punct");
1475 boolean is_space = STREQ (str, "space");
1476 boolean is_upper = STREQ (str, "upper");
1477 boolean is_xdigit = STREQ (str, "xdigit");
1479 if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
1481 /* Throw away the ] at the end of the character
1482 class. */
1483 PATFETCH (c);
1485 if (p == pend) return REG_EBRACK;
1487 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
1489 if ( (is_alnum && ISALNUM (ch))
1490 || (is_alpha && ISALPHA (ch))
1491 || (is_blank && ISBLANK (ch))
1492 || (is_cntrl && ISCNTRL (ch))
1493 || (is_digit && ISDIGIT (ch))
1494 || (is_graph && ISGRAPH (ch))
1495 || (is_lower && ISLOWER (ch))
1496 || (is_print && ISPRINT (ch))
1497 || (is_punct && ISPUNCT (ch))
1498 || (is_space && ISSPACE (ch))
1499 || (is_upper && ISUPPER (ch))
1500 || (is_xdigit && ISXDIGIT (ch)))
1501 SET_LIST_BIT (ch);
1503 had_char_class = true;
1505 else
1507 c1++;
1508 while (c1--)
1509 PATUNFETCH;
1510 SET_LIST_BIT ('[');
1511 SET_LIST_BIT (':');
1512 had_char_class = false;
1515 else
1517 had_char_class = false;
1518 SET_LIST_BIT (c);
1522 /* Discard any (non)matching list bytes that are all 0 at the
1523 end of the map. Decrease the map-length byte too. */
1524 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
1525 b[-1]--;
1526 b += b[-1];
1528 break;
1531 case '(':
1532 if (syntax & RE_NO_BK_PARENS)
1533 goto handle_open;
1534 else
1535 goto normal_char;
1538 case ')':
1539 if (syntax & RE_NO_BK_PARENS)
1540 goto handle_close;
1541 else
1542 goto normal_char;
1545 case '\n':
1546 if (syntax & RE_NEWLINE_ALT)
1547 goto handle_alt;
1548 else
1549 goto normal_char;
1552 case '|':
1553 if (syntax & RE_NO_BK_VBAR)
1554 goto handle_alt;
1555 else
1556 goto normal_char;
1559 case '{':
1560 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1561 goto handle_interval;
1562 else
1563 goto normal_char;
1566 case '\\':
1567 if (p == pend) return REG_EESCAPE;
1569 /* Do not translate the character after the \, so that we can
1570 distinguish, e.g., \B from \b, even if we normally would
1571 translate, e.g., B to b. */
1572 PATFETCH_RAW (c);
1574 switch (c)
1576 case '(':
1577 if (syntax & RE_NO_BK_PARENS)
1578 goto normal_backslash;
1580 handle_open:
1581 bufp->re_nsub++;
1582 regnum++;
1584 if (COMPILE_STACK_FULL)
1586 RETALLOC (compile_stack.stack, compile_stack.size << 1,
1587 compile_stack_elt_t);
1588 if (compile_stack.stack == NULL) return REG_ESPACE;
1590 compile_stack.size <<= 1;
1593 /* These are the values to restore when we hit end of this
1594 group. They are all relative offsets, so that if the
1595 whole pattern moves because of realloc, they will still
1596 be valid. */
1597 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
1598 COMPILE_STACK_TOP.fixup_alt_jump
1599 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
1600 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
1601 COMPILE_STACK_TOP.regnum = regnum;
1603 /* We will eventually replace the 0 with the number of
1604 groups inner to this one. But do not push a
1605 start_memory for groups beyond the last one we can
1606 represent in the compiled pattern. */
1607 if (regnum <= MAX_REGNUM)
1609 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
1610 BUF_PUSH_3 (start_memory, regnum, 0);
1613 compile_stack.avail++;
1615 fixup_alt_jump = 0;
1616 laststart = 0;
1617 begalt = b;
1618 /* If we've reached MAX_REGNUM groups, then this open
1619 won't actually generate any code, so we'll have to
1620 clear pending_exact explicitly. */
1621 pending_exact = 0;
1622 break;
1625 case ')':
1626 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
1628 if (COMPILE_STACK_EMPTY)
1629 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1630 goto normal_backslash;
1631 else
1632 return REG_ERPAREN;
1634 handle_close:
1635 if (fixup_alt_jump)
1636 { /* Push a dummy failure point at the end of the
1637 alternative for a possible future
1638 `pop_failure_jump' to pop. See comments at
1639 `push_dummy_failure' in `re_match_2'. */
1640 BUF_PUSH (push_dummy_failure);
1642 /* We allocated space for this jump when we assigned
1643 to `fixup_alt_jump', in the `handle_alt' case below. */
1644 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
1647 /* See similar code for backslashed left paren above. */
1648 if (COMPILE_STACK_EMPTY)
1649 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1650 goto normal_char;
1651 else
1652 return REG_ERPAREN;
1654 /* Since we just checked for an empty stack above, this
1655 ``can't happen''. */
1656 assert (compile_stack.avail != 0);
1658 /* We don't just want to restore into `regnum', because
1659 later groups should continue to be numbered higher,
1660 as in `(ab)c(de)' -- the second group is #2. */
1661 regnum_t this_group_regnum;
1663 compile_stack.avail--;
1664 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
1665 fixup_alt_jump
1666 = COMPILE_STACK_TOP.fixup_alt_jump
1667 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
1668 : 0;
1669 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
1670 this_group_regnum = COMPILE_STACK_TOP.regnum;
1671 /* If we've reached MAX_REGNUM groups, then this open
1672 won't actually generate any code, so we'll have to
1673 clear pending_exact explicitly. */
1674 pending_exact = 0;
1676 /* We're at the end of the group, so now we know how many
1677 groups were inside this one. */
1678 if (this_group_regnum <= MAX_REGNUM)
1680 unsigned char *inner_group_loc
1681 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
1683 *inner_group_loc = regnum - this_group_regnum;
1684 BUF_PUSH_3 (stop_memory, this_group_regnum,
1685 regnum - this_group_regnum);
1688 break;
1691 case '|': /* `\|'. */
1692 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
1693 goto normal_backslash;
1694 handle_alt:
1695 if (syntax & RE_LIMITED_OPS)
1696 goto normal_char;
1698 /* Insert before the previous alternative a jump which
1699 jumps to this alternative if the former fails. */
1700 GET_BUFFER_SPACE (3);
1701 INSERT_JUMP (on_failure_jump, begalt, b + 6);
1702 pending_exact = 0;
1703 b += 3;
1705 /* The alternative before this one has a jump after it
1706 which gets executed if it gets matched. Adjust that
1707 jump so it will jump to this alternative's analogous
1708 jump (put in below, which in turn will jump to the next
1709 (if any) alternative's such jump, etc.). The last such
1710 jump jumps to the correct final destination. A picture:
1711 _____ _____
1712 | | | |
1713 | v | v
1714 a | b | c
1716 If we are at `b', then fixup_alt_jump right now points to a
1717 three-byte space after `a'. We'll put in the jump, set
1718 fixup_alt_jump to right after `b', and leave behind three
1719 bytes which we'll fill in when we get to after `c'. */
1721 if (fixup_alt_jump)
1722 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
1724 /* Mark and leave space for a jump after this alternative,
1725 to be filled in later either by next alternative or
1726 when know we're at the end of a series of alternatives. */
1727 fixup_alt_jump = b;
1728 GET_BUFFER_SPACE (3);
1729 b += 3;
1731 laststart = 0;
1732 begalt = b;
1733 break;
1736 case '{':
1737 /* If \{ is a literal. */
1738 if (!(syntax & RE_INTERVALS)
1739 /* If we're at `\{' and it's not the open-interval
1740 operator. */
1741 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
1742 || (p - 2 == pattern && p == pend))
1743 goto normal_backslash;
1745 handle_interval:
1747 /* If got here, then the syntax allows intervals. */
1749 /* At least (most) this many matches must be made. */
1750 int lower_bound = -1, upper_bound = -1;
1752 beg_interval = p - 1;
1754 if (p == pend)
1756 if (syntax & RE_NO_BK_BRACES)
1757 goto unfetch_interval;
1758 else
1759 return REG_EBRACE;
1762 GET_UNSIGNED_NUMBER (lower_bound);
1764 if (c == ',')
1766 GET_UNSIGNED_NUMBER (upper_bound);
1767 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
1769 else
1770 /* Interval such as `{1}' => match exactly once. */
1771 upper_bound = lower_bound;
1773 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
1774 || lower_bound > upper_bound)
1776 if (syntax & RE_NO_BK_BRACES)
1777 goto unfetch_interval;
1778 else
1779 return REG_BADBR;
1782 if (!(syntax & RE_NO_BK_BRACES))
1784 if (c != '\\') return REG_EBRACE;
1786 PATFETCH (c);
1789 if (c != '}')
1791 if (syntax & RE_NO_BK_BRACES)
1792 goto unfetch_interval;
1793 else
1794 return REG_BADBR;
1797 /* We just parsed a valid interval. */
1799 /* If it's invalid to have no preceding re. */
1800 if (!laststart)
1802 if (syntax & RE_CONTEXT_INVALID_OPS)
1803 return REG_BADRPT;
1804 else if (syntax & RE_CONTEXT_INDEP_OPS)
1805 laststart = b;
1806 else
1807 goto unfetch_interval;
1810 /* If the upper bound is zero, don't want to succeed at
1811 all; jump from `laststart' to `b + 3', which will be
1812 the end of the buffer after we insert the jump. */
1813 if (upper_bound == 0)
1815 GET_BUFFER_SPACE (3);
1816 INSERT_JUMP (jump, laststart, b + 3);
1817 b += 3;
1820 /* Otherwise, we have a nontrivial interval. When
1821 we're all done, the pattern will look like:
1822 set_number_at <jump count> <upper bound>
1823 set_number_at <succeed_n count> <lower bound>
1824 succeed_n <after jump addr> <succed_n count>
1825 <body of loop>
1826 jump_n <succeed_n addr> <jump count>
1827 (The upper bound and `jump_n' are omitted if
1828 `upper_bound' is 1, though.) */
1829 else
1830 { /* If the upper bound is > 1, we need to insert
1831 more at the end of the loop. */
1832 unsigned nbytes = 10 + (upper_bound > 1) * 10;
1834 GET_BUFFER_SPACE (nbytes);
1836 /* Initialize lower bound of the `succeed_n', even
1837 though it will be set during matching by its
1838 attendant `set_number_at' (inserted next),
1839 because `re_compile_fastmap' needs to know.
1840 Jump to the `jump_n' we might insert below. */
1841 INSERT_JUMP2 (succeed_n, laststart,
1842 b + 5 + (upper_bound > 1) * 5,
1843 lower_bound);
1844 b += 5;
1846 /* Code to initialize the lower bound. Insert
1847 before the `succeed_n'. The `5' is the last two
1848 bytes of this `set_number_at', plus 3 bytes of
1849 the following `succeed_n'. */
1850 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
1851 b += 5;
1853 if (upper_bound > 1)
1854 { /* More than one repetition is allowed, so
1855 append a backward jump to the `succeed_n'
1856 that starts this interval.
1858 When we've reached this during matching,
1859 we'll have matched the interval once, so
1860 jump back only `upper_bound - 1' times. */
1861 STORE_JUMP2 (jump_n, b, laststart + 5,
1862 upper_bound - 1);
1863 b += 5;
1865 /* The location we want to set is the second
1866 parameter of the `jump_n'; that is `b-2' as
1867 an absolute address. `laststart' will be
1868 the `set_number_at' we're about to insert;
1869 `laststart+3' the number to set, the source
1870 for the relative address. But we are
1871 inserting into the middle of the pattern --
1872 so everything is getting moved up by 5.
1873 Conclusion: (b - 2) - (laststart + 3) + 5,
1874 i.e., b - laststart.
1876 We insert this at the beginning of the loop
1877 so that if we fail during matching, we'll
1878 reinitialize the bounds. */
1879 insert_op2 (set_number_at, laststart, b - laststart,
1880 upper_bound - 1, b);
1881 b += 5;
1884 pending_exact = 0;
1885 beg_interval = NULL;
1887 break;
1889 unfetch_interval:
1890 /* If an invalid interval, match the characters as literals. */
1891 assert (beg_interval);
1892 p = beg_interval;
1893 beg_interval = NULL;
1895 /* normal_char and normal_backslash need `c'. */
1896 PATFETCH (c);
1898 if (!(syntax & RE_NO_BK_BRACES))
1900 if (p > pattern && p[-1] == '\\')
1901 goto normal_backslash;
1903 goto normal_char;
1905 #ifdef emacs
1906 /* There is no way to specify the before_dot and after_dot
1907 operators. rms says this is ok. --karl */
1908 case '=':
1909 BUF_PUSH (at_dot);
1910 break;
1912 case 's':
1913 laststart = b;
1914 PATFETCH (c);
1915 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
1916 break;
1918 case 'S':
1919 laststart = b;
1920 PATFETCH (c);
1921 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
1922 break;
1923 #endif /* emacs */
1926 case 'w':
1927 laststart = b;
1928 BUF_PUSH (wordchar);
1929 break;
1932 case 'W':
1933 laststart = b;
1934 BUF_PUSH (notwordchar);
1935 break;
1938 case '<':
1939 BUF_PUSH (wordbeg);
1940 break;
1942 case '>':
1943 BUF_PUSH (wordend);
1944 break;
1946 case 'b':
1947 BUF_PUSH (wordbound);
1948 break;
1950 case 'B':
1951 BUF_PUSH (notwordbound);
1952 break;
1954 case '`':
1955 BUF_PUSH (begbuf);
1956 break;
1958 case '\'':
1959 BUF_PUSH (endbuf);
1960 break;
1962 case '1': case '2': case '3': case '4': case '5':
1963 case '6': case '7': case '8': case '9':
1964 if (syntax & RE_NO_BK_REFS)
1965 goto normal_char;
1967 c1 = c - '0';
1969 if (c1 > regnum)
1970 return REG_ESUBREG;
1972 /* Can't back reference to a subexpression if inside of it. */
1973 if (group_in_compile_stack (compile_stack, c1))
1974 goto normal_char;
1976 laststart = b;
1977 BUF_PUSH_2 (duplicate, c1);
1978 break;
1981 case '+':
1982 case '?':
1983 if (syntax & RE_BK_PLUS_QM)
1984 goto handle_plus;
1985 else
1986 goto normal_backslash;
1988 default:
1989 normal_backslash:
1990 /* You might think it would be useful for \ to mean
1991 not to translate; but if we don't translate it
1992 it will never match anything. */
1993 c = TRANSLATE (c);
1994 goto normal_char;
1996 break;
1999 default:
2000 /* Expects the character in `c'. */
2001 normal_char:
2002 /* If no exactn currently being built. */
2003 if (!pending_exact
2005 /* If last exactn not at current position. */
2006 || pending_exact + *pending_exact + 1 != b
2008 /* We have only one byte following the exactn for the count. */
2009 || *pending_exact == (1 << BYTEWIDTH) - 1
2011 /* If followed by a repetition operator. */
2012 || *p == '*' || *p == '^'
2013 || ((syntax & RE_BK_PLUS_QM)
2014 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2015 : (*p == '+' || *p == '?'))
2016 || ((syntax & RE_INTERVALS)
2017 && ((syntax & RE_NO_BK_BRACES)
2018 ? *p == '{'
2019 : (p[0] == '\\' && p[1] == '{'))))
2021 /* Start building a new exactn. */
2023 laststart = b;
2025 BUF_PUSH_2 (exactn, 0);
2026 pending_exact = b - 1;
2029 BUF_PUSH (c);
2030 (*pending_exact)++;
2031 break;
2032 } /* switch (c) */
2033 } /* while p != pend */
2036 /* Through the pattern now. */
2038 if (fixup_alt_jump)
2039 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2041 if (!COMPILE_STACK_EMPTY)
2042 return REG_EPAREN;
2044 free (compile_stack.stack);
2046 /* We have succeeded; set the length of the buffer. */
2047 bufp->used = b - bufp->buffer;
2049 #ifdef DEBUG
2050 if (debug)
2052 DEBUG_PRINT1 ("\nCompiled pattern: ");
2053 print_compiled_pattern (bufp);
2055 #endif /* DEBUG */
2057 return REG_NOERROR;
2058 } /* regex_compile */
2060 /* Subroutines for `regex_compile'. */
2062 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2064 static void
2065 store_op1 (op, loc, arg)
2066 re_opcode_t op;
2067 unsigned char *loc;
2068 int arg;
2070 *loc = (unsigned char) op;
2071 STORE_NUMBER (loc + 1, arg);
2075 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2077 static void
2078 store_op2 (op, loc, arg1, arg2)
2079 re_opcode_t op;
2080 unsigned char *loc;
2081 int arg1, arg2;
2083 *loc = (unsigned char) op;
2084 STORE_NUMBER (loc + 1, arg1);
2085 STORE_NUMBER (loc + 3, arg2);
2089 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2090 for OP followed by two-byte integer parameter ARG. */
2092 static void
2093 insert_op1 (op, loc, arg, end)
2094 re_opcode_t op;
2095 unsigned char *loc;
2096 int arg;
2097 unsigned char *end;
2099 register unsigned char *pfrom = end;
2100 register unsigned char *pto = end + 3;
2102 while (pfrom != loc)
2103 *--pto = *--pfrom;
2105 store_op1 (op, loc, arg);
2109 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2111 static void
2112 insert_op2 (op, loc, arg1, arg2, end)
2113 re_opcode_t op;
2114 unsigned char *loc;
2115 int arg1, arg2;
2116 unsigned char *end;
2118 register unsigned char *pfrom = end;
2119 register unsigned char *pto = end + 5;
2121 while (pfrom != loc)
2122 *--pto = *--pfrom;
2124 store_op2 (op, loc, arg1, arg2);
2128 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2129 after an alternative or a begin-subexpression. We assume there is at
2130 least one character before the ^. */
2132 static boolean
2133 at_begline_loc_p (pattern, p, syntax)
2134 const char *pattern, *p;
2135 reg_syntax_t syntax;
2137 const char *prev = p - 2;
2138 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2140 return
2141 /* After a subexpression? */
2142 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2143 /* After an alternative? */
2144 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2148 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2149 at least one character after the $, i.e., `P < PEND'. */
2151 static boolean
2152 at_endline_loc_p (p, pend, syntax)
2153 const char *p, *pend;
2154 int syntax;
2156 const char *next = p;
2157 boolean next_backslash = *next == '\\';
2158 const char *next_next = p + 1 < pend ? p + 1 : NULL;
2160 return
2161 /* Before a subexpression? */
2162 (syntax & RE_NO_BK_PARENS ? *next == ')'
2163 : next_backslash && next_next && *next_next == ')')
2164 /* Before an alternative? */
2165 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2166 : next_backslash && next_next && *next_next == '|');
2170 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2171 false if it's not. */
2173 static boolean
2174 group_in_compile_stack (compile_stack, regnum)
2175 compile_stack_type compile_stack;
2176 regnum_t regnum;
2178 int this_element;
2180 for (this_element = compile_stack.avail - 1;
2181 this_element >= 0;
2182 this_element--)
2183 if (compile_stack.stack[this_element].regnum == regnum)
2184 return true;
2186 return false;
2190 /* Read the ending character of a range (in a bracket expression) from the
2191 uncompiled pattern *P_PTR (which ends at PEND). We assume the
2192 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2193 Then we set the translation of all bits between the starting and
2194 ending characters (inclusive) in the compiled pattern B.
2196 Return an error code.
2198 We use these short variable names so we can use the same macros as
2199 `regex_compile' itself. */
2201 static reg_errcode_t
2202 compile_range (p_ptr, pend, translate, syntax, b)
2203 const char **p_ptr, *pend;
2204 char *translate;
2205 reg_syntax_t syntax;
2206 unsigned char *b;
2208 unsigned this_char;
2210 const char *p = *p_ptr;
2211 int range_start, range_end;
2213 if (p == pend)
2214 return REG_ERANGE;
2216 /* Even though the pattern is a signed `char *', we need to fetch
2217 with unsigned char *'s; if the high bit of the pattern character
2218 is set, the range endpoints will be negative if we fetch using a
2219 signed char *.
2221 We also want to fetch the endpoints without translating them; the
2222 appropriate translation is done in the bit-setting loop below. */
2223 range_start = ((unsigned char *) p)[-2];
2224 range_end = ((unsigned char *) p)[0];
2226 /* Have to increment the pointer into the pattern string, so the
2227 caller isn't still at the ending character. */
2228 (*p_ptr)++;
2230 /* If the start is after the end, the range is empty. */
2231 if (range_start > range_end)
2232 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2234 /* Here we see why `this_char' has to be larger than an `unsigned
2235 char' -- the range is inclusive, so if `range_end' == 0xff
2236 (assuming 8-bit characters), we would otherwise go into an infinite
2237 loop, since all characters <= 0xff. */
2238 for (this_char = range_start; this_char <= range_end; this_char++)
2240 SET_LIST_BIT (TRANSLATE (this_char));
2243 return REG_NOERROR;
2246 /* Failure stack declarations and macros; both re_compile_fastmap and
2247 re_match_2 use a failure stack. These have to be macros because of
2248 REGEX_ALLOCATE. */
2251 /* Number of failure points for which to initially allocate space
2252 when matching. If this number is exceeded, we allocate more
2253 space, so it is not a hard limit. */
2254 #ifndef INIT_FAILURE_ALLOC
2255 #define INIT_FAILURE_ALLOC 5
2256 #endif
2258 /* Roughly the maximum number of failure points on the stack. Would be
2259 exactly that if always used MAX_FAILURE_SPACE each time we failed.
2260 This is a variable only so users of regex can assign to it; we never
2261 change it ourselves. */
2262 int re_max_failures = 2000;
2264 typedef const unsigned char *fail_stack_elt_t;
2266 typedef struct
2268 fail_stack_elt_t *stack;
2269 unsigned size;
2270 unsigned avail; /* Offset of next open position. */
2271 } fail_stack_type;
2273 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
2274 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2275 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
2276 #define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])
2279 /* Initialize `fail_stack'. Do `return -2' if the alloc fails. */
2281 #define INIT_FAIL_STACK() \
2282 do { \
2283 fail_stack.stack = (fail_stack_elt_t *) \
2284 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
2286 if (fail_stack.stack == NULL) \
2287 return -2; \
2289 fail_stack.size = INIT_FAILURE_ALLOC; \
2290 fail_stack.avail = 0; \
2291 } while (0)
2294 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
2296 Return 1 if succeeds, and 0 if either ran out of memory
2297 allocating space for it or it was already too large.
2299 REGEX_REALLOCATE requires `destination' be declared. */
2301 #define DOUBLE_FAIL_STACK(fail_stack) \
2302 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
2303 ? 0 \
2304 : ((fail_stack).stack = (fail_stack_elt_t *) \
2305 REGEX_REALLOCATE ((fail_stack).stack, \
2306 (fail_stack).size * sizeof (fail_stack_elt_t), \
2307 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
2309 (fail_stack).stack == NULL \
2310 ? 0 \
2311 : ((fail_stack).size <<= 1, \
2312 1)))
2315 /* Push PATTERN_OP on FAIL_STACK.
2317 Return 1 if was able to do so and 0 if ran out of memory allocating
2318 space to do so. */
2319 #define PUSH_PATTERN_OP(pattern_op, fail_stack) \
2320 ((FAIL_STACK_FULL () \
2321 && !DOUBLE_FAIL_STACK (fail_stack)) \
2322 ? 0 \
2323 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \
2326 /* This pushes an item onto the failure stack. Must be a four-byte
2327 value. Assumes the variable `fail_stack'. Probably should only
2328 be called from within `PUSH_FAILURE_POINT'. */
2329 #define PUSH_FAILURE_ITEM(item) \
2330 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2332 /* The complement operation. Assumes `fail_stack' is nonempty. */
2333 #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2335 /* Used to omit pushing failure point id's when we're not debugging. */
2336 #ifdef DEBUG
2337 #define DEBUG_PUSH PUSH_FAILURE_ITEM
2338 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2339 #else
2340 #define DEBUG_PUSH(item)
2341 #define DEBUG_POP(item_addr)
2342 #endif
2345 /* Push the information about the state we will need
2346 if we ever fail back to it.
2348 Requires variables fail_stack, regstart, regend, reg_info, and
2349 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
2350 declared.
2352 Does `return FAILURE_CODE' if runs out of memory. */
2354 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
2355 do { \
2356 char *destination; \
2357 /* Must be int, so when we don't save any registers, the arithmetic \
2358 of 0 + -1 isn't done as unsigned. */ \
2359 int this_reg; \
2361 DEBUG_STATEMENT (failure_id++); \
2362 DEBUG_STATEMENT (nfailure_points_pushed++); \
2363 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
2364 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
2365 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
2367 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
2368 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
2370 /* Ensure we have enough space allocated for what we will push. */ \
2371 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
2373 if (!DOUBLE_FAIL_STACK (fail_stack)) \
2374 return failure_code; \
2376 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
2377 (fail_stack).size); \
2378 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2381 /* Push the info, starting with the registers. */ \
2382 DEBUG_PRINT1 ("\n"); \
2384 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
2385 this_reg++) \
2387 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
2388 DEBUG_STATEMENT (num_regs_pushed++); \
2390 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2391 PUSH_FAILURE_ITEM (regstart[this_reg]); \
2393 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2394 PUSH_FAILURE_ITEM (regend[this_reg]); \
2396 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
2397 DEBUG_PRINT2 (" match_null=%d", \
2398 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
2399 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
2400 DEBUG_PRINT2 (" matched_something=%d", \
2401 MATCHED_SOMETHING (reg_info[this_reg])); \
2402 DEBUG_PRINT2 (" ever_matched=%d", \
2403 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
2404 DEBUG_PRINT1 ("\n"); \
2405 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \
2408 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
2409 PUSH_FAILURE_ITEM (lowest_active_reg); \
2411 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
2412 PUSH_FAILURE_ITEM (highest_active_reg); \
2414 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
2415 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
2416 PUSH_FAILURE_ITEM (pattern_place); \
2418 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
2419 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
2420 size2); \
2421 DEBUG_PRINT1 ("'\n"); \
2422 PUSH_FAILURE_ITEM (string_place); \
2424 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
2425 DEBUG_PUSH (failure_id); \
2426 } while (0)
2428 /* This is the number of items that are pushed and popped on the stack
2429 for each register. */
2430 #define NUM_REG_ITEMS 3
2432 /* Individual items aside from the registers. */
2433 #ifdef DEBUG
2434 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
2435 #else
2436 #define NUM_NONREG_ITEMS 4
2437 #endif
2439 /* We push at most this many items on the stack. */
2440 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2442 /* We actually push this many items. */
2443 #define NUM_FAILURE_ITEMS \
2444 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
2445 + NUM_NONREG_ITEMS)
2447 /* How many items can still be added to the stack without overflowing it. */
2448 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2451 /* Pops what PUSH_FAIL_STACK pushes.
2453 We restore into the parameters, all of which should be lvalues:
2454 STR -- the saved data position.
2455 PAT -- the saved pattern position.
2456 LOW_REG, HIGH_REG -- the highest and lowest active registers.
2457 REGSTART, REGEND -- arrays of string positions.
2458 REG_INFO -- array of information about each subexpression.
2460 Also assumes the variables `fail_stack' and (if debugging), `bufp',
2461 `pend', `string1', `size1', `string2', and `size2'. */
2463 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2465 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
2466 int this_reg; \
2467 const unsigned char *string_temp; \
2469 assert (!FAIL_STACK_EMPTY ()); \
2471 /* Remove failure points and point to how many regs pushed. */ \
2472 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
2473 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
2474 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
2476 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
2478 DEBUG_POP (&failure_id); \
2479 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
2481 /* If the saved string location is NULL, it came from an \
2482 on_failure_keep_string_jump opcode, and we want to throw away the \
2483 saved NULL, thus retaining our current position in the string. */ \
2484 string_temp = POP_FAILURE_ITEM (); \
2485 if (string_temp != NULL) \
2486 str = (const char *) string_temp; \
2488 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
2489 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
2490 DEBUG_PRINT1 ("'\n"); \
2492 pat = (unsigned char *) POP_FAILURE_ITEM (); \
2493 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
2494 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
2496 /* Restore register info. */ \
2497 high_reg = (unsigned) POP_FAILURE_ITEM (); \
2498 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
2500 low_reg = (unsigned) POP_FAILURE_ITEM (); \
2501 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
2503 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
2505 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
2507 reg_info[this_reg].word = POP_FAILURE_ITEM (); \
2508 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
2510 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2511 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2513 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2514 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2517 DEBUG_STATEMENT (nfailure_points_popped++); \
2518 } /* POP_FAILURE_POINT */
2520 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2521 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2522 characters can start a string that matches the pattern. This fastmap
2523 is used by re_search to skip quickly over impossible starting points.
2525 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2526 area as BUFP->fastmap.
2528 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2529 the pattern buffer.
2531 Returns 0 if we succeed, -2 if an internal error. */
2534 re_compile_fastmap (bufp)
2535 struct re_pattern_buffer *bufp;
2537 int j, k;
2538 fail_stack_type fail_stack;
2539 #ifndef REGEX_MALLOC
2540 char *destination;
2541 #endif
2542 /* We don't push any register information onto the failure stack. */
2543 unsigned num_regs = 0;
2545 register char *fastmap = bufp->fastmap;
2546 unsigned char *pattern = bufp->buffer;
2547 unsigned long size = bufp->used;
2548 const unsigned char *p = pattern;
2549 register unsigned char *pend = pattern + size;
2551 /* Assume that each path through the pattern can be null until
2552 proven otherwise. We set this false at the bottom of switch
2553 statement, to which we get only if a particular path doesn't
2554 match the empty string. */
2555 boolean path_can_be_null = true;
2557 /* We aren't doing a `succeed_n' to begin with. */
2558 boolean succeed_n_p = false;
2560 assert (fastmap != NULL && p != NULL);
2562 INIT_FAIL_STACK ();
2563 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
2564 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2565 bufp->can_be_null = 0;
2567 while (p != pend || !FAIL_STACK_EMPTY ())
2569 if (p == pend)
2571 bufp->can_be_null |= path_can_be_null;
2573 /* Reset for next path. */
2574 path_can_be_null = true;
2576 p = fail_stack.stack[--fail_stack.avail];
2579 /* We should never be about to go beyond the end of the pattern. */
2580 assert (p < pend);
2582 #ifdef SWITCH_ENUM_BUG
2583 switch ((int) ((re_opcode_t) *p++))
2584 #else
2585 switch ((re_opcode_t) *p++)
2586 #endif
2589 /* I guess the idea here is to simply not bother with a fastmap
2590 if a backreference is used, since it's too hard to figure out
2591 the fastmap for the corresponding group. Setting
2592 `can_be_null' stops `re_search_2' from using the fastmap, so
2593 that is all we do. */
2594 case duplicate:
2595 bufp->can_be_null = 1;
2596 return 0;
2599 /* Following are the cases which match a character. These end
2600 with `break'. */
2602 case exactn:
2603 fastmap[p[1]] = 1;
2604 break;
2607 case charset:
2608 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2609 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2610 fastmap[j] = 1;
2611 break;
2614 case charset_not:
2615 /* Chars beyond end of map must be allowed. */
2616 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2617 fastmap[j] = 1;
2619 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2620 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2621 fastmap[j] = 1;
2622 break;
2625 case wordchar:
2626 for (j = 0; j < (1 << BYTEWIDTH); j++)
2627 if (SYNTAX (j) == Sword)
2628 fastmap[j] = 1;
2629 break;
2632 case notwordchar:
2633 for (j = 0; j < (1 << BYTEWIDTH); j++)
2634 if (SYNTAX (j) != Sword)
2635 fastmap[j] = 1;
2636 break;
2639 case anychar:
2640 /* `.' matches anything ... */
2641 for (j = 0; j < (1 << BYTEWIDTH); j++)
2642 fastmap[j] = 1;
2644 /* ... except perhaps newline. */
2645 if (!(bufp->syntax & RE_DOT_NEWLINE))
2646 fastmap['\n'] = 0;
2648 /* Return if we have already set `can_be_null'; if we have,
2649 then the fastmap is irrelevant. Something's wrong here. */
2650 else if (bufp->can_be_null)
2651 return 0;
2653 /* Otherwise, have to check alternative paths. */
2654 break;
2657 #ifdef emacs
2658 case syntaxspec:
2659 k = *p++;
2660 for (j = 0; j < (1 << BYTEWIDTH); j++)
2661 if (SYNTAX (j) == (enum syntaxcode) k)
2662 fastmap[j] = 1;
2663 break;
2666 case notsyntaxspec:
2667 k = *p++;
2668 for (j = 0; j < (1 << BYTEWIDTH); j++)
2669 if (SYNTAX (j) != (enum syntaxcode) k)
2670 fastmap[j] = 1;
2671 break;
2674 /* All cases after this match the empty string. These end with
2675 `continue'. */
2678 case before_dot:
2679 case at_dot:
2680 case after_dot:
2681 continue;
2682 #endif /* not emacs */
2685 case no_op:
2686 case begline:
2687 case endline:
2688 case begbuf:
2689 case endbuf:
2690 case wordbound:
2691 case notwordbound:
2692 case wordbeg:
2693 case wordend:
2694 case push_dummy_failure:
2695 continue;
2698 case jump_n:
2699 case pop_failure_jump:
2700 case maybe_pop_jump:
2701 case jump:
2702 case jump_past_alt:
2703 case dummy_failure_jump:
2704 EXTRACT_NUMBER_AND_INCR (j, p);
2705 p += j;
2706 if (j > 0)
2707 continue;
2709 /* Jump backward implies we just went through the body of a
2710 loop and matched nothing. Opcode jumped to should be
2711 `on_failure_jump' or `succeed_n'. Just treat it like an
2712 ordinary jump. For a * loop, it has pushed its failure
2713 point already; if so, discard that as redundant. */
2714 if ((re_opcode_t) *p != on_failure_jump
2715 && (re_opcode_t) *p != succeed_n)
2716 continue;
2718 p++;
2719 EXTRACT_NUMBER_AND_INCR (j, p);
2720 p += j;
2722 /* If what's on the stack is where we are now, pop it. */
2723 if (!FAIL_STACK_EMPTY ()
2724 && fail_stack.stack[fail_stack.avail - 1] == p)
2725 fail_stack.avail--;
2727 continue;
2730 case on_failure_jump:
2731 case on_failure_keep_string_jump:
2732 handle_on_failure_jump:
2733 EXTRACT_NUMBER_AND_INCR (j, p);
2735 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2736 end of the pattern. We don't want to push such a point,
2737 since when we restore it above, entering the switch will
2738 increment `p' past the end of the pattern. We don't need
2739 to push such a point since we obviously won't find any more
2740 fastmap entries beyond `pend'. Such a pattern can match
2741 the null string, though. */
2742 if (p + j < pend)
2744 if (!PUSH_PATTERN_OP (p + j, fail_stack))
2745 return -2;
2747 else
2748 bufp->can_be_null = 1;
2750 if (succeed_n_p)
2752 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
2753 succeed_n_p = false;
2756 continue;
2759 case succeed_n:
2760 /* Get to the number of times to succeed. */
2761 p += 2;
2763 /* Increment p past the n for when k != 0. */
2764 EXTRACT_NUMBER_AND_INCR (k, p);
2765 if (k == 0)
2767 p -= 4;
2768 succeed_n_p = true; /* Spaghetti code alert. */
2769 goto handle_on_failure_jump;
2771 continue;
2774 case set_number_at:
2775 p += 4;
2776 continue;
2779 case start_memory:
2780 case stop_memory:
2781 p += 2;
2782 continue;
2785 default:
2786 abort (); /* We have listed all the cases. */
2787 } /* switch *p++ */
2789 /* Getting here means we have found the possible starting
2790 characters for one path of the pattern -- and that the empty
2791 string does not match. We need not follow this path further.
2792 Instead, look at the next alternative (remembered on the
2793 stack), or quit if no more. The test at the top of the loop
2794 does these things. */
2795 path_can_be_null = false;
2796 p = pend;
2797 } /* while p */
2799 /* Set `can_be_null' for the last path (also the first path, if the
2800 pattern is empty). */
2801 bufp->can_be_null |= path_can_be_null;
2802 return 0;
2803 } /* re_compile_fastmap */
2805 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
2806 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
2807 this memory for recording register information. STARTS and ENDS
2808 must be allocated using the malloc library routine, and must each
2809 be at least NUM_REGS * sizeof (regoff_t) bytes long.
2811 If NUM_REGS == 0, then subsequent matches should allocate their own
2812 register data.
2814 Unless this function is called, the first search or match using
2815 PATTERN_BUFFER will allocate its own register data, without
2816 freeing the old data. */
2818 void
2819 re_set_registers (bufp, regs, num_regs, starts, ends)
2820 struct re_pattern_buffer *bufp;
2821 struct re_registers *regs;
2822 unsigned num_regs;
2823 regoff_t *starts, *ends;
2825 if (num_regs)
2827 bufp->regs_allocated = REGS_REALLOCATE;
2828 regs->num_regs = num_regs;
2829 regs->start = starts;
2830 regs->end = ends;
2832 else
2834 bufp->regs_allocated = REGS_UNALLOCATED;
2835 regs->num_regs = 0;
2836 regs->start = regs->end = (regoff_t) 0;
2840 /* Searching routines. */
2842 /* Like re_search_2, below, but only one string is specified, and
2843 doesn't let you say where to stop matching. */
2846 re_search (bufp, string, size, startpos, range, regs)
2847 struct re_pattern_buffer *bufp;
2848 const char *string;
2849 int size, startpos, range;
2850 struct re_registers *regs;
2852 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
2853 regs, size);
2857 /* Using the compiled pattern in BUFP->buffer, first tries to match the
2858 virtual concatenation of STRING1 and STRING2, starting first at index
2859 STARTPOS, then at STARTPOS + 1, and so on.
2861 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
2863 RANGE is how far to scan while trying to match. RANGE = 0 means try
2864 only at STARTPOS; in general, the last start tried is STARTPOS +
2865 RANGE.
2867 In REGS, return the indices of the virtual concatenation of STRING1
2868 and STRING2 that matched the entire BUFP->buffer and its contained
2869 subexpressions.
2871 Do not consider matching one past the index STOP in the virtual
2872 concatenation of STRING1 and STRING2.
2874 We return either the position in the strings at which the match was
2875 found, -1 if no match, or -2 if error (such as failure
2876 stack overflow). */
2879 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
2880 struct re_pattern_buffer *bufp;
2881 const char *string1, *string2;
2882 int size1, size2;
2883 int startpos;
2884 int range;
2885 struct re_registers *regs;
2886 int stop;
2888 int val;
2889 register char *fastmap = bufp->fastmap;
2890 register char *translate = bufp->translate;
2891 int total_size = size1 + size2;
2892 int endpos = startpos + range;
2894 /* Check for out-of-range STARTPOS. */
2895 if (startpos < 0 || startpos > total_size)
2896 return -1;
2898 /* Fix up RANGE if it might eventually take us outside
2899 the virtual concatenation of STRING1 and STRING2. */
2900 if (endpos < -1)
2901 range = -1 - startpos;
2902 else if (endpos > total_size)
2903 range = total_size - startpos;
2905 /* If the search isn't to be a backwards one, don't waste time in a
2906 search for a pattern that must be anchored. */
2907 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
2909 if (startpos > 0)
2910 return -1;
2911 else
2912 range = 1;
2915 /* Update the fastmap now if not correct already. */
2916 if (fastmap && !bufp->fastmap_accurate)
2917 if (re_compile_fastmap (bufp) == -2)
2918 return -2;
2920 /* Loop through the string, looking for a place to start matching. */
2921 for (;;)
2923 /* If a fastmap is supplied, skip quickly over characters that
2924 cannot be the start of a match. If the pattern can match the
2925 null string, however, we don't need to skip characters; we want
2926 the first null string. */
2927 if (fastmap && startpos < total_size && !bufp->can_be_null)
2929 if (range > 0) /* Searching forwards. */
2931 register const char *d;
2932 register int lim = 0;
2933 int irange = range;
2935 if (startpos < size1 && startpos + range >= size1)
2936 lim = range - (size1 - startpos);
2938 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
2940 /* Written out as an if-else to avoid testing `translate'
2941 inside the loop. */
2942 if (translate)
2943 while (range > lim
2944 && !fastmap[(unsigned char)
2945 translate[(unsigned char) *d++]])
2946 range--;
2947 else
2948 while (range > lim && !fastmap[(unsigned char) *d++])
2949 range--;
2951 startpos += irange - range;
2953 else /* Searching backwards. */
2955 register char c = (size1 == 0 || startpos >= size1
2956 ? string2[startpos - size1]
2957 : string1[startpos]);
2959 if (!fastmap[(unsigned char) TRANSLATE (c)])
2960 goto advance;
2964 /* If can't match the null string, and that's all we have left, fail. */
2965 if (range >= 0 && startpos == total_size && fastmap
2966 && !bufp->can_be_null)
2967 return -1;
2969 val = re_match_2 (bufp, string1, size1, string2, size2,
2970 startpos, regs, stop);
2971 if (val >= 0)
2972 return startpos;
2974 if (val == -2)
2975 return -2;
2977 advance:
2978 if (!range)
2979 break;
2980 else if (range > 0)
2982 range--;
2983 startpos++;
2985 else
2987 range++;
2988 startpos--;
2991 return -1;
2992 } /* re_search_2 */
2994 /* Declarations and macros for re_match_2. */
2996 static int bcmp_translate ();
2997 static boolean alt_match_null_string_p (),
2998 common_op_match_null_string_p (),
2999 group_match_null_string_p ();
3001 /* Structure for per-register (a.k.a. per-group) information.
3002 This must not be longer than one word, because we push this value
3003 onto the failure stack. Other register information, such as the
3004 starting and ending positions (which are addresses), and the list of
3005 inner groups (which is a bits list) are maintained in separate
3006 variables.
3008 We are making a (strictly speaking) nonportable assumption here: that
3009 the compiler will pack our bit fields into something that fits into
3010 the type of `word', i.e., is something that fits into one item on the
3011 failure stack. */
3012 typedef union
3014 fail_stack_elt_t word;
3015 struct
3017 /* This field is one if this group can match the empty string,
3018 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
3019 #define MATCH_NULL_UNSET_VALUE 3
3020 unsigned match_null_string_p : 2;
3021 unsigned is_active : 1;
3022 unsigned matched_something : 1;
3023 unsigned ever_matched_something : 1;
3024 } bits;
3025 } register_info_type;
3027 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
3028 #define IS_ACTIVE(R) ((R).bits.is_active)
3029 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
3030 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
3033 /* Call this when have matched a real character; it sets `matched' flags
3034 for the subexpressions which we are currently inside. Also records
3035 that those subexprs have matched. */
3036 #define SET_REGS_MATCHED() \
3037 do \
3039 unsigned r; \
3040 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
3042 MATCHED_SOMETHING (reg_info[r]) \
3043 = EVER_MATCHED_SOMETHING (reg_info[r]) \
3044 = 1; \
3047 while (0)
3050 /* This converts PTR, a pointer into one of the search strings `string1'
3051 and `string2' into an offset from the beginning of that string. */
3052 #define POINTER_TO_OFFSET(ptr) \
3053 (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
3055 /* Registers are set to a sentinel when they haven't yet matched. */
3056 #define REG_UNSET_VALUE ((char *) -1)
3057 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
3060 /* Macros for dealing with the split strings in re_match_2. */
3062 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3064 /* Call before fetching a character with *d. This switches over to
3065 string2 if necessary. */
3066 #define PREFETCH() \
3067 while (d == dend) \
3069 /* End of string2 => fail. */ \
3070 if (dend == end_match_2) \
3071 goto fail; \
3072 /* End of string1 => advance to string2. */ \
3073 d = string2; \
3074 dend = end_match_2; \
3078 /* Test if at very beginning or at very end of the virtual concatenation
3079 of `string1' and `string2'. If only one string, it's `string2'. */
3080 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3081 #define AT_STRINGS_END(d) ((d) == end2)
3084 /* Test if D points to a character which is word-constituent. We have
3085 two special cases to check for: if past the end of string1, look at
3086 the first character in string2; and if before the beginning of
3087 string2, look at the last character in string1. */
3088 #define WORDCHAR_P(d) \
3089 (SYNTAX ((d) == end1 ? *string2 \
3090 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3091 == Sword)
3093 /* Test if the character before D and the one at D differ with respect
3094 to being word-constituent. */
3095 #define AT_WORD_BOUNDARY(d) \
3096 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3097 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3100 /* Free everything we malloc. */
3101 #define FREE_VAR(var) if (var) free (var); var = NULL
3102 #define FREE_VARIABLES() \
3103 do { \
3104 FREE_VAR (fail_stack.stack); \
3105 FREE_VAR (regstart); \
3106 FREE_VAR (regend); \
3107 FREE_VAR (old_regstart); \
3108 FREE_VAR (old_regend); \
3109 FREE_VAR (best_regstart); \
3110 FREE_VAR (best_regend); \
3111 FREE_VAR (reg_info); \
3112 FREE_VAR (reg_dummy); \
3113 FREE_VAR (reg_info_dummy); \
3114 } while (0)
3117 /* These values must meet several constraints. They must not be valid
3118 register values; since we have a limit of 255 registers (because
3119 we use only one byte in the pattern for the register number), we can
3120 use numbers larger than 255. They must differ by 1, because of
3121 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3122 be larger than the value for the highest register, so we do not try
3123 to actually save any registers when none are active. */
3124 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3125 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3127 /* Matching routines. */
3129 #ifndef emacs /* Emacs never uses this. */
3130 /* re_match is like re_match_2 except it takes only a single string. */
3133 re_match (bufp, string, size, pos, regs)
3134 struct re_pattern_buffer *bufp;
3135 const char *string;
3136 int size, pos;
3137 struct re_registers *regs;
3139 return re_match_2 (bufp, NULL, 0, string, size, pos, regs, size);
3141 #endif /* not emacs */
3144 /* re_match_2 matches the compiled pattern in BUFP against the
3145 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3146 and SIZE2, respectively). We start matching at POS, and stop
3147 matching at STOP.
3149 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3150 store offsets for the substring each group matched in REGS. See the
3151 documentation for exactly how many groups we fill.
3153 We return -1 if no match, -2 if an internal error (such as the
3154 failure stack overflowing). Otherwise, we return the length of the
3155 matched substring. */
3158 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3159 struct re_pattern_buffer *bufp;
3160 const char *string1, *string2;
3161 int size1, size2;
3162 int pos;
3163 struct re_registers *regs;
3164 int stop;
3166 /* General temporaries. */
3167 int mcnt;
3168 unsigned char *p1;
3170 /* Just past the end of the corresponding string. */
3171 const char *end1, *end2;
3173 /* Pointers into string1 and string2, just past the last characters in
3174 each to consider matching. */
3175 const char *end_match_1, *end_match_2;
3177 /* Where we are in the data, and the end of the current string. */
3178 const char *d, *dend;
3180 /* Where we are in the pattern, and the end of the pattern. */
3181 unsigned char *p = bufp->buffer;
3182 register unsigned char *pend = p + bufp->used;
3184 /* We use this to map every character in the string. */
3185 char *translate = bufp->translate;
3187 /* Failure point stack. Each place that can handle a failure further
3188 down the line pushes a failure point on this stack. It consists of
3189 restart, regend, and reg_info for all registers corresponding to
3190 the subexpressions we're currently inside, plus the number of such
3191 registers, and, finally, two char *'s. The first char * is where
3192 to resume scanning the pattern; the second one is where to resume
3193 scanning the strings. If the latter is zero, the failure point is
3194 a ``dummy''; if a failure happens and the failure point is a dummy,
3195 it gets discarded and the next next one is tried. */
3196 fail_stack_type fail_stack;
3197 #ifdef DEBUG
3198 static unsigned failure_id = 0;
3199 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3200 #endif
3202 /* We fill all the registers internally, independent of what we
3203 return, for use in backreferences. The number here includes
3204 an element for register zero. */
3205 unsigned num_regs = bufp->re_nsub + 1;
3207 /* The currently active registers. */
3208 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3209 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3211 /* Information on the contents of registers. These are pointers into
3212 the input strings; they record just what was matched (on this
3213 attempt) by a subexpression part of the pattern, that is, the
3214 regnum-th regstart pointer points to where in the pattern we began
3215 matching and the regnum-th regend points to right after where we
3216 stopped matching the regnum-th subexpression. (The zeroth register
3217 keeps track of what the whole pattern matches.) */
3218 const char **regstart, **regend;
3220 /* If a group that's operated upon by a repetition operator fails to
3221 match anything, then the register for its start will need to be
3222 restored because it will have been set to wherever in the string we
3223 are when we last see its open-group operator. Similarly for a
3224 register's end. */
3225 const char **old_regstart, **old_regend;
3227 /* The is_active field of reg_info helps us keep track of which (possibly
3228 nested) subexpressions we are currently in. The matched_something
3229 field of reg_info[reg_num] helps us tell whether or not we have
3230 matched any of the pattern so far this time through the reg_num-th
3231 subexpression. These two fields get reset each time through any
3232 loop their register is in. */
3233 register_info_type *reg_info;
3235 /* The following record the register info as found in the above
3236 variables when we find a match better than any we've seen before.
3237 This happens as we backtrack through the failure points, which in
3238 turn happens only if we have not yet matched the entire string. */
3239 unsigned best_regs_set = false;
3240 const char **best_regstart, **best_regend;
3242 /* Logically, this is `best_regend[0]'. But we don't want to have to
3243 allocate space for that if we're not allocating space for anything
3244 else (see below). Also, we never need info about register 0 for
3245 any of the other register vectors, and it seems rather a kludge to
3246 treat `best_regend' differently than the rest. So we keep track of
3247 the end of the best match so far in a separate variable. We
3248 initialize this to NULL so that when we backtrack the first time
3249 and need to test it, it's not garbage. */
3250 const char *match_end = NULL;
3252 /* Used when we pop values we don't care about. */
3253 const char **reg_dummy;
3254 register_info_type *reg_info_dummy;
3256 #ifdef DEBUG
3257 /* Counts the total number of registers pushed. */
3258 unsigned num_regs_pushed = 0;
3259 #endif
3261 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3263 INIT_FAIL_STACK ();
3265 /* Do not bother to initialize all the register variables if there are
3266 no groups in the pattern, as it takes a fair amount of time. If
3267 there are groups, we include space for register 0 (the whole
3268 pattern), even though we never use it, since it simplifies the
3269 array indexing. We should fix this. */
3270 if (bufp->re_nsub)
3272 regstart = REGEX_TALLOC (num_regs, const char *);
3273 regend = REGEX_TALLOC (num_regs, const char *);
3274 old_regstart = REGEX_TALLOC (num_regs, const char *);
3275 old_regend = REGEX_TALLOC (num_regs, const char *);
3276 best_regstart = REGEX_TALLOC (num_regs, const char *);
3277 best_regend = REGEX_TALLOC (num_regs, const char *);
3278 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3279 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3280 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3282 if (!(regstart && regend && old_regstart && old_regend && reg_info
3283 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3285 FREE_VARIABLES ();
3286 return -2;
3289 #ifdef REGEX_MALLOC
3290 else
3292 /* We must initialize all our variables to NULL, so that
3293 `FREE_VARIABLES' doesn't try to free them. */
3294 regstart = regend = old_regstart = old_regend = best_regstart
3295 = best_regend = reg_dummy = NULL;
3296 reg_info = reg_info_dummy = (register_info_type *) NULL;
3298 #endif /* REGEX_MALLOC */
3300 /* The starting position is bogus. */
3301 if (pos < 0 || pos > size1 + size2)
3303 FREE_VARIABLES ();
3304 return -1;
3307 /* Initialize subexpression text positions to -1 to mark ones that no
3308 start_memory/stop_memory has been seen for. Also initialize the
3309 register information struct. */
3310 for (mcnt = 1; mcnt < num_regs; mcnt++)
3312 regstart[mcnt] = regend[mcnt]
3313 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3315 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3316 IS_ACTIVE (reg_info[mcnt]) = 0;
3317 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3318 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3321 /* We move `string1' into `string2' if the latter's empty -- but not if
3322 `string1' is null. */
3323 if (size2 == 0 && string1 != NULL)
3325 string2 = string1;
3326 size2 = size1;
3327 string1 = 0;
3328 size1 = 0;
3330 end1 = string1 + size1;
3331 end2 = string2 + size2;
3333 /* Compute where to stop matching, within the two strings. */
3334 if (stop <= size1)
3336 end_match_1 = string1 + stop;
3337 end_match_2 = string2;
3339 else
3341 end_match_1 = end1;
3342 end_match_2 = string2 + stop - size1;
3345 /* `p' scans through the pattern as `d' scans through the data.
3346 `dend' is the end of the input string that `d' points within. `d'
3347 is advanced into the following input string whenever necessary, but
3348 this happens before fetching; therefore, at the beginning of the
3349 loop, `d' can be pointing at the end of a string, but it cannot
3350 equal `string2'. */
3351 if (size1 > 0 && pos <= size1)
3353 d = string1 + pos;
3354 dend = end_match_1;
3356 else
3358 d = string2 + pos - size1;
3359 dend = end_match_2;
3362 DEBUG_PRINT1 ("The compiled pattern is: ");
3363 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3364 DEBUG_PRINT1 ("The string to match is: `");
3365 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3366 DEBUG_PRINT1 ("'\n");
3368 /* This loops over pattern commands. It exits by returning from the
3369 function if the match is complete, or it drops through if the match
3370 fails at this starting point in the input data. */
3371 for (;;)
3373 DEBUG_PRINT2 ("\n0x%x: ", p);
3375 if (p == pend)
3376 { /* End of pattern means we might have succeeded. */
3377 DEBUG_PRINT1 ("end of pattern ... ");
3379 /* If we haven't matched the entire string, and we want the
3380 longest match, try backtracking. */
3381 if (d != end_match_2)
3383 DEBUG_PRINT1 ("backtracking.\n");
3385 if (!FAIL_STACK_EMPTY ())
3386 { /* More failure points to try. */
3387 boolean same_str_p = (FIRST_STRING_P (match_end)
3388 == MATCHING_IN_FIRST_STRING);
3390 /* If exceeds best match so far, save it. */
3391 if (!best_regs_set
3392 || (same_str_p && d > match_end)
3393 || (!same_str_p && !MATCHING_IN_FIRST_STRING))
3395 best_regs_set = true;
3396 match_end = d;
3398 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3400 for (mcnt = 1; mcnt < num_regs; mcnt++)
3402 best_regstart[mcnt] = regstart[mcnt];
3403 best_regend[mcnt] = regend[mcnt];
3406 goto fail;
3409 /* If no failure points, don't restore garbage. */
3410 else if (best_regs_set)
3412 restore_best_regs:
3413 /* Restore best match. It may happen that `dend ==
3414 end_match_1' while the restored d is in string2.
3415 For example, the pattern `x.*y.*z' against the
3416 strings `x-' and `y-z-', if the two strings are
3417 not consecutive in memory. */
3418 DEBUG_PRINT1 ("Restoring best registers.\n");
3420 d = match_end;
3421 dend = ((d >= string1 && d <= end1)
3422 ? end_match_1 : end_match_2);
3424 for (mcnt = 1; mcnt < num_regs; mcnt++)
3426 regstart[mcnt] = best_regstart[mcnt];
3427 regend[mcnt] = best_regend[mcnt];
3430 } /* d != end_match_2 */
3432 DEBUG_PRINT1 ("Accepting match.\n");
3434 /* If caller wants register contents data back, do it. */
3435 if (regs && !bufp->no_sub)
3437 /* Have the register data arrays been allocated? */
3438 if (bufp->regs_allocated == REGS_UNALLOCATED)
3439 { /* No. So allocate them with malloc. We need one
3440 extra element beyond `num_regs' for the `-1' marker
3441 GNU code uses. */
3442 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3443 regs->start = TALLOC (regs->num_regs, regoff_t);
3444 regs->end = TALLOC (regs->num_regs, regoff_t);
3445 if (regs->start == NULL || regs->end == NULL)
3446 return -2;
3447 bufp->regs_allocated = REGS_REALLOCATE;
3449 else if (bufp->regs_allocated == REGS_REALLOCATE)
3450 { /* Yes. If we need more elements than were already
3451 allocated, reallocate them. If we need fewer, just
3452 leave it alone. */
3453 if (regs->num_regs < num_regs + 1)
3455 regs->num_regs = num_regs + 1;
3456 RETALLOC (regs->start, regs->num_regs, regoff_t);
3457 RETALLOC (regs->end, regs->num_regs, regoff_t);
3458 if (regs->start == NULL || regs->end == NULL)
3459 return -2;
3462 else
3463 assert (bufp->regs_allocated == REGS_FIXED);
3465 /* Convert the pointer data in `regstart' and `regend' to
3466 indices. Register zero has to be set differently,
3467 since we haven't kept track of any info for it. */
3468 if (regs->num_regs > 0)
3470 regs->start[0] = pos;
3471 regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
3472 : d - string2 + size1);
3475 /* Go through the first `min (num_regs, regs->num_regs)'
3476 registers, since that is all we initialized. */
3477 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
3479 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3480 regs->start[mcnt] = regs->end[mcnt] = -1;
3481 else
3483 regs->start[mcnt] = POINTER_TO_OFFSET (regstart[mcnt]);
3484 regs->end[mcnt] = POINTER_TO_OFFSET (regend[mcnt]);
3488 /* If the regs structure we return has more elements than
3489 were in the pattern, set the extra elements to -1. If
3490 we (re)allocated the registers, this is the case,
3491 because we always allocate enough to have at least one
3492 -1 at the end. */
3493 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3494 regs->start[mcnt] = regs->end[mcnt] = -1;
3495 } /* regs && !bufp->no_sub */
3497 FREE_VARIABLES ();
3498 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3499 nfailure_points_pushed, nfailure_points_popped,
3500 nfailure_points_pushed - nfailure_points_popped);
3501 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3503 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3504 ? string1
3505 : string2 - size1);
3507 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3509 return mcnt;
3512 /* Otherwise match next pattern command. */
3513 #ifdef SWITCH_ENUM_BUG
3514 switch ((int) ((re_opcode_t) *p++))
3515 #else
3516 switch ((re_opcode_t) *p++)
3517 #endif
3519 /* Ignore these. Used to ignore the n of succeed_n's which
3520 currently have n == 0. */
3521 case no_op:
3522 DEBUG_PRINT1 ("EXECUTING no_op.\n");
3523 break;
3526 /* Match the next n pattern characters exactly. The following
3527 byte in the pattern defines n, and the n bytes after that
3528 are the characters to match. */
3529 case exactn:
3530 mcnt = *p++;
3531 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3533 /* This is written out as an if-else so we don't waste time
3534 testing `translate' inside the loop. */
3535 if (translate)
3539 PREFETCH ();
3540 if (translate[(unsigned char) *d++] != (char) *p++)
3541 goto fail;
3543 while (--mcnt);
3545 else
3549 PREFETCH ();
3550 if (*d++ != (char) *p++) goto fail;
3552 while (--mcnt);
3554 SET_REGS_MATCHED ();
3555 break;
3558 /* Match any character except possibly a newline or a null. */
3559 case anychar:
3560 DEBUG_PRINT1 ("EXECUTING anychar.\n");
3562 PREFETCH ();
3564 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
3565 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
3566 goto fail;
3568 SET_REGS_MATCHED ();
3569 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
3570 d++;
3571 break;
3574 case charset:
3575 case charset_not:
3577 register unsigned char c;
3578 boolean not = (re_opcode_t) *(p - 1) == charset_not;
3580 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
3582 PREFETCH ();
3583 c = TRANSLATE (*d); /* The character to match. */
3585 /* Cast to `unsigned' instead of `unsigned char' in case the
3586 bit list is a full 32 bytes long. */
3587 if (c < (unsigned) (*p * BYTEWIDTH)
3588 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3589 not = !not;
3591 p += 1 + *p;
3593 if (!not) goto fail;
3595 SET_REGS_MATCHED ();
3596 d++;
3597 break;
3601 /* The beginning of a group is represented by start_memory.
3602 The arguments are the register number in the next byte, and the
3603 number of groups inner to this one in the next. The text
3604 matched within the group is recorded (in the internal
3605 registers data structure) under the register number. */
3606 case start_memory:
3607 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3609 /* Find out if this group can match the empty string. */
3610 p1 = p; /* To send to group_match_null_string_p. */
3612 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3613 REG_MATCH_NULL_STRING_P (reg_info[*p])
3614 = group_match_null_string_p (&p1, pend, reg_info);
3616 /* Save the position in the string where we were the last time
3617 we were at this open-group operator in case the group is
3618 operated upon by a repetition operator, e.g., with `(a*)*b'
3619 against `ab'; then we want to ignore where we are now in
3620 the string in case this attempt to match fails. */
3621 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3622 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
3623 : regstart[*p];
3624 DEBUG_PRINT2 (" old_regstart: %d\n",
3625 POINTER_TO_OFFSET (old_regstart[*p]));
3627 regstart[*p] = d;
3628 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
3630 IS_ACTIVE (reg_info[*p]) = 1;
3631 MATCHED_SOMETHING (reg_info[*p]) = 0;
3633 /* This is the new highest active register. */
3634 highest_active_reg = *p;
3636 /* If nothing was active before, this is the new lowest active
3637 register. */
3638 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3639 lowest_active_reg = *p;
3641 /* Move past the register number and inner group count. */
3642 p += 2;
3643 break;
3646 /* The stop_memory opcode represents the end of a group. Its
3647 arguments are the same as start_memory's: the register
3648 number, and the number of inner groups. */
3649 case stop_memory:
3650 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
3652 /* We need to save the string position the last time we were at
3653 this close-group operator in case the group is operated
3654 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3655 against `aba'; then we want to ignore where we are now in
3656 the string in case this attempt to match fails. */
3657 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3658 ? REG_UNSET (regend[*p]) ? d : regend[*p]
3659 : regend[*p];
3660 DEBUG_PRINT2 (" old_regend: %d\n",
3661 POINTER_TO_OFFSET (old_regend[*p]));
3663 regend[*p] = d;
3664 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
3666 /* This register isn't active anymore. */
3667 IS_ACTIVE (reg_info[*p]) = 0;
3669 /* If this was the only register active, nothing is active
3670 anymore. */
3671 if (lowest_active_reg == highest_active_reg)
3673 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3674 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3676 else
3677 { /* We must scan for the new highest active register, since
3678 it isn't necessarily one less than now: consider
3679 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
3680 new highest active register is 1. */
3681 unsigned char r = *p - 1;
3682 while (r > 0 && !IS_ACTIVE (reg_info[r]))
3683 r--;
3685 /* If we end up at register zero, that means that we saved
3686 the registers as the result of an `on_failure_jump', not
3687 a `start_memory', and we jumped to past the innermost
3688 `stop_memory'. For example, in ((.)*) we save
3689 registers 1 and 2 as a result of the *, but when we pop
3690 back to the second ), we are at the stop_memory 1.
3691 Thus, nothing is active. */
3692 if (r == 0)
3694 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3695 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3697 else
3698 highest_active_reg = r;
3701 /* If just failed to match something this time around with a
3702 group that's operated on by a repetition operator, try to
3703 force exit from the ``loop'', and restore the register
3704 information for this group that we had before trying this
3705 last match. */
3706 if ((!MATCHED_SOMETHING (reg_info[*p])
3707 || (re_opcode_t) p[-3] == start_memory)
3708 && (p + 2) < pend)
3710 boolean is_a_jump_n = false;
3712 p1 = p + 2;
3713 mcnt = 0;
3714 switch ((re_opcode_t) *p1++)
3716 case jump_n:
3717 is_a_jump_n = true;
3718 case pop_failure_jump:
3719 case maybe_pop_jump:
3720 case jump:
3721 case dummy_failure_jump:
3722 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3723 if (is_a_jump_n)
3724 p1 += 2;
3725 break;
3727 default:
3728 /* do nothing */ ;
3730 p1 += mcnt;
3732 /* If the next operation is a jump backwards in the pattern
3733 to an on_failure_jump right before the start_memory
3734 corresponding to this stop_memory, exit from the loop
3735 by forcing a failure after pushing on the stack the
3736 on_failure_jump's jump in the pattern, and d. */
3737 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
3738 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
3740 /* If this group ever matched anything, then restore
3741 what its registers were before trying this last
3742 failed match, e.g., with `(a*)*b' against `ab' for
3743 regstart[1], and, e.g., with `((a*)*(b*)*)*'
3744 against `aba' for regend[3].
3746 Also restore the registers for inner groups for,
3747 e.g., `((a*)(b*))*' against `aba' (register 3 would
3748 otherwise get trashed). */
3750 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
3752 unsigned r;
3754 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
3756 /* Restore this and inner groups' (if any) registers. */
3757 for (r = *p; r < *p + *(p + 1); r++)
3759 regstart[r] = old_regstart[r];
3761 /* xx why this test? */
3762 if ((int) old_regend[r] >= (int) regstart[r])
3763 regend[r] = old_regend[r];
3766 p1++;
3767 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3768 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
3770 goto fail;
3774 /* Move past the register number and the inner group count. */
3775 p += 2;
3776 break;
3779 /* \<digit> has been turned into a `duplicate' command which is
3780 followed by the numeric value of <digit> as the register number. */
3781 case duplicate:
3783 register const char *d2, *dend2;
3784 int regno = *p++; /* Get which register to match against. */
3785 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
3787 /* Can't back reference a group which we've never matched. */
3788 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
3789 goto fail;
3791 /* Where in input to try to start matching. */
3792 d2 = regstart[regno];
3794 /* Where to stop matching; if both the place to start and
3795 the place to stop matching are in the same string, then
3796 set to the place to stop, otherwise, for now have to use
3797 the end of the first string. */
3799 dend2 = ((FIRST_STRING_P (regstart[regno])
3800 == FIRST_STRING_P (regend[regno]))
3801 ? regend[regno] : end_match_1);
3802 for (;;)
3804 /* If necessary, advance to next segment in register
3805 contents. */
3806 while (d2 == dend2)
3808 if (dend2 == end_match_2) break;
3809 if (dend2 == regend[regno]) break;
3811 /* End of string1 => advance to string2. */
3812 d2 = string2;
3813 dend2 = regend[regno];
3815 /* At end of register contents => success */
3816 if (d2 == dend2) break;
3818 /* If necessary, advance to next segment in data. */
3819 PREFETCH ();
3821 /* How many characters left in this segment to match. */
3822 mcnt = dend - d;
3824 /* Want how many consecutive characters we can match in
3825 one shot, so, if necessary, adjust the count. */
3826 if (mcnt > dend2 - d2)
3827 mcnt = dend2 - d2;
3829 /* Compare that many; failure if mismatch, else move
3830 past them. */
3831 if (translate
3832 ? bcmp_translate (d, d2, mcnt, translate)
3833 : bcmp (d, d2, mcnt))
3834 goto fail;
3835 d += mcnt, d2 += mcnt;
3838 break;
3841 /* begline matches the empty string at the beginning of the string
3842 (unless `not_bol' is set in `bufp'), and, if
3843 `newline_anchor' is set, after newlines. */
3844 case begline:
3845 DEBUG_PRINT1 ("EXECUTING begline.\n");
3847 if (AT_STRINGS_BEG (d))
3849 if (!bufp->not_bol) break;
3851 else if (d[-1] == '\n' && bufp->newline_anchor)
3853 break;
3855 /* In all other cases, we fail. */
3856 goto fail;
3859 /* endline is the dual of begline. */
3860 case endline:
3861 DEBUG_PRINT1 ("EXECUTING endline.\n");
3863 if (AT_STRINGS_END (d))
3865 if (!bufp->not_eol) break;
3868 /* We have to ``prefetch'' the next character. */
3869 else if ((d == end1 ? *string2 : *d) == '\n'
3870 && bufp->newline_anchor)
3872 break;
3874 goto fail;
3877 /* Match at the very beginning of the data. */
3878 case begbuf:
3879 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
3880 if (AT_STRINGS_BEG (d))
3881 break;
3882 goto fail;
3885 /* Match at the very end of the data. */
3886 case endbuf:
3887 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
3888 if (AT_STRINGS_END (d))
3889 break;
3890 goto fail;
3893 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
3894 pushes NULL as the value for the string on the stack. Then
3895 `pop_failure_point' will keep the current value for the
3896 string, instead of restoring it. To see why, consider
3897 matching `foo\nbar' against `.*\n'. The .* matches the foo;
3898 then the . fails against the \n. But the next thing we want
3899 to do is match the \n against the \n; if we restored the
3900 string value, we would be back at the foo.
3902 Because this is used only in specific cases, we don't need to
3903 check all the things that `on_failure_jump' does, to make
3904 sure the right things get saved on the stack. Hence we don't
3905 share its code. The only reason to push anything on the
3906 stack at all is that otherwise we would have to change
3907 `anychar's code to do something besides goto fail in this
3908 case; that seems worse than this. */
3909 case on_failure_keep_string_jump:
3910 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
3912 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3913 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
3915 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
3916 break;
3919 /* Uses of on_failure_jump:
3921 Each alternative starts with an on_failure_jump that points
3922 to the beginning of the next alternative. Each alternative
3923 except the last ends with a jump that in effect jumps past
3924 the rest of the alternatives. (They really jump to the
3925 ending jump of the following alternative, because tensioning
3926 these jumps is a hassle.)
3928 Repeats start with an on_failure_jump that points past both
3929 the repetition text and either the following jump or
3930 pop_failure_jump back to this on_failure_jump. */
3931 case on_failure_jump:
3932 on_failure:
3933 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
3935 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3936 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
3938 /* If this on_failure_jump comes right before a group (i.e.,
3939 the original * applied to a group), save the information
3940 for that group and all inner ones, so that if we fail back
3941 to this point, the group's information will be correct.
3942 For example, in \(a*\)*\1, we need the preceding group,
3943 and in \(\(a*\)b*\)\2, we need the inner group. */
3945 /* We can't use `p' to check ahead because we push
3946 a failure point to `p + mcnt' after we do this. */
3947 p1 = p;
3949 /* We need to skip no_op's before we look for the
3950 start_memory in case this on_failure_jump is happening as
3951 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
3952 against aba. */
3953 while (p1 < pend && (re_opcode_t) *p1 == no_op)
3954 p1++;
3956 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
3958 /* We have a new highest active register now. This will
3959 get reset at the start_memory we are about to get to,
3960 but we will have saved all the registers relevant to
3961 this repetition op, as described above. */
3962 highest_active_reg = *(p1 + 1) + *(p1 + 2);
3963 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3964 lowest_active_reg = *(p1 + 1);
3967 DEBUG_PRINT1 (":\n");
3968 PUSH_FAILURE_POINT (p + mcnt, d, -2);
3969 break;
3972 /* A smart repeat ends with `maybe_pop_jump'.
3973 We change it to either `pop_failure_jump' or `jump'. */
3974 case maybe_pop_jump:
3975 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3976 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
3978 register unsigned char *p2 = p;
3980 /* Compare the beginning of the repeat with what in the
3981 pattern follows its end. If we can establish that there
3982 is nothing that they would both match, i.e., that we
3983 would have to backtrack because of (as in, e.g., `a*a')
3984 then we can change to pop_failure_jump, because we'll
3985 never have to backtrack.
3987 This is not true in the case of alternatives: in
3988 `(a|ab)*' we do need to backtrack to the `ab' alternative
3989 (e.g., if the string was `ab'). But instead of trying to
3990 detect that here, the alternative has put on a dummy
3991 failure point which is what we will end up popping. */
3993 /* Skip over open/close-group commands. */
3994 while (p2 + 2 < pend
3995 && ((re_opcode_t) *p2 == stop_memory
3996 || (re_opcode_t) *p2 == start_memory))
3997 p2 += 3; /* Skip over args, too. */
3999 /* If we're at the end of the pattern, we can change. */
4000 if (p2 == pend)
4002 /* Consider what happens when matching ":\(.*\)"
4003 against ":/". I don't really understand this code
4004 yet. */
4005 p[-3] = (unsigned char) pop_failure_jump;
4006 DEBUG_PRINT1
4007 (" End of pattern: change to `pop_failure_jump'.\n");
4010 else if ((re_opcode_t) *p2 == exactn
4011 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4013 register unsigned char c
4014 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4015 p1 = p + mcnt;
4017 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4018 to the `maybe_finalize_jump' of this case. Examine what
4019 follows. */
4020 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4022 p[-3] = (unsigned char) pop_failure_jump;
4023 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4024 c, p1[5]);
4027 else if ((re_opcode_t) p1[3] == charset
4028 || (re_opcode_t) p1[3] == charset_not)
4030 int not = (re_opcode_t) p1[3] == charset_not;
4032 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4033 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4034 not = !not;
4036 /* `not' is equal to 1 if c would match, which means
4037 that we can't change to pop_failure_jump. */
4038 if (!not)
4040 p[-3] = (unsigned char) pop_failure_jump;
4041 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4046 p -= 2; /* Point at relative address again. */
4047 if ((re_opcode_t) p[-1] != pop_failure_jump)
4049 p[-1] = (unsigned char) jump;
4050 DEBUG_PRINT1 (" Match => jump.\n");
4051 goto unconditional_jump;
4053 /* Note fall through. */
4056 /* The end of a simple repeat has a pop_failure_jump back to
4057 its matching on_failure_jump, where the latter will push a
4058 failure point. The pop_failure_jump takes off failure
4059 points put on by this pop_failure_jump's matching
4060 on_failure_jump; we got through the pattern to here from the
4061 matching on_failure_jump, so didn't fail. */
4062 case pop_failure_jump:
4064 /* We need to pass separate storage for the lowest and
4065 highest registers, even though we don't care about the
4066 actual values. Otherwise, we will restore only one
4067 register from the stack, since lowest will == highest in
4068 `pop_failure_point'. */
4069 unsigned dummy_low_reg, dummy_high_reg;
4070 unsigned char *pdummy;
4071 const char *sdummy;
4073 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4074 POP_FAILURE_POINT (sdummy, pdummy,
4075 dummy_low_reg, dummy_high_reg,
4076 reg_dummy, reg_dummy, reg_info_dummy);
4078 /* Note fall through. */
4081 /* Unconditionally jump (without popping any failure points). */
4082 case jump:
4083 unconditional_jump:
4084 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4085 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4086 p += mcnt; /* Do the jump. */
4087 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4088 break;
4091 /* We need this opcode so we can detect where alternatives end
4092 in `group_match_null_string_p' et al. */
4093 case jump_past_alt:
4094 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4095 goto unconditional_jump;
4098 /* Normally, the on_failure_jump pushes a failure point, which
4099 then gets popped at pop_failure_jump. We will end up at
4100 pop_failure_jump, also, and with a pattern of, say, `a+', we
4101 are skipping over the on_failure_jump, so we have to push
4102 something meaningless for pop_failure_jump to pop. */
4103 case dummy_failure_jump:
4104 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4105 /* It doesn't matter what we push for the string here. What
4106 the code at `fail' tests is the value for the pattern. */
4107 PUSH_FAILURE_POINT (0, 0, -2);
4108 goto unconditional_jump;
4111 /* At the end of an alternative, we need to push a dummy failure
4112 point in case we are followed by a `pop_failure_jump', because
4113 we don't want the failure point for the alternative to be
4114 popped. For example, matching `(a|ab)*' against `aab'
4115 requires that we match the `ab' alternative. */
4116 case push_dummy_failure:
4117 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4118 /* See comments just above at `dummy_failure_jump' about the
4119 two zeroes. */
4120 PUSH_FAILURE_POINT (0, 0, -2);
4121 break;
4123 /* Have to succeed matching what follows at least n times.
4124 After that, handle like `on_failure_jump'. */
4125 case succeed_n:
4126 EXTRACT_NUMBER (mcnt, p + 2);
4127 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4129 assert (mcnt >= 0);
4130 /* Originally, this is how many times we HAVE to succeed. */
4131 if (mcnt > 0)
4133 mcnt--;
4134 p += 2;
4135 STORE_NUMBER_AND_INCR (p, mcnt);
4136 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
4138 else if (mcnt == 0)
4140 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4141 p[2] = (unsigned char) no_op;
4142 p[3] = (unsigned char) no_op;
4143 goto on_failure;
4145 break;
4147 case jump_n:
4148 EXTRACT_NUMBER (mcnt, p + 2);
4149 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4151 /* Originally, this is how many times we CAN jump. */
4152 if (mcnt)
4154 mcnt--;
4155 STORE_NUMBER (p + 2, mcnt);
4156 goto unconditional_jump;
4158 /* If don't have to jump any more, skip over the rest of command. */
4159 else
4160 p += 4;
4161 break;
4163 case set_number_at:
4165 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4167 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4168 p1 = p + mcnt;
4169 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4170 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4171 STORE_NUMBER (p1, mcnt);
4172 break;
4175 case wordbound:
4176 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4177 if (AT_WORD_BOUNDARY (d))
4178 break;
4179 goto fail;
4181 case notwordbound:
4182 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4183 if (AT_WORD_BOUNDARY (d))
4184 goto fail;
4185 break;
4187 case wordbeg:
4188 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4189 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4190 break;
4191 goto fail;
4193 case wordend:
4194 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4195 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4196 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4197 break;
4198 goto fail;
4200 #ifdef emacs
4201 #ifdef emacs19
4202 case before_dot:
4203 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4204 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4205 goto fail;
4206 break;
4208 case at_dot:
4209 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4210 if (PTR_CHAR_POS ((unsigned char *) d) != point)
4211 goto fail;
4212 break;
4214 case after_dot:
4215 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4216 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
4217 goto fail;
4218 break;
4219 #else /* not emacs19 */
4220 case at_dot:
4221 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4222 if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
4223 goto fail;
4224 break;
4225 #endif /* not emacs19 */
4227 case syntaxspec:
4228 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4229 mcnt = *p++;
4230 goto matchsyntax;
4232 case wordchar:
4233 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4234 mcnt = (int) Sword;
4235 matchsyntax:
4236 PREFETCH ();
4237 if (SYNTAX (*d++) != (enum syntaxcode) mcnt)
4238 goto fail;
4239 SET_REGS_MATCHED ();
4240 break;
4242 case notsyntaxspec:
4243 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4244 mcnt = *p++;
4245 goto matchnotsyntax;
4247 case notwordchar:
4248 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4249 mcnt = (int) Sword;
4250 matchnotsyntax:
4251 PREFETCH ();
4252 if (SYNTAX (*d++) == (enum syntaxcode) mcnt)
4253 goto fail;
4254 SET_REGS_MATCHED ();
4255 break;
4257 #else /* not emacs */
4258 case wordchar:
4259 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4260 PREFETCH ();
4261 if (!WORDCHAR_P (d))
4262 goto fail;
4263 SET_REGS_MATCHED ();
4264 d++;
4265 break;
4267 case notwordchar:
4268 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4269 PREFETCH ();
4270 if (WORDCHAR_P (d))
4271 goto fail;
4272 SET_REGS_MATCHED ();
4273 d++;
4274 break;
4275 #endif /* not emacs */
4277 default:
4278 abort ();
4280 continue; /* Successfully executed one pattern command; keep going. */
4283 /* We goto here if a matching operation fails. */
4284 fail:
4285 if (!FAIL_STACK_EMPTY ())
4286 { /* A restart point is known. Restore to that state. */
4287 DEBUG_PRINT1 ("\nFAIL:\n");
4288 POP_FAILURE_POINT (d, p,
4289 lowest_active_reg, highest_active_reg,
4290 regstart, regend, reg_info);
4292 /* If this failure point is a dummy, try the next one. */
4293 if (!p)
4294 goto fail;
4296 /* If we failed to the end of the pattern, don't examine *p. */
4297 assert (p <= pend);
4298 if (p < pend)
4300 boolean is_a_jump_n = false;
4302 /* If failed to a backwards jump that's part of a repetition
4303 loop, need to pop this failure point and use the next one. */
4304 switch ((re_opcode_t) *p)
4306 case jump_n:
4307 is_a_jump_n = true;
4308 case maybe_pop_jump:
4309 case pop_failure_jump:
4310 case jump:
4311 p1 = p + 1;
4312 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4313 p1 += mcnt;
4315 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4316 || (!is_a_jump_n
4317 && (re_opcode_t) *p1 == on_failure_jump))
4318 goto fail;
4319 break;
4320 default:
4321 /* do nothing */ ;
4325 if (d >= string1 && d <= end1)
4326 dend = end_match_1;
4328 else
4329 break; /* Matching at this starting point really fails. */
4330 } /* for (;;) */
4332 if (best_regs_set)
4333 goto restore_best_regs;
4335 FREE_VARIABLES ();
4337 return -1; /* Failure to match. */
4338 } /* re_match_2 */
4340 /* Subroutine definitions for re_match_2. */
4343 /* We are passed P pointing to a register number after a start_memory.
4345 Return true if the pattern up to the corresponding stop_memory can
4346 match the empty string, and false otherwise.
4348 If we find the matching stop_memory, sets P to point to one past its number.
4349 Otherwise, sets P to an undefined byte less than or equal to END.
4351 We don't handle duplicates properly (yet). */
4353 static boolean
4354 group_match_null_string_p (p, end, reg_info)
4355 unsigned char **p, *end;
4356 register_info_type *reg_info;
4358 int mcnt;
4359 /* Point to after the args to the start_memory. */
4360 unsigned char *p1 = *p + 2;
4362 while (p1 < end)
4364 /* Skip over opcodes that can match nothing, and return true or
4365 false, as appropriate, when we get to one that can't, or to the
4366 matching stop_memory. */
4368 switch ((re_opcode_t) *p1)
4370 /* Could be either a loop or a series of alternatives. */
4371 case on_failure_jump:
4372 p1++;
4373 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4375 /* If the next operation is not a jump backwards in the
4376 pattern. */
4378 if (mcnt >= 0)
4380 /* Go through the on_failure_jumps of the alternatives,
4381 seeing if any of the alternatives cannot match nothing.
4382 The last alternative starts with only a jump,
4383 whereas the rest start with on_failure_jump and end
4384 with a jump, e.g., here is the pattern for `a|b|c':
4386 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4387 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4388 /exactn/1/c
4390 So, we have to first go through the first (n-1)
4391 alternatives and then deal with the last one separately. */
4394 /* Deal with the first (n-1) alternatives, which start
4395 with an on_failure_jump (see above) that jumps to right
4396 past a jump_past_alt. */
4398 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4400 /* `mcnt' holds how many bytes long the alternative
4401 is, including the ending `jump_past_alt' and
4402 its number. */
4404 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
4405 reg_info))
4406 return false;
4408 /* Move to right after this alternative, including the
4409 jump_past_alt. */
4410 p1 += mcnt;
4412 /* Break if it's the beginning of an n-th alternative
4413 that doesn't begin with an on_failure_jump. */
4414 if ((re_opcode_t) *p1 != on_failure_jump)
4415 break;
4417 /* Still have to check that it's not an n-th
4418 alternative that starts with an on_failure_jump. */
4419 p1++;
4420 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4421 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4423 /* Get to the beginning of the n-th alternative. */
4424 p1 -= 3;
4425 break;
4429 /* Deal with the last alternative: go back and get number
4430 of the `jump_past_alt' just before it. `mcnt' contains
4431 the length of the alternative. */
4432 EXTRACT_NUMBER (mcnt, p1 - 2);
4434 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
4435 return false;
4437 p1 += mcnt; /* Get past the n-th alternative. */
4438 } /* if mcnt > 0 */
4439 break;
4442 case stop_memory:
4443 assert (p1[1] == **p);
4444 *p = p1 + 2;
4445 return true;
4448 default:
4449 if (!common_op_match_null_string_p (&p1, end, reg_info))
4450 return false;
4452 } /* while p1 < end */
4454 return false;
4455 } /* group_match_null_string_p */
4458 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4459 It expects P to be the first byte of a single alternative and END one
4460 byte past the last. The alternative can contain groups. */
4462 static boolean
4463 alt_match_null_string_p (p, end, reg_info)
4464 unsigned char *p, *end;
4465 register_info_type *reg_info;
4467 int mcnt;
4468 unsigned char *p1 = p;
4470 while (p1 < end)
4472 /* Skip over opcodes that can match nothing, and break when we get
4473 to one that can't. */
4475 switch ((re_opcode_t) *p1)
4477 /* It's a loop. */
4478 case on_failure_jump:
4479 p1++;
4480 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4481 p1 += mcnt;
4482 break;
4484 default:
4485 if (!common_op_match_null_string_p (&p1, end, reg_info))
4486 return false;
4488 } /* while p1 < end */
4490 return true;
4491 } /* alt_match_null_string_p */
4494 /* Deals with the ops common to group_match_null_string_p and
4495 alt_match_null_string_p.
4497 Sets P to one after the op and its arguments, if any. */
4499 static boolean
4500 common_op_match_null_string_p (p, end, reg_info)
4501 unsigned char **p, *end;
4502 register_info_type *reg_info;
4504 int mcnt;
4505 boolean ret;
4506 int reg_no;
4507 unsigned char *p1 = *p;
4509 switch ((re_opcode_t) *p1++)
4511 case no_op:
4512 case begline:
4513 case endline:
4514 case begbuf:
4515 case endbuf:
4516 case wordbeg:
4517 case wordend:
4518 case wordbound:
4519 case notwordbound:
4520 #ifdef emacs
4521 case before_dot:
4522 case at_dot:
4523 case after_dot:
4524 #endif
4525 break;
4527 case start_memory:
4528 reg_no = *p1;
4529 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
4530 ret = group_match_null_string_p (&p1, end, reg_info);
4532 /* Have to set this here in case we're checking a group which
4533 contains a group and a back reference to it. */
4535 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4536 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
4538 if (!ret)
4539 return false;
4540 break;
4542 /* If this is an optimized succeed_n for zero times, make the jump. */
4543 case jump:
4544 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4545 if (mcnt >= 0)
4546 p1 += mcnt;
4547 else
4548 return false;
4549 break;
4551 case succeed_n:
4552 /* Get to the number of times to succeed. */
4553 p1 += 2;
4554 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4556 if (mcnt == 0)
4558 p1 -= 4;
4559 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4560 p1 += mcnt;
4562 else
4563 return false;
4564 break;
4566 case duplicate:
4567 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
4568 return false;
4569 break;
4571 case set_number_at:
4572 p1 += 4;
4574 default:
4575 /* All other opcodes mean we cannot match the empty string. */
4576 return false;
4579 *p = p1;
4580 return true;
4581 } /* common_op_match_null_string_p */
4584 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4585 bytes; nonzero otherwise. */
4587 static int
4588 bcmp_translate (s1, s2, len, translate)
4589 unsigned char *s1, *s2;
4590 register int len;
4591 char *translate;
4593 register unsigned char *p1 = s1, *p2 = s2;
4594 while (len)
4596 if (translate[*p1++] != translate[*p2++]) return 1;
4597 len--;
4599 return 0;
4602 /* Entry points for GNU code. */
4604 /* re_compile_pattern is the GNU regular expression compiler: it
4605 compiles PATTERN (of length SIZE) and puts the result in BUFP.
4606 Returns 0 if the pattern was valid, otherwise an error string.
4608 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
4609 are set in BUFP on entry.
4611 We call regex_compile to do the actual compilation. */
4613 const char *
4614 re_compile_pattern (pattern, length, bufp)
4615 const char *pattern;
4616 int length;
4617 struct re_pattern_buffer *bufp;
4619 reg_errcode_t ret;
4621 /* GNU code is written to assume at least RE_NREGS registers will be set
4622 (and at least one extra will be -1). */
4623 bufp->regs_allocated = REGS_UNALLOCATED;
4625 /* And GNU code determines whether or not to get register information
4626 by passing null for the REGS argument to re_match, etc., not by
4627 setting no_sub. */
4628 bufp->no_sub = 0;
4630 /* Match anchors at newline. */
4631 bufp->newline_anchor = 1;
4633 ret = regex_compile (pattern, length, re_syntax_options, bufp);
4635 return re_error_msg[(int) ret];
4638 /* Entry points compatible with 4.2 BSD regex library. We don't define
4639 them if this is an Emacs or POSIX compilation. */
4641 #if !defined (emacs) && !defined (_POSIX_SOURCE)
4643 /* BSD has one and only one pattern buffer. */
4644 static struct re_pattern_buffer re_comp_buf;
4646 char *
4647 re_comp (s)
4648 const char *s;
4650 reg_errcode_t ret;
4652 if (!s)
4654 if (!re_comp_buf.buffer)
4655 return "No previous regular expression";
4656 return 0;
4659 if (!re_comp_buf.buffer)
4661 re_comp_buf.buffer = (unsigned char *) malloc (200);
4662 if (re_comp_buf.buffer == NULL)
4663 return "Memory exhausted";
4664 re_comp_buf.allocated = 200;
4666 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
4667 if (re_comp_buf.fastmap == NULL)
4668 return "Memory exhausted";
4671 /* Since `re_exec' always passes NULL for the `regs' argument, we
4672 don't need to initialize the pattern buffer fields which affect it. */
4674 /* Match anchors at newlines. */
4675 re_comp_buf.newline_anchor = 1;
4677 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
4679 /* Yes, we're discarding `const' here. */
4680 return (char *) re_error_msg[(int) ret];
4685 re_exec (s)
4686 const char *s;
4688 const int len = strlen (s);
4689 return
4690 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
4692 #endif /* not emacs and not _POSIX_SOURCE */
4694 /* POSIX.2 functions. Don't define these for Emacs. */
4696 #ifndef emacs
4698 /* regcomp takes a regular expression as a string and compiles it.
4700 PREG is a regex_t *. We do not expect any fields to be initialized,
4701 since POSIX says we shouldn't. Thus, we set
4703 `buffer' to the compiled pattern;
4704 `used' to the length of the compiled pattern;
4705 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
4706 REG_EXTENDED bit in CFLAGS is set; otherwise, to
4707 RE_SYNTAX_POSIX_BASIC;
4708 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
4709 `fastmap' and `fastmap_accurate' to zero;
4710 `re_nsub' to the number of subexpressions in PATTERN.
4712 PATTERN is the address of the pattern string.
4714 CFLAGS is a series of bits which affect compilation.
4716 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
4717 use POSIX basic syntax.
4719 If REG_NEWLINE is set, then . and [^...] don't match newline.
4720 Also, regexec will try a match beginning after every newline.
4722 If REG_ICASE is set, then we considers upper- and lowercase
4723 versions of letters to be equivalent when matching.
4725 If REG_NOSUB is set, then when PREG is passed to regexec, that
4726 routine will report only success or failure, and nothing about the
4727 registers.
4729 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
4730 the return codes and their meanings.) */
4733 regcomp (preg, pattern, cflags)
4734 regex_t *preg;
4735 const char *pattern;
4736 int cflags;
4738 reg_errcode_t ret;
4739 unsigned syntax
4740 = (cflags & REG_EXTENDED) ?
4741 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
4743 /* regex_compile will allocate the space for the compiled pattern. */
4744 preg->buffer = 0;
4745 preg->allocated = 0;
4747 /* Don't bother to use a fastmap when searching. This simplifies the
4748 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
4749 characters after newlines into the fastmap. This way, we just try
4750 every character. */
4751 preg->fastmap = 0;
4753 if (cflags & REG_ICASE)
4755 unsigned i;
4757 preg->translate = (char *) malloc (CHAR_SET_SIZE);
4758 if (preg->translate == NULL)
4759 return (int) REG_ESPACE;
4761 /* Map uppercase characters to corresponding lowercase ones. */
4762 for (i = 0; i < CHAR_SET_SIZE; i++)
4763 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
4765 else
4766 preg->translate = NULL;
4768 /* If REG_NEWLINE is set, newlines are treated differently. */
4769 if (cflags & REG_NEWLINE)
4770 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
4771 syntax &= ~RE_DOT_NEWLINE;
4772 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
4773 /* It also changes the matching behavior. */
4774 preg->newline_anchor = 1;
4776 else
4777 preg->newline_anchor = 0;
4779 preg->no_sub = !!(cflags & REG_NOSUB);
4781 /* POSIX says a null character in the pattern terminates it, so we
4782 can use strlen here in compiling the pattern. */
4783 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
4785 /* POSIX doesn't distinguish between an unmatched open-group and an
4786 unmatched close-group: both are REG_EPAREN. */
4787 if (ret == REG_ERPAREN) ret = REG_EPAREN;
4789 return (int) ret;
4793 /* regexec searches for a given pattern, specified by PREG, in the
4794 string STRING.
4796 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
4797 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
4798 least NMATCH elements, and we set them to the offsets of the
4799 corresponding matched substrings.
4801 EFLAGS specifies `execution flags' which affect matching: if
4802 REG_NOTBOL is set, then ^ does not match at the beginning of the
4803 string; if REG_NOTEOL is set, then $ does not match at the end.
4805 We return 0 if we find a match and REG_NOMATCH if not. */
4808 regexec (preg, string, nmatch, pmatch, eflags)
4809 const regex_t *preg;
4810 const char *string;
4811 size_t nmatch;
4812 regmatch_t pmatch[];
4813 int eflags;
4815 int ret;
4816 struct re_registers regs;
4817 regex_t private_preg;
4818 int len = strlen (string);
4819 boolean want_reg_info = !preg->no_sub && nmatch > 0;
4821 private_preg = *preg;
4823 private_preg.not_bol = !!(eflags & REG_NOTBOL);
4824 private_preg.not_eol = !!(eflags & REG_NOTEOL);
4826 /* The user has told us exactly how many registers to return
4827 information about, via `nmatch'. We have to pass that on to the
4828 matching routines. */
4829 private_preg.regs_allocated = REGS_FIXED;
4831 if (want_reg_info)
4833 regs.num_regs = nmatch;
4834 regs.start = TALLOC (nmatch, regoff_t);
4835 regs.end = TALLOC (nmatch, regoff_t);
4836 if (regs.start == NULL || regs.end == NULL)
4837 return (int) REG_NOMATCH;
4840 /* Perform the searching operation. */
4841 ret = re_search (&private_preg, string, len,
4842 /* start: */ 0, /* range: */ len,
4843 want_reg_info ? &regs : (struct re_registers *) 0);
4845 /* Copy the register information to the POSIX structure. */
4846 if (want_reg_info)
4848 if (ret >= 0)
4850 unsigned r;
4852 for (r = 0; r < nmatch; r++)
4854 pmatch[r].rm_so = regs.start[r];
4855 pmatch[r].rm_eo = regs.end[r];
4859 /* If we needed the temporary register info, free the space now. */
4860 free (regs.start);
4861 free (regs.end);
4864 /* We want zero return to mean success, unlike `re_search'. */
4865 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
4869 /* Returns a message corresponding to an error code, ERRCODE, returned
4870 from either regcomp or regexec. We don't use PREG here. */
4872 size_t
4873 regerror (errcode, preg, errbuf, errbuf_size)
4874 int errcode;
4875 const regex_t *preg;
4876 char *errbuf;
4877 size_t errbuf_size;
4879 const char *msg;
4880 size_t msg_size;
4882 if (errcode < 0
4883 || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0])))
4884 /* Only error codes returned by the rest of the code should be passed
4885 to this routine. If we are given anything else, or if other regex
4886 code generates an invalid error code, then the program has a bug.
4887 Dump core so we can fix it. */
4888 abort ();
4890 msg = re_error_msg[errcode];
4892 /* POSIX doesn't require that we do anything in this case, but why
4893 not be nice. */
4894 if (! msg)
4895 msg = "Success";
4897 msg_size = strlen (msg) + 1; /* Includes the null. */
4899 if (errbuf_size != 0)
4901 if (msg_size > errbuf_size)
4903 strncpy (errbuf, msg, errbuf_size - 1);
4904 errbuf[errbuf_size - 1] = 0;
4906 else
4907 strcpy (errbuf, msg);
4910 return msg_size;
4914 /* Free dynamically allocated space used by PREG. */
4916 void
4917 regfree (preg)
4918 regex_t *preg;
4920 if (preg->buffer != NULL)
4921 free (preg->buffer);
4922 preg->buffer = NULL;
4924 preg->allocated = 0;
4925 preg->used = 0;
4927 if (preg->fastmap != NULL)
4928 free (preg->fastmap);
4929 preg->fastmap = NULL;
4930 preg->fastmap_accurate = 0;
4932 if (preg->translate != NULL)
4933 free (preg->translate);
4934 preg->translate = NULL;
4937 #endif /* not emacs */
4940 Local variables:
4941 make-backup-files: t
4942 version-control: t
4943 trim-versions-without-asking: nil
4944 End: