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