Reimplement rename()
[git/pclouds.git] / compat / regex.c
blob2d57c70b9ce75a20ce2e05f8d5dc2f8feb3026ed
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 #define _GNU_SOURCE
29 /* We need this for `regex.h', and perhaps for the Emacs include files. */
30 #include <sys/types.h>
32 /* We used to test for `BSTRING' here, but only GCC and Emacs define
33 `BSTRING', as far as I know, and neither of them use this code. */
34 #include <string.h>
35 #ifndef bcmp
36 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
37 #endif
38 #ifndef bcopy
39 #define bcopy(s, d, n) memcpy ((d), (s), (n))
40 #endif
41 #ifndef bzero
42 #define bzero(s, n) memset ((s), 0, (n))
43 #endif
45 #include <stdlib.h>
48 /* Define the syntax stuff for \<, \>, etc. */
50 /* This must be nonzero for the wordchar and notwordchar pattern
51 commands in re_match_2. */
52 #ifndef Sword
53 #define Sword 1
54 #endif
56 #ifdef SYNTAX_TABLE
58 extern char *re_syntax_table;
60 #else /* not SYNTAX_TABLE */
62 /* How many characters in the character set. */
63 #define CHAR_SET_SIZE 256
65 static char re_syntax_table[CHAR_SET_SIZE];
67 static void
68 init_syntax_once ()
70 register int c;
71 static int done = 0;
73 if (done)
74 return;
76 bzero (re_syntax_table, sizeof re_syntax_table);
78 for (c = 'a'; c <= 'z'; c++)
79 re_syntax_table[c] = Sword;
81 for (c = 'A'; c <= 'Z'; c++)
82 re_syntax_table[c] = Sword;
84 for (c = '0'; c <= '9'; c++)
85 re_syntax_table[c] = Sword;
87 re_syntax_table['_'] = Sword;
89 done = 1;
92 #endif /* not SYNTAX_TABLE */
94 #define SYNTAX(c) re_syntax_table[c]
97 /* Get the interface, including the syntax bits. */
98 #include "regex.h"
100 /* isalpha etc. are used for the character classes. */
101 #include <ctype.h>
103 #ifndef isascii
104 #define isascii(c) 1
105 #endif
107 #ifdef isblank
108 #define ISBLANK(c) (isascii (c) && isblank (c))
109 #else
110 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
111 #endif
112 #ifdef isgraph
113 #define ISGRAPH(c) (isascii (c) && isgraph (c))
114 #else
115 #define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c))
116 #endif
118 #define ISPRINT(c) (isascii (c) && isprint (c))
119 #define ISDIGIT(c) (isascii (c) && isdigit (c))
120 #define ISALNUM(c) (isascii (c) && isalnum (c))
121 #define ISALPHA(c) (isascii (c) && isalpha (c))
122 #define ISCNTRL(c) (isascii (c) && iscntrl (c))
123 #define ISLOWER(c) (isascii (c) && islower (c))
124 #define ISPUNCT(c) (isascii (c) && ispunct (c))
125 #define ISSPACE(c) (isascii (c) && isspace (c))
126 #define ISUPPER(c) (isascii (c) && isupper (c))
127 #define ISXDIGIT(c) (isascii (c) && isxdigit (c))
129 #ifndef NULL
130 #define NULL 0
131 #endif
133 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
134 since ours (we hope) works properly with all combinations of
135 machines, compilers, `char' and `unsigned char' argument types.
136 (Per Bothner suggested the basic approach.) */
137 #undef SIGN_EXTEND_CHAR
138 #if __STDC__
139 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
140 #else /* not __STDC__ */
141 /* As in Harbison and Steele. */
142 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
143 #endif
145 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
146 use `alloca' instead of `malloc'. This is because using malloc in
147 re_search* or re_match* could cause memory leaks when C-g is used in
148 Emacs; also, malloc is slower and causes storage fragmentation. On
149 the other hand, malloc is more portable, and easier to debug.
151 Because we sometimes use alloca, some routines have to be macros,
152 not functions -- `alloca'-allocated space disappears at the end of the
153 function it is called in. */
155 #ifdef REGEX_MALLOC
157 #define REGEX_ALLOCATE malloc
158 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
160 #else /* not REGEX_MALLOC */
162 /* Emacs already defines alloca, sometimes. */
163 #ifndef alloca
165 /* Make alloca work the best possible way. */
166 #ifdef __GNUC__
167 #define alloca __builtin_alloca
168 #else /* not __GNUC__ */
169 #if HAVE_ALLOCA_H
170 #include <alloca.h>
171 #else /* not __GNUC__ or HAVE_ALLOCA_H */
172 #ifndef _AIX /* Already did AIX, up at the top. */
173 char *alloca ();
174 #endif /* not _AIX */
175 #endif /* not HAVE_ALLOCA_H */
176 #endif /* not __GNUC__ */
178 #endif /* not alloca */
180 #define REGEX_ALLOCATE alloca
182 /* Assumes a `char *destination' variable. */
183 #define REGEX_REALLOCATE(source, osize, nsize) \
184 (destination = (char *) alloca (nsize), \
185 bcopy (source, destination, osize), \
186 destination)
188 #endif /* not REGEX_MALLOC */
191 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
192 `string1' or just past its end. This works if PTR is NULL, which is
193 a good thing. */
194 #define FIRST_STRING_P(ptr) \
195 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
197 /* (Re)Allocate N items of type T using malloc, or fail. */
198 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
199 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
200 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
202 #define BYTEWIDTH 8 /* In bits. */
204 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
206 #define MAX(a, b) ((a) > (b) ? (a) : (b))
207 #define MIN(a, b) ((a) < (b) ? (a) : (b))
209 typedef char boolean;
210 #define false 0
211 #define true 1
213 /* These are the command codes that appear in compiled regular
214 expressions. Some opcodes are followed by argument bytes. A
215 command code can specify any interpretation whatsoever for its
216 arguments. Zero bytes may appear in the compiled regular expression.
218 The value of `exactn' is needed in search.c (search_buffer) in Emacs.
219 So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
220 `exactn' we use here must also be 1. */
222 typedef enum
224 no_op = 0,
226 /* Followed by one byte giving n, then by n literal bytes. */
227 exactn = 1,
229 /* Matches any (more or less) character. */
230 anychar,
232 /* Matches any one char belonging to specified set. First
233 following byte is number of bitmap bytes. Then come bytes
234 for a bitmap saying which chars are in. Bits in each byte
235 are ordered low-bit-first. A character is in the set if its
236 bit is 1. A character too large to have a bit in the map is
237 automatically not in the set. */
238 charset,
240 /* Same parameters as charset, but match any character that is
241 not one of those specified. */
242 charset_not,
244 /* Start remembering the text that is matched, for storing in a
245 register. Followed by one byte with the register number, in
246 the range 0 to one less than the pattern buffer's re_nsub
247 field. Then followed by one byte with the number of groups
248 inner to this one. (This last has to be part of the
249 start_memory only because we need it in the on_failure_jump
250 of re_match_2.) */
251 start_memory,
253 /* Stop remembering the text that is matched and store it in a
254 memory register. Followed by one byte with the register
255 number, in the range 0 to one less than `re_nsub' in the
256 pattern buffer, and one byte with the number of inner groups,
257 just like `start_memory'. (We need the number of inner
258 groups here because we don't have any easy way of finding the
259 corresponding start_memory when we're at a stop_memory.) */
260 stop_memory,
262 /* Match a duplicate of something remembered. Followed by one
263 byte containing the register number. */
264 duplicate,
266 /* Fail unless at beginning of line. */
267 begline,
269 /* Fail unless at end of line. */
270 endline,
272 /* Succeeds if at beginning of buffer (if emacs) or at beginning
273 of string to be matched (if not). */
274 begbuf,
276 /* Analogously, for end of buffer/string. */
277 endbuf,
279 /* Followed by two byte relative address to which to jump. */
280 jump,
282 /* Same as jump, but marks the end of an alternative. */
283 jump_past_alt,
285 /* Followed by two-byte relative address of place to resume at
286 in case of failure. */
287 on_failure_jump,
289 /* Like on_failure_jump, but pushes a placeholder instead of the
290 current string position when executed. */
291 on_failure_keep_string_jump,
293 /* Throw away latest failure point and then jump to following
294 two-byte relative address. */
295 pop_failure_jump,
297 /* Change to pop_failure_jump if know won't have to backtrack to
298 match; otherwise change to jump. This is used to jump
299 back to the beginning of a repeat. If what follows this jump
300 clearly won't match what the repeat does, such that we can be
301 sure that there is no use backtracking out of repetitions
302 already matched, then we change it to a pop_failure_jump.
303 Followed by two-byte address. */
304 maybe_pop_jump,
306 /* Jump to following two-byte address, and push a dummy failure
307 point. This failure point will be thrown away if an attempt
308 is made to use it for a failure. A `+' construct makes this
309 before the first repeat. Also used as an intermediary kind
310 of jump when compiling an alternative. */
311 dummy_failure_jump,
313 /* Push a dummy failure point and continue. Used at the end of
314 alternatives. */
315 push_dummy_failure,
317 /* Followed by two-byte relative address and two-byte number n.
318 After matching N times, jump to the address upon failure. */
319 succeed_n,
321 /* Followed by two-byte relative address, and two-byte number n.
322 Jump to the address N times, then fail. */
323 jump_n,
325 /* Set the following two-byte relative address to the
326 subsequent two-byte number. The address *includes* the two
327 bytes of number. */
328 set_number_at,
330 wordchar, /* Matches any word-constituent character. */
331 notwordchar, /* Matches any char that is not a word-constituent. */
333 wordbeg, /* Succeeds if at word beginning. */
334 wordend, /* Succeeds if at word end. */
336 wordbound, /* Succeeds if at a word boundary. */
337 notwordbound /* Succeeds if not at a word boundary. */
339 #ifdef emacs
340 ,before_dot, /* Succeeds if before point. */
341 at_dot, /* Succeeds if at point. */
342 after_dot, /* Succeeds if after point. */
344 /* Matches any character whose syntax is specified. Followed by
345 a byte which contains a syntax code, e.g., Sword. */
346 syntaxspec,
348 /* Matches any character whose syntax is not that specified. */
349 notsyntaxspec
350 #endif /* emacs */
351 } re_opcode_t;
353 /* Common operations on the compiled pattern. */
355 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
357 #define STORE_NUMBER(destination, number) \
358 do { \
359 (destination)[0] = (number) & 0377; \
360 (destination)[1] = (number) >> 8; \
361 } while (0)
363 /* Same as STORE_NUMBER, except increment DESTINATION to
364 the byte after where the number is stored. Therefore, DESTINATION
365 must be an lvalue. */
367 #define STORE_NUMBER_AND_INCR(destination, number) \
368 do { \
369 STORE_NUMBER (destination, number); \
370 (destination) += 2; \
371 } while (0)
373 /* Put into DESTINATION a number stored in two contiguous bytes starting
374 at SOURCE. */
376 #define EXTRACT_NUMBER(destination, source) \
377 do { \
378 (destination) = *(source) & 0377; \
379 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
380 } while (0)
382 #ifdef DEBUG
383 static void
384 extract_number (dest, source)
385 int *dest;
386 unsigned char *source;
388 int temp = SIGN_EXTEND_CHAR (*(source + 1));
389 *dest = *source & 0377;
390 *dest += temp << 8;
393 #ifndef EXTRACT_MACROS /* To debug the macros. */
394 #undef EXTRACT_NUMBER
395 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
396 #endif /* not EXTRACT_MACROS */
398 #endif /* DEBUG */
400 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
401 SOURCE must be an lvalue. */
403 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
404 do { \
405 EXTRACT_NUMBER (destination, source); \
406 (source) += 2; \
407 } while (0)
409 #ifdef DEBUG
410 static void
411 extract_number_and_incr (destination, source)
412 int *destination;
413 unsigned char **source;
415 extract_number (destination, *source);
416 *source += 2;
419 #ifndef EXTRACT_MACROS
420 #undef EXTRACT_NUMBER_AND_INCR
421 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
422 extract_number_and_incr (&dest, &src)
423 #endif /* not EXTRACT_MACROS */
425 #endif /* DEBUG */
427 /* If DEBUG is defined, Regex prints many voluminous messages about what
428 it is doing (if the variable `debug' is nonzero). If linked with the
429 main program in `iregex.c', you can enter patterns and strings
430 interactively. And if linked with the main program in `main.c' and
431 the other test files, you can run the already-written tests. */
433 #ifdef DEBUG
435 /* We use standard I/O for debugging. */
436 #include <stdio.h>
438 /* It is useful to test things that ``must'' be true when debugging. */
439 #include <assert.h>
441 static int debug = 0;
443 #define DEBUG_STATEMENT(e) e
444 #define DEBUG_PRINT1(x) if (debug) printf (x)
445 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
446 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
447 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
448 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
449 if (debug) print_partial_compiled_pattern (s, e)
450 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
451 if (debug) print_double_string (w, s1, sz1, s2, sz2)
454 extern void printchar ();
456 /* Print the fastmap in human-readable form. */
458 void
459 print_fastmap (fastmap)
460 char *fastmap;
462 unsigned was_a_range = 0;
463 unsigned i = 0;
465 while (i < (1 << BYTEWIDTH))
467 if (fastmap[i++])
469 was_a_range = 0;
470 printchar (i - 1);
471 while (i < (1 << BYTEWIDTH) && fastmap[i])
473 was_a_range = 1;
474 i++;
476 if (was_a_range)
478 printf ("-");
479 printchar (i - 1);
483 putchar ('\n');
487 /* Print a compiled pattern string in human-readable form, starting at
488 the START pointer into it and ending just before the pointer END. */
490 void
491 print_partial_compiled_pattern (start, end)
492 unsigned char *start;
493 unsigned char *end;
495 int mcnt, mcnt2;
496 unsigned char *p = start;
497 unsigned char *pend = end;
499 if (start == NULL)
501 printf ("(null)\n");
502 return;
505 /* Loop over pattern commands. */
506 while (p < pend)
508 switch ((re_opcode_t) *p++)
510 case no_op:
511 printf ("/no_op");
512 break;
514 case exactn:
515 mcnt = *p++;
516 printf ("/exactn/%d", mcnt);
519 putchar ('/');
520 printchar (*p++);
522 while (--mcnt);
523 break;
525 case start_memory:
526 mcnt = *p++;
527 printf ("/start_memory/%d/%d", mcnt, *p++);
528 break;
530 case stop_memory:
531 mcnt = *p++;
532 printf ("/stop_memory/%d/%d", mcnt, *p++);
533 break;
535 case duplicate:
536 printf ("/duplicate/%d", *p++);
537 break;
539 case anychar:
540 printf ("/anychar");
541 break;
543 case charset:
544 case charset_not:
546 register int c;
548 printf ("/charset%s",
549 (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
551 assert (p + *p < pend);
553 for (c = 0; c < *p; c++)
555 unsigned bit;
556 unsigned char map_byte = p[1 + c];
558 putchar ('/');
560 for (bit = 0; bit < BYTEWIDTH; bit++)
561 if (map_byte & (1 << bit))
562 printchar (c * BYTEWIDTH + bit);
564 p += 1 + *p;
565 break;
568 case begline:
569 printf ("/begline");
570 break;
572 case endline:
573 printf ("/endline");
574 break;
576 case on_failure_jump:
577 extract_number_and_incr (&mcnt, &p);
578 printf ("/on_failure_jump/0/%d", mcnt);
579 break;
581 case on_failure_keep_string_jump:
582 extract_number_and_incr (&mcnt, &p);
583 printf ("/on_failure_keep_string_jump/0/%d", mcnt);
584 break;
586 case dummy_failure_jump:
587 extract_number_and_incr (&mcnt, &p);
588 printf ("/dummy_failure_jump/0/%d", mcnt);
589 break;
591 case push_dummy_failure:
592 printf ("/push_dummy_failure");
593 break;
595 case maybe_pop_jump:
596 extract_number_and_incr (&mcnt, &p);
597 printf ("/maybe_pop_jump/0/%d", mcnt);
598 break;
600 case pop_failure_jump:
601 extract_number_and_incr (&mcnt, &p);
602 printf ("/pop_failure_jump/0/%d", mcnt);
603 break;
605 case jump_past_alt:
606 extract_number_and_incr (&mcnt, &p);
607 printf ("/jump_past_alt/0/%d", mcnt);
608 break;
610 case jump:
611 extract_number_and_incr (&mcnt, &p);
612 printf ("/jump/0/%d", mcnt);
613 break;
615 case succeed_n:
616 extract_number_and_incr (&mcnt, &p);
617 extract_number_and_incr (&mcnt2, &p);
618 printf ("/succeed_n/0/%d/0/%d", mcnt, mcnt2);
619 break;
621 case jump_n:
622 extract_number_and_incr (&mcnt, &p);
623 extract_number_and_incr (&mcnt2, &p);
624 printf ("/jump_n/0/%d/0/%d", mcnt, mcnt2);
625 break;
627 case set_number_at:
628 extract_number_and_incr (&mcnt, &p);
629 extract_number_and_incr (&mcnt2, &p);
630 printf ("/set_number_at/0/%d/0/%d", mcnt, mcnt2);
631 break;
633 case wordbound:
634 printf ("/wordbound");
635 break;
637 case notwordbound:
638 printf ("/notwordbound");
639 break;
641 case wordbeg:
642 printf ("/wordbeg");
643 break;
645 case wordend:
646 printf ("/wordend");
648 #ifdef emacs
649 case before_dot:
650 printf ("/before_dot");
651 break;
653 case at_dot:
654 printf ("/at_dot");
655 break;
657 case after_dot:
658 printf ("/after_dot");
659 break;
661 case syntaxspec:
662 printf ("/syntaxspec");
663 mcnt = *p++;
664 printf ("/%d", mcnt);
665 break;
667 case notsyntaxspec:
668 printf ("/notsyntaxspec");
669 mcnt = *p++;
670 printf ("/%d", mcnt);
671 break;
672 #endif /* emacs */
674 case wordchar:
675 printf ("/wordchar");
676 break;
678 case notwordchar:
679 printf ("/notwordchar");
680 break;
682 case begbuf:
683 printf ("/begbuf");
684 break;
686 case endbuf:
687 printf ("/endbuf");
688 break;
690 default:
691 printf ("?%d", *(p-1));
694 printf ("/\n");
698 void
699 print_compiled_pattern (bufp)
700 struct re_pattern_buffer *bufp;
702 unsigned char *buffer = bufp->buffer;
704 print_partial_compiled_pattern (buffer, buffer + bufp->used);
705 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
707 if (bufp->fastmap_accurate && bufp->fastmap)
709 printf ("fastmap: ");
710 print_fastmap (bufp->fastmap);
713 printf ("re_nsub: %d\t", bufp->re_nsub);
714 printf ("regs_alloc: %d\t", bufp->regs_allocated);
715 printf ("can_be_null: %d\t", bufp->can_be_null);
716 printf ("newline_anchor: %d\n", bufp->newline_anchor);
717 printf ("no_sub: %d\t", bufp->no_sub);
718 printf ("not_bol: %d\t", bufp->not_bol);
719 printf ("not_eol: %d\t", bufp->not_eol);
720 printf ("syntax: %d\n", bufp->syntax);
721 /* Perhaps we should print the translate table? */
725 void
726 print_double_string (where, string1, size1, string2, size2)
727 const char *where;
728 const char *string1;
729 const char *string2;
730 int size1;
731 int size2;
733 unsigned this_char;
735 if (where == NULL)
736 printf ("(null)");
737 else
739 if (FIRST_STRING_P (where))
741 for (this_char = where - string1; this_char < size1; this_char++)
742 printchar (string1[this_char]);
744 where = string2;
747 for (this_char = where - string2; this_char < size2; this_char++)
748 printchar (string2[this_char]);
752 #else /* not DEBUG */
754 #undef assert
755 #define assert(e)
757 #define DEBUG_STATEMENT(e)
758 #define DEBUG_PRINT1(x)
759 #define DEBUG_PRINT2(x1, x2)
760 #define DEBUG_PRINT3(x1, x2, x3)
761 #define DEBUG_PRINT4(x1, x2, x3, x4)
762 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
763 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
765 #endif /* not DEBUG */
767 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
768 also be assigned to arbitrarily: each pattern buffer stores its own
769 syntax, so it can be changed between regex compilations. */
770 reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
773 /* Specify the precise syntax of regexps for compilation. This provides
774 for compatibility for various utilities which historically have
775 different, incompatible syntaxes.
777 The argument SYNTAX is a bit mask comprised of the various bits
778 defined in regex.h. We return the old syntax. */
780 reg_syntax_t
781 re_set_syntax (syntax)
782 reg_syntax_t syntax;
784 reg_syntax_t ret = re_syntax_options;
786 re_syntax_options = syntax;
787 return ret;
790 /* This table gives an error message for each of the error codes listed
791 in regex.h. Obviously the order here has to be same as there. */
793 static const char *re_error_msg[] =
794 { NULL, /* REG_NOERROR */
795 "No match", /* REG_NOMATCH */
796 "Invalid regular expression", /* REG_BADPAT */
797 "Invalid collation character", /* REG_ECOLLATE */
798 "Invalid character class name", /* REG_ECTYPE */
799 "Trailing backslash", /* REG_EESCAPE */
800 "Invalid back reference", /* REG_ESUBREG */
801 "Unmatched [ or [^", /* REG_EBRACK */
802 "Unmatched ( or \\(", /* REG_EPAREN */
803 "Unmatched \\{", /* REG_EBRACE */
804 "Invalid content of \\{\\}", /* REG_BADBR */
805 "Invalid range end", /* REG_ERANGE */
806 "Memory exhausted", /* REG_ESPACE */
807 "Invalid preceding regular expression", /* REG_BADRPT */
808 "Premature end of regular expression", /* REG_EEND */
809 "Regular expression too big", /* REG_ESIZE */
810 "Unmatched ) or \\)", /* REG_ERPAREN */
813 /* Subroutine declarations and macros for regex_compile. */
815 static void store_op1 (), store_op2 ();
816 static void insert_op1 (), insert_op2 ();
817 static boolean at_begline_loc_p (), at_endline_loc_p ();
818 static boolean group_in_compile_stack ();
819 static reg_errcode_t compile_range ();
821 /* Fetch the next character in the uncompiled pattern---translating it
822 if necessary. Also cast from a signed character in the constant
823 string passed to us by the user to an unsigned char that we can use
824 as an array index (in, e.g., `translate'). */
825 #define PATFETCH(c) \
826 do {if (p == pend) return REG_EEND; \
827 c = (unsigned char) *p++; \
828 if (translate) c = translate[c]; \
829 } while (0)
831 /* Fetch the next character in the uncompiled pattern, with no
832 translation. */
833 #define PATFETCH_RAW(c) \
834 do {if (p == pend) return REG_EEND; \
835 c = (unsigned char) *p++; \
836 } while (0)
838 /* Go backwards one character in the pattern. */
839 #define PATUNFETCH p--
842 /* If `translate' is non-null, return translate[D], else just D. We
843 cast the subscript to translate because some data is declared as
844 `char *', to avoid warnings when a string constant is passed. But
845 when we use a character as a subscript we must make it unsigned. */
846 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
849 /* Macros for outputting the compiled pattern into `buffer'. */
851 /* If the buffer isn't allocated when it comes in, use this. */
852 #define INIT_BUF_SIZE 32
854 /* Make sure we have at least N more bytes of space in buffer. */
855 #define GET_BUFFER_SPACE(n) \
856 while (b - bufp->buffer + (n) > bufp->allocated) \
857 EXTEND_BUFFER ()
859 /* Make sure we have one more byte of buffer space and then add C to it. */
860 #define BUF_PUSH(c) \
861 do { \
862 GET_BUFFER_SPACE (1); \
863 *b++ = (unsigned char) (c); \
864 } while (0)
867 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
868 #define BUF_PUSH_2(c1, c2) \
869 do { \
870 GET_BUFFER_SPACE (2); \
871 *b++ = (unsigned char) (c1); \
872 *b++ = (unsigned char) (c2); \
873 } while (0)
876 /* As with BUF_PUSH_2, except for three bytes. */
877 #define BUF_PUSH_3(c1, c2, c3) \
878 do { \
879 GET_BUFFER_SPACE (3); \
880 *b++ = (unsigned char) (c1); \
881 *b++ = (unsigned char) (c2); \
882 *b++ = (unsigned char) (c3); \
883 } while (0)
886 /* Store a jump with opcode OP at LOC to location TO. We store a
887 relative address offset by the three bytes the jump itself occupies. */
888 #define STORE_JUMP(op, loc, to) \
889 store_op1 (op, loc, (to) - (loc) - 3)
891 /* Likewise, for a two-argument jump. */
892 #define STORE_JUMP2(op, loc, to, arg) \
893 store_op2 (op, loc, (to) - (loc) - 3, arg)
895 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
896 #define INSERT_JUMP(op, loc, to) \
897 insert_op1 (op, loc, (to) - (loc) - 3, b)
899 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
900 #define INSERT_JUMP2(op, loc, to, arg) \
901 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
904 /* This is not an arbitrary limit: the arguments which represent offsets
905 into the pattern are two bytes long. So if 2^16 bytes turns out to
906 be too small, many things would have to change. */
907 #define MAX_BUF_SIZE (1L << 16)
910 /* Extend the buffer by twice its current size via realloc and
911 reset the pointers that pointed into the old block to point to the
912 correct places in the new one. If extending the buffer results in it
913 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
914 #define EXTEND_BUFFER() \
915 do { \
916 unsigned char *old_buffer = bufp->buffer; \
917 if (bufp->allocated == MAX_BUF_SIZE) \
918 return REG_ESIZE; \
919 bufp->allocated <<= 1; \
920 if (bufp->allocated > MAX_BUF_SIZE) \
921 bufp->allocated = MAX_BUF_SIZE; \
922 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
923 if (bufp->buffer == NULL) \
924 return REG_ESPACE; \
925 /* If the buffer moved, move all the pointers into it. */ \
926 if (old_buffer != bufp->buffer) \
928 b = (b - old_buffer) + bufp->buffer; \
929 begalt = (begalt - old_buffer) + bufp->buffer; \
930 if (fixup_alt_jump) \
931 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
932 if (laststart) \
933 laststart = (laststart - old_buffer) + bufp->buffer; \
934 if (pending_exact) \
935 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
937 } while (0)
940 /* Since we have one byte reserved for the register number argument to
941 {start,stop}_memory, the maximum number of groups we can report
942 things about is what fits in that byte. */
943 #define MAX_REGNUM 255
945 /* But patterns can have more than `MAX_REGNUM' registers. We just
946 ignore the excess. */
947 typedef unsigned regnum_t;
950 /* Macros for the compile stack. */
952 /* Since offsets can go either forwards or backwards, this type needs to
953 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
954 typedef int pattern_offset_t;
956 typedef struct
958 pattern_offset_t begalt_offset;
959 pattern_offset_t fixup_alt_jump;
960 pattern_offset_t inner_group_offset;
961 pattern_offset_t laststart_offset;
962 regnum_t regnum;
963 } compile_stack_elt_t;
966 typedef struct
968 compile_stack_elt_t *stack;
969 unsigned size;
970 unsigned avail; /* Offset of next open position. */
971 } compile_stack_type;
974 #define INIT_COMPILE_STACK_SIZE 32
976 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
977 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
979 /* The next available element. */
980 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
983 /* Set the bit for character C in a list. */
984 #define SET_LIST_BIT(c) \
985 (b[((unsigned char) (c)) / BYTEWIDTH] \
986 |= 1 << (((unsigned char) c) % BYTEWIDTH))
989 /* Get the next unsigned number in the uncompiled pattern. */
990 #define GET_UNSIGNED_NUMBER(num) \
991 { if (p != pend) \
993 PATFETCH (c); \
994 while (ISDIGIT (c)) \
996 if (num < 0) \
997 num = 0; \
998 num = num * 10 + c - '0'; \
999 if (p == pend) \
1000 break; \
1001 PATFETCH (c); \
1006 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1008 #define IS_CHAR_CLASS(string) \
1009 (STREQ (string, "alpha") || STREQ (string, "upper") \
1010 || STREQ (string, "lower") || STREQ (string, "digit") \
1011 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1012 || STREQ (string, "space") || STREQ (string, "print") \
1013 || STREQ (string, "punct") || STREQ (string, "graph") \
1014 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1016 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1017 Returns one of error codes defined in `regex.h', or zero for success.
1019 Assumes the `allocated' (and perhaps `buffer') and `translate'
1020 fields are set in BUFP on entry.
1022 If it succeeds, results are put in BUFP (if it returns an error, the
1023 contents of BUFP are undefined):
1024 `buffer' is the compiled pattern;
1025 `syntax' is set to SYNTAX;
1026 `used' is set to the length of the compiled pattern;
1027 `fastmap_accurate' is zero;
1028 `re_nsub' is the number of subexpressions in PATTERN;
1029 `not_bol' and `not_eol' are zero;
1031 The `fastmap' and `newline_anchor' fields are neither
1032 examined nor set. */
1034 static reg_errcode_t
1035 regex_compile (pattern, size, syntax, bufp)
1036 const char *pattern;
1037 int size;
1038 reg_syntax_t syntax;
1039 struct re_pattern_buffer *bufp;
1041 /* We fetch characters from PATTERN here. Even though PATTERN is
1042 `char *' (i.e., signed), we declare these variables as unsigned, so
1043 they can be reliably used as array indices. */
1044 register unsigned char c, c1;
1046 /* A random tempory spot in PATTERN. */
1047 const char *p1;
1049 /* Points to the end of the buffer, where we should append. */
1050 register unsigned char *b;
1052 /* Keeps track of unclosed groups. */
1053 compile_stack_type compile_stack;
1055 /* Points to the current (ending) position in the pattern. */
1056 const char *p = pattern;
1057 const char *pend = pattern + size;
1059 /* How to translate the characters in the pattern. */
1060 char *translate = bufp->translate;
1062 /* Address of the count-byte of the most recently inserted `exactn'
1063 command. This makes it possible to tell if a new exact-match
1064 character can be added to that command or if the character requires
1065 a new `exactn' command. */
1066 unsigned char *pending_exact = 0;
1068 /* Address of start of the most recently finished expression.
1069 This tells, e.g., postfix * where to find the start of its
1070 operand. Reset at the beginning of groups and alternatives. */
1071 unsigned char *laststart = 0;
1073 /* Address of beginning of regexp, or inside of last group. */
1074 unsigned char *begalt;
1076 /* Place in the uncompiled pattern (i.e., the {) to
1077 which to go back if the interval is invalid. */
1078 const char *beg_interval;
1080 /* Address of the place where a forward jump should go to the end of
1081 the containing expression. Each alternative of an `or' -- except the
1082 last -- ends with a forward jump of this sort. */
1083 unsigned char *fixup_alt_jump = 0;
1085 /* Counts open-groups as they are encountered. Remembered for the
1086 matching close-group on the compile stack, so the same register
1087 number is put in the stop_memory as the start_memory. */
1088 regnum_t regnum = 0;
1090 #ifdef DEBUG
1091 DEBUG_PRINT1 ("\nCompiling pattern: ");
1092 if (debug)
1094 unsigned debug_count;
1096 for (debug_count = 0; debug_count < size; debug_count++)
1097 printchar (pattern[debug_count]);
1098 putchar ('\n');
1100 #endif /* DEBUG */
1102 /* Initialize the compile stack. */
1103 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1104 if (compile_stack.stack == NULL)
1105 return REG_ESPACE;
1107 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1108 compile_stack.avail = 0;
1110 /* Initialize the pattern buffer. */
1111 bufp->syntax = syntax;
1112 bufp->fastmap_accurate = 0;
1113 bufp->not_bol = bufp->not_eol = 0;
1115 /* Set `used' to zero, so that if we return an error, the pattern
1116 printer (for debugging) will think there's no pattern. We reset it
1117 at the end. */
1118 bufp->used = 0;
1120 /* Always count groups, whether or not bufp->no_sub is set. */
1121 bufp->re_nsub = 0;
1123 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1124 /* Initialize the syntax table. */
1125 init_syntax_once ();
1126 #endif
1128 if (bufp->allocated == 0)
1130 if (bufp->buffer)
1131 { /* If zero allocated, but buffer is non-null, try to realloc
1132 enough space. This loses if buffer's address is bogus, but
1133 that is the user's responsibility. */
1134 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1136 else
1137 { /* Caller did not allocate a buffer. Do it for them. */
1138 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1140 if (!bufp->buffer) return REG_ESPACE;
1142 bufp->allocated = INIT_BUF_SIZE;
1145 begalt = b = bufp->buffer;
1147 /* Loop through the uncompiled pattern until we're at the end. */
1148 while (p != pend)
1150 PATFETCH (c);
1152 switch (c)
1154 case '^':
1156 if ( /* If at start of pattern, it's an operator. */
1157 p == pattern + 1
1158 /* If context independent, it's an operator. */
1159 || syntax & RE_CONTEXT_INDEP_ANCHORS
1160 /* Otherwise, depends on what's come before. */
1161 || at_begline_loc_p (pattern, p, syntax))
1162 BUF_PUSH (begline);
1163 else
1164 goto normal_char;
1166 break;
1169 case '$':
1171 if ( /* If at end of pattern, it's an operator. */
1172 p == pend
1173 /* If context independent, it's an operator. */
1174 || syntax & RE_CONTEXT_INDEP_ANCHORS
1175 /* Otherwise, depends on what's next. */
1176 || at_endline_loc_p (p, pend, syntax))
1177 BUF_PUSH (endline);
1178 else
1179 goto normal_char;
1181 break;
1184 case '+':
1185 case '?':
1186 if ((syntax & RE_BK_PLUS_QM)
1187 || (syntax & RE_LIMITED_OPS))
1188 goto normal_char;
1189 handle_plus:
1190 case '*':
1191 /* If there is no previous pattern... */
1192 if (!laststart)
1194 if (syntax & RE_CONTEXT_INVALID_OPS)
1195 return REG_BADRPT;
1196 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1197 goto normal_char;
1201 /* Are we optimizing this jump? */
1202 boolean keep_string_p = false;
1204 /* 1 means zero (many) matches is allowed. */
1205 char zero_times_ok = 0, many_times_ok = 0;
1207 /* If there is a sequence of repetition chars, collapse it
1208 down to just one (the right one). We can't combine
1209 interval operators with these because of, e.g., `a{2}*',
1210 which should only match an even number of `a's. */
1212 for (;;)
1214 zero_times_ok |= c != '+';
1215 many_times_ok |= c != '?';
1217 if (p == pend)
1218 break;
1220 PATFETCH (c);
1222 if (c == '*'
1223 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1226 else if (syntax & RE_BK_PLUS_QM && c == '\\')
1228 if (p == pend) return REG_EESCAPE;
1230 PATFETCH (c1);
1231 if (!(c1 == '+' || c1 == '?'))
1233 PATUNFETCH;
1234 PATUNFETCH;
1235 break;
1238 c = c1;
1240 else
1242 PATUNFETCH;
1243 break;
1246 /* If we get here, we found another repeat character. */
1249 /* Star, etc. applied to an empty pattern is equivalent
1250 to an empty pattern. */
1251 if (!laststart)
1252 break;
1254 /* Now we know whether or not zero matches is allowed
1255 and also whether or not two or more matches is allowed. */
1256 if (many_times_ok)
1257 { /* More than one repetition is allowed, so put in at the
1258 end a backward relative jump from `b' to before the next
1259 jump we're going to put in below (which jumps from
1260 laststart to after this jump).
1262 But if we are at the `*' in the exact sequence `.*\n',
1263 insert an unconditional jump backwards to the .,
1264 instead of the beginning of the loop. This way we only
1265 push a failure point once, instead of every time
1266 through the loop. */
1267 assert (p - 1 > pattern);
1269 /* Allocate the space for the jump. */
1270 GET_BUFFER_SPACE (3);
1272 /* We know we are not at the first character of the pattern,
1273 because laststart was nonzero. And we've already
1274 incremented `p', by the way, to be the character after
1275 the `*'. Do we have to do something analogous here
1276 for null bytes, because of RE_DOT_NOT_NULL? */
1277 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1278 && zero_times_ok
1279 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1280 && !(syntax & RE_DOT_NEWLINE))
1281 { /* We have .*\n. */
1282 STORE_JUMP (jump, b, laststart);
1283 keep_string_p = true;
1285 else
1286 /* Anything else. */
1287 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1289 /* We've added more stuff to the buffer. */
1290 b += 3;
1293 /* On failure, jump from laststart to b + 3, which will be the
1294 end of the buffer after this jump is inserted. */
1295 GET_BUFFER_SPACE (3);
1296 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1297 : on_failure_jump,
1298 laststart, b + 3);
1299 pending_exact = 0;
1300 b += 3;
1302 if (!zero_times_ok)
1304 /* At least one repetition is required, so insert a
1305 `dummy_failure_jump' before the initial
1306 `on_failure_jump' instruction of the loop. This
1307 effects a skip over that instruction the first time
1308 we hit that loop. */
1309 GET_BUFFER_SPACE (3);
1310 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1311 b += 3;
1314 break;
1317 case '.':
1318 laststart = b;
1319 BUF_PUSH (anychar);
1320 break;
1323 case '[':
1325 boolean had_char_class = false;
1327 if (p == pend) return REG_EBRACK;
1329 /* Ensure that we have enough space to push a charset: the
1330 opcode, the length count, and the bitset; 34 bytes in all. */
1331 GET_BUFFER_SPACE (34);
1333 laststart = b;
1335 /* We test `*p == '^' twice, instead of using an if
1336 statement, so we only need one BUF_PUSH. */
1337 BUF_PUSH (*p == '^' ? charset_not : charset);
1338 if (*p == '^')
1339 p++;
1341 /* Remember the first position in the bracket expression. */
1342 p1 = p;
1344 /* Push the number of bytes in the bitmap. */
1345 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1347 /* Clear the whole map. */
1348 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1350 /* charset_not matches newline according to a syntax bit. */
1351 if ((re_opcode_t) b[-2] == charset_not
1352 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1353 SET_LIST_BIT ('\n');
1355 /* Read in characters and ranges, setting map bits. */
1356 for (;;)
1358 if (p == pend) return REG_EBRACK;
1360 PATFETCH (c);
1362 /* \ might escape characters inside [...] and [^...]. */
1363 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1365 if (p == pend) return REG_EESCAPE;
1367 PATFETCH (c1);
1368 SET_LIST_BIT (c1);
1369 continue;
1372 /* Could be the end of the bracket expression. If it's
1373 not (i.e., when the bracket expression is `[]' so
1374 far), the ']' character bit gets set way below. */
1375 if (c == ']' && p != p1 + 1)
1376 break;
1378 /* Look ahead to see if it's a range when the last thing
1379 was a character class. */
1380 if (had_char_class && c == '-' && *p != ']')
1381 return REG_ERANGE;
1383 /* Look ahead to see if it's a range when the last thing
1384 was a character: if this is a hyphen not at the
1385 beginning or the end of a list, then it's the range
1386 operator. */
1387 if (c == '-'
1388 && !(p - 2 >= pattern && p[-2] == '[')
1389 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1390 && *p != ']')
1392 reg_errcode_t ret
1393 = compile_range (&p, pend, translate, syntax, b);
1394 if (ret != REG_NOERROR) return ret;
1397 else if (p[0] == '-' && p[1] != ']')
1398 { /* This handles ranges made up of characters only. */
1399 reg_errcode_t ret;
1401 /* Move past the `-'. */
1402 PATFETCH (c1);
1404 ret = compile_range (&p, pend, translate, syntax, b);
1405 if (ret != REG_NOERROR) return ret;
1408 /* See if we're at the beginning of a possible character
1409 class. */
1411 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
1412 { /* Leave room for the null. */
1413 char str[CHAR_CLASS_MAX_LENGTH + 1];
1415 PATFETCH (c);
1416 c1 = 0;
1418 /* If pattern is `[[:'. */
1419 if (p == pend) return REG_EBRACK;
1421 for (;;)
1423 PATFETCH (c);
1424 if (c == ':' || c == ']' || p == pend
1425 || c1 == CHAR_CLASS_MAX_LENGTH)
1426 break;
1427 str[c1++] = c;
1429 str[c1] = '\0';
1431 /* If isn't a word bracketed by `[:' and:`]':
1432 undo the ending character, the letters, and leave
1433 the leading `:' and `[' (but set bits for them). */
1434 if (c == ':' && *p == ']')
1436 int ch;
1437 boolean is_alnum = STREQ (str, "alnum");
1438 boolean is_alpha = STREQ (str, "alpha");
1439 boolean is_blank = STREQ (str, "blank");
1440 boolean is_cntrl = STREQ (str, "cntrl");
1441 boolean is_digit = STREQ (str, "digit");
1442 boolean is_graph = STREQ (str, "graph");
1443 boolean is_lower = STREQ (str, "lower");
1444 boolean is_print = STREQ (str, "print");
1445 boolean is_punct = STREQ (str, "punct");
1446 boolean is_space = STREQ (str, "space");
1447 boolean is_upper = STREQ (str, "upper");
1448 boolean is_xdigit = STREQ (str, "xdigit");
1450 if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
1452 /* Throw away the ] at the end of the character
1453 class. */
1454 PATFETCH (c);
1456 if (p == pend) return REG_EBRACK;
1458 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
1460 if ( (is_alnum && ISALNUM (ch))
1461 || (is_alpha && ISALPHA (ch))
1462 || (is_blank && ISBLANK (ch))
1463 || (is_cntrl && ISCNTRL (ch))
1464 || (is_digit && ISDIGIT (ch))
1465 || (is_graph && ISGRAPH (ch))
1466 || (is_lower && ISLOWER (ch))
1467 || (is_print && ISPRINT (ch))
1468 || (is_punct && ISPUNCT (ch))
1469 || (is_space && ISSPACE (ch))
1470 || (is_upper && ISUPPER (ch))
1471 || (is_xdigit && ISXDIGIT (ch)))
1472 SET_LIST_BIT (ch);
1474 had_char_class = true;
1476 else
1478 c1++;
1479 while (c1--)
1480 PATUNFETCH;
1481 SET_LIST_BIT ('[');
1482 SET_LIST_BIT (':');
1483 had_char_class = false;
1486 else
1488 had_char_class = false;
1489 SET_LIST_BIT (c);
1493 /* Discard any (non)matching list bytes that are all 0 at the
1494 end of the map. Decrease the map-length byte too. */
1495 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
1496 b[-1]--;
1497 b += b[-1];
1499 break;
1502 case '(':
1503 if (syntax & RE_NO_BK_PARENS)
1504 goto handle_open;
1505 else
1506 goto normal_char;
1509 case ')':
1510 if (syntax & RE_NO_BK_PARENS)
1511 goto handle_close;
1512 else
1513 goto normal_char;
1516 case '\n':
1517 if (syntax & RE_NEWLINE_ALT)
1518 goto handle_alt;
1519 else
1520 goto normal_char;
1523 case '|':
1524 if (syntax & RE_NO_BK_VBAR)
1525 goto handle_alt;
1526 else
1527 goto normal_char;
1530 case '{':
1531 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1532 goto handle_interval;
1533 else
1534 goto normal_char;
1537 case '\\':
1538 if (p == pend) return REG_EESCAPE;
1540 /* Do not translate the character after the \, so that we can
1541 distinguish, e.g., \B from \b, even if we normally would
1542 translate, e.g., B to b. */
1543 PATFETCH_RAW (c);
1545 switch (c)
1547 case '(':
1548 if (syntax & RE_NO_BK_PARENS)
1549 goto normal_backslash;
1551 handle_open:
1552 bufp->re_nsub++;
1553 regnum++;
1555 if (COMPILE_STACK_FULL)
1557 RETALLOC (compile_stack.stack, compile_stack.size << 1,
1558 compile_stack_elt_t);
1559 if (compile_stack.stack == NULL) return REG_ESPACE;
1561 compile_stack.size <<= 1;
1564 /* These are the values to restore when we hit end of this
1565 group. They are all relative offsets, so that if the
1566 whole pattern moves because of realloc, they will still
1567 be valid. */
1568 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
1569 COMPILE_STACK_TOP.fixup_alt_jump
1570 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
1571 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
1572 COMPILE_STACK_TOP.regnum = regnum;
1574 /* We will eventually replace the 0 with the number of
1575 groups inner to this one. But do not push a
1576 start_memory for groups beyond the last one we can
1577 represent in the compiled pattern. */
1578 if (regnum <= MAX_REGNUM)
1580 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
1581 BUF_PUSH_3 (start_memory, regnum, 0);
1584 compile_stack.avail++;
1586 fixup_alt_jump = 0;
1587 laststart = 0;
1588 begalt = b;
1589 /* If we've reached MAX_REGNUM groups, then this open
1590 won't actually generate any code, so we'll have to
1591 clear pending_exact explicitly. */
1592 pending_exact = 0;
1593 break;
1596 case ')':
1597 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
1599 if (COMPILE_STACK_EMPTY)
1600 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1601 goto normal_backslash;
1602 else
1603 return REG_ERPAREN;
1605 handle_close:
1606 if (fixup_alt_jump)
1607 { /* Push a dummy failure point at the end of the
1608 alternative for a possible future
1609 `pop_failure_jump' to pop. See comments at
1610 `push_dummy_failure' in `re_match_2'. */
1611 BUF_PUSH (push_dummy_failure);
1613 /* We allocated space for this jump when we assigned
1614 to `fixup_alt_jump', in the `handle_alt' case below. */
1615 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
1618 /* See similar code for backslashed left paren above. */
1619 if (COMPILE_STACK_EMPTY)
1620 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1621 goto normal_char;
1622 else
1623 return REG_ERPAREN;
1625 /* Since we just checked for an empty stack above, this
1626 ``can't happen''. */
1627 assert (compile_stack.avail != 0);
1629 /* We don't just want to restore into `regnum', because
1630 later groups should continue to be numbered higher,
1631 as in `(ab)c(de)' -- the second group is #2. */
1632 regnum_t this_group_regnum;
1634 compile_stack.avail--;
1635 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
1636 fixup_alt_jump
1637 = COMPILE_STACK_TOP.fixup_alt_jump
1638 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
1639 : 0;
1640 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
1641 this_group_regnum = COMPILE_STACK_TOP.regnum;
1642 /* If we've reached MAX_REGNUM groups, then this open
1643 won't actually generate any code, so we'll have to
1644 clear pending_exact explicitly. */
1645 pending_exact = 0;
1647 /* We're at the end of the group, so now we know how many
1648 groups were inside this one. */
1649 if (this_group_regnum <= MAX_REGNUM)
1651 unsigned char *inner_group_loc
1652 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
1654 *inner_group_loc = regnum - this_group_regnum;
1655 BUF_PUSH_3 (stop_memory, this_group_regnum,
1656 regnum - this_group_regnum);
1659 break;
1662 case '|': /* `\|'. */
1663 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
1664 goto normal_backslash;
1665 handle_alt:
1666 if (syntax & RE_LIMITED_OPS)
1667 goto normal_char;
1669 /* Insert before the previous alternative a jump which
1670 jumps to this alternative if the former fails. */
1671 GET_BUFFER_SPACE (3);
1672 INSERT_JUMP (on_failure_jump, begalt, b + 6);
1673 pending_exact = 0;
1674 b += 3;
1676 /* The alternative before this one has a jump after it
1677 which gets executed if it gets matched. Adjust that
1678 jump so it will jump to this alternative's analogous
1679 jump (put in below, which in turn will jump to the next
1680 (if any) alternative's such jump, etc.). The last such
1681 jump jumps to the correct final destination. A picture:
1682 _____ _____
1683 | | | |
1684 | v | v
1685 a | b | c
1687 If we are at `b', then fixup_alt_jump right now points to a
1688 three-byte space after `a'. We'll put in the jump, set
1689 fixup_alt_jump to right after `b', and leave behind three
1690 bytes which we'll fill in when we get to after `c'. */
1692 if (fixup_alt_jump)
1693 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
1695 /* Mark and leave space for a jump after this alternative,
1696 to be filled in later either by next alternative or
1697 when know we're at the end of a series of alternatives. */
1698 fixup_alt_jump = b;
1699 GET_BUFFER_SPACE (3);
1700 b += 3;
1702 laststart = 0;
1703 begalt = b;
1704 break;
1707 case '{':
1708 /* If \{ is a literal. */
1709 if (!(syntax & RE_INTERVALS)
1710 /* If we're at `\{' and it's not the open-interval
1711 operator. */
1712 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
1713 || (p - 2 == pattern && p == pend))
1714 goto normal_backslash;
1716 handle_interval:
1718 /* If got here, then the syntax allows intervals. */
1720 /* At least (most) this many matches must be made. */
1721 int lower_bound = -1, upper_bound = -1;
1723 beg_interval = p - 1;
1725 if (p == pend)
1727 if (syntax & RE_NO_BK_BRACES)
1728 goto unfetch_interval;
1729 else
1730 return REG_EBRACE;
1733 GET_UNSIGNED_NUMBER (lower_bound);
1735 if (c == ',')
1737 GET_UNSIGNED_NUMBER (upper_bound);
1738 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
1740 else
1741 /* Interval such as `{1}' => match exactly once. */
1742 upper_bound = lower_bound;
1744 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
1745 || lower_bound > upper_bound)
1747 if (syntax & RE_NO_BK_BRACES)
1748 goto unfetch_interval;
1749 else
1750 return REG_BADBR;
1753 if (!(syntax & RE_NO_BK_BRACES))
1755 if (c != '\\') return REG_EBRACE;
1757 PATFETCH (c);
1760 if (c != '}')
1762 if (syntax & RE_NO_BK_BRACES)
1763 goto unfetch_interval;
1764 else
1765 return REG_BADBR;
1768 /* We just parsed a valid interval. */
1770 /* If it's invalid to have no preceding re. */
1771 if (!laststart)
1773 if (syntax & RE_CONTEXT_INVALID_OPS)
1774 return REG_BADRPT;
1775 else if (syntax & RE_CONTEXT_INDEP_OPS)
1776 laststart = b;
1777 else
1778 goto unfetch_interval;
1781 /* If the upper bound is zero, don't want to succeed at
1782 all; jump from `laststart' to `b + 3', which will be
1783 the end of the buffer after we insert the jump. */
1784 if (upper_bound == 0)
1786 GET_BUFFER_SPACE (3);
1787 INSERT_JUMP (jump, laststart, b + 3);
1788 b += 3;
1791 /* Otherwise, we have a nontrivial interval. When
1792 we're all done, the pattern will look like:
1793 set_number_at <jump count> <upper bound>
1794 set_number_at <succeed_n count> <lower bound>
1795 succeed_n <after jump addr> <succed_n count>
1796 <body of loop>
1797 jump_n <succeed_n addr> <jump count>
1798 (The upper bound and `jump_n' are omitted if
1799 `upper_bound' is 1, though.) */
1800 else
1801 { /* If the upper bound is > 1, we need to insert
1802 more at the end of the loop. */
1803 unsigned nbytes = 10 + (upper_bound > 1) * 10;
1805 GET_BUFFER_SPACE (nbytes);
1807 /* Initialize lower bound of the `succeed_n', even
1808 though it will be set during matching by its
1809 attendant `set_number_at' (inserted next),
1810 because `re_compile_fastmap' needs to know.
1811 Jump to the `jump_n' we might insert below. */
1812 INSERT_JUMP2 (succeed_n, laststart,
1813 b + 5 + (upper_bound > 1) * 5,
1814 lower_bound);
1815 b += 5;
1817 /* Code to initialize the lower bound. Insert
1818 before the `succeed_n'. The `5' is the last two
1819 bytes of this `set_number_at', plus 3 bytes of
1820 the following `succeed_n'. */
1821 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
1822 b += 5;
1824 if (upper_bound > 1)
1825 { /* More than one repetition is allowed, so
1826 append a backward jump to the `succeed_n'
1827 that starts this interval.
1829 When we've reached this during matching,
1830 we'll have matched the interval once, so
1831 jump back only `upper_bound - 1' times. */
1832 STORE_JUMP2 (jump_n, b, laststart + 5,
1833 upper_bound - 1);
1834 b += 5;
1836 /* The location we want to set is the second
1837 parameter of the `jump_n'; that is `b-2' as
1838 an absolute address. `laststart' will be
1839 the `set_number_at' we're about to insert;
1840 `laststart+3' the number to set, the source
1841 for the relative address. But we are
1842 inserting into the middle of the pattern --
1843 so everything is getting moved up by 5.
1844 Conclusion: (b - 2) - (laststart + 3) + 5,
1845 i.e., b - laststart.
1847 We insert this at the beginning of the loop
1848 so that if we fail during matching, we'll
1849 reinitialize the bounds. */
1850 insert_op2 (set_number_at, laststart, b - laststart,
1851 upper_bound - 1, b);
1852 b += 5;
1855 pending_exact = 0;
1856 beg_interval = NULL;
1858 break;
1860 unfetch_interval:
1861 /* If an invalid interval, match the characters as literals. */
1862 assert (beg_interval);
1863 p = beg_interval;
1864 beg_interval = NULL;
1866 /* normal_char and normal_backslash need `c'. */
1867 PATFETCH (c);
1869 if (!(syntax & RE_NO_BK_BRACES))
1871 if (p > pattern && p[-1] == '\\')
1872 goto normal_backslash;
1874 goto normal_char;
1876 #ifdef emacs
1877 /* There is no way to specify the before_dot and after_dot
1878 operators. rms says this is ok. --karl */
1879 case '=':
1880 BUF_PUSH (at_dot);
1881 break;
1883 case 's':
1884 laststart = b;
1885 PATFETCH (c);
1886 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
1887 break;
1889 case 'S':
1890 laststart = b;
1891 PATFETCH (c);
1892 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
1893 break;
1894 #endif /* emacs */
1897 case 'w':
1898 laststart = b;
1899 BUF_PUSH (wordchar);
1900 break;
1903 case 'W':
1904 laststart = b;
1905 BUF_PUSH (notwordchar);
1906 break;
1909 case '<':
1910 BUF_PUSH (wordbeg);
1911 break;
1913 case '>':
1914 BUF_PUSH (wordend);
1915 break;
1917 case 'b':
1918 BUF_PUSH (wordbound);
1919 break;
1921 case 'B':
1922 BUF_PUSH (notwordbound);
1923 break;
1925 case '`':
1926 BUF_PUSH (begbuf);
1927 break;
1929 case '\'':
1930 BUF_PUSH (endbuf);
1931 break;
1933 case '1': case '2': case '3': case '4': case '5':
1934 case '6': case '7': case '8': case '9':
1935 if (syntax & RE_NO_BK_REFS)
1936 goto normal_char;
1938 c1 = c - '0';
1940 if (c1 > regnum)
1941 return REG_ESUBREG;
1943 /* Can't back reference to a subexpression if inside of it. */
1944 if (group_in_compile_stack (compile_stack, c1))
1945 goto normal_char;
1947 laststart = b;
1948 BUF_PUSH_2 (duplicate, c1);
1949 break;
1952 case '+':
1953 case '?':
1954 if (syntax & RE_BK_PLUS_QM)
1955 goto handle_plus;
1956 else
1957 goto normal_backslash;
1959 default:
1960 normal_backslash:
1961 /* You might think it would be useful for \ to mean
1962 not to translate; but if we don't translate it
1963 it will never match anything. */
1964 c = TRANSLATE (c);
1965 goto normal_char;
1967 break;
1970 default:
1971 /* Expects the character in `c'. */
1972 normal_char:
1973 /* If no exactn currently being built. */
1974 if (!pending_exact
1976 /* If last exactn not at current position. */
1977 || pending_exact + *pending_exact + 1 != b
1979 /* We have only one byte following the exactn for the count. */
1980 || *pending_exact == (1 << BYTEWIDTH) - 1
1982 /* If followed by a repetition operator. */
1983 || *p == '*' || *p == '^'
1984 || ((syntax & RE_BK_PLUS_QM)
1985 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
1986 : (*p == '+' || *p == '?'))
1987 || ((syntax & RE_INTERVALS)
1988 && ((syntax & RE_NO_BK_BRACES)
1989 ? *p == '{'
1990 : (p[0] == '\\' && p[1] == '{'))))
1992 /* Start building a new exactn. */
1994 laststart = b;
1996 BUF_PUSH_2 (exactn, 0);
1997 pending_exact = b - 1;
2000 BUF_PUSH (c);
2001 (*pending_exact)++;
2002 break;
2003 } /* switch (c) */
2004 } /* while p != pend */
2007 /* Through the pattern now. */
2009 if (fixup_alt_jump)
2010 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2012 if (!COMPILE_STACK_EMPTY)
2013 return REG_EPAREN;
2015 free (compile_stack.stack);
2017 /* We have succeeded; set the length of the buffer. */
2018 bufp->used = b - bufp->buffer;
2020 #ifdef DEBUG
2021 if (debug)
2023 DEBUG_PRINT1 ("\nCompiled pattern: ");
2024 print_compiled_pattern (bufp);
2026 #endif /* DEBUG */
2028 return REG_NOERROR;
2029 } /* regex_compile */
2031 /* Subroutines for `regex_compile'. */
2033 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2035 static void
2036 store_op1 (op, loc, arg)
2037 re_opcode_t op;
2038 unsigned char *loc;
2039 int arg;
2041 *loc = (unsigned char) op;
2042 STORE_NUMBER (loc + 1, arg);
2046 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2048 static void
2049 store_op2 (op, loc, arg1, arg2)
2050 re_opcode_t op;
2051 unsigned char *loc;
2052 int arg1, arg2;
2054 *loc = (unsigned char) op;
2055 STORE_NUMBER (loc + 1, arg1);
2056 STORE_NUMBER (loc + 3, arg2);
2060 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2061 for OP followed by two-byte integer parameter ARG. */
2063 static void
2064 insert_op1 (op, loc, arg, end)
2065 re_opcode_t op;
2066 unsigned char *loc;
2067 int arg;
2068 unsigned char *end;
2070 register unsigned char *pfrom = end;
2071 register unsigned char *pto = end + 3;
2073 while (pfrom != loc)
2074 *--pto = *--pfrom;
2076 store_op1 (op, loc, arg);
2080 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2082 static void
2083 insert_op2 (op, loc, arg1, arg2, end)
2084 re_opcode_t op;
2085 unsigned char *loc;
2086 int arg1, arg2;
2087 unsigned char *end;
2089 register unsigned char *pfrom = end;
2090 register unsigned char *pto = end + 5;
2092 while (pfrom != loc)
2093 *--pto = *--pfrom;
2095 store_op2 (op, loc, arg1, arg2);
2099 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2100 after an alternative or a begin-subexpression. We assume there is at
2101 least one character before the ^. */
2103 static boolean
2104 at_begline_loc_p (pattern, p, syntax)
2105 const char *pattern, *p;
2106 reg_syntax_t syntax;
2108 const char *prev = p - 2;
2109 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2111 return
2112 /* After a subexpression? */
2113 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2114 /* After an alternative? */
2115 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2119 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2120 at least one character after the $, i.e., `P < PEND'. */
2122 static boolean
2123 at_endline_loc_p (p, pend, syntax)
2124 const char *p, *pend;
2125 int syntax;
2127 const char *next = p;
2128 boolean next_backslash = *next == '\\';
2129 const char *next_next = p + 1 < pend ? p + 1 : NULL;
2131 return
2132 /* Before a subexpression? */
2133 (syntax & RE_NO_BK_PARENS ? *next == ')'
2134 : next_backslash && next_next && *next_next == ')')
2135 /* Before an alternative? */
2136 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2137 : next_backslash && next_next && *next_next == '|');
2141 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2142 false if it's not. */
2144 static boolean
2145 group_in_compile_stack (compile_stack, regnum)
2146 compile_stack_type compile_stack;
2147 regnum_t regnum;
2149 int this_element;
2151 for (this_element = compile_stack.avail - 1;
2152 this_element >= 0;
2153 this_element--)
2154 if (compile_stack.stack[this_element].regnum == regnum)
2155 return true;
2157 return false;
2161 /* Read the ending character of a range (in a bracket expression) from the
2162 uncompiled pattern *P_PTR (which ends at PEND). We assume the
2163 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2164 Then we set the translation of all bits between the starting and
2165 ending characters (inclusive) in the compiled pattern B.
2167 Return an error code.
2169 We use these short variable names so we can use the same macros as
2170 `regex_compile' itself. */
2172 static reg_errcode_t
2173 compile_range (p_ptr, pend, translate, syntax, b)
2174 const char **p_ptr, *pend;
2175 char *translate;
2176 reg_syntax_t syntax;
2177 unsigned char *b;
2179 unsigned this_char;
2181 const char *p = *p_ptr;
2182 int range_start, range_end;
2184 if (p == pend)
2185 return REG_ERANGE;
2187 /* Even though the pattern is a signed `char *', we need to fetch
2188 with unsigned char *'s; if the high bit of the pattern character
2189 is set, the range endpoints will be negative if we fetch using a
2190 signed char *.
2192 We also want to fetch the endpoints without translating them; the
2193 appropriate translation is done in the bit-setting loop below. */
2194 range_start = ((unsigned char *) p)[-2];
2195 range_end = ((unsigned char *) p)[0];
2197 /* Have to increment the pointer into the pattern string, so the
2198 caller isn't still at the ending character. */
2199 (*p_ptr)++;
2201 /* If the start is after the end, the range is empty. */
2202 if (range_start > range_end)
2203 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2205 /* Here we see why `this_char' has to be larger than an `unsigned
2206 char' -- the range is inclusive, so if `range_end' == 0xff
2207 (assuming 8-bit characters), we would otherwise go into an infinite
2208 loop, since all characters <= 0xff. */
2209 for (this_char = range_start; this_char <= range_end; this_char++)
2211 SET_LIST_BIT (TRANSLATE (this_char));
2214 return REG_NOERROR;
2217 /* Failure stack declarations and macros; both re_compile_fastmap and
2218 re_match_2 use a failure stack. These have to be macros because of
2219 REGEX_ALLOCATE. */
2222 /* Number of failure points for which to initially allocate space
2223 when matching. If this number is exceeded, we allocate more
2224 space, so it is not a hard limit. */
2225 #ifndef INIT_FAILURE_ALLOC
2226 #define INIT_FAILURE_ALLOC 5
2227 #endif
2229 /* Roughly the maximum number of failure points on the stack. Would be
2230 exactly that if always used MAX_FAILURE_SPACE each time we failed.
2231 This is a variable only so users of regex can assign to it; we never
2232 change it ourselves. */
2233 int re_max_failures = 2000;
2235 typedef const unsigned char *fail_stack_elt_t;
2237 typedef struct
2239 fail_stack_elt_t *stack;
2240 unsigned size;
2241 unsigned avail; /* Offset of next open position. */
2242 } fail_stack_type;
2244 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
2245 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2246 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
2247 #define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])
2250 /* Initialize `fail_stack'. Do `return -2' if the alloc fails. */
2252 #define INIT_FAIL_STACK() \
2253 do { \
2254 fail_stack.stack = (fail_stack_elt_t *) \
2255 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
2257 if (fail_stack.stack == NULL) \
2258 return -2; \
2260 fail_stack.size = INIT_FAILURE_ALLOC; \
2261 fail_stack.avail = 0; \
2262 } while (0)
2265 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
2267 Return 1 if succeeds, and 0 if either ran out of memory
2268 allocating space for it or it was already too large.
2270 REGEX_REALLOCATE requires `destination' be declared. */
2272 #define DOUBLE_FAIL_STACK(fail_stack) \
2273 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
2274 ? 0 \
2275 : ((fail_stack).stack = (fail_stack_elt_t *) \
2276 REGEX_REALLOCATE ((fail_stack).stack, \
2277 (fail_stack).size * sizeof (fail_stack_elt_t), \
2278 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
2280 (fail_stack).stack == NULL \
2281 ? 0 \
2282 : ((fail_stack).size <<= 1, \
2283 1)))
2286 /* Push PATTERN_OP on FAIL_STACK.
2288 Return 1 if was able to do so and 0 if ran out of memory allocating
2289 space to do so. */
2290 #define PUSH_PATTERN_OP(pattern_op, fail_stack) \
2291 ((FAIL_STACK_FULL () \
2292 && !DOUBLE_FAIL_STACK (fail_stack)) \
2293 ? 0 \
2294 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \
2297 /* This pushes an item onto the failure stack. Must be a four-byte
2298 value. Assumes the variable `fail_stack'. Probably should only
2299 be called from within `PUSH_FAILURE_POINT'. */
2300 #define PUSH_FAILURE_ITEM(item) \
2301 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2303 /* The complement operation. Assumes `fail_stack' is nonempty. */
2304 #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2306 /* Used to omit pushing failure point id's when we're not debugging. */
2307 #ifdef DEBUG
2308 #define DEBUG_PUSH PUSH_FAILURE_ITEM
2309 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2310 #else
2311 #define DEBUG_PUSH(item)
2312 #define DEBUG_POP(item_addr)
2313 #endif
2316 /* Push the information about the state we will need
2317 if we ever fail back to it.
2319 Requires variables fail_stack, regstart, regend, reg_info, and
2320 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
2321 declared.
2323 Does `return FAILURE_CODE' if runs out of memory. */
2325 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
2326 do { \
2327 char *destination; \
2328 /* Must be int, so when we don't save any registers, the arithmetic \
2329 of 0 + -1 isn't done as unsigned. */ \
2330 int this_reg; \
2332 DEBUG_STATEMENT (failure_id++); \
2333 DEBUG_STATEMENT (nfailure_points_pushed++); \
2334 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
2335 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
2336 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
2338 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
2339 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
2341 /* Ensure we have enough space allocated for what we will push. */ \
2342 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
2344 if (!DOUBLE_FAIL_STACK (fail_stack)) \
2345 return failure_code; \
2347 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
2348 (fail_stack).size); \
2349 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2352 /* Push the info, starting with the registers. */ \
2353 DEBUG_PRINT1 ("\n"); \
2355 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
2356 this_reg++) \
2358 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
2359 DEBUG_STATEMENT (num_regs_pushed++); \
2361 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2362 PUSH_FAILURE_ITEM (regstart[this_reg]); \
2364 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2365 PUSH_FAILURE_ITEM (regend[this_reg]); \
2367 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
2368 DEBUG_PRINT2 (" match_null=%d", \
2369 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
2370 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
2371 DEBUG_PRINT2 (" matched_something=%d", \
2372 MATCHED_SOMETHING (reg_info[this_reg])); \
2373 DEBUG_PRINT2 (" ever_matched=%d", \
2374 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
2375 DEBUG_PRINT1 ("\n"); \
2376 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \
2379 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
2380 PUSH_FAILURE_ITEM (lowest_active_reg); \
2382 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
2383 PUSH_FAILURE_ITEM (highest_active_reg); \
2385 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
2386 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
2387 PUSH_FAILURE_ITEM (pattern_place); \
2389 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
2390 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
2391 size2); \
2392 DEBUG_PRINT1 ("'\n"); \
2393 PUSH_FAILURE_ITEM (string_place); \
2395 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
2396 DEBUG_PUSH (failure_id); \
2397 } while (0)
2399 /* This is the number of items that are pushed and popped on the stack
2400 for each register. */
2401 #define NUM_REG_ITEMS 3
2403 /* Individual items aside from the registers. */
2404 #ifdef DEBUG
2405 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
2406 #else
2407 #define NUM_NONREG_ITEMS 4
2408 #endif
2410 /* We push at most this many items on the stack. */
2411 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2413 /* We actually push this many items. */
2414 #define NUM_FAILURE_ITEMS \
2415 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
2416 + NUM_NONREG_ITEMS)
2418 /* How many items can still be added to the stack without overflowing it. */
2419 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2422 /* Pops what PUSH_FAIL_STACK pushes.
2424 We restore into the parameters, all of which should be lvalues:
2425 STR -- the saved data position.
2426 PAT -- the saved pattern position.
2427 LOW_REG, HIGH_REG -- the highest and lowest active registers.
2428 REGSTART, REGEND -- arrays of string positions.
2429 REG_INFO -- array of information about each subexpression.
2431 Also assumes the variables `fail_stack' and (if debugging), `bufp',
2432 `pend', `string1', `size1', `string2', and `size2'. */
2434 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2436 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
2437 int this_reg; \
2438 const unsigned char *string_temp; \
2440 assert (!FAIL_STACK_EMPTY ()); \
2442 /* Remove failure points and point to how many regs pushed. */ \
2443 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
2444 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
2445 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
2447 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
2449 DEBUG_POP (&failure_id); \
2450 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
2452 /* If the saved string location is NULL, it came from an \
2453 on_failure_keep_string_jump opcode, and we want to throw away the \
2454 saved NULL, thus retaining our current position in the string. */ \
2455 string_temp = POP_FAILURE_ITEM (); \
2456 if (string_temp != NULL) \
2457 str = (const char *) string_temp; \
2459 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
2460 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
2461 DEBUG_PRINT1 ("'\n"); \
2463 pat = (unsigned char *) POP_FAILURE_ITEM (); \
2464 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
2465 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
2467 /* Restore register info. */ \
2468 high_reg = (unsigned) POP_FAILURE_ITEM (); \
2469 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
2471 low_reg = (unsigned) POP_FAILURE_ITEM (); \
2472 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
2474 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
2476 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
2478 reg_info[this_reg].word = POP_FAILURE_ITEM (); \
2479 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
2481 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2482 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2484 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2485 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2488 DEBUG_STATEMENT (nfailure_points_popped++); \
2489 } /* POP_FAILURE_POINT */
2491 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2492 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2493 characters can start a string that matches the pattern. This fastmap
2494 is used by re_search to skip quickly over impossible starting points.
2496 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2497 area as BUFP->fastmap.
2499 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2500 the pattern buffer.
2502 Returns 0 if we succeed, -2 if an internal error. */
2505 re_compile_fastmap (bufp)
2506 struct re_pattern_buffer *bufp;
2508 int j, k;
2509 fail_stack_type fail_stack;
2510 #ifndef REGEX_MALLOC
2511 char *destination;
2512 #endif
2513 /* We don't push any register information onto the failure stack. */
2514 unsigned num_regs = 0;
2516 register char *fastmap = bufp->fastmap;
2517 unsigned char *pattern = bufp->buffer;
2518 unsigned long size = bufp->used;
2519 const unsigned char *p = pattern;
2520 register unsigned char *pend = pattern + size;
2522 /* Assume that each path through the pattern can be null until
2523 proven otherwise. We set this false at the bottom of switch
2524 statement, to which we get only if a particular path doesn't
2525 match the empty string. */
2526 boolean path_can_be_null = true;
2528 /* We aren't doing a `succeed_n' to begin with. */
2529 boolean succeed_n_p = false;
2531 assert (fastmap != NULL && p != NULL);
2533 INIT_FAIL_STACK ();
2534 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
2535 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2536 bufp->can_be_null = 0;
2538 while (p != pend || !FAIL_STACK_EMPTY ())
2540 if (p == pend)
2542 bufp->can_be_null |= path_can_be_null;
2544 /* Reset for next path. */
2545 path_can_be_null = true;
2547 p = fail_stack.stack[--fail_stack.avail];
2550 /* We should never be about to go beyond the end of the pattern. */
2551 assert (p < pend);
2553 #ifdef SWITCH_ENUM_BUG
2554 switch ((int) ((re_opcode_t) *p++))
2555 #else
2556 switch ((re_opcode_t) *p++)
2557 #endif
2560 /* I guess the idea here is to simply not bother with a fastmap
2561 if a backreference is used, since it's too hard to figure out
2562 the fastmap for the corresponding group. Setting
2563 `can_be_null' stops `re_search_2' from using the fastmap, so
2564 that is all we do. */
2565 case duplicate:
2566 bufp->can_be_null = 1;
2567 return 0;
2570 /* Following are the cases which match a character. These end
2571 with `break'. */
2573 case exactn:
2574 fastmap[p[1]] = 1;
2575 break;
2578 case charset:
2579 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2580 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2581 fastmap[j] = 1;
2582 break;
2585 case charset_not:
2586 /* Chars beyond end of map must be allowed. */
2587 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2588 fastmap[j] = 1;
2590 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2591 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2592 fastmap[j] = 1;
2593 break;
2596 case wordchar:
2597 for (j = 0; j < (1 << BYTEWIDTH); j++)
2598 if (SYNTAX (j) == Sword)
2599 fastmap[j] = 1;
2600 break;
2603 case notwordchar:
2604 for (j = 0; j < (1 << BYTEWIDTH); j++)
2605 if (SYNTAX (j) != Sword)
2606 fastmap[j] = 1;
2607 break;
2610 case anychar:
2611 /* `.' matches anything ... */
2612 for (j = 0; j < (1 << BYTEWIDTH); j++)
2613 fastmap[j] = 1;
2615 /* ... except perhaps newline. */
2616 if (!(bufp->syntax & RE_DOT_NEWLINE))
2617 fastmap['\n'] = 0;
2619 /* Return if we have already set `can_be_null'; if we have,
2620 then the fastmap is irrelevant. Something's wrong here. */
2621 else if (bufp->can_be_null)
2622 return 0;
2624 /* Otherwise, have to check alternative paths. */
2625 break;
2628 #ifdef emacs
2629 case syntaxspec:
2630 k = *p++;
2631 for (j = 0; j < (1 << BYTEWIDTH); j++)
2632 if (SYNTAX (j) == (enum syntaxcode) k)
2633 fastmap[j] = 1;
2634 break;
2637 case notsyntaxspec:
2638 k = *p++;
2639 for (j = 0; j < (1 << BYTEWIDTH); j++)
2640 if (SYNTAX (j) != (enum syntaxcode) k)
2641 fastmap[j] = 1;
2642 break;
2645 /* All cases after this match the empty string. These end with
2646 `continue'. */
2649 case before_dot:
2650 case at_dot:
2651 case after_dot:
2652 continue;
2653 #endif /* not emacs */
2656 case no_op:
2657 case begline:
2658 case endline:
2659 case begbuf:
2660 case endbuf:
2661 case wordbound:
2662 case notwordbound:
2663 case wordbeg:
2664 case wordend:
2665 case push_dummy_failure:
2666 continue;
2669 case jump_n:
2670 case pop_failure_jump:
2671 case maybe_pop_jump:
2672 case jump:
2673 case jump_past_alt:
2674 case dummy_failure_jump:
2675 EXTRACT_NUMBER_AND_INCR (j, p);
2676 p += j;
2677 if (j > 0)
2678 continue;
2680 /* Jump backward implies we just went through the body of a
2681 loop and matched nothing. Opcode jumped to should be
2682 `on_failure_jump' or `succeed_n'. Just treat it like an
2683 ordinary jump. For a * loop, it has pushed its failure
2684 point already; if so, discard that as redundant. */
2685 if ((re_opcode_t) *p != on_failure_jump
2686 && (re_opcode_t) *p != succeed_n)
2687 continue;
2689 p++;
2690 EXTRACT_NUMBER_AND_INCR (j, p);
2691 p += j;
2693 /* If what's on the stack is where we are now, pop it. */
2694 if (!FAIL_STACK_EMPTY ()
2695 && fail_stack.stack[fail_stack.avail - 1] == p)
2696 fail_stack.avail--;
2698 continue;
2701 case on_failure_jump:
2702 case on_failure_keep_string_jump:
2703 handle_on_failure_jump:
2704 EXTRACT_NUMBER_AND_INCR (j, p);
2706 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2707 end of the pattern. We don't want to push such a point,
2708 since when we restore it above, entering the switch will
2709 increment `p' past the end of the pattern. We don't need
2710 to push such a point since we obviously won't find any more
2711 fastmap entries beyond `pend'. Such a pattern can match
2712 the null string, though. */
2713 if (p + j < pend)
2715 if (!PUSH_PATTERN_OP (p + j, fail_stack))
2716 return -2;
2718 else
2719 bufp->can_be_null = 1;
2721 if (succeed_n_p)
2723 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
2724 succeed_n_p = false;
2727 continue;
2730 case succeed_n:
2731 /* Get to the number of times to succeed. */
2732 p += 2;
2734 /* Increment p past the n for when k != 0. */
2735 EXTRACT_NUMBER_AND_INCR (k, p);
2736 if (k == 0)
2738 p -= 4;
2739 succeed_n_p = true; /* Spaghetti code alert. */
2740 goto handle_on_failure_jump;
2742 continue;
2745 case set_number_at:
2746 p += 4;
2747 continue;
2750 case start_memory:
2751 case stop_memory:
2752 p += 2;
2753 continue;
2756 default:
2757 abort (); /* We have listed all the cases. */
2758 } /* switch *p++ */
2760 /* Getting here means we have found the possible starting
2761 characters for one path of the pattern -- and that the empty
2762 string does not match. We need not follow this path further.
2763 Instead, look at the next alternative (remembered on the
2764 stack), or quit if no more. The test at the top of the loop
2765 does these things. */
2766 path_can_be_null = false;
2767 p = pend;
2768 } /* while p */
2770 /* Set `can_be_null' for the last path (also the first path, if the
2771 pattern is empty). */
2772 bufp->can_be_null |= path_can_be_null;
2773 return 0;
2774 } /* re_compile_fastmap */
2776 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
2777 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
2778 this memory for recording register information. STARTS and ENDS
2779 must be allocated using the malloc library routine, and must each
2780 be at least NUM_REGS * sizeof (regoff_t) bytes long.
2782 If NUM_REGS == 0, then subsequent matches should allocate their own
2783 register data.
2785 Unless this function is called, the first search or match using
2786 PATTERN_BUFFER will allocate its own register data, without
2787 freeing the old data. */
2789 void
2790 re_set_registers (bufp, regs, num_regs, starts, ends)
2791 struct re_pattern_buffer *bufp;
2792 struct re_registers *regs;
2793 unsigned num_regs;
2794 regoff_t *starts, *ends;
2796 if (num_regs)
2798 bufp->regs_allocated = REGS_REALLOCATE;
2799 regs->num_regs = num_regs;
2800 regs->start = starts;
2801 regs->end = ends;
2803 else
2805 bufp->regs_allocated = REGS_UNALLOCATED;
2806 regs->num_regs = 0;
2807 regs->start = regs->end = (regoff_t) 0;
2811 /* Searching routines. */
2813 /* Like re_search_2, below, but only one string is specified, and
2814 doesn't let you say where to stop matching. */
2817 re_search (bufp, string, size, startpos, range, regs)
2818 struct re_pattern_buffer *bufp;
2819 const char *string;
2820 int size, startpos, range;
2821 struct re_registers *regs;
2823 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
2824 regs, size);
2828 /* Using the compiled pattern in BUFP->buffer, first tries to match the
2829 virtual concatenation of STRING1 and STRING2, starting first at index
2830 STARTPOS, then at STARTPOS + 1, and so on.
2832 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
2834 RANGE is how far to scan while trying to match. RANGE = 0 means try
2835 only at STARTPOS; in general, the last start tried is STARTPOS +
2836 RANGE.
2838 In REGS, return the indices of the virtual concatenation of STRING1
2839 and STRING2 that matched the entire BUFP->buffer and its contained
2840 subexpressions.
2842 Do not consider matching one past the index STOP in the virtual
2843 concatenation of STRING1 and STRING2.
2845 We return either the position in the strings at which the match was
2846 found, -1 if no match, or -2 if error (such as failure
2847 stack overflow). */
2850 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
2851 struct re_pattern_buffer *bufp;
2852 const char *string1, *string2;
2853 int size1, size2;
2854 int startpos;
2855 int range;
2856 struct re_registers *regs;
2857 int stop;
2859 int val;
2860 register char *fastmap = bufp->fastmap;
2861 register char *translate = bufp->translate;
2862 int total_size = size1 + size2;
2863 int endpos = startpos + range;
2865 /* Check for out-of-range STARTPOS. */
2866 if (startpos < 0 || startpos > total_size)
2867 return -1;
2869 /* Fix up RANGE if it might eventually take us outside
2870 the virtual concatenation of STRING1 and STRING2. */
2871 if (endpos < -1)
2872 range = -1 - startpos;
2873 else if (endpos > total_size)
2874 range = total_size - startpos;
2876 /* If the search isn't to be a backwards one, don't waste time in a
2877 search for a pattern that must be anchored. */
2878 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
2880 if (startpos > 0)
2881 return -1;
2882 else
2883 range = 1;
2886 /* Update the fastmap now if not correct already. */
2887 if (fastmap && !bufp->fastmap_accurate)
2888 if (re_compile_fastmap (bufp) == -2)
2889 return -2;
2891 /* Loop through the string, looking for a place to start matching. */
2892 for (;;)
2894 /* If a fastmap is supplied, skip quickly over characters that
2895 cannot be the start of a match. If the pattern can match the
2896 null string, however, we don't need to skip characters; we want
2897 the first null string. */
2898 if (fastmap && startpos < total_size && !bufp->can_be_null)
2900 if (range > 0) /* Searching forwards. */
2902 register const char *d;
2903 register int lim = 0;
2904 int irange = range;
2906 if (startpos < size1 && startpos + range >= size1)
2907 lim = range - (size1 - startpos);
2909 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
2911 /* Written out as an if-else to avoid testing `translate'
2912 inside the loop. */
2913 if (translate)
2914 while (range > lim
2915 && !fastmap[(unsigned char)
2916 translate[(unsigned char) *d++]])
2917 range--;
2918 else
2919 while (range > lim && !fastmap[(unsigned char) *d++])
2920 range--;
2922 startpos += irange - range;
2924 else /* Searching backwards. */
2926 register char c = (size1 == 0 || startpos >= size1
2927 ? string2[startpos - size1]
2928 : string1[startpos]);
2930 if (!fastmap[(unsigned char) TRANSLATE (c)])
2931 goto advance;
2935 /* If can't match the null string, and that's all we have left, fail. */
2936 if (range >= 0 && startpos == total_size && fastmap
2937 && !bufp->can_be_null)
2938 return -1;
2940 val = re_match_2 (bufp, string1, size1, string2, size2,
2941 startpos, regs, stop);
2942 if (val >= 0)
2943 return startpos;
2945 if (val == -2)
2946 return -2;
2948 advance:
2949 if (!range)
2950 break;
2951 else if (range > 0)
2953 range--;
2954 startpos++;
2956 else
2958 range++;
2959 startpos--;
2962 return -1;
2963 } /* re_search_2 */
2965 /* Declarations and macros for re_match_2. */
2967 static int bcmp_translate ();
2968 static boolean alt_match_null_string_p (),
2969 common_op_match_null_string_p (),
2970 group_match_null_string_p ();
2972 /* Structure for per-register (a.k.a. per-group) information.
2973 This must not be longer than one word, because we push this value
2974 onto the failure stack. Other register information, such as the
2975 starting and ending positions (which are addresses), and the list of
2976 inner groups (which is a bits list) are maintained in separate
2977 variables.
2979 We are making a (strictly speaking) nonportable assumption here: that
2980 the compiler will pack our bit fields into something that fits into
2981 the type of `word', i.e., is something that fits into one item on the
2982 failure stack. */
2983 typedef union
2985 fail_stack_elt_t word;
2986 struct
2988 /* This field is one if this group can match the empty string,
2989 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
2990 #define MATCH_NULL_UNSET_VALUE 3
2991 unsigned match_null_string_p : 2;
2992 unsigned is_active : 1;
2993 unsigned matched_something : 1;
2994 unsigned ever_matched_something : 1;
2995 } bits;
2996 } register_info_type;
2998 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
2999 #define IS_ACTIVE(R) ((R).bits.is_active)
3000 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
3001 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
3004 /* Call this when have matched a real character; it sets `matched' flags
3005 for the subexpressions which we are currently inside. Also records
3006 that those subexprs have matched. */
3007 #define SET_REGS_MATCHED() \
3008 do \
3010 unsigned r; \
3011 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
3013 MATCHED_SOMETHING (reg_info[r]) \
3014 = EVER_MATCHED_SOMETHING (reg_info[r]) \
3015 = 1; \
3018 while (0)
3021 /* This converts PTR, a pointer into one of the search strings `string1'
3022 and `string2' into an offset from the beginning of that string. */
3023 #define POINTER_TO_OFFSET(ptr) \
3024 (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
3026 /* Registers are set to a sentinel when they haven't yet matched. */
3027 #define REG_UNSET_VALUE ((char *) -1)
3028 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
3031 /* Macros for dealing with the split strings in re_match_2. */
3033 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3035 /* Call before fetching a character with *d. This switches over to
3036 string2 if necessary. */
3037 #define PREFETCH() \
3038 while (d == dend) \
3040 /* End of string2 => fail. */ \
3041 if (dend == end_match_2) \
3042 goto fail; \
3043 /* End of string1 => advance to string2. */ \
3044 d = string2; \
3045 dend = end_match_2; \
3049 /* Test if at very beginning or at very end of the virtual concatenation
3050 of `string1' and `string2'. If only one string, it's `string2'. */
3051 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3052 #define AT_STRINGS_END(d) ((d) == end2)
3055 /* Test if D points to a character which is word-constituent. We have
3056 two special cases to check for: if past the end of string1, look at
3057 the first character in string2; and if before the beginning of
3058 string2, look at the last character in string1. */
3059 #define WORDCHAR_P(d) \
3060 (SYNTAX ((d) == end1 ? *string2 \
3061 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3062 == Sword)
3064 /* Test if the character before D and the one at D differ with respect
3065 to being word-constituent. */
3066 #define AT_WORD_BOUNDARY(d) \
3067 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3068 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3071 /* Free everything we malloc. */
3072 #ifdef REGEX_MALLOC
3073 #define FREE_VAR(var) if (var) free (var); var = NULL
3074 #define FREE_VARIABLES() \
3075 do { \
3076 FREE_VAR (fail_stack.stack); \
3077 FREE_VAR (regstart); \
3078 FREE_VAR (regend); \
3079 FREE_VAR (old_regstart); \
3080 FREE_VAR (old_regend); \
3081 FREE_VAR (best_regstart); \
3082 FREE_VAR (best_regend); \
3083 FREE_VAR (reg_info); \
3084 FREE_VAR (reg_dummy); \
3085 FREE_VAR (reg_info_dummy); \
3086 } while (0)
3087 #else /* not REGEX_MALLOC */
3088 /* Some MIPS systems (at least) want this to free alloca'd storage. */
3089 #define FREE_VARIABLES() alloca (0)
3090 #endif /* not REGEX_MALLOC */
3093 /* These values must meet several constraints. They must not be valid
3094 register values; since we have a limit of 255 registers (because
3095 we use only one byte in the pattern for the register number), we can
3096 use numbers larger than 255. They must differ by 1, because of
3097 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3098 be larger than the value for the highest register, so we do not try
3099 to actually save any registers when none are active. */
3100 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3101 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3103 /* Matching routines. */
3105 #ifndef emacs /* Emacs never uses this. */
3106 /* re_match is like re_match_2 except it takes only a single string. */
3109 re_match (bufp, string, size, pos, regs)
3110 struct re_pattern_buffer *bufp;
3111 const char *string;
3112 int size, pos;
3113 struct re_registers *regs;
3115 return re_match_2 (bufp, NULL, 0, string, size, pos, regs, size);
3117 #endif /* not emacs */
3120 /* re_match_2 matches the compiled pattern in BUFP against the
3121 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3122 and SIZE2, respectively). We start matching at POS, and stop
3123 matching at STOP.
3125 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3126 store offsets for the substring each group matched in REGS. See the
3127 documentation for exactly how many groups we fill.
3129 We return -1 if no match, -2 if an internal error (such as the
3130 failure stack overflowing). Otherwise, we return the length of the
3131 matched substring. */
3134 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3135 struct re_pattern_buffer *bufp;
3136 const char *string1, *string2;
3137 int size1, size2;
3138 int pos;
3139 struct re_registers *regs;
3140 int stop;
3142 /* General temporaries. */
3143 int mcnt;
3144 unsigned char *p1;
3146 /* Just past the end of the corresponding string. */
3147 const char *end1, *end2;
3149 /* Pointers into string1 and string2, just past the last characters in
3150 each to consider matching. */
3151 const char *end_match_1, *end_match_2;
3153 /* Where we are in the data, and the end of the current string. */
3154 const char *d, *dend;
3156 /* Where we are in the pattern, and the end of the pattern. */
3157 unsigned char *p = bufp->buffer;
3158 register unsigned char *pend = p + bufp->used;
3160 /* We use this to map every character in the string. */
3161 char *translate = bufp->translate;
3163 /* Failure point stack. Each place that can handle a failure further
3164 down the line pushes a failure point on this stack. It consists of
3165 restart, regend, and reg_info for all registers corresponding to
3166 the subexpressions we're currently inside, plus the number of such
3167 registers, and, finally, two char *'s. The first char * is where
3168 to resume scanning the pattern; the second one is where to resume
3169 scanning the strings. If the latter is zero, the failure point is
3170 a ``dummy''; if a failure happens and the failure point is a dummy,
3171 it gets discarded and the next next one is tried. */
3172 fail_stack_type fail_stack;
3173 #ifdef DEBUG
3174 static unsigned failure_id = 0;
3175 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3176 #endif
3178 /* We fill all the registers internally, independent of what we
3179 return, for use in backreferences. The number here includes
3180 an element for register zero. */
3181 unsigned num_regs = bufp->re_nsub + 1;
3183 /* The currently active registers. */
3184 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3185 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3187 /* Information on the contents of registers. These are pointers into
3188 the input strings; they record just what was matched (on this
3189 attempt) by a subexpression part of the pattern, that is, the
3190 regnum-th regstart pointer points to where in the pattern we began
3191 matching and the regnum-th regend points to right after where we
3192 stopped matching the regnum-th subexpression. (The zeroth register
3193 keeps track of what the whole pattern matches.) */
3194 const char **regstart, **regend;
3196 /* If a group that's operated upon by a repetition operator fails to
3197 match anything, then the register for its start will need to be
3198 restored because it will have been set to wherever in the string we
3199 are when we last see its open-group operator. Similarly for a
3200 register's end. */
3201 const char **old_regstart, **old_regend;
3203 /* The is_active field of reg_info helps us keep track of which (possibly
3204 nested) subexpressions we are currently in. The matched_something
3205 field of reg_info[reg_num] helps us tell whether or not we have
3206 matched any of the pattern so far this time through the reg_num-th
3207 subexpression. These two fields get reset each time through any
3208 loop their register is in. */
3209 register_info_type *reg_info;
3211 /* The following record the register info as found in the above
3212 variables when we find a match better than any we've seen before.
3213 This happens as we backtrack through the failure points, which in
3214 turn happens only if we have not yet matched the entire string. */
3215 unsigned best_regs_set = false;
3216 const char **best_regstart, **best_regend;
3218 /* Logically, this is `best_regend[0]'. But we don't want to have to
3219 allocate space for that if we're not allocating space for anything
3220 else (see below). Also, we never need info about register 0 for
3221 any of the other register vectors, and it seems rather a kludge to
3222 treat `best_regend' differently than the rest. So we keep track of
3223 the end of the best match so far in a separate variable. We
3224 initialize this to NULL so that when we backtrack the first time
3225 and need to test it, it's not garbage. */
3226 const char *match_end = NULL;
3228 /* Used when we pop values we don't care about. */
3229 const char **reg_dummy;
3230 register_info_type *reg_info_dummy;
3232 #ifdef DEBUG
3233 /* Counts the total number of registers pushed. */
3234 unsigned num_regs_pushed = 0;
3235 #endif
3237 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3239 INIT_FAIL_STACK ();
3241 /* Do not bother to initialize all the register variables if there are
3242 no groups in the pattern, as it takes a fair amount of time. If
3243 there are groups, we include space for register 0 (the whole
3244 pattern), even though we never use it, since it simplifies the
3245 array indexing. We should fix this. */
3246 if (bufp->re_nsub)
3248 regstart = REGEX_TALLOC (num_regs, const char *);
3249 regend = REGEX_TALLOC (num_regs, const char *);
3250 old_regstart = REGEX_TALLOC (num_regs, const char *);
3251 old_regend = REGEX_TALLOC (num_regs, const char *);
3252 best_regstart = REGEX_TALLOC (num_regs, const char *);
3253 best_regend = REGEX_TALLOC (num_regs, const char *);
3254 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3255 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3256 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3258 if (!(regstart && regend && old_regstart && old_regend && reg_info
3259 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3261 FREE_VARIABLES ();
3262 return -2;
3265 #ifdef REGEX_MALLOC
3266 else
3268 /* We must initialize all our variables to NULL, so that
3269 `FREE_VARIABLES' doesn't try to free them. */
3270 regstart = regend = old_regstart = old_regend = best_regstart
3271 = best_regend = reg_dummy = NULL;
3272 reg_info = reg_info_dummy = (register_info_type *) NULL;
3274 #endif /* REGEX_MALLOC */
3276 /* The starting position is bogus. */
3277 if (pos < 0 || pos > size1 + size2)
3279 FREE_VARIABLES ();
3280 return -1;
3283 /* Initialize subexpression text positions to -1 to mark ones that no
3284 start_memory/stop_memory has been seen for. Also initialize the
3285 register information struct. */
3286 for (mcnt = 1; mcnt < num_regs; mcnt++)
3288 regstart[mcnt] = regend[mcnt]
3289 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3291 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3292 IS_ACTIVE (reg_info[mcnt]) = 0;
3293 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3294 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3297 /* We move `string1' into `string2' if the latter's empty -- but not if
3298 `string1' is null. */
3299 if (size2 == 0 && string1 != NULL)
3301 string2 = string1;
3302 size2 = size1;
3303 string1 = 0;
3304 size1 = 0;
3306 end1 = string1 + size1;
3307 end2 = string2 + size2;
3309 /* Compute where to stop matching, within the two strings. */
3310 if (stop <= size1)
3312 end_match_1 = string1 + stop;
3313 end_match_2 = string2;
3315 else
3317 end_match_1 = end1;
3318 end_match_2 = string2 + stop - size1;
3321 /* `p' scans through the pattern as `d' scans through the data.
3322 `dend' is the end of the input string that `d' points within. `d'
3323 is advanced into the following input string whenever necessary, but
3324 this happens before fetching; therefore, at the beginning of the
3325 loop, `d' can be pointing at the end of a string, but it cannot
3326 equal `string2'. */
3327 if (size1 > 0 && pos <= size1)
3329 d = string1 + pos;
3330 dend = end_match_1;
3332 else
3334 d = string2 + pos - size1;
3335 dend = end_match_2;
3338 DEBUG_PRINT1 ("The compiled pattern is: ");
3339 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3340 DEBUG_PRINT1 ("The string to match is: `");
3341 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3342 DEBUG_PRINT1 ("'\n");
3344 /* This loops over pattern commands. It exits by returning from the
3345 function if the match is complete, or it drops through if the match
3346 fails at this starting point in the input data. */
3347 for (;;)
3349 DEBUG_PRINT2 ("\n0x%x: ", p);
3351 if (p == pend)
3352 { /* End of pattern means we might have succeeded. */
3353 DEBUG_PRINT1 ("end of pattern ... ");
3355 /* If we haven't matched the entire string, and we want the
3356 longest match, try backtracking. */
3357 if (d != end_match_2)
3359 DEBUG_PRINT1 ("backtracking.\n");
3361 if (!FAIL_STACK_EMPTY ())
3362 { /* More failure points to try. */
3363 boolean same_str_p = (FIRST_STRING_P (match_end)
3364 == MATCHING_IN_FIRST_STRING);
3366 /* If exceeds best match so far, save it. */
3367 if (!best_regs_set
3368 || (same_str_p && d > match_end)
3369 || (!same_str_p && !MATCHING_IN_FIRST_STRING))
3371 best_regs_set = true;
3372 match_end = d;
3374 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3376 for (mcnt = 1; mcnt < num_regs; mcnt++)
3378 best_regstart[mcnt] = regstart[mcnt];
3379 best_regend[mcnt] = regend[mcnt];
3382 goto fail;
3385 /* If no failure points, don't restore garbage. */
3386 else if (best_regs_set)
3388 restore_best_regs:
3389 /* Restore best match. It may happen that `dend ==
3390 end_match_1' while the restored d is in string2.
3391 For example, the pattern `x.*y.*z' against the
3392 strings `x-' and `y-z-', if the two strings are
3393 not consecutive in memory. */
3394 DEBUG_PRINT1 ("Restoring best registers.\n");
3396 d = match_end;
3397 dend = ((d >= string1 && d <= end1)
3398 ? end_match_1 : end_match_2);
3400 for (mcnt = 1; mcnt < num_regs; mcnt++)
3402 regstart[mcnt] = best_regstart[mcnt];
3403 regend[mcnt] = best_regend[mcnt];
3406 } /* d != end_match_2 */
3408 DEBUG_PRINT1 ("Accepting match.\n");
3410 /* If caller wants register contents data back, do it. */
3411 if (regs && !bufp->no_sub)
3413 /* Have the register data arrays been allocated? */
3414 if (bufp->regs_allocated == REGS_UNALLOCATED)
3415 { /* No. So allocate them with malloc. We need one
3416 extra element beyond `num_regs' for the `-1' marker
3417 GNU code uses. */
3418 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3419 regs->start = TALLOC (regs->num_regs, regoff_t);
3420 regs->end = TALLOC (regs->num_regs, regoff_t);
3421 if (regs->start == NULL || regs->end == NULL)
3422 return -2;
3423 bufp->regs_allocated = REGS_REALLOCATE;
3425 else if (bufp->regs_allocated == REGS_REALLOCATE)
3426 { /* Yes. If we need more elements than were already
3427 allocated, reallocate them. If we need fewer, just
3428 leave it alone. */
3429 if (regs->num_regs < num_regs + 1)
3431 regs->num_regs = num_regs + 1;
3432 RETALLOC (regs->start, regs->num_regs, regoff_t);
3433 RETALLOC (regs->end, regs->num_regs, regoff_t);
3434 if (regs->start == NULL || regs->end == NULL)
3435 return -2;
3438 else
3439 assert (bufp->regs_allocated == REGS_FIXED);
3441 /* Convert the pointer data in `regstart' and `regend' to
3442 indices. Register zero has to be set differently,
3443 since we haven't kept track of any info for it. */
3444 if (regs->num_regs > 0)
3446 regs->start[0] = pos;
3447 regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
3448 : d - string2 + size1);
3451 /* Go through the first `min (num_regs, regs->num_regs)'
3452 registers, since that is all we initialized. */
3453 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
3455 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3456 regs->start[mcnt] = regs->end[mcnt] = -1;
3457 else
3459 regs->start[mcnt] = POINTER_TO_OFFSET (regstart[mcnt]);
3460 regs->end[mcnt] = POINTER_TO_OFFSET (regend[mcnt]);
3464 /* If the regs structure we return has more elements than
3465 were in the pattern, set the extra elements to -1. If
3466 we (re)allocated the registers, this is the case,
3467 because we always allocate enough to have at least one
3468 -1 at the end. */
3469 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3470 regs->start[mcnt] = regs->end[mcnt] = -1;
3471 } /* regs && !bufp->no_sub */
3473 FREE_VARIABLES ();
3474 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3475 nfailure_points_pushed, nfailure_points_popped,
3476 nfailure_points_pushed - nfailure_points_popped);
3477 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3479 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3480 ? string1
3481 : string2 - size1);
3483 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3485 return mcnt;
3488 /* Otherwise match next pattern command. */
3489 #ifdef SWITCH_ENUM_BUG
3490 switch ((int) ((re_opcode_t) *p++))
3491 #else
3492 switch ((re_opcode_t) *p++)
3493 #endif
3495 /* Ignore these. Used to ignore the n of succeed_n's which
3496 currently have n == 0. */
3497 case no_op:
3498 DEBUG_PRINT1 ("EXECUTING no_op.\n");
3499 break;
3502 /* Match the next n pattern characters exactly. The following
3503 byte in the pattern defines n, and the n bytes after that
3504 are the characters to match. */
3505 case exactn:
3506 mcnt = *p++;
3507 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3509 /* This is written out as an if-else so we don't waste time
3510 testing `translate' inside the loop. */
3511 if (translate)
3515 PREFETCH ();
3516 if (translate[(unsigned char) *d++] != (char) *p++)
3517 goto fail;
3519 while (--mcnt);
3521 else
3525 PREFETCH ();
3526 if (*d++ != (char) *p++) goto fail;
3528 while (--mcnt);
3530 SET_REGS_MATCHED ();
3531 break;
3534 /* Match any character except possibly a newline or a null. */
3535 case anychar:
3536 DEBUG_PRINT1 ("EXECUTING anychar.\n");
3538 PREFETCH ();
3540 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
3541 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
3542 goto fail;
3544 SET_REGS_MATCHED ();
3545 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
3546 d++;
3547 break;
3550 case charset:
3551 case charset_not:
3553 register unsigned char c;
3554 boolean not = (re_opcode_t) *(p - 1) == charset_not;
3556 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
3558 PREFETCH ();
3559 c = TRANSLATE (*d); /* The character to match. */
3561 /* Cast to `unsigned' instead of `unsigned char' in case the
3562 bit list is a full 32 bytes long. */
3563 if (c < (unsigned) (*p * BYTEWIDTH)
3564 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3565 not = !not;
3567 p += 1 + *p;
3569 if (!not) goto fail;
3571 SET_REGS_MATCHED ();
3572 d++;
3573 break;
3577 /* The beginning of a group is represented by start_memory.
3578 The arguments are the register number in the next byte, and the
3579 number of groups inner to this one in the next. The text
3580 matched within the group is recorded (in the internal
3581 registers data structure) under the register number. */
3582 case start_memory:
3583 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3585 /* Find out if this group can match the empty string. */
3586 p1 = p; /* To send to group_match_null_string_p. */
3588 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3589 REG_MATCH_NULL_STRING_P (reg_info[*p])
3590 = group_match_null_string_p (&p1, pend, reg_info);
3592 /* Save the position in the string where we were the last time
3593 we were at this open-group operator in case the group is
3594 operated upon by a repetition operator, e.g., with `(a*)*b'
3595 against `ab'; then we want to ignore where we are now in
3596 the string in case this attempt to match fails. */
3597 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3598 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
3599 : regstart[*p];
3600 DEBUG_PRINT2 (" old_regstart: %d\n",
3601 POINTER_TO_OFFSET (old_regstart[*p]));
3603 regstart[*p] = d;
3604 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
3606 IS_ACTIVE (reg_info[*p]) = 1;
3607 MATCHED_SOMETHING (reg_info[*p]) = 0;
3609 /* This is the new highest active register. */
3610 highest_active_reg = *p;
3612 /* If nothing was active before, this is the new lowest active
3613 register. */
3614 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3615 lowest_active_reg = *p;
3617 /* Move past the register number and inner group count. */
3618 p += 2;
3619 break;
3622 /* The stop_memory opcode represents the end of a group. Its
3623 arguments are the same as start_memory's: the register
3624 number, and the number of inner groups. */
3625 case stop_memory:
3626 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
3628 /* We need to save the string position the last time we were at
3629 this close-group operator in case the group is operated
3630 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3631 against `aba'; then we want to ignore where we are now in
3632 the string in case this attempt to match fails. */
3633 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3634 ? REG_UNSET (regend[*p]) ? d : regend[*p]
3635 : regend[*p];
3636 DEBUG_PRINT2 (" old_regend: %d\n",
3637 POINTER_TO_OFFSET (old_regend[*p]));
3639 regend[*p] = d;
3640 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
3642 /* This register isn't active anymore. */
3643 IS_ACTIVE (reg_info[*p]) = 0;
3645 /* If this was the only register active, nothing is active
3646 anymore. */
3647 if (lowest_active_reg == highest_active_reg)
3649 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3650 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3652 else
3653 { /* We must scan for the new highest active register, since
3654 it isn't necessarily one less than now: consider
3655 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
3656 new highest active register is 1. */
3657 unsigned char r = *p - 1;
3658 while (r > 0 && !IS_ACTIVE (reg_info[r]))
3659 r--;
3661 /* If we end up at register zero, that means that we saved
3662 the registers as the result of an `on_failure_jump', not
3663 a `start_memory', and we jumped to past the innermost
3664 `stop_memory'. For example, in ((.)*) we save
3665 registers 1 and 2 as a result of the *, but when we pop
3666 back to the second ), we are at the stop_memory 1.
3667 Thus, nothing is active. */
3668 if (r == 0)
3670 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3671 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3673 else
3674 highest_active_reg = r;
3677 /* If just failed to match something this time around with a
3678 group that's operated on by a repetition operator, try to
3679 force exit from the ``loop'', and restore the register
3680 information for this group that we had before trying this
3681 last match. */
3682 if ((!MATCHED_SOMETHING (reg_info[*p])
3683 || (re_opcode_t) p[-3] == start_memory)
3684 && (p + 2) < pend)
3686 boolean is_a_jump_n = false;
3688 p1 = p + 2;
3689 mcnt = 0;
3690 switch ((re_opcode_t) *p1++)
3692 case jump_n:
3693 is_a_jump_n = true;
3694 case pop_failure_jump:
3695 case maybe_pop_jump:
3696 case jump:
3697 case dummy_failure_jump:
3698 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3699 if (is_a_jump_n)
3700 p1 += 2;
3701 break;
3703 default:
3704 /* do nothing */ ;
3706 p1 += mcnt;
3708 /* If the next operation is a jump backwards in the pattern
3709 to an on_failure_jump right before the start_memory
3710 corresponding to this stop_memory, exit from the loop
3711 by forcing a failure after pushing on the stack the
3712 on_failure_jump's jump in the pattern, and d. */
3713 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
3714 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
3716 /* If this group ever matched anything, then restore
3717 what its registers were before trying this last
3718 failed match, e.g., with `(a*)*b' against `ab' for
3719 regstart[1], and, e.g., with `((a*)*(b*)*)*'
3720 against `aba' for regend[3].
3722 Also restore the registers for inner groups for,
3723 e.g., `((a*)(b*))*' against `aba' (register 3 would
3724 otherwise get trashed). */
3726 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
3728 unsigned r;
3730 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
3732 /* Restore this and inner groups' (if any) registers. */
3733 for (r = *p; r < *p + *(p + 1); r++)
3735 regstart[r] = old_regstart[r];
3737 /* xx why this test? */
3738 if ((int) old_regend[r] >= (int) regstart[r])
3739 regend[r] = old_regend[r];
3742 p1++;
3743 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3744 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
3746 goto fail;
3750 /* Move past the register number and the inner group count. */
3751 p += 2;
3752 break;
3755 /* \<digit> has been turned into a `duplicate' command which is
3756 followed by the numeric value of <digit> as the register number. */
3757 case duplicate:
3759 register const char *d2, *dend2;
3760 int regno = *p++; /* Get which register to match against. */
3761 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
3763 /* Can't back reference a group which we've never matched. */
3764 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
3765 goto fail;
3767 /* Where in input to try to start matching. */
3768 d2 = regstart[regno];
3770 /* Where to stop matching; if both the place to start and
3771 the place to stop matching are in the same string, then
3772 set to the place to stop, otherwise, for now have to use
3773 the end of the first string. */
3775 dend2 = ((FIRST_STRING_P (regstart[regno])
3776 == FIRST_STRING_P (regend[regno]))
3777 ? regend[regno] : end_match_1);
3778 for (;;)
3780 /* If necessary, advance to next segment in register
3781 contents. */
3782 while (d2 == dend2)
3784 if (dend2 == end_match_2) break;
3785 if (dend2 == regend[regno]) break;
3787 /* End of string1 => advance to string2. */
3788 d2 = string2;
3789 dend2 = regend[regno];
3791 /* At end of register contents => success */
3792 if (d2 == dend2) break;
3794 /* If necessary, advance to next segment in data. */
3795 PREFETCH ();
3797 /* How many characters left in this segment to match. */
3798 mcnt = dend - d;
3800 /* Want how many consecutive characters we can match in
3801 one shot, so, if necessary, adjust the count. */
3802 if (mcnt > dend2 - d2)
3803 mcnt = dend2 - d2;
3805 /* Compare that many; failure if mismatch, else move
3806 past them. */
3807 if (translate
3808 ? bcmp_translate (d, d2, mcnt, translate)
3809 : bcmp (d, d2, mcnt))
3810 goto fail;
3811 d += mcnt, d2 += mcnt;
3814 break;
3817 /* begline matches the empty string at the beginning of the string
3818 (unless `not_bol' is set in `bufp'), and, if
3819 `newline_anchor' is set, after newlines. */
3820 case begline:
3821 DEBUG_PRINT1 ("EXECUTING begline.\n");
3823 if (AT_STRINGS_BEG (d))
3825 if (!bufp->not_bol) break;
3827 else if (d[-1] == '\n' && bufp->newline_anchor)
3829 break;
3831 /* In all other cases, we fail. */
3832 goto fail;
3835 /* endline is the dual of begline. */
3836 case endline:
3837 DEBUG_PRINT1 ("EXECUTING endline.\n");
3839 if (AT_STRINGS_END (d))
3841 if (!bufp->not_eol) break;
3844 /* We have to ``prefetch'' the next character. */
3845 else if ((d == end1 ? *string2 : *d) == '\n'
3846 && bufp->newline_anchor)
3848 break;
3850 goto fail;
3853 /* Match at the very beginning of the data. */
3854 case begbuf:
3855 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
3856 if (AT_STRINGS_BEG (d))
3857 break;
3858 goto fail;
3861 /* Match at the very end of the data. */
3862 case endbuf:
3863 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
3864 if (AT_STRINGS_END (d))
3865 break;
3866 goto fail;
3869 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
3870 pushes NULL as the value for the string on the stack. Then
3871 `pop_failure_point' will keep the current value for the
3872 string, instead of restoring it. To see why, consider
3873 matching `foo\nbar' against `.*\n'. The .* matches the foo;
3874 then the . fails against the \n. But the next thing we want
3875 to do is match the \n against the \n; if we restored the
3876 string value, we would be back at the foo.
3878 Because this is used only in specific cases, we don't need to
3879 check all the things that `on_failure_jump' does, to make
3880 sure the right things get saved on the stack. Hence we don't
3881 share its code. The only reason to push anything on the
3882 stack at all is that otherwise we would have to change
3883 `anychar's code to do something besides goto fail in this
3884 case; that seems worse than this. */
3885 case on_failure_keep_string_jump:
3886 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
3888 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3889 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
3891 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
3892 break;
3895 /* Uses of on_failure_jump:
3897 Each alternative starts with an on_failure_jump that points
3898 to the beginning of the next alternative. Each alternative
3899 except the last ends with a jump that in effect jumps past
3900 the rest of the alternatives. (They really jump to the
3901 ending jump of the following alternative, because tensioning
3902 these jumps is a hassle.)
3904 Repeats start with an on_failure_jump that points past both
3905 the repetition text and either the following jump or
3906 pop_failure_jump back to this on_failure_jump. */
3907 case on_failure_jump:
3908 on_failure:
3909 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
3911 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3912 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
3914 /* If this on_failure_jump comes right before a group (i.e.,
3915 the original * applied to a group), save the information
3916 for that group and all inner ones, so that if we fail back
3917 to this point, the group's information will be correct.
3918 For example, in \(a*\)*\1, we need the preceding group,
3919 and in \(\(a*\)b*\)\2, we need the inner group. */
3921 /* We can't use `p' to check ahead because we push
3922 a failure point to `p + mcnt' after we do this. */
3923 p1 = p;
3925 /* We need to skip no_op's before we look for the
3926 start_memory in case this on_failure_jump is happening as
3927 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
3928 against aba. */
3929 while (p1 < pend && (re_opcode_t) *p1 == no_op)
3930 p1++;
3932 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
3934 /* We have a new highest active register now. This will
3935 get reset at the start_memory we are about to get to,
3936 but we will have saved all the registers relevant to
3937 this repetition op, as described above. */
3938 highest_active_reg = *(p1 + 1) + *(p1 + 2);
3939 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3940 lowest_active_reg = *(p1 + 1);
3943 DEBUG_PRINT1 (":\n");
3944 PUSH_FAILURE_POINT (p + mcnt, d, -2);
3945 break;
3948 /* A smart repeat ends with `maybe_pop_jump'.
3949 We change it to either `pop_failure_jump' or `jump'. */
3950 case maybe_pop_jump:
3951 EXTRACT_NUMBER_AND_INCR (mcnt, p);
3952 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
3954 register unsigned char *p2 = p;
3956 /* Compare the beginning of the repeat with what in the
3957 pattern follows its end. If we can establish that there
3958 is nothing that they would both match, i.e., that we
3959 would have to backtrack because of (as in, e.g., `a*a')
3960 then we can change to pop_failure_jump, because we'll
3961 never have to backtrack.
3963 This is not true in the case of alternatives: in
3964 `(a|ab)*' we do need to backtrack to the `ab' alternative
3965 (e.g., if the string was `ab'). But instead of trying to
3966 detect that here, the alternative has put on a dummy
3967 failure point which is what we will end up popping. */
3969 /* Skip over open/close-group commands. */
3970 while (p2 + 2 < pend
3971 && ((re_opcode_t) *p2 == stop_memory
3972 || (re_opcode_t) *p2 == start_memory))
3973 p2 += 3; /* Skip over args, too. */
3975 /* If we're at the end of the pattern, we can change. */
3976 if (p2 == pend)
3978 /* Consider what happens when matching ":\(.*\)"
3979 against ":/". I don't really understand this code
3980 yet. */
3981 p[-3] = (unsigned char) pop_failure_jump;
3982 DEBUG_PRINT1
3983 (" End of pattern: change to `pop_failure_jump'.\n");
3986 else if ((re_opcode_t) *p2 == exactn
3987 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
3989 register unsigned char c
3990 = *p2 == (unsigned char) endline ? '\n' : p2[2];
3991 p1 = p + mcnt;
3993 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
3994 to the `maybe_finalize_jump' of this case. Examine what
3995 follows. */
3996 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
3998 p[-3] = (unsigned char) pop_failure_jump;
3999 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4000 c, p1[5]);
4003 else if ((re_opcode_t) p1[3] == charset
4004 || (re_opcode_t) p1[3] == charset_not)
4006 int not = (re_opcode_t) p1[3] == charset_not;
4008 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4009 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4010 not = !not;
4012 /* `not' is equal to 1 if c would match, which means
4013 that we can't change to pop_failure_jump. */
4014 if (!not)
4016 p[-3] = (unsigned char) pop_failure_jump;
4017 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4022 p -= 2; /* Point at relative address again. */
4023 if ((re_opcode_t) p[-1] != pop_failure_jump)
4025 p[-1] = (unsigned char) jump;
4026 DEBUG_PRINT1 (" Match => jump.\n");
4027 goto unconditional_jump;
4029 /* Note fall through. */
4032 /* The end of a simple repeat has a pop_failure_jump back to
4033 its matching on_failure_jump, where the latter will push a
4034 failure point. The pop_failure_jump takes off failure
4035 points put on by this pop_failure_jump's matching
4036 on_failure_jump; we got through the pattern to here from the
4037 matching on_failure_jump, so didn't fail. */
4038 case pop_failure_jump:
4040 /* We need to pass separate storage for the lowest and
4041 highest registers, even though we don't care about the
4042 actual values. Otherwise, we will restore only one
4043 register from the stack, since lowest will == highest in
4044 `pop_failure_point'. */
4045 unsigned dummy_low_reg, dummy_high_reg;
4046 unsigned char *pdummy;
4047 const char *sdummy;
4049 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4050 POP_FAILURE_POINT (sdummy, pdummy,
4051 dummy_low_reg, dummy_high_reg,
4052 reg_dummy, reg_dummy, reg_info_dummy);
4054 /* Note fall through. */
4057 /* Unconditionally jump (without popping any failure points). */
4058 case jump:
4059 unconditional_jump:
4060 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4061 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4062 p += mcnt; /* Do the jump. */
4063 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4064 break;
4067 /* We need this opcode so we can detect where alternatives end
4068 in `group_match_null_string_p' et al. */
4069 case jump_past_alt:
4070 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4071 goto unconditional_jump;
4074 /* Normally, the on_failure_jump pushes a failure point, which
4075 then gets popped at pop_failure_jump. We will end up at
4076 pop_failure_jump, also, and with a pattern of, say, `a+', we
4077 are skipping over the on_failure_jump, so we have to push
4078 something meaningless for pop_failure_jump to pop. */
4079 case dummy_failure_jump:
4080 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4081 /* It doesn't matter what we push for the string here. What
4082 the code at `fail' tests is the value for the pattern. */
4083 PUSH_FAILURE_POINT (0, 0, -2);
4084 goto unconditional_jump;
4087 /* At the end of an alternative, we need to push a dummy failure
4088 point in case we are followed by a `pop_failure_jump', because
4089 we don't want the failure point for the alternative to be
4090 popped. For example, matching `(a|ab)*' against `aab'
4091 requires that we match the `ab' alternative. */
4092 case push_dummy_failure:
4093 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4094 /* See comments just above at `dummy_failure_jump' about the
4095 two zeroes. */
4096 PUSH_FAILURE_POINT (0, 0, -2);
4097 break;
4099 /* Have to succeed matching what follows at least n times.
4100 After that, handle like `on_failure_jump'. */
4101 case succeed_n:
4102 EXTRACT_NUMBER (mcnt, p + 2);
4103 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4105 assert (mcnt >= 0);
4106 /* Originally, this is how many times we HAVE to succeed. */
4107 if (mcnt > 0)
4109 mcnt--;
4110 p += 2;
4111 STORE_NUMBER_AND_INCR (p, mcnt);
4112 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
4114 else if (mcnt == 0)
4116 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4117 p[2] = (unsigned char) no_op;
4118 p[3] = (unsigned char) no_op;
4119 goto on_failure;
4121 break;
4123 case jump_n:
4124 EXTRACT_NUMBER (mcnt, p + 2);
4125 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4127 /* Originally, this is how many times we CAN jump. */
4128 if (mcnt)
4130 mcnt--;
4131 STORE_NUMBER (p + 2, mcnt);
4132 goto unconditional_jump;
4134 /* If don't have to jump any more, skip over the rest of command. */
4135 else
4136 p += 4;
4137 break;
4139 case set_number_at:
4141 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4143 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4144 p1 = p + mcnt;
4145 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4146 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4147 STORE_NUMBER (p1, mcnt);
4148 break;
4151 case wordbound:
4152 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4153 if (AT_WORD_BOUNDARY (d))
4154 break;
4155 goto fail;
4157 case notwordbound:
4158 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4159 if (AT_WORD_BOUNDARY (d))
4160 goto fail;
4161 break;
4163 case wordbeg:
4164 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4165 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4166 break;
4167 goto fail;
4169 case wordend:
4170 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4171 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4172 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4173 break;
4174 goto fail;
4176 #ifdef emacs
4177 #ifdef emacs19
4178 case before_dot:
4179 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4180 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4181 goto fail;
4182 break;
4184 case at_dot:
4185 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4186 if (PTR_CHAR_POS ((unsigned char *) d) != point)
4187 goto fail;
4188 break;
4190 case after_dot:
4191 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4192 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
4193 goto fail;
4194 break;
4195 #else /* not emacs19 */
4196 case at_dot:
4197 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4198 if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
4199 goto fail;
4200 break;
4201 #endif /* not emacs19 */
4203 case syntaxspec:
4204 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4205 mcnt = *p++;
4206 goto matchsyntax;
4208 case wordchar:
4209 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4210 mcnt = (int) Sword;
4211 matchsyntax:
4212 PREFETCH ();
4213 if (SYNTAX (*d++) != (enum syntaxcode) mcnt)
4214 goto fail;
4215 SET_REGS_MATCHED ();
4216 break;
4218 case notsyntaxspec:
4219 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4220 mcnt = *p++;
4221 goto matchnotsyntax;
4223 case notwordchar:
4224 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4225 mcnt = (int) Sword;
4226 matchnotsyntax:
4227 PREFETCH ();
4228 if (SYNTAX (*d++) == (enum syntaxcode) mcnt)
4229 goto fail;
4230 SET_REGS_MATCHED ();
4231 break;
4233 #else /* not emacs */
4234 case wordchar:
4235 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4236 PREFETCH ();
4237 if (!WORDCHAR_P (d))
4238 goto fail;
4239 SET_REGS_MATCHED ();
4240 d++;
4241 break;
4243 case notwordchar:
4244 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4245 PREFETCH ();
4246 if (WORDCHAR_P (d))
4247 goto fail;
4248 SET_REGS_MATCHED ();
4249 d++;
4250 break;
4251 #endif /* not emacs */
4253 default:
4254 abort ();
4256 continue; /* Successfully executed one pattern command; keep going. */
4259 /* We goto here if a matching operation fails. */
4260 fail:
4261 if (!FAIL_STACK_EMPTY ())
4262 { /* A restart point is known. Restore to that state. */
4263 DEBUG_PRINT1 ("\nFAIL:\n");
4264 POP_FAILURE_POINT (d, p,
4265 lowest_active_reg, highest_active_reg,
4266 regstart, regend, reg_info);
4268 /* If this failure point is a dummy, try the next one. */
4269 if (!p)
4270 goto fail;
4272 /* If we failed to the end of the pattern, don't examine *p. */
4273 assert (p <= pend);
4274 if (p < pend)
4276 boolean is_a_jump_n = false;
4278 /* If failed to a backwards jump that's part of a repetition
4279 loop, need to pop this failure point and use the next one. */
4280 switch ((re_opcode_t) *p)
4282 case jump_n:
4283 is_a_jump_n = true;
4284 case maybe_pop_jump:
4285 case pop_failure_jump:
4286 case jump:
4287 p1 = p + 1;
4288 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4289 p1 += mcnt;
4291 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4292 || (!is_a_jump_n
4293 && (re_opcode_t) *p1 == on_failure_jump))
4294 goto fail;
4295 break;
4296 default:
4297 /* do nothing */ ;
4301 if (d >= string1 && d <= end1)
4302 dend = end_match_1;
4304 else
4305 break; /* Matching at this starting point really fails. */
4306 } /* for (;;) */
4308 if (best_regs_set)
4309 goto restore_best_regs;
4311 FREE_VARIABLES ();
4313 return -1; /* Failure to match. */
4314 } /* re_match_2 */
4316 /* Subroutine definitions for re_match_2. */
4319 /* We are passed P pointing to a register number after a start_memory.
4321 Return true if the pattern up to the corresponding stop_memory can
4322 match the empty string, and false otherwise.
4324 If we find the matching stop_memory, sets P to point to one past its number.
4325 Otherwise, sets P to an undefined byte less than or equal to END.
4327 We don't handle duplicates properly (yet). */
4329 static boolean
4330 group_match_null_string_p (p, end, reg_info)
4331 unsigned char **p, *end;
4332 register_info_type *reg_info;
4334 int mcnt;
4335 /* Point to after the args to the start_memory. */
4336 unsigned char *p1 = *p + 2;
4338 while (p1 < end)
4340 /* Skip over opcodes that can match nothing, and return true or
4341 false, as appropriate, when we get to one that can't, or to the
4342 matching stop_memory. */
4344 switch ((re_opcode_t) *p1)
4346 /* Could be either a loop or a series of alternatives. */
4347 case on_failure_jump:
4348 p1++;
4349 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4351 /* If the next operation is not a jump backwards in the
4352 pattern. */
4354 if (mcnt >= 0)
4356 /* Go through the on_failure_jumps of the alternatives,
4357 seeing if any of the alternatives cannot match nothing.
4358 The last alternative starts with only a jump,
4359 whereas the rest start with on_failure_jump and end
4360 with a jump, e.g., here is the pattern for `a|b|c':
4362 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4363 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4364 /exactn/1/c
4366 So, we have to first go through the first (n-1)
4367 alternatives and then deal with the last one separately. */
4370 /* Deal with the first (n-1) alternatives, which start
4371 with an on_failure_jump (see above) that jumps to right
4372 past a jump_past_alt. */
4374 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4376 /* `mcnt' holds how many bytes long the alternative
4377 is, including the ending `jump_past_alt' and
4378 its number. */
4380 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
4381 reg_info))
4382 return false;
4384 /* Move to right after this alternative, including the
4385 jump_past_alt. */
4386 p1 += mcnt;
4388 /* Break if it's the beginning of an n-th alternative
4389 that doesn't begin with an on_failure_jump. */
4390 if ((re_opcode_t) *p1 != on_failure_jump)
4391 break;
4393 /* Still have to check that it's not an n-th
4394 alternative that starts with an on_failure_jump. */
4395 p1++;
4396 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4397 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4399 /* Get to the beginning of the n-th alternative. */
4400 p1 -= 3;
4401 break;
4405 /* Deal with the last alternative: go back and get number
4406 of the `jump_past_alt' just before it. `mcnt' contains
4407 the length of the alternative. */
4408 EXTRACT_NUMBER (mcnt, p1 - 2);
4410 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
4411 return false;
4413 p1 += mcnt; /* Get past the n-th alternative. */
4414 } /* if mcnt > 0 */
4415 break;
4418 case stop_memory:
4419 assert (p1[1] == **p);
4420 *p = p1 + 2;
4421 return true;
4424 default:
4425 if (!common_op_match_null_string_p (&p1, end, reg_info))
4426 return false;
4428 } /* while p1 < end */
4430 return false;
4431 } /* group_match_null_string_p */
4434 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4435 It expects P to be the first byte of a single alternative and END one
4436 byte past the last. The alternative can contain groups. */
4438 static boolean
4439 alt_match_null_string_p (p, end, reg_info)
4440 unsigned char *p, *end;
4441 register_info_type *reg_info;
4443 int mcnt;
4444 unsigned char *p1 = p;
4446 while (p1 < end)
4448 /* Skip over opcodes that can match nothing, and break when we get
4449 to one that can't. */
4451 switch ((re_opcode_t) *p1)
4453 /* It's a loop. */
4454 case on_failure_jump:
4455 p1++;
4456 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4457 p1 += mcnt;
4458 break;
4460 default:
4461 if (!common_op_match_null_string_p (&p1, end, reg_info))
4462 return false;
4464 } /* while p1 < end */
4466 return true;
4467 } /* alt_match_null_string_p */
4470 /* Deals with the ops common to group_match_null_string_p and
4471 alt_match_null_string_p.
4473 Sets P to one after the op and its arguments, if any. */
4475 static boolean
4476 common_op_match_null_string_p (p, end, reg_info)
4477 unsigned char **p, *end;
4478 register_info_type *reg_info;
4480 int mcnt;
4481 boolean ret;
4482 int reg_no;
4483 unsigned char *p1 = *p;
4485 switch ((re_opcode_t) *p1++)
4487 case no_op:
4488 case begline:
4489 case endline:
4490 case begbuf:
4491 case endbuf:
4492 case wordbeg:
4493 case wordend:
4494 case wordbound:
4495 case notwordbound:
4496 #ifdef emacs
4497 case before_dot:
4498 case at_dot:
4499 case after_dot:
4500 #endif
4501 break;
4503 case start_memory:
4504 reg_no = *p1;
4505 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
4506 ret = group_match_null_string_p (&p1, end, reg_info);
4508 /* Have to set this here in case we're checking a group which
4509 contains a group and a back reference to it. */
4511 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4512 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
4514 if (!ret)
4515 return false;
4516 break;
4518 /* If this is an optimized succeed_n for zero times, make the jump. */
4519 case jump:
4520 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4521 if (mcnt >= 0)
4522 p1 += mcnt;
4523 else
4524 return false;
4525 break;
4527 case succeed_n:
4528 /* Get to the number of times to succeed. */
4529 p1 += 2;
4530 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4532 if (mcnt == 0)
4534 p1 -= 4;
4535 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4536 p1 += mcnt;
4538 else
4539 return false;
4540 break;
4542 case duplicate:
4543 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
4544 return false;
4545 break;
4547 case set_number_at:
4548 p1 += 4;
4550 default:
4551 /* All other opcodes mean we cannot match the empty string. */
4552 return false;
4555 *p = p1;
4556 return true;
4557 } /* common_op_match_null_string_p */
4560 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4561 bytes; nonzero otherwise. */
4563 static int
4564 bcmp_translate (s1, s2, len, translate)
4565 unsigned char *s1, *s2;
4566 register int len;
4567 char *translate;
4569 register unsigned char *p1 = s1, *p2 = s2;
4570 while (len)
4572 if (translate[*p1++] != translate[*p2++]) return 1;
4573 len--;
4575 return 0;
4578 /* Entry points for GNU code. */
4580 /* re_compile_pattern is the GNU regular expression compiler: it
4581 compiles PATTERN (of length SIZE) and puts the result in BUFP.
4582 Returns 0 if the pattern was valid, otherwise an error string.
4584 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
4585 are set in BUFP on entry.
4587 We call regex_compile to do the actual compilation. */
4589 const char *
4590 re_compile_pattern (pattern, length, bufp)
4591 const char *pattern;
4592 int length;
4593 struct re_pattern_buffer *bufp;
4595 reg_errcode_t ret;
4597 /* GNU code is written to assume at least RE_NREGS registers will be set
4598 (and at least one extra will be -1). */
4599 bufp->regs_allocated = REGS_UNALLOCATED;
4601 /* And GNU code determines whether or not to get register information
4602 by passing null for the REGS argument to re_match, etc., not by
4603 setting no_sub. */
4604 bufp->no_sub = 0;
4606 /* Match anchors at newline. */
4607 bufp->newline_anchor = 1;
4609 ret = regex_compile (pattern, length, re_syntax_options, bufp);
4611 return re_error_msg[(int) ret];
4614 /* Entry points compatible with 4.2 BSD regex library. We don't define
4615 them if this is an Emacs or POSIX compilation. */
4617 #if !defined (emacs) && !defined (_POSIX_SOURCE)
4619 /* BSD has one and only one pattern buffer. */
4620 static struct re_pattern_buffer re_comp_buf;
4622 char *
4623 re_comp (s)
4624 const char *s;
4626 reg_errcode_t ret;
4628 if (!s)
4630 if (!re_comp_buf.buffer)
4631 return "No previous regular expression";
4632 return 0;
4635 if (!re_comp_buf.buffer)
4637 re_comp_buf.buffer = (unsigned char *) malloc (200);
4638 if (re_comp_buf.buffer == NULL)
4639 return "Memory exhausted";
4640 re_comp_buf.allocated = 200;
4642 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
4643 if (re_comp_buf.fastmap == NULL)
4644 return "Memory exhausted";
4647 /* Since `re_exec' always passes NULL for the `regs' argument, we
4648 don't need to initialize the pattern buffer fields which affect it. */
4650 /* Match anchors at newlines. */
4651 re_comp_buf.newline_anchor = 1;
4653 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
4655 /* Yes, we're discarding `const' here. */
4656 return (char *) re_error_msg[(int) ret];
4661 re_exec (s)
4662 const char *s;
4664 const int len = strlen (s);
4665 return
4666 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
4668 #endif /* not emacs and not _POSIX_SOURCE */
4670 /* POSIX.2 functions. Don't define these for Emacs. */
4672 #ifndef emacs
4674 /* regcomp takes a regular expression as a string and compiles it.
4676 PREG is a regex_t *. We do not expect any fields to be initialized,
4677 since POSIX says we shouldn't. Thus, we set
4679 `buffer' to the compiled pattern;
4680 `used' to the length of the compiled pattern;
4681 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
4682 REG_EXTENDED bit in CFLAGS is set; otherwise, to
4683 RE_SYNTAX_POSIX_BASIC;
4684 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
4685 `fastmap' and `fastmap_accurate' to zero;
4686 `re_nsub' to the number of subexpressions in PATTERN.
4688 PATTERN is the address of the pattern string.
4690 CFLAGS is a series of bits which affect compilation.
4692 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
4693 use POSIX basic syntax.
4695 If REG_NEWLINE is set, then . and [^...] don't match newline.
4696 Also, regexec will try a match beginning after every newline.
4698 If REG_ICASE is set, then we considers upper- and lowercase
4699 versions of letters to be equivalent when matching.
4701 If REG_NOSUB is set, then when PREG is passed to regexec, that
4702 routine will report only success or failure, and nothing about the
4703 registers.
4705 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
4706 the return codes and their meanings.) */
4709 regcomp (preg, pattern, cflags)
4710 regex_t *preg;
4711 const char *pattern;
4712 int cflags;
4714 reg_errcode_t ret;
4715 unsigned syntax
4716 = (cflags & REG_EXTENDED) ?
4717 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
4719 /* regex_compile will allocate the space for the compiled pattern. */
4720 preg->buffer = 0;
4721 preg->allocated = 0;
4723 /* Don't bother to use a fastmap when searching. This simplifies the
4724 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
4725 characters after newlines into the fastmap. This way, we just try
4726 every character. */
4727 preg->fastmap = 0;
4729 if (cflags & REG_ICASE)
4731 unsigned i;
4733 preg->translate = (char *) malloc (CHAR_SET_SIZE);
4734 if (preg->translate == NULL)
4735 return (int) REG_ESPACE;
4737 /* Map uppercase characters to corresponding lowercase ones. */
4738 for (i = 0; i < CHAR_SET_SIZE; i++)
4739 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
4741 else
4742 preg->translate = NULL;
4744 /* If REG_NEWLINE is set, newlines are treated differently. */
4745 if (cflags & REG_NEWLINE)
4746 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
4747 syntax &= ~RE_DOT_NEWLINE;
4748 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
4749 /* It also changes the matching behavior. */
4750 preg->newline_anchor = 1;
4752 else
4753 preg->newline_anchor = 0;
4755 preg->no_sub = !!(cflags & REG_NOSUB);
4757 /* POSIX says a null character in the pattern terminates it, so we
4758 can use strlen here in compiling the pattern. */
4759 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
4761 /* POSIX doesn't distinguish between an unmatched open-group and an
4762 unmatched close-group: both are REG_EPAREN. */
4763 if (ret == REG_ERPAREN) ret = REG_EPAREN;
4765 return (int) ret;
4769 /* regexec searches for a given pattern, specified by PREG, in the
4770 string STRING.
4772 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
4773 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
4774 least NMATCH elements, and we set them to the offsets of the
4775 corresponding matched substrings.
4777 EFLAGS specifies `execution flags' which affect matching: if
4778 REG_NOTBOL is set, then ^ does not match at the beginning of the
4779 string; if REG_NOTEOL is set, then $ does not match at the end.
4781 We return 0 if we find a match and REG_NOMATCH if not. */
4784 regexec (preg, string, nmatch, pmatch, eflags)
4785 const regex_t *preg;
4786 const char *string;
4787 size_t nmatch;
4788 regmatch_t pmatch[];
4789 int eflags;
4791 int ret;
4792 struct re_registers regs;
4793 regex_t private_preg;
4794 int len = strlen (string);
4795 boolean want_reg_info = !preg->no_sub && nmatch > 0;
4797 private_preg = *preg;
4799 private_preg.not_bol = !!(eflags & REG_NOTBOL);
4800 private_preg.not_eol = !!(eflags & REG_NOTEOL);
4802 /* The user has told us exactly how many registers to return
4803 information about, via `nmatch'. We have to pass that on to the
4804 matching routines. */
4805 private_preg.regs_allocated = REGS_FIXED;
4807 if (want_reg_info)
4809 regs.num_regs = nmatch;
4810 regs.start = TALLOC (nmatch, regoff_t);
4811 regs.end = TALLOC (nmatch, regoff_t);
4812 if (regs.start == NULL || regs.end == NULL)
4813 return (int) REG_NOMATCH;
4816 /* Perform the searching operation. */
4817 ret = re_search (&private_preg, string, len,
4818 /* start: */ 0, /* range: */ len,
4819 want_reg_info ? &regs : (struct re_registers *) 0);
4821 /* Copy the register information to the POSIX structure. */
4822 if (want_reg_info)
4824 if (ret >= 0)
4826 unsigned r;
4828 for (r = 0; r < nmatch; r++)
4830 pmatch[r].rm_so = regs.start[r];
4831 pmatch[r].rm_eo = regs.end[r];
4835 /* If we needed the temporary register info, free the space now. */
4836 free (regs.start);
4837 free (regs.end);
4840 /* We want zero return to mean success, unlike `re_search'. */
4841 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
4845 /* Returns a message corresponding to an error code, ERRCODE, returned
4846 from either regcomp or regexec. We don't use PREG here. */
4848 size_t
4849 regerror (errcode, preg, errbuf, errbuf_size)
4850 int errcode;
4851 const regex_t *preg;
4852 char *errbuf;
4853 size_t errbuf_size;
4855 const char *msg;
4856 size_t msg_size;
4858 if (errcode < 0
4859 || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0])))
4860 /* Only error codes returned by the rest of the code should be passed
4861 to this routine. If we are given anything else, or if other regex
4862 code generates an invalid error code, then the program has a bug.
4863 Dump core so we can fix it. */
4864 abort ();
4866 msg = re_error_msg[errcode];
4868 /* POSIX doesn't require that we do anything in this case, but why
4869 not be nice. */
4870 if (! msg)
4871 msg = "Success";
4873 msg_size = strlen (msg) + 1; /* Includes the null. */
4875 if (errbuf_size != 0)
4877 if (msg_size > errbuf_size)
4879 strncpy (errbuf, msg, errbuf_size - 1);
4880 errbuf[errbuf_size - 1] = 0;
4882 else
4883 strcpy (errbuf, msg);
4886 return msg_size;
4890 /* Free dynamically allocated space used by PREG. */
4892 void
4893 regfree (preg)
4894 regex_t *preg;
4896 if (preg->buffer != NULL)
4897 free (preg->buffer);
4898 preg->buffer = NULL;
4900 preg->allocated = 0;
4901 preg->used = 0;
4903 if (preg->fastmap != NULL)
4904 free (preg->fastmap);
4905 preg->fastmap = NULL;
4906 preg->fastmap_accurate = 0;
4908 if (preg->translate != NULL)
4909 free (preg->translate);
4910 preg->translate = NULL;
4913 #endif /* not emacs */
4916 Local variables:
4917 make-backup-files: t
4918 version-control: t
4919 trim-versions-without-asking: nil
4920 End: