PARAMS removal.
[deliverable/binutils-gdb.git] / gdb / gnu-regex.c
1 /* *INDENT-OFF* */ /* keep in sync with glibc */
2 /* Extended regular expression matching and search library,
3 version 0.12.
4 (Implements POSIX draft P1003.2/D11.2, except for some of the
5 internationalization features.)
6 Copyright (C) 1993, 94, 95, 96, 97, 98 Free Software Foundation, Inc.
7
8 NOTE: The canonical source of this file is maintained with the
9 GNU C Library. Bugs can be reported to bug-glibc@gnu.org.
10
11 This program is free software; you can redistribute it and/or modify it
12 under the terms of the GNU General Public License as published by the
13 Free Software Foundation; either version 2, or (at your option) any
14 later version.
15
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software Foundation,
23 Inc., 59 Temple Place - Suite 330,
24 Boston, MA 02111-1307, USA. */
25
26 /* AIX requires this to be the first thing in the file. */
27 #if defined _AIX && !defined REGEX_MALLOC
28 #pragma alloca
29 #endif
30
31 #undef _GNU_SOURCE
32 #define _GNU_SOURCE
33
34 #ifdef HAVE_CONFIG_H
35 # include <config.h>
36 #endif
37
38 #ifndef PARAMS
39 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
40 # define PARAMS(args) args
41 # else
42 # define PARAMS(args) ()
43 # endif /* GCC. */
44 #endif /* Not PARAMS. */
45
46 #if defined STDC_HEADERS && !defined emacs
47 # include <stddef.h>
48 #else
49 /* We need this for `gnu-regex.h', and perhaps for the Emacs include files. */
50 # include <sys/types.h>
51 #endif
52
53 /* For platform which support the ISO C amendement 1 functionality we
54 support user defined character classes. */
55 #if defined _LIBC || (defined HAVE_WCTYPE_H && defined HAVE_WCHAR_H)
56 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
57 # include <wchar.h>
58 # include <wctype.h>
59 #endif
60
61 /* This is for other GNU distributions with internationalized messages. */
62 /* CYGNUS LOCAL: ../intl will handle this for us */
63 #ifdef ENABLE_NLS
64 # include <libintl.h>
65 #else
66 # define gettext(msgid) (msgid)
67 #endif
68
69 #ifndef gettext_noop
70 /* This define is so xgettext can find the internationalizable
71 strings. */
72 # define gettext_noop(String) String
73 #endif
74
75 /* The `emacs' switch turns on certain matching commands
76 that make sense only in Emacs. */
77 #ifdef emacs
78
79 # include "lisp.h"
80 # include "buffer.h"
81 # include "syntax.h"
82
83 #else /* not emacs */
84
85 /* If we are not linking with Emacs proper,
86 we can't use the relocating allocator
87 even if config.h says that we can. */
88 # undef REL_ALLOC
89
90 # if defined STDC_HEADERS || defined _LIBC
91 # include <stdlib.h>
92 # else
93 char *malloc ();
94 char *realloc ();
95 # endif
96
97 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
98 If nothing else has been done, use the method below. */
99 # ifdef INHIBIT_STRING_HEADER
100 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
101 # if !defined bzero && !defined bcopy
102 # undef INHIBIT_STRING_HEADER
103 # endif
104 # endif
105 # endif
106
107 /* This is the normal way of making sure we have a bcopy and a bzero.
108 This is used in most programs--a few other programs avoid this
109 by defining INHIBIT_STRING_HEADER. */
110 # ifndef INHIBIT_STRING_HEADER
111 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
112 # include <string.h>
113 # ifndef bzero
114 # ifndef _LIBC
115 # define bzero(s, n) (memset (s, '\0', n), (s))
116 # else
117 # define bzero(s, n) __bzero (s, n)
118 # endif
119 # endif
120 # else
121 # include <strings.h>
122 # ifndef memcmp
123 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
124 # endif
125 # ifndef memcpy
126 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
127 # endif
128 # endif
129 # endif
130
131 /* Define the syntax stuff for \<, \>, etc. */
132
133 /* This must be nonzero for the wordchar and notwordchar pattern
134 commands in re_match_2. */
135 # ifndef Sword
136 # define Sword 1
137 # endif
138
139 # ifdef SWITCH_ENUM_BUG
140 # define SWITCH_ENUM_CAST(x) ((int)(x))
141 # else
142 # define SWITCH_ENUM_CAST(x) (x)
143 # endif
144
145 /* How many characters in the character set. */
146 # define CHAR_SET_SIZE 256
147
148 /* GDB LOCAL: define _REGEX_RE_COMP to get BSD style re_comp and re_exec */
149 #ifndef _REGEX_RE_COMP
150 #define _REGEX_RE_COMP
151 #endif
152
153 # ifdef SYNTAX_TABLE
154
155 extern char *re_syntax_table;
156
157 # else /* not SYNTAX_TABLE */
158
159 static char re_syntax_table[CHAR_SET_SIZE];
160
161 static void
162 init_syntax_once ()
163 {
164 register int c;
165 static int done = 0;
166
167 if (done)
168 return;
169
170 bzero (re_syntax_table, sizeof re_syntax_table);
171
172 for (c = 'a'; c <= 'z'; c++)
173 re_syntax_table[c] = Sword;
174
175 for (c = 'A'; c <= 'Z'; c++)
176 re_syntax_table[c] = Sword;
177
178 for (c = '0'; c <= '9'; c++)
179 re_syntax_table[c] = Sword;
180
181 re_syntax_table['_'] = Sword;
182
183 done = 1;
184 }
185
186 # endif /* not SYNTAX_TABLE */
187
188 # define SYNTAX(c) re_syntax_table[c]
189
190 #endif /* not emacs */
191 \f
192 /* Get the interface, including the syntax bits. */
193 /* CYGNUS LOCAL: call it gnu-regex.h, not regex.h, to avoid name conflicts */
194 #include "gnu-regex.h"
195
196 /* isalpha etc. are used for the character classes. */
197 #include <ctype.h>
198
199 /* Jim Meyering writes:
200
201 "... Some ctype macros are valid only for character codes that
202 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
203 using /bin/cc or gcc but without giving an ansi option). So, all
204 ctype uses should be through macros like ISPRINT... If
205 STDC_HEADERS is defined, then autoconf has verified that the ctype
206 macros don't need to be guarded with references to isascii. ...
207 Defining isascii to 1 should let any compiler worth its salt
208 eliminate the && through constant folding."
209 Solaris defines some of these symbols so we must undefine them first. */
210
211 #undef ISASCII
212 #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
213 # define ISASCII(c) 1
214 #else
215 # define ISASCII(c) isascii(c)
216 #endif
217
218 #ifdef isblank
219 # define ISBLANK(c) (ISASCII (c) && isblank (c))
220 #else
221 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
222 #endif
223 #ifdef isgraph
224 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
225 #else
226 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
227 #endif
228
229 #undef ISPRINT
230 #define ISPRINT(c) (ISASCII (c) && isprint (c))
231 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
232 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
233 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
234 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
235 #define ISLOWER(c) (ISASCII (c) && islower (c))
236 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
237 #define ISSPACE(c) (ISASCII (c) && isspace (c))
238 #define ISUPPER(c) (ISASCII (c) && isupper (c))
239 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
240
241 #ifndef NULL
242 # define NULL (void *)0
243 #endif
244
245 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
246 since ours (we hope) works properly with all combinations of
247 machines, compilers, `char' and `unsigned char' argument types.
248 (Per Bothner suggested the basic approach.) */
249 #undef SIGN_EXTEND_CHAR
250 #if __STDC__
251 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
252 #else /* not __STDC__ */
253 /* As in Harbison and Steele. */
254 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
255 #endif
256 \f
257 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
258 use `alloca' instead of `malloc'. This is because using malloc in
259 re_search* or re_match* could cause memory leaks when C-g is used in
260 Emacs; also, malloc is slower and causes storage fragmentation. On
261 the other hand, malloc is more portable, and easier to debug.
262
263 Because we sometimes use alloca, some routines have to be macros,
264 not functions -- `alloca'-allocated space disappears at the end of the
265 function it is called in. */
266
267 #ifdef REGEX_MALLOC
268
269 # define REGEX_ALLOCATE malloc
270 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
271 # define REGEX_FREE free
272
273 #else /* not REGEX_MALLOC */
274
275 /* Emacs already defines alloca, sometimes. */
276 # ifndef alloca
277
278 /* Make alloca work the best possible way. */
279 # ifdef __GNUC__
280 # define alloca __builtin_alloca
281 # else /* not __GNUC__ */
282 # if HAVE_ALLOCA_H
283 # include <alloca.h>
284 # endif /* HAVE_ALLOCA_H */
285 # endif /* not __GNUC__ */
286
287 # endif /* not alloca */
288
289 # define REGEX_ALLOCATE alloca
290
291 /* Assumes a `char *destination' variable. */
292 # define REGEX_REALLOCATE(source, osize, nsize) \
293 (destination = (char *) alloca (nsize), \
294 memcpy (destination, source, osize))
295
296 /* No need to do anything to free, after alloca. */
297 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
298
299 #endif /* not REGEX_MALLOC */
300
301 /* Define how to allocate the failure stack. */
302
303 #if defined REL_ALLOC && defined REGEX_MALLOC
304
305 # define REGEX_ALLOCATE_STACK(size) \
306 r_alloc (&failure_stack_ptr, (size))
307 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
308 r_re_alloc (&failure_stack_ptr, (nsize))
309 # define REGEX_FREE_STACK(ptr) \
310 r_alloc_free (&failure_stack_ptr)
311
312 #else /* not using relocating allocator */
313
314 # ifdef REGEX_MALLOC
315
316 # define REGEX_ALLOCATE_STACK malloc
317 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
318 # define REGEX_FREE_STACK free
319
320 # else /* not REGEX_MALLOC */
321
322 # define REGEX_ALLOCATE_STACK alloca
323
324 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
325 REGEX_REALLOCATE (source, osize, nsize)
326 /* No need to explicitly free anything. */
327 # define REGEX_FREE_STACK(arg)
328
329 # endif /* not REGEX_MALLOC */
330 #endif /* not using relocating allocator */
331
332
333 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
334 `string1' or just past its end. This works if PTR is NULL, which is
335 a good thing. */
336 #define FIRST_STRING_P(ptr) \
337 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
338
339 /* (Re)Allocate N items of type T using malloc, or fail. */
340 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
341 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
342 #define RETALLOC_IF(addr, n, t) \
343 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
344 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
345
346 #define BYTEWIDTH 8 /* In bits. */
347
348 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
349
350 #undef MAX
351 #undef MIN
352 #define MAX(a, b) ((a) > (b) ? (a) : (b))
353 #define MIN(a, b) ((a) < (b) ? (a) : (b))
354
355 typedef char boolean;
356 #define false 0
357 #define true 1
358
359 static int re_match_2_internal (struct re_pattern_buffer *bufp,
360 const char *string1, int size1,
361 const char *string2, int size2,
362 int pos, struct re_registers *regs, int stop);
363 \f
364 /* These are the command codes that appear in compiled regular
365 expressions. Some opcodes are followed by argument bytes. A
366 command code can specify any interpretation whatsoever for its
367 arguments. Zero bytes may appear in the compiled regular expression. */
368
369 typedef enum
370 {
371 no_op = 0,
372
373 /* Succeed right away--no more backtracking. */
374 succeed,
375
376 /* Followed by one byte giving n, then by n literal bytes. */
377 exactn,
378
379 /* Matches any (more or less) character. */
380 anychar,
381
382 /* Matches any one char belonging to specified set. First
383 following byte is number of bitmap bytes. Then come bytes
384 for a bitmap saying which chars are in. Bits in each byte
385 are ordered low-bit-first. A character is in the set if its
386 bit is 1. A character too large to have a bit in the map is
387 automatically not in the set. */
388 charset,
389
390 /* Same parameters as charset, but match any character that is
391 not one of those specified. */
392 charset_not,
393
394 /* Start remembering the text that is matched, for storing in a
395 register. Followed by one byte with the register number, in
396 the range 0 to one less than the pattern buffer's re_nsub
397 field. Then followed by one byte with the number of groups
398 inner to this one. (This last has to be part of the
399 start_memory only because we need it in the on_failure_jump
400 of re_match_2.) */
401 start_memory,
402
403 /* Stop remembering the text that is matched and store it in a
404 memory register. Followed by one byte with the register
405 number, in the range 0 to one less than `re_nsub' in the
406 pattern buffer, and one byte with the number of inner groups,
407 just like `start_memory'. (We need the number of inner
408 groups here because we don't have any easy way of finding the
409 corresponding start_memory when we're at a stop_memory.) */
410 stop_memory,
411
412 /* Match a duplicate of something remembered. Followed by one
413 byte containing the register number. */
414 duplicate,
415
416 /* Fail unless at beginning of line. */
417 begline,
418
419 /* Fail unless at end of line. */
420 endline,
421
422 /* Succeeds if at beginning of buffer (if emacs) or at beginning
423 of string to be matched (if not). */
424 begbuf,
425
426 /* Analogously, for end of buffer/string. */
427 endbuf,
428
429 /* Followed by two byte relative address to which to jump. */
430 jump,
431
432 /* Same as jump, but marks the end of an alternative. */
433 jump_past_alt,
434
435 /* Followed by two-byte relative address of place to resume at
436 in case of failure. */
437 on_failure_jump,
438
439 /* Like on_failure_jump, but pushes a placeholder instead of the
440 current string position when executed. */
441 on_failure_keep_string_jump,
442
443 /* Throw away latest failure point and then jump to following
444 two-byte relative address. */
445 pop_failure_jump,
446
447 /* Change to pop_failure_jump if know won't have to backtrack to
448 match; otherwise change to jump. This is used to jump
449 back to the beginning of a repeat. If what follows this jump
450 clearly won't match what the repeat does, such that we can be
451 sure that there is no use backtracking out of repetitions
452 already matched, then we change it to a pop_failure_jump.
453 Followed by two-byte address. */
454 maybe_pop_jump,
455
456 /* Jump to following two-byte address, and push a dummy failure
457 point. This failure point will be thrown away if an attempt
458 is made to use it for a failure. A `+' construct makes this
459 before the first repeat. Also used as an intermediary kind
460 of jump when compiling an alternative. */
461 dummy_failure_jump,
462
463 /* Push a dummy failure point and continue. Used at the end of
464 alternatives. */
465 push_dummy_failure,
466
467 /* Followed by two-byte relative address and two-byte number n.
468 After matching N times, jump to the address upon failure. */
469 succeed_n,
470
471 /* Followed by two-byte relative address, and two-byte number n.
472 Jump to the address N times, then fail. */
473 jump_n,
474
475 /* Set the following two-byte relative address to the
476 subsequent two-byte number. The address *includes* the two
477 bytes of number. */
478 set_number_at,
479
480 wordchar, /* Matches any word-constituent character. */
481 notwordchar, /* Matches any char that is not a word-constituent. */
482
483 wordbeg, /* Succeeds if at word beginning. */
484 wordend, /* Succeeds if at word end. */
485
486 wordbound, /* Succeeds if at a word boundary. */
487 notwordbound /* Succeeds if not at a word boundary. */
488
489 #ifdef emacs
490 ,before_dot, /* Succeeds if before point. */
491 at_dot, /* Succeeds if at point. */
492 after_dot, /* Succeeds if after point. */
493
494 /* Matches any character whose syntax is specified. Followed by
495 a byte which contains a syntax code, e.g., Sword. */
496 syntaxspec,
497
498 /* Matches any character whose syntax is not that specified. */
499 notsyntaxspec
500 #endif /* emacs */
501 } re_opcode_t;
502 \f
503 /* Common operations on the compiled pattern. */
504
505 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
506
507 #define STORE_NUMBER(destination, number) \
508 do { \
509 (destination)[0] = (number) & 0377; \
510 (destination)[1] = (number) >> 8; \
511 } while (0)
512
513 /* Same as STORE_NUMBER, except increment DESTINATION to
514 the byte after where the number is stored. Therefore, DESTINATION
515 must be an lvalue. */
516
517 #define STORE_NUMBER_AND_INCR(destination, number) \
518 do { \
519 STORE_NUMBER (destination, number); \
520 (destination) += 2; \
521 } while (0)
522
523 /* Put into DESTINATION a number stored in two contiguous bytes starting
524 at SOURCE. */
525
526 #define EXTRACT_NUMBER(destination, source) \
527 do { \
528 (destination) = *(source) & 0377; \
529 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
530 } while (0)
531
532 #ifdef DEBUG
533 static void extract_number _RE_ARGS ((int *dest, unsigned char *source));
534 static void
535 extract_number (dest, source)
536 int *dest;
537 unsigned char *source;
538 {
539 int temp = SIGN_EXTEND_CHAR (*(source + 1));
540 *dest = *source & 0377;
541 *dest += temp << 8;
542 }
543
544 # ifndef EXTRACT_MACROS /* To debug the macros. */
545 # undef EXTRACT_NUMBER
546 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
547 # endif /* not EXTRACT_MACROS */
548
549 #endif /* DEBUG */
550
551 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
552 SOURCE must be an lvalue. */
553
554 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
555 do { \
556 EXTRACT_NUMBER (destination, source); \
557 (source) += 2; \
558 } while (0)
559
560 #ifdef DEBUG
561 static void extract_number_and_incr _RE_ARGS ((int *destination,
562 unsigned char **source));
563 static void
564 extract_number_and_incr (destination, source)
565 int *destination;
566 unsigned char **source;
567 {
568 extract_number (destination, *source);
569 *source += 2;
570 }
571
572 # ifndef EXTRACT_MACROS
573 # undef EXTRACT_NUMBER_AND_INCR
574 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
575 extract_number_and_incr (&dest, &src)
576 # endif /* not EXTRACT_MACROS */
577
578 #endif /* DEBUG */
579 \f
580 /* If DEBUG is defined, Regex prints many voluminous messages about what
581 it is doing (if the variable `debug' is nonzero). If linked with the
582 main program in `iregex.c', you can enter patterns and strings
583 interactively. And if linked with the main program in `main.c' and
584 the other test files, you can run the already-written tests. */
585
586 #ifdef DEBUG
587
588 /* We use standard I/O for debugging. */
589 # include <stdio.h>
590
591 /* It is useful to test things that ``must'' be true when debugging. */
592 # include <assert.h>
593
594 static int debug = 0;
595
596 # define DEBUG_STATEMENT(e) e
597 # define DEBUG_PRINT1(x) if (debug) printf (x)
598 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
599 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
600 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
601 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
602 if (debug) print_partial_compiled_pattern (s, e)
603 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
604 if (debug) print_double_string (w, s1, sz1, s2, sz2)
605
606
607 /* Print the fastmap in human-readable form. */
608
609 void
610 print_fastmap (fastmap)
611 char *fastmap;
612 {
613 unsigned was_a_range = 0;
614 unsigned i = 0;
615
616 while (i < (1 << BYTEWIDTH))
617 {
618 if (fastmap[i++])
619 {
620 was_a_range = 0;
621 putchar (i - 1);
622 while (i < (1 << BYTEWIDTH) && fastmap[i])
623 {
624 was_a_range = 1;
625 i++;
626 }
627 if (was_a_range)
628 {
629 printf ("-");
630 putchar (i - 1);
631 }
632 }
633 }
634 putchar ('\n');
635 }
636
637
638 /* Print a compiled pattern string in human-readable form, starting at
639 the START pointer into it and ending just before the pointer END. */
640
641 void
642 print_partial_compiled_pattern (start, end)
643 unsigned char *start;
644 unsigned char *end;
645 {
646 int mcnt, mcnt2;
647 unsigned char *p1;
648 unsigned char *p = start;
649 unsigned char *pend = end;
650
651 if (start == NULL)
652 {
653 printf ("(null)\n");
654 return;
655 }
656
657 /* Loop over pattern commands. */
658 while (p < pend)
659 {
660 printf ("%d:\t", p - start);
661
662 switch ((re_opcode_t) *p++)
663 {
664 case no_op:
665 printf ("/no_op");
666 break;
667
668 case exactn:
669 mcnt = *p++;
670 printf ("/exactn/%d", mcnt);
671 do
672 {
673 putchar ('/');
674 putchar (*p++);
675 }
676 while (--mcnt);
677 break;
678
679 case start_memory:
680 mcnt = *p++;
681 printf ("/start_memory/%d/%d", mcnt, *p++);
682 break;
683
684 case stop_memory:
685 mcnt = *p++;
686 printf ("/stop_memory/%d/%d", mcnt, *p++);
687 break;
688
689 case duplicate:
690 printf ("/duplicate/%d", *p++);
691 break;
692
693 case anychar:
694 printf ("/anychar");
695 break;
696
697 case charset:
698 case charset_not:
699 {
700 register int c, last = -100;
701 register int in_range = 0;
702
703 printf ("/charset [%s",
704 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
705
706 assert (p + *p < pend);
707
708 for (c = 0; c < 256; c++)
709 if (c / 8 < *p
710 && (p[1 + (c/8)] & (1 << (c % 8))))
711 {
712 /* Are we starting a range? */
713 if (last + 1 == c && ! in_range)
714 {
715 putchar ('-');
716 in_range = 1;
717 }
718 /* Have we broken a range? */
719 else if (last + 1 != c && in_range)
720 {
721 putchar (last);
722 in_range = 0;
723 }
724
725 if (! in_range)
726 putchar (c);
727
728 last = c;
729 }
730
731 if (in_range)
732 putchar (last);
733
734 putchar (']');
735
736 p += 1 + *p;
737 }
738 break;
739
740 case begline:
741 printf ("/begline");
742 break;
743
744 case endline:
745 printf ("/endline");
746 break;
747
748 case on_failure_jump:
749 extract_number_and_incr (&mcnt, &p);
750 printf ("/on_failure_jump to %d", p + mcnt - start);
751 break;
752
753 case on_failure_keep_string_jump:
754 extract_number_and_incr (&mcnt, &p);
755 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
756 break;
757
758 case dummy_failure_jump:
759 extract_number_and_incr (&mcnt, &p);
760 printf ("/dummy_failure_jump to %d", p + mcnt - start);
761 break;
762
763 case push_dummy_failure:
764 printf ("/push_dummy_failure");
765 break;
766
767 case maybe_pop_jump:
768 extract_number_and_incr (&mcnt, &p);
769 printf ("/maybe_pop_jump to %d", p + mcnt - start);
770 break;
771
772 case pop_failure_jump:
773 extract_number_and_incr (&mcnt, &p);
774 printf ("/pop_failure_jump to %d", p + mcnt - start);
775 break;
776
777 case jump_past_alt:
778 extract_number_and_incr (&mcnt, &p);
779 printf ("/jump_past_alt to %d", p + mcnt - start);
780 break;
781
782 case jump:
783 extract_number_and_incr (&mcnt, &p);
784 printf ("/jump to %d", p + mcnt - start);
785 break;
786
787 case succeed_n:
788 extract_number_and_incr (&mcnt, &p);
789 p1 = p + mcnt;
790 extract_number_and_incr (&mcnt2, &p);
791 printf ("/succeed_n to %d, %d times", p1 - start, mcnt2);
792 break;
793
794 case jump_n:
795 extract_number_and_incr (&mcnt, &p);
796 p1 = p + mcnt;
797 extract_number_and_incr (&mcnt2, &p);
798 printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
799 break;
800
801 case set_number_at:
802 extract_number_and_incr (&mcnt, &p);
803 p1 = p + mcnt;
804 extract_number_and_incr (&mcnt2, &p);
805 printf ("/set_number_at location %d to %d", p1 - start, mcnt2);
806 break;
807
808 case wordbound:
809 printf ("/wordbound");
810 break;
811
812 case notwordbound:
813 printf ("/notwordbound");
814 break;
815
816 case wordbeg:
817 printf ("/wordbeg");
818 break;
819
820 case wordend:
821 printf ("/wordend");
822
823 # ifdef emacs
824 case before_dot:
825 printf ("/before_dot");
826 break;
827
828 case at_dot:
829 printf ("/at_dot");
830 break;
831
832 case after_dot:
833 printf ("/after_dot");
834 break;
835
836 case syntaxspec:
837 printf ("/syntaxspec");
838 mcnt = *p++;
839 printf ("/%d", mcnt);
840 break;
841
842 case notsyntaxspec:
843 printf ("/notsyntaxspec");
844 mcnt = *p++;
845 printf ("/%d", mcnt);
846 break;
847 # endif /* emacs */
848
849 case wordchar:
850 printf ("/wordchar");
851 break;
852
853 case notwordchar:
854 printf ("/notwordchar");
855 break;
856
857 case begbuf:
858 printf ("/begbuf");
859 break;
860
861 case endbuf:
862 printf ("/endbuf");
863 break;
864
865 default:
866 printf ("?%d", *(p-1));
867 }
868
869 putchar ('\n');
870 }
871
872 printf ("%d:\tend of pattern.\n", p - start);
873 }
874
875
876 void
877 print_compiled_pattern (bufp)
878 struct re_pattern_buffer *bufp;
879 {
880 unsigned char *buffer = bufp->buffer;
881
882 print_partial_compiled_pattern (buffer, buffer + bufp->used);
883 printf ("%ld bytes used/%ld bytes allocated.\n",
884 bufp->used, bufp->allocated);
885
886 if (bufp->fastmap_accurate && bufp->fastmap)
887 {
888 printf ("fastmap: ");
889 print_fastmap (bufp->fastmap);
890 }
891
892 printf ("re_nsub: %d\t", bufp->re_nsub);
893 printf ("regs_alloc: %d\t", bufp->regs_allocated);
894 printf ("can_be_null: %d\t", bufp->can_be_null);
895 printf ("newline_anchor: %d\n", bufp->newline_anchor);
896 printf ("no_sub: %d\t", bufp->no_sub);
897 printf ("not_bol: %d\t", bufp->not_bol);
898 printf ("not_eol: %d\t", bufp->not_eol);
899 printf ("syntax: %lx\n", bufp->syntax);
900 /* Perhaps we should print the translate table? */
901 }
902
903
904 void
905 print_double_string (where, string1, size1, string2, size2)
906 const char *where;
907 const char *string1;
908 const char *string2;
909 int size1;
910 int size2;
911 {
912 int this_char;
913
914 if (where == NULL)
915 printf ("(null)");
916 else
917 {
918 if (FIRST_STRING_P (where))
919 {
920 for (this_char = where - string1; this_char < size1; this_char++)
921 putchar (string1[this_char]);
922
923 where = string2;
924 }
925
926 for (this_char = where - string2; this_char < size2; this_char++)
927 putchar (string2[this_char]);
928 }
929 }
930
931 void
932 printchar (c)
933 int c;
934 {
935 putc (c, stderr);
936 }
937
938 #else /* not DEBUG */
939
940 # undef assert
941 # define assert(e)
942
943 # define DEBUG_STATEMENT(e)
944 # define DEBUG_PRINT1(x)
945 # define DEBUG_PRINT2(x1, x2)
946 # define DEBUG_PRINT3(x1, x2, x3)
947 # define DEBUG_PRINT4(x1, x2, x3, x4)
948 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
949 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
950
951 #endif /* not DEBUG */
952 \f
953 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
954 also be assigned to arbitrarily: each pattern buffer stores its own
955 syntax, so it can be changed between regex compilations. */
956 /* This has no initializer because initialized variables in Emacs
957 become read-only after dumping. */
958 reg_syntax_t re_syntax_options;
959
960
961 /* Specify the precise syntax of regexps for compilation. This provides
962 for compatibility for various utilities which historically have
963 different, incompatible syntaxes.
964
965 The argument SYNTAX is a bit mask comprised of the various bits
966 defined in gnu-regex.h. We return the old syntax. */
967
968 reg_syntax_t
969 re_set_syntax (syntax)
970 reg_syntax_t syntax;
971 {
972 reg_syntax_t ret = re_syntax_options;
973
974 re_syntax_options = syntax;
975 #ifdef DEBUG
976 if (syntax & RE_DEBUG)
977 debug = 1;
978 else if (debug) /* was on but now is not */
979 debug = 0;
980 #endif /* DEBUG */
981 return ret;
982 }
983 #ifdef _LIBC
984 weak_alias (__re_set_syntax, re_set_syntax)
985 #endif
986 \f
987 /* This table gives an error message for each of the error codes listed
988 in gnu-regex.h. Obviously the order here has to be same as there.
989 POSIX doesn't require that we do anything for REG_NOERROR,
990 but why not be nice? */
991
992 static const char *re_error_msgid[] =
993 {
994 gettext_noop ("Success"), /* REG_NOERROR */
995 gettext_noop ("No match"), /* REG_NOMATCH */
996 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
997 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
998 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
999 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1000 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1001 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1002 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1003 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1004 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1005 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1006 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1007 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1008 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1009 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1010 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1011 };
1012 \f
1013 /* Avoiding alloca during matching, to placate r_alloc. */
1014
1015 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1016 searching and matching functions should not call alloca. On some
1017 systems, alloca is implemented in terms of malloc, and if we're
1018 using the relocating allocator routines, then malloc could cause a
1019 relocation, which might (if the strings being searched are in the
1020 ralloc heap) shift the data out from underneath the regexp
1021 routines.
1022
1023 Here's another reason to avoid allocation: Emacs
1024 processes input from X in a signal handler; processing X input may
1025 call malloc; if input arrives while a matching routine is calling
1026 malloc, then we're scrod. But Emacs can't just block input while
1027 calling matching routines; then we don't notice interrupts when
1028 they come in. So, Emacs blocks input around all regexp calls
1029 except the matching calls, which it leaves unprotected, in the
1030 faith that they will not malloc. */
1031
1032 /* Normally, this is fine. */
1033 #define MATCH_MAY_ALLOCATE
1034
1035 /* When using GNU C, we are not REALLY using the C alloca, no matter
1036 what config.h may say. So don't take precautions for it. */
1037 #ifdef __GNUC__
1038 # undef C_ALLOCA
1039 #endif
1040
1041 /* The match routines may not allocate if (1) they would do it with malloc
1042 and (2) it's not safe for them to use malloc.
1043 Note that if REL_ALLOC is defined, matching would not use malloc for the
1044 failure stack, but we would still use it for the register vectors;
1045 so REL_ALLOC should not affect this. */
1046 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1047 # undef MATCH_MAY_ALLOCATE
1048 #endif
1049
1050 \f
1051 /* Failure stack declarations and macros; both re_compile_fastmap and
1052 re_match_2 use a failure stack. These have to be macros because of
1053 REGEX_ALLOCATE_STACK. */
1054
1055
1056 /* Number of failure points for which to initially allocate space
1057 when matching. If this number is exceeded, we allocate more
1058 space, so it is not a hard limit. */
1059 #ifndef INIT_FAILURE_ALLOC
1060 # define INIT_FAILURE_ALLOC 5
1061 #endif
1062
1063 /* Roughly the maximum number of failure points on the stack. Would be
1064 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1065 This is a variable only so users of regex can assign to it; we never
1066 change it ourselves. */
1067
1068 #ifdef INT_IS_16BIT
1069
1070 # if defined MATCH_MAY_ALLOCATE
1071 /* 4400 was enough to cause a crash on Alpha OSF/1,
1072 whose default stack limit is 2mb. */
1073 long int re_max_failures = 4000;
1074 # else
1075 long int re_max_failures = 2000;
1076 # endif
1077
1078 union fail_stack_elt
1079 {
1080 unsigned char *pointer;
1081 long int integer;
1082 };
1083
1084 typedef union fail_stack_elt fail_stack_elt_t;
1085
1086 typedef struct
1087 {
1088 fail_stack_elt_t *stack;
1089 unsigned long int size;
1090 unsigned long int avail; /* Offset of next open position. */
1091 } fail_stack_type;
1092
1093 #else /* not INT_IS_16BIT */
1094
1095 # if defined MATCH_MAY_ALLOCATE
1096 /* 4400 was enough to cause a crash on Alpha OSF/1,
1097 whose default stack limit is 2mb. */
1098 int re_max_failures = 20000;
1099 # else
1100 int re_max_failures = 2000;
1101 # endif
1102
1103 union fail_stack_elt
1104 {
1105 unsigned char *pointer;
1106 int integer;
1107 };
1108
1109 typedef union fail_stack_elt fail_stack_elt_t;
1110
1111 typedef struct
1112 {
1113 fail_stack_elt_t *stack;
1114 unsigned size;
1115 unsigned avail; /* Offset of next open position. */
1116 } fail_stack_type;
1117
1118 #endif /* INT_IS_16BIT */
1119
1120 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1121 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1122 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1123
1124
1125 /* Define macros to initialize and free the failure stack.
1126 Do `return -2' if the alloc fails. */
1127
1128 #ifdef MATCH_MAY_ALLOCATE
1129 # define INIT_FAIL_STACK() \
1130 do { \
1131 fail_stack.stack = (fail_stack_elt_t *) \
1132 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1133 \
1134 if (fail_stack.stack == NULL) \
1135 return -2; \
1136 \
1137 fail_stack.size = INIT_FAILURE_ALLOC; \
1138 fail_stack.avail = 0; \
1139 } while (0)
1140
1141 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1142 #else
1143 # define INIT_FAIL_STACK() \
1144 do { \
1145 fail_stack.avail = 0; \
1146 } while (0)
1147
1148 # define RESET_FAIL_STACK()
1149 #endif
1150
1151
1152 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1153
1154 Return 1 if succeeds, and 0 if either ran out of memory
1155 allocating space for it or it was already too large.
1156
1157 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1158
1159 #define DOUBLE_FAIL_STACK(fail_stack) \
1160 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1161 ? 0 \
1162 : ((fail_stack).stack = (fail_stack_elt_t *) \
1163 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1164 (fail_stack).size * sizeof (fail_stack_elt_t), \
1165 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1166 \
1167 (fail_stack).stack == NULL \
1168 ? 0 \
1169 : ((fail_stack).size <<= 1, \
1170 1)))
1171
1172
1173 /* Push pointer POINTER on FAIL_STACK.
1174 Return 1 if was able to do so and 0 if ran out of memory allocating
1175 space to do so. */
1176 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1177 ((FAIL_STACK_FULL () \
1178 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1179 ? 0 \
1180 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1181 1))
1182
1183 /* Push a pointer value onto the failure stack.
1184 Assumes the variable `fail_stack'. Probably should only
1185 be called from within `PUSH_FAILURE_POINT'. */
1186 #define PUSH_FAILURE_POINTER(item) \
1187 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1188
1189 /* This pushes an integer-valued item onto the failure stack.
1190 Assumes the variable `fail_stack'. Probably should only
1191 be called from within `PUSH_FAILURE_POINT'. */
1192 #define PUSH_FAILURE_INT(item) \
1193 fail_stack.stack[fail_stack.avail++].integer = (item)
1194
1195 /* Push a fail_stack_elt_t value onto the failure stack.
1196 Assumes the variable `fail_stack'. Probably should only
1197 be called from within `PUSH_FAILURE_POINT'. */
1198 #define PUSH_FAILURE_ELT(item) \
1199 fail_stack.stack[fail_stack.avail++] = (item)
1200
1201 /* These three POP... operations complement the three PUSH... operations.
1202 All assume that `fail_stack' is nonempty. */
1203 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1204 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1205 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1206
1207 /* Used to omit pushing failure point id's when we're not debugging. */
1208 #ifdef DEBUG
1209 # define DEBUG_PUSH PUSH_FAILURE_INT
1210 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1211 #else
1212 # define DEBUG_PUSH(item)
1213 # define DEBUG_POP(item_addr)
1214 #endif
1215
1216
1217 /* Push the information about the state we will need
1218 if we ever fail back to it.
1219
1220 Requires variables fail_stack, regstart, regend, reg_info, and
1221 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1222 be declared.
1223
1224 Does `return FAILURE_CODE' if runs out of memory. */
1225
1226 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1227 do { \
1228 char *destination; \
1229 /* Must be int, so when we don't save any registers, the arithmetic \
1230 of 0 + -1 isn't done as unsigned. */ \
1231 /* Can't be int, since there is not a shred of a guarantee that int \
1232 is wide enough to hold a value of something to which pointer can \
1233 be assigned */ \
1234 active_reg_t this_reg; \
1235 \
1236 DEBUG_STATEMENT (failure_id++); \
1237 DEBUG_STATEMENT (nfailure_points_pushed++); \
1238 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1239 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1240 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1241 \
1242 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1243 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1244 \
1245 /* Ensure we have enough space allocated for what we will push. */ \
1246 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1247 { \
1248 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1249 return failure_code; \
1250 \
1251 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1252 (fail_stack).size); \
1253 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1254 } \
1255 \
1256 /* Push the info, starting with the registers. */ \
1257 DEBUG_PRINT1 ("\n"); \
1258 \
1259 if (1) \
1260 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1261 this_reg++) \
1262 { \
1263 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1264 DEBUG_STATEMENT (num_regs_pushed++); \
1265 \
1266 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1267 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1268 \
1269 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1270 PUSH_FAILURE_POINTER (regend[this_reg]); \
1271 \
1272 DEBUG_PRINT2 (" info: %p\n ", \
1273 reg_info[this_reg].word.pointer); \
1274 DEBUG_PRINT2 (" match_null=%d", \
1275 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1276 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1277 DEBUG_PRINT2 (" matched_something=%d", \
1278 MATCHED_SOMETHING (reg_info[this_reg])); \
1279 DEBUG_PRINT2 (" ever_matched=%d", \
1280 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1281 DEBUG_PRINT1 ("\n"); \
1282 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1283 } \
1284 \
1285 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1286 PUSH_FAILURE_INT (lowest_active_reg); \
1287 \
1288 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1289 PUSH_FAILURE_INT (highest_active_reg); \
1290 \
1291 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1292 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1293 PUSH_FAILURE_POINTER (pattern_place); \
1294 \
1295 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1296 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1297 size2); \
1298 DEBUG_PRINT1 ("'\n"); \
1299 PUSH_FAILURE_POINTER (string_place); \
1300 \
1301 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1302 DEBUG_PUSH (failure_id); \
1303 } while (0)
1304
1305 /* This is the number of items that are pushed and popped on the stack
1306 for each register. */
1307 #define NUM_REG_ITEMS 3
1308
1309 /* Individual items aside from the registers. */
1310 #ifdef DEBUG
1311 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1312 #else
1313 # define NUM_NONREG_ITEMS 4
1314 #endif
1315
1316 /* We push at most this many items on the stack. */
1317 /* We used to use (num_regs - 1), which is the number of registers
1318 this regexp will save; but that was changed to 5
1319 to avoid stack overflow for a regexp with lots of parens. */
1320 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1321
1322 /* We actually push this many items. */
1323 #define NUM_FAILURE_ITEMS \
1324 (((0 \
1325 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1326 * NUM_REG_ITEMS) \
1327 + NUM_NONREG_ITEMS)
1328
1329 /* How many items can still be added to the stack without overflowing it. */
1330 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1331
1332
1333 /* Pops what PUSH_FAIL_STACK pushes.
1334
1335 We restore into the parameters, all of which should be lvalues:
1336 STR -- the saved data position.
1337 PAT -- the saved pattern position.
1338 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1339 REGSTART, REGEND -- arrays of string positions.
1340 REG_INFO -- array of information about each subexpression.
1341
1342 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1343 `pend', `string1', `size1', `string2', and `size2'. */
1344
1345 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1346 { \
1347 DEBUG_STATEMENT (unsigned failure_id;) \
1348 active_reg_t this_reg; \
1349 const unsigned char *string_temp; \
1350 \
1351 assert (!FAIL_STACK_EMPTY ()); \
1352 \
1353 /* Remove failure points and point to how many regs pushed. */ \
1354 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1355 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1356 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1357 \
1358 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1359 \
1360 DEBUG_POP (&failure_id); \
1361 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1362 \
1363 /* If the saved string location is NULL, it came from an \
1364 on_failure_keep_string_jump opcode, and we want to throw away the \
1365 saved NULL, thus retaining our current position in the string. */ \
1366 string_temp = POP_FAILURE_POINTER (); \
1367 if (string_temp != NULL) \
1368 str = (const char *) string_temp; \
1369 \
1370 DEBUG_PRINT2 (" Popping string %p: `", str); \
1371 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1372 DEBUG_PRINT1 ("'\n"); \
1373 \
1374 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1375 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1376 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1377 \
1378 /* Restore register info. */ \
1379 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1380 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1381 \
1382 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1383 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1384 \
1385 if (1) \
1386 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1387 { \
1388 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1389 \
1390 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1391 DEBUG_PRINT2 (" info: %p\n", \
1392 reg_info[this_reg].word.pointer); \
1393 \
1394 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1395 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1396 \
1397 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1398 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1399 } \
1400 else \
1401 { \
1402 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1403 { \
1404 reg_info[this_reg].word.integer = 0; \
1405 regend[this_reg] = 0; \
1406 regstart[this_reg] = 0; \
1407 } \
1408 highest_active_reg = high_reg; \
1409 } \
1410 \
1411 set_regs_matched_done = 0; \
1412 DEBUG_STATEMENT (nfailure_points_popped++); \
1413 } /* POP_FAILURE_POINT */
1414
1415
1416 \f
1417 /* Structure for per-register (a.k.a. per-group) information.
1418 Other register information, such as the
1419 starting and ending positions (which are addresses), and the list of
1420 inner groups (which is a bits list) are maintained in separate
1421 variables.
1422
1423 We are making a (strictly speaking) nonportable assumption here: that
1424 the compiler will pack our bit fields into something that fits into
1425 the type of `word', i.e., is something that fits into one item on the
1426 failure stack. */
1427
1428
1429 /* Declarations and macros for re_match_2. */
1430
1431 typedef union
1432 {
1433 fail_stack_elt_t word;
1434 struct
1435 {
1436 /* This field is one if this group can match the empty string,
1437 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1438 #define MATCH_NULL_UNSET_VALUE 3
1439 unsigned match_null_string_p : 2;
1440 unsigned is_active : 1;
1441 unsigned matched_something : 1;
1442 unsigned ever_matched_something : 1;
1443 } bits;
1444 } register_info_type;
1445
1446 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1447 #define IS_ACTIVE(R) ((R).bits.is_active)
1448 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1449 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1450
1451
1452 /* Call this when have matched a real character; it sets `matched' flags
1453 for the subexpressions which we are currently inside. Also records
1454 that those subexprs have matched. */
1455 #define SET_REGS_MATCHED() \
1456 do \
1457 { \
1458 if (!set_regs_matched_done) \
1459 { \
1460 active_reg_t r; \
1461 set_regs_matched_done = 1; \
1462 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1463 { \
1464 MATCHED_SOMETHING (reg_info[r]) \
1465 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1466 = 1; \
1467 } \
1468 } \
1469 } \
1470 while (0)
1471
1472 /* Registers are set to a sentinel when they haven't yet matched. */
1473 static char reg_unset_dummy;
1474 #define REG_UNSET_VALUE (&reg_unset_dummy)
1475 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1476 \f
1477 /* Subroutine declarations and macros for regex_compile. */
1478
1479 static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1480 reg_syntax_t syntax,
1481 struct re_pattern_buffer *bufp));
1482 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1483 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1484 int arg1, int arg2));
1485 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1486 int arg, unsigned char *end));
1487 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1488 int arg1, int arg2, unsigned char *end));
1489 static boolean at_begline_loc_p _RE_ARGS ((const char *pattern, const char *p,
1490 reg_syntax_t syntax));
1491 static boolean at_endline_loc_p _RE_ARGS ((const char *p, const char *pend,
1492 reg_syntax_t syntax));
1493 static reg_errcode_t compile_range _RE_ARGS ((const char **p_ptr,
1494 const char *pend,
1495 char *translate,
1496 reg_syntax_t syntax,
1497 unsigned char *b));
1498
1499 /* Fetch the next character in the uncompiled pattern---translating it
1500 if necessary. Also cast from a signed character in the constant
1501 string passed to us by the user to an unsigned char that we can use
1502 as an array index (in, e.g., `translate'). */
1503 #ifndef PATFETCH
1504 # define PATFETCH(c) \
1505 do {if (p == pend) return REG_EEND; \
1506 c = (unsigned char) *p++; \
1507 if (translate) c = (unsigned char) translate[c]; \
1508 } while (0)
1509 #endif
1510
1511 /* Fetch the next character in the uncompiled pattern, with no
1512 translation. */
1513 #define PATFETCH_RAW(c) \
1514 do {if (p == pend) return REG_EEND; \
1515 c = (unsigned char) *p++; \
1516 } while (0)
1517
1518 /* Go backwards one character in the pattern. */
1519 #define PATUNFETCH p--
1520
1521
1522 /* If `translate' is non-null, return translate[D], else just D. We
1523 cast the subscript to translate because some data is declared as
1524 `char *', to avoid warnings when a string constant is passed. But
1525 when we use a character as a subscript we must make it unsigned. */
1526 #ifndef TRANSLATE
1527 # define TRANSLATE(d) \
1528 (translate ? (char) translate[(unsigned char) (d)] : (d))
1529 #endif
1530
1531
1532 /* Macros for outputting the compiled pattern into `buffer'. */
1533
1534 /* If the buffer isn't allocated when it comes in, use this. */
1535 #define INIT_BUF_SIZE 32
1536
1537 /* Make sure we have at least N more bytes of space in buffer. */
1538 #define GET_BUFFER_SPACE(n) \
1539 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1540 EXTEND_BUFFER ()
1541
1542 /* Make sure we have one more byte of buffer space and then add C to it. */
1543 #define BUF_PUSH(c) \
1544 do { \
1545 GET_BUFFER_SPACE (1); \
1546 *b++ = (unsigned char) (c); \
1547 } while (0)
1548
1549
1550 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1551 #define BUF_PUSH_2(c1, c2) \
1552 do { \
1553 GET_BUFFER_SPACE (2); \
1554 *b++ = (unsigned char) (c1); \
1555 *b++ = (unsigned char) (c2); \
1556 } while (0)
1557
1558
1559 /* As with BUF_PUSH_2, except for three bytes. */
1560 #define BUF_PUSH_3(c1, c2, c3) \
1561 do { \
1562 GET_BUFFER_SPACE (3); \
1563 *b++ = (unsigned char) (c1); \
1564 *b++ = (unsigned char) (c2); \
1565 *b++ = (unsigned char) (c3); \
1566 } while (0)
1567
1568
1569 /* Store a jump with opcode OP at LOC to location TO. We store a
1570 relative address offset by the three bytes the jump itself occupies. */
1571 #define STORE_JUMP(op, loc, to) \
1572 store_op1 (op, loc, (int) ((to) - (loc) - 3))
1573
1574 /* Likewise, for a two-argument jump. */
1575 #define STORE_JUMP2(op, loc, to, arg) \
1576 store_op2 (op, loc, (int) ((to) - (loc) - 3), arg)
1577
1578 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1579 #define INSERT_JUMP(op, loc, to) \
1580 insert_op1 (op, loc, (int) ((to) - (loc) - 3), b)
1581
1582 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1583 #define INSERT_JUMP2(op, loc, to, arg) \
1584 insert_op2 (op, loc, (int) ((to) - (loc) - 3), arg, b)
1585
1586
1587 /* This is not an arbitrary limit: the arguments which represent offsets
1588 into the pattern are two bytes long. So if 2^16 bytes turns out to
1589 be too small, many things would have to change. */
1590 /* Any other compiler which, like MSC, has allocation limit below 2^16
1591 bytes will have to use approach similar to what was done below for
1592 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1593 reallocating to 0 bytes. Such thing is not going to work too well.
1594 You have been warned!! */
1595 #if defined _MSC_VER && !defined WIN32
1596 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1597 The REALLOC define eliminates a flurry of conversion warnings,
1598 but is not required. */
1599 # define MAX_BUF_SIZE 65500L
1600 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1601 #else
1602 # define MAX_BUF_SIZE (1L << 16)
1603 # define REALLOC(p,s) realloc ((p), (s))
1604 #endif
1605
1606 /* Extend the buffer by twice its current size via realloc and
1607 reset the pointers that pointed into the old block to point to the
1608 correct places in the new one. If extending the buffer results in it
1609 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1610 #define EXTEND_BUFFER() \
1611 do { \
1612 unsigned char *old_buffer = bufp->buffer; \
1613 if (bufp->allocated == MAX_BUF_SIZE) \
1614 return REG_ESIZE; \
1615 bufp->allocated <<= 1; \
1616 if (bufp->allocated > MAX_BUF_SIZE) \
1617 bufp->allocated = MAX_BUF_SIZE; \
1618 bufp->buffer = (unsigned char *) REALLOC (bufp->buffer, bufp->allocated);\
1619 if (bufp->buffer == NULL) \
1620 return REG_ESPACE; \
1621 /* If the buffer moved, move all the pointers into it. */ \
1622 if (old_buffer != bufp->buffer) \
1623 { \
1624 b = (b - old_buffer) + bufp->buffer; \
1625 begalt = (begalt - old_buffer) + bufp->buffer; \
1626 if (fixup_alt_jump) \
1627 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1628 if (laststart) \
1629 laststart = (laststart - old_buffer) + bufp->buffer; \
1630 if (pending_exact) \
1631 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1632 } \
1633 } while (0)
1634
1635
1636 /* Since we have one byte reserved for the register number argument to
1637 {start,stop}_memory, the maximum number of groups we can report
1638 things about is what fits in that byte. */
1639 #define MAX_REGNUM 255
1640
1641 /* But patterns can have more than `MAX_REGNUM' registers. We just
1642 ignore the excess. */
1643 typedef unsigned regnum_t;
1644
1645
1646 /* Macros for the compile stack. */
1647
1648 /* Since offsets can go either forwards or backwards, this type needs to
1649 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1650 /* int may be not enough when sizeof(int) == 2. */
1651 typedef long pattern_offset_t;
1652
1653 typedef struct
1654 {
1655 pattern_offset_t begalt_offset;
1656 pattern_offset_t fixup_alt_jump;
1657 pattern_offset_t inner_group_offset;
1658 pattern_offset_t laststart_offset;
1659 regnum_t regnum;
1660 } compile_stack_elt_t;
1661
1662
1663 typedef struct
1664 {
1665 compile_stack_elt_t *stack;
1666 unsigned size;
1667 unsigned avail; /* Offset of next open position. */
1668 } compile_stack_type;
1669
1670
1671 #define INIT_COMPILE_STACK_SIZE 32
1672
1673 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1674 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1675
1676 /* The next available element. */
1677 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1678
1679
1680 /* Set the bit for character C in a list. */
1681 #define SET_LIST_BIT(c) \
1682 (b[((unsigned char) (c)) / BYTEWIDTH] \
1683 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1684
1685
1686 /* Get the next unsigned number in the uncompiled pattern. */
1687 #define GET_UNSIGNED_NUMBER(num) \
1688 { if (p != pend) \
1689 { \
1690 PATFETCH (c); \
1691 while (ISDIGIT (c)) \
1692 { \
1693 if (num < 0) \
1694 num = 0; \
1695 num = num * 10 + c - '0'; \
1696 if (p == pend) \
1697 break; \
1698 PATFETCH (c); \
1699 } \
1700 } \
1701 }
1702
1703 /* Use this only if they have btowc(), since wctype() is used below
1704 together with btowc(). btowc() is defined in the 1994 Amendment 1
1705 to ISO C and may not be present on systems where we have wchar.h
1706 and wctype.h. */
1707 #if defined _LIBC || (defined HAVE_WCTYPE_H && defined HAVE_WCHAR_H && defined HAVE_BTOWC)
1708 /* The GNU C library provides support for user-defined character classes
1709 and the functions from ISO C amendement 1. */
1710 # ifdef CHARCLASS_NAME_MAX
1711 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1712 # else
1713 /* This shouldn't happen but some implementation might still have this
1714 problem. Use a reasonable default value. */
1715 # define CHAR_CLASS_MAX_LENGTH 256
1716 # endif
1717
1718 # ifdef _LIBC
1719 # define IS_CHAR_CLASS(string) __wctype (string)
1720 # else
1721 # define IS_CHAR_CLASS(string) wctype (string)
1722 # endif
1723 #else
1724 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1725
1726 # define IS_CHAR_CLASS(string) \
1727 (STREQ (string, "alpha") || STREQ (string, "upper") \
1728 || STREQ (string, "lower") || STREQ (string, "digit") \
1729 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1730 || STREQ (string, "space") || STREQ (string, "print") \
1731 || STREQ (string, "punct") || STREQ (string, "graph") \
1732 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1733 #endif
1734 \f
1735 #ifndef MATCH_MAY_ALLOCATE
1736
1737 /* If we cannot allocate large objects within re_match_2_internal,
1738 we make the fail stack and register vectors global.
1739 The fail stack, we grow to the maximum size when a regexp
1740 is compiled.
1741 The register vectors, we adjust in size each time we
1742 compile a regexp, according to the number of registers it needs. */
1743
1744 static fail_stack_type fail_stack;
1745
1746 /* Size with which the following vectors are currently allocated.
1747 That is so we can make them bigger as needed,
1748 but never make them smaller. */
1749 static int regs_allocated_size;
1750
1751 static const char ** regstart, ** regend;
1752 static const char ** old_regstart, ** old_regend;
1753 static const char **best_regstart, **best_regend;
1754 static register_info_type *reg_info;
1755 static const char **reg_dummy;
1756 static register_info_type *reg_info_dummy;
1757
1758 /* Make the register vectors big enough for NUM_REGS registers,
1759 but don't make them smaller. */
1760
1761 static
1762 regex_grow_registers (num_regs)
1763 int num_regs;
1764 {
1765 if (num_regs > regs_allocated_size)
1766 {
1767 RETALLOC_IF (regstart, num_regs, const char *);
1768 RETALLOC_IF (regend, num_regs, const char *);
1769 RETALLOC_IF (old_regstart, num_regs, const char *);
1770 RETALLOC_IF (old_regend, num_regs, const char *);
1771 RETALLOC_IF (best_regstart, num_regs, const char *);
1772 RETALLOC_IF (best_regend, num_regs, const char *);
1773 RETALLOC_IF (reg_info, num_regs, register_info_type);
1774 RETALLOC_IF (reg_dummy, num_regs, const char *);
1775 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1776
1777 regs_allocated_size = num_regs;
1778 }
1779 }
1780
1781 #endif /* not MATCH_MAY_ALLOCATE */
1782 \f
1783 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
1784 compile_stack,
1785 regnum_t regnum));
1786
1787 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1788 Returns one of error codes defined in `gnu-regex.h', or zero for success.
1789
1790 Assumes the `allocated' (and perhaps `buffer') and `translate'
1791 fields are set in BUFP on entry.
1792
1793 If it succeeds, results are put in BUFP (if it returns an error, the
1794 contents of BUFP are undefined):
1795 `buffer' is the compiled pattern;
1796 `syntax' is set to SYNTAX;
1797 `used' is set to the length of the compiled pattern;
1798 `fastmap_accurate' is zero;
1799 `re_nsub' is the number of subexpressions in PATTERN;
1800 `not_bol' and `not_eol' are zero;
1801
1802 The `fastmap' and `newline_anchor' fields are neither
1803 examined nor set. */
1804
1805 /* Return, freeing storage we allocated. */
1806 #define FREE_STACK_RETURN(value) \
1807 return (free (compile_stack.stack), value)
1808
1809 static reg_errcode_t
1810 regex_compile (pattern, size, syntax, bufp)
1811 const char *pattern;
1812 size_t size;
1813 reg_syntax_t syntax;
1814 struct re_pattern_buffer *bufp;
1815 {
1816 /* We fetch characters from PATTERN here. Even though PATTERN is
1817 `char *' (i.e., signed), we declare these variables as unsigned, so
1818 they can be reliably used as array indices. */
1819 register unsigned char c, c1;
1820
1821 /* A random temporary spot in PATTERN. */
1822 const char *p1;
1823
1824 /* Points to the end of the buffer, where we should append. */
1825 register unsigned char *b;
1826
1827 /* Keeps track of unclosed groups. */
1828 compile_stack_type compile_stack;
1829
1830 /* Points to the current (ending) position in the pattern. */
1831 const char *p = pattern;
1832 const char *pend = pattern + size;
1833
1834 /* How to translate the characters in the pattern. */
1835 RE_TRANSLATE_TYPE translate = bufp->translate;
1836
1837 /* Address of the count-byte of the most recently inserted `exactn'
1838 command. This makes it possible to tell if a new exact-match
1839 character can be added to that command or if the character requires
1840 a new `exactn' command. */
1841 unsigned char *pending_exact = 0;
1842
1843 /* Address of start of the most recently finished expression.
1844 This tells, e.g., postfix * where to find the start of its
1845 operand. Reset at the beginning of groups and alternatives. */
1846 unsigned char *laststart = 0;
1847
1848 /* Address of beginning of regexp, or inside of last group. */
1849 unsigned char *begalt;
1850
1851 /* Place in the uncompiled pattern (i.e., the {) to
1852 which to go back if the interval is invalid. */
1853 const char *beg_interval;
1854
1855 /* Address of the place where a forward jump should go to the end of
1856 the containing expression. Each alternative of an `or' -- except the
1857 last -- ends with a forward jump of this sort. */
1858 unsigned char *fixup_alt_jump = 0;
1859
1860 /* Counts open-groups as they are encountered. Remembered for the
1861 matching close-group on the compile stack, so the same register
1862 number is put in the stop_memory as the start_memory. */
1863 regnum_t regnum = 0;
1864
1865 #ifdef DEBUG
1866 DEBUG_PRINT1 ("\nCompiling pattern: ");
1867 if (debug)
1868 {
1869 unsigned debug_count;
1870
1871 for (debug_count = 0; debug_count < size; debug_count++)
1872 putchar (pattern[debug_count]);
1873 putchar ('\n');
1874 }
1875 #endif /* DEBUG */
1876
1877 /* Initialize the compile stack. */
1878 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1879 if (compile_stack.stack == NULL)
1880 return REG_ESPACE;
1881
1882 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1883 compile_stack.avail = 0;
1884
1885 /* Initialize the pattern buffer. */
1886 bufp->syntax = syntax;
1887 bufp->fastmap_accurate = 0;
1888 bufp->not_bol = bufp->not_eol = 0;
1889
1890 /* Set `used' to zero, so that if we return an error, the pattern
1891 printer (for debugging) will think there's no pattern. We reset it
1892 at the end. */
1893 bufp->used = 0;
1894
1895 /* Always count groups, whether or not bufp->no_sub is set. */
1896 bufp->re_nsub = 0;
1897
1898 #if !defined emacs && !defined SYNTAX_TABLE
1899 /* Initialize the syntax table. */
1900 init_syntax_once ();
1901 #endif
1902
1903 if (bufp->allocated == 0)
1904 {
1905 if (bufp->buffer)
1906 { /* If zero allocated, but buffer is non-null, try to realloc
1907 enough space. This loses if buffer's address is bogus, but
1908 that is the user's responsibility. */
1909 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1910 }
1911 else
1912 { /* Caller did not allocate a buffer. Do it for them. */
1913 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1914 }
1915 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1916
1917 bufp->allocated = INIT_BUF_SIZE;
1918 }
1919
1920 begalt = b = bufp->buffer;
1921
1922 /* Loop through the uncompiled pattern until we're at the end. */
1923 while (p != pend)
1924 {
1925 PATFETCH (c);
1926
1927 switch (c)
1928 {
1929 case '^':
1930 {
1931 if ( /* If at start of pattern, it's an operator. */
1932 p == pattern + 1
1933 /* If context independent, it's an operator. */
1934 || syntax & RE_CONTEXT_INDEP_ANCHORS
1935 /* Otherwise, depends on what's come before. */
1936 || at_begline_loc_p (pattern, p, syntax))
1937 BUF_PUSH (begline);
1938 else
1939 goto normal_char;
1940 }
1941 break;
1942
1943
1944 case '$':
1945 {
1946 if ( /* If at end of pattern, it's an operator. */
1947 p == pend
1948 /* If context independent, it's an operator. */
1949 || syntax & RE_CONTEXT_INDEP_ANCHORS
1950 /* Otherwise, depends on what's next. */
1951 || at_endline_loc_p (p, pend, syntax))
1952 BUF_PUSH (endline);
1953 else
1954 goto normal_char;
1955 }
1956 break;
1957
1958
1959 case '+':
1960 case '?':
1961 if ((syntax & RE_BK_PLUS_QM)
1962 || (syntax & RE_LIMITED_OPS))
1963 goto normal_char;
1964 handle_plus:
1965 case '*':
1966 /* If there is no previous pattern... */
1967 if (!laststart)
1968 {
1969 if (syntax & RE_CONTEXT_INVALID_OPS)
1970 FREE_STACK_RETURN (REG_BADRPT);
1971 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1972 goto normal_char;
1973 }
1974
1975 {
1976 /* Are we optimizing this jump? */
1977 boolean keep_string_p = false;
1978
1979 /* 1 means zero (many) matches is allowed. */
1980 char zero_times_ok = 0, many_times_ok = 0;
1981
1982 /* If there is a sequence of repetition chars, collapse it
1983 down to just one (the right one). We can't combine
1984 interval operators with these because of, e.g., `a{2}*',
1985 which should only match an even number of `a's. */
1986
1987 for (;;)
1988 {
1989 zero_times_ok |= c != '+';
1990 many_times_ok |= c != '?';
1991
1992 if (p == pend)
1993 break;
1994
1995 PATFETCH (c);
1996
1997 if (c == '*'
1998 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1999 ;
2000
2001 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2002 {
2003 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2004
2005 PATFETCH (c1);
2006 if (!(c1 == '+' || c1 == '?'))
2007 {
2008 PATUNFETCH;
2009 PATUNFETCH;
2010 break;
2011 }
2012
2013 c = c1;
2014 }
2015 else
2016 {
2017 PATUNFETCH;
2018 break;
2019 }
2020
2021 /* If we get here, we found another repeat character. */
2022 }
2023
2024 /* Star, etc. applied to an empty pattern is equivalent
2025 to an empty pattern. */
2026 if (!laststart)
2027 break;
2028
2029 /* Now we know whether or not zero matches is allowed
2030 and also whether or not two or more matches is allowed. */
2031 if (many_times_ok)
2032 { /* More than one repetition is allowed, so put in at the
2033 end a backward relative jump from `b' to before the next
2034 jump we're going to put in below (which jumps from
2035 laststart to after this jump).
2036
2037 But if we are at the `*' in the exact sequence `.*\n',
2038 insert an unconditional jump backwards to the .,
2039 instead of the beginning of the loop. This way we only
2040 push a failure point once, instead of every time
2041 through the loop. */
2042 assert (p - 1 > pattern);
2043
2044 /* Allocate the space for the jump. */
2045 GET_BUFFER_SPACE (3);
2046
2047 /* We know we are not at the first character of the pattern,
2048 because laststart was nonzero. And we've already
2049 incremented `p', by the way, to be the character after
2050 the `*'. Do we have to do something analogous here
2051 for null bytes, because of RE_DOT_NOT_NULL? */
2052 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2053 && zero_times_ok
2054 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2055 && !(syntax & RE_DOT_NEWLINE))
2056 { /* We have .*\n. */
2057 STORE_JUMP (jump, b, laststart);
2058 keep_string_p = true;
2059 }
2060 else
2061 /* Anything else. */
2062 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2063
2064 /* We've added more stuff to the buffer. */
2065 b += 3;
2066 }
2067
2068 /* On failure, jump from laststart to b + 3, which will be the
2069 end of the buffer after this jump is inserted. */
2070 GET_BUFFER_SPACE (3);
2071 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2072 : on_failure_jump,
2073 laststart, b + 3);
2074 pending_exact = 0;
2075 b += 3;
2076
2077 if (!zero_times_ok)
2078 {
2079 /* At least one repetition is required, so insert a
2080 `dummy_failure_jump' before the initial
2081 `on_failure_jump' instruction of the loop. This
2082 effects a skip over that instruction the first time
2083 we hit that loop. */
2084 GET_BUFFER_SPACE (3);
2085 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2086 b += 3;
2087 }
2088 }
2089 break;
2090
2091
2092 case '.':
2093 laststart = b;
2094 BUF_PUSH (anychar);
2095 break;
2096
2097
2098 case '[':
2099 {
2100 boolean had_char_class = false;
2101
2102 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2103
2104 /* Ensure that we have enough space to push a charset: the
2105 opcode, the length count, and the bitset; 34 bytes in all. */
2106 GET_BUFFER_SPACE (34);
2107
2108 laststart = b;
2109
2110 /* We test `*p == '^' twice, instead of using an if
2111 statement, so we only need one BUF_PUSH. */
2112 BUF_PUSH (*p == '^' ? charset_not : charset);
2113 if (*p == '^')
2114 p++;
2115
2116 /* Remember the first position in the bracket expression. */
2117 p1 = p;
2118
2119 /* Push the number of bytes in the bitmap. */
2120 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2121
2122 /* Clear the whole map. */
2123 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2124
2125 /* charset_not matches newline according to a syntax bit. */
2126 if ((re_opcode_t) b[-2] == charset_not
2127 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2128 SET_LIST_BIT ('\n');
2129
2130 /* Read in characters and ranges, setting map bits. */
2131 for (;;)
2132 {
2133 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2134
2135 PATFETCH (c);
2136
2137 /* \ might escape characters inside [...] and [^...]. */
2138 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2139 {
2140 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2141
2142 PATFETCH (c1);
2143 SET_LIST_BIT (c1);
2144 continue;
2145 }
2146
2147 /* Could be the end of the bracket expression. If it's
2148 not (i.e., when the bracket expression is `[]' so
2149 far), the ']' character bit gets set way below. */
2150 if (c == ']' && p != p1 + 1)
2151 break;
2152
2153 /* Look ahead to see if it's a range when the last thing
2154 was a character class. */
2155 if (had_char_class && c == '-' && *p != ']')
2156 FREE_STACK_RETURN (REG_ERANGE);
2157
2158 /* Look ahead to see if it's a range when the last thing
2159 was a character: if this is a hyphen not at the
2160 beginning or the end of a list, then it's the range
2161 operator. */
2162 if (c == '-'
2163 && !(p - 2 >= pattern && p[-2] == '[')
2164 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2165 && *p != ']')
2166 {
2167 reg_errcode_t ret
2168 = compile_range (&p, pend, translate, syntax, b);
2169 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2170 }
2171
2172 else if (p[0] == '-' && p[1] != ']')
2173 { /* This handles ranges made up of characters only. */
2174 reg_errcode_t ret;
2175
2176 /* Move past the `-'. */
2177 PATFETCH (c1);
2178
2179 ret = compile_range (&p, pend, translate, syntax, b);
2180 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2181 }
2182
2183 /* See if we're at the beginning of a possible character
2184 class. */
2185
2186 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2187 { /* Leave room for the null. */
2188 char str[CHAR_CLASS_MAX_LENGTH + 1];
2189
2190 PATFETCH (c);
2191 c1 = 0;
2192
2193 /* If pattern is `[[:'. */
2194 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2195
2196 for (;;)
2197 {
2198 PATFETCH (c);
2199 if ((c == ':' && *p == ']') || p == pend
2200 || c1 == CHAR_CLASS_MAX_LENGTH)
2201 break;
2202 str[c1++] = c;
2203 }
2204 str[c1] = '\0';
2205
2206 /* If isn't a word bracketed by `[:' and `:]':
2207 undo the ending character, the letters, and leave
2208 the leading `:' and `[' (but set bits for them). */
2209 if (c == ':' && *p == ']')
2210 {
2211 /* CYGNUS LOCAL: Skip this code if we don't have btowc(). btowc() is */
2212 /* defined in the 1994 Amendment 1 to ISO C and may not be present on */
2213 /* systems where we have wchar.h and wctype.h. */
2214 #if defined _LIBC || (defined HAVE_WCTYPE_H && defined HAVE_WCHAR_H && defined HAVE_BTOWC)
2215 boolean is_lower = STREQ (str, "lower");
2216 boolean is_upper = STREQ (str, "upper");
2217 wctype_t wt;
2218 int ch;
2219
2220 wt = IS_CHAR_CLASS (str);
2221 if (wt == 0)
2222 FREE_STACK_RETURN (REG_ECTYPE);
2223
2224 /* Throw away the ] at the end of the character
2225 class. */
2226 PATFETCH (c);
2227
2228 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2229
2230 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
2231 {
2232 # ifdef _LIBC
2233 if (__iswctype (__btowc (ch), wt))
2234 SET_LIST_BIT (ch);
2235 #else
2236 if (iswctype (btowc (ch), wt))
2237 SET_LIST_BIT (ch);
2238 #endif
2239
2240 if (translate && (is_upper || is_lower)
2241 && (ISUPPER (ch) || ISLOWER (ch)))
2242 SET_LIST_BIT (ch);
2243 }
2244
2245 had_char_class = true;
2246 #else
2247 int ch;
2248 boolean is_alnum = STREQ (str, "alnum");
2249 boolean is_alpha = STREQ (str, "alpha");
2250 boolean is_blank = STREQ (str, "blank");
2251 boolean is_cntrl = STREQ (str, "cntrl");
2252 boolean is_digit = STREQ (str, "digit");
2253 boolean is_graph = STREQ (str, "graph");
2254 boolean is_lower = STREQ (str, "lower");
2255 boolean is_print = STREQ (str, "print");
2256 boolean is_punct = STREQ (str, "punct");
2257 boolean is_space = STREQ (str, "space");
2258 boolean is_upper = STREQ (str, "upper");
2259 boolean is_xdigit = STREQ (str, "xdigit");
2260
2261 if (!IS_CHAR_CLASS (str))
2262 FREE_STACK_RETURN (REG_ECTYPE);
2263
2264 /* Throw away the ] at the end of the character
2265 class. */
2266 PATFETCH (c);
2267
2268 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2269
2270 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2271 {
2272 /* This was split into 3 if's to
2273 avoid an arbitrary limit in some compiler. */
2274 if ( (is_alnum && ISALNUM (ch))
2275 || (is_alpha && ISALPHA (ch))
2276 || (is_blank && ISBLANK (ch))
2277 || (is_cntrl && ISCNTRL (ch)))
2278 SET_LIST_BIT (ch);
2279 if ( (is_digit && ISDIGIT (ch))
2280 || (is_graph && ISGRAPH (ch))
2281 || (is_lower && ISLOWER (ch))
2282 || (is_print && ISPRINT (ch)))
2283 SET_LIST_BIT (ch);
2284 if ( (is_punct && ISPUNCT (ch))
2285 || (is_space && ISSPACE (ch))
2286 || (is_upper && ISUPPER (ch))
2287 || (is_xdigit && ISXDIGIT (ch)))
2288 SET_LIST_BIT (ch);
2289 if ( translate && (is_upper || is_lower)
2290 && (ISUPPER (ch) || ISLOWER (ch)))
2291 SET_LIST_BIT (ch);
2292 }
2293 had_char_class = true;
2294 #endif /* libc || wctype.h */
2295 }
2296 else
2297 {
2298 c1++;
2299 while (c1--)
2300 PATUNFETCH;
2301 SET_LIST_BIT ('[');
2302 SET_LIST_BIT (':');
2303 had_char_class = false;
2304 }
2305 }
2306 else
2307 {
2308 had_char_class = false;
2309 SET_LIST_BIT (c);
2310 }
2311 }
2312
2313 /* Discard any (non)matching list bytes that are all 0 at the
2314 end of the map. Decrease the map-length byte too. */
2315 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2316 b[-1]--;
2317 b += b[-1];
2318 }
2319 break;
2320
2321
2322 case '(':
2323 if (syntax & RE_NO_BK_PARENS)
2324 goto handle_open;
2325 else
2326 goto normal_char;
2327
2328
2329 case ')':
2330 if (syntax & RE_NO_BK_PARENS)
2331 goto handle_close;
2332 else
2333 goto normal_char;
2334
2335
2336 case '\n':
2337 if (syntax & RE_NEWLINE_ALT)
2338 goto handle_alt;
2339 else
2340 goto normal_char;
2341
2342
2343 case '|':
2344 if (syntax & RE_NO_BK_VBAR)
2345 goto handle_alt;
2346 else
2347 goto normal_char;
2348
2349
2350 case '{':
2351 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2352 goto handle_interval;
2353 else
2354 goto normal_char;
2355
2356
2357 case '\\':
2358 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2359
2360 /* Do not translate the character after the \, so that we can
2361 distinguish, e.g., \B from \b, even if we normally would
2362 translate, e.g., B to b. */
2363 PATFETCH_RAW (c);
2364
2365 switch (c)
2366 {
2367 case '(':
2368 if (syntax & RE_NO_BK_PARENS)
2369 goto normal_backslash;
2370
2371 handle_open:
2372 bufp->re_nsub++;
2373 regnum++;
2374
2375 if (COMPILE_STACK_FULL)
2376 {
2377 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2378 compile_stack_elt_t);
2379 if (compile_stack.stack == NULL) return REG_ESPACE;
2380
2381 compile_stack.size <<= 1;
2382 }
2383
2384 /* These are the values to restore when we hit end of this
2385 group. They are all relative offsets, so that if the
2386 whole pattern moves because of realloc, they will still
2387 be valid. */
2388 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2389 COMPILE_STACK_TOP.fixup_alt_jump
2390 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2391 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2392 COMPILE_STACK_TOP.regnum = regnum;
2393
2394 /* We will eventually replace the 0 with the number of
2395 groups inner to this one. But do not push a
2396 start_memory for groups beyond the last one we can
2397 represent in the compiled pattern. */
2398 if (regnum <= MAX_REGNUM)
2399 {
2400 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2401 BUF_PUSH_3 (start_memory, regnum, 0);
2402 }
2403
2404 compile_stack.avail++;
2405
2406 fixup_alt_jump = 0;
2407 laststart = 0;
2408 begalt = b;
2409 /* If we've reached MAX_REGNUM groups, then this open
2410 won't actually generate any code, so we'll have to
2411 clear pending_exact explicitly. */
2412 pending_exact = 0;
2413 break;
2414
2415
2416 case ')':
2417 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2418
2419 if (COMPILE_STACK_EMPTY)
2420 {
2421 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2422 goto normal_backslash;
2423 else
2424 FREE_STACK_RETURN (REG_ERPAREN);
2425 }
2426
2427 handle_close:
2428 if (fixup_alt_jump)
2429 { /* Push a dummy failure point at the end of the
2430 alternative for a possible future
2431 `pop_failure_jump' to pop. See comments at
2432 `push_dummy_failure' in `re_match_2'. */
2433 BUF_PUSH (push_dummy_failure);
2434
2435 /* We allocated space for this jump when we assigned
2436 to `fixup_alt_jump', in the `handle_alt' case below. */
2437 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2438 }
2439
2440 /* See similar code for backslashed left paren above. */
2441 if (COMPILE_STACK_EMPTY)
2442 {
2443 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2444 goto normal_char;
2445 else
2446 FREE_STACK_RETURN (REG_ERPAREN);
2447 }
2448
2449 /* Since we just checked for an empty stack above, this
2450 ``can't happen''. */
2451 assert (compile_stack.avail != 0);
2452 {
2453 /* We don't just want to restore into `regnum', because
2454 later groups should continue to be numbered higher,
2455 as in `(ab)c(de)' -- the second group is #2. */
2456 regnum_t this_group_regnum;
2457
2458 compile_stack.avail--;
2459 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2460 fixup_alt_jump
2461 = COMPILE_STACK_TOP.fixup_alt_jump
2462 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2463 : 0;
2464 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2465 this_group_regnum = COMPILE_STACK_TOP.regnum;
2466 /* If we've reached MAX_REGNUM groups, then this open
2467 won't actually generate any code, so we'll have to
2468 clear pending_exact explicitly. */
2469 pending_exact = 0;
2470
2471 /* We're at the end of the group, so now we know how many
2472 groups were inside this one. */
2473 if (this_group_regnum <= MAX_REGNUM)
2474 {
2475 unsigned char *inner_group_loc
2476 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2477
2478 *inner_group_loc = regnum - this_group_regnum;
2479 BUF_PUSH_3 (stop_memory, this_group_regnum,
2480 regnum - this_group_regnum);
2481 }
2482 }
2483 break;
2484
2485
2486 case '|': /* `\|'. */
2487 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2488 goto normal_backslash;
2489 handle_alt:
2490 if (syntax & RE_LIMITED_OPS)
2491 goto normal_char;
2492
2493 /* Insert before the previous alternative a jump which
2494 jumps to this alternative if the former fails. */
2495 GET_BUFFER_SPACE (3);
2496 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2497 pending_exact = 0;
2498 b += 3;
2499
2500 /* The alternative before this one has a jump after it
2501 which gets executed if it gets matched. Adjust that
2502 jump so it will jump to this alternative's analogous
2503 jump (put in below, which in turn will jump to the next
2504 (if any) alternative's such jump, etc.). The last such
2505 jump jumps to the correct final destination. A picture:
2506 _____ _____
2507 | | | |
2508 | v | v
2509 a | b | c
2510
2511 If we are at `b', then fixup_alt_jump right now points to a
2512 three-byte space after `a'. We'll put in the jump, set
2513 fixup_alt_jump to right after `b', and leave behind three
2514 bytes which we'll fill in when we get to after `c'. */
2515
2516 if (fixup_alt_jump)
2517 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2518
2519 /* Mark and leave space for a jump after this alternative,
2520 to be filled in later either by next alternative or
2521 when know we're at the end of a series of alternatives. */
2522 fixup_alt_jump = b;
2523 GET_BUFFER_SPACE (3);
2524 b += 3;
2525
2526 laststart = 0;
2527 begalt = b;
2528 break;
2529
2530
2531 case '{':
2532 /* If \{ is a literal. */
2533 if (!(syntax & RE_INTERVALS)
2534 /* If we're at `\{' and it's not the open-interval
2535 operator. */
2536 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2537 || (p - 2 == pattern && p == pend))
2538 goto normal_backslash;
2539
2540 handle_interval:
2541 {
2542 /* If got here, then the syntax allows intervals. */
2543
2544 /* At least (most) this many matches must be made. */
2545 int lower_bound = -1, upper_bound = -1;
2546
2547 beg_interval = p - 1;
2548
2549 if (p == pend)
2550 {
2551 if (syntax & RE_NO_BK_BRACES)
2552 goto unfetch_interval;
2553 else
2554 FREE_STACK_RETURN (REG_EBRACE);
2555 }
2556
2557 GET_UNSIGNED_NUMBER (lower_bound);
2558
2559 if (c == ',')
2560 {
2561 GET_UNSIGNED_NUMBER (upper_bound);
2562 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2563 }
2564 else
2565 /* Interval such as `{1}' => match exactly once. */
2566 upper_bound = lower_bound;
2567
2568 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2569 || lower_bound > upper_bound)
2570 {
2571 if (syntax & RE_NO_BK_BRACES)
2572 goto unfetch_interval;
2573 else
2574 FREE_STACK_RETURN (REG_BADBR);
2575 }
2576
2577 if (!(syntax & RE_NO_BK_BRACES))
2578 {
2579 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2580
2581 PATFETCH (c);
2582 }
2583
2584 if (c != '}')
2585 {
2586 if (syntax & RE_NO_BK_BRACES)
2587 goto unfetch_interval;
2588 else
2589 FREE_STACK_RETURN (REG_BADBR);
2590 }
2591
2592 /* We just parsed a valid interval. */
2593
2594 /* If it's invalid to have no preceding re. */
2595 if (!laststart)
2596 {
2597 if (syntax & RE_CONTEXT_INVALID_OPS)
2598 FREE_STACK_RETURN (REG_BADRPT);
2599 else if (syntax & RE_CONTEXT_INDEP_OPS)
2600 laststart = b;
2601 else
2602 goto unfetch_interval;
2603 }
2604
2605 /* If the upper bound is zero, don't want to succeed at
2606 all; jump from `laststart' to `b + 3', which will be
2607 the end of the buffer after we insert the jump. */
2608 if (upper_bound == 0)
2609 {
2610 GET_BUFFER_SPACE (3);
2611 INSERT_JUMP (jump, laststart, b + 3);
2612 b += 3;
2613 }
2614
2615 /* Otherwise, we have a nontrivial interval. When
2616 we're all done, the pattern will look like:
2617 set_number_at <jump count> <upper bound>
2618 set_number_at <succeed_n count> <lower bound>
2619 succeed_n <after jump addr> <succeed_n count>
2620 <body of loop>
2621 jump_n <succeed_n addr> <jump count>
2622 (The upper bound and `jump_n' are omitted if
2623 `upper_bound' is 1, though.) */
2624 else
2625 { /* If the upper bound is > 1, we need to insert
2626 more at the end of the loop. */
2627 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2628
2629 GET_BUFFER_SPACE (nbytes);
2630
2631 /* Initialize lower bound of the `succeed_n', even
2632 though it will be set during matching by its
2633 attendant `set_number_at' (inserted next),
2634 because `re_compile_fastmap' needs to know.
2635 Jump to the `jump_n' we might insert below. */
2636 INSERT_JUMP2 (succeed_n, laststart,
2637 b + 5 + (upper_bound > 1) * 5,
2638 lower_bound);
2639 b += 5;
2640
2641 /* Code to initialize the lower bound. Insert
2642 before the `succeed_n'. The `5' is the last two
2643 bytes of this `set_number_at', plus 3 bytes of
2644 the following `succeed_n'. */
2645 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2646 b += 5;
2647
2648 if (upper_bound > 1)
2649 { /* More than one repetition is allowed, so
2650 append a backward jump to the `succeed_n'
2651 that starts this interval.
2652
2653 When we've reached this during matching,
2654 we'll have matched the interval once, so
2655 jump back only `upper_bound - 1' times. */
2656 STORE_JUMP2 (jump_n, b, laststart + 5,
2657 upper_bound - 1);
2658 b += 5;
2659
2660 /* The location we want to set is the second
2661 parameter of the `jump_n'; that is `b-2' as
2662 an absolute address. `laststart' will be
2663 the `set_number_at' we're about to insert;
2664 `laststart+3' the number to set, the source
2665 for the relative address. But we are
2666 inserting into the middle of the pattern --
2667 so everything is getting moved up by 5.
2668 Conclusion: (b - 2) - (laststart + 3) + 5,
2669 i.e., b - laststart.
2670
2671 We insert this at the beginning of the loop
2672 so that if we fail during matching, we'll
2673 reinitialize the bounds. */
2674 insert_op2 (set_number_at, laststart, b - laststart,
2675 upper_bound - 1, b);
2676 b += 5;
2677 }
2678 }
2679 pending_exact = 0;
2680 beg_interval = NULL;
2681 }
2682 break;
2683
2684 unfetch_interval:
2685 /* If an invalid interval, match the characters as literals. */
2686 assert (beg_interval);
2687 p = beg_interval;
2688 beg_interval = NULL;
2689
2690 /* normal_char and normal_backslash need `c'. */
2691 PATFETCH (c);
2692
2693 if (!(syntax & RE_NO_BK_BRACES))
2694 {
2695 if (p > pattern && p[-1] == '\\')
2696 goto normal_backslash;
2697 }
2698 goto normal_char;
2699
2700 #ifdef emacs
2701 /* There is no way to specify the before_dot and after_dot
2702 operators. rms says this is ok. --karl */
2703 case '=':
2704 BUF_PUSH (at_dot);
2705 break;
2706
2707 case 's':
2708 laststart = b;
2709 PATFETCH (c);
2710 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2711 break;
2712
2713 case 'S':
2714 laststart = b;
2715 PATFETCH (c);
2716 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2717 break;
2718 #endif /* emacs */
2719
2720
2721 case 'w':
2722 if (syntax & RE_NO_GNU_OPS)
2723 goto normal_char;
2724 laststart = b;
2725 BUF_PUSH (wordchar);
2726 break;
2727
2728
2729 case 'W':
2730 if (syntax & RE_NO_GNU_OPS)
2731 goto normal_char;
2732 laststart = b;
2733 BUF_PUSH (notwordchar);
2734 break;
2735
2736
2737 case '<':
2738 if (syntax & RE_NO_GNU_OPS)
2739 goto normal_char;
2740 BUF_PUSH (wordbeg);
2741 break;
2742
2743 case '>':
2744 if (syntax & RE_NO_GNU_OPS)
2745 goto normal_char;
2746 BUF_PUSH (wordend);
2747 break;
2748
2749 case 'b':
2750 if (syntax & RE_NO_GNU_OPS)
2751 goto normal_char;
2752 BUF_PUSH (wordbound);
2753 break;
2754
2755 case 'B':
2756 if (syntax & RE_NO_GNU_OPS)
2757 goto normal_char;
2758 BUF_PUSH (notwordbound);
2759 break;
2760
2761 case '`':
2762 if (syntax & RE_NO_GNU_OPS)
2763 goto normal_char;
2764 BUF_PUSH (begbuf);
2765 break;
2766
2767 case '\'':
2768 if (syntax & RE_NO_GNU_OPS)
2769 goto normal_char;
2770 BUF_PUSH (endbuf);
2771 break;
2772
2773 case '1': case '2': case '3': case '4': case '5':
2774 case '6': case '7': case '8': case '9':
2775 if (syntax & RE_NO_BK_REFS)
2776 goto normal_char;
2777
2778 c1 = c - '0';
2779
2780 if (c1 > regnum)
2781 FREE_STACK_RETURN (REG_ESUBREG);
2782
2783 /* Can't back reference to a subexpression if inside of it. */
2784 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
2785 goto normal_char;
2786
2787 laststart = b;
2788 BUF_PUSH_2 (duplicate, c1);
2789 break;
2790
2791
2792 case '+':
2793 case '?':
2794 if (syntax & RE_BK_PLUS_QM)
2795 goto handle_plus;
2796 else
2797 goto normal_backslash;
2798
2799 default:
2800 normal_backslash:
2801 /* You might think it would be useful for \ to mean
2802 not to translate; but if we don't translate it
2803 it will never match anything. */
2804 c = TRANSLATE (c);
2805 goto normal_char;
2806 }
2807 break;
2808
2809
2810 default:
2811 /* Expects the character in `c'. */
2812 normal_char:
2813 /* If no exactn currently being built. */
2814 if (!pending_exact
2815
2816 /* If last exactn not at current position. */
2817 || pending_exact + *pending_exact + 1 != b
2818
2819 /* We have only one byte following the exactn for the count. */
2820 || *pending_exact == (1 << BYTEWIDTH) - 1
2821
2822 /* If followed by a repetition operator. */
2823 || *p == '*' || *p == '^'
2824 || ((syntax & RE_BK_PLUS_QM)
2825 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2826 : (*p == '+' || *p == '?'))
2827 || ((syntax & RE_INTERVALS)
2828 && ((syntax & RE_NO_BK_BRACES)
2829 ? *p == '{'
2830 : (p[0] == '\\' && p[1] == '{'))))
2831 {
2832 /* Start building a new exactn. */
2833
2834 laststart = b;
2835
2836 BUF_PUSH_2 (exactn, 0);
2837 pending_exact = b - 1;
2838 }
2839
2840 BUF_PUSH (c);
2841 (*pending_exact)++;
2842 break;
2843 } /* switch (c) */
2844 } /* while p != pend */
2845
2846
2847 /* Through the pattern now. */
2848
2849 if (fixup_alt_jump)
2850 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2851
2852 if (!COMPILE_STACK_EMPTY)
2853 FREE_STACK_RETURN (REG_EPAREN);
2854
2855 /* If we don't want backtracking, force success
2856 the first time we reach the end of the compiled pattern. */
2857 if (syntax & RE_NO_POSIX_BACKTRACKING)
2858 BUF_PUSH (succeed);
2859
2860 free (compile_stack.stack);
2861
2862 /* We have succeeded; set the length of the buffer. */
2863 bufp->used = b - bufp->buffer;
2864
2865 #ifdef DEBUG
2866 if (debug)
2867 {
2868 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2869 print_compiled_pattern (bufp);
2870 }
2871 #endif /* DEBUG */
2872
2873 #ifndef MATCH_MAY_ALLOCATE
2874 /* Initialize the failure stack to the largest possible stack. This
2875 isn't necessary unless we're trying to avoid calling alloca in
2876 the search and match routines. */
2877 {
2878 int num_regs = bufp->re_nsub + 1;
2879
2880 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
2881 is strictly greater than re_max_failures, the largest possible stack
2882 is 2 * re_max_failures failure points. */
2883 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
2884 {
2885 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
2886
2887 # ifdef emacs
2888 if (! fail_stack.stack)
2889 fail_stack.stack
2890 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2891 * sizeof (fail_stack_elt_t));
2892 else
2893 fail_stack.stack
2894 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2895 (fail_stack.size
2896 * sizeof (fail_stack_elt_t)));
2897 # else /* not emacs */
2898 if (! fail_stack.stack)
2899 fail_stack.stack
2900 = (fail_stack_elt_t *) malloc (fail_stack.size
2901 * sizeof (fail_stack_elt_t));
2902 else
2903 fail_stack.stack
2904 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2905 (fail_stack.size
2906 * sizeof (fail_stack_elt_t)));
2907 # endif /* not emacs */
2908 }
2909
2910 regex_grow_registers (num_regs);
2911 }
2912 #endif /* not MATCH_MAY_ALLOCATE */
2913
2914 return REG_NOERROR;
2915 } /* regex_compile */
2916 \f
2917 /* Subroutines for `regex_compile'. */
2918
2919 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2920
2921 static void
2922 store_op1 (op, loc, arg)
2923 re_opcode_t op;
2924 unsigned char *loc;
2925 int arg;
2926 {
2927 *loc = (unsigned char) op;
2928 STORE_NUMBER (loc + 1, arg);
2929 }
2930
2931
2932 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2933
2934 static void
2935 store_op2 (op, loc, arg1, arg2)
2936 re_opcode_t op;
2937 unsigned char *loc;
2938 int arg1, arg2;
2939 {
2940 *loc = (unsigned char) op;
2941 STORE_NUMBER (loc + 1, arg1);
2942 STORE_NUMBER (loc + 3, arg2);
2943 }
2944
2945
2946 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2947 for OP followed by two-byte integer parameter ARG. */
2948
2949 static void
2950 insert_op1 (op, loc, arg, end)
2951 re_opcode_t op;
2952 unsigned char *loc;
2953 int arg;
2954 unsigned char *end;
2955 {
2956 register unsigned char *pfrom = end;
2957 register unsigned char *pto = end + 3;
2958
2959 while (pfrom != loc)
2960 *--pto = *--pfrom;
2961
2962 store_op1 (op, loc, arg);
2963 }
2964
2965
2966 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2967
2968 static void
2969 insert_op2 (op, loc, arg1, arg2, end)
2970 re_opcode_t op;
2971 unsigned char *loc;
2972 int arg1, arg2;
2973 unsigned char *end;
2974 {
2975 register unsigned char *pfrom = end;
2976 register unsigned char *pto = end + 5;
2977
2978 while (pfrom != loc)
2979 *--pto = *--pfrom;
2980
2981 store_op2 (op, loc, arg1, arg2);
2982 }
2983
2984
2985 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2986 after an alternative or a begin-subexpression. We assume there is at
2987 least one character before the ^. */
2988
2989 static boolean
2990 at_begline_loc_p (pattern, p, syntax)
2991 const char *pattern, *p;
2992 reg_syntax_t syntax;
2993 {
2994 const char *prev = p - 2;
2995 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2996
2997 return
2998 /* After a subexpression? */
2999 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3000 /* After an alternative? */
3001 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3002 }
3003
3004
3005 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3006 at least one character after the $, i.e., `P < PEND'. */
3007
3008 static boolean
3009 at_endline_loc_p (p, pend, syntax)
3010 const char *p, *pend;
3011 reg_syntax_t syntax;
3012 {
3013 const char *next = p;
3014 boolean next_backslash = *next == '\\';
3015 const char *next_next = p + 1 < pend ? p + 1 : 0;
3016
3017 return
3018 /* Before a subexpression? */
3019 (syntax & RE_NO_BK_PARENS ? *next == ')'
3020 : next_backslash && next_next && *next_next == ')')
3021 /* Before an alternative? */
3022 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3023 : next_backslash && next_next && *next_next == '|');
3024 }
3025
3026
3027 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3028 false if it's not. */
3029
3030 static boolean
3031 group_in_compile_stack (compile_stack, regnum)
3032 compile_stack_type compile_stack;
3033 regnum_t regnum;
3034 {
3035 int this_element;
3036
3037 for (this_element = compile_stack.avail - 1;
3038 this_element >= 0;
3039 this_element--)
3040 if (compile_stack.stack[this_element].regnum == regnum)
3041 return true;
3042
3043 return false;
3044 }
3045
3046
3047 /* Read the ending character of a range (in a bracket expression) from the
3048 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3049 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3050 Then we set the translation of all bits between the starting and
3051 ending characters (inclusive) in the compiled pattern B.
3052
3053 Return an error code.
3054
3055 We use these short variable names so we can use the same macros as
3056 `regex_compile' itself. */
3057
3058 static reg_errcode_t
3059 compile_range (p_ptr, pend, translate, syntax, b)
3060 const char **p_ptr, *pend;
3061 RE_TRANSLATE_TYPE translate;
3062 reg_syntax_t syntax;
3063 unsigned char *b;
3064 {
3065 unsigned this_char;
3066
3067 const char *p = *p_ptr;
3068 unsigned int range_start, range_end;
3069
3070 if (p == pend)
3071 return REG_ERANGE;
3072
3073 /* Even though the pattern is a signed `char *', we need to fetch
3074 with unsigned char *'s; if the high bit of the pattern character
3075 is set, the range endpoints will be negative if we fetch using a
3076 signed char *.
3077
3078 We also want to fetch the endpoints without translating them; the
3079 appropriate translation is done in the bit-setting loop below. */
3080 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
3081 range_start = ((const unsigned char *) p)[-2];
3082 range_end = ((const unsigned char *) p)[0];
3083
3084 /* Have to increment the pointer into the pattern string, so the
3085 caller isn't still at the ending character. */
3086 (*p_ptr)++;
3087
3088 /* If the start is after the end, the range is empty. */
3089 if (range_start > range_end)
3090 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
3091
3092 /* Here we see why `this_char' has to be larger than an `unsigned
3093 char' -- the range is inclusive, so if `range_end' == 0xff
3094 (assuming 8-bit characters), we would otherwise go into an infinite
3095 loop, since all characters <= 0xff. */
3096 for (this_char = range_start; this_char <= range_end; this_char++)
3097 {
3098 SET_LIST_BIT (TRANSLATE (this_char));
3099 }
3100
3101 return REG_NOERROR;
3102 }
3103 \f
3104 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3105 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3106 characters can start a string that matches the pattern. This fastmap
3107 is used by re_search to skip quickly over impossible starting points.
3108
3109 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3110 area as BUFP->fastmap.
3111
3112 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3113 the pattern buffer.
3114
3115 Returns 0 if we succeed, -2 if an internal error. */
3116
3117 int
3118 re_compile_fastmap (bufp)
3119 struct re_pattern_buffer *bufp;
3120 {
3121 int j, k;
3122 #ifdef MATCH_MAY_ALLOCATE
3123 fail_stack_type fail_stack;
3124 #endif
3125 #ifndef REGEX_MALLOC
3126 char *destination;
3127 #endif
3128
3129 register char *fastmap = bufp->fastmap;
3130 unsigned char *pattern = bufp->buffer;
3131 unsigned char *p = pattern;
3132 register unsigned char *pend = pattern + bufp->used;
3133
3134 #ifdef REL_ALLOC
3135 /* This holds the pointer to the failure stack, when
3136 it is allocated relocatably. */
3137 fail_stack_elt_t *failure_stack_ptr;
3138 #endif
3139
3140 /* Assume that each path through the pattern can be null until
3141 proven otherwise. We set this false at the bottom of switch
3142 statement, to which we get only if a particular path doesn't
3143 match the empty string. */
3144 boolean path_can_be_null = true;
3145
3146 /* We aren't doing a `succeed_n' to begin with. */
3147 boolean succeed_n_p = false;
3148
3149 assert (fastmap != NULL && p != NULL);
3150
3151 INIT_FAIL_STACK ();
3152 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3153 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3154 bufp->can_be_null = 0;
3155
3156 while (1)
3157 {
3158 if (p == pend || *p == succeed)
3159 {
3160 /* We have reached the (effective) end of pattern. */
3161 if (!FAIL_STACK_EMPTY ())
3162 {
3163 bufp->can_be_null |= path_can_be_null;
3164
3165 /* Reset for next path. */
3166 path_can_be_null = true;
3167
3168 p = fail_stack.stack[--fail_stack.avail].pointer;
3169
3170 continue;
3171 }
3172 else
3173 break;
3174 }
3175
3176 /* We should never be about to go beyond the end of the pattern. */
3177 assert (p < pend);
3178
3179 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3180 {
3181
3182 /* I guess the idea here is to simply not bother with a fastmap
3183 if a backreference is used, since it's too hard to figure out
3184 the fastmap for the corresponding group. Setting
3185 `can_be_null' stops `re_search_2' from using the fastmap, so
3186 that is all we do. */
3187 case duplicate:
3188 bufp->can_be_null = 1;
3189 goto done;
3190
3191
3192 /* Following are the cases which match a character. These end
3193 with `break'. */
3194
3195 case exactn:
3196 fastmap[p[1]] = 1;
3197 break;
3198
3199
3200 case charset:
3201 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3202 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3203 fastmap[j] = 1;
3204 break;
3205
3206
3207 case charset_not:
3208 /* Chars beyond end of map must be allowed. */
3209 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3210 fastmap[j] = 1;
3211
3212 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3213 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3214 fastmap[j] = 1;
3215 break;
3216
3217
3218 case wordchar:
3219 for (j = 0; j < (1 << BYTEWIDTH); j++)
3220 if (SYNTAX (j) == Sword)
3221 fastmap[j] = 1;
3222 break;
3223
3224
3225 case notwordchar:
3226 for (j = 0; j < (1 << BYTEWIDTH); j++)
3227 if (SYNTAX (j) != Sword)
3228 fastmap[j] = 1;
3229 break;
3230
3231
3232 case anychar:
3233 {
3234 int fastmap_newline = fastmap['\n'];
3235
3236 /* `.' matches anything ... */
3237 for (j = 0; j < (1 << BYTEWIDTH); j++)
3238 fastmap[j] = 1;
3239
3240 /* ... except perhaps newline. */
3241 if (!(bufp->syntax & RE_DOT_NEWLINE))
3242 fastmap['\n'] = fastmap_newline;
3243
3244 /* Return if we have already set `can_be_null'; if we have,
3245 then the fastmap is irrelevant. Something's wrong here. */
3246 else if (bufp->can_be_null)
3247 goto done;
3248
3249 /* Otherwise, have to check alternative paths. */
3250 break;
3251 }
3252
3253 #ifdef emacs
3254 case syntaxspec:
3255 k = *p++;
3256 for (j = 0; j < (1 << BYTEWIDTH); j++)
3257 if (SYNTAX (j) == (enum syntaxcode) k)
3258 fastmap[j] = 1;
3259 break;
3260
3261
3262 case notsyntaxspec:
3263 k = *p++;
3264 for (j = 0; j < (1 << BYTEWIDTH); j++)
3265 if (SYNTAX (j) != (enum syntaxcode) k)
3266 fastmap[j] = 1;
3267 break;
3268
3269
3270 /* All cases after this match the empty string. These end with
3271 `continue'. */
3272
3273
3274 case before_dot:
3275 case at_dot:
3276 case after_dot:
3277 continue;
3278 #endif /* emacs */
3279
3280
3281 case no_op:
3282 case begline:
3283 case endline:
3284 case begbuf:
3285 case endbuf:
3286 case wordbound:
3287 case notwordbound:
3288 case wordbeg:
3289 case wordend:
3290 case push_dummy_failure:
3291 continue;
3292
3293
3294 case jump_n:
3295 case pop_failure_jump:
3296 case maybe_pop_jump:
3297 case jump:
3298 case jump_past_alt:
3299 case dummy_failure_jump:
3300 EXTRACT_NUMBER_AND_INCR (j, p);
3301 p += j;
3302 if (j > 0)
3303 continue;
3304
3305 /* Jump backward implies we just went through the body of a
3306 loop and matched nothing. Opcode jumped to should be
3307 `on_failure_jump' or `succeed_n'. Just treat it like an
3308 ordinary jump. For a * loop, it has pushed its failure
3309 point already; if so, discard that as redundant. */
3310 if ((re_opcode_t) *p != on_failure_jump
3311 && (re_opcode_t) *p != succeed_n)
3312 continue;
3313
3314 p++;
3315 EXTRACT_NUMBER_AND_INCR (j, p);
3316 p += j;
3317
3318 /* If what's on the stack is where we are now, pop it. */
3319 if (!FAIL_STACK_EMPTY ()
3320 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3321 fail_stack.avail--;
3322
3323 continue;
3324
3325
3326 case on_failure_jump:
3327 case on_failure_keep_string_jump:
3328 handle_on_failure_jump:
3329 EXTRACT_NUMBER_AND_INCR (j, p);
3330
3331 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3332 end of the pattern. We don't want to push such a point,
3333 since when we restore it above, entering the switch will
3334 increment `p' past the end of the pattern. We don't need
3335 to push such a point since we obviously won't find any more
3336 fastmap entries beyond `pend'. Such a pattern can match
3337 the null string, though. */
3338 if (p + j < pend)
3339 {
3340 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3341 {
3342 RESET_FAIL_STACK ();
3343 return -2;
3344 }
3345 }
3346 else
3347 bufp->can_be_null = 1;
3348
3349 if (succeed_n_p)
3350 {
3351 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3352 succeed_n_p = false;
3353 }
3354
3355 continue;
3356
3357
3358 case succeed_n:
3359 /* Get to the number of times to succeed. */
3360 p += 2;
3361
3362 /* Increment p past the n for when k != 0. */
3363 EXTRACT_NUMBER_AND_INCR (k, p);
3364 if (k == 0)
3365 {
3366 p -= 4;
3367 succeed_n_p = true; /* Spaghetti code alert. */
3368 goto handle_on_failure_jump;
3369 }
3370 continue;
3371
3372
3373 case set_number_at:
3374 p += 4;
3375 continue;
3376
3377
3378 case start_memory:
3379 case stop_memory:
3380 p += 2;
3381 continue;
3382
3383
3384 default:
3385 abort (); /* We have listed all the cases. */
3386 } /* switch *p++ */
3387
3388 /* Getting here means we have found the possible starting
3389 characters for one path of the pattern -- and that the empty
3390 string does not match. We need not follow this path further.
3391 Instead, look at the next alternative (remembered on the
3392 stack), or quit if no more. The test at the top of the loop
3393 does these things. */
3394 path_can_be_null = false;
3395 p = pend;
3396 } /* while p */
3397
3398 /* Set `can_be_null' for the last path (also the first path, if the
3399 pattern is empty). */
3400 bufp->can_be_null |= path_can_be_null;
3401
3402 done:
3403 RESET_FAIL_STACK ();
3404 return 0;
3405 } /* re_compile_fastmap */
3406 #ifdef _LIBC
3407 weak_alias (__re_compile_fastmap, re_compile_fastmap)
3408 #endif
3409 \f
3410 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3411 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3412 this memory for recording register information. STARTS and ENDS
3413 must be allocated using the malloc library routine, and must each
3414 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3415
3416 If NUM_REGS == 0, then subsequent matches should allocate their own
3417 register data.
3418
3419 Unless this function is called, the first search or match using
3420 PATTERN_BUFFER will allocate its own register data, without
3421 freeing the old data. */
3422
3423 void
3424 re_set_registers (bufp, regs, num_regs, starts, ends)
3425 struct re_pattern_buffer *bufp;
3426 struct re_registers *regs;
3427 unsigned num_regs;
3428 regoff_t *starts, *ends;
3429 {
3430 if (num_regs)
3431 {
3432 bufp->regs_allocated = REGS_REALLOCATE;
3433 regs->num_regs = num_regs;
3434 regs->start = starts;
3435 regs->end = ends;
3436 }
3437 else
3438 {
3439 bufp->regs_allocated = REGS_UNALLOCATED;
3440 regs->num_regs = 0;
3441 regs->start = regs->end = (regoff_t *) 0;
3442 }
3443 }
3444 #ifdef _LIBC
3445 weak_alias (__re_set_registers, re_set_registers)
3446 #endif
3447 \f
3448 /* Searching routines. */
3449
3450 /* Like re_search_2, below, but only one string is specified, and
3451 doesn't let you say where to stop matching. */
3452
3453 int
3454 re_search (bufp, string, size, startpos, range, regs)
3455 struct re_pattern_buffer *bufp;
3456 const char *string;
3457 int size, startpos, range;
3458 struct re_registers *regs;
3459 {
3460 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3461 regs, size);
3462 }
3463 #ifdef _LIBC
3464 weak_alias (__re_search, re_search)
3465 #endif
3466
3467
3468 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3469 virtual concatenation of STRING1 and STRING2, starting first at index
3470 STARTPOS, then at STARTPOS + 1, and so on.
3471
3472 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3473
3474 RANGE is how far to scan while trying to match. RANGE = 0 means try
3475 only at STARTPOS; in general, the last start tried is STARTPOS +
3476 RANGE.
3477
3478 In REGS, return the indices of the virtual concatenation of STRING1
3479 and STRING2 that matched the entire BUFP->buffer and its contained
3480 subexpressions.
3481
3482 Do not consider matching one past the index STOP in the virtual
3483 concatenation of STRING1 and STRING2.
3484
3485 We return either the position in the strings at which the match was
3486 found, -1 if no match, or -2 if error (such as failure
3487 stack overflow). */
3488
3489 int
3490 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3491 struct re_pattern_buffer *bufp;
3492 const char *string1, *string2;
3493 int size1, size2;
3494 int startpos;
3495 int range;
3496 struct re_registers *regs;
3497 int stop;
3498 {
3499 int val;
3500 register char *fastmap = bufp->fastmap;
3501 register RE_TRANSLATE_TYPE translate = bufp->translate;
3502 int total_size = size1 + size2;
3503 int endpos = startpos + range;
3504
3505 /* Check for out-of-range STARTPOS. */
3506 if (startpos < 0 || startpos > total_size)
3507 return -1;
3508
3509 /* Fix up RANGE if it might eventually take us outside
3510 the virtual concatenation of STRING1 and STRING2.
3511 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3512 if (endpos < 0)
3513 range = 0 - startpos;
3514 else if (endpos > total_size)
3515 range = total_size - startpos;
3516
3517 /* If the search isn't to be a backwards one, don't waste time in a
3518 search for a pattern that must be anchored. */
3519 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3520 {
3521 if (startpos > 0)
3522 return -1;
3523 else
3524 range = 1;
3525 }
3526
3527 #ifdef emacs
3528 /* In a forward search for something that starts with \=.
3529 don't keep searching past point. */
3530 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3531 {
3532 range = PT - startpos;
3533 if (range <= 0)
3534 return -1;
3535 }
3536 #endif /* emacs */
3537
3538 /* Update the fastmap now if not correct already. */
3539 if (fastmap && !bufp->fastmap_accurate)
3540 if (re_compile_fastmap (bufp) == -2)
3541 return -2;
3542
3543 /* Loop through the string, looking for a place to start matching. */
3544 for (;;)
3545 {
3546 /* If a fastmap is supplied, skip quickly over characters that
3547 cannot be the start of a match. If the pattern can match the
3548 null string, however, we don't need to skip characters; we want
3549 the first null string. */
3550 if (fastmap && startpos < total_size && !bufp->can_be_null)
3551 {
3552 if (range > 0) /* Searching forwards. */
3553 {
3554 register const char *d;
3555 register int lim = 0;
3556 int irange = range;
3557
3558 if (startpos < size1 && startpos + range >= size1)
3559 lim = range - (size1 - startpos);
3560
3561 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
3562
3563 /* Written out as an if-else to avoid testing `translate'
3564 inside the loop. */
3565 if (translate)
3566 while (range > lim
3567 && !fastmap[(unsigned char)
3568 translate[(unsigned char) *d++]])
3569 range--;
3570 else
3571 while (range > lim && !fastmap[(unsigned char) *d++])
3572 range--;
3573
3574 startpos += irange - range;
3575 }
3576 else /* Searching backwards. */
3577 {
3578 register char c = (size1 == 0 || startpos >= size1
3579 ? string2[startpos - size1]
3580 : string1[startpos]);
3581
3582 if (!fastmap[(unsigned char) TRANSLATE (c)])
3583 goto advance;
3584 }
3585 }
3586
3587 /* If can't match the null string, and that's all we have left, fail. */
3588 if (range >= 0 && startpos == total_size && fastmap
3589 && !bufp->can_be_null)
3590 return -1;
3591
3592 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3593 startpos, regs, stop);
3594 #ifndef REGEX_MALLOC
3595 # ifdef C_ALLOCA
3596 alloca (0);
3597 # endif
3598 #endif
3599
3600 if (val >= 0)
3601 return startpos;
3602
3603 if (val == -2)
3604 return -2;
3605
3606 advance:
3607 if (!range)
3608 break;
3609 else if (range > 0)
3610 {
3611 range--;
3612 startpos++;
3613 }
3614 else
3615 {
3616 range++;
3617 startpos--;
3618 }
3619 }
3620 return -1;
3621 } /* re_search_2 */
3622 #ifdef _LIBC
3623 weak_alias (__re_search_2, re_search_2)
3624 #endif
3625 \f
3626 /* This converts PTR, a pointer into one of the search strings `string1'
3627 and `string2' into an offset from the beginning of that string. */
3628 #define POINTER_TO_OFFSET(ptr) \
3629 (FIRST_STRING_P (ptr) \
3630 ? ((regoff_t) ((ptr) - string1)) \
3631 : ((regoff_t) ((ptr) - string2 + size1)))
3632
3633 /* Macros for dealing with the split strings in re_match_2. */
3634
3635 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3636
3637 /* Call before fetching a character with *d. This switches over to
3638 string2 if necessary. */
3639 #define PREFETCH() \
3640 while (d == dend) \
3641 { \
3642 /* End of string2 => fail. */ \
3643 if (dend == end_match_2) \
3644 goto fail; \
3645 /* End of string1 => advance to string2. */ \
3646 d = string2; \
3647 dend = end_match_2; \
3648 }
3649
3650
3651 /* Test if at very beginning or at very end of the virtual concatenation
3652 of `string1' and `string2'. If only one string, it's `string2'. */
3653 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3654 #define AT_STRINGS_END(d) ((d) == end2)
3655
3656
3657 /* Test if D points to a character which is word-constituent. We have
3658 two special cases to check for: if past the end of string1, look at
3659 the first character in string2; and if before the beginning of
3660 string2, look at the last character in string1. */
3661 #define WORDCHAR_P(d) \
3662 (SYNTAX ((d) == end1 ? *string2 \
3663 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3664 == Sword)
3665
3666 /* Disabled due to a compiler bug -- see comment at case wordbound */
3667 #if 0
3668 /* Test if the character before D and the one at D differ with respect
3669 to being word-constituent. */
3670 #define AT_WORD_BOUNDARY(d) \
3671 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3672 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3673 #endif
3674
3675 /* Free everything we malloc. */
3676 #ifdef MATCH_MAY_ALLOCATE
3677 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
3678 # define FREE_VARIABLES() \
3679 do { \
3680 REGEX_FREE_STACK (fail_stack.stack); \
3681 FREE_VAR (regstart); \
3682 FREE_VAR (regend); \
3683 FREE_VAR (old_regstart); \
3684 FREE_VAR (old_regend); \
3685 FREE_VAR (best_regstart); \
3686 FREE_VAR (best_regend); \
3687 FREE_VAR (reg_info); \
3688 FREE_VAR (reg_dummy); \
3689 FREE_VAR (reg_info_dummy); \
3690 } while (0)
3691 #else
3692 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
3693 #endif /* not MATCH_MAY_ALLOCATE */
3694
3695 /* These values must meet several constraints. They must not be valid
3696 register values; since we have a limit of 255 registers (because
3697 we use only one byte in the pattern for the register number), we can
3698 use numbers larger than 255. They must differ by 1, because of
3699 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3700 be larger than the value for the highest register, so we do not try
3701 to actually save any registers when none are active. */
3702 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3703 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3704 \f
3705 /* Matching routines. */
3706
3707 #ifndef emacs /* Emacs never uses this. */
3708 /* re_match is like re_match_2 except it takes only a single string. */
3709
3710 int
3711 re_match (bufp, string, size, pos, regs)
3712 struct re_pattern_buffer *bufp;
3713 const char *string;
3714 int size, pos;
3715 struct re_registers *regs;
3716 {
3717 int result = re_match_2_internal (bufp, NULL, 0, string, size,
3718 pos, regs, size);
3719 # ifndef REGEX_MALLOC
3720 # ifdef C_ALLOCA
3721 alloca (0);
3722 # endif
3723 # endif
3724 return result;
3725 }
3726 # ifdef _LIBC
3727 weak_alias (__re_match, re_match)
3728 # endif
3729 #endif /* not emacs */
3730
3731 static boolean group_match_null_string_p _RE_ARGS ((unsigned char **p,
3732 unsigned char *end,
3733 register_info_type *reg_info));
3734 static boolean alt_match_null_string_p _RE_ARGS ((unsigned char *p,
3735 unsigned char *end,
3736 register_info_type *reg_info));
3737 static boolean common_op_match_null_string_p _RE_ARGS ((unsigned char **p,
3738 unsigned char *end,
3739 register_info_type *reg_info));
3740 static int bcmp_translate _RE_ARGS ((const char *s1, const char *s2,
3741 int len, char *translate));
3742
3743 /* re_match_2 matches the compiled pattern in BUFP against the
3744 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3745 and SIZE2, respectively). We start matching at POS, and stop
3746 matching at STOP.
3747
3748 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3749 store offsets for the substring each group matched in REGS. See the
3750 documentation for exactly how many groups we fill.
3751
3752 We return -1 if no match, -2 if an internal error (such as the
3753 failure stack overflowing). Otherwise, we return the length of the
3754 matched substring. */
3755
3756 int
3757 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3758 struct re_pattern_buffer *bufp;
3759 const char *string1, *string2;
3760 int size1, size2;
3761 int pos;
3762 struct re_registers *regs;
3763 int stop;
3764 {
3765 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
3766 pos, regs, stop);
3767 #ifndef REGEX_MALLOC
3768 # ifdef C_ALLOCA
3769 alloca (0);
3770 # endif
3771 #endif
3772 return result;
3773 }
3774 #ifdef _LIBC
3775 weak_alias (__re_match_2, re_match_2)
3776 #endif
3777
3778 /* This is a separate function so that we can force an alloca cleanup
3779 afterwards. */
3780 static int
3781 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
3782 struct re_pattern_buffer *bufp;
3783 const char *string1, *string2;
3784 int size1, size2;
3785 int pos;
3786 struct re_registers *regs;
3787 int stop;
3788 {
3789 /* General temporaries. */
3790 int mcnt;
3791 unsigned char *p1;
3792
3793 /* Just past the end of the corresponding string. */
3794 const char *end1, *end2;
3795
3796 /* Pointers into string1 and string2, just past the last characters in
3797 each to consider matching. */
3798 const char *end_match_1, *end_match_2;
3799
3800 /* Where we are in the data, and the end of the current string. */
3801 const char *d, *dend;
3802
3803 /* Where we are in the pattern, and the end of the pattern. */
3804 unsigned char *p = bufp->buffer;
3805 register unsigned char *pend = p + bufp->used;
3806
3807 /* Mark the opcode just after a start_memory, so we can test for an
3808 empty subpattern when we get to the stop_memory. */
3809 unsigned char *just_past_start_mem = 0;
3810
3811 /* We use this to map every character in the string. */
3812 RE_TRANSLATE_TYPE translate = bufp->translate;
3813
3814 /* Failure point stack. Each place that can handle a failure further
3815 down the line pushes a failure point on this stack. It consists of
3816 restart, regend, and reg_info for all registers corresponding to
3817 the subexpressions we're currently inside, plus the number of such
3818 registers, and, finally, two char *'s. The first char * is where
3819 to resume scanning the pattern; the second one is where to resume
3820 scanning the strings. If the latter is zero, the failure point is
3821 a ``dummy''; if a failure happens and the failure point is a dummy,
3822 it gets discarded and the next next one is tried. */
3823 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3824 fail_stack_type fail_stack;
3825 #endif
3826 #ifdef DEBUG
3827 static unsigned failure_id = 0;
3828 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3829 #endif
3830
3831 #ifdef REL_ALLOC
3832 /* This holds the pointer to the failure stack, when
3833 it is allocated relocatably. */
3834 fail_stack_elt_t *failure_stack_ptr;
3835 #endif
3836
3837 /* We fill all the registers internally, independent of what we
3838 return, for use in backreferences. The number here includes
3839 an element for register zero. */
3840 size_t num_regs = bufp->re_nsub + 1;
3841
3842 /* The currently active registers. */
3843 active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3844 active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3845
3846 /* Information on the contents of registers. These are pointers into
3847 the input strings; they record just what was matched (on this
3848 attempt) by a subexpression part of the pattern, that is, the
3849 regnum-th regstart pointer points to where in the pattern we began
3850 matching and the regnum-th regend points to right after where we
3851 stopped matching the regnum-th subexpression. (The zeroth register
3852 keeps track of what the whole pattern matches.) */
3853 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3854 const char **regstart, **regend;
3855 #endif
3856
3857 /* If a group that's operated upon by a repetition operator fails to
3858 match anything, then the register for its start will need to be
3859 restored because it will have been set to wherever in the string we
3860 are when we last see its open-group operator. Similarly for a
3861 register's end. */
3862 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3863 const char **old_regstart, **old_regend;
3864 #endif
3865
3866 /* The is_active field of reg_info helps us keep track of which (possibly
3867 nested) subexpressions we are currently in. The matched_something
3868 field of reg_info[reg_num] helps us tell whether or not we have
3869 matched any of the pattern so far this time through the reg_num-th
3870 subexpression. These two fields get reset each time through any
3871 loop their register is in. */
3872 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3873 register_info_type *reg_info;
3874 #endif
3875
3876 /* The following record the register info as found in the above
3877 variables when we find a match better than any we've seen before.
3878 This happens as we backtrack through the failure points, which in
3879 turn happens only if we have not yet matched the entire string. */
3880 unsigned best_regs_set = false;
3881 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3882 const char **best_regstart, **best_regend;
3883 #endif
3884
3885 /* Logically, this is `best_regend[0]'. But we don't want to have to
3886 allocate space for that if we're not allocating space for anything
3887 else (see below). Also, we never need info about register 0 for
3888 any of the other register vectors, and it seems rather a kludge to
3889 treat `best_regend' differently than the rest. So we keep track of
3890 the end of the best match so far in a separate variable. We
3891 initialize this to NULL so that when we backtrack the first time
3892 and need to test it, it's not garbage. */
3893 const char *match_end = NULL;
3894
3895 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
3896 int set_regs_matched_done = 0;
3897
3898 /* Used when we pop values we don't care about. */
3899 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3900 const char **reg_dummy;
3901 register_info_type *reg_info_dummy;
3902 #endif
3903
3904 #ifdef DEBUG
3905 /* Counts the total number of registers pushed. */
3906 unsigned num_regs_pushed = 0;
3907 #endif
3908
3909 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3910
3911 INIT_FAIL_STACK ();
3912
3913 #ifdef MATCH_MAY_ALLOCATE
3914 /* Do not bother to initialize all the register variables if there are
3915 no groups in the pattern, as it takes a fair amount of time. If
3916 there are groups, we include space for register 0 (the whole
3917 pattern), even though we never use it, since it simplifies the
3918 array indexing. We should fix this. */
3919 if (bufp->re_nsub)
3920 {
3921 regstart = REGEX_TALLOC (num_regs, const char *);
3922 regend = REGEX_TALLOC (num_regs, const char *);
3923 old_regstart = REGEX_TALLOC (num_regs, const char *);
3924 old_regend = REGEX_TALLOC (num_regs, const char *);
3925 best_regstart = REGEX_TALLOC (num_regs, const char *);
3926 best_regend = REGEX_TALLOC (num_regs, const char *);
3927 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3928 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3929 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3930
3931 if (!(regstart && regend && old_regstart && old_regend && reg_info
3932 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3933 {
3934 FREE_VARIABLES ();
3935 return -2;
3936 }
3937 }
3938 else
3939 {
3940 /* We must initialize all our variables to NULL, so that
3941 `FREE_VARIABLES' doesn't try to free them. */
3942 regstart = regend = old_regstart = old_regend = best_regstart
3943 = best_regend = reg_dummy = NULL;
3944 reg_info = reg_info_dummy = (register_info_type *) NULL;
3945 }
3946 #endif /* MATCH_MAY_ALLOCATE */
3947
3948 /* The starting position is bogus. */
3949 if (pos < 0 || pos > size1 + size2)
3950 {
3951 FREE_VARIABLES ();
3952 return -1;
3953 }
3954
3955 /* Initialize subexpression text positions to -1 to mark ones that no
3956 start_memory/stop_memory has been seen for. Also initialize the
3957 register information struct. */
3958 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
3959 {
3960 regstart[mcnt] = regend[mcnt]
3961 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3962
3963 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3964 IS_ACTIVE (reg_info[mcnt]) = 0;
3965 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3966 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3967 }
3968
3969 /* We move `string1' into `string2' if the latter's empty -- but not if
3970 `string1' is null. */
3971 if (size2 == 0 && string1 != NULL)
3972 {
3973 string2 = string1;
3974 size2 = size1;
3975 string1 = 0;
3976 size1 = 0;
3977 }
3978 end1 = string1 + size1;
3979 end2 = string2 + size2;
3980
3981 /* Compute where to stop matching, within the two strings. */
3982 if (stop <= size1)
3983 {
3984 end_match_1 = string1 + stop;
3985 end_match_2 = string2;
3986 }
3987 else
3988 {
3989 end_match_1 = end1;
3990 end_match_2 = string2 + stop - size1;
3991 }
3992
3993 /* `p' scans through the pattern as `d' scans through the data.
3994 `dend' is the end of the input string that `d' points within. `d'
3995 is advanced into the following input string whenever necessary, but
3996 this happens before fetching; therefore, at the beginning of the
3997 loop, `d' can be pointing at the end of a string, but it cannot
3998 equal `string2'. */
3999 if (size1 > 0 && pos <= size1)
4000 {
4001 d = string1 + pos;
4002 dend = end_match_1;
4003 }
4004 else
4005 {
4006 d = string2 + pos - size1;
4007 dend = end_match_2;
4008 }
4009
4010 DEBUG_PRINT1 ("The compiled pattern is:\n");
4011 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4012 DEBUG_PRINT1 ("The string to match is: `");
4013 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4014 DEBUG_PRINT1 ("'\n");
4015
4016 /* This loops over pattern commands. It exits by returning from the
4017 function if the match is complete, or it drops through if the match
4018 fails at this starting point in the input data. */
4019 for (;;)
4020 {
4021 #ifdef _LIBC
4022 DEBUG_PRINT2 ("\n%p: ", p);
4023 #else
4024 DEBUG_PRINT2 ("\n0x%x: ", p);
4025 #endif
4026
4027 if (p == pend)
4028 { /* End of pattern means we might have succeeded. */
4029 DEBUG_PRINT1 ("end of pattern ... ");
4030
4031 /* If we haven't matched the entire string, and we want the
4032 longest match, try backtracking. */
4033 if (d != end_match_2)
4034 {
4035 /* 1 if this match ends in the same string (string1 or string2)
4036 as the best previous match. */
4037 boolean same_str_p = (FIRST_STRING_P (match_end)
4038 == MATCHING_IN_FIRST_STRING);
4039 /* 1 if this match is the best seen so far. */
4040 boolean best_match_p;
4041
4042 /* AIX compiler got confused when this was combined
4043 with the previous declaration. */
4044 if (same_str_p)
4045 best_match_p = d > match_end;
4046 else
4047 best_match_p = !MATCHING_IN_FIRST_STRING;
4048
4049 DEBUG_PRINT1 ("backtracking.\n");
4050
4051 if (!FAIL_STACK_EMPTY ())
4052 { /* More failure points to try. */
4053
4054 /* If exceeds best match so far, save it. */
4055 if (!best_regs_set || best_match_p)
4056 {
4057 best_regs_set = true;
4058 match_end = d;
4059
4060 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4061
4062 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4063 {
4064 best_regstart[mcnt] = regstart[mcnt];
4065 best_regend[mcnt] = regend[mcnt];
4066 }
4067 }
4068 goto fail;
4069 }
4070
4071 /* If no failure points, don't restore garbage. And if
4072 last match is real best match, don't restore second
4073 best one. */
4074 else if (best_regs_set && !best_match_p)
4075 {
4076 restore_best_regs:
4077 /* Restore best match. It may happen that `dend ==
4078 end_match_1' while the restored d is in string2.
4079 For example, the pattern `x.*y.*z' against the
4080 strings `x-' and `y-z-', if the two strings are
4081 not consecutive in memory. */
4082 DEBUG_PRINT1 ("Restoring best registers.\n");
4083
4084 d = match_end;
4085 dend = ((d >= string1 && d <= end1)
4086 ? end_match_1 : end_match_2);
4087
4088 for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
4089 {
4090 regstart[mcnt] = best_regstart[mcnt];
4091 regend[mcnt] = best_regend[mcnt];
4092 }
4093 }
4094 } /* d != end_match_2 */
4095
4096 succeed_label:
4097 DEBUG_PRINT1 ("Accepting match.\n");
4098
4099 /* If caller wants register contents data back, do it. */
4100 if (regs && !bufp->no_sub)
4101 {
4102 /* Have the register data arrays been allocated? */
4103 if (bufp->regs_allocated == REGS_UNALLOCATED)
4104 { /* No. So allocate them with malloc. We need one
4105 extra element beyond `num_regs' for the `-1' marker
4106 GNU code uses. */
4107 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4108 regs->start = TALLOC (regs->num_regs, regoff_t);
4109 regs->end = TALLOC (regs->num_regs, regoff_t);
4110 if (regs->start == NULL || regs->end == NULL)
4111 {
4112 FREE_VARIABLES ();
4113 return -2;
4114 }
4115 bufp->regs_allocated = REGS_REALLOCATE;
4116 }
4117 else if (bufp->regs_allocated == REGS_REALLOCATE)
4118 { /* Yes. If we need more elements than were already
4119 allocated, reallocate them. If we need fewer, just
4120 leave it alone. */
4121 if (regs->num_regs < num_regs + 1)
4122 {
4123 regs->num_regs = num_regs + 1;
4124 RETALLOC (regs->start, regs->num_regs, regoff_t);
4125 RETALLOC (regs->end, regs->num_regs, regoff_t);
4126 if (regs->start == NULL || regs->end == NULL)
4127 {
4128 FREE_VARIABLES ();
4129 return -2;
4130 }
4131 }
4132 }
4133 else
4134 {
4135 /* These braces fend off a "empty body in an else-statement"
4136 warning under GCC when assert expands to nothing. */
4137 assert (bufp->regs_allocated == REGS_FIXED);
4138 }
4139
4140 /* Convert the pointer data in `regstart' and `regend' to
4141 indices. Register zero has to be set differently,
4142 since we haven't kept track of any info for it. */
4143 if (regs->num_regs > 0)
4144 {
4145 regs->start[0] = pos;
4146 regs->end[0] = (MATCHING_IN_FIRST_STRING
4147 ? ((regoff_t) (d - string1))
4148 : ((regoff_t) (d - string2 + size1)));
4149 }
4150
4151 /* Go through the first `min (num_regs, regs->num_regs)'
4152 registers, since that is all we initialized. */
4153 for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
4154 mcnt++)
4155 {
4156 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4157 regs->start[mcnt] = regs->end[mcnt] = -1;
4158 else
4159 {
4160 regs->start[mcnt]
4161 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4162 regs->end[mcnt]
4163 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4164 }
4165 }
4166
4167 /* If the regs structure we return has more elements than
4168 were in the pattern, set the extra elements to -1. If
4169 we (re)allocated the registers, this is the case,
4170 because we always allocate enough to have at least one
4171 -1 at the end. */
4172 for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
4173 regs->start[mcnt] = regs->end[mcnt] = -1;
4174 } /* regs && !bufp->no_sub */
4175
4176 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4177 nfailure_points_pushed, nfailure_points_popped,
4178 nfailure_points_pushed - nfailure_points_popped);
4179 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4180
4181 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4182 ? string1
4183 : string2 - size1);
4184
4185 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4186
4187 FREE_VARIABLES ();
4188 return mcnt;
4189 }
4190
4191 /* Otherwise match next pattern command. */
4192 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4193 {
4194 /* Ignore these. Used to ignore the n of succeed_n's which
4195 currently have n == 0. */
4196 case no_op:
4197 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4198 break;
4199
4200 case succeed:
4201 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4202 goto succeed_label;
4203
4204 /* Match the next n pattern characters exactly. The following
4205 byte in the pattern defines n, and the n bytes after that
4206 are the characters to match. */
4207 case exactn:
4208 mcnt = *p++;
4209 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4210
4211 /* This is written out as an if-else so we don't waste time
4212 testing `translate' inside the loop. */
4213 if (translate)
4214 {
4215 do
4216 {
4217 PREFETCH ();
4218 if ((unsigned char) translate[(unsigned char) *d++]
4219 != (unsigned char) *p++)
4220 goto fail;
4221 }
4222 while (--mcnt);
4223 }
4224 else
4225 {
4226 do
4227 {
4228 PREFETCH ();
4229 if (*d++ != (char) *p++) goto fail;
4230 }
4231 while (--mcnt);
4232 }
4233 SET_REGS_MATCHED ();
4234 break;
4235
4236
4237 /* Match any character except possibly a newline or a null. */
4238 case anychar:
4239 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4240
4241 PREFETCH ();
4242
4243 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4244 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4245 goto fail;
4246
4247 SET_REGS_MATCHED ();
4248 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4249 d++;
4250 break;
4251
4252
4253 case charset:
4254 case charset_not:
4255 {
4256 register unsigned char c;
4257 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4258
4259 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4260
4261 PREFETCH ();
4262 c = TRANSLATE (*d); /* The character to match. */
4263
4264 /* Cast to `unsigned' instead of `unsigned char' in case the
4265 bit list is a full 32 bytes long. */
4266 if (c < (unsigned) (*p * BYTEWIDTH)
4267 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4268 not = !not;
4269
4270 p += 1 + *p;
4271
4272 if (!not) goto fail;
4273
4274 SET_REGS_MATCHED ();
4275 d++;
4276 break;
4277 }
4278
4279
4280 /* The beginning of a group is represented by start_memory.
4281 The arguments are the register number in the next byte, and the
4282 number of groups inner to this one in the next. The text
4283 matched within the group is recorded (in the internal
4284 registers data structure) under the register number. */
4285 case start_memory:
4286 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4287
4288 /* Find out if this group can match the empty string. */
4289 p1 = p; /* To send to group_match_null_string_p. */
4290
4291 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4292 REG_MATCH_NULL_STRING_P (reg_info[*p])
4293 = group_match_null_string_p (&p1, pend, reg_info);
4294
4295 /* Save the position in the string where we were the last time
4296 we were at this open-group operator in case the group is
4297 operated upon by a repetition operator, e.g., with `(a*)*b'
4298 against `ab'; then we want to ignore where we are now in
4299 the string in case this attempt to match fails. */
4300 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4301 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4302 : regstart[*p];
4303 DEBUG_PRINT2 (" old_regstart: %d\n",
4304 POINTER_TO_OFFSET (old_regstart[*p]));
4305
4306 regstart[*p] = d;
4307 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4308
4309 IS_ACTIVE (reg_info[*p]) = 1;
4310 MATCHED_SOMETHING (reg_info[*p]) = 0;
4311
4312 /* Clear this whenever we change the register activity status. */
4313 set_regs_matched_done = 0;
4314
4315 /* This is the new highest active register. */
4316 highest_active_reg = *p;
4317
4318 /* If nothing was active before, this is the new lowest active
4319 register. */
4320 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4321 lowest_active_reg = *p;
4322
4323 /* Move past the register number and inner group count. */
4324 p += 2;
4325 just_past_start_mem = p;
4326
4327 break;
4328
4329
4330 /* The stop_memory opcode represents the end of a group. Its
4331 arguments are the same as start_memory's: the register
4332 number, and the number of inner groups. */
4333 case stop_memory:
4334 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4335
4336 /* We need to save the string position the last time we were at
4337 this close-group operator in case the group is operated
4338 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4339 against `aba'; then we want to ignore where we are now in
4340 the string in case this attempt to match fails. */
4341 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4342 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4343 : regend[*p];
4344 DEBUG_PRINT2 (" old_regend: %d\n",
4345 POINTER_TO_OFFSET (old_regend[*p]));
4346
4347 regend[*p] = d;
4348 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4349
4350 /* This register isn't active anymore. */
4351 IS_ACTIVE (reg_info[*p]) = 0;
4352
4353 /* Clear this whenever we change the register activity status. */
4354 set_regs_matched_done = 0;
4355
4356 /* If this was the only register active, nothing is active
4357 anymore. */
4358 if (lowest_active_reg == highest_active_reg)
4359 {
4360 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4361 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4362 }
4363 else
4364 { /* We must scan for the new highest active register, since
4365 it isn't necessarily one less than now: consider
4366 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4367 new highest active register is 1. */
4368 unsigned char r = *p - 1;
4369 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4370 r--;
4371
4372 /* If we end up at register zero, that means that we saved
4373 the registers as the result of an `on_failure_jump', not
4374 a `start_memory', and we jumped to past the innermost
4375 `stop_memory'. For example, in ((.)*) we save
4376 registers 1 and 2 as a result of the *, but when we pop
4377 back to the second ), we are at the stop_memory 1.
4378 Thus, nothing is active. */
4379 if (r == 0)
4380 {
4381 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4382 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4383 }
4384 else
4385 highest_active_reg = r;
4386 }
4387
4388 /* If just failed to match something this time around with a
4389 group that's operated on by a repetition operator, try to
4390 force exit from the ``loop'', and restore the register
4391 information for this group that we had before trying this
4392 last match. */
4393 if ((!MATCHED_SOMETHING (reg_info[*p])
4394 || just_past_start_mem == p - 1)
4395 && (p + 2) < pend)
4396 {
4397 boolean is_a_jump_n = false;
4398
4399 p1 = p + 2;
4400 mcnt = 0;
4401 switch ((re_opcode_t) *p1++)
4402 {
4403 case jump_n:
4404 is_a_jump_n = true;
4405 case pop_failure_jump:
4406 case maybe_pop_jump:
4407 case jump:
4408 case dummy_failure_jump:
4409 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4410 if (is_a_jump_n)
4411 p1 += 2;
4412 break;
4413
4414 default:
4415 /* do nothing */ ;
4416 }
4417 p1 += mcnt;
4418
4419 /* If the next operation is a jump backwards in the pattern
4420 to an on_failure_jump right before the start_memory
4421 corresponding to this stop_memory, exit from the loop
4422 by forcing a failure after pushing on the stack the
4423 on_failure_jump's jump in the pattern, and d. */
4424 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4425 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4426 {
4427 /* If this group ever matched anything, then restore
4428 what its registers were before trying this last
4429 failed match, e.g., with `(a*)*b' against `ab' for
4430 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4431 against `aba' for regend[3].
4432
4433 Also restore the registers for inner groups for,
4434 e.g., `((a*)(b*))*' against `aba' (register 3 would
4435 otherwise get trashed). */
4436
4437 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4438 {
4439 unsigned r;
4440
4441 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4442
4443 /* Restore this and inner groups' (if any) registers. */
4444 for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
4445 r++)
4446 {
4447 regstart[r] = old_regstart[r];
4448
4449 /* xx why this test? */
4450 if (old_regend[r] >= regstart[r])
4451 regend[r] = old_regend[r];
4452 }
4453 }
4454 p1++;
4455 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4456 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4457
4458 goto fail;
4459 }
4460 }
4461
4462 /* Move past the register number and the inner group count. */
4463 p += 2;
4464 break;
4465
4466
4467 /* \<digit> has been turned into a `duplicate' command which is
4468 followed by the numeric value of <digit> as the register number. */
4469 case duplicate:
4470 {
4471 register const char *d2, *dend2;
4472 int regno = *p++; /* Get which register to match against. */
4473 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4474
4475 /* Can't back reference a group which we've never matched. */
4476 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4477 goto fail;
4478
4479 /* Where in input to try to start matching. */
4480 d2 = regstart[regno];
4481
4482 /* Where to stop matching; if both the place to start and
4483 the place to stop matching are in the same string, then
4484 set to the place to stop, otherwise, for now have to use
4485 the end of the first string. */
4486
4487 dend2 = ((FIRST_STRING_P (regstart[regno])
4488 == FIRST_STRING_P (regend[regno]))
4489 ? regend[regno] : end_match_1);
4490 for (;;)
4491 {
4492 /* If necessary, advance to next segment in register
4493 contents. */
4494 while (d2 == dend2)
4495 {
4496 if (dend2 == end_match_2) break;
4497 if (dend2 == regend[regno]) break;
4498
4499 /* End of string1 => advance to string2. */
4500 d2 = string2;
4501 dend2 = regend[regno];
4502 }
4503 /* At end of register contents => success */
4504 if (d2 == dend2) break;
4505
4506 /* If necessary, advance to next segment in data. */
4507 PREFETCH ();
4508
4509 /* How many characters left in this segment to match. */
4510 mcnt = dend - d;
4511
4512 /* Want how many consecutive characters we can match in
4513 one shot, so, if necessary, adjust the count. */
4514 if (mcnt > dend2 - d2)
4515 mcnt = dend2 - d2;
4516
4517 /* Compare that many; failure if mismatch, else move
4518 past them. */
4519 if (translate
4520 ? bcmp_translate (d, d2, mcnt, translate)
4521 : memcmp (d, d2, mcnt))
4522 goto fail;
4523 d += mcnt, d2 += mcnt;
4524
4525 /* Do this because we've match some characters. */
4526 SET_REGS_MATCHED ();
4527 }
4528 }
4529 break;
4530
4531
4532 /* begline matches the empty string at the beginning of the string
4533 (unless `not_bol' is set in `bufp'), and, if
4534 `newline_anchor' is set, after newlines. */
4535 case begline:
4536 DEBUG_PRINT1 ("EXECUTING begline.\n");
4537
4538 if (AT_STRINGS_BEG (d))
4539 {
4540 if (!bufp->not_bol) break;
4541 }
4542 else if (d[-1] == '\n' && bufp->newline_anchor)
4543 {
4544 break;
4545 }
4546 /* In all other cases, we fail. */
4547 goto fail;
4548
4549
4550 /* endline is the dual of begline. */
4551 case endline:
4552 DEBUG_PRINT1 ("EXECUTING endline.\n");
4553
4554 if (AT_STRINGS_END (d))
4555 {
4556 if (!bufp->not_eol) break;
4557 }
4558
4559 /* We have to ``prefetch'' the next character. */
4560 else if ((d == end1 ? *string2 : *d) == '\n'
4561 && bufp->newline_anchor)
4562 {
4563 break;
4564 }
4565 goto fail;
4566
4567
4568 /* Match at the very beginning of the data. */
4569 case begbuf:
4570 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4571 if (AT_STRINGS_BEG (d))
4572 break;
4573 goto fail;
4574
4575
4576 /* Match at the very end of the data. */
4577 case endbuf:
4578 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4579 if (AT_STRINGS_END (d))
4580 break;
4581 goto fail;
4582
4583
4584 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4585 pushes NULL as the value for the string on the stack. Then
4586 `pop_failure_point' will keep the current value for the
4587 string, instead of restoring it. To see why, consider
4588 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4589 then the . fails against the \n. But the next thing we want
4590 to do is match the \n against the \n; if we restored the
4591 string value, we would be back at the foo.
4592
4593 Because this is used only in specific cases, we don't need to
4594 check all the things that `on_failure_jump' does, to make
4595 sure the right things get saved on the stack. Hence we don't
4596 share its code. The only reason to push anything on the
4597 stack at all is that otherwise we would have to change
4598 `anychar's code to do something besides goto fail in this
4599 case; that seems worse than this. */
4600 case on_failure_keep_string_jump:
4601 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4602
4603 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4604 #ifdef _LIBC
4605 DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
4606 #else
4607 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4608 #endif
4609
4610 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4611 break;
4612
4613
4614 /* Uses of on_failure_jump:
4615
4616 Each alternative starts with an on_failure_jump that points
4617 to the beginning of the next alternative. Each alternative
4618 except the last ends with a jump that in effect jumps past
4619 the rest of the alternatives. (They really jump to the
4620 ending jump of the following alternative, because tensioning
4621 these jumps is a hassle.)
4622
4623 Repeats start with an on_failure_jump that points past both
4624 the repetition text and either the following jump or
4625 pop_failure_jump back to this on_failure_jump. */
4626 case on_failure_jump:
4627 on_failure:
4628 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4629
4630 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4631 #ifdef _LIBC
4632 DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
4633 #else
4634 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4635 #endif
4636
4637 /* If this on_failure_jump comes right before a group (i.e.,
4638 the original * applied to a group), save the information
4639 for that group and all inner ones, so that if we fail back
4640 to this point, the group's information will be correct.
4641 For example, in \(a*\)*\1, we need the preceding group,
4642 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4643
4644 /* We can't use `p' to check ahead because we push
4645 a failure point to `p + mcnt' after we do this. */
4646 p1 = p;
4647
4648 /* We need to skip no_op's before we look for the
4649 start_memory in case this on_failure_jump is happening as
4650 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4651 against aba. */
4652 while (p1 < pend && (re_opcode_t) *p1 == no_op)
4653 p1++;
4654
4655 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
4656 {
4657 /* We have a new highest active register now. This will
4658 get reset at the start_memory we are about to get to,
4659 but we will have saved all the registers relevant to
4660 this repetition op, as described above. */
4661 highest_active_reg = *(p1 + 1) + *(p1 + 2);
4662 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4663 lowest_active_reg = *(p1 + 1);
4664 }
4665
4666 DEBUG_PRINT1 (":\n");
4667 PUSH_FAILURE_POINT (p + mcnt, d, -2);
4668 break;
4669
4670
4671 /* A smart repeat ends with `maybe_pop_jump'.
4672 We change it to either `pop_failure_jump' or `jump'. */
4673 case maybe_pop_jump:
4674 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4675 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
4676 {
4677 register unsigned char *p2 = p;
4678
4679 /* Compare the beginning of the repeat with what in the
4680 pattern follows its end. If we can establish that there
4681 is nothing that they would both match, i.e., that we
4682 would have to backtrack because of (as in, e.g., `a*a')
4683 then we can change to pop_failure_jump, because we'll
4684 never have to backtrack.
4685
4686 This is not true in the case of alternatives: in
4687 `(a|ab)*' we do need to backtrack to the `ab' alternative
4688 (e.g., if the string was `ab'). But instead of trying to
4689 detect that here, the alternative has put on a dummy
4690 failure point which is what we will end up popping. */
4691
4692 /* Skip over open/close-group commands.
4693 If what follows this loop is a ...+ construct,
4694 look at what begins its body, since we will have to
4695 match at least one of that. */
4696 while (1)
4697 {
4698 if (p2 + 2 < pend
4699 && ((re_opcode_t) *p2 == stop_memory
4700 || (re_opcode_t) *p2 == start_memory))
4701 p2 += 3;
4702 else if (p2 + 6 < pend
4703 && (re_opcode_t) *p2 == dummy_failure_jump)
4704 p2 += 6;
4705 else
4706 break;
4707 }
4708
4709 p1 = p + mcnt;
4710 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4711 to the `maybe_finalize_jump' of this case. Examine what
4712 follows. */
4713
4714 /* If we're at the end of the pattern, we can change. */
4715 if (p2 == pend)
4716 {
4717 /* Consider what happens when matching ":\(.*\)"
4718 against ":/". I don't really understand this code
4719 yet. */
4720 p[-3] = (unsigned char) pop_failure_jump;
4721 DEBUG_PRINT1
4722 (" End of pattern: change to `pop_failure_jump'.\n");
4723 }
4724
4725 else if ((re_opcode_t) *p2 == exactn
4726 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4727 {
4728 register unsigned char c
4729 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4730
4731 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4732 {
4733 p[-3] = (unsigned char) pop_failure_jump;
4734 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4735 c, p1[5]);
4736 }
4737
4738 else if ((re_opcode_t) p1[3] == charset
4739 || (re_opcode_t) p1[3] == charset_not)
4740 {
4741 int not = (re_opcode_t) p1[3] == charset_not;
4742
4743 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4744 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4745 not = !not;
4746
4747 /* `not' is equal to 1 if c would match, which means
4748 that we can't change to pop_failure_jump. */
4749 if (!not)
4750 {
4751 p[-3] = (unsigned char) pop_failure_jump;
4752 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4753 }
4754 }
4755 }
4756 else if ((re_opcode_t) *p2 == charset)
4757 {
4758 #ifdef DEBUG
4759 register unsigned char c
4760 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4761 #endif
4762
4763 #if 0
4764 if ((re_opcode_t) p1[3] == exactn
4765 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
4766 && (p2[2 + p1[5] / BYTEWIDTH]
4767 & (1 << (p1[5] % BYTEWIDTH)))))
4768 #else
4769 if ((re_opcode_t) p1[3] == exactn
4770 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[4]
4771 && (p2[2 + p1[4] / BYTEWIDTH]
4772 & (1 << (p1[4] % BYTEWIDTH)))))
4773 #endif
4774 {
4775 p[-3] = (unsigned char) pop_failure_jump;
4776 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4777 c, p1[5]);
4778 }
4779
4780 else if ((re_opcode_t) p1[3] == charset_not)
4781 {
4782 int idx;
4783 /* We win if the charset_not inside the loop
4784 lists every character listed in the charset after. */
4785 for (idx = 0; idx < (int) p2[1]; idx++)
4786 if (! (p2[2 + idx] == 0
4787 || (idx < (int) p1[4]
4788 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
4789 break;
4790
4791 if (idx == p2[1])
4792 {
4793 p[-3] = (unsigned char) pop_failure_jump;
4794 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4795 }
4796 }
4797 else if ((re_opcode_t) p1[3] == charset)
4798 {
4799 int idx;
4800 /* We win if the charset inside the loop
4801 has no overlap with the one after the loop. */
4802 for (idx = 0;
4803 idx < (int) p2[1] && idx < (int) p1[4];
4804 idx++)
4805 if ((p2[2 + idx] & p1[5 + idx]) != 0)
4806 break;
4807
4808 if (idx == p2[1] || idx == p1[4])
4809 {
4810 p[-3] = (unsigned char) pop_failure_jump;
4811 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4812 }
4813 }
4814 }
4815 }
4816 p -= 2; /* Point at relative address again. */
4817 if ((re_opcode_t) p[-1] != pop_failure_jump)
4818 {
4819 p[-1] = (unsigned char) jump;
4820 DEBUG_PRINT1 (" Match => jump.\n");
4821 goto unconditional_jump;
4822 }
4823 /* Note fall through. */
4824
4825
4826 /* The end of a simple repeat has a pop_failure_jump back to
4827 its matching on_failure_jump, where the latter will push a
4828 failure point. The pop_failure_jump takes off failure
4829 points put on by this pop_failure_jump's matching
4830 on_failure_jump; we got through the pattern to here from the
4831 matching on_failure_jump, so didn't fail. */
4832 case pop_failure_jump:
4833 {
4834 /* We need to pass separate storage for the lowest and
4835 highest registers, even though we don't care about the
4836 actual values. Otherwise, we will restore only one
4837 register from the stack, since lowest will == highest in
4838 `pop_failure_point'. */
4839 active_reg_t dummy_low_reg, dummy_high_reg;
4840 unsigned char *pdummy;
4841 const char *sdummy;
4842
4843 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4844 POP_FAILURE_POINT (sdummy, pdummy,
4845 dummy_low_reg, dummy_high_reg,
4846 reg_dummy, reg_dummy, reg_info_dummy);
4847 }
4848 /* Note fall through. */
4849
4850 unconditional_jump:
4851 #ifdef _LIBC
4852 DEBUG_PRINT2 ("\n%p: ", p);
4853 #else
4854 DEBUG_PRINT2 ("\n0x%x: ", p);
4855 #endif
4856 /* Note fall through. */
4857
4858 /* Unconditionally jump (without popping any failure points). */
4859 case jump:
4860 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4861 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4862 p += mcnt; /* Do the jump. */
4863 #ifdef _LIBC
4864 DEBUG_PRINT2 ("(to %p).\n", p);
4865 #else
4866 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4867 #endif
4868 break;
4869
4870
4871 /* We need this opcode so we can detect where alternatives end
4872 in `group_match_null_string_p' et al. */
4873 case jump_past_alt:
4874 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4875 goto unconditional_jump;
4876
4877
4878 /* Normally, the on_failure_jump pushes a failure point, which
4879 then gets popped at pop_failure_jump. We will end up at
4880 pop_failure_jump, also, and with a pattern of, say, `a+', we
4881 are skipping over the on_failure_jump, so we have to push
4882 something meaningless for pop_failure_jump to pop. */
4883 case dummy_failure_jump:
4884 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4885 /* It doesn't matter what we push for the string here. What
4886 the code at `fail' tests is the value for the pattern. */
4887 PUSH_FAILURE_POINT (NULL, NULL, -2);
4888 goto unconditional_jump;
4889
4890
4891 /* At the end of an alternative, we need to push a dummy failure
4892 point in case we are followed by a `pop_failure_jump', because
4893 we don't want the failure point for the alternative to be
4894 popped. For example, matching `(a|ab)*' against `aab'
4895 requires that we match the `ab' alternative. */
4896 case push_dummy_failure:
4897 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4898 /* See comments just above at `dummy_failure_jump' about the
4899 two zeroes. */
4900 PUSH_FAILURE_POINT (NULL, NULL, -2);
4901 break;
4902
4903 /* Have to succeed matching what follows at least n times.
4904 After that, handle like `on_failure_jump'. */
4905 case succeed_n:
4906 EXTRACT_NUMBER (mcnt, p + 2);
4907 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4908
4909 assert (mcnt >= 0);
4910 /* Originally, this is how many times we HAVE to succeed. */
4911 if (mcnt > 0)
4912 {
4913 mcnt--;
4914 p += 2;
4915 STORE_NUMBER_AND_INCR (p, mcnt);
4916 #ifdef _LIBC
4917 DEBUG_PRINT3 (" Setting %p to %d.\n", p - 2, mcnt);
4918 #else
4919 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - 2, mcnt);
4920 #endif
4921 }
4922 else if (mcnt == 0)
4923 {
4924 #ifdef _LIBC
4925 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p+2);
4926 #else
4927 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4928 #endif
4929 p[2] = (unsigned char) no_op;
4930 p[3] = (unsigned char) no_op;
4931 goto on_failure;
4932 }
4933 break;
4934
4935 case jump_n:
4936 EXTRACT_NUMBER (mcnt, p + 2);
4937 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4938
4939 /* Originally, this is how many times we CAN jump. */
4940 if (mcnt)
4941 {
4942 mcnt--;
4943 STORE_NUMBER (p + 2, mcnt);
4944 #ifdef _LIBC
4945 DEBUG_PRINT3 (" Setting %p to %d.\n", p + 2, mcnt);
4946 #else
4947 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + 2, mcnt);
4948 #endif
4949 goto unconditional_jump;
4950 }
4951 /* If don't have to jump any more, skip over the rest of command. */
4952 else
4953 p += 4;
4954 break;
4955
4956 case set_number_at:
4957 {
4958 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4959
4960 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4961 p1 = p + mcnt;
4962 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4963 #ifdef _LIBC
4964 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
4965 #else
4966 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4967 #endif
4968 STORE_NUMBER (p1, mcnt);
4969 break;
4970 }
4971
4972 #if 0
4973 /* The DEC Alpha C compiler 3.x generates incorrect code for the
4974 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4975 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4976 macro and introducing temporary variables works around the bug. */
4977
4978 case wordbound:
4979 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4980 if (AT_WORD_BOUNDARY (d))
4981 break;
4982 goto fail;
4983
4984 case notwordbound:
4985 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4986 if (AT_WORD_BOUNDARY (d))
4987 goto fail;
4988 break;
4989 #else
4990 case wordbound:
4991 {
4992 boolean prevchar, thischar;
4993
4994 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4995 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
4996 break;
4997
4998 prevchar = WORDCHAR_P (d - 1);
4999 thischar = WORDCHAR_P (d);
5000 if (prevchar != thischar)
5001 break;
5002 goto fail;
5003 }
5004
5005 case notwordbound:
5006 {
5007 boolean prevchar, thischar;
5008
5009 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5010 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5011 goto fail;
5012
5013 prevchar = WORDCHAR_P (d - 1);
5014 thischar = WORDCHAR_P (d);
5015 if (prevchar != thischar)
5016 goto fail;
5017 break;
5018 }
5019 #endif
5020
5021 case wordbeg:
5022 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5023 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
5024 break;
5025 goto fail;
5026
5027 case wordend:
5028 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5029 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
5030 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
5031 break;
5032 goto fail;
5033
5034 #ifdef emacs
5035 case before_dot:
5036 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5037 if (PTR_CHAR_POS ((unsigned char *) d) >= point)
5038 goto fail;
5039 break;
5040
5041 case at_dot:
5042 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5043 if (PTR_CHAR_POS ((unsigned char *) d) != point)
5044 goto fail;
5045 break;
5046
5047 case after_dot:
5048 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5049 if (PTR_CHAR_POS ((unsigned char *) d) <= point)
5050 goto fail;
5051 break;
5052
5053 case syntaxspec:
5054 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5055 mcnt = *p++;
5056 goto matchsyntax;
5057
5058 case wordchar:
5059 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5060 mcnt = (int) Sword;
5061 matchsyntax:
5062 PREFETCH ();
5063 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5064 d++;
5065 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
5066 goto fail;
5067 SET_REGS_MATCHED ();
5068 break;
5069
5070 case notsyntaxspec:
5071 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5072 mcnt = *p++;
5073 goto matchnotsyntax;
5074
5075 case notwordchar:
5076 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5077 mcnt = (int) Sword;
5078 matchnotsyntax:
5079 PREFETCH ();
5080 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5081 d++;
5082 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
5083 goto fail;
5084 SET_REGS_MATCHED ();
5085 break;
5086
5087 #else /* not emacs */
5088 case wordchar:
5089 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5090 PREFETCH ();
5091 if (!WORDCHAR_P (d))
5092 goto fail;
5093 SET_REGS_MATCHED ();
5094 d++;
5095 break;
5096
5097 case notwordchar:
5098 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5099 PREFETCH ();
5100 if (WORDCHAR_P (d))
5101 goto fail;
5102 SET_REGS_MATCHED ();
5103 d++;
5104 break;
5105 #endif /* not emacs */
5106
5107 default:
5108 abort ();
5109 }
5110 continue; /* Successfully executed one pattern command; keep going. */
5111
5112
5113 /* We goto here if a matching operation fails. */
5114 fail:
5115 if (!FAIL_STACK_EMPTY ())
5116 { /* A restart point is known. Restore to that state. */
5117 DEBUG_PRINT1 ("\nFAIL:\n");
5118 POP_FAILURE_POINT (d, p,
5119 lowest_active_reg, highest_active_reg,
5120 regstart, regend, reg_info);
5121
5122 /* If this failure point is a dummy, try the next one. */
5123 if (!p)
5124 goto fail;
5125
5126 /* If we failed to the end of the pattern, don't examine *p. */
5127 assert (p <= pend);
5128 if (p < pend)
5129 {
5130 boolean is_a_jump_n = false;
5131
5132 /* If failed to a backwards jump that's part of a repetition
5133 loop, need to pop this failure point and use the next one. */
5134 switch ((re_opcode_t) *p)
5135 {
5136 case jump_n:
5137 is_a_jump_n = true;
5138 case maybe_pop_jump:
5139 case pop_failure_jump:
5140 case jump:
5141 p1 = p + 1;
5142 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5143 p1 += mcnt;
5144
5145 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5146 || (!is_a_jump_n
5147 && (re_opcode_t) *p1 == on_failure_jump))
5148 goto fail;
5149 break;
5150 default:
5151 /* do nothing */ ;
5152 }
5153 }
5154
5155 if (d >= string1 && d <= end1)
5156 dend = end_match_1;
5157 }
5158 else
5159 break; /* Matching at this starting point really fails. */
5160 } /* for (;;) */
5161
5162 if (best_regs_set)
5163 goto restore_best_regs;
5164
5165 FREE_VARIABLES ();
5166
5167 return -1; /* Failure to match. */
5168 } /* re_match_2 */
5169 \f
5170 /* Subroutine definitions for re_match_2. */
5171
5172
5173 /* We are passed P pointing to a register number after a start_memory.
5174
5175 Return true if the pattern up to the corresponding stop_memory can
5176 match the empty string, and false otherwise.
5177
5178 If we find the matching stop_memory, sets P to point to one past its number.
5179 Otherwise, sets P to an undefined byte less than or equal to END.
5180
5181 We don't handle duplicates properly (yet). */
5182
5183 static boolean
5184 group_match_null_string_p (p, end, reg_info)
5185 unsigned char **p, *end;
5186 register_info_type *reg_info;
5187 {
5188 int mcnt;
5189 /* Point to after the args to the start_memory. */
5190 unsigned char *p1 = *p + 2;
5191
5192 while (p1 < end)
5193 {
5194 /* Skip over opcodes that can match nothing, and return true or
5195 false, as appropriate, when we get to one that can't, or to the
5196 matching stop_memory. */
5197
5198 switch ((re_opcode_t) *p1)
5199 {
5200 /* Could be either a loop or a series of alternatives. */
5201 case on_failure_jump:
5202 p1++;
5203 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5204
5205 /* If the next operation is not a jump backwards in the
5206 pattern. */
5207
5208 if (mcnt >= 0)
5209 {
5210 /* Go through the on_failure_jumps of the alternatives,
5211 seeing if any of the alternatives cannot match nothing.
5212 The last alternative starts with only a jump,
5213 whereas the rest start with on_failure_jump and end
5214 with a jump, e.g., here is the pattern for `a|b|c':
5215
5216 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5217 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5218 /exactn/1/c
5219
5220 So, we have to first go through the first (n-1)
5221 alternatives and then deal with the last one separately. */
5222
5223
5224 /* Deal with the first (n-1) alternatives, which start
5225 with an on_failure_jump (see above) that jumps to right
5226 past a jump_past_alt. */
5227
5228 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5229 {
5230 /* `mcnt' holds how many bytes long the alternative
5231 is, including the ending `jump_past_alt' and
5232 its number. */
5233
5234 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5235 reg_info))
5236 return false;
5237
5238 /* Move to right after this alternative, including the
5239 jump_past_alt. */
5240 p1 += mcnt;
5241
5242 /* Break if it's the beginning of an n-th alternative
5243 that doesn't begin with an on_failure_jump. */
5244 if ((re_opcode_t) *p1 != on_failure_jump)
5245 break;
5246
5247 /* Still have to check that it's not an n-th
5248 alternative that starts with an on_failure_jump. */
5249 p1++;
5250 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5251 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5252 {
5253 /* Get to the beginning of the n-th alternative. */
5254 p1 -= 3;
5255 break;
5256 }
5257 }
5258
5259 /* Deal with the last alternative: go back and get number
5260 of the `jump_past_alt' just before it. `mcnt' contains
5261 the length of the alternative. */
5262 EXTRACT_NUMBER (mcnt, p1 - 2);
5263
5264 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5265 return false;
5266
5267 p1 += mcnt; /* Get past the n-th alternative. */
5268 } /* if mcnt > 0 */
5269 break;
5270
5271
5272 case stop_memory:
5273 assert (p1[1] == **p);
5274 *p = p1 + 2;
5275 return true;
5276
5277
5278 default:
5279 if (!common_op_match_null_string_p (&p1, end, reg_info))
5280 return false;
5281 }
5282 } /* while p1 < end */
5283
5284 return false;
5285 } /* group_match_null_string_p */
5286
5287
5288 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5289 It expects P to be the first byte of a single alternative and END one
5290 byte past the last. The alternative can contain groups. */
5291
5292 static boolean
5293 alt_match_null_string_p (p, end, reg_info)
5294 unsigned char *p, *end;
5295 register_info_type *reg_info;
5296 {
5297 int mcnt;
5298 unsigned char *p1 = p;
5299
5300 while (p1 < end)
5301 {
5302 /* Skip over opcodes that can match nothing, and break when we get
5303 to one that can't. */
5304
5305 switch ((re_opcode_t) *p1)
5306 {
5307 /* It's a loop. */
5308 case on_failure_jump:
5309 p1++;
5310 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5311 p1 += mcnt;
5312 break;
5313
5314 default:
5315 if (!common_op_match_null_string_p (&p1, end, reg_info))
5316 return false;
5317 }
5318 } /* while p1 < end */
5319
5320 return true;
5321 } /* alt_match_null_string_p */
5322
5323
5324 /* Deals with the ops common to group_match_null_string_p and
5325 alt_match_null_string_p.
5326
5327 Sets P to one after the op and its arguments, if any. */
5328
5329 static boolean
5330 common_op_match_null_string_p (p, end, reg_info)
5331 unsigned char **p, *end;
5332 register_info_type *reg_info;
5333 {
5334 int mcnt;
5335 boolean ret;
5336 int reg_no;
5337 unsigned char *p1 = *p;
5338
5339 switch ((re_opcode_t) *p1++)
5340 {
5341 case no_op:
5342 case begline:
5343 case endline:
5344 case begbuf:
5345 case endbuf:
5346 case wordbeg:
5347 case wordend:
5348 case wordbound:
5349 case notwordbound:
5350 #ifdef emacs
5351 case before_dot:
5352 case at_dot:
5353 case after_dot:
5354 #endif
5355 break;
5356
5357 case start_memory:
5358 reg_no = *p1;
5359 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5360 ret = group_match_null_string_p (&p1, end, reg_info);
5361
5362 /* Have to set this here in case we're checking a group which
5363 contains a group and a back reference to it. */
5364
5365 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5366 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5367
5368 if (!ret)
5369 return false;
5370 break;
5371
5372 /* If this is an optimized succeed_n for zero times, make the jump. */
5373 case jump:
5374 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5375 if (mcnt >= 0)
5376 p1 += mcnt;
5377 else
5378 return false;
5379 break;
5380
5381 case succeed_n:
5382 /* Get to the number of times to succeed. */
5383 p1 += 2;
5384 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5385
5386 if (mcnt == 0)
5387 {
5388 p1 -= 4;
5389 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5390 p1 += mcnt;
5391 }
5392 else
5393 return false;
5394 break;
5395
5396 case duplicate:
5397 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5398 return false;
5399 break;
5400
5401 case set_number_at:
5402 p1 += 4;
5403
5404 default:
5405 /* All other opcodes mean we cannot match the empty string. */
5406 return false;
5407 }
5408
5409 *p = p1;
5410 return true;
5411 } /* common_op_match_null_string_p */
5412
5413
5414 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5415 bytes; nonzero otherwise. */
5416
5417 static int
5418 bcmp_translate (s1, s2, len, translate)
5419 const char *s1, *s2;
5420 register int len;
5421 RE_TRANSLATE_TYPE translate;
5422 {
5423 register const unsigned char *p1 = (const unsigned char *) s1;
5424 register const unsigned char *p2 = (const unsigned char *) s2;
5425 while (len)
5426 {
5427 if (translate[*p1++] != translate[*p2++]) return 1;
5428 len--;
5429 }
5430 return 0;
5431 }
5432 \f
5433 /* Entry points for GNU code. */
5434
5435 /* re_compile_pattern is the GNU regular expression compiler: it
5436 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5437 Returns 0 if the pattern was valid, otherwise an error string.
5438
5439 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5440 are set in BUFP on entry.
5441
5442 We call regex_compile to do the actual compilation. */
5443
5444 const char *
5445 re_compile_pattern (pattern, length, bufp)
5446 const char *pattern;
5447 size_t length;
5448 struct re_pattern_buffer *bufp;
5449 {
5450 reg_errcode_t ret;
5451
5452 /* GNU code is written to assume at least RE_NREGS registers will be set
5453 (and at least one extra will be -1). */
5454 bufp->regs_allocated = REGS_UNALLOCATED;
5455
5456 /* And GNU code determines whether or not to get register information
5457 by passing null for the REGS argument to re_match, etc., not by
5458 setting no_sub. */
5459 bufp->no_sub = 0;
5460
5461 /* Match anchors at newline. */
5462 bufp->newline_anchor = 1;
5463
5464 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5465
5466 if (!ret)
5467 return NULL;
5468 return gettext (re_error_msgid[(int) ret]);
5469 }
5470 #ifdef _LIBC
5471 weak_alias (__re_compile_pattern, re_compile_pattern)
5472 #endif
5473 \f
5474 /* Entry points compatible with 4.2 BSD regex library. We don't define
5475 them unless specifically requested. */
5476
5477 #if defined _REGEX_RE_COMP || defined _LIBC
5478
5479 /* BSD has one and only one pattern buffer. */
5480 static struct re_pattern_buffer re_comp_buf;
5481
5482 char *
5483 #ifdef _LIBC
5484 /* Make these definitions weak in libc, so POSIX programs can redefine
5485 these names if they don't use our functions, and still use
5486 regcomp/regexec below without link errors. */
5487 weak_function
5488 #endif
5489 re_comp (s)
5490 const char *s;
5491 {
5492 reg_errcode_t ret;
5493
5494 if (!s)
5495 {
5496 if (!re_comp_buf.buffer)
5497 return gettext ("No previous regular expression");
5498 return 0;
5499 }
5500
5501 if (!re_comp_buf.buffer)
5502 {
5503 re_comp_buf.buffer = (unsigned char *) malloc (200);
5504 if (re_comp_buf.buffer == NULL)
5505 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
5506 re_comp_buf.allocated = 200;
5507
5508 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5509 if (re_comp_buf.fastmap == NULL)
5510 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
5511 }
5512
5513 /* Since `re_exec' always passes NULL for the `regs' argument, we
5514 don't need to initialize the pattern buffer fields which affect it. */
5515
5516 /* Match anchors at newlines. */
5517 re_comp_buf.newline_anchor = 1;
5518
5519 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5520
5521 if (!ret)
5522 return NULL;
5523
5524 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5525 return (char *) gettext (re_error_msgid[(int) ret]);
5526 }
5527
5528
5529 int
5530 #ifdef _LIBC
5531 weak_function
5532 #endif
5533 re_exec (s)
5534 const char *s;
5535 {
5536 const int len = strlen (s);
5537 return
5538 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5539 }
5540
5541 #endif /* _REGEX_RE_COMP */
5542 \f
5543 /* POSIX.2 functions. Don't define these for Emacs. */
5544
5545 #ifndef emacs
5546
5547 /* regcomp takes a regular expression as a string and compiles it.
5548
5549 PREG is a regex_t *. We do not expect any fields to be initialized,
5550 since POSIX says we shouldn't. Thus, we set
5551
5552 `buffer' to the compiled pattern;
5553 `used' to the length of the compiled pattern;
5554 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5555 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5556 RE_SYNTAX_POSIX_BASIC;
5557 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5558 `fastmap' and `fastmap_accurate' to zero;
5559 `re_nsub' to the number of subexpressions in PATTERN.
5560
5561 PATTERN is the address of the pattern string.
5562
5563 CFLAGS is a series of bits which affect compilation.
5564
5565 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5566 use POSIX basic syntax.
5567
5568 If REG_NEWLINE is set, then . and [^...] don't match newline.
5569 Also, regexec will try a match beginning after every newline.
5570
5571 If REG_ICASE is set, then we considers upper- and lowercase
5572 versions of letters to be equivalent when matching.
5573
5574 If REG_NOSUB is set, then when PREG is passed to regexec, that
5575 routine will report only success or failure, and nothing about the
5576 registers.
5577
5578 It returns 0 if it succeeds, nonzero if it doesn't. (See gnu-regex.h for
5579 the return codes and their meanings.) */
5580
5581 int
5582 regcomp (preg, pattern, cflags)
5583 regex_t *preg;
5584 const char *pattern;
5585 int cflags;
5586 {
5587 reg_errcode_t ret;
5588 reg_syntax_t syntax
5589 = (cflags & REG_EXTENDED) ?
5590 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5591
5592 /* regex_compile will allocate the space for the compiled pattern. */
5593 preg->buffer = 0;
5594 preg->allocated = 0;
5595 preg->used = 0;
5596
5597 /* Don't bother to use a fastmap when searching. This simplifies the
5598 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5599 characters after newlines into the fastmap. This way, we just try
5600 every character. */
5601 preg->fastmap = 0;
5602
5603 if (cflags & REG_ICASE)
5604 {
5605 unsigned i;
5606
5607 preg->translate
5608 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
5609 * sizeof (*(RE_TRANSLATE_TYPE)0));
5610 if (preg->translate == NULL)
5611 return (int) REG_ESPACE;
5612
5613 /* Map uppercase characters to corresponding lowercase ones. */
5614 for (i = 0; i < CHAR_SET_SIZE; i++)
5615 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5616 }
5617 else
5618 preg->translate = NULL;
5619
5620 /* If REG_NEWLINE is set, newlines are treated differently. */
5621 if (cflags & REG_NEWLINE)
5622 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5623 syntax &= ~RE_DOT_NEWLINE;
5624 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5625 /* It also changes the matching behavior. */
5626 preg->newline_anchor = 1;
5627 }
5628 else
5629 preg->newline_anchor = 0;
5630
5631 preg->no_sub = !!(cflags & REG_NOSUB);
5632
5633 /* POSIX says a null character in the pattern terminates it, so we
5634 can use strlen here in compiling the pattern. */
5635 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5636
5637 /* POSIX doesn't distinguish between an unmatched open-group and an
5638 unmatched close-group: both are REG_EPAREN. */
5639 if (ret == REG_ERPAREN) ret = REG_EPAREN;
5640
5641 return (int) ret;
5642 }
5643 #ifdef _LIBC
5644 weak_alias (__regcomp, regcomp)
5645 #endif
5646
5647
5648 /* regexec searches for a given pattern, specified by PREG, in the
5649 string STRING.
5650
5651 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5652 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5653 least NMATCH elements, and we set them to the offsets of the
5654 corresponding matched substrings.
5655
5656 EFLAGS specifies `execution flags' which affect matching: if
5657 REG_NOTBOL is set, then ^ does not match at the beginning of the
5658 string; if REG_NOTEOL is set, then $ does not match at the end.
5659
5660 We return 0 if we find a match and REG_NOMATCH if not. */
5661
5662 int
5663 regexec (preg, string, nmatch, pmatch, eflags)
5664 const regex_t *preg;
5665 const char *string;
5666 size_t nmatch;
5667 regmatch_t pmatch[];
5668 int eflags;
5669 {
5670 int ret;
5671 struct re_registers regs;
5672 regex_t private_preg;
5673 int len = strlen (string);
5674 boolean want_reg_info = !preg->no_sub && nmatch > 0;
5675
5676 private_preg = *preg;
5677
5678 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5679 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5680
5681 /* The user has told us exactly how many registers to return
5682 information about, via `nmatch'. We have to pass that on to the
5683 matching routines. */
5684 private_preg.regs_allocated = REGS_FIXED;
5685
5686 if (want_reg_info)
5687 {
5688 regs.num_regs = nmatch;
5689 regs.start = TALLOC (nmatch, regoff_t);
5690 regs.end = TALLOC (nmatch, regoff_t);
5691 if (regs.start == NULL || regs.end == NULL)
5692 return (int) REG_NOMATCH;
5693 }
5694
5695 /* Perform the searching operation. */
5696 ret = re_search (&private_preg, string, len,
5697 /* start: */ 0, /* range: */ len,
5698 want_reg_info ? &regs : (struct re_registers *) 0);
5699
5700 /* Copy the register information to the POSIX structure. */
5701 if (want_reg_info)
5702 {
5703 if (ret >= 0)
5704 {
5705 unsigned r;
5706
5707 for (r = 0; r < nmatch; r++)
5708 {
5709 pmatch[r].rm_so = regs.start[r];
5710 pmatch[r].rm_eo = regs.end[r];
5711 }
5712 }
5713
5714 /* If we needed the temporary register info, free the space now. */
5715 free (regs.start);
5716 free (regs.end);
5717 }
5718
5719 /* We want zero return to mean success, unlike `re_search'. */
5720 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5721 }
5722 #ifdef _LIBC
5723 weak_alias (__regexec, regexec)
5724 #endif
5725
5726
5727 /* Returns a message corresponding to an error code, ERRCODE, returned
5728 from either regcomp or regexec. We don't use PREG here. */
5729
5730 size_t
5731 regerror (errcode, preg, errbuf, errbuf_size)
5732 int errcode;
5733 const regex_t *preg;
5734 char *errbuf;
5735 size_t errbuf_size;
5736 {
5737 const char *msg;
5738 size_t msg_size;
5739
5740 if (errcode < 0
5741 || errcode >= (int) (sizeof (re_error_msgid)
5742 / sizeof (re_error_msgid[0])))
5743 /* Only error codes returned by the rest of the code should be passed
5744 to this routine. If we are given anything else, or if other regex
5745 code generates an invalid error code, then the program has a bug.
5746 Dump core so we can fix it. */
5747 abort ();
5748
5749 msg = gettext (re_error_msgid[errcode]);
5750
5751 msg_size = strlen (msg) + 1; /* Includes the null. */
5752
5753 if (errbuf_size != 0)
5754 {
5755 if (msg_size > errbuf_size)
5756 {
5757 #if defined HAVE_MEMPCPY || defined _LIBC
5758 *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
5759 #else
5760 memcpy (errbuf, msg, errbuf_size - 1);
5761 errbuf[errbuf_size - 1] = 0;
5762 #endif
5763 }
5764 else
5765 memcpy (errbuf, msg, msg_size);
5766 }
5767
5768 return msg_size;
5769 }
5770 #ifdef _LIBC
5771 weak_alias (__regerror, regerror)
5772 #endif
5773
5774
5775 /* Free dynamically allocated space used by PREG. */
5776
5777 void
5778 regfree (preg)
5779 regex_t *preg;
5780 {
5781 if (preg->buffer != NULL)
5782 free (preg->buffer);
5783 preg->buffer = NULL;
5784
5785 preg->allocated = 0;
5786 preg->used = 0;
5787
5788 if (preg->fastmap != NULL)
5789 free (preg->fastmap);
5790 preg->fastmap = NULL;
5791 preg->fastmap_accurate = 0;
5792
5793 if (preg->translate != NULL)
5794 free (preg->translate);
5795 preg->translate = NULL;
5796 }
5797 #ifdef _LIBC
5798 weak_alias (__regfree, regfree)
5799 #endif
5800
5801 #endif /* not emacs */
This page took 0.189242 seconds and 5 git commands to generate.