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