(TRANSLATE, PATFETCH): Cast elt of `translate'.
[emacs.git] / src / regex.c
blob455c6cfb05ed6f038635c6bb84bd71afbc1b7111
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, 1994, 1995 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 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
33 /* We need this for `regex.h', and perhaps for the Emacs include files. */
34 #include <sys/types.h>
36 /* This is for other GNU distributions with internationalized messages. */
37 #if HAVE_LIBINTL_H || defined (_LIBC)
38 # include <libintl.h>
39 #else
40 # define gettext(msgid) (msgid)
41 #endif
43 /* The `emacs' switch turns on certain matching commands
44 that make sense only in Emacs. */
45 #ifdef emacs
47 #include "lisp.h"
48 #include "buffer.h"
49 #include "syntax.h"
51 #else /* not emacs */
53 /* If we are not linking with Emacs proper,
54 we can't use the relocating allocator
55 even if config.h says that we can. */
56 #undef REL_ALLOC
58 #if defined (STDC_HEADERS) || defined (_LIBC)
59 #include <stdlib.h>
60 #else
61 char *malloc ();
62 char *realloc ();
63 #endif
65 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
66 If nothing else has been done, use the method below. */
67 #ifdef INHIBIT_STRING_HEADER
68 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
69 #if !defined (bzero) && !defined (bcopy)
70 #undef INHIBIT_STRING_HEADER
71 #endif
72 #endif
73 #endif
75 /* This is the normal way of making sure we have a bcopy and a bzero.
76 This is used in most programs--a few other programs avoid this
77 by defining INHIBIT_STRING_HEADER. */
78 #ifndef INHIBIT_STRING_HEADER
79 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
80 #include <string.h>
81 #ifndef bcmp
82 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
83 #endif
84 #ifndef bcopy
85 #define bcopy(s, d, n) memcpy ((d), (s), (n))
86 #endif
87 #ifndef bzero
88 #define bzero(s, n) memset ((s), 0, (n))
89 #endif
90 #else
91 #include <strings.h>
92 #endif
93 #endif
95 /* Define the syntax stuff for \<, \>, etc. */
97 /* This must be nonzero for the wordchar and notwordchar pattern
98 commands in re_match_2. */
99 #ifndef Sword
100 #define Sword 1
101 #endif
103 #ifdef SWITCH_ENUM_BUG
104 #define SWITCH_ENUM_CAST(x) ((int)(x))
105 #else
106 #define SWITCH_ENUM_CAST(x) (x)
107 #endif
109 #ifdef SYNTAX_TABLE
111 extern char *re_syntax_table;
113 #else /* not SYNTAX_TABLE */
115 /* How many characters in the character set. */
116 #define CHAR_SET_SIZE 256
118 static char re_syntax_table[CHAR_SET_SIZE];
120 static void
121 init_syntax_once ()
123 register int c;
124 static int done = 0;
126 if (done)
127 return;
129 bzero (re_syntax_table, sizeof re_syntax_table);
131 for (c = 'a'; c <= 'z'; c++)
132 re_syntax_table[c] = Sword;
134 for (c = 'A'; c <= 'Z'; c++)
135 re_syntax_table[c] = Sword;
137 for (c = '0'; c <= '9'; c++)
138 re_syntax_table[c] = Sword;
140 re_syntax_table['_'] = Sword;
142 done = 1;
145 #endif /* not SYNTAX_TABLE */
147 #define SYNTAX(c) re_syntax_table[c]
149 #endif /* not emacs */
151 /* Get the interface, including the syntax bits. */
152 #include "regex.h"
154 /* isalpha etc. are used for the character classes. */
155 #include <ctype.h>
157 /* Jim Meyering writes:
159 "... Some ctype macros are valid only for character codes that
160 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
161 using /bin/cc or gcc but without giving an ansi option). So, all
162 ctype uses should be through macros like ISPRINT... If
163 STDC_HEADERS is defined, then autoconf has verified that the ctype
164 macros don't need to be guarded with references to isascii. ...
165 Defining isascii to 1 should let any compiler worth its salt
166 eliminate the && through constant folding." */
168 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
169 #define ISASCII(c) 1
170 #else
171 #define ISASCII(c) isascii(c)
172 #endif
174 #ifdef isblank
175 #define ISBLANK(c) (ISASCII (c) && isblank (c))
176 #else
177 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
178 #endif
179 #ifdef isgraph
180 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
181 #else
182 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
183 #endif
185 #define ISPRINT(c) (ISASCII (c) && isprint (c))
186 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
187 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
188 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
189 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
190 #define ISLOWER(c) (ISASCII (c) && islower (c))
191 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
192 #define ISSPACE(c) (ISASCII (c) && isspace (c))
193 #define ISUPPER(c) (ISASCII (c) && isupper (c))
194 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
196 #ifndef NULL
197 #define NULL (void *)0
198 #endif
200 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
201 since ours (we hope) works properly with all combinations of
202 machines, compilers, `char' and `unsigned char' argument types.
203 (Per Bothner suggested the basic approach.) */
204 #undef SIGN_EXTEND_CHAR
205 #if __STDC__
206 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
207 #else /* not __STDC__ */
208 /* As in Harbison and Steele. */
209 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
210 #endif
212 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
213 use `alloca' instead of `malloc'. This is because using malloc in
214 re_search* or re_match* could cause memory leaks when C-g is used in
215 Emacs; also, malloc is slower and causes storage fragmentation. On
216 the other hand, malloc is more portable, and easier to debug.
218 Because we sometimes use alloca, some routines have to be macros,
219 not functions -- `alloca'-allocated space disappears at the end of the
220 function it is called in. */
222 #ifdef REGEX_MALLOC
224 #define REGEX_ALLOCATE malloc
225 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
226 #define REGEX_FREE free
228 #else /* not REGEX_MALLOC */
230 /* Emacs already defines alloca, sometimes. */
231 #ifndef alloca
233 /* Make alloca work the best possible way. */
234 #ifdef __GNUC__
235 #define alloca __builtin_alloca
236 #else /* not __GNUC__ */
237 #if HAVE_ALLOCA_H
238 #include <alloca.h>
239 #else /* not __GNUC__ or HAVE_ALLOCA_H */
240 #ifndef _AIX /* Already did AIX, up at the top. */
241 char *alloca ();
242 #endif /* not _AIX */
243 #endif /* not HAVE_ALLOCA_H */
244 #endif /* not __GNUC__ */
246 #endif /* not alloca */
248 #define REGEX_ALLOCATE alloca
250 /* Assumes a `char *destination' variable. */
251 #define REGEX_REALLOCATE(source, osize, nsize) \
252 (destination = (char *) alloca (nsize), \
253 bcopy (source, destination, osize), \
254 destination)
256 /* No need to do anything to free, after alloca. */
257 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
259 #endif /* not REGEX_MALLOC */
261 /* Define how to allocate the failure stack. */
263 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
265 #define REGEX_ALLOCATE_STACK(size) \
266 r_alloc (&failure_stack_ptr, (size))
267 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
268 r_re_alloc (&failure_stack_ptr, (nsize))
269 #define REGEX_FREE_STACK(ptr) \
270 r_alloc_free (&failure_stack_ptr)
272 #else /* not using relocating allocator */
274 #ifdef REGEX_MALLOC
276 #define REGEX_ALLOCATE_STACK malloc
277 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
278 #define REGEX_FREE_STACK free
280 #else /* not REGEX_MALLOC */
282 #define REGEX_ALLOCATE_STACK alloca
284 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
285 REGEX_REALLOCATE (source, osize, nsize)
286 /* No need to explicitly free anything. */
287 #define REGEX_FREE_STACK(arg)
289 #endif /* not REGEX_MALLOC */
290 #endif /* not using relocating allocator */
293 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
294 `string1' or just past its end. This works if PTR is NULL, which is
295 a good thing. */
296 #define FIRST_STRING_P(ptr) \
297 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
299 /* (Re)Allocate N items of type T using malloc, or fail. */
300 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
301 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
302 #define RETALLOC_IF(addr, n, t) \
303 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
304 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
306 #define BYTEWIDTH 8 /* In bits. */
308 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
310 #undef MAX
311 #undef MIN
312 #define MAX(a, b) ((a) > (b) ? (a) : (b))
313 #define MIN(a, b) ((a) < (b) ? (a) : (b))
315 typedef char boolean;
316 #define false 0
317 #define true 1
319 static int re_match_2_internal ();
321 /* These are the command codes that appear in compiled regular
322 expressions. Some opcodes are followed by argument bytes. A
323 command code can specify any interpretation whatsoever for its
324 arguments. Zero bytes may appear in the compiled regular expression. */
326 typedef enum
328 no_op = 0,
330 /* Succeed right away--no more backtracking. */
331 succeed,
333 /* Followed by one byte giving n, then by n literal bytes. */
334 exactn,
336 /* Matches any (more or less) character. */
337 anychar,
339 /* Matches any one char belonging to specified set. First
340 following byte is number of bitmap bytes. Then come bytes
341 for a bitmap saying which chars are in. Bits in each byte
342 are ordered low-bit-first. A character is in the set if its
343 bit is 1. A character too large to have a bit in the map is
344 automatically not in the set. */
345 charset,
347 /* Same parameters as charset, but match any character that is
348 not one of those specified. */
349 charset_not,
351 /* Start remembering the text that is matched, for storing in a
352 register. Followed by one byte with the register number, in
353 the range 0 to one less than the pattern buffer's re_nsub
354 field. Then followed by one byte with the number of groups
355 inner to this one. (This last has to be part of the
356 start_memory only because we need it in the on_failure_jump
357 of re_match_2.) */
358 start_memory,
360 /* Stop remembering the text that is matched and store it in a
361 memory register. Followed by one byte with the register
362 number, in the range 0 to one less than `re_nsub' in the
363 pattern buffer, and one byte with the number of inner groups,
364 just like `start_memory'. (We need the number of inner
365 groups here because we don't have any easy way of finding the
366 corresponding start_memory when we're at a stop_memory.) */
367 stop_memory,
369 /* Match a duplicate of something remembered. Followed by one
370 byte containing the register number. */
371 duplicate,
373 /* Fail unless at beginning of line. */
374 begline,
376 /* Fail unless at end of line. */
377 endline,
379 /* Succeeds if at beginning of buffer (if emacs) or at beginning
380 of string to be matched (if not). */
381 begbuf,
383 /* Analogously, for end of buffer/string. */
384 endbuf,
386 /* Followed by two byte relative address to which to jump. */
387 jump,
389 /* Same as jump, but marks the end of an alternative. */
390 jump_past_alt,
392 /* Followed by two-byte relative address of place to resume at
393 in case of failure. */
394 on_failure_jump,
396 /* Like on_failure_jump, but pushes a placeholder instead of the
397 current string position when executed. */
398 on_failure_keep_string_jump,
400 /* Throw away latest failure point and then jump to following
401 two-byte relative address. */
402 pop_failure_jump,
404 /* Change to pop_failure_jump if know won't have to backtrack to
405 match; otherwise change to jump. This is used to jump
406 back to the beginning of a repeat. If what follows this jump
407 clearly won't match what the repeat does, such that we can be
408 sure that there is no use backtracking out of repetitions
409 already matched, then we change it to a pop_failure_jump.
410 Followed by two-byte address. */
411 maybe_pop_jump,
413 /* Jump to following two-byte address, and push a dummy failure
414 point. This failure point will be thrown away if an attempt
415 is made to use it for a failure. A `+' construct makes this
416 before the first repeat. Also used as an intermediary kind
417 of jump when compiling an alternative. */
418 dummy_failure_jump,
420 /* Push a dummy failure point and continue. Used at the end of
421 alternatives. */
422 push_dummy_failure,
424 /* Followed by two-byte relative address and two-byte number n.
425 After matching N times, jump to the address upon failure. */
426 succeed_n,
428 /* Followed by two-byte relative address, and two-byte number n.
429 Jump to the address N times, then fail. */
430 jump_n,
432 /* Set the following two-byte relative address to the
433 subsequent two-byte number. The address *includes* the two
434 bytes of number. */
435 set_number_at,
437 wordchar, /* Matches any word-constituent character. */
438 notwordchar, /* Matches any char that is not a word-constituent. */
440 wordbeg, /* Succeeds if at word beginning. */
441 wordend, /* Succeeds if at word end. */
443 wordbound, /* Succeeds if at a word boundary. */
444 notwordbound /* Succeeds if not at a word boundary. */
446 #ifdef emacs
447 ,before_dot, /* Succeeds if before point. */
448 at_dot, /* Succeeds if at point. */
449 after_dot, /* Succeeds if after point. */
451 /* Matches any character whose syntax is specified. Followed by
452 a byte which contains a syntax code, e.g., Sword. */
453 syntaxspec,
455 /* Matches any character whose syntax is not that specified. */
456 notsyntaxspec
457 #endif /* emacs */
458 } re_opcode_t;
460 /* Common operations on the compiled pattern. */
462 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
464 #define STORE_NUMBER(destination, number) \
465 do { \
466 (destination)[0] = (number) & 0377; \
467 (destination)[1] = (number) >> 8; \
468 } while (0)
470 /* Same as STORE_NUMBER, except increment DESTINATION to
471 the byte after where the number is stored. Therefore, DESTINATION
472 must be an lvalue. */
474 #define STORE_NUMBER_AND_INCR(destination, number) \
475 do { \
476 STORE_NUMBER (destination, number); \
477 (destination) += 2; \
478 } while (0)
480 /* Put into DESTINATION a number stored in two contiguous bytes starting
481 at SOURCE. */
483 #define EXTRACT_NUMBER(destination, source) \
484 do { \
485 (destination) = *(source) & 0377; \
486 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
487 } while (0)
489 #ifdef DEBUG
490 static void
491 extract_number (dest, source)
492 int *dest;
493 unsigned char *source;
495 int temp = SIGN_EXTEND_CHAR (*(source + 1));
496 *dest = *source & 0377;
497 *dest += temp << 8;
500 #ifndef EXTRACT_MACROS /* To debug the macros. */
501 #undef EXTRACT_NUMBER
502 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
503 #endif /* not EXTRACT_MACROS */
505 #endif /* DEBUG */
507 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
508 SOURCE must be an lvalue. */
510 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
511 do { \
512 EXTRACT_NUMBER (destination, source); \
513 (source) += 2; \
514 } while (0)
516 #ifdef DEBUG
517 static void
518 extract_number_and_incr (destination, source)
519 int *destination;
520 unsigned char **source;
522 extract_number (destination, *source);
523 *source += 2;
526 #ifndef EXTRACT_MACROS
527 #undef EXTRACT_NUMBER_AND_INCR
528 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
529 extract_number_and_incr (&dest, &src)
530 #endif /* not EXTRACT_MACROS */
532 #endif /* DEBUG */
534 /* If DEBUG is defined, Regex prints many voluminous messages about what
535 it is doing (if the variable `debug' is nonzero). If linked with the
536 main program in `iregex.c', you can enter patterns and strings
537 interactively. And if linked with the main program in `main.c' and
538 the other test files, you can run the already-written tests. */
540 #ifdef DEBUG
542 /* We use standard I/O for debugging. */
543 #include <stdio.h>
545 /* It is useful to test things that ``must'' be true when debugging. */
546 #include <assert.h>
548 static int debug = 0;
550 #define DEBUG_STATEMENT(e) e
551 #define DEBUG_PRINT1(x) if (debug) printf (x)
552 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
553 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
554 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
555 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
556 if (debug) print_partial_compiled_pattern (s, e)
557 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
558 if (debug) print_double_string (w, s1, sz1, s2, sz2)
561 /* Print the fastmap in human-readable form. */
563 void
564 print_fastmap (fastmap)
565 char *fastmap;
567 unsigned was_a_range = 0;
568 unsigned i = 0;
570 while (i < (1 << BYTEWIDTH))
572 if (fastmap[i++])
574 was_a_range = 0;
575 putchar (i - 1);
576 while (i < (1 << BYTEWIDTH) && fastmap[i])
578 was_a_range = 1;
579 i++;
581 if (was_a_range)
583 printf ("-");
584 putchar (i - 1);
588 putchar ('\n');
592 /* Print a compiled pattern string in human-readable form, starting at
593 the START pointer into it and ending just before the pointer END. */
595 void
596 print_partial_compiled_pattern (start, end)
597 unsigned char *start;
598 unsigned char *end;
600 int mcnt, mcnt2;
601 unsigned char *p = start;
602 unsigned char *pend = end;
604 if (start == NULL)
606 printf ("(null)\n");
607 return;
610 /* Loop over pattern commands. */
611 while (p < pend)
613 printf ("%d:\t", p - start);
615 switch ((re_opcode_t) *p++)
617 case no_op:
618 printf ("/no_op");
619 break;
621 case exactn:
622 mcnt = *p++;
623 printf ("/exactn/%d", mcnt);
626 putchar ('/');
627 putchar (*p++);
629 while (--mcnt);
630 break;
632 case start_memory:
633 mcnt = *p++;
634 printf ("/start_memory/%d/%d", mcnt, *p++);
635 break;
637 case stop_memory:
638 mcnt = *p++;
639 printf ("/stop_memory/%d/%d", mcnt, *p++);
640 break;
642 case duplicate:
643 printf ("/duplicate/%d", *p++);
644 break;
646 case anychar:
647 printf ("/anychar");
648 break;
650 case charset:
651 case charset_not:
653 register int c, last = -100;
654 register int in_range = 0;
656 printf ("/charset [%s",
657 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
659 assert (p + *p < pend);
661 for (c = 0; c < 256; c++)
662 if (c / 8 < *p
663 && (p[1 + (c/8)] & (1 << (c % 8))))
665 /* Are we starting a range? */
666 if (last + 1 == c && ! in_range)
668 putchar ('-');
669 in_range = 1;
671 /* Have we broken a range? */
672 else if (last + 1 != c && in_range)
674 putchar (last);
675 in_range = 0;
678 if (! in_range)
679 putchar (c);
681 last = c;
684 if (in_range)
685 putchar (last);
687 putchar (']');
689 p += 1 + *p;
691 break;
693 case begline:
694 printf ("/begline");
695 break;
697 case endline:
698 printf ("/endline");
699 break;
701 case on_failure_jump:
702 extract_number_and_incr (&mcnt, &p);
703 printf ("/on_failure_jump to %d", p + mcnt - start);
704 break;
706 case on_failure_keep_string_jump:
707 extract_number_and_incr (&mcnt, &p);
708 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
709 break;
711 case dummy_failure_jump:
712 extract_number_and_incr (&mcnt, &p);
713 printf ("/dummy_failure_jump to %d", p + mcnt - start);
714 break;
716 case push_dummy_failure:
717 printf ("/push_dummy_failure");
718 break;
720 case maybe_pop_jump:
721 extract_number_and_incr (&mcnt, &p);
722 printf ("/maybe_pop_jump to %d", p + mcnt - start);
723 break;
725 case pop_failure_jump:
726 extract_number_and_incr (&mcnt, &p);
727 printf ("/pop_failure_jump to %d", p + mcnt - start);
728 break;
730 case jump_past_alt:
731 extract_number_and_incr (&mcnt, &p);
732 printf ("/jump_past_alt to %d", p + mcnt - start);
733 break;
735 case jump:
736 extract_number_and_incr (&mcnt, &p);
737 printf ("/jump to %d", p + mcnt - start);
738 break;
740 case succeed_n:
741 extract_number_and_incr (&mcnt, &p);
742 extract_number_and_incr (&mcnt2, &p);
743 printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
744 break;
746 case jump_n:
747 extract_number_and_incr (&mcnt, &p);
748 extract_number_and_incr (&mcnt2, &p);
749 printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
750 break;
752 case set_number_at:
753 extract_number_and_incr (&mcnt, &p);
754 extract_number_and_incr (&mcnt2, &p);
755 printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
756 break;
758 case wordbound:
759 printf ("/wordbound");
760 break;
762 case notwordbound:
763 printf ("/notwordbound");
764 break;
766 case wordbeg:
767 printf ("/wordbeg");
768 break;
770 case wordend:
771 printf ("/wordend");
773 #ifdef emacs
774 case before_dot:
775 printf ("/before_dot");
776 break;
778 case at_dot:
779 printf ("/at_dot");
780 break;
782 case after_dot:
783 printf ("/after_dot");
784 break;
786 case syntaxspec:
787 printf ("/syntaxspec");
788 mcnt = *p++;
789 printf ("/%d", mcnt);
790 break;
792 case notsyntaxspec:
793 printf ("/notsyntaxspec");
794 mcnt = *p++;
795 printf ("/%d", mcnt);
796 break;
797 #endif /* emacs */
799 case wordchar:
800 printf ("/wordchar");
801 break;
803 case notwordchar:
804 printf ("/notwordchar");
805 break;
807 case begbuf:
808 printf ("/begbuf");
809 break;
811 case endbuf:
812 printf ("/endbuf");
813 break;
815 default:
816 printf ("?%d", *(p-1));
819 putchar ('\n');
822 printf ("%d:\tend of pattern.\n", p - start);
826 void
827 print_compiled_pattern (bufp)
828 struct re_pattern_buffer *bufp;
830 unsigned char *buffer = bufp->buffer;
832 print_partial_compiled_pattern (buffer, buffer + bufp->used);
833 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
835 if (bufp->fastmap_accurate && bufp->fastmap)
837 printf ("fastmap: ");
838 print_fastmap (bufp->fastmap);
841 printf ("re_nsub: %d\t", bufp->re_nsub);
842 printf ("regs_alloc: %d\t", bufp->regs_allocated);
843 printf ("can_be_null: %d\t", bufp->can_be_null);
844 printf ("newline_anchor: %d\n", bufp->newline_anchor);
845 printf ("no_sub: %d\t", bufp->no_sub);
846 printf ("not_bol: %d\t", bufp->not_bol);
847 printf ("not_eol: %d\t", bufp->not_eol);
848 printf ("syntax: %d\n", bufp->syntax);
849 /* Perhaps we should print the translate table? */
853 void
854 print_double_string (where, string1, size1, string2, size2)
855 const char *where;
856 const char *string1;
857 const char *string2;
858 int size1;
859 int size2;
861 unsigned this_char;
863 if (where == NULL)
864 printf ("(null)");
865 else
867 if (FIRST_STRING_P (where))
869 for (this_char = where - string1; this_char < size1; this_char++)
870 putchar (string1[this_char]);
872 where = string2;
875 for (this_char = where - string2; this_char < size2; this_char++)
876 putchar (string2[this_char]);
880 #else /* not DEBUG */
882 #undef assert
883 #define assert(e)
885 #define DEBUG_STATEMENT(e)
886 #define DEBUG_PRINT1(x)
887 #define DEBUG_PRINT2(x1, x2)
888 #define DEBUG_PRINT3(x1, x2, x3)
889 #define DEBUG_PRINT4(x1, x2, x3, x4)
890 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
891 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
893 #endif /* not DEBUG */
895 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
896 also be assigned to arbitrarily: each pattern buffer stores its own
897 syntax, so it can be changed between regex compilations. */
898 /* This has no initializer because initialized variables in Emacs
899 become read-only after dumping. */
900 reg_syntax_t re_syntax_options;
903 /* Specify the precise syntax of regexps for compilation. This provides
904 for compatibility for various utilities which historically have
905 different, incompatible syntaxes.
907 The argument SYNTAX is a bit mask comprised of the various bits
908 defined in regex.h. We return the old syntax. */
910 reg_syntax_t
911 re_set_syntax (syntax)
912 reg_syntax_t syntax;
914 reg_syntax_t ret = re_syntax_options;
916 re_syntax_options = syntax;
917 return ret;
920 /* This table gives an error message for each of the error codes listed
921 in regex.h. Obviously the order here has to be same as there.
922 POSIX doesn't require that we do anything for REG_NOERROR,
923 but why not be nice? */
925 static const char *re_error_msgid[] =
926 { "Success", /* REG_NOERROR */
927 "No match", /* REG_NOMATCH */
928 "Invalid regular expression", /* REG_BADPAT */
929 "Invalid collation character", /* REG_ECOLLATE */
930 "Invalid character class name", /* REG_ECTYPE */
931 "Trailing backslash", /* REG_EESCAPE */
932 "Invalid back reference", /* REG_ESUBREG */
933 "Unmatched [ or [^", /* REG_EBRACK */
934 "Unmatched ( or \\(", /* REG_EPAREN */
935 "Unmatched \\{", /* REG_EBRACE */
936 "Invalid content of \\{\\}", /* REG_BADBR */
937 "Invalid range end", /* REG_ERANGE */
938 "Memory exhausted", /* REG_ESPACE */
939 "Invalid preceding regular expression", /* REG_BADRPT */
940 "Premature end of regular expression", /* REG_EEND */
941 "Regular expression too big", /* REG_ESIZE */
942 "Unmatched ) or \\)", /* REG_ERPAREN */
945 /* Avoiding alloca during matching, to placate r_alloc. */
947 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
948 searching and matching functions should not call alloca. On some
949 systems, alloca is implemented in terms of malloc, and if we're
950 using the relocating allocator routines, then malloc could cause a
951 relocation, which might (if the strings being searched are in the
952 ralloc heap) shift the data out from underneath the regexp
953 routines.
955 Here's another reason to avoid allocation: Emacs
956 processes input from X in a signal handler; processing X input may
957 call malloc; if input arrives while a matching routine is calling
958 malloc, then we're scrod. But Emacs can't just block input while
959 calling matching routines; then we don't notice interrupts when
960 they come in. So, Emacs blocks input around all regexp calls
961 except the matching calls, which it leaves unprotected, in the
962 faith that they will not malloc. */
964 /* Normally, this is fine. */
965 #define MATCH_MAY_ALLOCATE
967 /* When using GNU C, we are not REALLY using the C alloca, no matter
968 what config.h may say. So don't take precautions for it. */
969 #ifdef __GNUC__
970 #undef C_ALLOCA
971 #endif
973 /* The match routines may not allocate if (1) they would do it with malloc
974 and (2) it's not safe for them to use malloc.
975 Note that if REL_ALLOC is defined, matching would not use malloc for the
976 failure stack, but we would still use it for the register vectors;
977 so REL_ALLOC should not affect this. */
978 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
979 #undef MATCH_MAY_ALLOCATE
980 #endif
983 /* Failure stack declarations and macros; both re_compile_fastmap and
984 re_match_2 use a failure stack. These have to be macros because of
985 REGEX_ALLOCATE_STACK. */
988 /* Number of failure points for which to initially allocate space
989 when matching. If this number is exceeded, we allocate more
990 space, so it is not a hard limit. */
991 #ifndef INIT_FAILURE_ALLOC
992 #define INIT_FAILURE_ALLOC 5
993 #endif
995 /* Roughly the maximum number of failure points on the stack. Would be
996 exactly that if always used MAX_FAILURE_SPACE each time we failed.
997 This is a variable only so users of regex can assign to it; we never
998 change it ourselves. */
999 #if defined (MATCH_MAY_ALLOCATE)
1000 int re_max_failures = 200000;
1001 #else
1002 int re_max_failures = 2000;
1003 #endif
1005 union fail_stack_elt
1007 unsigned char *pointer;
1008 int integer;
1011 typedef union fail_stack_elt fail_stack_elt_t;
1013 typedef struct
1015 fail_stack_elt_t *stack;
1016 unsigned size;
1017 unsigned avail; /* Offset of next open position. */
1018 } fail_stack_type;
1020 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1021 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1022 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1025 /* Define macros to initialize and free the failure stack.
1026 Do `return -2' if the alloc fails. */
1028 #ifdef MATCH_MAY_ALLOCATE
1029 #define INIT_FAIL_STACK() \
1030 do { \
1031 fail_stack.stack = (fail_stack_elt_t *) \
1032 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1034 if (fail_stack.stack == NULL) \
1035 return -2; \
1037 fail_stack.size = INIT_FAILURE_ALLOC; \
1038 fail_stack.avail = 0; \
1039 } while (0)
1041 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1042 #else
1043 #define INIT_FAIL_STACK() \
1044 do { \
1045 fail_stack.avail = 0; \
1046 } while (0)
1048 #define RESET_FAIL_STACK()
1049 #endif
1052 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1054 Return 1 if succeeds, and 0 if either ran out of memory
1055 allocating space for it or it was already too large.
1057 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1059 #define DOUBLE_FAIL_STACK(fail_stack) \
1060 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
1061 ? 0 \
1062 : ((fail_stack).stack = (fail_stack_elt_t *) \
1063 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1064 (fail_stack).size * sizeof (fail_stack_elt_t), \
1065 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1067 (fail_stack).stack == NULL \
1068 ? 0 \
1069 : ((fail_stack).size <<= 1, \
1070 1)))
1073 /* Push pointer POINTER on FAIL_STACK.
1074 Return 1 if was able to do so and 0 if ran out of memory allocating
1075 space to do so. */
1076 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1077 ((FAIL_STACK_FULL () \
1078 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1079 ? 0 \
1080 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1083 /* Push a pointer value onto the failure stack.
1084 Assumes the variable `fail_stack'. Probably should only
1085 be called from within `PUSH_FAILURE_POINT'. */
1086 #define PUSH_FAILURE_POINTER(item) \
1087 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1089 /* This pushes an integer-valued item onto the failure stack.
1090 Assumes the variable `fail_stack'. Probably should only
1091 be called from within `PUSH_FAILURE_POINT'. */
1092 #define PUSH_FAILURE_INT(item) \
1093 fail_stack.stack[fail_stack.avail++].integer = (item)
1095 /* Push a fail_stack_elt_t value onto the failure stack.
1096 Assumes the variable `fail_stack'. Probably should only
1097 be called from within `PUSH_FAILURE_POINT'. */
1098 #define PUSH_FAILURE_ELT(item) \
1099 fail_stack.stack[fail_stack.avail++] = (item)
1101 /* These three POP... operations complement the three PUSH... operations.
1102 All assume that `fail_stack' is nonempty. */
1103 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1104 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1105 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1107 /* Used to omit pushing failure point id's when we're not debugging. */
1108 #ifdef DEBUG
1109 #define DEBUG_PUSH PUSH_FAILURE_INT
1110 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1111 #else
1112 #define DEBUG_PUSH(item)
1113 #define DEBUG_POP(item_addr)
1114 #endif
1117 /* Push the information about the state we will need
1118 if we ever fail back to it.
1120 Requires variables fail_stack, regstart, regend, reg_info, and
1121 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
1122 declared.
1124 Does `return FAILURE_CODE' if runs out of memory. */
1126 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1127 do { \
1128 char *destination; \
1129 /* Must be int, so when we don't save any registers, the arithmetic \
1130 of 0 + -1 isn't done as unsigned. */ \
1131 int this_reg; \
1133 DEBUG_STATEMENT (failure_id++); \
1134 DEBUG_STATEMENT (nfailure_points_pushed++); \
1135 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1136 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1137 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1139 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1140 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1142 /* Ensure we have enough space allocated for what we will push. */ \
1143 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1145 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1146 return failure_code; \
1148 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1149 (fail_stack).size); \
1150 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1153 /* Push the info, starting with the registers. */ \
1154 DEBUG_PRINT1 ("\n"); \
1156 if (!(RE_NO_POSIX_BACKTRACKING & bufp->syntax)) \
1157 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1158 this_reg++) \
1160 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1161 DEBUG_STATEMENT (num_regs_pushed++); \
1163 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1164 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1166 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1167 PUSH_FAILURE_POINTER (regend[this_reg]); \
1169 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
1170 DEBUG_PRINT2 (" match_null=%d", \
1171 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1172 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1173 DEBUG_PRINT2 (" matched_something=%d", \
1174 MATCHED_SOMETHING (reg_info[this_reg])); \
1175 DEBUG_PRINT2 (" ever_matched=%d", \
1176 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1177 DEBUG_PRINT1 ("\n"); \
1178 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1181 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
1182 PUSH_FAILURE_INT (lowest_active_reg); \
1184 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
1185 PUSH_FAILURE_INT (highest_active_reg); \
1187 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
1188 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1189 PUSH_FAILURE_POINTER (pattern_place); \
1191 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
1192 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1193 size2); \
1194 DEBUG_PRINT1 ("'\n"); \
1195 PUSH_FAILURE_POINTER (string_place); \
1197 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1198 DEBUG_PUSH (failure_id); \
1199 } while (0)
1201 /* This is the number of items that are pushed and popped on the stack
1202 for each register. */
1203 #define NUM_REG_ITEMS 3
1205 /* Individual items aside from the registers. */
1206 #ifdef DEBUG
1207 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1208 #else
1209 #define NUM_NONREG_ITEMS 4
1210 #endif
1212 /* We push at most this many items on the stack. */
1213 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1215 /* We actually push this many items. */
1216 #define NUM_FAILURE_ITEMS \
1217 (((RE_NO_POSIX_BACKTRACKING & bufp->syntax \
1218 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1219 * NUM_REG_ITEMS) \
1220 + NUM_NONREG_ITEMS)
1222 /* How many items can still be added to the stack without overflowing it. */
1223 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1226 /* Pops what PUSH_FAIL_STACK pushes.
1228 We restore into the parameters, all of which should be lvalues:
1229 STR -- the saved data position.
1230 PAT -- the saved pattern position.
1231 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1232 REGSTART, REGEND -- arrays of string positions.
1233 REG_INFO -- array of information about each subexpression.
1235 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1236 `pend', `string1', `size1', `string2', and `size2'. */
1238 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1240 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
1241 int this_reg; \
1242 const unsigned char *string_temp; \
1244 assert (!FAIL_STACK_EMPTY ()); \
1246 /* Remove failure points and point to how many regs pushed. */ \
1247 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1248 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1249 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1251 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1253 DEBUG_POP (&failure_id); \
1254 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1256 /* If the saved string location is NULL, it came from an \
1257 on_failure_keep_string_jump opcode, and we want to throw away the \
1258 saved NULL, thus retaining our current position in the string. */ \
1259 string_temp = POP_FAILURE_POINTER (); \
1260 if (string_temp != NULL) \
1261 str = (const char *) string_temp; \
1263 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
1264 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1265 DEBUG_PRINT1 ("'\n"); \
1267 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1268 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
1269 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1271 /* Restore register info. */ \
1272 high_reg = (unsigned) POP_FAILURE_INT (); \
1273 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1275 low_reg = (unsigned) POP_FAILURE_INT (); \
1276 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1278 if (!(RE_NO_POSIX_BACKTRACKING & bufp->syntax)) \
1279 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1281 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1283 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1284 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
1286 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1287 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1289 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1290 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1292 else \
1294 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1296 reg_info[this_reg].word = 0; \
1297 regend[this_reg] = 0; \
1298 regstart[this_reg] = 0; \
1300 highest_active_reg = high_reg; \
1303 set_regs_matched_done = 0; \
1304 DEBUG_STATEMENT (nfailure_points_popped++); \
1305 } /* POP_FAILURE_POINT */
1309 /* Structure for per-register (a.k.a. per-group) information.
1310 Other register information, such as the
1311 starting and ending positions (which are addresses), and the list of
1312 inner groups (which is a bits list) are maintained in separate
1313 variables.
1315 We are making a (strictly speaking) nonportable assumption here: that
1316 the compiler will pack our bit fields into something that fits into
1317 the type of `word', i.e., is something that fits into one item on the
1318 failure stack. */
1320 typedef union
1322 fail_stack_elt_t word;
1323 struct
1325 /* This field is one if this group can match the empty string,
1326 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1327 #define MATCH_NULL_UNSET_VALUE 3
1328 unsigned match_null_string_p : 2;
1329 unsigned is_active : 1;
1330 unsigned matched_something : 1;
1331 unsigned ever_matched_something : 1;
1332 } bits;
1333 } register_info_type;
1335 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1336 #define IS_ACTIVE(R) ((R).bits.is_active)
1337 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1338 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1341 /* Call this when have matched a real character; it sets `matched' flags
1342 for the subexpressions which we are currently inside. Also records
1343 that those subexprs have matched. */
1344 #define SET_REGS_MATCHED() \
1345 do \
1347 if (!set_regs_matched_done) \
1349 unsigned r; \
1350 set_regs_matched_done = 1; \
1351 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1353 MATCHED_SOMETHING (reg_info[r]) \
1354 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1355 = 1; \
1359 while (0)
1361 /* Registers are set to a sentinel when they haven't yet matched. */
1362 static char reg_unset_dummy;
1363 #define REG_UNSET_VALUE (&reg_unset_dummy)
1364 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1366 /* Subroutine declarations and macros for regex_compile. */
1368 static void store_op1 (), store_op2 ();
1369 static void insert_op1 (), insert_op2 ();
1370 static boolean at_begline_loc_p (), at_endline_loc_p ();
1371 static boolean group_in_compile_stack ();
1372 static reg_errcode_t compile_range ();
1374 /* Fetch the next character in the uncompiled pattern---translating it
1375 if necessary. Also cast from a signed character in the constant
1376 string passed to us by the user to an unsigned char that we can use
1377 as an array index (in, e.g., `translate'). */
1378 #ifndef PATFETCH
1379 #define PATFETCH(c) \
1380 do {if (p == pend) return REG_EEND; \
1381 c = (unsigned char) *p++; \
1382 if (translate) c = (unsigned char) translate[c]; \
1383 } while (0)
1384 #endif
1386 /* Fetch the next character in the uncompiled pattern, with no
1387 translation. */
1388 #define PATFETCH_RAW(c) \
1389 do {if (p == pend) return REG_EEND; \
1390 c = (unsigned char) *p++; \
1391 } while (0)
1393 /* Go backwards one character in the pattern. */
1394 #define PATUNFETCH p--
1397 /* If `translate' is non-null, return translate[D], else just D. We
1398 cast the subscript to translate because some data is declared as
1399 `char *', to avoid warnings when a string constant is passed. But
1400 when we use a character as a subscript we must make it unsigned. */
1401 #ifndef TRANSLATE
1402 #define TRANSLATE(d) \
1403 (translate ? (char) translate[(unsigned char) (d)] : (d))
1404 #endif
1407 /* Macros for outputting the compiled pattern into `buffer'. */
1409 /* If the buffer isn't allocated when it comes in, use this. */
1410 #define INIT_BUF_SIZE 32
1412 /* Make sure we have at least N more bytes of space in buffer. */
1413 #define GET_BUFFER_SPACE(n) \
1414 while (b - bufp->buffer + (n) > bufp->allocated) \
1415 EXTEND_BUFFER ()
1417 /* Make sure we have one more byte of buffer space and then add C to it. */
1418 #define BUF_PUSH(c) \
1419 do { \
1420 GET_BUFFER_SPACE (1); \
1421 *b++ = (unsigned char) (c); \
1422 } while (0)
1425 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1426 #define BUF_PUSH_2(c1, c2) \
1427 do { \
1428 GET_BUFFER_SPACE (2); \
1429 *b++ = (unsigned char) (c1); \
1430 *b++ = (unsigned char) (c2); \
1431 } while (0)
1434 /* As with BUF_PUSH_2, except for three bytes. */
1435 #define BUF_PUSH_3(c1, c2, c3) \
1436 do { \
1437 GET_BUFFER_SPACE (3); \
1438 *b++ = (unsigned char) (c1); \
1439 *b++ = (unsigned char) (c2); \
1440 *b++ = (unsigned char) (c3); \
1441 } while (0)
1444 /* Store a jump with opcode OP at LOC to location TO. We store a
1445 relative address offset by the three bytes the jump itself occupies. */
1446 #define STORE_JUMP(op, loc, to) \
1447 store_op1 (op, loc, (to) - (loc) - 3)
1449 /* Likewise, for a two-argument jump. */
1450 #define STORE_JUMP2(op, loc, to, arg) \
1451 store_op2 (op, loc, (to) - (loc) - 3, arg)
1453 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1454 #define INSERT_JUMP(op, loc, to) \
1455 insert_op1 (op, loc, (to) - (loc) - 3, b)
1457 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1458 #define INSERT_JUMP2(op, loc, to, arg) \
1459 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1462 /* This is not an arbitrary limit: the arguments which represent offsets
1463 into the pattern are two bytes long. So if 2^16 bytes turns out to
1464 be too small, many things would have to change. */
1465 #define MAX_BUF_SIZE (1L << 16)
1468 /* Extend the buffer by twice its current size via realloc and
1469 reset the pointers that pointed into the old block to point to the
1470 correct places in the new one. If extending the buffer results in it
1471 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1472 #define EXTEND_BUFFER() \
1473 do { \
1474 unsigned char *old_buffer = bufp->buffer; \
1475 if (bufp->allocated == MAX_BUF_SIZE) \
1476 return REG_ESIZE; \
1477 bufp->allocated <<= 1; \
1478 if (bufp->allocated > MAX_BUF_SIZE) \
1479 bufp->allocated = MAX_BUF_SIZE; \
1480 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1481 if (bufp->buffer == NULL) \
1482 return REG_ESPACE; \
1483 /* If the buffer moved, move all the pointers into it. */ \
1484 if (old_buffer != bufp->buffer) \
1486 b = (b - old_buffer) + bufp->buffer; \
1487 begalt = (begalt - old_buffer) + bufp->buffer; \
1488 if (fixup_alt_jump) \
1489 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1490 if (laststart) \
1491 laststart = (laststart - old_buffer) + bufp->buffer; \
1492 if (pending_exact) \
1493 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1495 } while (0)
1498 /* Since we have one byte reserved for the register number argument to
1499 {start,stop}_memory, the maximum number of groups we can report
1500 things about is what fits in that byte. */
1501 #define MAX_REGNUM 255
1503 /* But patterns can have more than `MAX_REGNUM' registers. We just
1504 ignore the excess. */
1505 typedef unsigned regnum_t;
1508 /* Macros for the compile stack. */
1510 /* Since offsets can go either forwards or backwards, this type needs to
1511 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1512 typedef int pattern_offset_t;
1514 typedef struct
1516 pattern_offset_t begalt_offset;
1517 pattern_offset_t fixup_alt_jump;
1518 pattern_offset_t inner_group_offset;
1519 pattern_offset_t laststart_offset;
1520 regnum_t regnum;
1521 } compile_stack_elt_t;
1524 typedef struct
1526 compile_stack_elt_t *stack;
1527 unsigned size;
1528 unsigned avail; /* Offset of next open position. */
1529 } compile_stack_type;
1532 #define INIT_COMPILE_STACK_SIZE 32
1534 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1535 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1537 /* The next available element. */
1538 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1541 /* Set the bit for character C in a list. */
1542 #define SET_LIST_BIT(c) \
1543 (b[((unsigned char) (c)) / BYTEWIDTH] \
1544 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1547 /* Get the next unsigned number in the uncompiled pattern. */
1548 #define GET_UNSIGNED_NUMBER(num) \
1549 { if (p != pend) \
1551 PATFETCH (c); \
1552 while (ISDIGIT (c)) \
1554 if (num < 0) \
1555 num = 0; \
1556 num = num * 10 + c - '0'; \
1557 if (p == pend) \
1558 break; \
1559 PATFETCH (c); \
1564 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1566 #define IS_CHAR_CLASS(string) \
1567 (STREQ (string, "alpha") || STREQ (string, "upper") \
1568 || STREQ (string, "lower") || STREQ (string, "digit") \
1569 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1570 || STREQ (string, "space") || STREQ (string, "print") \
1571 || STREQ (string, "punct") || STREQ (string, "graph") \
1572 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1574 #ifndef MATCH_MAY_ALLOCATE
1576 /* If we cannot allocate large objects within re_match_2_internal,
1577 we make the fail stack and register vectors global.
1578 The fail stack, we grow to the maximum size when a regexp
1579 is compiled.
1580 The register vectors, we adjust in size each time we
1581 compile a regexp, according to the number of registers it needs. */
1583 static fail_stack_type fail_stack;
1585 /* Size with which the following vectors are currently allocated.
1586 That is so we can make them bigger as needed,
1587 but never make them smaller. */
1588 static int regs_allocated_size;
1590 static const char ** regstart, ** regend;
1591 static const char ** old_regstart, ** old_regend;
1592 static const char **best_regstart, **best_regend;
1593 static register_info_type *reg_info;
1594 static const char **reg_dummy;
1595 static register_info_type *reg_info_dummy;
1597 /* Make the register vectors big enough for NUM_REGS registers,
1598 but don't make them smaller. */
1600 static
1601 regex_grow_registers (num_regs)
1602 int num_regs;
1604 if (num_regs > regs_allocated_size)
1606 RETALLOC_IF (regstart, num_regs, const char *);
1607 RETALLOC_IF (regend, num_regs, const char *);
1608 RETALLOC_IF (old_regstart, num_regs, const char *);
1609 RETALLOC_IF (old_regend, num_regs, const char *);
1610 RETALLOC_IF (best_regstart, num_regs, const char *);
1611 RETALLOC_IF (best_regend, num_regs, const char *);
1612 RETALLOC_IF (reg_info, num_regs, register_info_type);
1613 RETALLOC_IF (reg_dummy, num_regs, const char *);
1614 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1616 regs_allocated_size = num_regs;
1620 #endif /* not MATCH_MAY_ALLOCATE */
1622 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1623 Returns one of error codes defined in `regex.h', or zero for success.
1625 Assumes the `allocated' (and perhaps `buffer') and `translate'
1626 fields are set in BUFP on entry.
1628 If it succeeds, results are put in BUFP (if it returns an error, the
1629 contents of BUFP are undefined):
1630 `buffer' is the compiled pattern;
1631 `syntax' is set to SYNTAX;
1632 `used' is set to the length of the compiled pattern;
1633 `fastmap_accurate' is zero;
1634 `re_nsub' is the number of subexpressions in PATTERN;
1635 `not_bol' and `not_eol' are zero;
1637 The `fastmap' and `newline_anchor' fields are neither
1638 examined nor set. */
1640 /* Return, freeing storage we allocated. */
1641 #define FREE_STACK_RETURN(value) \
1642 return (free (compile_stack.stack), value)
1644 static reg_errcode_t
1645 regex_compile (pattern, size, syntax, bufp)
1646 const char *pattern;
1647 int size;
1648 reg_syntax_t syntax;
1649 struct re_pattern_buffer *bufp;
1651 /* We fetch characters from PATTERN here. Even though PATTERN is
1652 `char *' (i.e., signed), we declare these variables as unsigned, so
1653 they can be reliably used as array indices. */
1654 register unsigned char c, c1;
1656 /* A random temporary spot in PATTERN. */
1657 const char *p1;
1659 /* Points to the end of the buffer, where we should append. */
1660 register unsigned char *b;
1662 /* Keeps track of unclosed groups. */
1663 compile_stack_type compile_stack;
1665 /* Points to the current (ending) position in the pattern. */
1666 const char *p = pattern;
1667 const char *pend = pattern + size;
1669 /* How to translate the characters in the pattern. */
1670 RE_TRANSLATE_TYPE translate = bufp->translate;
1672 /* Address of the count-byte of the most recently inserted `exactn'
1673 command. This makes it possible to tell if a new exact-match
1674 character can be added to that command or if the character requires
1675 a new `exactn' command. */
1676 unsigned char *pending_exact = 0;
1678 /* Address of start of the most recently finished expression.
1679 This tells, e.g., postfix * where to find the start of its
1680 operand. Reset at the beginning of groups and alternatives. */
1681 unsigned char *laststart = 0;
1683 /* Address of beginning of regexp, or inside of last group. */
1684 unsigned char *begalt;
1686 /* Place in the uncompiled pattern (i.e., the {) to
1687 which to go back if the interval is invalid. */
1688 const char *beg_interval;
1690 /* Address of the place where a forward jump should go to the end of
1691 the containing expression. Each alternative of an `or' -- except the
1692 last -- ends with a forward jump of this sort. */
1693 unsigned char *fixup_alt_jump = 0;
1695 /* Counts open-groups as they are encountered. Remembered for the
1696 matching close-group on the compile stack, so the same register
1697 number is put in the stop_memory as the start_memory. */
1698 regnum_t regnum = 0;
1700 #ifdef DEBUG
1701 DEBUG_PRINT1 ("\nCompiling pattern: ");
1702 if (debug)
1704 unsigned debug_count;
1706 for (debug_count = 0; debug_count < size; debug_count++)
1707 putchar (pattern[debug_count]);
1708 putchar ('\n');
1710 #endif /* DEBUG */
1712 /* Initialize the compile stack. */
1713 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1714 if (compile_stack.stack == NULL)
1715 return REG_ESPACE;
1717 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1718 compile_stack.avail = 0;
1720 /* Initialize the pattern buffer. */
1721 bufp->syntax = syntax;
1722 bufp->fastmap_accurate = 0;
1723 bufp->not_bol = bufp->not_eol = 0;
1725 /* Set `used' to zero, so that if we return an error, the pattern
1726 printer (for debugging) will think there's no pattern. We reset it
1727 at the end. */
1728 bufp->used = 0;
1730 /* Always count groups, whether or not bufp->no_sub is set. */
1731 bufp->re_nsub = 0;
1733 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1734 /* Initialize the syntax table. */
1735 init_syntax_once ();
1736 #endif
1738 if (bufp->allocated == 0)
1740 if (bufp->buffer)
1741 { /* If zero allocated, but buffer is non-null, try to realloc
1742 enough space. This loses if buffer's address is bogus, but
1743 that is the user's responsibility. */
1744 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1746 else
1747 { /* Caller did not allocate a buffer. Do it for them. */
1748 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1750 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1752 bufp->allocated = INIT_BUF_SIZE;
1755 begalt = b = bufp->buffer;
1757 /* Loop through the uncompiled pattern until we're at the end. */
1758 while (p != pend)
1760 PATFETCH (c);
1762 switch (c)
1764 case '^':
1766 if ( /* If at start of pattern, it's an operator. */
1767 p == pattern + 1
1768 /* If context independent, it's an operator. */
1769 || syntax & RE_CONTEXT_INDEP_ANCHORS
1770 /* Otherwise, depends on what's come before. */
1771 || at_begline_loc_p (pattern, p, syntax))
1772 BUF_PUSH (begline);
1773 else
1774 goto normal_char;
1776 break;
1779 case '$':
1781 if ( /* If at end of pattern, it's an operator. */
1782 p == pend
1783 /* If context independent, it's an operator. */
1784 || syntax & RE_CONTEXT_INDEP_ANCHORS
1785 /* Otherwise, depends on what's next. */
1786 || at_endline_loc_p (p, pend, syntax))
1787 BUF_PUSH (endline);
1788 else
1789 goto normal_char;
1791 break;
1794 case '+':
1795 case '?':
1796 if ((syntax & RE_BK_PLUS_QM)
1797 || (syntax & RE_LIMITED_OPS))
1798 goto normal_char;
1799 handle_plus:
1800 case '*':
1801 /* If there is no previous pattern... */
1802 if (!laststart)
1804 if (syntax & RE_CONTEXT_INVALID_OPS)
1805 FREE_STACK_RETURN (REG_BADRPT);
1806 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1807 goto normal_char;
1811 /* Are we optimizing this jump? */
1812 boolean keep_string_p = false;
1814 /* 1 means zero (many) matches is allowed. */
1815 char zero_times_ok = 0, many_times_ok = 0;
1817 /* If there is a sequence of repetition chars, collapse it
1818 down to just one (the right one). We can't combine
1819 interval operators with these because of, e.g., `a{2}*',
1820 which should only match an even number of `a's. */
1822 for (;;)
1824 zero_times_ok |= c != '+';
1825 many_times_ok |= c != '?';
1827 if (p == pend)
1828 break;
1830 PATFETCH (c);
1832 if (c == '*'
1833 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1836 else if (syntax & RE_BK_PLUS_QM && c == '\\')
1838 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1840 PATFETCH (c1);
1841 if (!(c1 == '+' || c1 == '?'))
1843 PATUNFETCH;
1844 PATUNFETCH;
1845 break;
1848 c = c1;
1850 else
1852 PATUNFETCH;
1853 break;
1856 /* If we get here, we found another repeat character. */
1859 /* Star, etc. applied to an empty pattern is equivalent
1860 to an empty pattern. */
1861 if (!laststart)
1862 break;
1864 /* Now we know whether or not zero matches is allowed
1865 and also whether or not two or more matches is allowed. */
1866 if (many_times_ok)
1867 { /* More than one repetition is allowed, so put in at the
1868 end a backward relative jump from `b' to before the next
1869 jump we're going to put in below (which jumps from
1870 laststart to after this jump).
1872 But if we are at the `*' in the exact sequence `.*\n',
1873 insert an unconditional jump backwards to the .,
1874 instead of the beginning of the loop. This way we only
1875 push a failure point once, instead of every time
1876 through the loop. */
1877 assert (p - 1 > pattern);
1879 /* Allocate the space for the jump. */
1880 GET_BUFFER_SPACE (3);
1882 /* We know we are not at the first character of the pattern,
1883 because laststart was nonzero. And we've already
1884 incremented `p', by the way, to be the character after
1885 the `*'. Do we have to do something analogous here
1886 for null bytes, because of RE_DOT_NOT_NULL? */
1887 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1888 && zero_times_ok
1889 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1890 && !(syntax & RE_DOT_NEWLINE))
1891 { /* We have .*\n. */
1892 STORE_JUMP (jump, b, laststart);
1893 keep_string_p = true;
1895 else
1896 /* Anything else. */
1897 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1899 /* We've added more stuff to the buffer. */
1900 b += 3;
1903 /* On failure, jump from laststart to b + 3, which will be the
1904 end of the buffer after this jump is inserted. */
1905 GET_BUFFER_SPACE (3);
1906 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1907 : on_failure_jump,
1908 laststart, b + 3);
1909 pending_exact = 0;
1910 b += 3;
1912 if (!zero_times_ok)
1914 /* At least one repetition is required, so insert a
1915 `dummy_failure_jump' before the initial
1916 `on_failure_jump' instruction of the loop. This
1917 effects a skip over that instruction the first time
1918 we hit that loop. */
1919 GET_BUFFER_SPACE (3);
1920 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1921 b += 3;
1924 break;
1927 case '.':
1928 laststart = b;
1929 BUF_PUSH (anychar);
1930 break;
1933 case '[':
1935 boolean had_char_class = false;
1937 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1939 /* Ensure that we have enough space to push a charset: the
1940 opcode, the length count, and the bitset; 34 bytes in all. */
1941 GET_BUFFER_SPACE (34);
1943 laststart = b;
1945 /* We test `*p == '^' twice, instead of using an if
1946 statement, so we only need one BUF_PUSH. */
1947 BUF_PUSH (*p == '^' ? charset_not : charset);
1948 if (*p == '^')
1949 p++;
1951 /* Remember the first position in the bracket expression. */
1952 p1 = p;
1954 /* Push the number of bytes in the bitmap. */
1955 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1957 /* Clear the whole map. */
1958 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1960 /* charset_not matches newline according to a syntax bit. */
1961 if ((re_opcode_t) b[-2] == charset_not
1962 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1963 SET_LIST_BIT ('\n');
1965 /* Read in characters and ranges, setting map bits. */
1966 for (;;)
1968 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1970 PATFETCH (c);
1972 /* \ might escape characters inside [...] and [^...]. */
1973 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1975 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1977 PATFETCH (c1);
1978 SET_LIST_BIT (c1);
1979 continue;
1982 /* Could be the end of the bracket expression. If it's
1983 not (i.e., when the bracket expression is `[]' so
1984 far), the ']' character bit gets set way below. */
1985 if (c == ']' && p != p1 + 1)
1986 break;
1988 /* Look ahead to see if it's a range when the last thing
1989 was a character class. */
1990 if (had_char_class && c == '-' && *p != ']')
1991 FREE_STACK_RETURN (REG_ERANGE);
1993 /* Look ahead to see if it's a range when the last thing
1994 was a character: if this is a hyphen not at the
1995 beginning or the end of a list, then it's the range
1996 operator. */
1997 if (c == '-'
1998 && !(p - 2 >= pattern && p[-2] == '[')
1999 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2000 && *p != ']')
2002 reg_errcode_t ret
2003 = compile_range (&p, pend, translate, syntax, b);
2004 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2007 else if (p[0] == '-' && p[1] != ']')
2008 { /* This handles ranges made up of characters only. */
2009 reg_errcode_t ret;
2011 /* Move past the `-'. */
2012 PATFETCH (c1);
2014 ret = compile_range (&p, pend, translate, syntax, b);
2015 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2018 /* See if we're at the beginning of a possible character
2019 class. */
2021 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2022 { /* Leave room for the null. */
2023 char str[CHAR_CLASS_MAX_LENGTH + 1];
2025 PATFETCH (c);
2026 c1 = 0;
2028 /* If pattern is `[[:'. */
2029 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2031 for (;;)
2033 PATFETCH (c);
2034 if (c == ':' || c == ']' || p == pend
2035 || c1 == CHAR_CLASS_MAX_LENGTH)
2036 break;
2037 str[c1++] = c;
2039 str[c1] = '\0';
2041 /* If isn't a word bracketed by `[:' and:`]':
2042 undo the ending character, the letters, and leave
2043 the leading `:' and `[' (but set bits for them). */
2044 if (c == ':' && *p == ']')
2046 int ch;
2047 boolean is_alnum = STREQ (str, "alnum");
2048 boolean is_alpha = STREQ (str, "alpha");
2049 boolean is_blank = STREQ (str, "blank");
2050 boolean is_cntrl = STREQ (str, "cntrl");
2051 boolean is_digit = STREQ (str, "digit");
2052 boolean is_graph = STREQ (str, "graph");
2053 boolean is_lower = STREQ (str, "lower");
2054 boolean is_print = STREQ (str, "print");
2055 boolean is_punct = STREQ (str, "punct");
2056 boolean is_space = STREQ (str, "space");
2057 boolean is_upper = STREQ (str, "upper");
2058 boolean is_xdigit = STREQ (str, "xdigit");
2060 if (!IS_CHAR_CLASS (str))
2061 FREE_STACK_RETURN (REG_ECTYPE);
2063 /* Throw away the ] at the end of the character
2064 class. */
2065 PATFETCH (c);
2067 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2069 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2071 /* This was split into 3 if's to
2072 avoid an arbitrary limit in some compiler. */
2073 if ( (is_alnum && ISALNUM (ch))
2074 || (is_alpha && ISALPHA (ch))
2075 || (is_blank && ISBLANK (ch))
2076 || (is_cntrl && ISCNTRL (ch)))
2077 SET_LIST_BIT (ch);
2078 if ( (is_digit && ISDIGIT (ch))
2079 || (is_graph && ISGRAPH (ch))
2080 || (is_lower && ISLOWER (ch))
2081 || (is_print && ISPRINT (ch)))
2082 SET_LIST_BIT (ch);
2083 if ( (is_punct && ISPUNCT (ch))
2084 || (is_space && ISSPACE (ch))
2085 || (is_upper && ISUPPER (ch))
2086 || (is_xdigit && ISXDIGIT (ch)))
2087 SET_LIST_BIT (ch);
2089 had_char_class = true;
2091 else
2093 c1++;
2094 while (c1--)
2095 PATUNFETCH;
2096 SET_LIST_BIT ('[');
2097 SET_LIST_BIT (':');
2098 had_char_class = false;
2101 else
2103 had_char_class = false;
2104 SET_LIST_BIT (c);
2108 /* Discard any (non)matching list bytes that are all 0 at the
2109 end of the map. Decrease the map-length byte too. */
2110 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2111 b[-1]--;
2112 b += b[-1];
2114 break;
2117 case '(':
2118 if (syntax & RE_NO_BK_PARENS)
2119 goto handle_open;
2120 else
2121 goto normal_char;
2124 case ')':
2125 if (syntax & RE_NO_BK_PARENS)
2126 goto handle_close;
2127 else
2128 goto normal_char;
2131 case '\n':
2132 if (syntax & RE_NEWLINE_ALT)
2133 goto handle_alt;
2134 else
2135 goto normal_char;
2138 case '|':
2139 if (syntax & RE_NO_BK_VBAR)
2140 goto handle_alt;
2141 else
2142 goto normal_char;
2145 case '{':
2146 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2147 goto handle_interval;
2148 else
2149 goto normal_char;
2152 case '\\':
2153 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2155 /* Do not translate the character after the \, so that we can
2156 distinguish, e.g., \B from \b, even if we normally would
2157 translate, e.g., B to b. */
2158 PATFETCH_RAW (c);
2160 switch (c)
2162 case '(':
2163 if (syntax & RE_NO_BK_PARENS)
2164 goto normal_backslash;
2166 handle_open:
2167 bufp->re_nsub++;
2168 regnum++;
2170 if (COMPILE_STACK_FULL)
2172 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2173 compile_stack_elt_t);
2174 if (compile_stack.stack == NULL) return REG_ESPACE;
2176 compile_stack.size <<= 1;
2179 /* These are the values to restore when we hit end of this
2180 group. They are all relative offsets, so that if the
2181 whole pattern moves because of realloc, they will still
2182 be valid. */
2183 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2184 COMPILE_STACK_TOP.fixup_alt_jump
2185 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2186 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2187 COMPILE_STACK_TOP.regnum = regnum;
2189 /* We will eventually replace the 0 with the number of
2190 groups inner to this one. But do not push a
2191 start_memory for groups beyond the last one we can
2192 represent in the compiled pattern. */
2193 if (regnum <= MAX_REGNUM)
2195 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2196 BUF_PUSH_3 (start_memory, regnum, 0);
2199 compile_stack.avail++;
2201 fixup_alt_jump = 0;
2202 laststart = 0;
2203 begalt = b;
2204 /* If we've reached MAX_REGNUM groups, then this open
2205 won't actually generate any code, so we'll have to
2206 clear pending_exact explicitly. */
2207 pending_exact = 0;
2208 break;
2211 case ')':
2212 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2214 if (COMPILE_STACK_EMPTY)
2215 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2216 goto normal_backslash;
2217 else
2218 FREE_STACK_RETURN (REG_ERPAREN);
2220 handle_close:
2221 if (fixup_alt_jump)
2222 { /* Push a dummy failure point at the end of the
2223 alternative for a possible future
2224 `pop_failure_jump' to pop. See comments at
2225 `push_dummy_failure' in `re_match_2'. */
2226 BUF_PUSH (push_dummy_failure);
2228 /* We allocated space for this jump when we assigned
2229 to `fixup_alt_jump', in the `handle_alt' case below. */
2230 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2233 /* See similar code for backslashed left paren above. */
2234 if (COMPILE_STACK_EMPTY)
2235 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2236 goto normal_char;
2237 else
2238 FREE_STACK_RETURN (REG_ERPAREN);
2240 /* Since we just checked for an empty stack above, this
2241 ``can't happen''. */
2242 assert (compile_stack.avail != 0);
2244 /* We don't just want to restore into `regnum', because
2245 later groups should continue to be numbered higher,
2246 as in `(ab)c(de)' -- the second group is #2. */
2247 regnum_t this_group_regnum;
2249 compile_stack.avail--;
2250 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2251 fixup_alt_jump
2252 = COMPILE_STACK_TOP.fixup_alt_jump
2253 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2254 : 0;
2255 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2256 this_group_regnum = COMPILE_STACK_TOP.regnum;
2257 /* If we've reached MAX_REGNUM groups, then this open
2258 won't actually generate any code, so we'll have to
2259 clear pending_exact explicitly. */
2260 pending_exact = 0;
2262 /* We're at the end of the group, so now we know how many
2263 groups were inside this one. */
2264 if (this_group_regnum <= MAX_REGNUM)
2266 unsigned char *inner_group_loc
2267 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2269 *inner_group_loc = regnum - this_group_regnum;
2270 BUF_PUSH_3 (stop_memory, this_group_regnum,
2271 regnum - this_group_regnum);
2274 break;
2277 case '|': /* `\|'. */
2278 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2279 goto normal_backslash;
2280 handle_alt:
2281 if (syntax & RE_LIMITED_OPS)
2282 goto normal_char;
2284 /* Insert before the previous alternative a jump which
2285 jumps to this alternative if the former fails. */
2286 GET_BUFFER_SPACE (3);
2287 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2288 pending_exact = 0;
2289 b += 3;
2291 /* The alternative before this one has a jump after it
2292 which gets executed if it gets matched. Adjust that
2293 jump so it will jump to this alternative's analogous
2294 jump (put in below, which in turn will jump to the next
2295 (if any) alternative's such jump, etc.). The last such
2296 jump jumps to the correct final destination. A picture:
2297 _____ _____
2298 | | | |
2299 | v | v
2300 a | b | c
2302 If we are at `b', then fixup_alt_jump right now points to a
2303 three-byte space after `a'. We'll put in the jump, set
2304 fixup_alt_jump to right after `b', and leave behind three
2305 bytes which we'll fill in when we get to after `c'. */
2307 if (fixup_alt_jump)
2308 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2310 /* Mark and leave space for a jump after this alternative,
2311 to be filled in later either by next alternative or
2312 when know we're at the end of a series of alternatives. */
2313 fixup_alt_jump = b;
2314 GET_BUFFER_SPACE (3);
2315 b += 3;
2317 laststart = 0;
2318 begalt = b;
2319 break;
2322 case '{':
2323 /* If \{ is a literal. */
2324 if (!(syntax & RE_INTERVALS)
2325 /* If we're at `\{' and it's not the open-interval
2326 operator. */
2327 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2328 || (p - 2 == pattern && p == pend))
2329 goto normal_backslash;
2331 handle_interval:
2333 /* If got here, then the syntax allows intervals. */
2335 /* At least (most) this many matches must be made. */
2336 int lower_bound = -1, upper_bound = -1;
2338 beg_interval = p - 1;
2340 if (p == pend)
2342 if (syntax & RE_NO_BK_BRACES)
2343 goto unfetch_interval;
2344 else
2345 FREE_STACK_RETURN (REG_EBRACE);
2348 GET_UNSIGNED_NUMBER (lower_bound);
2350 if (c == ',')
2352 GET_UNSIGNED_NUMBER (upper_bound);
2353 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2355 else
2356 /* Interval such as `{1}' => match exactly once. */
2357 upper_bound = lower_bound;
2359 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2360 || lower_bound > upper_bound)
2362 if (syntax & RE_NO_BK_BRACES)
2363 goto unfetch_interval;
2364 else
2365 FREE_STACK_RETURN (REG_BADBR);
2368 if (!(syntax & RE_NO_BK_BRACES))
2370 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2372 PATFETCH (c);
2375 if (c != '}')
2377 if (syntax & RE_NO_BK_BRACES)
2378 goto unfetch_interval;
2379 else
2380 FREE_STACK_RETURN (REG_BADBR);
2383 /* We just parsed a valid interval. */
2385 /* If it's invalid to have no preceding re. */
2386 if (!laststart)
2388 if (syntax & RE_CONTEXT_INVALID_OPS)
2389 FREE_STACK_RETURN (REG_BADRPT);
2390 else if (syntax & RE_CONTEXT_INDEP_OPS)
2391 laststart = b;
2392 else
2393 goto unfetch_interval;
2396 /* If the upper bound is zero, don't want to succeed at
2397 all; jump from `laststart' to `b + 3', which will be
2398 the end of the buffer after we insert the jump. */
2399 if (upper_bound == 0)
2401 GET_BUFFER_SPACE (3);
2402 INSERT_JUMP (jump, laststart, b + 3);
2403 b += 3;
2406 /* Otherwise, we have a nontrivial interval. When
2407 we're all done, the pattern will look like:
2408 set_number_at <jump count> <upper bound>
2409 set_number_at <succeed_n count> <lower bound>
2410 succeed_n <after jump addr> <succeed_n count>
2411 <body of loop>
2412 jump_n <succeed_n addr> <jump count>
2413 (The upper bound and `jump_n' are omitted if
2414 `upper_bound' is 1, though.) */
2415 else
2416 { /* If the upper bound is > 1, we need to insert
2417 more at the end of the loop. */
2418 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2420 GET_BUFFER_SPACE (nbytes);
2422 /* Initialize lower bound of the `succeed_n', even
2423 though it will be set during matching by its
2424 attendant `set_number_at' (inserted next),
2425 because `re_compile_fastmap' needs to know.
2426 Jump to the `jump_n' we might insert below. */
2427 INSERT_JUMP2 (succeed_n, laststart,
2428 b + 5 + (upper_bound > 1) * 5,
2429 lower_bound);
2430 b += 5;
2432 /* Code to initialize the lower bound. Insert
2433 before the `succeed_n'. The `5' is the last two
2434 bytes of this `set_number_at', plus 3 bytes of
2435 the following `succeed_n'. */
2436 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2437 b += 5;
2439 if (upper_bound > 1)
2440 { /* More than one repetition is allowed, so
2441 append a backward jump to the `succeed_n'
2442 that starts this interval.
2444 When we've reached this during matching,
2445 we'll have matched the interval once, so
2446 jump back only `upper_bound - 1' times. */
2447 STORE_JUMP2 (jump_n, b, laststart + 5,
2448 upper_bound - 1);
2449 b += 5;
2451 /* The location we want to set is the second
2452 parameter of the `jump_n'; that is `b-2' as
2453 an absolute address. `laststart' will be
2454 the `set_number_at' we're about to insert;
2455 `laststart+3' the number to set, the source
2456 for the relative address. But we are
2457 inserting into the middle of the pattern --
2458 so everything is getting moved up by 5.
2459 Conclusion: (b - 2) - (laststart + 3) + 5,
2460 i.e., b - laststart.
2462 We insert this at the beginning of the loop
2463 so that if we fail during matching, we'll
2464 reinitialize the bounds. */
2465 insert_op2 (set_number_at, laststart, b - laststart,
2466 upper_bound - 1, b);
2467 b += 5;
2470 pending_exact = 0;
2471 beg_interval = NULL;
2473 break;
2475 unfetch_interval:
2476 /* If an invalid interval, match the characters as literals. */
2477 assert (beg_interval);
2478 p = beg_interval;
2479 beg_interval = NULL;
2481 /* normal_char and normal_backslash need `c'. */
2482 PATFETCH (c);
2484 if (!(syntax & RE_NO_BK_BRACES))
2486 if (p > pattern && p[-1] == '\\')
2487 goto normal_backslash;
2489 goto normal_char;
2491 #ifdef emacs
2492 /* There is no way to specify the before_dot and after_dot
2493 operators. rms says this is ok. --karl */
2494 case '=':
2495 BUF_PUSH (at_dot);
2496 break;
2498 case 's':
2499 laststart = b;
2500 PATFETCH (c);
2501 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2502 break;
2504 case 'S':
2505 laststart = b;
2506 PATFETCH (c);
2507 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2508 break;
2509 #endif /* emacs */
2512 case 'w':
2513 laststart = b;
2514 BUF_PUSH (wordchar);
2515 break;
2518 case 'W':
2519 laststart = b;
2520 BUF_PUSH (notwordchar);
2521 break;
2524 case '<':
2525 BUF_PUSH (wordbeg);
2526 break;
2528 case '>':
2529 BUF_PUSH (wordend);
2530 break;
2532 case 'b':
2533 BUF_PUSH (wordbound);
2534 break;
2536 case 'B':
2537 BUF_PUSH (notwordbound);
2538 break;
2540 case '`':
2541 BUF_PUSH (begbuf);
2542 break;
2544 case '\'':
2545 BUF_PUSH (endbuf);
2546 break;
2548 case '1': case '2': case '3': case '4': case '5':
2549 case '6': case '7': case '8': case '9':
2550 if (syntax & RE_NO_BK_REFS)
2551 goto normal_char;
2553 c1 = c - '0';
2555 if (c1 > regnum)
2556 FREE_STACK_RETURN (REG_ESUBREG);
2558 /* Can't back reference to a subexpression if inside of it. */
2559 if (group_in_compile_stack (compile_stack, c1))
2560 goto normal_char;
2562 laststart = b;
2563 BUF_PUSH_2 (duplicate, c1);
2564 break;
2567 case '+':
2568 case '?':
2569 if (syntax & RE_BK_PLUS_QM)
2570 goto handle_plus;
2571 else
2572 goto normal_backslash;
2574 default:
2575 normal_backslash:
2576 /* You might think it would be useful for \ to mean
2577 not to translate; but if we don't translate it
2578 it will never match anything. */
2579 c = TRANSLATE (c);
2580 goto normal_char;
2582 break;
2585 default:
2586 /* Expects the character in `c'. */
2587 normal_char:
2588 /* If no exactn currently being built. */
2589 if (!pending_exact
2591 /* If last exactn not at current position. */
2592 || pending_exact + *pending_exact + 1 != b
2594 /* We have only one byte following the exactn for the count. */
2595 || *pending_exact == (1 << BYTEWIDTH) - 1
2597 /* If followed by a repetition operator. */
2598 || *p == '*' || *p == '^'
2599 || ((syntax & RE_BK_PLUS_QM)
2600 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2601 : (*p == '+' || *p == '?'))
2602 || ((syntax & RE_INTERVALS)
2603 && ((syntax & RE_NO_BK_BRACES)
2604 ? *p == '{'
2605 : (p[0] == '\\' && p[1] == '{'))))
2607 /* Start building a new exactn. */
2609 laststart = b;
2611 BUF_PUSH_2 (exactn, 0);
2612 pending_exact = b - 1;
2615 BUF_PUSH (c);
2616 (*pending_exact)++;
2617 break;
2618 } /* switch (c) */
2619 } /* while p != pend */
2622 /* Through the pattern now. */
2624 if (fixup_alt_jump)
2625 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2627 if (!COMPILE_STACK_EMPTY)
2628 FREE_STACK_RETURN (REG_EPAREN);
2630 /* If we don't want backtracking, force success
2631 the first time we reach the end of the compiled pattern. */
2632 if (syntax & RE_NO_POSIX_BACKTRACKING)
2633 BUF_PUSH (succeed);
2635 free (compile_stack.stack);
2637 /* We have succeeded; set the length of the buffer. */
2638 bufp->used = b - bufp->buffer;
2640 #ifdef DEBUG
2641 if (debug)
2643 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2644 print_compiled_pattern (bufp);
2646 #endif /* DEBUG */
2648 #ifndef MATCH_MAY_ALLOCATE
2649 /* Initialize the failure stack to the largest possible stack. This
2650 isn't necessary unless we're trying to avoid calling alloca in
2651 the search and match routines. */
2653 int num_regs = bufp->re_nsub + 1;
2655 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
2656 is strictly greater than re_max_failures, the largest possible stack
2657 is 2 * re_max_failures failure points. */
2658 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
2660 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
2662 #ifdef emacs
2663 if (! fail_stack.stack)
2664 fail_stack.stack
2665 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2666 * sizeof (fail_stack_elt_t));
2667 else
2668 fail_stack.stack
2669 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2670 (fail_stack.size
2671 * sizeof (fail_stack_elt_t)));
2672 #else /* not emacs */
2673 if (! fail_stack.stack)
2674 fail_stack.stack
2675 = (fail_stack_elt_t *) malloc (fail_stack.size
2676 * sizeof (fail_stack_elt_t));
2677 else
2678 fail_stack.stack
2679 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2680 (fail_stack.size
2681 * sizeof (fail_stack_elt_t)));
2682 #endif /* not emacs */
2685 regex_grow_registers (num_regs);
2687 #endif /* not MATCH_MAY_ALLOCATE */
2689 return REG_NOERROR;
2690 } /* regex_compile */
2692 /* Subroutines for `regex_compile'. */
2694 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2696 static void
2697 store_op1 (op, loc, arg)
2698 re_opcode_t op;
2699 unsigned char *loc;
2700 int arg;
2702 *loc = (unsigned char) op;
2703 STORE_NUMBER (loc + 1, arg);
2707 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2709 static void
2710 store_op2 (op, loc, arg1, arg2)
2711 re_opcode_t op;
2712 unsigned char *loc;
2713 int arg1, arg2;
2715 *loc = (unsigned char) op;
2716 STORE_NUMBER (loc + 1, arg1);
2717 STORE_NUMBER (loc + 3, arg2);
2721 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2722 for OP followed by two-byte integer parameter ARG. */
2724 static void
2725 insert_op1 (op, loc, arg, end)
2726 re_opcode_t op;
2727 unsigned char *loc;
2728 int arg;
2729 unsigned char *end;
2731 register unsigned char *pfrom = end;
2732 register unsigned char *pto = end + 3;
2734 while (pfrom != loc)
2735 *--pto = *--pfrom;
2737 store_op1 (op, loc, arg);
2741 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2743 static void
2744 insert_op2 (op, loc, arg1, arg2, end)
2745 re_opcode_t op;
2746 unsigned char *loc;
2747 int arg1, arg2;
2748 unsigned char *end;
2750 register unsigned char *pfrom = end;
2751 register unsigned char *pto = end + 5;
2753 while (pfrom != loc)
2754 *--pto = *--pfrom;
2756 store_op2 (op, loc, arg1, arg2);
2760 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2761 after an alternative or a begin-subexpression. We assume there is at
2762 least one character before the ^. */
2764 static boolean
2765 at_begline_loc_p (pattern, p, syntax)
2766 const char *pattern, *p;
2767 reg_syntax_t syntax;
2769 const char *prev = p - 2;
2770 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2772 return
2773 /* After a subexpression? */
2774 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2775 /* After an alternative? */
2776 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2780 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2781 at least one character after the $, i.e., `P < PEND'. */
2783 static boolean
2784 at_endline_loc_p (p, pend, syntax)
2785 const char *p, *pend;
2786 int syntax;
2788 const char *next = p;
2789 boolean next_backslash = *next == '\\';
2790 const char *next_next = p + 1 < pend ? p + 1 : 0;
2792 return
2793 /* Before a subexpression? */
2794 (syntax & RE_NO_BK_PARENS ? *next == ')'
2795 : next_backslash && next_next && *next_next == ')')
2796 /* Before an alternative? */
2797 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2798 : next_backslash && next_next && *next_next == '|');
2802 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2803 false if it's not. */
2805 static boolean
2806 group_in_compile_stack (compile_stack, regnum)
2807 compile_stack_type compile_stack;
2808 regnum_t regnum;
2810 int this_element;
2812 for (this_element = compile_stack.avail - 1;
2813 this_element >= 0;
2814 this_element--)
2815 if (compile_stack.stack[this_element].regnum == regnum)
2816 return true;
2818 return false;
2822 /* Read the ending character of a range (in a bracket expression) from the
2823 uncompiled pattern *P_PTR (which ends at PEND). We assume the
2824 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2825 Then we set the translation of all bits between the starting and
2826 ending characters (inclusive) in the compiled pattern B.
2828 Return an error code.
2830 We use these short variable names so we can use the same macros as
2831 `regex_compile' itself. */
2833 static reg_errcode_t
2834 compile_range (p_ptr, pend, translate, syntax, b)
2835 const char **p_ptr, *pend;
2836 RE_TRANSLATE_TYPE translate;
2837 reg_syntax_t syntax;
2838 unsigned char *b;
2840 unsigned this_char;
2842 const char *p = *p_ptr;
2843 int range_start, range_end;
2845 if (p == pend)
2846 return REG_ERANGE;
2848 /* Even though the pattern is a signed `char *', we need to fetch
2849 with unsigned char *'s; if the high bit of the pattern character
2850 is set, the range endpoints will be negative if we fetch using a
2851 signed char *.
2853 We also want to fetch the endpoints without translating them; the
2854 appropriate translation is done in the bit-setting loop below. */
2855 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
2856 range_start = ((const unsigned char *) p)[-2];
2857 range_end = ((const unsigned char *) p)[0];
2859 /* Have to increment the pointer into the pattern string, so the
2860 caller isn't still at the ending character. */
2861 (*p_ptr)++;
2863 /* If the start is after the end, the range is empty. */
2864 if (range_start > range_end)
2865 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2867 /* Here we see why `this_char' has to be larger than an `unsigned
2868 char' -- the range is inclusive, so if `range_end' == 0xff
2869 (assuming 8-bit characters), we would otherwise go into an infinite
2870 loop, since all characters <= 0xff. */
2871 for (this_char = range_start; this_char <= range_end; this_char++)
2873 SET_LIST_BIT (TRANSLATE (this_char));
2876 return REG_NOERROR;
2879 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2880 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2881 characters can start a string that matches the pattern. This fastmap
2882 is used by re_search to skip quickly over impossible starting points.
2884 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2885 area as BUFP->fastmap.
2887 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2888 the pattern buffer.
2890 Returns 0 if we succeed, -2 if an internal error. */
2893 re_compile_fastmap (bufp)
2894 struct re_pattern_buffer *bufp;
2896 int j, k;
2897 #ifdef MATCH_MAY_ALLOCATE
2898 fail_stack_type fail_stack;
2899 #endif
2900 #ifndef REGEX_MALLOC
2901 char *destination;
2902 #endif
2903 /* We don't push any register information onto the failure stack. */
2904 unsigned num_regs = 0;
2906 register char *fastmap = bufp->fastmap;
2907 unsigned char *pattern = bufp->buffer;
2908 unsigned long size = bufp->used;
2909 unsigned char *p = pattern;
2910 register unsigned char *pend = pattern + size;
2912 /* This holds the pointer to the failure stack, when
2913 it is allocated relocatably. */
2914 fail_stack_elt_t *failure_stack_ptr;
2916 /* Assume that each path through the pattern can be null until
2917 proven otherwise. We set this false at the bottom of switch
2918 statement, to which we get only if a particular path doesn't
2919 match the empty string. */
2920 boolean path_can_be_null = true;
2922 /* We aren't doing a `succeed_n' to begin with. */
2923 boolean succeed_n_p = false;
2925 assert (fastmap != NULL && p != NULL);
2927 INIT_FAIL_STACK ();
2928 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
2929 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2930 bufp->can_be_null = 0;
2932 while (1)
2934 if (p == pend || *p == succeed)
2936 /* We have reached the (effective) end of pattern. */
2937 if (!FAIL_STACK_EMPTY ())
2939 bufp->can_be_null |= path_can_be_null;
2941 /* Reset for next path. */
2942 path_can_be_null = true;
2944 p = fail_stack.stack[--fail_stack.avail].pointer;
2946 continue;
2948 else
2949 break;
2952 /* We should never be about to go beyond the end of the pattern. */
2953 assert (p < pend);
2955 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
2958 /* I guess the idea here is to simply not bother with a fastmap
2959 if a backreference is used, since it's too hard to figure out
2960 the fastmap for the corresponding group. Setting
2961 `can_be_null' stops `re_search_2' from using the fastmap, so
2962 that is all we do. */
2963 case duplicate:
2964 bufp->can_be_null = 1;
2965 goto done;
2968 /* Following are the cases which match a character. These end
2969 with `break'. */
2971 case exactn:
2972 fastmap[p[1]] = 1;
2973 break;
2976 case charset:
2977 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2978 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2979 fastmap[j] = 1;
2980 break;
2983 case charset_not:
2984 /* Chars beyond end of map must be allowed. */
2985 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2986 fastmap[j] = 1;
2988 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2989 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2990 fastmap[j] = 1;
2991 break;
2994 case wordchar:
2995 for (j = 0; j < (1 << BYTEWIDTH); j++)
2996 if (SYNTAX (j) == Sword)
2997 fastmap[j] = 1;
2998 break;
3001 case notwordchar:
3002 for (j = 0; j < (1 << BYTEWIDTH); j++)
3003 if (SYNTAX (j) != Sword)
3004 fastmap[j] = 1;
3005 break;
3008 case anychar:
3010 int fastmap_newline = fastmap['\n'];
3012 /* `.' matches anything ... */
3013 for (j = 0; j < (1 << BYTEWIDTH); j++)
3014 fastmap[j] = 1;
3016 /* ... except perhaps newline. */
3017 if (!(bufp->syntax & RE_DOT_NEWLINE))
3018 fastmap['\n'] = fastmap_newline;
3020 /* Return if we have already set `can_be_null'; if we have,
3021 then the fastmap is irrelevant. Something's wrong here. */
3022 else if (bufp->can_be_null)
3023 goto done;
3025 /* Otherwise, have to check alternative paths. */
3026 break;
3029 #ifdef emacs
3030 case syntaxspec:
3031 k = *p++;
3032 for (j = 0; j < (1 << BYTEWIDTH); j++)
3033 if (SYNTAX (j) == (enum syntaxcode) k)
3034 fastmap[j] = 1;
3035 break;
3038 case notsyntaxspec:
3039 k = *p++;
3040 for (j = 0; j < (1 << BYTEWIDTH); j++)
3041 if (SYNTAX (j) != (enum syntaxcode) k)
3042 fastmap[j] = 1;
3043 break;
3046 /* All cases after this match the empty string. These end with
3047 `continue'. */
3050 case before_dot:
3051 case at_dot:
3052 case after_dot:
3053 continue;
3054 #endif /* emacs */
3057 case no_op:
3058 case begline:
3059 case endline:
3060 case begbuf:
3061 case endbuf:
3062 case wordbound:
3063 case notwordbound:
3064 case wordbeg:
3065 case wordend:
3066 case push_dummy_failure:
3067 continue;
3070 case jump_n:
3071 case pop_failure_jump:
3072 case maybe_pop_jump:
3073 case jump:
3074 case jump_past_alt:
3075 case dummy_failure_jump:
3076 EXTRACT_NUMBER_AND_INCR (j, p);
3077 p += j;
3078 if (j > 0)
3079 continue;
3081 /* Jump backward implies we just went through the body of a
3082 loop and matched nothing. Opcode jumped to should be
3083 `on_failure_jump' or `succeed_n'. Just treat it like an
3084 ordinary jump. For a * loop, it has pushed its failure
3085 point already; if so, discard that as redundant. */
3086 if ((re_opcode_t) *p != on_failure_jump
3087 && (re_opcode_t) *p != succeed_n)
3088 continue;
3090 p++;
3091 EXTRACT_NUMBER_AND_INCR (j, p);
3092 p += j;
3094 /* If what's on the stack is where we are now, pop it. */
3095 if (!FAIL_STACK_EMPTY ()
3096 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3097 fail_stack.avail--;
3099 continue;
3102 case on_failure_jump:
3103 case on_failure_keep_string_jump:
3104 handle_on_failure_jump:
3105 EXTRACT_NUMBER_AND_INCR (j, p);
3107 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3108 end of the pattern. We don't want to push such a point,
3109 since when we restore it above, entering the switch will
3110 increment `p' past the end of the pattern. We don't need
3111 to push such a point since we obviously won't find any more
3112 fastmap entries beyond `pend'. Such a pattern can match
3113 the null string, though. */
3114 if (p + j < pend)
3116 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3118 RESET_FAIL_STACK ();
3119 return -2;
3122 else
3123 bufp->can_be_null = 1;
3125 if (succeed_n_p)
3127 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3128 succeed_n_p = false;
3131 continue;
3134 case succeed_n:
3135 /* Get to the number of times to succeed. */
3136 p += 2;
3138 /* Increment p past the n for when k != 0. */
3139 EXTRACT_NUMBER_AND_INCR (k, p);
3140 if (k == 0)
3142 p -= 4;
3143 succeed_n_p = true; /* Spaghetti code alert. */
3144 goto handle_on_failure_jump;
3146 continue;
3149 case set_number_at:
3150 p += 4;
3151 continue;
3154 case start_memory:
3155 case stop_memory:
3156 p += 2;
3157 continue;
3160 default:
3161 abort (); /* We have listed all the cases. */
3162 } /* switch *p++ */
3164 /* Getting here means we have found the possible starting
3165 characters for one path of the pattern -- and that the empty
3166 string does not match. We need not follow this path further.
3167 Instead, look at the next alternative (remembered on the
3168 stack), or quit if no more. The test at the top of the loop
3169 does these things. */
3170 path_can_be_null = false;
3171 p = pend;
3172 } /* while p */
3174 /* Set `can_be_null' for the last path (also the first path, if the
3175 pattern is empty). */
3176 bufp->can_be_null |= path_can_be_null;
3178 done:
3179 RESET_FAIL_STACK ();
3180 return 0;
3181 } /* re_compile_fastmap */
3183 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3184 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3185 this memory for recording register information. STARTS and ENDS
3186 must be allocated using the malloc library routine, and must each
3187 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3189 If NUM_REGS == 0, then subsequent matches should allocate their own
3190 register data.
3192 Unless this function is called, the first search or match using
3193 PATTERN_BUFFER will allocate its own register data, without
3194 freeing the old data. */
3196 void
3197 re_set_registers (bufp, regs, num_regs, starts, ends)
3198 struct re_pattern_buffer *bufp;
3199 struct re_registers *regs;
3200 unsigned num_regs;
3201 regoff_t *starts, *ends;
3203 if (num_regs)
3205 bufp->regs_allocated = REGS_REALLOCATE;
3206 regs->num_regs = num_regs;
3207 regs->start = starts;
3208 regs->end = ends;
3210 else
3212 bufp->regs_allocated = REGS_UNALLOCATED;
3213 regs->num_regs = 0;
3214 regs->start = regs->end = (regoff_t *) 0;
3218 /* Searching routines. */
3220 /* Like re_search_2, below, but only one string is specified, and
3221 doesn't let you say where to stop matching. */
3224 re_search (bufp, string, size, startpos, range, regs)
3225 struct re_pattern_buffer *bufp;
3226 const char *string;
3227 int size, startpos, range;
3228 struct re_registers *regs;
3230 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3231 regs, size);
3235 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3236 virtual concatenation of STRING1 and STRING2, starting first at index
3237 STARTPOS, then at STARTPOS + 1, and so on.
3239 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3241 RANGE is how far to scan while trying to match. RANGE = 0 means try
3242 only at STARTPOS; in general, the last start tried is STARTPOS +
3243 RANGE.
3245 In REGS, return the indices of the virtual concatenation of STRING1
3246 and STRING2 that matched the entire BUFP->buffer and its contained
3247 subexpressions.
3249 Do not consider matching one past the index STOP in the virtual
3250 concatenation of STRING1 and STRING2.
3252 We return either the position in the strings at which the match was
3253 found, -1 if no match, or -2 if error (such as failure
3254 stack overflow). */
3257 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3258 struct re_pattern_buffer *bufp;
3259 const char *string1, *string2;
3260 int size1, size2;
3261 int startpos;
3262 int range;
3263 struct re_registers *regs;
3264 int stop;
3266 int val;
3267 register char *fastmap = bufp->fastmap;
3268 register RE_TRANSLATE_TYPE translate = bufp->translate;
3269 int total_size = size1 + size2;
3270 int endpos = startpos + range;
3272 /* Check for out-of-range STARTPOS. */
3273 if (startpos < 0 || startpos > total_size)
3274 return -1;
3276 /* Fix up RANGE if it might eventually take us outside
3277 the virtual concatenation of STRING1 and STRING2.
3278 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3279 if (endpos < 0)
3280 range = 0 - startpos;
3281 else if (endpos > total_size)
3282 range = total_size - startpos;
3284 /* If the search isn't to be a backwards one, don't waste time in a
3285 search for a pattern that must be anchored. */
3286 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3288 if (startpos > 0)
3289 return -1;
3290 else
3291 range = 1;
3294 #ifdef emacs
3295 /* In a forward search for something that starts with \=.
3296 don't keep searching past point. */
3297 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3299 range = PT - startpos;
3300 if (range <= 0)
3301 return -1;
3303 #endif /* emacs */
3305 /* Update the fastmap now if not correct already. */
3306 if (fastmap && !bufp->fastmap_accurate)
3307 if (re_compile_fastmap (bufp) == -2)
3308 return -2;
3310 /* Loop through the string, looking for a place to start matching. */
3311 for (;;)
3313 /* If a fastmap is supplied, skip quickly over characters that
3314 cannot be the start of a match. If the pattern can match the
3315 null string, however, we don't need to skip characters; we want
3316 the first null string. */
3317 if (fastmap && startpos < total_size && !bufp->can_be_null)
3319 if (range > 0) /* Searching forwards. */
3321 register const char *d;
3322 register int lim = 0;
3323 int irange = range;
3325 if (startpos < size1 && startpos + range >= size1)
3326 lim = range - (size1 - startpos);
3328 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
3330 /* Written out as an if-else to avoid testing `translate'
3331 inside the loop. */
3332 if (translate)
3333 while (range > lim
3334 && !fastmap[(unsigned char)
3335 translate[(unsigned char) *d++]])
3336 range--;
3337 else
3338 while (range > lim && !fastmap[(unsigned char) *d++])
3339 range--;
3341 startpos += irange - range;
3343 else /* Searching backwards. */
3345 register char c = (size1 == 0 || startpos >= size1
3346 ? string2[startpos - size1]
3347 : string1[startpos]);
3349 if (!fastmap[(unsigned char) TRANSLATE (c)])
3350 goto advance;
3354 /* If can't match the null string, and that's all we have left, fail. */
3355 if (range >= 0 && startpos == total_size && fastmap
3356 && !bufp->can_be_null)
3357 return -1;
3359 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3360 startpos, regs, stop);
3361 #ifndef REGEX_MALLOC
3362 #ifdef C_ALLOCA
3363 alloca (0);
3364 #endif
3365 #endif
3367 if (val >= 0)
3368 return startpos;
3370 if (val == -2)
3371 return -2;
3373 advance:
3374 if (!range)
3375 break;
3376 else if (range > 0)
3378 range--;
3379 startpos++;
3381 else
3383 range++;
3384 startpos--;
3387 return -1;
3388 } /* re_search_2 */
3390 /* Declarations and macros for re_match_2. */
3392 static int bcmp_translate ();
3393 static boolean alt_match_null_string_p (),
3394 common_op_match_null_string_p (),
3395 group_match_null_string_p ();
3397 /* This converts PTR, a pointer into one of the search strings `string1'
3398 and `string2' into an offset from the beginning of that string. */
3399 #define POINTER_TO_OFFSET(ptr) \
3400 (FIRST_STRING_P (ptr) \
3401 ? ((regoff_t) ((ptr) - string1)) \
3402 : ((regoff_t) ((ptr) - string2 + size1)))
3404 /* Macros for dealing with the split strings in re_match_2. */
3406 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3408 /* Call before fetching a character with *d. This switches over to
3409 string2 if necessary. */
3410 #define PREFETCH() \
3411 while (d == dend) \
3413 /* End of string2 => fail. */ \
3414 if (dend == end_match_2) \
3415 goto fail; \
3416 /* End of string1 => advance to string2. */ \
3417 d = string2; \
3418 dend = end_match_2; \
3422 /* Test if at very beginning or at very end of the virtual concatenation
3423 of `string1' and `string2'. If only one string, it's `string2'. */
3424 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3425 #define AT_STRINGS_END(d) ((d) == end2)
3428 /* Test if D points to a character which is word-constituent. We have
3429 two special cases to check for: if past the end of string1, look at
3430 the first character in string2; and if before the beginning of
3431 string2, look at the last character in string1. */
3432 #define WORDCHAR_P(d) \
3433 (SYNTAX ((d) == end1 ? *string2 \
3434 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3435 == Sword)
3437 /* Test if the character before D and the one at D differ with respect
3438 to being word-constituent. */
3439 #define AT_WORD_BOUNDARY(d) \
3440 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3441 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3444 /* Free everything we malloc. */
3445 #ifdef MATCH_MAY_ALLOCATE
3446 #define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
3447 #define FREE_VARIABLES() \
3448 do { \
3449 REGEX_FREE_STACK (fail_stack.stack); \
3450 FREE_VAR (regstart); \
3451 FREE_VAR (regend); \
3452 FREE_VAR (old_regstart); \
3453 FREE_VAR (old_regend); \
3454 FREE_VAR (best_regstart); \
3455 FREE_VAR (best_regend); \
3456 FREE_VAR (reg_info); \
3457 FREE_VAR (reg_dummy); \
3458 FREE_VAR (reg_info_dummy); \
3459 } while (0)
3460 #else
3461 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
3462 #endif /* not MATCH_MAY_ALLOCATE */
3464 /* These values must meet several constraints. They must not be valid
3465 register values; since we have a limit of 255 registers (because
3466 we use only one byte in the pattern for the register number), we can
3467 use numbers larger than 255. They must differ by 1, because of
3468 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3469 be larger than the value for the highest register, so we do not try
3470 to actually save any registers when none are active. */
3471 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3472 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3474 /* Matching routines. */
3476 #ifndef emacs /* Emacs never uses this. */
3477 /* re_match is like re_match_2 except it takes only a single string. */
3480 re_match (bufp, string, size, pos, regs)
3481 struct re_pattern_buffer *bufp;
3482 const char *string;
3483 int size, pos;
3484 struct re_registers *regs;
3486 int result = re_match_2_internal (bufp, NULL, 0, string, size,
3487 pos, regs, size);
3488 alloca (0);
3489 return result;
3491 #endif /* not emacs */
3494 /* re_match_2 matches the compiled pattern in BUFP against the
3495 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3496 and SIZE2, respectively). We start matching at POS, and stop
3497 matching at STOP.
3499 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3500 store offsets for the substring each group matched in REGS. See the
3501 documentation for exactly how many groups we fill.
3503 We return -1 if no match, -2 if an internal error (such as the
3504 failure stack overflowing). Otherwise, we return the length of the
3505 matched substring. */
3508 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3509 struct re_pattern_buffer *bufp;
3510 const char *string1, *string2;
3511 int size1, size2;
3512 int pos;
3513 struct re_registers *regs;
3514 int stop;
3516 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
3517 pos, regs, stop);
3518 alloca (0);
3519 return result;
3522 /* This is a separate function so that we can force an alloca cleanup
3523 afterwards. */
3524 static int
3525 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
3526 struct re_pattern_buffer *bufp;
3527 const char *string1, *string2;
3528 int size1, size2;
3529 int pos;
3530 struct re_registers *regs;
3531 int stop;
3533 /* General temporaries. */
3534 int mcnt;
3535 unsigned char *p1;
3537 /* Just past the end of the corresponding string. */
3538 const char *end1, *end2;
3540 /* Pointers into string1 and string2, just past the last characters in
3541 each to consider matching. */
3542 const char *end_match_1, *end_match_2;
3544 /* Where we are in the data, and the end of the current string. */
3545 const char *d, *dend;
3547 /* Where we are in the pattern, and the end of the pattern. */
3548 unsigned char *p = bufp->buffer;
3549 register unsigned char *pend = p + bufp->used;
3551 /* Mark the opcode just after a start_memory, so we can test for an
3552 empty subpattern when we get to the stop_memory. */
3553 unsigned char *just_past_start_mem = 0;
3555 /* We use this to map every character in the string. */
3556 RE_TRANSLATE_TYPE translate = bufp->translate;
3558 /* Failure point stack. Each place that can handle a failure further
3559 down the line pushes a failure point on this stack. It consists of
3560 restart, regend, and reg_info for all registers corresponding to
3561 the subexpressions we're currently inside, plus the number of such
3562 registers, and, finally, two char *'s. The first char * is where
3563 to resume scanning the pattern; the second one is where to resume
3564 scanning the strings. If the latter is zero, the failure point is
3565 a ``dummy''; if a failure happens and the failure point is a dummy,
3566 it gets discarded and the next next one is tried. */
3567 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3568 fail_stack_type fail_stack;
3569 #endif
3570 #ifdef DEBUG
3571 static unsigned failure_id = 0;
3572 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3573 #endif
3575 /* This holds the pointer to the failure stack, when
3576 it is allocated relocatably. */
3577 fail_stack_elt_t *failure_stack_ptr;
3579 /* We fill all the registers internally, independent of what we
3580 return, for use in backreferences. The number here includes
3581 an element for register zero. */
3582 unsigned num_regs = bufp->re_nsub + 1;
3584 /* The currently active registers. */
3585 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3586 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3588 /* Information on the contents of registers. These are pointers into
3589 the input strings; they record just what was matched (on this
3590 attempt) by a subexpression part of the pattern, that is, the
3591 regnum-th regstart pointer points to where in the pattern we began
3592 matching and the regnum-th regend points to right after where we
3593 stopped matching the regnum-th subexpression. (The zeroth register
3594 keeps track of what the whole pattern matches.) */
3595 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3596 const char **regstart, **regend;
3597 #endif
3599 /* If a group that's operated upon by a repetition operator fails to
3600 match anything, then the register for its start will need to be
3601 restored because it will have been set to wherever in the string we
3602 are when we last see its open-group operator. Similarly for a
3603 register's end. */
3604 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3605 const char **old_regstart, **old_regend;
3606 #endif
3608 /* The is_active field of reg_info helps us keep track of which (possibly
3609 nested) subexpressions we are currently in. The matched_something
3610 field of reg_info[reg_num] helps us tell whether or not we have
3611 matched any of the pattern so far this time through the reg_num-th
3612 subexpression. These two fields get reset each time through any
3613 loop their register is in. */
3614 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3615 register_info_type *reg_info;
3616 #endif
3618 /* The following record the register info as found in the above
3619 variables when we find a match better than any we've seen before.
3620 This happens as we backtrack through the failure points, which in
3621 turn happens only if we have not yet matched the entire string. */
3622 unsigned best_regs_set = false;
3623 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3624 const char **best_regstart, **best_regend;
3625 #endif
3627 /* Logically, this is `best_regend[0]'. But we don't want to have to
3628 allocate space for that if we're not allocating space for anything
3629 else (see below). Also, we never need info about register 0 for
3630 any of the other register vectors, and it seems rather a kludge to
3631 treat `best_regend' differently than the rest. So we keep track of
3632 the end of the best match so far in a separate variable. We
3633 initialize this to NULL so that when we backtrack the first time
3634 and need to test it, it's not garbage. */
3635 const char *match_end = NULL;
3637 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
3638 int set_regs_matched_done = 0;
3640 /* Used when we pop values we don't care about. */
3641 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3642 const char **reg_dummy;
3643 register_info_type *reg_info_dummy;
3644 #endif
3646 #ifdef DEBUG
3647 /* Counts the total number of registers pushed. */
3648 unsigned num_regs_pushed = 0;
3649 #endif
3651 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3653 INIT_FAIL_STACK ();
3655 #ifdef MATCH_MAY_ALLOCATE
3656 /* Do not bother to initialize all the register variables if there are
3657 no groups in the pattern, as it takes a fair amount of time. If
3658 there are groups, we include space for register 0 (the whole
3659 pattern), even though we never use it, since it simplifies the
3660 array indexing. We should fix this. */
3661 if (bufp->re_nsub)
3663 regstart = REGEX_TALLOC (num_regs, const char *);
3664 regend = REGEX_TALLOC (num_regs, const char *);
3665 old_regstart = REGEX_TALLOC (num_regs, const char *);
3666 old_regend = REGEX_TALLOC (num_regs, const char *);
3667 best_regstart = REGEX_TALLOC (num_regs, const char *);
3668 best_regend = REGEX_TALLOC (num_regs, const char *);
3669 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3670 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3671 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3673 if (!(regstart && regend && old_regstart && old_regend && reg_info
3674 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3676 FREE_VARIABLES ();
3677 return -2;
3680 else
3682 /* We must initialize all our variables to NULL, so that
3683 `FREE_VARIABLES' doesn't try to free them. */
3684 regstart = regend = old_regstart = old_regend = best_regstart
3685 = best_regend = reg_dummy = NULL;
3686 reg_info = reg_info_dummy = (register_info_type *) NULL;
3688 #endif /* MATCH_MAY_ALLOCATE */
3690 /* The starting position is bogus. */
3691 if (pos < 0 || pos > size1 + size2)
3693 FREE_VARIABLES ();
3694 return -1;
3697 /* Initialize subexpression text positions to -1 to mark ones that no
3698 start_memory/stop_memory has been seen for. Also initialize the
3699 register information struct. */
3700 for (mcnt = 1; mcnt < num_regs; mcnt++)
3702 regstart[mcnt] = regend[mcnt]
3703 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3705 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3706 IS_ACTIVE (reg_info[mcnt]) = 0;
3707 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3708 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3711 /* We move `string1' into `string2' if the latter's empty -- but not if
3712 `string1' is null. */
3713 if (size2 == 0 && string1 != NULL)
3715 string2 = string1;
3716 size2 = size1;
3717 string1 = 0;
3718 size1 = 0;
3720 end1 = string1 + size1;
3721 end2 = string2 + size2;
3723 /* Compute where to stop matching, within the two strings. */
3724 if (stop <= size1)
3726 end_match_1 = string1 + stop;
3727 end_match_2 = string2;
3729 else
3731 end_match_1 = end1;
3732 end_match_2 = string2 + stop - size1;
3735 /* `p' scans through the pattern as `d' scans through the data.
3736 `dend' is the end of the input string that `d' points within. `d'
3737 is advanced into the following input string whenever necessary, but
3738 this happens before fetching; therefore, at the beginning of the
3739 loop, `d' can be pointing at the end of a string, but it cannot
3740 equal `string2'. */
3741 if (size1 > 0 && pos <= size1)
3743 d = string1 + pos;
3744 dend = end_match_1;
3746 else
3748 d = string2 + pos - size1;
3749 dend = end_match_2;
3752 DEBUG_PRINT1 ("The compiled pattern is: ");
3753 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3754 DEBUG_PRINT1 ("The string to match is: `");
3755 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3756 DEBUG_PRINT1 ("'\n");
3758 /* This loops over pattern commands. It exits by returning from the
3759 function if the match is complete, or it drops through if the match
3760 fails at this starting point in the input data. */
3761 for (;;)
3763 DEBUG_PRINT2 ("\n0x%x: ", p);
3765 if (p == pend)
3766 { /* End of pattern means we might have succeeded. */
3767 DEBUG_PRINT1 ("end of pattern ... ");
3769 /* If we haven't matched the entire string, and we want the
3770 longest match, try backtracking. */
3771 if (d != end_match_2)
3773 /* 1 if this match ends in the same string (string1 or string2)
3774 as the best previous match. */
3775 boolean same_str_p = (FIRST_STRING_P (match_end)
3776 == MATCHING_IN_FIRST_STRING);
3777 /* 1 if this match is the best seen so far. */
3778 boolean best_match_p;
3780 /* AIX compiler got confused when this was combined
3781 with the previous declaration. */
3782 if (same_str_p)
3783 best_match_p = d > match_end;
3784 else
3785 best_match_p = !MATCHING_IN_FIRST_STRING;
3787 DEBUG_PRINT1 ("backtracking.\n");
3789 if (!FAIL_STACK_EMPTY ())
3790 { /* More failure points to try. */
3792 /* If exceeds best match so far, save it. */
3793 if (!best_regs_set || best_match_p)
3795 best_regs_set = true;
3796 match_end = d;
3798 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3800 for (mcnt = 1; mcnt < num_regs; mcnt++)
3802 best_regstart[mcnt] = regstart[mcnt];
3803 best_regend[mcnt] = regend[mcnt];
3806 goto fail;
3809 /* If no failure points, don't restore garbage. And if
3810 last match is real best match, don't restore second
3811 best one. */
3812 else if (best_regs_set && !best_match_p)
3814 restore_best_regs:
3815 /* Restore best match. It may happen that `dend ==
3816 end_match_1' while the restored d is in string2.
3817 For example, the pattern `x.*y.*z' against the
3818 strings `x-' and `y-z-', if the two strings are
3819 not consecutive in memory. */
3820 DEBUG_PRINT1 ("Restoring best registers.\n");
3822 d = match_end;
3823 dend = ((d >= string1 && d <= end1)
3824 ? end_match_1 : end_match_2);
3826 for (mcnt = 1; mcnt < num_regs; mcnt++)
3828 regstart[mcnt] = best_regstart[mcnt];
3829 regend[mcnt] = best_regend[mcnt];
3832 } /* d != end_match_2 */
3834 succeed_label:
3835 DEBUG_PRINT1 ("Accepting match.\n");
3837 /* If caller wants register contents data back, do it. */
3838 if (regs && !bufp->no_sub)
3840 /* Have the register data arrays been allocated? */
3841 if (bufp->regs_allocated == REGS_UNALLOCATED)
3842 { /* No. So allocate them with malloc. We need one
3843 extra element beyond `num_regs' for the `-1' marker
3844 GNU code uses. */
3845 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3846 regs->start = TALLOC (regs->num_regs, regoff_t);
3847 regs->end = TALLOC (regs->num_regs, regoff_t);
3848 if (regs->start == NULL || regs->end == NULL)
3850 FREE_VARIABLES ();
3851 return -2;
3853 bufp->regs_allocated = REGS_REALLOCATE;
3855 else if (bufp->regs_allocated == REGS_REALLOCATE)
3856 { /* Yes. If we need more elements than were already
3857 allocated, reallocate them. If we need fewer, just
3858 leave it alone. */
3859 if (regs->num_regs < num_regs + 1)
3861 regs->num_regs = num_regs + 1;
3862 RETALLOC (regs->start, regs->num_regs, regoff_t);
3863 RETALLOC (regs->end, regs->num_regs, regoff_t);
3864 if (regs->start == NULL || regs->end == NULL)
3866 FREE_VARIABLES ();
3867 return -2;
3871 else
3873 /* These braces fend off a "empty body in an else-statement"
3874 warning under GCC when assert expands to nothing. */
3875 assert (bufp->regs_allocated == REGS_FIXED);
3878 /* Convert the pointer data in `regstart' and `regend' to
3879 indices. Register zero has to be set differently,
3880 since we haven't kept track of any info for it. */
3881 if (regs->num_regs > 0)
3883 regs->start[0] = pos;
3884 regs->end[0] = (MATCHING_IN_FIRST_STRING
3885 ? ((regoff_t) (d - string1))
3886 : ((regoff_t) (d - string2 + size1)));
3889 /* Go through the first `min (num_regs, regs->num_regs)'
3890 registers, since that is all we initialized. */
3891 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
3893 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3894 regs->start[mcnt] = regs->end[mcnt] = -1;
3895 else
3897 regs->start[mcnt]
3898 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
3899 regs->end[mcnt]
3900 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
3904 /* If the regs structure we return has more elements than
3905 were in the pattern, set the extra elements to -1. If
3906 we (re)allocated the registers, this is the case,
3907 because we always allocate enough to have at least one
3908 -1 at the end. */
3909 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3910 regs->start[mcnt] = regs->end[mcnt] = -1;
3911 } /* regs && !bufp->no_sub */
3913 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3914 nfailure_points_pushed, nfailure_points_popped,
3915 nfailure_points_pushed - nfailure_points_popped);
3916 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3918 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3919 ? string1
3920 : string2 - size1);
3922 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3924 FREE_VARIABLES ();
3925 return mcnt;
3928 /* Otherwise match next pattern command. */
3929 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3931 /* Ignore these. Used to ignore the n of succeed_n's which
3932 currently have n == 0. */
3933 case no_op:
3934 DEBUG_PRINT1 ("EXECUTING no_op.\n");
3935 break;
3937 case succeed:
3938 DEBUG_PRINT1 ("EXECUTING succeed.\n");
3939 goto succeed_label;
3941 /* Match the next n pattern characters exactly. The following
3942 byte in the pattern defines n, and the n bytes after that
3943 are the characters to match. */
3944 case exactn:
3945 mcnt = *p++;
3946 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3948 /* This is written out as an if-else so we don't waste time
3949 testing `translate' inside the loop. */
3950 if (translate)
3954 PREFETCH ();
3955 if ((unsigned char) translate[(unsigned char) *d++]
3956 != (unsigned char) *p++)
3957 goto fail;
3959 while (--mcnt);
3961 else
3965 PREFETCH ();
3966 if (*d++ != (char) *p++) goto fail;
3968 while (--mcnt);
3970 SET_REGS_MATCHED ();
3971 break;
3974 /* Match any character except possibly a newline or a null. */
3975 case anychar:
3976 DEBUG_PRINT1 ("EXECUTING anychar.\n");
3978 PREFETCH ();
3980 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
3981 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
3982 goto fail;
3984 SET_REGS_MATCHED ();
3985 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
3986 d++;
3987 break;
3990 case charset:
3991 case charset_not:
3993 register unsigned char c;
3994 boolean not = (re_opcode_t) *(p - 1) == charset_not;
3996 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
3998 PREFETCH ();
3999 c = TRANSLATE (*d); /* The character to match. */
4001 /* Cast to `unsigned' instead of `unsigned char' in case the
4002 bit list is a full 32 bytes long. */
4003 if (c < (unsigned) (*p * BYTEWIDTH)
4004 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4005 not = !not;
4007 p += 1 + *p;
4009 if (!not) goto fail;
4011 SET_REGS_MATCHED ();
4012 d++;
4013 break;
4017 /* The beginning of a group is represented by start_memory.
4018 The arguments are the register number in the next byte, and the
4019 number of groups inner to this one in the next. The text
4020 matched within the group is recorded (in the internal
4021 registers data structure) under the register number. */
4022 case start_memory:
4023 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4025 /* Find out if this group can match the empty string. */
4026 p1 = p; /* To send to group_match_null_string_p. */
4028 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4029 REG_MATCH_NULL_STRING_P (reg_info[*p])
4030 = group_match_null_string_p (&p1, pend, reg_info);
4032 /* Save the position in the string where we were the last time
4033 we were at this open-group operator in case the group is
4034 operated upon by a repetition operator, e.g., with `(a*)*b'
4035 against `ab'; then we want to ignore where we are now in
4036 the string in case this attempt to match fails. */
4037 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4038 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4039 : regstart[*p];
4040 DEBUG_PRINT2 (" old_regstart: %d\n",
4041 POINTER_TO_OFFSET (old_regstart[*p]));
4043 regstart[*p] = d;
4044 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4046 IS_ACTIVE (reg_info[*p]) = 1;
4047 MATCHED_SOMETHING (reg_info[*p]) = 0;
4049 /* Clear this whenever we change the register activity status. */
4050 set_regs_matched_done = 0;
4052 /* This is the new highest active register. */
4053 highest_active_reg = *p;
4055 /* If nothing was active before, this is the new lowest active
4056 register. */
4057 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4058 lowest_active_reg = *p;
4060 /* Move past the register number and inner group count. */
4061 p += 2;
4062 just_past_start_mem = p;
4064 break;
4067 /* The stop_memory opcode represents the end of a group. Its
4068 arguments are the same as start_memory's: the register
4069 number, and the number of inner groups. */
4070 case stop_memory:
4071 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4073 /* We need to save the string position the last time we were at
4074 this close-group operator in case the group is operated
4075 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4076 against `aba'; then we want to ignore where we are now in
4077 the string in case this attempt to match fails. */
4078 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4079 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4080 : regend[*p];
4081 DEBUG_PRINT2 (" old_regend: %d\n",
4082 POINTER_TO_OFFSET (old_regend[*p]));
4084 regend[*p] = d;
4085 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4087 /* This register isn't active anymore. */
4088 IS_ACTIVE (reg_info[*p]) = 0;
4090 /* Clear this whenever we change the register activity status. */
4091 set_regs_matched_done = 0;
4093 /* If this was the only register active, nothing is active
4094 anymore. */
4095 if (lowest_active_reg == highest_active_reg)
4097 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4098 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4100 else
4101 { /* We must scan for the new highest active register, since
4102 it isn't necessarily one less than now: consider
4103 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4104 new highest active register is 1. */
4105 unsigned char r = *p - 1;
4106 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4107 r--;
4109 /* If we end up at register zero, that means that we saved
4110 the registers as the result of an `on_failure_jump', not
4111 a `start_memory', and we jumped to past the innermost
4112 `stop_memory'. For example, in ((.)*) we save
4113 registers 1 and 2 as a result of the *, but when we pop
4114 back to the second ), we are at the stop_memory 1.
4115 Thus, nothing is active. */
4116 if (r == 0)
4118 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4119 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4121 else
4122 highest_active_reg = r;
4125 /* If just failed to match something this time around with a
4126 group that's operated on by a repetition operator, try to
4127 force exit from the ``loop'', and restore the register
4128 information for this group that we had before trying this
4129 last match. */
4130 if ((!MATCHED_SOMETHING (reg_info[*p])
4131 || just_past_start_mem == p - 1)
4132 && (p + 2) < pend)
4134 boolean is_a_jump_n = false;
4136 p1 = p + 2;
4137 mcnt = 0;
4138 switch ((re_opcode_t) *p1++)
4140 case jump_n:
4141 is_a_jump_n = true;
4142 case pop_failure_jump:
4143 case maybe_pop_jump:
4144 case jump:
4145 case dummy_failure_jump:
4146 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4147 if (is_a_jump_n)
4148 p1 += 2;
4149 break;
4151 default:
4152 /* do nothing */ ;
4154 p1 += mcnt;
4156 /* If the next operation is a jump backwards in the pattern
4157 to an on_failure_jump right before the start_memory
4158 corresponding to this stop_memory, exit from the loop
4159 by forcing a failure after pushing on the stack the
4160 on_failure_jump's jump in the pattern, and d. */
4161 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4162 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4164 /* If this group ever matched anything, then restore
4165 what its registers were before trying this last
4166 failed match, e.g., with `(a*)*b' against `ab' for
4167 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4168 against `aba' for regend[3].
4170 Also restore the registers for inner groups for,
4171 e.g., `((a*)(b*))*' against `aba' (register 3 would
4172 otherwise get trashed). */
4174 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4176 unsigned r;
4178 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4180 /* Restore this and inner groups' (if any) registers. */
4181 for (r = *p; r < *p + *(p + 1); r++)
4183 regstart[r] = old_regstart[r];
4185 /* xx why this test? */
4186 if (old_regend[r] >= regstart[r])
4187 regend[r] = old_regend[r];
4190 p1++;
4191 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4192 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4194 goto fail;
4198 /* Move past the register number and the inner group count. */
4199 p += 2;
4200 break;
4203 /* \<digit> has been turned into a `duplicate' command which is
4204 followed by the numeric value of <digit> as the register number. */
4205 case duplicate:
4207 register const char *d2, *dend2;
4208 int regno = *p++; /* Get which register to match against. */
4209 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4211 /* Can't back reference a group which we've never matched. */
4212 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4213 goto fail;
4215 /* Where in input to try to start matching. */
4216 d2 = regstart[regno];
4218 /* Where to stop matching; if both the place to start and
4219 the place to stop matching are in the same string, then
4220 set to the place to stop, otherwise, for now have to use
4221 the end of the first string. */
4223 dend2 = ((FIRST_STRING_P (regstart[regno])
4224 == FIRST_STRING_P (regend[regno]))
4225 ? regend[regno] : end_match_1);
4226 for (;;)
4228 /* If necessary, advance to next segment in register
4229 contents. */
4230 while (d2 == dend2)
4232 if (dend2 == end_match_2) break;
4233 if (dend2 == regend[regno]) break;
4235 /* End of string1 => advance to string2. */
4236 d2 = string2;
4237 dend2 = regend[regno];
4239 /* At end of register contents => success */
4240 if (d2 == dend2) break;
4242 /* If necessary, advance to next segment in data. */
4243 PREFETCH ();
4245 /* How many characters left in this segment to match. */
4246 mcnt = dend - d;
4248 /* Want how many consecutive characters we can match in
4249 one shot, so, if necessary, adjust the count. */
4250 if (mcnt > dend2 - d2)
4251 mcnt = dend2 - d2;
4253 /* Compare that many; failure if mismatch, else move
4254 past them. */
4255 if (translate
4256 ? bcmp_translate (d, d2, mcnt, translate)
4257 : bcmp (d, d2, mcnt))
4258 goto fail;
4259 d += mcnt, d2 += mcnt;
4261 /* Do this because we've match some characters. */
4262 SET_REGS_MATCHED ();
4265 break;
4268 /* begline matches the empty string at the beginning of the string
4269 (unless `not_bol' is set in `bufp'), and, if
4270 `newline_anchor' is set, after newlines. */
4271 case begline:
4272 DEBUG_PRINT1 ("EXECUTING begline.\n");
4274 if (AT_STRINGS_BEG (d))
4276 if (!bufp->not_bol) break;
4278 else if (d[-1] == '\n' && bufp->newline_anchor)
4280 break;
4282 /* In all other cases, we fail. */
4283 goto fail;
4286 /* endline is the dual of begline. */
4287 case endline:
4288 DEBUG_PRINT1 ("EXECUTING endline.\n");
4290 if (AT_STRINGS_END (d))
4292 if (!bufp->not_eol) break;
4295 /* We have to ``prefetch'' the next character. */
4296 else if ((d == end1 ? *string2 : *d) == '\n'
4297 && bufp->newline_anchor)
4299 break;
4301 goto fail;
4304 /* Match at the very beginning of the data. */
4305 case begbuf:
4306 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4307 if (AT_STRINGS_BEG (d))
4308 break;
4309 goto fail;
4312 /* Match at the very end of the data. */
4313 case endbuf:
4314 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4315 if (AT_STRINGS_END (d))
4316 break;
4317 goto fail;
4320 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4321 pushes NULL as the value for the string on the stack. Then
4322 `pop_failure_point' will keep the current value for the
4323 string, instead of restoring it. To see why, consider
4324 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4325 then the . fails against the \n. But the next thing we want
4326 to do is match the \n against the \n; if we restored the
4327 string value, we would be back at the foo.
4329 Because this is used only in specific cases, we don't need to
4330 check all the things that `on_failure_jump' does, to make
4331 sure the right things get saved on the stack. Hence we don't
4332 share its code. The only reason to push anything on the
4333 stack at all is that otherwise we would have to change
4334 `anychar's code to do something besides goto fail in this
4335 case; that seems worse than this. */
4336 case on_failure_keep_string_jump:
4337 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4339 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4340 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4342 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4343 break;
4346 /* Uses of on_failure_jump:
4348 Each alternative starts with an on_failure_jump that points
4349 to the beginning of the next alternative. Each alternative
4350 except the last ends with a jump that in effect jumps past
4351 the rest of the alternatives. (They really jump to the
4352 ending jump of the following alternative, because tensioning
4353 these jumps is a hassle.)
4355 Repeats start with an on_failure_jump that points past both
4356 the repetition text and either the following jump or
4357 pop_failure_jump back to this on_failure_jump. */
4358 case on_failure_jump:
4359 on_failure:
4360 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4362 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4363 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4365 /* If this on_failure_jump comes right before a group (i.e.,
4366 the original * applied to a group), save the information
4367 for that group and all inner ones, so that if we fail back
4368 to this point, the group's information will be correct.
4369 For example, in \(a*\)*\1, we need the preceding group,
4370 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4372 /* We can't use `p' to check ahead because we push
4373 a failure point to `p + mcnt' after we do this. */
4374 p1 = p;
4376 /* We need to skip no_op's before we look for the
4377 start_memory in case this on_failure_jump is happening as
4378 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4379 against aba. */
4380 while (p1 < pend && (re_opcode_t) *p1 == no_op)
4381 p1++;
4383 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
4385 /* We have a new highest active register now. This will
4386 get reset at the start_memory we are about to get to,
4387 but we will have saved all the registers relevant to
4388 this repetition op, as described above. */
4389 highest_active_reg = *(p1 + 1) + *(p1 + 2);
4390 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4391 lowest_active_reg = *(p1 + 1);
4394 DEBUG_PRINT1 (":\n");
4395 PUSH_FAILURE_POINT (p + mcnt, d, -2);
4396 break;
4399 /* A smart repeat ends with `maybe_pop_jump'.
4400 We change it to either `pop_failure_jump' or `jump'. */
4401 case maybe_pop_jump:
4402 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4403 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
4405 register unsigned char *p2 = p;
4407 /* Compare the beginning of the repeat with what in the
4408 pattern follows its end. If we can establish that there
4409 is nothing that they would both match, i.e., that we
4410 would have to backtrack because of (as in, e.g., `a*a')
4411 then we can change to pop_failure_jump, because we'll
4412 never have to backtrack.
4414 This is not true in the case of alternatives: in
4415 `(a|ab)*' we do need to backtrack to the `ab' alternative
4416 (e.g., if the string was `ab'). But instead of trying to
4417 detect that here, the alternative has put on a dummy
4418 failure point which is what we will end up popping. */
4420 /* Skip over open/close-group commands.
4421 If what follows this loop is a ...+ construct,
4422 look at what begins its body, since we will have to
4423 match at least one of that. */
4424 while (1)
4426 if (p2 + 2 < pend
4427 && ((re_opcode_t) *p2 == stop_memory
4428 || (re_opcode_t) *p2 == start_memory))
4429 p2 += 3;
4430 else if (p2 + 6 < pend
4431 && (re_opcode_t) *p2 == dummy_failure_jump)
4432 p2 += 6;
4433 else
4434 break;
4437 p1 = p + mcnt;
4438 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4439 to the `maybe_finalize_jump' of this case. Examine what
4440 follows. */
4442 /* If we're at the end of the pattern, we can change. */
4443 if (p2 == pend)
4445 /* Consider what happens when matching ":\(.*\)"
4446 against ":/". I don't really understand this code
4447 yet. */
4448 p[-3] = (unsigned char) pop_failure_jump;
4449 DEBUG_PRINT1
4450 (" End of pattern: change to `pop_failure_jump'.\n");
4453 else if ((re_opcode_t) *p2 == exactn
4454 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4456 register unsigned char c
4457 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4459 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4461 p[-3] = (unsigned char) pop_failure_jump;
4462 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4463 c, p1[5]);
4466 else if ((re_opcode_t) p1[3] == charset
4467 || (re_opcode_t) p1[3] == charset_not)
4469 int not = (re_opcode_t) p1[3] == charset_not;
4471 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4472 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4473 not = !not;
4475 /* `not' is equal to 1 if c would match, which means
4476 that we can't change to pop_failure_jump. */
4477 if (!not)
4479 p[-3] = (unsigned char) pop_failure_jump;
4480 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4484 else if ((re_opcode_t) *p2 == charset)
4486 #ifdef DEBUG
4487 register unsigned char c
4488 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4489 #endif
4491 if ((re_opcode_t) p1[3] == exactn
4492 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[4]
4493 && (p2[1 + p1[4] / BYTEWIDTH]
4494 & (1 << (p1[4] % BYTEWIDTH)))))
4496 p[-3] = (unsigned char) pop_failure_jump;
4497 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4498 c, p1[5]);
4501 else if ((re_opcode_t) p1[3] == charset_not)
4503 int idx;
4504 /* We win if the charset_not inside the loop
4505 lists every character listed in the charset after. */
4506 for (idx = 0; idx < (int) p2[1]; idx++)
4507 if (! (p2[2 + idx] == 0
4508 || (idx < (int) p1[4]
4509 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
4510 break;
4512 if (idx == p2[1])
4514 p[-3] = (unsigned char) pop_failure_jump;
4515 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4518 else if ((re_opcode_t) p1[3] == charset)
4520 int idx;
4521 /* We win if the charset inside the loop
4522 has no overlap with the one after the loop. */
4523 for (idx = 0;
4524 idx < (int) p2[1] && idx < (int) p1[4];
4525 idx++)
4526 if ((p2[2 + idx] & p1[5 + idx]) != 0)
4527 break;
4529 if (idx == p2[1] || idx == p1[4])
4531 p[-3] = (unsigned char) pop_failure_jump;
4532 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4537 p -= 2; /* Point at relative address again. */
4538 if ((re_opcode_t) p[-1] != pop_failure_jump)
4540 p[-1] = (unsigned char) jump;
4541 DEBUG_PRINT1 (" Match => jump.\n");
4542 goto unconditional_jump;
4544 /* Note fall through. */
4547 /* The end of a simple repeat has a pop_failure_jump back to
4548 its matching on_failure_jump, where the latter will push a
4549 failure point. The pop_failure_jump takes off failure
4550 points put on by this pop_failure_jump's matching
4551 on_failure_jump; we got through the pattern to here from the
4552 matching on_failure_jump, so didn't fail. */
4553 case pop_failure_jump:
4555 /* We need to pass separate storage for the lowest and
4556 highest registers, even though we don't care about the
4557 actual values. Otherwise, we will restore only one
4558 register from the stack, since lowest will == highest in
4559 `pop_failure_point'. */
4560 unsigned dummy_low_reg, dummy_high_reg;
4561 unsigned char *pdummy;
4562 const char *sdummy;
4564 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4565 POP_FAILURE_POINT (sdummy, pdummy,
4566 dummy_low_reg, dummy_high_reg,
4567 reg_dummy, reg_dummy, reg_info_dummy);
4569 /* Note fall through. */
4572 /* Unconditionally jump (without popping any failure points). */
4573 case jump:
4574 unconditional_jump:
4575 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4576 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4577 p += mcnt; /* Do the jump. */
4578 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4579 break;
4582 /* We need this opcode so we can detect where alternatives end
4583 in `group_match_null_string_p' et al. */
4584 case jump_past_alt:
4585 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4586 goto unconditional_jump;
4589 /* Normally, the on_failure_jump pushes a failure point, which
4590 then gets popped at pop_failure_jump. We will end up at
4591 pop_failure_jump, also, and with a pattern of, say, `a+', we
4592 are skipping over the on_failure_jump, so we have to push
4593 something meaningless for pop_failure_jump to pop. */
4594 case dummy_failure_jump:
4595 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4596 /* It doesn't matter what we push for the string here. What
4597 the code at `fail' tests is the value for the pattern. */
4598 PUSH_FAILURE_POINT (0, 0, -2);
4599 goto unconditional_jump;
4602 /* At the end of an alternative, we need to push a dummy failure
4603 point in case we are followed by a `pop_failure_jump', because
4604 we don't want the failure point for the alternative to be
4605 popped. For example, matching `(a|ab)*' against `aab'
4606 requires that we match the `ab' alternative. */
4607 case push_dummy_failure:
4608 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4609 /* See comments just above at `dummy_failure_jump' about the
4610 two zeroes. */
4611 PUSH_FAILURE_POINT (0, 0, -2);
4612 break;
4614 /* Have to succeed matching what follows at least n times.
4615 After that, handle like `on_failure_jump'. */
4616 case succeed_n:
4617 EXTRACT_NUMBER (mcnt, p + 2);
4618 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4620 assert (mcnt >= 0);
4621 /* Originally, this is how many times we HAVE to succeed. */
4622 if (mcnt > 0)
4624 mcnt--;
4625 p += 2;
4626 STORE_NUMBER_AND_INCR (p, mcnt);
4627 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
4629 else if (mcnt == 0)
4631 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4632 p[2] = (unsigned char) no_op;
4633 p[3] = (unsigned char) no_op;
4634 goto on_failure;
4636 break;
4638 case jump_n:
4639 EXTRACT_NUMBER (mcnt, p + 2);
4640 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4642 /* Originally, this is how many times we CAN jump. */
4643 if (mcnt)
4645 mcnt--;
4646 STORE_NUMBER (p + 2, mcnt);
4647 goto unconditional_jump;
4649 /* If don't have to jump any more, skip over the rest of command. */
4650 else
4651 p += 4;
4652 break;
4654 case set_number_at:
4656 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4658 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4659 p1 = p + mcnt;
4660 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4661 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4662 STORE_NUMBER (p1, mcnt);
4663 break;
4666 case wordbound:
4667 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4668 if (AT_WORD_BOUNDARY (d))
4669 break;
4670 goto fail;
4672 case notwordbound:
4673 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4674 if (AT_WORD_BOUNDARY (d))
4675 goto fail;
4676 break;
4678 case wordbeg:
4679 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4680 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4681 break;
4682 goto fail;
4684 case wordend:
4685 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4686 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4687 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4688 break;
4689 goto fail;
4691 #ifdef emacs
4692 case before_dot:
4693 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4694 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4695 goto fail;
4696 break;
4698 case at_dot:
4699 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4700 if (PTR_CHAR_POS ((unsigned char *) d) != point)
4701 goto fail;
4702 break;
4704 case after_dot:
4705 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4706 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
4707 goto fail;
4708 break;
4710 case syntaxspec:
4711 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4712 mcnt = *p++;
4713 goto matchsyntax;
4715 case wordchar:
4716 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4717 mcnt = (int) Sword;
4718 matchsyntax:
4719 PREFETCH ();
4720 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
4721 d++;
4722 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
4723 goto fail;
4724 SET_REGS_MATCHED ();
4725 break;
4727 case notsyntaxspec:
4728 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4729 mcnt = *p++;
4730 goto matchnotsyntax;
4732 case notwordchar:
4733 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4734 mcnt = (int) Sword;
4735 matchnotsyntax:
4736 PREFETCH ();
4737 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
4738 d++;
4739 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
4740 goto fail;
4741 SET_REGS_MATCHED ();
4742 break;
4744 #else /* not emacs */
4745 case wordchar:
4746 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4747 PREFETCH ();
4748 if (!WORDCHAR_P (d))
4749 goto fail;
4750 SET_REGS_MATCHED ();
4751 d++;
4752 break;
4754 case notwordchar:
4755 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4756 PREFETCH ();
4757 if (WORDCHAR_P (d))
4758 goto fail;
4759 SET_REGS_MATCHED ();
4760 d++;
4761 break;
4762 #endif /* not emacs */
4764 default:
4765 abort ();
4767 continue; /* Successfully executed one pattern command; keep going. */
4770 /* We goto here if a matching operation fails. */
4771 fail:
4772 if (!FAIL_STACK_EMPTY ())
4773 { /* A restart point is known. Restore to that state. */
4774 DEBUG_PRINT1 ("\nFAIL:\n");
4775 POP_FAILURE_POINT (d, p,
4776 lowest_active_reg, highest_active_reg,
4777 regstart, regend, reg_info);
4779 /* If this failure point is a dummy, try the next one. */
4780 if (!p)
4781 goto fail;
4783 /* If we failed to the end of the pattern, don't examine *p. */
4784 assert (p <= pend);
4785 if (p < pend)
4787 boolean is_a_jump_n = false;
4789 /* If failed to a backwards jump that's part of a repetition
4790 loop, need to pop this failure point and use the next one. */
4791 switch ((re_opcode_t) *p)
4793 case jump_n:
4794 is_a_jump_n = true;
4795 case maybe_pop_jump:
4796 case pop_failure_jump:
4797 case jump:
4798 p1 = p + 1;
4799 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4800 p1 += mcnt;
4802 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4803 || (!is_a_jump_n
4804 && (re_opcode_t) *p1 == on_failure_jump))
4805 goto fail;
4806 break;
4807 default:
4808 /* do nothing */ ;
4812 if (d >= string1 && d <= end1)
4813 dend = end_match_1;
4815 else
4816 break; /* Matching at this starting point really fails. */
4817 } /* for (;;) */
4819 if (best_regs_set)
4820 goto restore_best_regs;
4822 FREE_VARIABLES ();
4824 return -1; /* Failure to match. */
4825 } /* re_match_2 */
4827 /* Subroutine definitions for re_match_2. */
4830 /* We are passed P pointing to a register number after a start_memory.
4832 Return true if the pattern up to the corresponding stop_memory can
4833 match the empty string, and false otherwise.
4835 If we find the matching stop_memory, sets P to point to one past its number.
4836 Otherwise, sets P to an undefined byte less than or equal to END.
4838 We don't handle duplicates properly (yet). */
4840 static boolean
4841 group_match_null_string_p (p, end, reg_info)
4842 unsigned char **p, *end;
4843 register_info_type *reg_info;
4845 int mcnt;
4846 /* Point to after the args to the start_memory. */
4847 unsigned char *p1 = *p + 2;
4849 while (p1 < end)
4851 /* Skip over opcodes that can match nothing, and return true or
4852 false, as appropriate, when we get to one that can't, or to the
4853 matching stop_memory. */
4855 switch ((re_opcode_t) *p1)
4857 /* Could be either a loop or a series of alternatives. */
4858 case on_failure_jump:
4859 p1++;
4860 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4862 /* If the next operation is not a jump backwards in the
4863 pattern. */
4865 if (mcnt >= 0)
4867 /* Go through the on_failure_jumps of the alternatives,
4868 seeing if any of the alternatives cannot match nothing.
4869 The last alternative starts with only a jump,
4870 whereas the rest start with on_failure_jump and end
4871 with a jump, e.g., here is the pattern for `a|b|c':
4873 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4874 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4875 /exactn/1/c
4877 So, we have to first go through the first (n-1)
4878 alternatives and then deal with the last one separately. */
4881 /* Deal with the first (n-1) alternatives, which start
4882 with an on_failure_jump (see above) that jumps to right
4883 past a jump_past_alt. */
4885 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4887 /* `mcnt' holds how many bytes long the alternative
4888 is, including the ending `jump_past_alt' and
4889 its number. */
4891 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
4892 reg_info))
4893 return false;
4895 /* Move to right after this alternative, including the
4896 jump_past_alt. */
4897 p1 += mcnt;
4899 /* Break if it's the beginning of an n-th alternative
4900 that doesn't begin with an on_failure_jump. */
4901 if ((re_opcode_t) *p1 != on_failure_jump)
4902 break;
4904 /* Still have to check that it's not an n-th
4905 alternative that starts with an on_failure_jump. */
4906 p1++;
4907 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4908 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4910 /* Get to the beginning of the n-th alternative. */
4911 p1 -= 3;
4912 break;
4916 /* Deal with the last alternative: go back and get number
4917 of the `jump_past_alt' just before it. `mcnt' contains
4918 the length of the alternative. */
4919 EXTRACT_NUMBER (mcnt, p1 - 2);
4921 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
4922 return false;
4924 p1 += mcnt; /* Get past the n-th alternative. */
4925 } /* if mcnt > 0 */
4926 break;
4929 case stop_memory:
4930 assert (p1[1] == **p);
4931 *p = p1 + 2;
4932 return true;
4935 default:
4936 if (!common_op_match_null_string_p (&p1, end, reg_info))
4937 return false;
4939 } /* while p1 < end */
4941 return false;
4942 } /* group_match_null_string_p */
4945 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4946 It expects P to be the first byte of a single alternative and END one
4947 byte past the last. The alternative can contain groups. */
4949 static boolean
4950 alt_match_null_string_p (p, end, reg_info)
4951 unsigned char *p, *end;
4952 register_info_type *reg_info;
4954 int mcnt;
4955 unsigned char *p1 = p;
4957 while (p1 < end)
4959 /* Skip over opcodes that can match nothing, and break when we get
4960 to one that can't. */
4962 switch ((re_opcode_t) *p1)
4964 /* It's a loop. */
4965 case on_failure_jump:
4966 p1++;
4967 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4968 p1 += mcnt;
4969 break;
4971 default:
4972 if (!common_op_match_null_string_p (&p1, end, reg_info))
4973 return false;
4975 } /* while p1 < end */
4977 return true;
4978 } /* alt_match_null_string_p */
4981 /* Deals with the ops common to group_match_null_string_p and
4982 alt_match_null_string_p.
4984 Sets P to one after the op and its arguments, if any. */
4986 static boolean
4987 common_op_match_null_string_p (p, end, reg_info)
4988 unsigned char **p, *end;
4989 register_info_type *reg_info;
4991 int mcnt;
4992 boolean ret;
4993 int reg_no;
4994 unsigned char *p1 = *p;
4996 switch ((re_opcode_t) *p1++)
4998 case no_op:
4999 case begline:
5000 case endline:
5001 case begbuf:
5002 case endbuf:
5003 case wordbeg:
5004 case wordend:
5005 case wordbound:
5006 case notwordbound:
5007 #ifdef emacs
5008 case before_dot:
5009 case at_dot:
5010 case after_dot:
5011 #endif
5012 break;
5014 case start_memory:
5015 reg_no = *p1;
5016 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5017 ret = group_match_null_string_p (&p1, end, reg_info);
5019 /* Have to set this here in case we're checking a group which
5020 contains a group and a back reference to it. */
5022 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5023 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5025 if (!ret)
5026 return false;
5027 break;
5029 /* If this is an optimized succeed_n for zero times, make the jump. */
5030 case jump:
5031 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5032 if (mcnt >= 0)
5033 p1 += mcnt;
5034 else
5035 return false;
5036 break;
5038 case succeed_n:
5039 /* Get to the number of times to succeed. */
5040 p1 += 2;
5041 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5043 if (mcnt == 0)
5045 p1 -= 4;
5046 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5047 p1 += mcnt;
5049 else
5050 return false;
5051 break;
5053 case duplicate:
5054 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5055 return false;
5056 break;
5058 case set_number_at:
5059 p1 += 4;
5061 default:
5062 /* All other opcodes mean we cannot match the empty string. */
5063 return false;
5066 *p = p1;
5067 return true;
5068 } /* common_op_match_null_string_p */
5071 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5072 bytes; nonzero otherwise. */
5074 static int
5075 bcmp_translate (s1, s2, len, translate)
5076 unsigned char *s1, *s2;
5077 register int len;
5078 RE_TRANSLATE_TYPE translate;
5080 register unsigned char *p1 = s1, *p2 = s2;
5081 while (len)
5083 if (translate[*p1++] != translate[*p2++]) return 1;
5084 len--;
5086 return 0;
5089 /* Entry points for GNU code. */
5091 /* re_compile_pattern is the GNU regular expression compiler: it
5092 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5093 Returns 0 if the pattern was valid, otherwise an error string.
5095 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5096 are set in BUFP on entry.
5098 We call regex_compile to do the actual compilation. */
5100 const char *
5101 re_compile_pattern (pattern, length, bufp)
5102 const char *pattern;
5103 int length;
5104 struct re_pattern_buffer *bufp;
5106 reg_errcode_t ret;
5108 /* GNU code is written to assume at least RE_NREGS registers will be set
5109 (and at least one extra will be -1). */
5110 bufp->regs_allocated = REGS_UNALLOCATED;
5112 /* And GNU code determines whether or not to get register information
5113 by passing null for the REGS argument to re_match, etc., not by
5114 setting no_sub. */
5115 bufp->no_sub = 0;
5117 /* Match anchors at newline. */
5118 bufp->newline_anchor = 1;
5120 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5122 if (!ret)
5123 return NULL;
5124 return gettext (re_error_msgid[(int) ret]);
5127 /* Entry points compatible with 4.2 BSD regex library. We don't define
5128 them unless specifically requested. */
5130 #ifdef _REGEX_RE_COMP
5132 /* BSD has one and only one pattern buffer. */
5133 static struct re_pattern_buffer re_comp_buf;
5135 char *
5136 re_comp (s)
5137 const char *s;
5139 reg_errcode_t ret;
5141 if (!s)
5143 if (!re_comp_buf.buffer)
5144 return gettext ("No previous regular expression");
5145 return 0;
5148 if (!re_comp_buf.buffer)
5150 re_comp_buf.buffer = (unsigned char *) malloc (200);
5151 if (re_comp_buf.buffer == NULL)
5152 return gettext (re_error_msgid[(int) REG_ESPACE]);
5153 re_comp_buf.allocated = 200;
5155 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5156 if (re_comp_buf.fastmap == NULL)
5157 return gettext (re_error_msgid[(int) REG_ESPACE]);
5160 /* Since `re_exec' always passes NULL for the `regs' argument, we
5161 don't need to initialize the pattern buffer fields which affect it. */
5163 /* Match anchors at newlines. */
5164 re_comp_buf.newline_anchor = 1;
5166 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5168 if (!ret)
5169 return NULL;
5171 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5172 return (char *) gettext (re_error_msgid[(int) ret]);
5177 re_exec (s)
5178 const char *s;
5180 const int len = strlen (s);
5181 return
5182 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5184 #endif /* _REGEX_RE_COMP */
5186 /* POSIX.2 functions. Don't define these for Emacs. */
5188 #ifndef emacs
5190 /* regcomp takes a regular expression as a string and compiles it.
5192 PREG is a regex_t *. We do not expect any fields to be initialized,
5193 since POSIX says we shouldn't. Thus, we set
5195 `buffer' to the compiled pattern;
5196 `used' to the length of the compiled pattern;
5197 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5198 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5199 RE_SYNTAX_POSIX_BASIC;
5200 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5201 `fastmap' and `fastmap_accurate' to zero;
5202 `re_nsub' to the number of subexpressions in PATTERN.
5204 PATTERN is the address of the pattern string.
5206 CFLAGS is a series of bits which affect compilation.
5208 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5209 use POSIX basic syntax.
5211 If REG_NEWLINE is set, then . and [^...] don't match newline.
5212 Also, regexec will try a match beginning after every newline.
5214 If REG_ICASE is set, then we considers upper- and lowercase
5215 versions of letters to be equivalent when matching.
5217 If REG_NOSUB is set, then when PREG is passed to regexec, that
5218 routine will report only success or failure, and nothing about the
5219 registers.
5221 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5222 the return codes and their meanings.) */
5225 regcomp (preg, pattern, cflags)
5226 regex_t *preg;
5227 const char *pattern;
5228 int cflags;
5230 reg_errcode_t ret;
5231 unsigned syntax
5232 = (cflags & REG_EXTENDED) ?
5233 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5235 /* regex_compile will allocate the space for the compiled pattern. */
5236 preg->buffer = 0;
5237 preg->allocated = 0;
5238 preg->used = 0;
5240 /* Don't bother to use a fastmap when searching. This simplifies the
5241 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5242 characters after newlines into the fastmap. This way, we just try
5243 every character. */
5244 preg->fastmap = 0;
5246 if (cflags & REG_ICASE)
5248 unsigned i;
5250 preg->translate
5251 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
5252 * sizeof (*(RE_TRANSLATE_TYPE)0));
5253 if (preg->translate == NULL)
5254 return (int) REG_ESPACE;
5256 /* Map uppercase characters to corresponding lowercase ones. */
5257 for (i = 0; i < CHAR_SET_SIZE; i++)
5258 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5260 else
5261 preg->translate = NULL;
5263 /* If REG_NEWLINE is set, newlines are treated differently. */
5264 if (cflags & REG_NEWLINE)
5265 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5266 syntax &= ~RE_DOT_NEWLINE;
5267 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5268 /* It also changes the matching behavior. */
5269 preg->newline_anchor = 1;
5271 else
5272 preg->newline_anchor = 0;
5274 preg->no_sub = !!(cflags & REG_NOSUB);
5276 /* POSIX says a null character in the pattern terminates it, so we
5277 can use strlen here in compiling the pattern. */
5278 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5280 /* POSIX doesn't distinguish between an unmatched open-group and an
5281 unmatched close-group: both are REG_EPAREN. */
5282 if (ret == REG_ERPAREN) ret = REG_EPAREN;
5284 return (int) ret;
5288 /* regexec searches for a given pattern, specified by PREG, in the
5289 string STRING.
5291 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5292 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5293 least NMATCH elements, and we set them to the offsets of the
5294 corresponding matched substrings.
5296 EFLAGS specifies `execution flags' which affect matching: if
5297 REG_NOTBOL is set, then ^ does not match at the beginning of the
5298 string; if REG_NOTEOL is set, then $ does not match at the end.
5300 We return 0 if we find a match and REG_NOMATCH if not. */
5303 regexec (preg, string, nmatch, pmatch, eflags)
5304 const regex_t *preg;
5305 const char *string;
5306 size_t nmatch;
5307 regmatch_t pmatch[];
5308 int eflags;
5310 int ret;
5311 struct re_registers regs;
5312 regex_t private_preg;
5313 int len = strlen (string);
5314 boolean want_reg_info = !preg->no_sub && nmatch > 0;
5316 private_preg = *preg;
5318 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5319 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5321 /* The user has told us exactly how many registers to return
5322 information about, via `nmatch'. We have to pass that on to the
5323 matching routines. */
5324 private_preg.regs_allocated = REGS_FIXED;
5326 if (want_reg_info)
5328 regs.num_regs = nmatch;
5329 regs.start = TALLOC (nmatch, regoff_t);
5330 regs.end = TALLOC (nmatch, regoff_t);
5331 if (regs.start == NULL || regs.end == NULL)
5332 return (int) REG_NOMATCH;
5335 /* Perform the searching operation. */
5336 ret = re_search (&private_preg, string, len,
5337 /* start: */ 0, /* range: */ len,
5338 want_reg_info ? &regs : (struct re_registers *) 0);
5340 /* Copy the register information to the POSIX structure. */
5341 if (want_reg_info)
5343 if (ret >= 0)
5345 unsigned r;
5347 for (r = 0; r < nmatch; r++)
5349 pmatch[r].rm_so = regs.start[r];
5350 pmatch[r].rm_eo = regs.end[r];
5354 /* If we needed the temporary register info, free the space now. */
5355 free (regs.start);
5356 free (regs.end);
5359 /* We want zero return to mean success, unlike `re_search'. */
5360 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5364 /* Returns a message corresponding to an error code, ERRCODE, returned
5365 from either regcomp or regexec. We don't use PREG here. */
5367 size_t
5368 regerror (errcode, preg, errbuf, errbuf_size)
5369 int errcode;
5370 const regex_t *preg;
5371 char *errbuf;
5372 size_t errbuf_size;
5374 const char *msg;
5375 size_t msg_size;
5377 if (errcode < 0
5378 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
5379 /* Only error codes returned by the rest of the code should be passed
5380 to this routine. If we are given anything else, or if other regex
5381 code generates an invalid error code, then the program has a bug.
5382 Dump core so we can fix it. */
5383 abort ();
5385 msg = gettext (re_error_msgid[errcode]);
5387 msg_size = strlen (msg) + 1; /* Includes the null. */
5389 if (errbuf_size != 0)
5391 if (msg_size > errbuf_size)
5393 strncpy (errbuf, msg, errbuf_size - 1);
5394 errbuf[errbuf_size - 1] = 0;
5396 else
5397 strcpy (errbuf, msg);
5400 return msg_size;
5404 /* Free dynamically allocated space used by PREG. */
5406 void
5407 regfree (preg)
5408 regex_t *preg;
5410 if (preg->buffer != NULL)
5411 free (preg->buffer);
5412 preg->buffer = NULL;
5414 preg->allocated = 0;
5415 preg->used = 0;
5417 if (preg->fastmap != NULL)
5418 free (preg->fastmap);
5419 preg->fastmap = NULL;
5420 preg->fastmap_accurate = 0;
5422 if (preg->translate != NULL)
5423 free (preg->translate);
5424 preg->translate = NULL;
5427 #endif /* not emacs */
5430 Local variables:
5431 make-backup-files: t
5432 version-control: t
5433 trim-versions-without-asking: nil
5434 End: