]> code.delx.au - gnu-emacs/blob - src/regex.c
(detect_coding_mask): Initilize local variable C.
[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, 1998 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 (RE_TRANSLATE_P (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 (RE_TRANSLATE_P (translate) \
1565 ? (unsigned) RE_TRANSLATE (translate, (unsigned) (d)) : (d))
1566 #endif
1567
1568
1569 /* Macros for outputting the compiled pattern into `buffer'. */
1570
1571 /* If the buffer isn't allocated when it comes in, use this. */
1572 #define INIT_BUF_SIZE 32
1573
1574 /* Make sure we have at least N more bytes of space in buffer. */
1575 #define GET_BUFFER_SPACE(n) \
1576 while (b - bufp->buffer + (n) > bufp->allocated) \
1577 EXTEND_BUFFER ()
1578
1579 /* Make sure we have one more byte of buffer space and then add C to it. */
1580 #define BUF_PUSH(c) \
1581 do { \
1582 GET_BUFFER_SPACE (1); \
1583 *b++ = (unsigned char) (c); \
1584 } while (0)
1585
1586
1587 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1588 #define BUF_PUSH_2(c1, c2) \
1589 do { \
1590 GET_BUFFER_SPACE (2); \
1591 *b++ = (unsigned char) (c1); \
1592 *b++ = (unsigned char) (c2); \
1593 } while (0)
1594
1595
1596 /* As with BUF_PUSH_2, except for three bytes. */
1597 #define BUF_PUSH_3(c1, c2, c3) \
1598 do { \
1599 GET_BUFFER_SPACE (3); \
1600 *b++ = (unsigned char) (c1); \
1601 *b++ = (unsigned char) (c2); \
1602 *b++ = (unsigned char) (c3); \
1603 } while (0)
1604
1605
1606 /* Store a jump with opcode OP at LOC to location TO. We store a
1607 relative address offset by the three bytes the jump itself occupies. */
1608 #define STORE_JUMP(op, loc, to) \
1609 store_op1 (op, loc, (to) - (loc) - 3)
1610
1611 /* Likewise, for a two-argument jump. */
1612 #define STORE_JUMP2(op, loc, to, arg) \
1613 store_op2 (op, loc, (to) - (loc) - 3, arg)
1614
1615 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1616 #define INSERT_JUMP(op, loc, to) \
1617 insert_op1 (op, loc, (to) - (loc) - 3, b)
1618
1619 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1620 #define INSERT_JUMP2(op, loc, to, arg) \
1621 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1622
1623
1624 /* This is not an arbitrary limit: the arguments which represent offsets
1625 into the pattern are two bytes long. So if 2^16 bytes turns out to
1626 be too small, many things would have to change. */
1627 #define MAX_BUF_SIZE (1L << 16)
1628
1629
1630 /* Extend the buffer by twice its current size via realloc and
1631 reset the pointers that pointed into the old block to point to the
1632 correct places in the new one. If extending the buffer results in it
1633 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1634 #define EXTEND_BUFFER() \
1635 do { \
1636 unsigned char *old_buffer = bufp->buffer; \
1637 if (bufp->allocated == MAX_BUF_SIZE) \
1638 return REG_ESIZE; \
1639 bufp->allocated <<= 1; \
1640 if (bufp->allocated > MAX_BUF_SIZE) \
1641 bufp->allocated = MAX_BUF_SIZE; \
1642 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1643 if (bufp->buffer == NULL) \
1644 return REG_ESPACE; \
1645 /* If the buffer moved, move all the pointers into it. */ \
1646 if (old_buffer != bufp->buffer) \
1647 { \
1648 b = (b - old_buffer) + bufp->buffer; \
1649 begalt = (begalt - old_buffer) + bufp->buffer; \
1650 if (fixup_alt_jump) \
1651 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1652 if (laststart) \
1653 laststart = (laststart - old_buffer) + bufp->buffer; \
1654 if (pending_exact) \
1655 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1656 } \
1657 } while (0)
1658
1659
1660 /* Since we have one byte reserved for the register number argument to
1661 {start,stop}_memory, the maximum number of groups we can report
1662 things about is what fits in that byte. */
1663 #define MAX_REGNUM 255
1664
1665 /* But patterns can have more than `MAX_REGNUM' registers. We just
1666 ignore the excess. */
1667 typedef unsigned regnum_t;
1668
1669
1670 /* Macros for the compile stack. */
1671
1672 /* Since offsets can go either forwards or backwards, this type needs to
1673 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1674 typedef int pattern_offset_t;
1675
1676 typedef struct
1677 {
1678 pattern_offset_t begalt_offset;
1679 pattern_offset_t fixup_alt_jump;
1680 pattern_offset_t inner_group_offset;
1681 pattern_offset_t laststart_offset;
1682 regnum_t regnum;
1683 } compile_stack_elt_t;
1684
1685
1686 typedef struct
1687 {
1688 compile_stack_elt_t *stack;
1689 unsigned size;
1690 unsigned avail; /* Offset of next open position. */
1691 } compile_stack_type;
1692
1693
1694 #define INIT_COMPILE_STACK_SIZE 32
1695
1696 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1697 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1698
1699 /* The next available element. */
1700 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1701
1702
1703 /* Structure to manage work area for range table. */
1704 struct range_table_work_area
1705 {
1706 int *table; /* actual work area. */
1707 int allocated; /* allocated size for work area in bytes. */
1708 int used; /* actually used size in words. */
1709 };
1710
1711 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1712 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1713 do { \
1714 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1715 { \
1716 (work_area).allocated += 16 * sizeof (int); \
1717 if ((work_area).table) \
1718 (work_area).table \
1719 = (int *) realloc ((work_area).table, (work_area).allocated); \
1720 else \
1721 (work_area).table \
1722 = (int *) malloc ((work_area).allocated); \
1723 if ((work_area).table == 0) \
1724 FREE_STACK_RETURN (REG_ESPACE); \
1725 } \
1726 } while (0)
1727
1728 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1729 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1730 do { \
1731 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1732 (work_area).table[(work_area).used++] = (range_start); \
1733 (work_area).table[(work_area).used++] = (range_end); \
1734 } while (0)
1735
1736 /* Free allocated memory for WORK_AREA. */
1737 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1738 do { \
1739 if ((work_area).table) \
1740 free ((work_area).table); \
1741 } while (0)
1742
1743 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0)
1744 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1745 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1746
1747
1748 /* Set the bit for character C in a list. */
1749 #define SET_LIST_BIT(c) \
1750 (b[((unsigned char) (c)) / BYTEWIDTH] \
1751 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1752
1753
1754 /* Get the next unsigned number in the uncompiled pattern. */
1755 #define GET_UNSIGNED_NUMBER(num) \
1756 { if (p != pend) \
1757 { \
1758 PATFETCH (c); \
1759 while (ISDIGIT (c)) \
1760 { \
1761 if (num < 0) \
1762 num = 0; \
1763 num = num * 10 + c - '0'; \
1764 if (p == pend) \
1765 break; \
1766 PATFETCH (c); \
1767 } \
1768 } \
1769 }
1770
1771 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1772
1773 #define IS_CHAR_CLASS(string) \
1774 (STREQ (string, "alpha") || STREQ (string, "upper") \
1775 || STREQ (string, "lower") || STREQ (string, "digit") \
1776 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1777 || STREQ (string, "space") || STREQ (string, "print") \
1778 || STREQ (string, "punct") || STREQ (string, "graph") \
1779 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1780 \f
1781 #ifndef MATCH_MAY_ALLOCATE
1782
1783 /* If we cannot allocate large objects within re_match_2_internal,
1784 we make the fail stack and register vectors global.
1785 The fail stack, we grow to the maximum size when a regexp
1786 is compiled.
1787 The register vectors, we adjust in size each time we
1788 compile a regexp, according to the number of registers it needs. */
1789
1790 static fail_stack_type fail_stack;
1791
1792 /* Size with which the following vectors are currently allocated.
1793 That is so we can make them bigger as needed,
1794 but never make them smaller. */
1795 static int regs_allocated_size;
1796
1797 static const char ** regstart, ** regend;
1798 static const char ** old_regstart, ** old_regend;
1799 static const char **best_regstart, **best_regend;
1800 static register_info_type *reg_info;
1801 static const char **reg_dummy;
1802 static register_info_type *reg_info_dummy;
1803
1804 /* Make the register vectors big enough for NUM_REGS registers,
1805 but don't make them smaller. */
1806
1807 static
1808 regex_grow_registers (num_regs)
1809 int num_regs;
1810 {
1811 if (num_regs > regs_allocated_size)
1812 {
1813 RETALLOC_IF (regstart, num_regs, const char *);
1814 RETALLOC_IF (regend, num_regs, const char *);
1815 RETALLOC_IF (old_regstart, num_regs, const char *);
1816 RETALLOC_IF (old_regend, num_regs, const char *);
1817 RETALLOC_IF (best_regstart, num_regs, const char *);
1818 RETALLOC_IF (best_regend, num_regs, const char *);
1819 RETALLOC_IF (reg_info, num_regs, register_info_type);
1820 RETALLOC_IF (reg_dummy, num_regs, const char *);
1821 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1822
1823 regs_allocated_size = num_regs;
1824 }
1825 }
1826
1827 #endif /* not MATCH_MAY_ALLOCATE */
1828 \f
1829 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1830 Returns one of error codes defined in `regex.h', or zero for success.
1831
1832 Assumes the `allocated' (and perhaps `buffer') and `translate'
1833 fields are set in BUFP on entry.
1834
1835 If it succeeds, results are put in BUFP (if it returns an error, the
1836 contents of BUFP are undefined):
1837 `buffer' is the compiled pattern;
1838 `syntax' is set to SYNTAX;
1839 `used' is set to the length of the compiled pattern;
1840 `fastmap_accurate' is zero;
1841 `re_nsub' is the number of subexpressions in PATTERN;
1842 `not_bol' and `not_eol' are zero;
1843
1844 The `fastmap' and `newline_anchor' fields are neither
1845 examined nor set. */
1846
1847 /* Return, freeing storage we allocated. */
1848 #define FREE_STACK_RETURN(value) \
1849 do { \
1850 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1851 free (compile_stack.stack); \
1852 return value; \
1853 } while (0)
1854
1855 static reg_errcode_t
1856 regex_compile (pattern, size, syntax, bufp)
1857 const char *pattern;
1858 int size;
1859 reg_syntax_t syntax;
1860 struct re_pattern_buffer *bufp;
1861 {
1862 /* We fetch characters from PATTERN here. Even though PATTERN is
1863 `char *' (i.e., signed), we declare these variables as unsigned, so
1864 they can be reliably used as array indices. */
1865 register unsigned int c, c1;
1866
1867 /* A random temporary spot in PATTERN. */
1868 const char *p1;
1869
1870 /* Points to the end of the buffer, where we should append. */
1871 register unsigned char *b;
1872
1873 /* Keeps track of unclosed groups. */
1874 compile_stack_type compile_stack;
1875
1876 /* Points to the current (ending) position in the pattern. */
1877 const char *p = pattern;
1878 const char *pend = pattern + size;
1879
1880 /* How to translate the characters in the pattern. */
1881 RE_TRANSLATE_TYPE translate = bufp->translate;
1882
1883 /* Address of the count-byte of the most recently inserted `exactn'
1884 command. This makes it possible to tell if a new exact-match
1885 character can be added to that command or if the character requires
1886 a new `exactn' command. */
1887 unsigned char *pending_exact = 0;
1888
1889 /* Address of start of the most recently finished expression.
1890 This tells, e.g., postfix * where to find the start of its
1891 operand. Reset at the beginning of groups and alternatives. */
1892 unsigned char *laststart = 0;
1893
1894 /* Address of beginning of regexp, or inside of last group. */
1895 unsigned char *begalt;
1896
1897 /* Place in the uncompiled pattern (i.e., the {) to
1898 which to go back if the interval is invalid. */
1899 const char *beg_interval;
1900
1901 /* Address of the place where a forward jump should go to the end of
1902 the containing expression. Each alternative of an `or' -- except the
1903 last -- ends with a forward jump of this sort. */
1904 unsigned char *fixup_alt_jump = 0;
1905
1906 /* Counts open-groups as they are encountered. Remembered for the
1907 matching close-group on the compile stack, so the same register
1908 number is put in the stop_memory as the start_memory. */
1909 regnum_t regnum = 0;
1910
1911 /* Work area for range table of charset. */
1912 struct range_table_work_area range_table_work;
1913
1914 #ifdef DEBUG
1915 DEBUG_PRINT1 ("\nCompiling pattern: ");
1916 if (debug)
1917 {
1918 unsigned debug_count;
1919
1920 for (debug_count = 0; debug_count < size; debug_count++)
1921 putchar (pattern[debug_count]);
1922 putchar ('\n');
1923 }
1924 #endif /* DEBUG */
1925
1926 /* Initialize the compile stack. */
1927 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1928 if (compile_stack.stack == NULL)
1929 return REG_ESPACE;
1930
1931 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1932 compile_stack.avail = 0;
1933
1934 range_table_work.table = 0;
1935 range_table_work.allocated = 0;
1936
1937 /* Initialize the pattern buffer. */
1938 bufp->syntax = syntax;
1939 bufp->fastmap_accurate = 0;
1940 bufp->not_bol = bufp->not_eol = 0;
1941
1942 /* Set `used' to zero, so that if we return an error, the pattern
1943 printer (for debugging) will think there's no pattern. We reset it
1944 at the end. */
1945 bufp->used = 0;
1946
1947 /* Always count groups, whether or not bufp->no_sub is set. */
1948 bufp->re_nsub = 0;
1949
1950 #ifdef emacs
1951 /* bufp->multibyte is set before regex_compile is called, so don't alter
1952 it. */
1953 #else /* not emacs */
1954 /* Nothing is recognized as a multibyte character. */
1955 bufp->multibyte = 0;
1956 #endif
1957
1958 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1959 /* Initialize the syntax table. */
1960 init_syntax_once ();
1961 #endif
1962
1963 if (bufp->allocated == 0)
1964 {
1965 if (bufp->buffer)
1966 { /* If zero allocated, but buffer is non-null, try to realloc
1967 enough space. This loses if buffer's address is bogus, but
1968 that is the user's responsibility. */
1969 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1970 }
1971 else
1972 { /* Caller did not allocate a buffer. Do it for them. */
1973 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1974 }
1975 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1976
1977 bufp->allocated = INIT_BUF_SIZE;
1978 }
1979
1980 begalt = b = bufp->buffer;
1981
1982 /* Loop through the uncompiled pattern until we're at the end. */
1983 while (p != pend)
1984 {
1985 PATFETCH (c);
1986
1987 switch (c)
1988 {
1989 case '^':
1990 {
1991 if ( /* If at start of pattern, it's an operator. */
1992 p == pattern + 1
1993 /* If context independent, it's an operator. */
1994 || syntax & RE_CONTEXT_INDEP_ANCHORS
1995 /* Otherwise, depends on what's come before. */
1996 || at_begline_loc_p (pattern, p, syntax))
1997 BUF_PUSH (begline);
1998 else
1999 goto normal_char;
2000 }
2001 break;
2002
2003
2004 case '$':
2005 {
2006 if ( /* If at end of pattern, it's an operator. */
2007 p == pend
2008 /* If context independent, it's an operator. */
2009 || syntax & RE_CONTEXT_INDEP_ANCHORS
2010 /* Otherwise, depends on what's next. */
2011 || at_endline_loc_p (p, pend, syntax))
2012 BUF_PUSH (endline);
2013 else
2014 goto normal_char;
2015 }
2016 break;
2017
2018
2019 case '+':
2020 case '?':
2021 if ((syntax & RE_BK_PLUS_QM)
2022 || (syntax & RE_LIMITED_OPS))
2023 goto normal_char;
2024 handle_plus:
2025 case '*':
2026 /* If there is no previous pattern... */
2027 if (!laststart)
2028 {
2029 if (syntax & RE_CONTEXT_INVALID_OPS)
2030 FREE_STACK_RETURN (REG_BADRPT);
2031 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2032 goto normal_char;
2033 }
2034
2035 {
2036 /* Are we optimizing this jump? */
2037 boolean keep_string_p = false;
2038
2039 /* 1 means zero (many) matches is allowed. */
2040 char zero_times_ok = 0, many_times_ok = 0;
2041
2042 /* If there is a sequence of repetition chars, collapse it
2043 down to just one (the right one). We can't combine
2044 interval operators with these because of, e.g., `a{2}*',
2045 which should only match an even number of `a's. */
2046
2047 for (;;)
2048 {
2049 zero_times_ok |= c != '+';
2050 many_times_ok |= c != '?';
2051
2052 if (p == pend)
2053 break;
2054
2055 PATFETCH (c);
2056
2057 if (c == '*'
2058 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2059 ;
2060
2061 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2062 {
2063 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2064
2065 PATFETCH (c1);
2066 if (!(c1 == '+' || c1 == '?'))
2067 {
2068 PATUNFETCH;
2069 PATUNFETCH;
2070 break;
2071 }
2072
2073 c = c1;
2074 }
2075 else
2076 {
2077 PATUNFETCH;
2078 break;
2079 }
2080
2081 /* If we get here, we found another repeat character. */
2082 }
2083
2084 /* Star, etc. applied to an empty pattern is equivalent
2085 to an empty pattern. */
2086 if (!laststart)
2087 break;
2088
2089 /* Now we know whether or not zero matches is allowed
2090 and also whether or not two or more matches is allowed. */
2091 if (many_times_ok)
2092 { /* More than one repetition is allowed, so put in at the
2093 end a backward relative jump from `b' to before the next
2094 jump we're going to put in below (which jumps from
2095 laststart to after this jump).
2096
2097 But if we are at the `*' in the exact sequence `.*\n',
2098 insert an unconditional jump backwards to the .,
2099 instead of the beginning of the loop. This way we only
2100 push a failure point once, instead of every time
2101 through the loop. */
2102 assert (p - 1 > pattern);
2103
2104 /* Allocate the space for the jump. */
2105 GET_BUFFER_SPACE (3);
2106
2107 /* We know we are not at the first character of the pattern,
2108 because laststart was nonzero. And we've already
2109 incremented `p', by the way, to be the character after
2110 the `*'. Do we have to do something analogous here
2111 for null bytes, because of RE_DOT_NOT_NULL? */
2112 if (TRANSLATE ((unsigned char)*(p - 2)) == TRANSLATE ('.')
2113 && zero_times_ok
2114 && p < pend
2115 && TRANSLATE ((unsigned char)*p) == TRANSLATE ('\n')
2116 && !(syntax & RE_DOT_NEWLINE))
2117 { /* We have .*\n. */
2118 STORE_JUMP (jump, b, laststart);
2119 keep_string_p = true;
2120 }
2121 else
2122 /* Anything else. */
2123 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
2124
2125 /* We've added more stuff to the buffer. */
2126 b += 3;
2127 }
2128
2129 /* On failure, jump from laststart to b + 3, which will be the
2130 end of the buffer after this jump is inserted. */
2131 GET_BUFFER_SPACE (3);
2132 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2133 : on_failure_jump,
2134 laststart, b + 3);
2135 pending_exact = 0;
2136 b += 3;
2137
2138 if (!zero_times_ok)
2139 {
2140 /* At least one repetition is required, so insert a
2141 `dummy_failure_jump' before the initial
2142 `on_failure_jump' instruction of the loop. This
2143 effects a skip over that instruction the first time
2144 we hit that loop. */
2145 GET_BUFFER_SPACE (3);
2146 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
2147 b += 3;
2148 }
2149 }
2150 break;
2151
2152
2153 case '.':
2154 laststart = b;
2155 BUF_PUSH (anychar);
2156 break;
2157
2158
2159 case '[':
2160 {
2161 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2162
2163 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2164
2165 /* Ensure that we have enough space to push a charset: the
2166 opcode, the length count, and the bitset; 34 bytes in all. */
2167 GET_BUFFER_SPACE (34);
2168
2169 laststart = b;
2170
2171 /* We test `*p == '^' twice, instead of using an if
2172 statement, so we only need one BUF_PUSH. */
2173 BUF_PUSH (*p == '^' ? charset_not : charset);
2174 if (*p == '^')
2175 p++;
2176
2177 /* Remember the first position in the bracket expression. */
2178 p1 = p;
2179
2180 /* Push the number of bytes in the bitmap. */
2181 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2182
2183 /* Clear the whole map. */
2184 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2185
2186 /* charset_not matches newline according to a syntax bit. */
2187 if ((re_opcode_t) b[-2] == charset_not
2188 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2189 SET_LIST_BIT ('\n');
2190
2191 /* Read in characters and ranges, setting map bits. */
2192 for (;;)
2193 {
2194 int len;
2195 boolean escaped_char = false;
2196
2197 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2198
2199 PATFETCH (c);
2200
2201 /* \ might escape characters inside [...] and [^...]. */
2202 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2203 {
2204 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2205
2206 PATFETCH (c);
2207 escaped_char = true;
2208 }
2209 else
2210 {
2211 /* Could be the end of the bracket expression. If it's
2212 not (i.e., when the bracket expression is `[]' so
2213 far), the ']' character bit gets set way below. */
2214 if (c == ']' && p != p1 + 1)
2215 break;
2216 }
2217
2218 /* If C indicates start of multibyte char, get the
2219 actual character code in C, and set the pattern
2220 pointer P to the next character boundary. */
2221 if (bufp->multibyte && BASE_LEADING_CODE_P (c))
2222 {
2223 PATUNFETCH;
2224 c = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2225 p += len;
2226 }
2227 /* What should we do for the character which is
2228 greater than 0x7F, but not BASE_LEADING_CODE_P?
2229 XXX */
2230
2231 /* See if we're at the beginning of a possible character
2232 class. */
2233
2234 else if (!escaped_char &&
2235 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2236 {
2237 /* Leave room for the null. */
2238 char str[CHAR_CLASS_MAX_LENGTH + 1];
2239
2240 PATFETCH (c);
2241 c1 = 0;
2242
2243 /* If pattern is `[[:'. */
2244 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2245
2246 for (;;)
2247 {
2248 PATFETCH (c);
2249 if (c == ':' || c == ']' || p == pend
2250 || c1 == CHAR_CLASS_MAX_LENGTH)
2251 break;
2252 str[c1++] = c;
2253 }
2254 str[c1] = '\0';
2255
2256 /* If isn't a word bracketed by `[:' and `:]':
2257 undo the ending character, the letters, and
2258 leave the leading `:' and `[' (but set bits for
2259 them). */
2260 if (c == ':' && *p == ']')
2261 {
2262 int ch;
2263 boolean is_alnum = STREQ (str, "alnum");
2264 boolean is_alpha = STREQ (str, "alpha");
2265 boolean is_blank = STREQ (str, "blank");
2266 boolean is_cntrl = STREQ (str, "cntrl");
2267 boolean is_digit = STREQ (str, "digit");
2268 boolean is_graph = STREQ (str, "graph");
2269 boolean is_lower = STREQ (str, "lower");
2270 boolean is_print = STREQ (str, "print");
2271 boolean is_punct = STREQ (str, "punct");
2272 boolean is_space = STREQ (str, "space");
2273 boolean is_upper = STREQ (str, "upper");
2274 boolean is_xdigit = STREQ (str, "xdigit");
2275
2276 if (!IS_CHAR_CLASS (str))
2277 FREE_STACK_RETURN (REG_ECTYPE);
2278
2279 /* Throw away the ] at the end of the character
2280 class. */
2281 PATFETCH (c);
2282
2283 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2284
2285 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2286 {
2287 int translated = TRANSLATE (ch);
2288 /* This was split into 3 if's to
2289 avoid an arbitrary limit in some compiler. */
2290 if ( (is_alnum && ISALNUM (ch))
2291 || (is_alpha && ISALPHA (ch))
2292 || (is_blank && ISBLANK (ch))
2293 || (is_cntrl && ISCNTRL (ch)))
2294 SET_LIST_BIT (translated);
2295 if ( (is_digit && ISDIGIT (ch))
2296 || (is_graph && ISGRAPH (ch))
2297 || (is_lower && ISLOWER (ch))
2298 || (is_print && ISPRINT (ch)))
2299 SET_LIST_BIT (translated);
2300 if ( (is_punct && ISPUNCT (ch))
2301 || (is_space && ISSPACE (ch))
2302 || (is_upper && ISUPPER (ch))
2303 || (is_xdigit && ISXDIGIT (ch)))
2304 SET_LIST_BIT (translated);
2305 }
2306
2307 /* Repeat the loop. */
2308 continue;
2309 }
2310 else
2311 {
2312 c1++;
2313 while (c1--)
2314 PATUNFETCH;
2315 SET_LIST_BIT ('[');
2316
2317 /* Because the `:' may starts the range, we
2318 can't simply set bit and repeat the loop.
2319 Instead, just set it to C and handle below. */
2320 c = ':';
2321 }
2322 }
2323
2324 if (p < pend && p[0] == '-' && p[1] != ']')
2325 {
2326
2327 /* Discard the `-'. */
2328 PATFETCH (c1);
2329
2330 /* Fetch the character which ends the range. */
2331 PATFETCH (c1);
2332 if (bufp->multibyte && BASE_LEADING_CODE_P (c1))
2333 {
2334 PATUNFETCH;
2335 c1 = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2336 p += len;
2337 }
2338
2339 if (SINGLE_BYTE_CHAR_P (c)
2340 && ! SINGLE_BYTE_CHAR_P (c1))
2341 {
2342 /* Handle a range such as \177-\377 in multibyte mode.
2343 Split that into two ranges,,
2344 the low one ending at 0237, and the high one
2345 starting at ...040. */
2346 int c1_base = (c1 & ~0177) | 040;
2347 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2348 c1 = 0237;
2349 }
2350 else if (!SAME_CHARSET_P (c, c1))
2351 FREE_STACK_RETURN (REG_ERANGE);
2352 }
2353 else
2354 /* Range from C to C. */
2355 c1 = c;
2356
2357 /* Set the range ... */
2358 if (SINGLE_BYTE_CHAR_P (c))
2359 /* ... into bitmap. */
2360 {
2361 unsigned this_char;
2362 int range_start = c, range_end = c1;
2363
2364 /* If the start is after the end, the range is empty. */
2365 if (range_start > range_end)
2366 {
2367 if (syntax & RE_NO_EMPTY_RANGES)
2368 FREE_STACK_RETURN (REG_ERANGE);
2369 /* Else, repeat the loop. */
2370 }
2371 else
2372 {
2373 for (this_char = range_start; this_char <= range_end;
2374 this_char++)
2375 SET_LIST_BIT (TRANSLATE (this_char));
2376 }
2377 }
2378 else
2379 /* ... into range table. */
2380 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2381 }
2382
2383 /* Discard any (non)matching list bytes that are all 0 at the
2384 end of the map. Decrease the map-length byte too. */
2385 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2386 b[-1]--;
2387 b += b[-1];
2388
2389 /* Build real range table from work area. */
2390 if (RANGE_TABLE_WORK_USED (range_table_work))
2391 {
2392 int i;
2393 int used = RANGE_TABLE_WORK_USED (range_table_work);
2394
2395 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2396 bytes for COUNT and three bytes for each character. */
2397 GET_BUFFER_SPACE (2 + used * 3);
2398
2399 /* Indicate the existence of range table. */
2400 laststart[1] |= 0x80;
2401
2402 STORE_NUMBER_AND_INCR (b, used / 2);
2403 for (i = 0; i < used; i++)
2404 STORE_CHARACTER_AND_INCR
2405 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2406 }
2407 }
2408 break;
2409
2410
2411 case '(':
2412 if (syntax & RE_NO_BK_PARENS)
2413 goto handle_open;
2414 else
2415 goto normal_char;
2416
2417
2418 case ')':
2419 if (syntax & RE_NO_BK_PARENS)
2420 goto handle_close;
2421 else
2422 goto normal_char;
2423
2424
2425 case '\n':
2426 if (syntax & RE_NEWLINE_ALT)
2427 goto handle_alt;
2428 else
2429 goto normal_char;
2430
2431
2432 case '|':
2433 if (syntax & RE_NO_BK_VBAR)
2434 goto handle_alt;
2435 else
2436 goto normal_char;
2437
2438
2439 case '{':
2440 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2441 goto handle_interval;
2442 else
2443 goto normal_char;
2444
2445
2446 case '\\':
2447 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2448
2449 /* Do not translate the character after the \, so that we can
2450 distinguish, e.g., \B from \b, even if we normally would
2451 translate, e.g., B to b. */
2452 PATFETCH_RAW (c);
2453
2454 switch (c)
2455 {
2456 case '(':
2457 if (syntax & RE_NO_BK_PARENS)
2458 goto normal_backslash;
2459
2460 handle_open:
2461 bufp->re_nsub++;
2462 regnum++;
2463
2464 if (COMPILE_STACK_FULL)
2465 {
2466 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2467 compile_stack_elt_t);
2468 if (compile_stack.stack == NULL) return REG_ESPACE;
2469
2470 compile_stack.size <<= 1;
2471 }
2472
2473 /* These are the values to restore when we hit end of this
2474 group. They are all relative offsets, so that if the
2475 whole pattern moves because of realloc, they will still
2476 be valid. */
2477 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2478 COMPILE_STACK_TOP.fixup_alt_jump
2479 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2480 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2481 COMPILE_STACK_TOP.regnum = regnum;
2482
2483 /* We will eventually replace the 0 with the number of
2484 groups inner to this one. But do not push a
2485 start_memory for groups beyond the last one we can
2486 represent in the compiled pattern. */
2487 if (regnum <= MAX_REGNUM)
2488 {
2489 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2490 BUF_PUSH_3 (start_memory, regnum, 0);
2491 }
2492
2493 compile_stack.avail++;
2494
2495 fixup_alt_jump = 0;
2496 laststart = 0;
2497 begalt = b;
2498 /* If we've reached MAX_REGNUM groups, then this open
2499 won't actually generate any code, so we'll have to
2500 clear pending_exact explicitly. */
2501 pending_exact = 0;
2502 break;
2503
2504
2505 case ')':
2506 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2507
2508 if (COMPILE_STACK_EMPTY)
2509 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2510 goto normal_backslash;
2511 else
2512 FREE_STACK_RETURN (REG_ERPAREN);
2513
2514 handle_close:
2515 if (fixup_alt_jump)
2516 { /* Push a dummy failure point at the end of the
2517 alternative for a possible future
2518 `pop_failure_jump' to pop. See comments at
2519 `push_dummy_failure' in `re_match_2'. */
2520 BUF_PUSH (push_dummy_failure);
2521
2522 /* We allocated space for this jump when we assigned
2523 to `fixup_alt_jump', in the `handle_alt' case below. */
2524 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2525 }
2526
2527 /* See similar code for backslashed left paren above. */
2528 if (COMPILE_STACK_EMPTY)
2529 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2530 goto normal_char;
2531 else
2532 FREE_STACK_RETURN (REG_ERPAREN);
2533
2534 /* Since we just checked for an empty stack above, this
2535 ``can't happen''. */
2536 assert (compile_stack.avail != 0);
2537 {
2538 /* We don't just want to restore into `regnum', because
2539 later groups should continue to be numbered higher,
2540 as in `(ab)c(de)' -- the second group is #2. */
2541 regnum_t this_group_regnum;
2542
2543 compile_stack.avail--;
2544 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2545 fixup_alt_jump
2546 = COMPILE_STACK_TOP.fixup_alt_jump
2547 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2548 : 0;
2549 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2550 this_group_regnum = COMPILE_STACK_TOP.regnum;
2551 /* If we've reached MAX_REGNUM groups, then this open
2552 won't actually generate any code, so we'll have to
2553 clear pending_exact explicitly. */
2554 pending_exact = 0;
2555
2556 /* We're at the end of the group, so now we know how many
2557 groups were inside this one. */
2558 if (this_group_regnum <= MAX_REGNUM)
2559 {
2560 unsigned char *inner_group_loc
2561 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2562
2563 *inner_group_loc = regnum - this_group_regnum;
2564 BUF_PUSH_3 (stop_memory, this_group_regnum,
2565 regnum - this_group_regnum);
2566 }
2567 }
2568 break;
2569
2570
2571 case '|': /* `\|'. */
2572 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2573 goto normal_backslash;
2574 handle_alt:
2575 if (syntax & RE_LIMITED_OPS)
2576 goto normal_char;
2577
2578 /* Insert before the previous alternative a jump which
2579 jumps to this alternative if the former fails. */
2580 GET_BUFFER_SPACE (3);
2581 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2582 pending_exact = 0;
2583 b += 3;
2584
2585 /* The alternative before this one has a jump after it
2586 which gets executed if it gets matched. Adjust that
2587 jump so it will jump to this alternative's analogous
2588 jump (put in below, which in turn will jump to the next
2589 (if any) alternative's such jump, etc.). The last such
2590 jump jumps to the correct final destination. A picture:
2591 _____ _____
2592 | | | |
2593 | v | v
2594 a | b | c
2595
2596 If we are at `b', then fixup_alt_jump right now points to a
2597 three-byte space after `a'. We'll put in the jump, set
2598 fixup_alt_jump to right after `b', and leave behind three
2599 bytes which we'll fill in when we get to after `c'. */
2600
2601 if (fixup_alt_jump)
2602 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2603
2604 /* Mark and leave space for a jump after this alternative,
2605 to be filled in later either by next alternative or
2606 when know we're at the end of a series of alternatives. */
2607 fixup_alt_jump = b;
2608 GET_BUFFER_SPACE (3);
2609 b += 3;
2610
2611 laststart = 0;
2612 begalt = b;
2613 break;
2614
2615
2616 case '{':
2617 /* If \{ is a literal. */
2618 if (!(syntax & RE_INTERVALS)
2619 /* If we're at `\{' and it's not the open-interval
2620 operator. */
2621 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2622 || (p - 2 == pattern && p == pend))
2623 goto normal_backslash;
2624
2625 handle_interval:
2626 {
2627 /* If got here, then the syntax allows intervals. */
2628
2629 /* At least (most) this many matches must be made. */
2630 int lower_bound = -1, upper_bound = -1;
2631
2632 beg_interval = p - 1;
2633
2634 if (p == pend)
2635 {
2636 if (syntax & RE_NO_BK_BRACES)
2637 goto unfetch_interval;
2638 else
2639 FREE_STACK_RETURN (REG_EBRACE);
2640 }
2641
2642 GET_UNSIGNED_NUMBER (lower_bound);
2643
2644 if (c == ',')
2645 {
2646 GET_UNSIGNED_NUMBER (upper_bound);
2647 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2648 }
2649 else
2650 /* Interval such as `{1}' => match exactly once. */
2651 upper_bound = lower_bound;
2652
2653 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2654 || lower_bound > upper_bound)
2655 {
2656 if (syntax & RE_NO_BK_BRACES)
2657 goto unfetch_interval;
2658 else
2659 FREE_STACK_RETURN (REG_BADBR);
2660 }
2661
2662 if (!(syntax & RE_NO_BK_BRACES))
2663 {
2664 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2665
2666 PATFETCH (c);
2667 }
2668
2669 if (c != '}')
2670 {
2671 if (syntax & RE_NO_BK_BRACES)
2672 goto unfetch_interval;
2673 else
2674 FREE_STACK_RETURN (REG_BADBR);
2675 }
2676
2677 /* We just parsed a valid interval. */
2678
2679 /* If it's invalid to have no preceding re. */
2680 if (!laststart)
2681 {
2682 if (syntax & RE_CONTEXT_INVALID_OPS)
2683 FREE_STACK_RETURN (REG_BADRPT);
2684 else if (syntax & RE_CONTEXT_INDEP_OPS)
2685 laststart = b;
2686 else
2687 goto unfetch_interval;
2688 }
2689
2690 /* If the upper bound is zero, don't want to succeed at
2691 all; jump from `laststart' to `b + 3', which will be
2692 the end of the buffer after we insert the jump. */
2693 if (upper_bound == 0)
2694 {
2695 GET_BUFFER_SPACE (3);
2696 INSERT_JUMP (jump, laststart, b + 3);
2697 b += 3;
2698 }
2699
2700 /* Otherwise, we have a nontrivial interval. When
2701 we're all done, the pattern will look like:
2702 set_number_at <jump count> <upper bound>
2703 set_number_at <succeed_n count> <lower bound>
2704 succeed_n <after jump addr> <succeed_n count>
2705 <body of loop>
2706 jump_n <succeed_n addr> <jump count>
2707 (The upper bound and `jump_n' are omitted if
2708 `upper_bound' is 1, though.) */
2709 else
2710 { /* If the upper bound is > 1, we need to insert
2711 more at the end of the loop. */
2712 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2713
2714 GET_BUFFER_SPACE (nbytes);
2715
2716 /* Initialize lower bound of the `succeed_n', even
2717 though it will be set during matching by its
2718 attendant `set_number_at' (inserted next),
2719 because `re_compile_fastmap' needs to know.
2720 Jump to the `jump_n' we might insert below. */
2721 INSERT_JUMP2 (succeed_n, laststart,
2722 b + 5 + (upper_bound > 1) * 5,
2723 lower_bound);
2724 b += 5;
2725
2726 /* Code to initialize the lower bound. Insert
2727 before the `succeed_n'. The `5' is the last two
2728 bytes of this `set_number_at', plus 3 bytes of
2729 the following `succeed_n'. */
2730 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2731 b += 5;
2732
2733 if (upper_bound > 1)
2734 { /* More than one repetition is allowed, so
2735 append a backward jump to the `succeed_n'
2736 that starts this interval.
2737
2738 When we've reached this during matching,
2739 we'll have matched the interval once, so
2740 jump back only `upper_bound - 1' times. */
2741 STORE_JUMP2 (jump_n, b, laststart + 5,
2742 upper_bound - 1);
2743 b += 5;
2744
2745 /* The location we want to set is the second
2746 parameter of the `jump_n'; that is `b-2' as
2747 an absolute address. `laststart' will be
2748 the `set_number_at' we're about to insert;
2749 `laststart+3' the number to set, the source
2750 for the relative address. But we are
2751 inserting into the middle of the pattern --
2752 so everything is getting moved up by 5.
2753 Conclusion: (b - 2) - (laststart + 3) + 5,
2754 i.e., b - laststart.
2755
2756 We insert this at the beginning of the loop
2757 so that if we fail during matching, we'll
2758 reinitialize the bounds. */
2759 insert_op2 (set_number_at, laststart, b - laststart,
2760 upper_bound - 1, b);
2761 b += 5;
2762 }
2763 }
2764 pending_exact = 0;
2765 beg_interval = NULL;
2766 }
2767 break;
2768
2769 unfetch_interval:
2770 /* If an invalid interval, match the characters as literals. */
2771 assert (beg_interval);
2772 p = beg_interval;
2773 beg_interval = NULL;
2774
2775 /* normal_char and normal_backslash need `c'. */
2776 PATFETCH (c);
2777
2778 if (!(syntax & RE_NO_BK_BRACES))
2779 {
2780 if (p > pattern && p[-1] == '\\')
2781 goto normal_backslash;
2782 }
2783 goto normal_char;
2784
2785 #ifdef emacs
2786 /* There is no way to specify the before_dot and after_dot
2787 operators. rms says this is ok. --karl */
2788 case '=':
2789 BUF_PUSH (at_dot);
2790 break;
2791
2792 case 's':
2793 laststart = b;
2794 PATFETCH (c);
2795 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2796 break;
2797
2798 case 'S':
2799 laststart = b;
2800 PATFETCH (c);
2801 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2802 break;
2803
2804 case 'c':
2805 laststart = b;
2806 PATFETCH_RAW (c);
2807 BUF_PUSH_2 (categoryspec, c);
2808 break;
2809
2810 case 'C':
2811 laststart = b;
2812 PATFETCH_RAW (c);
2813 BUF_PUSH_2 (notcategoryspec, c);
2814 break;
2815 #endif /* emacs */
2816
2817
2818 case 'w':
2819 laststart = b;
2820 BUF_PUSH (wordchar);
2821 break;
2822
2823
2824 case 'W':
2825 laststart = b;
2826 BUF_PUSH (notwordchar);
2827 break;
2828
2829
2830 case '<':
2831 BUF_PUSH (wordbeg);
2832 break;
2833
2834 case '>':
2835 BUF_PUSH (wordend);
2836 break;
2837
2838 case 'b':
2839 BUF_PUSH (wordbound);
2840 break;
2841
2842 case 'B':
2843 BUF_PUSH (notwordbound);
2844 break;
2845
2846 case '`':
2847 BUF_PUSH (begbuf);
2848 break;
2849
2850 case '\'':
2851 BUF_PUSH (endbuf);
2852 break;
2853
2854 case '1': case '2': case '3': case '4': case '5':
2855 case '6': case '7': case '8': case '9':
2856 if (syntax & RE_NO_BK_REFS)
2857 goto normal_char;
2858
2859 c1 = c - '0';
2860
2861 if (c1 > regnum)
2862 FREE_STACK_RETURN (REG_ESUBREG);
2863
2864 /* Can't back reference to a subexpression if inside of it. */
2865 if (group_in_compile_stack (compile_stack, c1))
2866 goto normal_char;
2867
2868 laststart = b;
2869 BUF_PUSH_2 (duplicate, c1);
2870 break;
2871
2872
2873 case '+':
2874 case '?':
2875 if (syntax & RE_BK_PLUS_QM)
2876 goto handle_plus;
2877 else
2878 goto normal_backslash;
2879
2880 default:
2881 normal_backslash:
2882 /* You might think it would be useful for \ to mean
2883 not to translate; but if we don't translate it
2884 it will never match anything. */
2885 c = TRANSLATE (c);
2886 goto normal_char;
2887 }
2888 break;
2889
2890
2891 default:
2892 /* Expects the character in `c'. */
2893 normal_char:
2894 p1 = p - 1; /* P1 points the head of C. */
2895 #ifdef emacs
2896 if (bufp->multibyte)
2897 /* Set P to the next character boundary. */
2898 p += MULTIBYTE_FORM_LENGTH (p1, pend - p1) - 1;
2899 #endif
2900 /* If no exactn currently being built. */
2901 if (!pending_exact
2902
2903 /* If last exactn not at current position. */
2904 || pending_exact + *pending_exact + 1 != b
2905
2906 /* We have only one byte following the exactn for the count. */
2907 || *pending_exact >= (1 << BYTEWIDTH) - (p - p1)
2908
2909 /* If followed by a repetition operator. */
2910 || (p != pend && (*p == '*' || *p == '^'))
2911 || ((syntax & RE_BK_PLUS_QM)
2912 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
2913 : p != pend && (*p == '+' || *p == '?'))
2914 || ((syntax & RE_INTERVALS)
2915 && ((syntax & RE_NO_BK_BRACES)
2916 ? p != pend && *p == '{'
2917 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
2918 {
2919 /* Start building a new exactn. */
2920
2921 laststart = b;
2922
2923 BUF_PUSH_2 (exactn, 0);
2924 pending_exact = b - 1;
2925 }
2926
2927 /* Here, C may translated, therefore C may not equal to *P1. */
2928 while (1)
2929 {
2930 BUF_PUSH (c);
2931 (*pending_exact)++;
2932 if (++p1 == p)
2933 break;
2934
2935 /* Rest of multibyte form should be copied literally. */
2936 c = *(unsigned char *)p1;
2937 }
2938 break;
2939 } /* switch (c) */
2940 } /* while p != pend */
2941
2942
2943 /* Through the pattern now. */
2944
2945 if (fixup_alt_jump)
2946 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2947
2948 if (!COMPILE_STACK_EMPTY)
2949 FREE_STACK_RETURN (REG_EPAREN);
2950
2951 /* If we don't want backtracking, force success
2952 the first time we reach the end of the compiled pattern. */
2953 if (syntax & RE_NO_POSIX_BACKTRACKING)
2954 BUF_PUSH (succeed);
2955
2956 free (compile_stack.stack);
2957
2958 /* We have succeeded; set the length of the buffer. */
2959 bufp->used = b - bufp->buffer;
2960
2961 #ifdef DEBUG
2962 if (debug)
2963 {
2964 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2965 print_compiled_pattern (bufp);
2966 }
2967 #endif /* DEBUG */
2968
2969 #ifndef MATCH_MAY_ALLOCATE
2970 /* Initialize the failure stack to the largest possible stack. This
2971 isn't necessary unless we're trying to avoid calling alloca in
2972 the search and match routines. */
2973 {
2974 int num_regs = bufp->re_nsub + 1;
2975
2976 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
2977 {
2978 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
2979
2980 #ifdef emacs
2981 if (! fail_stack.stack)
2982 fail_stack.stack
2983 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2984 * sizeof (fail_stack_elt_t));
2985 else
2986 fail_stack.stack
2987 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2988 (fail_stack.size
2989 * sizeof (fail_stack_elt_t)));
2990 #else /* not emacs */
2991 if (! fail_stack.stack)
2992 fail_stack.stack
2993 = (fail_stack_elt_t *) malloc (fail_stack.size
2994 * sizeof (fail_stack_elt_t));
2995 else
2996 fail_stack.stack
2997 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2998 (fail_stack.size
2999 * sizeof (fail_stack_elt_t)));
3000 #endif /* not emacs */
3001 }
3002
3003 regex_grow_registers (num_regs);
3004 }
3005 #endif /* not MATCH_MAY_ALLOCATE */
3006
3007 return REG_NOERROR;
3008 } /* regex_compile */
3009 \f
3010 /* Subroutines for `regex_compile'. */
3011
3012 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3013
3014 static void
3015 store_op1 (op, loc, arg)
3016 re_opcode_t op;
3017 unsigned char *loc;
3018 int arg;
3019 {
3020 *loc = (unsigned char) op;
3021 STORE_NUMBER (loc + 1, arg);
3022 }
3023
3024
3025 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3026
3027 static void
3028 store_op2 (op, loc, arg1, arg2)
3029 re_opcode_t op;
3030 unsigned char *loc;
3031 int arg1, arg2;
3032 {
3033 *loc = (unsigned char) op;
3034 STORE_NUMBER (loc + 1, arg1);
3035 STORE_NUMBER (loc + 3, arg2);
3036 }
3037
3038
3039 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3040 for OP followed by two-byte integer parameter ARG. */
3041
3042 static void
3043 insert_op1 (op, loc, arg, end)
3044 re_opcode_t op;
3045 unsigned char *loc;
3046 int arg;
3047 unsigned char *end;
3048 {
3049 register unsigned char *pfrom = end;
3050 register unsigned char *pto = end + 3;
3051
3052 while (pfrom != loc)
3053 *--pto = *--pfrom;
3054
3055 store_op1 (op, loc, arg);
3056 }
3057
3058
3059 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3060
3061 static void
3062 insert_op2 (op, loc, arg1, arg2, end)
3063 re_opcode_t op;
3064 unsigned char *loc;
3065 int arg1, arg2;
3066 unsigned char *end;
3067 {
3068 register unsigned char *pfrom = end;
3069 register unsigned char *pto = end + 5;
3070
3071 while (pfrom != loc)
3072 *--pto = *--pfrom;
3073
3074 store_op2 (op, loc, arg1, arg2);
3075 }
3076
3077
3078 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3079 after an alternative or a begin-subexpression. We assume there is at
3080 least one character before the ^. */
3081
3082 static boolean
3083 at_begline_loc_p (pattern, p, syntax)
3084 const char *pattern, *p;
3085 reg_syntax_t syntax;
3086 {
3087 const char *prev = p - 2;
3088 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3089
3090 return
3091 /* After a subexpression? */
3092 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3093 /* After an alternative? */
3094 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3095 }
3096
3097
3098 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3099 at least one character after the $, i.e., `P < PEND'. */
3100
3101 static boolean
3102 at_endline_loc_p (p, pend, syntax)
3103 const char *p, *pend;
3104 int syntax;
3105 {
3106 const char *next = p;
3107 boolean next_backslash = *next == '\\';
3108 const char *next_next = p + 1 < pend ? p + 1 : 0;
3109
3110 return
3111 /* Before a subexpression? */
3112 (syntax & RE_NO_BK_PARENS ? *next == ')'
3113 : next_backslash && next_next && *next_next == ')')
3114 /* Before an alternative? */
3115 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3116 : next_backslash && next_next && *next_next == '|');
3117 }
3118
3119
3120 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3121 false if it's not. */
3122
3123 static boolean
3124 group_in_compile_stack (compile_stack, regnum)
3125 compile_stack_type compile_stack;
3126 regnum_t regnum;
3127 {
3128 int this_element;
3129
3130 for (this_element = compile_stack.avail - 1;
3131 this_element >= 0;
3132 this_element--)
3133 if (compile_stack.stack[this_element].regnum == regnum)
3134 return true;
3135
3136 return false;
3137 }
3138 \f
3139 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3140 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3141 characters can start a string that matches the pattern. This fastmap
3142 is used by re_search to skip quickly over impossible starting points.
3143
3144 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3145 area as BUFP->fastmap.
3146
3147 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3148 the pattern buffer.
3149
3150 Returns 0 if we succeed, -2 if an internal error. */
3151
3152 int
3153 re_compile_fastmap (bufp)
3154 struct re_pattern_buffer *bufp;
3155 {
3156 int i, j, k;
3157 #ifdef MATCH_MAY_ALLOCATE
3158 fail_stack_type fail_stack;
3159 #endif
3160 #ifndef REGEX_MALLOC
3161 char *destination;
3162 #endif
3163 /* We don't push any register information onto the failure stack. */
3164 unsigned num_regs = 0;
3165
3166 register char *fastmap = bufp->fastmap;
3167 unsigned char *pattern = bufp->buffer;
3168 unsigned long size = bufp->used;
3169 unsigned char *p = pattern;
3170 register unsigned char *pend = pattern + size;
3171
3172 /* This holds the pointer to the failure stack, when
3173 it is allocated relocatably. */
3174 fail_stack_elt_t *failure_stack_ptr;
3175
3176 /* Assume that each path through the pattern can be null until
3177 proven otherwise. We set this false at the bottom of switch
3178 statement, to which we get only if a particular path doesn't
3179 match the empty string. */
3180 boolean path_can_be_null = true;
3181
3182 /* We aren't doing a `succeed_n' to begin with. */
3183 boolean succeed_n_p = false;
3184
3185 /* If all elements for base leading-codes in fastmap is set, this
3186 flag is set true. */
3187 boolean match_any_multibyte_characters = false;
3188
3189 /* Maximum code of simple (single byte) character. */
3190 int simple_char_max;
3191
3192 assert (fastmap != NULL && p != NULL);
3193
3194 INIT_FAIL_STACK ();
3195 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3196 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3197 bufp->can_be_null = 0;
3198
3199 while (1)
3200 {
3201 if (p == pend || *p == succeed)
3202 {
3203 /* We have reached the (effective) end of pattern. */
3204 if (!FAIL_STACK_EMPTY ())
3205 {
3206 bufp->can_be_null |= path_can_be_null;
3207
3208 /* Reset for next path. */
3209 path_can_be_null = true;
3210
3211 p = fail_stack.stack[--fail_stack.avail].pointer;
3212
3213 continue;
3214 }
3215 else
3216 break;
3217 }
3218
3219 /* We should never be about to go beyond the end of the pattern. */
3220 assert (p < pend);
3221
3222 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3223 {
3224
3225 /* I guess the idea here is to simply not bother with a fastmap
3226 if a backreference is used, since it's too hard to figure out
3227 the fastmap for the corresponding group. Setting
3228 `can_be_null' stops `re_search_2' from using the fastmap, so
3229 that is all we do. */
3230 case duplicate:
3231 bufp->can_be_null = 1;
3232 goto done;
3233
3234
3235 /* Following are the cases which match a character. These end
3236 with `break'. */
3237
3238 case exactn:
3239 fastmap[p[1]] = 1;
3240 break;
3241
3242
3243 #ifndef emacs
3244 case charset:
3245 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3246 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3247 fastmap[j] = 1;
3248 break;
3249
3250
3251 case charset_not:
3252 /* Chars beyond end of map must be allowed. */
3253 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3254 fastmap[j] = 1;
3255
3256 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3257 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3258 fastmap[j] = 1;
3259 break;
3260
3261
3262 case wordchar:
3263 for (j = 0; j < (1 << BYTEWIDTH); j++)
3264 if (SYNTAX (j) == Sword)
3265 fastmap[j] = 1;
3266 break;
3267
3268
3269 case notwordchar:
3270 for (j = 0; j < (1 << BYTEWIDTH); j++)
3271 if (SYNTAX (j) != Sword)
3272 fastmap[j] = 1;
3273 break;
3274 #else /* emacs */
3275 case charset:
3276 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3277 j >= 0; j--)
3278 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3279 fastmap[j] = 1;
3280
3281 if (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3282 && match_any_multibyte_characters == false)
3283 {
3284 /* Set fastmap[I] 1 where I is a base leading code of each
3285 multibyte character in the range table. */
3286 int c, count;
3287
3288 /* Make P points the range table. */
3289 p += CHARSET_BITMAP_SIZE (&p[-2]);
3290
3291 /* Extract the number of ranges in range table into
3292 COUNT. */
3293 EXTRACT_NUMBER_AND_INCR (count, p);
3294 for (; count > 0; count--, p += 2 * 3) /* XXX */
3295 {
3296 /* Extract the start of each range. */
3297 EXTRACT_CHARACTER (c, p);
3298 j = CHAR_CHARSET (c);
3299 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3300 }
3301 }
3302 break;
3303
3304
3305 case charset_not:
3306 /* Chars beyond end of map must be allowed. End of map is
3307 `127' if bufp->multibyte is nonzero. */
3308 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3309 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3310 j < simple_char_max; j++)
3311 fastmap[j] = 1;
3312
3313 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3314 j >= 0; j--)
3315 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3316 fastmap[j] = 1;
3317
3318 if (bufp->multibyte)
3319 /* Any character set can possibly contain a character
3320 which doesn't match the specified set of characters. */
3321 {
3322 set_fastmap_for_multibyte_characters:
3323 if (match_any_multibyte_characters == false)
3324 {
3325 for (j = 0x80; j < 0xA0; j++) /* XXX */
3326 if (BASE_LEADING_CODE_P (j))
3327 fastmap[j] = 1;
3328 match_any_multibyte_characters = true;
3329 }
3330 }
3331 break;
3332
3333
3334 case wordchar:
3335 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3336 for (j = 0; j < simple_char_max; j++)
3337 if (SYNTAX (j) == Sword)
3338 fastmap[j] = 1;
3339
3340 if (bufp->multibyte)
3341 /* Any character set can possibly contain a character
3342 whose syntax is `Sword'. */
3343 goto set_fastmap_for_multibyte_characters;
3344 break;
3345
3346
3347 case notwordchar:
3348 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3349 for (j = 0; j < simple_char_max; j++)
3350 if (SYNTAX (j) != Sword)
3351 fastmap[j] = 1;
3352
3353 if (bufp->multibyte)
3354 /* Any character set can possibly contain a character
3355 whose syntax is not `Sword'. */
3356 goto set_fastmap_for_multibyte_characters;
3357 break;
3358 #endif
3359
3360 case anychar:
3361 {
3362 int fastmap_newline = fastmap['\n'];
3363
3364 /* `.' matches anything (but if bufp->multibyte is
3365 nonzero, matches `\000' .. `\127' and possible multibyte
3366 character) ... */
3367 if (bufp->multibyte)
3368 {
3369 simple_char_max = 0x80;
3370
3371 for (j = 0x80; j < 0xA0; j++)
3372 if (BASE_LEADING_CODE_P (j))
3373 fastmap[j] = 1;
3374 match_any_multibyte_characters = true;
3375 }
3376 else
3377 simple_char_max = (1 << BYTEWIDTH);
3378
3379 for (j = 0; j < simple_char_max; j++)
3380 fastmap[j] = 1;
3381
3382 /* ... except perhaps newline. */
3383 if (!(bufp->syntax & RE_DOT_NEWLINE))
3384 fastmap['\n'] = fastmap_newline;
3385
3386 /* Return if we have already set `can_be_null'; if we have,
3387 then the fastmap is irrelevant. Something's wrong here. */
3388 else if (bufp->can_be_null)
3389 goto done;
3390
3391 /* Otherwise, have to check alternative paths. */
3392 break;
3393 }
3394
3395 #ifdef emacs
3396 case wordbound:
3397 case notwordbound:
3398 case wordbeg:
3399 case wordend:
3400 case notsyntaxspec:
3401 case syntaxspec:
3402 /* This match depends on text properties. These end with
3403 aborting optimizations. */
3404 bufp->can_be_null = 1;
3405 goto done;
3406 #if 0
3407 k = *p++;
3408 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3409 for (j = 0; j < simple_char_max; j++)
3410 if (SYNTAX (j) == (enum syntaxcode) k)
3411 fastmap[j] = 1;
3412
3413 if (bufp->multibyte)
3414 /* Any character set can possibly contain a character
3415 whose syntax is K. */
3416 goto set_fastmap_for_multibyte_characters;
3417 break;
3418
3419 case notsyntaxspec:
3420 k = *p++;
3421 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3422 for (j = 0; j < simple_char_max; j++)
3423 if (SYNTAX (j) != (enum syntaxcode) k)
3424 fastmap[j] = 1;
3425
3426 if (bufp->multibyte)
3427 /* Any character set can possibly contain a character
3428 whose syntax is not K. */
3429 goto set_fastmap_for_multibyte_characters;
3430 break;
3431 #endif
3432
3433
3434 case categoryspec:
3435 k = *p++;
3436 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3437 for (j = 0; j < simple_char_max; j++)
3438 if (CHAR_HAS_CATEGORY (j, k))
3439 fastmap[j] = 1;
3440
3441 if (bufp->multibyte)
3442 /* Any character set can possibly contain a character
3443 whose category is K. */
3444 goto set_fastmap_for_multibyte_characters;
3445 break;
3446
3447
3448 case notcategoryspec:
3449 k = *p++;
3450 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3451 for (j = 0; j < simple_char_max; j++)
3452 if (!CHAR_HAS_CATEGORY (j, k))
3453 fastmap[j] = 1;
3454
3455 if (bufp->multibyte)
3456 /* Any character set can possibly contain a character
3457 whose category is not K. */
3458 goto set_fastmap_for_multibyte_characters;
3459 break;
3460
3461 /* All cases after this match the empty string. These end with
3462 `continue'. */
3463
3464
3465 case before_dot:
3466 case at_dot:
3467 case after_dot:
3468 continue;
3469 #endif /* emacs */
3470
3471
3472 case no_op:
3473 case begline:
3474 case endline:
3475 case begbuf:
3476 case endbuf:
3477 #ifndef emacs
3478 case wordbound:
3479 case notwordbound:
3480 case wordbeg:
3481 case wordend:
3482 #endif
3483 case push_dummy_failure:
3484 continue;
3485
3486
3487 case jump_n:
3488 case pop_failure_jump:
3489 case maybe_pop_jump:
3490 case jump:
3491 case jump_past_alt:
3492 case dummy_failure_jump:
3493 EXTRACT_NUMBER_AND_INCR (j, p);
3494 p += j;
3495 if (j > 0)
3496 continue;
3497
3498 /* Jump backward implies we just went through the body of a
3499 loop and matched nothing. Opcode jumped to should be
3500 `on_failure_jump' or `succeed_n'. Just treat it like an
3501 ordinary jump. For a * loop, it has pushed its failure
3502 point already; if so, discard that as redundant. */
3503 if ((re_opcode_t) *p != on_failure_jump
3504 && (re_opcode_t) *p != succeed_n)
3505 continue;
3506
3507 p++;
3508 EXTRACT_NUMBER_AND_INCR (j, p);
3509 p += j;
3510
3511 /* If what's on the stack is where we are now, pop it. */
3512 if (!FAIL_STACK_EMPTY ()
3513 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3514 fail_stack.avail--;
3515
3516 continue;
3517
3518
3519 case on_failure_jump:
3520 case on_failure_keep_string_jump:
3521 handle_on_failure_jump:
3522 EXTRACT_NUMBER_AND_INCR (j, p);
3523
3524 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3525 end of the pattern. We don't want to push such a point,
3526 since when we restore it above, entering the switch will
3527 increment `p' past the end of the pattern. We don't need
3528 to push such a point since we obviously won't find any more
3529 fastmap entries beyond `pend'. Such a pattern can match
3530 the null string, though. */
3531 if (p + j < pend)
3532 {
3533 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3534 {
3535 RESET_FAIL_STACK ();
3536 return -2;
3537 }
3538 }
3539 else
3540 bufp->can_be_null = 1;
3541
3542 if (succeed_n_p)
3543 {
3544 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3545 succeed_n_p = false;
3546 }
3547
3548 continue;
3549
3550
3551 case succeed_n:
3552 /* Get to the number of times to succeed. */
3553 p += 2;
3554
3555 /* Increment p past the n for when k != 0. */
3556 EXTRACT_NUMBER_AND_INCR (k, p);
3557 if (k == 0)
3558 {
3559 p -= 4;
3560 succeed_n_p = true; /* Spaghetti code alert. */
3561 goto handle_on_failure_jump;
3562 }
3563 continue;
3564
3565
3566 case set_number_at:
3567 p += 4;
3568 continue;
3569
3570
3571 case start_memory:
3572 case stop_memory:
3573 p += 2;
3574 continue;
3575
3576
3577 default:
3578 abort (); /* We have listed all the cases. */
3579 } /* switch *p++ */
3580
3581 /* Getting here means we have found the possible starting
3582 characters for one path of the pattern -- and that the empty
3583 string does not match. We need not follow this path further.
3584 Instead, look at the next alternative (remembered on the
3585 stack), or quit if no more. The test at the top of the loop
3586 does these things. */
3587 path_can_be_null = false;
3588 p = pend;
3589 } /* while p */
3590
3591 /* Set `can_be_null' for the last path (also the first path, if the
3592 pattern is empty). */
3593 bufp->can_be_null |= path_can_be_null;
3594
3595 done:
3596 RESET_FAIL_STACK ();
3597 return 0;
3598 } /* re_compile_fastmap */
3599 \f
3600 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3601 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3602 this memory for recording register information. STARTS and ENDS
3603 must be allocated using the malloc library routine, and must each
3604 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3605
3606 If NUM_REGS == 0, then subsequent matches should allocate their own
3607 register data.
3608
3609 Unless this function is called, the first search or match using
3610 PATTERN_BUFFER will allocate its own register data, without
3611 freeing the old data. */
3612
3613 void
3614 re_set_registers (bufp, regs, num_regs, starts, ends)
3615 struct re_pattern_buffer *bufp;
3616 struct re_registers *regs;
3617 unsigned num_regs;
3618 regoff_t *starts, *ends;
3619 {
3620 if (num_regs)
3621 {
3622 bufp->regs_allocated = REGS_REALLOCATE;
3623 regs->num_regs = num_regs;
3624 regs->start = starts;
3625 regs->end = ends;
3626 }
3627 else
3628 {
3629 bufp->regs_allocated = REGS_UNALLOCATED;
3630 regs->num_regs = 0;
3631 regs->start = regs->end = (regoff_t *) 0;
3632 }
3633 }
3634 \f
3635 /* Searching routines. */
3636
3637 /* Like re_search_2, below, but only one string is specified, and
3638 doesn't let you say where to stop matching. */
3639
3640 int
3641 re_search (bufp, string, size, startpos, range, regs)
3642 struct re_pattern_buffer *bufp;
3643 const char *string;
3644 int size, startpos, range;
3645 struct re_registers *regs;
3646 {
3647 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3648 regs, size);
3649 }
3650
3651 /* End address of virtual concatenation of string. */
3652 #define STOP_ADDR_VSTRING(P) \
3653 (((P) >= size1 ? string2 + size2 : string1 + size1))
3654
3655 /* Address of POS in the concatenation of virtual string. */
3656 #define POS_ADDR_VSTRING(POS) \
3657 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3658
3659 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3660 virtual concatenation of STRING1 and STRING2, starting first at index
3661 STARTPOS, then at STARTPOS + 1, and so on.
3662
3663 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3664
3665 RANGE is how far to scan while trying to match. RANGE = 0 means try
3666 only at STARTPOS; in general, the last start tried is STARTPOS +
3667 RANGE.
3668
3669 In REGS, return the indices of the virtual concatenation of STRING1
3670 and STRING2 that matched the entire BUFP->buffer and its contained
3671 subexpressions.
3672
3673 Do not consider matching one past the index STOP in the virtual
3674 concatenation of STRING1 and STRING2.
3675
3676 We return either the position in the strings at which the match was
3677 found, -1 if no match, or -2 if error (such as failure
3678 stack overflow). */
3679
3680 int
3681 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3682 struct re_pattern_buffer *bufp;
3683 const char *string1, *string2;
3684 int size1, size2;
3685 int startpos;
3686 int range;
3687 struct re_registers *regs;
3688 int stop;
3689 {
3690 int val;
3691 register char *fastmap = bufp->fastmap;
3692 register RE_TRANSLATE_TYPE translate = bufp->translate;
3693 int total_size = size1 + size2;
3694 int endpos = startpos + range;
3695 int anchored_start = 0;
3696
3697 /* Nonzero if we have to concern multibyte character. */
3698 int multibyte = bufp->multibyte;
3699
3700 /* Check for out-of-range STARTPOS. */
3701 if (startpos < 0 || startpos > total_size)
3702 return -1;
3703
3704 /* Fix up RANGE if it might eventually take us outside
3705 the virtual concatenation of STRING1 and STRING2.
3706 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3707 if (endpos < 0)
3708 range = 0 - startpos;
3709 else if (endpos > total_size)
3710 range = total_size - startpos;
3711
3712 /* If the search isn't to be a backwards one, don't waste time in a
3713 search for a pattern anchored at beginning of buffer. */
3714 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3715 {
3716 if (startpos > 0)
3717 return -1;
3718 else
3719 range = 0;
3720 }
3721
3722 #ifdef emacs
3723 /* In a forward search for something that starts with \=.
3724 don't keep searching past point. */
3725 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3726 {
3727 range = PT_BYTE - BEGV_BYTE - startpos;
3728 if (range < 0)
3729 return -1;
3730 }
3731 #endif /* emacs */
3732
3733 /* Update the fastmap now if not correct already. */
3734 if (fastmap && !bufp->fastmap_accurate)
3735 if (re_compile_fastmap (bufp) == -2)
3736 return -2;
3737
3738 /* See whether the pattern is anchored. */
3739 if (bufp->buffer[0] == begline)
3740 anchored_start = 1;
3741
3742 #ifdef emacs
3743 gl_state.object = re_match_object;
3744 {
3745 int charpos
3746 = SYNTAX_TABLE_BYTE_TO_CHAR (startpos > 0 ? startpos : startpos + 1);
3747
3748 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
3749 }
3750 #endif
3751
3752 /* Loop through the string, looking for a place to start matching. */
3753 for (;;)
3754 {
3755 /* If the pattern is anchored,
3756 skip quickly past places we cannot match.
3757 We don't bother to treat startpos == 0 specially
3758 because that case doesn't repeat. */
3759 if (anchored_start && startpos > 0)
3760 {
3761 if (! (bufp->newline_anchor
3762 && ((startpos <= size1 ? string1[startpos - 1]
3763 : string2[startpos - size1 - 1])
3764 == '\n')))
3765 goto advance;
3766 }
3767
3768 /* If a fastmap is supplied, skip quickly over characters that
3769 cannot be the start of a match. If the pattern can match the
3770 null string, however, we don't need to skip characters; we want
3771 the first null string. */
3772 if (fastmap && startpos < total_size && !bufp->can_be_null)
3773 {
3774 register const char *d;
3775 register unsigned int buf_ch;
3776
3777 d = POS_ADDR_VSTRING (startpos);
3778
3779 if (range > 0) /* Searching forwards. */
3780 {
3781 register int lim = 0;
3782 int irange = range;
3783
3784 if (startpos < size1 && startpos + range >= size1)
3785 lim = range - (size1 - startpos);
3786
3787 /* Written out as an if-else to avoid testing `translate'
3788 inside the loop. */
3789 if (RE_TRANSLATE_P (translate))
3790 {
3791 if (multibyte)
3792 while (range > lim)
3793 {
3794 int buf_charlen;
3795
3796 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
3797 buf_charlen);
3798
3799 buf_ch = RE_TRANSLATE (translate, buf_ch);
3800 if (buf_ch >= 0400
3801 || fastmap[buf_ch])
3802 break;
3803
3804 range -= buf_charlen;
3805 d += buf_charlen;
3806 }
3807 else
3808 while (range > lim
3809 && !fastmap[(unsigned char)
3810 RE_TRANSLATE (translate, (unsigned char) *d)])
3811 {
3812 d++;
3813 range--;
3814 }
3815 }
3816 else
3817 while (range > lim && !fastmap[(unsigned char) *d])
3818 {
3819 d++;
3820 range--;
3821 }
3822
3823 startpos += irange - range;
3824 }
3825 else /* Searching backwards. */
3826 {
3827 int room = (size1 == 0 || startpos >= size1
3828 ? size2 + size1 - startpos
3829 : size1 - startpos);
3830
3831 buf_ch = STRING_CHAR (d, room);
3832 if (RE_TRANSLATE_P (translate))
3833 buf_ch = RE_TRANSLATE (translate, buf_ch);
3834
3835 if (! (buf_ch >= 0400
3836 || fastmap[buf_ch]))
3837 goto advance;
3838 }
3839 }
3840
3841 /* If can't match the null string, and that's all we have left, fail. */
3842 if (range >= 0 && startpos == total_size && fastmap
3843 && !bufp->can_be_null)
3844 return -1;
3845
3846 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3847 startpos, regs, stop);
3848 #ifndef REGEX_MALLOC
3849 #ifdef C_ALLOCA
3850 alloca (0);
3851 #endif
3852 #endif
3853
3854 if (val >= 0)
3855 return startpos;
3856
3857 if (val == -2)
3858 return -2;
3859
3860 advance:
3861 if (!range)
3862 break;
3863 else if (range > 0)
3864 {
3865 /* Update STARTPOS to the next character boundary. */
3866 if (multibyte)
3867 {
3868 const unsigned char *p
3869 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3870 const unsigned char *pend
3871 = (const unsigned char *) STOP_ADDR_VSTRING (startpos);
3872 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
3873
3874 range -= len;
3875 if (range < 0)
3876 break;
3877 startpos += len;
3878 }
3879 else
3880 {
3881 range--;
3882 startpos++;
3883 }
3884 }
3885 else
3886 {
3887 range++;
3888 startpos--;
3889
3890 /* Update STARTPOS to the previous character boundary. */
3891 if (multibyte)
3892 {
3893 const unsigned char *p
3894 = (const unsigned char *) POS_ADDR_VSTRING (startpos);
3895 int len = 0;
3896
3897 /* Find the head of multibyte form. */
3898 while (!CHAR_HEAD_P (*p))
3899 p--, len++;
3900
3901 /* Adjust it. */
3902 #if 0 /* XXX */
3903 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
3904 ;
3905 else
3906 #endif
3907 {
3908 range += len;
3909 if (range > 0)
3910 break;
3911
3912 startpos -= len;
3913 }
3914 }
3915 }
3916 }
3917 return -1;
3918 } /* re_search_2 */
3919 \f
3920 /* Declarations and macros for re_match_2. */
3921
3922 static int bcmp_translate ();
3923 static boolean alt_match_null_string_p (),
3924 common_op_match_null_string_p (),
3925 group_match_null_string_p ();
3926
3927 /* This converts PTR, a pointer into one of the search strings `string1'
3928 and `string2' into an offset from the beginning of that string. */
3929 #define POINTER_TO_OFFSET(ptr) \
3930 (FIRST_STRING_P (ptr) \
3931 ? ((regoff_t) ((ptr) - string1)) \
3932 : ((regoff_t) ((ptr) - string2 + size1)))
3933
3934 /* Macros for dealing with the split strings in re_match_2. */
3935
3936 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3937
3938 /* Call before fetching a character with *d. This switches over to
3939 string2 if necessary. */
3940 #define PREFETCH() \
3941 while (d == dend) \
3942 { \
3943 /* End of string2 => fail. */ \
3944 if (dend == end_match_2) \
3945 goto fail; \
3946 /* End of string1 => advance to string2. */ \
3947 d = string2; \
3948 dend = end_match_2; \
3949 }
3950
3951
3952 /* Test if at very beginning or at very end of the virtual concatenation
3953 of `string1' and `string2'. If only one string, it's `string2'. */
3954 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3955 #define AT_STRINGS_END(d) ((d) == end2)
3956
3957
3958 /* Test if D points to a character which is word-constituent. We have
3959 two special cases to check for: if past the end of string1, look at
3960 the first character in string2; and if before the beginning of
3961 string2, look at the last character in string1. */
3962 #define WORDCHAR_P(d) \
3963 (SYNTAX ((d) == end1 ? *string2 \
3964 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3965 == Sword)
3966
3967 /* Disabled due to a compiler bug -- see comment at case wordbound */
3968
3969 /* The comment at case wordbound is following one, but we don't use
3970 AT_WORD_BOUNDARY anymore to support multibyte form.
3971
3972 The DEC Alpha C compiler 3.x generates incorrect code for the
3973 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
3974 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
3975 macro and introducing temporary variables works around the bug. */
3976
3977 #if 0
3978 /* Test if the character before D and the one at D differ with respect
3979 to being word-constituent. */
3980 #define AT_WORD_BOUNDARY(d) \
3981 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3982 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3983 #endif
3984
3985 /* Free everything we malloc. */
3986 #ifdef MATCH_MAY_ALLOCATE
3987 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
3988 #define FREE_VARIABLES() \
3989 do { \
3990 REGEX_FREE_STACK (fail_stack.stack); \
3991 FREE_VAR (regstart); \
3992 FREE_VAR (regend); \
3993 FREE_VAR (old_regstart); \
3994 FREE_VAR (old_regend); \
3995 FREE_VAR (best_regstart); \
3996 FREE_VAR (best_regend); \
3997 FREE_VAR (reg_info); \
3998 FREE_VAR (reg_dummy); \
3999 FREE_VAR (reg_info_dummy); \
4000 } while (0)
4001 #else
4002 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4003 #endif /* not MATCH_MAY_ALLOCATE */
4004
4005 /* These values must meet several constraints. They must not be valid
4006 register values; since we have a limit of 255 registers (because
4007 we use only one byte in the pattern for the register number), we can
4008 use numbers larger than 255. They must differ by 1, because of
4009 NUM_FAILURE_ITEMS above. And the value for the lowest register must
4010 be larger than the value for the highest register, so we do not try
4011 to actually save any registers when none are active. */
4012 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
4013 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
4014 \f
4015 /* Matching routines. */
4016
4017 #ifndef emacs /* Emacs never uses this. */
4018 /* re_match is like re_match_2 except it takes only a single string. */
4019
4020 int
4021 re_match (bufp, string, size, pos, regs)
4022 struct re_pattern_buffer *bufp;
4023 const char *string;
4024 int size, pos;
4025 struct re_registers *regs;
4026 {
4027 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4028 pos, regs, size);
4029 alloca (0);
4030 return result;
4031 }
4032 #endif /* not emacs */
4033
4034 #ifdef emacs
4035 /* In Emacs, this is the string or buffer in which we
4036 are matching. It is used for looking up syntax properties. */
4037 Lisp_Object re_match_object;
4038 #endif
4039
4040 /* re_match_2 matches the compiled pattern in BUFP against the
4041 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4042 and SIZE2, respectively). We start matching at POS, and stop
4043 matching at STOP.
4044
4045 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4046 store offsets for the substring each group matched in REGS. See the
4047 documentation for exactly how many groups we fill.
4048
4049 We return -1 if no match, -2 if an internal error (such as the
4050 failure stack overflowing). Otherwise, we return the length of the
4051 matched substring. */
4052
4053 int
4054 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4055 struct re_pattern_buffer *bufp;
4056 const char *string1, *string2;
4057 int size1, size2;
4058 int pos;
4059 struct re_registers *regs;
4060 int stop;
4061 {
4062 int result;
4063
4064 #ifdef emacs
4065 int charpos;
4066 gl_state.object = re_match_object;
4067 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4068 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4069 #endif
4070
4071 result = re_match_2_internal (bufp, string1, size1, string2, size2,
4072 pos, regs, stop);
4073 alloca (0);
4074 return result;
4075 }
4076
4077 /* This is a separate function so that we can force an alloca cleanup
4078 afterwards. */
4079 static int
4080 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4081 struct re_pattern_buffer *bufp;
4082 const char *string1, *string2;
4083 int size1, size2;
4084 int pos;
4085 struct re_registers *regs;
4086 int stop;
4087 {
4088 /* General temporaries. */
4089 int mcnt;
4090 unsigned char *p1;
4091
4092 /* Just past the end of the corresponding string. */
4093 const char *end1, *end2;
4094
4095 /* Pointers into string1 and string2, just past the last characters in
4096 each to consider matching. */
4097 const char *end_match_1, *end_match_2;
4098
4099 /* Where we are in the data, and the end of the current string. */
4100 const char *d, *dend;
4101
4102 /* Where we are in the pattern, and the end of the pattern. */
4103 unsigned char *p = bufp->buffer;
4104 register unsigned char *pend = p + bufp->used;
4105
4106 /* Mark the opcode just after a start_memory, so we can test for an
4107 empty subpattern when we get to the stop_memory. */
4108 unsigned char *just_past_start_mem = 0;
4109
4110 /* We use this to map every character in the string. */
4111 RE_TRANSLATE_TYPE translate = bufp->translate;
4112
4113 /* Nonzero if we have to concern multibyte character. */
4114 int multibyte = bufp->multibyte;
4115
4116 /* Failure point stack. Each place that can handle a failure further
4117 down the line pushes a failure point on this stack. It consists of
4118 restart, regend, and reg_info for all registers corresponding to
4119 the subexpressions we're currently inside, plus the number of such
4120 registers, and, finally, two char *'s. The first char * is where
4121 to resume scanning the pattern; the second one is where to resume
4122 scanning the strings. If the latter is zero, the failure point is
4123 a ``dummy''; if a failure happens and the failure point is a dummy,
4124 it gets discarded and the next next one is tried. */
4125 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4126 fail_stack_type fail_stack;
4127 #endif
4128 #ifdef DEBUG
4129 static unsigned failure_id = 0;
4130 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4131 #endif
4132
4133 /* This holds the pointer to the failure stack, when
4134 it is allocated relocatably. */
4135 fail_stack_elt_t *failure_stack_ptr;
4136
4137 /* We fill all the registers internally, independent of what we
4138 return, for use in backreferences. The number here includes
4139 an element for register zero. */
4140 unsigned num_regs = bufp->re_nsub + 1;
4141
4142 /* The currently active registers. */
4143 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4144 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4145
4146 /* Information on the contents of registers. These are pointers into
4147 the input strings; they record just what was matched (on this
4148 attempt) by a subexpression part of the pattern, that is, the
4149 regnum-th regstart pointer points to where in the pattern we began
4150 matching and the regnum-th regend points to right after where we
4151 stopped matching the regnum-th subexpression. (The zeroth register
4152 keeps track of what the whole pattern matches.) */
4153 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4154 const char **regstart, **regend;
4155 #endif
4156
4157 /* If a group that's operated upon by a repetition operator fails to
4158 match anything, then the register for its start will need to be
4159 restored because it will have been set to wherever in the string we
4160 are when we last see its open-group operator. Similarly for a
4161 register's end. */
4162 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4163 const char **old_regstart, **old_regend;
4164 #endif
4165
4166 /* The is_active field of reg_info helps us keep track of which (possibly
4167 nested) subexpressions we are currently in. The matched_something
4168 field of reg_info[reg_num] helps us tell whether or not we have
4169 matched any of the pattern so far this time through the reg_num-th
4170 subexpression. These two fields get reset each time through any
4171 loop their register is in. */
4172 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4173 register_info_type *reg_info;
4174 #endif
4175
4176 /* The following record the register info as found in the above
4177 variables when we find a match better than any we've seen before.
4178 This happens as we backtrack through the failure points, which in
4179 turn happens only if we have not yet matched the entire string. */
4180 unsigned best_regs_set = false;
4181 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4182 const char **best_regstart, **best_regend;
4183 #endif
4184
4185 /* Logically, this is `best_regend[0]'. But we don't want to have to
4186 allocate space for that if we're not allocating space for anything
4187 else (see below). Also, we never need info about register 0 for
4188 any of the other register vectors, and it seems rather a kludge to
4189 treat `best_regend' differently than the rest. So we keep track of
4190 the end of the best match so far in a separate variable. We
4191 initialize this to NULL so that when we backtrack the first time
4192 and need to test it, it's not garbage. */
4193 const char *match_end = NULL;
4194
4195 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
4196 int set_regs_matched_done = 0;
4197
4198 /* Used when we pop values we don't care about. */
4199 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4200 const char **reg_dummy;
4201 register_info_type *reg_info_dummy;
4202 #endif
4203
4204 #ifdef DEBUG
4205 /* Counts the total number of registers pushed. */
4206 unsigned num_regs_pushed = 0;
4207 #endif
4208
4209 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4210
4211 INIT_FAIL_STACK ();
4212
4213 #ifdef MATCH_MAY_ALLOCATE
4214 /* Do not bother to initialize all the register variables if there are
4215 no groups in the pattern, as it takes a fair amount of time. If
4216 there are groups, we include space for register 0 (the whole
4217 pattern), even though we never use it, since it simplifies the
4218 array indexing. We should fix this. */
4219 if (bufp->re_nsub)
4220 {
4221 regstart = REGEX_TALLOC (num_regs, const char *);
4222 regend = REGEX_TALLOC (num_regs, const char *);
4223 old_regstart = REGEX_TALLOC (num_regs, const char *);
4224 old_regend = REGEX_TALLOC (num_regs, const char *);
4225 best_regstart = REGEX_TALLOC (num_regs, const char *);
4226 best_regend = REGEX_TALLOC (num_regs, const char *);
4227 reg_info = REGEX_TALLOC (num_regs, register_info_type);
4228 reg_dummy = REGEX_TALLOC (num_regs, const char *);
4229 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
4230
4231 if (!(regstart && regend && old_regstart && old_regend && reg_info
4232 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
4233 {
4234 FREE_VARIABLES ();
4235 return -2;
4236 }
4237 }
4238 else
4239 {
4240 /* We must initialize all our variables to NULL, so that
4241 `FREE_VARIABLES' doesn't try to free them. */
4242 regstart = regend = old_regstart = old_regend = best_regstart
4243 = best_regend = reg_dummy = NULL;
4244 reg_info = reg_info_dummy = (register_info_type *) NULL;
4245 }
4246 #endif /* MATCH_MAY_ALLOCATE */
4247
4248 /* The starting position is bogus. */
4249 if (pos < 0 || pos > size1 + size2)
4250 {
4251 FREE_VARIABLES ();
4252 return -1;
4253 }
4254
4255 /* Initialize subexpression text positions to -1 to mark ones that no
4256 start_memory/stop_memory has been seen for. Also initialize the
4257 register information struct. */
4258 for (mcnt = 1; mcnt < num_regs; mcnt++)
4259 {
4260 regstart[mcnt] = regend[mcnt]
4261 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
4262
4263 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
4264 IS_ACTIVE (reg_info[mcnt]) = 0;
4265 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4266 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
4267 }
4268
4269 /* We move `string1' into `string2' if the latter's empty -- but not if
4270 `string1' is null. */
4271 if (size2 == 0 && string1 != NULL)
4272 {
4273 string2 = string1;
4274 size2 = size1;
4275 string1 = 0;
4276 size1 = 0;
4277 }
4278 end1 = string1 + size1;
4279 end2 = string2 + size2;
4280
4281 /* Compute where to stop matching, within the two strings. */
4282 if (stop <= size1)
4283 {
4284 end_match_1 = string1 + stop;
4285 end_match_2 = string2;
4286 }
4287 else
4288 {
4289 end_match_1 = end1;
4290 end_match_2 = string2 + stop - size1;
4291 }
4292
4293 /* `p' scans through the pattern as `d' scans through the data.
4294 `dend' is the end of the input string that `d' points within. `d'
4295 is advanced into the following input string whenever necessary, but
4296 this happens before fetching; therefore, at the beginning of the
4297 loop, `d' can be pointing at the end of a string, but it cannot
4298 equal `string2'. */
4299 if (size1 > 0 && pos <= size1)
4300 {
4301 d = string1 + pos;
4302 dend = end_match_1;
4303 }
4304 else
4305 {
4306 d = string2 + pos - size1;
4307 dend = end_match_2;
4308 }
4309
4310 DEBUG_PRINT1 ("The compiled pattern is: ");
4311 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4312 DEBUG_PRINT1 ("The string to match is: `");
4313 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4314 DEBUG_PRINT1 ("'\n");
4315
4316 /* This loops over pattern commands. It exits by returning from the
4317 function if the match is complete, or it drops through if the match
4318 fails at this starting point in the input data. */
4319 for (;;)
4320 {
4321 DEBUG_PRINT2 ("\n0x%x: ", p);
4322
4323 if (p == pend)
4324 { /* End of pattern means we might have succeeded. */
4325 DEBUG_PRINT1 ("end of pattern ... ");
4326
4327 /* If we haven't matched the entire string, and we want the
4328 longest match, try backtracking. */
4329 if (d != end_match_2)
4330 {
4331 /* 1 if this match ends in the same string (string1 or string2)
4332 as the best previous match. */
4333 boolean same_str_p = (FIRST_STRING_P (match_end)
4334 == MATCHING_IN_FIRST_STRING);
4335 /* 1 if this match is the best seen so far. */
4336 boolean best_match_p;
4337
4338 /* AIX compiler got confused when this was combined
4339 with the previous declaration. */
4340 if (same_str_p)
4341 best_match_p = d > match_end;
4342 else
4343 best_match_p = !MATCHING_IN_FIRST_STRING;
4344
4345 DEBUG_PRINT1 ("backtracking.\n");
4346
4347 if (!FAIL_STACK_EMPTY ())
4348 { /* More failure points to try. */
4349
4350 /* If exceeds best match so far, save it. */
4351 if (!best_regs_set || best_match_p)
4352 {
4353 best_regs_set = true;
4354 match_end = d;
4355
4356 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4357
4358 for (mcnt = 1; mcnt < num_regs; mcnt++)
4359 {
4360 best_regstart[mcnt] = regstart[mcnt];
4361 best_regend[mcnt] = regend[mcnt];
4362 }
4363 }
4364 goto fail;
4365 }
4366
4367 /* If no failure points, don't restore garbage. And if
4368 last match is real best match, don't restore second
4369 best one. */
4370 else if (best_regs_set && !best_match_p)
4371 {
4372 restore_best_regs:
4373 /* Restore best match. It may happen that `dend ==
4374 end_match_1' while the restored d is in string2.
4375 For example, the pattern `x.*y.*z' against the
4376 strings `x-' and `y-z-', if the two strings are
4377 not consecutive in memory. */
4378 DEBUG_PRINT1 ("Restoring best registers.\n");
4379
4380 d = match_end;
4381 dend = ((d >= string1 && d <= end1)
4382 ? end_match_1 : end_match_2);
4383
4384 for (mcnt = 1; mcnt < num_regs; mcnt++)
4385 {
4386 regstart[mcnt] = best_regstart[mcnt];
4387 regend[mcnt] = best_regend[mcnt];
4388 }
4389 }
4390 } /* d != end_match_2 */
4391
4392 succeed_label:
4393 DEBUG_PRINT1 ("Accepting match.\n");
4394
4395 /* If caller wants register contents data back, do it. */
4396 if (regs && !bufp->no_sub)
4397 {
4398 /* Have the register data arrays been allocated? */
4399 if (bufp->regs_allocated == REGS_UNALLOCATED)
4400 { /* No. So allocate them with malloc. We need one
4401 extra element beyond `num_regs' for the `-1' marker
4402 GNU code uses. */
4403 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4404 regs->start = TALLOC (regs->num_regs, regoff_t);
4405 regs->end = TALLOC (regs->num_regs, regoff_t);
4406 if (regs->start == NULL || regs->end == NULL)
4407 {
4408 FREE_VARIABLES ();
4409 return -2;
4410 }
4411 bufp->regs_allocated = REGS_REALLOCATE;
4412 }
4413 else if (bufp->regs_allocated == REGS_REALLOCATE)
4414 { /* Yes. If we need more elements than were already
4415 allocated, reallocate them. If we need fewer, just
4416 leave it alone. */
4417 if (regs->num_regs < num_regs + 1)
4418 {
4419 regs->num_regs = num_regs + 1;
4420 RETALLOC (regs->start, regs->num_regs, regoff_t);
4421 RETALLOC (regs->end, regs->num_regs, regoff_t);
4422 if (regs->start == NULL || regs->end == NULL)
4423 {
4424 FREE_VARIABLES ();
4425 return -2;
4426 }
4427 }
4428 }
4429 else
4430 {
4431 /* These braces fend off a "empty body in an else-statement"
4432 warning under GCC when assert expands to nothing. */
4433 assert (bufp->regs_allocated == REGS_FIXED);
4434 }
4435
4436 /* Convert the pointer data in `regstart' and `regend' to
4437 indices. Register zero has to be set differently,
4438 since we haven't kept track of any info for it. */
4439 if (regs->num_regs > 0)
4440 {
4441 regs->start[0] = pos;
4442 regs->end[0] = (MATCHING_IN_FIRST_STRING
4443 ? ((regoff_t) (d - string1))
4444 : ((regoff_t) (d - string2 + size1)));
4445 }
4446
4447 /* Go through the first `min (num_regs, regs->num_regs)'
4448 registers, since that is all we initialized. */
4449 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4450 {
4451 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4452 regs->start[mcnt] = regs->end[mcnt] = -1;
4453 else
4454 {
4455 regs->start[mcnt]
4456 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4457 regs->end[mcnt]
4458 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4459 }
4460 }
4461
4462 /* If the regs structure we return has more elements than
4463 were in the pattern, set the extra elements to -1. If
4464 we (re)allocated the registers, this is the case,
4465 because we always allocate enough to have at least one
4466 -1 at the end. */
4467 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4468 regs->start[mcnt] = regs->end[mcnt] = -1;
4469 } /* regs && !bufp->no_sub */
4470
4471 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4472 nfailure_points_pushed, nfailure_points_popped,
4473 nfailure_points_pushed - nfailure_points_popped);
4474 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4475
4476 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
4477 ? string1
4478 : string2 - size1);
4479
4480 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4481
4482 FREE_VARIABLES ();
4483 return mcnt;
4484 }
4485
4486 /* Otherwise match next pattern command. */
4487 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4488 {
4489 /* Ignore these. Used to ignore the n of succeed_n's which
4490 currently have n == 0. */
4491 case no_op:
4492 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4493 break;
4494
4495 case succeed:
4496 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4497 goto succeed_label;
4498
4499 /* Match the next n pattern characters exactly. The following
4500 byte in the pattern defines n, and the n bytes after that
4501 are the characters to match. */
4502 case exactn:
4503 mcnt = *p++;
4504 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4505
4506 /* This is written out as an if-else so we don't waste time
4507 testing `translate' inside the loop. */
4508 if (RE_TRANSLATE_P (translate))
4509 {
4510 #ifdef emacs
4511 if (multibyte)
4512 do
4513 {
4514 int pat_charlen, buf_charlen;
4515 unsigned int pat_ch, buf_ch;
4516
4517 PREFETCH ();
4518 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
4519 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4520
4521 if (RE_TRANSLATE (translate, buf_ch)
4522 != pat_ch)
4523 goto fail;
4524
4525 p += pat_charlen;
4526 d += buf_charlen;
4527 mcnt -= pat_charlen;
4528 }
4529 while (mcnt > 0);
4530 else
4531 #endif /* not emacs */
4532 do
4533 {
4534 PREFETCH ();
4535 if ((unsigned char) RE_TRANSLATE (translate, (unsigned char) *d)
4536 != (unsigned char) *p++)
4537 goto fail;
4538 d++;
4539 }
4540 while (--mcnt);
4541 }
4542 else
4543 {
4544 do
4545 {
4546 PREFETCH ();
4547 if (*d++ != (char) *p++) goto fail;
4548 }
4549 while (--mcnt);
4550 }
4551 SET_REGS_MATCHED ();
4552 break;
4553
4554
4555 /* Match any character except possibly a newline or a null. */
4556 case anychar:
4557 {
4558 int buf_charlen;
4559 unsigned int buf_ch;
4560
4561 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4562
4563 PREFETCH ();
4564
4565 #ifdef emacs
4566 if (multibyte)
4567 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4568 else
4569 #endif /* not emacs */
4570 {
4571 buf_ch = (unsigned char) *d;
4572 buf_charlen = 1;
4573 }
4574
4575 buf_ch = TRANSLATE (buf_ch);
4576
4577 if ((!(bufp->syntax & RE_DOT_NEWLINE)
4578 && buf_ch == '\n')
4579 || ((bufp->syntax & RE_DOT_NOT_NULL)
4580 && buf_ch == '\000'))
4581 goto fail;
4582
4583 SET_REGS_MATCHED ();
4584 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4585 d += buf_charlen;
4586 }
4587 break;
4588
4589
4590 case charset:
4591 case charset_not:
4592 {
4593 register unsigned int c;
4594 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4595 int len;
4596
4597 /* Start of actual range_table, or end of bitmap if there is no
4598 range table. */
4599 unsigned char *range_table;
4600
4601 /* Nonzero if there is range table. */
4602 int range_table_exists;
4603
4604 /* Number of ranges of range table. Not in bytes. */
4605 int count;
4606
4607 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4608
4609 PREFETCH ();
4610 c = (unsigned char) *d;
4611
4612 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
4613 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
4614 if (range_table_exists)
4615 EXTRACT_NUMBER_AND_INCR (count, range_table);
4616 else
4617 count = 0;
4618
4619 if (multibyte && BASE_LEADING_CODE_P (c))
4620 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
4621
4622 if (SINGLE_BYTE_CHAR_P (c))
4623 { /* Lookup bitmap. */
4624 c = TRANSLATE (c); /* The character to match. */
4625 len = 1;
4626
4627 /* Cast to `unsigned' instead of `unsigned char' in
4628 case the bit list is a full 32 bytes long. */
4629 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
4630 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4631 not = !not;
4632 }
4633 else if (range_table_exists)
4634 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
4635
4636 p = CHARSET_RANGE_TABLE_END (range_table, count);
4637
4638 if (!not) goto fail;
4639
4640 SET_REGS_MATCHED ();
4641 d += len;
4642 break;
4643 }
4644
4645
4646 /* The beginning of a group is represented by start_memory.
4647 The arguments are the register number in the next byte, and the
4648 number of groups inner to this one in the next. The text
4649 matched within the group is recorded (in the internal
4650 registers data structure) under the register number. */
4651 case start_memory:
4652 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4653
4654 /* Find out if this group can match the empty string. */
4655 p1 = p; /* To send to group_match_null_string_p. */
4656
4657 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4658 REG_MATCH_NULL_STRING_P (reg_info[*p])
4659 = group_match_null_string_p (&p1, pend, reg_info);
4660
4661 /* Save the position in the string where we were the last time
4662 we were at this open-group operator in case the group is
4663 operated upon by a repetition operator, e.g., with `(a*)*b'
4664 against `ab'; then we want to ignore where we are now in
4665 the string in case this attempt to match fails. */
4666 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4667 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4668 : regstart[*p];
4669 DEBUG_PRINT2 (" old_regstart: %d\n",
4670 POINTER_TO_OFFSET (old_regstart[*p]));
4671
4672 regstart[*p] = d;
4673 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4674
4675 IS_ACTIVE (reg_info[*p]) = 1;
4676 MATCHED_SOMETHING (reg_info[*p]) = 0;
4677
4678 /* Clear this whenever we change the register activity status. */
4679 set_regs_matched_done = 0;
4680
4681 /* This is the new highest active register. */
4682 highest_active_reg = *p;
4683
4684 /* If nothing was active before, this is the new lowest active
4685 register. */
4686 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4687 lowest_active_reg = *p;
4688
4689 /* Move past the register number and inner group count. */
4690 p += 2;
4691 just_past_start_mem = p;
4692
4693 break;
4694
4695
4696 /* The stop_memory opcode represents the end of a group. Its
4697 arguments are the same as start_memory's: the register
4698 number, and the number of inner groups. */
4699 case stop_memory:
4700 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4701
4702 /* We need to save the string position the last time we were at
4703 this close-group operator in case the group is operated
4704 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4705 against `aba'; then we want to ignore where we are now in
4706 the string in case this attempt to match fails. */
4707 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4708 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4709 : regend[*p];
4710 DEBUG_PRINT2 (" old_regend: %d\n",
4711 POINTER_TO_OFFSET (old_regend[*p]));
4712
4713 regend[*p] = d;
4714 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4715
4716 /* This register isn't active anymore. */
4717 IS_ACTIVE (reg_info[*p]) = 0;
4718
4719 /* Clear this whenever we change the register activity status. */
4720 set_regs_matched_done = 0;
4721
4722 /* If this was the only register active, nothing is active
4723 anymore. */
4724 if (lowest_active_reg == highest_active_reg)
4725 {
4726 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4727 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4728 }
4729 else
4730 { /* We must scan for the new highest active register, since
4731 it isn't necessarily one less than now: consider
4732 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4733 new highest active register is 1. */
4734 unsigned char r = *p - 1;
4735 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4736 r--;
4737
4738 /* If we end up at register zero, that means that we saved
4739 the registers as the result of an `on_failure_jump', not
4740 a `start_memory', and we jumped to past the innermost
4741 `stop_memory'. For example, in ((.)*) we save
4742 registers 1 and 2 as a result of the *, but when we pop
4743 back to the second ), we are at the stop_memory 1.
4744 Thus, nothing is active. */
4745 if (r == 0)
4746 {
4747 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4748 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4749 }
4750 else
4751 highest_active_reg = r;
4752 }
4753
4754 /* If just failed to match something this time around with a
4755 group that's operated on by a repetition operator, try to
4756 force exit from the ``loop'', and restore the register
4757 information for this group that we had before trying this
4758 last match. */
4759 if ((!MATCHED_SOMETHING (reg_info[*p])
4760 || just_past_start_mem == p - 1)
4761 && (p + 2) < pend)
4762 {
4763 boolean is_a_jump_n = false;
4764
4765 p1 = p + 2;
4766 mcnt = 0;
4767 switch ((re_opcode_t) *p1++)
4768 {
4769 case jump_n:
4770 is_a_jump_n = true;
4771 case pop_failure_jump:
4772 case maybe_pop_jump:
4773 case jump:
4774 case dummy_failure_jump:
4775 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4776 if (is_a_jump_n)
4777 p1 += 2;
4778 break;
4779
4780 default:
4781 /* do nothing */ ;
4782 }
4783 p1 += mcnt;
4784
4785 /* If the next operation is a jump backwards in the pattern
4786 to an on_failure_jump right before the start_memory
4787 corresponding to this stop_memory, exit from the loop
4788 by forcing a failure after pushing on the stack the
4789 on_failure_jump's jump in the pattern, and d. */
4790 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4791 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4792 {
4793 /* If this group ever matched anything, then restore
4794 what its registers were before trying this last
4795 failed match, e.g., with `(a*)*b' against `ab' for
4796 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4797 against `aba' for regend[3].
4798
4799 Also restore the registers for inner groups for,
4800 e.g., `((a*)(b*))*' against `aba' (register 3 would
4801 otherwise get trashed). */
4802
4803 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4804 {
4805 unsigned r;
4806
4807 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4808
4809 /* Restore this and inner groups' (if any) registers. */
4810 for (r = *p; r < *p + *(p + 1); r++)
4811 {
4812 regstart[r] = old_regstart[r];
4813
4814 /* xx why this test? */
4815 if (old_regend[r] >= regstart[r])
4816 regend[r] = old_regend[r];
4817 }
4818 }
4819 p1++;
4820 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4821 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4822
4823 goto fail;
4824 }
4825 }
4826
4827 /* Move past the register number and the inner group count. */
4828 p += 2;
4829 break;
4830
4831
4832 /* \<digit> has been turned into a `duplicate' command which is
4833 followed by the numeric value of <digit> as the register number. */
4834 case duplicate:
4835 {
4836 register const char *d2, *dend2;
4837 int regno = *p++; /* Get which register to match against. */
4838 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4839
4840 /* Can't back reference a group which we've never matched. */
4841 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4842 goto fail;
4843
4844 /* Where in input to try to start matching. */
4845 d2 = regstart[regno];
4846
4847 /* Where to stop matching; if both the place to start and
4848 the place to stop matching are in the same string, then
4849 set to the place to stop, otherwise, for now have to use
4850 the end of the first string. */
4851
4852 dend2 = ((FIRST_STRING_P (regstart[regno])
4853 == FIRST_STRING_P (regend[regno]))
4854 ? regend[regno] : end_match_1);
4855 for (;;)
4856 {
4857 /* If necessary, advance to next segment in register
4858 contents. */
4859 while (d2 == dend2)
4860 {
4861 if (dend2 == end_match_2) break;
4862 if (dend2 == regend[regno]) break;
4863
4864 /* End of string1 => advance to string2. */
4865 d2 = string2;
4866 dend2 = regend[regno];
4867 }
4868 /* At end of register contents => success */
4869 if (d2 == dend2) break;
4870
4871 /* If necessary, advance to next segment in data. */
4872 PREFETCH ();
4873
4874 /* How many characters left in this segment to match. */
4875 mcnt = dend - d;
4876
4877 /* Want how many consecutive characters we can match in
4878 one shot, so, if necessary, adjust the count. */
4879 if (mcnt > dend2 - d2)
4880 mcnt = dend2 - d2;
4881
4882 /* Compare that many; failure if mismatch, else move
4883 past them. */
4884 if (RE_TRANSLATE_P (translate)
4885 ? bcmp_translate (d, d2, mcnt, translate)
4886 : bcmp (d, d2, mcnt))
4887 goto fail;
4888 d += mcnt, d2 += mcnt;
4889
4890 /* Do this because we've match some characters. */
4891 SET_REGS_MATCHED ();
4892 }
4893 }
4894 break;
4895
4896
4897 /* begline matches the empty string at the beginning of the string
4898 (unless `not_bol' is set in `bufp'), and, if
4899 `newline_anchor' is set, after newlines. */
4900 case begline:
4901 DEBUG_PRINT1 ("EXECUTING begline.\n");
4902
4903 if (AT_STRINGS_BEG (d))
4904 {
4905 if (!bufp->not_bol) break;
4906 }
4907 else if (d[-1] == '\n' && bufp->newline_anchor)
4908 {
4909 break;
4910 }
4911 /* In all other cases, we fail. */
4912 goto fail;
4913
4914
4915 /* endline is the dual of begline. */
4916 case endline:
4917 DEBUG_PRINT1 ("EXECUTING endline.\n");
4918
4919 if (AT_STRINGS_END (d))
4920 {
4921 if (!bufp->not_eol) break;
4922 }
4923
4924 /* We have to ``prefetch'' the next character. */
4925 else if ((d == end1 ? *string2 : *d) == '\n'
4926 && bufp->newline_anchor)
4927 {
4928 break;
4929 }
4930 goto fail;
4931
4932
4933 /* Match at the very beginning of the data. */
4934 case begbuf:
4935 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4936 if (AT_STRINGS_BEG (d))
4937 break;
4938 goto fail;
4939
4940
4941 /* Match at the very end of the data. */
4942 case endbuf:
4943 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4944 if (AT_STRINGS_END (d))
4945 break;
4946 goto fail;
4947
4948
4949 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4950 pushes NULL as the value for the string on the stack. Then
4951 `pop_failure_point' will keep the current value for the
4952 string, instead of restoring it. To see why, consider
4953 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4954 then the . fails against the \n. But the next thing we want
4955 to do is match the \n against the \n; if we restored the
4956 string value, we would be back at the foo.
4957
4958 Because this is used only in specific cases, we don't need to
4959 check all the things that `on_failure_jump' does, to make
4960 sure the right things get saved on the stack. Hence we don't
4961 share its code. The only reason to push anything on the
4962 stack at all is that otherwise we would have to change
4963 `anychar's code to do something besides goto fail in this
4964 case; that seems worse than this. */
4965 case on_failure_keep_string_jump:
4966 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4967
4968 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4969 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4970
4971 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4972 break;
4973
4974
4975 /* Uses of on_failure_jump:
4976
4977 Each alternative starts with an on_failure_jump that points
4978 to the beginning of the next alternative. Each alternative
4979 except the last ends with a jump that in effect jumps past
4980 the rest of the alternatives. (They really jump to the
4981 ending jump of the following alternative, because tensioning
4982 these jumps is a hassle.)
4983
4984 Repeats start with an on_failure_jump that points past both
4985 the repetition text and either the following jump or
4986 pop_failure_jump back to this on_failure_jump. */
4987 case on_failure_jump:
4988 on_failure:
4989 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4990
4991 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4992 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4993
4994 /* If this on_failure_jump comes right before a group (i.e.,
4995 the original * applied to a group), save the information
4996 for that group and all inner ones, so that if we fail back
4997 to this point, the group's information will be correct.
4998 For example, in \(a*\)*\1, we need the preceding group,
4999 and in \(zz\(a*\)b*\)\2, we need the inner group. */
5000
5001 /* We can't use `p' to check ahead because we push
5002 a failure point to `p + mcnt' after we do this. */
5003 p1 = p;
5004
5005 /* We need to skip no_op's before we look for the
5006 start_memory in case this on_failure_jump is happening as
5007 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
5008 against aba. */
5009 while (p1 < pend && (re_opcode_t) *p1 == no_op)
5010 p1++;
5011
5012 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
5013 {
5014 /* We have a new highest active register now. This will
5015 get reset at the start_memory we are about to get to,
5016 but we will have saved all the registers relevant to
5017 this repetition op, as described above. */
5018 highest_active_reg = *(p1 + 1) + *(p1 + 2);
5019 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
5020 lowest_active_reg = *(p1 + 1);
5021 }
5022
5023 DEBUG_PRINT1 (":\n");
5024 PUSH_FAILURE_POINT (p + mcnt, d, -2);
5025 break;
5026
5027
5028 /* A smart repeat ends with `maybe_pop_jump'.
5029 We change it to either `pop_failure_jump' or `jump'. */
5030 case maybe_pop_jump:
5031 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5032 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
5033 {
5034 register unsigned char *p2 = p;
5035
5036 /* Compare the beginning of the repeat with what in the
5037 pattern follows its end. If we can establish that there
5038 is nothing that they would both match, i.e., that we
5039 would have to backtrack because of (as in, e.g., `a*a')
5040 then we can change to pop_failure_jump, because we'll
5041 never have to backtrack.
5042
5043 This is not true in the case of alternatives: in
5044 `(a|ab)*' we do need to backtrack to the `ab' alternative
5045 (e.g., if the string was `ab'). But instead of trying to
5046 detect that here, the alternative has put on a dummy
5047 failure point which is what we will end up popping. */
5048
5049 /* Skip over open/close-group commands.
5050 If what follows this loop is a ...+ construct,
5051 look at what begins its body, since we will have to
5052 match at least one of that. */
5053 while (1)
5054 {
5055 if (p2 + 2 < pend
5056 && ((re_opcode_t) *p2 == stop_memory
5057 || (re_opcode_t) *p2 == start_memory))
5058 p2 += 3;
5059 else if (p2 + 6 < pend
5060 && (re_opcode_t) *p2 == dummy_failure_jump)
5061 p2 += 6;
5062 else
5063 break;
5064 }
5065
5066 p1 = p + mcnt;
5067 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
5068 to the `maybe_finalize_jump' of this case. Examine what
5069 follows. */
5070
5071 /* If we're at the end of the pattern, we can change. */
5072 if (p2 == pend)
5073 {
5074 /* Consider what happens when matching ":\(.*\)"
5075 against ":/". I don't really understand this code
5076 yet. */
5077 p[-3] = (unsigned char) pop_failure_jump;
5078 DEBUG_PRINT1
5079 (" End of pattern: change to `pop_failure_jump'.\n");
5080 }
5081
5082 else if ((re_opcode_t) *p2 == exactn
5083 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
5084 {
5085 register unsigned int c
5086 = *p2 == (unsigned char) endline ? '\n' : p2[2];
5087
5088 if ((re_opcode_t) p1[3] == exactn)
5089 {
5090 if (!(multibyte /* && (c != '\n') */
5091 && BASE_LEADING_CODE_P (c))
5092 ? c != p1[5]
5093 : (STRING_CHAR (&p2[2], pend - &p2[2])
5094 != STRING_CHAR (&p1[5], pend - &p1[5])))
5095 {
5096 p[-3] = (unsigned char) pop_failure_jump;
5097 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
5098 c, p1[5]);
5099 }
5100 }
5101
5102 else if ((re_opcode_t) p1[3] == charset
5103 || (re_opcode_t) p1[3] == charset_not)
5104 {
5105 int not = (re_opcode_t) p1[3] == charset_not;
5106
5107 if (multibyte /* && (c != '\n') */
5108 && BASE_LEADING_CODE_P (c))
5109 c = STRING_CHAR (&p2[2], pend - &p2[2]);
5110
5111 /* Test if C is listed in charset (or charset_not)
5112 at `&p1[3]'. */
5113 if (SINGLE_BYTE_CHAR_P (c))
5114 {
5115 if (c < CHARSET_BITMAP_SIZE (&p1[3]) * BYTEWIDTH
5116 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5117 not = !not;
5118 }
5119 else if (CHARSET_RANGE_TABLE_EXISTS_P (&p1[3]))
5120 CHARSET_LOOKUP_RANGE_TABLE (not, c, &p1[3]);
5121
5122 /* `not' is equal to 1 if c would match, which means
5123 that we can't change to pop_failure_jump. */
5124 if (!not)
5125 {
5126 p[-3] = (unsigned char) pop_failure_jump;
5127 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5128 }
5129 }
5130 }
5131 else if ((re_opcode_t) *p2 == charset)
5132 {
5133 if ((re_opcode_t) p1[3] == exactn)
5134 {
5135 register unsigned int c = p1[5];
5136 int not = 0;
5137
5138 if (multibyte && BASE_LEADING_CODE_P (c))
5139 c = STRING_CHAR (&p1[5], pend - &p1[5]);
5140
5141 /* Test if C is listed in charset at `p2'. */
5142 if (SINGLE_BYTE_CHAR_P (c))
5143 {
5144 if (c < CHARSET_BITMAP_SIZE (p2) * BYTEWIDTH
5145 && (p2[2 + c / BYTEWIDTH]
5146 & (1 << (c % BYTEWIDTH))))
5147 not = !not;
5148 }
5149 else if (CHARSET_RANGE_TABLE_EXISTS_P (p2))
5150 CHARSET_LOOKUP_RANGE_TABLE (not, c, p2);
5151
5152 if (!not)
5153 {
5154 p[-3] = (unsigned char) pop_failure_jump;
5155 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5156 }
5157 }
5158
5159 /* It is hard to list up all the character in charset
5160 P2 if it includes multibyte character. Give up in
5161 such case. */
5162 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
5163 {
5164 /* Now, we are sure that P2 has no range table.
5165 So, for the size of bitmap in P2, `p2[1]' is
5166 enough. But P1 may have range table, so the
5167 size of bitmap table of P1 is extracted by
5168 using macro `CHARSET_BITMAP_SIZE'.
5169
5170 Since we know that all the character listed in
5171 P2 is ASCII, it is enough to test only bitmap
5172 table of P1. */
5173
5174 if ((re_opcode_t) p1[3] == charset_not)
5175 {
5176 int idx;
5177 /* We win if the charset_not inside the loop lists
5178 every character listed in the charset after. */
5179 for (idx = 0; idx < (int) p2[1]; idx++)
5180 if (! (p2[2 + idx] == 0
5181 || (idx < CHARSET_BITMAP_SIZE (&p1[3])
5182 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
5183 break;
5184
5185 if (idx == p2[1])
5186 {
5187 p[-3] = (unsigned char) pop_failure_jump;
5188 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5189 }
5190 }
5191 else if ((re_opcode_t) p1[3] == charset)
5192 {
5193 int idx;
5194 /* We win if the charset inside the loop
5195 has no overlap with the one after the loop. */
5196 for (idx = 0;
5197 (idx < (int) p2[1]
5198 && idx < CHARSET_BITMAP_SIZE (&p1[3]));
5199 idx++)
5200 if ((p2[2 + idx] & p1[5 + idx]) != 0)
5201 break;
5202
5203 if (idx == p2[1]
5204 || idx == CHARSET_BITMAP_SIZE (&p1[3]))
5205 {
5206 p[-3] = (unsigned char) pop_failure_jump;
5207 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
5208 }
5209 }
5210 }
5211 }
5212 }
5213 p -= 2; /* Point at relative address again. */
5214 if ((re_opcode_t) p[-1] != pop_failure_jump)
5215 {
5216 p[-1] = (unsigned char) jump;
5217 DEBUG_PRINT1 (" Match => jump.\n");
5218 goto unconditional_jump;
5219 }
5220 /* Note fall through. */
5221
5222
5223 /* The end of a simple repeat has a pop_failure_jump back to
5224 its matching on_failure_jump, where the latter will push a
5225 failure point. The pop_failure_jump takes off failure
5226 points put on by this pop_failure_jump's matching
5227 on_failure_jump; we got through the pattern to here from the
5228 matching on_failure_jump, so didn't fail. */
5229 case pop_failure_jump:
5230 {
5231 /* We need to pass separate storage for the lowest and
5232 highest registers, even though we don't care about the
5233 actual values. Otherwise, we will restore only one
5234 register from the stack, since lowest will == highest in
5235 `pop_failure_point'. */
5236 unsigned dummy_low_reg, dummy_high_reg;
5237 unsigned char *pdummy;
5238 const char *sdummy;
5239
5240 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
5241 POP_FAILURE_POINT (sdummy, pdummy,
5242 dummy_low_reg, dummy_high_reg,
5243 reg_dummy, reg_dummy, reg_info_dummy);
5244 }
5245 /* Note fall through. */
5246
5247
5248 /* Unconditionally jump (without popping any failure points). */
5249 case jump:
5250 unconditional_jump:
5251 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5252 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5253 p += mcnt; /* Do the jump. */
5254 DEBUG_PRINT2 ("(to 0x%x).\n", p);
5255 break;
5256
5257
5258 /* We need this opcode so we can detect where alternatives end
5259 in `group_match_null_string_p' et al. */
5260 case jump_past_alt:
5261 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
5262 goto unconditional_jump;
5263
5264
5265 /* Normally, the on_failure_jump pushes a failure point, which
5266 then gets popped at pop_failure_jump. We will end up at
5267 pop_failure_jump, also, and with a pattern of, say, `a+', we
5268 are skipping over the on_failure_jump, so we have to push
5269 something meaningless for pop_failure_jump to pop. */
5270 case dummy_failure_jump:
5271 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
5272 /* It doesn't matter what we push for the string here. What
5273 the code at `fail' tests is the value for the pattern. */
5274 PUSH_FAILURE_POINT (0, 0, -2);
5275 goto unconditional_jump;
5276
5277
5278 /* At the end of an alternative, we need to push a dummy failure
5279 point in case we are followed by a `pop_failure_jump', because
5280 we don't want the failure point for the alternative to be
5281 popped. For example, matching `(a|ab)*' against `aab'
5282 requires that we match the `ab' alternative. */
5283 case push_dummy_failure:
5284 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
5285 /* See comments just above at `dummy_failure_jump' about the
5286 two zeroes. */
5287 PUSH_FAILURE_POINT (0, 0, -2);
5288 break;
5289
5290 /* Have to succeed matching what follows at least n times.
5291 After that, handle like `on_failure_jump'. */
5292 case succeed_n:
5293 EXTRACT_NUMBER (mcnt, p + 2);
5294 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5295
5296 assert (mcnt >= 0);
5297 /* Originally, this is how many times we HAVE to succeed. */
5298 if (mcnt > 0)
5299 {
5300 mcnt--;
5301 p += 2;
5302 STORE_NUMBER_AND_INCR (p, mcnt);
5303 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
5304 }
5305 else if (mcnt == 0)
5306 {
5307 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
5308 p[2] = (unsigned char) no_op;
5309 p[3] = (unsigned char) no_op;
5310 goto on_failure;
5311 }
5312 break;
5313
5314 case jump_n:
5315 EXTRACT_NUMBER (mcnt, p + 2);
5316 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5317
5318 /* Originally, this is how many times we CAN jump. */
5319 if (mcnt)
5320 {
5321 mcnt--;
5322 STORE_NUMBER (p + 2, mcnt);
5323 goto unconditional_jump;
5324 }
5325 /* If don't have to jump any more, skip over the rest of command. */
5326 else
5327 p += 4;
5328 break;
5329
5330 case set_number_at:
5331 {
5332 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5333
5334 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5335 p1 = p + mcnt;
5336 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5337 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
5338 STORE_NUMBER (p1, mcnt);
5339 break;
5340 }
5341
5342 case wordbound:
5343 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5344
5345 /* We SUCCEED in one of the following cases: */
5346
5347 /* Case 1: D is at the beginning or the end of string. */
5348 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5349 break;
5350 else
5351 {
5352 /* C1 is the character before D, S1 is the syntax of C1, C2
5353 is the character at D, and S2 is the syntax of C2. */
5354 int c1, c2, s1, s2;
5355 int pos1 = PTR_TO_OFFSET (d - 1);
5356 int charpos;
5357
5358 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5359 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5360 #ifdef emacs
5361 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 ? pos1 : 1);
5362 UPDATE_SYNTAX_TABLE (charpos);
5363 #endif
5364 s1 = SYNTAX (c1);
5365 #ifdef emacs
5366 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5367 #endif
5368 s2 = SYNTAX (c2);
5369
5370 if (/* Case 2: Only one of S1 and S2 is Sword. */
5371 ((s1 == Sword) != (s2 == Sword))
5372 /* Case 3: Both of S1 and S2 are Sword, and macro
5373 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5374 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5375 break;
5376 }
5377 goto fail;
5378
5379 case notwordbound:
5380 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5381
5382 /* We FAIL in one of the following cases: */
5383
5384 /* Case 1: D is at the beginning or the end of string. */
5385 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5386 goto fail;
5387 else
5388 {
5389 /* C1 is the character before D, S1 is the syntax of C1, C2
5390 is the character at D, and S2 is the syntax of C2. */
5391 int c1, c2, s1, s2;
5392 int pos1 = PTR_TO_OFFSET (d - 1);
5393 int charpos;
5394
5395 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5396 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5397 #ifdef emacs
5398 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5399 UPDATE_SYNTAX_TABLE (charpos);
5400 #endif
5401 s1 = SYNTAX (c1);
5402 #ifdef emacs
5403 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5404 #endif
5405 s2 = SYNTAX (c2);
5406
5407 if (/* Case 2: Only one of S1 and S2 is Sword. */
5408 ((s1 == Sword) != (s2 == Sword))
5409 /* Case 3: Both of S1 and S2 are Sword, and macro
5410 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5411 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5412 goto fail;
5413 }
5414 break;
5415
5416 case wordbeg:
5417 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5418
5419 /* We FAIL in one of the following cases: */
5420
5421 /* Case 1: D is at the end of string. */
5422 if (AT_STRINGS_END (d))
5423 goto fail;
5424 else
5425 {
5426 /* C1 is the character before D, S1 is the syntax of C1, C2
5427 is the character at D, and S2 is the syntax of C2. */
5428 int c1, c2, s1, s2;
5429 int pos1 = PTR_TO_OFFSET (d);
5430 int charpos;
5431
5432 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5433 #ifdef emacs
5434 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1);
5435 UPDATE_SYNTAX_TABLE (charpos);
5436 #endif
5437 s2 = SYNTAX (c2);
5438
5439 /* Case 2: S2 is not Sword. */
5440 if (s2 != Sword)
5441 goto fail;
5442
5443 /* Case 3: D is not at the beginning of string ... */
5444 if (!AT_STRINGS_BEG (d))
5445 {
5446 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5447 #ifdef emacs
5448 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5449 #endif
5450 s1 = SYNTAX (c1);
5451
5452 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5453 returns 0. */
5454 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5455 goto fail;
5456 }
5457 }
5458 break;
5459
5460 case wordend:
5461 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5462
5463 /* We FAIL in one of the following cases: */
5464
5465 /* Case 1: D is at the beginning of string. */
5466 if (AT_STRINGS_BEG (d))
5467 goto fail;
5468 else
5469 {
5470 /* C1 is the character before D, S1 is the syntax of C1, C2
5471 is the character at D, and S2 is the syntax of C2. */
5472 int c1, c2, s1, s2;
5473 int pos1 = PTR_TO_OFFSET (d);
5474 int charpos;
5475
5476 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5477 #ifdef emacs
5478 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (pos1 - 1);
5479 UPDATE_SYNTAX_TABLE (charpos);
5480 #endif
5481 s1 = SYNTAX (c1);
5482
5483 /* Case 2: S1 is not Sword. */
5484 if (s1 != Sword)
5485 goto fail;
5486
5487 /* Case 3: D is not at the end of string ... */
5488 if (!AT_STRINGS_END (d))
5489 {
5490 GET_CHAR_AFTER_2 (c2, d, string1, end1, string2, end2);
5491 #ifdef emacs
5492 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5493 #endif
5494 s2 = SYNTAX (c2);
5495
5496 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5497 returns 0. */
5498 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5499 goto fail;
5500 }
5501 }
5502 break;
5503
5504 #ifdef emacs
5505 case before_dot:
5506 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5507 if (PTR_BYTE_POS ((unsigned char *) d) >= PT_BYTE)
5508 goto fail;
5509 break;
5510
5511 case at_dot:
5512 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5513 if (PTR_BYTE_POS ((unsigned char *) d) != PT_BYTE)
5514 goto fail;
5515 break;
5516
5517 case after_dot:
5518 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5519 if (PTR_BYTE_POS ((unsigned char *) d) <= PT_BYTE)
5520 goto fail;
5521 break;
5522
5523 case syntaxspec:
5524 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5525 mcnt = *p++;
5526 goto matchsyntax;
5527
5528 case wordchar:
5529 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5530 mcnt = (int) Sword;
5531 matchsyntax:
5532 PREFETCH ();
5533 #ifdef emacs
5534 {
5535 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5536 UPDATE_SYNTAX_TABLE (pos1);
5537 }
5538 #endif
5539 {
5540 int c, len;
5541
5542 if (multibyte)
5543 /* we must concern about multibyte form, ... */
5544 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5545 else
5546 /* everything should be handled as ASCII, even though it
5547 looks like multibyte form. */
5548 c = *d, len = 1;
5549
5550 if (SYNTAX (c) != (enum syntaxcode) mcnt)
5551 goto fail;
5552 d += len;
5553 }
5554 SET_REGS_MATCHED ();
5555 break;
5556
5557 case notsyntaxspec:
5558 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5559 mcnt = *p++;
5560 goto matchnotsyntax;
5561
5562 case notwordchar:
5563 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5564 mcnt = (int) Sword;
5565 matchnotsyntax:
5566 PREFETCH ();
5567 #ifdef emacs
5568 {
5569 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5570 UPDATE_SYNTAX_TABLE (pos1);
5571 }
5572 #endif
5573 {
5574 int c, len;
5575
5576 if (multibyte)
5577 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5578 else
5579 c = *d, len = 1;
5580
5581 if (SYNTAX (c) == (enum syntaxcode) mcnt)
5582 goto fail;
5583 d += len;
5584 }
5585 SET_REGS_MATCHED ();
5586 break;
5587
5588 case categoryspec:
5589 DEBUG_PRINT2 ("EXECUTING categoryspec %d.\n", *p);
5590 mcnt = *p++;
5591 PREFETCH ();
5592 {
5593 int c, len;
5594
5595 if (multibyte)
5596 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5597 else
5598 c = *d, len = 1;
5599
5600 if (!CHAR_HAS_CATEGORY (c, mcnt))
5601 goto fail;
5602 d += len;
5603 }
5604 SET_REGS_MATCHED ();
5605 break;
5606
5607 case notcategoryspec:
5608 DEBUG_PRINT2 ("EXECUTING notcategoryspec %d.\n", *p);
5609 mcnt = *p++;
5610 PREFETCH ();
5611 {
5612 int c, len;
5613
5614 if (multibyte)
5615 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5616 else
5617 c = *d, len = 1;
5618
5619 if (CHAR_HAS_CATEGORY (c, mcnt))
5620 goto fail;
5621 d += len;
5622 }
5623 SET_REGS_MATCHED ();
5624 break;
5625
5626 #else /* not emacs */
5627 case wordchar:
5628 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5629 PREFETCH ();
5630 if (!WORDCHAR_P (d))
5631 goto fail;
5632 SET_REGS_MATCHED ();
5633 d++;
5634 break;
5635
5636 case notwordchar:
5637 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5638 PREFETCH ();
5639 if (WORDCHAR_P (d))
5640 goto fail;
5641 SET_REGS_MATCHED ();
5642 d++;
5643 break;
5644 #endif /* not emacs */
5645
5646 default:
5647 abort ();
5648 }
5649 continue; /* Successfully executed one pattern command; keep going. */
5650
5651
5652 /* We goto here if a matching operation fails. */
5653 fail:
5654 if (!FAIL_STACK_EMPTY ())
5655 { /* A restart point is known. Restore to that state. */
5656 DEBUG_PRINT1 ("\nFAIL:\n");
5657 POP_FAILURE_POINT (d, p,
5658 lowest_active_reg, highest_active_reg,
5659 regstart, regend, reg_info);
5660
5661 /* If this failure point is a dummy, try the next one. */
5662 if (!p)
5663 goto fail;
5664
5665 /* If we failed to the end of the pattern, don't examine *p. */
5666 assert (p <= pend);
5667 if (p < pend)
5668 {
5669 boolean is_a_jump_n = false;
5670
5671 /* If failed to a backwards jump that's part of a repetition
5672 loop, need to pop this failure point and use the next one. */
5673 switch ((re_opcode_t) *p)
5674 {
5675 case jump_n:
5676 is_a_jump_n = true;
5677 case maybe_pop_jump:
5678 case pop_failure_jump:
5679 case jump:
5680 p1 = p + 1;
5681 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5682 p1 += mcnt;
5683
5684 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
5685 || (!is_a_jump_n
5686 && (re_opcode_t) *p1 == on_failure_jump))
5687 goto fail;
5688 break;
5689 default:
5690 /* do nothing */ ;
5691 }
5692 }
5693
5694 if (d >= string1 && d <= end1)
5695 dend = end_match_1;
5696 }
5697 else
5698 break; /* Matching at this starting point really fails. */
5699 } /* for (;;) */
5700
5701 if (best_regs_set)
5702 goto restore_best_regs;
5703
5704 FREE_VARIABLES ();
5705
5706 return -1; /* Failure to match. */
5707 } /* re_match_2 */
5708 \f
5709 /* Subroutine definitions for re_match_2. */
5710
5711
5712 /* We are passed P pointing to a register number after a start_memory.
5713
5714 Return true if the pattern up to the corresponding stop_memory can
5715 match the empty string, and false otherwise.
5716
5717 If we find the matching stop_memory, sets P to point to one past its number.
5718 Otherwise, sets P to an undefined byte less than or equal to END.
5719
5720 We don't handle duplicates properly (yet). */
5721
5722 static boolean
5723 group_match_null_string_p (p, end, reg_info)
5724 unsigned char **p, *end;
5725 register_info_type *reg_info;
5726 {
5727 int mcnt;
5728 /* Point to after the args to the start_memory. */
5729 unsigned char *p1 = *p + 2;
5730
5731 while (p1 < end)
5732 {
5733 /* Skip over opcodes that can match nothing, and return true or
5734 false, as appropriate, when we get to one that can't, or to the
5735 matching stop_memory. */
5736
5737 switch ((re_opcode_t) *p1)
5738 {
5739 /* Could be either a loop or a series of alternatives. */
5740 case on_failure_jump:
5741 p1++;
5742 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5743
5744 /* If the next operation is not a jump backwards in the
5745 pattern. */
5746
5747 if (mcnt >= 0)
5748 {
5749 /* Go through the on_failure_jumps of the alternatives,
5750 seeing if any of the alternatives cannot match nothing.
5751 The last alternative starts with only a jump,
5752 whereas the rest start with on_failure_jump and end
5753 with a jump, e.g., here is the pattern for `a|b|c':
5754
5755 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5756 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5757 /exactn/1/c
5758
5759 So, we have to first go through the first (n-1)
5760 alternatives and then deal with the last one separately. */
5761
5762
5763 /* Deal with the first (n-1) alternatives, which start
5764 with an on_failure_jump (see above) that jumps to right
5765 past a jump_past_alt. */
5766
5767 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
5768 {
5769 /* `mcnt' holds how many bytes long the alternative
5770 is, including the ending `jump_past_alt' and
5771 its number. */
5772
5773 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
5774 reg_info))
5775 return false;
5776
5777 /* Move to right after this alternative, including the
5778 jump_past_alt. */
5779 p1 += mcnt;
5780
5781 /* Break if it's the beginning of an n-th alternative
5782 that doesn't begin with an on_failure_jump. */
5783 if ((re_opcode_t) *p1 != on_failure_jump)
5784 break;
5785
5786 /* Still have to check that it's not an n-th
5787 alternative that starts with an on_failure_jump. */
5788 p1++;
5789 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5790 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
5791 {
5792 /* Get to the beginning of the n-th alternative. */
5793 p1 -= 3;
5794 break;
5795 }
5796 }
5797
5798 /* Deal with the last alternative: go back and get number
5799 of the `jump_past_alt' just before it. `mcnt' contains
5800 the length of the alternative. */
5801 EXTRACT_NUMBER (mcnt, p1 - 2);
5802
5803 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5804 return false;
5805
5806 p1 += mcnt; /* Get past the n-th alternative. */
5807 } /* if mcnt > 0 */
5808 break;
5809
5810
5811 case stop_memory:
5812 assert (p1[1] == **p);
5813 *p = p1 + 2;
5814 return true;
5815
5816
5817 default:
5818 if (!common_op_match_null_string_p (&p1, end, reg_info))
5819 return false;
5820 }
5821 } /* while p1 < end */
5822
5823 return false;
5824 } /* group_match_null_string_p */
5825
5826
5827 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5828 It expects P to be the first byte of a single alternative and END one
5829 byte past the last. The alternative can contain groups. */
5830
5831 static boolean
5832 alt_match_null_string_p (p, end, reg_info)
5833 unsigned char *p, *end;
5834 register_info_type *reg_info;
5835 {
5836 int mcnt;
5837 unsigned char *p1 = p;
5838
5839 while (p1 < end)
5840 {
5841 /* Skip over opcodes that can match nothing, and break when we get
5842 to one that can't. */
5843
5844 switch ((re_opcode_t) *p1)
5845 {
5846 /* It's a loop. */
5847 case on_failure_jump:
5848 p1++;
5849 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5850 p1 += mcnt;
5851 break;
5852
5853 default:
5854 if (!common_op_match_null_string_p (&p1, end, reg_info))
5855 return false;
5856 }
5857 } /* while p1 < end */
5858
5859 return true;
5860 } /* alt_match_null_string_p */
5861
5862
5863 /* Deals with the ops common to group_match_null_string_p and
5864 alt_match_null_string_p.
5865
5866 Sets P to one after the op and its arguments, if any. */
5867
5868 static boolean
5869 common_op_match_null_string_p (p, end, reg_info)
5870 unsigned char **p, *end;
5871 register_info_type *reg_info;
5872 {
5873 int mcnt;
5874 boolean ret;
5875 int reg_no;
5876 unsigned char *p1 = *p;
5877
5878 switch ((re_opcode_t) *p1++)
5879 {
5880 case no_op:
5881 case begline:
5882 case endline:
5883 case begbuf:
5884 case endbuf:
5885 case wordbeg:
5886 case wordend:
5887 case wordbound:
5888 case notwordbound:
5889 #ifdef emacs
5890 case before_dot:
5891 case at_dot:
5892 case after_dot:
5893 #endif
5894 break;
5895
5896 case start_memory:
5897 reg_no = *p1;
5898 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5899 ret = group_match_null_string_p (&p1, end, reg_info);
5900
5901 /* Have to set this here in case we're checking a group which
5902 contains a group and a back reference to it. */
5903
5904 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5905 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5906
5907 if (!ret)
5908 return false;
5909 break;
5910
5911 /* If this is an optimized succeed_n for zero times, make the jump. */
5912 case jump:
5913 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5914 if (mcnt >= 0)
5915 p1 += mcnt;
5916 else
5917 return false;
5918 break;
5919
5920 case succeed_n:
5921 /* Get to the number of times to succeed. */
5922 p1 += 2;
5923 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5924
5925 if (mcnt == 0)
5926 {
5927 p1 -= 4;
5928 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5929 p1 += mcnt;
5930 }
5931 else
5932 return false;
5933 break;
5934
5935 case duplicate:
5936 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5937 return false;
5938 break;
5939
5940 case set_number_at:
5941 p1 += 4;
5942
5943 default:
5944 /* All other opcodes mean we cannot match the empty string. */
5945 return false;
5946 }
5947
5948 *p = p1;
5949 return true;
5950 } /* common_op_match_null_string_p */
5951
5952
5953 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5954 bytes; nonzero otherwise. */
5955
5956 static int
5957 bcmp_translate (s1, s2, len, translate)
5958 unsigned char *s1, *s2;
5959 register int len;
5960 RE_TRANSLATE_TYPE translate;
5961 {
5962 register unsigned char *p1 = s1, *p2 = s2;
5963 unsigned char *p1_end = s1 + len;
5964 unsigned char *p2_end = s2 + len;
5965
5966 while (p1 != p1_end && p2 != p2_end)
5967 {
5968 int p1_charlen, p2_charlen;
5969 int p1_ch, p2_ch;
5970
5971 p1_ch = STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5972 p2_ch = STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5973
5974 if (RE_TRANSLATE (translate, p1_ch)
5975 != RE_TRANSLATE (translate, p2_ch))
5976 return 1;
5977
5978 p1 += p1_charlen, p2 += p2_charlen;
5979 }
5980
5981 if (p1 != p1_end || p2 != p2_end)
5982 return 1;
5983
5984 return 0;
5985 }
5986 \f
5987 /* Entry points for GNU code. */
5988
5989 /* re_compile_pattern is the GNU regular expression compiler: it
5990 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5991 Returns 0 if the pattern was valid, otherwise an error string.
5992
5993 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5994 are set in BUFP on entry.
5995
5996 We call regex_compile to do the actual compilation. */
5997
5998 const char *
5999 re_compile_pattern (pattern, length, bufp)
6000 const char *pattern;
6001 int length;
6002 struct re_pattern_buffer *bufp;
6003 {
6004 reg_errcode_t ret;
6005
6006 /* GNU code is written to assume at least RE_NREGS registers will be set
6007 (and at least one extra will be -1). */
6008 bufp->regs_allocated = REGS_UNALLOCATED;
6009
6010 /* And GNU code determines whether or not to get register information
6011 by passing null for the REGS argument to re_match, etc., not by
6012 setting no_sub. */
6013 bufp->no_sub = 0;
6014
6015 /* Match anchors at newline. */
6016 bufp->newline_anchor = 1;
6017
6018 ret = regex_compile (pattern, length, re_syntax_options, bufp);
6019
6020 if (!ret)
6021 return NULL;
6022 return gettext (re_error_msgid[(int) ret]);
6023 }
6024 \f
6025 /* Entry points compatible with 4.2 BSD regex library. We don't define
6026 them unless specifically requested. */
6027
6028 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
6029
6030 /* BSD has one and only one pattern buffer. */
6031 static struct re_pattern_buffer re_comp_buf;
6032
6033 char *
6034 #ifdef _LIBC
6035 /* Make these definitions weak in libc, so POSIX programs can redefine
6036 these names if they don't use our functions, and still use
6037 regcomp/regexec below without link errors. */
6038 weak_function
6039 #endif
6040 re_comp (s)
6041 const char *s;
6042 {
6043 reg_errcode_t ret;
6044
6045 if (!s)
6046 {
6047 if (!re_comp_buf.buffer)
6048 return gettext ("No previous regular expression");
6049 return 0;
6050 }
6051
6052 if (!re_comp_buf.buffer)
6053 {
6054 re_comp_buf.buffer = (unsigned char *) malloc (200);
6055 if (re_comp_buf.buffer == NULL)
6056 return gettext (re_error_msgid[(int) REG_ESPACE]);
6057 re_comp_buf.allocated = 200;
6058
6059 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6060 if (re_comp_buf.fastmap == NULL)
6061 return gettext (re_error_msgid[(int) REG_ESPACE]);
6062 }
6063
6064 /* Since `re_exec' always passes NULL for the `regs' argument, we
6065 don't need to initialize the pattern buffer fields which affect it. */
6066
6067 /* Match anchors at newlines. */
6068 re_comp_buf.newline_anchor = 1;
6069
6070 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6071
6072 if (!ret)
6073 return NULL;
6074
6075 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6076 return (char *) gettext (re_error_msgid[(int) ret]);
6077 }
6078
6079
6080 int
6081 #ifdef _LIBC
6082 weak_function
6083 #endif
6084 re_exec (s)
6085 const char *s;
6086 {
6087 const int len = strlen (s);
6088 return
6089 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6090 }
6091 #endif /* _REGEX_RE_COMP */
6092 \f
6093 /* POSIX.2 functions. Don't define these for Emacs. */
6094
6095 #ifndef emacs
6096
6097 /* regcomp takes a regular expression as a string and compiles it.
6098
6099 PREG is a regex_t *. We do not expect any fields to be initialized,
6100 since POSIX says we shouldn't. Thus, we set
6101
6102 `buffer' to the compiled pattern;
6103 `used' to the length of the compiled pattern;
6104 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6105 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6106 RE_SYNTAX_POSIX_BASIC;
6107 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
6108 `fastmap' and `fastmap_accurate' to zero;
6109 `re_nsub' to the number of subexpressions in PATTERN.
6110
6111 PATTERN is the address of the pattern string.
6112
6113 CFLAGS is a series of bits which affect compilation.
6114
6115 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6116 use POSIX basic syntax.
6117
6118 If REG_NEWLINE is set, then . and [^...] don't match newline.
6119 Also, regexec will try a match beginning after every newline.
6120
6121 If REG_ICASE is set, then we considers upper- and lowercase
6122 versions of letters to be equivalent when matching.
6123
6124 If REG_NOSUB is set, then when PREG is passed to regexec, that
6125 routine will report only success or failure, and nothing about the
6126 registers.
6127
6128 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6129 the return codes and their meanings.) */
6130
6131 int
6132 regcomp (preg, pattern, cflags)
6133 regex_t *preg;
6134 const char *pattern;
6135 int cflags;
6136 {
6137 reg_errcode_t ret;
6138 unsigned syntax
6139 = (cflags & REG_EXTENDED) ?
6140 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6141
6142 /* regex_compile will allocate the space for the compiled pattern. */
6143 preg->buffer = 0;
6144 preg->allocated = 0;
6145 preg->used = 0;
6146
6147 /* Don't bother to use a fastmap when searching. This simplifies the
6148 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
6149 characters after newlines into the fastmap. This way, we just try
6150 every character. */
6151 preg->fastmap = 0;
6152
6153 if (cflags & REG_ICASE)
6154 {
6155 unsigned i;
6156
6157 preg->translate
6158 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6159 * sizeof (*(RE_TRANSLATE_TYPE)0));
6160 if (preg->translate == NULL)
6161 return (int) REG_ESPACE;
6162
6163 /* Map uppercase characters to corresponding lowercase ones. */
6164 for (i = 0; i < CHAR_SET_SIZE; i++)
6165 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
6166 }
6167 else
6168 preg->translate = NULL;
6169
6170 /* If REG_NEWLINE is set, newlines are treated differently. */
6171 if (cflags & REG_NEWLINE)
6172 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6173 syntax &= ~RE_DOT_NEWLINE;
6174 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6175 /* It also changes the matching behavior. */
6176 preg->newline_anchor = 1;
6177 }
6178 else
6179 preg->newline_anchor = 0;
6180
6181 preg->no_sub = !!(cflags & REG_NOSUB);
6182
6183 /* POSIX says a null character in the pattern terminates it, so we
6184 can use strlen here in compiling the pattern. */
6185 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
6186
6187 /* POSIX doesn't distinguish between an unmatched open-group and an
6188 unmatched close-group: both are REG_EPAREN. */
6189 if (ret == REG_ERPAREN) ret = REG_EPAREN;
6190
6191 return (int) ret;
6192 }
6193
6194
6195 /* regexec searches for a given pattern, specified by PREG, in the
6196 string STRING.
6197
6198 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6199 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6200 least NMATCH elements, and we set them to the offsets of the
6201 corresponding matched substrings.
6202
6203 EFLAGS specifies `execution flags' which affect matching: if
6204 REG_NOTBOL is set, then ^ does not match at the beginning of the
6205 string; if REG_NOTEOL is set, then $ does not match at the end.
6206
6207 We return 0 if we find a match and REG_NOMATCH if not. */
6208
6209 int
6210 regexec (preg, string, nmatch, pmatch, eflags)
6211 const regex_t *preg;
6212 const char *string;
6213 size_t nmatch;
6214 regmatch_t pmatch[];
6215 int eflags;
6216 {
6217 int ret;
6218 struct re_registers regs;
6219 regex_t private_preg;
6220 int len = strlen (string);
6221 boolean want_reg_info = !preg->no_sub && nmatch > 0;
6222
6223 private_preg = *preg;
6224
6225 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6226 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6227
6228 /* The user has told us exactly how many registers to return
6229 information about, via `nmatch'. We have to pass that on to the
6230 matching routines. */
6231 private_preg.regs_allocated = REGS_FIXED;
6232
6233 if (want_reg_info)
6234 {
6235 regs.num_regs = nmatch;
6236 regs.start = TALLOC (nmatch, regoff_t);
6237 regs.end = TALLOC (nmatch, regoff_t);
6238 if (regs.start == NULL || regs.end == NULL)
6239 return (int) REG_NOMATCH;
6240 }
6241
6242 /* Perform the searching operation. */
6243 ret = re_search (&private_preg, string, len,
6244 /* start: */ 0, /* range: */ len,
6245 want_reg_info ? &regs : (struct re_registers *) 0);
6246
6247 /* Copy the register information to the POSIX structure. */
6248 if (want_reg_info)
6249 {
6250 if (ret >= 0)
6251 {
6252 unsigned r;
6253
6254 for (r = 0; r < nmatch; r++)
6255 {
6256 pmatch[r].rm_so = regs.start[r];
6257 pmatch[r].rm_eo = regs.end[r];
6258 }
6259 }
6260
6261 /* If we needed the temporary register info, free the space now. */
6262 free (regs.start);
6263 free (regs.end);
6264 }
6265
6266 /* We want zero return to mean success, unlike `re_search'. */
6267 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6268 }
6269
6270
6271 /* Returns a message corresponding to an error code, ERRCODE, returned
6272 from either regcomp or regexec. We don't use PREG here. */
6273
6274 size_t
6275 regerror (errcode, preg, errbuf, errbuf_size)
6276 int errcode;
6277 const regex_t *preg;
6278 char *errbuf;
6279 size_t errbuf_size;
6280 {
6281 const char *msg;
6282 size_t msg_size;
6283
6284 if (errcode < 0
6285 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6286 /* Only error codes returned by the rest of the code should be passed
6287 to this routine. If we are given anything else, or if other regex
6288 code generates an invalid error code, then the program has a bug.
6289 Dump core so we can fix it. */
6290 abort ();
6291
6292 msg = gettext (re_error_msgid[errcode]);
6293
6294 msg_size = strlen (msg) + 1; /* Includes the null. */
6295
6296 if (errbuf_size != 0)
6297 {
6298 if (msg_size > errbuf_size)
6299 {
6300 strncpy (errbuf, msg, errbuf_size - 1);
6301 errbuf[errbuf_size - 1] = 0;
6302 }
6303 else
6304 strcpy (errbuf, msg);
6305 }
6306
6307 return msg_size;
6308 }
6309
6310
6311 /* Free dynamically allocated space used by PREG. */
6312
6313 void
6314 regfree (preg)
6315 regex_t *preg;
6316 {
6317 if (preg->buffer != NULL)
6318 free (preg->buffer);
6319 preg->buffer = NULL;
6320
6321 preg->allocated = 0;
6322 preg->used = 0;
6323
6324 if (preg->fastmap != NULL)
6325 free (preg->fastmap);
6326 preg->fastmap = NULL;
6327 preg->fastmap_accurate = 0;
6328
6329 if (preg->translate != NULL)
6330 free (preg->translate);
6331 preg->translate = NULL;
6332 }
6333
6334 #endif /* not emacs */