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