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