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